text:
define([
    "Backbone",
    "lodash",
    "jQuery",
    "drop",
    "ExpressionGenerator",
    "rpnBuilder",
    "rpn",
    "mathIt"
], function(
    Backbone,
    _,
    $,
    drop,
    expressionGenerator,
    rpnBuilder,
    rpn,
    mathIt,
    ko,
    MathTemplate
) {
    var popupContent = {
        insertValue: "

 Неправильно!
" +
                        "
 Введи результат операции
" +
                        "<input type = 'text' class = 'question-input' id = 'question-input_input' />
",
        wrongNode: "Данную операцию нельзя выполнить в данный момент, выбери другую!",
        leaf: "Это операнд, выбери операцию"
    };

    var DEFAULT_OPTIONS = {
        position: "bottom center",
        remove: true,
        classes: "drop-theme-arrows"
    };

    var operations = ["+", "-", "*", "/"];

    var MainExpressionView = Backbone.View.extend({
        initialize: function() {
            this.subviews = [];
            this.user = { goodAnswer: 0, wrongAnswer: 0 , currentWrongAnswers: 0 };
            this.questionNumber = 0;
        },

        render: function() {
            this.$el.html(this.template());
            this.changeNode.bind(this);

            this.$el.find("#expression").hide();
            this._updateDebagStatistic();
            this.$el.find("#in").on("click", this._newExpression.bind(this));

            return this;
        },

        _newExpression: function() {
            var mathResultString = "";
            this.questionNumber++;
            this.user.currentWrongAnswers = 0;
            this._updateDebagStatistic();
            this.expression = expressionGenerator.generate(4);
            $(".result-expression").empty();
            var $expression = this.$el.find("#expression");
            $expression.show();
            $expression.text(_.join(this.expression, " "));
            var inputValue = $expression.text();
            inputValue = inputValue.replace(/ /g, " ");
            //var inputArr = _.toArray(inputValue);

            this.createExpressionInDOM($expression);

            this.$el.find(".lettering-item").on("click", this._openPopup.bind(this));

            mathResultString = inputValue;

            //var RPN = new rpnBuilder(inputValue);

            // Вариант с дефолтной функцией, только выражение без id
            //var rpnString = rpn.infix2rpn(inputValue);

            var rpnResult =  rpn.exp2rpnWithIds(inputValue);
            var rpnString = rpnResult.string;

            //var RPNObjectCollection = RPN.getTokensWithIds();
            var rpnObjectCollection =  rpnResult.map;

            this.nodes = new Map();
            this.createGraphFromRPN(rpnObjectCollection);
            //createGraphFromRPN(RPNObjectCollection);
            var resDiv = this.$el.find("#res");

            //var resString = RPN.getString();
            resDiv.text(rpnString);
            console.log(rpnString);
            this.$el.find("#math").text(mathResultString);
            //initGraph();
        },

        // Добавить отдельную логику для генерации контента попапа в случае неправильной операции (нужно объяснять почему)
        _openPopup: function(event) {
            if (this.activePopup) {
                //$(".drop").remove();
                this.activePopup.close();
                this.activePopup.remove();
                this.activePopup = null;
                return;
            }
            // id - номер В обратной польской нотации
            var id = event.target.dataset.id;

            var content;
            var node = this.nodes.get(+id);
            if (!node) {
                content = popupContent.wrongNode;
            } else if (this.isCalculatable(node)) {
                //TODO: Можно добавить оброботчики правильно и не правильно ответа.
                content = popupContent.insertValue;
            } else if (node.leaf) {
                content = popupContent.leaf;
                this.user.wrongAnswer++;
                this.user.currentWrongAnswers++;
            } else {
                content = popupContent.wrongNode;
                this.user.wrongAnswer++;
                this.user.currentWrongAnswers++;
            };
            this._updateDebagStatistic();
            this.activePopup = this._createPopup(content, event.target);
            this.activePopup.open();
            var input = $(this.activePopup.drop).find("input");
            // TODO: Расширить текс!!!
            var attentionText = $(this.activePopup.drop).find(".question-input_attention");
            var self = this;
            input.on("change", e => {
                var curValue = e.currentTarget.value;
                //TODO: Можно использовать метод из rpn Calculate
                if (self._campare(curValue, self.calculateNode(node))) {
                    //TODO: ПРОВЕРИТЬ КАК РАБОТАЕТ ДЛЯ ПРИМЕРОВ
                    self.changeNode(node, curValue);
                    self.activePopup.close();
                    self.activePopup.remove();
                    self.activePopup = null;
                    self.user.goodAnswer++;
                    self.user.currentWrongAnswers = 0;
                } else {
                    self.user.wrongAnswer++;
                    self.user.currentWrongAnswers++;
                    attentionText.show();
                    input.val("");
                }
                self._updateDebagStatistic();
            });
        },

        _updateDebagStatistic: function() {
            this.$el.find("#goodAnswer").text(this.user.goodAnswer);
            this.$el.find("#wrongAnswer").text(this.user.wrongAnswer);
            this.$el.find("#currentWrongAnswers").text(this.user.currentWrongAnswers);
            this.$el.find("#questionNumber").text(this.user.questionNumber);
        },

        //FOR INT and Float value
        _campare: function(a, b) {
            const EPS = 0.1;
            if (Math.abs(Math.abs(a) - Math.abs(b)) < EPS) {
                return true;
            }
            return false;
        },

        createExpressionInDOM: function($expression) {
            $expression.lettering("words");

            //TODO: добавить обработчики... !!!!
            // обращение через #word + i;
            // + можно повесить на + - и тд обработку по  наведению\нажатию.
            // можно пройти по всем элементам в $expression добавлять обработчик в зависимости от элемента

        },

        createGraphFromRPN: function(rpnWithIds) {
            var self = this;
            // var rpn = [];
            // _.each(rpnWithIds, e => {
            //     rpn.push(e.token);
            // })
            var tokensAndId = _.reverse(rpnWithIds);
            var lastId = 0;
            _.each(tokensAndId, t => {
                var node = { id: lastId, origId: t.id ,label: t.token,
                    childs: [], leaf: !operations.find(op => op == t.token) };
                lastId++;
                self.nodes.set(t.id, node);
            });

            var stack = [];
            var curHead;
            //_.each(self.nodes.values(), node => {
            self.nodes.forEach((node, id) => {
                curHead = _.last(stack);
                //console.log(stack);
                if (curHead) {
                    //console.log("curHead: " + curHead.label);
                    curHead.childs.unshift(node);
                    //console.log("push childs: " + node.label);
                    if (curHead.childs.length == 2) {
                        stack.pop();
                        //console.log(stack);
                        //console.log("pop: " + t.label);
                    }
                }
                if (!node.leaf) {
                    stack.push(node);
                    //console.log(stack);
                    //console.log("push: " + node.label);
                }
            });
        },

        calculateNode: function(node) {
            //var node = nodes[nodeId];
            //if (isCalculatable(node)) {
            return mathIt[node.label](node.childs[0].label, node.childs[1].label);
        },

        isCalculatable: function(node) {
            // only binar operation
            if (node.childs.length == 2) {
                return node.childs[0].leaf && node.childs[1].leaf;
            }
            return false;
        },

        changeNode: function(node, label) {
            node.label = label;
            var newMath = this.expression;
            var lastMath = this.expression;
            const text2 = _.join(lastMath, " ") + " = ";
            var resultExpression = $(".result-expression")[0];
            // if (resultExpression.children.length == 0) {
            //     const text = _.join(newMath, " ");
            //     resultExpression.append($("
" + text + "
"));
            // }
            console.log(newMath);
            newMath[node.origId] = label;
            console.log(node.origId);

            var nodeRoot = $("#word" + node.origId);
            nodeRoot.text(node.label);

            // удаление элементов из узла (грф вид)
            var child1ID = node.childs[0].origId;
            var child2ID = node.childs[1].origId;
            console.log(node.childs[0].origId);
            console.log(node.childs[1].origId);
            newMath[child1ID] = "";
            newMath[child2ID] = "";
            var left;
            var right;
            for (var i = child1ID; i >= 0; i--) {
                if (newMath[i] != "") {
                    left = i;
                    break;
                }
            }
            for (var i = child2ID; i <= newMath.length; i++) {
                if (newMath[i] != "") {
                    right = i;
                    break;
                }
            }
            if (newMath[left] == "(" && newMath[right] == ")") {
                newMath[left] = "";
                newMath[right] = "";
                this._removeWordById(left);
                this._removeWordById(right);
            }

            this._removeWordById(child1ID);
            this._removeWordById(child2ID);

            delete node.childs[0];
            delete node.childs[1];
            node.childs = [];
            node.leaf = true;
            console.log(newMath);
            var $math = $("#math");
            var newText = $math.text() + " = " + _.join(newMath, " ");
            $(resultExpression).append($("
" + text2 + "
"));
            $math.text(newText);
        },

        _removeWordById: function(id) {
            $("#word" + id).remove();
        },

        //TODO: добавить popup + обработчики нажатия и ввода ответа с использованием этих методов

        ////////////////////////////////////////  POPUP ------------ START ////////////////////////////////////////////////////

        _createPopup: function(content, target, options) {
            if (content && target) {
                options = options || {};
                options.content = content;
                options.target = target;
                options = _.extend(_.clone(DEFAULT_OPTIONS), options);

                // Create Tether element
                var popover = new drop(options);
                return popover;
            } else {
                console.warn("Tried to open popover with insufficient parameters.");
            }
        }

      ///////////////////////////////////////  POPUP ------------ END ////////////////////////////////////////////////////

    });

    return MainExpressionView;
});


text:
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// "liveMedia"
// Copyright (c) 1996-2012 Live Networks, Inc.  All rights reserved.
// A sink that generates an AVI file from a composite media session
// Implementation

#include "AVIFileSink.hh"
#include "InputFile.hh"
#include "OutputFile.hh"
#include "GroupsockHelper.hh"

#define fourChar(x,y,z,w) ( ((w)<<24)|((z)<<16)|((y)<<8)|(x) )/*little-endian*/

////////// AVISubsessionIOState ///////////
// A structure used to represent the I/O state of each input 'subsession':

class SubsessionBuffer {
public:
  SubsessionBuffer(unsigned bufferSize)
    : fBufferSize(bufferSize) {
    reset();
    fData = new unsigned char[bufferSize];
  }
  virtual ~SubsessionBuffer() { delete[] fData; }
  void reset() { fBytesInUse = 0; }
  void addBytes(unsigned numBytes) { fBytesInUse += numBytes; }

  unsigned char* dataStart() { return &fData[0]; }
  unsigned char* dataEnd() { return &fData[fBytesInUse]; }
  unsigned bytesInUse() const { return fBytesInUse; }
  unsigned bytesAvailable() const { return fBufferSize - fBytesInUse; }

  void setPresentationTime(struct timeval const& presentationTime) {
    fPresentationTime = presentationTime;
  }
  struct timeval const& presentationTime() const {return fPresentationTime;}

private:
  unsigned fBufferSize;
  struct timeval fPresentationTime;
  unsigned char* fData;
  unsigned fBytesInUse;
};

class AVISubsessionIOState {
public:
  AVISubsessionIOState(AVIFileSink& sink, MediaSubsession& subsession);
  virtual ~AVISubsessionIOState();

  void setAVIstate(unsigned subsessionIndex);
  void setFinalAVIstate();

  void afterGettingFrame(unsigned packetDataSize,
			 struct timeval presentationTime);
  void onSourceClosure();

  UsageEnvironment& envir() const { return fOurSink.envir(); }

public:
  SubsessionBuffer *fBuffer, *fPrevBuffer;
  AVIFileSink& fOurSink;
  MediaSubsession& fOurSubsession;

  unsigned short fLastPacketRTPSeqNum;
  Boolean fOurSourceIsActive;
  struct timeval fPrevPresentationTime;
  unsigned fMaxBytesPerSecond;
  Boolean fIsVideo, fIsAudio, fIsByteSwappedAudio;
  unsigned fAVISubsessionTag;
  unsigned fAVICodecHandlerType;
  unsigned fAVISamplingFrequency; // for audio
  u_int16_t fWAVCodecTag; // for audio
  unsigned fAVIScale;
  unsigned fAVIRate;
  unsigned fAVISize;
  unsigned fNumFrames;
  unsigned fSTRHFrameCountPosition;

private:
  void useFrame(SubsessionBuffer& buffer);
};

////////// AVIFileSink implementation //////////

AVIFileSink::AVIFileSink(UsageEnvironment& env,
			 MediaSession& inputSession,
			 char const* outputFileName,
			 unsigned bufferSize,
			 unsigned short movieWidth, unsigned short movieHeight,
			 unsigned movieFPS, Boolean packetLossCompensate)
  : Medium(env), fInputSession(inputSession),
    fBufferSize(bufferSize), fPacketLossCompensate(packetLossCompensate),
    fAreCurrentlyBeingPlayed(False), fNumSubsessions(0), fNumBytesWritten(0),
    fHaveCompletedOutputFile(False),
    fMovieWidth(movieWidth), fMovieHeight(movieHeight), fMovieFPS(movieFPS) {
  fOutFid = OpenOutputFile(env, outputFileName);
  if (fOutFid == NULL) return;

  // Set up I/O state for each input subsession:
  MediaSubsessionIterator iter(fInputSession);
  MediaSubsession* subsession;
  while ((subsession = iter.next()) != NULL) {
    // Ignore subsessions without a data source:
    FramedSource* subsessionSource = subsession->readSource();
    if (subsessionSource == NULL) continue;

    // If "subsession's" SDP description specified screen dimension
    // or frame rate parameters, then use these.
    if (subsession->videoWidth() != 0) {
      fMovieWidth = subsession->videoWidth();
    }
    if (subsession->videoHeight() != 0) {
      fMovieHeight = subsession->videoHeight();
    }
    if (subsession->videoFPS() != 0) {
      fMovieFPS = subsession->videoFPS();
    }

    AVISubsessionIOState* ioState
      = new AVISubsessionIOState(*this, *subsession);
    subsession->miscPtr = (void*)ioState;

    // Also set a 'BYE' handler for this subsession's RTCP instance:
    if (subsession->rtcpInstance() != NULL) {
      subsession->rtcpInstance()->setByeHandler(onRTCPBye, ioState);
    }

    ++fNumSubsessions;
  }

  // Begin by writing an AVI header:
  addFileHeader_AVI();
}

AVIFileSink::~AVIFileSink() {
  completeOutputFile();

  // Then, delete each active "AVISubsessionIOState":
  MediaSubsessionIterator iter(fInputSession);
  MediaSubsession* subsession;
  while ((subsession = iter.next()) != NULL) {
    AVISubsessionIOState* ioState
      = (AVISubsessionIOState*)(subsession->miscPtr);
    if (ioState == NULL) continue;

    delete ioState;
  }

  // Finally, close our output file:
  CloseOutputFile(fOutFid);
}

AVIFileSink* AVIFileSink
::createNew(UsageEnvironment& env, MediaSession& inputSession,
	    char const* outputFileName,
	    unsigned bufferSize,
	    unsigned short movieWidth, unsigned short movieHeight,
	    unsigned movieFPS, Boolean packetLossCompensate) {
  AVIFileSink* newSink =
    new AVIFileSink(env, inputSession, outputFileName, bufferSize,
		    movieWidth, movieHeight, movieFPS, packetLossCompensate);
  if (newSink == NULL || newSink->fOutFid == NULL) {
    Medium::close(newSink);
    return NULL;
  }

  return newSink;
}

Boolean AVIFileSink::startPlaying(afterPlayingFunc* afterFunc,
				  void* afterClientData) {
  // Make sure we're not already being played:
  if (fAreCurrentlyBeingPlayed) {
    envir().setResultMsg("This sink has already been played");
    return False;
  }

  fAreCurrentlyBeingPlayed = True;
  fAfterFunc = afterFunc;
  fAfterClientData = afterClientData;

  return continuePlaying();
}

Boolean AVIFileSink::continuePlaying() {
  // Run through each of our input session's 'subsessions',
  // asking for a frame from each one:
  Boolean haveActiveSubsessions = False;
  MediaSubsessionIterator iter(fInputSession);
  MediaSubsession* subsession;
  while ((subsession = iter.next()) != NULL) {
    FramedSource* subsessionSource = subsession->readSource();
    if (subsessionSource == NULL) continue;

    if (subsessionSource->isCurrentlyAwaitingData()) continue;

    AVISubsessionIOState* ioState
      = (AVISubsessionIOState*)(subsession->miscPtr);
    if (ioState == NULL) continue;

    haveActiveSubsessions = True;
    unsigned char* toPtr = ioState->fBuffer->dataEnd();
    unsigned toSize = ioState->fBuffer->bytesAvailable();
    subsessionSource->getNextFrame(toPtr, toSize,
				   afterGettingFrame, ioState,
				   onSourceClosure, ioState);
  }
  if (!haveActiveSubsessions) {
    envir().setResultMsg("No subsessions are currently active");
    return False;
  }

  return True;
}

void AVIFileSink
::afterGettingFrame(void* clientData, unsigned packetDataSize,
		    unsigned /*numTruncatedBytes*/,
		    struct timeval presentationTime,
		    unsigned /*durationInMicroseconds*/) {
  AVISubsessionIOState* ioState = (AVISubsessionIOState*)clientData;
  ioState->afterGettingFrame(packetDataSize, presentationTime);
}

void AVIFileSink::onSourceClosure(void* clientData) {
  AVISubsessionIOState* ioState = (AVISubsessionIOState*)clientData;
  ioState->onSourceClosure();
}

void AVIFileSink::onSourceClosure1() {
  // Check whether *all* of the subsession sources have closed.
  // If not, do nothing for now:
  MediaSubsessionIterator iter(fInputSession);
  MediaSubsession* subsession;
  while ((subsession = iter.next()) != NULL) {
    AVISubsessionIOState* ioState
      = (AVISubsessionIOState*)(subsession->miscPtr);
    if (ioState == NULL) continue;

    if (ioState->fOurSourceIsActive) return; // this source hasn't closed
  }

  completeOutputFile();

  // Call our specified 'after' function:
  if (fAfterFunc != NULL) {
    (*fAfterFunc)(fAfterClientData);
  }
}

void AVIFileSink::onRTCPBye(void* clientData) {
  AVISubsessionIOState* ioState = (AVISubsessionIOState*)clientData;

  struct timeval timeNow;
  gettimeofday(&timeNow, NULL);
  unsigned secsDiff
    = timeNow.tv_sec - ioState->fOurSink.fStartTime.tv_sec;

  MediaSubsession& subsession = ioState->fOurSubsession;
  ioState->envir() << "Received RTCP \"BYE\" on \""
		   << subsession.mediumName()
		   << "/" << subsession.codecName()
		   << "\" subsession (after "
		   << secsDiff << " seconds)\n";

  // Handle the reception of a RTCP "BYE" as if the source had closed:
  ioState->onSourceClosure();
}

void AVIFileSink::completeOutputFile() {
  if (fHaveCompletedOutputFile || fOutFid == NULL) return;

  // Update various AVI 'size' fields to take account of the codec data that
  // we've now written to the file:
  unsigned maxBytesPerSecond = 0;
  unsigned numVideoFrames = 0;
  unsigned numAudioFrames = 0;

  //// Subsession-specific fields:
  MediaSubsessionIterator iter(fInputSession);
  MediaSubsession* subsession;
  while ((subsession = iter.next()) != NULL) {
    AVISubsessionIOState* ioState
      = (AVISubsessionIOState*)(subsession->miscPtr);
    if (ioState == NULL) continue;

    maxBytesPerSecond += ioState->fMaxBytesPerSecond;

    setWord(ioState->fSTRHFrameCountPosition, ioState->fNumFrames);
    if (ioState->fIsVideo) numVideoFrames = ioState->fNumFrames;
    else if (ioState->fIsAudio) numAudioFrames = ioState->fNumFrames;
  }

  //// Global fields:
  fRIFFSizeValue += fNumBytesWritten;
  setWord(fRIFFSizePosition, fRIFFSizeValue);

  setWord(fAVIHMaxBytesPerSecondPosition, maxBytesPerSecond);
  setWord(fAVIHFrameCountPosition,
	  numVideoFrames > 0 ? numVideoFrames : numAudioFrames);

  fMoviSizeValue += fNumBytesWritten;
  setWord(fMoviSizePosition, fMoviSizeValue);

  // We're done:
  fHaveCompletedOutputFile = True;
}

////////// AVISubsessionIOState implementation ///////////

AVISubsessionIOState::AVISubsessionIOState(AVIFileSink& sink,
				     MediaSubsession& subsession)
  : fOurSink(sink), fOurSubsession(subsession),
    fMaxBytesPerSecond(0), fIsVideo(False), fIsAudio(False), fIsByteSwappedAudio(False), fNumFrames(0) {
  fBuffer = new SubsessionBuffer(fOurSink.fBufferSize);
  fPrevBuffer = sink.fPacketLossCompensate
    ? new SubsessionBuffer(fOurSink.fBufferSize) : NULL;

  FramedSource* subsessionSource = subsession.readSource();
  fOurSourceIsActive = subsessionSource != NULL;

  fPrevPresentationTime.tv_sec = 0;
  fPrevPresentationTime.tv_usec = 0;
}

AVISubsessionIOState::~AVISubsessionIOState() {
  delete fBuffer; delete fPrevBuffer;
}

void AVISubsessionIOState::setAVIstate(unsigned subsessionIndex) {
  fIsVideo = strcmp(fOurSubsession.mediumName(), "video") == 0;
  fIsAudio = strcmp(fOurSubsession.mediumName(), "audio") == 0;

  if (fIsVideo) {
    fAVISubsessionTag
      = fourChar('0'+subsessionIndex/10,'0'+subsessionIndex%10,'d','c');
    if (strcmp(fOurSubsession.codecName(), "JPEG") == 0) {
      fAVICodecHandlerType = fourChar('m','j','p','g');
    } else if (strcmp(fOurSubsession.codecName(), "MP4V-ES") == 0) {
      fAVICodecHandlerType = fourChar('D','I','V','X');
    } else if (strcmp(fOurSubsession.codecName(), "MPV") == 0) {
      fAVICodecHandlerType = fourChar('m','p','g','1'); // what about MPEG-2?
    } else if (strcmp(fOurSubsession.codecName(), "H263-1998") == 0 ||
	       strcmp(fOurSubsession.codecName(), "H263-2000") == 0) {
      fAVICodecHandlerType = fourChar('H','2','6','3');
    } else if (strcmp(fOurSubsession.codecName(), "H264") == 0) {
      fAVICodecHandlerType = fourChar('H','2','6','4');
    } else {
      fAVICodecHandlerType = fourChar('?','?','?','?');
    }
    fAVIScale = 1; // ??? #####
    fAVIRate = fOurSink.fMovieFPS; // ??? #####
    fAVISize = fOurSink.fMovieWidth*fOurSink.fMovieHeight*3; // ??? #####
  } else if (fIsAudio) {
    fIsByteSwappedAudio = False; // by default
    fAVISubsessionTag
      = fourChar('0'+subsessionIndex/10,'0'+subsessionIndex%10,'w','b');
    fAVICodecHandlerType = 1; // ??? ####
    unsigned numChannels = fOurSubsession.numChannels();
    fAVISamplingFrequency = fOurSubsession.rtpTimestampFrequency(); // default
    if (strcmp(fOurSubsession.codecName(), "L16") == 0) {
      fIsByteSwappedAudio = True; // need to byte-swap data before writing it
      fWAVCodecTag = 0x0001;
      fAVIScale = fAVISize = 2*numChannels; // 2 bytes/sample
      fAVIRate = fAVISize*fAVISamplingFrequency;
    } else if (strcmp(fOurSubsession.codecName(), "L8") == 0) {
      fWAVCodecTag = 0x0001;
      fAVIScale = fAVISize = numChannels; // 1 byte/sample
      fAVIRate = fAVISize*fAVISamplingFrequency;
    } else if (strcmp(fOurSubsession.codecName(), "PCMA") == 0) {
      fWAVCodecTag = 0x0006;
      fAVIScale = fAVISize = numChannels; // 1 byte/sample
      fAVIRate = fAVISize*fAVISamplingFrequency;
    } else if (strcmp(fOurSubsession.codecName(), "PCMU") == 0) {
      fWAVCodecTag = 0x0007;
      fAVIScale = fAVISize = numChannels; // 1 byte/sample
      fAVIRate = fAVISize*fAVISamplingFrequency;
    } else if (strcmp(fOurSubsession.codecName(), "MPA") == 0) {
      fWAVCodecTag = 0x0050;
      fAVIScale = fAVISize = 1;
      fAVIRate = 0; // ??? #####
    } else {
      fWAVCodecTag = 0x0001; // ??? #####
      fAVIScale = fAVISize = 1;
      fAVIRate = 0; // ??? #####
    }
  } else { // unknown medium
    fAVISubsessionTag
      = fourChar('0'+subsessionIndex/10,'0'+subsessionIndex%10,'?','?');
    fAVICodecHandlerType = 0;
    fAVIScale = fAVISize = 1;
    fAVIRate = 0; // ??? #####
  }
}

void AVISubsessionIOState::afterGettingFrame(unsigned packetDataSize,
					  struct timeval presentationTime) {
  // Begin by checking whether there was a gap in the RTP stream.
  // If so, try to compensate for this (if desired):
  unsigned short rtpSeqNum
    = fOurSubsession.rtpSource()->curPacketRTPSeqNum();
  if (fOurSink.fPacketLossCompensate && fPrevBuffer->bytesInUse() > 0) {
    short seqNumGap = rtpSeqNum - fLastPacketRTPSeqNum;
    for (short i = 1; i < seqNumGap; ++i) {
      // Insert a copy of the previous frame, to compensate for the loss:
      useFrame(*fPrevBuffer);
    }
  }
  fLastPacketRTPSeqNum = rtpSeqNum;

  // Now, continue working with the frame that we just got
  if (fBuffer->bytesInUse() == 0) {
    fBuffer->setPresentationTime(presentationTime);
  }
  fBuffer->addBytes(packetDataSize);

  useFrame(*fBuffer);
  if (fOurSink.fPacketLossCompensate) {
    // Save this frame, in case we need it for recovery:
    SubsessionBuffer* tmp = fPrevBuffer; // assert: != NULL
    fPrevBuffer = fBuffer;
    fBuffer = tmp;
  }
  fBuffer->reset(); // for the next input

  // Now, try getting more frames:
  fOurSink.continuePlaying();
}

void AVISubsessionIOState::useFrame(SubsessionBuffer& buffer) {
  unsigned char* const frameSource = buffer.dataStart();
  unsigned const frameSize = buffer.bytesInUse();
  struct timeval const& presentationTime = buffer.presentationTime();
  if (fPrevPresentationTime.tv_usec != 0||fPrevPresentationTime.tv_sec != 0) {
    int uSecondsDiff
      = (presentationTime.tv_sec - fPrevPresentationTime.tv_sec)*1000000
      + (presentationTime.tv_usec - fPrevPresentationTime.tv_usec);
    if (uSecondsDiff > 0) {
      unsigned bytesPerSecond = (unsigned)((frameSize*1000000.0)/uSecondsDiff);
      if (bytesPerSecond > fMaxBytesPerSecond) {
	fMaxBytesPerSecond = bytesPerSecond;
      }
    }
  }
  fPrevPresentationTime = presentationTime;

  if (fIsByteSwappedAudio) {
    // We need to swap the 16-bit audio samples from big-endian
    // to little-endian order, before writing them to a file:
    for (unsigned i = 0; i < frameSize; i += 2) {
      unsigned char tmp = frameSource[i];
      frameSource[i] = frameSource[i+1];
      frameSource[i+1] = tmp;
    }
  }

  // Write the data into the file:
  fOurSink.fNumBytesWritten += fOurSink.addWord(fAVISubsessionTag);
  fOurSink.fNumBytesWritten += fOurSink.addWord(frameSize);
  fwrite(frameSource, 1, frameSize, fOurSink.fOutFid);
  fOurSink.fNumBytesWritten += frameSize;
  // Pad to an even length:
  if (frameSize%2 != 0) fOurSink.fNumBytesWritten += fOurSink.addByte(0);

  ++fNumFrames;
}

void AVISubsessionIOState::onSourceClosure() {
  fOurSourceIsActive = False;
  fOurSink.onSourceClosure1();
}

////////// AVI-specific implementation //////////

unsigned AVIFileSink::addWord(unsigned word) {
  // Add "word" to the file in little-endian order:
  addByte(word); addByte(word>>8);
  addByte(word>>16); addByte(word>>24);

  return 4;
}

unsigned AVIFileSink::addHalfWord(unsigned short halfWord) {
  // Add "halfWord" to the file in little-endian order:
  addByte((unsigned char)halfWord); addByte((unsigned char)(halfWord>>8));

  return 2;
}

unsigned AVIFileSink::addZeroWords(unsigned numWords) {
  for (unsigned i = 0; i < numWords; ++i) {
    addWord(0);
  }

  return numWords*4;
}

unsigned AVIFileSink::add4ByteString(char const* str) {
  addByte(str[0]); addByte(str[1]); addByte(str[2]);
  addByte(str[3] == '\0' ? ' ' : str[3]); // e.g., for "AVI "

  return 4;
}

void AVIFileSink::setWord(unsigned filePosn, unsigned size) {
  do {
    if (SeekFile64(fOutFid, filePosn, SEEK_SET) < 0) break;
    addWord(size);
    if (SeekFile64(fOutFid, 0, SEEK_END) < 0) break; // go back to where we were

    return;
  } while (0);

  // One of the SeekFile64()s failed, probable because we're not a seekable file
  envir() << "AVIFileSink::setWord(): SeekFile64 failed (err "
	  << envir().getErrno() << ")\n";
}

// Methods for writing particular file headers.  Note the following macros:

#define addFileHeader(tag,name) \
    unsigned AVIFileSink::addFileHeader_##name() { \
        add4ByteString("" #tag ""); \
        unsigned headerSizePosn = (unsigned)TellFile64(fOutFid); addWord(0); \
        add4ByteString("" #name ""); \
        unsigned ignoredSize = 8;/*don't include size of tag or size fields*/ \
        unsigned size = 12

#define addFileHeader1(name) \
    unsigned AVIFileSink::addFileHeader_##name() { \
        add4ByteString("" #name ""); \
        unsigned headerSizePosn = (unsigned)TellFile64(fOutFid); addWord(0); \
        unsigned ignoredSize = 8;/*don't include size of name or size fields*/ \
        unsigned size = 8

#define addFileHeaderEnd \
  setWord(headerSizePosn, size-ignoredSize); \
  return size; \
}

addFileHeader(RIFF,AVI);
    size += addFileHeader_hdrl();
    size += addFileHeader_movi();
    fRIFFSizePosition = headerSizePosn;
    fRIFFSizeValue = size-ignoredSize;
addFileHeaderEnd;

addFileHeader(LIST,hdrl);
    size += addFileHeader_avih();

    // Then, add a "strl" header for each subsession (stream):
    // (Make the video subsession (if any) come before the audio subsession.)
    unsigned subsessionCount = 0;
    MediaSubsessionIterator iter(fInputSession);
    MediaSubsession* subsession;
    while ((subsession = iter.next()) != NULL) {
      fCurrentIOState = (AVISubsessionIOState*)(subsession->miscPtr);
      if (fCurrentIOState == NULL) continue;
      if (strcmp(subsession->mediumName(), "video") != 0) continue;

      fCurrentIOState->setAVIstate(subsessionCount++);
      size += addFileHeader_strl();
    }
    iter.reset();
    while ((subsession = iter.next()) != NULL) {
      fCurrentIOState = (AVISubsessionIOState*)(subsession->miscPtr);
      if (fCurrentIOState == NULL) continue;
      if (strcmp(subsession->mediumName(), "video") == 0) continue;

      fCurrentIOState->setAVIstate(subsessionCount++);
      size += addFileHeader_strl();
    }

    // Then add another JUNK entry
    ++fJunkNumber;
    size += addFileHeader_JUNK();
addFileHeaderEnd;

#define AVIF_HASINDEX           0x00000010 // Index at end of file?
#define AVIF_MUSTUSEINDEX       0x00000020
#define AVIF_ISINTERLEAVED      0x00000100
#define AVIF_TRUSTCKTYPE        0x00000800 // Use CKType to find key frames?
#define AVIF_WASCAPTUREFILE     0x00010000
#define AVIF_COPYRIGHTED        0x00020000

addFileHeader1(avih);
    unsigned usecPerFrame = fMovieFPS == 0 ? 0 : 1000000/fMovieFPS;
    size += addWord(usecPerFrame); // dwMicroSecPerFrame
    fAVIHMaxBytesPerSecondPosition = (unsigned)TellFile64(fOutFid);
    size += addWord(0); // dwMaxBytesPerSec (fill in later)
    size += addWord(0); // dwPaddingGranularity
    size += addWord(AVIF_TRUSTCKTYPE|AVIF_HASINDEX|AVIF_ISINTERLEAVED); // dwFlags
    fAVIHFrameCountPosition = (unsigned)TellFile64(fOutFid);
    size += addWord(0); // dwTotalFrames (fill in later)
    size += addWord(0); // dwInitialFrame
    size += addWord(fNumSubsessions); // dwStreams
    size += addWord(fBufferSize); // dwSuggestedBufferSize
    size += addWord(fMovieWidth); // dwWidth
    size += addWord(fMovieHeight); // dwHeight
    size += addZeroWords(4); // dwReserved
addFileHeaderEnd;

addFileHeader(LIST,strl);
    size += addFileHeader_strh();
    size += addFileHeader_strf();
    fJunkNumber = 0;
    size += addFileHeader_JUNK();
addFileHeaderEnd;

addFileHeader1(strh);
    size += add4ByteString(fCurrentIOState->fIsVideo ? "vids" :
			   fCurrentIOState->fIsAudio ? "auds" :
			   "????"); // fccType
    size += addWord(fCurrentIOState->fAVICodecHandlerType); // fccHandler
    size += addWord(0); // dwFlags
    size += addWord(0); // wPriority + wLanguage
    size += addWord(0); // dwInitialFrames
    size += addWord(fCurrentIOState->fAVIScale); // dwScale
    size += addWord(fCurrentIOState->fAVIRate); // dwRate
    size += addWord(0); // dwStart
    fCurrentIOState->fSTRHFrameCountPosition = (unsigned)TellFile64(fOutFid);
    size += addWord(0); // dwLength (fill in later)
    size += addWord(fBufferSize); // dwSuggestedBufferSize
    size += addWord((unsigned)-1); // dwQuality
    size += addWord(fCurrentIOState->fAVISize); // dwSampleSize
    size += addWord(0); // rcFrame (start)
    if (fCurrentIOState->fIsVideo) {
        size += addHalfWord(fMovieWidth);
        size += addHalfWord(fMovieHeight);
    } else {
        size += addWord(0);
    }
addFileHeaderEnd;

addFileHeader1(strf);
    if (fCurrentIOState->fIsVideo) {
      // Add a BITMAPINFO header:
      unsigned extraDataSize = 0;
      size += addWord(10*4 + extraDataSize); // size
      size += addWord(fMovieWidth);
      size += addWord(fMovieHeight);
      size += addHalfWord(1); // planes
      size += addHalfWord(24); // bits-per-sample #####
      size += addWord(fCurrentIOState->fAVICodecHandlerType); // compr. type
      size += addWord(fCurrentIOState->fAVISize);
      size += addZeroWords(4); // ??? #####
      // Later, add extra data here (if any) #####
    } else if (fCurrentIOState->fIsAudio) {
      // Add a WAVFORMATEX header:
      size += addHalfWord(fCurrentIOState->fWAVCodecTag);
      unsigned numChannels = fCurrentIOState->fOurSubsession.numChannels();
      size += addHalfWord(numChannels);
      size += addWord(fCurrentIOState->fAVISamplingFrequency);
      size += addWord(fCurrentIOState->fAVIRate); // bytes per second
      size += addHalfWord(fCurrentIOState->fAVISize); // block alignment
      unsigned bitsPerSample = (fCurrentIOState->fAVISize*8)/numChannels;
      size += addHalfWord(bitsPerSample);
      if (strcmp(fCurrentIOState->fOurSubsession.codecName(), "MPA") == 0) {
	// Assume MPEG layer II audio (not MP3): #####
	size += addHalfWord(22); // wav_extra_size
	size += addHalfWord(2); // fwHeadLayer
	size += addWord(8*fCurrentIOState->fAVIRate); // dwHeadBitrate #####
	size += addHalfWord(numChannels == 2 ? 1: 8); // fwHeadMode
	size += addHalfWord(0); // fwHeadModeExt
	size += addHalfWord(1); // wHeadEmphasis
	size += addHalfWord(16); // fwHeadFlags
	size += addWord(0); // dwPTSLow
	size += addWord(0); // dwPTSHigh
      }
    }
addFileHeaderEnd;

#define AVI_MASTER_INDEX_SIZE   256

addFileHeader1(JUNK);
    if (fJunkNumber == 0) {
      size += addHalfWord(4); // wLongsPerEntry
      size += addHalfWord(0); // bIndexSubType + bIndexType
      size += addWord(0); // nEntriesInUse #####
      size += addWord(fCurrentIOState->fAVISubsessionTag); // dwChunkId
      size += addZeroWords(2); // dwReserved
      size += addZeroWords(AVI_MASTER_INDEX_SIZE*4);
    } else {
      size += add4ByteString("odml");
      size += add4ByteString("dmlh");
      unsigned wtfCount = 248;
      size += addWord(wtfCount); // ??? #####
      size += addZeroWords(wtfCount/4);
    }
addFileHeaderEnd;

addFileHeader(LIST,movi);
    fMoviSizePosition = headerSizePosn;
    fMoviSizeValue = size-ignoredSize;
addFileHeaderEnd;

redpajama_set_name: RedPajamaGithub


text:
package com.falkirks;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(50);
        for (int i = 0; i < 50; i++) {
            Runnable worker = new Sender("localhost", 19132, i);
            executor.execute(worker);
        }
        executor.shutdown();
        while (!executor.isTerminated());
        System.out.println("Finished all threads");

    }
}


text:
#pragma once
#include <aws/acm/ACM_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace ACM
{
namespace Model
{
  enum class FailureReason
  {
    NOT_SET,
    NO_AVAILABLE_CONTACTS,
    ADDITIONAL_VERIFICATION_REQUIRED,
    DOMAIN_NOT_ALLOWED,
    INVALID_PUBLIC_DOMAIN,
    CAA_ERROR,
    PCA_LIMIT_EXCEEDED,
    PCA_INVALID_ARN,
    PCA_INVALID_STATE,
    PCA_REQUEST_FAILED,
    PCA_RESOURCE_NOT_FOUND,
    PCA_INVALID_ARGS,
    OTHER
  };

namespace FailureReasonMapper
{
AWS_ACM_API FailureReason GetFailureReasonForName(const Aws::String& name);

AWS_ACM_API Aws::String GetNameForFailureReason(FailureReason value);
} // namespace FailureReasonMapper
} // namespace Model
} // namespace ACM
} // namespace Aws


text:
package controlador.dto;
// Generated 31-ene-2017 13:00:46 by Hibernate Tools 4.3.1

import java.util.HashSet;
import java.util.Set;

/**
 * Alojamiento's DTO done by Hibernate.
 */
public class Alojamiento  implements java.io.Serializable {
    private String nombre;
    private String direccionSocial;
    private String razonSocial;
    private String telefonoContacto;
    private String descripcion;
    private int valoracion;
    private String fechaApertura;
    private Integer numHabitaciones;
    private String provincia;
    private Set<Habitacion> setHabitaciones;

    public Alojamiento(String nombre, String razonSocial, String fechaApertura) {
        this.nombre = nombre;
        this.razonSocial = razonSocial;
        this.fechaApertura = fechaApertura;
        setHabitaciones = new HashSet<>();
    }

    public Alojamiento(String nombre, String direccionSocial, String razonSocial, String telefonoContacto, String descripcion, int valoracion, String fechaApertura, Integer numHabitaciones, String provincia, Set<Habitacion> setHabitaciones) {
       this.nombre = nombre;
       this.direccionSocial = direccionSocial;
       this.razonSocial = razonSocial;
       this.telefonoContacto = telefonoContacto;
       this.descripcion = descripcion;
       this.valoracion = valoracion;
       this.fechaApertura = fechaApertura;
       this.numHabitaciones = numHabitaciones;
       this.provincia = provincia;
       this.setHabitaciones = setHabitaciones;
    }

    public String getNombre() {
        return this.nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
    public String getDireccionSocial() {
        return this.direccionSocial;
    }

    public void setDireccionSocial(String direccionSocial) {
        this.direccionSocial = direccionSocial;
    }
    public String getRazonSocial() {
        return this.razonSocial;
    }

    public void setRazonSocial(String razonSocial) {
        this.razonSocial = razonSocial;
    }
    public String getTelefonoContacto() {
        return this.telefonoContacto;
    }

    public void setTelefonoContacto(String telefonoContacto) {
        this.telefonoContacto = telefonoContacto;
    }
    public String getDescripcion() {
        return this.descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }
    public int getValoracion() {
        return this.valoracion;
    }

    public void setValoracion(int valoracion) {
        this.valoracion = valoracion;
    }
    public String getFechaApertura() {
        return this.fechaApertura;
    }

    public void setFechaApertura(String fechaApertura) {
        this.fechaApertura = fechaApertura;
    }
    public Integer getNumHabitaciones() {
        return this.numHabitaciones;
    }

    public void setNumHabitaciones(Integer numHabitaciones) {
        this.numHabitaciones = numHabitaciones;
    }
    public String getProvincia() {
        return this.provincia;
    }

    public void setProvincia(String provincia) {
        this.provincia = provincia;
    }

    /**
     * @return the setHabitaciones
     */
    public Set<Habitacion> getSetHabitaciones() {
        return setHabitaciones;
    }

    /**
     * @param setHabitaciones the setHabitaciones to set
     */
    public void setSetHabitaciones(Set<Habitacion> setHabitaciones) {
        this.setHabitaciones = setHabitaciones;
    }

    @Override
    public String toString() {
        return this.nombre;
    }
}


text:
<definitions xmlns="http://ws.apache.org/ns/synapse">
    <sequence name="main">
        <in>
            <payloadFactory>
                <format>
                    <m:messageBeforeLoopBack xmlns:m="http://services.samples">
                        <m:messageBeforeLoopBackSymbol>
                            <m:symbolBeforeLoopBack>$1</m:symbolBeforeLoopBack>
                        </m:messageBeforeLoopBackSymbol>
                    </m:messageBeforeLoopBack>
                </format>
                <args>
                    <arg xmlns:m0="http://services.samples"
                         evaluator="xml"
                         expression="//m0:symbol/text()"/>
                </args>
            </payloadFactory>

            <loopback/>

            <payloadFactory>
                <format>
                    <m:messageAfterLoopBack xmlns:m="http://services.samples">
                        <m:messageAfterLoopBackSymbol>
                            <m:symbolAfterLoopBack>$1</m:symbolAfterLoopBack>
                        </m:messageAfterLoopBackSymbol>
                    </m:messageAfterLoopBack>
                </format>
                <args>
                    <arg xmlns:m0="http://services.samples"
                         evaluator="xml"
                         expression="//m0:symbolBeforeLoopBack/text()"/>
                </args>
            </payloadFactory>
            <loopback/>
        </in>
        <out>
            <send/>
        </out>
    </sequence>
</definitions>


text:
Тест Lazy Load

        <form class="form-horizontal" role="form">

                Title post
                <input type="text" class="form-control" ng-model="post.title" placeholder="Enter title"
                       maxlength="128">

                Content post
                <textarea ng-model="post.content" class="form-control" placeholder="Enter content" rows="6"
                          maxlength="500"></textarea>

You can use html tags.

            Select status:
            <button type="button" class="btn btn-default" ng-model="post.status" data-animation="am-flip-x"
                    bs-options="icon.value as icon.label for icon in icons" bs-select>
                Action
            </button>

                <button type="submit" ng-click="save()" class="btn btn-success">Submit</button>
                Cancel

        </form>

Title: {{post.title}}

Content:

    JSON DATA

{{post | json}}


text:
#region License

#endregion

using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
using Spring.Social;

namespace CSharp.Meetup.Api
{
    /// <summary>
    /// The exception that is thrown when a error occurs while consuming Meetup REST API.
    /// </summary>
    /// <author>Scott Smith</author>
    [Serializable]
    public class MeetupApiException : SocialException
    {
        private readonly MeetupApiError _error;

        /// <summary>
        /// Gets the Meetup error.
        /// </summary>
        public MeetupApiError Error
        {
            get { return _error; }
        }

        /// <summary>
        /// Creates a new instance of the <see cref="MeetupApiException"/> class.
        /// </summary>
        /// <param name="message">A message about the exception.</param>
        /// <param name="error">The Meetup error.</param>
        public MeetupApiException(string message, MeetupApiError error)
            : base(message)
        {
            _error = error;
        }

        /// <summary>
        /// Creates a new instance of the <see cref="MeetupApiException"/> class.
        /// </summary>
        /// <param name="message">A message about the exception.</param>
        /// <param name="innerException">The inner exception that is the cause of the current exception.</param>
        public MeetupApiException(string message, Exception innerException)
            : base(message, innerException)
        {
            _error = MeetupApiError.ServerError;
        }

        /// <summary>
        /// Creates a new instance of the <see cref="MeetupApiException"/> class.
        /// </summary>
        /// <param name="info">
        /// The <see cref="System.Runtime.Serialization.SerializationInfo"/>
        /// that holds the serialized object data about the exception being thrown.
        /// </param>
        /// <param name="context">
        /// The <see cref="System.Runtime.Serialization.StreamingContext"/>
        /// that contains contextual information about the source or destination.
        /// </param>
        protected MeetupApiException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            if (info != null)
            {
                _error = (MeetupApiError)info.GetValue("Error", typeof(MeetupApiError));
            }
        }

        /// <summary>
        /// Populates the <see cref="System.Runtime.Serialization.SerializationInfo"/> with
        /// information about the exception.
        /// </summary>
        /// <param name="info">
        /// The <see cref="System.Runtime.Serialization.SerializationInfo"/> that holds
        /// the serialized object data about the exception being thrown.
        /// </param>
        /// <param name="context">
        /// The <see cref="System.Runtime.Serialization.StreamingContext"/> that contains contextual
        /// information about the source or destination.
        /// </param>
        [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);
            if (info != null)
            {
                info.AddValue("Error", _error);
            }
        }
    }
}


text:
package nvidia

import (
	"context"
	"fmt"
	"os"
	"os/exec"
	"strconv"
	"strings"

	"github.com/containerd/containerd/containers"
	"github.com/containerd/containerd/oci"
	specs "github.com/opencontainers/runtime-spec/specs-go"
)

// NvidiaCLI is the path to the Nvidia helper binary
const NvidiaCLI = "nvidia-container-cli"

// Capability specifies capabilities for the gpu inside the container
// Detailed explanation of options can be found:
// https://github.com/nvidia/nvidia-container-runtime#supported-driver-capabilities
type Capability string

const (
	// Compute capability
	Compute Capability = "compute"
	// Compat32 capability
	Compat32 Capability = "compat32"
	// Graphics capability
	Graphics Capability = "graphics"
	// Utility capability
	Utility Capability = "utility"
	// Video capability
	Video Capability = "video"
	// Display capability
	Display Capability = "display"
)

// AllCaps returns the complete list of supported Nvidia capabilties.
func AllCaps() []Capability {
	return []Capability{
		Compute,
		Compat32,
		Graphics,
		Utility,
		Video,
		Display,
	}
}

// WithGPUs adds NVIDIA gpu support to a container
func WithGPUs(opts ...Opts) oci.SpecOpts {
	return func(_ context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {
		c := &config{}
		for _, o := range opts {
			if err := o(c); err != nil {
				return err
			}
		}
		if c.OCIHookPath == "" {
			path, err := exec.LookPath("containerd")
			if err != nil {
				return err
			}
			c.OCIHookPath = path
		}
		nvidiaPath, err := exec.LookPath(NvidiaCLI)
		if err != nil {
			return err
		}
		if s.Hooks == nil {
			s.Hooks = &specs.Hooks{}
		}
		s.Hooks.Prestart = append(s.Hooks.Prestart, specs.Hook{
			Path: c.OCIHookPath,
			Args: append([]string{
				"containerd",
				"oci-hook",
				"--",
				nvidiaPath,
				// ensures the required kernel modules are properly loaded
				"--load-kmods",
			}, c.args()...),
			Env: os.Environ(),
		})
		return nil
	}
}

type config struct {
	Devices      []string
	Capabilities []Capability
	LoadKmods    bool
	LDCache      string
	LDConfig     string
	Requirements []string
	OCIHookPath  string
}

func (c *config) args() []string {
	var args []string

	if c.LoadKmods {
		args = append(args, "--load-kmods")
	}
	if c.LDCache != "" {
		args = append(args, fmt.Sprintf("--ldcache=%s", c.LDCache))
	}
	args = append(args,
		"configure",
	)
	if len(c.Devices) > 0 {
		args = append(args, fmt.Sprintf("--device=%s", strings.Join(c.Devices, ",")))
	}
	for _, c := range c.Capabilities {
		args = append(args, fmt.Sprintf("--%s", c))
	}
	if c.LDConfig != "" {
		args = append(args, fmt.Sprintf("--ldconfig=%s", c.LDConfig))
	}
	for _, r := range c.Requirements {
		args = append(args, fmt.Sprintf("--require=%s", r))
	}
	args = append(args, "--pid={{pid}}", "{{rootfs}}")
	return args
}

// Opts are options for configuring gpu support
type Opts func(*config) error

// WithDevices adds the provided device indexes to the container
func WithDevices(ids ...int) Opts {
	return func(c *config) error {
		for _, i := range ids {
			c.Devices = append(c.Devices, strconv.Itoa(i))
		}
		return nil
	}
}

// WithDeviceUUIDs adds the specific device UUID to the container
func WithDeviceUUIDs(uuids ...string) Opts {
	return func(c *config) error {
		c.Devices = append(c.Devices, uuids...)
		return nil
	}
}

// WithAllDevices adds all gpus to the container
func WithAllDevices(c *config) error {
	c.Devices = []string{"all"}
	return nil
}

// WithAllCapabilities adds all capabilities to the container for the gpus
func WithAllCapabilities(c *config) error {
	c.Capabilities = AllCaps()
	return nil
}

// WithCapabilities adds the specified capabilities to the container for the gpus
func WithCapabilities(caps ...Capability) Opts {
	return func(c *config) error {
		c.Capabilities = append(c.Capabilities, caps...)
		return nil
	}
}

// WithRequiredCUDAVersion sets the required cuda version
func WithRequiredCUDAVersion(major, minor int) Opts {
	return func(c *config) error {
		c.Requirements = append(c.Requirements, fmt.Sprintf("cuda>=%d.%d", major, minor))
		return nil
	}
}

// WithOCIHookPath sets the hook path for the binary
func WithOCIHookPath(path string) Opts {
	return func(c *config) error {
		c.OCIHookPath = path
		return nil
	}
}

// WithLookupOCIHookPath sets the hook path for the binary via a binary name
func WithLookupOCIHookPath(name string) Opts {
	return func(c *config) error {
		path, err := exec.LookPath(name)
		if err != nil {
			return err
		}
		c.OCIHookPath = path
		return nil
	}
}


text:
Projects

    {% for project in site.data.projects %}

        {{ project.name }}

    {% endfor %}


text:
<?php

use Phinx\Migration\AbstractMigration;

class AlterTablePostingsChangeDatetime extends AbstractMigration
{
    public function up()
    {
        $this->execute('ALTER TABLE "postings" ALTER COLUMN "datetime" TYPE TIMESTAMP WITH TIME ZONE');
    }

    public function down()
    {
        $this->execute('ALTER TABLE "postings" ALTER COLUMN "datetime" TYPE TIMESTAMP WITHOUT TIME ZONE');
    }
}


text:
<?php

/* Unregister WP widgets. */
add_action( 'widgets_init', 'hybrid_unregister_widgets' );

/* Register Hybrid widgets. */
add_action( 'widgets_init', 'hybrid_register_widgets' );

/**
 * Registers the core frameworks widgets.  These widgets typically overwrite the equivalent default WordPress
 * widget by extending the available options of the widget.
 *
 * @since 0.6.0
 * @access public
 * @uses register_widget() Registers individual widgets with WordPress
 * @link http://codex.wordpress.org/Function_Reference/register_widget
 * @return void
 */
function hybrid_register_widgets() {

	/* Load the archives widget class. */
	require_once( trailingslashit( HYBRID_CLASSES ) . 'widget-archives.php' );

	/* Load the authors widget class. */
	require_once( trailingslashit( HYBRID_CLASSES ) . 'widget-authors.php' );

	/* Load the bookmarks widget class. */
	if ( get_option( 'link_manager_enabled' ) )
		require_once( trailingslashit( HYBRID_CLASSES ) . 'widget-bookmarks.php' );

	/* Load the calendar widget class. */
	require_once( trailingslashit( HYBRID_CLASSES ) . 'widget-calendar.php' );

	/* Load the categories widget class. */
	require_once( trailingslashit( HYBRID_CLASSES ) . 'widget-categories.php' );

	/* Load the nav menu widget class. */
	require_once( trailingslashit( HYBRID_CLASSES ) . 'widget-nav-menu.php' );

	/* Load the pages widget class. */
	require_once( trailingslashit( HYBRID_CLASSES ) . 'widget-pages.php' );

	/* Load the search widget class. */
	require_once( trailingslashit( HYBRID_CLASSES ) . 'widget-search.php' );

	/* Load the tags widget class. */
	require_once( trailingslashit( HYBRID_CLASSES ) . 'widget-tags.php' );

	/* Register the archives widget. */
	register_widget( 'Hybrid_Widget_Archives' );

	/* Register the authors widget. */
	register_widget( 'Hybrid_Widget_Authors' );

	/* Register the bookmarks widget. */
	if ( get_option( 'link_manager_enabled' ) )
		register_widget( 'Hybrid_Widget_Bookmarks' );

	/* Register the calendar widget. */
	register_widget( 'Hybrid_Widget_Calendar' );

	/* Register the categories widget. */
	register_widget( 'Hybrid_Widget_Categories' );

	/* Register the nav menu widget. */
	register_widget( 'Hybrid_Widget_Nav_Menu' );

	/* Register the pages widget. */
	register_widget( 'Hybrid_Widget_Pages' );

	/* Register the search widget. */
	register_widget( 'Hybrid_Widget_Search' );

	/* Register the tags widget. */
	register_widget( 'Hybrid_Widget_Tags' );
}

/**
 * Unregister default WordPress widgets that are replaced by the framework's widgets.  Widgets that
 * aren't replaced by the framework widgets are not unregistered.
 *
 * @since 0.3.2
 * @access public
 * @uses unregister_widget() Unregisters a registered widget.
 * @link http://codex.wordpress.org/Function_Reference/unregister_widget
 * @return void
 */
function hybrid_unregister_widgets() {

	/* Unregister the default WordPress widgets. */
	unregister_widget( 'WP_Widget_Archives' );
	unregister_widget( 'WP_Widget_Calendar' );
	unregister_widget( 'WP_Widget_Categories' );
	unregister_widget( 'WP_Widget_Links' );
	unregister_widget( 'WP_Nav_Menu_Widget' );
	unregister_widget( 'WP_Widget_Pages' );
	unregister_widget( 'WP_Widget_Search' );
	unregister_widget( 'WP_Widget_Tag_Cloud' );
}

?>


text:
<?php

if (!defined('CPG_NUKE')) { die("You can't access this file directly..."); }

define('ECARDS_PHP', true);
require("modules/" . $module_name . "/include/load.inc");

if (!USER_CAN_SEND_ECARDS) cpg_die(_ERROR, ACCESS_DENIED, __FILE__, __LINE__);
// ecard security fix
// $max_anon_ecards = (!isset($_COOKIE['ecard'])?1:($_COOKIE['ecard']);
$max_anon_ecards = 1;
// if (!isset($_COOKIE['ecard'])){
if (($_COOKIE['ecard'] != 0) && (USER_ID != 1)) {
	setcookie('ecard', $max_anon_ecards, 0, $MAIN_CFG['cookie']['path'], $MAIN_CFG['cookie']['domain']); // time()+60*60*24
}
// }
require_once("includes/nbbcode.php");

// init.inc $pid = intval($_GET['pid']);
// init.inc $album = $_GET['album'];
// init.inc $pos = intval($_GET['pos']);
$thisalbum= "a.aid = $album";
$sender_name = $_POST['sender_name'] ? $_POST['sender_name'] :  (isset($USER['name']) ? $USER['name'] : CPG_USERNAME);
$sender_email = $_POST['sender_email']? $_POST['sender_email'] : (isset($USER['email']) ? $USER['email'] : '');
$recipient_name = $_POST['recipient_name'];
$recipient_email = $_POST['recipient_email'];
$greetings = $_POST['greetings'];
$message = $_POST['message'];
$sender_email_warning = '';
$recipient_email_warning = '';

$result = $db->sql_query("SELECT * FROM {$CONFIG['TABLE_PICTURES']} AS p INNER JOIN {$CONFIG['TABLE_ALBUMS']} ON visibility IN (0,".USER_IN_GROUPS.") WHERE pid='".$pid."' GROUP BY pid");
if (!$db->sql_numrows($result)) cpg_die(_ERROR, NON_EXIST_AP);
$row = $db->sql_fetchrow($result);
$thumb_pic_url = get_pic_url($row, 'thumb');
// Check supplied email address
$valid_email_pattern = "#^[_\.0-9a-z\-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,6}$#";
$valid_sender_email = preg_match($valid_email_pattern, $sender_email);
$valid_recipient_email = preg_match($valid_email_pattern, $recipient_email);
$invalid_email = '' . INVALID_EMAIL . '';
if (!$valid_sender_email && count($_POST) > 0) $sender_email_warning = $invalid_email;
if (!$valid_recipient_email && count($_POST) > 0) $recipient_email_warning = $invalid_email;

// Create and send the e-card
if (count($_POST) > 0 && $valid_sender_email && $valid_recipient_email) {
	global $nukeurl, $CONFIG;

// mailer
	require("includes/classes/phpmailer.php");
	$mail = new PHPMailer();
	$mail->SetLanguage();
	$mail->From	 = $sender_email;
	$mail->FromName = $sender_name;
	$mail->AddAddress($recipient_email,$recipient_name);
	$mail->Priority = 3;
	$mail->Encoding = "8bit";
	$mail->CharSet = CHARSET;
	$mail->Subject = sprintf(E_ECARD_TITLE, $sender_name);
	if($MAIN_CFG['email']['smtp_on']){
		$mail->IsSMTP();   // set mailer to use SMTP
		$mail->Host = $MAIN_CFG['email']['smtphost'];
		if ($MAIN_CFG['email']['smtp_auth']){
			$mail->SMTPAuth = true;	 // turn on SMTP authentication
			$mail->Username = $MAIN_CFG['email']['smtp_uname'];  // SMTP username
			$mail->Password = $MAIN_CFG['email']['smtp_pass']; // SMTP password
		}
	} else {
		$mail->IsMail();
	}

	//$gallery_dir
	$gallery_url_prefix = $CONFIG['ecards_more_pic_target'];

	if ($CONFIG['make_intermediate'] && max($row['pwidth'], $row['pheight']) > $CONFIG['picture_width']) {
		$n_picname = get_pic_url($row, 'normal');
		$image = $row['filepath'].$CONFIG['normal_pfx'].$row['filename'];
	} else {
		$n_picname = get_pic_url($row, 'fullsize');
		$image = $row['filepath'].$row['filename'];
	}
	if (!stristr($n_picname, 'http:')) $n_picname = $CONFIG['ecards_more_pic_target'] . "$n_picname";

	$data = array(
		'rn' => $_POST['recipient_name'],
		'sn' => $_POST['sender_name'],
		'se' => $_POST['sender_email'],
		'p' => $n_picname,
		'g' => $greetings,
		'm' => $message,
	);
	$encoded_data = urlencode(base64_encode(serialize($data)));
	$params = array('{LANG_DIR}' => CPG_TEXT_DIR,
		'{TITLE}' => sprintf(E_ECARD_TITLE, $sender_name),
		'{CHARSET}' =>  _CHARSET,
		'{VIEW_ECARD_TGT}' => getlink("&file=displayecard&data=$encoded_data",false,1),
		'{VIEW_ECARD_LNK}' => VIEW_ECARD,
		'{PIC_URL}' => 'cid:the-image',
		'{IMG_PATH}' => $nukeurl.'/'.$THEME_DIR.'/images/' ,
		'{GREETINGS}' => $greetings,
		'{MESSAGE}' => nl2br(set_smilies($message, $nukeurl)),
		'{SENDER_EMAIL}' => $sender_email,
		'{SENDER_NAME}' => $sender_name,
		'{VIEW_MORE_TGT}' => getlink("",1,1),
		'{VIEW_MORE_LNK}' => VIEW_MORE_PICS,
	);
	$message = template_eval($template_ecard, $params);

	$mail->IsHTML(true);
	$mail->AltBody = strip_tags($message);
	$mail->Body	= $message;
	$ext = strtolower(substr($row['filename'],-3));
	if ($ext == "gif") {
		$type = "image/gif";
	} else if ($ext == "png") {
		$type = "image/png";
	} else {
		$type = "image/jpeg";
	}
	if (!$mail->AddEmbeddedImage($image, "the-image", "ecard.$ext", "base64", $type)) {
		cpg_die(_ERROR, $mail->ErrorInfo, __FILE__, __LINE__);
	}
	if (!$mail->Send()) {
		cpg_die(_ERROR, $mail->ErrorInfo, __FILE__, __LINE__);
		//cpg_die(_ERROR, SEND_FAILED, __FILE__, __LINE__);

	}
	url_refresh(getlink("&file=displayimage&album=$album&pos=$pos"));
	pageheader(E_TITLE);
	msg_box(INFO, SEND_SUCCESS, CONTINU, getlink("&file=displayimage&album=$album&pos=$pos"));
	pagefooter();
}

pageheader(E_TITLE);
starttable("100%");
echo '
<form method="post" name="post" action="'.getlink("&file=ecard&album=$album&pid=$pid&pos=$pos").'" enctype="multipart/form-data" accept-charset="utf-8">

'.E_TITLE.'

	'.FROM.'

	'._YOUR_NAME.'

		<input type="text" class="textinput" name="sender_name" value="'.$sender_name.'" style="width: 100%;" />

	'.YOUR_EMAIL.'

		<input type="text" class="textinput" name="sender_email" value="'.$sender_email.'" style="width: 100%;" />

		'.$sender_email_warning.'

	'.TO,'

	'.RCPT_NAME.'

		<input type="text" class="textinput" name="recipient_name" value="'.$recipient_name.'" style="width: 100%;" />

	'.RCPT_EMAIL.'

		<input type="text" class="textinput" name="recipient_email" value="'.$recipient_email.'" style="width: 100%;" />

		'.$recipient_email_warning.'

	'.GREETINGS.'

		<input type="text" class="textinput" name="greetings" value="'.$greetings.'" style="width: 100%;" />

	'.MESSAGE.'

		<textarea name="message" class="textinput" rows="8" cols="40" wrap="virtual" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);" style="width: 100%;">'.$message.'</textarea>

	'.smilies_table('onerow', 'message', 'post').'

	<input type="submit" class="button" value="'.E_TITLE.'" />

</form>';

endtable();
pagefooter();


text:
'use strict';

const models = require('./index');

/**
 * IaaS VM workload-specific backup item.
 *
 * @extends models['ProtectedItem']
 */
class AzureIaaSVMProtectedItem extends models['ProtectedItem'] {
  /**
   * Create a AzureIaaSVMProtectedItem.
   * @member {string} [friendlyName] Friendly name of the VM represented by
   * this backup item.
   * @member {string} [virtualMachineId] Fully qualified ARM ID of the virtual
   * machine represented by this item.
   * @member {string} [protectionStatus] Backup status of this backup item.
   * @member {string} [protectionState] Backup state of this backup item.
   * Possible values include: 'Invalid', 'IRPending', 'Protected',
   * 'ProtectionError', 'ProtectionStopped', 'ProtectionPaused'
   * @member {string} [healthStatus] Health status of protected item. Possible
   * values include: 'Passed', 'ActionRequired', 'ActionSuggested', 'Invalid'
   * @member {array} [healthDetails] Health details on this backup item.
   * @member {string} [lastBackupStatus] Last backup operation status. Possible
   * values: Healthy, Unhealthy.
   * @member {date} [lastBackupTime] Timestamp of the last backup operation on
   * this backup item.
   * @member {string} [protectedItemDataId] Data ID of the protected item.
   * @member {object} [extendedInfo] Additional information for this backup
   * item.
   * @member {date} [extendedInfo.oldestRecoveryPoint] The oldest backup copy
   * available for this backup item.
   * @member {number} [extendedInfo.recoveryPointCount] Number of backup copies
   * available for this backup item.
   * @member {boolean} [extendedInfo.policyInconsistent] Specifies if backup
   * policy associated with the backup item is inconsistent.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of AzureIaaSVMProtectedItem
   *
   * @returns {object} metadata of AzureIaaSVMProtectedItem
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'AzureIaaSVMProtectedItem',
      type: {
        name: 'Composite',
        polymorphicDiscriminator: {
          serializedName: 'protectedItemType',
          clientName: 'protectedItemType'
        },
        uberParent: 'ProtectedItem',
        className: 'AzureIaaSVMProtectedItem',
        modelProperties: {
          backupManagementType: {
            required: false,
            serializedName: 'backupManagementType',
            type: {
              name: 'String'
            }
          },
          workloadType: {
            required: false,
            serializedName: 'workloadType',
            type: {
              name: 'String'
            }
          },
          containerName: {
            required: false,
            serializedName: 'containerName',
            type: {
              name: 'String'
            }
          },
          sourceResourceId: {
            required: false,
            serializedName: 'sourceResourceId',
            type: {
              name: 'String'
            }
          },
          policyId: {
            required: false,
            serializedName: 'policyId',
            type: {
              name: 'String'
            }
          },
          lastRecoveryPoint: {
            required: false,
            serializedName: 'lastRecoveryPoint',
            type: {
              name: 'DateTime'
            }
          },
          protectedItemType: {
            required: true,
            serializedName: 'protectedItemType',
            isPolymorphicDiscriminator: true,
            type: {
              name: 'String'
            }
          },
          friendlyName: {
            required: false,
            serializedName: 'friendlyName',
            type: {
              name: 'String'
            }
          },
          virtualMachineId: {
            required: false,
            serializedName: 'virtualMachineId',
            type: {
              name: 'String'
            }
          },
          protectionStatus: {
            required: false,
            serializedName: 'protectionStatus',
            type: {
              name: 'String'
            }
          },
          protectionState: {
            required: false,
            serializedName: 'protectionState',
            type: {
              name: 'String'
            }
          },
          healthStatus: {
            required: false,
            serializedName: 'healthStatus',
            type: {
              name: 'String'
            }
          },
          healthDetails: {
            required: false,
            serializedName: 'healthDetails',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'AzureIaaSVMHealthDetailsElementType',
                  type: {
                    name: 'Composite',
                    className: 'AzureIaaSVMHealthDetails'
                  }
              }
            }
          },
          lastBackupStatus: {
            required: false,
            serializedName: 'lastBackupStatus',
            type: {
              name: 'String'
            }
          },
          lastBackupTime: {
            required: false,
            serializedName: 'lastBackupTime',
            type: {
              name: 'DateTime'
            }
          },
          protectedItemDataId: {
            required: false,
            serializedName: 'protectedItemDataId',
            type: {
              name: 'String'
            }
          },
          extendedInfo: {
            required: false,
            serializedName: 'extendedInfo',
            type: {
              name: 'Composite',
              className: 'AzureIaaSVMProtectedItemExtendedInfo'
            }
          }
        }
      }
    };
  }
}

module.exports = AzureIaaSVMProtectedItem;


text:
package com.icss.hit.hibernate.vo;

import java.util.Date;

/**
 * Files entity.
 *
 * @author MyEclipse Persistence Tools
 */

public class Files implements java.io.Serializable {

	// Fields

	private Long FId;
	private FileFolder fileFolder;
	private String FName;
	private Date FTime;

	// Constructors

	/** default constructor */
	public Files() {
	}

	/** minimal constructor */
	public Files(FileFolder fileFolder) {
		this.fileFolder = fileFolder;
	}

	/** full constructor */
	public Files(FileFolder fileFolder, String FName, Date FTime) {
		this.fileFolder = fileFolder;
		this.FName = FName;
		this.FTime = FTime;
	}

	// Property accessors

	public Long getFId() {
		return this.FId;
	}

	public void setFId(Long FId) {
		this.FId = FId;
	}

	public FileFolder getFileFolder() {
		return this.fileFolder;
	}

	public void setFileFolder(FileFolder fileFolder) {
		this.fileFolder = fileFolder;
	}

	public String getFName() {
		return this.FName;
	}

	public void setFName(String FName) {
		this.FName = FName;
	}

	public Date getFTime() {
		return this.FTime;
	}

	public void setFTime(Date FTime) {
		this.FTime = FTime;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="fragment_names">
        <item>Basic behaviour</item>
        <item>Basic expanded</item>
        <item>Inverse behaviour</item>
        <item>Inverse expanded</item>
    </string-array>
</resources>


text:
package org.apache.geode.internal.serialization;

/**
 * A DeserializationContext is provided to the fromData method in a DataSerializableFixedID
 * implementation during deserialization.
 */
public interface DeserializationContext {

  /** return the version of the source/destination of this serializer */
  Version getSerializationVersion();

  /** return the serializer */
  ObjectDeserializer getDeserializer();

}


text:
package fr.smarquis.usi;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class InterceptorActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.usi_interceptor_activity);

        Intent intent = getIntent();
        fillIntent(intent, ((TextView) findViewById(R.id.intent)));
        fillData(intent, ((TextView) findViewById(R.id.data)));
        fillExtras(intent, ((TextView) findViewById(R.id.extras)));
    }

    private void fillIntent(@Nullable Intent intent, @NonNull TextView textView) {
        if (intent == null) {
            textView.setText(Printer.EMPTY);
            return;
        }
        Truss truss = new Truss();
        Printer.append(truss, "action", intent.getAction());
        Printer.append(truss, "categories", intent.getCategories());
        Printer.append(truss, "type", intent.getType());
        Printer.append(truss, "flags", Flags.decode(intent.getFlags()));
        Printer.append(truss, "package", intent.getPackage());
        Printer.append(truss, "component", intent.getComponent());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            Printer.append(truss, "referrer", getReferrer());
        }
        textView.setText(truss.build());
    }

    private void fillData(@Nullable Intent intent, @NonNull TextView textView) {
        Uri data = intent == null ? null : intent.getData();
        if (data == null) {
            textView.setText(Printer.EMPTY);
            return;
        }

        Truss truss = new Truss();
        Printer.append(truss, "raw", data);
        Printer.append(truss, "scheme", data.getScheme());
        Printer.append(truss, "host", data.getHost());
        Printer.append(truss, "port", data.getPort());
        Printer.append(truss, "path", data.getPath());
        Printer.appendKey(truss, "query");
        boolean query = false;
        if (data.isHierarchical()) {
            for (String queryParameterName : data.getQueryParameterNames()) {
                Printer.appendSecondary(truss, queryParameterName, data.getQueryParameter(queryParameterName));
                query = true;
            }
        }
        if (!query) {
            Printer.appendValue(truss, null);
        }
        Printer.append(truss, "fragment", data.getFragment());
        textView.setText(truss.build());
    }

    private static void fillExtras(@Nullable Intent intent, @NonNull TextView textView) {
        Bundle extras = intent == null ? null : intent.getExtras();
        if (extras == null) {
            textView.setText(Printer.EMPTY);
            return;
        }

        Truss truss = new Truss();
        for (String key : extras.keySet()) {
            Printer.appendWithClass(truss, key, extras.get(key));
        }
        textView.setText(truss.build());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        final Intent nextIntent = getNextIntent();
        if (nextIntent != null) {
            MenuItem restartItem = menu.add(R.string.usi_menu_restart).setIcon(R.drawable.usi_ic_repeat_white_36dp).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    startActivity(Intent.createChooser(nextIntent, null));
                    return true;
                }
            });
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                restartItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM);
            }
        }
        MenuItem settingsItem = menu.add(R.string.usi_menu_settings).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                startActivity(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName())));
                return true;
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            settingsItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_NEVER);
        }
        return true;
    }

    /**
     * @return the next Intent to launch or null if this is the single resolved activity
     */
    private Intent getNextIntent() {
        Intent target = new Intent(getIntent()).setComponent(null);
        return getPackageManager().queryIntentActivities(target, PackageManager.MATCH_ALL).size() > 1 ? target : null;
    }

}


text:
package io.aeron.logbuffer;

import org.agrona.concurrent.UnsafeBuffer;

import static io.aeron.logbuffer.FrameDescriptor.*;
import static io.aeron.logbuffer.LogBufferDescriptor.applyDefaultHeader;
import static io.aeron.logbuffer.TermUnblocker.Status.*;
import static io.aeron.protocol.HeaderFlyweight.HDR_TYPE_PAD;

/**
 * Unblocks a term buffer if a publisher has died leaving the log with a partial log entry.
 */
public class TermUnblocker
{
    public enum Status
    {
        /**
         * No action has been taken during operation.
         */
        NO_ACTION,

        /**
         * The term has been unblocked so that the log can progress.
         */
        UNBLOCKED,

        /**
         * The term has been unblocked from the offset until the end of the term.
         */
        UNBLOCKED_TO_END,
    }

    /**
     * Attempt to unblock the current term at the current offset.
     *

     *
Current position length is > 0, then return

     *
Current position length is 0, scan forward by frame alignment until, one of the following:
     *

     *
reach a non-0 length, unblock up to indicated position (check original frame length for non-0)

     *
reach end of term and tail position >= end of term, unblock up to end of term (check original
     * frame length for non-0)
     *

     *
reach tail position < end of term, do NOT unblock

     *

     *

     *

     *
     * @param logMetaDataBuffer containing the default headers
     * @param termBuffer        to unblock
     * @param blockedOffset     to unblock at
     * @param tailOffset        to unblock up to
     * @param termId            for the current term.
     * @return whether unblocking was done, not done, or applied to end of term
     */
    public static Status unblock(
        final UnsafeBuffer logMetaDataBuffer,
        final UnsafeBuffer termBuffer,
        final int blockedOffset,
        final int tailOffset,
        final int termId)
    {
        Status status = NO_ACTION;
        int frameLength = frameLengthVolatile(termBuffer, blockedOffset);

        if (frameLength < 0)
        {
            resetHeader(logMetaDataBuffer, termBuffer, blockedOffset, termId, -frameLength);
            status = UNBLOCKED;
        }
        else if (0 == frameLength)
        {
            int currentOffset = blockedOffset + FRAME_ALIGNMENT;

            while (currentOffset < tailOffset)
            {
                frameLength = frameLengthVolatile(termBuffer, currentOffset);

                if (frameLength != 0)
                {
                    if (scanBackToConfirmZeroed(termBuffer, currentOffset, blockedOffset))
                    {
                        final int length = currentOffset - blockedOffset;
                        resetHeader(logMetaDataBuffer, termBuffer, blockedOffset, termId, length);
                        status = UNBLOCKED;
                    }

                    break;
                }

                currentOffset += FRAME_ALIGNMENT;
            }

            if (currentOffset == termBuffer.capacity())
            {
                if (0 == frameLengthVolatile(termBuffer, blockedOffset))
                {
                    final int length = currentOffset - blockedOffset;
                    resetHeader(logMetaDataBuffer, termBuffer, blockedOffset, termId, length);
                    status = UNBLOCKED_TO_END;
                }
            }
        }

        return status;
    }

    private static void resetHeader(
        final UnsafeBuffer logMetaDataBuffer,
        final UnsafeBuffer termBuffer,
        final int termOffset,
        final int termId,
        final int frameLength)
    {
        applyDefaultHeader(logMetaDataBuffer, termBuffer, termOffset);
        frameType(termBuffer, termOffset, HDR_TYPE_PAD);
        frameTermOffset(termBuffer, termOffset);
        frameTermId(termBuffer, termOffset, termId);
        frameLengthOrdered(termBuffer, termOffset, frameLength);
    }

    private static boolean scanBackToConfirmZeroed(final UnsafeBuffer buffer, final int from, final int limit)
    {
        int i = from - FRAME_ALIGNMENT;
        boolean allZeros = true;
        while (i >= limit)
        {
            if (0 != frameLengthVolatile(buffer, i))
            {
                allZeros = false;
                break;
            }

            i -= FRAME_ALIGNMENT;
        }

        return allZeros;
    }
}


text:
This is the official repository for the Where Am I Android application.

Please read the license agreement before changing the provided code.


text:
import Control.Monad
import Control.Monad.Trans.Resource
import Control.Concurrent.STM
import Data.Conduit
import Data.Conduit.Lazy
import System.Environment
import System.FilePath
import Codec.Binary.UTF8.String

import Network.SSH.Client.LibSSH2.Foreign
import Network.SSH.Client.LibSSH2.Conduit
import Network.SSH.Client.LibSSH2

main = do
  args <- getArgs
  case args of
    [user, host, port, cmd]  -> ssh user host (read port) cmd
    _ -> putStrLn "Synopsis: ssh-client USERNAME HOSTNAME PORT COMMAND"

ssh login host port command = do
  initialize True
  home <- getEnv "HOME"
  let known_hosts = home </> ".ssh" </> "known_hosts"
      public = home </> ".ssh" </> "id_rsa.pub"
      private = home </> ".ssh" </> "id_rsa"
  withSessionBlocking host port $ \session -> do
    r <- checkHost session host port known_hosts
    publicKeyAuthFile session login public private ""
    (Just ch, src) <- execCommand True session command
    res <- runResourceT $ lazyConsume src
    forM (map decodeString res) putStrLn
    rc <- getReturnCode ch
    putStrLn $ "Exit code: " ++ show rc
  exit


text:
<?php
App::uses('TenantBaseSchema', 'Risto.Model');

class TenantSchema extends TenantBaseSchema {

}


text:
"""A script testing the extraction pipeline of RHEA

Steps
1) Initialise Format, Extractor and RadialVelocity
2) Define file paths for science, flat and dark frames
3) Extract/import spectra
4) Create/import reference spectra
5) Calculate radial velocities
6) Plot radial velocities
"""
import numpy as np
try:
    import pyfits
except:
    import astropy.io.fits as pyfits
import pymfe
import glob
from astropy.coordinates import SkyCoord
from astropy import units as u

#===============================================================================
# Parameters/Constants/Variables/Initialisation
#===============================================================================
# Constants/Variables
do_bcor = True
med_cut = 0.5
coord = SkyCoord('01 44 04.08338 -15 56 14.9262',unit=(u.hourangle, u.deg))

# Specified header parameters
xbin = 2
ybin = 1
exptime = 1200

badpixel_mask= pyfits.getdata('/priv/mulga1/jbento/rhea2_data/badpix.fits')
badpix=np.where(badpixel_mask==1)

# Initialise objects
rhea2_format = pymfe.rhea.Format()
rhea2_extract = pymfe.Extractor(rhea2_format, transpose_data=False,
                                badpixmask=badpix)
xx, wave, blaze = rhea2_format.spectral_format()
rv = pymfe.rv.RadialVelocity()

#===============================================================================
# File paths (Observations, Flats and Darks, save/load directories)
#===============================================================================
# Science Frames
star = "gammaCrucis"
base_path = "/priv/mulga1/jbento/rhea2_data/gammaCrucis/"

all_files = glob.glob(base_path + "2015*/*" + star + "*.fit*")
all_files.sort()
files = []

# Only consider files that have the same exposure time and correct binning
for f in all_files:
    fits = pyfits.open(f)
    header = fits[0].header

    x_head = header["XBINNING"]
    y_head = header["YBINNING"]
    exp_head = header["EXPTIME"]

    if x_head == xbin and y_head == ybin and exp_head == exptime:
        files.append(f)

    fits.close()

# Flats and Darks
dark_path = base_path + "Dark frames/Masterdark_target_" + str(exptime) +".fits"
star_dark = pyfits.getdata(dark_path)
flat_dark = pyfits.getdata(base_path + "Dark frames/Masterdark_flat.fit")

# Note: this particular flat was chosen as it has an exposure time of 3 seconds,
# the same length as the flat dark that will be used to correct it
flat_path = base_path + "20150527/20150527_Masterflat.fit"
flat_files = [flat_path]*len(files)

# Set to len(0) arrays when extracting ThAr
#star_dark = np.empty(0)
#flat_dark = np.empty(0)
#flat_files = np.empty(0)

# Extracted spectra output
out_path = "/priv/mulga1/mireland/rhea/Gacrux_Extracted_" + str(exptime) + "/"
extracted_files = glob.glob(out_path + "*" + star + "*.fits")
extracted_files = extracted_files[:-1] #Last file has different binning

# RV csv output
base_rv_path = out_path + star

#===============================================================================
# Extract and save spectra/load previously extracted spectra
#===============================================================================
# Extract spectra ("wave" removed)
# OPTION 1: Extract and save spectra

#fluxes, vars, bcors, mjds = rv.extract_spectra(files, rhea2_extract,
#                                               star_dark=star_dark,
#                                               flat_files=flat_files,
#                                               flat_dark=flat_dark,
#                                              coord=coord, do_bcor=do_bcor)

# Save spectra (Make sure to save "wave" generated from rhea2_format)
#rv.save_fluxes(files, fluxes, vars, bcors, wave, mjds, out_path)

# OPTION 2: Load previously extracted spectra
fluxes, vars, wave, bcors, mjds = rv.load_fluxes(extracted_files)

#===============================================================================
# Create and save/import reference spectrum
#===============================================================================
# Number of frames to use for reference spectrum
n = 10

# OPTION 1: Create and save a new reference spectrum
wave_ref, ref_spect = rv.create_ref_spect(wave, fluxes[:n,:,:], vars[:n,:,:],
                                          bcors[:n], med_cut=med_cut)

rv.save_ref_spect(files[:n], ref_spect, vars[:n,:,:], wave_ref, bcors[:n],
                  mjds[:n], out_path, star)

# OPTION 2: Import a pre-existing reference spectrum
#ref_spect, vars_ref, wave_ref, bcors_ref, mjds_ref = rv.load_ref_spect(ref_path)

#===============================================================================
# Calculate, save and plot radial velocities
#===============================================================================
# Calculate RVs
rvs, rv_sigs = rv.calculate_rv_shift(wave_ref, ref_spect, fluxes, vars, bcors,
                                     wave)

nf = fluxes.shape[0]
nm = fluxes.shape[1]

bcor_rvs = rvs - bcors.repeat(nm).reshape( (nf, nm) )

# Save RVs
rv.save_rvs(rvs, rv_sigs, bcors, mjds, bcor_rvs, base_rv_path)