text:
package org.wso2.carbon.event.input.adapter.http;

import org.wso2.carbon.event.input.adapter.core.InputEventAdapter;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterConfiguration;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterListener;
import org.wso2.carbon.event.input.adapter.core.exception.InputEventAdapterException;
import org.wso2.carbon.event.input.adapter.core.exception.TestConnectionNotSupportedException;
import org.wso2.carbon.event.input.adapter.http.internal.HTTPEventAdapterManager;
import org.wso2.carbon.event.input.adapter.http.internal.util.HTTPEventAdapterConstants;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public final class HTTPEventAdapter implements InputEventAdapter {

    private final InputEventAdapterConfiguration eventAdapterConfiguration;
    private final Map<String, String> globalProperties;
    private InputEventAdapterListener eventAdaptorListener;
    private final String id = UUID.randomUUID().toString();

    public static ExecutorService executorService;
    public HTTPEventAdapter(InputEventAdapterConfiguration eventAdapterConfiguration,
                            Map<String, String> globalProperties) {
        this.eventAdapterConfiguration = eventAdapterConfiguration;
        this.globalProperties = globalProperties;
    }

    @Override
    public void init(InputEventAdapterListener eventAdaptorListener) throws InputEventAdapterException {
        this.eventAdaptorListener = eventAdaptorListener;

        //ThreadPoolExecutor will be assigned  if it is null
        if (executorService == null) {
            int minThread;
            int maxThread;
            long defaultKeepAliveTime;
            int jobQueueSize;

            //If global properties are available those will be assigned else constant values will be assigned
            if (globalProperties.get(HTTPEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME) != null) {
                minThread = Integer.parseInt(globalProperties.get(
                        HTTPEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE_NAME));
            } else {
                minThread = HTTPEventAdapterConstants.ADAPTER_MIN_THREAD_POOL_SIZE;
            }

            if (globalProperties.get(HTTPEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME) != null) {
                maxThread = Integer.parseInt(globalProperties.get(
                        HTTPEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE_NAME));
            } else {
                maxThread = HTTPEventAdapterConstants.ADAPTER_MAX_THREAD_POOL_SIZE;
            }

            if (globalProperties.get(HTTPEventAdapterConstants.DEFAULT_KEEP_ALIVE_TIME_NAME) != null) {
                defaultKeepAliveTime = Integer.parseInt(globalProperties.get(
                        HTTPEventAdapterConstants.DEFAULT_KEEP_ALIVE_TIME_NAME));
            } else {
                defaultKeepAliveTime = HTTPEventAdapterConstants.DEFAULT_KEEP_ALIVE_TIME;
            }

            if (globalProperties.get(HTTPEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME) != null) {
                jobQueueSize = Integer.parseInt(globalProperties.get(
                        HTTPEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE_NAME));
            } else {
                jobQueueSize = HTTPEventAdapterConstants.ADAPTER_EXECUTOR_JOB_QUEUE_SIZE;
            }

            executorService = new ThreadPoolExecutor(minThread, maxThread, defaultKeepAliveTime,
                    TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(jobQueueSize));
        }
    }

    @Override
    public void testConnect() throws TestConnectionNotSupportedException {
        throw new TestConnectionNotSupportedException("not-supported");
    }

    @Override
    public void connect() {
        HTTPEventAdapterManager.registerDynamicEndpoint(eventAdapterConfiguration.getName(), this);
    }

    @Override
    public void disconnect() {
        HTTPEventAdapterManager.unregisterDynamicEndpoint(eventAdapterConfiguration.getName(), this);
    }

    @Override
    public void destroy() {
    }

    public InputEventAdapterListener getEventAdaptorListener() {
        return eventAdaptorListener;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof HTTPEventAdapter)) return false;

        HTTPEventAdapter that = (HTTPEventAdapter) o;

        if (!id.equals(that.id)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }
}


text:
define([
    'backbone',
    'marionette',
    'jquery',
    'underscore',
    'handlebars',
    "hbs!main/components/modal/bootstrapModalTemplate",
    "hbs!main/components/modal/bootstrapModalHeaderTemplate"
], function(Backbone, Marionette, $, _, Handlebars, BootstrapModalTemplate, BootstrapModalHeaderTemplate) {
    var DivModel = Backbone.Model.extend({
        defaults: {
            'sizeClass': '',
            'backdrop': true,
            'keyboard': true
        }
    });
    var Modal = {
        generateDiv: function(modalOptions, ModalLayoutView) {
            var regionName = modalOptions.regionName || 'mainModalDialog',
                temp = Backbone.Marionette.LayoutView.extend({
                    model: new DivModel(),
                    initialize: function() {
                        if (modalOptions.keyboard === false) {
                            this.model.set('keyboard', modalOptions.keyboard);
                        }
                        if (modalOptions.backdrop === false || modalOptions.backdrop === 'static') {
                            this.model.set('backdrop', modalOptions.backdrop);
                        }

                        this.addRegion(regionName, '#' + regionName);
                        this.channel = modalOptions.channel;
                        this.model.set('regionName', regionName);
                        this.configureEvents(regionName);
                        this.modalLayoutView = new ModalLayoutView();
                    },
                    onRender: function() {
                        this.getRegion(regionName).show(this.modalLayoutView);
                    },
                    template: Handlebars.compile('

'),
                    tagName: 'div',
                    attributes: {
                        'id': 'mainModal',
                    },
                    configureEvents: function(regionName) { //this might be extraneous but it allows the use of events to control which item is shown
                        var show = this.show;
                        this.channel.comply('show:' + regionName, function(e) {
                            show(regionName);
                        });
                    },
                    hide: function(regionName) {
                        var el = this.getRegion(regionName).$el;
                        el.modal('hide');
                        //this.activeRegion = null;
                    },
                    show: function(regionName) {
                        var el = this.getRegion(regionName).$el,
                            channel = this.channel,
                            self = this;

                        if (this.activeRegion) {
                            this.getRegion(this.activeRegion).$el.one('hidden.bs.modal', function(e) {
                                el.modal('show', true);
                                self.activeRegion = regionName;
                            });
                            this.hide(this.activeRegion);
                        } else {
                            el.modal('show', true);
                            this.activeRegion = regionName;
                        }

                        el.one('shown.bs.modal', function(e) {
                            channel.trigger('shown:' + regionName);
                        });
                    }
                });
            return temp;
        },
        generateLayout: function(ModalRegionView, modalOptions) {
            var modalTitle = modalOptions.title,
                modalHeader = modalOptions.headerView,
                ModalButtonControlView = modalOptions.footerView;
            if (modalTitle || modalHeader) {
                var ModalHeaderView;
                if (modalHeader) {
                    ModalHeaderView = modalHeader.extend({
                        className: 'modal-header'
                    });
                } else {
                    var ModalModel = Backbone.Model.extend({
                        defaults: {
                            'modal-title': modalTitle
                        }
                    });
                    var modalModel = new ModalModel();
                    ModalHeaderView = Backbone.Marionette.ItemView.extend({
                        template: BootstrapModalHeaderTemplate,
                        model: modalModel,
                        className: 'modal-header'
                    });
                }
            }

            var ModalButtonControlViewDefault = Backbone.Marionette.ItemView.extend({
                template: _.template("Close"),
                className: 'btn btn-default',
                tagName: 'button',
                attributes: {
                    'type': 'button',
                    'data-dismiss': 'modal',
                    'id': 'modal-close-button'
                }
            });

            var ModalLayoutView = Backbone.Marionette.LayoutView.extend({
                template: BootstrapModalTemplate,
                model: new Backbone.Model(),
                initialize: function() {
                    this.modalRegionView = ModalRegionView;
                    if (ModalButtonControlView) {
                        this.modalButtonControlView = new ModalButtonControlView();
                    } else {
                        this.modalButtonControlView = new ModalButtonControlViewDefault();
                    }
                    if (ModalHeaderView) {
                        this.modalHeaderView = new ModalHeaderView();
                    }
                    if (modalOptions.size === 'large') {
                        this.model.set('sizeClass', 'modal-lg');
                    } else if (modalOptions.size === 'xlarge') {
                        this.model.set('sizeClass', 'modal-xlg');
                    }
                    if (this.model.get('sizeClass')) {
                        this.$el.addClass(this.model.get('sizeClass'));
                    }
                },
                className: 'modal-dialog',
                events: {
                    'keydown input': function(e) {
                        if (e.which === 13) { //Prevent IE bug which issues data-dismiss in a modal on enter key
                            e.preventDefault();
                        }
                    }
                },
                regions: {
                    modalHeaderRegion: '#modal-header',
                    modalRegion: '#modal-body',
                    modalButtonControlRegion: '#modal-footer'
                },
                onRender: function() {
                    this.modalRegion.show(this.modalRegionView);
                    this.modalButtonControlRegion.show(this.modalButtonControlView);
                    if (this.modalHeaderView) {
                        this.modalHeaderRegion.show(this.modalHeaderView);
                    }
                    var el = this.$el;
                    this.$('[data-dismiss="modal"]').on('click', function(e) { //broadcast that we need to close all modals in this workflow
                        e.preventDefault();
                        el.trigger('close.bs.modal');
                    });
                    this.$('[data-dismiss="modal"]').on('keydown', function(e) { //508 for enter key on close triggers
                        if (e.which === 13 || e.keyCode === 13) {
                            e.preventDefault();
                            el.trigger('close.bs.modal');
                        }
                    });
                },
            });
            return ModalLayoutView;
        }
    };
    return Modal;
});

redpajama_set_name: RedPajamaGithub


text:
<!--L
  Copyright Oracle Inc

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details.
L-->

<project basedir="." default="all" name="JMX">

    <property name="src" value="./src"/>
    <property name="classes" value="./classes"/>
    <property name="server.dir" value="../.."/>

    <path id="classpath.jmx">
        <pathelement path="${server.dir}/exist.jar"/>
        <fileset dir="${server.dir}/lib/core">
            <include name="excalibur-cli-*.jar"/>
            <include name="log4j-*.jar"/>
        </fileset>
    </path>

    <condition property="java14-only">
        <equals arg1="${ant.java.version}" arg2="1.4"/>
    </condition>

    <target name="check-java-version" if="java14-only">
        <echo message="Java version warning"/>
        <echo message="--------------------"/>
        <echo message="Java 5 is required to use eXist's management extensions (JMX) "/>
        <echo message="interface. Your version is ${ant.java.version}. The JMX interface "/>
        <echo message="will be disabled."/>
    </target>

    <target name="all">
        <antcall target="check-java-version"/>
        <antcall target="jar"/>
    </target>

    <target name="prepare" unless="java14-only">
        <mkdir dir="${classes}"/>
    </target>

    <target name="clean">
        <delete file="${server.dir}/lib/extensions/exist-jmx.jar"/>
        <delete dir="${classes}"/>
    </target>

    <target name="compile" depends="prepare" unless="java14-only">
        <echo message="Compiling JMX agent and client tools"/>
        <echo message="-----------------------------------------"/>
        <javac debug="true" destdir="${classes}" encoding="UTF-8"
            optimize="${build.optimize}" srcdir="${src}"
            source="1.5" target="1.5">
            <classpath>
                <path refid="classpath.jmx"/>
            </classpath>
        </javac>
    </target>

    <target name="jar" depends="compile" unless="java14-only">
        <echo message="Don't forget to resign the jar files when needed:"/>
        <echo message="./build.sh -f build/scripts/jarsigner.xml jnlp-sign-exist"/>
        <echo message="-----------------------------------------"/>

        <jar destfile="${server.dir}/lib/extensions/exist-jmx.jar" basedir="${classes}"
            keepcompression="true" update="true"/>
    </target>
</project>


text:
from connection import get_connections, create_connection, update_connection,\
                       connection, connections, connection_clone, connection_delete
from connector import get_connectors, connectors, connector
from framework import framework
from job import get_jobs, create_job, update_job,\
                job, jobs, job_clone, job_delete,\
                job_start, job_stop, job_status
from submission import get_submissions, submissions


text:
package oodesign;

import java.util.ArrayList;

public class Deck<T extends Card> {
	protected ArrayList<T> cards = new ArrayList<T>();
	private int dealtIndex = 0;

	public void shuffle(){}

	public int remainingCards(){
		return cards.size() - dealtIndex;
	}

	public void dealHand(int number){}

}


text:
import { HammerGesturesPluginCommon } from './hammer_common';
export declare class HammerGesturesPlugin extends HammerGesturesPluginCommon {
    constructor();
    supports(eventName: string): boolean;
    addEventListener(element: any, eventName: string, handler: Function, shouldSupportBubble: boolean): void;
}


text:
import React, { Component } from 'react';

import {
  Badge,
  Button,
  ButtonDropdown,
  Card,
  CardBody,
  CardFooter,
  CardHeader,
  Col,
  Collapse,
  DropdownItem,
  DropdownMenu,
  DropdownToggle,
  Fade,
  Form,
  FormGroup,
  FormText,
  FormFeedback,
  Input,
  InputGroup,
  InputGroupAddon,
  InputGroupText,
  Label,
  Row
} from 'reactstrap';

import Lista from './Lista.js';

class Vendas extends Component {
  constructor(props) {
    super(props);

    this.state = {
      resumo: {
        "periodo": {
          "id": 0,
          "dataInicial": null,
          "dataFinal": null,
          "valorEmAberto": 0,
          "valorCaixa": 0,
          "createdAt": null,
          "updatedAt": null
        },
        "vendas": {
          "valorTotal": 0,
          "valorDesconto": 0,
          "valorFinal": 0,
          "valorAcrescimo": 0,
          "valorPago": 0,
          "valorCC": 0,
          "valorCD": 0,
          "valorD": 0,
          "quantidadeItens": 0,
          "totalVendas": 0
        }
      },
      lista: {
        title: "",
        header: [

        ],
        data: [
          [

          ]
        ]
      }
    };
  }

  componentDidMount() {
    let request = 'http://localhost:8000/api/';
    fetch(request + 'vendas')
      .then((response) => {
        return response.json();

      }).then((data) => {

        this.setState({lista: data});
      })
      .then(()=>{

        return fetch(request + 'vendas/resumoPeriodo')
      })
      .then((response) => {

        return response.json();
      }).then((data) => {

        this.setState({resumo:data});
      });
  }

  render() {
      let formarter = Intl.NumberFormat('pt-BR', { style: 'currency',  currency: 'BRL' });

    return (

      <Row>
      <Col xs="4">
            <Card>
              <CardHeader>Resumo</CardHeader>
              <CardBody>

Total de vendas

{this.state.resumo.vendas.totalVendas}

Valor em vendas

{formarter.format(this.state.resumo.vendas.valorTotal)}

Valor em aberto

{formarter.format(this.state.resumo.vendas.valorTotal)}

Desconto

{formarter.format(this.state.resumo.vendas.valorDesconto)}

Acréscimo

{formarter.format(this.state.resumo.vendas.valorAcrescimo)}

Caixa

{formarter.format(this.state.resumo.periodo.valorCaixa)}

Valor final

{formarter.format(this.state.resumo.vendas.valorFinal)}

              </CardBody>
            </Card>
          </Col>
        </Row>
        <Row>
          <Col xs="12">
          <Lista title={this.state.lista.title} header={this.state.lista.header} data={this.state.lista.data}/>
          </Col>
        </Row>

    );
  }
}

export default Vendas;


text:
((Dropzone) => {
  Dropzone.options.synapseImageUpload = {
    maxFilesize: 2,
    init: function() {
        this.on('error', function(file, response) {
            $(file.previewElement).find('.dz-error-message').text(response.error_full_message);
        });
    }
  }
})(Dropzone);


text:
//*******************************************************************************************************
//  RuntimeConfigurationService.svc.cs - Gbtc
//
//  Tennessee Valley Authority, 2009
//  No copyright is claimed pursuant to 17 USC § 105.  All Other Rights Reserved.
//
//  Code Modification History:
//  -----------------------------------------------------------------------------------------------------
//  11/25/2009 - Pinal C. Patel
//       Generated original version of source code.
//  11/07/2010 - Pinal C. Patel
//       Modified to fix breaking changes made to SelfHostingService.
//
//*******************************************************************************************************

using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Web;
using GSF.Configuration;
using GSF.Data;
using GSF.ServiceModel;

namespace substationSBGServices
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class RuntimeConfigurationService : SelfHostingService, IRuntimeConfigurationService
    {
        #region [ Members ]

        // Fields
        private string m_connectionString;

        #endregion

        #region [ Constructors ]

        /// <summary>
        /// Initializes a new instance of the <see cref="RuntimeConfigurationService"/> class.
        /// </summary>
        public RuntimeConfigurationService()
            : base()
        {
            PersistSettings = true;
        }

        #endregion

        #region [ Properties ]

        /// <summary>
        /// Gets or sets the connection string to be used for connection the SQL Server database from where configuration is to be retrieved.
        /// </summary>
        public string ConnectionString
        {
            get
            {
                return m_connectionString;
            }
            set
            {
                m_connectionString = value;
            }
        }

        #endregion

        #region [ Methods ]

        /// <summary>
        /// Saves <see cref="RuntimeConfigurationService"/> settings to the config file if the <see cref="RestService.PersistSettings"/> property is set to true.
        /// </summary>
        public override void SaveSettings()
        {
            base.SaveSettings();
            if (PersistSettings)
            {
                // Ensure that settings category is specified.
                if (string.IsNullOrEmpty(SettingsCategory))
                    throw new InvalidOperationException("SettingsCategory property has not been set");

                // Save settings under the specified category.
                ConfigurationFile config = ConfigurationFile.Current;
                CategorizedSettingsElement element = null;
                CategorizedSettingsElementCollection settings = config.Settings[SettingsCategory];
                element = settings["ConnectionString", true];
                element.Update(m_connectionString, element.Description, element.Encrypted);
                config.Save();
            }
        }

        /// <summary>
        /// Loads saved <see cref="RuntimeConfigurationService"/> settings from the config file if the <see cref="RestService.PersistSettings"/> property is set to true.
        /// </summary>
        public override void LoadSettings()
        {
            base.LoadSettings();
            if (PersistSettings)
            {
                // Ensure that settings category is specified.
                if (string.IsNullOrEmpty(SettingsCategory))
                    throw new InvalidOperationException("SettingsCategory property has not been set");

                // Load settings from the specified category.
                ConfigurationFile config = ConfigurationFile.Current;
                CategorizedSettingsElementCollection settings = config.Settings[SettingsCategory];
                settings.Add("ConnectionString", m_connectionString, "Connection string for connecting to the SQL Server database containing the configuration.", true);
                ConnectionString = settings["ConnectionString"].ValueAs(m_connectionString);
            }
        }

        public Stream GetConfiguration(string nodeName)
        {
            // Initialize service if uninitialized.
            Initialize();

            // Check for the required parameters.
            if (string.IsNullOrEmpty(nodeName))
                throw new ArgumentNullException("nodeName");

            if (string.IsNullOrEmpty(m_connectionString))
                throw new ArgumentNullException("ConnectionString");

            SqlConnection database = null;
            DataSet configuration = new DataSet("Iaon"); ;
            MemoryStream output = new MemoryStream();
            try
            {
                // Open connection to the database.
                database = new SqlConnection(m_connectionString);
                database.Open();

                // Lookup ID of the specified node.
                object nodeID = database.ExecuteScalar(string.Format("SELECT ID FROM Node WHERE [Name] = '{0}'", nodeName));
                if (nodeID == null)
                    throw new ArgumentException("nodeName is not valid.");

                // Add configuration entities table to the output.
                DataTable entities, entity;
                entities = database.RetrieveData("SELECT * FROM ConfigurationEntity WHERE Enabled <> 0 ORDER BY LoadOrder");
                entities.TableName = "ConfigurationEntity";
                configuration.Tables.Add(entities.Copy());

                // Add each configuration entity to the output.
                foreach (DataRow row in entities.Rows)
                {
                    // Load configuration entity data filtered by node ID.
                    entity = database.RetrieveData(string.Format("SELECT * FROM {0} WHERE NodeID = '{1}'", row["SourceName"].ToString(), nodeID.ToString()));
                    entity.TableName = row["RuntimeName"].ToString();

                    // Remove redundant node ID column from the data.
                    entity.Columns.Remove("NodeID");

                    // Add entity configuration data to the output.
                    configuration.Tables.Add(entity.Copy());
                }

                // Extract prepared data in XML format.
                configuration.WriteXml(output);

                // Return formatted output to requestor.
                output.Position = 0;
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/xml";
                WebOperationContext.Current.OutgoingResponse.ContentLength = output.Length;
                return output;
            }
            finally
            {
                // Release used memory.
                if (database != null)
                    database.Dispose();

                if (configuration != null)
                    configuration.Dispose();
            }
        }

        #endregion
    }
}


text:
<?php

/* AcmeTeamBundle:Default:edit.html.twig */
class __TwigTemplate_ccfd0d1a07a370e1c4bae007f9377e4ec8612b383161c32bfd1c284e2ef33c7a extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("::base.html.twig");

        $this->blocks = array(
            'body' => array($this, 'block_body'),
            'content' => array($this, 'block_content'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::base.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 2
    public function block_body($context, array $blocks = array())
    {
        // line 3
        echo "    ";
        $this->displayBlock('content', $context, $blocks);
    }

    public function block_content($context, array $blocks = array())
    {
        // line 4
        echo "

Edit Team

                <form action=\"";
        // line 11
        echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("edit_team", array("id" => $this->getContext($context, "id"))), "html", null, true);
        echo "\" method=\"post\" ";
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getContext($context, "form"), 'enctype');
        echo " class=\"form-group\">
                    ";
        // line 12
        if ((!$this->getAttribute($this->getAttribute($this->getContext($context, "form"), "vars"), "valid"))) {
            // line 13
            echo "

                            ";
            // line 14
            echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "name"), 'errors');
            echo "
                            ";
            // line 15
            echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "designation"), 'errors');
            echo "
                            ";
            // line 16
            echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "skills"), 'errors');
            echo "
                            ";
            // line 17
            echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "image"), 'errors');
            echo "
                            ";
            // line 18
            echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "facebook"), 'errors');
            echo "
                            ";
            // line 19
            echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "twitter"), 'errors');
            echo "
                            ";
            // line 20
            echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "gmail"), 'errors');
            echo "
                            ";
            // line 21
            echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "description"), 'errors');
            echo "

                    ";
        }
        // line 24
        echo "

                        ";
        // line 25
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "name"), 'label', array("label_attr" => array("class" => "control-label col-sm-2"), "label" => "Name: "));
        echo "

                            ";
        // line 27
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "name"), 'widget', array("attr" => array("class" => "form-control", "placeholder" => "Name")));
        echo "

                        ";
        // line 31
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "designation"), 'label', array("label_attr" => array("class" => "control-label col-sm-2"), "label" => "Designation: "));
        echo "

                            ";
        // line 33
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "designation"), 'widget', array("attr" => array("class" => "form-control", "placeholder" => "Designation")));
        echo "

                        ";
        // line 37
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "skills"), 'label', array("label_attr" => array("class" => "control-label col-sm-2"), "label" => "Skills: "));
        echo "

                            ";
        // line 39
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "skills"), 'widget', array("attr" => array("class" => "", "placeholder" => "Skills")));
        echo "

                        ";
        // line 43
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "facebook"), 'label', array("label_attr" => array("class" => "control-label col-sm-2"), "label" => "Facebook: "));
        echo "

                            ";
        // line 45
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "facebook"), 'widget', array("attr" => array("class" => "form-control", "placeholder" => "Facebook")));
        echo "

                        ";
        // line 49
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "twitter"), 'label', array("label_attr" => array("class" => "control-label col-sm-2"), "label" => "Twitter: "));
        echo "

                            ";
        // line 51
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "twitter"), 'widget', array("attr" => array("class" => "form-control", "placeholder" => "Twitter")));
        echo "

                        ";
        // line 55
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "gmail"), 'label', array("label_attr" => array("class" => "control-label col-sm-2"), "label" => "Gmail: "));
        echo "

                            ";
        // line 57
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "gmail"), 'widget', array("attr" => array("class" => "form-control", "placeholder" => "Gmail")));
        echo "

                        ";
        // line 61
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "image"), 'label', array("label_attr" => array("class" => "control-label col-sm-2"), "label" => "Image: "));
        echo "

                            ";
        // line 63
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "image"), 'widget', array("attr" => array("class" => "btn btn-default btn-file")));
        echo "

                        ";
        // line 67
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "image"), 'label', array("label_attr" => array("class" => "control-label col-sm-2"), "label" => "Image: "));
        echo "

                            env, $this->env->getExtension('assets')->getAssetUrl(twig_join_filter(array(0 => "uploads/team/", 1 => $this->getContext($context, "id"), 2 => "/", 3 => $this->getContext($context, "image")))), "html", null, true);
        echo "\" style=\"width:80px; height: 50px;\" />

                        ";
        // line 73
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "description"), 'label', array("label_attr" => array("class" => "control-label col-sm-2"), "label" => "Description: "));
        echo "

                            ";
        // line 75
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getContext($context, "form"), "description"), 'widget', array("attr" => array("class" => "form-control", "placeholder" => "Description")));
        echo "

                        <input type=\"submit\" formnovalidate value=\"Insert\" name=\"insert\" class=\"btn btn-primary\"/>
                        <input type=\"reset\" name=\"Reset\" value=\"Reset\" class=\"btn btn-danger\" onclick=\"javascript:window.location.href = '";
        // line 80
        echo $this->env->getExtension('routing')->getPath("acme_team");
        echo "'\"/>

                </form>
            \t\t\t

    ";
    }

    public function getTemplateName()
    {
        return "AcmeTeamBundle:Default:edit.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  205 => 80,  197 => 75,  192 => 73,  185 => 69,  180 => 67,  173 => 63,  168 => 61,  161 => 57,  156 => 55,  149 => 51,  144 => 49,  137 => 45,  132 => 43,  125 => 39,  120 => 37,  113 => 33,  108 => 31,  101 => 27,  96 => 25,  93 => 24,  87 => 21,  83 => 20,  79 => 19,  75 => 18,  71 => 17,  67 => 16,  63 => 15,  59 => 14,  56 => 13,  54 => 12,  48 => 11,  39 => 4,  32 => 3,  29 => 2,);
    }
}


text:
package com.morazow

import com.twitter.scalding.Tool
import org.apache.hadoop.util.ToolRunner
import org.apache.hadoop.conf.Configuration

trait JobRunner {

  val className: String
  val localModeArgs: Array[String]

  def main(args: Array[String]) {
    if (args.length != 0) {
      // run on cluster, hadoop mode
      ToolRunner.run(new Configuration, new Tool, className +: args)
    } else {
      // run locally
      ToolRunner.run(new Configuration, new Tool, className +: localModeArgs)
    }
  }

}


text:
ig.module(
	'game.entities.projectiles.arrow'
)
.requires(
	'impact.entity'
)

.defines(function(){
	EntityArrow = ig.Entity.extend({
		/* Set up projectile properties */
		animSheet: new ig.AnimationSheet('media/arrow.png', 35, 35),
        size: {x: 30, y: 10},
        offset: {x: 2, y: 12},
		maxVel: {x: 100, y: 0},
		speed: 100,

		/* Set up collision properties */
		type: ig.Entity.TYPE.A,
        checkAgainst: ig.Entity.TYPE.NONE,
        collides: ig.Entity.COLLIDES.ACTIVE,

		/* init method */
		init: function( x, y, settings ) {
			// Define animation frames
			this.addAnim('idle', 0.1, [0]);
			// Read settings from parent object (player.js)
        	this.parent( x , y, settings );
            // Define animation frames
            this.addAnim('idle', 0.1, [0, 1, 2]);
            // Assign velocity based on flip property of player (stored in settings)
            this.vel.x = settings.flip ? -1*this.speed : 1*this.speed;
            // Flip projectile based on player's flip value
            this.currentAnim.flip.x = settings.flip;
            this.hurtTimer = new ig.Timer(1.0);
        },

        /* check method for collisions */
        check: function( other ) {
            other.receiveDamage( 5, this );
            this.kill();
        },

        /* Kill projectile on collision on the x-axis */
        handleMovementTrace: function(res){
            this.parent(res);
            if(res.collision.x){
            	this.kill();
            }
        },

        collideWith: function(other, axis){
            if(other instanceof EntityPlayer){
                ig.game.hurtTimer.reset();
                console.log('Player was hit');
                ig.game.hitSFX.volume = 0.7;
                ig.game.hitSFX.play();
                ig.game.screenshakeIntensity = 10;
                other.receiveDamage(5, this);
                this.kill();
            }

        },

	});
});


text:
include(AddFileDependencies)

macro(add_td_sources srcs)
  file(GLOB tds *.td)
  if( tds )
    source_group("TableGen descriptions" FILES ${tds})
    set_source_files_properties(${tds} PROPERTIES HEADER_FILE_ONLY ON)
    list(APPEND ${srcs} ${tds})
  endif()
endmacro(add_td_sources)

macro(add_header_files srcs)
  file(GLOB hds *.h)
  if( hds )
    set_source_files_properties(${hds} PROPERTIES HEADER_FILE_ONLY ON)
    list(APPEND ${srcs} ${hds})
  endif()
endmacro(add_header_files)

function(llvm_process_sources OUT_VAR)
  set( sources ${ARGN} )
  llvm_check_source_file_list( ${sources} )
  # Create file dependencies on the tablegenned files, if any.  Seems
  # that this is not strictly needed, as dependencies of the .cpp
  # sources on the tablegenned .inc files are detected and handled,
  # but just in case...
  foreach( s ${sources} )
    set( f ${CMAKE_CURRENT_SOURCE_DIR}/${s} )
    add_file_dependencies( ${f} ${TABLEGEN_OUTPUT} )
  endforeach(s)
  if( MSVC_IDE )
    # This adds .td and .h files to the Visual Studio solution:
    add_td_sources(sources)
    add_header_files(sources)
  endif()
  set( ${OUT_VAR} ${sources} PARENT_SCOPE )
endfunction(llvm_process_sources)

function(llvm_check_source_file_list)
  set(listed ${ARGN})
  file(GLOB globbed *.cpp)
  foreach(g ${globbed})
    get_filename_component(fn ${g} NAME)
    list(FIND listed ${fn} idx)
    if( idx LESS 0 )
      message(SEND_ERROR "Found unknown source file ${g}
Please update ${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt\n")
    endif()
  endforeach()
endfunction(llvm_check_source_file_list)


text:
/*Given a string, find out the lexicographically smallest and largest substring of length k.

[Note: Lexicographic order is also known as alphabetic order dictionary order. So "ball" is smaller than "cat", "dog" is smaller than "dorm". Capital letter always comes before smaller letter, so "Happy" is smaller than "happy" and "Zoo" is smaller than "ball".]

Input Format

First line will consist a string containing english alphabets which has at most 1000 characters. 2nd line will consist an integer k.

Output Format

In the first line print the lexicographically minimum substring. In the second line print the lexicographically maximum substring.

*/

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc = new Scanner(System.in);
        String high = "";
        String low  = "";
         String [] a[];
        String input = sc.nextLine();
        int num = sc.nextInt();

        if(input.length() == num){
            System.out.println(input);
            System.out.println(input);
        }
        else{
        for(int i =0 ; i<= input.length()-num ; i++)
            {
           String subString = input.substring(i,i+num);
           if(i == 0){
                low = subString;
            }
           if(subString.compareTo(high)>0){
                high = subString;
            }else if(subString.compareTo(low)<0){
                low = subString;
           }
        }
       }
        System.out.println(low);
        System.out.println(high);
    }
  }


text:
package org.cyclops.integrateddynamics.part.aspect.write.redstone;

import net.minecraft.core.Direction;
import net.minecraftforge.common.util.LazyOptional;
import org.cyclops.cyclopscore.datastructure.DimPos;
import org.cyclops.integrateddynamics.api.block.IDynamicRedstone;
import org.cyclops.integrateddynamics.api.part.PartTarget;

/**
 * Interface for redstone writing the component.
 * @author rubensworks
 */
public interface IWriteRedstoneComponent {

    public void setRedstoneLevel(PartTarget target, int level, boolean strongPower);

    public void setLastPulseValue(PartTarget target, int value);

    public int getLastPulseValue(PartTarget target);

    public void deactivate(PartTarget target);

    public LazyOptional<IDynamicRedstone> getDynamicRedstoneBlock(DimPos dimPos, Direction side);

}


text:
"""
This is a demo shim that accepts incoming webhooks, implemented using Flask.

Run this directly on your development machine or under any WSGI webserver.
The following functions parse the webhook payload, translate and send it to other services.
"""

from loginsightwebhookdemo import app
import logging
import sys

# Define if you want to leverage SSL
SSLCERT = ''
SSLKEY = ''

def main(PORT):
    # Configure logging - overwrite on every start
    logging.basicConfig(filename='li_webhook_shim.log', filemode='w', level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')

    # stdout
    root = logging.getLogger()
    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    ch.setFormatter(formatter)
    root.addHandler(ch)

    logging.info("Please navigate to the below URL for the available routes")

    if (SSLCERT and SSLKEY):
        context = (SSLCERT, SSLKEY)
        app.run(host='0.0.0.0', port=PORT, ssl_context=context, threaded=True, debug=True)
    else:
        app.run(host='0.0.0.0', port=PORT)

if __name__ == "__main__":
    PORT = 5001
    if (len(sys.argv) == 2):
        PORT = sys.argv[1]
    main(PORT)


text:
#pragma once
#include <aws/opsworkscm/OpsWorksCM_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/opsworkscm/model/AccountAttribute.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace OpsWorksCM
{
namespace Model
{
  class AWS_OPSWORKSCM_API DescribeAccountAttributesResult
  {
  public:
    DescribeAccountAttributesResult();
    DescribeAccountAttributesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    DescribeAccountAttributesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     * <p> The attributes that are currently set for the account. </p>
     */
    inline const Aws::Vector<AccountAttribute>& GetAttributes() const{ return m_attributes; }

    /**
     * <p> The attributes that are currently set for the account. </p>
     */
    inline void SetAttributes(const Aws::Vector<AccountAttribute>& value) { m_attributes = value; }

    /**
     * <p> The attributes that are currently set for the account. </p>
     */
    inline void SetAttributes(Aws::Vector<AccountAttribute>&& value) { m_attributes = std::move(value); }

    /**
     * <p> The attributes that are currently set for the account. </p>
     */
    inline DescribeAccountAttributesResult& WithAttributes(const Aws::Vector<AccountAttribute>& value) { SetAttributes(value); return *this;}

    /**
     * <p> The attributes that are currently set for the account. </p>
     */
    inline DescribeAccountAttributesResult& WithAttributes(Aws::Vector<AccountAttribute>&& value) { SetAttributes(std::move(value)); return *this;}

    /**
     * <p> The attributes that are currently set for the account. </p>
     */
    inline DescribeAccountAttributesResult& AddAttributes(const AccountAttribute& value) { m_attributes.push_back(value); return *this; }

    /**
     * <p> The attributes that are currently set for the account. </p>
     */
    inline DescribeAccountAttributesResult& AddAttributes(AccountAttribute&& value) { m_attributes.push_back(std::move(value)); return *this; }

  private:

    Aws::Vector<AccountAttribute> m_attributes;
  };

} // namespace Model
} // namespace OpsWorksCM
} // namespace Aws


text:
import uuid
import datetime
import sqlahelper

from sqlalchemy import Column, ForeignKey, Table, func
from sqlalchemy.types import Unicode, Boolean, DateTime, Integer, Float, Binary
from sqlalchemy.orm import scoped_session, relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

from shapely import wkb
from shapely.geometry import asShape

from shapely.geometry.multipoint import asMultiPoint
from shapely.geometry.multilinestring import asMultiLineString
from shapely.geometry.multipolygon import MultiPolygonAdapter
from geoalchemy2 import Geometry
from geoalchemy2.shape import from_shape

import geojson

engine = sqlahelper.get_engine('mymaps')
Base = declarative_base(bind=engine)
DBSession = scoped_session(sessionmaker(bind=engine))

class Map(Base):
    __tablename__ = 'map'
    uuid = Column(Unicode, primary_key=True,
                  default=lambda: unicode(uuid.uuid4().hex))
    user_login = Column(Unicode(50))
    title = Column(Unicode(50))
    description = Column(Unicode)
    public = Column(Boolean)
    create_date = Column(DateTime, default=datetime.datetime.now)
    update_date = Column(DateTime, onupdate=datetime.datetime.now)
    zoom = Column(Integer)
    x = Column(Float)
    y = Column(Float)
    theme = Column(Unicode)
    bg_layer = Column(Unicode)
    bg_opacity = Column(Float, default=100)
    layers = Column(Unicode)
    layers_indices = Column(Unicode)
    layers_opacity = Column(Unicode)
    layers_visibility = Column(Unicode)
    selected_node = Column(Unicode)
    rating = Column(Float, default=0)
    rating_count = Column(Integer, default=0)
    category_id = Column(Integer, ForeignKey('category.id'), default=999)
    label = Column(Unicode)
    category = relationship('Category', backref='maps')
    features = relationship('Feature', backref='map')

    def get_title(self):
        if self.title is not None:
            return self.title.replace("'", "_")
        return None

    def todict(self):
        def convert_datetime(value):
            if value is not None:
                return value.strftime("%Y-%m-%d %H:%M:%S")
            else:
                return None

        for c in self.__table__.columns:
            if isinstance(c.type, DateTime):
                value = convert_datetime(getattr(self, c.name))
            else:
                value = getattr(self, c.name)
            yield(c.name, value)

    def __iter__(self):
        """Returns an iterable that supports .next()
            so we can do dict(sa_instance)
        """
        return self.todict()

    @staticmethod
    def get(id):
        """ Get map by its id. """
        return DBSession.query(Map).get(id)

    @staticmethod
    def belonging_to(user):
        """ Get maps that belong to user. """
        maps = DBSession.query(Map).filter(
            func.lower(Map.user_login) == func.lower(user)) \
            .order_by("category_id asc,title asc").all()

        return [{'title': map.title,
                 'uuid': map.uuid,
                 'public': map.public,
                 'create_date': map.create_date,
                 'update_date': map.update_date,
                 'category': map.category.name
                 if map.category_id is not None else None,
                 'owner': map.user_login.lower()} for map in maps]

class Feature(Base):
    __tablename__ = 'feature'
    __template__ = 'tooltips/category.mako'

    id = Column(Integer, primary_key=True)
    name = Column(Unicode(50))
    description = Column(Unicode)
    image = Column(Unicode(255))
    thumbnail = Column(Unicode(255))
    color = Column(Unicode(255))
    stroke = Column(Integer, default=2)
    is_label = Column(Boolean, default=False)
    is_circle = Column(Boolean, default=False)
    linestyle = Column(Integer, default=0)
    show_orientation = Column(Boolean, default=False)
    geometry = Column(Geometry(srid=2169))
    map_id = Column(Unicode, ForeignKey('map.uuid'))
    symbol_id = Column(Integer)
    size = Column(Float, default=10)
    angle = Column(Float, default=0)
    font_size = Column(Integer, default=15)
    opacity = Column(Float, default=0.5)
    shape = Column(Unicode(255))
    last_modified_by = Column(Unicode(50))
    display_order = Column(Integer, default=0)

    def __init__(self, feature=None):
        if feature:
            self.__update__(feature)

    def __update__(self, feature):
        try:
            order = feature.properties.get('display_order')
            self.display_order = order
        except:
            self.display_order = 0
        self.name = feature.properties.get('name')
        self.description = feature.properties.get('description')
        self.thumbnail = feature.properties.get('thumbnail')
        self.image = feature.properties.get('image')
        self.color = feature.properties.get('color')
        self.stroke = feature.properties.get('stroke')
        self.is_label = feature.properties.get('isLabel')
        self.is_circle = feature.properties.get('isCircle')
        self.show_orientation = feature.properties.get('showOrientation')
        linestyle = feature.properties.get('linestyle')
        self.linestyle = 0 if linestyle == 'plain' else 1\
            if linestyle == 'dashed' else 2\
            if linestyle == 'dotted' else 0
        self.shape = feature.properties.get('shape')
        size = feature.properties.get('size')
        self.size = size if size is not None and unicode(size).isnumeric()\
            else 10
        angle = feature.properties.get('angle')
        try:
            self.angle = float(angle)
        except TypeError:
            self.angle = 0
        font_size = feature.properties.get('fontSize')
        self.font_size = font_size if font_size is not None and\
            unicode(font_size).isnumeric() else 15
        symbol_id = feature.properties.get('symbolId')
        self.symbol_id = None if symbol_id is not None and\
            len(unicode(symbol_id)) == 0\
            else symbol_id

        opacity = feature.properties.get('opacity')
        self.opacity = opacity if opacity is not None and\
            unicode(opacity).isnumeric() else 0.5

        if hasattr(feature.geometry, "__geo_interface__"):
            ob = feature.geometry.__geo_interface__
        else:
            ob = feature.geometry
        geom_type = ob.get("type").lower()

        if geom_type != 'geometrycollection':
            # openlayers gpx writter creates a 4 dimension geometry and
            # shapely does not allow if for linestring.
            if geom_type == 'linestring':
                feature.geometry.coordinates = \
                    [coordinate[0:2] for coordinate
                        in feature.geometry.coordinates]
            elif geom_type == 'multilinestring':
                multilinestring = feature.geometry.coordinates
                feature.geometry.coordinates = \
                    [[coord[0:2] for coord in multilinestring[i]]
                        for i in range(len(multilinestring))]

            shape = asShape(feature.geometry)

        else:
            geoms = []
            is_transformable = True
            types = None
            for geom in feature.geometry.geometries:
                if hasattr(geom, "__geo_interface__"):
                    ob = geom.__geo_interface__
                else:
                    ob = geom
                geom_type = ob.get("type").lower()

                if types is None:
                    types = geom_type
                else:
                    is_transformable = types == geom_type
                    if not is_transformable:
                        break

                geoms.append(asShape(geom))
            if is_transformable:
                if types == "point":
                    shape = asMultiPoint(geoms)
                elif types == "linestring":
                    shape = asMultiLineString(geoms)
                elif types == "polygon":
                    shape = MultiPolygonAdapter(geoms, context_type='geojson')
            else:
                shape = None
        # ST_FORCE2D is used because the db only allows geometry with
        # 2 dimensions.
        self.geometry = func.ST_Force2D(from_shape(shape, srid=2169))\
            if shape is not None else None

    @property
    def __geo_interface__(self):
        geometry = wkb.loads(str(self.geometry), True)
        properties = dict(name=self.name,
                          description=self.description,
                          thumbnail=self.thumbnail,
                          image=self.image,
                          color=self.color,
                          stroke=self.stroke,
                          isLabel=self.is_label,
                          isCircle=self.is_circle,
                          showOrientation=self.show_orientation,
                          linestyle='plain' if self.linestyle == 0
                          else 'dashed' if self.linestyle == 1 else 'dotted',
                          fid=self.id,
                          symbolId=self.symbol_id,
                          angle=self.angle if self.angle is not None else 0,
                          size=self.size if self.size is not None else 10,
                          fontSize=self.font_size
                          if self.font_size is not None else 15,
                          opacity=self.opacity
                          if self.opacity is not None else 0.5,
                          shape=self.shape,
                          display_order=self.display_order
                          if self.display_order is not None else 0,
                          )
        return geojson.Feature(id=self.id,
                               geometry=geometry,
                               properties=properties
                               )

    @property
    def geom(self):
        if hasattr(self.geometry, "geom_wkb"):
            return wkb.loads(str(self.geometry.geom_wkb))
        else:
            if hasattr(self, "_shape"):
                return self._shape
            else:
                return None

role_categories = Table('role_categories',
                        Base.metadata,
                        Column('role_id',
                               Integer,
                               ForeignKey('role.id')),
                        Column('category_id',
                               Integer,
                               ForeignKey('category.id')))

class Category(Base):
    __tablename__ = 'category'

    id = Column(Integer, primary_key=True)
    name = Column(Unicode(255))
    allow_labeling = Column(Boolean)

    def __init__(self, name):
        self.name = name

    def todict(self):
        return {'id': self.id,
                'name': self.name,
                'allow_labeling': self.allow_labeling}

    @staticmethod
    def belonging_to(user):
        user_role = DBSession.query(Role).get(user.mymaps_role)
        categories = user_role.categories\
            if user_role.categories is not None else []
        return [category.todict() for category in categories]

    @staticmethod
    def all():
        categories = DBSession.query(Category).all()
        return [category.todict() for category in categories]

class Role(Base):
    __tablename__ = 'role'

    id = Column(Integer, primary_key=True)
    name = Column(Unicode(255))
    categories = relationship(Category, secondary=role_categories)

    def __init__(self, name):
        self.name = name

class Symbols(Base):
    __tablename__ = 'symbols'

    id = Column(Integer, primary_key=True)
    symbol_name = Column(Unicode(255))
    login_owner = Column(Unicode(255))
    symbol = Column(Binary)
    is_public = Column(Boolean)
    synchronized = Column(Boolean, default=False)

class Images(Base):
    __tablename__ = 'images'

    id = Column(Integer, primary_key=True)
    image = Column(Binary)
    name = Column(Unicode(255))
    login_owner = Column(Unicode(255))

class Item(Base):
    __tablename__ = 'item'
    __table_args__ = ({'schema': 'themes_prod', 'autoload': False})

    id = Column(Unicode(255), primary_key=True)
    isgroup = Column(Boolean)
    label = Column(Unicode(255))
    open_expanded = Column(Boolean)
    icon_type = Column(Unicode(10))
    image_format = Column(Unicode(20))
    metadataid = Column(Unicode(50))
    legendname = Column(Unicode(255))
    queryable = Column(Boolean)
    exclusion = Column(Unicode(1000))
    opacity = Column(Float)
    service_url = Column(Unicode(255))
    category_id = Column(Integer)
    server_resolutions = Column(Unicode(255))
    use_client_zoom = Column(Boolean)
    is_wms = Column(Boolean)
    wms_url = Column(Unicode(1000))
    wms_layers = Column(Unicode(2500))
    wms_format = Column(Unicode(20))
    wms_profiles_guichet = Column(Unicode(255))
    is_poi = Column(Boolean)
    id_collection = Column(Integer)


text:
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Cinotam.AbpModuleZero.MultiTenancy;

namespace Cinotam.ModuleZero.AppModule.MultiTenancy.Dto
{
    [AutoMap(typeof(Tenant))]
    public class TenantViewModel : EntityDto<int>
    {
        public string Name { get; set; }
        public string TenancyName { get; set; }
    }
}


text:
<?php

use Mockery as m;

class FilterFactoryTest extends PHPUnit_Framework_TestCase {

    public function tearDown()
    {
        m::close();
    }

    public function setUp()
    {
        $this->factory = new Basset\Factory\FilterFactory(array('foo' => 'FooFilter', 'bar' => array('BarFilter', function($filter)
        {
            $filter->setArgument('foo');
        })), array(), 'testing');

        $this->factory->setLogger(m::mock('Illuminate\Log\Writer'));
    }

    public function testMakeNewFilterInstanceFromString()
    {
        $this->assertInstanceOf('Basset\Filter\Filter', $this->factory->make('FooFilter'));
    }

    public function testMakeFilterInstanceFromExistingFilterInstance()
    {
        $filter = m::mock('Basset\Filter\Filter');
        $this->assertEquals($filter, $this->factory->make($filter));
    }

    public function testMakeFromConfigAlias()
    {
        $filter = $this->factory->make('foo');
        $this->assertEquals('FooFilter', $filter->getFilter());
    }

    public function testMakeFromConfigAliasWithCallback()
    {
        $filter = $this->factory->make('bar');
        $this->assertContains('foo', $filter->getArguments());
    }

}


text:
package guitests.guihandles;

import guitests.GuiRobot;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.control.ListView;
import javafx.stage.Stage;
import seedu.address.TestApp;
import seedu.address.model.person.Person;
import seedu.address.model.person.ReadOnlyPerson;
import seedu.address.testutil.TestUtil;

import java.util.List;
import java.util.Optional;
import java.util.Set;

import static org.junit.Assert.assertTrue;

/**
 * Provides a handle for the panel containing the person list.
 */
public class PersonListPanelHandle extends GuiHandle {

    public static final int NOT_FOUND = -1;
    public static final String CARD_PANE_ID = "#cardPane";

    private static final String PERSON_LIST_VIEW_ID = "#personListView";

    public PersonListPanelHandle(GuiRobot guiRobot, Stage primaryStage) {
        super(guiRobot, primaryStage, TestApp.APP_TITLE);
    }

    public List<ReadOnlyPerson> getSelectedPersons() {
        ListView<ReadOnlyPerson> personList = getListView();
        return personList.getSelectionModel().getSelectedItems();
    }

    public ListView<ReadOnlyPerson> getListView() {
        return getNode(PERSON_LIST_VIEW_ID);
    }

    /**
     * Returns true if the list is showing the person details correctly and in correct order.
     * @param persons A list of person in the correct order.
     */
    public boolean isListMatching(ReadOnlyPerson... persons) {
        return this.isListMatching(0, persons);
    }

    /**
     * Clicks on the ListView.
     */
    public void clickOnListView() {
        Point2D point = TestUtil.getScreenMidPoint(getListView());
        guiRobot.clickOn(point.getX(), point.getY());
    }

    /**
     * Returns true if the {@code persons} appear as the sub list (in that order) at position {@code startPosition}.
     */
    public boolean containsInOrder(int startPosition, ReadOnlyPerson... persons) {
        List<ReadOnlyPerson> personsInList = getListView().getItems();

        // Return false if the list in panel is too short to contain the given list
        if (startPosition + persons.length > personsInList.size()) {
            return false;
        }

        // Return false if any of the persons doesn't match
        for (int i = 0; i < persons.length; i++) {
            if (!personsInList.get(startPosition + i).getName().fullName.equals(persons[i].getName().fullName)) {
                return false;
            }
        }

        return true;
    }

    /**
     * Returns true if the list is showing the person details correctly and in correct order.
     * @param startPosition The starting position of the sub list.
     * @param persons A list of person in the correct order.
     */
    public boolean isListMatching(int startPosition, ReadOnlyPerson... persons) throws IllegalArgumentException {
        if (persons.length + startPosition != getListView().getItems().size()) {
            throw new IllegalArgumentException("List size mismatched\n" +
                    "Expected " + (getListView().getItems().size() - 1) + " persons");
        }
        assertTrue(this.containsInOrder(startPosition, persons));
        for (int i = 0; i < persons.length; i++) {
            final int scrollTo = i + startPosition;
            guiRobot.interact(() -> getListView().scrollTo(scrollTo));
            guiRobot.sleep(200);
            if (!TestUtil.compareCardAndPerson(getPersonCardHandle(startPosition + i), persons[i])) {
                return false;
            }
        }
        return true;
    }

    public PersonCardHandle navigateToPerson(String name) {
        guiRobot.sleep(500); //Allow a bit of time for the list to be updated
        final Optional<ReadOnlyPerson> person = getListView().getItems().stream()
                                                    .filter(p -> p.getName().fullName.equals(name))
                                                    .findAny();
        if (!person.isPresent()) {
            throw new IllegalStateException("Name not found: " + name);
        }

        return navigateToPerson(person.get());
    }

    /**
     * Navigates the listview to display and select the person.
     */
    public PersonCardHandle navigateToPerson(ReadOnlyPerson person) {
        int index = getPersonIndex(person);

        guiRobot.interact(() -> {
            getListView().scrollTo(index);
            guiRobot.sleep(150);
            getListView().getSelectionModel().select(index);
        });
        guiRobot.sleep(100);
        return getPersonCardHandle(person);
    }

    /**
     * Returns the position of the person given, {@code NOT_FOUND} if not found in the list.
     */
    public int getPersonIndex(ReadOnlyPerson targetPerson) {
        List<ReadOnlyPerson> personsInList = getListView().getItems();
        for (int i = 0; i < personsInList.size(); i++) {
            if (personsInList.get(i).getName().equals(targetPerson.getName())) {
                return i;
            }
        }
        return NOT_FOUND;
    }

    /**
     * Gets a person from the list by index
     */
    public ReadOnlyPerson getPerson(int index) {
        return getListView().getItems().get(index);
    }

    public PersonCardHandle getPersonCardHandle(int index) {
        return getPersonCardHandle(new Person(getListView().getItems().get(index)));
    }

    public PersonCardHandle getPersonCardHandle(ReadOnlyPerson person) {
        Set<Node> nodes = getAllCardNodes();
        Optional<Node> personCardNode = nodes.stream()
                .filter(n -> new PersonCardHandle(guiRobot, primaryStage, n).isSamePerson(person))
                .findFirst();
        if (personCardNode.isPresent()) {
            return new PersonCardHandle(guiRobot, primaryStage, personCardNode.get());
        } else {
            return null;
        }
    }

    protected Set<Node> getAllCardNodes() {
        return guiRobot.lookup(CARD_PANE_ID).queryAll();
    }

    public int getNumberOfPeople() {
        return getListView().getItems().size();
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Core;

namespace Azure.AI.MetricsAdvisor.Models
{
    /// <summary>
    /// Sometimes it's inconvenient to treat every data point outside of an expected range as an anomaly. Transient
    /// fluctuations may occur depending on the nature of the data being monitored. A suppress condition makes it
    /// possible to ignore an initial group of anomalous points, treating them as normal, and start detecting
    /// anomalies only when a specified threshold is exceeded. As soon as a new anomalous data point is detected,
    /// the service peeks at the latest ingested points of the time series it belongs. If the amount of anomalous
    /// points exceed a specified ratio, the current point will be labeled as an anomaly.
    /// </summary>
    public partial class SuppressCondition
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SuppressCondition"/> class.
        /// </summary>
        /// <param name="minimumNumber">
        /// The amount of data points to peek at when looking back on the previously ingested data.
        /// Must include the most recent point, so value must be at least 1.
        /// </param>
        /// <param name="minimumRatio">
        /// The minimum percentage of anomalous values that must be present in the latest ingested data
        /// points to consider the current point an anomaly. Value is between (0, 100].
        /// </param>
        public SuppressCondition(int minimumNumber, double minimumRatio)
        {
            MinimumNumber = minimumNumber;
            MinimumRatio = minimumRatio;
        }

        /// <summary>
        /// The amount of data points to peek at when looking back on the previously ingested data.
        /// Must include the most recent point, so value must be at least 1.
        /// </summary>
        [CodeGenMember("MinNumber")]
        public int MinimumNumber { get; set; }

        /// <summary>
        /// The minimum percentage of anomalous values that must be present in the latest ingested
        /// data points to consider the current point an anomaly. Value is between (0, 100].
        /// </summary>
        [CodeGenMember("MinRatio")]
        public double MinimumRatio { get; set; }

        internal SuppressConditionPatch GetPatchModel() => new SuppressConditionPatch()
        {
            MinNumber = MinimumNumber,
            MinRatio = MinimumRatio
        };
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>Maintenance Tracker: IconPickerViewController Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Maintenance Tracker
    1.0

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Files Functions Variables Properties

Properties |
List of all members

IconPickerViewController Class Reference

#import <IconPickerViewController.h>

Inheritance diagram for IconPickerViewController:

  <map id="IconPickerViewController_map" name="IconPickerViewController_map">
</map>

Properties

id

< IconPickerViewControllerDelegate > 	delegate

Detailed Description

Definition at line 19 of file IconPickerViewController.h.

Property Documentation

          - (id<IconPickerViewControllerDelegate>) delegate

readwritenonatomicweak

Definition at line 21 of file IconPickerViewController.h.

The documentation for this class was generated from the following file:

/Users/Kalai/Desktop/classes/IconPickerViewController.h

IconPickerViewController

Generated on Sun Jul 28 2013 17:51:22 for Maintenance Tracker by

     1.8.4


text:
<?php
namespace Tagged\Rest;

class Schema {
    protected $_schema;
    function __construct($config){
        $this->_schema = array();
    }

    public function get(){
        return $this->_schema;
    }

    static function build($config=array()){
        $schema = new static($config);
        return $schema->get();
    }

    public static function __callStatic($method, $args) {
        $class = "\\Tagged\Rest\\Schema\\$method";
        return forward_static_call_array(
            array($class,'build'),
            $args
        );
    }
}


text:
package types

import (
	"errors"
	"strings"
)

// AerospikeError implements error interface for aerospike specific errors.
// All errors returning from the library are of this type.
// Errors resulting from Go's stdlib are not translated to this type, unless
// they are a net.Timeout error.
type AerospikeError struct {
	error

	resultCode ResultCode
}

// ResultCode returns the ResultCode from AerospikeError object.
func (ase AerospikeError) ResultCode() ResultCode {
	return ase.resultCode
}

// New AerospikeError generates a new AerospikeError instance.
// If no message is provided, the result code will be translated into the default
// error message automatically.
func NewAerospikeError(code ResultCode, messages ...string) error {
	if len(messages) == 0 {
		messages = []string{ResultCodeToString(code)}
	}

	err := errors.New(strings.Join(messages, " "))
	return AerospikeError{error: err, resultCode: code}
}


text:
'use strict';

goog.provide('grrUi.appController.module');

goog.require('grrUi.core.module');
goog.require('grrUi.flow.module');
goog.require('grrUi.hunt.module');
goog.require('grrUi.semantic.module');

/**
 * Main GRR UI application module.
 */
grrUi.appController.module = angular.module('grrUi.appController',
                                            [grrUi.core.module.name,
                                             grrUi.hunt.module.name,
                                             grrUi.flow.module.name,
                                             grrUi.semantic.module.name]);

grrUi.appController.module.controller('GrrUiAppController', function() {});


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Champignons de France, Discom. 120 (1882)

#### Original name
Peziza polygoni Lasch

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans>

    <jupiter base-package="com.bytebeats.jupiter" />

    <bean id="userDao" class="com.bytebeats.jupiter.demo.dao.UserDaoImpl" scope="singleton" init-method="init" ></bean>

    <bean id="userService" class="com.bytebeats.jupiter.demo.service.UserServiceImpl">
        <property name="userDao" ref="userDao"></property>
    </bean>

    <bean id="userController" class="com.bytebeats.jupiter.demo.controller.UserController">
        <property name="userService" ref="userService"></property>
    </bean>
</beans>


text:
package fr.blogre.goupil;

/**
 * Layout to render view
 * @author jean-baptiste
 *
 */
public class Layout {

	public String header;
	public String footer;

}


text:
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    qmlRegisterType<WaterfallItem>("hu.timur", 1, 0, "Waterfall");

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:///desktop/main.qml")));

    return app.exec();
}


text:
using System;
using Binarysharp.MemoryManagement.Internals;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MemorySharpTests.Internals
{
    [TestClass]
    public class MarshalTypeTests
    {
        /// <summary>
        /// Mashals a double object into an array of bytes.
        /// </summary>
        [TestMethod]
        public void ToByteArrayDoubleType()
        {
            // Arrange
            const double originalValue = 3.141592;
            var valueInBytes = BitConverter.GetBytes(originalValue);

            // Act
            var ret = MarshalType<double>.ObjectToByteArray(originalValue);

            // Assert
            CollectionAssert.AreEqual(valueInBytes, ret, "Both variables aren't equal.");
        }

        /// <summary>
        /// Marshals a Point structure in and out a block of unmanaged memory.
        /// </summary>
        [TestMethod]
        public void ToManagedObjectPointStruct()
        {
            // Arrange
            var customStruct = Resources.CustomStruct;

            // Act
            var byteArray = MarshalType<Point>.ObjectToByteArray(customStruct);
            var customStruct2 = MarshalType<Point>.ByteArrayToObject(byteArray);

            // Assert
            Assert.AreEqual(customStruct, customStruct2, "Both structures are not equal.");
        }

        /// <summary>
        /// Converts a pointer to a long type.
        /// </summary>
        [TestMethod]
        public void PtrToObjectLong()
        {
            // Arrange
            var ptr = new IntPtr(32);

            // Act
            var value = MarshalType<long>.PtrToObject(Resources.MemorySharp, ptr);

            // Assert
            Assert.AreEqual(32, value);
        }

        /// <summary>
        /// Converts a pointer to a structure.
        /// </summary>
        [TestMethod]
        public void PtrToObjectString()
        {
            // Arrange
            var point = Resources.CustomStruct;
            var sharp = Resources.MemorySharp;

            // Act
            using (var memory = sharp.Memory.Allocate(MarshalType<Point>.Size))
            {
                memory.Write(point);
                var ret = MarshalType<Point>.PtrToObject(sharp, memory.BaseAddress);

                // Assert
                Assert.AreEqual(point, ret);
            }
        }
    }
}


text:
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.

/*******************************************************************
* Purpose: InternalHelper
*******************************************************************/
using System;
using System.CodeDom;
using System.Collections;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Windows.Automation;
using System.Windows;

namespace InternalHelper.Tests.Patterns
{
	using InternalHelper;
	using InternalHelper.Tests;
	using InternalHelper.Enumerations;
	using Microsoft.Test.UIAutomation;
	using Microsoft.Test.UIAutomation.Core;
	using Microsoft.Test.UIAutomation.TestManager;
	using Microsoft.Test.UIAutomation.Interfaces;

    /// -----------------------------------------------------------------------
    ///
    /// -----------------------------------------------------------------------
    public class GridPatternWrapper : PatternObject
    {
        #region Variables

        // Pattern variable
        GridPattern m_pattern;

        #endregion Variables

		/// -------------------------------------------------------------------
		///
		/// -------------------------------------------------------------------
		internal GridPatternWrapper(AutomationElement element, string testSuite, TestPriorities priority, TypeOfControl typeOfControl, TypeOfPattern typeOfPattern, string dirResults, bool testEvents, IApplicationCommands commands)
            :
            base(element, testSuite, priority, typeOfControl, typeOfPattern, dirResults, testEvents, commands)
        {
            m_pattern = (GridPattern)GetPattern(m_le, m_useCurrent, GridPattern.Pattern);
        }

        #region Properties

        internal int pattern_getColumnCount
        {
            get
            {
                if (m_useCurrent)
                    return m_pattern.Current.ColumnCount;
                else
                    return m_pattern.Cached.ColumnCount;
            }
        }
        internal int pattern_getRowCount
        {
            get
            {
                if (m_useCurrent)
                    return m_pattern.Current.RowCount;
                else
                    return m_pattern.Cached.RowCount;
            }
        }

        #endregion Properties

        #region Methods

        internal AutomationElement pattern_GetItem(int row, int column, bool expectedException, CheckType checkType)
        {
            AutomationElement element = null;

            string call = "GetItem(" + row + ", " + column + ")";
            try
            {
                element = m_pattern.GetItem(row, column);
            }
            catch (InvalidOperationException e)
            {
                if (!expectedException)
                    ThrowMe(checkType, call + " threw an expection unexpectedly : " + e.Message);
                Comment("Successfully called " + call + " with exception thrown as expected");
                return null;
            }

            if (expectedException)
                ThrowMe(checkType, call + " did not throw an expection as expected");

            Comment("Successfully called " + call + " without an exception thrown");
            return element;

        }

        #endregion Methods
    }
}

namespace Microsoft.Test.UIAutomation.Tests.Patterns
{
    using InternalHelper;
    using InternalHelper.Tests;
    using InternalHelper.Tests.Patterns;
    using InternalHelper.Enumerations;
    using Microsoft.Test.UIAutomation;
    using Microsoft.Test.UIAutomation.Core;
    using Microsoft.Test.UIAutomation.TestManager;
    using Microsoft.Test.UIAutomation.Interfaces;

    /// -----------------------------------------------------------------------
    ///
    /// -----------------------------------------------------------------------
    public sealed class GridTests : GridPatternWrapper
    {
        #region Member variables

        const string THIS = "GridTests";

        #endregion Member variables

		/// -------------------------------------------------------------------
		///
		/// -------------------------------------------------------------------
		public const string TestSuite = NAMESPACE + "." + THIS;

		/// -------------------------------------------------------------------
		///
		/// -------------------------------------------------------------------
		public static readonly string TestWhichPattern = Automation.PatternName(GridPattern.Pattern);

		/// -------------------------------------------------------------------
		///
		/// -------------------------------------------------------------------
		public GridTests(AutomationElement element, TestPriorities priority, string dirResults, bool testEvents, TypeOfControl typeOfControl, IApplicationCommands commands)
            :
            base(element, TestSuite, priority, typeOfControl, TypeOfPattern.Grid, dirResults, testEvents, commands)
        {
        }

        #region Tests

        ///TestCase: GridPattern.S.1.1/2/3
        [TestCaseAttribute("GridPattern.S.1.1/2/3",
             Priority = TestPriorities.Pri1,
             Status = TestStatus.Works,
             Author = "Microsoft Corp.",
             Description = new string[]{
											"Verify that all cells within ColumnCount and RowCount return !null"
										}
             )]
        public void GetCellS11(TestCaseAttribute testCase)
        {
            HeaderComment(testCase);

            AutomationElement le;

            for (int col = 0; col < pattern_getColumnCount; col++)
            {
                for (int row = 0; row < pattern_getRowCount; row++)
                {
                    Comment("Looking at GetCell(" + row + ", " + col + ")");
                    le = pattern_GetItem(row, col, false, CheckType.Verification);
                    if (le == null)
                        ThrowMe(CheckType.Verification, "GetCell(" + row + ", " + col + ") returned null");

                }
            }
            m_TestStep++;
        }

        #endregion Tests

        #region Step/Verification
        #endregion Step/Verification

        #region Library

        #endregion Library

    }
}


text:
#pragma once

#include <cstdint>
#include <string>

#include "envoy/common/random_generator.h"
#include "envoy/event/timer.h"
#include "envoy/http/codec.h"
#include "envoy/http/header_map.h"
#include "envoy/router/router.h"
#include "envoy/runtime/runtime.h"
#include "envoy/upstream/upstream.h"

#include "common/common/backoff_strategy.h"
#include "common/http/header_utility.h"

#include "absl/strings/string_view.h"
#include "absl/types/optional.h"

namespace Envoy {
namespace Router {

/**
 * Wraps retry state for the router.
 */
class RetryStateImpl : public RetryState {
public:
  static RetryStatePtr create(const RetryPolicy& route_policy,
                              Http::RequestHeaderMap& request_headers,
                              const Upstream::ClusterInfo& cluster, const VirtualCluster* vcluster,
                              Runtime::Loader& runtime, Random::RandomGenerator& random,
                              Event::Dispatcher& dispatcher, TimeSource& time_source,
                              Upstream::ResourcePriority priority);
  ~RetryStateImpl() override;

  /**
   * Returns the RetryPolicy extracted from the x-envoy-retry-on header.
   * @param config is the value of the header.
   * @return std::pair<uint32_t, bool> the uint32_t is a bitset representing the
   *         valid retry policies in @param config. The bool is TRUE iff all the
   *         policies specified in @param config are valid.
   */
  static std::pair<uint32_t, bool> parseRetryOn(absl::string_view config);

  /**
   * Returns the RetryPolicy extracted from the x-envoy-retry-grpc-on header.
   * @param config is the value of the header.
   * @return std::pair<uint32_t, bool> the uint32_t is a bitset representing the
   *         valid retry policies in @param config. The bool is TRUE iff all the
   *         policies specified in @param config are valid.
   */
  static std::pair<uint32_t, bool> parseRetryGrpcOn(absl::string_view retry_grpc_on_header);

  // Router::RetryState
  bool enabled() override { return retry_on_ != 0; }
  absl::optional<std::chrono::milliseconds>
  parseResetInterval(const Http::ResponseHeaderMap& response_headers) const override;
  RetryStatus shouldRetryHeaders(const Http::ResponseHeaderMap& response_headers,
                                 DoRetryCallback callback) override;
  // Returns true if the retry policy would retry the passed headers. Does not
  // take into account circuit breaking or remaining tries.
  bool wouldRetryFromHeaders(const Http::ResponseHeaderMap& response_headers) override;
  RetryStatus shouldRetryReset(const Http::StreamResetReason reset_reason,
                               DoRetryCallback callback) override;
  RetryStatus shouldHedgeRetryPerTryTimeout(DoRetryCallback callback) override;

  void onHostAttempted(Upstream::HostDescriptionConstSharedPtr host) override {
    std::for_each(retry_host_predicates_.begin(), retry_host_predicates_.end(),
                  [&host](auto predicate) { predicate->onHostAttempted(host); });
    if (retry_priority_) {
      retry_priority_->onHostAttempted(host);
    }
  }

  bool shouldSelectAnotherHost(const Upstream::Host& host) override {
    return std::any_of(
        retry_host_predicates_.begin(), retry_host_predicates_.end(),
        [&host](auto predicate) { return predicate->shouldSelectAnotherHost(host); });
  }

  const Upstream::HealthyAndDegradedLoad& priorityLoadForRetry(
      const Upstream::PrioritySet& priority_set,
      const Upstream::HealthyAndDegradedLoad& original_priority_load,
      const Upstream::RetryPriority::PriorityMappingFunc& priority_mapping_func) override {
    if (!retry_priority_) {
      return original_priority_load;
    }
    return retry_priority_->determinePriorityLoad(priority_set, original_priority_load,
                                                  priority_mapping_func);
  }

  uint32_t hostSelectionMaxAttempts() const override { return host_selection_max_attempts_; }

private:
  RetryStateImpl(const RetryPolicy& route_policy, Http::RequestHeaderMap& request_headers,
                 const Upstream::ClusterInfo& cluster, const VirtualCluster* vcluster,
                 Runtime::Loader& runtime, Random::RandomGenerator& random,
                 Event::Dispatcher& dispatcher, TimeSource& time_source,
                 Upstream::ResourcePriority priority);

  void enableBackoffTimer();
  void resetRetry();
  bool wouldRetryFromReset(const Http::StreamResetReason reset_reason);
  RetryStatus shouldRetry(bool would_retry, DoRetryCallback callback);

  const Upstream::ClusterInfo& cluster_;
  const VirtualCluster* vcluster_;
  Runtime::Loader& runtime_;
  Random::RandomGenerator& random_;
  Event::Dispatcher& dispatcher_;
  TimeSource& time_source_;
  uint32_t retry_on_{};
  uint32_t retries_remaining_{};
  DoRetryCallback callback_;
  Event::TimerPtr retry_timer_;
  Upstream::ResourcePriority priority_;
  BackOffStrategyPtr backoff_strategy_;
  BackOffStrategyPtr ratelimited_backoff_strategy_{};
  std::vector<Upstream::RetryHostPredicateSharedPtr> retry_host_predicates_;
  Upstream::RetryPrioritySharedPtr retry_priority_;
  uint32_t host_selection_max_attempts_;
  std::vector<uint32_t> retriable_status_codes_;
  std::vector<Http::HeaderMatcherSharedPtr> retriable_headers_;
  std::vector<ResetHeaderParserSharedPtr> reset_headers_{};
  std::chrono::milliseconds reset_max_interval_{};
};

} // namespace Router
} // namespace Envoy


text:
[![Lint Code Base](https://github.com/BretFisher/node-docker-good-defaults/actions/workflows/call-super-linter.yaml/badge.svg)](https://github.com/BretFisher/node-docker-good-defaults/actions/workflows/call-super-linter.yaml)
[![Docker Build](https://github.com/BretFisher/node-docker-good-defaults/actions/workflows/call-docker-build.yaml/badge.svg)](https://github.com/BretFisher/node-docker-good-defaults/actions/workflows/call-docker-build.yaml)

> This tries to be a "good defaults" example of starting to use Node.js in Docker for local development and shipping to production with basic bells, whistles, and best practices. Issues/PR welcome.

**Note** I have more advanced examples of Node.js Dockerfiles and Compose files in my [DockerCon 2022 talk and repository](https://github.com/BretFisher/nodejs-rocks-in-docker).
I also have more about everything Docker and Node.js in my 8 hour video course [Docker for Node.js](https://www.bretfisher.com/node/).

**Also Note**, I have other resources on [Docker and Kubernetes here](https://www.bretfisher.com/docker).

## Local Development Features

- **Dev as close to prod as you can**.
Docker Compose builds a local development image that is just like the production image except for the
below dev-only features needed in the image.
The goal is to have dev environment be as close to test and prod as possible while still giving all the
nice tools to make you a happy dev.
- **Prevent needing node/npm on host**.
This installs `node_modules` outside app root in the container image so local development won't run into a
problem of bind-mounting over it with local source code. This means it will run `npm install`
once on container build and you don't need to run npm on host or on each docker run.
It will re-run on build if you change `package.json`.
- **One line startup**. Uses `docker compose up` for single-line build and run of local
development server.
- **Edit locally while code runs in container**.
Docker Compose uses proper bind-mounts of host source code into container so you can edit
locally while running code in Linux container.
- **Use nodemon in container**. Docker Compose uses nodemon for development for auto-restarting
Node.js in container when you change files on host.
- **Enable debug from host to container**. Opens the inspect port 9229 for using host-based
debugging like chrome tools or VS Code. Nodemon enables `--inspect` by default in Docker Compose.
- **Provides VSCode debug configs and tasks for tests**. for Visual Studio Code fans,
`.vscode` directory has the goods, thanks to @JPLemelin.
- **Small image and quick re-builds**. `COPY` in `package.json` and run `npm install`
**before** `COPY` in your source code. This saves big on build time and keeps the container image lean.
- **Bind-mount package.json**. This allows adding packages in realtime without rebuilding images. e.g.
`docker compose exec -w /opt/node_app node npm install --save <package name>`

## Production-minded Features

- **Use Docker built-in healthchecks**. This uses Dockerfile `HEALTHCHECK` with `/healthz` route to
help Docker know if your container is running properly (example always returns 200, but you get the idea).
- **Proper NODE_ENV use**. Defaults to `NODE_ENV=production` in Dockerfile and overrides to
`development` in docker-compose for local dev.
- **Don't add dev dependencies into the production image**. Proper `NODE_ENV` use means dev dependencies
won't be installed in the image by default. Using Docker Compose will build with them by default.
- **Enables proper SIGTERM/SIGINT for graceful exit**. Defaults to `node index.js` rather than npm
for allowing graceful shutdown of node.
npm doesn't pass SIGTERM/SIGINT properly (you can't ctrl-c when running `docker run` in foreground).
To get `node index.js` to graceful exit, extra signal-catching code is needed.
The `Dockerfile` and `index.js` document the options and links to known issues.
- **Run Node.js in the container as `node` user, not `root`**.
- **Use docker-stack.yml example for Docker Swarm deployments**.

## Assumptions

- You have Docker and Docker Compose installed (Docker Desktop for Mac/Windows/Linux).
- You want to use Docker for local development (i.e. never need to install Node.js/npm on host)
and have dev and prod Docker images be as close as possible.
- You don't want to lose fidelity in your dev workflow. You want a easy environment setup,
using local editors, Node.js debug/inspect, local code repository, while Node.js server runs in a container.
- You use `docker-compose` for local development only (docker-compose was never intended to be
a production deployment tool anyway).
- The `docker-compose.yml` is not meant for `docker stack deploy` in Docker Swarm,
it's meant for happy local development. Use `docker-stack.yml` for Swarm.

## Getting Started

If this was your Node.js app, to start local development you would:

- Running `docker compose up` is all you need. It will:
- Build custom local image enabled for development (nodemon, `NODE_ENV=development`).
- Start container from that image with ports 80 and 9229 open (on localhost).
- Starts with `nodemon` to restart Node.js on file change in host pwd.
- Mounts the pwd to the app dir in container.
- If you need other services like databases,
just add to compose file and they'll be added to the custom Docker network for this app on `up`.
- Compose won't rebuild automatically, so either run `docker compose build` after changing `package.json`
or do what I do and always run `docker compose up --build`.
- Be sure to use `docker compose down` to cleanup after your done dev'ing.

If you wanted to add a package while docker-compose was running your app:

- `docker compose exec -w /opt/node_app node npm install --save <package name>`
- This installs it inside the running container.
- Nodemon will detect the change and restart.
- `--save` will add it to the package.json for next `docker compose build`

To execute the unit-tests, you would:

- Execute `docker compose exec node npm test`, It will:
- Run a process `npm test` in the container.
- You can use the *vscode* to debug unit-tests with config `Docker Test (Attach 9230 --inspect)`,
It will:
  - Start a debugging process in the container and wait-for-debugger, this is done by *vscode tasks*
  - It will also kill a previous debugging process if existing.

## Ways to improve security

### Run Node.js as Non-Root User

As mentioned in the official docker Node.js image docs, Docker runs the image as root.
This can pose a
[potential security issue](https://github.com/nodejs/docker-node/blob/master/docs/BestPractices.md#non-root-user).

As a security best practice, it is recommended for Node.js apps to listen on non-privileged ports
[as mentioned here](https://github.com/i0natan/nodebestpractices/blob/master/sections/security/non-root-user.md).

## Other Resources

- [https://blog.hasura.io/an-exhaustive-guide-to-writing-dockerfiles-for-node-js-web-apps-bbee6bd2f3c4](https://blog.hasura.io/an-exhaustive-guide-to-writing-dockerfiles-for-node-js-web-apps-bbee6bd2f3c4)