text:
/*global jQuery */

/**
 * Gestiona las operaciones de filtrado de datos sobre el origen de datos que utiliza el componente.
 *
 * @summary Plugin de filtrado del componente RUP Table.
 * @module rup_jqtable/filter
 * @example
 *
 * $("#idComponente").rup_jqtable({
 * 	url: "../jqGridUsuario",
 * 	usePlugins:["filter"],
 * 	filter:{
 * 		// Propiedades de configuración del plugin filter
 * 	}
 * });
 */
(function ($) {

	/**
	 * Definición de los métodos principales que configuran la inicialización del plugin.
	 *
	 * postConfiguration: Método que se ejecuta después de la invocación del componente jqGrid.
	 *
	 */
	jQuery.rup_jqtable.registerPlugin('filter',{
		loadOrder:1,
		preConfiguration: function(settings){
			var $self = this;
			return $self.rup_jqtable('preConfigureFilter', settings);
		},
		postConfiguration: function(settings){
			var $self = this;
			return $self.rup_jqtable('postConfigureFilter', settings);
		}
	});

	//********************************
	// DEFINICIÓN DE MÉTODOS PÚBLICOS
	//********************************

	/**
	 * Extensión del componente rup_jqtable para permitir la gestión del filtrado de registros de la tabla.
	 *
	 * Los métodos implementados son:
	 *
	 * postConfigureFilter(settings): Método que define la preconfiguración necesaria para el correcto funcionamiento del componente.
	 *
	 * Se almacena la referencia de los diferentes componentes:
	 *
	 * settings.filter.$filterContainer : Contenedor del formulario de filtrado
	 * settings.filter.$filterButton : Botón que realiza el filtrado
	 * settings.filter.$cleanButton : Botón para limpiar el formulario
	 * settings.filter.$collapsableLayer : Capa que puede ser ocultada/mostrada
	 * settings.filter.$toggleIcon1Id : Control que oculta muestra el fomulario
	 * settings.filter.$filterSummary : Contenedor donde se especifican los criterios de filtrado
	 *
	 */
	jQuery.fn.rup_jqtable('extend',{
		/**
			* Metodo que realiza la pre-configuración del plugin filter del componente RUP Table.
			* Este método se ejecuta antes de la incialización del plugin.
			*
			* @name preConfigureFilter
			* @function
			* @param {object} settings - Parámetros de configuración del componente.
			*/
		preConfigureFilter: function(settings){
			var $self = this, tableId = settings.id, filterSettings = settings.filter, filterFormId,
				toggleIcon1Tmpl,toggleLabelTmpl,filterSummaryTmpl,toggleIcon2Tmpl,$toggleIcon1,$toggleLabel,$filterSummary,$toggleIcon2;

			/*
			 * Inicialización de los identificadores y componentes por defecto de los componentes de filtrado
			 */
			filterSettings.id = (filterSettings.id!==undefined?filterSettings.id:tableId+'_filter_form');
			filterSettings.filterToolbarId = (filterSettings.filterToolbar!==undefined?filterSettings.filterToolbar:tableId+'_filter_toolbar');
			filterSettings.filterButtonId = (filterSettings.filterButtonId!==undefined?filterSettings.filterButtonId:tableId+'_filter_filterButton');
			filterSettings.cleanButtonId = (filterSettings.cleanButtonId!==undefined?filterSettings.cleanButtonId:tableId+'_filter_cleanButton');
			filterSettings.collapsableLayerId = (filterSettings.collapsableLayerId!==undefined?filterSettings.collapsableLayerId:tableId+'_filter_fieldset');

			filterSettings.toggleIcon1Id = (filterSettings.toggleIcon1!==undefined?filterSettings.toggleIcon1:tableId+'_filter_toggle_icon1');
			filterSettings.toggleLabelId = (filterSettings.toggleLabelId!==undefined?filterSettings.toggleLabelId:tableId+'_filter_toggle_label');
			filterSettings.filterSummaryId = (filterSettings.filterSummaryId!==undefined?filterSettings.filterSummaryId:tableId+'_filter_summary');
			filterSettings.toggleIcon2Id = (filterSettings.toggleIcon2!==undefined?filterSettings.toggleIcon2:tableId+'_filter_toggle_icon2');

			filterSettings.$filterContainer = jQuery('#'+filterSettings.id);
			filterSettings.$filterToolbar = jQuery('#'+filterSettings.filterToolbarId);

			if (filterSettings.$filterContainer.length===0){
				alert('El identificador especificado para el fomulario de búsqueda no existe.');
			}else if (filterSettings.$filterToolbar.length===0){
				alert('El identificador especificado para la barra de controles del formulario de filtrado no existe.');
			}else{
				/*
				 * Se almacena la referencia de los diferentes componentes
				 *
				 * $filterContainer : Contenedor del formulario de filtrado
				 * $filterButton : Botón que realiza el filtrado
				 * $cleanButton : Botón para limpiar el formulario
				 * $collapsableLayer : Capa que puede ser ocultada/mostrada
				 * $toggleIcon1Id : Control que oculta muestra el fomulario
				 * $filterSummary : Contenedor donde se especifican los criterios de filtrado
				 */
				toggleIcon1Tmpl = jQuery.rup.i18nParse(jQuery.rup.i18n.base,'rup_jqtable.templates.filter.toggleIcon1');
				toggleLabelTmpl = jQuery.rup.i18nParse(jQuery.rup.i18n.base,'rup_jqtable.templates.filter.toggleLabel');
				filterSummaryTmpl = jQuery.rup.i18nParse(jQuery.rup.i18n.base,'rup_jqtable.templates.filter.filterSummary');
				toggleIcon2Tmpl = jQuery.rup.i18nParse(jQuery.rup.i18n.base,'rup_jqtable.templates.filter.toggleIcon2');

				$toggleIcon1 = $(jQuery.jgrid.format(toggleIcon1Tmpl, filterSettings.toggleIcon1Id));
				$toggleLabel = $(jQuery.jgrid.format(toggleLabelTmpl, filterSettings.toggleLabelId, $.rup.i18n.base.rup_jqtable.plugins.filter.filterCriteria));
				$filterSummary = $(jQuery.jgrid.format(filterSummaryTmpl, filterSettings.filterSummaryId));
				$toggleIcon2 = $(jQuery.jgrid.format(toggleIcon2Tmpl, filterSettings.toggleIcon2Id));

				filterSettings.$filterToolbar.append($toggleIcon1).append($toggleLabel).append($filterSummary).append($toggleIcon2);

				filterSettings.$filterContainer = jQuery('#'+filterSettings.id);
				filterSettings.$filterButton = jQuery('#'+filterSettings.filterButtonId);

				//Creacion del boton de filtrado
				//filterSettings.$filterButton.addClass("dropdownButton");
				//filterSettings.$filterButton.append('

Filtro
<form><fieldset class="dropdownButton-inputs">

</fieldset>       <fieldset class="dropdownButton-actions"><input class="ui-button ui-widget ui-state-default ui-corner-all"  value="Guardar" type="submit"><input  class="ui-button ui-widget ui-state-default ui-corner-all"  value="Aplicar" type="submit"> <input class="ui-button ui-widget ui-state-default ui-corner-all"  value="Eliminar" type="submit"></fieldset>                 </form>

▼

');

				filterSettings.$cleanButton = jQuery('#'+filterSettings.cleanButtonId);
				filterSettings.$collapsableLayer = jQuery('#'+filterSettings.collapsableLayerId);

				filterSettings.$toggleIcon1 = $toggleIcon1;
				filterSettings.$toggleLabel = $toggleLabel;
				filterSettings.$filterSummary = $filterSummary;
				filterSettings.$toggleIcon2 = $toggleIcon2;

				/*
				 * TODO: Comprobar que la configuración es correcta
				 */

				if (filterSettings.$filterContainer.prop('tagName')==='FORM'){
					filterSettings.$filterContainer.ajaxForm();
				}

				// Se utiliza el plugin ajaxForm de jQuery para configurar el formualario de busqueda como AJAX.
				// Se redimensiona el formulario de busqueda al tamanyo del grid.
				filterSettings.$filterContainer.parent().css('width',$self.rup_jqtable('getGridParam', 'width'));

				// Se configura la url de filtrado
				if (settings.filter.url === null){
					settings.filter.url = settings.baseUrl +'/filter';
				}
				settings.url = settings.filter.url;

				// Se almacena en las propiedades la url utilizada para la busqueda a partir de la especificada en el grid.
				settings.searchURL = $self.rup_jqtable('getGridParam', 'url');

				// Se asigna a la tecla ENTER la funcion de busqueda.
				filterSettings.$filterContainer.bind('keydown', function(evt) {
					if (evt.keyCode == 13) {
						// TODO : poner como evento
						//$self.rup_jqtable("showSearchCriteria");
						$self.rup_jqtable('filter');
					}
				});

				// Creacion del boton de busqueda.
				filterSettings.$filterButton.bind('click', function () {
					// TODO: Control cambios
					// TODO : poner como evento

					//Deshabilitar el nombre del filtro en el filterSummary una vez que ha terminado el filtro por defecto
					if (settings.$firstStartUp){

						settings.$firstStartUp=false;
					}
					//$self.rup_jqtable("showSearchCriteria");
					$self.rup_jqtable('filter');
				});

				// Creacion del botón de limpiar formulario.
				filterSettings.$cleanButton.bind('click', function () {
					// TODO : poner como evento
					if (settings.$firstStartUp){

						settings.$firstStartUp=false;
					}

					$self.rup_jqtable('cleanFilterForm').rup_jqtable('filter');
					if (filterSettings.validate!==undefined){
						jQuery('.rup-maint_validateIcon', filterSettings.$filterContainer).remove();
					}
					//$self.rup_jqtable("showSearchCriteria");
				});

				filterSettings.$toggleIcon1.add(filterSettings.$toggleLabel).add(filterSettings.$toggleIcon2)
					.attr('tabindex','0')
					.on({
						'keydown':function(evt) {
							if (evt.keyCode == 13) {
								$self.rup_jqtable('toggleFilterForm');
							}
						}
					});

				filterSettings.$filterToolbar.addClass('cursor_pointer').on({
					'click':function(){
						$self.rup_jqtable('toggleFilterForm');
					}
				});

				if (settings.filter.showHidden === true){
					filterSettings.$collapsableLayer.hide();
					//						filterSettings.$collapsableRowShow.show();
					filterSettings.$toggleIcon1.removeClass('ui-icon-triangle-1-n').addClass('ui-icon-triangle-1-s');
					filterSettings.$filterSummary.parent().addClass('rup-maint_searchCriteria');
				}

				// Configuración de validaciones
				if (filterSettings.validate!==undefined){
					filterSettings.$filterContainer.rup_validate(filterSettings.validate);

					$self.on({
						'rupTable_beforeFilter.filter.validate': function(){

							//filterSettings.$filterContainer.rup_validate("resetForm");
							if (multifilterSettings!==undefined){
								if(!settings.$firstStartUp){
									return filterSettings.$filterContainer.valid();
								}else{
									return null;
								}
							}else{
								return filterSettings.$filterContainer.valid();
							}
						}

					});
				}
			}

			$self.on({
				'rupTable_serializeGridData.filter': function(events, postData){
					var	filterParams = form2object(settings.filter.$filterContainer[0]),
						queryStrFilterParams = jQuery.param(filterParams),
						lastFilterParams = $self.data('tmp.lastFilterParams');

					var filtro;
					if (settings.$firstStartUp==true){
						var filtro= multifilterSettings.$filterDefaultValue;
					}
					if (filtro==undefined){
						jQuery.extend(postData, {'filter':filterParams});
					}else{
						jQuery.extend(postData, {'filter':filtro});
					}

					if (lastFilterParams === undefined || lastFilterParams !== queryStrFilterParams){
						jQuery.extend(postData, {page:($self.data('tmp.firstLoad')===true && settings.core.startOnPage!==null?settings.core.startOnPage:'1')});
						$self.data('tmp.lastFilterParams', queryStrFilterParams);
					}

				}
			});

			$self.on('jqGridGridComplete',function(event){
				if ($self.data('settings')!==undefined){
					$self.rup_jqtable('showSearchCriteria');
				}
			});

			// gestion de evento por defecto Multifiltro

			if (settings.multifilter != undefined
									&& settings.multifilter != null) {
				var $filterForm, $filterDefaultName,$firstStartUp;
				var multifilterSettings = settings.multifilter;
				settings.filter.$filterForm = $('#'
										+ settings.id + '_filter_form');

				var selector;

				settings.$firstStartUp=true;

				if (multifilterSettings.idFilter != null) {
					selector = multifilterSettings.idFilter;
				} else {
					selector = settings.id;
				}
				var usuario;
				if (multifilterSettings.userFilter != null) {
					usuario = multifilterSettings.userFilter;
				} else {
					usuario = LOGGED_USER;
				}
				var getDefault;
				if (multifilterSettings.getDefault!=null){
					getDefault = multifilterSettings.getDefault;
				}else{
					getDefault = true;
				}
				// getDefault
				if (getDefault){
					$.rup_ajax({
						url : settings.baseUrl
													+ '/multiFilter/getDefault?filterSelector='
													+ selector + '&user='
													+ usuario,
						type : 'GET',
						dataType : 'json',
						showLoading : false,
						contentType : 'application/json',
						//async : false,
						complete : function(jqXHR,
							textStatus) {
							if (settings.loadOnStartUp){
								$self.rup_jqtable('filter');
							}
							$self.triggerHandler('rupTable_multifilter_fillForm',$self.data.filterData);

							//												$self.triggerHandler("rupTable_multifilter_fillForm",form2object(settings.filter.$filterContainer[0]));
						},
						success : function(data, status,
							xhr) {
							if (data != null) {
								var valorFiltro = $
									.parseJSON(data.filterValue);

								$self._fillForm(valorFiltro);

								//settings.filter.$filterSummary.html(""+data.filterName+"");
								multifilterSettings.$filterDefaultName = data.filterName;
								multifilterSettings.$filterDefaultValue = valorFiltro;
								$self.data.filterData=valorFiltro;
							}

						},
						error : function(xhr, ajaxOptions,
							thrownError) {

						}
					});

				}

			}

		},
		/**
		 * Metodo que realiza la post-configuración del plugin filter del componente RUP Table.
		 * Este método se ejecuta después de la incialización del plugin.
		 *
		 * @name postConfigureFilter
		 * @function
		 * @param {object} settings - Parámetros de configuración del componente.
		 */
		postConfigureFilter: function(settings){
			var $self = this, filterFormId, filterSettings;

		}
	});

	//********************************
	// DEFINICIÓN DE MÉTODOS PÚBLICOS
	//********************************

	/**
	 * Métodos públicos del plugin filter.
	 *
	 * cleanFilterForm: Realiza una limpieza de los campos del formulario.
	 * filter: Lanza el filtrado de la tabla de acuerdo a los criterios indicados en el formulario.
	 * toggleFilterForm: Método encargado de ocultar y mostrar el formulario de filtrado.
	 *
	 */
	jQuery.fn.rup_jqtable('extend',{
		/**
     * Limpia los campos del formulario de filtrado.
     *
     * @function  cleanFilterForm
		 * @fires module:rup_jqtable#rupTable_filter_beforeCleanFilterForm
		 * @fires module:rup_jqtable#rupTable_filter_afterCleanFilterForm
     * @example
     * $("#idComponente").rup_jqtable("cleanFilterForm");
     */
		cleanFilterForm : function () {
			var $self = this,
				settings = $self.data('settings');
			$self.triggerHandler('rupTable_filter_beforeCleanFilterForm');
			$self.rup_jqtable('resetForm', settings.filter.$filterContainer);
			$self.triggerHandler('rupTable_filter_afterCleanFilterForm');

			return $self;
		},
		/**
     * Realiza el filtrado de acuerdo a los datos existentes en el formulario de filtrado.
     *
     * @function  filter
		 * @fires module:rup_jqtable#rupTable_beforeFilter
     * @example
     * $("#idComponente").rup_jqtable("filter");
     */
		filter : function(){
			var $self = this,
				settings = $self.data('settings');

			var bfr = $self.triggerHandler('rupTable_beforeFilter');
			if (bfr === false || bfr === 'stop') { return; }

			if ($.isFunction(settings.filter.beforeFilter)) {
				bfr = settings.filter.beforeFilter.call($self);
				if(bfr === undefined) { bfr = true; }
				if ( bfr === false ) { return; }
			}

			$self.rup_jqtable('setGridParam',{page:'1'});

			$self.trigger('reloadGrid');
		},
		/**
     * Devuelve los parámetros de filtrado empleados en el filtrado.
     *
     * @function  getFilterParams
     * @example
     * $("#idComponente").rup_jqtable("getFilterParams");
     */
		getFilterParams : function(){
			var $self = this,
				settings = $self.data('settings');

			return form2object(settings.filter.$filterContainer[0]);
		},
		/**
     *  Oculta el formulario de filtrado.
     *
     * @function  hideFilterForm
     * @example
     * $("#idComponente").rup_jqtable("hideFilterForm");
     */
		hideFilterForm: function(){
			var $self = $(this), settings = $self.data('settings'), filterSettings = settings.filter;

			filterSettings.$collapsableLayer.hide(settings.filter.transitionConfig);

			//			filterSettings.$collapsableRowShow.show(settings.filter.transitionConfig);

			filterSettings.$toggleIcon2.removeClass('ui-icon-circle-triangle-n').addClass('ui-icon-circle-triangle-s');
			filterSettings.$toggleIcon1.removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
			filterSettings.$filterSummary.parent().addClass('rup-maint_searchCriteria');
		},
		/**
     * Muestra el formulario de filtrado.
     *
     * @function showFilterForm
     * @example
     * $("#idComponente").rup_jqtable("showFilterForm");
     */
		showFilterForm: function(){
			var $self = $(this), settings = $self.data('settings'), filterSettings = settings.filter;
			// Se muestra el formulario de búsqueda
			filterSettings.$collapsableLayer.show($.extend({},settings.filter.transitionConfig,{
				complete: function(){
					// Anadido el foco al primer campo del formulario
					jQuery('input:first', filterSettings.$filterContainer).focus();
				}
			}));

			filterSettings.$toggleIcon2.removeClass('ui-icon-circle-triangle-s').addClass('ui-icon-circle-triangle-n');
			filterSettings.$toggleIcon1.removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
			filterSettings.$filterSummary.parent().removeClass('rup-maint_searchCriteria');
			//Eliminar tooltip
			//			$titleSearch.rup_tooltip("destroy");

			//			filterSettings.$collapsableRowShow.hide(settings.filter.transitionConfig);
		},
		/**
     * Alterna el estado del formulario de filtrado entre visible y oculto.
     *
     * @function toggleFilterForm
     * @example
     * $("#idComponente").rup_jqtable("toggleFilterForm");
     */
		toggleFilterForm: function(){
			var $self = $(this), settings = $self.data('settings'), filterSettings = settings.filter;

			if (filterSettings.$collapsableLayer.is(':hidden')) {
				//MOSTRAR
				$self.rup_jqtable('showFilterForm');

			}else{
				// OCULTAR
				$self.rup_jqtable('hideFilterForm');
			}

			return $self;
		},
		/**
     * Actualiza el resumen de los criterios de filtrado a partir de los valores existentes en el formulario.
     *
     * @function showSearchCriteria
     * @example
     * $("#idComponente").rup_jqtable("showSearchCriteria");
     */
		showSearchCriteria: function(){
			var $self = this, settings = $self.data('settings'),
				searchString = ' ', temp = '', label, numSelected,
				field, fieldId, fieldName, fieldValue,
				aux = settings.filter.$filterContainer.serializeArray(),
				searchForm = settings.filter.$filterContainer,
				filterMulticombo = new Array();
			var obj;

			//añadir arbol
			var nombreArbol=$('.jstree',settings.filter.$filterContainer);
			var arboles=	$('.jstree',settings.filter.$filterContainer);
			$.each(arboles,function( index,item ){
				obj= new Object();
				obj.name=$(item).attr('name');
				obj.value=$(item).rup_tree('getRupValue').length;
				obj.type='rup_tree';
				aux.push(obj);
			});

			for (var i = 0; i < aux.length; i++) {
				if (aux[i].value !== ''  && $.inArray(aux[i].name,settings.filter.excludeSummary)!=0) {

					//CAMPO a tratar
					field = $('[name=\'' + aux[i].name + '\']',searchForm);

					//Comprobar si se debe excluir el campo
					if ($.inArray(field.attr('id'), settings.filter.filterExclude) !== -1){
						continue;
					}

					//Seleccionar radio
					if (field.length > 1){
						field = $('[name=\'' + aux[i].name + '\']:checked',searchForm);
					}
					//Omitir campos hidden
					if ($(field).attr('type') === 'hidden'){
						continue;
					}

					//ID del campo
					fieldId = $(field).attr('id');
					//ID para elementos tipo rup.combo
					if ($(field).attr('ruptype') === 'combo'){
						if (field.next('.ui-multiselect').length==0){
							fieldId += '-button';
						}
					}
					//ID para elementos tipo rup.autocomplete
					if ($(field).attr('ruptype') === 'autocomplete'){
						fieldId = fieldId.substring(0, fieldId.indexOf('_label'));
					}

					//NAME
					label = $('label[for^=\'' + fieldId + '\']',searchForm);
					if (label.length>0){
						//
						fieldName = label.html();
					} else {
						//

						//

						if ($(field).attr('ruptype') !== 'combo'){
							//fieldName= $("[name='" + aux[i].name + "']",searchForm).prev('div').html();
							fieldName= $('[name=\'' + aux[i].name + '\']',searchForm).prev('div').find('label').first().html();
						} else {
							//fieldName= $("[name='" + aux[i].name + "']",searchForm).parent().prev('div').html();

							// Buscamos el label asociado al combo
							// Primero por id
							var $auxField = $('[name=\'' + aux[i].name + '\']',searchForm), $labelField;

							$labelField = jQuery('[for=\''+$auxField.attr('id')+'\']');

							if ($labelField.length>0){
								fieldName = $labelField.first().text();
							}else{

								fieldName= $('[name=\'' + aux[i].name + '\']',searchForm).parent().prev('div').find('label').first().html();

							}
						}
					}
					if (fieldName === null || fieldName === undefined){
						fieldName = '';
					}

					//VALUE
					fieldValue = ' = ';
					switch($(field)[0].tagName){
					case 'INPUT':
						fieldValue = fieldValue + $(field).val();
						if ($(field)[0].type === 'checkbox' || $(field)[0].type === 'radio'){
							fieldValue = '';
						}
						break;
						//Rup-tree
					case 'DIV':
						$.each(aux,function( index,item ){
							if (item.name==field.attr('id')){
								if (item.value!=0){
									fieldValue +=' = '+ item.value;
								}
							} else {
								fieldValue = '';
							}

						});
						if (fieldValue==''){
							fieldName = '';
						}
						break;
					case 'SELECT':
						if (field.next('.ui-multiselect').length==0){
							fieldValue = fieldValue + $('option[value=\''+aux[i].value+'\']',field).html();
						} else {
							if ($.inArray($(field).attr('id'), filterMulticombo)===-1){
								numSelected = field.rup_combo('value').length;
								if (numSelected !== 0){
									fieldValue += numSelected;
								} else {
									fieldName = '';
									fieldValue = '';
								}
								filterMulticombo.push($(field).attr('id'));
							} else {
								fieldName = '';
								fieldValue = '';
							}
						}
						break;
					}

					//Parsear NAME
					var parseableChars = new Array(':','=');
					for (var j=0; j<parseableChars.length; j++){
						if (fieldName !== '' && fieldName.indexOf(parseableChars[j])!== -1){
							fieldName = fieldName.substring(0,fieldName.indexOf(parseableChars[j]));
							break;
						}
					}

					//Controlar rup.combo con valor vacío
					while (fieldValue.indexOf('&nbsp;')!==-1){
						fieldValue = fieldValue.replace ('&nbsp;','');
					}

					//Si no tiene NAME sacar solo el valor
					if (fieldName === '' && fieldValue.indexOf(' = ')!==-1){
						fieldValue = fieldValue.substring(2, fieldValue.length);
					}

					//Si no tiene NAME ni VALUE omitir
					if (fieldName === '' && $.trim(fieldValue) === ''){
						continue;
					}
					searchString = searchString + fieldName + fieldValue + ', ';
				}
			}

			if (jQuery.isFunction(settings.filter.fncSearchCriteria)){
				searchString = jQuery.proxy(settings.filter.fncSearchCriteria, $self, searchString)();
			}

			if ($.trim(searchString).length-1==$.trim(searchString).lastIndexOf(','))
			{
				searchString=searchString.substr(0,searchString.lastIndexOf(','))+' ';
			}

			if (settings.multifilter) {
				if (jQuery.isFunction(settings.multifilter.fncFilterName)){
					searchString = jQuery.proxy(settings.multifilter.fncFilterName, $self, searchString)();
				}
			}
			//Contiene criterios
			//			if (searchString.length>1){
			//searchString = searchString.substring(0, searchString.length-2);

			var initialHeight = $('#titleSearch_' + settings.id.name).css('height'),
				height,
				tmp = searchString,
				tooltip = false;

				//Añadir criterios
			while(true){
				settings.filter.$filterSummary.html(' ' + tmp + '');
				height = $('#titleSearch_' + settings.id.name).css('height');
				if (height === initialHeight){
					break;
				}
				tmp = tmp.substring(0, tmp.lastIndexOf(',')) + ' ...';
				tooltip = true;
			}

			//Tooltip con criterios
			if (tooltip){
				settings.filter.$filterSummary
					.rup_tooltip({
						content: {
							text: searchString.substring(1)
						},
						position: {
							my: 'bottom center',
							at: 'top center'
						}
					});
			}
		}
		//		}
	});

	//*******************************
	// DEFINICIÓN DE MÉTODOS PRIVADOS
	//*******************************

	jQuery.fn.rup_jqtable('extend',{
		/**
     * Obtiene el label correspondiente a un campo por el que se realiza el filtrado.
     *
     * @function _getSearchFormFieldLabel
		 * @private
		 * @param {object} $field Referencia jQuery a un campo del formulario de filtrado.
		 * @param {object} $form Referencia jQuery al formulario de filtrado.
		 * @return {string} - Label identificador al campo del formulario indicado por parámetro.
     * @example
     * $self._getSearchFormFieldLabel($field, $form);
     */
		_getSearchFormFieldLabel: function($field, $form){
			var fieldId = $field.attr('id'), $label, formFieldLabel='', rupType = $field.attr('ruptype');

			if (rupType !== 'combo'){
				$label = jQuery('label[for=\''+fieldId+'\']', $form);
			}else{
				$label = jQuery('label[for=\''+fieldId+'-button\']', $form);
			}

			if ($label.length>0){
				//
				formFieldLabel = $label.html();
			} else {
				//

				//

				if ($field.attr('ruptype') !== 'combo'){
					//fieldName= $("[name='" + aux[i].name + "']",searchForm).prev('div').html();
					formFieldLabel= $('[name=\'' + name + '\']', $form).prev('div').find('label').first().html();
				} else {
					//fieldName= $("[name='" + aux[i].name + "']",searchForm).parent().prev('div').html();
					formFieldLabel= $('[name=\'' + name + '\']', $form).parent().prev('div').find('label').first().html();
				}
			}

			// Eliminamos los caracteres ':' y '=' que puedan existir en el label
			formFieldLabel = formFieldLabel.replace(/[:=]/g,'');

			return formFieldLabel;
		},
		/**
     * Obtiene el value del campo por el que se está filtrando.
     *
     * @function _getSearchFormFieldLabel
		 * @private
		 * @param {object} $field Referencia jQuery a un campo del formulario de filtrado.
		 * @param {object} $form Referencia jQuery al formulario de filtrado.
		 * @return {string} - Value correspondiente al campo del formulario indicado por parámetro.
     * @example
     * $self._getSearchFormFieldValue($field, $form);
     */
		_getSearchFormFieldValue: function($field, $form){
			var fieldValue = ' = ', filterMulticombo = [], numSelected, fieldName;

			//VALUE
			switch($field.prop('tagName')){
			case 'INPUT':
				fieldValue = fieldValue + $field.val();
				if ($field.attr('type') === 'checkbox' || $field.attr('type') === 'radio'){
					fieldValue = '';
				}
				break;
			case 'SELECT':
				if ($field.next('.ui-multiselect').length==0){
					fieldValue = fieldValue + $('option[value=\''+$field.rup_combo('getRupValue')+'\']', $field).html();
				} else {
					if ($.inArray($field.attr('id'), filterMulticombo)===-1){
						numSelected = $field.rup_combo('value').length;
						if (numSelected !== 0){
							fieldValue += numSelected;
						} else {
							fieldName = '';
							fieldValue = '';
						}
						filterMulticombo.push($field.attr('id'));
					} else {
						fieldName = '';
						fieldValue = '';
					}
				}
				break;
			}

			//Controlar rup.combo con valor vacío
			while (fieldValue.indexOf('&nbsp;')!==-1){
				fieldValue = fieldValue.replace ('&nbsp;','');
			}

			return fieldValue;
		}

	});

	//*******************************************************
	// DEFINICIÓN DE LA CONFIGURACION POR DEFECTO DEL PATRON
	//*******************************************************

	/**
	 * Parámetros de configuración por defecto para el plugin filter.
	 *
	 */
	/**
 	* @description Propiedades de configuración del plugin filter del componente RUP Table.
 	*
 	* @name options
 	*
 	* @property {boolean} [showHidden=false] -  Determina si el formulario de filtrado se debe de mostrar inicialmente oculto o no.
 	* @property {string} [url=null] - Url que se va a utilizar para realizar las peticiones de filtrado de la tabla. En caso de no especificarse una concreta, se utilizará por defecto una construida a partir de la url base. (urlBase + /filter).
 	* @property {object} [transitionConfig] - Configuración del efecto de la animación de mostrar/ocultar el formulario defiltrado.
 	* @property {function} [fncSearchCriteria] - Permite especificar una función de callback en la cual es posible modificar la cadena de texto con la que se muestra el resumen de los parámetros de filtrado.
 	*/
	jQuery.fn.rup_jqtable.plugins.filter = {};
	jQuery.fn.rup_jqtable.plugins.filter.defaults = {
		core:{
			startOnPage :null
		},
		filter:{
			url: null,
			showHidden:false,
			transitionConfig:{
				duration: 'slow',
				effect: 'blind'
			}
		}
	};

	/* ********* */
	/* EVENTOS
  /* ********* */

	/**
   *  Se lanza antes de producirse la petición de filtrado.
   *
   * @event module:rup_jqtable#rupTable_beforeFilter
   * @property {Event} e - Objeto Event correspondiente al evento disparado.
   * @example
   * $("#idComponente").on("rupTable_beforeFilter", function(event){ });
   */

	/**
    *   El botón de limpiar el formulario, limpia y filtra el formulario. Este evento se lanza antes de limpiar el formulario del filtro pero antes de filtrar con el formulario limpio.
    *
    * @event module:rup_jqtable#rupTable_filter_beforeCleanFilterForm
    * @property {Event} e - Objeto Event correspondiente al evento disparado.
    * @example
    * $("#idComponente").on("rupTable_filter_beforeCleanFilterForm", function(event){ });
    */

	/**
    *   El botón de limpiar el formulario, limpia y filtra el formulario. Este evento se lanza después de limpiar el formulario del filtro pero antes de filtrar con el formulario limpio.
    *
    * @event module:rup_jqtable#rupTable_filter_afterCleanFilterForm
    * @property {Event} e - Objeto Event correspondiente al evento disparado.
    * @example
    * $("#idComponente").on("rupTable_filter_afterCleanFilterForm", function(event,){ });
    */

})(jQuery);


text:
/* nodeunit tests */

var signature = require("../../build/signature.js");

exports.testScoping = function(test){
    var myObject = {
        objectVar: "I am an object var, context is good",
        myFunction: signature({
            "string": function(str) {
                return this.objectVar + " - " + str;
            }
        })
    };

    test.strictEqual(
        myObject.myFunction("test"),
        "I am an object var, context is good - test",
        "Proper Scoping of the called methods"
    );

    test.done();
};

exports.testNegator = function(test){
    var myFunction = signature({
        "string": function(str) {
            return "string - " + str;
        },
        "!string": function(notStr) {
            return "!string - " + notStr;
        }
    });

    test.strictEqual(
        myFunction("test"),
        "string - test"
    );

    test.strictEqual(
        myFunction(101),
        "!string - 101"
    );

    test.done();
};

exports.testVariousParsing = function(test){
    var myFunction = signature({
        "isNegative": function (negativeNumber) {
            return "negative number " + negativeNumber;
        },
        "[number]": function(optionalNumber) {
            return "optional number " + optionalNumber;
        },
        "function": function(funct) {
            return funct.apply();
        },
        "string": function(str) {
            return str;
        },
        "number, number": function(number1, number2) {
            return "multiply 2 numbers: " + number1*number2;
        },
        "number, number, number": function(number1, number2, number3) {
            return "multiply 3 numbers: " + number1*number2*number3;
        },
        "string, number": function(str, number) {
            return str + number;
        }
    }, {
        isNegative: function (value) {
            return (value < 0);
        }
    });

    test.strictEqual(
        myFunction(),
        "optional number undefined"
    );

    // BUGBUG fails because the expression parser doesn't build an object that supports empty paths.
    // May be solved by checking if we're at an end node

    test.strictEqual(
        myFunction(111),
        "optional number 111"
    );

    test.strictEqual(
        myFunction(function() {
            return ("executed function passed as param");
        }),
        "executed function passed as param"
    );

    test.strictEqual(
        myFunction("returned string passed as param"),
        "returned string passed as param"
    );

    test.strictEqual(
        myFunction(-10),
        "negative number -10"
    );

    test.strictEqual(
        myFunction(5, 6),
        "multiply 2 numbers: 30"
    );

    test.strictEqual(
        myFunction(5, 6, 2),
        "multiply 3 numbers: 60"
    );

    test.strictEqual(
        myFunction("Printing six: ", 6),
        "Printing six: 6"
    );

    test.strictEqual(
        myFunction(["should not do anything with Array"]),
        undefined
    );

    test.done();
};

exports.testOptionalsAtTheStart = function(test){
    var myFunction = signature({
        "[string], [function], number": function (str, funct, num) {
            return [str, typeof funct, num];
        }
    });

    test.deepEqual(
        myFunction("d", 50),
        ["d", "undefined", 50]
    );

    test.deepEqual(
        myFunction("d", function () {}, 40),
        ["d", "function", 40]
    );

    test.deepEqual(
        myFunction(50),
        [undefined, "undefined", 50]
    );

    test.deepEqual(
        myFunction(function () {}, 50),
        [undefined, "function", 50]
    );

    test.done();
};

exports.testOptionalsAtTheEnd = function(test){
    var myFunction = signature({
        "number, [string], [function]": function(num, str, funct) {
            //optionals at the end
            return [num, str, typeof funct];
        }
    });

    test.deepEqual(
        myFunction(50, "d"),
        [50, "d", "undefined"]
    );

    test.deepEqual(
        myFunction(50, "d", function () {}),
        [50, "d", "function"]
    );

    test.deepEqual(
        myFunction(50, function () {}),
        [50, undefined, "function"]
    );

    test.done();
};

exports.testjQueryLookalike = function(test){
    var $ = {
        on: signature({
            "any, [any], [any], function": function(events, selector, data, callback) {            //must be first or no match
                //console.log("******** events, [selector], [data], function ********");
                return [events, selector, data, typeof callback];
            },
            "any, [any], [any]": function(events, selector, data) {
                //console.log("******** events, [selector], [data] ********");
                return [events, selector, data];
            }
        })
    };

    test.deepEqual(
        $.on(),
        undefined
    );

    test.deepEqual(
        $.on("arg1", "arg2", function() {}),
        ["arg1", "arg2", undefined, "function"]
    );

    test.deepEqual(
        $.on("arg1", "arg2", "arg3"),
        ["arg1", "arg2", "arg3"]
    );

    test.deepEqual(
        $.on("arg1", "arg2", "arg3", function() {}),
        ["arg1", "arg2", "arg3", "function"]
    );

    test.done();
};

exports.testEmptyPaths = function(test){
    var myFunction = signature({
        "[number]": function(optionalNumber) {
            return "optional number " + optionalNumber;
        }
    });

    test.strictEqual(
        myFunction(),
        "optional number undefined"
    );

    test.strictEqual(
        myFunction(1),
        "optional number 1"
    );

    test.done();
};

exports.testEmptyPaths2 = function(test){
    var myFunction = signature({
        "[number], [number]": function(optionalNumber1, optionalNumber2) {
            return "optional numbers " + optionalNumber1 + " " + optionalNumber2;
        }
    });

    test.strictEqual(
        myFunction(),
        "optional numbers undefined undefined"
    );

    test.strictEqual(
        myFunction(1),
        "optional numbers 1 undefined"
    );

    test.strictEqual(
        myFunction(1, 2),
        "optional numbers 1 2"
    );

    test.done();
};

exports.testEmptyExpression= function(test){
    var myFunction = signature({
        "": function() {
            return "no arguments";
        }
    });

    test.strictEqual(
        myFunction(),
        "no arguments"
    );

    test.done();
};

exports["Test jQuery .on lookalike"] = function(test){

    var $ = {
        on: signature({
            "!object, [string], [any], function": function(types, selector, data, fn) {
                return [types, selector, data, typeof fn];
            },
            "!object, [string], [any], false": function(types, selector, data) {
                var fn = function() {return false;};
                return [types, selector, data, typeof fn];
            },
            "object, [string], [any]": function(types, selector, data) {
                return [types, selector, data];
            }
        })
    };

    test.deepEqual(
        $.on("selector", "subselector", 3, function () {}),
        ["selector", "subselector", 3, "function"]
    );

    test.deepEqual(
        $.on("selector", "subselector", function () {}),
        ["selector", "subselector", undefined, "function"]
    );

    test.done();
};

exports["Test ..."] = function(test){

    var $ = {
        on: signature({
            "!object..., object...": function(notObjects, object) {
                return [notObjects, object];
            },
            "!object..., [object...]": function(notObjects, object) {
                return [notObjects, object];
            }
        })
    };

    test.deepEqual(
        $.on("a", "b", 1, {1:1}, {2:2}),
        [["a", "b", 1], [{1:1}, {2:2}]]
    );

    test.done();
};

exports["Test ... Part #2"] = function(test){

    var $ = {
        on: signature({
            "!object..., [object...], string": function(notObjects, object, string) {
                return [notObjects, object, string];
            }
        })
    };

    test.deepEqual(
        $.on("a", "b", 1, "e"),
        [["a", "b", 1], undefined, "e"]
    );

    test.done();
};

exports["Test catchall"] = function(test){

    var $ = {
        on: signature({
            "*": function() {
                return arguments[3];
            }
        })
    };

    test.deepEqual(
        $.on("a", "b", 1, "e"),
        "e"
    );

    test.done();
};

redpajama_set_name: RedPajamaGithub


text:
1. [icons8](https://icons8.com/)
2. [flaticon](http://www.flaticon.com/)
3. [freepik](http://www.freepik.com/)
4. [iconfinder](https://www.iconfinder.com/)

##  Стоки
1. [Sell image](http://sell-image.com/)
2. [pexels](https://www.pexels.com/)
3. [unsplash - free](https://unsplash.com/)
4. [stock up](https://www.sitebuilderreport.com/stock-up)
5. [stocksnap - free](https://stocksnap.io/)

## Градиенты
1. [WebGradients](https://webgradients.com/?utm_source=forwebdev&utm_medium=announcement&utm_campaign=webgradients--180-priyatnyh-gradientov-dl)

## Кнопочки
1. [Button Styles Inspiration](https://tympanus.net/Development/ButtonStylesInspiration/)
2. [Creative Button Styles](https://tympanus.net/Development/CreativeButtons/)

## Ховеры
1. [Hover Effect Ideas](https://tympanus.net/Development/HoverEffectIdeas/index.html)
2. [Caption Hover Effects](https://tympanus.net/Tutorials/CaptionHoverEffects/index3.html)

## Сайты
1. [Bare Bones Broth](https://www.barebonesbroth.com/)
2. [Brdr Kruger](https://brdr-kruger.com/en)
3. [Helbak Ceramics](http://www.helbak.com/)
4. [YoGadget](http://yogadget.ru/)
5. [Трио](http://mytrio.ru/choice/)
6. [Калуга астрал](http://hr.astralnalog.ru/)
7. [Layer](https://layer.com/)
8. [Syncano](https://www.syncano.io/)
9. [Adverti](https://adverti.io/)
10. [Cole Jackowski](http://colejackowski.com/)
11. [AI Domains](https://whois.ai/cgi-bin/main.py)
12. [Flynn](https://flynn.io/)
13. [Supergiant](https://supergiant.io/)
14. [Fresh Flash](http://www.freshflash.su/)
15. [Enjoy Me](https://enjoyme.ru/)
16. [Status](https://status.im/)


text:
Given(/^a project "([^"]*)" with a donation address "([^"]*)" associated with "([^"]*)"$/) do |arg1, arg2, arg3|
  @project = Project.create!(
    name: arg1,
    full_name: "example/#{arg1}",
    bitcoin_address: 'mq4NtnmQoQoPfNWEPbhSvxvncgtGo6L8WY',
    hold_tips: false,
    address_label: "project-#{arg1}",
  )
  step %Q[the project has a donation address "#{arg2}" associated with "#{arg3}"]
end

Then(/^I should see the project donation address associated with "(.*?)"$/) do |arg1|
  address = @project.donation_addresses.find_by(sender_address: arg1).donation_address
  expect(address).not_to be_blank
  expect(page).to have_content(address)
end

Given(/^there's a new incoming transaction of "(.*?)" to the donation address associated with "(.*?)"$/) do |arg1, arg2|
  address = @project.donation_addresses.find_by(sender_address: arg2).donation_address
  expect(address).not_to be_blank
  BitcoinDaemon.instance.add_transaction(account: @project.address_label, amount: arg1.to_d, address: address)
end

Given(/^there's a new incoming transaction of "([^"]*)" to "([^"]*)" in transaction "([^"]*)"$/) do |arg1, arg2, arg3|
  donation_address = DonationAddress.find_by!(donation_address: arg2)
  project = donation_address.project
  BitcoinDaemon.instance.add_transaction(
    account: project.address_label,
    amount: arg1.to_d,
    address: donation_address.donation_address,
    txid: arg3,
  )
end

Then(/^I should see the donor "(.*?)" sent "(.*?)"$/) do |arg1, arg2|
  within ".donor-row", text: arg1 do
    expect(find(".amount").text.to_d).to eq(arg2.to_d)
  end
end

Given(/^the project has a donation address "(.*?)" associated with "(.*?)"$/) do |arg1, arg2|
  @project.donation_addresses.create!(sender_address: arg2, donation_address: arg1)
end

When(/^there's a new incoming transaction of "([^"]*?)" to the project donation address$/) do |arg1|
  BitcoinDaemon.instance.add_transaction(account: @project.address_label, amount: arg1.to_d, address: @project.bitcoin_address)
end


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using MessageHub.Lib.DTO;
using MessageHub.Lib.Entity;

namespace MessageHub.Lib.Repository
{
	public interface IChatRepository<TEntity, TContext> : IDisposable
		where TEntity : BaseChatEntity
		where TContext : class
	{
		TContext Context { get; set; }

		/// <summary>
		/// Get a single entity
		/// </summary>
		TEntity Get(int id);

		/// <summary>
		/// Gets multiple entity based on filter and ordering by property
		/// </summary>
		IEnumerable<TEntity> Get();

		/// <summary>
		/// Save Data in DataStore
		/// </summary>
		void Insert(TEntity entity);

		/// <summary>
		/// Remove Data in DataStore
		/// </summary>
		void Delete(int id);

		/// <summary>
		/// Update the record in DataStore based on changes
		/// </summary>
		void Update(TEntity entity);

		/// <summary>
		/// Calls Save changes of Context
		/// </summary>
		int Save();
	}
}


text:
'use strict';

require('dotenv').config({silent: true});

const irc = require('irc');
const moment = require('moment');
const crypto = require('crypto');

const euro2016commands = require('./commands/euro2016');
const alert = require('./util/alert');
const ircUtil = require('./util/irc');
const track = require('./util/track');

const server = process.env.IRC_SERVER || 'irc.rizon.net';
const nick = process.env.IRC_NICK || 'Euro2016';
const channels = process.env.IRC_CHANNELS.split(',').map(channel => `#${channel }`) || [];
const port = process.env.IRC_PORT || 6667;
const realName = process.env.IRC_REALNAME || null;
const userName = process.env.IRC_NAME || null;

const client = new irc.Client(server, nick, { port, channels, realName, userName });

const ALERT_MESSAGES_PER_MINUTE = process.env.IRC_ALERT_MESSAGES_PER_MINUTE || 100;
const commandMonitor = {};

const helpMapping = {
    group: {
        desc: 'Show standings for a group',
        usage: '[query]',
        example: ['a', 'france']
    },
    country: {
        desc: 'Show matches for a country',
        usage: '[country]',
        example: ['england', 'rep ireland', 'ger'],
        aliases: ['team']
    },
    matches: {
        desc: 'Show matches on a given day',
        usage: '[day]',
        example: ['tomorrow', 'this friday', 'yesterday']
    },
    player: {
        desc: 'Query player information (beta)',
        usage: '[player name]',
        example: ['rooney', 'rashford', 'ibra', 'cech']
    },
    next: {
        desc: 'Show the next match',
        usage: ''
    },
    lineups: {
        desc: 'Show the lineups for a specific match or the next match',
        usage: '!lineups [COUNTRY]',
        example: ['', 'england', 'ger']
    }
};

const commandMapping = {
    hello: require('./commands/hello'),
    help: (command, client) => require('./commands/help')(command, client, helpMapping, Object.keys(commandMapping)),
    group: euro2016commands.group,
    country: euro2016commands.country,
    team: euro2016commands.country,
    matches: euro2016commands.matches,
    player: euro2016commands.player,
    next: euro2016commands.next,
    lineups: euro2016commands.lineups
};

client.addListener('registered', () => {
    if (process.env.IRC_PASSWORD) {
        client.say('nickserv', `IDENTIFY ${process.env.IRC_PASSWORD}`);
    }
});

client.addListener('message', (from, to, message) => {
    const command = ircUtil.parseCommand(message, from, to);
    if (!command) {
        return;
    }
    const min = moment(new Date).format('YYYY-MM-DD HH:mm');
    if (!commandMonitor[min]) {
        commandMonitor[min] = 0;
    }
    commandMonitor[min]++;
    if (commandMonitor[min] === ALERT_MESSAGES_PER_MINUTE) {
        alert('Euro 2016 IRC Bot High usage!', `Over ${ALERT_MESSAGES_PER_MINUTE} commands per minute detected.`);
    }

    const userHash = crypto.createHash('sha256').update(from).digest('hex');
    if (ircUtil.mapCommand(command, commandMapping, client)) {
        track('command', userHash, { command, server, message });
    } else {
        track('invalid_command', userHash, { command, server, message });
    }
});

/* eslint-disable no-console */
client.addListener('error', message => {
    alert('ERROR with Euro2016 IRC Bot', message);
    track('error', 0, { server, nick, message });
    console.log('error: ', message);
});


text:
'use strict';

var spawn = require('cross-spawn');
var which = require('which');

module.exports = function (grunt) {

  var checkBinary = function (cmd, errMsg) {
    try {
      which.sync(cmd);
    } catch (err) {
      return grunt.warn(
        '\n' + errMsg + '\n' +
        'More info: https://github.com/maiis/grunt-tomcat\n'
      );
    }
  };

  grunt.registerTask('tomcat', 'Start / Stop Catalina Server', function () {

    var options = this.options();
    var bin = 'catalina';
    var cmd = this.args[0];

    if (options.bootstrap) {
      if (!grunt.file.exists(options.bootstrap)) {
        return grunt.warn(
          '\n Path to bootstrap dose not exist.' +
          'More info: https://github.com/maiis/grunt-tomcat\n'
        );
      } else {
        bin = 'sh ' + options.bootstrap;
      }
    } else {
      checkBinary(bin,
        'You need to have Catalina installed and in your PATH for this task to work.'
      );
    }

    grunt.verbose.writeln('Command: ' + bin + ' ' + cmd);

    spawn(bin, [cmd], {stdio: 'inherit'});
  });

};


text:
window.PAGE={handePage:100};
document.addEventListener("deviceready", function(){
  document.addEventListener("backbutton", function(e){
    if(window.disabledBackButton) {
      return e.preventDefault();
    }
    var pages = document.getElementsByClassName('box-block');
    if(pages.length){
      e.preventDefault();
      window.backPage(pages[pages.length-1].id);
    } else {
      navigator.app.exitApp();
    }
  }, false);
}, false);
window.dispatch = function(fn, args) {
    fn = (typeof fn == "function") ? fn : window[fn];
    return fn.apply(this, args || []);
}
window.openPage = function(p, params, callback){
  var showPageEffect = function(){
    window.PAGE.handePage++
    var firstStyle = 'z-index:'+window.PAGE.handePage
    var secondStyle = ';transform: translateY(0px);will-change: transform, -webkit-transform, opacity;transition-duration: 280ms;transition-timing-function: cubic-bezier(0.36,0.66,0.04,1);'
    if(SO.code === 2){
      secondStyle = ';transform: translateX(0px);transition-duration: 280ms;'
    }
    if(window.disabledOpenPageEffect) {
      secondStyle = ';opacity: 1;top: 0;'
    }
    var newStyle = document.getElementById(p).getElementsByClassName('page')[0].getAttribute('style')
    if(newStyle) {
      newStyle += ' '+firstStyle + secondStyle
    } else {
      newStyle = firstStyle + secondStyle
    }
    document.getElementById(p).getElementsByClassName('page')[0].setAttribute("style", newStyle);
    if(callback) {
      window.dispatch(callback, [params]);
    }
    var newClass = document.getElementById(p).getElementsByClassName('page')[0].getAttribute('class')
    newClass += ' show'
    var validOpenPage = function(){
      setTimeout(function(){
        if(document.getElementById(p) && document.getElementById(p).querySelectorAll('.page').length){
          showPageBind();
        } else {
          validOpenPage();
        }
      },10);
    }
    validOpenPage();
    var customEvent = new CustomEvent("openPage",{ "detail": {page:p}});
    document.dispatchEvent(customEvent);
    var showPageBind = function(){
      setTimeout(function(){
        document.getElementById(p).getElementsByClassName('page')[0].setAttribute('class',newClass)
        setTimeout(function(){
          var style = document.getElementById(p).getElementsByClassName('page')[0].getAttribute('style')
          style = style.replace(secondStyle,'')
          document.getElementById(p).getElementsByClassName('page')[0].setAttribute('style',style)
        },280)
      }, 100);
    };
  }
  if(arguments.length===2) {
    callback = params
  }
  if(p.indexOf('.html') < 0){
    p =p+'.html';
  }
  //check if page is openned.
  if(document.getElementById(p)){
    var pages = document.getElementsByClassName('box-block');
    if(pages[pages.length-1].id === document.getElementById(p).id){
      return false;
    }
    document.getElementById(p).parentNode.removeChild(document.getElementById(p));
  }
  var xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    if (this.readyState == 4) {
      var page = this.responseText;
      page = page.replace('backPage()','backPage(\''+p+'\')');
      var body = document.getElementsByTagName('body')[0]
      if(document.getElementsByClassName('body').length){
        body = document.getElementsByClassName('body')[0]
      }
      var div = document.createElement('div')
      div.setAttribute('class','box-block')
      div.setAttribute('id',p)
      div.innerHTML = page
      body.appendChild(div);
      showPageEffect();
    }
  };
  xhttp.open("GET", p + '?cache='+new Date().getTime(), true);
  document.dispatchEvent(new Event('firedCloseMenu'));
  xhttp.send();
}
window.backPage = function(p){
  var page = ""
  if(!p) {
    var pages = document.querySelectorAll('.page.show')
    var elementFind = { zIndex:-1 }
    for (var i = 0; i < pages.length; i++) {
      var zIndexNow = Number(pages[i].style['zIndex'])
      if(elementFind.zIndex<zIndexNow) {
        elementFind.zIndex=zIndexNow
        elementFind.element = pages[i]
      }
    }
    if(elementFind.zIndex) {
      p = elementFind.element.parentElement.id
    }
  }
  var page = document.getElementById(p).getElementsByClassName('page')[0];
  var style = ';transform: translateY(0px);will-change: transform, -webkit-transform, opacity;transition-duration: 280ms;'
  if(window.disabledOpenPageEffect) {
    style = ''
  }
  var newStyle = document.getElementById(p).getElementsByClassName('page')[0].getAttribute('style')
  if(newStyle) {
    newStyle += ' '+style
  } else {
    newStyle = style
  }
  document.getElementById(p).getElementsByClassName('page')[0].setAttribute("style", newStyle);
  var newClass = document.getElementById(p).getElementsByClassName('page')[0].getAttribute('class')
  newClass += newClass.replace('show','')
  document.getElementById(p).getElementsByClassName('page')[0].setAttribute('class',newClass);
  var customEvent = new CustomEvent("backPage",{ "detail": {page:p}});
  document.dispatchEvent(customEvent);
  setTimeout(function(){
    var elm = document.getElementById(p);
    elm.parentElement.removeChild(elm);
  }, !window.disabledOpenPageEffect ? 280 : 0)
}


text:
Custom Switch for iOS, based on UIControl class.

Primitive and easy customizable switch for iOS.

![A preview of this control](http://i.piccy.info/i9/5744c7bfd25dc3128ccd9beab742aa42/1448004349/22445/973185/Simulator_Screen_Shot_Nov_20_2015_09_24_33.png)

``` Objective-C
RSSwitch *myswitch = [[RSSwitch alloc] initWithFrame:CGRectMake(30, 30, 100, 50)];
[myswitch setOnColor:[UIColor greenColor]];
[myswitch setOffColor:[UIColor whiteColor]];

// you can easily change border radius/color/width by accessing switch view layer
[myswitch setBorderColor:[UIColor lightGrayColor]];
myswitch.handleView.backgroundColor = [UIColor whiteColor];
myswitch.handleView.layer.borderColor = [UIColor lightGrayColor].CGColor;

// switch notificate you for events UIControlEventTouchUpInside and UIControlEventTouchUpOutnside
[myswitch addTarget:self action:@selector(switchSwitched:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:myswitch];

```

``` Objective-C
-(void)switchSwitched:(RSSwitch *)sender {
    NSLog(@"state: %i", sender.isOn);
}
```

## License

RSSwitch is licensed under the terms of the MIT license. Please see the [LICENSE](LICENSE) file for full details.


text:
package org.hisp.dhis.query;

import com.google.common.collect.Lists;
import org.hisp.dhis.common.IdentifiableObject;
import org.hisp.dhis.common.PagerUtils;
import org.hisp.dhis.hibernate.HibernateUtils;
import org.hisp.dhis.schema.Property;
import org.hisp.dhis.schema.Schema;
import org.hisp.dhis.schema.SchemaService;
import org.hisp.dhis.system.util.ReflectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
public class InMemoryQueryEngine<T extends IdentifiableObject>
    implements QueryEngine<T>
{
    @Autowired
    private SchemaService schemaService;

    @Override
    public List<T> query( Query query )
    {
        validateQuery( query );
        List<T> list = runQuery( query );
        list = runSorter( query, list );

        return PagerUtils.pageCollection( list, query.getFirstResult(), query.getMaxResults() );
    }

    @Override
    public int count( Query query )
    {
        validateQuery( query );
        List<T> list = runQuery( query );

        return list.size();
    }

    private void validateQuery( Query query )
    {
        if ( query.getSchema() == null )
        {
            throw new QueryException( "Invalid Query object, does not contain Schema" );
        }

        if ( query.getObjects() == null )
        {
            throw new QueryException( "InMemoryQueryEngine requires an existing object list to work on." );
        }
    }

    @SuppressWarnings( "unchecked" )
    private List<T> runQuery( Query query )
    {
        return query.getObjects().stream()
            .filter( object -> test( query, (T) object ) )
            .map( object -> (T) object )
            .collect( Collectors.toList() );
    }

    private List<T> runSorter( Query query, List<T> objects )
    {
        List<T> sorted = new ArrayList<>( objects );

        sorted.sort( ( o1, o2 ) ->
        {
            for ( Order order : query.getOrders() )
            {
                int result = order.compare( o1, o2 );
                if ( result != 0 ) return result;
            }

            return 0;
        } );

        return sorted;
    }

    private boolean test( Query query, T object )
    {
        List<Boolean> testResults = new ArrayList<>();

        for ( Criterion criterion : query.getCriterions() )
        {
            Boolean testResult = false;

            // normal Restriction, just assume Conjunction
            if ( Restriction.class.isInstance( criterion ) )
            {
                Restriction restriction = (Restriction) criterion;
                testResult = testAnd( query, object, Lists.newArrayList( restriction ) );
            }
            else if ( Conjunction.class.isInstance( criterion ) )
            {
                Conjunction conjunction = (Conjunction) criterion;
                testResult = testAnd( query, object, conjunction.getCriterions() );
            }
            else if ( Disjunction.class.isInstance( criterion ) )
            {
                Disjunction disjunction = (Disjunction) criterion;
                testResult = testOr( query, object, disjunction.getCriterions() );
            }

            testResults.add( testResult );
        }

        return !testResults.contains( Boolean.FALSE );
    }

    private boolean testAnd( Query query, T object, List<Criterion> criterions )
    {
        for ( Criterion criterion : criterions )
        {
            if ( Restriction.class.isInstance( criterion ) )
            {
                Restriction restriction = (Restriction) criterion;
                Object value = getValue( query, object, restriction.getPath() );

                if ( !Collection.class.isInstance( value ) )
                {
                    if ( !restriction.getOperator().test( value ) )
                    {
                        return false;
                    }
                }
                else
                {
                    Collection<?> collection = (Collection<?>) value;

                    for ( Object item : collection )
                    {
                        if ( restriction.getOperator().test( item ) )
                        {
                            return true;
                        }
                    }

                    return false;
                }
            }
        }

        return true;
    }

    private boolean testOr( Query query, T object, List<Criterion> criterions )
    {
        for ( Criterion criterion : criterions )
        {
            if ( Restriction.class.isInstance( criterion ) )
            {
                Restriction restriction = (Restriction) criterion;
                Object value = getValue( query, object, restriction.getPath() );

                if ( !Collection.class.isInstance( value ) )
                {
                    if ( restriction.getOperator().test( value ) )
                    {
                        return true;
                    }
                }
                else
                {
                    Collection<?> collection = (Collection<?>) value;

                    for ( Object item : collection )
                    {
                        if ( restriction.getOperator().test( item ) )
                        {
                            return true;
                        }
                    }
                }
            }
        }

        return false;
    }

    private Object getValue( Query query, Object object, String path )
    {
        String[] paths = path.split( "\\." );
        Schema currentSchema = query.getSchema();

        for ( int i = 0; i < paths.length; i++ )
        {
            Property property = currentSchema.getProperty( paths[i] );

            if ( property == null )
            {
                throw new QueryException( "No property found for path " + path );
            }

            if ( property.isCollection() )
            {
                currentSchema = schemaService.getDynamicSchema( property.getItemKlass() );
            }
            else
            {
                currentSchema = schemaService.getDynamicSchema( property.getKlass() );
            }

            object = collect( object, property );

            if ( i == (paths.length - 1) )
            {
                if ( property.isCollection() )
                {
                    return Lists.newArrayList( object );
                }

                return object;
            }

        }

        throw new QueryException( "No values found for path " + path );
    }

    @SuppressWarnings( { "unchecked", "rawtypes" } )
    private Object collect( Object object, Property property )
    {
        object = HibernateUtils.unwrap( object );

        if ( Collection.class.isInstance( object ) )
        {
            Collection<?> collection = (Collection<?>) object;
            List<Object> items = new ArrayList<>();

            for ( Object item : collection )
            {
                Object collect = collect( item, property );

                if ( Collection.class.isInstance( collect ) )
                {
                    items.addAll( ((Collection) collect) );
                }
                else
                {
                    items.add( collect );
                }
            }

            return items;
        }

        return ReflectionUtils.invokeMethod( object, property.getGetterMethod() );
    }
}


text:
import { modules } from "app/AppRegistry"
import { matchRoute } from "app/navigation/routes"
import { defaultEnvironment } from "app/relay/createEnvironment"
import { GlobalStore, useFeatureFlag } from "app/store/GlobalStore"
import { RateLimiter } from "limiter"
import { useEffect } from "react"
import {
  createOperationDescriptor,
  fetchQuery,
  getRequest,
  GraphQLTaggedNode,
  Variables,
} from "relay-runtime"
import { logPrefetching } from "./loggers"

const DEFAULT_QUERIES_PER_INTERVAL = 60

let limiter: RateLimiter

// Initializes the rate limiter because we load parameters from Echo.
export const useInitializeQueryPrefetching = () => {
  const echoMessages = GlobalStore.useAppState((state) => state.artsyPrefs.echo.state.messages)

  useEffect(() => {
    const queriesPerInterval = Number(
      echoMessages.find((message) => message.name === "EigenQueryPrefetchingRateLimit")?.content ||
        DEFAULT_QUERIES_PER_INTERVAL
    )

    limiter = new RateLimiter({
      tokensPerInterval: queriesPerInterval,
      interval: "minute",
      fireImmediately: true,
    })
  }, [])
}

// Limit requests and don't execute when rate limit is reached.
async function isRateLimited() {
  const remainingRequests = await limiter.removeTokens(1)

  return remainingRequests < 0
}

const prefetchQuery = async (query: GraphQLTaggedNode, variables?: Variables) => {
  const environment = defaultEnvironment
  const operation = createOperationDescriptor(getRequest(query), variables ?? {})

  await fetchQuery(environment, query, variables ?? {}, {
    networkCacheConfig: { force: false },
  }).toPromise()

  // this will retain the result in the relay store so it's not garbage collected.
  environment.retain(operation)
}

const prefetchUrl = async (url: string, variables?: Variables) => {
  if (await isRateLimited()) {
    console.log("Reached prefetching rate limit.")
    return
  }

  const result = matchRoute(url)

  if (result.type !== "match") {
    return
  }

  const module = modules[result.module]

  if (module.type !== "react") {
    console.error(`Failed to prefetch ${url} (cannot prefetch ${module.type} module).`)
    return
  }

  const queries = module.Queries

  if (!queries) {
    console.error(`Failed to prefetch "${url}" (couldn't find queries).`)
    return
  }

  const options = { ...result.params, ...variables }

  try {
    for (const query of queries) {
      prefetchQuery(query, options)
    }
  } catch (error) {
    console.error(`Prefetching "${url}" failed.`, error)
  }

  if (logPrefetching) {
    console.log(`Prefetching "${url}"`)
  }
}

export const usePrefetch = () => {
  const enablePrefetching = useFeatureFlag("AREnableQueriesPrefetching")

  if (!enablePrefetching || __TEST__) {
    return () => null
  }

  return prefetchUrl
}


text:
package whatsmeow

import (
	"context"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"errors"
	"fmt"
	"sort"
	"strconv"
	"strings"
	"time"

	"go.mau.fi/libsignal/signalerror"
	"google.golang.org/protobuf/proto"

	"go.mau.fi/libsignal/groups"
	"go.mau.fi/libsignal/keys/prekey"
	"go.mau.fi/libsignal/protocol"
	"go.mau.fi/libsignal/session"

	waBinary "go.mau.fi/whatsmeow/binary"
	waProto "go.mau.fi/whatsmeow/binary/proto"
	"go.mau.fi/whatsmeow/types"
)

// GenerateMessageID generates a random string that can be used as a message ID on WhatsApp.
//
//   msgID := whatsmeow.GenerateMessageID()
//   cli.SendMessage(context.Background(), targetJID, msgID, &waProto.Message{...})
func GenerateMessageID() types.MessageID {
	id := make([]byte, 8)
	_, err := rand.Read(id)
	if err != nil {
		// Out of entropy
		panic(err)
	}
	return "3EB0" + strings.ToUpper(hex.EncodeToString(id))
}

type MessageDebugTimings struct {
	Queue time.Duration

	Marshal         time.Duration
	GetParticipants time.Duration
	GetDevices      time.Duration
	GroupEncrypt    time.Duration
	PeerEncrypt     time.Duration

	Send  time.Duration
	Resp  time.Duration
	Retry time.Duration
}

type SendResponse struct {
	// The message timestamp returned by the server
	Timestamp time.Time

	// The ID of the sent message
	ID types.MessageID

	// Message handling duration, used for debugging
	DebugTimings MessageDebugTimings
}

// SendMessage sends the given message.
//
// If the message ID is not provided, a random message ID will be generated.
//
// This method will wait for the server to acknowledge the message before returning.
// The return value is the timestamp of the message from the server.
//
// The message itself can contain anything you want (within the protobuf schema).
// e.g. for a simple text message, use the Conversation field:
//   cli.SendMessage(context.Background(), targetJID, "", &waProto.Message{
//       Conversation: proto.String("Hello, World!"),
//   })
//
// Things like replies, mentioning users and the "forwarded" flag are stored in ContextInfo,
// which can be put in ExtendedTextMessage and any of the media message types.
//
// For uploading and sending media/attachments, see the Upload method.
//
// For other message types, you'll have to figure it out yourself. Looking at the protobuf schema
// in binary/proto/def.proto may be useful to find out all the allowed fields.
func (cli *Client) SendMessage(ctx context.Context, to types.JID, id types.MessageID, message *waProto.Message) (resp SendResponse, err error) {
	isPeerMessage := to.User == cli.Store.ID.User
	if to.AD && !isPeerMessage {
		err = ErrRecipientADJID
		return
	}

	if len(id) == 0 {
		id = GenerateMessageID()
	}
	resp.ID = id

	start := time.Now()
	// Sending multiple messages at a time can cause weird issues and makes it harder to retry safely
	cli.messageSendLock.Lock()
	resp.DebugTimings.Queue = time.Since(start)
	defer cli.messageSendLock.Unlock()

	respChan := cli.waitResponse(id)
	// Peer message retries aren't implemented yet
	if !isPeerMessage {
		cli.addRecentMessage(to, id, message)
	}
	var phash string
	var data []byte
	switch to.Server {
	case types.GroupServer, types.BroadcastServer:
		phash, data, err = cli.sendGroup(ctx, to, id, message, &resp.DebugTimings)
	case types.DefaultUserServer:
		if isPeerMessage {
			data, err = cli.sendPeerMessage(to, id, message, &resp.DebugTimings)
		} else {
			data, err = cli.sendDM(ctx, to, id, message, &resp.DebugTimings)
		}
	default:
		err = fmt.Errorf("%w %s", ErrUnknownServer, to.Server)
	}
	start = time.Now()
	if err != nil {
		cli.cancelResponse(id, respChan)
		return
	}
	var respNode *waBinary.Node
	select {
	case respNode = <-respChan:
	case <-ctx.Done():
		err = ctx.Err()
		return
	}
	resp.DebugTimings.Resp = time.Since(start)
	if isDisconnectNode(respNode) {
		start = time.Now()
		respNode, err = cli.retryFrame("message send", id, data, respNode, ctx, 0)
		resp.DebugTimings.Retry = time.Since(start)
		if err != nil {
			return
		}
	}
	ag := respNode.AttrGetter()
	resp.Timestamp = ag.UnixTime("t")
	expectedPHash := ag.OptionalString("phash")
	if len(expectedPHash) > 0 && phash != expectedPHash {
		cli.Log.Warnf("Server returned different participant list hash when sending to %s. Some devices may not have received the message.", to)
		// TODO also invalidate device list caches
		cli.groupParticipantsCacheLock.Lock()
		delete(cli.groupParticipantsCache, to)
		cli.groupParticipantsCacheLock.Unlock()
	}
	return
}

// RevokeMessage deletes the given message from everyone in the chat.
// You can only revoke your own messages, and if the message is too old, then other users will ignore the deletion.
//
// This method will wait for the server to acknowledge the revocation message before returning.
// The return value is the timestamp of the message from the server.
func (cli *Client) RevokeMessage(chat types.JID, id types.MessageID) (SendResponse, error) {
	return cli.SendMessage(context.TODO(), chat, "", &waProto.Message{
		ProtocolMessage: &waProto.ProtocolMessage{
			Type: waProto.ProtocolMessage_REVOKE.Enum(),
			Key: &waProto.MessageKey{
				FromMe:    proto.Bool(true),
				Id:        proto.String(id),
				RemoteJid: proto.String(chat.String()),
			},
		},
	})
}

const (
	DisappearingTimerOff     = time.Duration(0)
	DisappearingTimer24Hours = 24 * time.Hour
	DisappearingTimer7Days   = 7 * 24 * time.Hour
	DisappearingTimer90Days  = 90 * 24 * time.Hour
)

// ParseDisappearingTimerString parses common human-readable disappearing message timer strings into Duration values.
// If the string doesn't look like one of the allowed values (0, 24h, 7d, 90d), the second return value is false.
func ParseDisappearingTimerString(val string) (time.Duration, bool) {
	switch strings.ReplaceAll(strings.ToLower(val), " ", "") {
	case "0d", "0h", "0s", "0", "off":
		return DisappearingTimerOff, true
	case "1day", "day", "1d", "1", "24h", "24", "86400s", "86400":
		return DisappearingTimer24Hours, true
	case "1week", "week", "7d", "7", "168h", "168", "604800s", "604800":
		return DisappearingTimer7Days, true
	case "3months", "3m", "3mo", "90d", "90", "2160h", "2160", "7776000s", "7776000":
		return DisappearingTimer90Days, true
	default:
		return 0, false
	}
}

// SetDisappearingTimer sets the disappearing timer in a chat. Both private chats and groups are supported, but they're
// set with different methods.
//
// Note that while this function allows passing non-standard durations, official WhatsApp apps will ignore those,
// and in groups the server will just reject the change. You can use the DisappearingTimer<Duration> constants for convenience.
//
// In groups, the server will echo the change as a notification, so it'll show up as a *events.GroupInfo update.
func (cli *Client) SetDisappearingTimer(chat types.JID, timer time.Duration) (err error) {
	switch chat.Server {
	case types.DefaultUserServer:
		_, err = cli.SendMessage(context.TODO(), chat, "", &waProto.Message{
			ProtocolMessage: &waProto.ProtocolMessage{
				Type:                waProto.ProtocolMessage_EPHEMERAL_SETTING.Enum(),
				EphemeralExpiration: proto.Uint32(uint32(timer.Seconds())),
			},
		})
	case types.GroupServer:
		if timer == 0 {
			_, err = cli.sendGroupIQ(context.TODO(), iqSet, chat, waBinary.Node{Tag: "not_ephemeral"})
		} else {
			_, err = cli.sendGroupIQ(context.TODO(), iqSet, chat, waBinary.Node{
				Tag: "ephemeral",
				Attrs: waBinary.Attrs{
					"expiration": strconv.Itoa(int(timer.Seconds())),
				},
			})
			if errors.Is(err, ErrIQBadRequest) {
				err = wrapIQError(ErrInvalidDisappearingTimer, err)
			}
		}
	default:
		err = fmt.Errorf("can't set disappearing time in a %s chat", chat.Server)
	}
	return
}

func participantListHashV2(participants []types.JID) string {
	participantsStrings := make([]string, len(participants))
	for i, part := range participants {
		participantsStrings[i] = part.String()
	}

	sort.Strings(participantsStrings)
	hash := sha256.Sum256([]byte(strings.Join(participantsStrings, "")))
	return fmt.Sprintf("2:%s", base64.RawStdEncoding.EncodeToString(hash[:6]))
}

func (cli *Client) sendGroup(ctx context.Context, to types.JID, id types.MessageID, message *waProto.Message, timings *MessageDebugTimings) (string, []byte, error) {
	var participants []types.JID
	var err error
	start := time.Now()
	if to.Server == types.GroupServer {
		participants, err = cli.getGroupMembers(ctx, to)
		if err != nil {
			return "", nil, fmt.Errorf("failed to get group members: %w", err)
		}
	} else {
		// TODO use context
		participants, err = cli.getBroadcastListParticipants(to)
		if err != nil {
			return "", nil, fmt.Errorf("failed to get broadcast list members: %w", err)
		}
	}
	timings.GetParticipants = time.Since(start)
	start = time.Now()
	plaintext, _, err := marshalMessage(to, message)
	timings.Marshal = time.Since(start)
	if err != nil {
		return "", nil, err
	}

	start = time.Now()
	builder := groups.NewGroupSessionBuilder(cli.Store, pbSerializer)
	senderKeyName := protocol.NewSenderKeyName(to.String(), cli.Store.ID.SignalAddress())
	signalSKDMessage, err := builder.Create(senderKeyName)
	if err != nil {
		return "", nil, fmt.Errorf("failed to create sender key distribution message to send %s to %s: %w", id, to, err)
	}
	skdMessage := &waProto.Message{
		SenderKeyDistributionMessage: &waProto.SenderKeyDistributionMessage{
			GroupId:                             proto.String(to.String()),
			AxolotlSenderKeyDistributionMessage: signalSKDMessage.Serialize(),
		},
	}
	skdPlaintext, err := proto.Marshal(skdMessage)
	if err != nil {
		return "", nil, fmt.Errorf("failed to marshal sender key distribution message to send %s to %s: %w", id, to, err)
	}

	cipher := groups.NewGroupCipher(builder, senderKeyName, cli.Store)
	encrypted, err := cipher.Encrypt(padMessage(plaintext))
	if err != nil {
		return "", nil, fmt.Errorf("failed to encrypt group message to send %s to %s: %w", id, to, err)
	}
	ciphertext := encrypted.SignedSerialize()
	timings.GroupEncrypt = time.Since(start)

	node, allDevices, err := cli.prepareMessageNode(ctx, to, id, message, participants, skdPlaintext, nil, timings)
	if err != nil {
		return "", nil, err
	}

	phash := participantListHashV2(allDevices)
	node.Attrs["phash"] = phash
	node.Content = append(node.GetChildren(), waBinary.Node{
		Tag:     "enc",
		Content: ciphertext,
		Attrs:   waBinary.Attrs{"v": "2", "type": "skmsg"},
	})

	start = time.Now()
	data, err := cli.sendNodeAndGetData(*node)
	timings.Send = time.Since(start)
	if err != nil {
		return "", nil, fmt.Errorf("failed to send message node: %w", err)
	}
	return phash, data, nil
}

func (cli *Client) sendPeerMessage(to types.JID, id types.MessageID, message *waProto.Message, timings *MessageDebugTimings) ([]byte, error) {
	node, err := cli.preparePeerMessageNode(to, id, message, timings)
	if err != nil {
		return nil, err
	}
	start := time.Now()
	data, err := cli.sendNodeAndGetData(*node)
	timings.Send = time.Since(start)
	if err != nil {
		return nil, fmt.Errorf("failed to send message node: %w", err)
	}
	return data, nil
}

func (cli *Client) sendDM(ctx context.Context, to types.JID, id types.MessageID, message *waProto.Message, timings *MessageDebugTimings) ([]byte, error) {
	start := time.Now()
	messagePlaintext, deviceSentMessagePlaintext, err := marshalMessage(to, message)
	timings.Marshal = time.Since(start)
	if err != nil {
		return nil, err
	}

	node, _, err := cli.prepareMessageNode(ctx, to, id, message, []types.JID{to, cli.Store.ID.ToNonAD()}, messagePlaintext, deviceSentMessagePlaintext, timings)
	if err != nil {
		return nil, err
	}
	start = time.Now()
	data, err := cli.sendNodeAndGetData(*node)
	timings.Send = time.Since(start)
	if err != nil {
		return nil, fmt.Errorf("failed to send message node: %w", err)
	}
	return data, nil
}

func getTypeFromMessage(msg *waProto.Message) string {
	switch {
	case msg.ViewOnceMessage != nil:
		return getTypeFromMessage(msg.ViewOnceMessage.Message)
	case msg.EphemeralMessage != nil:
		return getTypeFromMessage(msg.EphemeralMessage.Message)
	case msg.ReactionMessage != nil:
		return "reaction"
	case msg.Conversation != nil, msg.ExtendedTextMessage != nil, msg.ProtocolMessage != nil:
		return "text"
	//TODO this requires setting mediatype in the enc nodes
	//case msg.ImageMessage != nil, msg.DocumentMessage != nil, msg.AudioMessage != nil, msg.VideoMessage != nil:
	//	return "media"
	default:
		return "text"
	}
}

func getEditAttribute(msg *waProto.Message) string {
	if msg.ProtocolMessage != nil && msg.GetProtocolMessage().GetType() == waProto.ProtocolMessage_REVOKE && msg.GetProtocolMessage().GetKey() != nil {
		if msg.GetProtocolMessage().GetKey().GetFromMe() {
			return "7"
		} else {
			return "8"
		}
	} else if msg.ReactionMessage != nil && msg.ReactionMessage.GetText() == "" {
		return "7"
	}
	return ""
}

func (cli *Client) preparePeerMessageNode(to types.JID, id types.MessageID, message *waProto.Message, timings *MessageDebugTimings) (*waBinary.Node, error) {
	attrs := waBinary.Attrs{
		"id":       id,
		"type":     "text",
		"category": "peer",
		"to":       to,
	}
	if message.GetProtocolMessage().GetType() == waProto.ProtocolMessage_APP_STATE_SYNC_KEY_REQUEST {
		attrs["push_priority"] = "high"
	}
	start := time.Now()
	plaintext, err := proto.Marshal(message)
	timings.Marshal = time.Since(start)
	if err != nil {
		err = fmt.Errorf("failed to marshal message: %w", err)
		return nil, err
	}
	start = time.Now()
	encrypted, isPreKey, err := cli.encryptMessageForDevice(plaintext, to, nil)
	timings.PeerEncrypt = time.Since(start)
	if err != nil {
		return nil, fmt.Errorf("failed to encrypt peer message for %s: %v", to, err)
	}
	content := []waBinary.Node{*encrypted}
	if isPreKey {
		content = append(content, cli.makeDeviceIdentityNode())
	}
	return &waBinary.Node{
		Tag:     "message",
		Attrs:   attrs,
		Content: content,
	}, nil
}

func (cli *Client) prepareMessageNode(ctx context.Context, to types.JID, id types.MessageID, message *waProto.Message, participants []types.JID, plaintext, dsmPlaintext []byte, timings *MessageDebugTimings) (*waBinary.Node, []types.JID, error) {
	start := time.Now()
	allDevices, err := cli.GetUserDevicesContext(ctx, participants)
	timings.GetDevices = time.Since(start)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to get device list: %w", err)
	}

	attrs := waBinary.Attrs{
		"id":   id,
		"type": getTypeFromMessage(message),
		"to":   to,
	}
	if editAttr := getEditAttribute(message); editAttr != "" {
		attrs["edit"] = editAttr
	}

	start = time.Now()
	participantNodes, includeIdentity := cli.encryptMessageForDevices(ctx, allDevices, id, plaintext, dsmPlaintext)
	timings.PeerEncrypt = time.Since(start)
	content := []waBinary.Node{{
		Tag:     "participants",
		Content: participantNodes,
	}}
	if includeIdentity {
		content = append(content, cli.makeDeviceIdentityNode())
	}
	return &waBinary.Node{
		Tag:     "message",
		Attrs:   attrs,
		Content: content,
	}, allDevices, nil
}

func marshalMessage(to types.JID, message *waProto.Message) (plaintext, dsmPlaintext []byte, err error) {
	plaintext, err = proto.Marshal(message)
	if err != nil {
		err = fmt.Errorf("failed to marshal message: %w", err)
		return
	}

	if to.Server != types.GroupServer {
		dsmPlaintext, err = proto.Marshal(&waProto.Message{
			DeviceSentMessage: &waProto.DeviceSentMessage{
				DestinationJid: proto.String(to.String()),
				Message:        message,
			},
		})
		if err != nil {
			err = fmt.Errorf("failed to marshal message (for own devices): %w", err)
			return
		}
	}

	return
}

func (cli *Client) makeDeviceIdentityNode() waBinary.Node {
	deviceIdentity, err := proto.Marshal(cli.Store.Account)
	if err != nil {
		panic(fmt.Errorf("failed to marshal device identity: %w", err))
	}
	return waBinary.Node{
		Tag:     "device-identity",
		Content: deviceIdentity,
	}
}

func (cli *Client) encryptMessageForDevices(ctx context.Context, allDevices []types.JID, id string, msgPlaintext, dsmPlaintext []byte) ([]waBinary.Node, bool) {
	includeIdentity := false
	participantNodes := make([]waBinary.Node, 0, len(allDevices))
	var retryDevices []types.JID
	for _, jid := range allDevices {
		plaintext := msgPlaintext
		if jid.User == cli.Store.ID.User && dsmPlaintext != nil {
			if jid == *cli.Store.ID {
				continue
			}
			plaintext = dsmPlaintext
		}
		encrypted, isPreKey, err := cli.encryptMessageForDeviceAndWrap(plaintext, jid, nil)
		if errors.Is(err, ErrNoSession) {
			retryDevices = append(retryDevices, jid)
			continue
		} else if err != nil {
			cli.Log.Warnf("Failed to encrypt %s for %s: %v", id, jid, err)
			continue
		}
		participantNodes = append(participantNodes, *encrypted)
		if isPreKey {
			includeIdentity = true
		}
	}
	if len(retryDevices) > 0 {
		bundles, err := cli.fetchPreKeys(ctx, retryDevices)
		if err != nil {
			cli.Log.Warnf("Failed to fetch prekeys for %v to retry encryption: %v", retryDevices, err)
		} else {
			for _, jid := range retryDevices {
				resp := bundles[jid]
				if resp.err != nil {
					cli.Log.Warnf("Failed to fetch prekey for %s: %v", jid, resp.err)
					continue
				}
				plaintext := msgPlaintext
				if jid.User == cli.Store.ID.User && dsmPlaintext != nil {
					plaintext = dsmPlaintext
				}
				encrypted, isPreKey, err := cli.encryptMessageForDeviceAndWrap(plaintext, jid, resp.bundle)
				if err != nil {
					cli.Log.Warnf("Failed to encrypt %s for %s (retry): %v", id, jid, err)
					continue
				}
				participantNodes = append(participantNodes, *encrypted)
				if isPreKey {
					includeIdentity = true
				}
			}
		}
	}
	return participantNodes, includeIdentity
}

func (cli *Client) encryptMessageForDeviceAndWrap(plaintext []byte, to types.JID, bundle *prekey.Bundle) (*waBinary.Node, bool, error) {
	node, includeDeviceIdentity, err := cli.encryptMessageForDevice(plaintext, to, bundle)
	if err != nil {
		return nil, false, err
	}
	return &waBinary.Node{
		Tag:     "to",
		Attrs:   waBinary.Attrs{"jid": to},
		Content: []waBinary.Node{*node},
	}, includeDeviceIdentity, nil
}

func (cli *Client) encryptMessageForDevice(plaintext []byte, to types.JID, bundle *prekey.Bundle) (*waBinary.Node, bool, error) {
	builder := session.NewBuilderFromSignal(cli.Store, to.SignalAddress(), pbSerializer)
	if bundle != nil {
		cli.Log.Debugf("Processing prekey bundle for %s", to)
		err := builder.ProcessBundle(bundle)
		if cli.AutoTrustIdentity && errors.Is(err, signalerror.ErrUntrustedIdentity) {
			cli.Log.Warnf("Got %v error while trying to process prekey bundle for %s, clearing stored identity and retrying", err, to)
			cli.clearUntrustedIdentity(to)
			err = builder.ProcessBundle(bundle)
		}
		if err != nil {
			return nil, false, fmt.Errorf("failed to process prekey bundle: %w", err)
		}
	} else if !cli.Store.ContainsSession(to.SignalAddress()) {
		return nil, false, ErrNoSession
	}
	cipher := session.NewCipher(builder, to.SignalAddress())
	ciphertext, err := cipher.Encrypt(padMessage(plaintext))
	if err != nil {
		return nil, false, fmt.Errorf("cipher encryption failed: %w", err)
	}

	encType := "msg"
	if ciphertext.Type() == protocol.PREKEY_TYPE {
		encType = "pkmsg"
	}

	return &waBinary.Node{
		Tag: "enc",
		Attrs: waBinary.Attrs{
			"v":    "2",
			"type": encType,
		},
		Content: ciphertext.Serialize(),
	}, encType == "pkmsg", nil
}


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

<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
    [<!ENTITY instrInclude SYSTEM "classpath://../hibernate/crms/assessment/instrInclude.xml" >
     <!ENTITY instrInclude2 SYSTEM "classpath://../hibernate/crms/assessment/instrInclude2.xml" >
     <!ENTITY udsInstrInclude SYSTEM "classpath://../hibernate/crms/assessment/udsInstrInclude.xml" >]>

<hibernate-mapping>

	<class name="edu.ucsf.lava.crms.assessment.model.UdsFtldBis" table="instrumenttracking" select-before-update="true">

		&instrInclude;
		&udsInstrInclude;

		<join table="udsftldbis">
			<key column="InstrID"/>
			<property name="ftdcpc4f" column="FTDCPC4F" type="short"/>
			<property name="ftdworku" column="FTDWORKU" type="short"/>
			<property name="ftdmist" column="FTDMIST" type="short"/>
			<property name="ftdcrit" column="FTDCRIT" type="short"/>
			<property name="ftdworr" column="FTDWORR" type="short"/>
			<property name="ftdbad" column="FTDBAD" type="short"/>
			<property name="ftdpoor" column="FTDPOOR" type="short"/>
			<property name="ftdffear" column="FTDFFEAR" type="short"/>
			<property name="ftdbist" column="FTDBIST" type="short"/>
		</join>

        &instrInclude2;

	</class>

</hibernate-mapping>


text:
title: "Overview of the Machines tab"
excerpt: ""
---
The Machines tab gives information on the virtual machines that are available to host your applications. The VMs, which are application servers, can be hosted in a public cloud or within your infrastructure.
[block:image]
{
  "images": [
    {
      "image": [
        "https://files.readme.io/63ead7e-machines-overview-2.0.0.png",
        "machines-overview-2.0.0.png",
        2550,
        1350,
        "#046cb4"
      ]
    }
  ]
}
[/block]


text:
<?php

use App\FDAClient;
use Carbon\Carbon;

class ApiKeyTest extends TestCase {

	public function setUp()
	{
		parent::setUp();

	  $this->apiKey = env('OPENFDA_API_KEY');
	}

	public function tearDown()
	{
	  putenv('OPENFDA_API_KEY=' . $this->apiKey);

	  parent::tearDown();
	}

	/**
	 * Tests that when no key is set, we don't add anything to the api query
	 *
	 * @return void
	 */
	public function testNoKey()
	{
		putenv('OPENFDA_API_KEY=');

		$client = new FDAClient();

		$this->assertNotContains('api_key', $client->formatUrl([]));
	}

	/**
	 * Tests that when a key is set it is added to the api query
	 *
	 * @return void
	 */
	public function testOneKey()
	{
		putenv('OPENFDA_API_KEY=API_KEY1');

		$client = new FDAClient();

		$this->assertContains('api_key=API_KEY1', $client->formatUrl([]));
	}

	/**
	 * Tests that multiple keys are cycled
	 *
	 * @return void
	 */
	public function testMultipleKeys()
	{
		$keys = ['API_KEY1', 'API_KEY2', 'API_KEY3'];

		putenv('OPENFDA_API_KEY=' . implode(',', $keys));

		$client = new FDAClient();
		foreach($keys AS $key) {
			$this->assertContains('api_key=' . $key, $client->formatUrl([]));
		}
	}

}


text:
class Scholarship::IterationParticipationsController < ApplicationController
  include ::Scholarship::BaseController
  include Applicat::Mvc::Controller::Resource
  include VoluntaryScholarship::IterationParticipationsHelper

  transition_actions Scholarship::IterationParticipation::EVENTS

  before_filter :find_iteration_participation, only: [:new]

  load_and_authorize_resource

  rescue_from ActiveRecord::RecordNotFound, with: :not_found

  def index
    @iteration = Scholarship::Iteration.find(params[:iteration_id])
    @program = @iteration.program
    @iteration_participations = @iteration.participations.accepted.order_by_user_full_name.paginate(page: params[:page], per_page: 25)
  end

  def new
  end

  def create
    @iteration_participation = Scholarship::IterationParticipation.new(params[:scholarship_iteration_participation])
    @iteration_participation.user = current_user
    @iteration = @iteration_participation.iteration
    @program = @iteration.program

    if @iteration_participation.save
      redirect_to scholarship_iteration_participants_path(@iteration_participation.iteration), notice: t('general.form.successfully_created')
    else
      render :new
    end
  end

  def edit
  end

  def update
    if params[:scholarship_iteration_participation][:roles].present? && !can_update_scholarship_iteration_participation_roles?(@iteration_participation)
      raise CanCan::AccessDenied
    end

    if @iteration_participation.update_attributes(params[:scholarship_iteration_participation])
      redirect_to [:edit, @iteration_participation], notice: t('general.form.successfully_updated')
    else
      render :edit
    end
  end

  def destroy
    @iteration_participation.destroy
    redirect_to scholarship_iteration_participants_path(@iteration_participation.iteration), notice: t('general.form.destroyed')
  end

  def resource
    @iteration_participation
  end

  def with_state
    @iteration_participations = Scholarship::IterationParticipation.of_organization_owner(current_user).send(params[:state]).
    order_by_user_full_name.includes(iteration: { program: :organization}).paginate(page: params[:page], per_page: 25)
    render layout: false
  end

  private

  def find_iteration_participation
    @iteration_participation = case action_name
    when 'new'
      @iteration = Scholarship::Iteration.find(params[:iteration_id])
      @program = @iteration.program
      @iteration.participations.new
    end
  end

  def not_found
    redirect_to root_path, notice: t('general.exceptions.not_found')
  end
end


text:
using System;

namespace Platform.Support
{
#if PORTABLE

    namespace Core
    {
#endif

    public static partial class Extensions
    {
    }

#if PORTABLE
    }

#endif
}


text:
package com.ikut.utils;

import android.content.Context;

import com.ikut.R;

public class Utils {

	//Set all the navigation icons and always to set "zero 0" for the item is a category
	public static int[] iconNavigation = new int[] {
			0,
			0,
			R.drawable.ic_action_settings,
			R.drawable.ic_action_help};

	//get title of the item navigation
	public static String getTitleItem(Context context, int posicion){
		String[] titulos = context.getResources().getStringArray(R.array.nav_menu_items);
		return titulos[posicion];
	}

}//end class


text:
const React = require('react');
const types = require('react').PropTypes;
const {Actions} = require('p-flux');

class PlaylistPage extends React.Component {
  static propTypes = {
    playlist: types.object
  };

  onClick = () => {
    const {playlist} = this.props;
    const {id} = playlist;
    const addedEntry = this._input.value;
    Actions.socketEmitPlaylistUpdate({id, entry: addedEntry});
  }

  render() {
    const {playlist} = this.props;
    if (!playlist) return (
Playlist Does Not Exist
);

    const {entries} = playlist;
    const entriesList = entries && entries.map((entry, i) =>
{entry}
);
    return (

        <input name="entry-input" className="entry-input" ref={(c) => this._input = c}/>
        <button className="add-entry" onClick={this.onClick}>Add Entry</button>

          {entriesList}

    );
  }
}

module.exports = PlaylistPage;


text:
import axios from 'axios';
import { fetchTasks } from './taskActions';
import { openNotification } from '../../common/actions';
import * as types from '../constants/tasklistActionTypes';

export function addTasklist(payload){
	return function(dispatch){
		dispatch(addTasklistRequest());
		dispatch(openNotification());
		axios.post('/tasks/addtasklist', payload)
		.then(function(res){
			socket.emit('add tasklist', {tasklist: res.data.tasklist});
			dispatch(addTasklistSuccess(res.data.tasklist));
		})
		.catch(function(err){
			dispatch(addTasklistFailure(err));
		});
	}
}

export function addTasklistRequest(){
	return {
		type: types.ADD_TASKLIST_REQUEST
	}
}

export function addTasklistSuccess(tasklist){
	return {
		type: types.ADD_TASKLIST_SUCCESS,
		payload: tasklist
	}
}

export function addTasklistFailure(err){
	return {
		type: types.ADD_TASKLIST_FAILURE,
		payload: {
			errors: err
		}
	}
}

export function fetchTasklists(projectId){
	return function(dispatch){
		dispatch(fetchTasklistsRequest());
		dispatch(openNotification());
		axios.get('/tasks/fetchtasklists', {
			params: {
				projectId: projectId
			}
		})
		.then(function(res){
			dispatch(fetchTasklistsSuccess(res.data.tasklists));
			res.data.tasklists[0] && dispatch(fetchTasks(res.data.tasklists[0]._id, 0, res.data.tasklists[0].tasklistName));

			//clear currentTasklistId from state tree to prevent project which has none tasklist
			// from getting the previous [currentTasklistId] in state tree.
			res.data.tasklists.length == 0 && dispatch(setCurrentTasklistIdToNull());

		})
		.catch(function(err){
			dispatch(fetchTasklistsFailure(err));
		});
	}
}

export function fetchTasklistsRequest(){
	return {
		type: types.FETCH_TASKLISTS_REQUEST
	}
}

export function fetchTasklistsSuccess(tasklists){
	return {
		type: types.FETCH_TASKLISTS_SUCCESS,
		payload: tasklists
	}
}

export function fetchTasklistsFailure(err){
	return {
		type: types.FETCH_TASKLISTS_FAILURE,
		payload: {
			errors: err
		}
	}
}

export function setCurrentTasklistIdToNull(){
	return {
		type: types.SET_CURRENT_TASKLIST_ID_TO_NULL
	}
}

export function deleteTasklist(tasklistId, projectId){
	return function(dispatch){
		dispatch(deleteTasklistRequest());
		axios.delete('/tasks/deletetasklist', {
			params: {
				tasklistId: tasklistId
			}
		})
		.then(function(res){
			socket.emit('delete tasklist',{ tasklistId: res.data.tasklistId, room: projectId});
			dispatch(deleteTasklistSuccess(res.data.tasklistId));
		})
		.catch(function(err){
			dispatch(deleteTasklistFailure(err));
		});
	}
}

export function deleteTasklistRequest(){
	return {
		type: types.DELETE_TASKLIST_REQUEST
	}
}

export function deleteTasklistSuccess(tasklistId){
	return {
		type: types.DELETE_TASKLIST_SUCCESS,
		payload: tasklistId
	}
}

export function deleteTasklistFailure(err){
	return {
		type: types.DELETE_TASKLIST_FAILURE
	}
}