text:
name              "tile"
maintainer        "OpenStreetMap Administrators"
maintainer_email  "admins@openstreetmap.org"
license           "Apache-2.0"
description       "Installs and configures tile servers"

version           "1.0.0"
supports          "ubuntu"
depends           "apache"
depends           "git"
depends           "munin"
depends           "nodejs"
depends           "postgresql"
depends           "python"
depends           "systemd"
depends           "tools"


text:
package com.flextrade.jfixture.customisation;

import com.flextrade.jfixture.NoSpecimen;
import com.flextrade.jfixture.SpecimenSupplier;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.ArrayList;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

public class TestCustomBuilder {

    private CustomBuilder builder;

    @Mock
    private SpecimenSupplier<ArrayList> mockSpecimenBuilder;

    @Before
    public void initialise() {
        MockitoAnnotations.initMocks(this);
        this.builder = new CustomBuilder<ArrayList>(ArrayList.class, this.mockSpecimenBuilder);
    }

    @Test
    public void exact_class_type_invokes_builder() {
        this.builder.create(ArrayList.class, null);
        verify(this.mockSpecimenBuilder).create();
    }

    @Test
    public void different_class_type_returns_no_specimen() {
        Object result = this.builder.create(String.class, null);
        assertEquals(new NoSpecimen(), result);
    }

    @Test
    public void different_class_type_does_not_invoke_builder() {
        this.builder.create(String.class, null);
        verify(this.mockSpecimenBuilder, never()).create();
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
*function getElementByClassName(node,classname){}
*node: the search start point of DOM
*className: the classname of elements you want to get
*return:array();
*/

function getElementByClassName(node,classname){
    if(node.getElementByClassName){
        return getElementByClassName(classname);
    } else {
        var result = [];
        var elems = node.getElementsByTagName("*");
        for(var i=0; i<elems.length;i++){
            if(eles[i].className.indexOf(classname)!=-1){
                result[result.length] = elems[i];
            }
        }
        return result;
    }

}


text:
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

Menu

<?php
if (!defined('DS')) define('DS','/');
$dir = ROOT_PATH  . 'pages' . DS;
$dirUrl = ROOT_PATH . 'pages' . DS;
$imgdir = ROOT_PATH . 'images' . DS;

function webfile($filename) {
    // returns true if given file is html or php
    $webfiles = array("htm", "html", "php");
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    return(in_array($ext, $webfiles));
}

// Open pages directory, and use the files there to create navigation menu.
// Filenames should start with a sort-order character followed by hyphen,
// followed by the menu text. For example, "A-Contact_us.html".
if (is_dir($dir)) {
    $files = array_filter(scandir($dir),"webfile");  // interesting files only
    // Put "Home" first
    echo '
';
    echo (isset($SELECTED) ? '<a ' : "Home
';
        'href="'.ROOT_PATH .'index.php">Home
';
    // Now iterate over files in pages directory for other menu items
    foreach ($files as $file) {
        echo '
';
        if (isset($SELECTED) && $SELECTED == $file) {
            echo "<a class='selected' ";
        }
        else {
            echo " ". $item ."
";
    }
}
?>


text:
<?php

namespace Qafoo\ChangeTrack\FISCalculator;

use Qafoo\ChangeTrack\Analyzer\ResultBuilder;

class ClassTransactionDatabaseFactoryTest extends \PHPUnit_Framework_TestCase
{
    public function testCreateDatabase()
    {
        $resultBuilder = new ResultBuilder('irrelevant-repository');

        $resultBuilder->revisionChanges('1')
            ->packageChanges('A')
            ->classChanges('Foo')
            ->methodChanges('bar')
            ->lineAdded();
        $resultBuilder->revisionChanges('2')
            ->packageChanges('A')
            ->classChanges('Foo')
            ->methodChanges('baz')
            ->lineAdded();
        $resultBuilder->revisionChanges('2')
            ->packageChanges('A')
            ->classChanges('Bam')
            ->methodChanges('bambam')
            ->lineAdded();

        $result = $resultBuilder->buildResult();

        $databaseFactory = new ClassTransactionDatabaseFactory();
        $database = $databaseFactory->createDatabase($result);

        $this->assertEquals(
            array(
                new ClassItem('A', 'Foo'),
                new ClassItem('A', 'Bam'),
            ),
            $database->getItems()
        );
    }
}


text:
Title: Links / 2015-03-25
Date: 2015-03-25 00:00
Tags: dashboard, mongodb, hbase, data mining, books, docker, consul, containers, chef, jenkins, stash

- [TLS Prober](http://n0where.net/identifying-tls-implementation/) is a tool for identifying the implementation in use by SSL/TLS servers. It analyses the behaviour of a server by sending a range of probes then comparing the responses with a database of known signatures.
- [Does Your Dashboard Suck?](http://daily.captaindash.com/does-your-dashboard-suck/)
- [A quick guide to MongoDB to work with](http://www.phloxblog.in/quick-guide-mongodb-work/)
- [Hbase Training](https://intellipaat.com/hbase-training/)
- [How to get started with Hadoop?](https://intellipaat.com/blog/how-to-start-hadoop/)
- [27 free data mining books](http://www.analyticbridge.com/forum/topics/27-free-data-mining-books?groupUrl=books)
- [Go undercover with the ElasticBox agent](https://elasticbox.com/blog/improved-elasticbox-agent/)
- [Security Best Practices: Building Docker Images](http://linux-audit.com/security-best-practices-for-building-docker-images/)
- [Consul: the end of CNAMEs and PuppetDB?](http://blog.bennycornelissen.nl/consul-the-end-of-the-cname/)
- [A High Available Docker Container Platform Using CoreOS And Consul](http://blog.xebia.com/2015/03/24/a-high-available-docker-container-platform-using-coreos-and-consul/)
- [Chef best practices](http://devops.com/blogs/chef-best-practices/)
- [Stash pullrequest builder plugin for Jenkins](https://wiki.jenkins-ci.org/display/JENKINS/Stash+pullrequest+builder+plugin)


text:
/*************************************************************************/
/*  bounds.cpp                                                           */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "bounds.h"

void Bounds::_bind_methods() {

	ClassDB::bind_method(D_METHOD("set_bsp_tree", "bsp_tree"), &Bounds::set_bsp_tree);
	ClassDB::bind_method(D_METHOD("get_bsp_tree"), &Bounds::get_bsp_tree);

	ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "bsp_tree"), "set_bsp_tree", "get_bsp_tree");
}

void Bounds::set_bsp_tree(const BSP_Tree &p_bsp_tree) {

	bsp_tree = p_bsp_tree;
}

BSP_Tree Bounds::get_bsp_tree() const {

	return bsp_tree;
}

Bounds::Bounds() {
}


text:
extern crate serde_derive;

extern crate reqwest;
extern crate url;

pub use language::Language;
pub use concept::Concept;
pub use category::Category;

pub mod language;
pub mod concept;
pub mod category;

static BASE_API_URL: &'static str = "http://syntaxdb.com/api/v1";

pub struct SyntaxDbClient {
    client: reqwest::Client,
}

impl SyntaxDbClient {
    pub fn new() -> SyntaxDbClient {
        SyntaxDbClient { client: reqwest::Client::new().unwrap() }
    }

    /// The Languages endpoint returns all languages available on SyntaxCenter, sorted by position
    /// by default.
    pub fn get_languages(&self,
                         fields: Option<Vec<&str>>,
                         limit: Option<i32>,
                         sort: Option<&str>)
                         -> Result<Vec<Language>, reqwest::Error> {
        let url_base = format!("{}/languages", BASE_API_URL);
        let mut url = url::Url::parse(&url_base).unwrap();

        if let Some(f) = fields {
            url.query_pairs_mut().append_pair("query", &f.join(","));
        };

        if let Some(l) = limit {
            url.query_pairs_mut().append_pair("limit", &l.to_string());

        };

        if let Some(s) = sort {
            url.query_pairs_mut().append_pair("sort", &s);
        };

        self.client.get(url.as_str()).send()?.json()
    }

    /// Returns the language corresponding to the permalink along with its information.
    pub fn get_language_by_permalink<'a>(&self,
                                         language_permalink: &'a str,
                                         fields: Option<Vec<&str>>)
                                         -> Result<Language, reqwest::Error> {
        let url_base = format!("{}/languages/{}", BASE_API_URL, language_permalink);
        let mut url = url::Url::parse(&url_base).unwrap();
        if let Some(f) = fields {
            url.query_pairs_mut().append_pair("fields", &f.join(","));
        };

        self.client.get(url.as_str()).send()?.json()
    }

    /// The language categories endpoint returns all of the categories corresponding to the
    /// language.
    pub fn get_language_categories<'a>(&self,
                                       language_permalink: &'a str,
                                       fields: Option<Vec<&str>>,
                                       limit: Option<i32>,
                                       sort: Option<&str>)
                                       -> Result<Vec<Category>, reqwest::Error> {
        let base_url = format!("{}/languages/{}/categories",
                               BASE_API_URL,
                               language_permalink);
        let mut url = url::Url::parse(&base_url).unwrap();
        if let Some(f) = fields {
            url.query_pairs_mut().append_pair("fields", &f.join(","));
        };

        if let Some(l) = limit {
            url.query_pairs_mut().append_pair("limit", &l.to_string());
        };

        if let Some(s) = sort {
            url.query_pairs_mut().append_pair("sort", &s);
        };

        self.client.get(url.as_str()).send()?.json()
    }

    /// The category concepts endpoint returns all concepts belonging to the category, sorted by
    /// position by default.
    pub fn get_language_category_concepts<'a>(&self,
                                              language_permalink: &'a str,
                                              category_id: i32,
                                              fields: Option<Vec<&str>>,
                                              limit: Option<i32>,
                                              sort: Option<&str>)
                                              -> Result<Vec<Concept>, reqwest::Error> {
        let base_url = format!("{}/languages/{}/categories/{}/concepts",
                               BASE_API_URL,
                               language_permalink,
                               category_id);
        let mut url = url::Url::parse(&base_url).unwrap();
        if let Some(f) = fields {
            url.query_pairs_mut().append_pair("fields", &f.join(","));
        };

        if let Some(l) = limit {
            url.query_pairs_mut().append_pair("limit", &l.to_string());
        };

        if let Some(s) = sort {
            url.query_pairs_mut().append_pair("sort", &s);
        };

        self.client.get(url.as_str()).send()?.json()
    }

    /// The language concepts endpoint returns all concepts belonging to the language, sorted by
    /// position by default.
    pub fn get_language_concepts<'a>(&self,
                                     language_permalink: &'a str,
                                     fields: Option<Vec<&str>>,
                                     limit: Option<i32>,
                                     sort: Option<&str>)
                                     -> Result<Vec<Concept>, reqwest::Error> {
        let base_url = format!("{}/languages/{}/concepts", BASE_API_URL, language_permalink);
        let mut url = url::Url::parse(&base_url).unwrap();
        if let Some(f) = fields {
            url.query_pairs_mut().append_pair("fields", &f.join(","));
        };

        if let Some(l) = limit {
            url.query_pairs_mut().append_pair("limit", &l.to_string());
        };

        if let Some(s) = sort {
            url.query_pairs_mut().append_pair("sort", &s);
        };

        self.client.get(url.as_str()).send()?.json()
    }

    /// This search language concepts endpoint returns all concepts within the specified language
    /// that matches the query.
    pub fn search_language_concepts<'a>(&self,
                                        language_permalink: &'a str,
                                        search: &'a str,
                                        fields: Option<Vec<&str>>,
                                        limit: Option<i32>)
                                        -> Result<Vec<Concept>, reqwest::Error> {
        let base_url = format!("{}/languages/{}/concepts/search",
                               BASE_API_URL,
                               language_permalink);
        let mut url = url::Url::parse_with_params(&base_url, &[("q", search)]).unwrap();
        if let Some(f) = fields {
            url.query_pairs_mut().append_pair("fields", &f.join(","));
        };

        if let Some(l) = limit {
            url.query_pairs_mut().append_pair("limit", &l.to_string());
        };

        self.client.get(url.as_str()).send()?.json()

    }

    /// The Concepts endpoint returns an array of concepts contained in SyntaxCenter. By default,
    /// the array is limited to 20 concepts, sorted by ID in ascending order.
    pub fn get_concepts(&self,
                        fields: Option<Vec<&str>>,
                        limit: Option<i32>,
                        sort: Option<&str>)
                        -> Result<Vec<Concept>, reqwest::Error> {
        let base_url = format!("{}/concepts", BASE_API_URL);
        let mut url = url::Url::parse(&base_url).unwrap();
        if let Some(f) = fields {
            url.query_pairs_mut().append_pair("fields", &f.join(","));
        };

        if let Some(l) = limit {
            url.query_pairs_mut().append_pair("limit", &l.to_string());
        };

        if let Some(s) = sort {
            url.query_pairs_mut().append_pair("sort", &s);
        };

        self.client.get(url.as_str()).send()?.json()
    }

    /// Full text search for matching concepts across the entire database.
    pub fn search_concepts<'a>(&self,
                               search: &'a str,
                               fields: Option<Vec<&str>>,
                               limit: Option<i32>)
                               -> Result<Vec<Concept>, reqwest::Error> {
        let base_url = format!("{}/concepts/search", BASE_API_URL);
        let mut url = url::Url::parse_with_params(&base_url, &[("q", search)]).unwrap();
        if let Some(f) = fields {
            url.query_pairs_mut().append_pair("fields", &f.join(","));
        };

        if let Some(l) = limit {
            url.query_pairs_mut().append_pair("limit", &l.to_string());
        };

        self.client.get(url.as_str()).send()?.json()
    }

    /// Returns the concept corresponding to the unique identifier.
    pub fn get_concept_by_id(&self,
                             concept_id: i32,
                             fields: Option<Vec<&str>>)
                             -> Result<Concept, reqwest::Error> {
        let base_url = format!("{}/concepts/{}", BASE_API_URL, concept_id);
        let mut url = url::Url::parse(&base_url).unwrap();
        if let Some(f) = fields {
            url.query_pairs_mut().append_pair("fields", &f.join(","));
        }
        self.client.get(url.as_str()).send()?.json()
    }

    /// The language concepts endpoint returns all concepts belonging to the language, sorted by
    /// position by default.
    pub fn get_language_concepts_by_concept_id(&self,
                                               language_permalink: &str,
                                               concept_permalink: &str,
                                               fields: Option<Vec<&str>>)
                                               -> Result<Concept, reqwest::Error> {
        let base_url = format!("{}/languages/{}/concepts/{}",
                               BASE_API_URL,
                               language_permalink,
                               concept_permalink);
        let url = match fields {
            Some(f) => url::Url::parse_with_params(&base_url, &[("fileds", &f.join(","))]),
            None => url::Url::parse(&base_url),
        };
        self.client.get(url.unwrap().as_str()).send()?.json()
    }
}

#[cfg(test)]
mod tests {
    use super::SyntaxDbClient;
    #[test]
    fn get_languages() {
        let client = SyntaxDbClient::new();
        let languages = client
            .get_languages(Some(vec!["id", "language_name"]),
                           None,
                           Some("language_name"))
            .unwrap();
        if let Some(ref ln) = languages[0].language_name {
            assert_eq!(ln, "C");
        }
    }

    #[test]
    fn get_language_by_permalink() {
        let client = SyntaxDbClient::new();
        let languages = client
            .get_languages(None, Some(1), Some("language_name"))
            .unwrap();
        if let Some(ref lp) = languages[0].language_permalink {
            let language = client.get_language_by_permalink(lp, None).unwrap();
            assert_eq!(language.id.unwrap(), 2);
        }
    }

    #[test]
    fn get_language_categories() {
        let client = SyntaxDbClient::new();
        let categories = client
            .get_language_categories("java", None, None, None)
            .unwrap();
        if let Some(ref cn) = categories[1].category_name {
            assert_eq!(cn, "Variables");
        }
    }

    #[test]
    fn get_language_category_concepts() {

        let client = SyntaxDbClient::new();
        let concepts = client
            .get_language_category_concepts("java", 2, None, None, None)
            .unwrap();
        if let Some(ref cn) = concepts[0].concept_name {
            assert_eq!(cn, "Primitive Data Types");
        }
    }

    #[test]
    fn get_language_concepts() {
        let client = SyntaxDbClient::new();
        let concepts = client
            .get_language_concepts("java", None, None, None)
            .unwrap();
        if let Some(ref cn) = concepts[0].concept_name {
            assert_eq!(cn, "Print");
        }
    }

    #[test]
    fn search_language_concepts() {
        let client = SyntaxDbClient::new();
        let concepts = client
            .search_language_concepts("java", "map", None, None)
            .unwrap();
        if let Some(ref cn) = concepts[0].concept_name {
            assert_eq!(cn, "HashMaps");
        }
    }

    #[test]
    fn get_concepts() {
        let client = SyntaxDbClient::new();
        let concepts = client.get_concepts(None, None, None).unwrap();
        if let Some(ref cn) = concepts[0].concept_name {
            assert_eq!(cn, "Print");
        }
    }

    #[test]
    fn search_concepts() {
        let client = SyntaxDbClient::new();
        let concepts = client.search_concepts("variable", None, None).unwrap();
        if let Some(ref cn) = concepts[0].concept_name {
            assert_eq!(cn, "Variable Declaration");
        }
    }

    #[test]
    fn get_concept_by_id() {
        let client = SyntaxDbClient::new();
        let concept = client.get_concept_by_id(12, None).unwrap();
        if let Some(ref cn) = concept.concept_name {
            assert_eq!(cn, "While Loop");
        }
    }

    #[test]
    fn get_language_concepts_by_concept_id() {
        let client = SyntaxDbClient::new();
        let concept = client
            .get_language_concepts_by_concept_id("java", "print", None)
            .unwrap();
        if let Some(ref cn) = concept.concept_name {
            assert_eq!(cn, "Print");
        }
    }
}


text:
cant = int(raw_input("Cuantos valores ingresara? "))

#Algunas variables que usaremos
maximo = -float('inf')
minimo = float('inf')

#Ahora pedimos todos los valores:
for i in range(cant):
	valor = float(raw_input("Valor "+str(i+1)+": "))
	if valor > maximo: maximo = valor
	if valor < minimo: minimo = valor

print "El rango es "+str(maximo - minimo)


text:
#import <UIKit/UIKit.h>

#import <AsyncDisplayKit/ASRangeController.h>
#import <AsyncDisplayKit/ASCollectionViewProtocols.h>

@class ASCellNode;
@protocol ASCollectionViewDataSource;
@protocol ASCollectionViewDelegate;

/**
 * Node-based collection view.
 *
 * ASCollectionView is a version of UICollectionView that uses nodes -- specifically, ASCellNode subclasses -- with asynchronous
 * pre-rendering instead of synchronously loading UICollectionViewCells.
 */
@interface ASCollectionView : UICollectionView

@property (nonatomic, weak) id<ASCollectionViewDataSource> asyncDataSource;
@property (nonatomic, weak) id<ASCollectionViewDelegate> asyncDelegate;

/**
 * Tuning parameters for the working range.
 *
 * Defaults to a trailing buffer of one screenful and a leading buffer of two screenfuls.
 */
@property (nonatomic, assign) ASRangeTuningParameters rangeTuningParameters;

/**
 * Reload everything from scratch, destroying the working range and all cached nodes.
 *
 * @warning This method is substantially more expensive than UICollectionView's version.
 */
- (void)reloadData;

/**
 * Section updating.
 *
 * All operations are asynchronous and thread safe. You can call it from background thread (it is recommendated) and the UI table
 * view will be updated asynchronously. The asyncDataSource must be updated to reflect the changes before these methods are called.
 */
- (void)insertSections:(NSIndexSet *)sections;
- (void)deleteSections:(NSIndexSet *)sections;
- (void)reloadSections:(NSIndexSet *)sections;
- (void)moveSection:(NSInteger)section toSection:(NSInteger)newSection;

/**
 * Items updating.
 *
 * All operations are asynchronous and thread safe. You can call it from background thread (it is recommendated) and the UI table
 * view will be updated asynchronously. The asyncDataSource must be updated to reflect the changes before these methods are called.
 */
- (void)insertItemsAtIndexPaths:(NSArray *)indexPaths;
- (void)deleteItemsAtIndexPaths:(NSArray *)indexPaths;
- (void)reloadItemsAtIndexPaths:(NSArray *)indexPaths;
- (void)moveItemAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath;

/**
 * Query the sized node at `indexPath` for its calculatedSize.
 *
 * @param indexPath The index path for the node of interest.
 */
- (CGSize)calculatedSizeForNodeAtIndexPath:(NSIndexPath *)indexPath;

@end

/**
 * This is a node-based UICollectionViewDataSource.
 */
@protocol ASCollectionViewDataSource <ASCommonCollectionViewDataSource, NSObject>

/**
 * Similar to -collectionView:cellForItemAtIndexPath:.
 *
 * @param collection The sender.
 *
 * @param indexPath The index path of the requested node.
 *
 * @returns a node for display at this indexpath.  Must be thread-safe (can be called on the main thread or a background
 * queue) and should not implement reuse (it will be called once per row).  Unlike UICollectionView's version, this method
 * is not called when the row is about to display.
 */
- (ASCellNode *)collectionView:(ASCollectionView *)collectionView nodeForItemAtIndexPath:(NSIndexPath *)indexPath;

@end

/**
 * This is a node-based UICollectionViewDelegate.
 */
@protocol ASCollectionViewDelegate <ASCommonCollectionViewDelegate, NSObject>

@optional

- (void)collectionView:(UICollectionView *)collectionView willDisplayNodeForItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingNodeForItemAtIndexPath:(NSIndexPath*)indexPath;

@end


text:
package application.core.repository.rn;

import application.core.model.rn.RNProduct;
import application.core.repository.CWMDRepository;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public interface RNProductRepository extends CWMDRepository<Integer, RNProduct> {
}


text:
import NavigoRouter from "../../index";
import Navigo from "../index";

describe("Given the Navigo library", () => {
  beforeEach(() => {
    history.pushState({}, "", "/");
  });
  describe("when destroying the router", () => {
    it("should empty the routes array and remove the listener to popstate", () => {
      const remove = jest.spyOn(window, "removeEventListener");
      const r: NavigoRouter = new Navigo("/");
      r.on("foo", () => {});

      r.destroy();

      expect(r.routes).toHaveLength(0);
      expect(remove).toBeCalledWith("popstate", expect.any(Function));
      expect(r.destroyed).toEqual(true);
    });
  });
});


text:
*Each day contains:*

* a README with instructions to following if you're performing the walkthrough on your own.
* a PDF of the slides used during the presentation.
* presenter notes for whoever may choose to give the presentation.

* The first few days will be discussion about core concepts followed by how to start setting up our FakeFlix Movie app. As the days progress, application code and concepts will start blending together and we can more quickly build up our application.


text:
The `dist` folder contains sample configs for various platforms.

## Assumptions

The examples assume you will either be using replicators default settings or that you will be writing your configuration file(s) within `/etc/replicator.d` on the filesystem.

## Upstart

On systems using [upstart](http://upstart.ubuntu.com/), the [upstart configuration file](https://github.com/elsevier-core-engineering/replicator/blob/master/dist/upstart/replicator.conf) can be used to control the replicator binary. It should be placed under `/etc/init/replicator.conf`. This will then allow you to control the daemon through `start|stop|restart` commands.

## Systemd

On systems using [systemd](https://www.freedesktop.org/wiki/Software/systemd/), the [basic systemd unit file](https://github.com/elsevier-core-engineering/replicator/blob/master/dist/systemd/replicator.service) can be usd to control the replicator daemon and should be placed under `/etc/systemd/system/replicator.service`. This then allows you to control the daemon through `start|stop|restart` commands.


text:
package io.cattle.platform.servicediscovery.api.resource;

import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.model.Service;
import io.cattle.platform.docker.constants.DockerInstanceConstants;
import io.cattle.platform.servicediscovery.api.constants.ServiceDiscoveryConstants;
import io.cattle.platform.util.type.NamedUtils;

import java.util.ArrayList;
import java.util.List;

public class ServiceDiscoveryConfigItem {
    /**
     *
     * Unsupported docker compose variables
     * - build
     * - env_file
     * - net - might add support for that before the feature goes out
     * - environment - don't support the case when only key is specified, but no value - can't extract local machine
     * info here
     *
     */
    // COMPOSE PARAMETERS
    private static List<ServiceDiscoveryConfigItem> supportedServiceConfigItems = new ArrayList<>();
    public static final ServiceDiscoveryConfigItem IMAGE = new ServiceDiscoveryConfigItem(InstanceConstants.FIELD_IMAGE_UUID, "image");
    public static final ServiceDiscoveryConfigItem COMMAND = new ServiceDiscoveryConfigItem("command", "command");
    public static final ServiceDiscoveryConfigItem PORTS = new ServiceDiscoveryConfigItem("ports", "ports");
    public static final ServiceDiscoveryConfigItem VOLUMES = new ServiceDiscoveryConfigItem("dataVolumes", "volumes");
    public static final ServiceDiscoveryConfigItem VOLUMESFROM = new ServiceDiscoveryConfigItem("dataVolumesFrom",
            "volumes_from");
    public static final ServiceDiscoveryConfigItem ENVIRONMENT = new ServiceDiscoveryConfigItem("environment", "environment");
    public static final ServiceDiscoveryConfigItem DNS = new ServiceDiscoveryConfigItem("dns", "dns");
    public static final ServiceDiscoveryConfigItem CAPADD = new ServiceDiscoveryConfigItem("capAdd", "cap_add");
    public static final ServiceDiscoveryConfigItem CAPDROP = new ServiceDiscoveryConfigItem("capDrop", "cap_drop");
    public static final ServiceDiscoveryConfigItem DNSSEARCH = new ServiceDiscoveryConfigItem("dnsSearch", "dns_search");
    public static final ServiceDiscoveryConfigItem WORKINGDIR = new ServiceDiscoveryConfigItem("workingDir", "working_dir");
    public static final ServiceDiscoveryConfigItem ENTRYPOINT = new ServiceDiscoveryConfigItem("entryPoint", "entrypoint");
    public static final ServiceDiscoveryConfigItem USER = new ServiceDiscoveryConfigItem("user", "user");
    public static final ServiceDiscoveryConfigItem HOSTNAME = new ServiceDiscoveryConfigItem("hostname", "hostname");
    public static final ServiceDiscoveryConfigItem DOMAINNAME = new ServiceDiscoveryConfigItem("domainName", "domainname");
    public static final ServiceDiscoveryConfigItem MEMLIMIT = new ServiceDiscoveryConfigItem("memory", "mem_limit");
    public static final ServiceDiscoveryConfigItem PRIVILEGED = new ServiceDiscoveryConfigItem("privileged", "privileged");
    public static final ServiceDiscoveryConfigItem RESTART = new ServiceDiscoveryConfigItem("restartPolicy", "restart");
    public static final ServiceDiscoveryConfigItem STDINOPEN = new ServiceDiscoveryConfigItem("stdinOpen", "stdin_open");
    public static final ServiceDiscoveryConfigItem TTY = new ServiceDiscoveryConfigItem("tty", "tty");
    public static final ServiceDiscoveryConfigItem CPUSHARES = new ServiceDiscoveryConfigItem("cpuShares", "cpu_shares");
    public static final ServiceDiscoveryConfigItem VOLUME_DRIVER = new ServiceDiscoveryConfigItem("volumeDriver", "volume_driver");
    public static final ServiceDiscoveryConfigItem EXPOSE = new ServiceDiscoveryConfigItem("expose", "expose");
    public static final ServiceDiscoveryConfigItem EXTERNALLINKS = new ServiceDiscoveryConfigItem("instanceLinks",
            "external_links");
    public static final ServiceDiscoveryConfigItem LINKS = new ServiceDiscoveryConfigItem(null,
            "links", false, true);
    public static final ServiceDiscoveryConfigItem NETWORKMODE = new ServiceDiscoveryConfigItem(
            DockerInstanceConstants.FIELD_NETWORK_MODE,
            "net");
    public static final ServiceDiscoveryConfigItem CPUSET = new ServiceDiscoveryConfigItem("cpuSet", "cpuset");

    public static final ServiceDiscoveryConfigItem LABELS = new ServiceDiscoveryConfigItem(
            InstanceConstants.FIELD_LABELS, InstanceConstants.FIELD_LABELS);

    // CATTLE PARAMETERS
    public static final ServiceDiscoveryConfigItem SCALE = new ServiceDiscoveryConfigItem("scale", "scale",
            false, false);
    public static final ServiceDiscoveryConfigItem HEALTHCHECK = new ServiceDiscoveryConfigItem(
            InstanceConstants.FIELD_HEALTH_CHECK,
            NamedUtils.toUnderscoreSeparated(InstanceConstants.FIELD_HEALTH_CHECK),
            true, false);

    public static final ServiceDiscoveryConfigItem LB_CONGFIG = new ServiceDiscoveryConfigItem(
            ServiceDiscoveryConstants.FIELD_LOAD_BALANCER_CONFIG,
            NamedUtils.toUnderscoreSeparated(ServiceDiscoveryConstants.FIELD_LOAD_BALANCER_CONFIG),
            false, false);

    public static final ServiceDiscoveryConfigItem EXTERNAL_IPS = new ServiceDiscoveryConfigItem(
            ServiceDiscoveryConstants.FIELD_EXTERNALIPS,
            "external_ips", false, false);

    /**
     * Name as it appears in docker-compose file
     */
    private String dockerName;

    /**
     * Name as it appears in cattle (can be diff from what defined in a config)
     */
    private String cattleName;

    /**
     * Defines whether the property is the launch config property
     */
    private boolean isLaunchConfigItem;

    private boolean isDockerComposeProperty;

    public ServiceDiscoveryConfigItem(String cattleName, String dockerName, boolean isLaunchConfigItem,
            boolean isDockerComposeProperty) {
        super();
        this.cattleName = cattleName;
        this.dockerName = dockerName;
        this.isLaunchConfigItem = isLaunchConfigItem;
        this.isDockerComposeProperty = isDockerComposeProperty;
        supportedServiceConfigItems.add(this);
    }

    public ServiceDiscoveryConfigItem() {
    }

    public ServiceDiscoveryConfigItem(String cattleName, String dockerName) {
        this(cattleName, dockerName, true, true);
    }

    public static List<ServiceDiscoveryConfigItem> getSupportedLaunchConfigItems() {
        return supportedServiceConfigItems;
    }

    public String getDockerName() {
        return dockerName;
    }

    public boolean isLaunchConfigItem() {
        return isLaunchConfigItem;
    }

    public String getCattleName() {
        return cattleName;
    }

    public boolean isDockerComposeProperty() {
        return isDockerComposeProperty;
    }

    public static ServiceDiscoveryConfigItem getServiceConfigItemByDockerName(String externalName) {
        for (ServiceDiscoveryConfigItem serviceItem : supportedServiceConfigItems) {
            if (serviceItem.getDockerName().equalsIgnoreCase(externalName)) {
                return serviceItem;
            }
        }
        return null;
    }

    public static ServiceDiscoveryConfigItem getServiceConfigItemByCattleName(String internalName, Service service) {
        for (ServiceDiscoveryConfigItem serviceItem : supportedServiceConfigItems) {
            if (serviceItem.getCattleName() != null && serviceItem.getCattleName().equalsIgnoreCase(internalName)) {
                // special handling for external service hostname
                if (service.getKind().equalsIgnoreCase(ServiceDiscoveryConstants.KIND.EXTERNALSERVICE.name())
                        && serviceItem.getCattleName().equalsIgnoreCase(HOSTNAME.cattleName)) {
                    return new ServiceDiscoveryConfigItem(serviceItem.getCattleName(), serviceItem.getDockerName(),
                            false, false);
                }
                return serviceItem;
            }
        }
        return null;
    }

}


text:
<?php

namespace ETNA\FeatureContext;

use Silex;

trait SilexApplication
{
    static private $silex_app;

    /**
     * @BeforeScenario
     */
    static public function setupSilexApplication()
    {
        self::$silex_app = new Silex\Application();

        self::$silex_app["auth.force_guest"]         = true;
        self::$silex_app["auth.cookie_expiration"]   = false;
        self::$silex_app["auth.public_key.tmp_path"] = realpath(__DIR__ . "/../../../tmp/") . "/public-local.testing.key";
        self::$silex_app["auth.authenticator_url"]   = "file://" . __DIR__ . "/../../../tmp/keys/";
        self::$silex_app["auth.cookie_expiration"]   = "+10minutes";

        self::$silex_app->register(new \ETNA\Silex\Provider\Auth\AuthServiceProvider());

        $GLOBALS["app"] = self::$silex_app;
    }
}


text:
<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta
            http-equiv="refresh"
            content="0;
                       url=docs/installation.html"
            />

        <title>Your Site Title Here</title>

        If you are not redirected automatically, follow this
        link.


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

"use strict";

var CAM = {};

/**
 * The core process engine.
 * @author Daniel Meyer
 */
(function(CAM) {

  var ExecutionException = (function () {

    function ExecutionException(message, activityExecution) {
      this.message = message;
      this.activityExecution = activityExecution;
      throw message;
    }

    return ExecutionException;
  })();

  /**
   * the activity types to be used by the process engine.
   * An activity type realizes the process language specific
   * behavior of an activity.
   *
   */
  var activityTypes = { };

  var LISTENER_START = "start";
  var LISTENER_END = "end";
  var LISTENER_TAKE = "take";

  // static utility functions ////////////////////////////////////

  var getActivitiesByType = function(activityDefinition, type, recursive) {
    var baseElements = [];
    for (var i = 0; i < activityDefinition.baseElements.length; i++) {
      var childActivity = activityDefinition.baseElements[i];
      if(!!childActivity.type && childActivity.type == type){
        baseElements.push(childActivity);
        if(recursive) {
          baseElements = baseElements.concat(getActivitiesByType(childActivity, type, recursive));
        }
      }
    }
    return baseElements;
  };

  var getActivityById = function(activityDefinition, id) {
    for (var i = 0; i < activityDefinition.baseElements.length; i++) {
      var chidActivity = activityDefinition.baseElements[i];
      if(!!chidActivity.id && chidActivity.id == id){
        return chidActivity;
      }
    }
    return null;
  };

  var getActivityType = function(activityDefinition) {
    var type = activityDefinition.type;
    if(!!type) {
      return activityTypes[type];
    } else {
      return null;
    }
  };

  var getSequenceFlows = function(activityDefinition, scopeActivity) {
    var result = [];
    if(!!activityDefinition.outgoing) {
      var outgoingSequenceFlowIds = activityDefinition.outgoing;

      for (var i = 0; i < outgoingSequenceFlowIds.length; i++) {
        var sequenceFlowId = outgoingSequenceFlowIds[i];
        result.push(getActivityById(scopeActivity, sequenceFlowId));
      }
    }

    return result;
  };

  ///////////////////////////////////////////////////////////////

  var ActivityExecution = (function () {

    // constructor
    function ActivityExecution(activityDefinition, parentExecution) {

      if(!activityDefinition) {
        throw new ExecutionException("Activity definition cannot be null", this);
      }

      this.activityDefinition = activityDefinition;
      // a list of child activity executions
      this.activityExecutions = [];
      // indicates whether the execution has been ended
      this.isEnded = false;
      // the parent execution
      this.parentExecution = parentExecution;
      // the variables of this execution
      this.variables = {};

      this.startDate = null;
      this.endDate = null;
    }

    ActivityExecution.prototype.bindVariableScope = function(scope) {
      if(!!this.parentExecution) {
        this.parentExecution.bindVariableScope(scope);
      }
      var variables = this.variables;
      for(var varName in variables) {
        scope[varName] = variables[varName];
      }
    }

    ActivityExecution.prototype.executeActivities = function(activities) {
      for (var i = 0; i < activities.length; i++) {
        this.executeActivity(activities[i]);
      };
    };

    ActivityExecution.prototype.executeActivity = function(activity, sequenceFlow) {
      var childExecutor = new ActivityExecution(activity, this);
      this.activityExecutions.push(childExecutor);
       if(!!sequenceFlow) {
        childExecutor.incomingSequenceFlowId = sequenceFlow.id;
      }
      childExecutor.start();
    };

    ActivityExecution.prototype.invokeListeners = function(type, sequenceFlow) {
      var listeners = this.activityDefinition.listeners;
      if(!!listeners) {
        for(var i = 0; i < listeners.length; i++) {
          var listener = listeners[i];
          if(!!listener[type]) {
            listener[type](this, sequenceFlow);
          }
        }
      }
    };

    ActivityExecution.prototype.start = function() {
      this.startDate = new Date();

      // invoke listeners on activity start
      this.invokeListeners(LISTENER_START);

      // if the activity is async, we do not execute it right away
      // but simpley return. Execution can be continued using the
      // continue() function
      if(!!this.activityDefinition.asyncCallback) {
        this.activityDefinition.asyncCallback(this);
      } else {
        this.continue();
      }
    };

    ActivityExecution.prototype.continue = function() {

      // execute activity type
      var activityType = getActivityType(this.activityDefinition);
      activityType.execute(this);
    };

    ActivityExecution.prototype.end = function(notifyParent) {
      this.isEnded = true;
      this.endDate = new Date();

      // invoke listeners on activity end
      this.invokeListeners(LISTENER_END);

      if(!!this.parentExecution) {
        // remove from parent
        var parent = this.parentExecution;
        // notify parent
        if(notifyParent) {
          parent.hasEnded(this);
        }
      }
    };

    ActivityExecution.prototype.takeAll = function(sequenceFlows) {
      for(var i = 0; i < sequenceFlows.length; i++) {
        this.take(sequenceFlows[i]);
      }
    };

    ActivityExecution.prototype.take = function(sequenceFlow) {
      var toId = sequenceFlow.targetRef;
      var toActivity = getActivityById(this.parentExecution.activityDefinition, toId);
      if(!toActivity) {
        throw new ExecutionException("cannot find activity with id '"+toId+"'");
      }
      // end this activity
      this.end(false);

      // invoke listeners on sequence flow take
      this.invokeListeners(LISTENER_TAKE, sequenceFlow);

      // have the parent execute the next activity
      this.parentExecution.executeActivity(toActivity, sequenceFlow);
    };

    ActivityExecution.prototype.signal = function(definitionId) {
      var signalFn = function (execution) {
        if(execution.isEnded) {
          throw new ExecutionException("cannot signal an ended activity instance", execution);
        }
        var type = getActivityType(execution.activityDefinition);
        if(!!type.signal) {
          type.signal(execution);
        } else {
          execution.end();
        }
      };

      if (definitionId) {
        for (var index in this.activityExecutions) {
          var execution = this.activityExecutions[index];
          if (execution.activityDefinition.id == definitionId) {
            signalFn(execution);
            break;
          }
        }
      }else {
        signalFn(this);
      }
    };

    /**
     * called by the child activity executors when they are ended
     */
    ActivityExecution.prototype.hasEnded = function(activityExecution) {
      var allEnded = true;
      for(var i; i < this.activityExecutions.length; i++) {
        allEnded &= this.activityExecutions[i].isEnded;
      }

      if(allEnded) {
        var activityType = getActivityType(this.activityDefinition);
        if(!!activityType.allActivitiesEnded) {
          activityType.allActivitiesEnded(this);
        } else {
          this.end();
        }
      }
    };

    /**
     * an activity instance is a java script object that holds the state of an
     * ActivityExecution. It can be regarded as the serialized representation
     * of an execution tree.
     */
    ActivityExecution.prototype.getActivityInstance = function() {
      var activityInstance = {
        "activityId" : this.activityDefinition.id,
        "isEnded" : this.isEnded,
        "startDate" : this.startDate,
        "endDate" : this.endDate,
      }
      if(this.activityExecutions.length > 0) {
        activityInstance["activities"] = [];
        for(var i = 0; i < this.activityExecutions.length; i++) {
          activityInstance.activities.push(this.activityExecutions[i].getActivityInstance());
        }
      }
      return activityInstance;
    };

    return ActivityExecution;
  })();

  // export public APIs
  CAM.ActivityExecution = ActivityExecution;
  CAM.ExecutionException = ExecutionException;
  CAM.activityTypes = activityTypes;
  CAM.getActivitiesByType = getActivitiesByType;
  CAM.getActivityById = getActivityById;
  CAM.getActivityType = getActivityType;
  CAM.getSequenceFlows = getSequenceFlows;

  CAM.LISTENER_START = LISTENER_START;
  CAM.LISTENER_END = LISTENER_END;
  CAM.LISTENER_TAKE = LISTENER_TAKE;

})(CAM);

/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

/**
 * The BPMN 2.0 activity type module.
 *
 * This module provides the BPMN 2.0 specific runtime behavior
 *
 * @author Daniel Meyer
 */
(function(CAM) {

  // variables & conditions //////////////////////////////////////////

  var VariableScope = (function () {

    function VariableScope(activityExecution) {
      activityExecution.bindVariableScope(this);
    };

    VariableScope.prototype.evaluateCondition = function(condition) {
      return eval(condition);
    };

    return VariableScope;
  })();

  function evaluateCondition(condition, activityExecution) {
    return new VariableScope(activityExecution).evaluateCondition(condition);
  }

  // the default outgoing behavior for BPMN 2.0 activities //////////

  function leave(activityExecution) {

    // SEPC p.427 §13.2.1
    // Multiple outgoing Sequence Flows behaves as a parallel split.
    // Multiple outgoing Sequence Flows with conditions behaves as an inclusive split.
    // A mix of multiple outgoing Sequence Flows with and without conditions is considered as a combination of a parallel and an inclusive split

    var sequenceFlowsToTake = [];
    var availableSequenceFlows = CAM.getSequenceFlows(activityExecution.activityDefinition,
                                                  activityExecution.parentExecution.activityDefinition);
    var defaultFlowId = activityExecution.activityDefinition.default;

    var defaultFlow = null;
    var noConditionalFlowActivated = true;

    for(var i =0; i<availableSequenceFlows.length; i++) {
      var sequenceFlow = availableSequenceFlows[i];

      if(!!defaultFlowId && defaultFlowId == sequenceFlow.id) {
        defaultFlow = sequenceFlow;

      } else if(!sequenceFlow.condition) {
        sequenceFlowsToTake.push(sequenceFlow);

      } else if(evaluateCondition(sequenceFlow.condition, activityExecution)) {
        sequenceFlowsToTake.push(sequenceFlow);
        noConditionalFlowActivated = false;
      }

    }

    // the default flow is only activated if all conditional flows are false
    if(noConditionalFlowActivated && !!defaultFlow) {
      sequenceFlowsToTake.push(defaultFlow);
    }

    activityExecution.takeAll(sequenceFlowsToTake);
  }

  // actual activity types //////////////////////////////////////////

  var process = {
    "execute" : function(activityExecution) {

      // find start events
      var startEvents = CAM.getActivitiesByType(activityExecution.activityDefinition, "startEvent");

      if(startEvents.length == 0) {
        throw "process must have at least one start event";
      }

      // activate all start events
      activityExecution.executeActivities(startEvents);
    }
  };

  var startEvent = {
    "execute" : function(activityExecution) {
      leave(activityExecution);
    }
  };

  var intermediateThrowEvent = {
    "execute" : function(activityExecution) {
      leave(activityExecution);
    }
  };

  var endEvent = {
    "execute" : function(activityExecution) {
      activityExecution.end(true);
    }
  };

  var task = {
    "execute" : function(activityExecution) {
      leave(activityExecution);
    }
  };

  var userTask = {
    "execute" : function(activityExecution) {
      // wait state
    },
    "signal" : function(activityExecution) {
      leave(activityExecution);
    }
  };

  var serviceTask = {
    "execute" : function(activityExecution) {
      leave(activityExecution);
    }
  };

  /**
   * implementation of the exclusive gateway
   */
  var exclusiveGateway = {
    "execute" : function(activityExecution) {
      var outgoingSequenceFlows = activityExecution.activityDefinition.sequenceFlows;

      var sequenceFlowToTake,
        defaultFlow;

      for(var i = 0; i<outgoingSequenceFlows.length; i++) {
        var sequenceFlow = outgoingSequenceFlows[i];
        if(!sequenceFlow.condition) {
          // we make sure at deploy time that there is only a single sequence flow without a condition
          defaultFlow = sequenceFlow;
        } else if(evaluateCondition(sequenceFlow.condition, activityExecution)) {
          sequenceFlowToTake = sequenceFlow;
          break;
        }
      }

      if(!sequenceFlowToTake) {
        if(!defaultFlow) {
          throw "Cannot determine outgoing sequence flow for exclusive gateway '"+activityExecution.activityDefinition+"': " +
            "All conditions evaluate to false and a default sequence flow has not been specified."
        } else {
          sequenceFlowToTake = defaultFlow;
        }
      }

      activityExecution.take(sequenceFlowToTake);
    }
  };

  /**
   * implementation of the parallel gateway
   */
  var parallelGateway = {
    "execute" : function(activityExecution) {
      var outgoingSequenceFlows = CAM.getSequenceFlows(activityExecution.activityDefinition,
                                                   activityExecution.parentExecution.activityDefinition);

      // join
      var executionsToJoin = [];
      var parent = activityExecution.parentExecution;
      for(var i=0; i<parent.activityExecutions.length; i++) {
        var sibling = parent.activityExecutions[i];
        if(sibling.activityDefinition == activityExecution.activityDefinition && !sibling.isEnded) {
          executionsToJoin.push(sibling);
        }
      }

      if(executionsToJoin.length == activityExecution.activityDefinition.cardinality) {
        // end all joined executions but this one,
        for(var i=0; i<executionsToJoin.length; i++) {
          var joinedExecution = executionsToJoin[i];
          if(joinedExecution != activityExecution) {
            joinedExecution.end(false);
          }
        }
        // continue with this execution
        activityExecution.takeAll(outgoingSequenceFlows);
      }

    }
  };

  // register activity types
  CAM.activityTypes["startEvent"] = startEvent;
  CAM.activityTypes["intermediateThrowEvent"] = intermediateThrowEvent;
  CAM.activityTypes["endEvent"] = endEvent;
  CAM.activityTypes["exclusiveGateway"] = exclusiveGateway;
  CAM.activityTypes["task"] = task;
  CAM.activityTypes["userTask"] = userTask;
  CAM.activityTypes["serviceTask"] = serviceTask;
  CAM.activityTypes["process"] = process;
  CAM.activityTypes["parallelGateway"] = parallelGateway;

})(CAM);
// if we are in a require enviroment, define the module
if (typeof define == 'function') {
  define([], function () {
    return CAM;
  });
}


text:
'use strict';

const angular = require('angular');

module.exports = angular
  .module('spinnaker.core.instance.details.console.link', [
    require('angular-ui-bootstrap'),
    require('./consoleOutput.modal.controller.js'),
  ])
  .directive('consoleOutputLink', function () {
    return {
      restrict: 'E',
      template: '<a href ng-click="vm.showConsoleOutput()">{{vm.text}}</a>',
      scope: {},
      bindToController: {
        instance: '=',
        text: '='
      },
      controllerAs: 'vm',
      controller: function($uibModal) {
        this.text = this.text || 'Console Output (Raw)';
        this.showConsoleOutput = function  () {
          $uibModal.open({
            templateUrl: require('./consoleOutput.modal.html'),
            controller: 'ConsoleOutputCtrl as ctrl',
            size: 'lg',
            resolve: {
              instance: () => this.instance
            }
          });
        };
      },
    };
  }).name;


text:
import gql from "graphql-tag";

export const CHANNELS_QUERY = gql`
	query Channels($sortBy: String!, $skip: Int!, $take: Int!, $language: String!) {
		channels(sortBy: $sortBy, skip: $skip, take: $take, language: $language) {
			iD
			title
			thumbnail
			description
			lastUploadAt
			publishedAt
			views
			subscribers
			videoCount
		}
	}
`;


text:
typedef struct material
{
  char *name;
  vec4f_t ambient;
  vec4f_t diffuse;
  vec4f_t specular;
  float shininess;
  float dissolve;
  GLuint ambient_map;
  GLuint diffuse_map;
  GLuint specular_map;
  GLuint bump_map;
  GLuint refl_map;
} material_t;

void material_init(material_t *this);
void material_term(material_t *this);

bool material_load_from_mdl(material_t *this, mdl_material_t *mdl);

typedef struct mesh
{
  unsigned int count;
  GLuint vao;
  material_t *mat;
} mesh_t;

void mesh_init(mesh_t *this);
void mesh_term(mesh_t *this);

bool mesh_load_from_mdl(mesh_t *this, mdl_mesh_t *mdl);

typedef struct model
{
  unsigned int count;
  mesh_t *meshes;
  GLuint _shader_id;
  shader_data_t *_shader_data;
  vec3f_t min, max;

  GLuint mtl_shininess_loc;
  GLuint mtl_ambient_loc;
  GLuint mtl_diffuse_loc;
  GLuint mtl_specular_loc;
  GLuint tex_ambient_loc;
  GLuint tex_diffuse_loc;
  GLuint tex_specular_loc;
  GLuint tex_bump_loc;
  GLuint has_tex_ambient_loc;
  GLuint has_tex_diffuse_loc;
  GLuint has_tex_specular_loc;
  GLuint has_tex_bump_loc;
} model_t;

void model_init(model_t *this);
void model_term(model_t *this);

bool model_load_from_file(model_t *this, const char *filename, const char *name, GLuint shader_id, shader_data_t *shader_data);
bool model_load_from_mdl(model_t *this, mdl_model_t *mdl, GLuint shader_id, shader_data_t *shader_data);

void model_draw(model_t *this);

#endif // VIEW3D_MODEL_H


text:
<!DOCTYPE html>

	<meta charset="utf-8" th:replace="layout::head(${WEBSITE_TITLE})" />
	<title>WallRide</title>

カスタムフィールド編集

			<form id="custom-field-form" th:fragment="form(title,customfield)" class="form-horizontal" method="post" th:object="${form}" th:action="@{__${ADMIN_PATH}__/customfields/create}">

					<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
					Error

				<input type="hidden" name="id" th:value="${customField}? ${customField.id} : ''"  />

					FieldName

						<input type="text" th:field="*{name}" class="form-control" th:attr="placeholder=#{FieldName}" />

					FieldName

						<input type="text" th:field="*{code}" class="form-control" th:attr="placeholder=#{Code}" />

					Description

						<textarea type="text" th:field="*{description}" class="form-control" style="min-height: 150px" th:attr="placeholder=#{Description}"></textarea>

					FieldType

						<select class="form-control" th:field="*{type}">
							<option th:each="fieldType : ${fieldTypes}" th:value="${fieldType}" th:text="${#messages.msg('CustomField.FieldType.' + fieldType)}" th:selected="${customField ne null and #strings.toString(customField.fieldType) eq #strings.toString(fieldType)}">指定なし</option>
						</select>

					FieldOption

						<input type="text" id="custom-field-options-input" class="form-control"/>

						 追加

								<button class="pull-right btn btn-link remove" data-dismiss="option"></button>

							<button name="submit" class="btn btn-primary ok" th:text="#{Save}">Save</button>

			</form>


text:
PROJECT_NAME     := template_pca10028
TARGETS          := nrf51422_xxac
OUTPUT_DIRECTORY := _build

SDK_ROOT := ../../../../../..
PROJ_DIR := ../../..

$(OUTPUT_DIRECTORY)/nrf51422_xxac.out: \
  LINKER_SCRIPT  := template_gcc_nrf51.ld

# Source files common to all targets
SRC_FILES += \
  $(SDK_ROOT)/components/libraries/log/src/nrf_log_backend_serial.c \
  $(SDK_ROOT)/components/libraries/log/src/nrf_log_frontend.c \
  $(SDK_ROOT)/components/libraries/button/app_button.c \
  $(SDK_ROOT)/components/libraries/util/app_error.c \
  $(SDK_ROOT)/components/libraries/util/app_error_weak.c \
  $(SDK_ROOT)/components/libraries/fifo/app_fifo.c \
  $(SDK_ROOT)/components/libraries/gpiote/app_gpiote.c \
  $(SDK_ROOT)/components/libraries/pwm/app_pwm.c \
  $(SDK_ROOT)/components/libraries/scheduler/app_scheduler.c \
  $(SDK_ROOT)/components/libraries/timer/app_timer.c \
  $(SDK_ROOT)/components/libraries/twi/app_twi.c \
  $(SDK_ROOT)/components/libraries/uart/app_uart_fifo.c \
  $(SDK_ROOT)/components/libraries/util/app_util_platform.c \
  $(SDK_ROOT)/components/libraries/crc16/crc16.c \
  $(SDK_ROOT)/components/libraries/crc32/crc32.c \
  $(SDK_ROOT)/components/libraries/hardfault/nrf51/handler/hardfault_handler_gcc.c \
  $(SDK_ROOT)/components/libraries/hardfault/hardfault_implementation.c \
  $(SDK_ROOT)/components/libraries/hci/hci_mem_pool.c \
  $(SDK_ROOT)/components/libraries/hci/hci_slip.c \
  $(SDK_ROOT)/components/libraries/hci/hci_transport.c \
  $(SDK_ROOT)/components/libraries/led_softblink/led_softblink.c \
  $(SDK_ROOT)/components/libraries/low_power_pwm/low_power_pwm.c \
  $(SDK_ROOT)/components/libraries/mem_manager/mem_manager.c \
  $(SDK_ROOT)/components/libraries/util/nrf_assert.c \
  $(SDK_ROOT)/components/libraries/csense/nrf_csense.c \
  $(SDK_ROOT)/components/libraries/csense_drv/nrf_drv_csense.c \
  $(SDK_ROOT)/components/libraries/queue/nrf_queue.c \
  $(SDK_ROOT)/components/libraries/util/sdk_errors.c \
  $(SDK_ROOT)/components/libraries/slip/slip.c \
  $(SDK_ROOT)/components/boards/boards.c \
  $(SDK_ROOT)/components/drivers_nrf/hal/nrf_adc.c \
  $(SDK_ROOT)/components/drivers_nrf/adc/nrf_drv_adc.c \
  $(SDK_ROOT)/components/drivers_nrf/clock/nrf_drv_clock.c \
  $(SDK_ROOT)/components/drivers_nrf/common/nrf_drv_common.c \
  $(SDK_ROOT)/components/drivers_nrf/gpiote/nrf_drv_gpiote.c \
  $(SDK_ROOT)/components/drivers_nrf/i2s/nrf_drv_i2s.c \
  $(SDK_ROOT)/components/drivers_nrf/lpcomp/nrf_drv_lpcomp.c \
  $(SDK_ROOT)/components/drivers_nrf/pdm/nrf_drv_pdm.c \
  $(SDK_ROOT)/components/drivers_nrf/power/nrf_drv_power.c \
  $(SDK_ROOT)/components/drivers_nrf/ppi/nrf_drv_ppi.c \
  $(SDK_ROOT)/components/drivers_nrf/pwm/nrf_drv_pwm.c \
  $(SDK_ROOT)/components/drivers_nrf/qdec/nrf_drv_qdec.c \
  $(SDK_ROOT)/components/drivers_nrf/rng/nrf_drv_rng.c \
  $(SDK_ROOT)/components/drivers_nrf/rtc/nrf_drv_rtc.c \
  $(SDK_ROOT)/components/drivers_nrf/saadc/nrf_drv_saadc.c \
  $(SDK_ROOT)/components/drivers_nrf/spi_master/nrf_drv_spi.c \
  $(SDK_ROOT)/components/drivers_nrf/spi_slave/nrf_drv_spis.c \
  $(SDK_ROOT)/components/drivers_nrf/swi/nrf_drv_swi.c \
  $(SDK_ROOT)/components/drivers_nrf/timer/nrf_drv_timer.c \
  $(SDK_ROOT)/components/drivers_nrf/twi_master/nrf_drv_twi.c \
  $(SDK_ROOT)/components/drivers_nrf/twis_slave/nrf_drv_twis.c \
  $(SDK_ROOT)/components/drivers_nrf/uart/nrf_drv_uart.c \
  $(SDK_ROOT)/components/drivers_nrf/wdt/nrf_drv_wdt.c \
  $(SDK_ROOT)/components/drivers_nrf/nrf_soc_nosd/nrf_nvic.c \
  $(SDK_ROOT)/components/drivers_nrf/hal/nrf_saadc.c \
  $(SDK_ROOT)/components/drivers_nrf/nrf_soc_nosd/nrf_soc.c \
  $(SDK_ROOT)/components/libraries/bsp/bsp.c \
  $(SDK_ROOT)/components/libraries/bsp/bsp_nfc.c \
  $(PROJ_DIR)/main.c \
  $(SDK_ROOT)/external/segger_rtt/RTT_Syscalls_GCC.c \
  $(SDK_ROOT)/external/segger_rtt/SEGGER_RTT.c \
  $(SDK_ROOT)/external/segger_rtt/SEGGER_RTT_printf.c \
  $(SDK_ROOT)/components/toolchain/gcc/gcc_startup_nrf51.S \
  $(SDK_ROOT)/components/toolchain/system_nrf51.c \

# Include folders common to all targets
INC_FOLDERS += \
  $(SDK_ROOT)/components \
  ../config \
  $(SDK_ROOT)/components/drivers_nrf/comp \
  $(SDK_ROOT)/components/drivers_nrf/spi_master \
  $(SDK_ROOT)/components/libraries/pwm \
  $(SDK_ROOT)/components/drivers_nrf/twi_master \
  $(SDK_ROOT)/components/libraries/fifo \
  $(SDK_ROOT)/components/drivers_nrf/pdm \
  $(SDK_ROOT)/components/libraries/crc32 \
  $(SDK_ROOT)/components/drivers_nrf/delay \
  $(SDK_ROOT)/components/libraries/crc16 \
  $(SDK_ROOT)/components/libraries/mem_manager \
  $(SDK_ROOT)/components/toolchain/cmsis/include \
  $(SDK_ROOT)/components/drivers_nrf/timer \
  $(SDK_ROOT)/components/libraries/util \
  $(SDK_ROOT)/components/libraries/hardfault \
  $(SDK_ROOT)/components/drivers_nrf/pwm \
  $(SDK_ROOT)/components/drivers_nrf/uart \
  $(SDK_ROOT)/components/libraries/csense_drv \
  $(SDK_ROOT)/components/libraries/csense \
  $(SDK_ROOT)/components/libraries/low_power_pwm \
  $(SDK_ROOT)/components/drivers_nrf/swi \
  $(SDK_ROOT)/components/libraries/hardfault/nrf51 \
  $(SDK_ROOT)/components/libraries/scheduler \
  $(SDK_ROOT)/components/libraries/bsp \
  $(SDK_ROOT)/components/drivers_nrf/rng \
  $(SDK_ROOT)/components/libraries/uart \
  $(SDK_ROOT)/components/device \
  $(SDK_ROOT)/components/libraries/hci \
  $(SDK_ROOT)/components/libraries/log \
  $(SDK_ROOT)/components/drivers_nrf/spi_slave \
  $(SDK_ROOT)/components/libraries/slip \
  $(SDK_ROOT)/components/libraries/button \
  $(SDK_ROOT)/components/drivers_nrf/lpcomp \
  $(SDK_ROOT)/components/libraries/timer \
  $(SDK_ROOT)/components/drivers_nrf/i2s \
  $(SDK_ROOT)/components/libraries/queue \
  $(SDK_ROOT)/components/libraries/gpiote \
  $(SDK_ROOT)/components/drivers_nrf/gpiote \
  $(SDK_ROOT)/components/drivers_nrf/saadc \
  $(SDK_ROOT)/components/drivers_nrf/power \
  $(SDK_ROOT)/components/drivers_nrf/nrf_soc_nosd \
  $(SDK_ROOT)/components/toolchain \
  $(SDK_ROOT)/external/segger_rtt \
  $(SDK_ROOT)/components/boards \
  $(SDK_ROOT)/components/drivers_nrf/hal \
  $(SDK_ROOT)/components/toolchain/gcc \
  $(SDK_ROOT)/components/drivers_nrf/rtc \
  $(SDK_ROOT)/components/drivers_nrf/common \
  $(SDK_ROOT)/components/libraries/twi \
  $(SDK_ROOT)/components/drivers_nrf/adc \
  $(SDK_ROOT)/components/drivers_nrf/clock \
  $(PROJ_DIR) \
  $(SDK_ROOT)/components/libraries/led_softblink \
  $(SDK_ROOT)/components/drivers_nrf/wdt \
  $(SDK_ROOT)/components/drivers_nrf/ppi \
  $(SDK_ROOT)/components/drivers_nrf/qdec \
  $(SDK_ROOT)/components/drivers_nrf/twis_slave \
  $(SDK_ROOT)/components/libraries/log/src \

# Libraries common to all targets
LIB_FILES += \

# C flags common to all targets
CFLAGS += -DNRF51
CFLAGS += -DNRF51422
CFLAGS += -DSWI_DISABLE0
CFLAGS += -DBOARD_PCA10028
CFLAGS += -mcpu=cortex-m0
CFLAGS += -mthumb -mabi=aapcs
CFLAGS +=  -Wall -Werror -O3 -g3
CFLAGS += -mfloat-abi=soft
# keep every function in separate section, this allows linker to discard unused ones
CFLAGS += -ffunction-sections -fdata-sections -fno-strict-aliasing
CFLAGS += -fno-builtin --short-enums

# C++ flags common to all targets
CXXFLAGS += \

# Assembler flags common to all targets
ASMFLAGS += -x assembler-with-cpp
ASMFLAGS += -DNRF51
ASMFLAGS += -DNRF51422
ASMFLAGS += -DSWI_DISABLE0
ASMFLAGS += -DBOARD_PCA10028

# Linker flags
LDFLAGS += -mthumb -mabi=aapcs -L $(TEMPLATE_PATH) -T$(LINKER_SCRIPT)
LDFLAGS += -mcpu=cortex-m0
# let linker to dump unused sections
LDFLAGS += -Wl,--gc-sections
# use newlib in nano version
LDFLAGS += --specs=nano.specs -lc -lnosys

.PHONY: $(TARGETS) default all clean help flash

# Default target - first one defined
default: nrf51422_xxac

# Print all targets that can be built
help:
	@echo following targets are available:
	@echo 	nrf51422_xxac

TEMPLATE_PATH := $(SDK_ROOT)/components/toolchain/gcc

include $(TEMPLATE_PATH)/Makefile.common

$(foreach target, $(TARGETS), $(call define_target, $(target)))

# Flash the program
flash: $(OUTPUT_DIRECTORY)/nrf51422_xxac.hex
	@echo Flashing: $<
	nrfjprog --program $< -f nrf51 --sectorerase
	nrfjprog --reset -f nrf51

erase:
	nrfjprog --eraseall -f nrf52


text:
package org.apache.carbondata.integration.spark.testsuite.dataload

import org.apache.spark.sql.Row
import org.apache.spark.sql.test.util.QueryTest
import org.scalatest.BeforeAndAfterAll

/**
  * Test Class for data loading use one pass
  *
  */
class TestLoadDataWithSinglePass extends QueryTest with BeforeAndAfterAll {

  override def beforeAll {
    sql("DROP TABLE IF EXISTS table_two_pass")
    sql("DROP TABLE IF EXISTS table_one_pass")
    sql("DROP TABLE IF EXISTS table_one_pass_2")

    sql(
      """
        |CREATE TABLE table_two_pass (ID int, date Timestamp, country String,
        |name String, phonetype String, serialname String, salary int)
        |STORED BY 'org.apache.carbondata.format'
      """.stripMargin)

    sql(
      s"""
        |LOAD DATA local inpath '$resourcesPath/source.csv' INTO TABLE table_two_pass
        |OPTIONS('DELIMITER'= ',', 'SINGLE_PASS'='false')
      """.stripMargin)

    sql(
      """
        |CREATE TABLE table_one_pass (ID int, date Timestamp, country String,
        |name String, phonetype String, serialname String, salary int)
        |STORED BY 'org.apache.carbondata.format'
      """.stripMargin)

    sql(
      s"""
        |LOAD DATA local inpath '$resourcesPath/source.csv' INTO TABLE table_one_pass
        |OPTIONS('DELIMITER'= ',', 'SINGLE_PASS'='true')
      """.stripMargin)
  }

  test("test data loading use one pass") {
    checkAnswer(
      sql("select * from table_one_pass"),
      sql("select * from table_two_pass")
    )
  }

  test("test data loading use one pass when offer column dictionary file") {
    sql(
      """
        |CREATE TABLE table_one_pass_2 (ID int, date Timestamp, country String,
        |name String, phonetype String, serialname String, salary int)
        |STORED BY 'org.apache.carbondata.format'
      """.stripMargin)
    sql(
      s"""
        |LOAD DATA local inpath '$resourcesPath/source.csv' INTO TABLE table_one_pass_2
        |OPTIONS('DELIMITER'= ',', 'SINGLE_PASS'='true', 'COLUMNDICT'=
        |'country:$resourcesPath/columndictionary/country.csv, name:$resourcesPath/columndictionary/name.csv')
      """.stripMargin)

    checkAnswer(
      sql("select * from table_one_pass_2"),
      sql("select * from table_two_pass")
    )
  }

  test("test data loading use one pass when do incremental load") {
    sql(
      s"""
        |LOAD DATA local inpath '$resourcesPath/dataIncrement.csv' INTO TABLE table_two_pass
        |OPTIONS('DELIMITER'= ',', 'SINGLE_PASS'='false')
      """.stripMargin)
    sql(
      s"""
        |LOAD DATA local inpath '$resourcesPath/dataIncrement.csv' INTO TABLE table_one_pass
        |OPTIONS('DELIMITER'= ',', 'SINGLE_PASS'='true')
      """.stripMargin)

    checkAnswer(
      sql("select * from table_one_pass"),
      sql("select * from table_two_pass")
    )
  }

  test("test data loading with dctionary exclude") {
    sql("DROP TABLE IF EXISTS dict_exclude")
    sql(
      """
        |CREATE TABLE dict_exclude (ID int, date Timestamp, country String,
        |name String, phonetype String, serialname String, salary int)
        |STORED BY 'org.apache.carbondata.format' TBLPROPERTIES('DICTIONARY_EXCLUDE'='country,name,serialname,phonetype')
      """.stripMargin)
    sql(
      s"""
         |LOAD DATA local inpath '$resourcesPath/source.csv' INTO TABLE dict_exclude
         |OPTIONS('DELIMITER'= ',', 'SINGLE_PASS'='FALSE')
      """.stripMargin)
    checkAnswer(sql("select name from dict_exclude limit 1"),Row("aaa1"))
  }

  override def afterAll {
    sql("DROP TABLE IF EXISTS table_two_pass")
    sql("DROP TABLE IF EXISTS table_one_pass")
    sql("DROP TABLE IF EXISTS table_one_pass_2")
    sql("DROP TABLE IF EXISTS dict_exclude")
  }
}


text:
#ifndef GHERKIN_AST_PRINTER_H_
#define GHERKIN_AST_PRINTER_H_

#include "gherkin_document.h"
#include <stdio.h>

#ifdef __cplusplus
extern "C" {
#endif

void AstPrinter_print_gherkin_document(FILE* file, const GherkinDocument* gherkin_document);

#ifdef __cplusplus
}
#endif

#endif /* GHERKIN_AST_PRINTER_H_ */


text:
//
//  XLEBaseTableViewController.h
//  Pods
//
//  Created by Randy on 16/2/25.
//
//

#import <UIKit/UIKit.h>
#import "XLEBaseViewController.h"
#import "XLEListRequestOpeProtocol.h"
#import "XLEBaseTableView.h"
#import "XLETableViewCell.h"
#import "XLETableViewListDelegate.h"

@class XLETableConfigModel;

NS_ASSUME_NONNULL_BEGIN

@interface XLEBaseTableViewController : XLEBaseViewController<XLETableViewListDelegate>
@property (weak, nonatomic) id<XLEListRequestOpeProtocol> requestDelegate;
@property (strong, nonatomic) XLEBaseTableView *tableView;
@property (assign, nonatomic) UIEdgeInsets tableViewInsets;

@property (strong, nonatomic) XLEPageModel *pageModel;

/**
 *  控制是否每次进入界面的时候强制刷新 默认NO
 */
@property (assign, nonatomic) BOOL forceRefreshWhenViewAppear;

- (instancetype)initWithConfig:(XLETableConfigModel *)config;

@end

NS_ASSUME_NONNULL_END


text:
This is the source of [survivejs.com](survivejs.com).

## Development

First, you need to clone this repository and the `webpack_react` one:

```
$ git clone https://github.com/survivejs/site
$ git clone https://github.com/survivejs/webpack_react
```

Then, you need to build each `webpack_react` project (it is a needed requisite to build this site):

```
$ cd webpack_react/project_source
$ ./build_all.js
```

Now going back to the `site` project, you need to install the dependencies:

```
$ npm install
$ npm install -g antwar-cli
```

**NOTE**: There's some glitch in Antwar preventing it to work locally so it has to go this way.

Finally, you can start the development server:

```
$ npm start
```

Now you can go to `http://localhost:8000`.

## Deployment

After you modify `antwar.config.js` to configure your deploy settings, you need to generate a static build:

```
$ npm run build
```

And after you checked out the build, you can deploy it with:

```
$ npm run deploy
```

## License

The site is available under MIT. So as long as there's proper attribution you can reuse the content. Ideally you would contribute your improvements back but that's not absolutely necessary.


text:
<?php
    //classes loading begin
    function classLoad ($myClass) {
        if(file_exists('../model/'.$myClass.'.php')){
            include('../model/'.$myClass.'.php');
        }
        elseif(file_exists('../controller/'.$myClass.'.php')){
            include('../controller/'.$myClass.'.php');
        }
    }
    spl_autoload_register("classLoad");
    include('../config/config.php');
    //classes loading end
    session_start();

    //post input processing
    $idProjet = htmlentities($_POST['idProjet']);
    if( !empty($_POST['nom'])){
        $nom = htmlentities($_POST['nom']);
        $cin = htmlentities($_POST['cin']);
		$adresse = htmlentities($_POST['adresse']);
		$dateNaissance = htmlentities($_POST['dateNaissance']);
		$dateContrat = htmlentities($_POST['dateContrat']);
		$matiere = htmlentities($_POST['matiere']);
		$prix = htmlentities($_POST['prix']);
		$mesure = htmlentities($_POST['mesure']);
		$prixTotal = htmlentities($_POST['prixTotal']);
		$idContrat = htmlentities($_POST['idContrat']);

        $contrat = new ContratTravail(array('id' => $idContrat, 'nom' => $nom, 'cin' => $cin,
        'dateNaissance' => $dateNaissance, 'dateContrat' => $dateContrat,
		'adresse' => $adresse, 'matiere' => $matiere, 'prix' => $prix, 'mesure' => $mesure,
		'prixTotal' => $prixTotal));
        $contratTravailManager = new ContratTravailManager($pdo);
        $contratTravailManager->update($contrat);
        $_SESSION['contrat-update-success']="تم تعديل العقد بنجاح";
    }
    else{
        $_SESSION['contrat-update-error'] = " خطأ في التسجيل"."يجب ادخال  الاسم ";
    }
	header('Location:../view/contrats-travail.php?idProjet='.$idProjet);


text:
require 'utils/logger'
require 'utils/cfg'
require 'utils/shell'

module Nginx
  class Manager
    class << self

      def remove(ports)
        ports = [*ports]
        $logger.info "removing #{ports} from nginx"
        modify_nginx do |ofile, iline|
          ofile.puts(iline) if !line_matches_ports(iline, ports)
        end
      end

      def add(ports)
        ports = [*ports]
        $logger.info "adding #{ports} to nginx"
        modify_nginx do |ofile, iline|
          ofile.puts(iline)
          if iline =~ /upstream phantomjs/
            ports.each do |port|
              ofile.puts(phantom_upstream(port)) unless port_defined?(port)
            end
          end
        end
      end

      private

      def phantom_upstream(port)
        "  server 127.0.0.1:#{port} fail_timeout=0; # #{Time.now}"
      end

      def port_defined?(port)
        File.readlines(Cfg.nginx_conf).grep(/#{port}/).size > 0
      end

      def switch_nginx_configs
        $logger.info "switching nginx configurations"
        `mv #{Cfg.new_nginx_conf} #{Cfg.nginx_conf}`
      end

      def reload_nginx
        $logger.info "reloading nginx"
        Utils::Shell.execute "nginx -s reload"
      end

      def modify_nginx
        File.open(Cfg.new_nginx_conf, "w") do |ofile|
          File.foreach(Cfg.nginx_conf) do |iline|
            yield ofile, iline
          end
        end
        switch_nginx_configs
        reload_nginx
      end

      def line_matches_ports(line, ports)
        line =~ ports_regexp(ports)
      end

      def ports_regexp(ports)
        /#{ports.join("|")}/
      end

    end
  end
end


text:
inbox module
============

.. automodule:: inbox
    :members:
    :undoc-members:
    :show-inheritance:


text:
"""Primitive parseable objects in the IMAP protocol."""

from __future__ import annotations

import re
from abc import abstractmethod, ABCMeta
from collections.abc import Iterable, Iterator, Sequence
from functools import total_ordering
from re import Match
from typing import cast, Any, SupportsBytes

from . import AnyParseable, Parseable, ExpectedParseable, Params
from .exceptions import NotParseable
from .state import ExpectContinuation
from ..bytes import MaybeBytes, MaybeBytesT, BytesFormat, WriteStream, \
    Writeable

__all__ = ['Nil', 'Number', 'Atom', 'List', 'String',
           'QuotedString', 'LiteralString']

class Nil(Parseable[None]):
    """Represents a ``NIL`` object from an IMAP stream."""

    _nil_pattern = re.compile(b'^NIL$', re.I)

    __slots__: list[str] = []

    def __init__(self) -> None:
        super().__init__()

    @property
    def value(self) -> None:
        """Always returns ``None``."""
        return None

    def __bytes__(self) -> bytes:
        return b'NIL'

    def __hash__(self) -> int:
        return hash(Nil)

    def __eq__(self, other: Any) -> bool:
        if isinstance(other, Nil):
            return True
        return super().__eq__(other)

    @classmethod
    def parse(cls, buf: memoryview, params: Params) \
            -> tuple[Nil, memoryview]:
        start = cls._whitespace_length(buf)
        match = cls._atom_pattern.match(buf, start)
        if not match:
            raise NotParseable(buf)
        atom = match.group(0)
        if not cls._nil_pattern.match(atom):
            raise NotParseable(buf)
        return cls(), buf[match.end(0):]

@total_ordering
class Number(Parseable[int]):
    """Represents a number object from an IMAP stream.

    Args:
        num: The integer value.

    """

    _num_pattern = re.compile(br'^\d+$')

    __slots__ = ['num', '_raw']

    def __init__(self, num: int) -> None:
        super().__init__()
        self.num = num
        self._raw = b'%d' % num

    @property
    def value(self) -> int:
        """The integer value."""
        return self.num

    @classmethod
    def parse(cls, buf: memoryview, params: Params) \
            -> tuple[Number, memoryview]:
        start = cls._whitespace_length(buf)
        match = cls._atom_pattern.match(buf, start)
        if not match:
            raise NotParseable(buf)
        atom = match.group(0)
        if not cls._num_pattern.match(atom):
            raise NotParseable(buf)
        return cls(int(match.group(0))), buf[match.end(0):]

    def __bytes__(self) -> bytes:
        return self._raw

    def __hash__(self) -> int:
        return hash((Number, self.value))

    def __eq__(self, other: Any) -> bool:
        if isinstance(other, Number):
            return self.value == other.value
        elif isinstance(other, int):
            return self.value == other
        return super().__eq__(other)

    def __lt__(self, other: Any) -> bool:
        if isinstance(other, Number):
            return self.value < other.value
        elif isinstance(other, int):
            return self.value < other
        return NotImplemented

class Atom(Parseable[bytes]):
    """Represents an atom object from an IMAP stream.

    Args:
        value: The atom bytestring.

    """

    __slots__ = ['_value']

    def __init__(self, value: bytes) -> None:
        super().__init__()
        self._value = value

    @property
    def value(self) -> bytes:
        """The atom bytestring."""
        return self._value

    @classmethod
    def parse(cls, buf: memoryview, params: Params) \
            -> tuple[Atom, memoryview]:
        start = cls._whitespace_length(buf)
        match = cls._atom_pattern.match(buf, start)
        if not match:
            raise NotParseable(buf[start:])
        atom = match.group(0)
        return cls(atom), buf[match.end(0):]

    def __bytes__(self) -> bytes:
        return self.value

    def __hash__(self) -> int:
        return hash((Atom, self.value))

    def __eq__(self, other: Any) -> bool:
        if isinstance(other, Atom):
            return self.value == other.value
        return super().__eq__(other)

class String(Parseable[bytes], metaclass=ABCMeta):
    """Represents a string object from an IMAP string. This object may not be
    instantiated directly, use one of its derivatives instead.

    """

    _MAX_LEN = 4096

    __slots__: list[str] = []

    @property
    @abstractmethod
    def binary(self) -> bool:
        """True if the string should be transmitted as binary."""
        ...

    @property
    @abstractmethod
    def length(self) -> int:
        """The length of the string value."""
        ...

    @classmethod
    def parse(cls, buf: memoryview, params: Params) \
            -> tuple[String, memoryview]:
        try:
            return QuotedString.parse(buf, params)
        except NotParseable:
            pass
        return LiteralString.parse(buf, params)

    @classmethod
    def build(cls, value: object, binary: bool = False,
              fallback: object = None) -> Nil | String:
        """Produce either a :class:`QuotedString` or :class:`LiteralString`
        based on the contents of ``data``. This is useful to improve
        readability of response data.

        Args:
            value: The string to serialize.
            binary: True if the string should be transmitted as binary.
            fallback: The default value to use if ``value`` is None.

        """
        if value is None:
            if fallback is None:
                return Nil()
            else:
                return cls.build(fallback, binary)
        elif not value:
            return QuotedString(b'')
        elif isinstance(value, bytes):
            ascii_ = value
        elif isinstance(value, memoryview):
            ascii_ = bytes(value)
        elif hasattr(value, '__bytes__'):
            ascii_ = bytes(cast(SupportsBytes, value))
        elif isinstance(value, str) or hasattr(value, '__str__'):
            value = str(value)
            try:
                ascii_ = bytes(value, 'ascii')
            except UnicodeEncodeError:
                ascii_ = bytes(value, 'utf-8', 'replace')
                return LiteralString(ascii_, binary)
        else:
            raise TypeError(value)
        if not binary and len(ascii_) < 64 \
                and b'\n' not in ascii_ \
                and b'\x00' not in ascii_:
            return QuotedString(ascii_)
        else:
            return LiteralString(ascii_, binary)

    def __bytes__(self) -> bytes:
        raise NotImplementedError

    def __hash__(self) -> int:
        return hash((String, self.value))

    def __eq__(self, other: Any) -> bool:
        if isinstance(other, String):
            return self.value == other.value
        return super().__eq__(other)

class QuotedString(String):
    """Represents a string object from an IMAP stream that was encased in
    double-quotes.

    Args:
        string: The string value.

    """

    _quoted_pattern = re.compile(br'(?:\r|\n|\\.|\")')
    _quoted_specials_pattern = re.compile(br'[\"\\]')

    __slots__ = ['_string', '_raw']

    def __init__(self, string: bytes, raw: bytes | None = None) -> None:
        super().__init__()
        self._string = string
        self._raw = raw

    @property
    def value(self) -> bytes:
        """The string value."""
        return self._string

    @property
    def binary(self) -> bool:
        return False

    @property
    def length(self) -> int:
        return len(self._string)

    @classmethod
    def parse(cls, buf: memoryview, params: Params) \
            -> tuple[QuotedString, memoryview]:
        start = cls._whitespace_length(buf)
        if buf[start:start + 1] != b'"':
            raise NotParseable(buf)
        marker = start + 1
        unquoted = bytearray()
        for match in cls._quoted_pattern.finditer(buf, marker):
            unquoted += buf[marker:match.start(0)]
            match_group = match.group(0)
            if match_group in (b'\r', b'\n'):
                raise NotParseable(buf)
            elif match_group.startswith(b'\\'):
                escape_char = match_group[-1:]
                if escape_char in (b'\\', b'"'):
                    unquoted += escape_char
                else:
                    raise NotParseable(buf)
                marker = match.end(0)
            else:
                end = match.end(0)
                quoted = buf[start:end + 1]
                return cls(bytes(unquoted), bytes(quoted)), buf[end:]
        raise NotParseable(buf)

    @classmethod
    def _escape_quoted_specials(cls, match: Match[bytes]) -> bytes:
        return b'\\' + match.group(0)

    def __bytes__(self) -> bytes:
        if self._raw is not None:
            return bytes(self._raw)
        pat = self._quoted_specials_pattern
        quoted_string = pat.sub(self._escape_quoted_specials, self.value)
        self._raw = BytesFormat(b'"%b"') % (quoted_string, )
        return self._raw

class LiteralString(String):
    """Represents a string object from an IMAP stream that used the literal
    syntax.

    Args:
        string: The literal string value.
        binary: True if the string is considered binary data.

    """

    _literal_pattern = re.compile(br'(~?){(\d+)(\+?)}\r?\n')

    __slots__ = ['_string', '_length', '_binary', '_raw']

    def __init__(self, string: bytes | Writeable,
                 binary: bool = False) -> None:
        super().__init__()
        self._string = string
        self._length = len(string)
        self._binary = binary
        self._raw: bytes | None = None

    @property
    def value(self) -> bytes:
        return bytes(self._string)

    @property
    def binary(self) -> bool:
        return self._binary

    @property
    def length(self) -> int:
        return self._length

    @property
    def _prefix(self) -> bytes:
        binary_prefix = b'~' if self.binary else b''
        return b'%b{%d}\r\n' % (binary_prefix, self.length)

    @classmethod
    def _check_too_big(cls, params: Params, length: int) -> bool:
        if params.command_name == b'APPEND':
            max_len = params.max_append_len
        else:
            max_len = cls._MAX_LEN
        return max_len is not None and length > max_len

    @classmethod
    def parse(cls, buf: memoryview, params: Params) \
            -> tuple[LiteralString, memoryview]:
        start = cls._whitespace_length(buf)
        match = cls._literal_pattern.match(buf, start)
        if not match:
            raise NotParseable(buf)
        binary = match.group(1) == b'~'
        literal_length = int(match.group(2))
        if cls._check_too_big(params, literal_length):
            raise NotParseable(buf, b'TOOBIG')
        elif match.group(3) == b'+':
            buf = buf[match.end(0):]
            literal = bytes(buf[0:literal_length])
        elif len(buf) > match.end(0):
            raise NotParseable(buf[match.end(0):])
        elif params.allow_continuations:
            expected = ExpectContinuation(b'Literal string', literal_length)
            buf = expected.expect(params.state)
            literal = bytes(buf[0:literal_length])
        else:
            raise NotParseable(buf)
        if len(literal) != literal_length:
            raise NotParseable(buf)
        return cls(literal, binary), buf[literal_length:]

    def write(self, writer: WriteStream) -> None:
        writer.write(self._prefix)
        if isinstance(self._string, Writeable):
            self._string.write(writer)
        else:
            writer.write(self._string)

    def __len__(self) -> int:
        return len(self._prefix) + self.length

    def __bytes__(self) -> bytes:
        if self._raw is None:
            self._raw = self.tobytes()
        return self._raw

class List(Parseable[Sequence[MaybeBytes]]):
    """Represents a list of :class:`Parseable` objects from an IMAP stream.

    Args:
        items: The list of parsed objects.
        sort: If True, the list of items is sorted.

    """

    _end_pattern = re.compile(br' *\)')

    __slots__ = ['items']

    def __init__(self, items: Iterable[MaybeBytes],
                 sort: bool = False) -> None:
        super().__init__()
        if sort:
            items_list = sorted(items)  # type: ignore
        else:
            items_list = list(items)
        self.items: Sequence[MaybeBytes] = items_list

    @property
    def value(self) -> Sequence[MaybeBytes]:
        """The list of parsed objects."""
        return self.items

    def get_as(self, cls: type[MaybeBytesT]) -> Sequence[MaybeBytesT]:
        """Return the list of parsed objects."""
        _ = cls  # noqa
        return cast(Sequence[MaybeBytesT], self.items)

    def __iter__(self) -> Iterator[MaybeBytes]:
        return iter(self.value)

    def __len__(self) -> int:
        return len(self.value)

    @classmethod
    def parse(cls, buf: memoryview, params: Params) \
            -> tuple[List, memoryview]:
        start = cls._whitespace_length(buf)
        if buf[start:start + 1] != b'(':
            raise NotParseable(buf)
        items: list[AnyParseable] = []
        buf = buf[start + 1:]
        while True:
            match = cls._end_pattern.match(buf)
            if match:
                return cls(items), buf[match.end(0):]
            elif items and not cls._whitespace_length(buf):
                raise NotParseable(buf)
            params_copy = params.copy(expected=params.list_expected)
            item, buf = ExpectedParseable.parse(buf, params_copy)
            items.append(item)

    def write(self, writer: WriteStream) -> None:
        writer.write(b'(')
        is_first = True
        for item in self.items:
            if is_first:
                is_first = False
            else:
                writer.write(b' ')
            if isinstance(item, Writeable):
                item.write(writer)
            else:
                writer.write(bytes(item))
        writer.write(b')')

    def __bytes__(self) -> bytes:
        raw_items = BytesFormat(b' ').join(self.items)
        return b'(%b)' % raw_items

    def __hash__(self) -> int:
        return hash((List, self.value))

    def __eq__(self, other: Any) -> bool:
        if isinstance(other, List):
            return self.__eq__(other.value)
        elif isinstance(other, Sequence):
            if len(self.value) != len(other):
                return False
            for i, val in enumerate(self.value):
                if val != other[i]:
                    return False
            return True
        return super().__eq__(other)