text:
function palace = mindPalace(classes)
    %I'm not a psychopath, Anderson. I'm a high-functioning sociopath.
    myPalace = struct();
    made = [];
    for i = (1:length(classes))
        item = classes{i};
        type = class(item);
        if ismember(type,made)
            myPalace.(type) = [myPalace.(type) {item}];
        else
            myPalace = setfield(myPalace, type, {item});
            made = [made type];
        end
    end
    palace = myPalace;
end


text:
Exclusive Rules

 Setting Up

 The Loyalist players units are already setup.

The Rebel Player places their units on the first turn. They will appear in a box labeled Deploy/Staging.
                The placement of the non airborne unit will determine where the beachheads appear. Beachhead hexes are
                where supply and non airborne reinforcements appear.

                Airborne units once places will create an air landing zone. Air landing zones are where airborne supply and
                reinforcements appear.

If all air landing zones are occupied and destroyed by the loyalist player,
                future airborne units, if any, will arrive at a beach landing zone, one turn later than normal

redpajama_set_name: RedPajamaGithub


text:
#ifndef _ACSERR__H_
#define _ACSERR__H_

#ifndef __cplusplus
#error This is a C++ include file and cannot be used from plain C
#endif

#include "acserrLegacy.h"
#include <sstream>

// forward declaration
class ACSLogImpl;

namespace ACSErr
{

/**
 * Helper class for CORBA error trace (#ACSErr::ErrorTrace)
 *
 */

class ErrorTraceHelper
{
  protected:
    friend class CompletionImpl;
    friend class ::ACSLogImpl;
    friend class ::ACSError;

    ErrorTraceHelper(ACSErr::ErrorTrace &et);

// for OK cases and wrapping error completion
     void setErrorTrace(ACSErr::ErrorTrace &et, int depth);

// default constructor (OK completion)
    ErrorTraceHelper()
	: m_errorTracePtr(0), m_current(0), m_depth(0)
	{}

// create new error trace
    ErrorTraceHelper (ACSErr::ACSErrType et, ACSErr::ErrorCode ec,
		      const char* file, int line, const char* routine, const char* sd,
		      ACSErr::Severity severity,
		      ACSErr::ErrorTrace &errortrace);

// adding previos error trace
    ErrorTraceHelper (const ACSErr::ErrorTrace &pet,
		      ACSErr::ACSErrType et, ACSErr::ErrorCode ec,
		      const char* file, int line, const char* routine, const char* sd,
		      ACSErr::Severity severity,
		      ACSErr::ErrorTrace &errortrace);

    /**
     * assigning ACSErr::ErrorTrace directly
     */
    ErrorTraceHelper& operator=(ACSErr::ErrorTrace& eth);

  public:

    /**
     * Logs the complete error trace into the logging system.
     * For each such exception in the trace, a separate log entry
     * is created, in accordance with the ACS error logging specification.
     * @param priorty: priorty with which the error trace will be logged
     * If priorty is not specified the completion/error trace will
     * be logged with ERROR priorty.
     * The priority can be used to log an important error trace at LM_DEBUG level
     * before sending it to a remote client.
     * The responsibility of ultimately decide is an error trace
     * shall be logged or closed is ultimately left to the higher level client,
     * but a bad behaving client could "forget" to log.
     * In order to make sure potentially critical information is not lost,
     * the servant application can decide to log anyway the error trace
     * as debug information before sending it to the client.
     */
    void log(ACE_Log_Priority priorty=LM_ERROR);

    /**
     * Returns a string describing the error on top of the error trace.
     */
    std::string toString();

    /**
     * Adds data to the current error trace.
     * If the name apperas more than one time it adds it more times.
     * @param name data name, which should be shorter than 255 characters otherwise is truncated. If name is NULL the method return w/o setting anything.
     * @param value string data value , which should be shorter than 255 characters, otherwise is truncated. If value is NULL the method return w/o setting anything.
     */
    void addData (const char* name, const char* value);

    /**
     * Variation of addData for non cons char* value, otherwise the template versioin is taken.
     * It just pass work to addData(const char* name, const char* value).
     */
    void addData (const char* name, char* value)
        {
            addData (name, (const char*)value);
        }//addData

    /**
     * Templated version of #addData adds data (pair of name-value)
     * It works for all types that can be put to std::ostringstream.
     * @param name data name, which should be shorter than 255 characters otherwise is truncated. If name is NULL the method return w/o setting anything.
     * @param value data value. The stringified length of value should not exceed 255 characters, otherwise it is truncated. If value is NULL the method return w/o setting anything.
     *
     */
    template<typename T>
    void addData (const char* name, T value)
	{
	    const char *s;
	    std::ostringstream ostr;
	    ostr << value << std::ends;
	    std::string ts=ostr.str(); // we have to make a temporary string otherwise there is problem with memory:  s = ostr.str().c_str(); does not work
	    s = ts.c_str();
	    addData (name, s);
	}//addData

    /**
     * Sets member value of current error. This method is mainly used by generated code.
     * If this function is used the fist time it adds new name-value pair.
     * @param name data name. If name or value are NULL it returns w/o setting anything.
     * @param value string data value
     */
    void setMemberValue (const char* name, const char* value);

    /**
     * Version of setMember that takes value as ACE_CString. This method is mainly used by generated code.
     * If this function is used the fist time it adds new name-value pair.
     * @param name data name. If name is NULL it returns w/o setting anything.
     * @param value string data value
     */
    void setMemberValue (const char* name, ACE_CString &value);

    /**
     * Sets member value. Template version of #setMemberValue. This method is mainly used by generated code.
     * It works for all types that can be put to std::ostringstream like: int, string and double.
     * @param name member name. If name is NULL it returns w/o setting anything.
     * @param value member value
     */
    template<typename T>
    void setMemberValue (const char* name, T value)
	{
	    const char *s;
	    if (name==NULL) return;

	    std::ostringstream ostr;
	    ostr << value << std::ends;
	    std::string ts=ostr.str(); // we have to make a temporary string otherwise there is problem with memory
	    s = ts.c_str();
	    setMemberValue (name, s);
	}//setMemberValue

    /**
     * Gets data value for data name (first occurrence). If data for name is not found it returns an empty string.
     * @param name data name. If name is NULL an empty string is returned.
     * @return value string data value
     */
    ACE_CString getData (const char* name);

    /**
     * Gets data value for data name (first occurrence). This method is mainly used by generated code.
     * If data for name is not found it returns an empty string.
     * @param name data name
     * @param value string data value
     */
    void getMemberValue(const char* name, char*& value)
	{
	    value = CORBA::string_dup(getData(name).c_str());
	}

    /**
     * Template version of #getMemberValue. Gets data value for data name (first occurrence).
     * It works for all types that can be retreived from  std::istringstream like: int, string and double.
     * If data name is not found it returns empty string.
     * @param name data name
     * @param value data value
     */
    template<typename T>
    void getMemberValue (const char* name, T &value)
	{
	    std::istringstream istr(getData(name).c_str());
	    istr >> value;
	}//getMemberValue

    /**
     * Another version of getMemberValue, which is more elegant since it returns value. This function is mainly used by generated code.
     * It works for all types that can be retreived from  std::istringstream like: int, string and double.
     * @param name data name
     * @return data vlaue of right type
     */
    template<typename T>
    T getMemberValue (const char* name);

    /**
     * Returns copy of short (!) description of current error. User have to take care of releasing it!
     * @return pointer to the char (=string).
     * TBD: should return description if it is possible to retreive it. To be changed or removed.
     * short description should be retreived using #getShortDescription
     */
    char* getDescription();

    /**
     * Returns copy of short description of current error. User have to take care of releasing it!
     * @return pointer to the char (=string)
     */
    char* getShortDescription();

  /**
   * Returns file name information of the error
   * @return pointer to char contains file name
   */
  char* getFileName(){ return CORBA::string_dup(m_current->file); }

  /**
   * Returns line number information of the error
   * @return CORBA::ULong line number
   */
  CORBA::ULong getLineNumber(){ return m_current->lineNum; }

  /**
   * Returns routine information of tehe error
   * @return pointer to char contains routine name
   */
  char* getRoutine(){ return CORBA::string_dup (m_current->routine); }

  /**
   * Returns host name information of the error
   * @return pointer to char contains host name
   */
  char* getHostName(){ return CORBA::string_dup (m_current->host); }

  /**
   * Retruns process information of the error. Its name or process ID.
   * @return pointer to the char points to the copy of process information
   */
  char* getProcessName(){ return CORBA::string_dup (m_current->process); }

  /**
   * Returns thread information of the error. The name of thread or its ID.
   * @return pointer to the char points to the copy of thread information
   */
  char* getThread(){ return CORBA::string_dup (m_current->thread); }

  /**
   * Returns source object information of the error.
   * @return pointer to the char points to the copy of the source object (caller has to delete it).
   */
  char* getSourceObject(){ return CORBA::string_dup (m_current->sourceObject); }
  /**
   * Returns time stamp of the error in 100th of nanoseconds.
   * @return CORBA::ULongLong time stamp
   */
  CORBA::ULongLong getTimeStamp (){ return m_current->timeStamp; }

  /**
   * Returns error code
   * @return  ACSErr::ErrorCode
   */
    ACSErr::ErrorCode getErrorCode(){ return m_current->errorCode; }

  /**
   * Returns error type
   * @return  ACSErr::ACSErrType
   */
    ACSErr::ACSErrType getErrorType(){ return m_current->errorType; }

  /**
   *Returns error severity
   */
  ACSErr::Severity getSeverity() { return m_current->severity; }

 /**
   *Returns depth of error stack
   *@return unsigned int depth
   */
  unsigned int getDepth(){ return m_depth; }

 /**
   * Sets time stamp of the error in 100th of nanoseconds.
   * @parm time CORBA::ULongLong time stamp
   */
 void setTimeStamp (CORBA::ULongLong time){ m_current->timeStamp = time; }

 /**
  * Sets source object
  * @param source object
  *
  */
  void setSourceObject(const char* so){ m_current->sourceObject = CORBA::string_dup (so); }

 /**
  * Sets file name
  * @param fn file name
  *
  */
  void setFileName(const char* fn){ m_current->file = CORBA::string_dup (fn); }

 /**
  * Sets line number
  * @param ln line number
  *
  */
  void setLineNumber (CORBA::ULong ln){ m_current->lineNum = ln; }//? should we delete previos one

 /**
   *Sets current error code
   * @param ty error type (should be of type ACSErr::ACSErrType defined in acserrType.idl)
   * @param ec erro code
   *
   */
  void setError (ACSErr::ACSErrType ty, ACSErr::ErrorCode ec)
	{ m_current->errorType=ty; m_current->errorCode=ec; }

  /**
   *Sets error severity
   *@param: severity errro severity
   *
   */
  void setSeverity(ACSErr::Severity severity) {m_current->severity = severity; }

  /**
   * Sets host name
   *@param hn host name
   */
  static void setHostName (const char* hn);

  /**
   * Sets process name
   * @param process name
   */
  static void setProcessName (const char *pn);

  /**
   * Moves to the next errortrace element and return its pointer (not copy).
   * If there is no next errortrace element NULL will be returned
   * @return pointer to the errortrace structure
   */
  ACSErr::ErrorTrace *getNext();

    /**
     * Tells if we are at the end of error trace. This method should be used with combination of getNext to find out when the end of the error trace is reached.
     * @return true if we reach the end of error trace otherwise false
     */
    bool last() { return (m_depth==0 || m_current->previousError.length()==0); }

  /**
   * Moves to the first (top) errortrace element and return its pointer (not copy).
   * @return pointer to the errortrace structure
   */
  ACSErr::ErrorTrace *top(){ m_current = m_errorTracePtr; return m_current;}

   /**
   * Gets reference to errortrace structure. User must take care for makeing copy of structure or should use method returnErrorTrace
   * @return reference to the current errortrace structure
   *\todo if current is NULL than exception should be thrown
   */
    ACSErr::ErrorTrace& getErrorTrace(){ return *m_current; } // should check if stack is empty

    static ACS::Time getTime();

    /**
     * Return pointer to ErrorTraceHelper what is itself (=this).
     * It is here just to make generated code simpler.
     * @return pointer to itself
     */
    ErrorTraceHelper*  getErrorTraceHelper() { return this; }

  protected:

    void fill (ACSErr::ACSErrType et, ACSErr::ErrorCode ec, ACSErr::Severity severity,
	       const char* file, int line, const char* routine, const char* sd);

   /**
     * Logs just a single part (item) of an errortrace into the logging system.
     * This method is used internaly by the #log method
     * @param c pointer to error trace structure
     * @param level error trace level
     * @param priorty: priorty with which the error trace will be logged
     * If priorty is not specified the completuion/error trace will be logged with ERROR priorty.
     */
    void log (ACSErr::ErrorTrace * c,
	      int level, char *stackId,
	      ACE_Log_Priority priorty=LM_ERROR);

    void toString (ACSErr::ErrorTrace * c, int level, std::ostringstream& oss);

    ACSErr::ErrorTrace *m_errorTracePtr;
//& m_errorTraceRef;
    ACSErr::ErrorTrace *m_current;
    unsigned int m_depth;

    static char m_hostName[64];
    static char m_processName[64];
    static const unsigned int m_maxDepth;
};

/*******************************************************************************************/
/**
 * Class for initalizing #ACSErrCompletion
 */

class CompletionInit : public ACSErr::Completion
{
  public:
    CompletionInit(const ACSErr::Completion &c);

    CompletionInit(ACSErr::CompletionType t, ACSErr::CompletionCode c, bool initTrace=true);

  /**
   * Returns completion code
   * @return  ACSErr::CompletionCode
   */
    ACSErr::CompletionCode getCode(){ return code; }

  /**
   * Returns completion type
   * @return  ACSErr::ACSErrType
   */
    ACSErr::CompletionType getType(){ return type; }

  /**
   * Returns completion time stamp in 100th (1/100) of nanoseconds.
   * @return CORBA::ULongLong time stamp
   */
  CORBA::ULongLong getTimeStamp (){ return timeStamp; }
};

/**************************************************************************************/
/**
 * Implementation / Helper class for handling #ACSErr::Completion
 */

class CompletionImpl : public CompletionInit
{
  public:
// default constructor
    CompletionImpl();

    CompletionImpl (ACSErr::ACSErrType t, ACSErr::ErrorCode c) :
	CompletionInit(t, c, false)/*,
	m_errorTraceHelper(previousError[0], previousError.length())
*/
	{
	}

    CompletionImpl (ACSErr::ACSErrType t, ACSErr::ErrorCode c,
		      const char* file, int line, const char* routine, const char* sd,
		      ACSErr::Severity severity) :
	CompletionInit(t, c),
	m_errorTraceHelper(t, c, file, line, routine, sd, severity, previousError[0])
	{}

// adding previous (remote or local) with reference
    CompletionImpl (const ACSErr::Completion &pc, ACSErr::ACSErrType t, ACSErr::ErrorCode c,
		      const char* file, int line, const char* routine, const char* sd,
		      ACSErr::Severity severity) :
	CompletionInit(t, c),
	m_errorTraceHelper(pc.previousError[0], t, c, file, line, routine, sd, severity, previousError[0])
	{}
// adding previous remote completion as pointer
    CompletionImpl (ACSErr::Completion *pc, ACSErr::ACSErrType t, ACSErr::ErrorCode c,
		      const char* file, int line, const char* routine, const char* sd,
		      ACSErr::Severity severity) :
	CompletionInit(t, c),
	m_errorTraceHelper(pc->previousError[0], t, c, file, line, routine, sd, severity, previousError[0])
	{ delete pc; }

// adding previous completion as pointer
    CompletionImpl (CompletionImpl *pc, ACSErr::ACSErrType t, ACSErr::ErrorCode c,
		      const char* file, int line, const char* routine, const char* sd,
		      ACSErr::Severity severity) :
	CompletionInit(t, c),
	m_errorTraceHelper(pc->previousError[0], t, c, file, line, routine, sd, severity, previousError[0])
	{ delete pc; }

// adding error trace
    CompletionImpl (const ACSErr::ErrorTrace &et, ACSErr::ACSErrType t, ACSErr::ErrorCode c,
		      const char* file, int line, const char* routine, const char* sd,
		      ACSErr::Severity severity) :
	CompletionInit(t, c),
	m_errorTraceHelper(et, t, c, file, line, routine, sd, severity, previousError[0])
	{}

//wrapping remote (CORBA) Completion
    /**
     * Wrapper constructor for remote (CORBA) completions (#ACSErr::Completion).
     * @param c remote CORBA completion
     * @parm del flag which indiactes if the completion should be deleted. Its default value is true, so the remote completion is deleted.
     */
    CompletionImpl(ACSErr::Completion* c, bool del=true);

   /**
     * Wrapper constructor for remote (CORBA) completions (#ACSErr::Completion) that is contained in a #Completion_var.
     * @param c reference to #Completion_var
     * #Completion from #Completion_var is copied, so after that the #Completion_var still contains the completion.
     */
    CompletionImpl(ACSErr::Completion_var& c);

    CompletionImpl (const ACSErr::Completion &c);

    /**
       Copy constructor
    */
    CompletionImpl (const CompletionImpl &c);

    /**
       Destructor
     */
    virtual ~CompletionImpl(){}

  /**
   * Returns copy of completion structure (and delete #CompletionImpl object).
   * This method should be used in a method when we retrun #ACSErr::Completion
   * (when we go from local (C++) to remote (CORBA)
   * @param deletion flag indicates if #CompletionImpl has to be deleted.
   * Default value is true what means that #CompletionImpl object will be deleted.
   * DO NOT use true (default) value when #CompletionImpl is allocated on the stack !!!
   * @return pointer to the CORBA #ACSErr::Completion structure.
   */
    ACSErr::Completion* returnCompletion (bool deletion=true)
	{
	    ACSErr::Completion *tmp = new ACSErr::Completion(*this);
	    if (deletion) delete this;
	    return tmp;
	}//returnCompletion

    /**
     * Returns copy of completion structure (#ACSErr::Completion) which can be assign to #ACSErr::Completion_out.
     * This method should be used when #ACSErrCompletion is used as out(put) parameter of a method (#ACSErr::Completion_out).
     * DO NOT use this method on client side !!
     * @param deletion flag indicates if #CompletionImpl has to be deleted.
     * Default value is false what means that #CompletionImpl object will not be deleted
     * (oposit than in #returnCompeltion()).
     * DO NOT use true value when #CompletionImpl is allocated on the stack !!!
     * @return pointer to the CORBA #ACSErr::Completion structure.
     */
    ACSErr::Completion* outCompletion(bool del=false) { return this->returnCompletion(del); }

    /**
     * Tells if CompletionImpl is error-free or not (i.e. if is it contain error trace or not)
     @return true if CompletionImpl is error-free otherwise false.
     */

    bool isErrorFree(){ return (previousError.length() == 0); }

  /**
   * Returns pointer to the ErrorTraceHelper. If there is no error trace it returns NULL.
   * @return pointer to the errortrace helper object
   */
    ErrorTraceHelper*  getErrorTraceHelper(){ return (ErrorTraceHelper*)( (previousError.length() > 0) ? &m_errorTraceHelper : NULL); }

    /**
     * Logs Completion/errortrace into the logging system
     * @param priorty priorty with which the completion/error trace will be logged
     * If priorty is not specified the completuion/error trace will be logged with ERROR priorty.
     */
    void log(ACE_Log_Priority priorty=LM_ERROR);

    template<typename T>
    void addData (const char* name, T value)
	{
	    if (!isErrorFree())
		{
		m_errorTraceHelper.addData(name, value);
		}
	}

    CompletionImpl& operator=(CompletionImpl&);

    /**
     * assignment for remote (CORBA) completions.
     * @param c pointer to the remote (CORBA) completion
     * It takes over the memory managment of #Completion, so the Completion is deleted.
     */
    CompletionImpl& operator=(Completion* c);

     /**
     * assignment for remote (CORBA) completion that is contained in a #Completion_var.
     * @param c pointer to the  #Completion_var.
     * This assigment makes a copy of #Completion that is contained inside the #Completion_var, so after the #Completion_var still conatins #Completion.
     */
    CompletionImpl& operator=(Completion_var& c);

  protected:
    ErrorTraceHelper m_errorTraceHelper;
};//CompletionImpl

/*************************************************************************************/
//template implementation
//

// specialization for strings
template<>
char * ErrorTraceHelper::getMemberValue<char*> (const char* name);

template<>
ACE_CString ErrorTraceHelper::getMemberValue<ACE_CString> (const char* name);

template<typename T>
T ErrorTraceHelper::getMemberValue (const char* name)
{
    T value;
    std::istringstream istr(getData(name).c_str());
    istr >> value;
    return value;
}//getMemberValue

}

// these two lines are just for backward compatibility and should be removed
// ... with next release
typedef ACSErr::CompletionInit CompletionInit;
typedef ACSErr::CompletionImpl CompletionImpl;
typedef ACSErr::ErrorTraceHelper ErrorTraceHelper;

#endif


text:
namespace Ui{
	class PlayerWidget;
};

class PlayerWidget : public QWidget{
	Q_OBJECT
public:
	PlayerWidget(QWidget *parent = 0);
	~PlayerWidget();

public slots:
	void LoadIcons();

private:
	Ui::PlayerWidget *ui;
	QMediaPlaylist *PLAYLIST;
	QMediaPlayer *PLAYER;
	QMenu *configMenu, *addMenu;
	bool updatinglists;

private slots:
	void playClicked();
	void pauseClicked();
	void stopClicked();
	void nextClicked();
	void prevClicked();

	void AddFilesToPlaylist();
	void AddDirToPlaylist();
	void AddURLToPlaylist();
	void ClearPlaylist();
	void ShufflePlaylist();
	void userlistSelectionChanged(); //front-end combobox was changed by the user
	void playerStateChanged();
	void playlistChanged(); //list of items changed
	void currentSongChanged();
	void updateProgress(qint64 val);
	void updateMaxProgress(qint64 val);
};

// Wrapper class to put this into a desktop plugin container
class AudioPlayerPlugin : public LDPlugin{
	Q_OBJECT
public:
	AudioPlayerPlugin(QWidget* parent, QString ID);
	~AudioPlayerPlugin();

private:
	PlayerWidget *player;

public slots:
	void LocaleChange(){
	  QTimer::singleShot(0,player, SLOT(LoadIcons()));
	}
	void ThemeChange(){
	  QTimer::singleShot(0,player, SLOT(LoadIcons()));
	}
};

#endif


text:
/**
 * Display file sizes of minified packages and gzipped packages.
 */
module.exports = function (grunt) {

    var gzip = require('gzip-js');
    var fs = require('fs');

    grunt.registerMultiTask('gzipStats', 'GZips the files and displays stats', function () {
        var srcFolder = this.data.src;
        grunt.log.writeln('Calculating GZip stats for the folder: '.cyan + srcFolder.yellow);

        var files = grunt.file.expand({
            filter : "isFile"
        }, srcFolder + '/**/*.js');
        grunt.log.writeln('\n      min      gzip   gain  file');
        grunt.log.writeln('--------------------------------------------------------------------------------');

        var sizeTotal = 0, sizeGzipTotal = 0;
        files.forEach(function (filePath) {
            var sizeKbOrig = (fs.statSync(filePath).size / 1024);
            var gzipped = callGzip(grunt.file.read(filePath));
            var sizeKbGzip = (gzipped.length / 1024);

            var filePathShort = filePath.replace(srcFolder, '');
            grunt.log.writeln(size(sizeKbOrig) + size(sizeKbGzip) + gain(sizeKbOrig, sizeKbGzip) + filePathShort);
            sizeTotal += sizeKbOrig;
            sizeGzipTotal += sizeKbGzip;
        });
        grunt.log.writeln('--------------------------------------------------------------------------------');
        grunt.log.writeln(size(sizeTotal) + size(sizeGzipTotal) + gain(sizeTotal, sizeGzipTotal));

        // Fail task if errors were logged.
        if (this.errorCount) {
            return false;
        }
        // Otherwise, print a success message
        grunt.log.ok();
    });

    // Return gzipped source.
    function callGzip (src) {
        return src ? gzip.zip(src, {}) : '';
    }

    /**
     * @param {Float} sizeKb
     */
    function size (sizeKb) {
        sizeKb = sizeKb.toFixed(1); // should have length 3..5 (e.g. '186.0' or '7.3')
        var prependLen = 6 - sizeKb.length;
        return (new Array(prependLen + 1).join(' ')) + sizeKb + ' kB ';
    }

    /**
     * @param {Float} sizeKbOrig
     * @param {Float} sizeKbGzip
     */
    function gain (sizeKbOrig, sizeKbGzip) {
        var gain = ((1 - (sizeKbGzip / sizeKbOrig)) * 100).toFixed(0);
        var prependLen = 5 - gain.length;
        return (new Array(prependLen + 1).join(' ')) + gain + '%  ';
    }

};


text:
'use strict'

/**
 * The CLI helper used by the CLI extension.
 *
 * @module extensions/Cli/Cli
 */

const { spawn } = require('child_process')
const path = require('path')

/**
 * Cli extension.
 *
 * @class
 */
class Cli {
    constructor() {
        /**
         * The Current Working Directory.
         *
         * @type {string}
         */
        this.cwd = process.cwd()

        /**
         * An object containing environment variables to inject when running your command.
         *
         * @type {Object}
         */
        this.env = {}

        /** @type {string} */
        this.killSignal = null

        /** @type {number} */
        this.killDelay = 0

        /**
         * Latest command execution exit code.
         *
         * @type {number}
         */
        this.exitCode = null

        /**
         * The command's output.
         *
         * @type {string}
         */
        this.stdout = ''

        /**
         * The command's error output.
         *
         * @type {string}
         */
        this.stderr = ''
    }

    /**
     * Sets the Current Working Directory for the command.
     *
     * @param {string} cwd - The new CWD
     */
    setCwd(cwd) {
        if (cwd.indexOf('/') === 0) {
            this.cwd = cwd
        } else {
            this.cwd = path.join(process.cwd(), cwd)
        }
    }

    /**
     * Returns Current Working Directory.
     *
     * @return {string}
     */
    getCwd() {
        return this.cwd
    }

    /**
     * Defines environment variables.
     * Beware that all existing ones will be overridden!
     *
     * @param {Object} env - The environment variables object
     */
    setEnvironmentVariables(env) {
        this.env = env
    }

    /**
     * Defines a single environment variable.
     *
     * @param {string} name  - The environment variable name
     * @param {string} value - The value associated to the variable
     */
    setEnvironmentVariable(name, value) {
        this.env[name] = value
    }

    scheduleKillProcess(delay, signal) {
        this.killDelay = delay
        this.killSignal = signal
    }

    /**
     * Returns latest command execution exit code.
     *
     * @return {number} The exit code
     */
    getExitCode() {
        return this.exitCode
    }

    /**
     * Returns captured output.
     *
     * @throws {TypeError} Argument `type` must be one of: 'stdout', 'stderr'
     * @param {string} [type=stdout] - The standard stream type
     * @returns {string} The captured output
     */
    getOutput(type = 'stdout') {
        if (type === 'stdout') return this.stdout
        else if (type === 'stderr') return this.stderr

        throw new TypeError(`invalid output type '${type}', must be one of: 'stdout', 'stderr'`)
    }

    /**
     * Resets the Cli helper:
     * - CWD is reset to current process CWD
     * - environment variables
     * - killDelay & killSignal are disabled
     * - exitCode is set to null
     * - stdout is set to an empty string
     * - stderr is set to an empty string
     */
    reset() {
        this.cwd = process.cwd()
        this.env = {}
        this.killDelay = 0
        this.killSignal = null
        this.exitCode = null
        this.stdout = ''
        this.stderr = ''
    }

    /**
     * Run given command.
     *
     * @param {string} rawCommand - The command string
     * @returns {Promise.<boolean>} The resulting `Promise`
     */
    run(rawCommand) {
        const [command, ...args] = rawCommand.split(' ')

        return new Promise((resolve, reject) => {
            // we inherit from current env vars
            // otherwise, we can have problem with PATH
            const cmd = spawn(command, args, {
                cwd: this.cwd,
                env: Object.assign({}, process.env, this.env),
            })

            let killer
            let killed = false
            if (this.killSignal !== null) {
                killer = setTimeout(() => {
                    cmd.kill(this.killSignal)
                    killed = true
                }, this.killDelay)
            }

            const cmdStdout = []
            const cmdStderr = []

            cmd.stdout.on('data', cmdStdout.push.bind(cmdStdout))
            cmd.stderr.on('data', cmdStderr.push.bind(cmdStderr))

            cmd.on('close', (code, signal) => {
                if (killer !== undefined) {
                    if (killed !== true) {
                        clearTimeout(killer)

                        return reject(
                            new Error(
                                `process.kill('${this.killSignal}') scheduled but process exited (delay: ${this.killDelay}ms)`
                            )
                        )
                    }
                }

                this.exitCode = code

                this.stdout = Buffer.concat(cmdStdout).toString()
                this.stderr = Buffer.concat(cmdStderr).toString()

                resolve(true)
            })
        })
    }
}

/**
 * Create a new isolated Cli
 * @return {Cli}
 */
module.exports = function (...args) {
    return new Cli(...args)
}

/**
 * Cli extension.
 * @type {Cli}
 */
module.exports.Cli = Cli


text:
<!DOCTYPE html>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ronald Chacon</title>

    <link rel="stylesheet" href="css/normalize.css">
    <link rel="stylesheet" href="css/foundation.css">
    <link rel="stylesheet" href="css/index.css">
    <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">

Ronald Chacon

                            Menu

Home

About Me

Projects

Contact

Blog

Ronald Chacon

Web Design | Developer | Rubyist

About Me

I'm a 26 year old web developer from the Silicon Valley (San Francisco) who is currently studying at Dev Bootcamp. My passion is all about creating real elegant looking websites. Always keeping it clean and simple with that added functionally of user interaction you would like to see. If you would like to connect with me, then be sure to find me on Twitter, Facebook, Google+, LinkedIn and GitHub.

Projects

This is a future project.

Bacon ipsum dolor sit amet nulla ham qui sint exercitation eiusmod commodo, chuck duis velit. Aute in reprehenderit, dolore aliqua non est magna in labore pig pork biltong. Eiusmod swine spare ribs reprehenderit culpa. Boudin aliqua adipisicing rump corned beef.

This is a future project.

Bacon ipsum dolor sit amet nulla ham qui sint exercitation eiusmod commodo, chuck duis velit. Aute in reprehenderit, dolore aliqua non est magna in labore pig pork biltong. Eiusmod swine spare ribs reprehenderit culpa. Boudin aliqua adipisicing rump corned beef.

This is a future project.

Bacon ipsum dolor sit amet nulla ham qui sint exercitation eiusmod commodo, chuck duis velit. Aute in reprehenderit, dolore aliqua non est magna in labore pig pork biltong. Eiusmod swine spare ribs reprehenderit culpa. Boudin aliqua adipisicing rump corned beef.

Get in touch!

I would love to hear from you!

                        Contact Me

Ronald Chacon


text:
package org.apache.xbean.finder.archive;

import junit.framework.TestCase;
import org.apache.xbean.finder.filter.Filter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @version $Rev$ $Date$
 */
public class FilteredArchiveTest extends TestCase {

    private MockArchive archive;

    public void testNothingFiltered() throws Exception {

        assertEquals(archive, new FilteredArchive(archive, new Nothing()));
    }

    public void testFilterHalf() throws Exception {

        List<String> list = list(new FilteredArchive(archive, new Half()));

        assertEquals(25, list.size());
    }

    public void testFilterAll() throws Exception {

        List<String> list = list(new FilteredArchive(archive, new All()));

        assertEquals(0, list.size());
    }

    public static void assertEquals(Iterable<Archive.Entry> expectedList, Iterable<Archive.Entry> actualList) {
        final Iterator<Archive.Entry> expected = expectedList.iterator();
        final Iterator<Archive.Entry> actual = actualList.iterator();

        int i = 0;
        while (expected.hasNext() && actual.hasNext()) {
            assertEquals(expected.next().getName(), actual.next().getName());
            i++;
        }

        assertEquals(i + " items were the same", expected.hasNext(), actual.hasNext());
    }

    public static class Nothing implements Filter {

        public boolean accept(String name) {
            return true;
        }
    }

    public static class All implements Filter {

        public boolean accept(String name) {
            return false;
        }
    }

    public static class Half implements Filter {

        private boolean accept;

        public boolean accept(String name) {
            return accept = !accept;
        }
    }

    public static List<String> list(Iterable<Archive.Entry> iterable) {
        List<String> list = new ArrayList<String>();

        for (Archive.Entry t : iterable) {
            list.add(t.getName());
        }

        return list;
    }

    @Override
    protected void setUp() throws Exception {
        // 50 entries
        archive = new MockArchive(
                "org.apache.xbean.asm.AnnotationVisitor",
                "org.apache.xbean.asm.AnnotationWriter",
                "org.apache.xbean.asm.Attribute",
                "org.apache.xbean.asm.ClassAdapter",
                "org.apache.xbean.asm.commons.AdviceAdapter",
                "org.apache.xbean.asm.commons.AnalyzerAdapter",
                "org.apache.xbean.asm.commons.GeneratorAdapter",
                "org.apache.xbean.asm.commons.JSRInlinerAdapter",
                "org.apache.xbean.asm.commons.RemappingAnnotationAdapter",
                "org.apache.xbean.asm.commons.RemappingClassAdapter",
                "org.apache.xbean.asm.commons.RemappingFieldAdapter",
                "org.apache.xbean.asm.commons.RemappingMethodAdapter",
                "org.apache.xbean.asm.commons.RemappingSignatureAdapter",
                "org.apache.xbean.asm.commons.SerialVersionUIDAdder",
                "org.apache.xbean.asm.MethodAdapter",
                "org.apache.xbean.asm.tree.AnnotationNode",
                "org.apache.xbean.asm.tree.MultiANewArrayInsnNode",
                "org.apache.xbean.finder.AnnotatedMember",
                "org.apache.xbean.finder.AnnotatedMethod",
                "org.apache.xbean.finder.AnnotatedTarget",
                "org.apache.xbean.finder.AnnotationFinder",
                "org.apache.xbean.finder.archive.Archive",
                "org.apache.xbean.finder.BundleAnnotationFinder",
                "org.apache.xbean.finder.archive.BundleArchive",
                "org.apache.xbean.finder.BundleAssignableClassFinder",
                "org.apache.xbean.finder.archive.ClassesArchive",
                "org.apache.xbean.finder.archive.ClasspathArchive",
                "org.apache.xbean.finder.MetaAnnotation",
                "org.apache.xbean.finder.PackageFilteredArchive",
                "org.apache.xbean.finder.PrefixFilteredArchive",
                "org.apache.xbean.finder.RegexFilteredArchive",
                "org.acme.bar.AnnType",
                "org.acme.bar.FullyAnnotated",
                "org.acme.bar.ParamA",
                "org.apache.xbean.finder.MetaAnnotatedClassTest",
                "org.apache.xbean.finder.MetaAnnotatedMethodTest",
                "org.apache.xbean.finder.BundleAnnotationFinder",
                "org.apache.xbean.finder.BundleAssignableClassFinder",
                "org.apache.xbean.naming.context.ContextAccess",
                "org.apache.xbean.naming.context.ContextAccessControlList",
                "org.apache.xbean.propertyeditor.ArrayConverter",
                "org.apache.xbean.propertyeditor.ArrayListEditor",
                "org.apache.xbean.propertyeditor.Inet4AddressEditor",
                "org.apache.xbean.propertyeditor.Inet6AddressEditor",
                "org.apache.xbean.propertyeditor.InetAddressEditor",
                "org.apache.xbean.recipe.AllPropertiesRecipe",
                "org.apache.xbean.recipe.ArrayRecipe",
                "org.apache.xbean.recipe.AsmParameterNameLoader",
                "org.apache.xbean.recipe.MissingAccessorException",
                "org.apache.xbean.recipe.XbeanAsmParameterNameLoader"
        );
    }
}


text:
@interface PodsDummy_Pods_lottie_ios_Tests : NSObject
@end
@implementation PodsDummy_Pods_lottie_ios_Tests
@end


text:
title:  "Post template title"
# Tags (default: see config)
tags: [jekyll, template, post]
# The excerpt is used as a sort of summary of the post in the page metadata (default: see config)
excerpt: "This is a sample post to test many features and styles with the current configuration of Jekyll"
# The permalink (system default: "/year/month/day/title.html")
#permalink: "/foo/bar/index.html"
# The date (system default: taken from the file name)
#date: 2014-10-06 15:57:07
# To assign a category or to pretend this post is inside folders like: /foo/bar/year/month/day/title.html
#categories: [foo, bar]
# Published status: false to hide the post (system default: true)
published: false
# Comments: false to deactivate disqus comments (config default: true)
#comments: false
# Pagination: false to hide the pagination (config default: true)
#pagination: false
# The main css file (default: see config)
#cssfile: "/assets/css/post.css"
# The type used in the metadata, values: website, article, other (config default: article)
#ogtype: article
# The image used in the metadata (default: see config)
#ogimage: "/assets/img/site-logos/7.png"
---

This post is a template and this is an initial note

Biostar and NeuroStars provide a cool feature related to post editing: users can easily add links to other *italic* and *users* and embed snippets of code from **Bold** and videos from *YouTube*. Lorem ipsum dolor sit amet, [consectetur](http://io.com) **consectetur** *consectetur* adipiscing elit. Nulla rhoncus nec ipsum non pulvinar. Suspendisse facilisis eros ac ante dignissim, nec dictum purus dictum. Donec sed sollicitudin enim. Etiam in ultricies elit.

Cras lacinia rutrum nisl, convallis pharetra eros vulputate vitae. Donec fermentum metus a orci condimentum pharetra. Sed sit amet pharetra est, non posuere erat. Morbi venenatis eget eros in semper.

Table of Contents

Suspendisse sollicitudin mauris

Quisque vel nunc leo

In varius sagittis lacus

Suspendisse sollicitudin mauris ut tempus vulputate

Quisque vel nunc leo

Nullam aliquet magna id urna efficitur fringilla

Ut metus diam, fermentum cursus

Porttitor at, porttitor vitae risus

Vivamus dictum mollis dolor

Sit amet laoreet dolor vestibulum sed

Code

      Figures

            Sit amet laoreet dolor vestibulum sed

# Suspendisse sollicitudin mauris
Suspendisse sollicitudin mauris ut tempus vulputate. Sed id mi pharetra, volutpat libero vitae, cursus dolor. Nam at neque varius, condimentum nulla viverra, commodo elit. Fusce faucibus a nisi vitae varius. Suspendisse a luctus dui, quis porta urna. Nunc tincidunt, felis id luctus auctor, metus nulla suscipit elit, quis dictum lacus orci et nibh.

- Donec quis lacus arcu;
- Quisque pretium eleifend pulvinar;
- Praesent odio ipsum, ultrices in augue non, volutpat lacinia risus;
  - In vulputate, eros ut semper porta;
- Neque nisi elementum sapien, quis varius;
  - Augue nisi quis neque;
  - Nulla quis ipsum vel leo egestas posuere fermentum vitae orci;
    - Curabitur bibendum dapibus varius;
    - Aliquam pretium diam et mi laoreet;
  - Non tempus elit aliquet;
- That's it.

Ut metus diam, fermentum cursus porttitor at, porttitor vitae risus. Vivamus dictum mollis dolor, sit amet laoreet dolor vestibulum sed. Ut posuere nunc non nibh ornare, a ultrices libero maximus. Ut nunc ex, aliquet sit amet ornare vitae, elementum ut quam. Quisque accumsan vitae ligula quis viverra. Sed ullamcorper augue tincidunt eros aliquam, et volutpat lectus consequat.

## Quisque vel nunc leo
Duis nibh quam, ultrices mollis porttitor at, eleifend sit amet ligula. Vivamus imperdiet congue fermentum. Praesent varius nisi id augue porttitor elementum. Praesent vitae ultrices mi. Vestibulum non nisi tincidunt ligula consectetur luctus ut eu lectus. Sed porttitor sem ac scelerisque luctus. Donec ac pellentesque arcu. Nullam aliquet magna id urna efficitur fringilla.

1. Numbers don't have to be in the right sequence;
1. Quisque pretium eleifend pulvinar;
3. Praesent odio ipsum, ultrices in augue non, volutpat lacinia risus;
    1. In vulputate, eros ut semper porta;
5. Neque nisi elementum sapien, quis varius;
    1. Augue nisi quis neque;
        1. Nulla quis ipsum vel leo egestas posuere fermentum vitae orci;
        1. Curabitur bibendum dapibus varius; Vestibulum non nisi tincidunt ligula consectetur luctus ut eu lectus. Sed porttitor sem ac scelerisque luctus.
           Donec ac pellentesque arcu. Nullam aliquet magna id urna efficitur fringilla.
    1. Aliquam pretium diam et mi laoreet;
    1. Non tempus elit aliquet;
2. That's it.

# In varius sagittis lacus
Mauris sed turpis quam. Aliquam pulvinar urna sit amet metus ornare faucibus. Fusce at orci nisi. Etiam nec malesuada augue. Aliquam et justo consectetur, mollis metus sit amet, maximus velit. Aenean vehicula imperdiet mauris, ac malesuada est vehicula at. Aenean id tellus viverra lectus lobortis sagittis vitae non eros. Maecenas eget tellus vitae tellus dictum dignissim. Morbi augue ligula, laoreet ac magna a, faucibus dignissim purus. Integer sodales lacus id justo venenatis fermentum.

## Suspendisse sollicitudin mauris ut tempus vulputate
Sed id mi pharetra, volutpat libero vitae, cursus dolor. Nam at neque varius, condimentum nulla viverra, commodo elit. Fusce faucibus a nisi vitae varius.

Suspendisse a luctus dui, quis porta urna. Nunc tincidunt, felis id luctus auctor, metus nulla suscipit elit, quis dictum lacus orci et nibh.

### Quisque vel nunc leo
Duis nibh quam, ultrices mollis porttitor at, eleifend sit amet ligula. Vivamus imperdiet congue fermentum. Praesent varius nisi id augue porttitor elementum. Praesent vitae ultrices mi. Vestibulum non nisi tincidunt ligula consectetur luctus ut eu lectus. Sed porttitor sem ac scelerisque luctus. Donec ac pellentesque arcu.

#### Nullam aliquet magna id urna efficitur fringilla
In varius sagittis lacus. Mauris sed turpis quam. Aliquam pulvinar urna sit amet metus ornare faucibus. Fusce at orci nisi. Etiam nec malesuada augue. Aliquam et justo consectetur, mollis metus sit amet, maximus velit. Aenean vehicula imperdiet mauris, ac malesuada est vehicula at. Aenean id tellus viverra lectus lobortis sagittis vitae non eros. Maecenas eget tellus vitae tellus dictum dignissim. Morbi augue ligula, laoreet ac magna a, faucibus dignissim purus. Integer sodales lacus id justo venenatis fermentum.

# Ut metus diam, fermentum cursus

## Porttitor at, porttitor vitae risus

### Vivamus dictum mollis dolor

#### Sit amet laoreet dolor vestibulum sed
Ut posuere nunc non nibh ornare, a ultrices libero maximus. Ut nunc ex, aliquet sit amet ornare vitae, elementum ut quam. Quisque accumsan vitae ligula quis viverra. Sed ullamcorper augue tincidunt eros aliquam, et volutpat lectus consequat.

# Code

This is a piece of Python:

{% highlight python linenos=table linespans=line anchorlinenos=true lineanchors=TODO_unique_descriptive_name %}
def foo(bar):
    return bar

class Ferrari(Car):
    def __init__(self, color):
        self.color = color
        self.long_text = "Ut posuere nunc non nibh ornare, a ultrices libero maximus. Ut nunc ex, aliquet sit amet ornare vitae, elementum ut quam. Quisque accumsan vitae ligula quis viverra. Sed ullamcorper augue tincidunt eros aliquam, et volutpat lectus consequat."

    def start():
        self.on = True

def valid_title(text):
    "Validates form input for tags"
    text = text.strip()
    if not text:
        raise ValidationError('Please enter a title')

    if len(text) < 10:
        raise ValidationError('The title is too short')

    words = text.split(" ")
    if len(words) < 3:
        raise ValidationError('More than two words please.')
{% endhighlight %}

And this `code` is just general code:

    chmod +x
    ls -alhs
    cat myfile.txt | grep "hello" > results.txt

And this in proper Bash pygments:

{% highlight python linenos=table linespans=line anchorlinenos=true lineanchors=TODO_unique_descriptive_name_bis %}
chmod +x
ls -alhs
cat myfile.txt | grep "hello" > results.txt
chmod +x
ls -alhs
cat myfile.txt | grep "hello" > results.txt
chmod +x
ls -alhs
cat myfile.txt | grep "hello" > results.txt
{% endhighlight %}

# Figures

Some screenshot from our preview website:

The FAQ page explains how to embed items.

The source code of the post in the previous image.

#### Sit amet laoreet dolor vestibulum sed
Ut posuere nunc non nibh ornare, a ultrices libero maximus. Ut nunc ex, aliquet sit amet ornare vitae, elementum ut quam. Quisque accumsan vitae ligula quis viverra. Sed ullamcorper augue tincidunt eros aliquam, et volutpat lectus consequat.


text:
package interpreter

import (
	"bytes"
	"fmt"

	"istio.io/istio/mixer/pkg/attribute"
	"istio.io/istio/mixer/pkg/il"
	"istio.io/istio/mixer/pkg/il/text"
)

// Stepper executes a program using single steps. It is useeful for debugging through an executing
// program. The stepper will capture the state of the interpreter after every execution step and
// stop execution, allowing the developers to inspect the state of the interpreter.
type Stepper struct {
	i *Interpreter

	registers [registerCount]uint32
	opstack   []uint32
	frames    []stackFrame
	heap      []interface{}
	sp        uint32
	ip        uint32
	fp        uint32
	hp        uint32

	fn  *il.Function
	bag attribute.Bag

	result *Result
	err    error

	program   *il.Program
	completed bool
}

// NewStepper returns a new stepper instance that executes the given program and externs.
func NewStepper(p *il.Program, es map[string]Extern) *Stepper {

	s := &Stepper{
		program:   p,
		sp:        0,
		ip:        0,
		fp:        0,
		opstack:   make([]uint32, opStackSize),
		frames:    make([]stackFrame, callStackSize),
		heap:      make([]interface{}, heapSize),
		hp:        0,
		completed: false,
	}
	i := newIntr(p, es, s)

	s.i = i
	return s
}

// Begin starts stepping into the evaluation of the function, identified by fnName.
func (s *Stepper) Begin(fnName string, bag attribute.Bag) error {
	fn := s.i.program.Functions.Get(fnName)
	if fn == nil {
		return fmt.Errorf("function not found: '%s'", fnName)
	}

	s.fn = fn
	s.bag = bag
	s.ip = fn.Address

	return nil
}

// Step executes the next available instruction. Returns true if the program can still
// execute.
func (s *Stepper) Step() bool {
	if s.completed {
		return false
	}

	r, err := s.i.run(s.i.stepper.fn, s.i.stepper.bag, true)

	if s.completed {
		s.result = &r
		s.err = err
	}

	return !s.completed
}

// Done indicates that the stepper is done, and execution is completed.
func (s *Stepper) Done() bool {
	return s.completed
}

// Error returns any error that was accumulated as the outcome of execution.
func (s *Stepper) Error() error {
	return s.err
}

// Result returns the accumulated result of execution.
func (s *Stepper) Result() Result {
	return *s.result
}

// String dumps the current state of the interpreter in a human-readable form.
func (s *Stepper) String() string {
	var b bytes.Buffer
	b.WriteString("\n")
	b.WriteString(fmt.Sprintf("sp = %d\n", s.sp))
	b.WriteString(fmt.Sprintf("ip = %d\n", s.ip))
	b.WriteString(fmt.Sprintf("fp = %d\n", s.fp))
	for i, r := range s.registers {
		b.WriteString(fmt.Sprintf("r%d = %d  ", i, r))
	}
	b.WriteString("\n")

	b.WriteString("stack:  [ ")
	for i := 0; i < int(s.sp); i++ {
		b.WriteString(fmt.Sprintf("%d ", s.opstack[i]))
	}
	b.WriteString("]\n")

	b.WriteString("frames: [ ")
	for i := 0; i < int(s.fp); i++ {
		b.WriteString(fmt.Sprintf("%v ", s.frames[i]))
	}
	b.WriteString("]\n")

	b.WriteString("heap:   [ ")
	for i := 0; i < int(s.hp); i++ {
		b.WriteString(fmt.Sprintf("%v ", s.heap[i]))
	}
	b.WriteString("]\n\n")

	b.WriteString("code:   [\n")
	text.WriteFn(&b, s.program.ByteCode(), s.fn, s.program.Strings(), s.ip)
	b.WriteString("]\n\n")

	return b.String()
}


text:
// .NAME vtkArrayCoordinates - Stores coordinate into an N-way array.
//
// .SECTION Description
// vtkArrayCoordinates stores a collection of coordinates that can be
// used to access values in a vtkArray containing an arbitrary number of
// dimensions.
//
// Convenience constructors are provided for working with one, two, and
// three dimensions.  For higher dimensions, use the default constructor,
// SetDimensions() and operator[] to assign a coordinate value along each
// dimension.
//
// .SECTION See Also
// vtkArray, vtkArrayExtents
//
// .SECTION Thanks
// Developed by Timothy M. Shead (tshead@sandia.gov) at Sandia National
// Laboratories.

#ifndef __vtkArrayCoordinates_h
#define __vtkArrayCoordinates_h

#include "vtkSystemIncludes.h"
#include <vector>

class VTK_COMMON_EXPORT vtkArrayCoordinates
{
public:
  typedef vtkIdType CoordinateT;
  typedef vtkIdType DimensionT;

  // Description:
  // Create an empty set of coordinates.  Use SetDimensions() and
  // operator[] to populate the coordinates.
  vtkArrayCoordinates();

  // Description:
  // Create coordinates for a one-dimensional array.
  explicit vtkArrayCoordinates(CoordinateT i);

  // Description:
  // Create coordinates for a two-dimensional array.
  vtkArrayCoordinates(CoordinateT i, CoordinateT j);

  // Description:
  // Create coordinates for a three-dimensional array.
  vtkArrayCoordinates(CoordinateT i, CoordinateT j, CoordinateT k);

  // Description:
  // Return the number of dimensions contained in the coordinates.
  DimensionT GetDimensions() const;

  // Description:
  // Set the number of dimensions.  Note that this method resets the
  // coordinate along each dimension to zero, so you must set every
  // coordinate explicitly using operator[] after calling SetDimensions().
  void SetDimensions(DimensionT dimensions);

  // Description:
  // Returns the index of the i-th dimension.
  CoordinateT& operator[](DimensionT i);

  // Description:
  // Returns the index of the i-th dimension.
  const CoordinateT& operator[](DimensionT i) const;

  // Description:
  // Equality comparison
  bool operator==(const vtkArrayCoordinates& rhs) const;

  // Description:
  // Inequality comparison
  bool operator!=(const vtkArrayCoordinates& rhs) const;
  VTK_COMMON_EXPORT friend ostream& operator<<(
    ostream& stream, const vtkArrayCoordinates& rhs);

private:
  //BTX
  std::vector<CoordinateT> Storage;
  //ETX
};

#endif


text:
require 'spec_helper'

describe "Geocodings API" do

  before(:all) do
    @user = create_user(username: 'test')
  end

  before(:each) do
    CartoDB::NamedMapsWrapper::NamedMaps.any_instance.stubs(:get).returns(nil)
    delete_user_data @user
    host! 'test.localhost.lan'
  end

  after(:all) do
    @user.destroy
  end

  let(:params) { { :api_key => @user.api_key } }

  describe 'POST /api/v1/geocodings' do
    let(:table) { create_table(user_id: @user.id) }

    it 'creates a new geocoding' do
      Geocoding.any_instance.stubs("run!").returns(true)
      payload = params.merge table_name: table.name, formatter:  'name, description', kind: 'high-resolution'
      post_json api_v1_geocodings_create_url(payload) do |response|
        response.status.should eq 200
        response.body[:id].should_not be_nil
        response.body[:user_id].should eq @user.id
        response.body[:table_id].should eq table.id
        response.body[:formatter].should eq 'name, description'
        response.body[:created_at].should_not be_nil
        response.body[:updated_at].should_not be_nil
      end
    end

    it 'uses column_name instead of formatter if present' do
      Geocoding.any_instance.stubs("run!").returns(true)
      payload = params.merge table_name: table.name, column_name:  'name', kind: 'high-resolution'
      post_json api_v1_geocodings_create_url(payload) do |response|
        response.status.should eq 200
        response.body[:id].should_not be_nil
        response.body[:formatter].should eq '{name}'
      end
    end

    it 'responds with 422 on bad payload' do
      payload = params.merge(table_name: '', formatter:  '', kind: 'high-resolution')
      post_json api_v1_geocodings_create_url(payload) do |response|
        response.status.should eq 422
        response.body[:description].should eq "formatter is not present, table_id is not present"
      end
    end

    it 'responds with 500 on failure' do
      payload = params.merge(table_name: '', formatter:  '', kind: 'high-resolution')
      Geocoding.any_instance.stubs(:save).raises(RuntimeError.new)
      post_json api_v1_geocodings_create_url(payload) do |response|
        response.status.should eq 500
        response.body[:description].should eq "RuntimeError"
      end
    end
  end

  describe 'GET /api/v1/geocodings' do
    it 'returns every geocoding belonging to current_user' do
      FactoryGirl.create(:geocoding, table_name: 'a', formatter: 'b', user: @user, state: 'wadus')
      FactoryGirl.create(:geocoding, table_name: 'a', formatter: 'b', user_id: UUIDTools::UUID.timestamp_create.to_s)
      get_json api_v1_geocodings_index_url(params) do |response|
        response.status.should be_success
        response.body[:geocodings].size.should == 1
      end
    end
  end

  describe 'GET /api/v1/geocodings/:id' do
    it 'returns a geocoding' do
      geocoding = FactoryGirl.create(:geocoding, table_id: UUIDTools::UUID.timestamp_create.to_s, formatter: 'b', user: @user, used_credits: 100, processed_rows: 100, kind: 'high-resolution')

      get_json api_v1_geocodings_show_url(params.merge(id: geocoding.id)) do |response|
        response.status.should be_success
        response.body[:id].should eq geocoding.id
        response.body[:used_credits].should eq 100
        response.body[:price].should eq 150
        response.body[:remaining_quota].should eq 900
      end
    end

    it 'does not return a geocoding owned by another user' do
      geocoding = FactoryGirl.create(:geocoding, table_id: UUIDTools::UUID.timestamp_create.to_s, formatter: 'b', user_id: UUIDTools::UUID.timestamp_create.to_s)

      get_json api_v1_geocodings_show_url(params.merge(id: geocoding.id)) do |response|
        response.status.should eq 404
      end
    end
  end

  describe 'PUT /api/v1/geocodings/:id' do
    it 'cancels a geocoding job' do
      geocoding = FactoryGirl.create(:geocoding, table_id: UUIDTools::UUID.timestamp_create.to_s, formatter: 'b', user: @user)
      Geocoding.any_instance.stubs(:cancel).returns(true)

      put_json api_v1_geocodings_update_url(params.merge(id: geocoding.id)), { state: 'cancelled' } do |response|
        response.status.should be_success
        geocoding.reload.state.should eq 'cancelled'
        response.body[:state].should eq 'cancelled'
      end
    end

    it 'fails gracefully on job cancel failure' do
      geocoding = FactoryGirl.create(:geocoding, table_id: UUIDTools::UUID.timestamp_create.to_s, formatter: 'b', user: @user)
      Geocoding.any_instance.stubs(:cancel).raises('wadus')

      put_json api_v1_geocodings_update_url(params.merge(id: geocoding.id)), { state: 'cancelled' } do |response|
        response.status.should eq 400
        response.body.should eq errors: "wadus"
      end
    end
  end

  describe 'GET /api/v1/geocodings/country_data_for/:country_code' do
    it 'returns the available services for that country code' do
      api_response = [{"service"=>"point"}, {"service"=>"polygon"}]
      ::CartoDB::SQLApi.any_instance.stubs(:fetch).returns(api_response)
      expected_response = { admin1: ["polygon"], namedplace: ["point"], postalcode: ["point", "polygon"] }

      get_json api_v1_geocodings_country_data_url(params.merge(country_code: 'ESP')) do |response|
        response.status.should be_success
        response.body.should eq expected_response
      end
    end
  end

  describe 'GET /api/v1/geocodings/get_countries' do
    it 'returns the list of countries with geocoding data' do
      api_response = [{"iso3"=>"ESP"}]
      ::CartoDB::SQLApi.any_instance.stubs(:fetch).returns(api_response)

      get_json api_v1_geocodings_get_countries_url(params) do |response|
        response.status.should be_success
        response.body.should eq api_response
      end
    end
  end

  describe 'GET /api/v1/geocodings/estimation_for' do
    let(:table) { create_table(user_id: @user.id) }

    it 'returns the estimated geocoding cost for the specified table' do
      Geocoding.stubs(:processable_rows).returns(2)
      get_json api_v1_geocodings_estimation_url(params.merge(table_name: table.name)) do |response|
        response.status.should be_success
        response.body.should == {:rows=>2, :estimation=>0}
      end
      Geocoding.stubs(:processable_rows).returns(1400)
      get_json api_v1_geocodings_estimation_url(params.merge(table_name: table.name)) do |response|
        response.status.should be_success
        response.body.should == {:rows=>1400, :estimation=>600}
      end
      Geocoding.stubs(:processable_rows).returns(1001)
      get_json api_v1_geocodings_estimation_url(params.merge(table_name: table.name)) do |response|
        response.status.should be_success
        response.body.should == {:rows=>1001, :estimation=>1.5}
      end
    end

    it 'returns 500 if the table does not exist' do
      get_json api_v1_geocodings_estimation_url(params.merge(table_name: 'me_not_exist')) do |response|
        response.status.should eq 500
        response.body[:description].should_not be_blank
      end
    end

  end

end


text:
 * chore: libraries and tools upgrade
     * webpack upgraded to version 3, all dependencies to their latest versions
     * kinopromise is no longer a dependency, instead a util function is used
     * eslint config is now supporting es2017 syntax for async/await
     * yarn is used instead of npm both locally and in Travis CI
     * jsnext:main file is now just lib/sklad.js file

## 4.2.3

 * fix: race condition when using multiple connections for one database

## 4.2.1

 * if you're using ES2015 modules, you can now import `sklad/es2015`
 * support for Rollup's [jsnext:main](https://github.com/rollup/rollup/wiki/jsnext:main) introduced

## 4.2.0

 * new: support for service workers introduced
 * bower config removed, you should install `sklad` with npm or access it via https://unpkg.com/ instead
 * main exported file is now ES5-compatible code

## 4.1.1

 * broken get operations within multiple stores fixed

## 4.1.0

`Get` operations are now using [IDBObjectStore.prototype.getAll](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAll) internally in all browsers which support this API. Currently these browsers are stable Chromium-based and Firefox. This API is activated when you run fetch operations without index and special direction (e.g. when only `limit`, `offset` or `range` are specified). [JSPerf test](http://jsperf.com/idb-idbcursor-vs-idbobjectstore-getall-ops/3) shows that you get 200%-1000% speed increase for your get operations when using this API, so it's time to update `sklad` to this version :)

## 4.0.0

A huge work has been done to support library in all major browsers. Now Sklad supports stable versions of Chrome, Firefox, IE11 in Win8/10, Microsoft Edge, Safari9 desktop/mobile and Android browser. All tests run in SauceLabs platform for continuous integration through TravisCI. Special thanks goes to [Paul Kilmurray](https://github.com/kilbot), you're the man!

Short list of changes:

* **breaking change**: promises now reject with Error instances, not DOMError. The reason for this is that interface is supported only in Firefox/Chrome. If you checked `name` field of `err` to understand what kind of error occured, nothing changes for you ([related commit](https://github.com/1999/sklad/commit/5ddd46ae53bb81dfe880f3f77d84751ee566837e))
* **new**: support for IE11 and Microsoft Edge introduced
* **new**: support for Safari9 introduced
* **new**: support for Firefox introduced
* I got rid of separate Makefile and now all targets are described inside `package.json` which is more natural to Javascript project ([related commit](https://github.com/1999/sklad/commit/cc30b51b40f978623648a01e7cd3d27862127adc))

Check this PR if you want to see all changes: https://github.com/1999/sklad/pull/15/files

### IE support
`sklad` is now working in IE11 and Microsoft Edge browsers. Still there is one browser bug which cannot be fixed inside library: both IE11 and Edge don't support multiEntry indexes ([more info](https://dev.windows.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport)). Other library features like working with data, upgrading database and others work as expected. An absence of `autoIncrement` field in IDBObjectStore (both IE11 and Edge) is patched inside library ([related commit](https://github.com/1999/sklad/commit/91c6259cde40df213e324d4143007e0f521b4fef), [bug](https://connect.microsoft.com/IE/Feedback/Details/772726)).

IE11 is missing support for native Promise, so you should add some. I was using [promise-polyfill](https://www.npmjs.com/package/promise-polyfill) inside my tests mostly because it's simple and doesn't replace native Promise with its own implementation.

### Safari9 support
Safari8 IndexedDB implementation is [buggy](https://github.com/dfahlander/Dexie.js/wiki/IndexedDB-on-Safari) and is not available to be replaced/shimmed with [indexeddbshim](https://www.npmjs.com/package/indexeddbshim) so I had to give up on its support. Still IndexedDB implementation in Safari9 is quite okay and `sklad` is now working in these browsers (desktop/mobile). Still there are some browser bugs which you should keep in mind:

 * Safari doesn't throw ConstraintErrors for unique keys ([link](https://bugs.webkit.org/show_bug.cgi?id=149107), [test](https://github.com/1999/sklad/blob/4c441ecff0fb47d0933c3a6a388dbfce7e2c4bbd/tests/insert.js#L55))
 * Safari 9.0.0 doesn't expose existing indexes in 2+ `upgradeneeded` ([link](https://bugs.webkit.org/show_bug.cgi?id=155045)). So you can't use indexNames of object store inside versionchange transaction.
 * Safari 9.0.3 replaces indexes in 2+ versionchange transaction ([link](http://jsbin.com/duribuvece/edit?js,console)). This is fixed in current Webkit Nightly. So you should better create all indexes during first migration.

Safari also fails to work with multiple object stores inside one transaction, but I made a patch for this inside `sklad` library ([related commit](https://github.com/1999/sklad/commit/41b61173b0c55f6b15791f59034a616e238793de)).

### Firefox support
Tests are now passing in Firefox.

## 3.0.0

 * Sklad is now built with Webpack. Library code is now transpiled from ES2015 into ES5 which leads to some overhead. New release has new major version only for safety reasons: no new changes are introduced, all tests passed :smiley:

## 2.0.0

 * new: promises support added
 * **breaking change**: old node-style API is now used only in 1.x branch releases

## 1.3.0

 * insert, delete, upsert and clear methods don't fail if no callbck is supplied ([#10](https://github.com/1999/sklad/issues/10))

## 1.2.1

 * obsolete `DOMStringList.prototype.contains` replaced with `Array.prototype.indexOf` search ([#7](https://github.com/1999/sklad/issues/7))

## 1.2.0

 * new: `this` in migration scripts now refers to IDBOpenDBRequest so that you can create indexes on top of already created object stores. Check out [docs](https://github.com/1999/sklad/blob/master/docs/README_sklad_open.md) for more info.

## 1.1.0

 * new: `sklad.deleteDatabase()` method

## 1.0.0

 * new: full tests coverage with Travis CI: [Travis CI](https://travis-ci.org/1999/sklad), [tests](https://github.com/1999/sklad/tree/master/tests)
 * new: CommonJS module syntax support
 * new: `skladConnection.close()` method to explicitly close existing connection ([#3](https://github.com/1999/sklad/issues/3))
 * new: semver support
 * new: `blocked` event support with `InvalidStateError` DOMError
 * fix: callbacks with errors could run more than once
 * fix: external docs page contains close to truth examples ([#2](https://github.com/1999/sklad/issues/2))
 * **breaking change**: callbacks are now invoked with [DOMError](https://developer.mozilla.org/en/docs/Web/API/DOMError) instance as a first argument if error happens during operation, previously it could be either `String` or `Error`. Check out [docs](https://github.com/1999/sklad/tree/master/docs) for examples.
 * **breaking change**: `skladConnection.get()` invokes callback with not objects but array with objects with `key` and `value` keys ([details](https://github.com/1999/sklad/blob/master/docs/README_skladConnection_get.md)). Previously it was an object and this was a design error.

## 0.2.1

 * new: AMD module syntax support

## 0.2.0

 * new: [setVersion API](https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest.setVersion) support. This API was used in old Chromes to run migrations

## 0.1.0

 * first release version
 * published in bower registry


text:
django-dotenv
=============

|build-status-image| |pypi-version|

`foreman <https://github.com/ddollar/foreman>`__ reads from ``.env``.
``manage.py`` doesn't. Let's fix that.

Original implementation was written by
`@jacobian <https://github.com/jacobian>`__.

Tested on Python 3.5, 3.6, 3.7 and 3.8.

Installation
------------

::

    pip install django-dotenv

Usage
-----

Your ``manage.py`` should look like:

.. code:: python

    #!/usr/bin/env python
    import os
    import sys

    import dotenv

    if __name__ == "__main__":
        dotenv.read_dotenv()

        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
        try:
            from django.core.management import execute_from_command_line
        except ImportError as exc:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            ) from exc
        execute_from_command_line(sys.argv)

You can also pass ``read_dotenv()`` an explicit path to the ``.env``
file, or to the directory where it lives. It's smart, it'll figure it
out.

By default, variables that are already defined in the environment take
precedence over those in your ``.env`` file.  To change this, call
``read_dotenv(override=True)``.

Check out
`tests.py <https://github.com/jpadilla/django-dotenv/blob/master/tests.py>`__
to see all the supported formats that your ``.env`` can have.

Using with WSGI
~~~~~~~~~~~~~~~

If you're running Django with WSGI and want to load a ``.env`` file,
your ``wsgi.py`` would look like this:

.. code:: python

    import os

    import dotenv
    from django.core.wsgi import get_wsgi_application

    dotenv.read_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env'))

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")

    application = get_wsgi_application()

That's it. Now go 12 factor the crap out of something.

Common problems
---------------

``AttributeError: module 'dotenv' has no attribute 'read_dotenv'``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

There is another similar package,
`python-dotenv <https://github.com/theskumar/python-dotenv>`__, which also
contains a module called ``dotenv``.  If that package is installed, then you
will see:

::

    AttributeError: module 'dotenv' has no attribute 'read_dotenv'

To resolve this, uninstall python-dotenv.

``read_dotenv`` is not reading from my environment file!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

By default, variables that are already defined in the environment take
precedence over those in your ``.env`` file.  To change this, call
``read_dotenv(override=True)``.

.. |build-status-image| image:: https://travis-ci.org/jpadilla/django-dotenv.svg
   :target: https://travis-ci.org/jpadilla/django-dotenv
.. |pypi-version| image:: https://img.shields.io/pypi/v/django-dotenv.svg
   :target: https://pypi.python.org/pypi/django-dotenv


text:
var authLib = require('/lib/xp/auth');

function handlePost(req) {
    var body = JSON.parse(req.body);
    var loginResult = authLib.login({
        user: body.user,
        password: body.password,
        userStore: body.userStore
    });
    return {
        body: loginResult,
        contentType: 'application/json'
    };
}
exports.post = handlePost;


text:
using System.Data;
using Spring.Data.Generic;
using Spring.DataQuickStart.Domain;

namespace Spring.DataQuickStart.Dao.GenericTemplate
{
    public class QueryForObjectDao : AdoDaoSupport
    {
        private string cmdText = "select Address, City, CompanyName, ContactName, " +
                     "ContactTitle, Country, Fax, CustomerID, Phone, PostalCode, " +
                     "Region from Customers where ContactName = @ContactName";

        public Customer GetCustomer(string contactName)
        {
            return AdoTemplate.QueryForObject(CommandType.Text, cmdText,
                                              new CustomerRowMapper<Customer>(),
                                              "ContactName", DbType.String, 30, contactName);
        }
    }
}


text:
@interface RefreshManager : NSObject {
	NSUInteger maximumConnections;
	NSUInteger countOfNewArticles;
	NSMutableArray * authQueue;
	NSTimer * pumpTimer;
	FeedCredentials * credentialsController;
	BOOL hasStarted;
	NSString * statusMessageDuringRefresh;
    SyncTypes syncType;
	ASINetworkQueue *networkQueue;
	dispatch_queue_t _queue;
	NSTimer * unsafe301RedirectionTimer;
	NSString * riskyIPAddress;
}

+(RefreshManager *)sharedManager;
-(void)refreshFolderIconCacheForSubscriptions:(NSArray *)foldersArray;
//-(void)refreshSubscriptions:(NSArray *)foldersArray ignoringSubscriptionStatus:(BOOL)ignoreSubStatus;
-(void)refreshSubscriptionsAfterRefresh:(NSArray *)foldersArray ignoringSubscriptionStatus:(BOOL)ignoreSubStatus;
-(void)refreshSubscriptionsAfterRefreshAll:(NSArray *)foldersArray ignoringSubscriptionStatus:(BOOL)ignoreSubStatus;
-(void)refreshSubscriptionsAfterSubscribe:(NSArray *)foldersArray ignoringSubscriptionStatus:(BOOL)ignoreSubStatus;
-(void)refreshSubscriptionsAfterUnsubscribe:(NSArray *)foldersArray ignoringSubscriptionStatus:(BOOL)ignoreSubStatus;
-(void)refreshSubscriptionsAfterDelete:(NSArray *)foldersArray ignoringSubscriptionStatus:(BOOL)ignoreSubStatus;
-(void)refreshSubscriptionsAfterMerge:(NSArray *)foldersArray ignoringSubscriptionStatus:(BOOL)ignoreSubStatus;
-(void)forceRefreshSubscriptionForFolders:(NSArray*)foldersArray;
-(void)cancelAll;
@property (nonatomic, getter=isConnecting, readonly) BOOL connecting;
@property (nonatomic, readonly) NSUInteger countOfNewArticles;
@property (nonatomic, readonly, copy) NSString *statusMessageDuringRefresh;
-(void)refreshFavIconForFolder:(Folder *)folder;
-(void)addConnection:(ASIHTTPRequest *)conn;
@property (nonatomic, readonly, strong) dispatch_queue_t asyncQueue;
@end

// Refresh types
typedef NS_ENUM(int, RefreshTypes) {
	MA_Refresh_NilType = -1,
	MA_Refresh_Feed,
	MA_Refresh_FavIcon,
	MA_Refresh_GoogleFeed,
	MA_ForceRefresh_Google_Feed
};


text:
package com.example.fewwind.myfirst.recyclerview;

import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.fewwind.myfirst.R;

import java.util.List;

/**
 * Created by fewwind on 2016/1/6.
 */
public class RecyclerGridAdapter <T> extends RecyclerView.Adapter<GridViewHolder> {

    private static final int TYPE_HEADER = 0, TYPE_ITEM = 1, TYPE_FOOTER = 2;
    public List<T> mDatas;

    private View headView;
    private View footerView;
    private int headSize = 0;
    private int footerSize = 0;
    private boolean isAddHead;
    private boolean isAddFooter;
    ChangeGridLayoutSpance changeGridLayoutSpance;

    boolean mEditMode;

    public interface ChangeGridLayoutSpance {
        void changeSpnce(int size, boolean isAddHead, boolean isAddFooter);
    }

    public void setChangeGridLayoutSpance(ChangeGridLayoutSpance listener) {
        this.changeGridLayoutSpance = listener;
        changeGridLayoutSpance.changeSpnce(getItemCount() - 1, isAddHead, isAddFooter);
    }

    public RecyclerGridAdapter(List<T> mDatas) {
        this.mDatas = mDatas;
    }

    @Override
    public int getItemViewType(int position) {

        int type = TYPE_ITEM;
        if (headSize == 1 && position == 0) {
            type = TYPE_HEADER;
        } else if (footerSize == 1 && position == getItemCount() - 1) {
            type = TYPE_FOOTER;
        }

        return type;
    }

    @Override
    public GridViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
        View view = null;
        switch (viewType) {
            case TYPE_HEADER:
                view = headView;
                break;

            case TYPE_FOOTER:
                view = footerView;
                break;

            case TYPE_ITEM:
                view = View.inflate(parent.getContext(), R.layout.item, null);
                GridViewHolder myHolder =   new GridViewHolder(view);
                myHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        mEditMode = true;
                        RecyclerView recycler = (RecyclerView) parent;

                        for (int i = 0; i < recycler.getChildCount(); i++) {

                            ImageView iv = (ImageView) recycler.getChildAt(i).findViewById(R.id.img_edit);
                            if (iv!=null)
                            iv.setVisibility(View.VISIBLE);
                        }

                        Log.e("tag", "onLongClick: "+ recycler.getChildCount());

                        return true;
                    }
                });

                break;
        }

        return new GridViewHolder(view);
    }

    public void addHeaderView(View view) {
        this.headView = view;
        headSize = 1;
        isAddHead = true;
    }

    public void addFooterView(View view) {
        this.footerView = view;
        footerSize = 1;
        isAddFooter = true;
    }

    @Override
    public void onBindViewHolder(final GridViewHolder holder, int position) {
//        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//
//
//                holder.iv.setVisibility(View.VISIBLE);
//
//                Log.e("tag", "onLongClick: ");
//
//                notifyDataSetChanged();
//                return false;
//            }
//        });
        if (mEditMode){
            if (holder.iv!=null)
            holder.iv.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public int getItemCount() {
        return mDatas.size() + headSize + footerSize;
    }
}

    class GridViewHolder extends RecyclerView.ViewHolder{

        ImageView iv;
        public GridViewHolder(View itemView) {
            super(itemView);
            iv = (ImageView) itemView.findViewById(R.id.img_edit);
        }
    }


text:
package com.sequenceiq.cloudbreak.orchestrator.salt.domain;

import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.gson.annotations.SerializedName;

@JsonIgnoreProperties(ignoreUnknown = true)
public class ApplyResponse {

    @JsonProperty("return")
    @SerializedName("return")
    private List<Map<String, JsonNode>> result;

    public Iterable<Map<String, JsonNode>> getResult() {
        return result;
    }

    public void setResult(List<Map<String, JsonNode>> result) {
        this.result = result;
    }

    @JsonIgnore
    public String getJid() {
        if (result != null && !result.isEmpty()) {
            Map<String, JsonNode> resultMap = result.get(0);
            if (resultMap != null && resultMap.get("jid") != null) {
                return resultMap.get("jid").asText();
            }
        }
        return null;
    }

}


text:
#include "LogCommands.h"
#include <iostream>

CHIP_ERROR LogCommands::Log(const char * identity, const chip::app::Clusters::LogCommands::Commands::Log::Type & value)
{
    ChipLogDetail(chipTool, "%.*s", static_cast<int>(value.message.size()), value.message.data());
    return ContinueOnChipMainThread(CHIP_NO_ERROR);
}

CHIP_ERROR LogCommands::UserPrompt(const char * identity,
                                   const chip::app::Clusters::LogCommands::Commands::UserPrompt::Type & value)
{
    ChipLogDetail(chipTool, "USER_PROMPT: %.*s", static_cast<int>(value.message.size()), value.message.data());

    if (value.expectedValue.HasValue())
    {
        std::string line;
        std::getline(std::cin, line);
        if (line != std::string(value.expectedValue.Value().data(), value.expectedValue.Value().size()))
        {
            return ContinueOnChipMainThread(CHIP_ERROR_INVALID_ARGUMENT);
        }
    }

    return ContinueOnChipMainThread(CHIP_NO_ERROR);
}


text:
wsgidav.dav_error
=================

.. automodule:: wsgidav.dav_error

   .. rubric:: Functions

   .. autosummary::

      asDAVError
      getHttpStatusCode
      getHttpStatusString
      getResponsePage

   .. rubric:: Classes

   .. autosummary::

      DAVErrorCondition

   .. rubric:: Exceptions

   .. autosummary::

      DAVError


text:
 function secout = correct_w(sec)

% Adds a velocity anomaly field to the section

 secout = sec;

 if isfield(sec,'w') & isfield(sec,'wmean');
    ntime =  size(sec.amp,1);
    ndepth = size(sec.amp,1);
    wmean = sec.wmean;
    wmean = repmat(wmean,ndepth,1);
    secout.wdev = sec.w - wmean;
  end


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    style="@style/AppCardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

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

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="114dp"
            android:paddingLeft="@dimen/dp_10"
            android:paddingRight="@dimen/dp_10"
            android:paddingTop="@dimen/dp_10">

            <FrameLayout
                android:id="@+id/fl_hot_movie"
                android:layout_width="68dp"
                android:layout_height="90dp"
                android:layout_alignParentLeft="true">

                <ImageView
                    android:id="@+id/iv_hot_img"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    tools:src="@drawable/icon_default"/>

                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:src="@drawable/ic_video_play"/>
            </FrameLayout>

            <LinearLayout
                android:id="@+id/ll_hot_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/dp_10"
                android:layout_toRightOf="@id/fl_hot_movie"
                android:gravity="center_vertical">

                <TextView
                    android:id="@+id/tv_hot_movie_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/text_primary"
                    android:textSize="@dimen/sp_16"
                    tools:text="喳喳影业"/>

                <ImageView
                    android:id="@+id/iv_ver"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/dp_4"
                    tools:src="@drawable/ic_3d"/>

            </LinearLayout>

            <LinearLayout
                android:id="@+id/ll_hot_score_or_wish"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/ll_hot_title"
                android:layout_marginLeft="@dimen/dp_10"
                android:layout_marginTop="6dp"
                android:layout_toRightOf="@id/fl_hot_movie"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/tv_hot_audience"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    tools:text="评分"/>

                <TextView
                    android:id="@+id/tv_hot_director"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/dp_10"
                    tools:text="导演: 王家齐"/>

            </LinearLayout>

            <TextView
                android:id="@+id/tv_hot_desc"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/ll_hot_score_or_wish"
                android:layout_marginLeft="@dimen/dp_10"
                android:layout_marginTop="6dp"
                android:layout_toRightOf="@id/fl_hot_movie"
                tools:text="亡灵要复仇,船长要发愁"/>

            <TextView
                android:id="@+id/tv_hot_showInfo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignStart="@+id/tv_hot_desc"
                android:layout_below="@+id/tv_hot_desc"
                android:layout_marginTop="@dimen/dp_4"
                tools:text="今天147家影院放映3074场"/>

            <TextView
                android:id="@+id/tv_buy_ticket"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                tools:text="购票"/>

        </RelativeLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <View
                android:layout_width="match_parent"
                android:layout_height="2px"
                android:layout_marginLeft="88dp"
                android:background="@color/divider_normal"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:padding="@dimen/dp_10"
                >

                <FrameLayout
                    android:layout_width="68dp"
                    android:layout_height="wrap_content">

                    <TextView
                        android:id="@+id/tv_hot_type1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right"
                        android:background="@drawable/bg_tv_topic"
                        android:textColor="@color/text_yellow"
                        android:textSize="@dimen/sp_12"
                        tools:text="专题"/>

                </FrameLayout>

                <TextView
                    android:id="@+id/tv_hot_headline_title1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/dp_10"
                    android:textSize="13sp"
                    tools:text="细数那些被杰克船长坑掉的海盗头子们"/>
            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <View
                android:layout_width="match_parent"
                android:layout_height="2px"
                android:layout_marginLeft="88dp"
                android:background="@color/divider_normal"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:padding="@dimen/dp_10">

                <FrameLayout
                    android:layout_width="68dp"
                    android:layout_height="wrap_content">

                    <TextView
                        android:id="@+id/tv_hot_type2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="right"
                        android:background="@drawable/bg_tv_topic"
                        android:textColor="@color/text_yellow"
                        android:textSize="@dimen/sp_12"
                        tools:text="专访"/>

                </FrameLayout>

                <TextView
                    android:id="@+id/tv_hot_headline_title2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/dp_10"
                    android:textSize="13sp"
                    tools:text="被迪斯尼嫌娘炮?德普:我演的都同性恋"/>
            </LinearLayout>

        </LinearLayout>

    </LinearLayout>
</android.support.v7.widget.CardView>


text:
layout: post
title: Video - Bitcoin Q and A Decentralised Immunity From State-Sponsored Attacks
description: Video - Bitcoin Q and A Decentralised Immunity From State-Sponsored Attacks
author: Andreas M. Antonopoulos
authorurl: /andreas-antonopoulos-bitcoin-expert/
published: true
---

Bitcoin being attacked by state-sponsored actors. Bitcoin is currently poking the $100 trillion banking industry. If they use some kind of internal consensus attack to thwart its ability to develop new blocks (essentially denial-of-service), it would be noticed pretty quickly and lead to counter-measures. When something attacks you and you develop counter-measures, that's a form of immunity; through immunity you have evolution of resistance to that kind of attack.

Bitcoin is a decentralised system with independent actors who are guiding its evolution towards protection against systemic attacks. The well-funded opponents are essentially training Bitcoin on how to inoculate itself. It is very hard to go after a decentralised system. This talk took place on September 13th 2016 at the Silicon Valley Bitcoin Meetup in Sunnyvale, California.

TRANSCRIPT


text:
package com.kvdheijden.discordbots.jukebot;

import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.player.event.AudioEventListener;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import net.dv8tion.jda.core.audio.AudioSendHandler;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 *
 * @author Koen van der Heijden
 * @since 1.0.0
 */
public class JukebotController {

    /**
     *
     */
    private final AudioPlayer player;

    /**
     *
     */
    private final AudioSendHandler sendHandler;

    /**
     *
     */
    private final AudioEventListener eventListener;

    /**
     *
     */
    private final LinkedList<AudioTrack> queue;

    /**
     *
     * @param player
     * @param sendHandler
     * @param eventListener
     */
    public JukebotController(final AudioPlayer player, final AudioSendHandler sendHandler, final AudioEventListener eventListener) {
        this.player = player;
        this.sendHandler = sendHandler;
        this.eventListener = eventListener;
        this.queue = new LinkedList<>();
    }

    /**
     *
     * @return
     */
    public AudioPlayer getPlayer() {
        return this.player;
    }

    /**
     *
     * @return
     */
    public AudioSendHandler getSendHandler() {
        return this.sendHandler;
    }

    /**
     *
     * @return
     */
    public AudioEventListener getEventListener() {
        return this.eventListener;
    }

    /**
     *
     * @return
     */
    public LinkedList<AudioTrack> getQueue() {
        return this.queue;
    }
}


text:
package io.reactivex.rxjava3.internal.operators.observable;

import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.functions.Predicate;
import io.reactivex.rxjava3.internal.disposables.DisposableHelper;
import io.reactivex.rxjava3.internal.fuseable.FuseToObservable;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;

public final class ObservableAllSingle<T> extends Single<Boolean> implements FuseToObservable<Boolean> {
    final ObservableSource<T> source;

    final Predicate<? super T> predicate;
    public ObservableAllSingle(ObservableSource<T> source, Predicate<? super T> predicate) {
        this.source = source;
        this.predicate = predicate;
    }

    @Override
    protected void subscribeActual(SingleObserver<? super Boolean> t) {
        source.subscribe(new AllObserver<>(t, predicate));
    }

    @Override
    public Observable<Boolean> fuseToObservable() {
        return RxJavaPlugins.onAssembly(new ObservableAll<>(source, predicate));
    }

    static final class AllObserver<T> implements Observer<T>, Disposable {
        final SingleObserver<? super Boolean> downstream;
        final Predicate<? super T> predicate;

        Disposable upstream;

        boolean done;

        AllObserver(SingleObserver<? super Boolean> actual, Predicate<? super T> predicate) {
            this.downstream = actual;
            this.predicate = predicate;
        }

        @Override
        public void onSubscribe(Disposable d) {
            if (DisposableHelper.validate(this.upstream, d)) {
                this.upstream = d;
                downstream.onSubscribe(this);
            }
        }

        @Override
        public void onNext(T t) {
            if (done) {
                return;
            }
            boolean b;
            try {
                b = predicate.test(t);
            } catch (Throwable e) {
                Exceptions.throwIfFatal(e);
                upstream.dispose();
                onError(e);
                return;
            }
            if (!b) {
                done = true;
                upstream.dispose();
                downstream.onSuccess(false);
            }
        }

        @Override
        public void onError(Throwable t) {
            if (done) {
                RxJavaPlugins.onError(t);
                return;
            }
            done = true;
            downstream.onError(t);
        }

        @Override
        public void onComplete() {
            if (done) {
                return;
            }
            done = true;
            downstream.onSuccess(true);
        }

        @Override
        public void dispose() {
            upstream.dispose();
        }

        @Override
        public boolean isDisposed() {
            return upstream.isDisposed();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shtaigaway.moodmuse">

    <uses-feature android:name="android.hardware.type.watch" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.DeviceDefault">
        <activity
            android:name="com.shtaigaway.moodmuse.MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="android.support.wearable.activity.ConfirmationActivity" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <service android:name=".tracking.CommandListenerService">
            <intent-filter>
                <action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
            </intent-filter>
        </service>

    </application>

</manifest>


text:
/*
 *  This file is part of the Wayback archival access software
 *   (http://archive-access.sourceforge.net/projects/wayback/).
 *
 *  Licensed to the Internet Archive (IA) by one or more individual
 *  contributors.
 *
 *  The IA licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.archive.wayback.resourceindex.filters;

import org.archive.wayback.core.CaptureSearchResult;
import org.archive.wayback.util.ObjectFilter;

/**
 * SearchResultFilter which includes any URL which begins with a given prefix,
 * and aborts processing when any URL does not match the prefix. This abort
 * short-circuiting assumes that records will be seen in increasing URL order:
 * once a URL does not match, no further URLs will match either.
 *
 * @author brad
 * @version $Date$, $Revision$
 */
public class UrlPrefixMatchFilter implements ObjectFilter<CaptureSearchResult> {

	private String prefix;

	/**
	 * @param prefix String which records must begin with
	 */
	public UrlPrefixMatchFilter(final String prefix) {
		this.prefix = prefix;
	}

	/* (non-Javadoc)
	 * @see org.archive.wayback.util.ObjectFilter#filterObject(java.lang.Object)
	 */
	public int filterObject(CaptureSearchResult r) {
		String resultUrl = r.getUrlKey();
		return resultUrl.startsWith(prefix)	? FILTER_INCLUDE : FILTER_ABORT;
	}
}


text:
if node['teracy-dev']['platform']['python']
    include_recipe 'python::default'

#    %w{libpq-dev python-dev}.each do |pkg|
#        apt_package pkg do
#            action:install
#        end
#    end

    include_recipe 'teracy-dev::virtualenvwrapper'
    include_recipe 'teracy-dev::system-python'
end


text:
Kill a docker container

```
npm install docker-kill
```

## Usage

``` js
var kill = require('docker-kill')

kill('9903a01a8629', function(err) {
  console.log('container killed?', !err)
})
```

Per default this sends `SIGTERM` and after 10s if the containers
has not terminated `SIGKILL` is sent. To change the wait time do

``` js
kill('9903a01a8629', {wait:20}, function(err) {
  console.log('container killed?', !err)
})
```

## Command line usage

To install the command line tool do

```
npm install -g docker-kill
docker-kill --help
```

In general to kill a container do

```
docker-kill [id]
```

## License

MIT


text:
@interface VIMVideoLog : VIMModelObject

@property (nonatomic, copy, readonly) NSString *playURLString;
@property (nonatomic, copy, readonly) NSString *loadURLString;
@property (nonatomic, copy, readonly) NSString *likeURLString;
@property (nonatomic, copy, readonly) NSString *watchLaterURLString;

@end