text:
'use strict';
var path = require('path');
var generators = require('yeoman-generator');
var yosay = require('yosay');

module.exports = generators.Base.extend({
  constructor: function () {
    generators.Base.apply(this, arguments);

    this.option('theme', {
      type: String,
      required: false,
      defaults: "hermosa",
      desc: "When specified, switches to an alternate theme than the default. Default: hermosa"
    });

    this.option('atmotool', {
      type: Boolean,
      required: false,
      defaults: false,
      desc: 'When specified, will create a local.conf and uploadall script for use with atmotool cli'
    });

  },

  initializing: function () {
    this.generatorsPrefix = this.options.flat ? '' : 'generators/';
    this.themeDir = "theme-" + this.options.theme;
  },

  prompting: {

    // basic questions
    askFor: function () {
      var done = this.async();
      this.log(yosay('Hello! Let\'s create an Akana API Portal Theme customization.'));

      var prompts = [
      /*
        {
          type: 'list',
          name: 'defaultVersion',
          message: 'Customization option',
          choices: ['hero', 'showcase'],
          default: 'hero'
        },
        */
        {
          type: 'input',
          name: 'companyName',
          message: 'Please provide a company name',
          default: 'Custom Starter'
        },
        {
          type: 'input',
          name: 'author',
          message: 'Author',
          default: 'you'
        },
        {
          type: 'input',
          name: 'cmSiteTitle',
          message: 'Title for CM site',
          default: 'API Catalog'
        },
        {
          type: 'input',
          name: 'mainColor',
          message: 'Base color for theme',
          default: '#2683b4'
        },
        {
          type: 'input',
          name: 'landingHeadline',
          message: 'Landing page Headline',
          default: 'Extend your Reach'
        },
        {
          type: 'input',
          name: 'landingTagline',
          message: 'Landing page Tagline',
          default: 'APIs you can trust'
        },
        {
          type: 'list',
          name: 'headerType',
          choices: ['default-transparent', 'default-dark', 'default-wide'],
          message: "Header type",
          default: 'default-transparent'
        },
        { type: 'input',
          name: 'containerHeaderColor',
          message: 'solid header color',
          default: '#2683b4',
          when: function(answers) {
            return answers.headerType === 'default-wide';
          }
        },
        {
          type: 'input',
          name: 'resourceMenuHeaderAppsHover',
          message: 'Hover on Apps Menu Title',
          default: 'My Apps',
          when: function(answers) {
            return answers.headerType === 'default-wide';
          }
        },
        {
          type: 'input',
          name: 'resourceMenuHeaderGroupsHover',
          message: 'Hover on Groups Menu Title',
          default: 'My Groups',
          when: function(answers) {
            return answers.headerType === 'default-wide';
          }
        },
        {
          type: 'input',
          name: 'resourceMenuHeaderApisHover',
          message: 'Hover on APIs Menu Title',
          default: 'My APIs',
          when: function(answers) {
            return answers.headerType === 'default-wide';
          }
        },
        {
          type: 'input',
          name: 'resourceMenuHeaderAdminHover',
          message: 'Hover on Admin Menu Title',
          default: 'Admin',
          when: function(answers) {
            return answers.headerType === 'default-wide';
          }
        },
        {
          type: 'input',
          name: 'headerGradientTop',
          message: 'dark gradient top',
          default: '#5a5b5d',
          when: function (answers) {
            return answers.headerType === 'default-dark';
          }
        },
        {
          type: 'input',
          name: 'headerGradientMiddle',
          message: 'dark gradient middle',
          default: '#47474a',
          when: function (answers) {
            return answers.headerType === 'default-dark';
          }
        },
        {
          type: 'input',
          name: 'headerGradientBottom',
          message: 'dark gradient bottom',
          default: '#3e3f41',
          when: function (answers) {
            return answers.headerType === 'default-dark';
          }
        },
        {
          type: 'input',
          name: 'logoImage',
          message: 'logo image name',
          default: 'atmologo.png'
        },
        {
          type: 'input',
          name: 'logoW',
          message: 'width of the logo (px), max 295px',
          default: 202,
          validate: function (width) {
            return width <= 295;
          }
        },
        {
          type: 'input',
          name: 'landingHeroImage',
          message: 'hero image name',
          default: 'starter_industries.jpg'
        }
      ];

      this.prompt(prompts, function (props) {
        this.props = props;
        this.config.set(props);
        this.companyName = props.companyName;
        this.props.theme = this.options.theme;
        done();
      }.bind(this));

    },

    /* atmotool */
    askAboutAtmotool: function () {

      // if there's --atmotool, continue
      if (!this.options.atmotool) {
        return;
      }

      var done = this.async();
      var prompts = [
        {
          type: 'input',
          name: 'lcCompanyName',
          message: 'a company name',
          default: this.companyName.replace(/\s/g, '').toLowerCase()
        },
        {
          type: 'input',
          name: 'cmUrl',
          message: 'base url for API Portal',
          default: 'http://ent.akana-dev.net:9900'
        },
        {
          type: 'input',
          name: 'cmEmail',
          message: 'admin email for API Portal',
          default: 'administrator@cm.akana.demo'
        },
        {
          type: 'password',
          name: 'cmPassword',
          message: 'admin password for API Portal',
          default: 'password'
        }
      ];

      this.log('Atmotool questions...');
      this.prompt(prompts, function (props) {
        var source = this.props;
        var key;
        // combine new props to existing
        for (key in props) {
          if (props.hasOwnProperty(key)) {
            source[key] = props[key];
          }
        }
        this.config.set(source);
        this.lcCompanyName = props.lcCompanyName;
        done();
      }.bind(this));

    }, /* atmotool end */

  },

  writing: {
    projectfiles: function () {
      /*
      may want to check if dir exists and bail, otherwise
      !fs.existsSync(this.themeDir)
      */

      this.companyDir = 'CM_' + this.companyName.replace(/\s/g, '') + '/';

      this.template('README.md', this.companyDir + 'README.md');
      this.template(this.themeDir + '/' + 'custom.less', this.companyDir +  'custom.less');
      this.directory(this.themeDir + '/' + 'resources',  this.companyDir + 'resources');
      this.directory(this.themeDir + '/' + 'content', this.companyDir + 'content');

      // atmotool
      if (this.options.atmotool) {
        var addInDir = "addin-atmotool";
        this.template(addInDir + '/' + 'template_local.conf', this.companyDir + 'local.conf');
        this.template(addInDir + '/' + 'template_gitignore', this.companyDir + '.gitignore');
        // https://github.com/yeoman/yeoman/issues/1235
        // https://github.com/yeoman/generator/pull/489
        // modern way of copying, as opposed to the above convenience
        // - use either: fs.copy(templatePath, destinationPath)
        // - or: fs.copyTpl(templatePath, destinationPath, modelObject)
        this.fs.copyTpl(
          this.templatePath(addInDir + '/' + 'template_uploadall'),
          this.destinationPath(this.companyDir + 'uploadall'),
          this,
          {
            interpolate: /<%=([\s\S]+?)%>/g
          }
        );
      }

    },

    config: function () {
      this.directory('config');
    }
  },

  end: function () {
    if (this.props.logoImage !== "atmologo.png") {
      this.log('Please remember to place ' + this.props.logoImage + ' in the ' + this.companyDir + 'resources/theme/' + this.options.theme + '/style/images directory.');
    }
    if (this.props.landingHeroImage !== "starter_industries.jpg") {
      this.log('Please remember to place ' + this.props.landingHeroImage + ' in the ' + this.companyDir + 'content/home/landing/images directory.');
    }
    this.log(yosay('Happy Community Managing! - Akana http://akana.com @akanainc'));
  }

});


text:
<?xml version="1.0"?>
<!DOCTYPE modulesynopsis SYSTEM "../style/modulesynopsis.dtd">
<?xml-stylesheet type="text/xsl" href="../style/manual.en.xsl"?>

<modulesynopsis metafile="mod_remoteip.xml.meta">

<name>mod_remoteip</name>
<description>Replaces the original client IP address for the connection
with the useragent IP address list presented by a proxies or a load balancer
via the request headers.
</description>

<status>Base</status>
<sourcefile>mod_remoteip.c</sourcefile>
<identifier>remoteip_module</identifier>

This module is used to treat the useragent which initiated the
    request as the originating useragent as identified by httpd for the
    purposes of authorization and logging, even where that useragent is
    behind a load balancer, front end server, or proxy server.

The module overrides the client IP address for the connection
    with the useragent IP address reported in the request header configured
    with the <directive module="mod_remoteip">RemoteIPHeader</directive> directive.

Additionally, this module implements the server side of
    HAProxy's
    PROXY Protocol when
    using the <directive module="mod_remoteip">RemoteIPProxyProtocol</directive>
    directive.

Once replaced as instructed, this overridden useragent IP address is
    then used for the <module>mod_authz_host</module>
    <directive module="mod_authz_core" name="Require">Require ip</directive>
    feature, is reported by <module>mod_status</module>, and is recorded by
    <module>mod_log_config</module> %a and <module>core</module>
    %a format strings. The underlying client IP of the connection
    is available in the %{c}a format string.

    <note type="warning">It is critical to only enable this behavior from
    intermediate hosts (proxies, etc) which are trusted by this server, since
    it is trivial for the remote useragent to impersonate another
    useragent.</note>

<seealso><module>mod_authz_host</module></seealso>
<seealso><module>mod_status</module></seealso>
<seealso><module>mod_log_config</module></seealso>
<seealso>Proxy Protocol Spec</seealso>

<title>Remote IP Processing</title>

Apache by default identifies the useragent with the connection's
    client_ip value, and the connection remote_host and remote_logname are
    derived from this value. These fields play a role in authentication,
    authorization and logging and other purposes by other loadable
    modules.

mod_remoteip overrides the client IP of the connection with the
    advertised useragent IP as provided by a proxy or load balancer, for
    the duration of the request. A load balancer might establish a long
    lived keepalive connection with the server, and each request will
    have the correct useragent IP, even though the underlying client IP
    address of the load balancer remains unchanged.

When multiple, comma delimited useragent IP addresses are listed in the
    header value, they are processed in Right-to-Left order.  Processing
    halts when a given useragent IP address is not trusted to present the
    preceding IP address.  The header field is updated to this remaining
    list of unconfirmed IP addresses, or if all IP addresses were trusted,
    this header is removed from the request altogether.

In overriding the client IP, the module stores the list of intermediate
    hosts in a remoteip-proxy-ip-list note, which <module>mod_log_config</module>
    can record using the %{remoteip-proxy-ip-list}n format token.
    If the administrator needs to store this as an additional header, this
    same value can also be recording as a header using the directive
    <directive module="mod_remoteip">RemoteIPProxiesHeader</directive>.

    <note><title>IPv4-over-IPv6 Mapped Addresses</title>
    As with httpd in general, any IPv4-over-IPv6 mapped addresses are recorded
    in their IPv4 representation.</note>

    <note><title>Internal (Private) Addresses</title>
    All internal addresses 10/8, 172.16/12, 192.168/16, 169.254/16 and 127/8
    blocks (and IPv6 addresses outside of the public 2000::/3 block) are only
    evaluated by mod_remoteip when <directive module="mod_remoteip">RemoteIPInternalProxy</directive>
    internal (intranet) proxies are registered.</note>

<directivesynopsis>
<name>RemoteIPHeader</name>
<description>Declare the header field which should be parsed for useragent IP addresses</description>
<syntax>RemoteIPHeader <var>header-field</var></syntax>
<contextlist><context>server config</context><context>virtual host</context></contextlist>

<usage>

The <directive module="mod_remoteip">RemoteIPHeader</directive> directive triggers
    <module>mod_remoteip</module> to treat the value of the specified
    <var>header-field</var> header as the useragent IP address, or list
    of intermediate useragent IP addresses, subject to further configuration
    of the <directive module="mod_remoteip">RemoteIPInternalProxy</directive> and
    <directive module="mod_remoteip">RemoteIPTrustedProxy</directive> directives.

    <note type="warning"> Unless these other directives are used, <module>mod_remoteip</module>
    will trust all hosts presenting a non internal address in the
    <directive module="mod_remoteip">RemoteIPHeader</directive> header value.
    </note>

    <example><title>Internal (Load Balancer) Example</title>
    <highlight language="config">
        RemoteIPHeader X-Client-IP
        </highlight>
    </example>

    <example><title>Proxy Example</title>
    <highlight language="config">
        RemoteIPHeader X-Forwarded-For
        </highlight>
    </example>
</usage>
</directivesynopsis>

<directivesynopsis>
<name>RemoteIPInternalProxy</name>
<description>Declare client intranet IP addresses trusted to present the RemoteIPHeader value</description>
<syntax>RemoteIPInternalProxy <var>proxy-ip</var>|<var>proxy-ip/subnet</var>|<var>hostname</var> ...</syntax>
<contextlist><context>server config</context><context>virtual host</context></contextlist>

<usage>

The <directive module="mod_remoteip">RemoteIPInternalProxy</directive> directive adds one
    or more addresses (or address blocks) to trust as presenting a valid
    RemoteIPHeader value of the useragent IP.  Unlike the
    <directive module="mod_remoteip">RemoteIPTrustedProxy</directive> directive, any IP address
    presented in this header, including private intranet addresses, are
    trusted when passed from these proxies.

    <example><title>Internal (Load Balancer) Example</title>
    <highlight language="config">
RemoteIPHeader X-Client-IP
RemoteIPInternalProxy 10.0.2.0/24
RemoteIPInternalProxy gateway.localdomain
        </highlight>
    </example>
</usage>
</directivesynopsis>

<directivesynopsis>
<name>RemoteIPInternalProxyList</name>
<description>Declare client intranet IP addresses trusted to present the RemoteIPHeader value</description>
<syntax>RemoteIPInternalProxyList <var>filename</var></syntax>
<contextlist><context>server config</context><context>virtual host</context></contextlist>

<usage>

The <directive module="mod_remoteip">RemoteIPInternalProxyList</directive> directive specifies
    a file parsed at startup, and builds a list of addresses (or address blocks)
    to trust as presenting a valid RemoteIPHeader value of the useragent IP.

The '#' hash character designates a comment line, otherwise
    each whitespace or newline separated entry is processed identically to
    the <directive module="mod_remoteip">RemoteIPInternalProxy</directive> directive.

    <example><title>Internal (Load Balancer) Example</title>
        <highlight language="config">
RemoteIPHeader X-Client-IP
RemoteIPInternalProxyList conf/trusted-proxies.lst
        </highlight>
    </example>

    <example><title>conf/trusted-proxies.lst contents</title>

# Our internally trusted proxies;
10.0.2.0/24         #Everyone in the testing group
gateway.localdomain #The front end balancer

    </example>
</usage>
</directivesynopsis>

<directivesynopsis>
<name>RemoteIPProxiesHeader</name>
<description>Declare the header field which will record all intermediate IP addresses</description>
<syntax>RemoteIPProxiesHeader <var>HeaderFieldName</var></syntax>
<contextlist><context>server config</context><context>virtual host</context></contextlist>

<usage>

The <directive module="mod_remoteip">RemoteIPProxiesHeader</directive> directive specifies
    a header into which <module>mod_remoteip</module> will collect a list of
    all of the intermediate client IP addresses trusted to resolve the useragent
    IP of the request. Note that intermediate
    <directive module="mod_remoteip">RemoteIPTrustedProxy</directive> addresses are recorded in
    this header, while any intermediate
    <directive module="mod_remoteip">RemoteIPInternalProxy</directive> addresses are discarded.

    <example><title>Example</title>
    <highlight language="config">
RemoteIPHeader X-Forwarded-For
RemoteIPProxiesHeader X-Forwarded-By
    </highlight>
    </example>
</usage>
</directivesynopsis>

<directivesynopsis>
<name>RemoteIPProxyProtocol</name>
<description>Enable or disable PROXY protocol handling</description>
<syntax>RemoteIPProxyProtocol On|Off</syntax>
<contextlist><context>server config</context><context>virtual host</context>
</contextlist>
<compatibility>RemoteIPProxyProtocol is only available in httpd 2.4.26 and newer</compatibility>

<usage>

The <directive>RemoteIPProxyProtocol</directive> directive enables or
    disables the reading and handling of the PROXY protocol connection header.
    If enabled with the On flag, the upstream client must
    send the header every time it opens a connection or the connection will
    be aborted unless it is in the list of disabled hosts provided by <directive
    module="mod_remoteip">RemoteIPProxyProtocolExceptions</directive>
    directive.

While this directive may be specified in any virtual host, it is
    important to understand that because the PROXY protocol is connection
    based and protocol agnostic, the enabling and disabling is actually based
    on ip-address and port. This means that if you have multiple name-based
    virtual hosts for the same host and port, and you enable it any one of
    them, then it is enabled for all them (with that host and port). It also
    means that if you attempt to enable the PROXY protocol in one and disable
    in the other, that won't work; in such a case the last one wins and a
    notice will be logged indicating which setting was being overridden.

    <highlight language="config">
Listen 80
<VirtualHost *:80>
    ServerName www.example.com
    RemoteIPProxyProtocol On

    #Requests to this virtual host must have a PROXY protocol
    # header provided. If it is missing, the connection will
    # be aborted
</VirtualHost>

Listen 8080
<VirtualHost *:8080>
    ServerName www.example.com
    RemoteIPProxyProtocol On
    RemoteIPProxyProtocolExceptions 127.0.0.1 10.0.0.0/8

    #Requests to this virtual host must have a PROXY protocol
    # header provided. If it is missing, the connection will
    # be aborted except when coming from localhost or the
    # 10.x.x.x RFC1918 range
</VirtualHost>
    </highlight>
</usage>
</directivesynopsis>

<directivesynopsis>
<name>RemoteIPProxyProtocolExceptions</name>
<description>Disable processing of PROXY header for certain hosts or networks</description>
<syntax>RemoteIPProxyProtocolExceptions host|range [host|range] [host|range]</syntax>
<contextlist><context>server config</context><context>virtual host</context>
</contextlist>
<compatibility>RemoteIPProxyProtocolExceptions is only available in httpd 2.4.26 and newer</compatibility>

<usage>

The <directive>RemoteIPProxyProtocol</directive> directive enables or
    disables the reading and handling of the PROXY protocol connection header.
    Sometimes it is desirable to require clients to provide the PROXY header, but
    permit other clients to connect without it. This directive allows a server
    administrator to configure a single host or CIDR range of hosts that may do
    so.

</usage>
</directivesynopsis>

<directivesynopsis>
<name>RemoteIPTrustedProxy</name>
<description>Restrict client IP addresses trusted to present the RemoteIPHeader value</description>
<syntax>RemoteIPTrustedProxy <var>proxy-ip</var>|<var>proxy-ip/subnet</var>|<var>hostname</var> ...</syntax>
<contextlist><context>server config</context><context>virtual host</context></contextlist>

<usage>

The <directive module="mod_remoteip">RemoteIPTrustedProxy</directive>
    directive restricts which peer IP addresses (or address blocks) will be
    trusted to present  a valid RemoteIPHeader value of the useragent IP.

 Unlike the <directive module="mod_remoteip">RemoteIPInternalProxy</directive> directive, any intranet
    or private IP address reported by such proxies, including the 10/8, 172.16/12,
    192.168/16, 169.254/16 and 127/8 blocks (or outside of the IPv6 public
    2000::/3 block) are not trusted as the useragent IP, and are left in the
    <directive module="mod_remoteip">RemoteIPHeader</directive> header's value.

    <note type="warning">By default, <module>mod_remoteip</module> will trust
    all hosts presenting a non internal address in the
    <directive module="mod_remoteip">RemoteIPHeader</directive> header value.
    </note>

    <example><title>Trusted (Load Balancer) Example</title>
        <highlight language="config">
RemoteIPHeader X-Forwarded-For
RemoteIPTrustedProxy 10.0.2.16/28
RemoteIPTrustedProxy proxy.example.com
        </highlight>
    </example>
</usage>
</directivesynopsis>

<directivesynopsis>
<name>RemoteIPTrustedProxyList</name>
<description>Restrict client IP addresses trusted to present the RemoteIPHeader value</description>
<syntax>RemoteIPTrustedProxyList <var>filename</var></syntax>
<contextlist><context>server config</context><context>virtual host</context></contextlist>

<usage>

The <directive module="mod_remoteip">RemoteIPTrustedProxyList</directive> directive specifies
    a file parsed at startup, and builds a list of addresses (or address blocks)
    to trust as presenting a valid RemoteIPHeader value of the useragent IP.

The '#' hash character designates a comment line, otherwise
    each whitespace or newline separated entry is processed identically to
    the <directive module="mod_remoteip">RemoteIPTrustedProxy</directive> directive.

    <example><title>Trusted (Load Balancer) Example</title>
    <highlight language="config">
RemoteIPHeader X-Forwarded-For
RemoteIPTrustedProxyList conf/trusted-proxies.lst
        </highlight>
    </example>

    <example><title>conf/trusted-proxies.lst contents</title>
       # Identified external proxies;

       192.0.2.16/28         #wap phone group of proxies

       proxy.isp.example.com #some well known ISP
    </example>
</usage>
</directivesynopsis>

</modulesynopsis>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Music\Bundle\WebsiteBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class WebsiteBundle extends Bundle
{
}


text:
package org.myrobotlab.runtime;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.logging.Level;
import org.slf4j.Logger;

import org.myrobotlab.framework.Encoder;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;

/**
 * Extract information from the process information pseudo-file system called
 * "/proc".
 *
 * @author pmdusso
 * @version 1.0 @created 24-abr-2012 15:22:37
 *
 *          origin : http://djmonitor.googlecode.com/svn-history/r1/src/parser/
 *          ProcParser.java Code license GNU GPL v3
 *
 */
public class ProcParser {

	static public final String CPU = "CPU";
	static public final String MEMORY = "MEMORY";
	static public final String DISK = "DISK";
	static public final String NETWORK = "NETWORK";

	/*
	 * The pid of the process - not thread safe
	 */
	static private int processPid = -1;
	/*
	 * The line which the number of cpu cores is located in /proc/cpuinfo in
	 * kernel 2.6.32-34-generic.
	 */
	public static final int cpucoresline = 12;

	/*
	 * Constant access path string. Those with 'pid' before are in /proc/[pid]/;
	 * Those with 'net' are in /proc/net/. Those without are directly in /proc/.
	 */
	public static final String pidStatmPath = "/proc/#/statm";
	public static final String pidStatPath = "/proc/#/stat";
	public static final String statPath = "/proc/stat";
	public static final String cpuinfoPath = "/proc/cpuinfo";
	public static final String meminfoPath = "/proc/meminfo";
	public static final String netdevPath = "/proc/net/dev";
	public static final String partitionsPath = "/proc/partitions";
	public static final String diskstatsPath = "/proc/diskstats";
	public static final String EMPTY = "";
	public static final String COLON = ":";
	public static final String SPACE = " ";
	public static final String SHARP = "#";
	public static final String LINE_SEPARATOR = "line.separator";

	public final static Logger log = LoggerFactory.getLogger(ProcParser.class);

	public int setPid(int pid) {
		processPid = pid;
		return pid;
	}

	/**
	 * Gathers the usage statistic from the /proc file system for CPU, Memory,
	 * Disk and Network
	 */
	static public ArrayList<String> getUsage(String uType) {
		if ((uType == null) || (processPid < 0)) {
			throw new IllegalArgumentException();
		}
		ArrayList<String> usageData = null;

		switch (uType.toUpperCase()) {
		case CPU:
			usageData = getCpuUsage();
			break;
		case MEMORY:
			usageData = getMemoryUsage(processPid);
			break;
		case DISK:
			usageData = getDiskUsage();
			break;
		case NETWORK:
			usageData = getNetworkUsage();
			break;
		default:
			break;
		}
		return usageData;
	}

	/**
	 *
	 * @param _processPid
	 * @param _memberValues
	 * @throws IOException
	 */
	public static ArrayList<String> getCpuUsage() {
		BufferedReader br = null;
		ArrayList<String> data = new ArrayList<String>();
		String[] tempData;
		try {
			int numberOfCores = getNumberofCores();
			// Parse /proc/stat file and fill the member values list
			// We gonna parse de first line (total) and each line corresponding
			// to
			// one core
			// Line example: cpu0 311689 2102 654770 6755602 32431 38 4127 0 0 0
			br = getStream(statPath);
			// read a dummy line just for skip the total cpu line
			br.readLine();
			for (int core = 1; core <= numberOfCores; core++) {
				data.add(String.valueOf(core));
				tempData = br.readLine().split(SPACE);
				// Adds the first 9 fields.
				for (int field = 1; field < 10; field++) {
					data.add(tempData[field]);
				}
			}
			br.close();
		} catch (IOException e) {
			Logging.logException(e);
		}
		return data;
	}

	/**
	 * DEPRECATE - why do this? Java can do this?
	 */
	public static int getNumberofCores() throws FileNotFoundException, IOException, NumberFormatException {
		String[] tempData = null;
		String[] tempFile = null;

		// Parse /proc/cpuinfo to obtain how many cores the CPU has.
		tempFile = getContents(cpuinfoPath).split(System.getProperty(LINE_SEPARATOR));
		for (String line : tempFile) {
			if (line.contains("cpu cores")) {
				tempData = line.split(COLON);
				break;
			}
		}
		return Integer.parseInt(tempData[1].trim());
	}

	public static Integer getArmInstructionVersion() {
		String[] tempData = null;
		String[] tempFile = null;

		Integer ret = 6;

		// Parse /proc/cpuinfo to obtain how many cores the CPU has.
		String cpuInfo = getContents(cpuinfoPath);
		if (cpuInfo != null) {
			tempFile = cpuInfo.split(System.getProperty(LINE_SEPARATOR));

			for (String line : tempFile) {
				if (line.contains("Processor")) {
					tempData = line.split(COLON);
					break;
				}
			}
			if (tempData == null)
			{
				log.error("proc data not found - not a Linux system?");
				return null;
			}

			if (tempData.length == 2) {
				String idata = tempData[1];
				int pos0 = idata.indexOf("ARMv");
				if (pos0 > 0) {
					String vdata = idata.substring(pos0 + 4, pos0 + 5);
					try {
						ret = Integer.parseInt(vdata);
					} catch (Exception e) {
						Logging.logException(e);
					}
				}

			}
		}

		return ret;
	}

	/**
	 * Get memory usage information. Files: /proc/[pid]/statm /proc/[pid]/stat
	 *
	 * @param _processPid
	 * @param _memberValues
	 */
	public static ArrayList<String> getMemoryUsage(int _processPid) {
		BufferedReader br = null;
		ArrayList<String> data = new ArrayList<String>();
		String[] tempData = null;
		try {
			// Parse /proc/[pid]/statm file and fill the member values list with
			// its contents (all)
			tempData = getContents(pidStatmPath.replace(SHARP, String.valueOf(_processPid))).trim().split(SPACE);
			data.addAll(Arrays.asList(tempData));
			// Parse /proc/[pid]/stat file and fill the member values list just
			// with values 22, 23 and 24 (vsize, resident set size and resident
			// set size limit).
			tempData = getContents(pidStatPath.replace(SHARP, String.valueOf(_processPid))).trim().split(SPACE);
			data.add(tempData[22]);
			data.add(tempData[23]);
			data.add(tempData[24]);
			// Parse /proc/meminfo file for the system memory information.
			br = getStream(meminfoPath);
			for (int i = 0; i < 4; i++) {
				tempData = br.readLine().trim().split(SPACE);
				for (String s : tempData) {
					if (!s.isEmpty() && Encoder.tryParseInt(s)) {
						data.add(s);
					}
				}
			}
			br.close();
		} catch (IOException e) {
			Logging.logException(e);
		}
		return data;
	}

	/**
	 *
	 * @param _memberValues
	 */
	public static ArrayList<String> getNetworkUsage() {
		ArrayList<String> data = new ArrayList<String>();
		String[] tempData = null;
		String[] tempFile = null;

		tempFile = getContents(netdevPath).split(System.getProperty(LINE_SEPARATOR));
		// Skip the first two lines (headers)
		for (int i = 2; i < tempFile.length; i++) {
			// Parse /proc/net/dev to obtain network statistics.
			// Line e.g.:
			// lo: 4852 43 0 0 0 0 0 0 4852 43 0 0 0 0 0 0
			tempData = tempFile[i].replace(COLON, SPACE).split(SPACE);
			data.addAll(Arrays.asList(tempData));
			data.removeAll(Collections.singleton(EMPTY));
		}
		return data;
	}

	/**
	 *
	 * @param _memberValues
	 */
	public static ArrayList<String> getPartitionUsage() {
		ArrayList<String> data = new ArrayList<String>();
		String[] tempData = null;
		String[] tempFile = null;

		tempFile = getContents(partitionsPath).split(System.getProperty(LINE_SEPARATOR));

		// parse the disk partitions
		for (int i = 2; i < tempFile.length; i++) {
			tempData = tempFile[i].split(SPACE);
			data.addAll(Arrays.asList(tempData));
			data.removeAll(Collections.singleton(EMPTY));
		}
		return data;
	}

	/*
	 * Create a list with the partitions name to be used to find their
	 * statistics in /proc/diskstats file
	 */
	public static ArrayList<String> getPartitionNames(ArrayList<String> data) {

		ArrayList<String> partitionsName = new ArrayList<String>();
		for (String string : data) {
			if (!Encoder.tryParseInt(string)) {
				partitionsName.add(string);
			}
		}
		return partitionsName;
	}

	/**
	 *
	 * @param _memberValues
	 */
	public static ArrayList<String> getDiskUsage() {
		ArrayList<String> partitionData = getPartitionUsage();
		ArrayList<String> data = new ArrayList<String>();
		String[] tempData = null;
		String[] tempFile = null;

		tempFile = getContents(diskstatsPath).split(System.getProperty(LINE_SEPARATOR));
		ArrayList<String> tempPart = getPartitionNames(partitionData);
		// Parse /proc/diskstats to obtain disk statistics

		for (String line : tempFile) {
			for (String partition : tempPart) {
				if (line.contains(SPACE + partition + SPACE)) {
					// split(SPACE);
					tempData = line.split(SPACE);
					// adds the rest of the disk statistics
					data.addAll(Arrays.asList(tempData));
					data.removeAll(Collections.singleton(EMPTY));
				}
			}
		}

		return data;
	}

	/**
	 * Fetch the entire contents of a text file, and return it in a String. This
	 * style of implementation does not throw Exceptions to the caller.
	 *
	 * @param path
	 *            is a file which already exists and can be read.
	 * @throws IOException
	 */
	static private synchronized String getContents(String path) {
		// ...checks on aFile are elided
		StringBuilder contents = new StringBuilder();

		try {
			// use buffering, reading one line at a time
			// FileReader always assumes default encoding is OK!
			BufferedReader input = new BufferedReader(new FileReader(new File(path)));
			try {
				String line = null; // not declared within while loop
				/*
				 * readLine is a bit quirky : it returns the content of a line
				 * MINUS the newline. it returns null only for the END of the
				 * stream. it returns an empty String if two newlines appear in
				 * a row.
				 */
				while ((line = input.readLine()) != null) {
					contents.append(line);
					contents.append(System.getProperty(LINE_SEPARATOR));
				}
			} finally {
				input.close();

			}
		} catch (IOException e) {
			Logging.logException(e);
		}

		return contents.toString();
	}

	/**
	 * Opens a stream from a existing file and return it. This style of
	 * implementation does not throw Exceptions to the caller.
	 *
	 * @param path
	 *            is a file which already exists and can be read.
	 * @throws IOException
	 */
	private synchronized static BufferedReader getStream(String _path) throws IOException {
		BufferedReader br = null;
		File file = new File(_path);
		FileReader fileReader = null;
		try {
			fileReader = new FileReader(file);
			br = new BufferedReader(fileReader);

		} catch (IOException e) {
			Logging.logException(e);
		}
		return br;
	}

	public static void main(String[] args) {
		LoggingFactory.getInstance().configure();
		LoggingFactory.getInstance().setLevel("DEBUG");

		Integer v = ProcParser.getArmInstructionVersion();
		log.info("{}", v);
		log.info("{}", v);
	}
}// end ProcInfoParser


text:
const tilebelt=require("@mapbox/tilebelt")
tile=process.argv[2].split(':')
console.log(tilebelt.tileToBBOX([parseInt(tile[1]),parseInt(tile[2]),parseInt(tile[0])]))


text:
package org.apache.isis.viewer.restfulobjects.tck.objectsoftype;

public class Post_whenArgIsHrefAndLinksToEntityOfWrongType_bad_TODO {

}


text:
<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function show($id)
    {
        $user = User::findOrFail($id);
        return view('users.usersDetail')->with('user', $user);
    }
}


text:
<?php

namespace GoldenPlanet\WebpackBundle\Model;

class AssetCollectionModel
{
	/**
	 * @var AssetItemModel[]
	 */
	private $assets = [];

	/**
	 * This will contain modification time and the array of collected assets
	 * It is required for caching purposes, to avoid restarting the webpack process
	 *
	 * @var array
	 */
	private $context;

	/**
	 * @return AssetItemModel[]
	 */
	public function getAssets()
	{
		return $this->assets;
	}

	/**
	 * @param array|AssetItemModel[] $assets
	 *
	 * @return AssetCollectionModel
	 */
	public function setAssets(array $assets)
	{
		$this->assets = $assets;

		return $this;
	}

	/**
	 * @param AssetItemModel $asset
	 *
	 * @return $this
	 */
	public function addAsset(AssetItemModel $asset)
	{
		$this->assets[] = $asset;

		return $this;
	}

	/**
	 * @param array|AssetItemModel[] $assets Array of strings
	 *
	 * @return $this
	 */
	public function addAssets(array $assets)
	{
		$this->assets = array_merge($this->assets, $assets);

		return $this;
	}

	/**
	 * @return array
	 */
	public function getContext()
	{
		return $this->context;
	}

	/**
	 * @param asset $context
	 *
	 * @return AssetCollectionModel
	 */
	public function setContext($context)
	{
		$this->context = $context;

		return $this;
	}
}


text:
/**
 * @author SkySom
 */
@API(owner = "xyz/brassgoggledcoders/moarcarts", apiVersion = "1.0", provides = "moarcarts|API")
package xyz.brassgoggledcoders.moarcarts.api;

import net.minecraftforge.fml.common.API;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ObjectiveUtility</title>
<meta name="date" content="2016-10-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.drip.execution.optimizer

Interface ObjectiveUtility

All Known Implementing Classes:

MeanVarianceObjectiveUtility, PowerVarianceObjectiveUtility

public interface ObjectiveUtility

ObjectiveUtility exposes the Objective Utility Function that needs to be optimized to extract the
        Optimal Execution Trajectory. The References are:

        - Almgren, R., and N. Chriss (1999): Value under Liquidation, Risk 12 (12).

        - Almgren, R., and N. Chriss (2000): Optimal Execution of Portfolio Transactions, Journal of Risk 3 (2)
                5-39.

        - Bertsimas, D., and A. W. Lo (1998): Optimal Control of Execution Costs, Journal of Financial Markets,
                1, 1-50.

        - Chan, L. K. C., and J. Lakonishak (1995): The Behavior of Stock Prices around Institutional Trades,
                Journal of Finance, 50, 1147-1174.

        - Keim, D. B., and A. Madhavan (1997): Transaction Costs and Investment Style: An Inter-exchange
                Analysis of Institutional Equity Trades, Journal of Financial Economics, 46, 265-292.

Author:

Lakshmi Krishnamurthy

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

ControlNodesGreek
sensitivity(TrajectoryControlNodesGreek tcngExpectation,
           TrajectoryControlNodesGreek tcngVariance)

Generate the Objective Function Sensitivity given the Expectation and the Variance Control Node
        Sensitivity

Method Detail

sensitivity

ControlNodesGreek sensitivity(TrajectoryControlNodesGreek tcngExpectation,
                              TrajectoryControlNodesGreek tcngVariance)

Generate the Objective Function Sensitivity given the Expectation and the Variance Control Node
        Sensitivity

Parameters:

tcngExpectation - The Control Node Trajectory Expectation Sensitivity

tcngVariance - The Control Node Trajectory Variance Sensitivity

Returns:

The Control Node Trajectory Objective Function Sensitivity Sensitivity

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
#ifndef TFRT_GPU_WRAPPER_RCCL_WRAPPER_H_
#define TFRT_GPU_WRAPPER_RCCL_WRAPPER_H_

#include <cstddef>
#include <memory>

#include "tfrt/gpu/wrapper/ccl_wrapper.h"

namespace tfrt {
namespace gpu {
namespace wrapper {

llvm::Expected<int> RcclGetVersion();
llvm::Expected<ncclUniqueId> RcclGetUniqueId();
llvm::Expected<OwningCclComm> RcclCommInitRank(CurrentContext current,
                                               int nranks, ncclUniqueId commId,
                                               int rank);
llvm::Error RcclCommDestroy(ncclComm_t comm);
llvm::Error RcclCommAbort(ncclComm_t comm);

llvm::Error RcclCommGetAsyncError(ncclComm_t comm);
llvm::Expected<int> RcclCommCount(ncclComm_t comm);
llvm::Expected<int> RcclCommUserRank(ncclComm_t comm);

llvm::Error RcclReduce(CurrentContext current, Pointer<const void> sendbuff,
                       Pointer<void> recvbuff, size_t count,
                       ncclDataType_t datatype, ncclRedOp_t op, int root,
                       ncclComm_t comm, hipStream_t stream);
llvm::Error RcclBcast(CurrentContext current, Pointer<void> buffer,
                      size_t count, ncclDataType_t datatype, int root,
                      ncclComm_t comm, hipStream_t stream);
llvm::Error RcclBroadcast(CurrentContext current, Pointer<const void> sendbuff,
                          Pointer<void> recvbuff, size_t count,
                          ncclDataType_t datatype, int root, ncclComm_t comm,
                          hipStream_t stream);
llvm::Error RcclAllReduce(CurrentContext current, Pointer<const void> sendbuff,
                          Pointer<void> recvbuff, size_t count,
                          ncclDataType_t datatype, ncclRedOp_t op,
                          ncclComm_t comm, hipStream_t stream);
llvm::Error RcclReduceScatter(CurrentContext current,
                              Pointer<const void> sendbuff,
                              Pointer<void> recvbuff, size_t recvcount,
                              ncclDataType_t datatype, ncclRedOp_t op,
                              ncclComm_t comm, hipStream_t stream);
llvm::Error RcclAllGather(CurrentContext current, Pointer<const void> sendbuff,
                          Pointer<void> recvbuff, size_t sendcount,
                          ncclDataType_t datatype, ncclComm_t comm,
                          hipStream_t stream);
llvm::Error RcclSend(CurrentContext current, Pointer<const void> sendbuff,
                     size_t count, ncclDataType_t datatype, int peer,
                     ncclComm_t comm, hipStream_t stream);
llvm::Error RcclRecv(CurrentContext current, Pointer<void> recvbuff,
                     size_t count, ncclDataType_t datatype, int peer,
                     ncclComm_t comm, hipStream_t stream);

llvm::Error RcclGroupStart();
llvm::Error RcclGroupEnd();

}  // namespace wrapper
}  // namespace gpu
}  // namespace tfrt

#endif  // TFRT_GPU_WRAPPER_RCCL_WRAPPER_H_


text:
/**
 * log4js 配置文件
 *
 * 日志等级由低到高
 * ALL TRACE DEBUG INFO WARN ERROR FATAL OFF.
 *
 * 关于log4js的appenders的配置说明
 * https://github.com/nomiddlename/log4js-node/wiki/Appenders
 * https://github.com/tough1985/hello-koa2/blob/master/config/log_config.js
 */

const path = require('path');

//日志根目录
let baseLogPath = path.resolve(__dirname, '../../../logs')

//错误日志目录
const errorPath = "/error";

//错误日志文件名
const errorFileName = "error";

//错误日志输出完整路径
let errorLogPath = baseLogPath + errorPath + "/" + errorFileName;
// const errorLogPath = path.resolve(__dirname, "../logs/error/error");

//响应日志目录
const responsePath = "/response";

//响应日志文件名
const responseFileName = "response";

//响应日志输出完整路径
let responseLogPath = baseLogPath + responsePath + "/" + responseFileName;
// var responseLogPath = path.resolve(__dirname, "../logs/response/response");

module.exports = function(pathLog){
    if (pathLog) {
        baseLogPath = pathLog
    }

    errorLogPath = baseLogPath + errorPath + "/" + errorFileName;
    responseLogPath = baseLogPath + responsePath + "/" + responseFileName;

    return {
        "appenders"   : {
            //错误日志
            "errorLogger" : {
                "category"             : "errorLogger",             //logger名称
                "type"                 : "dateFile",                   //日志类型
                "filename"             : errorLogPath,             //日志输出位置
                "alwaysIncludePattern" : true,          //是否总是有后缀名
                "pattern"              : "-yyyy-MM-dd-hh.log",      //后缀,每小时创建一个新的日志文件
                "path"                 : errorPath                     //自定义属性,错误日志的根目录
            },
            //响应日志
            "responseLogger" : {
                "category"             : "responseLogger",
                "type"                 : "dateFile",
                "filename"             : responseLogPath,
                "alwaysIncludePattern" : true,
                "pattern"              : "-yyyy-MM-dd-hh.log",
                "path"                 : responsePath
            }
        },
        "categories": {
            "error": { "appenders": ['errorLogger'], level: 'error' },
            "response": { "appenders": ['responseLogger'], level: 'ALL' },
            "default": { "appenders": ['errorLogger'], level: 'error' }
        },
        "baseLogPath" : baseLogPath                  //logs根目录
    }
}


text:
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2016 Intel Corporation. All Rights Reserved.

/**
* \file pipeline_async.h
* @brief Describes the \c rs::core::pipeline_async and \c rs::core::pipeline_async_impl classes.
*/

#pragma once
#include "rs/core/pipeline_async_interface.h"

#ifdef WIN32
#ifdef realsense_pipeline_EXPORTS
#define  DLL_EXPORT __declspec(dllexport)
#else
#define  DLL_EXPORT __declspec(dllimport)
#endif /* realsense_pipeline_EXPORTS */
#else /* defined (WIN32) */
#define DLL_EXPORT
#endif

namespace rs
{
    namespace core
    {
        /**
        * @brief Forward declaration for the actual pipeline implementation as part of the pimpl pattern.
        */
        class pipeline_async_impl;

        /**
         * @brief Instantiation class, as part of the pimpl pattern for \c pipeline_async_interface.
         *
         * For complete class documentation, see \c pipeline_async_interface.
         */
        class DLL_EXPORT pipeline_async : public pipeline_async_interface
        {
        public:
            /**
             * @brief Constructor to initialize a pipeline async interface with a live camera, currently connected to the platform.
             */
            pipeline_async();

            /**
             * @brief The testing_mode enum expresses the pipeline testing modes for record and playback.
             */
            enum class testing_mode
            {
                playback,   /** The streaming source will be a playback file */
                record      /** The streaming source will be a device which is currently connected to the platform, and the streaming output will
                                be recorded to a file */
            };

            /**
             * @brief Constructor to initialize a pipeline for testing using record and playback.
             *
             * @param[in] mode            Select the pipeline testing mode, streaming from a playback file or record mode, which streams from a live camera
             *                            and records the output to a file.
             * @param[in] file_path       The input file path for playback mode or record mode output file path.
             */
            pipeline_async(const testing_mode mode, const char * file_path);

            pipeline_async(const pipeline_async&) = delete;
            pipeline_async& operator= (const pipeline_async&) = delete;
            pipeline_async(pipeline_async&&) = delete;
            pipeline_async& operator= (pipeline_async&&) = delete;

            virtual status add_cv_module(video_module_interface *cv_module) override;
            virtual status query_cv_module(uint32_t index, video_module_interface **cv_module) const override;
            virtual status query_default_config(uint32_t index, video_module_interface::supported_module_config & default_config) const override;
            virtual status set_config(const video_module_interface::supported_module_config & config) override;
            virtual status query_current_config(video_module_interface::actual_module_config & current_config) const override;
            virtual status reset() override;
            virtual status start(callback_handler * app_callbacks_handler) override;
            virtual status stop() override;
            virtual rs::device * get_device() override;
            virtual ~pipeline_async();
        private:
            pipeline_async_impl * m_pimpl; /**<The actual pipeline asynchronous implementation. */
        };
    }
}


text:
// Copyright (c) 2012 INRIA Sophia-Antipolis (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
// You can redistribute it and/or modify it under the terms of the GNU
// General Public License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
//
//
// Author(s)     : Sebastien Loriot
//

#ifndef CGAL_AABB_FACE_GRAPH_TRIANGLE_PRIMITIVE_H
#define CGAL_AABB_FACE_GRAPH_TRIANGLE_PRIMITIVE_H

#include <CGAL/AABB_primitive.h>
#include <CGAL/Polyhedron_3.h>
#include <CGAL/Polyhedron_3_property_map.h>
#include <CGAL/Default.h>

namespace CGAL {

/*!
 * \ingroup PkgAABB_tree
 * Primitive type for a facet of a polyhedral surface.
 * It wraps a handle to a facet of a polyhedron to a 3D triangle.
 * The polyhedron from which the primitive is built should not be deleted
 * while the AABB tree holding the primitive is in use.
 *
 * \cgalModels `AABBPrimitiveWithSharedData`
 *
 *\tparam FaceGraph is a \cgal polyhedron.
 *\tparam VertexPointPMap must be set to `CGAL::Default`
 *        This parameter is useless for the moment and will be useful in an upcoming release of \cgal.
 *\tparam OneFaceGraphPerTree is either `CGAL::Tag_true or `CGAL::Tag_false`.
 * In the former case, we guarantee that all the primitives will be from a
 * common polyhedron and some data will be factorized so that the size of
 * the primitive is reduced. In the latter case, the primitives can be from
 * different polyhedra and extra storage is required in the primitives. The default is `CGAL::Tag_true`.
 *        This parameter is useless for the moment and will be useful in an upcoming release of \cgal.
 *\tparam CacheDatum is either `CGAL::Tag_true` or `CGAL::Tag_false`. In the former case, the datum is stored
 *        in the primitive, while in the latter it is constructed on the fly to reduce the memory footprint.
 *        The default is `CGAL::Tag_false` (datum is not stored).
 *\sa `AABBPrimitive`
 *\sa `AABB_primitive<Id,ObjectPropertyMap,PointPropertyMapPolyhedron,ExternalPropertyMaps,CacheDatum>`
 *\sa `AABB_halfedge_graph_segment_primitive<HalfedgeGraph,OneHalfedgeGraphPerTree,CacheDatum>`
 */
template < class FaceGraph,
           class VertexPointPMap = Default,
           class OneFaceGraphPerTree = Tag_true,
           class CacheDatum=Tag_false >
class AABB_face_graph_triangle_primitive
#ifndef DOXYGEN_RUNNING
: public AABB_primitive<  typename boost::mpl::if_<
                            typename boost::is_const<FaceGraph>::type,
                            typename FaceGraph::Facet_const_handle,
                            typename FaceGraph::Facet_handle
                           >::type,
                         Triangle_from_facet_handle_property_map<FaceGraph>,
                         One_point_from_facet_handle_property_map<FaceGraph>,
                         OneFaceGraphPerTree,
                         CacheDatum >
#endif
{
  typedef typename boost::mpl::if_<
                          typename boost::is_const<FaceGraph>::type,
                          typename FaceGraph::Facet_const_handle,
                          typename FaceGraph::Facet_handle >::type  Id_;
  typedef Triangle_from_facet_handle_property_map<FaceGraph>  Triangle_property_map;
  typedef One_point_from_facet_handle_property_map<FaceGraph> Point_property_map;

  typedef AABB_primitive< Id_,
                          Triangle_property_map,
                          Point_property_map,
                          OneFaceGraphPerTree,
                          CacheDatum > Base;

public:
  #ifdef DOXYGEN_RUNNING
  /// \name Types
  /// @{
  /*!
  The point type.
  */
  typedef boost::property_traits< boost::property_map< FaceGraph, vertex_point_t>::type >::value_type Point;
  /*!
  Geometric data type.
  */
  typedef Kernel_traits<Point>::Kernel::Triangle_3 Datum;
  /*!
  Id type.
  */
  typedef boost::graph_traits<FaceGraph>::face_descriptor Id;
  /// @}

  /*!
  If `OneFaceGraphPerTree` is CGAL::Tag_true, constructs a `Shared_data` object from a reference to the polyhedon `graph`.
  */
  static unspecified_type construct_shared_data( FaceGraph& graph );
  #endif

  // constructors
  /*!
    \tparam Iterator an input iterator with `Id` as value type.
    Constructs a primitive.
  */
  template <class Iterator>
  AABB_face_graph_triangle_primitive(Iterator it, FaceGraph& graph)
    : Base( Id_(it),
            Triangle_property_map(&graph),
            Point_property_map(&graph) ){}

  /// \internal
  typedef internal::Cstr_shared_data<FaceGraph, Base, Triangle_property_map, Point_property_map, OneFaceGraphPerTree> Cstr_shared_data;
  /// \internal
  static
  typename Cstr_shared_data::Shared_data
  construct_shared_data(FaceGraph& graph)
  {
    return Cstr_shared_data::construct_shared_data(graph);
  }

};

}  // end namespace CGAL

#endif // CGAL_AABB_FACE_GRAPH_TRIANGLE_PRIMITIVE_H


text:
namespace ozz {
namespace animation {
namespace offline {

// Translation interpolation method.
// This must be the same Lerp as the one used by the sampling job.
math::Float3 LerpTranslation(const math::Float3& _a,
                             const math::Float3& _b,
                             float _alpha) {
  return math::Lerp(_a, _b, _alpha);
}

// Rotation interpolation method.
// This must be the same Lerp as the one used by the sampling job.
// The goal is to take the shortest path between _a and _b. This code replicates
// this behavior that is actually not done at runtime, but when building the
// animation.
math::Quaternion LerpRotation(const math::Quaternion& _a,
                              const math::Quaternion& _b,
                              float _alpha) {
  // Finds the shortest path. This is done by the AnimationBuilder for runtime
  // animations.
  const float dot = _a.x * _b.x + _a.y * _b.y + _a.z * _b.z + _a.w * _b.w;
  return math::NLerp(_a, dot < 0.f ? -_b : _b, _alpha); // _b an -_b are the
                                                        // same rotation.
}

// Scale interpolation method.
// This must be the same Lerp as the one used by the sampling job.
math::Float3 LerpScale(const math::Float3& _a,
                       const math::Float3& _b,
                       float _alpha) {
  return math::Lerp(_a, _b, _alpha);
}
}  // offline
}  // animation
}  // ozz


text:
package com.fincatto.nfe310.transformers;

import org.simpleframework.xml.transform.Transform;

import com.fincatto.nfe310.classes.nota.NFViaTransporteInternacional;

public class NFViaTransporteInternacionalTransformer implements Transform<NFViaTransporteInternacional> {

    @Override
    public NFViaTransporteInternacional read(final String codigo) throws Exception {
        return NFViaTransporteInternacional.valueOfCodigo(codigo);
    }

    @Override
    public String write(final NFViaTransporteInternacional via) throws Exception {
        return via.getCodigo();
    }
}


text:
package main

import (
	"encoding/xml"
	"errors"
	"fmt"
	"sort"
	"strconv"
	"strings"

	stringcase "github.com/reiver/go-stringcase"
)

// ZwClasses contains the configuration parsed by data/zwave-defs.xml
type ZwClasses struct {
	XMLName        xml.Name        `xml:"zw_classes"`
	BasicDevices   []BasicDevice   `xml:"bas_dev"`
	GenericDevices []GenericDevice `xml:"gen_dev"`
	CommandClasses []CommandClass  `xml:"cmd_class"`
}

// BasicDevice .
type BasicDevice struct {
	Name     string `xml:"name,attr"`
	Key      string `xml:"key,attr"`
	Help     string `xml:"help,attr"`
	ReadOnly bool   `xml:"read_only,attr"`
	Comment  string `xml:"comment,attr"`
}

// GenericDevice .
type GenericDevice struct {
	Key             string           `xml:"key,attr"`
	Name            string           `xml:"name,attr"`
	Help            string           `xml:"help,attr"`
	Comment         string           `xml:"comment,attr"`
	ReadOnly        bool             `xml:"read_only,attr"`
	SpecificDevices []SpecificDevice `xml:"spec_dev"`
}

// SpecificDevice .
type SpecificDevice struct {
	Name    string `xml:"name,attr"`
	Key     string `xml:"key,attr"`
	Help    string `xml:"help,attr"`
	Comment string `xml:"comment,attr"`
}

// CommandClass contains a command class
type CommandClass struct {
	Name     string    `xml:"name,attr"`
	Key      string    `xml:"key,attr"`
	Version  int       `xml:"version,attr"`
	Help     string    `xml:"help,attr"`
	Comment  string    `xml:"comment,attr"`
	Commands []Command `xml:"cmd"`

	Enabled bool `xml:"-"`
}

// GetBaseName will strip COMMAND_CLASS_ from  name.
func (c CommandClass) GetBaseName() string {
	return strings.Replace(c.Name, "COMMAND_CLASS_", "", 1)
}

// GetConstName will add version if it exists and convert to pascal case.
func (c CommandClass) GetConstName() string {
	name := c.GetBaseName()
	if c.Version > 1 {
		versionStr := strconv.Itoa(c.Version)
		name += "_V" + versionStr
	}

	return stringcase.ToPascalCase(name)
}

// GetDirName will retrieve  the directory name.
func (c CommandClass) GetDirName() string {
	ccname := stringcase.ToPropertyCase(c.GetBaseName())

	if c.Version > 1 {
		versionStr := strconv.Itoa(c.Version)
		ccname += "-v" + versionStr
	}

	return ccname
}

// GetPackageName will get the package name.
func (c CommandClass) GetPackageName() string {
	ccname := stringcase.ToLowerCase(stringcase.ToPascalCase(c.GetBaseName()))

	if c.Version > 1 {
		versionStr := strconv.Itoa(c.Version)
		ccname += "v" + versionStr
	}

	return ccname
}

// CanGenerate should  determine if this command class  can be genereated and return the reason if not
func (c CommandClass) CanGenerate() (can bool, reason string) {
	if len(c.Commands) == 0 {
		return false, "No commands"
	}

	if c.Name == "ZWAVE_CMD_CLASS" {
		return false, "Not an actual command class"
	}

	if c.Name == "COMMAND_CLASS_ZIP" {
		return false, "Not supported"
	}

	return true, ""
}

// CanGen will return whether the command class can be generated.
func (c CommandClass) CanGen() (can bool) {
	can, _ = c.CanGenerate()
	return
}

// Command contains a command.
type Command struct {
	Name     string `xml:"name,attr"`
	Key      string `xml:"key,attr"`
	Type     string `xml:"type,attr"`
	HashCode string
	Comment  string `xml:"comment,attr"`

	Params        []Param        `xml:"param"`
	VariantGroups []VariantGroup `xml:"variant_group"`
	CC            CommandClass   `xml:"-"`
}

// GetBaseName is the base name of the command.
func (c Command) GetBaseName(cc CommandClass) string {
	commandName := c.Name

	if strings.HasPrefix(strings.ToLower(commandName), "command_") &&
		!strings.HasPrefix(strings.ToLower(commandName), "command_class_") {
		commandName = commandName[8:]
	}

	ccBaseName := cc.GetBaseName()

	if strings.HasPrefix(commandName, ccBaseName) {
		if len(commandName) > len(ccBaseName) {
			commandName = commandName[len(ccBaseName)+1:]
		}
	}

	return commandName
}

// GetStructName returns the name of the  struct to be generated.
func (c Command) GetStructName(cc CommandClass) string {
	return stringcase.ToPascalCase(c.GetBaseName(cc))
}

// GetFileName returns the name of the file for this  command.
func (c Command) GetFileName(cc CommandClass) string {
	return stringcase.ToPropertyCase(c.GetBaseName(cc))
}

func (c Command) OrderedKeys() []string {
	var keys []string

	for _, param := range c.Params {
		keys = append(keys, param.Key)
	}

	for _, vg := range c.VariantGroups {
		keys = append(keys, vg.Key)
	}

	sort.Strings(keys)

	return keys
}

// func (c Command) AddUnmarshalField(key string) string {
// 	fmt.Println(key)

// 	for _, param := range c.Params {
// 		if param.Key == key {
// 			fmt.Printf("found param key: %s\n", key)

// 			paramTemplate, err := template.ParseFiles("gen/templates/unmarshal-command-param.tpl")
// 			if err != nil {
// 				log.Fatalf("parse unmarshal command param template: %v", err)
// 			}

// 			var buf bytes.Buffer

// 			if err := paramTemplate.Execute(&buf, &param); err != nil {
// 				log.Fatalf("exec unmarshal command param template: %v", err)
// 			}

// 			return buf.String()
// 		}
// 	}

// 	for _, vg := range c.VariantGroups {
// 		if vg.Key == key {
// 			fmt.Printf("found vg key: %s\n", key)
// 		}
// 	}

// 	return ""
// }

// func (c Command) AddMarshalField(key string) string {
// 	for _, param := range c.Params {
// 		if param.Key == key {
// 			fmt.Printf("found param key: %s\n", key)

// 			paramTemplate, err := template.ParseFiles("gen/templates/unmarshal-command-param.tpl")
// 			if err != nil {
// 				log.Fatalf("parse unmarshal command param template: %v", err)
// 			}

// 			var buf bytes.Buffer

// 			if err := paramTemplate.Execute(&buf, &param); err != nil {
// 				log.Fatalf("exec unmarshal command param template: %v", err)
// 			}

// 			return buf.String()
// 		}
// 	}

// 	for _, vg := range c.VariantGroups {
// 		if vg.Key == key {
// 			fmt.Printf("found vg key: %s\n", key)
// 		}
// 	}

// 	return ""
// }
func (c Command) GetFieldType(key string) string {
	for _, param := range c.Params {
		if param.Key == key {
			return "param"
		}
	}

	for _, vg := range c.VariantGroups {
		if vg.Key == key {
			return "vg"
		}
	}

	return ""
}

func (c Command) GetParam(key string) Param {

	for _, param := range c.Params {
		if param.Key == key {
			return param
		}
	}

	return Param{}
}

func (c Command) GetVg(key string) VariantGroup {

	for _, vg := range c.VariantGroups {
		if vg.Key == key {
			return vg
		}
	}

	return VariantGroup{}
}

func (c Command) FindVgLengthVar(key string, keys []string) string {
	for i := range keys {
		if keys[i] == key {
			if i == 0 {
				panic("vg was first index")
			}
			for j := i - 1; j >= 0; j-- {
				param := c.GetParam(keys[j])
				switch param.Type {
				case "BYTE":
					return toGoName(param.Name)
				case "STRUCT_BYTE":
					if len(param.BitField) == 0 {
						panic("no bitfields  in  STRUCT_BYTE")
					}
					for _, bf := range param.BitField {
						if bf.IsNotReserved() {
							return fmt.Sprintf("%s.%s", toGoName(param.Name), toGoName(bf.FieldName))

						}
					}
				}
			}
		}
	}
	panic("len not found")
}

type VariantGroup struct {
	Key          string `xml:"key,attr"`
	Name         string `xml:"name,attr"`
	VariantKey   string `xml:"variantKey,attr"`
	ParamOffs    string `xml:"paramOffs,attr"`
	SizeMask     string `xml:"sizeMask,attr"`
	SizeOffs     string `xml:"sizeoffs,attr"`
	TypeHashCode string `xml:"typehashcode,attr"`

	Params []Param `xml:"param"`
}

type Param struct {
	Key            string `xml:"key,attr"`
	Name           string `xml:"name,attr"`
	Type           string `xml:"type,attr"`
	TypeHashCode   string `xml:"typehashcode,attr"`
	Comment        string `xml:"comment,attr"`
	EncapType      string `xml:"encaptype,attr"`
	OptionalOffset string `xml:"optionaloffs,attr"`
	OptionalMask   string `xml:"optionalmask,attr"`
	Encapsulated   bool   `xml:"encapsulated,attr"`
	CommandMask    string `xml:"cmd_mask,attr"`
	Affix          bool   `xml:"affix,attr"`

	ArrayAttrib []ArrayAttrib `xml:"arrayattrib"`
	Bit24       []Bit24       `xml:"bit_24"`
	BitField    []BitField    `xml:"bitfield"`
	BitFlag     []BitFlag     `xml:"bitflag"`
	Const       []Const       `xml:"const"`
	DWord       []DWord       `xml:"dword"`
	FieldEnum   []FieldEnum   `xml:"fieldenum"`
	ValueAttrib []ValueAttrib `xml:"valueattrib"`
	Variant     []Variant     `xml:"variant"`
	Bitmask     []Bitmask     `xml:"bitmask"`
	Word        []Word        `xml:"word"`
}

// IsNotReserved will return false if the parameter name is reserved.
func (p Param) IsNotReserved() bool {
	return !isReservedString(p.Name)
}

// GetEncodedByteLength will return the length of  the data.
func (p Param) GetEncodedByteLength() (uint8, error) {
	switch p.Type {

	case "BYTE":
		return 1, nil

	case "CONST":
		return 1, nil

	case "MARKER":
		return 1, nil

	case "STRUCT_BYTE":
		return 1, errors.New("Unimplemented param type: STRUCT_BYTE")

	case "WORD":
		return 2, nil

	case "BIT_24":
		return 3, nil

	case "DWORD":
		return 4, nil

	case "ARRAY":
		if len(p.ArrayAttrib) > 0 && p.ArrayAttrib[0].Length != 0 {
			return byte(p.ArrayAttrib[0].Length), nil
		} else {
			return 0, errors.New("Field has unknown or indeterminate length")
		}

	default:
		fmt.Println(p.Name, p.Type)
		return 0, errors.New("Field has unknown or indeterminate length")

	}
}

// GetGoType will return the go type associated with the parameter type.
func (p Param) GetGoType() (string, error) {
	switch p.Type {

	case "ARRAY":
		if p.ArrayAttrib != nil && len(p.ArrayAttrib) == 1 {
			if p.ArrayAttrib[0].IsAscii {
				return "string", nil
			} else {
				return "[]byte", nil
			}
		} else if p.ArrayAttrib != nil {
			return "", errors.New("Weird number of <ArrayAttrib> elements")
		}
		return "[]byte", nil

	case "BIT_24":
		return "uint32", nil

	case "BITMASK":
		// @todo there are some command classes (that we currently don't generate)
		// that have a BITMASK in the middle of the payload. We don't currently
		// support that.
		return "[]byte", nil

	case "BYTE":
		return "byte", nil

	case "CONST":
		return "byte", nil

	case "DWORD":
		return "uint32", nil

	case "ENUM":
		return "", errors.New("Unimplemented param type: ENUM")

	case "ENUM_ARRAY":
		return "", errors.New("Unimplemented param type: ENUM_ARRAY")

	case "MARKER":
		return "", errors.New("Unimplemented param type: MARKER")

	case "MULTI_ARRAY":
		return "", errors.New("Unimplemented param type: MULTI_ARRAY")

	case "STRUCT_BYTE":
		return "", errors.New("Unimplemented param type: STRUCT_BYTE")

	case "VARIANT":
		return "[]byte", nil

	case "WORD":
		return "uint16", nil

	default:
		return "", errors.New("Unknown param type: " + p.Type)

	}
}

type ArrayAttrib struct {
	Key     string `xml:"key,attr"`
	Length  int    `xml:"len,attr"`
	IsAscii bool   `xml:"is_ascii,attr"`
}

type ArrayLen struct {
	Key          string `xml:"key,attr"`
	ParamOffset  byte   `xml:"paramoffs,attr"`
	LengthOffset byte   `xml:"lenoffs,attr"`
	LengthMask   byte   `xml:"lenmask,attr"`
}

type Bit24 struct {
	Key        string `xml:"key,attr"`
	HasDefines bool   `xml:"hasdefines,attr"`
	ShowHex    bool   `xml:"showhex,attr"`
}

type BitField struct {
	Key       string `xml:"key,attr"`
	FieldName string `xml:"fieldname,attr"`
	FieldMask string `xml:"fieldmask,attr"`
	Shifter   uint8  `xml:"shifter,attr"`
}

func (b BitField) IsNotReserved() bool {
	return !isReservedString(b.FieldName)
}

type BitFlag struct {
	Key      string `xml:"key,attr"`
	FlagName string `xml:"flagname,attr"`
	FlagMask string `xml:"flagmask,attr"`
}

func (b BitFlag) IsNotReserved() bool {
	return !isReservedString(b.FlagName)
}

type Const struct {
	Key      string `xml:"key,attr"`
	FlagName string `xml:"flagname,attr"`
	FlagMask string `xml:"flagmask,attr"`
}

type DWord struct {
	Key        string `xml:"key,attr"`
	HasDefines bool   `xml:"hasdefines,attr"`
	ShowHex    bool   `xml:"showhex,attr"`
}

type Enum struct {
	Key  string `xml:"key,attr"`
	Name string `xml:"name,attr"`
}

type FieldEnum struct {
	Key       string `xml:"key,attr"`
	FieldName string `xml:"fieldname,attr"`
	FieldMask string `xml:"fieldmask,attr"`
	Shifter   uint8  `xml:"shifter,attr"`
	Value     string `xml:"value,attr"`

	EnumValues []FieldEnum `xml:"fieldenum"`
}

func (f FieldEnum) IsNotReserved() bool {
	return !isReservedString(f.FieldName)
}

type ValueAttrib struct {
	Key        string `xml:"key,attr"`
	HasDefines bool   `xml:"hasdefines,attr"`
	ShowHex    bool   `xml:"showhex,attr"`
}

type Variant struct {
	Key         string `xml:"key,attr"`
	ParamOffset byte   `xml:"paramoffs,attr"`
	HasDefines  bool   `xml:"hasdefines,attr"`
	ShowHex     bool   `xml:"showhex,attr"`
	Signed      bool   `xml:"signed,attr"`
	SizeMask    string `xml:"sizemask,attr"`
	SizeOffset  string `xml:"sizeoffs,attr"`

	MarkerDelimited bool
	MarkerValue     string
	RemainingBytes  uint8
}

type Bitmask struct {
	Key          string `xml:"key,attr"`
	ParamOffset  byte   `xml:"paramoffs,attr"`
	LengthOffset byte   `xml:"lenoffs,attr"`
	LengthMask   string `xml:"lenmask,attr"`
	Length       byte   `xml:"len,attr"`
}

type Word struct {
	Key        string `xml:"key,attr"`
	HasDefines bool   `xml:"hasdefines,attr"`
	ShowHex    bool   `xml:"showhex,attr"`
}


text:
class AddUserIdToGroups < ActiveRecord::Migration
  def change
    add_column :groups, :user_id, :integer
    add_index :groups, :user_id
  end
end


text:
import sys

from twisted.internet import reactor
from twisted.python import log

from autobahn.twisted.websocket import WebSocketClientFactory, \
    WebSocketClientProtocol, \
    connectWS

class EchoClientProtocol(WebSocketClientProtocol):

    def onConnect(self, response):
        print(response)

    def sendHello(self):
        self.sendMessage("Hello, world!".encode('utf8'))

    def onOpen(self):
        self.sendHello()

    def onMessage(self, payload, isBinary):
        if not isBinary:
            print("Text message received: {}".format(payload.decode('utf8')))
        reactor.callLater(1, self.sendHello)

if __name__ == '__main__':

    if len(sys.argv) < 2:
        print("Need the WebSocket server address, i.e. ws://127.0.0.1:9000")
        sys.exit(1)

    log.startLogging(sys.stdout)

    headers = {'MyCustomClientHeader': 'Bazbar'}

    factory = WebSocketClientFactory(sys.argv[1], headers=headers)
    factory.protocol = EchoClientProtocol
    connectWS(factory)

    reactor.run()


text:
package models.daos

import java.util.UUID

import models.AuthToken
import models.daos.AuthTokenDAOImpl._
import org.joda.time.DateTime

import scala.collection.mutable
import scala.concurrent.Future

/**
 * Give access to the [[AuthToken]] object.
 */
class AuthTokenDAOImpl extends AuthTokenDAO {

  /**
   * Finds a token by its ID.
   *
   * @param id The unique token ID.
   * @return The found token or None if no token for the given ID could be found.
   */
  def find(id: UUID) = Future.successful(tokens.get(id))

  /**
   * Finds expired tokens.
   *
   * @param dateTime The current date time.
   */
  def findExpired(dateTime: DateTime) = Future.successful {
    tokens.filter {
      case (id, token) =>
        token.expiry.isBefore(dateTime)
    }.values.toSeq
  }

  /**
   * Saves a token.
   *
   * @param token The token to save.
   * @return The saved token.
   */
  def save(token: AuthToken) = {
    tokens += (token.id -> token)
    Future.successful(token)
  }

  /**
   * Removes the token for the given ID.
   *
   * @param id The ID for which the token should be removed.
   * @return A future to wait for the process to be completed.
   */
  def remove(id: UUID) = {
    tokens -= id
    Future.successful(())
  }
}

/**
 * The companion object.
 */
object AuthTokenDAOImpl {

  /**
   * The list of tokens.
   */
  val tokens: mutable.HashMap[UUID, AuthToken] = mutable.HashMap()
}


text:
    Погода

    {% for plugin, forecast in weather %}

{{ plugin }}:

                {% for day, data in forecast %}
                    {{ day }}
                {% endfor %}

                {% for day, data in forecast %}
                    {% for d in data %}

{{ d.temperature }} °C

{{ d.wind_speed }} м/с

                    {% endfor %}
                {% endfor %}

    {% endfor %}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Limitless - Responsive Web Application Kit by Eugene Kopyov</title>

	<link href="https://fonts.googleapis.com/css?family=Roboto:400,300,100,500,700,900" rel="stylesheet" type="text/css">
	<link href="assets/css/icons/icomoon/styles.css" rel="stylesheet" type="text/css">
	<link href="assets/css/bootstrap.css" rel="stylesheet" type="text/css">
	<link href="assets/css/core.css" rel="stylesheet" type="text/css">
	<link href="assets/css/components.css" rel="stylesheet" type="text/css">
	<link href="assets/css/colors.css" rel="stylesheet" type="text/css">

Forms inside modals Login and other forms inside modal

Login form

							<button type="button" class="btn bg-blue btn-block" data-toggle="modal" data-target="#modal-login"> Launch modal</button>

Registration form

							<button type="button" class="btn bg-blue btn-block" data-toggle="modal" data-target="#modal-registration"> Launch modal</button>

Unlock user form

							<button type="button" class="btn bg-blue btn-block" data-toggle="modal" data-target="#modal-unlock"> Launch modal</button>

Password recover form

							<button type="button" class="btn bg-blue btn-block" data-toggle="modal" data-target="#modal-recover"> Launch modal</button>

Tabbed form

							<button type="button" class="btn bg-blue btn-block" data-toggle="modal" data-target="#modal-tabbed"> Launch modal</button>

Form with validation

							<button type="button" class="btn bg-blue btn-block" data-toggle="modal" data-target="#modal-validation"> Launch modal</button>

								<form class="modal-body" action="index.html">

Login to your account Your credentials

										<input type="text" class="form-control" placeholder="Username">

										<input type="text" class="form-control" placeholder="Password">

													<input type="checkbox" class="styled" checked="checked">
													Remember

												Forgot password?

										<button type="submit" class="btn bg-blue btn-block">Login </button>

or sign in with

Don't have an account?

									Sign up
									By continuing, you're confirming that you've read our Terms & Conditions and Cookie Policy
								</form>

								<form class="modal-body" action="index.html">

Create account All fields are required

Your credentials

										<input type="text" class="form-control" placeholder="Eugene">

										<input type="text" class="form-control" placeholder="Create password">

Your privacy

										<input type="text" class="form-control" placeholder="Your email">

										<input type="text" class="form-control" placeholder="Repeat email">

Additions

												<input type="checkbox" class="styled" checked="checked">
												Send me test account settings

												<input type="checkbox" class="styled" checked="checked">
												Subscribe to monthly newsletter

												<input type="checkbox" class="styled">
												Accept terms of service

										<button type="submit" class="btn bg-blue btn-block">Register </button>
										<button type="button" class="btn btn-default btn-block" data-dismiss="modal">Cancel</button>

									By continuing, you're confirming that you've read our Terms & Conditions and Cookie Policy
								</form>

								<form class="modal-body" action="index.html">

Victoria Baker Unlock your account

										<input type="text" class="form-control" placeholder="Your password">

													<input type="checkbox" class="styled" checked="checked">
													Remember

												Forgot password?

									<button type="submit" class="btn bg-slate btn-block">Unlock </button>
									<button type="button" class="btn btn-default btn-block" data-dismiss="modal">Cancel</button>
								</form>

								<form class="modal-body" action="index.html">

Password recovery We'll send you instructions in email

										<input type="email" class="form-control" placeholder="Your email">

									<button type="submit" class="btn bg-blue btn-block">Reset password </button>
									<button type="button" class="btn btn-default btn-block" data-dismiss="modal">Cancel</button>
								</form>

								<form action="index.html">

Sign in

Register

											<form action="index.html">

Login to your account Your credentials

													<input type="text" class="form-control" placeholder="Username" name="username" required="required">

													<input type="text" class="form-control" placeholder="Password" name="password" required="required">

																<input type="checkbox" class="styled" checked="checked">
																Remember

															Forgot password?

													<button type="submit" class="btn bg-blue btn-block">Login </button>

											</form>

or sign in with

											By continuing, you're confirming that you've read our Terms & Conditions and Cookie Policy

											<form action="index.html">

Create new account All fields are required

													<input type="text" class="form-control" placeholder="Your username">

													<input type="text" class="form-control" placeholder="Create password">

													<input type="text" class="form-control" placeholder="Your email">

Additions

															<input type="checkbox" class="styled" checked="checked">
															Send me test account settings

															<input type="checkbox" class="styled" checked="checked">
															Subscribe to monthly newsletter

															<input type="checkbox" class="styled">
															Accept terms of service

												<button type="submit" class="btn bg-indigo-400 btn-block">Register </button>
												<button type="button" class="btn btn-default btn-block" data-dismiss="modal">Cancel</button>
											</form>

								</form>

								<form class="modal-body form-validate" action="index.html">

Login to your account Your credentials

										<input type="text" class="form-control" placeholder="Username" name="username" required="required">

										<input type="text" class="form-control" placeholder="Password" name="password" required="required">

													<input type="checkbox" class="styled" checked="checked">
													Remember

												Forgot password?

										<button type="submit" class="btn bg-blue btn-block">Login </button>

or sign in with

Don't have an account?

									Sign up
									By continuing, you're confirming that you've read our Terms & Conditions and Cookie Policy
								</form>


text:
import { kea, resetContext } from '../../src'

describe('action types', () => {
  beforeEach(() => {
    resetContext()
  })

  test('action types object is created', () => {
    const logic = kea({
      path: () => ['kea', 'test'],
      actions: {
        updateName: (name) => ({ name }),
        anotherAction: true,
      },
    })

    logic.mount()

    expect(logic.path).toEqual(['kea', 'test'])
    expect(Object.keys(logic.actions).sort()).toEqual(['anotherAction', 'updateName'])

    expect(logic.actionTypes).toEqual({
      anotherAction: logic.actions.anotherAction.toString(),
      updateName: logic.actions.updateName.toString(),
    })
  })
})


text:
var Base = require('../Base');
var moment = require('moment');
var debug = require('debug')('raabbajam:priceCacheCalendar:lion');
var _ = require('lodash');
var db = require('../libs/db');
var priceScrapers = require('priceScraper');
var LionPriceScrapers = priceScrapers.lion;
var cheerio = require('cheerio');
var Promise = require('bluebird');

function init(dt, scrape, args) {
	this._super('lion', dt, scrape, args);
	this.parallel = true;
	this._this = args._this;
	this.resFlight = args.resFlight;
}

function getAllRoutes() {
	var _this = this;
	var routes = [];
	var $ = cheerio.load(_this._scrape);
	var rms = $('td[id^=RM]')
		.html();
	if (!rms)
		return false;

	function looper(dir) {
		function getRow(i) {
			return $('tr[id^=RM' + dir + '_C' + i + ']');
		}
		var rowId = 0;
		var row = getRow(rowId);
		if (!row)
			return false;
		do {
			row.each(function(i, tr) {
				var rm = $('td[id^=RM]', tr)
					.html();
				if (!rm)
					return true;
				var currentRoute = rm.match(/[A-Z]{6}/)[0].toLowerCase();
				if (routes.indexOf(currentRoute) === -1) {
					routes.push(currentRoute);
				}
			});
			rowId++;
			row = getRow(rowId);
		} while (row.length);
	}
	looper(0);
	looper(1);
	return routes;
}

function mergeCache() {
	var _this = this;
	var _cache = _this.cache;
	var lowestPrices = {};
	var $ = cheerio.load(_this._scrape);
	var rms = $('td[id^=RM]')
		.html();
	if (!rms)
		return false;

	function looper(dir) {
		function getRow(i) {
			return $('tr[id^=RM' + dir + '_C' + i + ']');
		}
		var realRoute = _this._dt.ori.toLowerCase() + _this._dt.dst.toLowerCase();
		var rowId = 0;
		var row = getRow(rowId);
		if (!row)
			return false;
		do {
			var lowestPriceRows = [];
			row.each(function(i, tr) {
				var rm = $('td[id^=RM]', tr)
					.html();
				if (!rm)
					return true;
				var currentRoute = rm.match(/[A-Z]{6}/)[0].toLowerCase();
				if (!_this.cache[currentRoute])
					return true;
				var flightCode = $(tr)
					.find('td')
					.eq(0)
					.text()
					.trim()
					.substr(0, 2)
					.toLowerCase();
				// get all radio
				$('td[id] input[type=radio][id]', tr)
					.each(function(i, radio) {
						var span = $(radio)
							.parent();
						var available = $('label', span)
							.text();
						var classCode = span.attr('title')
							.substr(0, 1)
							.toLowerCase();
						var cachePrice = (_cache[currentRoute] &&
							_cache[currentRoute][flightCode] &&
							_cache[currentRoute][flightCode][classCode]) || 0;
						cachePrice = Math.round(cachePrice / 10) * 10;
						// update lowest price
						// if seat still available
						// and,
						// 	either lowest price for this route still 0
						//  	or
						//  	seat price cheaper than lowest price
						//  	but not zero
						if (!!available && (!lowestPrices[currentRoute] || (lowestPrices[currentRoute] > cachePrice && !!cachePrice)))
							lowestPrices[currentRoute] = cachePrice;
						// if in 'span' there is no '.rp' class and cachePrice is not zero
						if (!!cachePrice && !$('.rp', span)
							.length)
							span.append('rplion' + cachePrice + 'rplion');
					});
				lowestPriceRows.push(lowestPrices[currentRoute]);
			});
			// if there is more than one flight in on one row
			if (row.length > 1 && lowestPriceRows.length > 1 && _.every(lowestPriceRows)) {
				var lowestPriceRow = lowestPriceRows.reduce(function(price, num) {
					return num + price;
				}, 0);
				if (!lowestPrices[realRoute] || lowestPriceRow < lowestPrices[realRoute]) {
					lowestPrices[realRoute] = lowestPriceRow;
					// console.log(lowestPrices[realRoute], lowestPriceRow);
				}
			}
			rowId++;
			row = getRow(rowId);
		} while (row.length);
	}
	looper(0);
	looper(1);
	this._scrape = '' + $('body')
		.html() + '';
	return lowestPrices;
}
/**
 * return an array of object with ori, dst, class and flight property
 * @param  {Object} row Row object
 * @return {Array}     An array of object with ori, dst, class and flight property
 */
function getCheapestInRow(rowAll) {
	var _this = this;
	var seatRequest = _this.paxNum || 1;
	var outs = [];
	var classes, ori, dst, flight, flights;
	classes = ori = dst = flight = flights = '';
	var transitCounter = 0;
	var transits = [];
	var realDst = _this._dt.dst;
	var realOri = _this._dt.ori;
	var RT = false;
	_.each(rowAll, function(row, idx) {
		if(row.RT){
			var data = JSON.parse(JSON.stringify(_this._dt));
			realDst = data.ori;
			realOri = data.dst;
			RT = true;
			return true;
		}
		var aClass = Object.keys(row)
			.filter(function(b) {
				return b.length === 1;
			});
		var available = false;
		_.forEachRight(aClass, function(_class) {
			var matchAvailable = row[_class];
			if (!!matchAvailable) {
				if (+matchAvailable >= seatRequest) {
					available = true;
					classes += _class;
					return false;
				}
			}
		});
		if(!available)
			return true;
		flight = row.aircraft.replace(/\ /g, '-').toLowerCase();
		var rute = row.hidden.match(/[A-Z]{6}/)[0] || '';
		var pipe = '';
		if(flights.length>=1)
			pipe = '|';
		flights += pipe+flight;
		ori = rute.substr(0, 3);
		dst = rute.substr(3, 3);
		if (!rowAll[idx+1]
			|| (rowAll[idx+1] && (!rowAll[idx+1].connection || rowAll[idx+1].connection==0))){
			if(rowAll[idx].connection!=0 && flights.indexOf('|')=='-1'){
				classes = flights = '';
				transitCounter = 0;
				transits = [];
				return true;
			}
			if(RT){
				out = {
					ori: ori,
					dst: realDst,
					flight: flights,
					class: classes,
				};
			}else{
				out = {
					ori: realOri,
					dst: dst,
					flight: flights,
					class: classes,
				};
			}
			if (out.class.length === out.flight.split('|').length)
				outs.push(out);
			classes = flights = '';
			transitCounter = 0;
			transits = [];
		} else {
			transits[transitCounter++] = dst;
		}
	});
	/*throw('tes');*/
	debug('outs', outs);
	return outs;
}

/**
 * Generate data to scrape from id
 * @param  {String} id String id from database
 * @return {Object}    Object data for scrape
 */
function generateData(ids) {
	var dataAll = [];
	for(var i in ids){
		var id = ids[i];
		var _id = id.split('_');
		var cek_instant_id = _id[3] + '_' + _id[4];
		cek_instant_id = cek_instant_id.toUpperCase();
		var date = this._dt.dep_date;
		if(_id[1] == this._dt.ori.toLowerCase())
			date = this._dt.ret_date;
		var data = {
			ori: _id[0],
			dst: _id[1],
			airline: _id[2],
			flightCode: _id[3],
			classCode: _id[4],
			cek_instant: 1,
			cek_instant_id: cek_instant_id,
			dep_date: date,
			// dep_date      : moment().add(1, 'M').format('DD+MMM+YYYY'),
			rute: 'OW',
			dep_radio: cek_instant_id,
			action: 'price',
			xToken: this._dt.xToken,
		};
		for (var i = 5, j = 1, ln = _id.length; i < ln; i++, j++) {
			data['transit' + j] = _id[i];
		}
		dataAll.push(data);
	}
	return dataAll;
}

/**
 * Scrape lost data
 * @param  {String} id Data generated id to scrape
 * @return {Object}    Return cache data after scrape it
 */
function scrapeLostData(ids) {
	var _this = this;
	var dt = _this.generateData(ids);
    _this.modes = _this._this.defaultModes || ['100', '110', '111'];
	var options = {
		ids: dt,
		mode: _this.modes[0]
	};
	_this.oriData = JSON.parse(JSON.stringify(_this._dt));
	_this._this.data.query = dt[0];
    _this._this.data.query.rute = 'ow';
	_this.data = [];
	_this.data.query = this._dt;
	_this.allModes = [];
	_this.resultsPrice = [];
    _this._this.data.query.adult = options.mode[0];
    _this._this.data.query.child = options.mode[1];
    _this._this.data.query.infant = options.mode[2];
	return new Promise(function(resolve, reject){
		_this.getCache(options, 'idsDep', resolve);
	});
}

function getCache(options, note, resolve){
    var _this = this;
    _this.idsDep = [];
    _this.idsRet = [];
    for(var i in options.ids){
    	var id = options.ids[i];
    	if(id.ori.toLowerCase()==_this.oriData.ori.toLowerCase() || id.dst.toLowerCase()==_this.oriData.dst.toLowerCase()){
    		_this.idsDep.push(id);
    	}else{
    		_this.idsRet.push(id);
    	}
    }
    var that = _this._this;
    _this.allModes.push(options.mode);
    _this.relogModes = false;
    for(var i in _this.modes){
        if(!_this.allModes[i]){
            _this.relogModes = _this.modes[i];
            break;
        }
    }
    if(note=='idsRet'){
    	var newRute = _this.oriData.ori+'_'+_this.oriData.dst;
    	that.data.query.ori = newRute.split('_')[1];
    	that.data.query.dst = newRute.split('_')[0];
    	that.data.query.dep_date = _this.oriData.ret_date;
	    if(_this.idsRet.length==0)
	        that.resFlight = true;
    }else{
	    if(_this.idsDep.length==0)
	        that.resFlight = true;
    }
    debug(note, 'that.data.query', that.data.query, _this.relogModes, _this.modes, 'that.resFlight', that.resFlight);
    that.step1()
    .then(function(res){
        that.resFlight = res;
        var time = 0;
        var arrayPromise = _this[note].map(function (_dt) {
            return new Promise(function(resolve, reject){
            	setTimeout(function(){
            		resolve(_this.getPrice(_dt, that));
            	},time);
            	time = time+1000;
            });
        });
        Promise.all(arrayPromise)
        .then(function(res){
            that.resFlight = false;
            if(_this.relogModes){
                that.data.query.adult = _this.relogModes[0];
                that.data.query.child = _this.relogModes[1];
                that.data.query.infant = _this.relogModes[2];
                options.mode = _this.relogModes;
            	return _this.getCache(options, note, resolve);
            }else{
            	if(note!='idsRet' && _this.oriData.rute.toLowerCase()=='rt'){
					_this.allModes = [];
                	options.mode = that.defaultModes[0];
	                that.data.query.adult = options.mode[0];
	                that.data.query.child = options.mode[1];
	                that.data.query.infant = options.mode[2];
            		return _this.getCache(options, 'idsRet', resolve);
            	}else{
            		_this._dt.ori = _this.oriData.ori;
    				_this._dt.dst = _this.oriData.dst;
            		return resolve();
            	}
            }
        })
        .catch(function(err){
            debug(err.stack);
            return resolve();
        })
    })
    .catch(function(err){
        debug(err.stack);
        return resolve();
    })
}

function getPrice(_dt, that){
    var _this = this;
    var that = _this._this;
    return new Promise(function(resl, rejc){
    	_dt.adult = that.data.query.adult;
    	_dt.child = that.data.query.child;
    	_dt.infant = that.data.query.infant;
        var _data = JSON.parse(JSON.stringify(_dt));
        that.step1Price(_data)
        .then(function(res){
            that.jsonPrice(res)
            .then(function(results){
                var _id = _data.ori+'_'+_data.dst+'_'+_data.airline+'_'+_data.dep_radio;
                if(!_this.resultsPrice[_id]){
                    _this.resultsPrice[_id] = [];
                }
                _this.resultsPrice[_id].push(results)
                if(!_this.relogModes){
                    _this.saveCache(_this.resultsPrice[_id], _dt, function(err, res){
                        return resl(res);
                    });
                }else{
                    return resl(results);
                }
            })
            .catch(function(err){
                debug(err.stack);
                return resl(err);
            })
        })
        .catch(function(err){
            debug(err.stack);
            return resl(err);
        })
    })
    .catch(function(err){
        debug(err.stack);
        return Promise.resolve(err);
    })
}

function calculateAdult(results) {
	debug(JSON.stringify(results));
    var adult = results[0][0].price.total.replace(/\,/g, '').replace(/\./g,'');
    return parseInt(adult);
}

function calculateChild(results) {
    var child = results[0][0].price.total.replace(/\,/g, '').replace(/\./g,'');
    return parseInt(child);
}

function calculateInfant(results) {
    var total_100 = results[0][0].price.total.replace(/\,/g, '').replace(/\./g,'');
    var total_101 = results[1][0].price.total.replace(/\,/g, '').replace(/\./g,'');
    return total_101-total_100;
}

function calculateBasic(results) {
    var basic = results[0][0].price.published_fare.replace(/\,/g, '').replace(/\./g,'');
    return parseInt(basic);
}

/**
 * Merge json data with cheapest data from db
 * @param  {Object} json JSON formatted of scraped data
 * @return {Object}      JSON formatted of scraped data already merged with cache data
 */
function mergeCachePrices(json) {
	var seatRequest = this.paxNum || 1;
	var _json = _.cloneDeep(json);
	var _this = this;
	//debug('_this.cachePrices',JSON.stringify(_this.cachePrices));
	var departureCheapests = [];
	var returnCheapests = [];
	var lastDst, classes, ori, dst, flight, flights, realOri, realDst, rute, _rute;
	var _cheapest = {};
	classes = ori = dst = flight = flights = realOri = realDst = '';
	var transitCounter = 0;
	var transits = [];
	var rowIdx = 0;
	var realDst = _this._dt.dst;
	var realOri = _this._dt.ori;
	var allRow = _this.prepareRows(_json);
	var RT = false;
	_.each(allRow[0], function(row, idx) {
		if(row.RT){
			debug('mergeCachePrices rute is RT');
			var data = JSON.parse(JSON.stringify(_this._dt));
			realDst = data.ori;
			realOri = data.dst;
			RT = true;
			rowIdx = 0;
			return true;
		}
		var aClass = Object.keys(row)
			.filter(function(b) {
				return b.length === 1;
			});

		var format = ['DDMMM', 'DMMM'];
		var format2 = ['DDMMMHHmm', 'DMMMHHmm'];
		var hiddens = row.hidden.split('|');
		var date = moment(hiddens[3], format);
		var dayRangeForExpiredCheck = 2;
		var checkDate = moment()
			.add(dayRangeForExpiredCheck, 'day');
		_this.isSameDay = false;
		if (date.isBefore(checkDate, 'day'))
			_this.isSameDay = true;
		var depart = moment(hiddens[3] + hiddens[8], format2);
		var available = false;
		_.forEachRight(aClass, function(_class) {
			var matchAvailable = row[_class];
			if (!!matchAvailable) {
				if (+matchAvailable >= seatRequest) {
					if (_this.isBookable(depart)){
						available = true;
						classes += _class;
					}
					return false;
				}
			}
		});
		flight = row.aircraft.replace(/\ /g, '-').toLowerCase();
		var rute = row.hidden.match(/[A-Z]{6}/)[0] || '';
		var pipe = '';
		if(flights.length>=1)
			pipe = '|';
		flights += pipe+flight;
		ori = rute.substr(0, 3).toLowerCase();
		dst = rute.substr(3, 3).toLowerCase();
		if(RT)
			_rute = ori+realDst;
		else
			_rute = realOri+dst;
		if(!available){
			_this.cachePrices[_rute] = _this.cachePrices[_rute] || {};
			_this.cachePrices[_rute][flights] = _this.cachePrices[_rute][flights] || {};
			_cheapest = {
				class: 'Full'
			};
			if(RT)
				returnCheapests[rowIdx++] = _cheapest;
			else
				departureCheapests[rowIdx++] = _cheapest;
			classes = flights = '';
			transitCounter = 0;
			transits = [];
			_cheapest = {};
			return true;
		}
		if (!allRow[0][idx+1]
			|| (allRow[0][idx+1] && (!allRow[0][idx+1].connection || allRow[0][idx+1].connection==0))){
			if(allRow[0][idx].connection!=0 && flights.indexOf('|')=='-1'){
				classes = flights = '';
				transitCounter = 0;
				transits = [];
				_cheapest = {};
				return true;
			}
			try {
				_cheapest.prices = _this.cachePrices[_rute][flights.toLowerCase()][classes.toLowerCase()];
				_cheapest.class = classes;
				_cheapest.flights = flights;
			} catch (e) {
				debug(e.stack, _rute, flights, classes);
				_this.cachePrices[_rute] = _this.cachePrices[_rute] || {};
				_this.cachePrices[_rute][flights] = _this.cachePrices[_rute][flights] || {};
				_cheapest = {
					class: 'Full'
				};
			}
			if(RT)
				returnCheapests[rowIdx++] = _cheapest;
			else
				departureCheapests[rowIdx++] = _cheapest;
			classes = flights = '';
			transitCounter = 0;
			transits = [];
			_cheapest = {};
		} else {
			transits[transitCounter++] = dst;
		}
	});
	_json.cachePrices = _this.cachePrices;
	_json[0].dep_cheapests = departureCheapests;
	if(_this._dt.rute.toLowerCase()=='rt' || _this.oriData && _this.oriData.rute=='rt'){
		_json[0].ret_cheapests = returnCheapests;
	}
	return _json;
}

/**
 * Preparing rows to be looped on process
 * @param  {Object} json JSON formatted data from scraping
 * @return {Object}      Array of rows to be looped for getAkkCheaoest function
 */
function prepareRows(json) {
	var _json = _.cloneDeep(json[0]);
	var rows = [];
	rows = rows.concat(_.values(_json.dep_table));
	if (!!_json.ret_table[0])
		rows = rows.concat({ RT:true }, _.values(_json.ret_table));
	return [rows];
}

function getCalendarPrice(json) {
	var _this = this;
	var format = ['DDMMM', 'DMMM'];
	var format2 = ['DDMMMHHmm', 'DMMMHHmm'];
	return new Promise(function(resolve, reject) {
		if (!json[0].dep_table || !json[0].dep_table[0])
			return resolve();
		var hiddens = json[0].dep_table[0].hidden.split('|');
		var date = moment(hiddens[3], format);
		var dayRangeForExpiredCheck = 2;
		var checkDate = moment()
			.add(dayRangeForExpiredCheck, 'day');
		_this.isSameDay = false;
		if (date.isBefore(checkDate, 'day'))
			_this.isSameDay = true;
		var cheapests = [];
		var realDst = _this._dt.dst;
		var rowIdx = 0;
		_.each(json[0].dep_table, function(flight, i) {
			var rute = flight.hidden.match(/[A-Z]{6}/)[0] || '';
			dst = rute.substr(3, 3).toLowerCase();
			if (dst === realDst.toLowerCase()) {
				hiddens = flight.hidden.split('|');
				var depart = moment(hiddens[3] + hiddens[8], format2);
				if (_this.isBookable(depart)){
					try{
						if (json[0].dep_cheapests[rowIdx].prices){
							cheapests.push(json[0].dep_cheapests[rowIdx]);
						}
					}catch(e){
						debug('getCalendarPrice',json[0].dep_cheapests[rowIdx]);
					}
					rowIdx++;
				}
			}
		});
		debug('before filter %d', rowIdx);
		debug('after filter %d', cheapests.length);
		if((_this._dt.rute.toLowerCase()=='rt' || _this.oriData && _this.oriData.rute=='rt')
			 && json[0].ret_table && json[0].ret_table[0]){
			var hiddens = json[0].ret_table[0].hidden.split('|');
			var date = moment(hiddens[3], format);
			var dayRangeForExpiredCheck = 2;
			var checkDate = moment()
				.add(dayRangeForExpiredCheck, 'day');
			_this.isSameDay = false;
			if (date.isBefore(checkDate, 'day'))
				_this.isSameDay = true;
			var retCheapests = [];
			var rowIdx = 0;
			_.each(json[0].ret_table, function(flight, i) {
				hiddens = flight.hidden.split('|');
				var depart = moment(hiddens[3] + hiddens[8], format2);
				if (_this.isBookable(depart)){
					try{
						if (json[0].ret_cheapests[rowIdx].prices){
							retCheapests.push(json[0].ret_cheapests[rowIdx]);
						}
					}catch(e){
						debug('getCalendarPrice',json[0].ret_cheapests[rowIdx]);
					}
					rowIdx++;
				}
			});
			debug('return before filter %d', _.size(json[0].ret_table));
			debug('return after filter %d', retCheapests.length);
		}
		var cheapestFlight = _.min(cheapests, function(cheapest, i) {
			debug('cheapests: %j', cheapest.prices.adult);
			return cheapest.prices.adult;
		});
		return resolve(cheapestFlight.prices);
	});
}

var LionPrototype = {
	init: init,
	getAllRoutes: getAllRoutes,
	mergeCache: mergeCache,
	getCheapestInRow: getCheapestInRow,
	generateData: generateData,
	scrapeLostData: scrapeLostData,
	mergeCachePrices: mergeCachePrices,
	prepareRows: prepareRows,
	getCalendarPrice: getCalendarPrice,
	getCache: getCache,
	getPrice: getPrice,
	calculateAdult: calculateAdult,
	calculateChild: calculateChild,
	calculateInfant: calculateInfant,
	calculateBasic: calculateBasic,
};
var Lion = Base.extend(LionPrototype);
module.exports = Lion;