text:
import arcpy
import msparkdb

# define map document and dataframe
mxd = arcpy.mapping.MapDocument(r"CURRENT")
df = arcpy.mapping.ListDataFrames(mxd,'*')[0]

# input parameters
request_in = arcpy.GetParameterAsText(0)
request_id = request_in.upper()
loc_name = arcpy.GetParameterAsText(1)
loc_in = loc_name + '\SHEET1$'
new_db = arcpy.GetParameterAsText(2)
new_mdb_loc = arcpy.GetParameterAsText(3)
new_mdb_name = arcpy.GetParameterAsText(4)
mdb_loc = arcpy.GetParameterAsText(5)

# define variables
loc_out = request_id + "_LOC"
loc_table = request_id + '_loc_table'
xy_event = request_id + '_xy_event'

# define database
if str(new_db) == 'true':
	space = msparkdb.newmdb(new_mdb_loc,new_mdb_name)
else:
	space = mdb_loc

# create location table
arcpy.env.workspace = space
msparkdb.loctable(request_id,loc_in,space,loc_table,xy_event,loc_out)


text:
<?php
	require '../Predis/src/Autoloader.php';

	Predis\Autoloader::register();

	include("SessionManager.php");
	new SessionManager();

	$_SESSION['username'] = "xugang";

	echo "session";
 ?>

redpajama_set_name: RedPajamaGithub


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="org.coursera.capstone.android.fragment.QuestionFragment">

    <TextView
        android:id="@+id/checking_question_txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="@dimen/text_h2"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_alignParentBottom="true">

        <Button
            android:id="@+id/checking_answer_1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/checking_answer_2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/checking_answer_3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</RelativeLayout>


text:
/**
 * Created by lequanghiep on 1/16/2017.
 */
'use strict';

angular.module('myApp')
    .controller('AccountController', function ($scope, $stateParams, StringUtils, API_URL, Button, DateUtils
        , DataTable, Dialog, AccountService) {
        $scope.status = {
            step: 1,
            type: $stateParams.type
        };
        $scope.title = StringUtils.capitalize($scope.status.type);
        $scope.account = {};

        $scope.changeView = function changeView(param) {
            $scope.status.step = param === 'back' ? $scope.status.step - 1 : $scope.status.step + 1;
            if (param === 'back') {
                $scope.account = {};
            }
        };

        $scope.saveAccount = function saveAccount() {
            var method = $scope.account.id ? AccountService.updateAccount : AccountService.saveAccount;
            method.call(null, $scope.account)
                .then(Dialog.onSuccess.bind(null, 'Success', 'Save account success', $scope.changeView.bind(null, 'back')))
                .catch(Dialog.onFailure.bind(null, 'Fail', 'Save account fail', null));
        };

        var reloadListAccount = function reloadListAccount() {
            angular.element(document.querySelector('#accountDataTable')).DataTable().ajax.reload(null, false);
        };

        $scope.deleteAccount = function deleteAccount(id) {
            Dialog.deleteDialog('Do you want delete this class?', AccountService.deleteAccount.bind(null, id)
                , reloadListAccount.bind(null));
        };

        $scope.edit = function (data) {
            $scope.$apply(function () {
                $scope.changeView();
                $scope.account = data;
                $scope.account.dateOfBirth = DateUtils.convertMilToDate($scope.account.dateOfBirth);
            });
        };

        var loadAccountsList = function loadAccountsList() {
            var options = {
                url: [API_URL, 'account/fetch'].join(''),
                columns: [
                    {'title': 'ID', 'data': null},
                    {'title': 'Fullname', 'data': 'fullname'},
                    {'title': 'Username', 'data': 'username'},
                    {'title': 'Email', 'data': 'email'},
                    {'title': 'Phone Number', 'data': 'phoneNumber'},
                    {'title': 'Student Id', 'data': 'studentId'},
                    {'title': 'Class Name', 'data': 'className'},
                    {'title': 'Date Of Birth', 'data': 'dateOfBirth'},
                    {'title': 'Gender', 'data': 'gender'},
                    {'': ''}
                ],
                columnDefs: [
                    {
                        "render": function () {
                            return Button.groupButton([Button.editButton(), Button.deleteButton()]);
                        },
                        "targets": -1
                    },
                    {
                        "render": function (data) {
                            return DateUtils.convertMilToDate(data);
                        },
                        "targets": -3
                    }
                ]
            };

            options.delete = function (data) {
                $scope.deleteAccount(data);
            };
            options.edit = function (data) {
                $scope.edit(data);
            };
            DataTable.generateDataTable(options, angular.element(document.querySelector('#accountDataTable')));
        };

        $scope.$on('$includeContentLoaded', function (obj, url) {
            if (url === 'scripts/user_account/account.list.template.html') {
                loadAccountsList();
            }
        });
    });


text:
package org.apache.beehive.netui.compiler.grammar;

import org.apache.beehive.netui.compiler.typesystem.env.CoreAnnotationProcessorEnv;
import org.apache.beehive.netui.compiler.Diagnostics;
import org.apache.beehive.netui.compiler.RuntimeVersionChecker;

public class ValidateValidWhenGrammar
        extends BaseValidationRuleGrammar
{
    private static final String[][] REQUIRED_ATTRS = { { CONDITION_ATTR }, { MESSAGE_ATTR, MESSAGE_KEY_ATTR } };

    public ValidateValidWhenGrammar( CoreAnnotationProcessorEnv env, Diagnostics diagnostics,
                                     RuntimeVersionChecker rvc )
    {
        super( env, diagnostics, rvc );
    }

    public String[][] getRequiredAttrs()
    {
        return REQUIRED_ATTRS;
    }
}


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.0">
    <title>Landing Page</title>
    <link rel="stylesheet" href="css/foundation.css">
    <link rel="stylesheet" href="css/landing.css"
    <link rel="stylesheet" href="css/app.css">

w

s

jhakdfhakdhakj

jhakdfhakdhakj


text:
var DayGridFillRenderer = FillRenderer.extend({

	fillSegTag: 'td', // override the default tag name
	dayGrid: null,

	constructor: function(dayGrid) {
		FillRenderer.call(this, dayGrid);

		this.dayGrid = dayGrid;
	},

	attachSegEls: function(type, segs) {
		var nodes = [];
		var i, seg;
		var skeletonEl;

		for (i = 0; i < segs.length; i++) {
			seg = segs[i];
			skeletonEl = this.renderFillRow(type, seg);
			this.dayGrid.rowEls.eq(seg.row).append(skeletonEl);
			nodes.push(skeletonEl[0]);
		}

		return nodes;
	},

	// Generates the HTML needed for one row of a fill. Requires the seg's el to be rendered.
	renderFillRow: function(type, seg) {
		var colCnt = this.dayGrid.colCnt;
		var startCol = seg.leftCol;
		var endCol = seg.rightCol + 1;
		var className;
		var skeletonEl;
		var trEl;

		if (type === 'businessHours') {
			className = 'bgevent';
		}
		else {
			className = type.toLowerCase();
		}

		skeletonEl = $(
			'
' +
				'

' +
			'
'
		);
		trEl = skeletonEl.find('tr');

		if (startCol > 0) {
			trEl.append('');
		}

		trEl.append(
			seg.el.attr('colspan', endCol - startCol)
		);

		if (endCol < colCnt) {
			trEl.append('');
		}

		this.dayGrid.bookendCells(trEl);

		return skeletonEl;
	}
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/wasing-ts.iml" filepath="$PROJECT_DIR$/wasing-ts.iml" />
    </modules>
  </component>
</project>


text:
function [w,S] = omega(g)
% [w,S] = omega(g) --- clique number
% Returns w, the size of a largest clique, and S, a largest clique.
% Note: Uses integer programming so may run slowly (if at all) on larger
% graphs.
%
% REQUIRES THE OPTIMIZATION TOOLBOX

% Note: Our implementation is simply alpha(-g).

h = graph;
copy(h,g);
complement(h);
[w,S] = alpha(h);
free(h);


text:
layout: book
title: Books
description: Learn to code with our JavaScript books.
---

{% include books.html %}


text:
require 'rails_helper'

RSpec.describe HostMachinesController, type: :controller do
  let(:user) do
    create(:user, name: 'foobar', user_login_id: 'foobar', email: 'foobar@foobar.com')
  end
  describe 'Search for Hosts' do
    it 'should return hosts according to supplied search string' do
      sign_in user
      host_machines = create_list(:host_machine, 3)
      get :search, params: { q: 'host' }
      expect(response.body).to eq(host_machines.map { |m| { id: m.id, name: m.name } }.to_json)
    end
  end

  describe 'PATCH #update' do
    context 'authenticated as admin' do
      it 'should update requested host machine' do
        host_machine = create(:host_machine, default_admins: true)
        sign_in user
        patch :update, params: { id: host_machine.id, host_machine: { default_admins: false } }
        host_machine.reload
        expect(host_machine.default_admins). to be false
      end
    end

    context 'authenticated as non admin' do
      it 'should not update requested host machine' do
        create(:user)
        non_admin = create(:user, admin: false)
        host_machine = create(:host_machine, default_admins: true)
        sign_in non_admin
        patch :update, params: { id: host_machine.id, host_machine: { default_admins: false } }
        host_machine.reload
        expect(host_machine.default_admins). to be true
      end

      it 'should redirect to host machines path' do
        create(:user)
        non_admin = create(:user, admin: false)
        host_machine = create(:host_machine, default_admins: true)
        sign_in non_admin
        patch :update, params: { id: host_machine.id, host_machine: { default_admins: false } }
        expect(response).to redirect_to(host_machines_path)
      end

      it 'should flash message unathorized access' do
        create(:user)
        non_admin = create(:user, admin: false)
        host_machine = create(:host_machine, default_admins: true)
        sign_in non_admin
        patch :update, params: { id: host_machine.id, host_machine: { default_admins: false } }
        expect(flash[:notice]).to eq('Unauthorized access')
      end
    end
  end

  describe 'DELETE #delete_group' do
    context 'authenticated as admin' do
      it 'should delete group from host machine' do
        admin = create(:user)
        host_machine = create(:host_machine)
        group = create(:group)
        host_machine.groups << group
        sign_in admin
        delete :delete_group, params: { id: host_machine.id, group_id: group.id }
        host_machine.reload
        expect(host_machine.groups.count).to eq(0)
      end
    end

    context 'authenticated as non admin' do
      it 'should not delete group from host machine' do
        create(:user)
        non_admin = create(:user, admin: false)
        host_machine = create(:host_machine)
        group = create(:group)
        host_machine.groups << group
        sign_in non_admin
        delete :delete_group, params: { id: host_machine.id, group_id: group.id }
        host_machine.reload
        expect(host_machine.groups.count).to eq(1)
      end

      it 'should redirect to host machines path' do
        create(:user)
        non_admin = create(:user, admin: false)
        host_machine = create(:host_machine)
        group = create(:group)
        host_machine.groups << group
        sign_in non_admin
        delete :delete_group, params: { id: host_machine.id, group_id: group.id }
        expect(response).to redirect_to(host_machines_path)
      end

      it 'should flash notice message unauthorized access' do
        create(:user)
        non_admin = create(:user, admin: false)
        host_machine = create(:host_machine)
        group = create(:group)
        host_machine.groups << group
        sign_in non_admin
        delete :delete_group, params: { id: host_machine.id, group_id: group.id }
        expect(flash[:notice]).to eq('Unauthorized access')
      end
    end
  end
end


text:
import stainless.lang._
import stainless.annotation._

object AccessorMutation1 {

  @mutable
  sealed abstract class Toto {
    var value: BigInt
  }

  case class Foo(var value: BigInt) extends Toto
  case class Bar(var value: BigInt) extends Toto

  sealed abstract class Tata extends Toto
  case class Baz(var value: BigInt) extends Tata

  def t1(toto: Toto) = {
    toto.value = 2
    assert(toto.value == 2)
  }

  def t2(tata: Tata) = {
    tata.value = 2
    assert(tata.value == 2)
  }

}


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="cmf_content.admin" class="%cmf_content.persistence.phpcr.admin.class%">
            <tag name="sonata.admin" manager_type="doctrine_phpcr" group="dashboard.cmf" label_catalogue="CmfContentBundle" label="dashboard.label_static_content" label_translator_strategy="sonata.admin.label.strategy.underscore" />
            <argument/>
            <argument>%cmf_content.persistence.phpcr.document.class%</argument>
            <argument>SonataAdminBundle:CRUD</argument>

            <call method="setRouteBuilder">
                <argument type="service" id="sonata.admin.route.path_info_slashes" />
            </call>

            <call method="setRootPath">
                <argument>%cmf_content.persistence.phpcr.content_basepath%</argument>
            </call>
        </service>
    </services>
</container>


text:
#region License
// Copyright (c) Amos Voron. All rights reserved.
// Licensed under the Apache 2.0 License. See LICENSE in the project root for license information.
#endregion

using System;
using QueryTalk.Wall;

namespace QueryTalk
{
    public static partial class Extensions
    {
        /// <summary>
        /// Specifies that only the first set of rows will be returned from the query result.
        /// </summary>
        /// <param name="prev">A predecessor object.</param>
        /// <param name="rows">Is the numeric bigint expression that specifies the number of rows to be returned.</param>
        public static TopChainer Top(this ITop prev, long rows)
        {
            if (prev is ISemantic)
            {
                return new TopChainer((ISemantic)prev, rows, false);
            }
            else
            {
                return new TopChainer((Chainer)prev, rows, false);
            }
        }

        /// <summary>
        /// Specifies that only the first set of rows will be returned from the query result.
        /// </summary>
        /// <param name="prev">A predecessor object.</param>
        /// <param name="rows">Is the numeric float expression that specifies the percent of rows from the result set.</param>
        public static TopChainer Top(this ITop prev, double rows)
        {
            if (prev is ISemantic)
            {
                return new TopChainer((ISemantic)prev, rows, false);
            }
            else
            {
                return new TopChainer((Chainer)prev, rows, false);
            }
        }

        /// <summary>
        /// Specifies that only the first row will be returned from the query result.
        /// </summary>
        /// <param name="prev">A predecessor object.</param>
        public static TopChainer TopOne(this ITop prev)
        {
            if (prev is ISemantic)
            {
                return new TopChainer((ISemantic)prev, 1, false);
            }
            else
            {
                return new TopChainer((Chainer)prev, 1, false);
            }
        }

        /// <summary>
        /// Specifies that all the rows with the same value in the ORDER BY columns appearing as the last of the TOP n (PERCENT) rows will be returned from the query result.
        /// </summary>
        /// <param name="prev">A predecessor object.</param>
        /// <param name="rows">Is the numeric bigint expression that specifies the number of rows to be returned.</param>
        public static TopChainer TopWithTies(this ITop prev, long rows)
        {
            if (prev is ISemantic)
            {
                return new TopChainer((ISemantic)prev, rows, true);
            }
            else
            {
                return new TopChainer((Chainer)prev, rows, true);
            }
        }

        /// <summary>
        /// Specifies that all the rows with the same value in the ORDER BY columns appearing as the last of the TOP n (PERCENT) rows will be returned from the query result.
        /// </summary>
        /// <param name="prev">A predecessor object.</param>
        /// <param name="rows">Is the numeric float expression that specifies the percent of rows from the result set.</param>
        public static TopChainer TopWithTies(this ITop prev, double rows)
        {
            if (prev is ISemantic)
            {
                return new TopChainer((ISemantic)prev, rows, true);
            }
            else
            {
                return new TopChainer((Chainer)prev, rows, true);
            }
        }

        #region Variable

        /// <summary>
        /// Specifies that only the first set of rows will be returned from the query result where the numeric expression is passed as variable.
        /// </summary>
        /// <param name="prev">A predecessor object.</param>
        /// <param name="variable">Is the name of the variabler of the TOP value.</param>
        public static TopChainer Top(this ITop prev, string variable)
        {
            return new TopChainer((Chainer)prev, variable, false);
        }

        /// <summary>
        /// Specifies that all the rows with the same value in the ORDER BY columns appearing as the last of the TOP n (PERCENT) rows will be returned from the query result, where the numeric expression is passed as variable.
        /// </summary>
        /// <param name="prev">A predecessor object.</param>
        /// <param name="variable">Is the name of the variable of the TOP value.</param>
        public static TopChainer TopWithTies(this ITop prev, string variable)
        {
            return new TopChainer((Chainer)prev, variable, true);
        }

        #endregion

        #region Internal

        internal static TopChainer Top(this ITop prev, Nullable<long> top, int overloader)
        {
            if (prev is ISemantic)
            {
                return new TopChainer((ISemantic)prev, top, false, 0);
            }
            else
            {
                return new TopChainer((Chainer)prev, top, false, true);
            }
        }

        #endregion
    }
}


text:
.class public Lcom/android/internal/util/IndentingPrintWriter;
.super Ljava/io/PrintWriter;
.source "IndentingPrintWriter.java"

# instance fields
.field private mBuilder:Ljava/lang/StringBuilder;

.field private mCurrent:[C

.field private mEmptyLine:Z

.field private final mIndent:Ljava/lang/String;

# direct methods
.method public constructor <init>(Ljava/io/Writer;Ljava/lang/String;)V
    .locals 1
    .parameter "writer"
    .parameter "indent"

    .prologue
    .line 35
    invoke-direct {p0, p1}, Ljava/io/PrintWriter;-><init>(Ljava/io/Writer;)V

    .line 30
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    iput-object v0, p0, Lcom/android/internal/util/IndentingPrintWriter;->mBuilder:Ljava/lang/StringBuilder;

    .line 32
    const/4 v0, 0x1

    iput-boolean v0, p0, Lcom/android/internal/util/IndentingPrintWriter;->mEmptyLine:Z

    .line 36
    iput-object p2, p0, Lcom/android/internal/util/IndentingPrintWriter;->mIndent:Ljava/lang/String;

    .line 37
    return-void
.end method

.method private writeIndent()V
    .locals 3

    .prologue
    const/4 v2, 0x0

    .line 75
    iget-boolean v0, p0, Lcom/android/internal/util/IndentingPrintWriter;->mEmptyLine:Z

    if-eqz v0, :cond_1

    .line 76
    iput-boolean v2, p0, Lcom/android/internal/util/IndentingPrintWriter;->mEmptyLine:Z

    .line 77
    iget-object v0, p0, Lcom/android/internal/util/IndentingPrintWriter;->mBuilder:Ljava/lang/StringBuilder;

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->length()I

    move-result v0

    if-eqz v0, :cond_1

    .line 78
    iget-object v0, p0, Lcom/android/internal/util/IndentingPrintWriter;->mCurrent:[C

    if-nez v0, :cond_0

    .line 79
    iget-object v0, p0, Lcom/android/internal/util/IndentingPrintWriter;->mBuilder:Ljava/lang/StringBuilder;

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/String;->toCharArray()[C

    move-result-object v0

    iput-object v0, p0, Lcom/android/internal/util/IndentingPrintWriter;->mCurrent:[C

    .line 81
    :cond_0
    iget-object v0, p0, Lcom/android/internal/util/IndentingPrintWriter;->mCurrent:[C

    iget-object v1, p0, Lcom/android/internal/util/IndentingPrintWriter;->mCurrent:[C

    array-length v1, v1

    invoke-super {p0, v0, v2, v1}, Ljava/io/PrintWriter;->write([CII)V

    .line 84
    :cond_1
    return-void
.end method

# virtual methods
.method public decreaseIndent()V
    .locals 3

    .prologue
    .line 45
    iget-object v0, p0, Lcom/android/internal/util/IndentingPrintWriter;->mBuilder:Ljava/lang/StringBuilder;

    const/4 v1, 0x0

    iget-object v2, p0, Lcom/android/internal/util/IndentingPrintWriter;->mIndent:Ljava/lang/String;

    invoke-virtual {v2}, Ljava/lang/String;->length()I

    move-result v2

    invoke-virtual {v0, v1, v2}, Ljava/lang/StringBuilder;->delete(II)Ljava/lang/StringBuilder;

    .line 46
    const/4 v0, 0x0

    iput-object v0, p0, Lcom/android/internal/util/IndentingPrintWriter;->mCurrent:[C

    .line 47
    return-void
.end method

.method public increaseIndent()V
    .locals 2

    .prologue
    .line 40
    iget-object v0, p0, Lcom/android/internal/util/IndentingPrintWriter;->mBuilder:Ljava/lang/StringBuilder;

    iget-object v1, p0, Lcom/android/internal/util/IndentingPrintWriter;->mIndent:Ljava/lang/String;

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 41
    const/4 v0, 0x0

    iput-object v0, p0, Lcom/android/internal/util/IndentingPrintWriter;->mCurrent:[C

    .line 42
    return-void
.end method

.method public printPair(Ljava/lang/String;Ljava/lang/Object;)V
    .locals 2
    .parameter "key"
    .parameter "value"

    .prologue
    .line 50
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {v0, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, "="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-static {p2}, Ljava/lang/String;->valueOf(Ljava/lang/Object;)Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, " "

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-virtual {p0, v0}, Lcom/android/internal/util/IndentingPrintWriter;->print(Ljava/lang/String;)V

    .line 51
    return-void
.end method

.method public write([CII)V
    .locals 6
    .parameter "buf"
    .parameter "offset"
    .parameter "count"

    .prologue
    .line 55
    add-int v0, p2, p3

    .line 56
    .local v0, bufferEnd:I
    move v4, p2

    .line 57
    .local v4, lineStart:I
    move v2, p2

    .local v2, lineEnd:I
    move v3, v2

    .line 58
    .end local v2           #lineEnd:I
    .local v3, lineEnd:I
    :goto_0
    if-ge v3, v0, :cond_1

    .line 59
    add-int/lit8 v2, v3, 0x1

    .end local v3           #lineEnd:I
    .restart local v2       #lineEnd:I
    aget-char v1, p1, v3

    .line 60
    .local v1, ch:C
    const/16 v5, 0xa

    if-ne v1, v5, :cond_0

    .line 61
    invoke-direct {p0}, Lcom/android/internal/util/IndentingPrintWriter;->writeIndent()V

    .line 62
    sub-int v5, v2, v4

    invoke-super {p0, p1, v4, v5}, Ljava/io/PrintWriter;->write([CII)V

    .line 63
    move v4, v2

    .line 64
    const/4 v5, 0x1

    iput-boolean v5, p0, Lcom/android/internal/util/IndentingPrintWriter;->mEmptyLine:Z

    :cond_0
    move v3, v2

    .line 66
    .end local v2           #lineEnd:I
    .restart local v3       #lineEnd:I
    goto :goto_0

    .line 68
    .end local v1           #ch:C
    :cond_1
    if-eq v4, v3, :cond_2

    .line 69
    invoke-direct {p0}, Lcom/android/internal/util/IndentingPrintWriter;->writeIndent()V

    .line 70
    sub-int v5, v3, v4

    invoke-super {p0, p1, v4, v5}, Ljava/io/PrintWriter;->write([CII)V

    .line 72
    :cond_2
    return-void
.end method


text:
using mvlSite.CompressionMiddleware.Compressors;
using Owin;

namespace mvlSite.CompressionMiddleware
{
    public static class CompressionExtension
    {
        public static IAppBuilder UseCompression(this IAppBuilder appBuilder)
        {
            var tmpSettings = new CompressionSettings(new GZipCompressor(), new DeflateCompressor());
            return appBuilder.Use<CompressionMiddleware>(tmpSettings);
        }
    }
}


text:
from __future__ import print_function, absolute_import, unicode_literals

import sys
import math
from os.path import abspath, split

import colors
import click
import six

from pygments import highlight
from pygments.formatters import Terminal256Formatter, TerminalFormatter
from pygments.lexers import get_lexer_by_name

import coverage

from cuv.analysis import CoverageAnalysis, create_analysis
from cuv.util import print_banner, paged_echo
from unidiff import PatchSet

def diff_coverage_files(file_a, file_b, cfg):
    """
    This shows the difference in lines covered between two coverage files
    """

    data_a = coverage.Coverage(data_file=file_a)
    data_a.load()

    data_b = coverage.Coverage(data_file=file_b)
    data_b.load()

    click.echo(
        "Comparing {} vs {}".format(
            click.style(file_a, fg='red'),
            click.style(file_b, fg='green'),
        )
    )

    diff_coverage_data(data_a, data_b, cfg)

def diff_coverage_data(data_a, data_b, cfg):
    """
    """
    files_a = set(data_a.get_data().measured_files())
    files_b = set(data_b.get_data().measured_files())
    common_files = files_a.intersection(files_b)

    for fname in common_files:
        a = create_analysis(data_a, fname)
        b = create_analysis(data_b, fname)
        a_has = []
        b_has = []

        if a.statements != b.statements:
            click.echo("{}: statement mismatch".format(fname))
        else:
            for x in a.statements:
                if x in a.missing:
                    if x not in b.missing:
                        b_has.append(x)
                else:
                    if x in b.missing:
                        a_has.append(x)
            if a_has != [] or b_has != []:
                click.echo(
                    "{}: {} vs. {}".format(
                        fname,
                        click.style(','.join([str(s) for s in a_has]), fg='red'),
                        click.style(','.join([str(s) for s in b_has]), fg='green'),
                    )
                )

def diff_color(input_file, cfg):
    """
    colorizes a diff file
    """
    cov = cfg.data

    with paged_echo() as pager:
        term_width = click.get_terminal_size()[0]
        modified = []
        measured = [
            abspath(p)
            for p in cov.get_data().measured_files()
        ]
        diff = PatchSet(input_file)
        patched_to_measured = match_coverage_files(measured, diff)

        for thing in diff:
            if thing.is_modified_file or thing.is_added_file:
                target = thing.target_file
                if target.startswith('b/') or target.startswith('a/'):
                    target = target[2:]
                target = abspath(target)
                target = patched_to_measured.get(target, target)
                if target in measured:
                    covdata = cov._analyze(abspath(target))
                    modified.append((thing, covdata))
#                    pager.echo(abspath(target))
                else:
                    msg = "skip: {}".format(target)
                    msg = msg + (' ' * (term_width - len(msg)))
                    pager.echo(colors.color(msg, bg='yellow', fg='black'))

        total_added_lines = 0
        total_covered_lines = 0

        for (patch, covdata) in modified:
            fname = str(patch.target_file) + (' ' * (term_width - len(patch.target_file)))
            pager.echo(colors.color(fname, bg='cyan', fg='black'))
            for hunk in patch:
                for line in hunk:
                    kw = dict()
                    if line.is_added:
                        total_added_lines += 1
                        if line.target_line_no in covdata.missing:
                            pager.echo(colors.color(u'\u258c', fg='red', bg=52), nl=False, color=True)
                            kw['bg'] = 52
                        else:
                            total_covered_lines += 1
                            pager.echo(colors.color(u'\u258f', fg='green'), nl=False, color=True)
                    else:
                        pager.echo(' ', nl=False)
                    out = u"{}".format(line).strip()
                    if line.is_added:
                        kw['fg'] = 'green'
                    elif line.is_removed:
                        kw['fg'] = 'red'
                    pager.echo(colors.color(out, **kw))

        if total_added_lines == 0:
            raise click.ClickException("No covered lines at all")

        percent_covered = (total_covered_lines / float(total_added_lines))
        msg = u"{} covered of {} added lines".format(total_covered_lines, total_added_lines)
        print_banner(msg, percent_covered, pager=pager)
        return

        target_fname = abspath(target_fname)
        for fname in cov.get_data().measured_files():
            if target_fname == abspath(fname):
                match.append(fname)

        if len(match) != 1:
            if len(match) == 0:
                # this file wasn't in the coverage data, so we just dump
                # it to stdout as-is. (FIXME: ideally, also
                # syntax-highlighted anyway)
                with open(target_fname, 'r') as f:
                    for line in f.readlines():
                        sys.stdout.write(line)
                return
            else:
                raise RuntimeError("Multiple matches: %s" % ', '.join(match))

        fname = match[0]
        covdata = cov._analyze(fname)

        percent = 1.0  # if no statements, it's all covered, right?
        if covdata.numbers.n_statements:
            percent = float(covdata.numbers.n_statements - covdata.numbers.n_missing) / covdata.numbers.n_statements
        total_statements = covdata.numbers.n_statements
        total_missing = covdata.numbers.n_missing

        fill = min(click.get_terminal_size()[0], 80)
        print_banner(fname, percent, fill)

        # it was tempting to write/override/wrap this Formatter and mess
        # with the background color based on our coverage data -- and
        # that's not a terrible idea, but the way TerminalFormatter is
        # written, it's not very nice. Basically, we'd have to wrap the
        # output stream, look for ANSI reset codes, and re-do the
        # background color after each reset (for "uncovered" lines)...  so
        # I didn't do that. Instead we just hack it by splitting on the
        # reset codes (see below)

        formatter = TerminalFormatter(style=style)
        lines = highlight(
            open(fname).read(), get_lexer_by_name('python'),
            formatter=formatter,
        )
        lines = lines.split(u'\n')

        for (i, line) in enumerate(lines):
    #        assert type(line) is unicode
            spaces = fill - len(colors.strip_color(line))
            spaces = u' ' * spaces
            if (i + 1) not in covdata.missing:
                if (i + 1) in covdata.excluded:
                    line = colors.strip_color(line)
                    pager.echo(colors.color(u'\u258f', fg=46, bg=236) + colors.color(line + spaces, bg=236, fg=242), color=True)
                elif cfg.branch and (i + 1) in covdata.branch_lines():
                    line = colors.strip_color(line)
                    pager.echo(colors.color(u'\u258f', bg=52, fg=160) + colors.color(line + spaces, bg=52), color=True)
                else:
                    pager.echo(u'{}{}{}'.format(colors.color(u'\u258f', fg=46), line, spaces), color=True)
            else:
                # HACK-O-MATIC, uhm. Yeah, so what we're doing here is
                # splitting the output from the formatter on the ANSI
                # "reset" code, and the re-assembling it with the "52"
                # (dark red) background color. I appoligize in advance;
                # PRs with improvements encouraged!
                reset_code = u"\x1b[39;49;00m"
                segments = (line + spaces).split(reset_code)
                reset_plus_bg = u"\x1b[39;49;00m\x1b[39;49;48;5;52m"
                out = u"\x1b[39;49;48;5;52m" + reset_plus_bg.join(segments)
                pager.echo(colors.color(u'\u258f', bg=52, fg=160) + out, color=True)
                # (on the plus side: this preserves syntax-highlighting
                # while also getting a background color on the whole
                # line)

def match_coverage_files(measured, diff):
    """
    :param list measured: absolute paths of files in the coverage data
    :param PatchSet diff: the diff (containing relative paths) we're comparing

    basically trying to reverse-enginner the "base path" of both the
    "measured" and "patched" files, assuming that they're the same
    project (e.g. /home/foo/src/project/src/__init__.py might be your
    checkout's file in the diff (so like "a/src/__init__.py" in the
    diff) while
    /home/foo/src/project/.tox/py3/lib/python3.9/site-packages/project/__init__.py
    might be what's in the coverage file)
    """

    patched = []
    for thing in diff:
        if thing.is_modified_file or thing.is_added_file:
            target = thing.target_file
            if target.startswith('b/') or target.startswith('a/'):
                target = target[2:]
            patched.append(abspath(target))

    patched_to_measured = {}

    for m in measured:
        # XXX FIXME pathlib or something
        m_segs = m.split("/")
        best = None
        for p in patched:
            p_segs = p.split("/")
            end = -1
            while m_segs[end] == p_segs[end] and -end < len(m_segs):
                end = end - 1
            if best is None or end < best[0]:
                best = end, p
        # we demand "< -1" because at least the filename itself must
        # match
        if best is not None and best[0] < -1:
            patched_to_measured[best[1]] = m
    return patched_to_measured

def _diff_coverage_statistics(cov, diff_file):
    """
    :returns: a dict containing statistics about coverage of
    differences in the provided diff. Contains the following items:

     - total_added_lines: number of "+" lines in the diff
     - total_covered_lines: number of "+" lines with test-coverage
    """

    modified = []
    measured = [
        abspath(p)
        for p in cov.get_data().measured_files()
    ]

    diff = PatchSet(diff_file, encoding="utf8")
    patched_to_measured = match_coverage_files(measured, diff)

    # XXX code partially duplicated above, in match_coverage_files
    for thing in diff:
        if thing.is_modified_file or thing.is_added_file:
            target = thing.target_file
            if target.startswith('b/') or target.startswith('a/'):
                target = target[2:]
            target = abspath(target)
            target = patched_to_measured.get(target, target)
            if target in measured:
                covdata = cov._analyze(target)
                modified.append((thing, covdata))

    # this chunk is "pretty" similar to the stuff in diff_cov so
    # it might be worth combining, somehow?
    total_added_lines = 0
    total_covered_lines = 0

    for (patch, covdata) in modified:
        for hunk in patch:
            for line in hunk:
                if line.is_added:
                    total_added_lines += 1
                    if line.target_line_no not in covdata.missing:
                        total_covered_lines += 1
    return {
        "total_added_lines": total_added_lines,
        "total_covered_lines": total_covered_lines,
    }

def diff_report(input_file, cfg):
    """
    produces a summary report about a diff
    """
    cov = cfg.data

    stats = _diff_coverage_statistics(cov, input_file)

    percent_covered = (stats["total_covered_lines"] / float(stats["total_added_lines"])) * 100.0
    click.echo(
        u"{percent:.1f}%: {covered} covered of {added} added lines (leaving {missing} missing)".format(
            percent=percent_covered,
            covered=stats["total_covered_lines"],
            added=stats["total_added_lines"],
            missing=(stats["total_added_lines"] - stats["total_covered_lines"]),
        )
    )


text:
@interface CSRecordAudioViewController () <AVAudioRecorderDelegate, AVAudioPlayerDelegate>

@property (nonatomic, strong) AVAudioRecorder *recorder;
@property (nonatomic, strong) NSTimer* updateTimer;
@property (nonatomic, strong) NSTimer* recordTimer;
@property (nonatomic, strong) NSData* audioData;
@property (nonatomic, strong) NSTimer* pulseTimer;
@property (nonatomic, strong) SE2AudioPlayerView *audioPlayer;

@end

@implementation CSRecordAudioViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    NSArray *pathComponents = [NSArray arrayWithObjects:
                               [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
                               @"MyAudioMemo.m4a",
                               nil];
    NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];

    // Setup audio session
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

    // Define the recorder setting
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];

    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];

    // Initiate and prepare the recorder
    _recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:NULL];
    _recorder.delegate = self;
    _recorder.meteringEnabled = YES;
    [_recorder prepareToRecord];

    self.audioView.backgroundColor = [UIColor whiteColor];
    self.audioView.layer.masksToBounds = YES;

    self.playButton.layer.cornerRadius = self.playButton.frame.size.height/2;
    self.playButton.layer.borderWidth = 2.0f;
    self.playButton.layer.borderColor = kAppDefaultColor(1).CGColor;

    self.playLabel.textColor = kAppDefaultColor(1);
    self.playLabel.alpha = 0.0f;

    self.expandingGreenBackgroundView.layer.cornerRadius = self.expandingGreenBackgroundView.frame.size.height/2;
    self.expandingGreenBackgroundView.backgroundColor = kAppDefaultColor(1);

    self.pulastingView.layer.cornerRadius = self.pulastingView.frame.size.height/2;
    self.pulastingView.layer.borderWidth = 1/((self.audioView.frame.size.height+50)/150);
    self.pulastingView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.pulastingView.backgroundColor = [UIColor clearColor];

    self.audioPlayerView.layer.cornerRadius = 5.0f;
    self.audioPlayerView.layer.borderColor = kAppDefaultColor(1).CGColor;
    self.audioPlayerView.layer.borderWidth = 1.0f;
    self.audioPlayerView.alpha = 0;

    self.edgesForExtendedLayout = UIRectEdgeNone;

    self.okButton.enabled = NO;
}

-(void)viewWillDisappear:(BOOL)animated{

    [self.updateTimer invalidate];
    self.updateTimer = nil;
    [self.recordTimer invalidate];
    self.recordTimer = nil;
    [_pulseTimer invalidate];
    _pulseTimer = nil;

    [super viewWillDisappear:animated];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) initAudio{

    _audioData = [NSData dataWithContentsOfURL:_recorder.url];
    NSString* sizeString = [NSString stringWithFormat:@"%ld", (unsigned long)_audioData.length];
    [self.okButton setTitle:[NSString stringWithFormat:@"Ok, %@", [CSUtils readableFileSize:sizeString]] forState:UIControlStateNormal];
    self.okButton.enabled = YES;
}

-(void) animateView
{
    [UIView animateWithDuration:0.7
                     animations:^{

                         const CGFloat scale = sqrt(pow(self.audioView.frame.size.height / 2, 2) + pow(self.audioView.frame.size.width / 2, 2)) / 25;
                         [self.expandingGreenBackgroundView setTransform:CGAffineTransformMakeScale(scale, scale)];

                         self.playLabel.alpha = 1.0f;
                         [self.playImageView setTransform:CGAffineTransformMakeScale(0.8f, 0.8f)];

                         [self.view layoutIfNeeded];

                     } completion:^(BOOL finished) {
                         [self pulseAnimation];
                         [self pulseTimer];
                         _pulseTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                                                        target:self
                                                                      selector:@selector(pulseAnimation)
                                                                      userInfo:nil
                                                                       repeats:YES];
                     }];
}

-(void) pulseAnimation
{
    [UIView animateWithDuration:0.7
                     animations:^{

                         const CGFloat scale = sqrt(pow(self.audioView.frame.size.height / 2, 2) + pow(self.audioView.frame.size.width / 2, 2)) / 25;
                         [self.pulastingView setTransform:CGAffineTransformMakeScale(scale, scale)];

                     } completion:^(BOOL finished) {

                         self.pulastingView.alpha = 0;
                         const CGFloat scale = 1;
                         [self.pulastingView setTransform:CGAffineTransformMakeScale(scale, scale)];
                         self.pulastingView.alpha = 1;

                     }];
}

-(void)animateReverseColor
{
    [UIView animateWithDuration:0.2
                     animations:^{

                         const CGFloat scale = 1;
                         [self.expandingGreenBackgroundView setTransform:CGAffineTransformMakeScale(scale, scale)];

                         self.playLabel.alpha = 0.0f;
                         [self.playImageView setTransform:CGAffineTransformMakeScale(1.0f, 1.0f)];

                     } completion:^(BOOL finished) {
                         [self addAudioPlayer];
                     }];

}

-(void)addAudioPlayer
{
    _audioPlayer = [[SE2AudioPlayerView alloc] initWithFrame:CGRectMake(0,
                                                                        0,
                                                                        self.audioPlayerView.frame.size.width,
                                                                        self.audioPlayerView.frame.size.height)
                                                         url:[_recorder.url path]];
    [self.audioPlayerView addSubview:_audioPlayer];

    [self animateAudioPlayer:YES];

}

-(void)animateAudioPlayer:(BOOL)boolValue
{
    [UIView animateWithDuration:0.2
                     animations:^{

                         self.audioPlayerView.alpha = boolValue ? 1 : 0;

                     } completion:^(BOOL finished) {

                         if (!boolValue) {
                             _audioPlayer = nil;
                         }

                     }];
}

- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag{

    [self initAudio];
}

- (void)updateSlider{

}

- (void)updateRecTime{

}

- (IBAction)onRecord:(id)sender
{
    if (!_recorder.recording) {
        [self animateView];
        [self animateAudioPlayer:NO];

        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];

        // Start recording
        [_recorder record];

    } else {

        // Pause recording
        [_recorder stop];

        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        [audioSession setActive:NO error:nil];

        [self.recordTimer invalidate];
        self.recordTimer = nil;
        [_pulseTimer invalidate];
        _pulseTimer = nil;

        [self animateReverseColor];

    }

}

- (IBAction)onCancelClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)onOkClicked:(id)sender {
    NSString* mimeType = @"audio/wav";
    NSString* fileName = [NSString stringWithFormat:@"audio_%@.%@", [NSString stringWithFormat:@"%d", (int)[[NSDate date] timeIntervalSince1970]], @"wav"];

    NSData* data = [NSData dataWithContentsOfURL:_recorder.url];

    CSUploadManager* manager = [CSUploadManager new];
    [manager uploadFile:data fileName:fileName mimeType:mimeType viewForLoading:self.view completition:^(id responseObject){

        [[NSNotificationCenter defaultCenter] postNotificationName:kAppFileUploadedNotification
                                                            object:nil
                                                          userInfo:[NSDictionary dictionaryWithObject:responseObject forKey:paramResponseObject]];
        [self.navigationController popViewControllerAnimated:YES];

    }];
}
@end


text:
#ifndef CMSIS_PLUS_RTOS_OS_MEMPOOL_H_
#define CMSIS_PLUS_RTOS_OS_MEMPOOL_H_

// ----------------------------------------------------------------------------

#if defined(__cplusplus)

#include <cmsis-plus/rtos/os-decls.h>
#include <cmsis-plus/rtos/os-memory.h>

#include <cmsis-plus/diag/trace.h>

// ----------------------------------------------------------------------------

namespace os
{
  namespace rtos
  {

    // ========================================================================

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpadded"

    /**
     * @brief Synchronised **memory pool**, using the
     * default RTOS allocator.
     * @headerfile os.h <cmsis-plus/rtos/os.h>
     * @ingroup cmsis-plus-rtos-mempool
     */
    class memory_pool : public internal::object_named_system
    {
    public:

      // ======================================================================

      /**
       * @brief Type of memory pool size storage.
       * @details
       * A numeric value that can hold the maximum size of the
       * memory pool, usually a 16-bits unsigned value.
       * @ingroup cmsis-plus-rtos-mempool
       */
      using size_t = uint16_t;

      /**
       * @brief Maximum pool size.
       * @details
       * A constant numeric value used to validate the pool size.
       * @ingroup cmsis-plus-rtos-mempool
       */
      static constexpr memory_pool::size_t max_size =
          static_cast<memory_pool::size_t> (0 - 1);

      // ======================================================================

      /**
       * @brief Memory pool attributes.
       * @headerfile os.h <cmsis-plus/rtos/os.h>
       * @ingroup cmsis-plus-rtos-mempool
       */
      class attributes : public internal::attributes_clocked
      {
      public:

        /**
         * @name Constructors & Destructor
         * @{
         */

        /**
         * @brief Construct a memory pool attributes object instance.
         * @par Parameters
         *  None.
         */
        constexpr
        attributes ();

        // The rule of five.
        attributes (const attributes&) = default;
        attributes (attributes&&) = default;
        attributes&
        operator= (const attributes&) = default;
        attributes&
        operator= (attributes&&) = default;

        /**
         * @brief Destruct the memory pool attributes object instance.
         */
        ~attributes () = default;

        /**
         * @}
         */

      public:

        /**
         * @name Public Member Variables
         * @{
         */

        // Public members; no accessors and mutators required.
        // Warning: must match the type & order of the C file header.
        /**
         * @brief Address of the user defined storage for the memory pool.
         */
        void* mp_pool_address = nullptr;

        /**
         * @brief Size of the user defined storage for the memory pool.
         */
        std::size_t mp_pool_size_bytes = 0;

        // Add more attributes here.

        /**
         * @}
         */

      }; /* class attributes */

      /**
       * @brief Default memory pool initialiser.
       * @ingroup cmsis-plus-rtos-mempool
       */
      static const attributes initializer;

      /**
       * @brief Storage for a memory pool.
       * @details
       * Each message is stored in an element
       * extended to a multiple of pointers. The free lists
       * is kept inside the blocks and does not require additional
       * storage.
       */
      template<typename T, std::size_t blocks, std::size_t block_size_bytes>
        class arena
        {
        public:
          T pool[(blocks * block_size_bytes + sizeof(T) - 1) / sizeof(T)];
        };

      /**
       * @brief Calculator for pool storage requirements.
       * @param blocks Number of blocks.
       * @param block_size_bytes Size of block.
       * @return Total required storage in bytes, including internal alignment.
       */
      template<typename T>
        constexpr std::size_t
        compute_allocated_size_bytes (std::size_t blocks,
                                      std::size_t block_size_bytes)
        {
          // Align each block
          return (blocks
              * ((block_size_bytes + (sizeof(T) - 1)) & ~(sizeof(T) - 1)));
        }

      // ======================================================================

      /**
       * @brief Default RTOS allocator.
       */
      using allocator_type = memory::allocator<thread::stack::allocation_element_t>;

      /**
       * @name Constructors & Destructor
       * @{
       */

      /**
       * @brief Construct a memory pool object instance.
       * @param [in] blocks The maximum number of items in the pool.
       * @param [in] block_size_bytes The size of an item, in bytes.
       * @param [in] attr Reference to attributes.
       * @param [in] allocator Reference to allocator. Default a
       * local temporary instance.
       */
      memory_pool (std::size_t blocks, std::size_t block_size_bytes,
                   const attributes& attr = initializer,
                   const allocator_type& allocator = allocator_type ());
      /**
       * @brief Construct a named memory pool object instance.
       * @param [in] name Pointer to name.
       * @param [in] blocks The maximum number of items in the pool.
       * @param [in] block_size_bytes The size of an item, in bytes.
       * @param [in] attr Reference to attributes.
       * @param [in] allocator Reference to allocator. Default a
       * local temporary instance.
       */
      memory_pool (const char* name, std::size_t blocks,
                   std::size_t block_size_bytes, const attributes& attr =
                       initializer,
                   const allocator_type& allocator = allocator_type ());

    protected:

      /**
       * @cond ignore
       */

      // Internal constructors, used from templates.
      memory_pool ();
      memory_pool (const char* name);

      /**
       * @endcond
       */

    public:

      /**
       * @cond ignore
       */

      // The rule of five.
      memory_pool (const memory_pool&) = delete;
      memory_pool (memory_pool&&) = delete;
      memory_pool&
      operator= (const memory_pool&) = delete;
      memory_pool&
      operator= (memory_pool&&) = delete;

      /**
       * @endcond
       */

    public:

      /**
       * @brief Destruct the memory pool object instance.
       */
      virtual
      ~memory_pool ();

      /**
       * @}
       */

      /**
       * @name Operators
       * @{
       */

      /**
       * @brief Compare memory pools.
       * @retval true The given memory pool is the same as this memory pool.
       * @retval false The memory pools are different.
       */
      bool
      operator== (const memory_pool& rhs) const;

      /**
       * @}
       */

    public:

      /**
       * @name Public Member Functions
       * @{
       */

      /**
       * @brief Allocate a memory block.
       * @par Parameters
       *  None.
       * @return Pointer to memory block, or `nullptr` if interrupted.
       */
      void*
      alloc (void);

      /**
       * @brief Try to allocate a memory block.
       * @par Parameters
       *  None.
       * @return Pointer to memory block, or `nullptr` if no memory available.
       */
      void*
      try_alloc (void);

      /**
       * @brief Allocate a memory block with timeout.
       * @param [in] timeout Timeout to wait, in clock units (ticks or seconds).
       * @return Pointer to memory block, or `nullptr` if timeout.
       */
      void*
      timed_alloc (clock::duration_t timeout);

      /**
       * @brief Free the memory block.
       * @param [in] block Pointer to memory block to free.
       * @retval result::ok The memory block was released.
       * @retval EINVAL The block does not belong to the memory pool.
       */
      result_t
      free (void* block);

      /**
       * @brief Get memory pool capacity.
       * @par Parameters
       *  None.
       * @return The max number of blocks in the pool.
       */
      std::size_t
      capacity (void) const;

      /**
       * @brief Get blocks count.
       * @par Parameters
       *  None.
       * @return The number of blocks used from the queue.
       */
      std::size_t
      count (void) const;

      /**
       * @brief Get block size.
       * @par Parameters
       *  None.
       * @return The block size, in bytes.
       */
      std::size_t
      block_size (void) const;

      /**
       * @brief Check if the memory pool is empty.
       * @par Parameters
       *  None
       * @retval true The memory pool has no allocated blocks.
       * @retval false The memory pool has allocated blocks.
       */
      bool
      empty (void) const;

      /**
       * @brief Check if the memory pool is full.
       * @par Parameters
       *  None.
       * @retval true All memory blocks are allocated.
       * @retval false There are still memory blocks that can be allocated.
       */
      bool
      full (void) const;

      /**
       * @brief Reset the memory pool.
       * @par Parameters
       *  None.
       * @retval result::ok The memory pool was reset.
       * @retval EPERM Cannot be invoked from an Interrupt Service Routines.
       */
      result_t
      reset (void);

      /**
       * @brief Get the pool storage address.
       * @par Parameters
       *  None.
       * @return Pointer to storage.
       */
      void*
      pool (void);

      /**
       * @}
       */

    protected:

      /**
       * @name Private Member Functions
       * @{
       */

      /**
       * @cond ignore
       */

      /**
       * @brief Internal function used during memory pool construction.
       * @param [in] blocks The maximum number of items in the pool.
       * @param [in] block_size_bytes The size of an item, in bytes.
       * @param [in] attr Reference to attributes.
       * @param [in] pool_address Pointer to queue storage.
       * @param [in] pool_size_bytes Size of queue storage.
       */
      void
      internal_construct_ (std::size_t blocks, std::size_t block_size_bytes,
                           const attributes& attr, void* pool_address,
                           std::size_t pool_size_bytes);

      /**
       * @brief Internal initialisation.
       * @par Parameters
       *  None.
       * @returns
       *  Nothing.
       */
      void
      internal_init_ (void);

      /**
       * @brief Internal function used to get the first linked block.
       * @par Parameters
       *  None.
       * @return Pointer to block or `nullptr` if no more blocks available.
       */
      void*
      internal_try_first_ (void);

      /**
       * @endcond
       */

      /**
       * @}
       */

    protected:

      /**
       * @name Private Member Variables
       * @{
       */

      /**
       * @cond ignore
       */

#if !defined(OS_USE_RTOS_PORT_MEMORY_POOL)
      /**
       * @brief List of threads waiting to alloc.
       */
      internal::waiting_threads_list list_;
      /**
       * @brief Pointer to clock to be used for timeouts.
       */
      clock* clock_ = nullptr;
#endif
      /**
       * @brief The static address where the pool is stored
       * (from `attr.mp_pool_address`).
       */
      void* pool_addr_ = nullptr;
      /**
       * @brief The dynamic address if the pool was allocated
       * (and must be deallocated)
       */
      void* allocated_pool_addr_ = nullptr;

      /**
       * @brief Pointer to allocator.
       */
      const void* allocator_ = nullptr;

#if defined(OS_USE_RTOS_PORT_MEMORY_POOL)
      friend class port::memory_pool;
      os_mempool_port_data_t port_;
#endif

      /**
       * @brief Total size of the statically allocated pool storage
       * (from `attr.mp_pool_size_bytes`).
       */
      std::size_t pool_size_bytes_ = 0;
      /**
       * @brief Total size of the dynamically allocated pool storage.
       */
      std::size_t allocated_pool_size_elements_ = 0;

      /**
       * @brief The number of blocks in the pool.
       */
      memory_pool::size_t blocks_ = 0;

      /**
       * @brief The size of a block, in bytes.
       */
      memory_pool::size_t block_size_bytes_ = 0;

      /**
       * @brief The current number of blocks allocated from the pool.
       */
      volatile memory_pool::size_t count_ = 0;

      /**
       * @brief Pointer to the first free block, or nullptr.
       */
      void* volatile first_ = nullptr;

      /**
       * @endcond
       */

      /**
       * @}
       */

    };

    // ========================================================================

    /**
     * @brief Template of a synchronised **memory pool** with allocator.
     * @headerfile os.h <cmsis-plus/rtos/os.h>
     * @ingroup cmsis-plus-rtos-mempool
     */
    template<typename Allocator = memory::allocator<void*>>
      class memory_pool_allocated : public memory_pool
      {
      public:

        /**
         * @brief Standard allocator type definition.
         */
        using allocator_type = Allocator;

        /**
         * @name Constructors & Destructor
         * @{
         */

        /**
         * @brief Construct a memory pool object instance.
         * @param [in] blocks The maximum number of items in the pool.
         * @param [in] block_size_bytes The size of an item, in bytes.
         * @param [in] attr Reference to attributes.
         * @param [in] allocator Reference to allocator. Default a
         * local temporary instance.
         */
        memory_pool_allocated (std::size_t blocks, std::size_t block_size_bytes,
                               const attributes& attr = initializer,
                               const allocator_type& allocator =
                                   allocator_type ());

        /**
         * @brief Construct a named memory pool object instance.
         * @param [in] name Pointer to name.
         * @param [in] blocks The maximum number of items in the pool.
         * @param [in] block_size_bytes The size of an item, in bytes.
         * @param [in] attr Reference to attributes.
         * @param [in] allocator Reference to allocator. Default a
         * local temporary instance.
         */
        memory_pool_allocated (const char* name, std::size_t blocks,
                               std::size_t block_size_bytes,
                               const attributes& attr = initializer,
                               const allocator_type& allocator =
                                   allocator_type ());

        /**
         * @cond ignore
         */

        // The rule of five.
        memory_pool_allocated (const memory_pool_allocated&) = delete;
        memory_pool_allocated (memory_pool_allocated&&) = delete;
        memory_pool_allocated&
        operator= (const memory_pool_allocated&) = delete;
        memory_pool_allocated&
        operator= (memory_pool_allocated&&) = delete;

        /**
         * @endcond
         */

        /**
         * @brief Destruct the memory pool object instance.
         */
        virtual
        ~memory_pool_allocated ();

        /**
         * @}
         */

      };

    // ========================================================================

    /**
     * @brief Template of a synchronised **memory pool** with
     * block type and allocator.
     * @headerfile os.h <cmsis-plus/rtos/os.h>
     * @ingroup cmsis-plus-rtos-mempool
     */
    template<typename T, typename Allocator = memory::allocator<void*>>
      class memory_pool_typed : public memory_pool_allocated<Allocator>
      {
      public:

        /**
         * @brief Standard allocator type definition.
         */
        using value_type = T;
        /**
         * @brief Standard allocator type definition.
         */
        using allocator_type = Allocator;

        /**
         * @name Constructors & Destructor
         * @{
         */

        /**
         * @brief Construct a memory pool object instance.
         * @param [in] blocks The maximum number of items in the pool.
         * @param [in] attr Reference to attributes.
         * @param [in] allocator Reference to allocator. Default a
         * local temporary instance.
         */
        memory_pool_typed (std::size_t blocks,
                           const memory_pool::attributes& attr =
                               memory_pool::initializer,
                           const allocator_type& allocator = allocator_type ());

        /**
         * @brief Construct a named memory pool object instance.
         * @param [in] name Pointer to name.
         * @param [in] blocks The maximum number of items in the pool.
         * @param [in] attr Reference to attributes.
         * @param [in] allocator Reference to allocator. Default a
         * local temporary instance.
         */
        memory_pool_typed (const char* name, std::size_t blocks,
                           const memory_pool::attributes& attr =
                               memory_pool::initializer,
                           const allocator_type& allocator = allocator_type ());

        /**
         * @cond ignore
         */

        // The rule of five.
        memory_pool_typed (const memory_pool_typed&) = delete;
        memory_pool_typed (memory_pool_typed&&) = delete;
        memory_pool_typed&
        operator= (const memory_pool_typed&) = delete;
        memory_pool_typed&
        operator= (memory_pool_typed&&) = delete;

        /**
         * @endcond
         */

        /**
         * @brief Destruct the memory pool object instance.
         */
        virtual
        ~memory_pool_typed ();

        /**
         * @}
         */

      public:

        /**
         * @name Public Member Functions
         * @{
         */

        /**
         * @brief Allocate a memory block.
         * @par Parameters
         *  None.
         * @return Pointer to memory block, or `nullptr` if interrupted.
         */
        value_type*
        alloc (void);

        /**
         * @brief Allocate a memory block.
         * @par Parameters
         *  None.
         * @return Pointer to memory block, or `nullptr` if no memory available.
         */
        value_type*
        try_alloc (void);

        /**
         * @brief Allocate a memory block with timeout.
         * @param [in] timeout Timeout to wait, in clock units (ticks or seconds).
         * @return Pointer to memory block, or `nullptr` if timeout.
         */
        value_type*
        timed_alloc (clock::duration_t timeout);

        /**
         * @brief Free the memory block.
         * @par Parameters
         *  None.
         * @retval result::ok The memory block was released.
         * @retval EINVAL The block does not belong to the memory pool.
         */
        result_t
        free (value_type* block);

        /**
         * @}
         */

      };

    // ========================================================================

    /**
     * @brief Template of a synchronised **memory pool** with
     * block type and local storage.
     * @headerfile os.h <cmsis-plus/rtos/os.h>
     * @ingroup cmsis-plus-rtos-mempool
     */
    template<typename T, std::size_t N>
      class memory_pool_inclusive : public memory_pool
      {
      public:

        /**
         * @brief Local type of message.
         */
        using value_type = T;

        /**
         * @brief Local constant based on template definition.
         */
        static const std::size_t blocks = N;

        /**
         * @name Constructors & Destructor
         * @{
         */

        /**
         * @brief Construct a memory pool object instance.
         * @param [in] attr Reference to attributes.
         */
        memory_pool_inclusive (const attributes& attr = initializer);

        /**
         * @brief Construct a named memory pool object instance.
         * @param [in] name Pointer to name.
         * @param [in] attr Reference to attributes.
         */
        memory_pool_inclusive (const char* name, const attributes& attr =
                                   initializer);

        /**
         * @cond ignore
         */

        // The rule of five.
        memory_pool_inclusive (const memory_pool_inclusive&) = delete;
        memory_pool_inclusive (memory_pool_inclusive&&) = delete;
        memory_pool_inclusive&
        operator= (const memory_pool_inclusive&) = delete;
        memory_pool_inclusive&
        operator= (memory_pool_inclusive&&) = delete;

        /**
         * @endcond
         */

        /**
         * @brief Destruct the memory pool object instance.
         */
        virtual
        ~memory_pool_inclusive ();

        /**
         * @}
         */

      protected:

        /**
         * @name Private Member Variables
         * @{
         */

        /**
         * @brief Local storage for the pool.
         * @details
         * The local storage is large enough to include `blocks`
         * blocks of type `T`.
         * For performance reasons, the individual components are
         * aligned as pointers.
         */
        arena<void*, blocks, sizeof(T)> arena_;

        /**
         * @}
         */

      public:

        /**
         * @name Public Member Functions
         * @{
         */

        /**
         * @brief Allocate a memory block.
         * @par Parameters
         *  None.
         * @return Pointer to memory block, or `nullptr` if interrupted.
         */
        value_type*
        alloc (void);

        /**
         * @brief Allocate a memory block.
         * @par Parameters
         *  None.
         * @return Pointer to memory block, or `nullptr` if no memory available.
         */
        value_type*
        try_alloc (void);

        /**
         * @brief Allocate a memory block with timeout.
         * @param [in] timeout Timeout to wait, in clock units (ticks or seconds).
         * @return Pointer to memory block, or `nullptr` if timeout.
         */
        value_type*
        timed_alloc (clock::duration_t timeout);

        /**
         * @brief Free the memory block.
         * @par Parameters
         *  None.
         * @retval result::ok The memory block was released.
         * @retval EINVAL The block does not belong to the memory pool.
         */
        result_t
        free (value_type* block);

        /**
         * @}
         */

      };

#pragma GCC diagnostic pop

  } /* namespace rtos */
} /* namespace os */

// ===== Inline & template implementations ====================================

namespace os
{
  namespace rtos
  {
    constexpr
    memory_pool::attributes::attributes ()
    {
      ;
    }

    // ========================================================================

    /**
     * @details
     * Identical memory pools should have the same memory address.
     */
    inline bool
    memory_pool::operator== (const memory_pool& rhs) const
    {
      return this == &rhs;
    }

    /**
     * @details
     *
     * @note Can be invoked from Interrupt Service Routines.
     */
    inline std::size_t
    memory_pool::capacity (void) const
    {
      return blocks_;
    }

    /**
     * @details
     *
     * @note Can be invoked from Interrupt Service Routines.
     */
    inline std::size_t
    memory_pool::block_size (void) const
    {
      return block_size_bytes_;
    }

    /**
     * @details
     *
     * @note Can be invoked from Interrupt Service Routines.
     */
    inline std::size_t
    memory_pool::count (void) const
    {
      return count_;
    }

    /**
     * @details
     *
     * @note Can be invoked from Interrupt Service Routines.
     */
    inline bool
    memory_pool::empty (void) const
    {
      return (count () == 0);
    }

    /**
     * @details
     *
     * @note Can be invoked from Interrupt Service Routines.
     */
    inline bool
    memory_pool::full (void) const
    {
      return (count () == capacity ());
    }

    /**
     * @details
     *
     * @note Can be invoked from Interrupt Service Routines.
     */
    inline void*
    memory_pool::pool (void)
    {
      return pool_addr_;
    }

    // ========================================================================

    /**
     * This constructor shall initialise a memory pool object
     * with attributes referenced by _attr_.
     * If the attributes specified by _attr_ are modified later,
     * the memory pool attributes shall not be affected.
     * Upon successful initialisation, the state of the memory pool
     * variable shall become initialised.
     *
     * Only the memory pool itself may be used for allocations.
     * It is not allowed to make copies of
     * condition variable objects.
     *
     * In cases where default memory pool attributes are
     * appropriate, the variable `memory_pool::initializer` can be used to
     * initialise condition variables.
     * The effect shall be equivalent to creating a memory pool object with
     * the simple constructor.
     *
     * If the attributes define a storage area (via `mp_pool_address` and
     * `mp_pool_size_bytes`), that storage is used, otherwise
     * the storage is dynamically allocated using the RTOS specific allocator
     * (`rtos::memory::allocator`).
     *
     * @warning Cannot be invoked from Interrupt Service Routines.
     */
    template<typename Allocator>
      inline
      memory_pool_allocated<Allocator>::memory_pool_allocated (
          std::size_t blocks, std::size_t block_size_bytes,
          const attributes& attr, const allocator_type& allocator) :
          memory_pool_allocated
            { nullptr, blocks, block_size_bytes, attr, allocator }
      {
        ;
      }

    /**
     * This constructor shall initialise a named memory pool object
     * with attributes referenced by _attr_.
     * If the attributes specified by _attr_ are modified later,
     * the memory pool attributes shall not be affected.
     * Upon successful initialisation, the state of the memory pool
     * variable shall become initialised.
     *
     * Only the memory pool itself may be used for allocations.
     * It is not allowed to make copies of
     * condition variable objects.
     *
     * In cases where default memory pool attributes are
     * appropriate, the variable `memory_pool::initializer` can be used to
     * initialise condition variables.
     * The effect shall be equivalent to creating a memory pool object with
     * the simple constructor.
     *
     * If the attributes define a storage area (via `mp_pool_address` and
     * `mp_pool_size_bytes`), that storage is used, otherwise
     * the storage is dynamically allocated using the RTOS specific allocator
     * (`rtos::memory::allocator`).
     *
     * @warning Cannot be invoked from Interrupt Service Routines.
     */
    template<typename Allocator>
      memory_pool_allocated<Allocator>::memory_pool_allocated (
          const char* name, std::size_t blocks, std::size_t block_size_bytes,
          const attributes& attr, const allocator_type& allocator) :
          memory_pool
            { name }
      {
#if defined(OS_TRACE_RTOS_MEMPOOL)
        trace::printf ("%s() @%p %s %d %d\n", __func__, this, this->name (),
                       blocks, block_size_bytes);
#endif
        if (attr.mp_pool_address != nullptr)
          {
            // Do not use any allocator at all.
            internal_construct_ (blocks, block_size_bytes, attr, nullptr, 0);
          }
        else
          {
            allocator_ = &allocator;

            // If no user storage was provided via attributes,
            // allocate it dynamically via the allocator.
            allocated_pool_size_elements_ = (compute_allocated_size_bytes<
                typename allocator_type::value_type> (blocks, block_size_bytes)
                + sizeof(typename allocator_type::value_type) - 1)
                / sizeof(typename allocator_type::value_type);

            allocated_pool_addr_ =
                const_cast<allocator_type&> (allocator).allocate (
                    allocated_pool_size_elements_);

            internal_construct_ (
                blocks,
                block_size_bytes,
                attr,
                allocated_pool_addr_,
                allocated_pool_size_elements_
                    * sizeof(typename allocator_type::value_type));
          }
      }

    /**
     * @details
     * This destructor shall destroy a memory pool object; the object
     * becomes, in effect, uninitialised. An implementation may cause
     * the destructor to set the object to an invalid value.
     *
     * It shall be safe to destroy an initialised memory pool object
     * upon which no threads are currently blocked. Attempting to
     * destroy a memory pool object upon which other threads are
     * currently blocked results in undefined behaviour.
     *
     * If the storage for the memory pool was dynamically allocated,
     * it is deallocated using the same allocator.
     *
     * @warning Cannot be invoked from Interrupt Service Routines.
     */
    template<typename Allocator>
      memory_pool_allocated<Allocator>::~memory_pool_allocated ()
      {
#if defined(OS_TRACE_RTOS_MEMPOOL)
        trace::printf ("%s() @%p %s\n", __func__, this, name ());
#endif
        typedef typename std::allocator_traits<allocator_type>::pointer pointer;

        if (allocated_pool_addr_ != nullptr)
          {
            static_cast<allocator_type*> (const_cast<void*> (allocator_))->deallocate (
                static_cast<pointer> (allocated_pool_addr_),
                allocated_pool_size_elements_);

            allocated_pool_addr_ = nullptr;
          }
      }

    // ========================================================================

    /**
     * This constructor shall initialise a memory pool object
     * with attributes referenced by _attr_.
     * If the attributes specified by _attr_ are modified later,
     * the memory pool attributes shall not be affected.
     * Upon successful initialisation, the state of the memory pool
     * variable shall become initialised.
     *
     * Only the memory pool itself may be used for allocations.
     * It is not allowed to make copies of
     * condition variable objects.
     *
     * In cases where default memory pool attributes are
     * appropriate, the variable `memory_pool::initializer` can be used to
     * initialise condition variables.
     * The effect shall be equivalent to creating a memory pool object with
     * the simple constructor.
     *
     * If the attributes define a storage area (via `mp_pool_address` and
     * `mp_pool_size_bytes`), that storage is used, otherwise
     * the storage is dynamically allocated using the RTOS specific allocator
     * (`rtos::memory::allocator`).
     *
     * Implemented as a wrapper over the parent constructor, automatically
     * passing the message size.
     *
     * @warning Cannot be invoked from Interrupt Service Routines.
     */
    template<typename T, typename Allocator>
      inline
      memory_pool_typed<T, Allocator>::memory_pool_typed (
          std::size_t blocks, const memory_pool::attributes& attr,
          const allocator_type& allocator) :
          memory_pool_allocated<allocator_type> (blocks, sizeof(T), attr,
                                                 allocator)
      {
        ;
      }

    /**
     * This constructor shall initialise a named memory pool object
     * with attributes referenced by _attr_.
     * If the attributes specified by _attr_ are modified later,
     * the memory pool attributes shall not be affected.
     * Upon successful initialisation, the state of the memory pool
     * variable shall become initialised.
     *
     * Only the memory pool itself may be used for allocations.
     * It is not allowed to make copies of
     * condition variable objects.
     *
     * In cases where default memory pool attributes are
     * appropriate, the variable `memory_pool::initializer` can be used to
     * initialise condition variables.
     * The effect shall be equivalent to creating a memory pool object with
     * the simple constructor.
     *
     * If the attributes define a storage area (via `mp_pool_address` and
     * `mp_pool_size_bytes`), that storage is used, otherwise
     * the storage is dynamically allocated using the RTOS specific allocator
     * (`rtos::memory::allocator`).
     *
     * Implemented as a wrapper over the parent constructor, automatically
     * passing the message size.
     *
     * @warning Cannot be invoked from Interrupt Service Routines.
     */
    template<typename T, typename Allocator>
      inline
      memory_pool_typed<T, Allocator>::memory_pool_typed (
          const char* name, std::size_t blocks,
          const memory_pool::attributes& attr, const allocator_type& allocator) :
          memory_pool_allocated<allocator_type> (name, blocks, sizeof(T), attr,
                                                 allocator)
      {
        ;
      }

    /**
     * @details
     * This destructor shall destroy a memory pool object; the object
     * becomes, in effect, uninitialised. An implementation may cause
     * the destructor to set the object to an invalid value.
     *
     * It shall be safe to destroy an initialised memory pool object
     * upon which no threads are currently blocked. Attempting to
     * destroy a memory pool object upon which other threads are
     * currently blocked results in undefined behaviour.
     *
     * If the storage for the memory pool was dynamically allocated,
     * it is deallocated using the same allocator.
     *
     * Implemented as a wrapper over the parent destructor.
     *
     * @warning Cannot be invoked from Interrupt Service Routines.
     */
    template<typename T, typename Allocator>
      memory_pool_typed<T, Allocator>::~memory_pool_typed ()
      {
        ;
      }

    /**
     * @details
     * Wrapper over the parent method, automatically
     * passing the cast.
     *
     * @see memory_pool::alloc().
     */
    template<typename T, typename Allocator>
      inline typename memory_pool_typed<T, Allocator>::value_type*
      memory_pool_typed<T, Allocator>::alloc (void)
      {
        return static_cast<value_type*> (memory_pool_allocated<allocator_type>::alloc ());
      }

    /**
     * @details
     * Wrapper over the parent method, automatically
     * passing the cast.
     *
     * @see memory_pool::try_alloc().
     */
    template<typename T, typename Allocator>
      inline typename memory_pool_typed<T, Allocator>::value_type*
      memory_pool_typed<T, Allocator>::try_alloc (void)
      {
        return static_cast<value_type*> (memory_pool_allocated<allocator_type>::try_alloc ());
      }

    /**
     * @details
     * Wrapper over the parent method, automatically
     * passing the cast.
     *
     * @see memory_pool::timed_alloc().
     */
    template<typename T, typename Allocator>
      inline typename memory_pool_typed<T, Allocator>::value_type*
      memory_pool_typed<T, Allocator>::timed_alloc (clock::duration_t timeout)
      {
        return static_cast<value_type*> (memory_pool_allocated<allocator_type>::timed_alloc (
            timeout));
      }

    /**
     * @details
     * Wrapper over the parent method, automatically
     * passing the cast.
     *
     * @see memory_pool::free().
     */
    template<typename T, typename Allocator>
      inline result_t
      memory_pool_typed<T, Allocator>::free (value_type* block)
      {
        return memory_pool_allocated<allocator_type>::free (block);
      }

    // ========================================================================

    /**
     * This constructor shall initialise a memory pool object
     * with attributes referenced by _attr_.
     * If the attributes specified by _attr_ are modified later,
     * the memory pool attributes shall not be affected.
     * Upon successful initialisation, the state of the memory pool
     * variable shall become initialised.
     *
     * Only the memory pool itself may be used for allocations.
     * It is not allowed to make copies of
     * condition variable objects.
     *
     * In cases where default memory pool attributes are
     * appropriate, the variable `memory_pool::initializer` can be used to
     * initialise condition variables.
     * The effect shall be equivalent to creating a memory pool object with
     * the simple constructor.
     *
     * The storage shall be statically allocated inside the
     * memory pool object instance.
     *
     * Implemented as a wrapper over the parent constructor, automatically
     * passing the message size and the storage details.
     *
     * @warning Cannot be invoked from Interrupt Service Routines.
     */
    template<typename T, std::size_t N>
      memory_pool_inclusive<T, N>::memory_pool_inclusive (
          const attributes& attr)
      {
        internal_construct_ (blocks, sizeof(T), attr, &arena_, sizeof(arena_));
      }

    /**
     * This constructor shall initialise a named memory pool object
     * with attributes referenced by _attr_.
     * If the attributes specified by _attr_ are modified later,
     * the memory pool attributes shall not be affected.
     * Upon successful initialisation, the state of the memory pool
     * variable shall become initialised.
     *
     * Only the memory pool itself may be used for allocations.
     * It is not allowed to make copies of
     * condition variable objects.
     *
     * In cases where default memory pool attributes are
     * appropriate, the variable `memory_pool::initializer` can be used to
     * initialise condition variables.
     * The effect shall be equivalent to creating a memory pool object with
     * the simple constructor.
     *
     * The storage shall be statically allocated inside the
     * memory pool object instance.
     *
     * Implemented as a wrapper over the parent constructor, automatically
     * passing the message size and the storage details.
     *
     * @warning Cannot be invoked from Interrupt Service Routines.
     */
    template<typename T, std::size_t N>
      memory_pool_inclusive<T, N>::memory_pool_inclusive (
          const char* name, const attributes& attr) :
          memory_pool
            { name }
      {
        internal_construct_ (blocks, sizeof(T), attr, &arena_, sizeof(arena_));
      }

    /**
     * @details
     * This destructor shall destroy the memory pool object; the object
     * becomes, in effect, uninitialised. An implementation may cause
     * the destructor to set the object to an invalid value.
     *
     * It shall be safe to destroy an initialised memory pool object
     * upon which no threads are currently blocked. Attempting to
     * destroy a memory pool object upon which other threads are
     * currently blocked results in undefined behaviour.
     *
     * @warning Cannot be invoked from Interrupt Service Routines.
     */
    template<typename T, std::size_t N>
      memory_pool_inclusive<T, N>::~memory_pool_inclusive ()
      {
        ;
      }

    /**
     * @details
     * Wrapper over the parent method, automatically
     * passing the cast.
     *
     * @see memory_pool::alloc().
     */
    template<typename T, std::size_t N>
      inline typename memory_pool_inclusive<T, N>::value_type*
      memory_pool_inclusive<T, N>::alloc (void)
      {
        return static_cast<value_type*> (memory_pool::alloc ());
      }

    /**
     * @details
     * Wrapper over the parent method, automatically
     * passing the cast.
     *
     * @see memory_pool::try_alloc().
     */
    template<typename T, std::size_t N>
      inline typename memory_pool_inclusive<T, N>::value_type*
      memory_pool_inclusive<T, N>::try_alloc (void)
      {
        return static_cast<value_type*> (memory_pool::try_alloc ());
      }

    /**
     * @details
     * Wrapper over the parent method, automatically
     * passing the cast.
     *
     * @see memory_pool::timed_alloc().
     */
    template<typename T, std::size_t N>
      inline typename memory_pool_inclusive<T, N>::value_type*
      memory_pool_inclusive<T, N>::timed_alloc (clock::duration_t timeout)
      {
        return static_cast<value_type*> (memory_pool::timed_alloc (timeout));
      }

    /**
     * @details
     * Wrapper over the parent method, automatically
     * passing the cast.
     *
     * @see memory_pool::free().
     */
    template<typename T, std::size_t N>
      inline result_t
      memory_pool_inclusive<T, N>::free (value_type* block)
      {
        return memory_pool::free (block);
      }

  } /* namespace rtos */
} /* namespace os */

// ----------------------------------------------------------------------------

#endif /* __cplusplus */

#endif /* CMSIS_PLUS_RTOS_OS_MEMPOOL_H_ */


text:
package utilities;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;

import db.BidDAOImpl;
import db.ItemDAOImpl;
import db.UserDAOImpl;
import entities.Bid;
import entities.Item;
import entities.User;

public class Recommentation {

	Map<Long,Integer> indexOfUser;
	Map<Long,Integer> indexOfItem;
	private int PlhthosUsers;
	private int PlhthosItems;
	public List<List<Long>> UsersRecommendedItems;

	public Recommentation()
	{
		indexOfUser = new HashMap<Long,Integer>();
		indexOfItem = new HashMap<Long,Integer>();
	}

	//taksinomish similarities
	static <K,V extends Comparable<? super V>>
	SortedSet<Map.Entry<K,V>> entriesSortedByValue(Map<K,V> map) {
		SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(new Comparator<Map.Entry<K,V>>() {
            @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                int res = ((Double) e1.getValue()).compareTo((Double) e2.getValue());
                return res != 0 ? res : 1;
            }
        }
		);
		sortedEntries.addAll(map.entrySet());
		return sortedEntries;
	}

	public static Object getKeyFromValue(Map hm, Object value) {
    	for (Object o : hm.keySet()) {
     		if (hm.get(o).equals(value)) {
        		return o;
      		}
    	}
    	return null;
  	}

	//GENERATE USER VECTORS
	//vhma 1: Fere Ola ta bids apo thn vash
	//vhma 2: Ftiakse gia kathe user ena dianysma me stoixeia to zeugos (item_id,amount)
	//vhma 3: Taksinomhse ayta ta dianysmata ws pros to item_id
	//vhma 4: (Proeraitiko) Omalopoihse ta amount diairontas olo to dianysma me to Max_Amount
	public double[][] GenerateUsersVectors()
	{
		Integer user_count,item_count;

		//fere mou to plhthos twn items
		BidDAOImpl bidd = new BidDAOImpl();
		List<Bid> bids = bidd.findAll();
		item_count = 0;
		user_count = 0;

		System.out.println("arxikopoiw ta maps");
		// vres to plh8os twn diaforetikwn bidder kai item
		for(Bid bid:bids){

			if(indexOfItem.get(bid.getItem().getItemId()) == null)
			{
				indexOfItem.put(bid.getItem().getItemId(),item_count);
				item_count++;
			}

			if(indexOfUser.get(bid.getUser().getUserId()) == null)
			{
				indexOfUser.put(bid.getUser().getUserId(),user_count);
				user_count++;
			}

		}
		System.out.println("TELOS arxikopoihshs ta maps");

		PlhthosItems = item_count;
		PlhthosUsers = user_count;

		//ftiakse to dianysma me ta amount tou kathe user
		double[][] UsersVectors = new double[PlhthosUsers][PlhthosItems];
		int i,j;
		for(i=0; i<PlhthosUsers; i++)
			for(j=0; j<PlhthosItems; j++)
				UsersVectors[i][j] = 0.0;

		Integer user_position = null, item_position = null;

		System.out.println("Ftiaxnw to pinaka usevectors");
		for(Bid bid: bids)
		{
			//			if( indexOfUser.containsKey(bid.getUser().getUserId()) )
			user_position = indexOfUser.get(bid.getUser().getUserId());
			//			if(indexOfItem.containsKey(bid.getItem().getItemId()))
			item_position = indexOfItem.get(bid.getItem().getItemId());

			String ammount = bid.getAmount();
			ammount = ammount.replace(",", "");
			ammount = ammount.replace("$", "");

			UsersVectors[user_position][item_position] = Double.parseDouble(ammount);
		}

		System.out.println("TELOS Ftiaxnw to pinaka usevectors");

		return UsersVectors;
	}

	//KNN
	//vhma 5:Vres ta similarity tou kathe user me olous tous user(cosine_similarity)
	//vhma 6:Ftiakse gia kathe user mia lista me stoixeia to zeugos (user_id(neighbor),similarity)
	//vhma 7:Omalopoihse ayta ta similarity sto (0,1)
	//vhma 8:Taksinomiseta ws pros to similarity
	//vhma 9:Krata ta K megalytera kai epestrepse mia lista me ta neighbors_id tou kathe user
	public List<ArrayList<Integer>> KNN(double[][] usersVectors , int K)
	{
		Integer user,neighbor,item;
		db.RecommendedItemDAOImpl recd = new db.RecommendedItemDAOImpl();
		List<ArrayList<Integer>> UsersNeighbors = new ArrayList<ArrayList<Integer>>() ;

		System.out.println(" users = " + PlhthosUsers + " Items = " + PlhthosItems);

		for(user=0; user<PlhthosUsers; user++)
		{

			if(user%100 == 0 )
			{
				System.out.println(((double)user/(double)PlhthosUsers)*100 + "%");
				System.out.println("user = " + user);
			}

			HashMap<Integer,Double> similarities = new HashMap<Integer,Double>();

			for(neighbor=0; neighbor<PlhthosUsers; neighbor++)
			{
				double sum1 = 0;
				double sum2 = 0;
				double sum3 = 0;
				Double similarity = 0.0;

				if(neighbor != user)
				{
					for(item=0; item<PlhthosItems; item++)
					{
						sum1 += usersVectors[user][item] * usersVectors[neighbor][item];
						sum2 += usersVectors[user][item] * usersVectors[user][item];
						sum3 += usersVectors[neighbor][item] * usersVectors[neighbor][item];
					}

					if (sum1 == 0 && (sum2 == 0 || sum3 == 0))
						similarity = -1.0;
					else
						similarity = sum1 / (Math.sqrt(sum2) * Math.sqrt(sum3));

					similarity = (similarity+1)/2;
					//					System.out.println("similarity = " + similarity + " sum1 = " +sum1 + " sum2 = " + sum2 + " sum3 = " + sum3);

					similarities.put(neighbor, similarity);
				}
			}

			TreeMap<Integer, Double> sim = sortMapByValue2(similarities);

			// map apo itemId -> frequency of item
			HashMap<Long,Integer> itemFrequencyMap = new HashMap<Long,Integer>();

			int j = 0;

			// vres to key pou exei authn thn apostash
			for( Map.Entry<Integer, Double> entry : sim.entrySet())
			{
				if( j == K ) break;
				Integer itemPos;
				Integer neighbourId = entry.getKey();

				// gia ka8e item
				for(Long item_id: indexOfItem.keySet() )
				{
					itemPos = indexOfItem.get(item_id);
					/* ypologise ta frequency twn item apo tous geitones
					 */
					if(usersVectors[user][itemPos] == 0.0 && usersVectors[neighbourId][itemPos] > 0.0)
					{
						if( itemFrequencyMap.get(item_id) == null)
							itemFrequencyMap.put(item_id, 1);
						else
							itemFrequencyMap.put(item_id,new Integer(itemFrequencyMap.get(item_id)+1));

					}
				}
				j++;
			}

			TreeMap<Long, Integer> sortedMap = sortMapByValue(itemFrequencyMap);

			System.out.println("sorted map = " + sortedMap);

			// vale ta top 5 item sth vash
//			int i = 0;
//			for (Map.Entry<Long, Integer> entry : sortedMap.entrySet()) {
//
//				if( i == 5 )
//					break;
//
//				Long user_id = (Long) getKeyFromValue(indexOfUser,user);
//
//				//vale sthn vash
//				//to item_id kai to user_id
//				entities.RecommendedItem rec = new entities.RecommendedItem();
//				rec.setUserId(user_id);
//				rec.setItemId(entry.getKey());
//				recd.insert(rec);
//
//				i++;
//
//			}
		}

		return  UsersNeighbors;
	}

	public static TreeMap<Long, Integer> sortMapByValue(HashMap<Long, Integer> map){
		Comparator<Long> comparator = new ValueComparator(map);
		//TreeMap is a map sorted by its keys.
		//The comparator is used to sort the TreeMap by keys.
		TreeMap<Long, Integer> result = new TreeMap<Long, Integer>(comparator);
		result.putAll(map);
		return result;
	}

	public static TreeMap<Integer, Double> sortMapByValue2(HashMap<Integer, Double> map){
		Comparator<Integer> comparator = new ValueComparator2(map);
		//TreeMap is a map sorted by its keys.
		//The comparator is used to sort the TreeMap by keys.
		TreeMap<Integer, Double> result = new TreeMap<Integer, Double>(comparator);
		result.putAll(map);
		return result;
	}

	//FIND RECOMMENDED ITEMS

	//vhma 10: Xrhsimopoihse thn lista pou ftiaksame sto vhma 2 pou afora mono tous geitones tou kathe user
	//vhma 11: Vale ola ta item_id se mia lista gia ta opoia isxyei h synthikh (userAmount == 0 && neighborAmount > 0)
	//vhma 12: Vale sthn vash, sto table Recommentation ta (user_id,item_id)
	public void FindRecommendedItems(List<ArrayList<Integer>> neighbors,double[][] usersVectors){

		db.RecommendedItemDAOImpl recd = new db.RecommendedItemDAOImpl();

//		UsersRecommendedItems = null;
		Integer user = 0;
		for(List<Integer> userIndex:neighbors)
		{
			List<Long> UserRecommendedItems = new ArrayList<Long>();
			for(Integer neighbor:userIndex)
			{
				Integer item = 0;
				for(Long item_id: indexOfItem.keySet())
				{
					if(usersVectors[user][item] == 0.0 && usersVectors[neighbor][item] > 0.0)
					{
						UserRecommendedItems.add(item_id);
						Long user_id = (Long) getKeyFromValue(indexOfUser,user);

						//vale sthn vash
						//to item_id kai to user_id
						entities.RecommendedItem rec = new entities.RecommendedItem();
						rec.setUserId(user_id);
						rec.setItemId(item_id);
						recd.insert(rec);

					}
					item++;
				}

			}
			UsersRecommendedItems.add(UserRecommendedItems);
			user++;
		}

		return ;
	}

//	public List<Long> getRecommendedItems(String username)
//	{
//		GenerateUsersVectors(); //Make Users Vectors with Amounts
//
//		int K = 5;
//		List<List<Integer>> neighbors = KNN(UsersVectors,K); //find neighbors with KNN ( K=5 )
//
//		FindRecommendedItems(neighbors); //Find Users Recommended items
//
//		UserDAOImpl userd = new UserDAOImpl();
//		entities.User user = userd.getByUserName(username);
//
//		Integer indexUser = indexOfUser.get(user.getUserId());
//		List<Long> RecommendedItems = UsersRecommendedItems.get(indexUser);
//		return RecommendedItems;
//
//	}
}