text:
package gov.nih.nci.evs.browser.test;

import java.util.*;

import org.LexGrid.LexBIG.DataModel.Collections.AssociatedConceptList;
import org.LexGrid.LexBIG.DataModel.Collections.AssociationList;
import org.LexGrid.LexBIG.DataModel.Collections.ConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Collections.LocalNameList;
import org.LexGrid.LexBIG.DataModel.Collections.NameAndValueList;
import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept;
import org.LexGrid.LexBIG.DataModel.Core.Association;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.DataModel.Core.NameAndValue;
import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeGraph;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet;
import org.LexGrid.LexBIG.LexBIGService.LexBIGService;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.SearchDesignationOption;
import org.LexGrid.LexBIG.Utility.Iterators.ResolvedConceptReferencesIterator;
import org.apache.log4j.Logger;

import gov.nih.nci.evs.browser.bean.OntologyBean;
import gov.nih.nci.evs.browser.utils.RemoteServerUtil;
import gov.nih.nci.evs.browser.utils.ResolvedConceptReferencesIteratorWrapper;

public class ContainsRelationTest {
    // --------------------------------------------------------------------------
    private static Logger _logger =
        Logger.getLogger(ContainsRelationTest.class);
    private static final String SEPARATOR =
        "----------------------------------------"
            + "----------------------------------------";

    // --------------------------------------------------------------------------
    private static int RESOLVE_SOURCE = 1;
    private static int RESOLVE_TARGET = -1;
    private static int RESTRICT_SOURCE = -1;
    private static int RESTRICT_TARGET = 1;

    // --------------------------------------------------------------------------
    public ContainsRelationTest() {
        String scheme = "NCI Metathesaurus";
        // String matchText = "single dose vial";
        String matchText = "single dose";
        String source = "ALL";
        String matchAlgorithm = "contains";
        String version = null;
        String rel = null;
        String rela = null;
        int maxToReturn = 1000;
        search(scheme, matchText, source, matchAlgorithm, version, rel, rela,
            maxToReturn);
    }

    private void search(String scheme, String matchText, String source,
        String matchAlgorithm, String version, String rel, String rela,
        int maxToReturn) {
        try {
            _logger.debug(SEPARATOR);
            _logger.debug("Calling new SearchUtils().searchByRELA");
            _logger.debug("  * scheme: " + scheme);
            _logger.debug("  * matchText: " + matchText);
            _logger.debug("  * source: " + source);
            _logger.debug("  * matchAlgorithm: " + matchAlgorithm);
            _logger.debug("  * version: " + version);
            _logger.debug("  * rel: " + rel);
            _logger.debug("  * rela: " + rela);
            _logger.debug("  * maxToReturn: " + maxToReturn);
            ResolvedConceptReferencesIteratorWrapper wrapper =
                searchByRELA(scheme, version, matchText, source,
                    matchAlgorithm, rel, rela, maxToReturn);

            ResolvedConceptReferencesIterator iterator = wrapper.getIterator();
            printConcepts(iterator, maxToReturn);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void printConcepts(ResolvedConceptReferencesIterator iterator,
        int maxToReturn) throws Exception {
        _logger.debug(SEPARATOR);
        int i = 0, size = iterator.numberRemaining();
        while (iterator.hasNext()) {
            ResolvedConceptReference[] rcrs =
                iterator.next(maxToReturn).getResolvedConceptReference();
            for (ResolvedConceptReference rcr : rcrs) {
                String code = rcr.getConceptCode();
                String name = rcr.getEntityDescription().getContent();
                _logger.debug(++i + ") " + code + ": " + name);
            }
        }
        _logger.debug("size: " + size);
    }

    public ResolvedConceptReferencesIteratorWrapper searchByRELA(String scheme,
        String version, String matchText, String source, String matchAlgorithm,
        String rel, String rela, int maxToReturn) {

        if (matchText == null || matchText.length() == 0)
            return null;

        matchText = matchText.trim();
        if (matchAlgorithm.compareToIgnoreCase("contains") == 0) {
            matchAlgorithm = findBestContainsAlgorithm(matchText);
        }

        ResolvedConceptReferencesIterator iterator = null;
        CodedNodeSet cns = null;
        CodedNodeSet.PropertyType[] propertyTypes =
            new CodedNodeSet.PropertyType[1];
        propertyTypes[0] = PropertyType.PRESENTATION;
        LexBIGService lbSvc = null;
        try {
            lbSvc = new RemoteServerUtil().createLexBIGService();
            if (lbSvc == null) {
                _logger.warn("lbSvc = null");
                return null;
            }
            CodingSchemeVersionOrTag versionOrTag =
                new CodingSchemeVersionOrTag();
            if (version != null)
                versionOrTag.setVersion(version);

            cns = lbSvc.getNodeSet(scheme, versionOrTag, null);
            if (cns == null) {
                _logger.warn("cns = null");
                return null;
            }

            try {
                LocalNameList sourceList = null;
                if (source != null && source.compareToIgnoreCase("ALL") != 0) {
                    sourceList = new LocalNameList();
                    sourceList.addEntry(source);
                }

                cns =
                    cns.restrictToMatchingDesignations(matchText,
                        SearchDesignationOption.ALL, matchAlgorithm, null);

                if (source != null && source.compareTo("ALL") != 0) {
                    cns =
                        cns.restrictToProperties(null, propertyTypes,
                            sourceList, null, null);
                }

                try {
                    ResolvedConceptReferencesIterator it =
                        cns.resolve(null, null, null, null, false);
                    int num = it.numberRemaining();
                    if (num > 1000) {
                        System.out.println("Matching target concepts size: "
                            + num + " > 1000 -- method aborts.");
                        return null;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            } catch (Exception ex) {
                return null;
            }
        } catch (Exception e) {
            return null;
        }

        if (cns == null) {
            return null;
        }

        try {
            CodedNodeGraph cng =
                getRestrictedCodedNodeGraph(lbSvc, scheme, version, rel, rela,
                    cns, 1);

            if (cng == null) {
                return null;
            }

            boolean resolveForward = false;
            boolean resolveBackward = true;
            int resolveAssociationDepth = 0;

            System.out.println("Calling resolveCodedNodeGraph");
            iterator =
                resolveCodedNodeGraph(lbSvc, scheme, version, cng,
                    RESOLVE_SOURCE, -1);

            if (iterator != null) {
                return new ResolvedConceptReferencesIteratorWrapper(iterator);
            }

        } catch (Exception ex) {

        }
        return null;
    }

    private String findBestContainsAlgorithm(String matchText) {
        if (matchText == null)
            return "nonLeadingWildcardLiteralSubString";
        matchText = matchText.trim();
        if (matchText.length() == 0)
            return "nonLeadingWildcardLiteralSubString"; // or null
        if (matchText.length() > 1)
            return "nonLeadingWildcardLiteralSubString";
        char ch = matchText.charAt(0);
        if (Character.isDigit(ch))
            return "literal";
        else if (Character.isLetter(ch))
            return "LuceneQuery";
        else
            return "literalContains";
    }

    public ResolvedConceptReferencesIterator resolveCodedNodeGraph(
        LexBIGService lbSvc, String scheme, String version, CodedNodeGraph cng,
        int direction, int maxToReturn) {
        ConceptReferenceList codeList = new ConceptReferenceList();
        try {
            ResolvedConceptReferenceList rcrl = null;
            try {
                boolean resolveForward = true;
                boolean resolveBackward = false;
                int resolveAssociationDepth = 0;
                int resolveCodedEntryDepth = 0;

                rcrl =
                    cng.resolveAsList(null, resolveForward,
                        resolveBackward, // graphFocus, resolveForward,
                        // resolveBackward
                        resolveCodedEntryDepth, resolveAssociationDepth, null,
                        null, null, maxToReturn);

            } catch (Exception ex) {
                System.out.println("Exception thrown -- cng.resolveAsList.");
                return null;
            }

            ResolvedConceptReference[] rcrArray =
                rcrl.getResolvedConceptReference();
            org.LexGrid.concepts.Concept ce = null;

            for (int i = 0; i < rcrArray.length; i++) {
                if (direction == RESOLVE_SOURCE) {
                    codeList.addConceptReference(rcrArray[i]);

                } else if (direction == RESOLVE_TARGET) {
                    AssociationList al = rcrArray[i].getSourceOf();
                    Association[] assos = al.getAssociation();
                    if (assos != null) {
                        for (int j = 0; j < assos.length; j++) {
                            Association asso = (Association) assos[j];
                            AssociatedConceptList acl =
                                asso.getAssociatedConcepts();
                            AssociatedConcept[] ac_array =
                                acl.getAssociatedConcept();
                            for (int k = 0; k < ac_array.length; k++) {
                                AssociatedConcept ac =
                                    (AssociatedConcept) ac_array[k];
                                codeList.addConceptReference(ac);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        CodedNodeSet cns = null;
        try {
            CodingSchemeVersionOrTag versionOrTag =
                new CodingSchemeVersionOrTag();
            if (version != null)
                versionOrTag.setVersion(version);

            cns = lbSvc.getNodeSet(scheme, versionOrTag, null);
            cns = cns.restrictToCodes(codeList);
            if (cns == null) {
                return null;
            }
            ResolvedConceptReferencesIterator it =
                cns.resolve(null, null, null, null, false);
            return it;
        } catch (Exception ex) {

        }
        return null;
    }

    public CodedNodeGraph getRestrictedCodedNodeGraph(LexBIGService lbSvc,
        String scheme, String version, String rel, String rela,
        CodedNodeSet cns, int direction) {
        CodedNodeGraph cng = null;
        CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
        versionOrTag.setVersion(version);

        _logger.warn("getRestrictedCodedNodeGraph rel: " + rel);
        _logger.warn("getRestrictedCodedNodeGraph rela: " + rela);

        try {
            cng = lbSvc.getNodeGraph(scheme, versionOrTag, null);
            NameAndValueList asso_list = null;
            String[] associationsToNavigate = null;

            if (rel == null) {
                Vector w = OntologyBean.getAssociationNames();
                if (w == null || w.size() == 0) {
                    _logger
                        .warn("OntologyBean.getAssociationNames() returns null, or nothing???");
                } else {
                    associationsToNavigate = new String[w.size()];
                    for (int i = 0; i < w.size(); i++) {
                        String nm = (String) w.elementAt(i);
                        associationsToNavigate[i] = nm;
                    }
                }
            } else {
                associationsToNavigate = new String[] { rel };
            }
            asso_list = createNameAndValueList(associationsToNavigate, null);

            NameAndValueList qualifier_list = null;
            if (rela != null) {
                qualifier_list =
                    createNameAndValueList(new String[] { "rela" },
                        new String[] { rela });
            }

            cng = cng.restrictToAssociations(asso_list, qualifier_list);

            if (cns != null) {
                if (direction == -1) {
                    _logger.warn("restrictToSourceCodes... ");

                    cng = cng.restrictToSourceCodes(cns);
                } else if (direction == 1) {
                    _logger.warn("restrictToTargetCodes... ");

                    cng = cng.restrictToTargetCodes(cns);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return cng;
    }

    public static NameAndValueList createNameAndValueList(String[] names,
        String[] values) {
        NameAndValueList nvList = null;
        if (names != null && names.length > 0) {
            nvList = new NameAndValueList();
            for (int i = 0; i < names.length; i++) {
                NameAndValue nv = new NameAndValue();
                nv.setName(names[i]);
                if (values != null) {
                    nv.setContent(values[i]);
                }
                nvList.addNameAndValue(nv);
            }
        }
        return nvList;
    }

    private static String[] parse(String[] args) {
        String prevArg = "";
        ArrayList<String> newArgs = new ArrayList<String>();
        for (int i = 0; i < args.length; ++i) {
            String arg = args[i];
            if (arg.equals("-propertyFile")) {
                prevArg = arg;
            } else if (prevArg.equals("-propertyFile")) {
                System.setProperty(
                    "gov.nih.nci.evs.browser.NCImBrowserProperties", arg);
                prevArg = "";
            } else {
                newArgs.add(arg);
            }
        }
        return newArgs.toArray(new String[newArgs.size()]);
    }

    public static void main(String[] args) {
        parse(args);
        new ContainsRelationTest();
    }
}


text:
import React from 'react'
import { grey200, grey300, white } from 'material-ui/styles/colors'
import IconButton from 'material-ui/IconButton'
import IconLogs from 'material-ui/svg-icons/action/receipt'
import IconTerminal from 'material-ui/svg-icons/hardware/computer'
import IconEdit from 'material-ui/svg-icons/editor/mode-edit'
import IconView from 'material-ui/svg-icons/image/crop-free'
import IconDelete from 'material-ui/svg-icons/action/delete'
import IconDetach from 'material-ui/svg-icons/image/filter-none'
import IconScale from 'material-ui/svg-icons/communication/import-export'
import IconSuspend from 'material-ui/svg-icons/content/block'
import { connect } from 'react-redux'
import Popover from 'material-ui/Popover'

const orderedActions = ['logs', 'terminal', 'suspend', 'scale', 'detach', 'edit', 'get', 'delete']

const actionIcons = {
  logs: <IconLogs/>,
  terminal: <IconTerminal/>,
  suspend: <IconSuspend/>,
  scale: <IconScale/>,
  edit: <IconEdit/>,
  get: <IconView/>,
  delete: <IconDelete/>,
  detach: <IconDetach/>,
}

const mapStateToProps = function(store) {
  return {
    accessEvaluator: store.session.accessEvaluator,
  }
}

export default connect(mapStateToProps) (
class RowActionMenu extends React.PureComponent {

  render() {

    const styles = {
      popover: {
        marginTop: 8,
        marginLeft: 70,
        marginRight: 0,
        paddingLeft: 15,
        paddingRight: 15,
        paddingTop: 6,
        paddingBottom: 6,
        backgroundColor: '#BBB',
        border: '1px solid #000',
        borderRadius: '3px',
        boxShadow: 'rgba(0, 0, 0, 0.16) 0px 3px 10px, rgba(0, 0, 0, 0.23) 0px 3px 10px',
        display: 'flex',
      },
      actionContainer: {
        position: 'relative',
        display: 'inline-block',
        float: 'left',
      },
      actionLabel: {
        position: 'absolute',
        bottom: 0,
        textAlign: 'center',
        width: '100%',
        color: white,
        fontSize: 10,
        zIndex: 100,
        pointerEvents: 'none',
      },
      actionButton: {
        backgroundColor: 'transparent',
        marginTop: 4,
        marginBottom: 4,
        color: grey200,
        fontSize: 18,
        fontWeight: 600,
      },
      actionButtonLabel: {
        textTransform: 'none',
        color: grey300,
      },
      actionIcon: {
        color: white,
        marginTop: -4,
      },
      actionHoverStyle: {
        backgroundColor: '#999',
      },
    }

    let { props } = this
    let { access, handlers, anchorEl, open } = props

    if (!access) {
      return null
    }

    let actions = []
    for (let action of orderedActions) {
      if (access[action]) {

        let text = action
        let handler = handlers[action]
        if (action === 'get') {
          if (access['edit']) {
            continue
          } else {
            text = 'yaml'
            handler = handlers.edit
          }
        }

        let closeAndHandle = () => {
          handlers.close && handlers.close()
          handler()
        }

        actions.push(

{text}

            <IconButton
              className={`row-action ${action}`}
              onTouchTap={closeAndHandle}
              style={styles.actionButton}
              hoveredStyle={styles.actionHoverStyle}
              iconStyle={styles.actionIcon}
            >
              {actionIcons[action]}
            </IconButton>

        )
      }
    }

    return (
      <Popover
        className="actions-popover"
        style={styles.popover}
        open={open}
        anchorEl={anchorEl}
        onRequestClose={handlers.close}
        zDepth={0}
        anchorOrigin={{horizontal: 'right', vertical: 'bottom'}}
        targetOrigin={{horizontal: 'left', vertical: 'bottom'}}
      >
        {actions}
      </Popover>
    )
  }
})

redpajama_set_name: RedPajamaGithub


text:
package org.switchyard.metadata;

import javax.xml.namespace.QName;

import org.switchyard.ExchangePattern;

/**
 * Default implementation of ServiceOperation for ExchangePattern.IN_ONLY
 * operations.
 */
public class InOnlyOperation extends BaseServiceOperation {

    protected InOnlyOperation() {
        super(ExchangePattern.IN_OUT);
    }

    /**
     * Create a new instance of an InOnly operation with a default message name.
     * @param operationName the name of the operation
     */
    public InOnlyOperation(String operationName) {
        super(ExchangePattern.IN_ONLY, operationName, null, null, null);
    }

    /**
     * Create a new instance of an InOnly operation with a specific message name.
     * @param operationName the name of the operation
     * @param inputName the name of the input message
     */
    public InOnlyOperation(String operationName, QName inputName) {
        super(ExchangePattern.IN_ONLY, operationName, inputName, null, null);
    }

}


text:
using System.Globalization;
using Xunit;

namespace System.Tests
{
    public partial class UInt32Tests
    {
        [Theory]
        [MemberData(nameof(Parse_Valid_TestData))]
        public static void Parse_Span_Valid(string value, NumberStyles style, IFormatProvider provider, uint expected)
        {
            Assert.Equal(expected, uint.Parse(value.AsReadOnlySpan(), style, provider));

            Assert.True(uint.TryParse(value.AsReadOnlySpan(), out uint result, style, provider));
            Assert.Equal(expected, result);
        }

        [Theory]
        [MemberData(nameof(Parse_Invalid_TestData))]
        public static void Parse_Span_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
        {
            if (value != null)
            {
                Assert.Throws(exceptionType, () => uint.Parse(value.AsReadOnlySpan(), style, provider));

                Assert.False(uint.TryParse(value.AsReadOnlySpan(), out uint result, style, provider));
                Assert.Equal(0, (int)result);
            }
        }
    }
}


text:
"use strict";

module.exports = {
  Model: require("./node"),
  View: require("./node_view")
};


text:
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier:  Apache-2.0

namespace CompareFacesExample
{
    // snippet-start:[Rekognition.dotnetv3.CompareFacesExample]
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to compare faces in two images.
    /// The example uses the AWS SDK for .NET 3.7 and .NET Core 5.0.
    /// </summary>
    public class CompareFaces
    {
        public static async Task Main()
        {
            float similarityThreshold = 70F;
            string sourceImage = "source.jpg";
            string targetImage = "target.jpg";

            var rekognitionClient = new AmazonRekognitionClient();

            Amazon.Rekognition.Model.Image imageSource = new Amazon.Rekognition.Model.Image();

            try
            {
                using FileStream fs = new FileStream(sourceImage, FileMode.Open, FileAccess.Read);
                byte[] data = new byte[fs.Length];
                fs.Read(data, 0, (int)fs.Length);
                imageSource.Bytes = new MemoryStream(data);
            }
            catch (Exception)
            {
                Console.WriteLine($"Failed to load source image: {sourceImage}");
                return;
            }

            Amazon.Rekognition.Model.Image imageTarget = new Amazon.Rekognition.Model.Image();

            try
            {
                using FileStream fs = new FileStream(targetImage, FileMode.Open, FileAccess.Read);
                byte[] data = new byte[fs.Length];
                data = new byte[fs.Length];
                fs.Read(data, 0, (int)fs.Length);
                imageTarget.Bytes = new MemoryStream(data);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to load target image: {targetImage}");
                Console.WriteLine(ex.Message);
                return;
            }

            var compareFacesRequest = new CompareFacesRequest
            {
                SourceImage = imageSource,
                TargetImage = imageTarget,
                SimilarityThreshold = similarityThreshold,
            };

            // Call operation
            var compareFacesResponse = await rekognitionClient.CompareFacesAsync(compareFacesRequest);

            // Display results
            compareFacesResponse.FaceMatches.ForEach(match =>
            {
                ComparedFace face = match.Face;
                BoundingBox position = face.BoundingBox;
                Console.WriteLine($"Face at {position.Left} {position.Top} matches with {match.Similarity}% confidence.");
            });

            Console.WriteLine($"Found {compareFacesResponse.UnmatchedFaces.Count} face(s) that did not match.");
        }
    }
    // snippet-end:[Rekognition.dotnetv3.CompareFacesExample]
}


text:
import React, { Component } from 'react';
import Relay from 'react-relay';
import { Tabs, Tab } from 'material-ui/Tabs';
import Paper from 'material-ui/Paper';
import { CategoryTab, ClothTab } from './components';
import { AddFloatButton } from './widgets';

class ClothBrowserPage extends Component {
	state = {
		slideIndex: 0,
		selectCategoryId: null
	}
	tabSelectChange = (value) => {
		this.setState({slideIndex: value});
	}
	onSelectCategory = (category) => {
		this.setState({slideIndex: 1, selectCategoryId: category.id});
	}
	render() {
		let contentView;
		switch(this.state.slideIndex) {
			case 0:
				contentView = <CategoryTab viewer={this.props.viewer}
					onSelectCategory={this.onSelectCategory}/>;
				break;
			case 1:
				contentView = <ClothTab viewer={this.props.viewer}
					defaultCategoryId={this.state.selectCategoryId}/>
				break;
		}

		return (
			<div className='flex flex-fill'>
				<Paper>
		      <Tabs onChange={this.tabSelectChange} value={this.state.slideIndex}>
		        <Tab label='Categories' value={0}/>
		        <Tab label='Items' value={1}/>
		      </Tabs>
	      </Paper>
	      {contentView}
      </div>
		);
	}
}

export default Relay.createContainer(ClothBrowserPage, {
	fragments: {
		viewer: () => Relay.QL`
			fragment on Viewer {
				${CategoryTab.getFragment('viewer')}
				${ClothTab.getFragment('viewer')}
			}
		`
	}
});


text: {{'services.menuFloatServices.'+item | translate }}


text:
extern zend_class_entry *phalcon_queue_beanstalk_ce;

ZEPHIR_INIT_CLASS(Phalcon_Queue_Beanstalk);

PHP_METHOD(Phalcon_Queue_Beanstalk, __construct);
PHP_METHOD(Phalcon_Queue_Beanstalk, connect);
PHP_METHOD(Phalcon_Queue_Beanstalk, put);
PHP_METHOD(Phalcon_Queue_Beanstalk, reserve);
PHP_METHOD(Phalcon_Queue_Beanstalk, choose);
PHP_METHOD(Phalcon_Queue_Beanstalk, watch);
PHP_METHOD(Phalcon_Queue_Beanstalk, ignore);
PHP_METHOD(Phalcon_Queue_Beanstalk, pauseTube);
PHP_METHOD(Phalcon_Queue_Beanstalk, kick);
PHP_METHOD(Phalcon_Queue_Beanstalk, stats);
PHP_METHOD(Phalcon_Queue_Beanstalk, statsTube);
PHP_METHOD(Phalcon_Queue_Beanstalk, listTubes);
PHP_METHOD(Phalcon_Queue_Beanstalk, listTubeUsed);
PHP_METHOD(Phalcon_Queue_Beanstalk, listTubesWatched);
PHP_METHOD(Phalcon_Queue_Beanstalk, peekReady);
PHP_METHOD(Phalcon_Queue_Beanstalk, peekBuried);
PHP_METHOD(Phalcon_Queue_Beanstalk, peekDelayed);
PHP_METHOD(Phalcon_Queue_Beanstalk, jobPeek);
PHP_METHOD(Phalcon_Queue_Beanstalk, readStatus);
PHP_METHOD(Phalcon_Queue_Beanstalk, readYaml);
PHP_METHOD(Phalcon_Queue_Beanstalk, read);
PHP_METHOD(Phalcon_Queue_Beanstalk, write);
PHP_METHOD(Phalcon_Queue_Beanstalk, disconnect);
PHP_METHOD(Phalcon_Queue_Beanstalk, quit);

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_queue_beanstalk___construct, 0, 0, 0)
	ZEND_ARG_ARRAY_INFO(0, parameters, 1)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_queue_beanstalk_put, 0, 0, 1)
	ZEND_ARG_INFO(0, data)
	ZEND_ARG_ARRAY_INFO(0, options, 1)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_queue_beanstalk_reserve, 0, 0, 0)
	ZEND_ARG_INFO(0, timeout)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_queue_beanstalk_choose, 0, 0, 1)
	ZEND_ARG_INFO(0, tube)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_queue_beanstalk_watch, 0, 0, 1)
	ZEND_ARG_INFO(0, tube)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_queue_beanstalk_ignore, 0, 0, 1)
	ZEND_ARG_INFO(0, tube)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_queue_beanstalk_pausetube, 0, 0, 2)
	ZEND_ARG_INFO(0, tube)
	ZEND_ARG_INFO(0, delay)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_queue_beanstalk_kick, 0, 0, 1)
	ZEND_ARG_INFO(0, bound)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_queue_beanstalk_statstube, 0, 0, 1)
	ZEND_ARG_INFO(0, tube)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_queue_beanstalk_jobpeek, 0, 0, 1)
	ZEND_ARG_INFO(0, id)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_queue_beanstalk_read, 0, 0, 0)
	ZEND_ARG_INFO(0, length)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_queue_beanstalk_write, 0, 0, 1)
	ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()

ZEPHIR_INIT_FUNCS(phalcon_queue_beanstalk_method_entry) {
	PHP_ME(Phalcon_Queue_Beanstalk, __construct, arginfo_phalcon_queue_beanstalk___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
	PHP_ME(Phalcon_Queue_Beanstalk, connect, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, put, arginfo_phalcon_queue_beanstalk_put, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, reserve, arginfo_phalcon_queue_beanstalk_reserve, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, choose, arginfo_phalcon_queue_beanstalk_choose, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, watch, arginfo_phalcon_queue_beanstalk_watch, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, ignore, arginfo_phalcon_queue_beanstalk_ignore, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, pauseTube, arginfo_phalcon_queue_beanstalk_pausetube, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, kick, arginfo_phalcon_queue_beanstalk_kick, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, stats, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, statsTube, arginfo_phalcon_queue_beanstalk_statstube, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, listTubes, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, listTubeUsed, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, listTubesWatched, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, peekReady, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, peekBuried, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, peekDelayed, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, jobPeek, arginfo_phalcon_queue_beanstalk_jobpeek, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, readStatus, NULL, ZEND_ACC_FINAL|ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, readYaml, NULL, ZEND_ACC_FINAL|ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, read, arginfo_phalcon_queue_beanstalk_read, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, write, arginfo_phalcon_queue_beanstalk_write, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, disconnect, NULL, ZEND_ACC_PUBLIC)
	PHP_ME(Phalcon_Queue_Beanstalk, quit, NULL, ZEND_ACC_PUBLIC)
	PHP_FE_END
};


text:
<?php

namespace Ekyna\Component\Commerce\Support\Model;

use Ekyna\Component\Commerce\Common\Model\AttachmentInterface;

/**
 * Class TicketAttachmentInterface
 * @package Ekyna\Component\Commerce\Support\Model
 * @author  Etienne Dauvergne <contact@ekyna.com>
 */
interface TicketAttachmentInterface extends AttachmentInterface
{
    /**
     * Returns the message.
     *
     * @return TicketMessageInterface
     */
    public function getMessage();

    /**
     * Sets the message.
     *
     * @param TicketMessageInterface $message
     *
     * @return $this|TicketAttachmentInterface
     */
    public function setMessage(TicketMessageInterface $message = null);
}


text:
package com.jcodes.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOClient {

	/* 缓冲区大小 */
	private static int BLOCK = 4096;
	private int count = 0;
	private Selector selector;
	private SocketChannel socketChannel;
	public NIOClient(String houstname, int port) throws IOException {
		// 打开socket通道
		socketChannel = SocketChannel.open();
		// 设置为非阻塞方式
		socketChannel.configureBlocking(false);
		// 打开选择器
		selector = Selector.open();
		// 注册连接服务端socket动作
		socketChannel.register(selector, SelectionKey.OP_CONNECT);
		// 连接
		socketChannel.connect(new InetSocketAddress(houstname, port));
	}

	/**
	 * 开始发送数据
	 *
	 * @throws IOException
	 */
	public void start() throws IOException {
		while (true) {
			// 选择操作,阻塞式等待,直到至少有一个通道被选择,有可能返回多个,也有可能返回0个,当准备好操作的通道被更新状态了
			int selected = selector.select();
			if (selected > 0) {
				// 返回此选择器的已选择键集。
				Set<SelectionKey> selectionKeys = selector.selectedKeys();
				Iterator<SelectionKey> iterator = selectionKeys.iterator();
				while (iterator.hasNext()) {
					SelectionKey selectionKey = iterator.next();
					System.err.println("附加数据:" +selectionKey.attachment());
					handleKey(selectionKey);
					selectionKey.attach("我是同一个附加数据");
				}
				selectionKeys.clear();
			}

			if(count == 10) {
				break;
			}
			try {
				// 睡眠3秒
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
		socketChannel.close();
	}

	/**
	 * 处理选择器事件
	 *
	 * @param selectionKey
	 * @throws IOException
	 */
	private void handleKey(SelectionKey selectionKey) throws IOException {
		if (selectionKey.isConnectable()) {
			NIOUtils.connect(selectionKey);
			String sendMsg = "客户端连接";
			NIOUtils.write(selectionKey, sendMsg.getBytes());
			System.out.println("客户端发送数据:" + sendMsg);
		} else if (selectionKey.isReadable()) {
			byte[] dst = new byte[BLOCK];
			NIOUtils.read(selectionKey, dst);
			System.err.println("客户端接收数据:" + new String(dst, 0, dst.length));
		} else if (selectionKey.isWritable()) {
			String sendMsg = "Client--" + (count++);
			NIOUtils.write(selectionKey, sendMsg.getBytes());
			System.out.println("客户端发送数据:" + sendMsg);
		}

	}

	public static void main(String[] args) throws IOException {
		new NIOClient("localhost", 8888).start();
	}

}


text:
/**
 * test.aria.pageEngine.utils.PageConfigHelper test
 */
Aria.classDefinition({
    $classpath : "test.aria.pageEngine.utils.PageConfigHelperTest",
    $extends : "aria.jsunit.TestCase",
    $dependencies : ["aria.pageEngine.utils.PageConfigHelper", "aria.utils.Array", "aria.utils.Object"],
    $resources : {
        pageDefOne : "test.aria.pageEngine.utils.test.PageConfigOne"
    },
    $prototype : {

        testGetMenus : function () {
            var menus = {
                "menuOne" : ["childOne", "childTwo"]
            };
            var pageDef = {
                contents : {
                    menus : menus,
                    placeholderContents : {}
                },
                pageComposition : {}
            };

            var pgh = new aria.pageEngine.utils.PageConfigHelper(pageDef);
            this.assertTrue(pgh.getMenus() == menus, "getMenus method not working correctly");
            pgh.$dispose();
        },

        testGetPageDependencies : function () {
            var pgh = new aria.pageEngine.utils.PageConfigHelper(this.pageDefOne.pageDef);
            var dep = pgh.getPageDependencies();

            // templates
            this._testContains(dep.templates, ["body.template", "body.first.template", "body.middle.template",
                    "body.second.template", "main.page.template"], "Incorrect templates dependencies");
            this.assertTrue(dep.templates.length == 5);

            // classes
            this._testContains(dep.classes, ["module.one.classpath", "module.two.classpath", "module.three.classpath"]);
            this.assertTrue(dep.classes.length == 3);

            // common modules refpaths
            this._testContains(dep.modules.common, ["modOne"]);
            this.assertTrue(dep.modules.common.length == 1);

            // page-specific modules refpaths
            this._testContains(dep.modules.page, ["modOne", "modTwo", "mod.modthree", "modFour"]);
            this.assertTrue(dep.modules.page.length == 4);
            pgh.$dispose();

        },

        testAutoRefpathAddition : function () {
            var pgh = new aria.pageEngine.utils.PageConfigHelper(this.pageDefOne.pageDef);
            var modules = pgh.getPageModulesDescriptions();
            var refpaths = ["modOne", "modTwo", "mod.modthree", "modFour", "modFive"];
            var testVar = true;
            for (var i = 0, len = refpaths.length; i < len; i++) {
                testVar = testVar && (this._getModuleWithRefpath(modules, refpaths[i]).refpath == refpaths[i]);
            }
            this.assertTrue(testVar, "Module definitions have not been decorated with refpaths");

            pgh.$dispose();
        },

        testGetPageModulesDescriptions : function () {
            var pgh = new aria.pageEngine.utils.PageConfigHelper(this.pageDefOne.pageDef);

            var modules = pgh.getPageModulesDescriptions(["modOne", "mod.modthree"]);
            this.assertTrue(modules.length == 2);
            this.assertTrue(this._getModuleWithRefpath(modules, "modOne") != null);
            this.assertTrue(this._getModuleWithRefpath(modules, "mod.modthree") != null);

            modules = pgh.getPageModulesDescriptions([]);
            this.assertTrue(modules.length === 0);

            modules = pgh.getPageModulesDescriptions(["modOne", "mod.modthree", "doesnotexist"]);
            this.assertTrue(modules.length === 2);

            pgh.$dispose();
        },

        testGetLazyPlaceholderIds : function () {
            var pgh = new aria.pageEngine.utils.PageConfigHelper(this.pageDefOne.pageDefTwo);
            var lazyDeps = pgh.getLazyPlaceholdersIds();
            this.assertTrue(lazyDeps.length == 3);
            this._testContains(["body.middle", "body.middle.top", "bottomRight"], lazyDeps, "");
            this._testContains(lazyDeps, ["body.middle", "body.middle.top", "bottomRight"], "");
            pgh.$dispose();
        },

        testGetLazyPageDependencies : function () {
            var pgh = new aria.pageEngine.utils.PageConfigHelper(this.pageDefOne.pageDefTwo);
            var dep = pgh.getPageDependencies(false);

            // css
            this._testContains(dep.css, ["a.css", "d.css", "e.css", "f.css", "g.css", "h.css"]);
            this.assertTrue(dep.css.length == 6);

            // templates
            this._testContains(dep.templates, ["body.template", "body.first.template", "body.second.template",
                    "main.page.template"], "Incorrect templates dependencies");
            this.assertTrue(dep.templates.length == 4);

            // classes
            this._testContains(dep.classes, ["module.one.classpath", "module.two.classpath", "module.three.classpath"]);
            this.assertTrue(dep.classes.length == 3);

            // common modules refpaths
            this._testContains(dep.modules.common, ["modOne"]);
            this.assertTrue(dep.modules.common.length == 1);

            // page-specific modules refpaths
            this._testContains(dep.modules.page, ["modOne", "mod.modthree", "modFour"]);
            this.assertTrue(dep.modules.page.length == 3);

            dep = pgh.getPageDependencies(true);

            // css
            this._testContains(dep.css, ["b.css", "c.css", "d.css"]);
            this.assertTrue(dep.css.length == 3);

            // templates
            this._testContains(dep.templates, ["body.middle.template", "body.second.template"], "Incorrect lazy templates dependencies");
            this.assertTrue(dep.templates.length == 2);

            // classes
            this._testContains(dep.classes, ["module.four.classpath"]);
            this.assertTrue(dep.classes.length == 1);

            // common modules refpaths
            this.assertTrue(dep.modules.common.length === 0);

            // page-specific modules refpaths
            this._testContains(dep.modules.page, ["modTwo"]);
            this.assertTrue(dep.modules.page.length == 1);
            pgh.$dispose();

        },

        _testContains : function (container, content, errorMsg) {
            var containsAll = true;
            var arrayUtils = aria.utils.Array;
            for (var i = 0, len = content.length; i < len; i++) {
                containsAll = containsAll && arrayUtils.contains(container, content[i]);
            }
            this.assertTrue(containsAll, errorMsg);
        },

        _getModuleWithRefpath : function (modules, refpath) {
            for (var i = 0, len = modules.length; i < len; i++) {
                if (modules[i].refpath == refpath) {
                    return modules[i];
                }
            }
            return null;
        }

    }
});


text:
{% extends "admin/index.html" %}
{% load i18n %}

{% block content_title %}{% endblock %}

{% block extrastyle %}
{{ block.super }}

{% endblock %}

{% block content %}

        Date
        Start Odo
        End Odo
        Distance [km]
        Energe used [kWh]
        Energe charged [kWh]
        Efficiency [Wh/km]

{% endblock %}


text:
import datetime
import requests
import json
from bs4 import BeautifulSoup

def write_json(file_name, content):
    with open(file_name, 'w') as output_file:
        json.dump(content, output_file, indent=4)

res = requests.get('http://new.cpc.com.tw/division/mb/oil-more1-1.aspx')
source =  res.text
tmp1 = source.split('')
nineeight = tmp1[2].split('	')
ninefive = tmp1[4].split('	')
ninetwo = tmp1[6].split('	')
ultra = tmp1[10].split('	')
ninetwoP = ninetwo[0]
ninefiveP = ninefive[0]
nineeightP = nineeight[0]
ultraP = ultra[0]
tmp2 = source.split('')
d1 = tmp2[5]
d2 = tmp2[6]
d3 = tmp2[7]
year = d1.split('')
month = d2.split('')
day = d3.split('')
newdate = datetime.datetime(int(year[0]), int(month[0]), int(day[0]))
date = newdate.strftime("%Y-%m-%d")

req = requests.get('http://new.cpc.com.tw/mobile/Home/')
boca_soup = BeautifulSoup(req.text, "html.parser") #get text content of the website
main = boca_soup.find('div', attrs={"id": "price"})
status = main.find('div', attrs={"id":'floatprice-LU'}).text
float_date = main.find('div', attrs={"id":'floatprice-date'}).text
float_price = main.find('div', attrs={"id":'floatprice-R'}).text

data = {'date':date,'ninetwo':float(ninetwoP),'ninefive':float(ninefiveP),'nineeight':float(nineeightP),'ultra':float(ultraP),'type':0, 'status': status, 'float_date': float_date, 'float_price': float_price}
print (data)
write_json('./data/oil.json', data)


text:
const DEFAULT_ENCODING = 'UTF8';
const FILESYSTEM_DELAY = 1100;

var path = require('path');
var assert = require('assert');
var async = require('async');
var fs = require('fs');
var moment = require('moment');
var request = require('supertest');
var nock = require('nock');
var zlib = require('zlib');
var timekeeper = require('timekeeper');
var solidus = require('../solidus.js');
var SolidusServer = require('../lib/server.js');
var Page = require('../lib/page.js');

var original_path = __dirname;
var site1_path = path.join( original_path, 'fixtures', 'site 1' );
var site2_path = path.join( original_path, 'fixtures', 'site2' );

var normalizePath = function( file_path ){
  return file_path.replace( /\//g, path.sep );
};

describe( 'Solidus', function(){

  describe( 'production', function(){

    var solidus_server;
    var original_redirects = [];

    beforeEach( function( done ){
      process.chdir( site1_path );
      // Generate time-based redirects
      // These are used to ensure that temporary redirects are properly checked
      original_redirects = fs.readFileSync( 'redirects.js', DEFAULT_ENCODING );
      delete require.cache[require.resolve(site1_path + '/redirects.js')];
      var original_redirects_arr = require(site1_path + '/redirects.js');
      var redirect_date_format = 'YYYY-MM-DD HH:mm:ss';
      var temporal_redirects = [{
        start: moment().add( 's', 5 ).format( redirect_date_format ),
        from: '/future-redirect',
        to: '/'
      }, {
        start: moment().subtract( 's', 5 ).format( redirect_date_format ),
        end: moment().add( 's', 5 ).format( redirect_date_format ),
        from: '/current-redirect',
        to: '/'
      }, {
        start: moment().subtract( 's', 10 ).format( redirect_date_format ),
        end: moment().subtract( 's', 5 ).format( redirect_date_format ),
        from: '/past-redirect',
        to: '/'
      }];
      var overlapping_redirects = [{
        start: moment().add( 's', 5 ).format( redirect_date_format ),
        from: '/overlapping-redirect',
        to: '/overlapping-redirect-future'
      }, {
        start: moment().subtract( 's', 5 ).format( redirect_date_format ),
        end: moment().add( 's', 5 ).format( redirect_date_format ),
        from: '/overlapping-redirect',
        to: '/overlapping-redirect-current'
      }, {
        start: moment().subtract( 's', 10 ).format( redirect_date_format ),
        end: moment().subtract( 's', 5 ).format( redirect_date_format ),
        from: '/overlapping-redirect',
        to: '/overlapping-redirect-past'
      }];
      var combined_redirects = JSON.stringify( temporal_redirects.concat( overlapping_redirects ) );
      fs.appendFileSync( 'redirects.js', ';module.exports = module.exports.concat(' + combined_redirects + ');', DEFAULT_ENCODING );

      // mock http endpoints for resources
      nock('https://solid.us').get('/basic/1').reply( 200, { test: true } );
      nock('https://solid.us').get('/basic/2').reply( 200, { test: true } );
      nock('https://solid.us').get('/dynamic/segment/3').reply( 200, { test: true } );
      nock('https://solid.us').get('/resource/options/url').reply( 200, { test: true } );
      nock('https://solid.us').get('/resource/options/query?test=true').reply( 200, { test: true } );
      nock('https://solid.us').get('/resource/options/dynamic/query?test=3').reply( 200, { test: true } );
      nock('https://solid.us').get('/resource/options/double/dynamic/query?a=%2C&b=%2C&test2=4&c=%2C&d=%252C&test=3').reply( 200, { test: true } );
      nock('https://solid.us').get('/centralized/auth/query').reply( 200, { test: true } );
      nock('https://solid.us').get('/resource/options/headers').matchHeader( 'key', '12345' ).reply( 200, { test: true } );
      nock('https://a.solid.us').get('/centralized/auth').matchHeader( 'key', '12345' ).reply( 200, { test: true } );
      nock('https://b.solid.us').get('/centralized/auth/query?key=12345').reply( 200, { test: true } );
      // empty dynamic segments
      nock('https://solid.us').get('/dynamic/segment/').reply( 200, { test: false } );
      nock('https://solid.us').get('/resource/options/dynamic/query?test=').reply( 200, { test: false } );
      nock('https://solid.us').get('/resource/options/double/dynamic/query?a=%2C&b=%2C&test2=&c=%2C&d=%252C&test=').reply( 200, { test: false } );

      async.parallel([
        // compressed resources
        function( callback ){
          zlib.gzip( '{"test":true}', function( _, result ){
            nock('https://solid.us').get('/compressed/gzip').reply( 200, result, { 'Content-Encoding': 'gzip' } );
            callback();
          });
        },
        function( callback ){
          zlib.deflate( '{"test":true}', function( _, result ){
            nock('https://solid.us').get('/compressed/deflate').reply( 200, result, { 'Content-Encoding': 'deflate' } );
            callback();
          });
        }
      ],
      function(){
        solidus_server = solidus.start({
          log_level: -1,
          port: 9009
        });
        solidus_server.on( 'ready', done );
      });
    });

    afterEach( function(){
      solidus_server.stop();
      fs.writeFileSync( 'redirects.js', original_redirects, DEFAULT_ENCODING );
      process.chdir( original_path );
    });

    it( 'Starts a new http server', function( done ){
      request( solidus_server.router )
        .get('/')
        .end( function( err, res ){
          if( err ) throw err;
          done();
        });
    });

    it( 'Creates routes based on the contents of /views', function( done ){
      var s_request = request( solidus_server.router );
      async.parallel([
        function( callback ){
          s_request.get('/').expect( 200, callback );
        },
        function( callback ){
          s_request.get('/layout').expect( 200, callback );
        }
      ], function( err, results ){
        if( err ) throw err;
        done();
      });
    });

    it( 'Creates routes with dynamic segments', function( done ){
      var s_request = request( solidus_server.router );
      async.parallel([
        function( callback ){
          s_request.get('/dynamic/1').expect( 200, callback );
        },
        function( callback ){
          s_request.get('/dynamic/2').expect( 200, callback );
        }
      ], function( err, results ){
        if( err ) throw err;
        done();
      });
    });

    it( 'Creates routes for page contexts', function( done ){
      var s_request = request( solidus_server.router );
      async.parallel([
        function( callback ){
          s_request.get('/.json')
            .expect( 'Content-Type', /json/ )
            .expect( 200 )
            .end( function( err, res ){
              assert( res.body.page.title === 'test' );
              assert( res.body.parameters );
              assert( res.body.query );
              callback( err );
            });
        },
        function( callback ){
          s_request.get('/layout.json?test=true')
            .expect( 'Content-Type', /json/ )
            .expect( 200 )
            .end( function( err, res ){
              assert( res.body.page );
              assert( res.body.parameters );
              assert( res.body.query.test );
              callback( err );
            });
        },
        function( callback ){
          s_request.get('/dynamic/1.json')
            .expect( 'Content-Type', /json/ )
            .expect( 200 )
            .end( function( err, res ){
              assert( res.body.page );
              assert( res.body.parameters.segment == '1' );
              assert( res.body.query );
              callback( err );
            });
        },
        function( callback ){
          s_request.get('/dynamic/2.json')
            .expect( 'Content-Type', /json/ )
            .expect( 200 )
            .end( function( err, res ){
              assert( res.body.page );
              assert( res.body.parameters.segment == '2' );
              assert( res.body.query );
              callback( err );
            });
        }
      ], function( err, results ){
        if( err ) throw err;
        done();
      });
    });

    it( 'Returns 404s for unmatched routes', function( done ){
      var s_request = request( solidus_server.router );
      s_request.get('/nonexistent-url')
        .expect( 404 )
        .end( function( err, res ){
          assert(res.text.indexOf('Not here!') > -1);
          if( err ) throw err;
          done();
        });
    });

    it( 'Makes URL information available in page context', function( done ){
      var s_request = request( solidus_server.router );
      s_request.get('/.json')
        .expect( 'Content-Type', /json/ )
        .expect( 200 )
        .end( function( err, res ){
          assert( res.body.url );
          assert( res.body.url.path === '/.json' );
          if( err ) throw err;
          done();
        });
    });

    it( 'Sets noindex header for preview mode', function( done ){
      var s_request = request( solidus_server.router );
      s_request.get('/?is_preview=true')
        .expect( 'x-robots-tag', /noindex/ )
        .end( function( err, res ){
          if (err) throw err;
          done();
        });
    });

    it( 'Finds the list of partials used by each page', function(done) {
      var partials = ['partial1', 'partial2', 'partial3', 'partial/4', 'partial9', "partial'10", 'partial11', 'partial"12'];
      assert.deepEqual(solidus_server.views[solidus_server.pathFromPartialName('multiple_partials')].partials, partials);
      done();
    });

    it( 'Fetches resources and adds them to the page context', function( done ){
      var s_request = request( solidus_server.router );
      async.parallel([
        function( callback ){
          s_request.get('/.json?resource_test=3&resource_test2=4')
            .expect( 'Content-Type', /json/ )
            .expect( 200 )
            .end( function( err, res ){
              assert( res.body.resources.basic.test );
              assert( res.body.resources.basic2.test );
              assert( res.body.resources['dynamic-segment'].test );
              assert( res.body.resources['resource-options-url'].test );
              assert( res.body.resources['resource-options-query'].test );
              assert( res.body.resources['resource-options-headers'].test );
              assert( res.body.resources['resource-options-double-dynamic-query'].test );
              assert( res.body.resources['resource-options-dynamic-query'].test );
              assert( res.body.resources['centralized-auth'].test );
              assert( res.body.resources['centralized-auth-query'].test );
              assert( res.body.resources['compressed-gzip'].test );
              assert( res.body.resources['compressed-deflate'].test );
              callback( err );
            });
        }
      ], function( err, results ){
        if( err ) throw err;
        done();
      });
    });

    it( 'Sets request url as resource referer', function(done) {
      nock('https://solid.us').get('/cache?a=1').matchHeader('Referer', 'http://some.domain.com:123/caching?a=1').reply( 200, { test: 1 } );
      nock('https://solid.us').get('/cache?a=2').matchHeader('Referer', 'http://some.domain.com:123/caching?a=1').reply( 200, { test: 2 } );

      var s_request = request(solidus_server.router);
      s_request.get('/caching?a=1')
        .set('Host', 'some.domain.com:123')
        .expect(200)
        .end(function(err, res) {
          if (err) throw err;
          done();
        });
    });

    it('Renders an error with error.hbs when a mandatory resource has an error', function(done) {
      var s_request = request(solidus_server.router);
      async.parallel([
        function(callback) {
          // Bad fetched data
          nock('https://solid.us').get('/error/mandatory?test=1').reply(200, 'Not JSON');
          nock('https://solid.us').get('/error/optional?test=1').reply(200, {test: 1});
          s_request.get('/with_resource_error?test=1')
            .expect(500)
            .end(function(err, res) {
              assert(res.text.indexOf('Oh no (500)!') > -1);
              callback(err);
            });
        },
        function(callback) {
          // 200 status and error in response message
          nock('https://solid.us').get('/error/mandatory?test=2').reply(200, {status: 'error', error: 'Could not find such a thing'});
          nock('https://solid.us').get('/error/optional?test=2').reply(200, {test: 2});
          s_request.get('/with_resource_error?test=2')
            .expect(404)
            .end(function(err, res) {
              assert(res.text.indexOf('Not here!') > -1);
              callback(err);
            });
        },
        function(callback) {
          // Bad status
          nock('https://solid.us').get('/error/mandatory?test=3').reply(401, {error: 'Nice try'});
          nock('https://solid.us').get('/error/optional?test=3').reply(200, {test: 3});
          s_request.get('/with_resource_error?test=3')
            .expect(401)
            .end(function(err, res) {
              assert(res.text.indexOf('Oh no (401)!') > -1);
              callback(err);
            });
        },
        function(callback) {
          // No error with mandatory resource
          nock('https://solid.us').get('/error/mandatory?test=4').reply(200, {test: 4});
          nock('https://solid.us').get('/error/optional?test=4').reply(401, {error: 'Nice try'});
          s_request.get('/with_resource_error.json?test=4')
            .expect(200)
            .end(function(err, res) {
              assert.equal(res.body.resources.mandatory.test, 4);
              assert.equal(res.body.resources.optional, undefined);
              callback(err);
            });
        },
        function(callback) {
          // Missing static resource
          nock('https://solid.us').get('/cache/1').reply(404, {error: 'Could not find such a thing'});
          nock('https://solid.us').get('/cache/2').reply(404, {error: 'Could not find such a thing'});
          s_request.get('/with_all_features')
            .expect(500)
            .end(function(err, res) {
              assert(res.text.indexOf('Oh no (500)!') > -1);
              callback(err);
            });
        },
        function(callback) {
          // No errors with preview parameter
          nock('https://solid.us').get('/error/mandatory?test=5').reply(401, {error: 'Nice try'});
          nock('https://solid.us').get('/error/optional?test=5').reply(401, {error: 'Nice try'});
          s_request.get('/with_resource_error.json?test=5&is_preview=true')
            .expect(200)
            .end(function(err, res) {
              assert.equal(res.body.resources.mandatory, undefined);
              assert.equal(res.body.resources.optional, undefined);
              callback(err);
            });
        },
      ], function(err, results) {
        if (err) throw err;
        done();
      });
    });

    it( 'Preprocesses the context of pages', function( done ){
      var s_request = request( solidus_server.router );
      async.parallel([
        function( callback ){
          s_request.get('/.json')
            .expect( 'Content-Type', /json/ )
            .expect( 200 )
            .end( function( err, res ){
              if( err ) throw err;
              assert( res.body.test === true );
              callback( err );
            });
        },
      ], function( err, results ){
        if( err ) throw err;
        done();
      });
    });

    it('Renders an error when the preprocessor has an error', function(done) {
      var s_request = request(solidus_server.router);
      async.parallel([
        function(callback) {
          s_request.get('/with_preprocessor_error?error=exception')
            .expect(500)
            .end(function(err, res) {
              assert(res.text.indexOf('Oh no (500)!') > -1);
              callback();
            });
        },
        function(callback) {
          s_request.get('/with_preprocessor_error?error=status_code')
            .expect(401)
            .end(function(err, res) {
              assert(res.text.indexOf('Oh no (401)!') > -1);
              callback();
            });
        },
        function(callback) {
          s_request.get('/with_preprocessor_error?error=redirect')
            .expect(302)
            .expect('location', '/redirected', callback);
        },
        function(callback) {
          s_request.get('/with_preprocessor_error?error=redirect_permanent')
            .expect(301)
            .expect('location', '/redirected', callback);
        },
        function(callback) {
          s_request.get('/with_preprocessor_error?error=invalid_redirect_array')
            .expect(200)
            .end(function(err, res) {
              if( err ) throw err;
              assert(res.text.indexOf('No error happened!') > -1);
              callback();
            });
        },
        function(callback) {
          s_request.get('/with_preprocessor_error?error=no_context')
            .expect(500)
            .end(function(err, res) {
              assert(res.text.indexOf('Oh no (500)!') > -1);
              callback();
            });
        }
      ], function(err) {
        if (err) throw err;
        done();
      });
    });

    it('Ignores preprocessor errors in preview mode', function(done) {
      var s_request = request(solidus_server.router);
      async.parallel([
        function(callback) {
          s_request.get('/with_preprocessor_error?error=exception&is_preview=true')
            .expect(200)
            .end(function(err, res) {
              if( err ) throw err;
              assert(res.text.indexOf('No error happened!') > -1);
              callback();
            });
        },
        function(callback) {
          s_request.get('/with_preprocessor_error?error=status_code&is_preview=true')
            .expect(200)
            .end(function(err, res) {
              if( err ) throw err;
              assert(res.text.indexOf('No error happened!') > -1);
              callback();
            });
        },
        function(callback) {
          s_request.get('/with_preprocessor_error?error=redirect&is_preview=true')
            .expect(200)
            .end(function(err, res) {
              if( err ) throw err;
              assert(res.text.indexOf('No error happened!') > -1);
              callback();
            });
        },
        function(callback) {
          s_request.get('/with_preprocessor_error?error=redirect_permanent&is_preview=true')
            .expect(200)
            .end(function(err, res) {
              if( err ) throw err;
              assert(res.text.indexOf('No error happened!') > -1);
              callback();
            });
        },
        function(callback) {
          s_request.get('/with_preprocessor_error?error=invalid_redirect_array&is_preview=true')
            .expect(200)
            .end(function(err, res) {
              if( err ) throw err;
              assert(res.text.indexOf('No error happened!') > -1);
              callback();
            });
        },
        function(callback) {
          s_request.get('/with_preprocessor_error?error=no_context&is_preview=true')
            .expect(200)
            .end(function(err, res) {
              if( err ) throw err;
              assert(res.text.indexOf('No error happened!') > -1);
              callback();
            });
        }
      ], function(err) {
        if (err) throw err;
        done();
      });
    });

    it('Renders error.hbs when an error occurs', function(done) {
      var s_request = request(solidus_server.router);
      async.parallel([
        // Error while rendering page
        function(callback) {
          s_request.get('/with_preprocessor_error?error=exception')
            .expect(500)
            .end(function(err, res) {
              if( err ) throw err;
              assert(res.text.indexOf('<title>Original title</title>') > -1); // Original page title
              assert(res.text.indexOf('Oh no (500)!') > -1); // Error page content
              assert(res.text.indexOf('Le undefined sacrebleu !') > -1); // Helper used in error page
              callback();
            });
        },
        // Missing page
        function(callback) {
          s_request.get('/doesnotexist')
            .expect(404)
            .end(function(err, res) {
              if( err ) throw err;
              assert(res.text.indexOf('<title>Error title</title>') > -1); // Error page title
              assert(res.text.indexOf('Not here!') > -1); // Error page content
              assert(res.text.indexOf('Le undefined sacrebleu !') > -1); // Helper used in error page
              callback();
            });
        },
      ], function(err) {
        if (err) throw err;
        done();
      });
    });

    it( 'Serves assets in /assets', function( done ){
      var s_request = request( solidus_server.router );
      async.parallel([
        function( callback ){
          s_request.get('/scripts/test.js')
            .expect( 200, callback )
            .expect( 'cache-control', 'public, max-age=31536000' );
        },
        function( callback ){
          s_request.get('/styles/test.css').expect( 200, callback );
        }
      ], function( err, results ){
        if( err ) throw err;
        done();
      });
    });

    it( 'Creates redirects based on the contents of redirects.js', function( done ){
      var s_request = request( solidus_server.router );
      async.parallel([
        function( callback ){
          s_request.get('/redirect1').expect( 302, callback );
        },
        function( callback ){
          s_request.get('/redirect2').expect( 302, callback );
        },
        function( callback ){
          s_request.get('/redirect3').expect( 404, callback );
        },
        function( callback ){
          s_request.get('/redirect4').expect( 404, callback );
        },
        function( callback ){
          s_request.get('/redirect5').expect( 301, callback );
        },
        function( callback ){
          s_request.get('/redirect6/old/path').expect( 'location', '/new/path/old', callback );
        },
        function( callback ){
          s_request.get('/redirect7/12-34-56-78').expect( 'location', '/new/56/12/78', callback );
        },
        function( callback ){
          s_request.get('/redirect8/old/path').expect( 'location', '/new/path/OLD', callback );
        },
        function( callback ){
          s_request.get('/redirect9/12-34-56-78').expect( 'location', '/new/56/12/1078', callback );
        },
        function( callback ){
          s_request.get('/match-http-root?with=params').set('Host', 'solidusjs.com').expect( 'location', '/new/match-http-root', callback );
        },
        function( callback ){
          // Bad protocol
          s_request.get('/match-https-root?with=params').set('Host', 'solidusjs.com').expect( 404, callback );
        },
        function( callback ){
          // Bad host
          s_request.get('/match-http-root?with=params').set('Host', 'www.solidusjs.com').expect( 404, callback );
        },
        function( callback ){
          s_request.get('/some/path?with=params').set('Host', 'no-path.com').expect( 'location', 'http://www.no-path.com/some/path?with=params', callback );
        },
        function( callback ){
          s_request.get('/to-https-www?with=params').set('Host', 'solidusjs.com').expect( 'location', 'https://www.solidusjs.com/to-https-www?with=params', callback );
        },
        function( callback ){
          s_request.get('/to-https-www-url/old-path?with=params').set('Host', 'solidusjs.com').expect( 'location', 'https://www.solidusjs.com/new/url/old-path', callback );
        },
        function( callback ){
          s_request.get('/past-redirect').expect( 404, callback );
        },
        function( callback ){
          s_request.get('/current-redirect').expect( 302, callback );
        },
        function( callback ){
          s_request.get('/future-redirect').expect( 404, callback );
        },
        function( callback ){
          s_request.get('/overlapping-redirect').expect( 'location', '/overlapping-redirect-current', callback );
        }
      ], function( err, results ){
        if( err ) throw err;
        done();
      });
    });

    it( 'Sets the default layout', function(){
      assert( solidus_server.handlebars.defaultLayout === 'layout' );
    });

    it( 'Uses the layout closest to a page view', function( done ){
      var s_request = request( solidus_server.router );
      async.parallel([
        function( callback ){
          s_request
            .get('/deeply/nested/page/using/a_layout.json')
            .expect( 200 )
            .end( function( err, res ){
              assert( res.body.layout === normalizePath('deeply/nested/layout.hbs') );
              callback( err );
            });
        },
        function( callback ){
          s_request
            .get('/deeply/nested/page.json')
            .expect( 200 )
            .end( function( err, res ){
              assert( res.body.layout === normalizePath('deeply/nested/layout.hbs') );
              callback( err );
            });
        }
      ], function( err, results ){
        if( err ) throw err;
        done();
      });
    });

    it( 'Makes partials available even if they have the same name in different directories', function( done ){
      var s_request = request( solidus_server.router );
      async.parallel([
        function( callback ){
          s_request
            .get('/partial_holder/')
            .expect( 200 )
            .end( function( err, res ){
              assert( res.text == 'partial.hbs' );
              callback( err );
            });
        },
        function( callback ){
          s_request
            .get('/partial_holder2/')
            .expect( 200 )
            .end( function( err, res ){
              assert( res.text == 'deeply/partial.hbs' );
              callback( err );
            });
        }
      ], function( err, results ){
        if( err ) throw err;
        done();
      });
    });

    it( 'Makes partials available from node_modules', function( done ){
      request(solidus_server.router)
        .get('/partial_holder3/')
        .expect(200)
        .end(function(err, res) {
          assert.ifError(err);
          assert.equal(res.text, 'partial.hbs\nPartial from external module.\nPartial with same path as external partial (site 1/node_modules/extra/conflict).');
          done();
        });
    });

    describe('Sends appropriate cache headers with pages', function() {
      var now;

      beforeEach(function() {
        now = new Date().getTime()
        timekeeper.freeze(now);
      });

      afterEach(function() {
        timekeeper.reset();
      });

      it( '5 minutes for pages without resources', function( done ){
        var s_request = request( solidus_server.router );
        s_request
          .get('/partial')
          .expect( 'cache-control', 'public, max-age=300, stale-while-revalidate=86400, stale-if-error=86400' )
          .expect( 'expires', new Date(now + 300 * 1000).toUTCString() )
          .end( function( err, res ){
            if( err ) throw err;
            done();
          });
      });

      it( 'nearest resource expiration for pages with resources', function( done ){
        nock('https://solid.us').get('/cache?a=1').reply(200, {test: 1}, {'Cache-Control': 'max-age=111'});
        nock('https://solid.us').get('/cache?a=2').reply(200, {test: 2}, {'Cache-Control': 'max-age=222'});

        var s_request = request( solidus_server.router );
        s_request
          .get('/caching')
          .expect( 'cache-control', 'public, max-age=111, stale-while-revalidate=86400, stale-if-error=86400' )
          .expect( 'expires', new Date(now + 111 * 1000).toUTCString() )
          .end( function( err, res ){
            if( err ) throw err;
            done();
          });
      });

      it( 'ignores resources with expiration higher than 5 minutes', function( done ){
        nock('https://solid.us').get('/cache?a=1').reply(200, {test: 1}, {'Cache-Control': 'max-age=1111'});
        nock('https://solid.us').get('/cache?a=2').reply(200, {test: 2}, {'Cache-Control': 'max-age=222'});

        var s_request = request( solidus_server.router );
        s_request
          .get('/caching')
          .expect( 'cache-control', 'public, max-age=222, stale-while-revalidate=86400, stale-if-error=86400' )
          .expect( 'expires', new Date(now + 222 * 1000).toUTCString() )
          .end( function( err, res ){
            if( err ) throw err;
            done();
          });
      });

      it( 'ignores resources without expiration', function( done ){
        nock('https://solid.us').get('/cache?a=1').reply(200, {test: 1});
        nock('https://solid.us').get('/cache?a=2').reply(200, {test: 2}, {'Cache-Control': 'max-age=222'});

        var s_request = request( solidus_server.router );
        s_request
          .get('/caching')
          .expect( 'cache-control', 'public, max-age=222, stale-while-revalidate=86400, stale-if-error=86400' )
          .expect( 'expires', new Date(now + 222 * 1000).toUTCString() )
          .end( function( err, res ){
            if( err ) throw err;
            done();
          });
      });

      it( 'ignores bad resources with expiration', function( done ){
        nock('https://solid.us').get('/cache?a=1').reply(400, {test: 1}, {'Cache-Control': 'max-age=111'});
        nock('https://solid.us').get('/cache?a=2').reply(200, {test: 2}, {'Cache-Control': 'max-age=222'});

        var s_request = request( solidus_server.router );
        s_request
          .get('/caching')
          .expect( 'cache-control', 'public, max-age=222, stale-while-revalidate=86400, stale-if-error=86400' )
          .expect( 'expires', new Date(now + 222 * 1000).toUTCString() )
          .end( function( err, res ){
            if( err ) throw err;
            done();
          });
      });
    })

    it( 'Runs helpers after preprocessors', function( done ){
      var s_request = request( solidus_server.router );
      s_request
        .get('/helpers')
        .end( function( err, res ){
          assert( res.text.indexOf('SOLIDUS') > -1 ); // Handlebars-helper
          assert( res.text.indexOf('Le Solidus sacrebleu !') > -1 ); // Site helper
          done();
        });
    });

    it('Sets the X-Powered-By header for HTML requests', function(done) {
      var s_request = request(solidus_server.router);
      s_request
        .get('/')
        .expect('X-Powered-By', 'Solidus/' + require('../package.json').version)
        .end(function(err, res) {
          if (err) throw err;
          done();
        });
    });

    it('Sets the X-Powered-By header for JSON requests', function(done) {
      var s_request = request(solidus_server.router);
      s_request
        .get('/.json')
        .expect('X-Powered-By', 'Solidus/' + require('../package.json').version)
        .end(function(err, res) {
          if (err) throw err;
          done();
        });
    });

    it('Sets the X-Powered-By header for 404s', function(done) {
      var s_request = request(solidus_server.router);
      s_request
        .get('/nonexistent-url')
        .expect('X-Powered-By', 'Solidus/' + require('../package.json').version)
        .end(function(err, res) {
          if (err) throw err;
          done();
        });
    });

    describe('/api/resource.json', function() {
      beforeEach(function() {
        var now = new Date(1397524638000); // Test date rounded to the second, to simplify comparisons
        timekeeper.freeze(now);
      });

      afterEach(function() {
        timekeeper.reset();
      });

      it('fetches and renders the url in the query string', function(done) {
        nock('https://solid.us').get('/api-resource').reply(200, {test: 2});

        var s_request = request(solidus_server.router);
        s_request.get('/api/resource.json?url=https://solid.us/api-resource')
          .expect(200)
          .expect('Content-Type', /json/)
          .end(function(err, res) {
            if (err) throw err;
            assert.deepEqual(res.body, {test: 2});
            done();
          });
      });

      it('renders an error when missing url', function(done) {
        var s_request = request(solidus_server.router);
        s_request.get('/api/resource.json')
          .expect(400)
          .expect('Content-Type', /json/)
          .end(function(err, res) {
            if (err) throw err;
            assert.deepEqual(res.body, {error: "Missing 'url' parameter"});
            done();
          });
      });

      it('renders an error when bad url', function(done) {
        var s_request = request(solidus_server.router);
        s_request.get('/api/resource.json?url=not-a-url')
          .expect(400)
          .expect('Content-Type', /json/)
          .end(function(err, res) {
            if (err) throw err;
            assert.deepEqual(res.body, {error: "Invalid 'url' parameter"});
            done();
          });
      });

      it('fetches and renders an error when resource is invalid', function(done) {
        nock('https://solid.us').get('/api-resource').reply(200, 'this is not json');

        var s_request = request(solidus_server.router);
        s_request.get('/api/resource.json?url=https://solid.us/api-resource')
          .expect(400)
          .expect('Content-Type', /json/)
          .end(function(err, res) {
            if (err) throw err;
            assert.deepEqual(res.body, {status: 400, error: 'Invalid JSON', message: {error: 'Unexpected token h'}});
            done();
          });
      });

      it('returns the resource\'s freshness when the resource is valid and has caching headers', function(done) {
        nock('https://solid.us').get('/api-resource').reply(200, {test: 2}, {'Cache-Control': 'max-age=123'});

        var s_request = request(solidus_server.router);
        s_request.get('/api/resource.json?url=https://solid.us/api-resource')
          .expect('Cache-Control', 'public, max-age=123, stale-while-revalidate=86400, stale-if-error=86400')
          .expect('Expires', new Date(new Date().getTime() + 123 * 1000).toUTCString())
          .end(function(err, res) {
            if (err) throw err;
            done();
          });
      });

      it('returns the default freshness when the resource is valid and has no caching headers', function(done) {
        nock('https://solid.us').get('/api-resource').reply(200, {test: 2});

        var s_request = request(solidus_server.router);
        s_request.get('/api/resource.json?url=https://solid.us/api-resource')
          .expect('Cache-Control', 'public, max-age=300, stale-while-revalidate=86400, stale-if-error=86400')
          .expect('Expires', new Date(new Date().getTime() + 5 * 60 * 1000).toUTCString())
          .end(function(err, res) {
            if (err) throw err;
            done();
          });
      });

      it('returns the resource\'s freshness when the resource is invalid and has caching headers', function(done) {
        nock('https://solid.us').get('/api-resource').reply(400, {test: 2}, {'Cache-Control': 'max-age=123'});

        var s_request = request(solidus_server.router);
        s_request.get('/api/resource.json?url=https://solid.us/api-resource')
          .expect('Cache-Control', 'public, max-age=123, stale-while-revalidate=86400, stale-if-error=86400')
          .expect('Expires', new Date(new Date().getTime() + 123 * 1000).toUTCString())
          .end(function(err, res) {
            if (err) throw err;
            done();
          });
      });

      it('returns no freshness when the resource is invalid and has no caching headers', function(done) {
        nock('https://solid.us').get('/api-resource').reply(400, {test: 2});

        var s_request = request(solidus_server.router);
        s_request.get('/api/resource.json?url=https://solid.us/api-resource')
          .expect('Cache-Control', 'public, max-age=0, stale-while-revalidate=86400, stale-if-error=86400')
          .expect('Expires', new Date().toUTCString())
          .end(function(err, res) {
            if (err) throw err;
            done();
          });
      });

      it('fetches the url using the appropriate auth', function(done) {
        nock('https://a.solid.us').get('/api-resource').matchHeader('key', '12345').reply(200, {test: 2});

        var s_request = request(solidus_server.router);
        s_request.get('/api/resource.json?url=https://a.solid.us/api-resource')
          .expect(200)
          .expect('Content-Type', /json/)
          .end(function(err, res) {
            if (err) throw err;
            assert.deepEqual(res.body, {test: 2});
            done();
          });
      });
    });

    describe('no-cache request header', function() {
      it('adds no-cache headers to resources', function(done) {
        nock('https://solid.us').get('/cache?a=1').matchHeader('Cache-Control', 'no-cache').matchHeader('Pragma', 'no-cache').reply(200, {test: 1});
        nock('https://solid.us').get('/cache?a=2').matchHeader('Cache-Control', 'no-cache').matchHeader('Pragma', 'no-cache').reply(200, {test: 2});

        var s_request = request(solidus_server.router);
        s_request.get('/caching')
          .set('cache-control', 'no-cache')
          .expect(200)
          .end( function( err, res ){
            if( err ) throw err;
            done();
          });
      });

      it('adds no-cache headers to api resources', function(done) {
        nock('https://solid.us').get('/api-resource').matchHeader('Cache-Control', 'no-cache').matchHeader('Pragma', 'no-cache').reply(200, {test: 2});

        var s_request = request(solidus_server.router);
        s_request.get('/api/resource.json?url=https://solid.us/api-resource')
          .set('PRAGMA', 'no-cache')
          .expect(200)
          .end(function(err, res) {
            if (err) throw err;
            done();
          });
      });
    });
  });

  describe( 'development', function(){

    var solidus_server;

    beforeEach( function( done ){
      process.chdir( site2_path );
      solidus_server = solidus.start({
        log_level: -1,
        port: 9009,
        dev: true,
        livereload_port: 12345
      });
      // hack that will work until .start callback is complete
      solidus_server.on( 'ready', function(){
        setTimeout( done, FILESYSTEM_DELAY );
      });
    });

    afterEach( function(){
      solidus_server.stop();
      process.chdir( original_path );
    });

    it( 'Adds a route when a new view is added', function( done ){
      fs.writeFileSync( 'views/watch_test.hbs', 'test', DEFAULT_ENCODING );
      var s_request = request( solidus_server.router );
      setTimeout( function(){
        s_request.get('/watch_test').expect( 200, function( err ){
          if( err ) throw err;
          done();
        });
      }, FILESYSTEM_DELAY );
    });

    it( 'Removes a route when a view is removed', function( done ){
      fs.unlinkSync('views/watch_test.hbs');
      var s_request = request( solidus_server.router );
      setTimeout( function(){
        s_request.get('/watch_test').expect( 404, function( err ){
          if( err ) throw err;
          done();
        });
      }, FILESYSTEM_DELAY );
    });

    it( 'Adds redirects when redirects.js is added', function( done ){
      var s_request = request( solidus_server.router );
      var redirects_json = JSON.stringify([{"from": "/redirect1", "to": "/"}]);
      fs.writeFileSync( 'redirects.js', 'module.exports = ' + redirects_json, DEFAULT_ENCODING );
      setTimeout(function() {
        async.parallel([
          function(callback) {
            s_request.get('/redirect1').expect(302, callback);
          },
          function(callback) {
            s_request.get('/redirect2').expect(404, callback);
          },
        ], function(err) {
          if (err) throw err;
          done();
        });
      }, FILESYSTEM_DELAY);
    });

    it( 'Updates redirects when redirects.js changes', function( done ){
      var s_request = request( solidus_server.router );
      var redirects_json = JSON.stringify([{"from": "/redirect2", "to": "/"}]);
      fs.writeFileSync( 'redirects.js', 'module.exports = ' + redirects_json, DEFAULT_ENCODING );
      setTimeout(function() {
        async.parallel([
          function(callback) {
            s_request.get('/redirect1').expect(404, callback);
          },
          function(callback) {
            s_request.get('/redirect2').expect(302, callback);
          },
        ], function(err) {
          if (err) throw err;
          done();
        });
      }, FILESYSTEM_DELAY);
    });

    it( 'Removes redirects when redirects.js is deleted', function( done ){
      var s_request = request( solidus_server.router );
      fs.unlinkSync('redirects.js');
      setTimeout(function() {
        async.parallel([
          function(callback) {
            s_request.get('/redirect1').expect(404, callback);
          },
          function(callback) {
            s_request.get('/redirect2').expect(404, callback);
          },
        ], function(err) {
          if (err) throw err;
          done();
        });
      }, FILESYSTEM_DELAY);
    });

    var test_preprocessor_contents = 'module.exports=function(context){context.test = true;return context;};';

    it( 'Adds preprocessors when a preprocessor js file is added', function( done ){
      var s_request = request( solidus_server.router );
      fs.writeFileSync( 'preprocessors/test.js', test_preprocessor_contents, DEFAULT_ENCODING );
      setTimeout( function(){
        s_request.get('/test.json')
          .expect( 200 )
          .end( function( err, res ){
            if( err ) throw err;
            assert( res.body.test );
            done();
          });
      }, FILESYSTEM_DELAY );
    });

    var parent_preprocessor_contents = 'var child = require("./child");module.exports=function(context){context.test = child();return context;};';
    var child_preprocessor_contents = 'module.exports=function(){return "ok";};';
    var child_preprocessor_contents_2 = 'module.exports=function(){return "okok";};';

    it( 'Invalidates all cached preprocessor modules on a change to any of them', function( done ){
      this.timeout(FILESYSTEM_DELAY * 2.5);
      var s_request = request( solidus_server.router );
      fs.writeFileSync( 'preprocessors/test.js', parent_preprocessor_contents, DEFAULT_ENCODING );
      fs.writeFileSync( 'preprocessors/child.js', child_preprocessor_contents, DEFAULT_ENCODING );
      setTimeout( function(){
        s_request.get('/test.json')
          .expect( 200 )
          .end( function( err, res ){
            if( err ) throw err;
            assert( res.body.test === 'ok' );

            fs.writeFileSync( 'preprocessors/child.js', child_preprocessor_contents_2, DEFAULT_ENCODING );

            setTimeout( function(){
              s_request.get('/test.json')
                .expect( 200 )
                .end( function( err, res ){
                  if( err ) throw err;
                  assert( res.body.test === 'okok' );
                  fs.unlinkSync('preprocessors/child.js');
                  done();
                });
            }, FILESYSTEM_DELAY );
          });
      }, FILESYSTEM_DELAY );
    });

    it( 'Removes preprocessors when their file is removed', function( done ){
      fs.unlinkSync('preprocessors/test.js');
      var s_request = request( solidus_server.router );
      setTimeout( function(){
        s_request.get('/test.json')
          .expect( 200 )
          .end( function( err, res ){
            if( err ) throw err;
            assert( !res.body.test );
            done();
          });
      }, FILESYSTEM_DELAY );
    });

    var helpers_js = "module.exports={uppercase:function(string){return string+' is uppercase';}};";
    var helpers2_js = "module.exports={uppercase:function(string){return string+' is uppercase 2';}};";

    it( 'Adds helpers when helpers.js is added', function( done ){
      var s_request = request( solidus_server.router );
      fs.writeFileSync( 'helpers.js', helpers_js, DEFAULT_ENCODING );
      setTimeout( function(){
        s_request
          .get('/helpers')
          .end( function( err, res ){
            if( err ) throw err;
            assert( res.text.indexOf('Site helpers loaded is uppercase') > -1 );
            done();
          });
      }, FILESYSTEM_DELAY );
    });

    it( 'Updates helpers when helpers.js changes', function( done ){
      var s_request = request( solidus_server.router );
      fs.writeFileSync( 'helpers.js', helpers2_js, DEFAULT_ENCODING );
      setTimeout( function(){
        s_request
          .get('/helpers')
          .end( function( err, res ){
            if( err ) throw err;
            assert( res.text.indexOf('Site helpers loaded is uppercase 2') > -1 );
            done();
          });
      }, FILESYSTEM_DELAY );
    });

    it( 'Removes helpers when helpers.js is deleted', function( done ){
      var s_request = request( solidus_server.router );
      fs.unlinkSync('helpers.js');
      setTimeout( function(){
        s_request
          .get('/helpers')
          .end( function( err, res ){
            if( err ) throw err;
            assert( res.text.indexOf('Site helpers loaded is uppercase') == -1 );
            done();
          });
      }, FILESYSTEM_DELAY );
    });

    it( 'Passes dev variables to view context', function( done ){
      var s_request = request( solidus_server.router );
      s_request.get('/dev.json')
        .expect( 200 )
        .end( function( err, res ){
          if( err ) throw err;
          assert( res.body.dev );
          assert( res.body.development );
          assert.equal( 12345, res.body.livereload_port );
          done();
        });
    });

    it( 'Does not send cache headers in development', function( done ){
      var s_request = request( solidus_server.router );
      s_request.get('/dev')
        .expect('cache-control', 'no-cache, no-store, max-age=0, must-revalidate')
        .expect('x-robots-tag', 'noindex, nofollow')
        .end( function( err, res ){
          if( err ) throw err;
          done();
        });
    });

    it( 'Does not cache assets in development', function( done ){
      var s_request = request( solidus_server.router );
      s_request.get('/scripts/test.js')
        .expect( 'cache-control', 'public, max-age=0' )
        .end( function( err, res ){
          if( err ) throw err;
          done();
        });
    });

    it('Renders the default error response when error.hbs is missing', function(done) {
      var s_request = request(solidus_server.router);
      async.parallel([
        function(callback) {
          // 200 status and error in response message
          nock('https://solid.us').get('/error/mandatory?test=2').reply(200, {status: 'error', error: 'Could not find such a thing'});
          nock('https://solid.us').get('/error/optional?test=2').reply(200, {test: 2});
          s_request.get('/with_resource_error?test=2')
            .expect(404)
            .end(function(err, res) {
              assert.equal(res.text, '404 Not Found');
              callback(err);
            });
        },
        function(callback) {
          // Bad status
          nock('https://solid.us').get('/error/mandatory?test=3').reply(401, {error: 'Nice try'});
          nock('https://solid.us').get('/error/optional?test=3').reply(200, {test: 3});
          s_request.get('/with_resource_error?test=3')
            .expect(401)
            .end(function(err, res) {
              assert.equal(res.text, '401 Unauthorized');
              callback(err);
            });
        }
      ], function(err, results) {
        if (err) throw err;
        done();
      });
    });

  });

  describe('log server', function() {
    var solidus_server;

    beforeEach(function(done) {
      process.chdir(site1_path);
      solidus_server = solidus.start({
        dev: true,
        log_level: 0,
        port: 9009,
        log_server_port: 12345,
        log_server_level: 3
      });
      solidus_server.on('ready', done);
    });

    afterEach(function() {
      process.chdir(original_path);
    });

    it('Sends the logs to the web socket', function(done) {
      var socket = require('socket.io-client')('http://localhost:12345');
      socket.on('connect', function() {
        // Our web socket client is connected, make a Solidus request
        request(solidus_server.router).get('/helpers.json').end(function(err, res) {
          if (err) throw err;
          assert.equal(12345, res.body.log_server_port);
        });
      });

      socket.on('log', function(data) {
        // Solidus emitted a log message, if it's the last message stop the server
        if (data.level == 3 && /\/helpers \[200\] served in \d+ms/.test(data.message)) {
          solidus_server.stop();
        }
      });

      socket.on('disconnect', function() {
        // The log server was closed, we're done
        done();
      });
    });
  });

  describe('Page.toObjectString', function() {
    var solidus_server;

    before(function(done) {
      process.chdir(site1_path);
      solidus_server = new SolidusServer({start_server: false});
      solidus_server.on('ready', done);
    });

    after(function() {
      process.chdir(original_path);
    });

    it('returns a JS string version of the parsed view', function(done) {
      var parent_file_path = path.join(solidus_server.paths.assets, 'scripts', 'index.js');
      var expected = '{resources:{"cache1":"https://solid.us/cache/1","cache2":"https://solid.us/cache/2"},preprocessor:require("../../preprocessors/index.js"),template:require("../../views/with_all_features.hbs"),template_options:{helpers:require("../../helpers.js"),partials:{"partial":require("../../views/partial.hbs"),"partial_holder":require("../../views/partial_holder.hbs"),"partial_holder2":require("../../views/partial_holder2.hbs"),"deeply/partial":require("../../views/deeply/partial.hbs")}}}';
      assert.equal(solidus_server.views[solidus_server.pathFromPartialName('with_all_features')].toObjectString(parent_file_path), expected);
      done();
    });

    it('with missing features', function(done) {
      var parent_file_path = path.join(solidus_server.paths.assets, 'scripts', 'index.js');
      var expected = '{template:require("../../views/partial.hbs"),template_options:{helpers:require("../../helpers.js")}}';
      assert.equal(solidus_server.views[solidus_server.pathFromPartialName('partial')].toObjectString(parent_file_path), expected);
      done();
    });
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Diagnostics;

namespace Lookum.Framework.Lookup
{
    public abstract class DatabaseLookup<K, V> : BaseLookup<K, V>
    {
        protected string ConnectionString { get; set; }
        protected int CommandTimeOut { get; set; }

        protected DatabaseLookup()
            : base()
        { }

        protected DatabaseLookup(bool throwException)
            : base(throwException)
        { }

        protected DatabaseLookup(V defaultValue)
            : base(defaultValue)
        {}

        protected DatabaseLookup(Func<K, V> nonMatchBehavior)
            : base(nonMatchBehavior)
        { }

        /// <summary>
        /// Load the Lookup to store in memory all the keys/values found in the database
        /// </summary>
        /// <param name="connectionString">The connectionString to use to connect to the database</param>
        /// <param name="commandTimeout">Maximum time allowed to execute the query before throwing an error</param>
        public virtual void Load(string connectionString, int commandTimeout)
        {
            ConnectionString = connectionString;
            CommandTimeOut = commandTimeout;
        }

        public void Load(string connectionString)
        {
            this.Load(connectionString, -1);
        }

        protected override void OnLoad()
        {
            using (var conn = new SqlConnection())
            {
                conn.ConnectionString = ConnectionString;
                using (var cmd = BuildCommand(conn, CommandTimeOut))
                {
                    //Effective execution of the query
                    conn.Open();
                    var dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        K id;
                        V value;

                        var items = new List<object>();
                        for (int i = 0; i < dr.FieldCount; i++)
                            items.Add(dr.GetValue(i));

                        //Mapping of the two fields to a map container.
                        if (IsPrimitive(typeof(K)))
                            id = BuildPrimitiveKey(items.ToArray());
                        else
                            id = BuildKey(items.ToArray());

                        if (IsPrimitive(typeof(V)))
                            value = BuildPrimitiveValue(items.ToArray());
                        else
                            value = BuildValue(items.ToArray());

                        if (Map.Keys.Contains(id))
                            ManageDuplicateKey(id, value);

                        Map.Add(id, value);
                    }
                }
            }
        }

        protected bool IsPrimitive(Type t)
        {
            return t.IsPrimitive || t.IsValueType || (t == typeof(string));
        }

        protected virtual K BuildKey(object[] items)
        {
            throw new ArgumentException("By default, Lookum is expecting a primitive for the key. If you want to return an object in place of a primitive for the value, you need to override the method 'BuildKey' of your database lookup.");
        }

        private Z BuildPrimitive<Z>(object item)
        {
            try
            {
                return (Z)item;
            }
            catch (InvalidCastException ex)
            {
                var stackTrace = new StackTrace();
                var primitiveRole = stackTrace.GetFrame(1).GetMethod().Name.Replace("BuildPrimitive", "").ToLower();

                throw new InvalidCastException(
                    String.Format(
                            "The specified type for the {2} of the lookup ({0}) doesn't match with the type returned by the database ({1})"
                            , typeof(Z).Name
                            , item.GetType().Name
                            , primitiveRole
                            )
                    , ex);
            }
        }

        protected virtual K BuildPrimitiveKey(object[] items)
        {
            return BuildPrimitive<K>(items[0]);
        }

        protected virtual V BuildValue(object[] items)
        {
            throw new ArgumentException("By default, Lookum is expecting a primitive for the value. If you want to return an object in place of a primitive for the value, you need to override the method 'BuildValue' of your database lookup.");
        }

        protected virtual V BuildPrimitiveValue(object[] items)
        {
            return BuildPrimitive<V>(items[items.Length-1]);
        }

        protected IDbCommand BuildCommand(SqlConnection conn, int commandTimeout)
        {
            var cmd = BuildCommand();
            cmd.Connection = conn;

            if (commandTimeout >= 0)
                cmd.CommandTimeout = commandTimeout;

            return cmd;
        }

        protected abstract IDbCommand BuildCommand();

        protected string ReadResourceContent(string filename)
        {
            if (!filename.Contains('.'))
                filename += ".sql";

            var path = String.Format("{0}.{1}.{2}", this.GetType().Namespace, "Resources", filename);
            var content = string.Empty;

            using (Stream stream = Assembly.GetExecutingAssembly()
                                           .GetManifestResourceStream(path))
            using (StreamReader reader = new StreamReader(stream))
            {
                content = reader.ReadToEnd();
            }

            return content;
        }

        protected virtual void ManageDuplicateKey(K id, V value)
        {
            var msg = String.Format("The key '{0}' has already been added to the lookup and you're trying to add it a second time. The lookup currently contains {1} element{2}."
                                                        , id
                                                        , Map.Count()
                                                        , Map.Count() > 1 ? "s" : string.Empty
                                                    );
            throw new InvalidOperationException(msg);
        }
    }
}


text:
package com.berge.drawer.lisener;

import com.berge.drawer.model.MaterialAccount;

/**
 * Listener account created yours drawables
 * Created by Adrià Bergé on 18/01/2015.
 */
public interface OnAccountDataLoaded {

    /**
     * finish load photo
     * @param account
     */
    public void onUserPhotoLoaded(MaterialAccount account);

    /**
     * finish load background
     * @param account
     */
    public void onBackgroundLoaded(MaterialAccount account);
}