text:
package it.sinergis.datacatalogue.services;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import it.sinergis.datacatalogue.bean.jpa.Gsc006DatasourceEntity;
import it.sinergis.datacatalogue.bean.jpa.Gsc007DatasetEntity;
import it.sinergis.datacatalogue.common.Constants;
import it.sinergis.datacatalogue.exception.DCException;
import it.sinergis.datacatalogue.persistence.PersistenceServiceProvider;
import it.sinergis.datacatalogue.persistence.services.Gsc006DatasourcePersistence;
import it.sinergis.datacatalogue.persistence.services.Gsc007DatasetPersistence;
import it.sinergis.datacatalogue.persistence.services.util.ServiceUtil;

public class DatasetsService extends ServiceCommons {

	public static String RESPONSE_JSON_STATUS_DONE = "{Status:'Done',Description:'Operation ok'}";
	public static String RESPONSE_JSON_LIST_DATASET = " {dataset:[{name:'Dataset1',realname:'dataset1',datasourcename:'Datasource1',description:'First dataset',tobeingested:'true',refreshinterval:'3'},"
			+ "{name:'Dataset2',realname:'Dataset2',datasourcename:'Datasource2',description:'Second dataset'}]}";
	public static String RESPONSE_JSON_LIST_COLS_METADATA = " {columns:[{name:'Col1',type:'number',alias:'Col 1',visibility:'true'},{name:'Col2',type:'char',alias:'Col 2',visibility:'false'}]}";

	/** Logger. */
	private static Logger logger;

	/** Dao datasource. */
	private Gsc006DatasourcePersistence gsc006Dao;

	/** Dao dataset. */
	private Gsc007DatasetPersistence gsc007Dao;

	/** Constructor. */
	public DatasetsService() {
		logger = Logger.getLogger(this.getClass());
		gsc007Dao = PersistenceServiceProvider.getService(Gsc007DatasetPersistence.class);
		gsc006Dao = PersistenceServiceProvider.getService(Gsc006DatasourcePersistence.class);
	}

	public String createDataset(String req) {
		try {
			checkJsonWellFormed(req);
			checkMandatoryParameters(Constants.CREATE_DATASET, req);
			logger.info(req);

			// check if there's another dataset already saved with the same
			// name
			Gsc007DatasetEntity datasetEntity = getDatasetObjectFromDatasetname(req);

			// if no results found -> add new record
			if (datasetEntity == null) {
				// check if datasource with the given id exists
				String idDatasource = getFieldValueFromJsonText(req, Constants.DATASOURCE_ID_FIELD);

				if (StringUtils.isNumeric(idDatasource)) {
					Gsc006DatasourceEntity datasourceEntity = gsc006Dao.load(Long.parseLong(idDatasource));

					if (datasourceEntity != null) {
						Gsc007DatasetEntity dset = new Gsc007DatasetEntity();
						Gsc007DatasetEntity dsetUpdated = new Gsc007DatasetEntity();

						String datasourceType = getFieldValueFromJsonText(datasourceEntity.getJson(), Constants.TYPE);

						// If the datasource is a SHAPE
						if (datasourceType != null && datasourceType.equalsIgnoreCase(Constants.SHAPE)) {

							ObjectNode node = (ObjectNode) om.readTree(req);

							//TODO add code here
							String datasetFilename = getFieldValueFromJsonText(req, Constants.DSET_REALNAME_FIELD);
							String URL = getFieldValueFromJsonText(req, Constants.URL);
							//if the update is needed something special has to be specified as datasourcename
							if("auto_update".equalsIgnoreCase(datasetFilename)) {
								//get the datasourcename through the url (if no url specified error is thrown)
								if(URL == null || URL.isEmpty()) {
									logger.error("Since the dataset has to be retrieved from a remote location, the URL parameter needs to be specified in the request.");
									throw new DCException(Constants.ER706, req);
								}
								//create the datasetname through the given url
								int separatorIndex = URL.lastIndexOf("\\") != -1 ? URL.lastIndexOf("\\") +1 : URL.lastIndexOf("/") +1;
								datasetFilename = URL.substring(separatorIndex);
								String fileNameNoExtension = datasetFilename.substring(0, datasetFilename.lastIndexOf("."));
								node.put(Constants.DSET_REALNAME_FIELD,fileNameNoExtension+".shp");

								//update the json
								dset.setJson(node.toString());
								//call the updateshapeservice update method
								UpdateShapeService updateShapeService = new UpdateShapeService();
								dsetUpdated = updateShapeService.updateFile(dset);
							}

							String datasourcePath = getFieldValueFromJsonText(datasourceEntity.getJson(),
									Constants.PATH);

							String datasetFilenameSHP = datasetFilename.substring(0, datasetFilename.lastIndexOf(".")).concat(".shp");
							if (StringUtils.isNotEmpty(datasourcePath) && StringUtils.isNotEmpty(datasetFilenameSHP)) {

								if (!datasourcePath.endsWith("/")) {
									datasourcePath = datasourcePath.concat("/");
								}
								String columnsJson = ServiceUtil
										.createJSONColumnsFromShapeFile(datasourcePath + datasetFilenameSHP);

								//add the last updated field
								DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
								String dateFormatted = formatter.format(System.currentTimeMillis());
								node.put(Constants.LAST_UPDATE_TS, dateFormatted);

								node.put(Constants.COLUMNS, om.readTree(columnsJson));

								if(dsetUpdated != null ) {
									dset = dsetUpdated;
								}

								dset.setJson(node.toString());

							} else {
								logger.error("Path parameter is mandatory for datasources that handle shape files.");
								throw new DCException(Constants.ER703, req);
							}

							//gsc007Dao.save(dsetUpdated);
						}
						// if the datasource is POSTGIS
						else if (datasourceType != null && datasourceType.equalsIgnoreCase(Constants.POSTGIS)) {

							String urlDatasource = getFieldValueFromJsonText(datasourceEntity.getJson(), Constants.URL);
							String portDatasource = getFieldValueFromJsonText(datasourceEntity.getJson(),
									Constants.PORT);
							String schema = getFieldValueFromJsonText(datasourceEntity.getJson(),
									Constants.SCHEMA_FIELD);
							String username = getFieldValueFromJsonText(datasourceEntity.getJson(),
									Constants.USERNAME_FIELD);
							String password = getFieldValueFromJsonText(datasourceEntity.getJson(),
									Constants.PASSWORD_FIELD);
							String database = getFieldValueFromJsonText(datasourceEntity.getJson(), Constants.DATABASE);
							String datasetRealname = getFieldValueFromJsonText(req, Constants.DSET_REALNAME_FIELD);

							if (StringUtils.isNotEmpty(urlDatasource) && StringUtils.isNotEmpty(portDatasource)
									&& StringUtils.isNotEmpty(schema) && StringUtils.isNotEmpty(username)
									&& StringUtils.isNotEmpty(password) && StringUtils.isNotEmpty(datasetRealname)) {
								String columnsJson = ServiceUtil.createJSONColumnsFromPostGisDB(Constants.POSTGIS,
										urlDatasource, portDatasource, schema, database, username, password,
										datasetRealname);

								ObjectNode node = (ObjectNode) om.readTree(req);
								node.put(Constants.COLUMNS, om.readTree(columnsJson));

								dset.setJson(node.toString());
							} else {
								dset.setJson(req);
							}
						} else {
							dset.setJson(req);
						}

						// request exists

						dset = gsc007Dao.save(dset);

						logger.info("Dataset succesfully created");
						return createJsonStatus(Constants.STATUS_DONE, Constants.DATASETS_CREATED, dset.getId(), req);
					} else {
						// Datasource doesn't exist
						throw new DCException(Constants.ER705, req);
					}
				} else {
					// Datasource id has to be numeric
					throw new DCException(Constants.ER12, req);
				}

			} else {
				// dataset with the same name already exists
				throw new DCException(Constants.ER704, req);
			}

		} catch (DCException rpe) {
			return rpe.returnErrorString();
		} catch (Exception e) {
			logger.error("create dataset service error", e);
			DCException rpe = new DCException(Constants.ER01, req);
			logger.error("createDataset service: unhandled error " + rpe.returnErrorString());

			return rpe.returnErrorString();
		}
	}

	public String updateDataset(String req) {
		try {
			checkJsonWellFormed(req);
			checkMandatoryParameters(Constants.UPDATE_DATASET, req);
			logger.info(req);

			// Retrieving input parameters
			String idDataset = getFieldValueFromJsonText(req, Constants.DSET_ID_FIELD);

			Gsc007DatasetEntity entityFound = gsc007Dao.load(Long.parseLong(idDataset));
			if (entityFound == null) {
				throw new DCException(Constants.ER702, req);
			} else {

				// Before updating we have to be sure that dataset name
				// doesn't already exist in another record (not the one
				// we're updating)
				Gsc007DatasetEntity datasetEntity = getDatasetObjectFromDatasetname(req);

				// if no results found or the result is-> update record
				if (datasetEntity == null || (datasetEntity.getId().longValue() == entityFound.getId().longValue())) {

					// check that the datasource with the given id exists
					String idDatasource = getFieldValueFromJsonText(req, Constants.DATASOURCE_ID_FIELD);
					if (StringUtils.isNumeric(idDatasource)) {

						Gsc006DatasourceEntity datasourceEntity = gsc006Dao.load(Long.parseLong(idDatasource));

						if (datasourceEntity != null) {
							JsonNode node = om.readTree(req);
							((ObjectNode) node).remove(Constants.DSET_ID_FIELD);

							((ObjectNode) node).put(Constants.COLUMNS, om.readTree(getObjectFromJsonText(entityFound.getJson(), Constants.COLUMNS)));
							entityFound.setJson(node.toString());
							gsc007Dao.save(entityFound);

							logger.info("Dataset succesfully updated");
							return createJsonStatus(Constants.STATUS_DONE, Constants.DATASETS_UPDATED,
									entityFound.getId(), req);
						} else {
							// Datasource doesn't exist
							throw new DCException(Constants.ER705, req);
						}
					} else {
						// Datasource id has to be numeric
						throw new DCException(Constants.ER12, req);
					}
				} else {
					// Update failed, dataset with the same name already exists
					throw new DCException(Constants.ER704, req);
				}
			}

		} catch (DCException rpe) {
			return rpe.returnErrorString();
		} catch (Exception e) {
			logger.error("update dataset service error", e);
			DCException rpe = new DCException(Constants.ER01, req);
			logger.error("update service: unhandled error " + rpe.returnErrorString());

			return rpe.returnErrorString();
		}
	}

	public String deleteDataset(String req) {
		try {
			checkJsonWellFormed(req);
			checkMandatoryParameters(Constants.DELETE_DATASET, req);
			logger.info(req);

			// Retrieving input parameters
			String idDataset = getFieldValueFromJsonText(req, Constants.DSET_ID_FIELD);

			if (StringUtils.isNumeric(idDataset)) {
				DeleteService deleteService = new DeleteService();
				deleteService.deleteDataset(null, null, Long.parseLong(idDataset), null);

				logger.info("datasetr succesfully deleted");
				logger.info(req);
				return createJsonStatus(Constants.STATUS_DONE, Constants.DATASETS_DELETED, null, req);

			} else {
				// Dataset id has to be numeric
				throw new DCException(Constants.ER12, req);
			}

		} catch (DCException rpe) {
			return rpe.returnErrorString();
		} catch (Exception e) {
			logger.error("delete dataset service error", e);
			DCException rpe = new DCException(Constants.ER01, req);
			logger.error("delete service: unhandled error " + rpe.returnErrorString());

			return rpe.returnErrorString();
		}
	}

	public String listDataset(String req) {
		try {
			checkJsonWellFormed(req);
			checkMandatoryParameters(Constants.LIST_DATASET, req);
			logger.info(req);

			List<Gsc007DatasetEntity> dsets = null;
			// Retrieving input parameters
			String idDataset = getFieldValueFromJsonText(req, Constants.DSET_ID_FIELD);
			String datasetName = getFieldValueFromJsonText(req, Constants.DSET_NAME_FIELD);
			String idDatasource = getFieldValueFromJsonText(req, Constants.DATASOURCE_ID_FIELD);
			String idOrganization = getFieldValueFromJsonText(req, Constants.ORG_ID_FIELD);

			// Dataset id has to be numeric
			if (StringUtils.isNotEmpty(idDataset) && !StringUtils.isNumeric(idDataset)) {
				throw new DCException(Constants.ER12, req);
			}

			// Datasource id has to be numeric
			if (StringUtils.isNotEmpty(idDatasource) && !StringUtils.isNumeric(idDatasource)) {
				throw new DCException(Constants.ER12, req);
			}

			// Organization id has to be numeric
			if (StringUtils.isNotEmpty(idOrganization) && !StringUtils.isNumeric(idOrganization)) {
				throw new DCException(Constants.ER12, req);
			}

			// load dataset from its id if idDataset is the only parameter used
			// in this search
			if (StringUtils.isNotEmpty(idDataset) && StringUtils.isEmpty(datasetName)
					&& StringUtils.isEmpty(idDatasource) && StringUtils.isEmpty(idOrganization)) {
				dsets = new ArrayList<Gsc007DatasetEntity>();

				Gsc007DatasetEntity entityFound = gsc007Dao.load(Long.parseLong(idDataset));
				if (entityFound == null) {
					// No dataset found with given parameters.
					throw new DCException(Constants.ER702, req);
				}
				dsets.add(entityFound);

			} else if (StringUtils.isNotEmpty(idDataset) || StringUtils.isNotEmpty(datasetName)
					|| StringUtils.isNotEmpty(idDatasource) || StringUtils.isNotEmpty(idOrganization)) {

				String query = createSearchQuery(Constants.DATASETS_TABLE_NAME, Constants.DATASOURCE_TABLE_NAME,
						idDataset, datasetName, idDatasource, idOrganization);
				dsets = gsc007Dao.getDatasets(query);
			}
			// else we select all datasets
			else {

				dsets = gsc007Dao.loadAll();
			}

			logger.info("Datasets found: " + dsets.size());

			Map<String, List<Map<String, Object>>> dsetsResult = new HashMap<String, List<Map<String, Object>>>();

			List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();

			for (Gsc007DatasetEntity entity : dsets) {

				Map<String, Object> dsetsMap = new HashMap<String, Object>();
				// ID dataset
				dsetsMap.put(Constants.DSET_ID_FIELD, entity.getId().toString());

				// Dataset name
				String datasetNameField = getFieldValueFromJsonText(entity.getJson(), Constants.DSET_NAME_FIELD);
				dsetsMap.put(Constants.DSET_NAME_FIELD, datasetNameField);

				// Dataset real name
				String realName = getFieldValueFromJsonText(entity.getJson(), Constants.DSET_REALNAME_FIELD);
				dsetsMap.put(Constants.DSET_REALNAME_FIELD, realName);

				String idDataSource = getFieldValueFromJsonText(entity.getJson(), Constants.DATASOURCE_ID_FIELD);
				dsetsMap.put(Constants.DATASOURCE_ID_FIELD, idDataSource);

				Gsc006DatasourceEntity datasource = gsc006Dao.load(Long.parseLong(idDataSource));
				dsetsMap.put(Constants.DATASOURCE_NAME_FIELD,
						getFieldValueFromJsonText(datasource.getJson(), Constants.DATASOURCE_NAME_FIELD));

				// description
				String description = getFieldValueFromJsonText(entity.getJson(), Constants.DESCRIPTION_FIELD);
				dsetsMap.put(Constants.DESCRIPTION_FIELD, description);

				// url
				String url = getFieldValueFromJsonText(entity.getJson(), Constants.URL);
				dsetsMap.put(Constants.URL, url);

				// tobeingested
				String tobeingested = getFieldValueFromJsonText(entity.getJson(), Constants.DSET_TOBEINGESTED_FIELD);
				dsetsMap.put(Constants.DSET_TOBEINGESTED_FIELD, tobeingested);

				// refreshinterval
				String refreshinterval = getFieldValueFromJsonText(entity.getJson(),
						Constants.DSET_REFRESHINTERVAL_FIELD);
				dsetsMap.put(Constants.DSET_REFRESHINTERVAL_FIELD, refreshinterval);

				resultList.add(dsetsMap);
			}

			dsetsResult.put(Constants.DSET_RESULT, resultList);

			String jsonString;
			try {
				ObjectMapper mapper = new ObjectMapper();
				jsonString = mapper.writeValueAsString(dsetsResult);
			} catch (IOException e) {
				logger.error("IOException", e);
				throw new DCException(Constants.ER01, req);
			}

			return jsonString;

		} catch (DCException rpe) {
			return rpe.returnErrorString();
		} catch (Exception e) {
			logger.error("list dataset service error", e);
			DCException rpe = new DCException(Constants.ER01, req);
			logger.error("listDataset service: unhandled error " + rpe.returnErrorString());

			return rpe.returnErrorString();
		}
	}

	public String listColumns(String req) {
		try {
			checkJsonWellFormed(req);
			checkMandatoryParameters(Constants.LIST_DATASET_COLUMNS, req);
			logger.info(req);

			// Retrieving input parameters
			String idDataset = getFieldValueFromJsonText(req, Constants.DSET_ID_FIELD);

			if (StringUtils.isNumeric(idDataset)) {
				Gsc007DatasetEntity entityFound = gsc007Dao.load(Long.parseLong(idDataset));
				if (entityFound == null) {
					// No dataset found with given parameters.
					throw new DCException(Constants.ER702, req);
				} else {

					Map<String, Object> mapColumns = new HashMap<>();
					String columns = getObjectFromJsonText(entityFound.getJson(), Constants.COLUMNS);

					if (columns != null) {
						mapColumns.put(Constants.COLUMNS, om.readTree(columns));
						return om.writeValueAsString(mapColumns);
					} else {
						// No columns found for dataset
						throw new DCException(Constants.ER708, req);
					}
				}
			} else {
				// Dataset id has to be numeric
				throw new DCException(Constants.ER12, req);
			}

		} catch (DCException rpe) {
			return rpe.returnErrorString();
		} catch (Exception e) {
			logger.error("list dataset service error", e);
			DCException rpe = new DCException(Constants.ER01, req);
			logger.error("listDataset service: unhandled error " + rpe.returnErrorString());

			return rpe.returnErrorString();
		}
	}

	public String updateColumnsMetadata(String req) {
		try {
			checkJsonWellFormed(req);
			checkMandatoryParameters(Constants.UPDATE_DATASET_COLUMNS, req);
			logger.info(req);

			// Retrieving input parameters
			String idDataset = getFieldValueFromJsonText(req, Constants.DSET_ID_FIELD);
			String columns = getObjectFromJsonText(req, Constants.COLUMNS);

			if (StringUtils.isNumeric(idDataset)) {
				Gsc007DatasetEntity entityFound = gsc007Dao.load(Long.parseLong(idDataset));
				if (entityFound == null) {
					// No dataset found with given parameters.
					throw new DCException(Constants.ER702, req);
				} else {
					// we don't check columns, we just replace the columns value
					// with the one sent by the client
					ObjectNode node = (ObjectNode) om.readTree(entityFound.getJson());
					node.remove(Constants.COLUMNS);
					node.put(Constants.COLUMNS, om.readTree(columns));

					entityFound.setJson(node.toString());
					gsc007Dao.save(entityFound);

					logger.info("Dataset columns succesfully updated");
					return createJsonStatus(Constants.STATUS_DONE, Constants.DATASETS_UPDATED, entityFound.getId(),
							req);

				}
			} else {
				// Dataset id has to be numeric
				throw new DCException(Constants.ER12, req);
			}

		} catch (DCException rpe) {
			return rpe.returnErrorString();
		} catch (Exception e) {
			logger.error("list dataset service error", e);
			DCException rpe = new DCException(Constants.ER01, req);
			logger.error("listDataset service: unhandled error " + rpe.returnErrorString());

			return rpe.returnErrorString();
		}
	}

	public String createCronService(String req) {
		return RESPONSE_JSON_STATUS_DONE;
	}

	/**
	 * Retrieves the dataset given its name.
	 *
	 * @param json
	 * @return
	 * @throws RPException
	 */
	private Gsc007DatasetEntity getDatasetObjectFromDatasetname(String json) throws DCException {

		String datasetName = getFieldValueFromJsonText(json, Constants.DSET_NAME_FIELD);

		try {
			StringBuilder builderQuery = new StringBuilder();
			builderQuery.append("'");
			builderQuery.append(Constants.DSET_NAME_FIELD);
			builderQuery.append("' = '");
			builderQuery.append(datasetName);
			builderQuery.append("'");

			String query = createQuery(builderQuery.toString(), Constants.DATASETS_TABLE_NAME,
					Constants.JSON_COLUMN_NAME, "select");

			logger.debug("Executing query: " + query);
			List<Gsc007DatasetEntity> entityList = gsc007Dao.getDatasets(query);

			if (entityList.size() == 1) {
				return entityList.get(0);
			} else if (entityList.size() == 0) {
				return null;
			} else {
				logger.error("One result expected from query, results found: " + entityList.size());
				throw new DCException(Constants.ER01);
			}
		} catch (Exception e) {
			logger.error("Generic exception occurred ", e);
			throw new DCException(Constants.ER01);
		}

	}

	/**
	 *  Query example:
	 * SELECT * FROM gscdatacatalogue.gsc_007_dataset dataset
	 * WHERE dataset.id IN (
	 * SELECT
	 * gsc007.id
	 *	FROM
	 *	gscdatacatalogue.gsc_007_dataset gsc007,
	 *	gscdatacatalogue.gsc_006_datasource gsc006
	 *	WHERE
	 *	gsc006.id = cast(gsc007.json->>'iddatasource' as integer)
	 *	AND gsc007.id = '150'
	 *	AND gsc007.json->>'iddatasource' = '269'
	 *	AND gsc007.json->>'datasetname' ILIKE '%new%'
	 *		AND gsc006.json->>'organization' = '665'
	 *	) */
	private String createSearchQuery(String tableNameDataset, String tableNameDatasource, String idDataset,
			String datasetName, String idDatasource, String idOrganization) {

		StringBuilder sb = new StringBuilder();
		sb.append("SELECT * FROM ").append(tableNameDataset).append(" dataset WHERE dataset.id IN ( ");
		sb.append("SELECT gsc007.id FROM ").append(tableNameDataset).append(" gsc007, ").append(tableNameDatasource)
				.append(" gsc006 WHERE ");
		sb.append("gsc006.id = cast(gsc007.json->>'").append(Constants.DATASOURCE_ID_FIELD).append("' as integer) ");

		if (StringUtils.isNotEmpty(idDataset)) {
			sb.append(" AND gsc007.id = ").append(idDataset);
		}

		if (StringUtils.isNotEmpty(datasetName)) {
			sb.append(" AND gsc007.json->>'").append(Constants.DSET_NAME_FIELD).append("' ILIKE '%").append(datasetName)
					.append("%'");
		}

		if (StringUtils.isNotEmpty(idDatasource)) {
			sb.append(" AND gsc007.json->>'").append(Constants.DATASOURCE_ID_FIELD).append("' = '").append(idDatasource).append("'");
		}

		if (StringUtils.isNotEmpty(idOrganization)) {
			sb.append(" AND gsc006.json->>'").append(Constants.ORG_FIELD).append("' = '").append(idOrganization).append("'");
		}

		sb.append(")");
		return sb.toString();
	}

	private void forcedUpdate(String newdatasetname,String URL,String datasourceId) {
		//1) if the update is needed something special has to be specified as datasourcename
		//2) get the datasourcename through the url (if no url specified error is thrown)
		//3) save the dataset
		//4) call the updateshapeservice update method
	}
}


text:
var win1 = Ti.UI.currentWindow;
var messageButton = Ti.UI.createButton(
    {
            systemButton: Titanium.UI.Android
    }
);
messageButton.addEventListener(
    'click',
    function () {
        var messageWindow = Ti.UI.createWindow(
            {
                url: 'message_window.js',
                title: 'message',
                backgroundColor: '#fff'
            }
        );
        messageWindow.open();
    }
);
win1.rightNavButton = messageButton;

var data = [];
var tableView = Ti.UI.createTableView({
    data:data
});

function updateTimeline (timeline) {
    var currentData = [];
    for (var i=0;i<timeline.length;i++) {
        var tweet = timeline[i];
        var row = Ti.UI.createTableViewRow(
            {
                height: 'auto',
                layout: 'vertical'
            }
        );

        var imageView = Ti.UI.createImageView(
            {
                image: tweet.user.profile_image_url,
                width: 48,
                height: 48,
            }
        );
        row.add(imageView);

        var nameLabel = Ti.UI.createLabel(
            {
                width: 'auto',
                height: 'auto',
                left: 58,
                top: 'auto',
                fontSize: 6,
                fontWeight: 'bold',
                color: '#2b4771'
            }
        );
        nameLabel.text = tweet.user.screen_name;
        row.add(nameLabel);

        var commentLabel = Ti.UI.createLabel(
            {
                width: 'auto',
                left: 58,
                top: 'auto',
                height: 'auto',
                fontSize: 8
            }
        );
        commentLabel.text = tweet.text;
        row.add(commentLabel);

        var dateLabel = Ti.UI.createLabel(
            {
                width: 'auto',
                height: 'auto',
                left: 58,
                top: 'auto',
                fontSize: 6
            }
        );
        dateLabel.text = tweet.created_at;
        row.add(dateLabel);

        currentData.push(row);
    }
    tableView.setData(currentData);
}

var xhr = Ti.Network.createHTTPClient();
var user = 'hatenatech';
var url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=" + user;
xhr.open('GET', url);
xhr.onload = function() {
    var timeline = JSON.parse(this.responseText);
    updateTimeline(timeline);
};
xhr.send();

win.add(tableView);

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Event Manager</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/normalize.css">
    <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/main.css">
    <link rel="stylesheet" href="bower_components/angular-material/angular-material.css">
    <link rel="stylesheet" href="bower_components/sc-date-time/dist/sc-date-time.css">
    <link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="app.css">

    <toolbar></toolbar>
    <md-content flex layout-padding id="content">

        <ng-view></ng-view>
    </md-content>


text:
#ifndef LIP_CORE_COMMON_H
#define LIP_CORE_COMMON_H

/**
 * @defgroup common Common
 * @brief Common structures and functions
 *
 * @{
 */

#include <lip/config.h>
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>

#if LIP_DYNAMIC == 1
#	ifdef _WIN32
#		ifdef LIP_CORE_BUILDING
#			define LIP_CORE_DECL __declspec(dllexport)
#		else
#			define LIP_CORE_DECL __declspec(dllimport)
#		endif
#	else
#		ifdef LIP_CORE_BUILDING
#			define LIP_CORE_DECL __attribute__((visibility("default")))
#		else
#			define LIP_CORE_DECL
#		endif
#	endif
#else
#	define LIP_CORE_DECL
#endif

#define LIP_CORE_API LIP_LINKAGE LIP_CORE_DECL

#if defined(__GNUC__) || defined(__clang__)
#	define LIP_MAYBE_UNUSED __attribute__((unused))
#	define LIP_PRINTF_LIKE(x, y) __attribute__((format(printf, x, y)))
#else
#	define LIP_MAYBE_UNUSED
#	define LIP_PRINTF_LIKE(x, y)
#endif

#define LIP_ENUM(NAME, FOREACH) \
	LIP_DEFINE_ENUM(NAME, FOREACH) \
	LIP_DEFINE_ENUM_TO_STR(NAME, FOREACH)

#define LIP_DEFINE_ENUM(NAME, FOREACH) \
	typedef enum NAME { FOREACH(LIP_GEN_ENUM) } NAME;
#define LIP_GEN_ENUM(ENUM) ENUM,

#define LIP_DEFINE_ENUM_TO_STR(NAME, FOREACH) \
	LIP_MAYBE_UNUSED static inline const char* NAME##_to_str(NAME value) { \
		switch(value) { \
			FOREACH(LIP_DEFINE_ENUM_CASE) \
			default: return 0; \
		} \
	}
#define LIP_DEFINE_ENUM_CASE(ENUM) case ENUM : return #ENUM ;

/// Convenient macro to help during implementation of various interfaces.
#define LIP_CONTAINER_OF(PTR, TYPE, MEMBER) \
	(TYPE*)((char*)PTR - offsetof(TYPE, MEMBER))

#define LIP_MIN(A, B) ((A) < (B) ? (A) : (B))
#define LIP_MAX(A, B) ((A) > (B) ? (A) : (B))

/**
 * @brief Declaration macro for array type.
 *
 * @see array
 */
#define lip_array(T) T*

#ifdef __cplusplus
#	define LIP_ALIGN_OF(TYPE) alignof(TYPE)
#else
#	define LIP_ALIGN_OF(TYPE) offsetof(struct { char c; TYPE t;}, t)
#endif

/** @enum lip_value_type_t Type of a ::lip_value_s.
 * @var LIP_VAL_NIL
 * A null value.
 *
 * @var LIP_VAL_NUMBER
 * A double precision floating point number.
 * When a lip_value_s has this type, access it through lip_value_s::number.
 *
 * @var LIP_VAL_BOOLEAN
 * A boolen value.
 * When a lip_value_s has this type, access it through lip_value_s::boolean.
 *
 * @var LIP_VAL_STRING
 * A string.
 * When lip_value_s has this value, access it using ::lip_as_string.
 *
 * @var LIP_VAL_SYMBOL
 * A symbol.
 * When lip_value_s has this value, access it using ::lip_as_string.
 *
 * @var LIP_VAL_LIST
 * A list.
 * When lip_value_s has this value, access it using ::lip_as_list.
 *
 * @var LIP_VAL_FUNCTION
 * A function.
 * Use ::lip_call to call a function.
 *
 * @var LIP_VAL_PLACEHOLDER
 * A placeholder value.
 * Under normal circumstances, it should be impossible to encounter this value.
 *
 * @var LIP_VAL_NATIVE
 * An opaque native pointer.
 */

#define LIP_VAL(F) \
	F(LIP_VAL_NIL) \
	F(LIP_VAL_NUMBER) \
	F(LIP_VAL_BOOLEAN) \
	F(LIP_VAL_STRING) \
	F(LIP_VAL_SYMBOL) \
	F(LIP_VAL_LIST) \
	F(LIP_VAL_FUNCTION) \
	F(LIP_VAL_PLACEHOLDER) \
	F(LIP_VAL_NATIVE)

LIP_ENUM(lip_value_type_t, LIP_VAL)

/** @enum lip_exec_status_t Execution status.
 * @var LIP_EXEC_OK
 * Successful execution.
 *
 * @var LIP_EXEC_ERROR
 * Error during execution.
 */

#define LIP_EXEC(F) \
	F(LIP_EXEC_OK) \
	F(LIP_EXEC_ERROR)

LIP_ENUM(lip_exec_status_t, LIP_EXEC)

#ifdef __cplusplus
#	define LIP_FLEXIBLE_ARRAY_MEMBER(TYPE, NAME) TYPE NAME[1]
#else
#	define LIP_FLEXIBLE_ARRAY_MEMBER(TYPE, NAME) TYPE NAME[]
#endif

typedef struct lip_fs_s lip_fs_t;
typedef struct lip_loc_s lip_loc_t;
typedef struct lip_loc_range_s lip_loc_range_t;
typedef struct lip_string_ref_s lip_string_ref_t;
typedef struct lip_string_s lip_string_t;
typedef struct lip_list_s lip_list_t;
typedef struct lip_in_s lip_in_t;
typedef struct lip_out_s lip_out_t;
typedef struct lip_allocator_s lip_allocator_t;
typedef struct lip_value_s lip_value_t;
typedef struct lip_vm_s lip_vm_t;
typedef struct lip_vm_config_s lip_vm_config_t;
typedef struct lip_vm_hook_s lip_vm_hook_t;
typedef struct lip_module_loader_s lip_module_loader_t;

/**
 * @brief Native function signature.
 *
 * @param vm The VM making the call.
 * @param result Pointer to write result (or error) to.
 *
 * @return Execution status.
 *
 * @see lip_declare_function
 * @see lip_get_args
 * @see lip_get_env
 */
typedef lip_exec_status_t(*lip_native_fn_t)(lip_vm_t* vm, lip_value_t* result);

/// Source file location.
struct lip_loc_s
{
	/// Line number (first line is 1).
	uint32_t line;
	/// Column number (first character is 1).
	uint32_t column;
};

/// A range in source file.
struct lip_loc_range_s
{
	/// Start position.
	lip_loc_t start;
	/// End position.
	lip_loc_t end;
};

/// Referenced string type.
struct lip_string_ref_s
{
	/// Length of the string.
	size_t length;
	/// Pointer to first char.
	const char* ptr;
};

/// Runtime string type.
struct lip_string_s
{
	/// Length of the string.
	size_t length;
	/// Content of the string.
	LIP_FLEXIBLE_ARRAY_MEMBER(char, ptr);
};

/**
 * @brief Lip's list type.
 *
 * Members are packed contiguously in memory, starting with lip_list_s::elements.
 * When a list is sliced, it retains a reference to its parent through lip_list_s::root.
 *
 * @see LIP_VAL_LIST
 */
struct lip_list_s
{
	/// Number of elmements.
	size_t length;
	/// Pointer to first element.
	lip_value_t* elements;
	/// Reference to parent list.
	lip_value_t* root;
};

/**
 * @brief A value in lip
 *
 * Except for `type`, its members should not be accessed directly.
 * Unless specified otherwise, use `lip_as_*` and `lip_make_*` functions to create and access this struct instead.
 */
struct lip_value_s
{
	/// Type of the value
	lip_value_type_t type;
	union
	{
		/// Should not be accessed directly.
		uint32_t index;
		/// Should not be accessed directly.
		void* reference;
		/// Valid when lip_value_s::type is ::LIP_VAL_BOOLEAN.
		bool boolean;
		/// Valid when lip_value_s::type is ::LIP_VAL_NUMBER.
		double number;
	} data;
};

/// Configuration for a ::lip_vm_s instance.
struct lip_vm_config_s
{
	/// Length of the operand stack (in number of entries).
	uint32_t os_len;
	/// Length of the call stack (in number of entries).
	uint32_t cs_len;
	/// Length of the environment stack (in number of entries).
	uint32_t env_len;
};

/**
 * @brief VM execution hook.
 *
 * @see lip_set_hook
 */
struct lip_vm_hook_s
{
	/**
	 * @brief Called before an instruction is executed.
	 *
	 * @param hook The current hook.
	 * @param vm The vm executing the hook.
	 */
	void(*step)(lip_vm_hook_t* hook, const lip_vm_t* vm);

	/**
	 * @brief Called when an error is thrown.
	 *
	 * @param hook The current hook.
	 * @param vm The vm executing the hook.
	 */
	void(*error)(lip_vm_hook_t* hook, const lip_vm_t* vm);
};

/// Constant location value for pieces of code that do not have location information.
static const lip_loc_range_t LIP_LOC_NOWHERE = {
	// For C++ compatibility, I can't do this:
	//.start = { .line = 0, .column = 0 },
	//.end = { .line = 0, .column = 0 }
	{ 0, 0 },
	{ 0, 0 }
};

/// Create a string ref from a C-string.
LIP_MAYBE_UNUSED static inline lip_string_ref_t
lip_string_ref(const char* string)
{
	lip_string_ref_t result = { strlen(string), string };
	return result;
}

/// Compare two lip_string_ref_s for equality.
LIP_MAYBE_UNUSED static inline bool
lip_string_ref_equal(lip_string_ref_t lhs, lip_string_ref_t rhs)
{
	return lhs.length == rhs.length
		&& (lhs.ptr == rhs.ptr || memcmp(lhs.ptr, rhs.ptr, lhs.length) == 0);
}

/// Compare two lip_string_s for equality.
LIP_MAYBE_UNUSED static inline bool
lip_string_equal(lip_string_t* lhs, lip_string_t* rhs)
{
	return lhs == rhs
		|| (lhs->length == rhs->length && memcmp(lhs->ptr, rhs->ptr, lhs->length) == 0);
}

/**
 * @}
 */

#endif


text:
using extensions::Extension;
using extensions::ExtensionList;

ExtensionToolbarModel::ExtensionToolbarModel(ExtensionService* service)
    : service_(service),
      prefs_(service->profile()->GetPrefs()),
      extensions_initialized_(false) {
  DCHECK(service_);

  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
                 content::Source<Profile>(service_->profile()));
  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED,
                 content::Source<Profile>(service_->profile()));
  registrar_.Add(this, chrome::NOTIFICATION_EXTENSIONS_READY,
                 content::Source<Profile>(service_->profile()));
  registrar_.Add(
      this, chrome::NOTIFICATION_EXTENSION_BROWSER_ACTION_VISIBILITY_CHANGED,
      content::Source<extensions::ExtensionPrefs>(service_->extension_prefs()));

  visible_icon_count_ = prefs_->GetInteger(prefs::kExtensionToolbarSize);
}

ExtensionToolbarModel::~ExtensionToolbarModel() {
}

void ExtensionToolbarModel::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void ExtensionToolbarModel::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

void ExtensionToolbarModel::MoveBrowserAction(const Extension* extension,
                                              int index) {
  ExtensionList::iterator pos = std::find(begin(), end(), extension);
  if (pos == end()) {
    NOTREACHED();
    return;
  }
  toolitems_.erase(pos);

  int i = 0;
  bool inserted = false;
  for (ExtensionList::iterator iter = begin(); iter != end(); ++iter, ++i) {
    if (i == index) {
      toolitems_.insert(iter, make_scoped_refptr(extension));
      inserted = true;
      break;
    }
  }

  if (!inserted) {
    DCHECK_EQ(index, static_cast<int>(toolitems_.size()));
    index = toolitems_.size();

    toolitems_.push_back(make_scoped_refptr(extension));
  }

  FOR_EACH_OBSERVER(Observer, observers_, BrowserActionMoved(extension, index));

  UpdatePrefs();
}

ExtensionToolbarModel::Action ExtensionToolbarModel::ExecuteBrowserAction(
    const Extension* extension,
    Browser* browser,
    GURL* popup_url_out) {
  TabContents* tab_contents = chrome::GetActiveTabContents(browser);
  if (!tab_contents)
    return ACTION_NONE;

  int tab_id = ExtensionTabUtil::GetTabId(tab_contents->web_contents());
  if (tab_id < 0)
    return ACTION_NONE;

  ExtensionAction* browser_action = extension->browser_action();

  // For browser actions, visibility == enabledness.
  if (!browser_action->GetIsVisible(tab_id))
    return ACTION_NONE;

  tab_contents->extension_tab_helper()->active_tab_permission_manager()->
      GrantIfRequested(extension);

  if (browser_action->HasPopup(tab_id)) {
    if (popup_url_out)
      *popup_url_out = browser_action->GetPopupUrl(tab_id);
    return ACTION_SHOW_POPUP;
  }

  service_->browser_event_router()->BrowserActionExecuted(
      *browser_action, browser);
  return ACTION_NONE;
}

void ExtensionToolbarModel::SetVisibleIconCount(int count) {
  visible_icon_count_ = count == static_cast<int>(size()) ? -1 : count;
  prefs_->SetInteger(prefs::kExtensionToolbarSize, visible_icon_count_);
}

void ExtensionToolbarModel::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  if (type == chrome::NOTIFICATION_EXTENSIONS_READY) {
    InitializeExtensionList();
    return;
  }

  if (!service_->is_ready())
    return;

  const Extension* extension = NULL;
  if (type == chrome::NOTIFICATION_EXTENSION_UNLOADED) {
    extension = content::Details<extensions::UnloadedExtensionInfo>(
        details)->extension;
  } else {
    extension = content::Details<const Extension>(details).ptr();
  }
  if (type == chrome::NOTIFICATION_EXTENSION_LOADED) {
    // We don't want to add the same extension twice. It may have already been
    // added by EXTENSION_BROWSER_ACTION_VISIBILITY_CHANGED below, if the user
    // hides the browser action and then disables and enables the extension.
    for (size_t i = 0; i < toolitems_.size(); i++) {
      if (toolitems_[i].get() == extension)
        return;  // Already exists.
    }
    if (service_->extension_prefs()->GetBrowserActionVisibility(extension))
      AddExtension(extension);
  } else if (type == chrome::NOTIFICATION_EXTENSION_UNLOADED) {
    RemoveExtension(extension);
  } else if (
        type ==
        chrome::NOTIFICATION_EXTENSION_BROWSER_ACTION_VISIBILITY_CHANGED) {
    if (service_->extension_prefs()->GetBrowserActionVisibility(extension))
      AddExtension(extension);
    else
      RemoveExtension(extension);
  } else {
    NOTREACHED() << "Received unexpected notification";
  }
}

void ExtensionToolbarModel::AddExtension(const Extension* extension) {
  // We only care about extensions with browser actions.
  if (!extension->browser_action())
    return;

  if (extension->id() == last_extension_removed_ &&
      last_extension_removed_index_ < toolitems_.size()) {
    toolitems_.insert(begin() + last_extension_removed_index_,
                      make_scoped_refptr(extension));
    FOR_EACH_OBSERVER(Observer, observers_,
        BrowserActionAdded(extension, last_extension_removed_index_));
  } else {
    toolitems_.push_back(make_scoped_refptr(extension));
    FOR_EACH_OBSERVER(Observer, observers_,
                      BrowserActionAdded(extension, toolitems_.size() - 1));
  }

  last_extension_removed_ = "";
  last_extension_removed_index_ = -1;

  UpdatePrefs();
}

void ExtensionToolbarModel::RemoveExtension(const Extension* extension) {
  ExtensionList::iterator pos = std::find(begin(), end(), extension);
  if (pos == end()) {
    return;
  }

  last_extension_removed_ = extension->id();
  last_extension_removed_index_ = pos - begin();

  toolitems_.erase(pos);
  FOR_EACH_OBSERVER(Observer, observers_,
                    BrowserActionRemoved(extension));

  UpdatePrefs();
}

// Combine the currently enabled extensions that have browser actions (which
// we get from the ExtensionService) with the ordering we get from the
// pref service. For robustness we use a somewhat inefficient process:
// 1. Create a vector of extensions sorted by their pref values. This vector may
// have holes.
// 2. Create a vector of extensions that did not have a pref value.
// 3. Remove holes from the sorted vector and append the unsorted vector.
void ExtensionToolbarModel::InitializeExtensionList() {
  DCHECK(service_->is_ready());

  std::vector<std::string> pref_order = service_->extension_prefs()->
      GetToolbarOrder();
  // Items that have a pref for their position.
  ExtensionList sorted;
  sorted.resize(pref_order.size(), NULL);
  // The items that don't have a pref for their position.
  ExtensionList unsorted;

  // Create the lists.
  for (ExtensionSet::const_iterator it = service_->extensions()->begin();
       it != service_->extensions()->end(); ++it) {
    const Extension* extension = *it;
    if (!extension->browser_action())
      continue;
    if (!service_->extension_prefs()->GetBrowserActionVisibility(extension))
      continue;

    std::vector<std::string>::iterator pos =
        std::find(pref_order.begin(), pref_order.end(), extension->id());
    if (pos != pref_order.end()) {
      int index = std::distance(pref_order.begin(), pos);
      sorted[index] = extension;
    } else {
      unsorted.push_back(make_scoped_refptr(extension));
    }
  }

  // Merge the lists.
  toolitems_.reserve(sorted.size() + unsorted.size());
  for (ExtensionList::iterator iter = sorted.begin();
       iter != sorted.end(); ++iter) {
    if (*iter != NULL)
      toolitems_.push_back(*iter);
  }
  toolitems_.insert(toolitems_.end(), unsorted.begin(), unsorted.end());

  // Inform observers.
  for (size_t i = 0; i < toolitems_.size(); i++) {
    FOR_EACH_OBSERVER(Observer, observers_,
                      BrowserActionAdded(toolitems_[i], i));
  }

  UpdatePrefs();

  extensions_initialized_ = true;
  FOR_EACH_OBSERVER(Observer, observers_, ModelLoaded());
}

void ExtensionToolbarModel::UpdatePrefs() {
  if (!service_->extension_prefs())
    return;

  std::vector<std::string> ids;
  ids.reserve(toolitems_.size());
  for (ExtensionList::iterator iter = begin(); iter != end(); ++iter)
    ids.push_back((*iter)->id());
  service_->extension_prefs()->SetToolbarOrder(ids);
}

const Extension* ExtensionToolbarModel::GetExtensionByIndex(int index) const {
  return toolitems_[index];
}

int ExtensionToolbarModel::IncognitoIndexToOriginal(int incognito_index) {
  int original_index = 0, i = 0;
  for (ExtensionList::iterator iter = begin(); iter != end();
       ++iter, ++original_index) {
    if (service_->IsIncognitoEnabled((*iter)->id())) {
      if (incognito_index == i)
        break;
      ++i;
    }
  }
  return original_index;
}

int ExtensionToolbarModel::OriginalIndexToIncognito(int original_index) {
  int incognito_index = 0, i = 0;
  for (ExtensionList::iterator iter = begin(); iter != end();
       ++iter, ++i) {
    if (original_index == i)
      break;
    if (service_->IsIncognitoEnabled((*iter)->id()))
      ++incognito_index;
  }
  return incognito_index;
}


text:
namespace BrumWithMe.Web.Models.Trip
{
    public class CarViewModel
    {
        public int Id { get; set; }

        public string Make { get; set; }

        public string Model { get; set; }

        public int Year { get; set; }

        public string Color { get; set; }

        public string ImageUrl { get; set; }

        public string Name
        {
            get
            {
                return $"{this.Make} {this.Model} ({this.Year})";
            }
        }
    }
}


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe AuthorsHelper, 'display_profile_item' do
  include AuthorsHelper

  it 'should display the item as a list item if show_item is true' do
    item = display_profile_item(item = 'my@jabber.org', show_item = true, item_desc = 'Jabber:')
    item.should have_tag('li', 'Jabber: my@jabber.org')
  end

  it 'should NOT display the item as a list item if show_item is false' do
    item = display_profile_item(item = 'my@jabber.org', show_item = false, item_desc = 'Jabber:')
    item.should be_nil
  end

  it 'should display a link if the item is an url' do
    item = display_profile_item(item = 'http://twitter.com/mytwitter', show_item = true, item_desc = 'Twitter:')
    item.should have_tag('li') do
      with_tag('a','http://twitter.com/mytwitter')
    end
  end

end


text:
<?php

namespace MotOb;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\ModuleManager\Feature\ControllerProviderInterface;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
/**
 * MotAttendance\Module
 *
 * @package MotAttendance
 */
class Module implements
    AutoloaderProviderInterface,
    ServiceProviderInterface,
    ConfigProviderInterface,
    ControllerProviderInterface
{
    public function onBootstrap(MvcEvent $event)
    {
        $eventManager        = $event->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

    public function getConfig()
    {
        $config      = [];
        $configFiles = [
            'module.config.php',
            'routes.config.php',
            'navigation.config.php',
        ];

        foreach ($configFiles as $configFile) {
            $config = \Zend\Stdlib\ArrayUtils::merge($config, include  __DIR__ .'/config/'. $configFile);
        }

        return $config;
    }

    public function getAutoloaderConfig()
    {
        return [
            'Zend\Loader\StandardAutoloader' => [
                'namespaces' => [
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ]
            ]
        ];
    }

    public function getControllerConfig()
    {
        return include __DIR__ . '/config/controllers.config.php';
    }

     public function getServiceConfig()
     {
         return array(
//             'factories' => array(
//                 'MotOb\Model\AlbumTable' =>  function($sm) {
//                     $tableGateway = $sm->get('AlbumTableGateway');
//                     $table = new AlbumTable($tableGateway);
//                     return $table;
//                 },
//                 'AttendanceTableGateway' => function ($sm) {
//                     $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
//                     $resultSetPrototype = new ResultSet();
//                     $resultSetPrototype->setArrayObjectPrototype(new Attendance());
//                     return new TableGateway('MotOb', $dbAdapter, null, $resultSetPrototype);
//                 },
//             ),
         );
     //  return include __DIR__ . '/config/services.config.php';
     }
}


text: require "emory/version"


text:
<?xml version = '1.0' encoding = 'UTF-8'?>
<TableProxyOraclev12c class="oracle.dbtools.crest.model.design.storage.oracle.v12c.TableProxyOraclev12c" name="TRABAJADORES" directorySegmentName="seg_0" id="612B3F31-278A-65DF-D03E-CD6FEEC798F6">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
<partitionedRowMovement>DISABLE</partitionedRowMovement>
<temporaryChanged>false</temporaryChanged>
<accessDriverType>oracle_loader</accessDriverType>
<rejectLimit></rejectLimit>
<columnProxies itemClass="oracle.dbtools.crest.model.design.storage.oracle.v12c.ColumnProxyOraclev12c">
<ColumnProxy name="dni" id="13F5F8A6-99E8-B1DC-6072-08E1FEFECB0A">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="piso" id="147C7B61-C30B-1797-65D4-1FD8186E8447">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="numero" id="15587393-76AB-3DFF-32FA-F59F2662B542">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="ciudad" id="1CC5E051-F818-1138-7A5F-7861400EFBBE">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="movilEmpresa" id="35199DD1-503E-EAC0-2B9B-DEF9E8C1E10B">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="salario" id="473A6AA1-F753-F869-3F13-1AA97CA701A2">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="nombre" id="71750FBF-073B-5393-0C4D-019D86EE4CA3">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="segundoApellido" id="7A988482-18C6-B996-D07A-A1BA18A6B3D5">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="calle" id="81EF4D17-95B6-D3C6-1B87-CF01D9020FD3">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="fechaNacimiento" id="AFDAE1EC-5C5D-DC6F-4505-A823B467CF25">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="ID" id="C08C0833-6F10-9657-5840-6528A37096CF">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="movilPersonal" id="CD628DD7-F2EE-EE69-A550-5591F3C3CBFD">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="provincia" id="D69371CA-56ED-B9B2-0171-E1F0375FFE4D">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="codigoPostal" id="DE3E6131-AA92-78DA-9682-3E7C511AA02C">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="primerApellido" id="E0E38C8F-27C0-D533-3D43-319F7376DC20">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="CENTROS_ID" id="E997209D-A47C-EBAC-C47C-E0D52CB8AC93">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="mano" id="F0A89A60-9502-DD92-361A-B8007A47BD7C">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
<ColumnProxy name="categoria" id="F1470D87-0DEE-B446-2915-81EF2075EC7D">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ColumnProxy>
</columnProxies>
<foreignKeys>
<ForeignKey class="oracle.dbtools.crest.model.design.storage.oracle.v10g.FKProxyOraclev10g" name="TRABAJADORES_CENTROS_FK" id="46502EE5-6409-813E-4310-8BB0E84BA0E9">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
</ForeignKey>
</foreignKeys>
<primaryKeys>
<PrimaryKey class="oracle.dbtools.crest.model.design.storage.oracle.v10g.PKProxyOraclev10g" name="TRABAJADORES_PK" id="AA9DA175-7CF0-D20D-54BF-FAB98DC47993">
<createdBy>7fprog03</createdBy>
<createdTime>2017-04-10 18:07:35 UTC</createdTime>
<generatorID>Generado por el Usuario</generatorID>
<ownerDesignName>FINAL</ownerDesignName>
<indexSort>SORTED</indexSort>
</PrimaryKey>
</primaryKeys>
</TableProxyOraclev12c>


text:
killall rl_glue 2>/dev/null
killall test_1_agent 2>/dev/null
killall test_speed_environment 2>/dev/null
killall test_speed_experiment 2>/dev/null
sleep 1
rl_glue &
sleep 1
./test_1_agent &
sleep 1
./test_speed_environment &
sleep 1
./test_speed_experiment

test_outcome=$?
exit $test_outcome


text:
#include <geekos/kthread.h>
#include <geekos/int.h>
#include <geekos/kassert.h>
#include <geekos/screen.h>
#include <geekos/synch.h>
#include <geekos/user.h>
/*
 * NOTES:
 * - The GeekOS mutex and condition variable APIs are based on those
 *   in pthreads.
 * - Unlike disabling interrupts, mutexes offer NO protection against
 *   concurrent execution of interrupt handlers.  Mutexes and
 *   condition variables should only be used from kernel threads,
 *   with interrupts enabled.
 */

/* ----------------------------------------------------------------------
 * Private functions
 * ---------------------------------------------------------------------- */

static struct Semaphore_List s_semaphoreList;

int Create_Semaphore(char* name, int ival)
{
	struct Semaphore* sema = (&s_semaphoreList)->head;
	static ulong_t sid = 1;
	int i;
	int* userSemaphoreList;
	//find sem by sname
	while (sema != 0)
	{
		if (strcmp(sema->name, name) == 0)
		{
			//Print("exist sema->name: %s, %d\n", sema->name, sema->sid);
			sema->refCount++;
			return sema->sid;
		}
		sema = Get_Next_In_Semaphore_List(sema);
	}

	/* If there is no sem, then create sem */
	sema = (struct Semaphore*)Malloc(sizeof(struct Semaphore));
	sema->sid = sid++;
	strcpy(sema->name, name);
	sema->count = ival;
	sema->refCount++;
	Mutex_Init(&(sema->mutex));
	Cond_Init(&(sema->cond));
	Add_To_Back_Of_Semaphore_List(&s_semaphoreList, sema);

	userSemaphoreList = g_currentThread->userContext->semaphores;
	for(i = 0; i < USER_MAX_FILES; i++){
		if(userSemaphoreList[i] == NULL){
			userSemaphoreList[i] = sema->sid;
			break;
		}
	}

	if(i == USER_MAX_FILES)
	{
		/* weak */
	}

	//Print("new sema->name: %s, %d\n", sema->name, sema->sid);
	return sema->sid;

}

int Destroy_Semaphore(int sid)
{
	struct Semaphore* sema = (&s_semaphoreList)->head;
	int i;
	int* userSemaphoreList;

	/* Find sem by sid */
	while (sema != 0) {
		if (sema->sid == sid) {
			if(--sema->refCount == 0) {
				//Print("*** Destoroyed Sem : %d ***\n", sid);
				Remove_From_Semaphore_List(&s_semaphoreList, sema);
				Free(sema);
			}
			userSemaphoreList = g_currentThread->userContext->semaphores;
			for(i = 0; i < USER_MAX_FILES; i++){
				if(userSemaphoreList[i] == sid){
					userSemaphoreList[i] = NULL;
					break;
				}
			}

			if(i == USER_MAX_FILES)
			{
				/* weak */
			}

			return 0;
		}
		sema = Get_Next_In_Semaphore_List(sema);
	}
	return -1;
}

int P(int sid)
{
	struct Semaphore* sema = (&s_semaphoreList)->head;
	struct Mutex* mutex;
	struct Condition* cond;

	/* Find sem by sid */
	while (sema != 0)
	{
		if (sema->sid == sid)
		{
			mutex = &(sema->mutex); // important
			cond = &(sema->cond);

			Enable_Interrupts();
			Mutex_Lock(mutex);
			while(sema->count <= 0)
			{
				Cond_Wait(cond, mutex);
				//Print("WAKE UP!");
			}
			sema->count--;
			Mutex_Unlock(mutex);
			Disable_Interrupts();

			return 0;
		}
		sema = Get_Next_In_Semaphore_List(sema);
	}

	return -1;
}

int V(int sid)
{
	struct Semaphore* sema = (&s_semaphoreList)->head;
	struct Mutex* mutex;
	struct Condition* cond;

	//find sem by sid
	while (sema != 0)
	{
		if (sema->sid == sid)
		{
			mutex = &(sema->mutex);
			cond = &(sema->cond);

			Enable_Interrupts();
			Mutex_Lock(mutex);
			sema->count++;
			//Print("wait queue : %d", cond->waitQueue);
			Cond_Broadcast(cond);
			Mutex_Unlock(mutex);
			Disable_Interrupts();

			return 0;
		}
		sema = Get_Next_In_Semaphore_List(sema);
	}

	return -1;
}

/*
 * The mutex is currently locked.
 * Atomically reenable preemption and wait in the
 * mutex's wait queue.
 */
static void Mutex_Wait(struct Mutex *mutex)
{
    KASSERT(mutex->state == MUTEX_LOCKED);
    KASSERT(g_preemptionDisabled);

    Disable_Interrupts();
    g_preemptionDisabled = false;
    Wait(&mutex->waitQueue);
    g_preemptionDisabled = true;
    Enable_Interrupts();
}

/*
 * Lock given mutex.
 * Preemption must be disabled.
 */
static __inline__ void Mutex_Lock_Imp(struct Mutex* mutex)
{
    KASSERT(g_preemptionDisabled);

    /* Make sure we're not already holding the mutex */
    KASSERT(!IS_HELD(mutex));

    /* Wait until the mutex is in an unlocked state */
    while (mutex->state == MUTEX_LOCKED) {
	Mutex_Wait(mutex);
    }

    /* Now it's ours! */
    mutex->state = MUTEX_LOCKED;
    mutex->owner = g_currentThread;
}

/*
 * Unlock given mutex.
 * Preemption must be disabled.
 */
static __inline__ void Mutex_Unlock_Imp(struct Mutex* mutex)
{
    KASSERT(g_preemptionDisabled);

    /* Make sure mutex was actually acquired by this thread. */
    KASSERT(IS_HELD(mutex));

    /* Unlock the mutex. */
    mutex->state = MUTEX_UNLOCKED;
    mutex->owner = 0;

    /*
     * If there are threads waiting to acquire the mutex,
     * wake one of them up.  Note that it is legal to inspect
     * the queue with interrupts enabled because preemption
     * is disabled, and therefore we know that no thread can
     * concurrently add itself to the queue.
     */
    if (!Is_Thread_Queue_Empty(&mutex->waitQueue)) {
	Disable_Interrupts();
	Wake_Up_One(&mutex->waitQueue);
	Enable_Interrupts();
    }
}

/* ----------------------------------------------------------------------
 * Public functions
 * ---------------------------------------------------------------------- */

/*
 * Initialize given mutex.
 */
void Mutex_Init(struct Mutex* mutex)
{
    mutex->state = MUTEX_UNLOCKED;
    mutex->owner = 0;
    Clear_Thread_Queue(&mutex->waitQueue);
}

/*
 * Lock given mutex.
 */
void Mutex_Lock(struct Mutex* mutex)
{
    KASSERT(Interrupts_Enabled());

    g_preemptionDisabled = true;
    Mutex_Lock_Imp(mutex);
    g_preemptionDisabled = false;
}

/*
 * Unlock given mutex.
 */
void Mutex_Unlock(struct Mutex* mutex)
{
    KASSERT(Interrupts_Enabled());

    g_preemptionDisabled = true;
    Mutex_Unlock_Imp(mutex);
    g_preemptionDisabled = false;
}

/*
 * Initialize given condition.
 */
void Cond_Init(struct Condition* cond)
{
    Clear_Thread_Queue(&cond->waitQueue);
}

/*
 * Wait on given condition (protected by given mutex).
 */
void Cond_Wait(struct Condition* cond, struct Mutex* mutex)
{
    KASSERT(Interrupts_Enabled());

    /* Ensure mutex is held. */
    KASSERT(IS_HELD(mutex));

    /* Turn off scheduling. */
    g_preemptionDisabled = true;

    /*
     * Release the mutex, but leave preemption disabled.
     * No other threads will be able to run before this thread
     * is able to wait.  Therefore, this thread will not
     * miss the eventual notification on the condition.
     */
    Mutex_Unlock_Imp(mutex);

    /*
     * Atomically reenable preemption and wait in the condition wait queue.
     * Other threads can run while this thread is waiting,
     * and eventually one of them will call Cond_Signal() or Cond_Broadcast()
     * to wake up this thread.
     * On wakeup, disable preemption again.
     */
    Disable_Interrupts();
    g_preemptionDisabled = false;
    Wait(&cond->waitQueue);
    g_preemptionDisabled = true;
    Enable_Interrupts();

    /* Reacquire the mutex. */
    Mutex_Lock_Imp(mutex);

    /* Turn scheduling back on. */
    g_preemptionDisabled = false;
}

/*
 * Wake up one thread waiting on the given condition.
 * The mutex guarding the condition should be held!
 */
void Cond_Signal(struct Condition* cond)
{
    KASSERT(Interrupts_Enabled());
    Disable_Interrupts();  /* prevent scheduling */
    Wake_Up_One(&cond->waitQueue);
    Enable_Interrupts();  /* resume scheduling */
}

/*
 * Wake up all threads waiting on the given condition.
 * The mutex guarding the condition should be held!
 */
void Cond_Broadcast(struct Condition* cond)
{
    KASSERT(Interrupts_Enabled());
    Disable_Interrupts();  /* prevent scheduling */
    Wake_Up(&cond->waitQueue);
    Enable_Interrupts();  /* resume scheduling */
}


text:
AUTHOR = u'Adrian Sampson'

# -- General configuration -----------------------------------------------------

extensions = []

#templates_path = ['_templates']
exclude_patterns = ['_build']
source_suffix = '.rst'
master_doc = 'index'

project = u'beets'
copyright = u'2011, Adrian Sampson'

version = '1.0b13'
release = '1.0b13'

pygments_style = 'sphinx'

# -- Options for HTML output ---------------------------------------------------

html_theme = 'default'
#html_static_path = ['_static']
htmlhelp_basename = 'beetsdoc'

# -- Options for LaTeX output --------------------------------------------------

latex_documents = [
  ('index', 'beets.tex', u'beets Documentation',
   AUTHOR, 'manual'),
]

# -- Options for manual page output --------------------------------------------

man_pages = [
    ('reference/cli', 'beet', u'music tagger and library organizer',
     [AUTHOR], 1),
    ('reference/config', 'beetsconfig', u'beets configuration file',
     [AUTHOR], 5),
]


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Wifi on African Uhambo</title>
    <link>https://africanuhambo.co.uk/tags/wifi/index.xml</link>
    <description>Recent content in Wifi on African Uhambo</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <copyright>Code released under the MIT license.</copyright>
    <atom:link href="https://africanuhambo.co.uk/tags/wifi/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Back on UK soil</title>
      <link>https://africanuhambo.co.uk/2013/08/24/back-on-uk-soil/</link>
      <pubDate>Sat, 24 Aug 2013 18:40:32 +0000</pubDate>

      <guid>https://africanuhambo.co.uk/2013/08/24/back-on-uk-soil/</guid>
      <description>
Well we are back on UK soil, behind on our updates due to a lack of wifi, most are written so we will post them ASAP.

Long drive home now!

</description>
    </item>

  </channel>
</rss>