text:
"use strict";
const { Command, SerializedArgumentParser, ParsingError } = require("sosamba");
const { prototype: { permissionCheck: isOwner } } = require("../lib/commandTypes/OwnerCommand");
const config = require("../config");
const PhoneMessageListener = require("../lib/speakerPhone.v4");
const RegisterSymbol = Symbol("tt.bot.phone.register");
const CallSymbol = Symbol("tt.bot.phone.call");
const LookupSymbol = Symbol("tt.bot.phone.lookup");
const DeleteSymbol = Symbol("tt.bot.phone.delete");
const { version: sosambaVersion } = require("sosamba/package.json");

const convertNumber = input => input
    .replace(/(a|b|c)/ig, "2")
    .replace(/(d|e|f)/ig, "3")
    .replace(/(g|h|i)/ig, "4")
    .replace(/(j|k|l)/ig, "5")
    .replace(/(m|n|o)/ig, "6")
    .replace(/(p|q|r|s)/ig, "7")
    .replace(/(t|u|v)/ig, "8")
    .replace(/(w|x|y|z)/ig, "9")
    .replace(/(-|\(|\))/g, "")
    .replace(/\s+/g, "");
const checkValidNumber = n => !isNaN(n) &&
    n.length === 14 && // TTBOT and the 9-digit number
    /^88268/.test(n);

class PhoneCommand extends Command {
    constructor(sosamba, ...args) {
        super(sosamba, ...args, {
            name: "phone",
            argParser: new SerializedArgumentParser(sosamba, {
                allowQuotedString: true,
                args: [{
                    name: "action",
                    type: (val, ctx) => {
                        if (val === "register" && sosamba.isAdmin(ctx.member)) return RegisterSymbol;
                        if (val === "call") return CallSymbol;
                        if (val === "lookup") {
                            ctx.action = LookupSymbol;
                            return LookupSymbol;
                        }
                        if (val === "delete" && sosamba.isAdmin(ctx.member)) return DeleteSymbol;
                        throw new ParsingError("Invalid action");
                    },
                    description: "the action to do",
                }, {
                    name: "number",
                    type: async (val, ctx) => {
                        const num = convertNumber(val);
                        if (!checkValidNumber(num)) {
                            if (ctx.action === LookupSymbol) return undefined;
                            throw new ParsingError(await ctx.t("NUMBER_INVALID", true));
                        }
                        return num;
                    },
                    default: SerializedArgumentParser.None,
                    rest: true
                }]
            }),
            description: "Talk with people across Discord."
        });

        this.speakerPhone = sosamba.messageListeners.add(new PhoneMessageListener(sosamba));
    }

    async checkHasNumber(ctx, number) {
        if (!number) {
            await ctx.send({
                embed: {
                    title: ":x: Argument required",
                    description: "The argument `number` is required.",
                    color: 0xFF0000,
                    footer: {
                        text: `Sosamba v${sosambaVersion}`
                    }
                }
            });
            return;
        }
        return true;
    }

    async run(ctx, [action, number]) {
        if (action === RegisterSymbol) {
            if (!await this.checkHasNumber(ctx, number)) return;
            const phones = await ctx.db.getGuildPhoneNumbers(ctx.guild.id);
            if (phones.length > 0 && !isOwner({
                author: {
                    id: ctx.guild.ownerID
                }
            })) {
                await ctx.send(await ctx.t("ALREADY_HAVE_NUMBER"));
                return;
            }

            if (number.startsWith("882680") && !isOwner({
                author: {
                    id: ctx.guild.ownerID
                }
            })) {
                await ctx.send(await ctx.t("NUMBER_RESERVED"));
                return;
            }

            if (await ctx.db.getPhoneNumber(number)) {
                await ctx.send(await ctx.t("NUMBER_EXISTS"));
                return;
            }

            await ctx.send(await ctx.t("QUESTION_NUMBER_PRIVATE"));
            const isPrivate = await ctx.askYesNo();
            await ctx.db.createPhoneNumber({
                id: number,
                private: isPrivate,
                channelID: ctx.channel.id,
                guildID: ctx.guild.id
            });
            await ctx.send(await ctx.t("NUMBER_CREATED"));
        } else if (action === CallSymbol) {
            if (!await this.checkHasNumber(ctx, number)) return;
            const [thisChannelNumber] = await ctx.db.getChannelPhoneNumbers(ctx.guild.id, ctx.channel.id);
            if (!thisChannelNumber) {
                await ctx.send(await ctx.t("CALLER_NO_NUMBER"));
                return;
            }
            const otherSideNumber = await ctx.db.getPhoneNumber(number);
            if (!otherSideNumber) {
                await ctx.send(await ctx.t("NUMBER_NONEXISTANT"));
                return;
            }

            await ctx.send(await ctx.t("CALLING"));

            try {
                await this.sosamba.createMessage(otherSideNumber.channelID, {
                    content: `Incoming call by ${thisChannelNumber.id} ${!thisChannelNumber.private ? `(#${ctx.channel.name} at ${ctx.guild.name})` : ""}\nType \`${config.prefix}pickup\` to pick up the call. Else, type \`${config.prefix}hangup\`. You have 2 minutes to pick up the call, else the call will be automatically hung up.`,
                    allowedMentions: {}
                });
                try {
                    const answer = await ctx.waitForAnyMessage(otherSideNumber.channelID,
                        ctx => ctx.msg.content === `${config.prefix}pickup`
                            || ctx.msg.content === `${config.prefix}hangup`,
                        2 * 60e3);

                    if (answer.msg.content === `${config.prefix}pickup`) {
                        this.speakerPhone.addChannels(ctx.channel, this.sosamba.getChannel(otherSideNumber.channelID), thisChannelNumber, otherSideNumber);
                    } else {
                        for (const cID of [otherSideNumber.channelID, ctx.channel.id]) {
                            await this.sosamba.createMessage(cID, "The call was hung up.");
                        }
                    }
                } catch (err) {
                    console.error(err);
                    for (const cID of [otherSideNumber.channelID, ctx.channel.id]) {
                        await this.sosamba.createMessage(cID, "The call timed out.");
                    }
                }
            } catch {
                if (!this.sosamba.guilds.has(otherSideNumber.guildID)) {
                    await ctx.send(await ctx.t("CALL_ABORTED_BOT_REMOVED"));
                    const phoneNumbers = await ctx.db.getGuildPhoneNumbers(otherSideNumber.guildID);
                    await Promise.all(phoneNumbers.map(async ({ id }) => ctx.db.deletePhoneNumber(id)));
                    return;
                } else {
                    await ctx.send(await ctx.t("CALL_ABORTED_NO_PERMISSIONS"));
                    return;
                }

            }
        } else if (action === LookupSymbol) {
            let data;
            if (number) data = await ctx.db.getPhoneNumber(number);
            else [data] = await ctx.db.getChannelPhoneNumbers(ctx.guild.id, ctx.channel.id);

            if (!data) {
                await ctx.send(await ctx.t("NUMBER_NONEXISTANT"));
                return;
            }

            const fields = [{
                name: await ctx.t("PRIVATE_NUMBER"),
                value: data.private ? await ctx.t("YES")
                    : await ctx.t("NO"),
                inline: true
            }];

            const isOnServer = this.sosamba.guilds.has(data.guildID);
            if (!isOnServer) {
                const phoneNumbersInDelGuild = await ctx.db.getGuildPhoneNumbers(data.guildID);
                await Promise.all(phoneNumbersInDelGuild.map(async ({ id }) => ctx.db.deletePhoneNumber(id)));
                this.log.info(`Deleted the phone numbers from ${data.guildID}: ${phoneNumbersInDelGuild.map(d => d.id).join(", ")}`);
            }

            const c = this.sosamba.getChannel(data.channelID);
            if (!data.private || !isOnServer) fields.push({
                name: await ctx.t("CHANNEL_INFORMATION"),
                value: isOnServer ? await ctx.t("CHANNEL_INFORMATION_VALUE", c, {
                    name: this.sosamba.escapeMarkdown(c.guild.name)
                }) : await ctx.t("NUMBER_AVAILABLE"),
                inline: true
            });

            await ctx.send({
                embed: {
                    author: {
                        name: await ctx.t("NUMBER_INFORMATION", data.id)
                    },
                    fields,
                    color: 0x008800
                }
            });
        } else if (action === DeleteSymbol) {
            if (!await this.checkHasNumber(ctx, number)) return;
            const phone = ctx.db.getPhoneNumber(number);
            if (!phone || !isOwner(ctx)
                && (phone && phone.guildID !== ctx.guild.id)
            ) {
                await ctx.send(await ctx.t("NUMBER_NONEXISTANT"));
                return;
            }
            await ctx.send(await ctx.t("QUESTION_DELETE_NUM", number));

            if (await ctx.askYesNo()) {
                await ctx.db.deletePhoneNumber(number);
                await ctx.send(await ctx.t("NUMBER_DELETED"));
            } else {
                await ctx.send(await ctx.t("OP_CANCELLED"));
            }
        }
    }
}

module.exports = PhoneCommand;


text:
#include <conio.h>
#include <time.h>
#include "stdbrick.hpp"
#include "ieee80211facade.hpp"
#include "depuncturer.hpp"
#include "PHY_11a.hpp"
#include "PHY_11b.hpp"
#include "viterbi.hpp"
#include "pilot.hpp"
#include "channel_11a.hpp"
#include "cca.hpp"
#include "freqoffset.hpp"
#include "fft.hpp"
#include "scramble.hpp"
#include "deinterleaver.hpp"
#include "samples.hpp"
#include "sampling.hpp"
#include "monitor.h"
#include "appext.h"
#include "thread_func.h"

#define OUT_BUF_SIZE (16*1024*1024)
static UCHAR                    OutputBuf[OUT_BUF_SIZE];
static SORA_RADIO_RX_STREAM		RxStream;
static PVOID				    RxBuffer = NULL;
static ULONG				    RxBufferSize = 0;

HANDLE thread1 = NULL, thread2 = NULL; // thread2 for viterbi; thread1 for others
ISource * ssrc, * svit;
IControlPoint * scs;

typedef struct _tagBB11aDemodContext :
	  LOCAL_CONTEXT(TDropAny)
  	, LOCAL_CONTEXT(TBB11aFrameSink)
  	, LOCAL_CONTEXT(T11aViterbi)
	, LOCAL_CONTEXT(T11aPLCPParser)
	, LOCAL_CONTEXT(T11aDemap)
	, LOCAL_CONTEXT(TPilotTrack)
	, LOCAL_CONTEXT(TChannelEqualization)
	, LOCAL_CONTEXT(T11aLTSymbol)
	, LOCAL_CONTEXT(TChannelEst)
	, LOCAL_CONTEXT(TCCA11a)
	, LOCAL_CONTEXT(TPhaseCompensate)
	, LOCAL_CONTEXT(TFFT64)
	, LOCAL_CONTEXT(TFreqCompensation)
	, LOCAL_CONTEXT(TDCRemoveEx)
    , LOCAL_CONTEXT(TRxStream)
    , LOCAL_CONTEXT(TBB11aRxRateSel)
{
    // Statistic monitor for frames
    Monitor monitor;

    FINL void MoveState_RX_CS(bool finished, bool good)
    {
        QueryMacStopwatch();
        if (finished)
        {
            if (good)
            {
                monitor.IncGoodCounter();
                monitor.IncThroughput(CF_11aRxVector::frame_length() - 4); // Accumulate viterbi thread output length, excluding CRC32
            }
            else
            {
                monitor.IncBadCounter();
            }
        }
    }

    FINL void QueryMacStopwatch()
    {
        monitor.Query(false); // false means receiving
    }

    FINL void OnPowerDetected()
    {
        QueryMacStopwatch();
    }

    void Reset () {
		// Reset all CFacade data in the context
        ResetCarrierSense();

		// CF_11aSymSel
		CF_11aSymState::Reset();

		// CF_CFOffset
		CF_CFOffset::Reset ();

		// CF_Channel_11a
		CF_Channel_11a::Reset ();

		// CF_FreqOffsetComp
		CF_FreqCompensate::Reset ();

		// CF_PhaseCompensation
		CF_PhaseCompensate::Reset ();

		// CF_PilotTrack
		CF_PilotTrack::Reset ();

		// CF_11RxPLCPSwitch
		CF_11RxPLCPSwitch::Reset();

        // CF_11aRxVector
        CF_11aRxVector::Reset();
	}

    void ResetCarrierSense () {
		// CF_Error
		CF_Error::error_code() = E_ERROR_SUCCESS;

		// CF_11CCA
		CF_11CCA::Reset();
	}

	void Init (PSORA_RADIO_RX_STREAM pRxStream, UCHAR* output, uint out_size )
	{
		// CF_11CCA
		CF_11CCA::cca_pwr_threshold() = 1000*1000; // set energy threshold

		// CF_RxStream
		CF_RxStream::rxstream_pointer() = pRxStream;
		CF_RxStream::rxstream_touched() = 0;

		// CF_VecDC
		CF_VecDC::Reset ();

		// CF_RxFrameBuffer
		CF_RxFrameBuffer::Init (output, out_size);

		Reset ();
	}
}BB11aDemodContext;

// Contruct bricks
BB11aDemodContext BB11aDemodCtx;

struct sym_selector {
	FINL
	int operator()(BB11aDemodContext& ctx) {
		if ( ctx.CF_11aSymState::symbol_type()  == CF_11aSymState::SYMBOL_TRAINING ) {
			return PORT_0;
		} else {
		 	return PORT_1;
		}
	}
};

typedef TGDemux<2, COMPLEX16, 4, sym_selector> T11aSymSelEx;

//
// Define the selector object for the plcp switch
//
struct plcp_selector {
	FINL
	int operator()(BB11aDemodContext& ctx) {
		if ( ctx.CF_11RxPLCPSwitch::plcp_state()  == CF_11RxPLCPSwitch::plcp_header ) {
			return PORT_0;
		} else {
		 	return PORT_1;
        }
	}
};

/*************************************************************************
Processing graph

src-> downsample -> rxswt -> dc_removedc -> BB11aCCA -> estimate_dc
                     |-> symsel -> LTSSymbol -> ch_est -> fine_cfo -> drop
                               |-> dataSym -> FFT -> Equalization -> phase_comp ..->
  ..-> pilot -> plcpswt -> plcp_demap -> plcp_deinter -> plcp_viterbi -> plcp_parser
                      | -> 6M_demap -> 6M_deinter -> thread_sep -> viterbi -> desc -> frame_sink

*************************************************************************/

// Note: use "static inline" instead of "inline" to prevent silent function confliction during linking.
// Otherwise, it will introduce wrong linking result because these inline function share the same name,
// and indeed not inlined.
// ref: http://stackoverflow.com/questions/2217628/multiple-definition-of-inline-functions-when-linking-static-libs
static inline
void CreateDemodGraph11a_40M (ISource*& srcAll, ISource*& srcViterbi, IControlPoint*& cpCarrierSense)
{
    CREATE_BRICK_SINK  (drop, TDropAny,    BB11aDemodCtx );

    CREATE_BRICK_SINK   (fsink, TBB11aFrameSink, BB11aDemodCtx );
	CREATE_BRICK_FILTER (desc,   T11aDesc,	BB11aDemodCtx, fsink );

	typedef T11aViterbi <5000*8, 48, 256> T11aViterbiComm;
	CREATE_BRICK_FILTER (viterbi, T11aViterbiComm::Filter,	BB11aDemodCtx, desc );

    CREATE_BRICK_FILTER (vit0, TThreadSeparator<>::Filter, BB11aDemodCtx, viterbi);

	// 6M
	CREATE_BRICK_FILTER (di6, 	T11aDeinterleaveBPSK, BB11aDemodCtx, vit0 );
    CREATE_BRICK_FILTER (dm6, 	T11aDemapBPSK::Filter,      BB11aDemodCtx, di6 );

	// 12M
	CREATE_BRICK_FILTER (di12, 	T11aDeinterleaveQPSK, BB11aDemodCtx, vit0 );
    CREATE_BRICK_FILTER (dm12, 	T11aDemapQPSK::Filter,      BB11aDemodCtx, di12 );

	// 24M
	CREATE_BRICK_FILTER (di24, 	T11aDeinterleaveQAM16, BB11aDemodCtx, vit0 );
    CREATE_BRICK_FILTER (dm24, 	T11aDemapQAM16::Filter,      BB11aDemodCtx, di24 );

	// 48M
	CREATE_BRICK_FILTER (di48, 	T11aDeinterleaveQAM64, BB11aDemodCtx, vit0 );
    CREATE_BRICK_FILTER (dm48, 	T11aDemapQAM64::Filter,      BB11aDemodCtx, di48 );

	// PLCP
    CREATE_BRICK_SINK   (plcp,      T11aPLCPParser, BB11aDemodCtx );
	CREATE_BRICK_FILTER (sviterbik, T11aViterbiSig, BB11aDemodCtx, plcp );
	CREATE_BRICK_FILTER (dibpsk, 	T11aDeinterleaveBPSK, BB11aDemodCtx, sviterbik );
    CREATE_BRICK_FILTER (dmplcp, 	T11aDemapBPSK::Filter, BB11aDemodCtx, dibpsk );

    CREATE_BRICK_DEMUX5 ( sigsel,	TBB11aRxRateSel,    BB11aDemodCtx,
                        dmplcp, dm6, dm12, dm24, dm48 );

	CREATE_BRICK_FILTER (pilot,  TPilotTrack, BB11aDemodCtx, sigsel );
	CREATE_BRICK_FILTER (pcomp,  TPhaseCompensate, BB11aDemodCtx, pilot );
	CREATE_BRICK_FILTER (chequ,  TChannelEqualization, BB11aDemodCtx, pcomp );
	CREATE_BRICK_FILTER (fft,    TFFT64, BB11aDemodCtx, chequ );
	CREATE_BRICK_FILTER (fcomp,	 TFreqCompensation, BB11aDemodCtx, fft );
	CREATE_BRICK_FILTER (dsym,   T11aDataSymbol, BB11aDemodCtx, fcomp );
	CREATE_BRICK_FILTER (dsym0,  TNoInline,      BB11aDemodCtx, dsym );

	// LTS path
//	CREATE_BRICK_FILTER (fcfo,  TFineCFOEst, BB11aDemodCtx, drop );
//	CREATE_BRICK_FILTER (chest, TChannelEst, BB11aDemodCtx, fcfo );
//	CREATE_BRICK_FILTER (lsym,  T11aLTSymbol, BB11aDemodCtx, chest );

	CREATE_BRICK_SINK (lsym,	T11aLTS, BB11aDemodCtx );

	CREATE_BRICK_DEMUX2 (symsel, T11aSymSelEx::Filter, BB11aDemodCtx,
			lsym, dsym0 );

	CREATE_BRICK_FILTER (dcest, TDCEstimator, BB11aDemodCtx, drop );
	CREATE_BRICK_FILTER (cca,   TCCA11a,      BB11aDemodCtx, dcest );
	CREATE_BRICK_FILTER (dc,    TDCRemoveEx<4>::Filter, BB11aDemodCtx, cca );
    cpCarrierSense = cca;

	CREATE_BRICK_DEMUX2 ( rxswt, TBB11bRxSwitch, BB11aDemodCtx,
			dc, symsel);

	CREATE_BRICK_FILTER (ds2, TDownSample2, BB11aDemodCtx, rxswt );
    CREATE_BRICK_SOURCE (ssrc, TRxStream, BB11aDemodCtx, ds2);

    srcAll = ssrc;
	srcViterbi = vit0;
}

static inline
void CreateDemodGraph11a_44M (ISource*& srcAll, ISource*& srcViterbi, IControlPoint*& cpCarrierSense)
{
    CREATE_BRICK_SINK  (drop, TDropAny,    BB11aDemodCtx );

    CREATE_BRICK_SINK   (fsink, TBB11aFrameSink, BB11aDemodCtx );
	CREATE_BRICK_FILTER (desc,   T11aDesc,	BB11aDemodCtx, fsink );

	typedef T11aViterbi <5000*8, 48, 256> T11aViterbiComm;
	CREATE_BRICK_FILTER (viterbi, T11aViterbiComm::Filter,	BB11aDemodCtx, desc );

    CREATE_BRICK_FILTER (vit0, TThreadSeparator<>::Filter, BB11aDemodCtx, viterbi);

	// 6M
	CREATE_BRICK_FILTER (di6, 	T11aDeinterleaveBPSK, BB11aDemodCtx, vit0 );
    CREATE_BRICK_FILTER (dm6, 	T11aDemapBPSK::Filter,      BB11aDemodCtx, di6 );

	// 12M
	CREATE_BRICK_FILTER (di12, 	T11aDeinterleaveQPSK, BB11aDemodCtx, vit0 );
    CREATE_BRICK_FILTER (dm12, 	T11aDemapQPSK::Filter,      BB11aDemodCtx, di12 );

	// 24M
	CREATE_BRICK_FILTER (di24, 	T11aDeinterleaveQAM16, BB11aDemodCtx, vit0 );
    CREATE_BRICK_FILTER (dm24, 	T11aDemapQAM16::Filter,      BB11aDemodCtx, di24 );

	// 48M
	CREATE_BRICK_FILTER (di48, 	T11aDeinterleaveQAM64, BB11aDemodCtx, vit0 );
    CREATE_BRICK_FILTER (dm48, 	T11aDemapQAM64::Filter,      BB11aDemodCtx, di48 );

	// PLCP
    CREATE_BRICK_SINK   (plcp,      T11aPLCPParser, BB11aDemodCtx );
	CREATE_BRICK_FILTER (sviterbik, T11aViterbiSig, BB11aDemodCtx, plcp );
	CREATE_BRICK_FILTER (dibpsk, 	T11aDeinterleaveBPSK, BB11aDemodCtx, sviterbik );
    CREATE_BRICK_FILTER (dmplcp, 	T11aDemapBPSK::Filter, BB11aDemodCtx, dibpsk );

    CREATE_BRICK_DEMUX5 ( sigsel,	TBB11aRxRateSel,    BB11aDemodCtx,
                        dmplcp, dm6, dm12, dm24, dm48 );

	CREATE_BRICK_FILTER (pilot,  TPilotTrack, BB11aDemodCtx, sigsel );
	CREATE_BRICK_FILTER (pcomp,  TPhaseCompensate, BB11aDemodCtx, pilot );
	CREATE_BRICK_FILTER (chequ,  TChannelEqualization, BB11aDemodCtx, pcomp );
	CREATE_BRICK_FILTER (fft,    TFFT64, BB11aDemodCtx, chequ );
	CREATE_BRICK_FILTER (fcomp,	 TFreqCompensation, BB11aDemodCtx, fft );
	CREATE_BRICK_FILTER (dsym,   T11aDataSymbol, BB11aDemodCtx, fcomp );
	CREATE_BRICK_FILTER (dsym0,  TNoInline,      BB11aDemodCtx, dsym );

	// LTS path
//	CREATE_BRICK_FILTER (fcfo,  TFineCFOEst, BB11aDemodCtx, drop );
//	CREATE_BRICK_FILTER (chest, TChannelEst, BB11aDemodCtx, fcfo );
//	CREATE_BRICK_FILTER (lsym,  T11aLTSymbol, BB11aDemodCtx, chest );

	CREATE_BRICK_SINK (lsym,	T11aLTS, BB11aDemodCtx );

	CREATE_BRICK_DEMUX2 (symsel, T11aSymSelEx::Filter, BB11aDemodCtx,
			lsym, dsym0 );

	CREATE_BRICK_FILTER (dcest, TDCEstimator, BB11aDemodCtx, drop );
	CREATE_BRICK_FILTER (cca,   TCCA11a,      BB11aDemodCtx, dcest );
	CREATE_BRICK_FILTER (dc,    TDCRemoveEx<4>::Filter, BB11aDemodCtx, cca );
    cpCarrierSense = cca;

	CREATE_BRICK_DEMUX2 ( rxswt, TBB11bRxSwitch, BB11aDemodCtx,
			dc, symsel);

	CREATE_BRICK_FILTER (ds2, TDownSample2, BB11aDemodCtx, rxswt );
    CREATE_BRICK_FILTER (ds44, TDownSample44_40, BB11aDemodCtx, ds2);
    CREATE_BRICK_SOURCE (ssrc, TRxStream, BB11aDemodCtx, ds44);

    srcAll = ssrc;
	srcViterbi = vit0;
}

BOOLEAN RxThread ( void * ) {
    //ssrc->Seek(ISource::END_POS);
    while (1) {
        BB11aDemodCtx.QueryMacStopwatch();

	    ssrc->Process ();
	    ulong& err = BB11aDemodCtx.CF_Error::error_code();

	    if ( err != E_ERROR_SUCCESS ) {
			// Any event happened
		    if ( err == E_ERROR_FRAME_OK ) {
			    // One frame is received
                BB11aDemodCtx.MoveState_RX_CS(true, true);
            } else if ( err == E_ERROR_CRC32_FAIL) {
                BB11aDemodCtx.MoveState_RX_CS(true, false);
		    } else if ( err == E_ERROR_CS_TIMEOUT ) {
                // Channel clean
                BB11aDemodCtx.ResetCarrierSense();
		        scs->Reset ();
                break;
		    } else {
                BB11aDemodCtx.MoveState_RX_CS(false, false);
                //printf("err = %08X\n", err);
		    }

            // Flush the brick graph, make related brick threads safe to reset
            ssrc->Flush();

		    BB11aDemodCtx.Reset ();
		    ssrc->Reset ();

            if ( err == E_ERROR_FRAME_OK || err == E_ERROR_CRC32_FAIL)
            {
                ssrc->Seek(ISource::END_POS);
            }
			break;
        }
    }
    return TRUE;
}

BOOLEAN ViterbiThread ( void * ) {
	svit->Process ();
    return TRUE;
}

static int Dot11ARxInit()
{
	HRESULT hr;

	hr = SoraURadioMapRxSampleBuf(TARGET_RADIO, &RxBuffer, &RxBufferSize);
    printf("Map Buffer ret : %08x\n", hr);
	printf("Rxbuf: %08x, size: %08x\n", RxBuffer, RxBufferSize);

	if (FAILED(hr)) return -1;

	printf("%08x, %08x, %08x, %08x\n",
            ((PULONG)RxBuffer)[0],
            ((PULONG)RxBuffer)[1],
            ((PULONG)RxBuffer)[2],
            ((PULONG)RxBuffer)[3]);

	hr = SoraURadioAllocRxStream(&RxStream, TARGET_RADIO, (PUCHAR)RxBuffer, RxBufferSize);
    printf("SoraURadioAllocRxStream ret: %08x\n", hr);
    if (FAILED(hr)) return -2;

    printf("Rx Context Init ended.\n");

	return 0;
}

void Dot11ARxApp_Brick(const Config& config)
{
	HRESULT		hr;
	if (Dot11ARxInit() < 0)
		goto out;

    BB11aDemodCtx.Init(&RxStream, OutputBuf, OUT_BUF_SIZE);

    if (config.GetSampleRate() == 40)
        CreateDemodGraph11a_40M(ssrc, svit, scs);
    else
    {
        assert(config.GetSampleRate() == 44);
        CreateDemodGraph11a_44M(ssrc, svit, scs);
    }

    thread2 = AllocStartThread(ViterbiThread, NULL);
    if (!thread2) goto out;

    ssrc->Reset();

    thread1 = AllocStartThread(RxThread, NULL);
	if (!thread1) goto out;

    printf("\n\nPress any key to exit the program\n");
    time_t start = time(NULL);
	while(!_kbhit())
    {
        // Timeout if interval configured
        if (config.Interval() != 0 && difftime(time(NULL), start) >= config.Interval()) break;
	}

out:
    StopFreeThread(thread1);
    StopFreeThread(thread2);
    IReferenceCounting::Release(ssrc);
    SoraURadioReleaseRxStream(&RxStream, TARGET_RADIO);

	hr = SoraURadioUnmapRxSampleBuf(TARGET_RADIO, RxBuffer);
	printf("Unmap rx buffer ret: %08x\n", hr);
	printf("Rx out.\n");
}

redpajama_set_name: RedPajamaGithub


text:
package sbt

object VersionRange {
  /** True if the revision is an ivy-range, not a complete revision. */
  def isVersionRange(revision: String): Boolean = {
    (revision endsWith "+") ||
      (revision contains "[") ||
      (revision contains "]") ||
      (revision contains "(") ||
      (revision contains ")")
  }

  // Assuming Ivy is used to resolve conflict, this removes the version range
  // when it is open-ended to avoid dependency resolution hitting the Internet to get the latest.
  // See https://github.com/sbt/sbt/issues/2954
  def stripMavenVersionRange(version: String): Option[String] =
    if (isVersionRange(version)) {
      val noSpace = version.replaceAllLiterally(" ", "")
      noSpace match {
        case MavenVersionSetPattern(open1, x1, comma, x2, close1, rest) =>
          // http://maven.apache.org/components/enforcer/enforcer-rules/versionRanges.html
          (open1, Option(x1), Option(comma), Option(x2), close1) match {
            case (_, None, _, Some(x2), "]") => Some(x2)
            // a good upper bound is unknown
            case (_, None, _, Some(x2), ")") => None
            case (_, Some(x1), _, None, _)   => Some(x1)
            case _                           => None
          }
        case _ => None
      }
    } else None

  /** Converts Ivy revision ranges to that of Maven POM */
  def fromIvyToMavenVersion(revision: String): String = {
    def plusRange(s: String, shift: Int = 0) = {
      def pow(i: Int): Int = if (i > 0) 10 * pow(i - 1) else 1
      val (prefixVersion, lastVersion) = (s + "0" * shift).reverse.split("\\.", 2) match {
        case Array(revLast, revRest) =>
          (revRest.reverse + ".", revLast.reverse)
        case Array(revLast) => ("", revLast.reverse)
      }
      val lastVersionInt = lastVersion.toInt
      s"[${prefixVersion}${lastVersion},${prefixVersion}${lastVersionInt + pow(shift)})"
    }
    val DotPlusPattern = """(.+)\.\+""".r
    val DotNumPlusPattern = """(.+)\.(\d+)\+""".r
    val NumPlusPattern = """(\d+)\+""".r
    val maxDigit = 5
    try {
      revision match {
        case "+"                           => "[0,)"
        case DotPlusPattern(base)          => plusRange(base)
        // This is a heuristic.  Maven just doesn't support Ivy's notions of 1+, so
        // we assume version ranges never go beyond 5 siginificant digits.
        case NumPlusPattern(tail)          => (0 until maxDigit).map(plusRange(tail, _)).mkString(",")
        case DotNumPlusPattern(base, tail) => (0 until maxDigit).map(plusRange(base + "." + tail, _)).mkString(",")
        case rev if rev endsWith "+"       => sys.error(s"dynamic revision '$rev' cannot be translated to POM")
        case rev if startSym(rev(0)) && stopSym(rev(rev.length - 1)) =>
          val start = rev(0)
          val stop = rev(rev.length - 1)
          val mid = rev.substring(1, rev.length - 1)
          (if (start == ']') "(" else start) + mid + (if (stop == '[') ")" else stop)
        case _ => revision
      }
    } catch {
      case e: NumberFormatException =>
        // TODO - if the version doesn't meet our expectations, maybe we just issue a hard
        //        error instead of softly ignoring the attempt to rewrite.
        //sys.error(s"Could not fix version [$revision] into maven style version")
        revision
    }
  }

  def hasMavenVersionRange(version: String): Boolean =
    if (version.length <= 1) false
    else startSym(version(0)) && stopSym(version(version.length - 1))

  private[this] val startSym = Set(']', '[', '(')
  private[this] val stopSym = Set(']', '[', ')')
  private[this] val MavenVersionSetPattern = """([\]\[\(])([\w\.\-]+)?(,)?([\w\.\-]+)?([\]\[\)])(,.+)?""".r
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CLK.Web.Mvc
{
    public class DefaultModelBinder : System.Web.Mvc.DefaultModelBinder
    {
        // Methods
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            #region Contracts

            if (controllerContext == null) throw new ArgumentNullException();
            if (bindingContext == null) throw new ArgumentNullException();
            if (propertyDescriptor == null) throw new ArgumentNullException();

            #endregion

            // PropertyModelBinderAttribute
            var propertyModelBinderAttribute = propertyDescriptor.Attributes.OfType<CustomModelBinderAttribute>().FirstOrDefault();
            if (propertyModelBinderAttribute == null)
            {
                // BindProperty
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
            else
            {
                // PropertyModelBinder
                var propertyModelBinder = propertyModelBinderAttribute.GetBinder();
                if (propertyModelBinder == null) return;

                // PropertyModelBindingContext
                var propertyModelBindingContext = new ModelBindingContext()
                {
                    ModelMetadata = bindingContext.PropertyMetadata[propertyDescriptor.Name],
                    ModelName = this.CreatePropertyName(bindingContext.ModelName, propertyDescriptor.Name),
                    ModelState = bindingContext.ModelState,
                    ValueProvider = bindingContext.ValueProvider
                };

                // BindProperty
                var value = propertyModelBinder.BindModel(controllerContext, propertyModelBindingContext);
                if (value == null) return;

                // SetValue
                propertyDescriptor.SetValue(bindingContext.Model, value);
            }
        }

        private string CreatePropertyName(string prefix = null, string propertyName = null)
        {
            // PropertyName
            if (String.IsNullOrEmpty(prefix) == true)
            {
                return propertyName;
            }

            // Prefix
            if (String.IsNullOrEmpty(propertyName))
            {
                return prefix;
            }

            // Prefix.PropertyName
            return prefix + "." + propertyName;
        }
    }
}


text:
require "rails_helper"

describe "alchemy/essences/_essence_picture_editor" do
  let(:picture) { stub_model(Alchemy::Picture) }

  let(:essence_picture) do
    stub_model(
      Alchemy::EssencePicture,
      picture: picture,
      caption: "This is a cute cat",
    )
  end

  let(:content) do
    stub_model(
      Alchemy::Content,
      name: "image",
      essence_type: "EssencePicture",
      essence: essence_picture,
    )
  end

  let(:settings) { Hash.new }

  before do
    view.class.send(:include, Alchemy::Admin::BaseHelper)
    view.class.send(:include, Alchemy::Admin::EssencesHelper)
    allow(view).to receive(:content_label).and_return("")
    allow(view).to receive(:essence_picture_thumbnail).and_return("")
  end

  subject do
    allow(content).to receive(:settings) { settings }
    render partial: "alchemy/essences/essence_picture_editor",
      locals: {essence_picture_editor: Alchemy::ContentEditor.new(content)}
    rendered
  end

  context "with settings[:deletable] being nil" do
    it "should not render a button to link and unlink the picture" do
      is_expected.to have_selector("a .icon.fa-link")
      is_expected.to have_selector("a .icon.fa-unlink")
    end
  end

  context "with settings[:deletable] being false" do
    let(:settings) do
      {
        linkable: false,
      }
    end

    it "should not render a button to link and unlink the picture" do
      is_expected.to_not have_selector("a .icon.fa-link")
      is_expected.to_not have_selector("a .icon.fa-unlink")
    end

    it "but renders the disabled link and unlink icons" do
      is_expected.to have_selector(".icon.fa-link")
      is_expected.to have_selector(".icon.fa-unlink")
    end
  end

  context "with allow_image_cropping? true" do
    before do
      allow(essence_picture).to receive(:allow_image_cropping?) { true }
    end

    it "shows cropping link" do
      is_expected.to have_selector('a[href*="crop"]')
    end
  end

  context "with allow_image_cropping? false" do
    before do
      allow(essence_picture).to receive(:allow_image_cropping?) { false }
    end

    it "shows disabled cropping link" do
      is_expected.to have_selector("a.disabled .icon.fa-crop")
    end
  end
end


text:
package org.apereo.cas.impl.account;

import org.apereo.cas.adaptors.ldap.LdapIntegrationTestsOperations;
import org.apereo.cas.api.PasswordlessUserAccountStore;
import org.apereo.cas.config.LdapPasswordlessAuthenticationConfiguration;
import org.apereo.cas.impl.BasePasswordlessUserAccountStoreTests;
import org.apereo.cas.util.junit.EnabledIfPortOpen;

import com.unboundid.ldap.sdk.LDAPConnection;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.TestPropertySource;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link LdapPasswordlessUserAccountStoreTests}.
 *
 * @author Misagh Moayyed
 * @since 6.2.0
 */
@Tag("Ldap")
@EnabledIfPortOpen(port = 10389)
@TestPropertySource(properties = {
    "cas.authn.passwordless.accounts.ldap.ldapUrl=ldap://localhost:10389",
    "cas.authn.passwordless.accounts.ldap.baseDn=ou=people,dc=example,dc=org",
    "cas.authn.passwordless.accounts.ldap.searchFilter=cn={0}",
    "cas.authn.passwordless.accounts.ldap.bindDn=cn=Directory Manager",
    "cas.authn.passwordless.accounts.ldap.bindCredential=password",
    "cas.authn.passwordless.accounts.ldap.email-attribute=mail",
    "cas.authn.passwordless.accounts.ldap.phone-attribute=telephoneNumber"
})
@Slf4j
@Import(LdapPasswordlessAuthenticationConfiguration.class)
public class LdapPasswordlessUserAccountStoreTests extends BasePasswordlessUserAccountStoreTests {
    @Autowired
    @Qualifier("passwordlessUserAccountStore")
    private PasswordlessUserAccountStore passwordlessUserAccountStore;

    @BeforeAll
    @SneakyThrows
    public static void bootstrap() {
        @Cleanup
        val localhost = new LDAPConnection("localhost", 10389, "cn=Directory Manager", "password");
        val resource = new ClassPathResource("ldif/ldap-passwordless.ldif");
        LOGGER.debug("Populating LDAP entries from [{}]", resource);
        LdapIntegrationTestsOperations.populateEntries(localhost, resource.getInputStream(), "ou=people,dc=example,dc=org");
    }

    @Test
    public void verifyAction() {
        val user = passwordlessUserAccountStore.findUser("passwordlessuser");
        assertTrue(user.isPresent());
        assertEquals("passwordlessuser@example.org", user.get().getEmail());
        assertEquals("123456789", user.get().getPhone());
    }
}


text:
Solidity in Depth
#################

This section should provide you with all you need to know about Solidity.
If something is missing here, please contact us on
`Gitter <https://gitter.im/ethereum/solidity>`_ or make a pull request on
`Github <https://github.com/ethereum/solidity/pulls>`_.

.. toctree::
   :maxdepth: 2

   layout-of-source-files.rst
   structure-of-a-contract.rst
   types.rst
   units-and-global-variables.rst
   control-structures.rst
   contracts.rst
   miscellaneous.rst


text:
<?php

namespace Assely\Sidebar;

use Assely\Support\Accessors\HasSlug;
use Assely\Support\Accessors\HasTitles;
use Assely\Support\Accessors\HasArguments;

class Sidebar
{
    use HasSlug, HasArguments, HasTitles;

    /**
     * Default widget area arguments.
     *
     * @var array
     */
    private $defaults = [
        'before_widget' => '
',
        'after_widget' => '
',
        'before_title' => '
',
        'after_title' => '
',

        'title' => [],
        'description' => '',
    ];

    /**
     * Sidebar manager.
     *
     * @var \Assely\Sidebar\SidebarManager
     */
    private $manager;

    /**
     * Construnct sidebar.
     *
     * @param \Assely\Sidebar\SidebarManager $manager
     */
    public function __construct(SidebarManager $manager)
    {
        $this->manager = $manager;
    }

    /**
     * Bootstrap sidebar.
     *
     * @return void
     */
    public function boot()
    {
        $this->setSingular($this->getArgument('title'));
        $this->setPlural($this->getArgument('title'));

        $this->manager->boot($this);
    }

    /**
     * Register widget area.
     *
     * @return int
     */
    public function register()
    {
        $parameters = [
            'name' => $this->getSingular(),
            'id' => $this->getSlug(),
        ];

        return register_sidebar(array_merge($this->getArguments(), $parameters));
    }

    /**
     * Gets sidebar.
     *
     * @return void
     */
    public function render()
    {
        dynamic_sidebar($this->getSlug());
    }

    /**
     * Check if sidebar has widgets.
     *
     * @return bool
     */
    public function hasWidgets()
    {
        return is_active_sidebar($this->getSlug());
    }
}


text:
define(["game/functions/menuSprite"], function (Sprite){

    var Button = function (args){
        this.name = args.name;
        this.tag = "button";
        this.overImage = args.overImage;
        this.normalImage = args.image;
        this.sprite = new Sprite({x : args.x, y : args.y, width : args.width, height : args.height, image : args.image, context : args.context});
        this.callback = args.callback;
        this.left = args.left;
        this.right = args.right;
        this.up = args.up;
        this.down = args.down;
    }

    Button.prototype.draw = function draw (){
        this.sprite.draw();
    }

    Button.prototype.metamorph = function metamorph (bool){
        if(bool)
            this.sprite.image = this.overImage;
        else
            this.sprite.image = this.normalImage;

    }

    return Button;
})


text:
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License.  See License.txt in the project root for license information.

using System.Web.OData.Routing;
using Microsoft.OData.Edm;

namespace System.Web.OData.Formatter
{
    /// <summary>
    /// Media type mapping that associates requests for the raw value of non-binary primitive properties to
    /// the text/plain content type.
    /// </summary>
    public class ODataPrimitiveValueMediaTypeMapping : ODataRawValueMediaTypeMapping
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ODataPrimitiveValueMediaTypeMapping"/> class.
        /// </summary>
        public ODataPrimitiveValueMediaTypeMapping()
            : base("text/plain")
        {
        }

        /// <inheritdoc/>
        protected override bool IsMatch(PropertyAccessPathSegment propertySegment)
        {
            return propertySegment != null &&
                   propertySegment.Property.Type.IsPrimitive() &&
                   !propertySegment.Property.Type.IsBinary();
        }
    }
}


text:
Video-Wall
==========

Wall-to-wall YouTube videos. This free app is published in the Google Play Store.

The app shows a video wall of thumbnail images for videos in a YouTube playlist. One of the thumbnails will flip over and begin playing a video from the playlist, which will play until it finishes. After that, the video will be replaced with a thumnbail, and a different thumbnail will flip over to play another video.

Features:

Grid of animated YouTube videos

Select playlist of HD videos

Configure animated effects

Play current video in YouTube app

Instructions:

To select a playlist: Press the Menu button and then "Select Playlist".

To change the animated effect: Press the Menu button, select "Settings/Effect".

To play the current video in the YouTube app: Press the OK button. Press Back to get back to the video wall app.

To jump to the next video: Press the media next button.

Limitations:

Due to a YouTube player API bug, only a static list of playlists are supported for now.

Developers:

The code is based on the YouTube Android Player API sample app. The code is released under the Apache 2.0 open source license. The source code is commented to explain the design.

Other apps developed by Entertailion:

Able Remote for Google TV: The ultimate Google TV remote

Open Launcher for Google TV: The ultimate Google TV launcher

Overlay for Google TV: Live TV effects for Google TV

GTV Tasker Plugin: Control your Google TV with Tasker actions

FAQ:

The app doesn't work on my Google TV device -  You need to have version 1.6 (4845) of the YouTube app (or higher)

Why does the video pause? - The videos pause when they are buffering. All the videos are in HD and require a good broadband connection. Restarting the Google TV device might also help


text:
'use strict';

const Promise = require('bluebird');

function promisifyMiddleware(middleware) {
    return function(req, res, next) {
        Promise.try(function(){
            return middleware(req, res);
        })
        .then(() => {
            if (! res.finished) {
                setImmediate(next);
            }
        })
        .catch(next);
    };
}

module.exports = promisifyMiddleware;


text:
require 'set_attributes'
require 'schema'
require 'telemetry/logger'
require 'dependency'; Dependency.activate
require 'event_store/messaging'

require 'event_store/entity_projection/entity_projection'


text:
<?php

namespace App\G6K\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Question\Question;

use App\Security\UserManagerInterface;

use App\Security\Util\SecurityFunction;

/**
 * Changes the password of a user into the users database.
 *
 */
class ChangePasswordSecurityCommand extends CommandBase {

	private $userManager;

	/**
	 * @inheritdoc
	 */
	public function __construct(string $projectDir, UserManagerInterface $userManager) {
		parent::__construct($projectDir, "Changes the password of a user into the users database.");
		$this->userManager = $userManager;
	}

	/**
	 * @inheritdoc
	 */
	protected function getCommandName() {
		return 'g6k:security:user:password:change';
	}

	/**
	 * @inheritdoc
	 */
	protected function getCommandDescription() {
		return $this->translator->trans('Changes the password of a user into the users database.');
	}

	/**
	 * @inheritdoc
	 */
	protected function getCommandHelp() {
		return
			  $this->translator->trans("This command allows you change the password of a user into the users database.")."\n"
			. "\n"
			. $this->translator->trans("You must provide:")."\n"
			. $this->translator->trans("- the username of the user.")."\n"
			. $this->translator->trans("- the new password of the user.")."\n"
		;
	}

	/**
	 * @inheritdoc
	 */
	protected function getCommandArguments() {
		return [
			[
				'username',
				InputArgument::REQUIRED,
				$this->translator->trans('The username of the user.')
			],
			[
				'password',
				InputArgument::REQUIRED,
				$this->translator->trans('The new password of the user.')
			]
		];
	}

	/**
	 * @inheritdoc
	 */
	protected function getCommandOptions() {
		return [
			[
				'skip-strength-validation',
				's',
				InputOption::VALUE_NONE,
				$this->translator->trans('Skip the strength validation of the new password.'),
			]
		];
	}

	/**
	 * Checks the argument of the current command (g6k:security:user:password:change).
	 *
	 * @param   \Symfony\Component\Console\Input\InputInterface $input The input interface
	 * @param   \Symfony\Component\Console\Output\OutputInterface $output The output interface
	 * @return  void
	 *
	 */
	protected function interact(InputInterface $input, OutputInterface $output) {
		$questions = array();
		if (!$input->getArgument('username')) {
			$question = new Question('Please enter an username : ');
			$question->setValidator(function ($username) {
				if (empty($username)) {
					throw new \Exception('The username can not be empty');
				}

				return $username;
			});
			$questions['username'] = $question;
		}
		if (!$input->getArgument('password')) {
			$question = new Question('Please enter the new password : ');
			$question->setValidator(function ($password) {
				if (empty($password)) {
					throw new \Exception('The password can not be empty');
				}

				return $password;
			});
			$question->setHidden(true);
			$questions['password'] = $question;
		}
	   foreach ($questions as $name => $question) {
			$answer = $this->getHelper('question')->ask($input, $output, $question);
			$input->setArgument($name, $answer);
		}
	}

	/**
	 * @inheritdoc
	 */
	protected function execute(InputInterface $input, OutputInterface $output) {
		parent::execute($input, $output);
		$username = $input->getArgument('username');
		$password = $input->getArgument('password');
		$skipValidation = $input->getOption('skip-strength-validation');

		try {
			$user = $this->userManager->findUserByUsername($username);
			if ($user === null) {
				$this->failure($output, "The user '%s%' doesn't exists.", ['%s%' => $username]);
				return 1;
			} else {
				if (! $skipValidation && ! SecurityFunction::isPasswordStrong($password)) {
					$this->failure($output, "User '%s%' : password should be at least 8 characters in length and should include at least one upper case letter, one number, and one special character.", ['%s%' => $username]);
					return 1;
				} else {
					$user->setPlainPassword($password);
					$this->userManager->updateUser($user);
					$this->success($output, "Updated user '%s%' password", ['%s%' => $username]);
					return 0;
				}
			}
		} catch(\Exception $e) {
			$this->failure($output, "The password of the user '%s%' can't be updated. Reason : %r%", ['%s%' => $username, '%r%' => $e->getMessage()]);
			return 1;
		}
	}

}


text:
/**
 * Class - AccordionBox
 * event management component - Accordion
 *
 * JavaScript
 *
 * @author   Sergii Beskorovainyi <bsa2657@yandex.ru>
 * @license  MIT <http://www.opensource.org/licenses/mit-license.php>
 * @link     https://github.com/bsa-git/zf-myblog/
 */
BSA.AccordionBox = Class.create({

    id: '', // Container for accordion
    accordion: null, // The object of the accordion
    options: null, // Options for creating accordion
    states: null,  // Accordion states (which sections are opened or deactivated)
    // List of events
    events: {
        initializedAccordion: 'initialized',
        clickedAccordion: 'clicked',
        disabledAccordion: 'disabled',
        enabledAccordion: 'enabled',
        hiddenSection: 'hidden',
        shownSection: 'shown',
        disabledSection: 'disabled',
        enabledSection: 'enabled'
    },

    // Subscribed events
    onInitializedAccordionEvent: [],
    onClickedAccordionEvent: [],
    onDisabledAccordionEvent: [],
    onEnabledAccordionEvent: [],
    onHiddenSectionEvent: [],
    onShownSectionEvent: [],
    onDisabledSectionEvent: [],
    onEnabledSectionEvent: [],

    // Object initialization
    initialize : function(params)
    {

        // Установим id
        if (params && $(params.id)){
            this.id = params.id;
        }else{
            return;
        }

        // Состояние аккордиона
        if(params.states){
            this.states = params.states;
        }

        // Создадим пользовательские события
        this.createCustomEvents();

        // Создадим обьект аккордион
        if (params.options){
            this.options = params.options;
            this.accordion = new Accordion(this.id, params.options);
        }else{
            this.accordion = new Accordion(this.id);
        }

        // Удалим фиксированные размеры по высоте контейнера -> div.toggle
        this.accordion.elements.toggles.each(function(toggle){
            toggle.setStyle({
                height: ''
            });

        })
        // Сделаем видимыми контейнеры -> div.accordion-toggle-container
        $$("div.accordion-toggle-container").invoke('show');

        // Сделаем видимыми контейнеры -> div#accordion-container
        // это используется для того что бы правильно отображалась страница
        // когда отключен javascript
        if($('accordion-container')){
            if($('accordion-container').select("li.section").size()){
                $('accordion-container').show();
            }

        }
    },

    // Creating a custom event for accordion
    createCustomEvents: function(){
        var self = this;
        var idTimeout;
        var section;
        //------------------
        // onInitializedAccordionEvent
        document.observe(self.id + ":" + self.events.initializedAccordion, function(event) {
            // Обработаем пользовательское событие и установим состояния секций аккордиона
            // с задержкой в 300 мсек чтобы за это время успели загеристрироваться все клиенты
            idTimeout = window.setTimeout(function() {
                // Обработаем пользовательское событие инициализации аккордиона
                if(self.onInitializedAccordionEvent.length > 0){
                    self.onInitializedAccordionEvent.each(function(objEvent){
                        //                        objEvent.handlerEvent(objEvent.client, event.memo);
                        if(objEvent.client.accordion.id && event.memo.accordion.id){
                            if(objEvent.client.accordion.id == event.memo.accordion.id){
                                objEvent.handlerEvent(objEvent.client, event.memo);
                            }
                        }else{
                            objEvent.handlerEvent(objEvent.client, event.memo);
                        }
                    })
                }

                // установим состояния секций аккордиона
                self.setStateAccordion(self.states, event.memo.accordion);
                window.clearTimeout(idTimeout);
            }, 300);

        });

        // onClickedAccordionEvent
        document.observe(self.id + ":" + self.events.clickedAccordion, function(event) {
            if(self.onClickedAccordionEvent.length > 0){
                self.onClickedAccordionEvent.each(function(objEvent){
                    //                    objEvent.handlerEvent(objEvent.client, event.memo);
                    if(objEvent.client.accordion.id && event.memo.accordion.id){
                        if(objEvent.client.accordion.id == event.memo.accordion.id){
                            objEvent.handlerEvent(objEvent.client, event.memo);
                        }
                    }else{
                        objEvent.handlerEvent(objEvent.client, event.memo);
                    }
                })
            }
        });

        // onDisabledAccordionEvent
        document.observe(self.id + ":" + self.events.disabledAccordion, function(event) {
            if(self.onDisabledAccordionEvent.length > 0){
                self.onDisabledAccordionEvent.each(function(objEvent){
                    //                    objEvent.handlerEvent(objEvent.client, event.memo);
                    if(objEvent.client.accordion.id && event.memo.accordion.id){
                        if(objEvent.client.accordion.id == event.memo.accordion.id){
                            objEvent.handlerEvent(objEvent.client, event.memo);
                        }
                    }else{
                        objEvent.handlerEvent(objEvent.client, event.memo);
                    }
                })
            }
        });

        // onEnabledAccordionEvent
        document.observe(self.id + ":" + self.events.enabledAccordion, function(event) {
            if(self.onEnabledAccordionEvent.length > 0){
                self.onEnabledAccordionEvent.each(function(objEvent){
                    //                    objEvent.handlerEvent(objEvent.client, event.memo);
                    if(objEvent.client.accordion.id && event.memo.accordion.id){
                        if(objEvent.client.accordion.id == event.memo.accordion.id){
                            objEvent.handlerEvent(objEvent.client, event.memo);
                        }
                    }else{
                        objEvent.handlerEvent(objEvent.client, event.memo);
                    }
                })
            }
        });

        // onHiddenSectionEvent
        document.observe(self.id + "Section:" + self.events.hiddenSection, function(event) {

            if(self.onHiddenSectionEvent.length > 0){
                self.onHiddenSectionEvent.each(function(objEvent){
                    //                    objEvent.handlerEvent(objEvent.client, event.memo);
                    if(objEvent.client.accordion.id && event.memo.accordion.id){
                        if(objEvent.client.accordion.id == event.memo.accordion.id){
                            objEvent.handlerEvent(objEvent.client, event.memo);
                        }
                    }else{
                        objEvent.handlerEvent(objEvent.client, event.memo);
                    }
                })
            }
        });

        // onShownSectionEvent
        document.observe(self.id + "Section:" + self.events.shownSection, function(event) {

            if(self.onShownSectionEvent.length > 0){
                self.onShownSectionEvent.each(function(objEvent){
                    if(objEvent.client.accordion.id && event.memo.accordion.id){
                        if(objEvent.client.accordion.id == event.memo.accordion.id){
                            objEvent.handlerEvent(objEvent.client, event.memo);
                        }
                    }else{
                        objEvent.handlerEvent(objEvent.client, event.memo);
                    }
                })
            }
        });

        // onDisabledSectionEvent
        document.observe(self.id + "Section:" + self.events.disabledSection, function(event) {
            section = event.memo.section.elements.section;
            section.writeAttribute('title', lb.getMsg('msgAccessDenied'));

            if(self.onDisabledSectionEvent.length > 0){
                self.onDisabledSectionEvent.each(function(objEvent){
                    //                    objEvent.handlerEvent(objEvent.client, event.memo);
                    if(objEvent.client.accordion.id && event.memo.accordion.id){
                        if(objEvent.client.accordion.id == event.memo.accordion.id){
                            objEvent.handlerEvent(objEvent.client, event.memo);
                        }
                    }else{
                        objEvent.handlerEvent(objEvent.client, event.memo);
                    }
                })
            }
        });

        // onEnabledSectionEvent
        document.observe(self.id + "Section:" + self.events.enabledSection, function(event) {
            section = event.memo.section.elements.section;
            section.writeAttribute('title', '');

            if(self.onEnabledSectionEvent.length > 0){
                self.onEnabledSectionEvent.each(function(objEvent){
                    //                    objEvent.handlerEvent(objEvent.client, event.memo);
                    if(objEvent.client.accordion.id && event.memo.accordion.id){
                        if(objEvent.client.accordion.id == event.memo.accordion.id){
                            objEvent.handlerEvent(objEvent.client, event.memo);
                        }
                    }else{
                        objEvent.handlerEvent(objEvent.client, event.memo);
                    }
                })
            }
        });
    },

    //Set state of the sections for accordion
    setStateAccordion: function(states, accordion){
        var section;
        var self = this;
        //--------------------
        if(states && states.disable.size()){
            states.disable.each(function(index){
                section = self.getThisSection(accordion, index);
                if(section){
                    section.disable();
                }
            })
        }

        if(states && states.show.size()){
            states.show.each(function(index){
                section = self.getThisSection(accordion, index);
                if(section){
                    accordion.showSection(section);
                }
            })
        }
    },

    // Get accordion section of the index
    getThisSection: function(accordion, index){
        var result = null;
        accordion.sections.each(function(section){
            var index_ = section.elements.title.readAttribute('href');
            if(index_ == index){
                result = section;
            }
        })
        return result;
    }

})

// The function is executed after the download of the browser window
// are created objects, which are entered in the list of instances
// ex. $H(AccordionBox: [new AccordionBox(), ... ,new AccordionBox()])
BSA.AccordionBox.RegRunOnLoad = function() {
    // Получим параметры для создания обьекта
    var params = scriptParams.get('AccordionBox');
    // Ф-ия создания обьектов по их параметрам
    var createObject = function (param) {
        var accordion = scriptInstances.get('AccordionBox');
        if (accordion) {
            accordion.push(new BSA.AccordionBox(param));
        } else {
            scriptInstances.set('AccordionBox', [new BSA.AccordionBox(param)]);
        }
    };
    // Создание обьектов
    if (params) {
        params.each(function (param) {
            createObject(param);
        });
    } else {
        createObject();
    }
}
runOnLoad(BSA.AccordionBox.RegRunOnLoad);


text:
describe 'vault remove' do
  after(:each) do
    run 'kontena vault rm --force foo'
    run 'kontena vault rm --force foo0'
    run 'kontena vault rm --force foo1'
  end

  it 'removes a vault key' do
    run! 'kontena vault write foo bar'
    run! 'kontena vault rm --force foo'
  end

  it 'removes multiple vault keys' do
    2.times do |i|
      run! "kontena vault write foo#{i} bar"
    end
    run! 'kontena vault rm --force foo0 foo1'
  end
end


text:
ref: info-privacy-security-polices-enhancing-tech
title: "Information Privacy and Security Policies and Enhancing Technologies"
semester: 5
author: atsohou-en
excerpt: "Conceptual foundation: information privacy, anonymity, unlinkability, unobservability, information security, threats, vulnerabilities, risk. Privacy by Design. Information security risk assessment and management: information security requirements, risk analysis methods (OCTAVE, CRAMM, SBA scenario). Information Security Policies. Privacy risk analysis, Privacy in the Digital Era (e-commerce, e-government, social networks), users'  information privacy behaviors: privacy perception, intention to disclose personal information, privacy concerns, Information privacy policies, Personal data protection regulation, Privacy enhancing tools, Privacy awareness enhancing tools, Selected research topics."
uri: "https://e-class.ionio.gr/courses/DCS265/"
code: HY365
type: "Elective"
hours: 4
extra:
ects: 4
---

bibliography:
  - "Andreas Pfitzmann, Marit Hansen (2010)  A Terminology for talking about Privacy by data minimization: Anonymity, Unlinkability, Undetectability, Unobservability, Pseudonymity, and Identity Management, v0.34 (http://dud.inf.tu-dresden.de/Anon_Terminology.shtml )"


text:
using System;
using System.Drawing;
using System.IO;
using ImageResizer;

namespace Postcard.Processing.Transformation
{
    /// <summary>
    /// Обрезка
    /// </summary>
    public class Crop : ITask
    {
        public int Height { get; set; }
        public int Width { get; set; }

        public Image Apply(Image image)
        {
            var setting = new ResizeSettings(String.Format("w={0}&h={1}&mode=crop&scale=both", Width, Height));
            var srcImage = Path.GetTempFileName();
            image.Save(srcImage);
            var outImage = Path.GetTempFileName();
            ImageBuilder.Current.Build(srcImage, outImage, setting);
            return Image.FromFile(outImage);
        }
    }
}


text:
export class ExperimentTask {
    constructor(name, otype) {
        this.id = '';
        this.name = name;
        this.otype = otype;
        this.tasks = [];
        this.description = '';
        this.flags = {
            important: false,
            review: false,
            error: false,
            done: false
        };
        this.displayState = {
            details: {
                showNotes: true,
                showFiles: false,
                showSamples: false,
                currentFilesTab: 0,
                currentSamplesTab: 0
            },
            flags: {
                errorClass: 'mc-flag-not-set',
                importantClass: 'mc-flag-not-set',
                reviewClass: 'mc-flag-not-set'
            },
            selectedClass: '',
            open: false,
            maximize: false
        };
        this.node = null;
    }

    addTask(task) {
        this.tasks.push(task);
    }
}

export class Experiment {
    constructor(name) {
        this.name = name;
        this.goal = '';
        this.description = '';
        this.aim = '';
        this.status = 'active';
        this.tasks = [];
    }

    addTask(name, otype) {
        let task = new ExperimentTask(name, otype);
        this.tasks.push(task);
    }
}