text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>colors.css</title>
<meta name="Author" content="Czigler Ferenc">
<meta name="Copyright" content="(C) Copyright Czigler Ferenc All Rights Reserved.">

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

colors.css download page

Download

Compressed version: colors.min.css

Development version: colors.css

Latest version: 1.0.3

Formats

Background colors: .bg-colorname

Text colors: .color-colorname

Border colors: .border-colorname

Fills for SVG: .fill-colorname

Strokes for SVG: .stroke-colorname

Background colors

Basic colors

bg-blue

bg-red

bg-white

bg-silver

bg-gray

bg-grey

bg-lightgray

bg-lightgrey

bg-black

bg-maroon

bg-yellow

bg-olive

bg-lime

bg-green

bg-teal

bg-aqua

bg-navy

bg-fuchsia

bg-purple

bg-cyan

bg-darkblue

bg-lightblue

bg-magenta

bg-orange

bg-brown

bg-pink

bg-indigo

bg-darkgrey

bg-darkgray

bg-steelblue

Material colors

bg-material-red

bg-material-pink

bg-material-purple

bg-material-deeppurple

bg-material-indigo

bg-material-blue

bg-material-lightblue

bg-material-cyan

bg-material-teal

bg-material-green

bg-material-lime

bg-material-lightgreen

bg-material-yellow

bg-material-amber

bg-material-orange

bg-material-deeporange

bg-material-brown

bg-material-grey

bg-material-gray

bg-material-bluegrey

bg-material-bluegray

bg-material-black

bg-material-white

Corporate colors

bg-google-blue

bg-google-yellow

bg-google-green

bg-google-red

bg-facebook-blue1

bg-facebook-blue2

bg-facebook-blue3

bg-facebook-grey

bg-facebook-white

bg-microsoft-orange

bg-microsoft-green

bg-microsoft-blue

bg-microsoft-yellow

bg-twitter-blue

bg-twitter-grey1

bg-twitter-grey2

bg-twitter-grey3

bg-twitter-grey4

bg-twitter-white

bg-instagram

bg-intel

bg-ibm

bg-yahoo

bg-amazon-yellow

bg-amazon-blue

bg-netflix-black

bg-netflix-red

bg-cocacola

bg-pepsi-red

bg-pepsi-blue

bg-ikea-yellow

bg-ikea-blue

Other colors

bg-riverside

bg-airyblue

bg-sharkskin

bg-aurorared

bg-warmtaupe

bg-dustycedar

bg-lushmedow

bg-spicymustard

bg-pottersclay

bg-bodacious

bg-peachecho

bg-serenity

bg-snorkelblue

bg-limpetshell

bg-lilacgrey

bg-icedcoffee

bg-fiesta

bg-buttercup

bg-greenflash

bg-rosequartz

bg-marsala

bg-radiandorchid

bg-emerald

bg-tangerinetango

bg-honeysucle

bg-turquise

bg-mimosa

bg-blueizis

bg-chilipepper

bg-sanddollar

bg-blueturquoise

bg-tigerlily

bg-aquasky

bg-truered

bg-fuchsiarose

bg-ceruleanblue

bg-midnightblue

bg-slategray

bg-lightslategrey

bg-royalblue

bg-eu-gold

bg-eu-navy

iOS colors

bg-ios-red

bg-ios-orange

bg-ios-yellow

bg-ios-green

bg-ios-teal

bg-ios-blue

bg-ios-purple

bg-ios-pink

bg-ios-indigo

bg-ios-red-dark

bg-ios-orange-dark

bg-ios-yellow-dark

bg-ios-green-dark

bg-ios-teal-dark

bg-ios-blue-dark

bg-ios-purple

bg-ios-pink-dark

bg-ios-indigo-dark

bg-ios-grey1

bg-ios-grey2

bg-ios-grey3

bg-ios-grey4

bg-ios-grey5

bg-ios-grey6

bg-ios-grey1-dark

bg-ios-grey2-dark

bg-ios-grey3-dark

bg-ios-grey4-dark

bg-ios-grey5-dark

bg-ios-grey6-dark

By Adam Morse (MIT license)

bg-mrmrs-navy

bg-mrmrs-blue

bg-mrmrs-aqua

bg-mrmrs-teal

bg-mrmrs-olive

bg-mrmrs-green

bg-mrmrs-lime

bg-mrmrs-yellow

bg-mrmrs-orange

bg-mrmrs-red

bg-mrmrs-fuchsia

bg-mrmrs-purple

bg-mrmrs-maroon

bg-mrmrs-white

bg-mrmrs-gray

bg-mrmrs-silver

bg-mrmrs-black

Text colors

Basic colors

color-blue

color-red

color-white

color-silver

color-gray

color-grey

color-lightgray

color-lightgrey

color-black

color-maroon

color-yellow

color-olive

color-lime

color-green

color-teal

color-aqua

color-navy

color-fuchsia

color-purple

color-cyan

color-darkblue

color-lightblue

color-magenta

color-orange

color-brown

color-pink

color-indigo

color-darkgrey

color-darkgray

color-steelblue

Material colors

color-material-red

color-material-pink

color-material-purple

color-material-deeppurple

color-material-indigo

color-material-blue

color-material-lightblue

color-material-cyan

color-material-teal

color-material-green

color-material-lime

color-material-lightgreen

color-material-yellow

color-material-amber

color-material-orange

color-material-deeporange

color-material-brown

color-material-grey

color-material-gray

color-material-bluegrey

color-material-bluegray

color-material-black

color-material-white

Corporate colors

color-google-blue

color-google-yellow

color-google-green

color-google-red

color-facebook-blue1

color-facebook-blue2

color-facebook-blue3

color-facebook-grey

color-facebook-white

color-microsoft-orange

color-microsoft-green

color-microsoft-blue

color-microsoft-yellow

color-twitter-blue

color-twitter-grey1

color-twitter-grey2

color-twitter-grey3

color-twitter-grey4

color-twitter-white

color-instagram

color-intel

color-ibm

color-yahoo

color-amazon-yellow

color-amazon-blue

color-netflix-black

color-netflix-red

color-cocacola

color-pepsi-red

color-pepsi-blue

color-ikea-yellow

color-ikea-blue

Other colors

color-riverside

color-airyblue

color-sharkskin

color-aurorared

color-warmtaupe

color-dustycedar

color-lushmedow

color-spicymustard

color-pottersclay

color-bodacious

color-peachecho

color-serenity

color-snorkelblue

color-limpetshell

color-lilacgrey

color-icedcoffee

color-fiesta

color-buttercup

color-greenflash

color-rosequartz

color-marsala

color-radiandorchid

color-emerald

color-tangerinetango

color-honeysucle

color-turquise

color-mimosa

color-blueizis

color-chilipepper

color-sanddollar

color-blueturquoise

color-tigerlily

color-aquasky

color-truered

color-fuchsiarose

color-ceruleanblue

color-midnightblue

color-slategray

color-lightslategrey

color-royalblue

color-eu-gold

color-eu-navy

iOS colors

color-ios-red

color-ios-orange

color-ios-yellow

color-ios-green

color-ios-teal

color-ios-blue

color-ios-purple

color-ios-pink

color-ios-indigo

color-ios-red-dark

color-ios-orange-dark

color-ios-yellow-dark

color-ios-green-dark

color-ios-teal-dark

color-ios-blue-dark

color-ios-purple

color-ios-pink-dark

color-ios-indigo-dark

color-ios-grey1

color-ios-grey2

color-ios-grey3

color-ios-grey4

color-ios-grey5

color-ios-grey6

color-ios-grey1-dark

color-ios-grey2-dark

color-ios-grey3-dark

color-ios-grey4-dark

color-ios-grey5-dark

color-ios-grey6-dark

By Adam Morse (MIT license)

color-mrmrs-navy

color-mrmrs-blue

color-mrmrs-aqua

color-mrmrs-teal

color-mrmrs-olive

color-mrmrs-green

color-mrmrs-lime

color-mrmrs-yellow

color-mrmrs-orange

color-mrmrs-red

color-mrmrs-fuchsia

color-mrmrs-purple

color-mrmrs-maroon

color-mrmrs-white

color-mrmrs-gray

color-mrmrs-silver

color-mrmrs-black

Border colors

Basic colors

border-blue

border-red

border-white

border-silver

border-gray

border-grey

border-lightgray

border-lightgrey

border-black

border-maroon

border-yellow

border-olive

border-lime

border-green

border-teal

border-aqua

border-navy

border-fuchsia

border-purple

border-cyan

border-darkblue

border-lightblue

border-magenta

border-orange

border-brown

border-pink

border-indigo

border-darkgrey

border-darkgray

border-steelblue

Material colors

border-material-red

border-material-pink

border-material-purple

border-material-deeppurple

border-material-indigo

border-material-blue

border-material-lightblue

border-material-cyan

border-material-teal

border-material-green

border-material-lime

border-material-lightgreen

border-material-yellow

border-material-amber

border-material-orange

border-material-deeporange

border-material-brown

border-material-grey

border-material-gray

border-material-bluegrey

border-material-bluegray

border-material-black

border-material-white

Corporate colors

border-google-blue

border-google-yellow

border-google-green

border-google-red

border-facebook-blue1

border-facebook-blue2

border-facebook-blue3

border-facebook-grey

border-facebook-white

border-microsoft-orange

border-microsoft-green

border-microsoft-blue

border-microsoft-yellow

border-twitter-blue

border-twitter-grey1

border-twitter-grey2

border-twitter-grey3

border-twitter-grey4

border-twitter-white

border-instagram

border-intel

border-ibm

border-yahoo

border-amazon-yellow

border-amazon-blue

border-netflix-black

border-netflix-red

border-cocacola

border-pepsi-red

border-pepsi-blue

border-ikea-yellow

border-ikea-blue

Other colors

border-riverside

border-airyblue

border-sharkskin

border-aurorared

border-warmtaupe

border-dustycedar

border-lushmedow

border-spicymustard

border-pottersclay

border-bodacious

border-peachecho

border-serenity

border-snorkelblue

border-limpetshell

border-lilacgrey

border-icedcoffee

border-fiesta

border-buttercup

border-greenflash

border-rosequartz

border-marsala

border-radiandorchid

border-emerald

border-tangerinetango

border-honeysucle

border-turquise

border-mimosa

border-blueizis

border-chilipepper

border-sanddollar

border-blueturquoise

border-tigerlily

border-aquasky

border-truered

border-fuchsiarose

border-ceruleanblue

border-midnightblue

border-slategray

border-lightslategrey

border-royalblue

border-eu-gold

border-eu-navy

iOS colors

border-ios-red

border-ios-orange

border-ios-yellow

border-ios-green

border-ios-teal

border-ios-blue

border-ios-purple

border-ios-pink

border-ios-indigo

border-ios-red-dark

border-ios-orange-dark

border-ios-yellow-dark

border-ios-green-dark

border-ios-teal-dark

border-ios-blue-dark

border-ios-purple

border-ios-pink-dark

border-ios-indigo-dark

border-ios-grey1

border-ios-grey2

border-ios-grey3

border-ios-grey4

border-ios-grey5

border-ios-grey6

border-ios-grey1-dark

border-ios-grey2-dark

border-ios-grey3-dark

border-ios-grey4-dark

border-ios-grey5-dark

border-ios-grey6-dark

By Adam Morse (MIT license)

border-mrmrs-navy

border-mrmrs-blue

border-mrmrs-aqua

border-mrmrs-teal

border-mrmrs-olive

border-mrmrs-green

border-mrmrs-lime

border-mrmrs-yellow

border-mrmrs-orange

border-mrmrs-red

border-mrmrs-fuchsia

border-mrmrs-purple

border-mrmrs-maroon

border-mrmrs-white

border-mrmrs-gray

border-mrmrs-silver

border-mrmrs-black

© Copyright 2016 Ferenc Czigler


text:
"use strict";

/*global module, require*/

var d3 = require("d3"),
    allTypes = d3.set(
	require("./process-node.js").keys()
    ),
    intersection = function(a, b) {
	return d3.set(a.values().filter(function(o) {
	    return b.has(o);
	}));
    };

/*
 Works out what types are valid for an undecided node to become.
 */
module.exports = function(node, nodeCollection) {
    if (node.type !== "undecided") {
	throw new Error("Only appropriate for undecided nodes.");
    }

    var allowed = allTypes;

    nodeCollection.edgesToNode(node)
	.forEach(function(e) {
	    allowed = intersection(allowed, e.parent().allowedChildren);
	});

    allowed.remove("undecided");

    return allowed;
};

redpajama_set_name: RedPajamaGithub


text:
require 'pp'
module Awssh
  class Command
    def initialize(argv)
      @options = {
          verbose: false,
          config: '~/.awssh',
          multi: false,
          test: false,
          list: false,
          identity: nil,
      }
      @config = {
          multi: 'csshX',
          single: 'ssh',
          user: nil,
          use_names: false,
          cache: '~/.awssh.cache',
          expires: 1.day
      }.stringify_keys

      @config_file = File.expand_path(@options[:config])
      Awssh::Config.load(@config_file)
      @config = Awssh::Config.data

      OptionParser.new do |opts|
        opts.banner = "Usage: awssh [options] [search terms]"

        opts.separator ''
        opts.separator 'Search Terms:'
        opts.separator '  matches against AWS Tag "Name"'
        opts.separator '  positive check for each entry'
        opts.separator '    name =~ /term/'
        opts.separator '  negative check if the term starts with ^'
        opts.separator '    name !~ /term/'
        opts.separator ''
        opts.separator 'Options:'
        opts.on('-c', "--config", "override config file (default: ~/.awssh)") do |c|
          @options[:config] = c
        end
        opts.on('-V', '--version', 'print version') do |v|
          puts "awssh version: #{Awssh::Version::STRING}"
          exit 0
        end
        opts.on('-iIDENTITY', '--identity=IDENTITY', 'set ssh key') do |i|
          @options[:identity] = i
        end
        opts.on('--init', 'initialize config') do |i|
          path = File.expand_path(@options[:config])
          puts "creating config file: #{path}"
          if File.exists?(path)
            backup = "#{path}.#{Time.now.to_i}"
            puts "moving previous config to #{backup}"
            FileUtils.mv(path, backup)
          end
          File.open(path, "w+") { |f| f.write Awssh::Config::DEFAULT }
          exit 0
        end
        opts.separator ''
        opts.on('-l', '--list', 'just list servers') do |l|
          @options[:list] = true
        end
        opts.on('-n', '--test', 'just output ssh command') do |n|
          @options[:test] = n
        end
        opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
          @options[:verbose] = v
        end

        opts.separator ''
        opts.on('-U', '--update', 'just update the cache') do |u|
          @options[:update] = true
        end
        opts.on('--no-cache', 'disable cache for this run') do |u|
          @config.cache = false
        end
        opts.separator ''
        opts.on('-m', '--[no-]multi', 'connect to multiple servers') do |m|
          @options[:multi] = m
        end
        opts.on('-u', '--user USER', 'override user setting') do |u|
          @config.user = u
        end
      end.parse!(argv)

      @cloud = Awssh::Cloud.connect(@config.key, @config.secret, @config.region)
      @cache = Awssh::Cache.new(@config.cache, @config.expires||1.day)
      @search = argv

      if @options[:update]
        cache(:servers, true) { @cloud.servers }
        exit 0
      end

      if @options[:verbose]
        puts "options: #{@options.inspect}"
        puts "config: #{@config.inspect}"
      end
    end

    def run
      @servers = cache(:servers) { @cloud.servers }
      search = Awssh::Search.new(@servers, @search)
      list = search.filter
      hosts = hosts(list)

      if hosts.count == 0
        puts "no servers found."
        exit 1
      end

      multi_not_multi = (hosts.count > 1 && !@options[:multi])

      if @options[:list] || @options[:verbose] || multi_not_multi
        puts_hosts(hosts)
      end
      puts "#{hosts.count} servers found" if @options[:verbose]
      exit 0 if @options[:list]
      if multi_not_multi
        puts "more than one server found and multi is false"
        puts "use the -m flag to connect to multiple servers"
        exit 1
      end

      connect(hosts)
    end

    def connect(hosts)
      cmd = command(hosts)
      if @options[:test] || @options[:verbose]
        puts cmd
      end
      exec(cmd) unless @options[:test]
    end

    def command(hosts)
      id = @options[:identity] ? "-i #{@options[:identity]}" : nil
      if @options[:multi]
        command = "#{@config.multi} #{id} #{hosts.map { |e| host(e) }.join(' ')}"
      else
        command = "#{@config.single} #{id} #{host(hosts.first)}"
      end
      command
    end

    def cache(key, force=!@config.cache, &block)
      @cache.fetch(key, force, &block)
    end

    def hosts(list)
      list.map do |l|
        (id,_) = l.split('||')
        @servers.to_a.detect {|e| e[:id] == id}
      end.compact.sort_by {|e| e[:name]}
    end

    def host(host)
      out = []
      out << "#{@config.user}@" if @config.user
      if @config.use_names
        out << [host[:name], @config.domain].compact.join('.')
      else
        out << host[:private]
      end
      out.join('')
    end

    def puts_hosts(hosts)
      hosts.each do |host|
        puts "%10s   %-15s   %s" % [host[:id], host[:private], host[:name]]
      end
    end
  end
end


text:
module.exports = {
  path: '/demo(/)',
  getChildRoutes(location, callback) {
    require.ensure([], function (require) {
      callback(null, [
        // require('./login/'),
        require('./noredux/'),
      ])
    })
  },
  getIndexRoute(location, callback) {
    require.ensure([], function (require) {
      callback(null, require('./default/'))
    })
  },
  getComponent(nextState, cb) {
    require.ensure([], (require) => {
      cb(null, require('containers/Domain').default)
    })
  },
}


text:
package leap.orm.mapping;

import leap.db.model.DbColumn;
import leap.db.model.DbColumnBuilder;
import leap.db.model.DbSchema;
import leap.db.model.DbTable;
import leap.orm.metadata.MetadataContext;
import leap.orm.metadata.MetadataException;

public class SchemaMappingProcessor extends MappingProcessorAdapter {

	@Override
    public void postMappingEntity(MetadataContext context, EntityMappingBuilder emb) throws MetadataException {
		if(!context.getConfig().isReadDbSchema()) {
			return;
		}
		if(null == context.getDb()) {
			return;
		}

		String entityName = emb.getEntityName();

		DbSchema schema = context.getDb().getMetadata().getSchema(emb.getTableCatalog(),emb.getTableSchema());
		if(null == schema) return;

		//find matched table name in db schema
		DbTable  table;
		if(!emb.isTableNameDeclared()){
			table = findTableOf(context, entityName, schema);
		}else{
			table = schema.findTable(emb.getTableName());
		}

		if(null != table){
			mappingTableToEntity(context, table, emb);
		}
    }

	@Override
    public void finalMappingEntity(MetadataContext context, EntityMappingBuilder emb) throws MetadataException {
		DbTable table = emb.getPhysicalTable();

		if(null != table){
			//Checks the declared id fields and primary key columns.
			if(emb.isIdDeclared() && !table.isView()) {
				if(table.getPrimaryKeyColumns().length != emb.getIdFieldMappings().size()) {
					throw new MappingConfigException("The declared id fields(" + emb.getIdFieldMappings().size() +
													 ") do not match the primary key columns(" + table.getPrimaryKeyColumns().length +
													 ") in entity '" + emb.getEntityName() + "'");
				}

				for(DbColumn pk : table.getPrimaryKeyColumns()) {
					FieldMappingBuilder fmb = findFieldOf(context, pk, emb);
					if(null == fmb) {
						throw new MappingConfigException("Id field must be declared in entity '" + emb.getEntityName() +
														 "' for primary key column '" + pk.getName() + "' in table '" + table.getName() + "'");
					}
				}
			}

			for(FieldMappingBuilder fmb : emb.getFieldMappings()) {
				DbColumn column;

				if(!fmb.isColumnNameDeclared()) {
					column = findColumnOf(context, table, fmb);
				}else{
					column = table.findColumn(fmb.getColumn().getName());
				}

				if(null != column) {
					mappingColumnToField(context, table, column, emb, fmb);
				}
			}

            if(emb.isAutoGenerateColumns()) {
                for (DbColumn column : table.getColumns()) {
                    FieldMappingBuilder fmb = emb.findFieldMappingByColumn(column.getName());
                    if (null == fmb && (context.getMappingStrategy().isAutoGeneratedColumn(context, column) || column.isPrimaryKey())) {
                        emb.addFieldMapping(context.getMappingStrategy().createFieldMappingByColumn(context, emb, column));
                    }
                }
            }
		}
    }

	protected void mappingTableToEntity(MetadataContext context, DbTable table,EntityMappingBuilder emb) {
		emb.setTableName(context.getNamingStrategy().tableName(table.getName()));
		emb.setPhysicalTable(table);
	}

	protected void mappingColumnToField(MetadataContext context,
										DbTable table,DbColumn column,
										EntityMappingBuilder emb,FieldMappingBuilder fmb){

		DbColumnBuilder cb = new DbColumnBuilder(column);
        if(table.isView() && fmb.isId()) {
            cb.setPrimaryKey(true);
            cb.setNullable(false);
        }

        cb.setName(context.getNamingStrategy().columnName(cb.getName()));
        fmb.setColumn(cb);
        fmb.setHasPhysicalColumn(true);

		if(null == fmb.getNullable()){
			fmb.setNullable(cb.isNullable());
		}
	}

	protected FieldMappingBuilder findFieldOf(MetadataContext context,DbColumn column,EntityMappingBuilder emb){
		for(FieldMappingBuilder fmb : emb.getFieldMappings()){
			if(fmb.isColumnNameDeclared() && fmb.getColumn().getName().equalsIgnoreCase(column.getName())) {
				return fmb;
			}

			if(context.getNamingStrategy().isColumnOfField(column.getName(), fmb.getFieldName())){
				return fmb;
			}
		}
		return null;
	}

	protected DbColumn findColumnOf(MetadataContext context,DbTable table, FieldMappingBuilder fmb ){
		for(DbColumn column : table.getColumns()) {
			if(context.getNamingStrategy().isColumnOfField(column.getName(), fmb.getFieldName())) {
				return column;
			}
		}
		return null;
	}

	protected DbTable findTableOf(MetadataContext context, String entityName,DbSchema schema){
		for(DbTable table : schema.getTables()){
			if(context.getNamingStrategy().isTableOfEntity(table.getName(), entityName)){
				return table;
			}
		}

		if(context.getConfig().isAutoMappingTableWithAcronym()) {
			for (DbTable table : schema.getTables()) {
				if (context.getNamingStrategy().isTableOfWithAcronym(table.getName(), entityName)) {
					return table;
				}
			}
		}

		return null;
	}
}


text:
function [mode_loc,mode_y,evaluations,nmmso_state] =  NMMSO_iterative( ...
    swarm_size, problem_func,problem_function_params, max_evaluations, ...
    mn,mx,evaluations,nmmso_state,max_evol,tol_val)

% Implementation of the Niching Migratory Multi-Swarm Optimser, described
% in:
% "Running Up Those Hills: Multi-Modal Search with the Niching Migratory
% Multi-Swarm Optimiser"
% by Jonathan E. Fieldsend
% published in Proceedings of the IEEE Congress on Evolutionary Computation,
% pages 2593-2600, 2014
%
% Please reference this paper if you undertake work utilising this code.
% Implementation (c) by Jonathan Fieldsend, University of Exeter, 2014
%
% Assumes function maximisation
%
% REQUIRED ARGUMENTS
%
% swarm_size = maximum number of elements (particles) per swarm
% problem_func = string containing name of function to be optimised
% problem_funcion_params = meta-parameters needed by problem function
%   (distinct from optimisation (design) parameters
% max_evaluations = maximum number of evaluations to be taken through the
%   problem function
% mn = minimum design parameter values (a vector with param_num elements)
% mx = maximum design parameter values (a vector with param_num elements)
% evaluations = number of evaluations expended already. If set at 0, this
%   will initialise the swarm_state structure and run the algorithm for a
%   single generation, otherwise it will run it for a single generation
%   from the evaluations number inputted
% swarm_state = structure holding state of swarm. Can be empty or omitted
%   if evaluations set at zero, must be provided if evals > 0
%
% OPTIONAL ARGUMENTS
%
% max_evol = maximum number of swarms to update in a generation. If not
%   provided this is set at 100
% tol_val = tolerance value for merging automatically (default 10^-6)
%
% OUTPUTS
%
% mode_loc = design space location of current mode estimates (swarm
%   gbests), note that at least one is likely to be very poor due to the
%   new swarm spawning at the end of each generation, and that these will
%   be a combination of both global and local mode estimate
% mode_y = function evalutions corresponding to the mode estimates
% evaluations = number of problem function evaluations until this point
% nmmso_state = structure holding the state of the swarms. Unless you want
%   to pick apart the details of how the algorithm searchs the space, then
%   the only two elements you will probably be interested in are X and Y
%   which are preallocated matrices to hold all locations visited
%   (therefore nmmso_state.X(1:evaluations,:) will hold all the design
%   space locations visited by the optimiser thus far.
%
% Thanks to Chris Wood and Ally Hume at the Edinburgh Parallel
% Computing Centre for identifying the error in the max_evol check
% and indice selection in the evolve subroutine

if (evaluations < 0)
   error('Must run algorithm for a positive number of function evaluations');
end
if exist('max_evol','var') == 0
    disp('default max_eval used, set at 100');
    max_evol = 100;
end

if max_evol <= 0
    disp('Max_eval cannot be negative or zero, default max_eval used, set at 100');
    max_evol = 100;
end

if exist('tol_val','var') == 0
    disp('default tol_val used, set at 10^-6');
    tol_val = 10^-6;
end

if evaluations == 0
    % preallocate matrices for speed, with a buffer at end in case of final
    % generation exploring begound max_evaluations limit
    nmmso_state.X = zeros(max_evaluations+500,length(mx));
    nmmso_state.Y = zeros(max_evaluations+500,1);
    nmmso_state.index = 1;
    nmmso_state.converged_modes = 0;

    % get initial locations
    [nmmso_state] = get_initial_locations(nmmso_state,mn,mx);
    [swarm,nmmso_state] = evaluate_first(...
        nmmso_state.active_modes(1).swarm,problem_func,problem_function_params,nmmso_state,swarm_size,mn,mx);
    nmmso_state.active_modes(1).swarm=swarm;
    % track number of evaluations taken
    evaluations = 1;

    % keep modes in matrices for effciency on some computations
    nmmso_state.M_loc =  nmmso_state.active_modes(1).swarm.mode_location;
    nmmso_state.V_loc = nmmso_state.active_modes(1).swarm.mode_value;
    nmmso_state.tol_val = tol_val;
end

if (evaluations<max_evaluations) % if limited evalutions not already exhausted/exceeded
    % first see if modes should be merged together
    number_of_mid_evals=0;
    while sum(nmmso_state.active_modes_changed) > 0
        [nmmso_state,merge_evals] = merge_swarms(nmmso_state,problem_func,problem_function_params,mn,mx);
        number_of_mid_evals = number_of_mid_evals+merge_evals; % track function evals used
    end

    % Now increment the swarms
    % if we have more than max_evol, then only increment a subset
    limit = min(max_evol,length(nmmso_state.active_modes));
    if length(nmmso_state.active_modes)>max_evol % have to select a subset
        if rand()<0.5 % select fittest
            [~, fit_I] = sort(nmmso_state.V_loc,'descend');
        else % select at random
            fit_I = randperm(length(nmmso_state.V_loc));
        end
    else
        fit_I = 1:limit; % can increment all
    end
    I2 = fit_I(1:limit);

    % increment
    for jj=1:length(I2)
        [nmmso_state] = increment_swarm(nmmso_state,I2(jj),mn,mx,swarm_size);
    end
    % evaluate new member/new locations of swarm member
    [nmmso_state,number_of_new_locations] = evaluate_new_locations(nmmso_state,problem_func,problem_function_params,I2);

    % attempt to split off a member from one of the swarms to seed a new
    % swarm (if detected to be on another peak)
    [nmmso_state,number_of_hive_samples] = hive(nmmso_state,problem_func,mn,mx,problem_function_params,max_evol,swarm_size);

    % create speculative new swarm, either at random in design space, or
    % via crossover
    if (rand()<0.5 || (length(nmmso_state.active_modes)==1) || (length(mx)==1) || (max_evol==1))
        number_of_evol_modes=0;
        [nmmso_state,number_rand_modes] = random_new(nmmso_state,problem_func,mn,mx,problem_function_params,swarm_size);
    else
        number_rand_modes=0;
        [nmmso_state,number_of_evol_modes] = evolve(nmmso_state,problem_func,mn,mx,problem_function_params,max_evol,swarm_size);
    end

    % update the total number of function evaluations used, with those
    % required at each of the algorithm stages
    evaluations = evaluations+number_of_mid_evals+number_of_new_locations+number_of_evol_modes+number_rand_modes+number_of_hive_samples;

    fprintf('Number of swarms %d, evals %d, max mode est. %f\n',length(nmmso_state.active_modes),evaluations,max(nmmso_state.V_loc));
    fprintf('\n');
else
    display('Evaluations taken already exhuasted/exceeded');
end

% get mode estimate locations
[mode_loc,mode_y] = extract_modes(nmmso_state);

%--------------------------------------------------------------------------
function [RES,RES_Y] = extract_modes(nmmso_state)

RES = zeros(length(nmmso_state.active_modes), length(nmmso_state.active_modes(1).swarm.mode_location));
RES_Y = zeros(length(nmmso_state.active_modes),1);

for i=1:length(nmmso_state.active_modes)
    RES(i,:) = nmmso_state.active_modes(i).swarm.mode_location;
    RES_Y(i) = nmmso_state.active_modes(i).swarm.mode_value;
end

%--------------------------------------------------------------------------
function [nmmso_state] = get_initial_locations(nmmso_state,mn,mx)

nmmso_state.active_modes(1).swarm.new_location=rand(size(mx)).*(mx-mn)+mn;
nmmso_state.active_modes_changed(1) = 1;

%--------------------------------------------------------------------------
function [swarm,nmmso_state] = evaluate_first(swarm,problem_func,problem_function_params,nmmso_state,swarm_size,mn,mx)

% new_location is the only solution thus far in mode, so by definition is
% also the mode estimate, and the only history thus far

y = feval(problem_func, swarm.new_location,problem_function_params);
swarm.mode_location = swarm.new_location; %gbest location
swarm.mode_value = y; %gbest value

% initialise containers for swarm elements
swarm.history_locations = zeros(swarm_size,length(swarm.mode_location)); % current locations of swarm
swarm.history_values = ones(swarm_size,1)*-inf; % current values of swarm

swarm.pbest_locations = zeros(swarm_size,length(swarm.mode_location)); % current best locations of swarm
swarm.pbest_values = ones(swarm_size,1)*-inf; % current best locations of swarm

swarm.velocities = rand(size(mx)).*(mx-mn)+mn; % random initial velocities of swarm
swarm.number_of_particles = 1;

swarm.history_locations(1,:) = swarm.mode_location;
swarm.history_values(1) = y;

swarm.pbest_locations(1,:) = swarm.mode_location;
swarm.pbest_values(1) = y;

% track all made
nmmso_state.X(nmmso_state.index,:) = swarm.new_location;
nmmso_state.Y(nmmso_state.index)= y;
nmmso_state.index = nmmso_state.index +1;

%--------------------------------------------------------------------------
function [nmmso_state,number_of_mid_evals] = merge_swarms(nmmso_state,problem_func,problem_function_params,mn,mx)

% only concern ourselves with modes that have actually shifted, or are new
% since the last generation, as no need to check others
I = find(nmmso_state.active_modes_changed==1);
nmmso_state.active_modes_changed = nmmso_state.active_modes_changed*0; % reset

n = length(I);
number_of_mid_evals=0;
if n>=1 && (length(nmmso_state.active_modes)>1) % only compare if there is a changed mode, and more than one mode in system
    to_compare = zeros(n,2);
    to_compare(:,1) = I;
    for i=1:n
        d = dist2(nmmso_state.M_loc(I(i),:),nmmso_state.M_loc); % dist2 can be found in the freely available netlab tool suite
        d(I(i)) = inf; % will be closest to itself, so need to get second closest
        [tmp, to_compare(i,2)] = min(d);
        nmmso_state.active_modes(I(i)).swarm.dist = sqrt(tmp); % track Euc dist to nearest neighbour mode

        if nmmso_state.active_modes(I(i)).swarm.number_of_particles==1
            reject=0;
            % in situation where a new swarm, and therefore distance to
            % neighbour swarm now calculated
            % so set the initial velocity at a more reasonable value for
            % the first particle, rather than using the uniform in design space
            temp_vel = mn-1;
            while (sum(temp_vel < mn)> 0 || sum(temp_vel > mx)>0)
                temp_vel = uniform_sphere_points(1,length(nmmso_state.active_modes(I(i)).swarm.new_location))*(nmmso_state.active_modes(I(i)).swarm.dist/2);
                reject = reject+1;
                if reject>20
                    % rejecting lots, so likely in a corner of design space
                    % where a significant volume of the sphere lies outside
                    % the bounds, so will make do with a random legal
                    % velocity in bounds
                    temp_vel = rand(size(nmmso_state.active_modes(I(i)).swarm.new_location)).*(mx-mn) + mn;
                end
            end
            nmmso_state.active_modes(I(i)).swarm.velocities(1,:) = temp_vel;
        end
    end

    % to_compare now contains the pairs of indices of closest modes, where at
    % least one mode has shifted location/is new since last generation. However,
    % there may be duplicated pairs (through reversals), so need to omit these.
    to_compare = sort(to_compare,2);
    % now sorted so that first column elements are always smaller than second
    % column elemets on same row
    [~,ind]=sort(to_compare(:,1));
    to_compare = to_compare(ind,:); %now sorted so that first column is sorted smallest to highest

    % remove_duplicates
    for i=n:-1:2
        I = find(to_compare(:,1) == to_compare(i,1)); %get indices of all with first index element same
        if sum(sum(repmat(to_compare(i,:),length(I),1)==to_compare(I,:),2)==2)>1 % if more than one vector duplication
            to_compare(i,:)=[];
        end
    end

    % now check for merging
    n = size(to_compare,1);
    to_merge =[];
    number_of_mid_evals=0;

    for i=1:n
        % merge if sufficiently close
        if sqrt(dist2(nmmso_state.active_modes(to_compare(i,1)).swarm.mode_location,nmmso_state.active_modes(to_compare(i,2)).swarm.mode_location)) < nmmso_state.tol_val
            to_merge = [to_merge; i]; % alas can't preallocate, as don't know the size
        else % otherwise merge if mid region is fitter
            % evaluate exact mid point between modes, and add to mode 2
            % history

            mid_loc = 0.5*(nmmso_state.active_modes(to_compare(i,1)).swarm.mode_location-nmmso_state.active_modes(to_compare(i,2)).swarm.mode_location)+nmmso_state.active_modes(to_compare(i,2)).swarm.mode_location;

            % little sanity check
            if (sum(mid_loc < mn)> 0 || sum(mid_loc > mx)>0)
                error('mid point out of range!');
            end

            nmmso_state.active_modes(to_compare(i,2)).swarm.new_location = mid_loc;
            [nmmso_state,mode_shift,y] = evaluate_mid(nmmso_state,to_compare(i,2),problem_func,problem_function_params);
            if mode_shift==1 % better than mode 2 current mode, so merge
                nmmso_state.M_loc(to_compare(i,2),:)= nmmso_state.active_modes(to_compare(i,2)).swarm.mode_location;
                nmmso_state.V_loc(to_compare(i,2))= nmmso_state.active_modes(to_compare(i,2)).swarm.mode_value;
                to_merge = [to_merge; i];
                nmmso_state.active_modes_changed(to_compare(i,2))=1; % track that the mode value has improved
            elseif (nmmso_state.active_modes(to_compare(i,1)).swarm.mode_value <= y) % better than (or equal to) mode 1 current mode, so merge
                to_merge = [to_merge; i];
            end
            number_of_mid_evals = number_of_mid_evals+1;
        end
    end
    % merge those marked pairs, and flag the lower one for deletion
    delete_index= zeros(size(to_merge));
    for i=1:length(to_merge)
        if (to_compare(to_merge(i),2)==to_compare(to_merge(i),1))
            error('indices sould not be equal');
        end
        % if peak of mode 1 is higher than mode 2, then replace
        if (nmmso_state.active_modes(to_compare(to_merge(i),1)).swarm.mode_value > nmmso_state.active_modes(to_compare(to_merge(i),2)).swarm.mode_value)
            delete_index(i) = to_compare(to_merge(i),2);
            nmmso_state.active_modes(to_compare(to_merge(i),1)).swarm = merge_swarms_together(nmmso_state.active_modes(to_compare(to_merge(i),1)).swarm,nmmso_state.active_modes(to_compare(to_merge(i),2)).swarm);
            nmmso_state.active_modes_changed(to_compare(i,1))=1; % track that the mode value has merged and should be compared again
        else
            delete_index(i) = to_compare(to_merge(i),1);
            nmmso_state.active_modes(to_compare(to_merge(i),2)).swarm = merge_swarms_together(nmmso_state.active_modes(to_compare(to_merge(i),2)).swarm,nmmso_state.active_modes(to_compare(to_merge(i),1)).swarm);
            nmmso_state.active_modes_changed(to_compare(i,2))=1; % track that the mode value has merged and should be compared again
        end
    end

    % remove one of the merged pair
    prev_merge=-1;
    delete_index=sort(delete_index);
    for i=length(delete_index):-1:1
        if (delete_index(i)~= prev_merge) % if not duplicated
            prev_merge=delete_index(i);
            nmmso_state.active_modes(delete_index(i))=[];
            nmmso_state.M_loc(delete_index(i),:)=[];
            nmmso_state.V_loc(delete_index(i))=[];
            nmmso_state.converged_modes(delete_index(i))=[];
            nmmso_state.active_modes_changed(delete_index(i))=[];
        end
    end
end
if length(nmmso_state.active_modes)==1
    nmmso_state.active_modes(1).swarm.dist = min(mx-mn); % only one mode, so choose arbitary dist for it (smallest design dimension)
end

%--------------------------------------------------------------------------
function [nmmso_state,mode_shift,y] = evaluate(nmmso_state,chg,problem_func,problem_function_params)

y = feval(problem_func, nmmso_state.active_modes(chg).swarm.new_location,problem_function_params);
mode_shift=0;
if (y > nmmso_state.active_modes(chg).swarm.mode_value)
    nmmso_state.active_modes(chg).swarm.mode_location = nmmso_state.active_modes(chg).swarm.new_location;
    nmmso_state.active_modes(chg).swarm.mode_value = y;
    mode_shift = 1;
end

nmmso_state.active_modes(chg).swarm.history_locations(nmmso_state.active_modes(chg).swarm.shifted_loc,:) =  nmmso_state.active_modes(chg).swarm.new_location;
nmmso_state.active_modes(chg).swarm.history_values(nmmso_state.active_modes(chg).swarm.shifted_loc) = y;
% if better than personal best for swarm member - then replace
if (y > nmmso_state.active_modes(chg).swarm.pbest_values(nmmso_state.active_modes(chg).swarm.shifted_loc))
    nmmso_state.active_modes(chg).swarm.pbest_values(nmmso_state.active_modes(chg).swarm.shifted_loc) = y;
    nmmso_state.active_modes(chg).swarm.pbest_locations(nmmso_state.active_modes(chg).swarm.shifted_loc,:) = nmmso_state.active_modes(chg).swarm.new_location;
end

nmmso_state.X(nmmso_state.index,:) = nmmso_state.active_modes(chg).swarm.new_location;
nmmso_state.Y(nmmso_state.index) = y;
nmmso_state.index = nmmso_state.index+1;

%--------------------------------------------------------------------------
function [nmmso_state,mode_shift,y] = evaluate_mid(nmmso_state,chg,problem_func,test_function_params)

% new_location is the only solution thus far in mode, so by definition is
% also the mode estimate, and the only history thus far

y = feval(problem_func, nmmso_state.active_modes(chg).swarm.new_location,test_function_params);
mode_shift=0;

if (y > nmmso_state.active_modes(chg).swarm.mode_value)
    nmmso_state.active_modes(chg).swarm.mode_location = nmmso_state.active_modes(chg).swarm.new_location;
    nmmso_state.active_modes(chg).swarm.mode_value = y;
    mode_shift = 1;
end

nmmso_state.X(nmmso_state.index,:) = nmmso_state.active_modes(chg).swarm.new_location;
nmmso_state.Y(nmmso_state.index) = y;
nmmso_state.index = nmmso_state.index+1;

%--------------------------------------------------------------------------
function swarm1 = merge_swarms_together(swarm1,swarm2)

% merges swarm1 contents into swarm2, keeping the best elements of both

n1 = swarm1.number_of_particles;
n2 = swarm2.number_of_particles;
max_size = size(swarm1.history_locations,1);

if (n1+n2<=max_size)
    swarm1.number_of_particles = n1+n2;
    % simplest situation, where the combined active members of both
    % populations are below the total size they can grow to
    swarm1.history_locations(n1+1:n1+n2,:) = swarm2.history_locations(1:n2,:); % current locations of swarm
    swarm1.history_values(n1+1:n1+n2) = swarm2.history_values(1:n2); % current values of swarm

    swarm1.pbest_locations(n1+1:n1+n2,:) = swarm2.pbest_locations(1:n2,:); % current best locations of swarm
    swarm1.pbest_values(n1+1:n1+n2) = swarm2.pbest_values(1:n2); % current best locations of swarm

    swarm1.velocities(n1+1:n1+n2,:) = swarm2.velocities(1:n2,:); % current velocities of swarm
else
    % select best out of combined population, based on current location
    % (rather than pbest)

    swarm1.number_of_particles = max_size;
    temp_h_loc = [swarm1.history_locations(1:n1,:); swarm2.history_locations(1:n2,:)];
    temp_h_v = [swarm1.history_values(1:n1); swarm2.history_values(1:n2)];

    temp_p_loc = [swarm1.pbest_locations(1:n1,:); swarm2.pbest_locations(1:n2,:)];
    temp_p_v = [swarm1.pbest_values(1:n1); swarm2.pbest_values(1:n2)];
    temp_vel = [swarm1.velocities(1:n1,:); swarm2.velocities(1:n2,:)];

    [~,I] = sort(temp_h_v,'descend');
    swarm1.history_locations = temp_h_loc(I(1:max_size),:);
    swarm1.history_values = temp_h_v(I(1:max_size),:);
    swarm1.pbest_locations = temp_p_loc(I(1:max_size),:);
    swarm1.pbest_values = temp_p_v(I(1:max_size),:);
    swarm1.velocities = temp_vel(I(1:max_size),:);
end

%--------------------------------------------------------------------------
function [nmmso_state, cs] = increment_swarm(nmmso_state,chg,mn,mx,swarm_size)

cs =0;
new_location = mn-1;

d = nmmso_state.active_modes(chg).swarm.dist;

shifted =0;
omega=0.1;
reject=0;
r = randperm(swarm_size); % select a particle at random to move

while (sum(new_location < mn)> 0 || sum(new_location > mx)>0)
    % if swarm not yet at capacity, simply add a new particle
    if nmmso_state.active_modes(chg).swarm.number_of_particles < swarm_size
        new_location = nmmso_state.active_modes(chg).swarm.mode_location + uniform_sphere_points(1,length(new_location))*(d/2);
    else % otherwise move an existing particle
        shifted =1;
        nmmso_state.active_modes(chg).swarm.shifted_loc = r(1);
        temp_velocity = omega*nmmso_state.active_modes(chg).swarm.velocities(nmmso_state.active_modes(chg).swarm.shifted_loc,:) ...
            + 2.0 * rand(size(new_location)).*(nmmso_state.active_modes(chg).swarm.mode_location - nmmso_state.active_modes(chg).swarm.history_locations(nmmso_state.active_modes(chg).swarm.shifted_loc,:)) ...
            + 2.0 * rand(size(new_location)).*(nmmso_state.active_modes(chg).swarm.pbest_locations(nmmso_state.active_modes(chg).swarm.shifted_loc,:) - nmmso_state.active_modes(chg).swarm.history_locations(nmmso_state.active_modes(chg).swarm.shifted_loc,:));
        if (reject>20)
            % if we keep rejecting, then put at extreme any violating
            % design parameters
            I_max= find(((nmmso_state.active_modes(chg).swarm.history_locations(nmmso_state.active_modes(chg).swarm.shifted_loc,:) + temp_velocity)>mx)==1);
            I_min= find(((nmmso_state.active_modes(chg).swarm.history_locations(nmmso_state.active_modes(chg).swarm.shifted_loc,:) + temp_velocity)<mn)==1);
            if isempty(I_max)==0
                temp_velocity(I_max)= rand(1,length(I_max)).*(mx(I_max)-nmmso_state.active_modes(chg).swarm.history_locations(nmmso_state.active_modes(chg).swarm.shifted_loc,I_max));
            end
            if isempty(I_min)==0
                temp_velocity(I_min)= rand(1,length(I_min)).*((nmmso_state.active_modes(chg).swarm.history_locations(nmmso_state.active_modes(chg).swarm.shifted_loc,I_min)-mn(I_min))*-1);
            end
        end
        new_location = nmmso_state.active_modes(chg).swarm.history_locations(nmmso_state.active_modes(chg).swarm.shifted_loc,:) + temp_velocity;
        reject=reject+1;
    end
end
reject =0;
if (shifted ==1) % if moved, update velocity with that used
    nmmso_state.active_modes(chg).swarm.velocities(nmmso_state.active_modes(chg).swarm.shifted_loc,:) = temp_velocity;
else % otherwise initialise velocity in sphere based on distance from gbest to next closest mode
    nmmso_state.active_modes(chg).swarm.number_of_particles = nmmso_state.active_modes(chg).swarm.number_of_particles+1;
    nmmso_state.active_modes(chg).swarm.shifted_loc = nmmso_state.active_modes(chg).swarm.number_of_particles;
    temp_vel = mn-1;
    while (sum(temp_vel < mn)> 0 || sum(temp_vel > mx)>0)
        temp_vel = uniform_sphere_points(1,length(new_location))*(d/2);
        reject = reject+1;
        if reject>20 % resolve if keep rejecting
            temp_vel = rand(size(new_location)).*(mx-mx) + mn;
        end
    end
    nmmso_state.active_modes(chg).swarm.velocities(nmmso_state.active_modes(chg).swarm.shifted_loc,:) = temp_vel;

end
nmmso_state.active_modes(chg).swarm.new_location = new_location;

%--------------------------------------------------------------------------
function [nmmso_state,number_of_new_locations] = evaluate_new_locations(nmmso_state,problem_func,problem_function_params,I)

nmmso_state.active_modes_changed = zeros(length(nmmso_state.active_modes),1); % at this point should be unflagged
for i=1:length(I)
    [nmmso_state,mode_shift] = evaluate(nmmso_state,I(i),problem_func,problem_function_params);
    if mode_shift==1
        nmmso_state.active_modes_changed(I(i)) = 1;
        nmmso_state.M_loc(I(i),:) = nmmso_state.active_modes(I(i)).swarm.new_location;
        nmmso_state.V_loc(I(i)) = nmmso_state.active_modes(I(i)).swarm.mode_value;
        nmmso_state.active_modes(I(i)).swarm.less_fit_move=0;
    end
end
number_of_new_locations = length(I);

%--------------------------------------------------------------------------
function [nmmso_state,number_of_new_modes] = evolve(nmmso_state,problem_func,mn,mx,problem_function_params,max_evol,swarm_size)

n = length(nmmso_state.active_modes);

if n>max_evol
    if rand()<0.5
        [~, I] = sort(nmmso_state.V_loc,'descend');
    else
        I=randperm(n);
    end
    I = I(1:max_evol);
    n = max_evol;
else
    I = 1:n;
end

II = randperm(n);
% uniform crossover of two mode elements
R = UNI(nmmso_state.active_modes(I(II(1))).swarm.mode_location,nmmso_state.active_modes(I(II(2))).swarm.mode_location);

nmmso_state.M_loc = [nmmso_state.M_loc; R];

swarm.new_location = R;
[swarm,nmmso_state] = evaluate_first(swarm,problem_func,problem_function_params,nmmso_state,swarm_size,mn,mx);
nmmso_state.V_loc = [nmmso_state.V_loc; swarm.mode_value];
nmmso_state.active_modes(end+1).swarm = swarm;

% mark these as new
nmmso_state.active_modes_changed = [nmmso_state.active_modes_changed; 1];
nmmso_state.converged_modes = [nmmso_state.converged_modes; 0];
number_of_new_modes = 1;

%--------------------------------------------------------------------------
function [nmmso_state,number_of_new_samples] = hive(nmmso_state,problem_func,mn,mx,problem_function_params,max_evol,swarm_size)

number_of_new_samples=0;

LL = length(nmmso_state.active_modes);
fit_I = randperm(LL);

limit = min(max_evol,LL);

I2 = fit_I(1:limit);
CI = zeros(length(I2));
% first identify those swarms who are at capacity, and therefore may be
% considered for splitting off a member
for i=1:length(I2);
    if nmmso_state.active_modes(i).swarm.number_of_particles >= swarm_size
        CI(i)=1;
    end
end
CI = find(CI==1);
% only check on full swarms
if isempty(CI)==0
    % select swarm at random
    r = randperm(length(CI));
    r = CI(r(1));
    % select an active swarm member at random
    k = randperm(nmmso_state.active_modes(r).swarm.number_of_particles);
    k = k(1);
    R = nmmso_state.active_modes(r).swarm.history_locations(k,:);
    R_v = nmmso_state.active_modes(r).swarm.history_values(k,:);

    % only look at splitting off member who is greater than tol_value
    % distance away -- otherwise will be merged right in again at the
    % next iteration
    if sqrt(dist2(R,nmmso_state.active_modes(r).swarm.mode_location))>nmmso_state.tol_val

        mid_loc = 0.5*(nmmso_state.active_modes(r).swarm.mode_location-R)+R;

        swarm.new_location = mid_loc;
        [swarm,nmmso_state] = evaluate_first(swarm,problem_func,problem_function_params,nmmso_state,swarm_size,mn,mx);
        mid_loc_val = swarm.mode_value;
        % if valley between, then hive off the old swarm member to create new swarm
        if swarm.mode_value < R_v
            reject=0;
            % allocate new swarm
            swarm.mode_location = R; %gbest location
            swarm.mode_value = R_v; %gbest value

            swarm.history_locations(1,:) = R;
            swarm.history_values(1) = R_v;

            swarm.pbest_locations(1,:) = R;
            swarm.pbest_values(1) = R_v;

            nmmso_state.M_loc = [nmmso_state.M_loc; R];
            nmmso_state.V_loc = [nmmso_state.V_loc; R_v];

            nmmso_state.active_modes(end+1).swarm = swarm;

            nmmso_state.active_modes_changed = [nmmso_state.active_modes_changed; 1];
            nmmso_state.converged_modes = [nmmso_state.converged_modes; 0];

            % remove from existing swarm and replace with mid eval
            d = sqrt(dist2(nmmso_state.active_modes(r).swarm.mode_location,R));

            nmmso_state.active_modes(r).swarm.history_locations(k,:) = mid_loc;
            nmmso_state.active_modes(r).swarm.history_values(k,:) = mid_loc_val;

            nmmso_state.active_modes(r).swarm.pbest_locations(k,:) = mid_loc;
            nmmso_state.active_modes(r).swarm.pbest_values(k,:) = mid_loc_val;

            temp_vel = mn-1;
            while (sum(temp_vel < mn)> 0 || sum(temp_vel > mx)>0)
                temp_vel = uniform_sphere_points(1,length(R))*(d/2);
                reject = reject+1;
                if reject>20 % resolve repeated rejection
                    temp_vel = rand(size(R)).*(mx-mn) + mn;
                end
            end
            nmmso_state.active_modes(r).swarm.velocities(k,:) = temp_vel;
        else
            if swarm.mode_value > nmmso_state.active_modes(r).swarm.mode_value
                % discovered better than original, so replace mode accordingly
                nmmso_state.active_modes(r).swarm.mode_value = swarm.mode_value;
                nmmso_state.active_modes(r).swarm.mode_location = swarm.mode_location;
            end
        end

        number_of_new_samples = number_of_new_samples+1;
    end

end

%--------------------------------------------------------------------------
function [nmmso_state,number_rand_modes] = random_new(nmmso_state,problem_func,mn,mx,problem_function_params,swarm_size)

number_rand_modes = 1;
x = rand(size(mx)).*(mx-mn)+mn;

nmmso_state.active_modes_changed = [nmmso_state.active_modes_changed; ones(number_rand_modes,1)];
nmmso_state.converged_modes = [nmmso_state.converged_modes; zeros(number_rand_modes,1)];
swarm.new_location = x(1,:);

[swarm,nmmso_state] = evaluate_first(swarm,problem_func,problem_function_params,nmmso_state,swarm_size,mn,mx);
nmmso_state.active_modes(end+1).swarm = swarm;
nmmso_state.M_loc = [nmmso_state.M_loc; x];
nmmso_state.V_loc = [nmmso_state.V_loc; nmmso_state.active_modes(end).swarm.mode_value];

%--------------------------------------------------------------------------

function [x_c, x_d] = UNI(x1,x2)
% simulated binary crossover
l = length(x1);
x_c =x1;
x_d = x2;
r = find(rand(l,1)>0.5);
if isempty(r)==1 % ensure at least one swapped
    r = randperm(l);
    r=r(1);
else
    if length(r) == l % complete swap of all elements of parents
        p = randperm(l);
        r(p) = []; % randomly remove one of the elements to swap
    end
end
x_c(r) = x2(r);
x_d(r) = x1(r);

%--------------------------------------------------------------------------

function X = uniform_sphere_points(n,d)

% X = uniform_sphere_points(n,d)
%
%function generates n points unformly within the unit sphere in d dimensions

z= randn(n,d);

r1 = sqrt(sum(z.^2,2));

X=z./repmat(r1,1,d);
r=rand(n,1).^(1/d);

X = X.*repmat(r,1,d);


text:
local schema_def = require "kong.plugins.hmac-auth.schema"
local v = require("spec.helpers").validate_plugin_config_schema

describe("Plugin: hmac-auth (schema)", function()
  it("accepts empty config", function()
    local ok, err = v({}, schema_def)
    assert.is_truthy(ok)
    assert.is_nil(err)
  end)
  it("accepts correct clock skew", function()
    local ok, err = v({ clock_skew = 10 }, schema_def)
    assert.is_truthy(ok)
    assert.is_nil(err)
  end)
  it("errors with negative clock skew", function()
    local ok, err = v({ clock_skew = -10 }, schema_def)
    assert.is_falsy(ok)
    assert.equal("value must be greater than 0", err.config.clock_skew)
  end)
  it("errors with wrong algorithm", function()
    local ok, err = v({ algorithms = { "sha1024" } }, schema_def)
    assert.is_falsy(ok)
    assert.equal("expected one of: hmac-sha1, hmac-sha256, hmac-sha384, hmac-sha512",
                 err.config.algorithms[1])
  end)
end)


text:
package br.curso.a_032_viewpager;

import java.util.ArrayList;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {

	private Context context;

	private ViewPager pager;

	private PagerTabStrip pagerTabStrip;

	private ArrayList<Fragment> fragments;
	private String[] titulos = { "Titulo 1", "Titulo 2", "Titulo 3" };

	private Frag_01 frag_01;
	private Frag_02 frag_02;
	private Frag_03 frag_03;

	private FPagerAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.telainicial);
		//
		context = getBaseContext();
		//
		frag_01 = new Frag_01();
		frag_02 = new Frag_02();
		frag_03 = new Frag_03();
		//
		fragments = new ArrayList<Fragment>();
		fragments.add(frag_01);
		fragments.add(frag_02);
		fragments.add(frag_03);
		//
		adapter = new FPagerAdapter(getSupportFragmentManager(), fragments);
		//
		pager = (ViewPager) findViewById(R.id.pager);
		pager.setAdapter(adapter);
		pager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				Toast.makeText(context, String.valueOf(position),
						Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
			}
		});
		//
		pager.setCurrentItem(1);

	}

	private class FPagerAdapter extends FragmentPagerAdapter {

		ArrayList<Fragment> fragments;

		public FPagerAdapter(FragmentManager fm, ArrayList<Fragment> fragments) {
			super(fm);
			this.fragments = fragments;
		}

		@Override
		public Fragment getItem(int position) {
			return fragments.get(position);
		}

		@Override
		public int getCount() {
			return fragments.size();
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return titulos[position];
		}

	}

}


text:
namespace ash {

NetworkFeaturePodButton::NetworkFeaturePodButton(
    FeaturePodControllerBase* controller,
    Delegate* delegate)
    : FeaturePodButton(controller), delegate_(delegate) {
  DCHECK(delegate);
}

NetworkFeaturePodButton::~NetworkFeaturePodButton() = default;

void NetworkFeaturePodButton::OnThemeChanged() {
  FeaturePodButton::OnThemeChanged();
  delegate_->OnFeaturePodButtonThemeChanged();
}

BEGIN_METADATA(NetworkFeaturePodButton, FeaturePodButton)
END_METADATA

}  // namespace ash


text:
<!DOCTYPE html>

        <title>aciPlugin namespaced options - A jQuery plugin boilerplate</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

This is a demo to show using namespaced options, setting a property inside an object set as an option is now possible.


text:
/**
 * @file
 *   This file contains the definitions of a spinel decoder.
 */

#ifndef SPINEL_DECODER_HPP_
#define SPINEL_DECODER_HPP_

#include <openthread/config.h>

#include <openthread/ip6.h>
#include <openthread/ncp.h>

#include "openthread-core-config.h"
#include "ncp/spinel.h"

namespace ot {
namespace Ncp {

/**
 * This class defines a spinel decoder.
 *
 */
class SpinelDecoder
{
public:
    enum
    {
        kMaxNestedStructs = 4, ///< Maximum number of nested structs.
    };

    /**
     * This constructor initializes a `SpinelDecoder` object.
     *
     */
    SpinelDecoder(void);

    /**
     * This method initializes the decoder to start decoding a new frame.
     *
     * It sets the read position to the start of the frame and also erases/voids any saved positions (see
     * `SavePosition()` and `ResetToSaved()` methods).
     *
     * @param[in] aFrame                Pointer to the buffer containing the frame to be decoded.
     * @param[in] aLength               Length (number of bytes) of the frame.
     *
     */
    void Init(const uint8_t *aFrame, uint16_t aLength);

    /**
     * This method returns the pointer to the start of the frame.
     *
     * @returns A pointer to buffer containing current frame being decoded.
     *
     */
    const uint8_t *GetFrame(void) const { return mFrame; }

    /**
     * This method returns the total length of current frame being decoded.
     *
     * @returns The length of current frame being decoded.
     *
     */
    uint16_t GetLength(void) const { return mLength; }

    /**
     * This method returns the number of bytes that are already read/decoded from the frame.
     *
     * @returns The number of bytes already read from frame.
     *
     */
    uint16_t GetReadLength(void) const { return mIndex; }

    /**
     * This method returns the number of remaining (not yet read/decoded) bytes in the frame.
     *
     * @returns The number of remaining unread bytes in the frame.
     *
     */
    uint16_t GetRemainingLength(void) const { return mLength - mIndex; }

    /**
     * This method indicates whether or not all the bytes in the frame are read.
     *
     * @returns TRUE if all the bytes in the buffer are read, FALSE otherwise.
     *
     */
    bool IsAllRead(void) const { return (mIndex == mLength); }

    /**
     * This method resets the read position to beginning of frame. It will also void/erase any previously saved
     * position using `SavePosition()` method.
     *
     */
    void Reset(void);

    /**
     * This method decodes and reads a boolean value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aBool                Reference to variable to output the read value.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadBool(bool &aBool);

    /**
     * This method decodes and reads an `int8_t` value form the frame.
     *
     * On success, the read position get updated.
     *
     * @param[out] aInt8                Reference to variable to output the read value.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadInt8(int8_t &aInt8);

    /**
     * This method decodes and reads an `uint8_t` value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aUint8               Reference to variable to output the read value.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadUint8(uint8_t &aUint8);

    /**
     * This method decodes and reads an `int16_t` value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aInt16               Reference to variable to output the read value.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadInt16(int16_t &aInt16);

    /**
     * This method decodes and reads an `uint16_t` value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aUint16              Reference to variable to output the read value.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadUint16(uint16_t &aUint16);

    /**
     * This method decodes and reads an `int32_t` value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aInt32               Reference to variable to output the read value.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadInt32(int32_t &aInt32);

    /**
     * This method decodes and reads an `uint32_t` value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aUint32              Reference to variable to output the read value.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadUint32(uint32_t &aUint32);

    /**
     * This method decodes and reads an `int64_t` value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aInt64               Reference to variable to output the read value.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadInt64(int64_t &aInt64);

    /**
     * This method decodes and reads an `uint64_t` value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aUint64              Reference to variable to output the read value.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadUint64(uint64_t &aUint64);

    /**
     * This method decodes (using spinel packed integer format) and reads an unsigned integer value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aUint                Reference to variable to output the read value.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadUintPacked(unsigned int &aUint);

    /**
     * This method decodes and reads an IPv6 address form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aIp6AddrPtr          Reference to IPv6 address pointer to output the value (as `spinel_ipv6addr_t`).
     *                                  On success, the pointer variable is updated.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadIp6Address(const spinel_ipv6addr_t *&aIp6AddrPtr)
    {
        return ReadItem(reinterpret_cast<const uint8_t **>(&aIp6AddrPtr), sizeof(spinel_ipv6addr_t));
    }

    /**
     * This method decodes and reads an IPv6 address form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aIp6AddrPtr          Reference to IPv6 address pointer to output the value (as `otIp6Address`).
     *                                  On success, the pointer variable is updated.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadIp6Address(const otIp6Address *&aIp6AddrPtr)
    {
        return ReadItem(reinterpret_cast<const uint8_t **>(&aIp6AddrPtr), sizeof(spinel_ipv6addr_t));
    }

    /**
     * This method decodes and reads an IPv6 address form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aIp6AddrBufPtr       Reference to a buffer pointer to output the value.
     *                                  On success, the pointer variable is updated.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadIp6Address(const uint8_t *&aIp6AddrBufPtr)
    {
        return ReadItem(&aIp6AddrBufPtr, sizeof(spinel_ipv6addr_t));
    }

    /**
     * This method decodes and reads an IPv6 address form the frame.
     *
     * On success, the read position gets updated and the IP address is copied into the given output variable.
     *
     * @param[out] aIp6Addr             Reference to IPv6 address variable to output the value (as `spinel_ipv6addr_t`).
     *                                  On success, the address is copied into the output variable.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadIp6Address(spinel_ipv6addr_t &aIp6Addr);

    /**
     * This method decodes and reads an IPv6 address form the frame.
     *
     * On success, the read position gets updated and the IP address is copied into the given output variable.
     *
     * @param[out] aIp6Addr             Reference to IPv6 address variable to output the value (as `otIp6Address`).
     *                                  On success, the address is copied into the output variable.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadIp6Address(otIp6Address &aIp6Addr);

    /**
     * This method decodes and reads an EUI64 value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aEui64Ptr            Reference to an EUI64 pointer to output the value (as `spinel_eui64_t`).
     *                                  On success, the pointer variable is updated.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadEui64(const spinel_eui64_t *&aEui64Ptr)
    {
        return ReadItem(reinterpret_cast<const uint8_t **>(&aEui64Ptr), sizeof(spinel_eui64_t));
    }

    /**
     * This method decodes and reads an EUI64 value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aEui64Ptr            Reference to an EUI64 pointer to output the value (as `otExtAddress`).
     *                                  On success, the pointer variable is updated.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadEui64(const otExtAddress *&aEui64Ptr)
    {
        return ReadItem(reinterpret_cast<const uint8_t **>(&aEui64Ptr), sizeof(spinel_eui64_t));
    }

    /**
     * This method decodes and reads an EUI64 value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aEui64BufPtr         Reference to a buffer pointer to output the value.
     *                                  On success, the pointer variable is updated.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadEui64(const uint8_t *&aEui64BufPtr) { return ReadItem(&aEui64BufPtr, sizeof(spinel_eui64_t)); }

    /**
     * This method decodes and reads an EUI64 value form the frame.
     *
     * On success, the read position gets updated and the EUI64 value is copied into the given output variable.
     *
     * @param[out] aEui64               Reference to EUI64 variable to output the value (as `spinel_eui64_t`).
     *                                  On success, the address is copied into the output variable.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadEui64(spinel_eui64_t &aEui64);

    /**
     * This method decodes and reads an EUI64 value form the frame.
     *
     * On success, the read position gets updated and the EUI64 value is copied into the given output variable.
     *
     * @param[out] aEui64               Reference to EUI64 variable to output the value (as `otExtAddress`).
     *                                  On success, the address is copied into the output variable.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadEui64(otExtAddress &aEui64);

    /**
     * This method decodes and reads an EUI48 value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aEui48Ptr            Reference to an EUI48 pointer to output the value (as `spinel_eui48_t`).
     *                                  On success, the pointer variable is updated.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadEui48(const spinel_eui48_t *&aEui48Ptr)
    {
        return ReadItem(reinterpret_cast<const uint8_t **>(&aEui48Ptr), sizeof(spinel_eui48_t));
    }

    /**
     * This method decodes and reads an EUI48 value form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aEui48BufPtr         Reference to a buffer pointer to output the value.
     *                                  On success, the pointer variable is updated.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadEui48(const uint8_t *&aEui48BufPtr) { return ReadItem(&aEui48BufPtr, sizeof(spinel_eui48_t)); }

    /**
     * This method decodes and reads an EUI48 value form the frame.
     *
     * On success, the read position gets updated and the EUI48 value is copied into the given output variable.
     *
     * @param[out] aEui48               Reference to EUI48 variable to output the value (as `spinel_eui48_t`).
     *                                  On success, value is copied into the output variable.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadEui48(spinel_eui48_t &aEui48);

    /**
     * This method decodes and reads a UTF8 string form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aUtf8                Reference to a `char` pointer to output the string.
     *                                  On success, the pointer variable is updated.
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadUtf8(const char *&aUtf8);

    /**
     * This method decodes and reads a data blob (sequence of bytes) form the frame.
     *
     * On success, the read position gets updated.
     *
     * @param[out] aData                Reference to pointer variable to output the data.
     *                                  On success, the pointer variable is updated.
     * @param[out] aDataLength          Reference to variable to output the data length (number of bytes).
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadData(const uint8_t *&aData, uint16_t &aDataLen);

    /**
     * This method decodes and reads a data blob (sequence of bytes) with data length.
     *
     * The data length is assumed to be prepended before the data content (encoded as a `uint16_t`). The size of the
     * length field should not be included in the length value. This method corresponds to `SPINEL_DATATYPE_DATA_WLEN`
     * type.
     *
     * @param[out] aData                Reference to pointer variable to output the data.
     *                                  On success, the pointer variable is updated.
     * @param[out] aDataLength          Reference to variable to out the data length (number of bytes).
     *
     * @retval OT_ERROR_NONE            Successfully read the value.
     * @retval OT_ERROR_PARSE           Failed to parse/decode the value.
     *
     */
    otError ReadDataWithLen(const uint8_t *&aData, uint16_t &aDataLen);

    /**
     * This method opens a struct in the frame.
     *
     * After a successful call to this method, all the subsequent `Read{SomeType}()` methods decode and read the
     * field/value from the current open struct until the struct is closed using `CloseStruct()` method. Structures can
     * be nested. Up to `kMaxNestedStructs` nested structs can be opened at the same time.
     *
     * @retval OT_ERROR_NONE            Successfully opened a struct.
     * @retval OT_ERROR_PARSE           Failed to parse/open a struct.
     * @retval OT_ERROR_INVALID_STATE   Already at the maximum number of nested open structures.
     *
     */
    otError OpenStruct(void);

    /**
     * This method closes the most recently opened struct (using `OpenStruct()`) in the frame.
     *
     * On success, the read position is moved to end of the struct skipping any unread bytes within the struct.
     *
     * @retval OT_ERROR_NONE            Successfully closed the struct.
     * @retval OT_ERROR_INVALID_STATE   There is no current open struct to close.
     *
     */
    otError CloseStruct(void);

    /**
     * This method returns the number of remaining/unread bytes in the current inner-most open structure.
     *
     * If there is no currently open structure the number of remaining bytes in whole frame is returned instead.
     *
     * @returns The number of remaining unread bytes in the inner-most open structure.
     *
     */
    uint16_t GetRemainingLengthInStruct(void) const { return mEnd - mIndex; }

    /**
     * This method indicates whether or not all the bytes in inner-most open structure are read.
     *
     * If there is no currently open structure, the whole frame is considered instead.
     *
     * @returns TRUE if all the bytes are read, FALSE otherwise.
     *
     */
    bool IsAllReadInStruct(void) const { return (mIndex == mEnd); }

    /**
     * This method saves the current read position in the frame.
     *
     * A subsequent call to `SavePosition()` will overwrite the previously saved position. The saved position can be
     * used to move the read position back (using `ResetToSaved()`) and re-read the same content.
     *
     * Saved position can be within an open struct, and it remembers its enclosing struct. When the enclosing struct is
     * closed, the saved position will be voided and can no longer be used. This ensures that we cannot jump back to
     * middle an already fully decoded/read and closed struct.
     *
     */
    void SavePosition(void);

    /**
     * This method resets/moves the read position to a previously saved position.
     *
     * The saved position remembers its enclosing structure. When `ResetToSaved()` is called, the current open
     * structure will be the same as when position was saved.
     *
     * @retval OT_ERROR_NONE            Successfully reset the read position.
     * @retval OT_ERROR_INVALID_STATE   The saved position is not valid (there is no saved position or the saved
     *                                  position was voided since its enclosing struct was closed).
     *
     */
    otError ResetToSaved(void);

private:
    otError ReadItem(const uint8_t **aPtr, uint16_t aSize);
    void    ClearSavedPosition(void) { mSavedIndex = mLength; }
    bool    IsSavedPositionValid(void) const { return (mSavedIndex < mLength); }

    const uint8_t *mFrame;          // Frame buffer.
    uint16_t       mLength;         // Frame length (number of bytes).
    uint16_t       mIndex;          // Current read index.
    uint16_t       mEnd;            // Current end index (end of struct if in a struct, or end of buffer otherwise).
    uint8_t        mNumOpenStructs; // Number of open structs.

    uint8_t  mSavedNumOpenStructs; // Number of open structs when read position was saved.
    uint16_t mSavedIndex;          // Read index when position was saved.
    uint16_t mSavedEnd;            // End index when position was saved.

    uint16_t mPrevEnd[kMaxNestedStructs];
};

} // namespace Ncp
} // namespace ot

#endif // SPINEL_DECODER_HPP_


text:
"""Algorithms to characterize the number of triangles in a graph."""
from itertools import combinations

import networkx as nx
from networkx import NetworkXError
from ..utils import not_implemented_for

__author__ = """\n""".join(['Aric Hagberg <aric.hagberg@gmail.com>',
                            'Dan Schult (dschult@colgate.edu)',
                            'Pieter Swart (swart@lanl.gov)',
                            'Jordi Torrents <jtorrents@milnou.net>'])

__all__= ['triangles', 'average_clustering', 'clustering', 'transitivity',
          'square_clustering']

@not_implemented_for('directed')
def triangles(G, nodes=None):
    """Compute the number of triangles.

    Finds the number of triangles that include a node as one vertex.

    Parameters
    ----------
    G : graph
       A networkx graph
    nodes : container of nodes, optional (default= all nodes in G)
       Compute triangles for nodes in this container.

    Returns
    -------
    out : dictionary
       Number of triangles keyed by node label.

    Examples
    --------
    >>> G=nx.complete_graph(5)
    >>> print(nx.triangles(G,0))
    6
    >>> print(nx.triangles(G))
    {0: 6, 1: 6, 2: 6, 3: 6, 4: 6}
    >>> print(list(nx.triangles(G,(0,1)).values()))
    [6, 6]

    Notes
    -----
    When computing triangles for the entire graph each triangle is counted
    three times, once at each node.  Self loops are ignored.

    """
    # If `nodes` represents a single node in the graph, return only its number
    # of triangles.
    if nodes in G:
        return next(_triangles_and_degree_iter(G,nodes))[2] // 2
    # Otherwise, `nodes` represents an iterable of nodes, so return a
    # dictionary mapping node to number of triangles.
    return {v: t // 2 for v, d, t in _triangles_and_degree_iter(G, nodes)}

def _triangles_and_degree_iter(G,nodes=None):
    """ Return an iterator of (node, degree, triangles).

    This double counts triangles so you may want to divide by 2.
    See degree() and triangles() for definitions and details.

    """
    if G.is_multigraph():
        raise NetworkXError("Not defined for multigraphs.")

    if nodes is None:
        nodes_nbrs = G.adj.items()
    else:
        nodes_nbrs= ( (n,G[n]) for n in G.nbunch_iter(nodes) )

    for v,v_nbrs in nodes_nbrs:
        vs=set(v_nbrs)-set([v])
        ntriangles=0
        for w in vs:
            ws=set(G[w])-set([w])
            ntriangles+=len(vs.intersection(ws))
        yield (v,len(vs),ntriangles)

def _weighted_triangles_and_degree_iter(G, nodes=None, weight='weight'):
    """ Return an iterator of (node, degree, weighted_triangles).

    Used for weighted clustering.

    """
    if G.is_multigraph():
        raise NetworkXError("Not defined for multigraphs.")

    if weight is None or list(G.edges())==[]:
        max_weight=1.0
    else:
        max_weight=float(max(d.get(weight,1.0)
                             for u,v,d in G.edges(data=True)))
    if nodes is None:
        nodes_nbrs = G.adj.items()
    else:
        nodes_nbrs= ( (n,G[n]) for n in G.nbunch_iter(nodes) )

    for i,nbrs in nodes_nbrs:
        inbrs=set(nbrs)-set([i])
        weighted_triangles=0.0
        seen=set()
        for j in inbrs:
            wij=G[i][j].get(weight,1.0)/max_weight
            seen.add(j)
            jnbrs=set(G[j])-seen # this keeps from double counting
            for k in inbrs&jnbrs:
                wjk=G[j][k].get(weight,1.0)/max_weight
                wki=G[i][k].get(weight,1.0)/max_weight
                weighted_triangles+=(wij*wjk*wki)**(1.0/3.0)
        yield (i,len(inbrs),weighted_triangles*2)

def average_clustering(G, nodes=None, weight=None, count_zeros=True):
    r"""Compute the average clustering coefficient for the graph G.

    The clustering coefficient for the graph is the average,

    .. math::

       C = \frac{1}{n}\sum_{v \in G} c_v,

    where `n` is the number of nodes in `G`.

    Parameters
    ----------
    G : graph

    nodes : container of nodes, optional (default=all nodes in G)
       Compute average clustering for nodes in this container.

    weight : string or None, optional (default=None)
       The edge attribute that holds the numerical value used as a weight.
       If None, then each edge has weight 1.

    count_zeros : bool
       If False include only the nodes with nonzero clustering in the average.

    Returns
    -------
    avg : float
       Average clustering

    Examples
    --------
    >>> G=nx.complete_graph(5)
    >>> print(nx.average_clustering(G))
    1.0

    Notes
    -----
    This is a space saving routine; it might be faster
    to use the clustering function to get a list and then take the average.

    Self loops are ignored.

    References
    ----------
    .. [1] Generalizations of the clustering coefficient to weighted
       complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
       K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
       http://jponnela.com/web_documents/a9.pdf
    .. [2] Marcus Kaiser,  Mean clustering coefficients: the role of isolated
       nodes and leafs on clustering measures for small-world networks.
       http://arxiv.org/abs/0802.2512
    """
    c=clustering(G,nodes,weight=weight).values()
    if not count_zeros:
        c = [v for v in c if v > 0]
    return sum(c)/float(len(c))

def clustering(G, nodes=None, weight=None):
    r"""Compute the clustering coefficient for nodes.

    For unweighted graphs, the clustering of a node `u`
    is the fraction of possible triangles through that node that exist,

    .. math::

      c_u = \frac{2 T(u)}{deg(u)(deg(u)-1)},

    where `T(u)` is the number of triangles through node `u` and
    `deg(u)` is the degree of `u`.

    For weighted graphs, the clustering is defined
    as the geometric average of the subgraph edge weights [1]_,

    .. math::

       c_u = \frac{1}{deg(u)(deg(u)-1))}
            \sum_{uv} (\hat{w}_{uv} \hat{w}_{uw} \hat{w}_{vw})^{1/3}.

    The edge weights `\hat{w}_{uv}` are normalized by the maximum weight in the
    network `\hat{w}_{uv} = w_{uv}/\max(w)`.

    The value of `c_u` is assigned to 0 if `deg(u) < 2`.

    Parameters
    ----------
    G : graph

    nodes : container of nodes, optional (default=all nodes in G)
       Compute clustering for nodes in this container.

    weight : string or None, optional (default=None)
       The edge attribute that holds the numerical value used as a weight.
       If None, then each edge has weight 1.

    Returns
    -------
    out : float, or dictionary
       Clustering coefficient at specified nodes

    Examples
    --------
    >>> G=nx.complete_graph(5)
    >>> print(nx.clustering(G,0))
    1.0
    >>> print(nx.clustering(G))
    {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}

    Notes
    -----
    Self loops are ignored.

    References
    ----------
    .. [1] Generalizations of the clustering coefficient to weighted
       complex networks by J. Saramäki, M. Kivelä, J.-P. Onnela,
       K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
       http://jponnela.com/web_documents/a9.pdf
    """
    if G.is_directed():
        raise NetworkXError('Clustering algorithms are not defined ',
                            'for directed graphs.')
    if weight is not None:
        td_iter=_weighted_triangles_and_degree_iter(G,nodes,weight)
    else:
        td_iter=_triangles_and_degree_iter(G,nodes)

    clusterc={}

    for v,d,t in td_iter:
        if t==0:
            clusterc[v]=0.0
        else:
            clusterc[v]=t/float(d*(d-1))

    if nodes in G:
        return list(clusterc.values())[0] # return single value
    return clusterc

def transitivity(G):
    r"""Compute graph transitivity, the fraction of all possible triangles
    present in G.

    Possible triangles are identified by the number of "triads"
    (two edges with a shared vertex).

    The transitivity is

    .. math::

        T = 3\frac{\#triangles}{\#triads}.

    Parameters
    ----------
    G : graph

    Returns
    -------
    out : float
       Transitivity

    Examples
    --------
    >>> G = nx.complete_graph(5)
    >>> print(nx.transitivity(G))
    1.0
    """
    triangles=0 # 6 times number of triangles
    contri=0  # 2 times number of connected triples
    for v,d,t in _triangles_and_degree_iter(G):
        contri += d*(d-1)
        triangles += t
    if triangles==0: # we had no triangles or possible triangles
        return 0.0
    else:
        return triangles/float(contri)

def square_clustering(G, nodes=None):
    r""" Compute the squares clustering coefficient for nodes.

    For each node return the fraction of possible squares that exist at
    the node [1]_

    .. math::
       C_4(v) = \frac{ \sum_{u=1}^{k_v}
       \sum_{w=u+1}^{k_v} q_v(u,w) }{ \sum_{u=1}^{k_v}
       \sum_{w=u+1}^{k_v} [a_v(u,w) + q_v(u,w)]},

    where `q_v(u,w)` are the number of common neighbors of `u` and `w`
    other than `v` (ie squares), and
    `a_v(u,w) = (k_u - (1+q_v(u,w)+\theta_{uv}))(k_w - (1+q_v(u,w)+\theta_{uw}))`,
    where `\theta_{uw} = 1` if `u` and `w` are connected and 0 otherwise.

    Parameters
    ----------
    G : graph

    nodes : container of nodes, optional (default=all nodes in G)
       Compute clustering for nodes in this container.

    Returns
    -------
    c4 : dictionary
       A dictionary keyed by node with the square clustering coefficient value.

    Examples
    --------
    >>> G=nx.complete_graph(5)
    >>> print(nx.square_clustering(G,0))
    1.0
    >>> print(nx.square_clustering(G))
    {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}

    Notes
    -----
    While `C_3(v)` (triangle clustering) gives the probability that
    two neighbors of node v are connected with each other, `C_4(v)` is
    the probability that two neighbors of node v share a common
    neighbor different from v. This algorithm can be applied to both
    bipartite and unipartite networks.

    References
    ----------
    .. [1] Pedro G. Lind, Marta C. González, and Hans J. Herrmann. 2005
        Cycles and clustering in bipartite networks.
        Physical Review E (72) 056127.
    """
    if nodes is None:
        node_iter = G
    else:
        node_iter =  G.nbunch_iter(nodes)
    clustering = {}
    for v in node_iter:
        clustering[v] = 0.0
        potential=0
        for u,w in combinations(G[v], 2):
            squares = len((set(G[u]) & set(G[w])) - set([v]))
            clustering[v] += squares
            degm = squares + 1.0
            if w in G[u]:
                degm += 1
            potential += (len(G[u]) - degm) * (len(G[w]) - degm) + squares
        if potential > 0:
            clustering[v] /= potential
    if nodes in G:
        return list(clustering.values())[0] # return single value
    return clustering