text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PlainLogic.ViscaController.Visca.Responses;

namespace PlainLogic.ViscaController.Visca
{
    public enum ResponseTypes
    {
        Acknowledgement,
        CommandComplete,
        InqueryComplete,
        Error
    }

    public abstract class ViscaResponse
    {
        public ResponseTypes ResponseType { get; private set; }

        public byte SourceAddress { get; private set; }
        public byte Socket { get; private set; }

        internal static ViscaResponse ProcessResponse( byte[] packet, ViscaCommand pendingCmd, out bool matchesPending )
        {
            byte src = (byte)( packet[0] >> 4 );
            byte socket = (byte)( packet[1] & 0x0F );
            byte replyType = (byte)( packet[1] >> 4 );

            matchesPending = false;

            if( packet.Last() != 0xFF ) throw new ArgumentException( "Invalid Data:  Does not end with expected 0xFF" );

            ViscaResponse response =  null;

            switch( replyType )
            {
                case 4: //Ack
                    if( pendingCmd == null ) throw new InvalidOperationException();

                    response = new Acknowledgement();
                    matchesPending = true;
                    break;

                case 5: //Completion (commands/inquiries)
                    if( packet.Length == 3 ) //Command Complete
                    {
                        response = new CommandComplete();
                    }
                    else
                    {
                        matchesPending = true;
                        response = (ViscaInquiryResponse)Activator.CreateInstance( pendingCmd.InquiryResponseType );
                    }
                    break;

                case 6: //Error
                    if( packet.Length != 4 ) throw new ArgumentException( "Invalid Data: Error Packet not correct." );
                    response = new CommandError( packet[2] );

                    if( pendingCmd != null ) matchesPending = true;

                    break;

                default: throw new NotSupportedException();
            }

            response.SourceAddress = src;
            response.Socket = socket;

            if( response is ViscaInquiryResponse )
            {
                //process only the meat data of the packet (strip out header and footer bytes)
                byte[] data = new byte[packet.Length - 3];

                Array.Copy( packet, 2, data, 0, packet.Length - 3 );

                ( (ViscaInquiryResponse)response ).ProcessResponse_Internal( data );
            }

            return response;
        }

        internal ViscaResponse( ResponseTypes type )
        {
            ResponseType = type;
        }
    }

    public abstract class ViscaInquiryResponse : ViscaResponse
    {
        protected ViscaInquiryResponse() : base( ResponseTypes.InqueryComplete ) { }

        internal void ProcessResponse_Internal( byte[] data )
        {
            OnProcessResponse( data );
        }

        protected abstract void OnProcessResponse( byte[] data );
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>IEndpointLifecycleSubscriber (apache-cassandra API)</title>
<meta name="date" content="2014-09-07">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.service

Interface IEndpointLifecycleSubscriber

public interface IEndpointLifecycleSubscriber

Interface on which interested parties can be notified of high level endpoint
 state changes.

 Note that while IEndpointStateChangeSubscriber notify about gossip related
 changes (IEndpointStateChangeSubscriber.onJoin() is called when a node join
 gossip), this interface allows to be notified about higher level events.

Method Summary

Methods

Modifier and Type
Method and Description

void
onDown(java.net.InetAddress endpoint)

Called when a node is marked DOWN.

void
onJoinCluster(java.net.InetAddress endpoint)

Called when a new node joins the cluster, i.e.

void
onLeaveCluster(java.net.InetAddress endpoint)

Called when a new node leave the cluster (decommission or removeToken).

void
onMove(java.net.InetAddress endpoint)

Called when a node has moved (to a new token).

void
onUp(java.net.InetAddress endpoint)

Called when a node is marked UP.

Method Detail

onJoinCluster

void onJoinCluster(java.net.InetAddress endpoint)

Called when a new node joins the cluster, i.e. either has just been
 bootstrapped or "instajoins".

Parameters:

endpoint - the newly added endpoint.

onLeaveCluster

void onLeaveCluster(java.net.InetAddress endpoint)

Called when a new node leave the cluster (decommission or removeToken).

Parameters:

endpoint - the endpoint that is leaving.

onUp

void onUp(java.net.InetAddress endpoint)

Called when a node is marked UP.

Parameters:

endpoint - the endpoint marked UP.

onDown

void onDown(java.net.InetAddress endpoint)

Called when a node is marked DOWN.

Parameters:

endpoint - the endpoint marked DOWN.

onMove

void onMove(java.net.InetAddress endpoint)

Called when a node has moved (to a new token).

Parameters:

endpoint - the endpoint that has moved.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2014 The Apache Software Foundation

redpajama_set_name: RedPajamaGithub


text:
/* Linuxthreads - a simple clone()-based implementation of Posix        */
/* threads for Linux.                                                   */
/* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr)              */
/*                                                                      */
/* This program is free software; you can redistribute it and/or        */
/* modify it under the terms of the GNU Library General Public License  */
/* as published by the Free Software Foundation; either version 2       */
/* of the License, or (at your option) any later version.               */
/*                                                                      */
/* This program is distributed in the hope that it will be useful,      */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of       */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        */
/* GNU Library General Public License for more details.                 */

/* Mutexes */

#include <bits/libc-lock.h>
#include <errno.h>
#include <sched.h>
#include <stddef.h>
#include <limits.h>
#include "pthread.h"
#include "internals.h"
#include "spinlock.h"
#include "queue.h"
#include "restart.h"

int __pthread_mutex_init(pthread_mutex_t * mutex,
                       const pthread_mutexattr_t * mutex_attr)
{
  __pthread_init_lock(&mutex->__m_lock);
  mutex->__m_kind =
    mutex_attr == NULL ? PTHREAD_MUTEX_TIMED_NP : mutex_attr->__mutexkind;
  mutex->__m_count = 0;
  mutex->__m_owner = NULL;
  return 0;
}
strong_alias (__pthread_mutex_init, pthread_mutex_init)

int __pthread_mutex_destroy(pthread_mutex_t * mutex)
{
  switch (mutex->__m_kind) {
  case PTHREAD_MUTEX_ADAPTIVE_NP:
  case PTHREAD_MUTEX_RECURSIVE_NP:
    if ((mutex->__m_lock.__status & 1) != 0)
      return EBUSY;
    return 0;
  case PTHREAD_MUTEX_ERRORCHECK_NP:
  case PTHREAD_MUTEX_TIMED_NP:
    if (mutex->__m_lock.__status != 0)
      return EBUSY;
    return 0;
  default:
    return EINVAL;
  }
}
strong_alias (__pthread_mutex_destroy, pthread_mutex_destroy)

int __pthread_mutex_trylock(pthread_mutex_t * mutex)
{
  pthread_descr self;
  int retcode;

  switch(mutex->__m_kind) {
  case PTHREAD_MUTEX_ADAPTIVE_NP:
    retcode = __pthread_trylock(&mutex->__m_lock);
    return retcode;
  case PTHREAD_MUTEX_RECURSIVE_NP:
    self = thread_self();
    if (mutex->__m_owner == self) {
      mutex->__m_count++;
      return 0;
    }
    retcode = __pthread_trylock(&mutex->__m_lock);
    if (retcode == 0) {
      mutex->__m_owner = self;
      mutex->__m_count = 0;
    }
    return retcode;
  case PTHREAD_MUTEX_ERRORCHECK_NP:
    retcode = __pthread_alt_trylock(&mutex->__m_lock);
    if (retcode == 0) {
      mutex->__m_owner = thread_self();
    }
    return retcode;
  case PTHREAD_MUTEX_TIMED_NP:
    retcode = __pthread_alt_trylock(&mutex->__m_lock);
    return retcode;
  default:
    return EINVAL;
  }
}
strong_alias (__pthread_mutex_trylock, pthread_mutex_trylock)

int __pthread_mutex_lock(pthread_mutex_t * mutex)
{
  pthread_descr self;

  switch(mutex->__m_kind) {
  case PTHREAD_MUTEX_ADAPTIVE_NP:
    __pthread_lock(&mutex->__m_lock, NULL);
    return 0;
  case PTHREAD_MUTEX_RECURSIVE_NP:
    self = thread_self();
    if (mutex->__m_owner == self) {
      mutex->__m_count++;
      return 0;
    }
    __pthread_lock(&mutex->__m_lock, self);
    mutex->__m_owner = self;
    mutex->__m_count = 0;
    return 0;
  case PTHREAD_MUTEX_ERRORCHECK_NP:
    self = thread_self();
    if (mutex->__m_owner == self) return EDEADLK;
    __pthread_alt_lock(&mutex->__m_lock, self);
    mutex->__m_owner = self;
    return 0;
  case PTHREAD_MUTEX_TIMED_NP:
    __pthread_alt_lock(&mutex->__m_lock, NULL);
    return 0;
  default:
    return EINVAL;
  }
}
strong_alias (__pthread_mutex_lock, pthread_mutex_lock)

int __pthread_mutex_timedlock (pthread_mutex_t *mutex,
			       const struct timespec *abstime)
{
  pthread_descr self;
  int res;

  if (__builtin_expect (abstime->tv_nsec, 0) < 0
      || __builtin_expect (abstime->tv_nsec, 0) >= 1000000000)
    return EINVAL;

  switch(mutex->__m_kind) {
  case PTHREAD_MUTEX_ADAPTIVE_NP:
    __pthread_lock(&mutex->__m_lock, NULL);
    return 0;
  case PTHREAD_MUTEX_RECURSIVE_NP:
    self = thread_self();
    if (mutex->__m_owner == self) {
      mutex->__m_count++;
      return 0;
    }
    __pthread_lock(&mutex->__m_lock, self);
    mutex->__m_owner = self;
    mutex->__m_count = 0;
    return 0;
  case PTHREAD_MUTEX_ERRORCHECK_NP:
    self = thread_self();
    if (mutex->__m_owner == self) return EDEADLK;
    res = __pthread_alt_timedlock(&mutex->__m_lock, self, abstime);
    if (res != 0)
      {
	mutex->__m_owner = self;
	return 0;
      }
    return ETIMEDOUT;
  case PTHREAD_MUTEX_TIMED_NP:
    /* Only this type supports timed out lock. */
    return (__pthread_alt_timedlock(&mutex->__m_lock, NULL, abstime)
	    ? 0 : ETIMEDOUT);
  default:
    return EINVAL;
  }
}
strong_alias (__pthread_mutex_timedlock, pthread_mutex_timedlock)

int __pthread_mutex_unlock(pthread_mutex_t * mutex)
{
  switch (mutex->__m_kind) {
  case PTHREAD_MUTEX_ADAPTIVE_NP:
    __pthread_unlock(&mutex->__m_lock);
    return 0;
  case PTHREAD_MUTEX_RECURSIVE_NP:
    if (mutex->__m_owner != thread_self())
      return EPERM;
    if (mutex->__m_count > 0) {
      mutex->__m_count--;
      return 0;
    }
    mutex->__m_owner = NULL;
    __pthread_unlock(&mutex->__m_lock);
    return 0;
  case PTHREAD_MUTEX_ERRORCHECK_NP:
    if (mutex->__m_owner != thread_self() || mutex->__m_lock.__status == 0)
      return EPERM;
    mutex->__m_owner = NULL;
    __pthread_alt_unlock(&mutex->__m_lock);
    return 0;
  case PTHREAD_MUTEX_TIMED_NP:
    __pthread_alt_unlock(&mutex->__m_lock);
    return 0;
  default:
    return EINVAL;
  }
}
strong_alias (__pthread_mutex_unlock, pthread_mutex_unlock)

int __pthread_mutexattr_init(pthread_mutexattr_t *attr)
{
  attr->__mutexkind = PTHREAD_MUTEX_TIMED_NP;
  return 0;
}
strong_alias (__pthread_mutexattr_init, pthread_mutexattr_init)

int __pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
{
  return 0;
}
strong_alias (__pthread_mutexattr_destroy, pthread_mutexattr_destroy)

int __pthread_mutexattr_settype(pthread_mutexattr_t *attr, int kind)
{
  if (kind != PTHREAD_MUTEX_ADAPTIVE_NP
      && kind != PTHREAD_MUTEX_RECURSIVE_NP
      && kind != PTHREAD_MUTEX_ERRORCHECK_NP
      && kind != PTHREAD_MUTEX_TIMED_NP)
    return EINVAL;
  attr->__mutexkind = kind;
  return 0;
}
weak_alias (__pthread_mutexattr_settype, pthread_mutexattr_settype)
#if !defined(_ELIX_LEVEL) || _ELIX_LEVEL >= 2
strong_alias ( __pthread_mutexattr_settype, __pthread_mutexattr_setkind_np)
weak_alias (__pthread_mutexattr_setkind_np, pthread_mutexattr_setkind_np)
#endif /* !_ELIX_LEVEL || _ELIX_LEVEL >= 2 */

int __pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *kind)
{
  *kind = attr->__mutexkind;
  return 0;
}
weak_alias (__pthread_mutexattr_gettype, pthread_mutexattr_gettype)
#if !defined(_ELIX_LEVEL) || _ELIX_LEVEL >= 2
strong_alias (__pthread_mutexattr_gettype, __pthread_mutexattr_getkind_np)
weak_alias (__pthread_mutexattr_getkind_np, pthread_mutexattr_getkind_np)
#endif /* !_ELIX_LEVEL || _ELIX_LEVEL >= 2 */

#if !defined(_ELIX_LEVEL) || _ELIX_LEVEL >= 3

int __pthread_mutexattr_getpshared (const pthread_mutexattr_t *attr,
				   int *pshared)
{
  *pshared = PTHREAD_PROCESS_PRIVATE;
  return 0;
}
weak_alias (__pthread_mutexattr_getpshared, pthread_mutexattr_getpshared)

int __pthread_mutexattr_setpshared (pthread_mutexattr_t *attr, int pshared)
{
  if (pshared != PTHREAD_PROCESS_PRIVATE && pshared != PTHREAD_PROCESS_SHARED)
    return EINVAL;

  /* For now it is not possible to shared a conditional variable.  */
  if (pshared != PTHREAD_PROCESS_PRIVATE)
    return ENOSYS;

  return 0;
}
weak_alias (__pthread_mutexattr_setpshared, pthread_mutexattr_setpshared)

#endif /* !_ELIX_LEVEL || _ELIX_LEVEL >= 3 */

/* Once-only execution */

static pthread_mutex_t once_masterlock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t once_finished = PTHREAD_COND_INITIALIZER;
static int fork_generation = 0;	/* Child process increments this after fork. */

enum { NEVER = 0, IN_PROGRESS = 1, DONE = 2 };

/* If a thread is canceled while calling the init_routine out of
   pthread once, this handler will reset the once_control variable
   to the NEVER state. */

static void pthread_once_cancelhandler(void *arg)
{
    pthread_once_t *once_control = arg;

    pthread_mutex_lock(&once_masterlock);
    *once_control = NEVER;
    pthread_mutex_unlock(&once_masterlock);
    pthread_cond_broadcast(&once_finished);
}

int __pthread_once(pthread_once_t * once_control, void (*init_routine)(void))
{
  /* flag for doing the condition broadcast outside of mutex */
  int state_changed;

  /* Test without locking first for speed */
  if (*once_control == DONE) {
    READ_MEMORY_BARRIER();
    return 0;
  }
  /* Lock and test again */

  state_changed = 0;

  pthread_mutex_lock(&once_masterlock);

  /* If this object was left in an IN_PROGRESS state in a parent
     process (indicated by stale generation field), reset it to NEVER. */
  if ((*once_control & 3) == IN_PROGRESS && (*once_control & ~3) != fork_generation)
    *once_control = NEVER;

  /* If init_routine is being called from another routine, wait until
     it completes. */
  while ((*once_control & 3) == IN_PROGRESS) {
    pthread_cond_wait(&once_finished, &once_masterlock);
  }
  /* Here *once_control is stable and either NEVER or DONE. */
  if (*once_control == NEVER) {
    *once_control = IN_PROGRESS | fork_generation;
    pthread_mutex_unlock(&once_masterlock);
    pthread_cleanup_push(pthread_once_cancelhandler, once_control);
    init_routine();
    pthread_cleanup_pop(0);
    pthread_mutex_lock(&once_masterlock);
    WRITE_MEMORY_BARRIER();
    *once_control = DONE;
    state_changed = 1;
  }
  pthread_mutex_unlock(&once_masterlock);

  if (state_changed)
    pthread_cond_broadcast(&once_finished);

  return 0;
}
strong_alias (__pthread_once, pthread_once)

/*
 * Handle the state of the pthread_once mechanism across forks.  The
 * once_masterlock is acquired in the parent process prior to a fork to ensure
 * that no thread is in the critical region protected by the lock.  After the
 * fork, the lock is released. In the child, the lock and the condition
 * variable are simply reset.  The child also increments its generation
 * counter which lets pthread_once calls detect stale IN_PROGRESS states
 * and reset them back to NEVER.
 */

void __pthread_once_fork_prepare(void)
{
  pthread_mutex_lock(&once_masterlock);
}

void __pthread_once_fork_parent(void)
{
  pthread_mutex_unlock(&once_masterlock);
}

void __pthread_once_fork_child(void)
{
  pthread_mutex_init(&once_masterlock, NULL);
  pthread_cond_init(&once_finished, NULL);
  if (fork_generation <= INT_MAX - 4)
    fork_generation += 4;	/* leave least significant two bits zero */
  else
    fork_generation = 0;
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Class: OutputBuilder</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href=".././rdoc-style.css" type="text/css" media="screen" />

          Class
          OutputBuilder

            In:

                lib/albacore/output.rb

            Parent:

                Object

Methods

      dir
      erb
      file
      file
      new
      output_to

Included Modules

        FileUtils

Public Class methods

          new(dir_to, dir_from)

          output_to(dir_to, dir_from) {|OutputBuilder.new(dir_to, dir_from)| ...}

Public Instance methods

          dir(dir)

          erb(f, ft, locals)

          file(f)

          file(f, ft)

[Validate]


text:
import Score from "./Score";
import BestTime from "./BestTime";
import Lives from "./Lives";

export default class HUD {
  constructor(state) {
    this.state = state;
    this.scorer = new Score();
    this.best_time = new BestTime(window);
    this.lives = new Lives(3);
    this.level_name = this.state.state.levelManager.getCurrentLevel();

    this.textStyle = {
      font: "bold 24px Arial",
      fill: "#000000",
      boundsAlignH: "center",
      boundsAlignV: "middle"
    };
    this.hud = this.state.add.text(100, this.state.game.height - 80, '', this.textStyle);
    this.hud.fixedToCamera = true;
    this.hud.setShadow(2, 2, 'rgba(255,255,255,1)', 0.1);

  }

  getLives() {
    return this.lives.getLives();
  }

  loseLife() {
    return this.lives.loseLife();
  }

  getScore() {
    return this.scorer.getScore();
  }

  getIncrement() {
    return this.scorer.getIncrement();
  }

  incrementScore() {
    return this.scorer.incrementScore();
  }

  getTime() {
    return this.state.game.time.totalElapsedSeconds().toFixed(3);
  }

  setBestTime() {
    return this.best_time.setBestTime(this.level_name, this.getTime());
  }

  getBestTime() {
    return this.best_time.getBestTime(this.level_name);
  }

  updateHUD() {
    this.hud.setText(
        `  Life: ${this.getLives()}` +
        `        Score: ${this.getScore()}` +
        `\n` +
        `  Time: ${this.getTime()}` +
        `  Best Time: ${this.getBestTime() || 'N/A'}`
    );
  }
}


text:
package cn.com.easy.deploy.service.command;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

import cn.com.easy.deploy.dto.deployproject.DeployTaskDTO;
import cn.com.easy.deploy.dto.deployproject.DeployTaskDetailDTO;
import cn.com.easy.deploy.dto.servermanage.ServerDTO;
import cn.com.easy.deploy.entity.DeployType;
import cn.com.easy.deploy.utils.DateUtils;

/**
 * linux 命令接口实现
 *
 * @author nibili
 *
 */
@Service
public class CommandImpl implements ICommand {

	// private static Logger logger =
	// LoggerFactory.getLogger(CommandImpl.class);

	// 存放上传文件的根路径
	@Value("${deploy.file.rootpath}")
	private String fileDeployRoot = "";

	// 存放上传密钥文件的根路径
	@Value("${deploy.server.rootpath}")
	private String serverRoot;

	/** 同时部署到服务器的线程数 */
	@Value("${deploy.server.threads}")
	private int threads;

	/** 压缩解压的后缀 */
	private final String FILE_END_TAGS = ".tar.gz";

	/**
	 * 创建命令文件 [root@localhost ~]# cat test.sh

	 *
	 * #!/bin/sh ips=( "192.168.1.2" "192.168.1.3" "192.168.1.4");

	 * users=("root" "billy" "tom" "lilei");

	 * ports=("1234" "9527" "3210" "2345");

	 * authtypes=(0 1 1 0);

	 * ipsLength=${#ips[@]}

	 * for((i=0;i<ipsLength;i++))

	 * do

	 * if [ ${authtypes[i]} -eq 0 ]; then

	 * echo "${users[i]}:${ports[i]}:${ips[i]} 密码认证"

	 * else

	 * echo ${users[i]}:${ports[i]}:${ips[i]} 密钥认证

	 * fi

	 * done
	 *
	 * @param deployFileDTO
	 * @return 命令
	 * @throws Exception
	 */
	@Override
	public String createCommandFile(DeployTaskDTO deployTaskDTO) throws Exception {

		StringBuilder commandSb = new StringBuilder();
		commandSb.append("#!/bin/sh\n");
		// 添加ip user port的数组
		this.appendIpsUsersPortsAuthtypesToCommandBuilder(commandSb, deployTaskDTO.getServers());
		commandSb.append("ipsLength=${#ips[@]}\n");
		commandSb.append("for((i=0;i<ipsLength;i++))\n");
		commandSb.append("do\n");
		if (deployTaskDTO.getIsConcurrence() == 1) {
			// 指定采用多线程
			commandSb.append("if [ 0 -eq 0 ];then\n");
			// 线程控制
			commandSb.append("if [ $(($i%").append(this.threads).append(")) -eq 0 ]; then\n");
			commandSb.append("wait\n");
			commandSb.append("fi\n");
		}
		// 部署命令和部署任务的添加
		this.apppendTasks(commandSb, deployTaskDTO);
		if (deployTaskDTO.getIsConcurrence() == 1) {
			commandSb.append("fi&\n");
		}
		commandSb.append("done\n");
		commandSb.append("wait\n");
		String folder = fileDeployRoot + deployTaskDTO.getProjectId() + "/deploytask" + deployTaskDTO.getId() + "/";
		File folderFile = new File(folder);
		if (folderFile.exists()) {
			FileUtils.deleteQuietly(folderFile);
		}
		String filePath = folder + DateUtils.getCurrentDateTime().getTime() + ".sh";
		FileUtils.write(new File(filePath), commandSb.toString(), "UTF-8");
		return filePath;
	}

	/**
	 * 部署命令和部署任务的添加
	 *
	 * @param commandSb
	 * @param deployTaskDTO
	 * @throws IOException
	 */
	private void apppendTasks(StringBuilder commandSb, DeployTaskDTO deployTaskDTO) throws IOException {

		StringBuilder passwdTaskSb = new StringBuilder();// 密码方式,任务命令
		StringBuilder keyFileSb = new StringBuilder();// 密钥方式,任务命令
		for (DeployTaskDetailDTO detailDTO : deployTaskDTO.getDeployTaskDetails()) {

			switch (detailDTO.getType()) {
				case DeployType.TYPE_COMMAND:
					// 命令类型!
					// 命令
					String command = detailDTO.getCommand();
					// 先进入文件夹,再执行命令
					String commandFolder = "";
					String commandEndStr = "";
					String tempFirstCommand = command.split(" ")[0];
					if (tempFirstCommand.indexOf("/") != -1) {
						commandFolder = tempFirstCommand.substring(0, tempFirstCommand.lastIndexOf("/"));
						commandEndStr = command.substring(tempFirstCommand.lastIndexOf("/"));
					}
					// -------------------------------密钥方式
					keyFileSb.append("#").append(detailDTO.getName()).append("\n");
					keyFileSb.append("echo \"执行命令:").append(detailDTO.getName()).append(" ${ips[i]}").append("\"\n");
					keyFileSb.append("ssh -p ${ports[i]} ${users[i]}@${ips[i]} -i ").append(serverRoot).append("${users[i]}${ips[i]} ")
							.append("\"").append("source /etc/profile;");
					if (tempFirstCommand.indexOf("/") != -1) {
						keyFileSb.append("chmod +x ").append(command.split(" ")[0]).append(";").append("cd ").append(commandFolder)
								.append(";");
						keyFileSb.append("." + commandEndStr);
					} else {
						keyFileSb.append(command);
					}
					keyFileSb.append("\" \n");
					// ------------------------------密码方式
					passwdTaskSb.append("#").append(detailDTO.getName()).append("\n");
					passwdTaskSb.append("echo \"执行命令:").append(detailDTO.getName()).append(" ${ips[i]}").append("\"\n");
					passwdTaskSb.append("sshpass -f ").append(serverRoot).append("${users[i]}${ips[i]} ")
							.append(" ssh -p ${ports[i]} ${users[i]}@${ips[i]} ").append("\"").append("source /etc/profile;");
					if (tempFirstCommand.indexOf("/") != -1) {
						passwdTaskSb.append("chmod +x ").append(command.split(" ")[0]).append(";").append("cd ").append(commandFolder)
								.append(";").append("." + commandEndStr);
					} else {
						passwdTaskSb.append(command);
					}
					passwdTaskSb.append("\" \n");
					continue;
				case DeployType.TYPE_FILE:
					// 文件类型!
					// 先压缩文件
					synchronized (detailDTO.getId()) {
						this.tarFile(deployTaskDTO.getProjectId(), detailDTO.getId());
					}
					// ------------------------密钥方式---------------------
					if (detailDTO.getIsEmptyFolder() == 1) {
						// 部署前是否移除,当前的远程文件夹
						keyFileSb.append("#先删除文件夹\n");
						keyFileSb.append("echo \"先删除文件夹 ${ips[i]}\"\n");
						keyFileSb.append("ssh -p ${ports[i]} ${users[i]}@${ips[i]} -i ").append(serverRoot).append("${users[i]}${ips[i]} ")
								.append("\"rm -rf ").append(detailDTO.getDeployPath()).append("\"\n");
					}
					keyFileSb.append("ssh -p ${ports[i]} ${users[i]}@${ips[i]} -i ").append(serverRoot).append("${users[i]}${ips[i]} ")
							.append("\"mkdir -p ").append(detailDTO.getDeployPath()).append("\"\n");
					keyFileSb.append("#部署文件到远程服务器\n");
					keyFileSb.append("echo \"部署文件: ").append(detailDTO.getFileName()).append(" 到远程服务器 ${ips[i]}\" \n");
					keyFileSb.append("scp -P ${ports[i]} -i ").append(serverRoot).append("${users[i]}${ips[i]} ")
							.append(this.fileDeployRoot).append(deployTaskDTO.getProjectId()).append("/deployfile")
							.append(detailDTO.getId()).append("/").append("file").append(String.valueOf(detailDTO.getId()))
							.append(this.FILE_END_TAGS).append(" ${users[i]}@${ips[i]}:").append(detailDTO.getDeployPath()).append("\n");
					keyFileSb.append("#解压文件\n");
					keyFileSb.append("echo \"解压文件 ").append(detailDTO.getFileName()).append(" ${ips[i]}\" \n");
					keyFileSb.append("ssh -p ${ports[i]} ${users[i]}@${ips[i]} -i ").append(serverRoot).append("${users[i]}${ips[i]} ")
							.append(" \"cd ").append(detailDTO.getDeployPath()).append("; ").append("source /etc/profile;");
					// if (detailDTO.getFileName().endsWith(".war")) {
					// keyFileSb.append("jar -xvf ").append("file").append(String.valueOf(detailDTO.getId())).append(this.FILE_END_TAGS);
					// } else {
					// if (detailDTO.getFileName().endsWith(".zip")) {
					// keyFileSb.append("unzip ").append("file").append(String.valueOf(detailDTO.getId())).append(this.FILE_END_TAGS);
					// } else {
					// if (detailDTO.getFileName().endsWith(".gz") ||
					// detailDTO.getFileName().endsWith(".rar")) {
					keyFileSb.append("tar -xvf ").append("file").append(String.valueOf(detailDTO.getId())).append(this.FILE_END_TAGS)
							.append(";");
					// }
					// }
					// }
					keyFileSb.append("rm -rf ").append("file").append(String.valueOf(detailDTO.getId())).append(this.FILE_END_TAGS);
					keyFileSb.append("\"\n");
					// ------------------------密码方式---------------------
					if (detailDTO.getIsEmptyFolder() == 1) {
						// 部署前是否移除,当前的远程文件夹
						passwdTaskSb.append("#先删除文件夹\n");
						passwdTaskSb.append("echo \"先删除文件夹 ${ips[i]}\"\n");
						passwdTaskSb.append("sshpass -f ").append(serverRoot).append("${users[i]}${ips[i]} ")
								.append(" ssh -p ${ports[i]} ${users[i]}@${ips[i]} ").append("\"").append("rm -rf ")
								.append(detailDTO.getDeployPath()).append("\"\n");
					}
					passwdTaskSb.append("sshpass -f ").append(serverRoot).append("${users[i]}${ips[i]} ")
							.append(" ssh -p ${ports[i]} ${users[i]}@${ips[i]} ").append("\"mkdir -p ").append(detailDTO.getDeployPath())
							.append("\"\n");
					passwdTaskSb.append("#部署文件到远程服务器\n");
					passwdTaskSb.append("echo \"部署文件: ").append(detailDTO.getFileName()).append(" 到远程服务器 ${ips[i]}\" \n");
					passwdTaskSb.append("sshpass -f ").append(serverRoot).append("${users[i]}${ips[i]} ").append(" scp -P ${ports[i]} ")
							.append(this.fileDeployRoot).append(deployTaskDTO.getProjectId()).append("/deployfile")
							.append(detailDTO.getId()).append("/").append("file").append(String.valueOf(detailDTO.getId()))
							.append(this.FILE_END_TAGS).append(" ${users[i]}@${ips[i]}:").append(detailDTO.getDeployPath()).append("\n");
					passwdTaskSb.append("#解压文件\n");
					passwdTaskSb.append("echo \"解压文件 ").append(detailDTO.getFileName()).append(" ${ips[i]}\" \n");
					passwdTaskSb.append("sshpass -f ").append(serverRoot).append("${users[i]}${ips[i]} ")
							.append(" ssh -p ${ports[i]} ${users[i]}@${ips[i]} ").append(" \"cd ").append(detailDTO.getDeployPath())
							.append("; ").append("source /etc/profile;");
					// if (detailDTO.getFileName().endsWith(".war")) {
					// passwdTaskSb.append("jar -xvf ").append("file").append(String.valueOf(detailDTO.getId()))
					// .append(this.FILE_END_TAGS);
					// } else {
					// if (detailDTO.getFileName().endsWith(".zip")) {
					// passwdTaskSb.append("unzip ").append("file").append(String.valueOf(detailDTO.getId()))
					// .append(this.FILE_END_TAGS);
					// } else {
					// if (detailDTO.getFileName().endsWith(".gz") ||
					// detailDTO.getFileName().endsWith(".rar")) {
					passwdTaskSb.append("tar -xvf ").append("file").append(String.valueOf(detailDTO.getId())).append(this.FILE_END_TAGS)
							.append(";");
					// }
					// }
					// }
					passwdTaskSb.append("rm -rf ").append("file").append(String.valueOf(detailDTO.getId())).append(this.FILE_END_TAGS);
					passwdTaskSb.append("\"\n");
					continue;
			}
		}
		// 命令类型
		commandSb.append("if [ ${authtypes[i]} -eq 1 ]; then\n");
		commandSb.append(keyFileSb);
		commandSb.append("else\n");
		commandSb.append(passwdTaskSb);
		commandSb.append("fi\n");
	}

	/**
	 *
	 * 压缩文件
	 *
	 * @param projectId
	 * @param deployFileId
	 * @param filename
	 * @throws IOException
	 */
	private void tarFile(Long projectId, Long deployFileId) throws IOException {

		// 主文件夹
		String path = this.fileDeployRoot + "/" + String.valueOf(projectId) + "/deployfile" + String.valueOf(deployFileId) + "/";
		// 上传文件名 开头
		String fileNameStart = "file" + String.valueOf(deployFileId);
		// 上传文件名 全名
		String fileName = fileNameStart + this.FILE_END_TAGS;
		// 创建可执行文件,(如果直接执行压缩命令,压缩文件内容为空)
		String tarFilePath = path + fileNameStart + "/tar.sh";
		FileUtils.write(new File(tarFilePath), "tar -zcf " + fileName + " *", false);
		// 让其有运行的权限
		Process p = Runtime.getRuntime().exec("chmod +x " + tarFilePath);
		while (p.getInputStream().read(new byte[255]) != -1) {

		}
		// 执行linux命令,压缩
		p = Runtime.getRuntime().exec("./tar.sh", null, new File(path + fileNameStart));
		while (p.getInputStream().read(new byte[255]) != -1) {

		}
		// 执行linux命令,移到外层文件夹
		Runtime.getRuntime().exec("mv " + fileName + " ../", null, new File(path + fileNameStart));
		while (p.getInputStream().read(new byte[255]) != -1) {

		}
	}

	/**
	 * 添加ip user port的数组
	 *
	 * @param commandSb
	 * @param servers
	 */
	private void appendIpsUsersPortsAuthtypesToCommandBuilder(StringBuilder commandSb, List<ServerDTO> servers) {

		// 添加 ips,users,ports
		StringBuilder ipsSb = new StringBuilder();
		StringBuilder usersSb = new StringBuilder();
		StringBuilder portsSb = new StringBuilder();
		StringBuilder authtypesSb = new StringBuilder();
		ipsSb.append("ips=(");
		usersSb.append("users=(");
		portsSb.append("ports=(");
		authtypesSb.append("authtypes=(");
		for (ServerDTO server : servers) {
			ipsSb.append(" \"").append(server.getIp()).append("\"");
			usersSb.append(" \"").append(server.getUserName()).append("\"");
			portsSb.append(" \"").append(server.getPort()).append("\"");
			authtypesSb.append(" \"").append(server.getAuthType()).append("\"");
		}
		ipsSb.append(");\n");
		usersSb.append(");\n");
		portsSb.append(");\n");
		authtypesSb.append(");\n");
		commandSb.append(ipsSb).append(usersSb).append(portsSb).append(authtypesSb);
	}

	/**
	 * 执行命令
	 *
	 * @param command
	 *            命令
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<LineNumberReader> executeCommandFile(String command) throws Exception {

		if (command.contains("rm ") || command.contains("mv ")) {
			throw new Exception("命令不合法");
		}
		Process process = Runtime.getRuntime().exec(command);
		LineNumberReader errorStreamReader = new LineNumberReader(new InputStreamReader(process.getErrorStream()));
		LineNumberReader input = new LineNumberReader(new InputStreamReader(process.getInputStream()));
		List<LineNumberReader> readers = Lists.newArrayList();
		readers.add(input);
		readers.add(errorStreamReader);
		return readers;
	}
}


text:
from decimal import Decimal as D

from django import forms
from django.conf import settings
from django.core import exceptions
from django.utils.translation import gettext_lazy as _
from oscar.core.loading import get_model
from oscar.forms.widgets import DatePickerInput
from oscar.templatetags.currency_filters import currency

from oscar_accounts import codes, names

Account = get_model('oscar_accounts', 'Account')
AccountType = get_model('oscar_accounts', 'AccountType')

class SearchForm(forms.Form):
    name = forms.CharField(required=False)
    code = forms.CharField(required=False)
    STATUS_CHOICES = (
        ('', "------"),
        (Account.OPEN, _("Open")),
        (Account.FROZEN, _("Frozen")),
        (Account.CLOSED, _("Closed")))
    status = forms.ChoiceField(choices=STATUS_CHOICES, required=False)

class TransferSearchForm(forms.Form):
    reference = forms.CharField(required=False)
    start_date = forms.DateField(required=False, widget=DatePickerInput)
    end_date = forms.DateField(required=False, widget=DatePickerInput)

class EditAccountForm(forms.ModelForm):
    name = forms.CharField(label=_("Name"), required=True)

    class Meta:
        model = Account
        exclude = ['status', 'code', 'credit_limit', 'balance']
        widgets = {
            'start_date': DatePickerInput,
            'end_date': DatePickerInput,
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['product_range'].help_text = (
            "You may need to create a product range first")

        # Add field for account type (if there is a choice)
        deferred_income = AccountType.objects.get(name=names.DEFERRED_INCOME)
        types = deferred_income.get_children()
        if types.count() > 1:
            self.fields['account_type'] = forms.ModelChoiceField(
                queryset=types)
        elif types.count() == 1:
            del self.fields['account_type']
            self._account_type = types[0]
        else:
            raise exceptions.ImproperlyConfigured(
                "You need to define some 'deferred income' account types")

class SourceAccountMixin(object):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Add field for source account (if there is a choice)
        unpaid_sources = AccountType.objects.get(
            name=names.UNPAID_ACCOUNT_TYPE)
        sources = unpaid_sources.accounts.all()
        if sources.count() > 1:
            self.fields['source_account'] = forms.ModelChoiceField(
                queryset=unpaid_sources.accounts.all())
        elif sources.count() == 1:
            self._source_account = sources[0]
        else:
            raise exceptions.ImproperlyConfigured(
                "You need to define some 'unpaid source' accounts")

    def get_source_account(self):
        if 'source_account' in self.cleaned_data:
            return self.cleaned_data['source_account']
        return self._source_account

class NewAccountForm(SourceAccountMixin, EditAccountForm):
    initial_amount = forms.DecimalField(
        min_value=getattr(settings, 'ACCOUNTS_MIN_LOAD_VALUE', D('0.00')),
        max_value=getattr(settings, 'ACCOUNTS_MAX_ACCOUNT_VALUE', None),
        decimal_places=2)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Add field for source account (if there is a choice)
        unpaid_sources = AccountType.objects.get(
            name=names.UNPAID_ACCOUNT_TYPE)
        sources = unpaid_sources.accounts.all()
        if sources.count() > 1:
            self.fields['source_account'] = forms.ModelChoiceField(
                queryset=unpaid_sources.accounts.all())
        elif sources.count() == 1:
            self._source_account = sources[0]
        else:
            raise exceptions.ImproperlyConfigured(
                "You need to define some 'unpaid source' accounts")

    def save(self, *args, **kwargs):
        kwargs['commit'] = False
        account = super().save(*args, **kwargs)
        account.code = codes.generate()
        if hasattr(self, '_account_type'):
            account.account_type = self._account_type
        account.save()
        self.save_m2m()
        return account

    def get_source_account(self):
        if 'source_account' in self.cleaned_data:
            return self.cleaned_data['source_account']
        return self._source_account

class UpdateAccountForm(EditAccountForm):
    pass

class ChangeStatusForm(forms.ModelForm):
    status = forms.CharField(widget=forms.widgets.HiddenInput)
    new_status = None

    def __init__(self, *args, **kwargs):
        kwargs['initial']['status'] = self.new_status
        super().__init__(*args, **kwargs)

    class Meta:
        model = Account
        exclude = ['name', 'account_type', 'description', 'category', 'code', 'start_date',
                   'end_date', 'credit_limit', 'balance', 'product_range',
                   'primary_user', 'secondary_users',
                   'can_be_used_for_non_products']

class FreezeAccountForm(ChangeStatusForm):
    new_status = Account.FROZEN

class ThawAccountForm(ChangeStatusForm):
    new_status = Account.OPEN

class TopUpAccountForm(SourceAccountMixin, forms.Form):
    amount = forms.DecimalField(
        min_value=getattr(settings, 'ACCOUNTS_MIN_LOAD_VALUE', D('0.00')),
        max_value=getattr(settings, 'ACCOUNTS_MAX_ACCOUNT_VALUE', None),
        decimal_places=2)

    def __init__(self, *args, **kwargs):
        self.account = kwargs.pop('instance')
        super().__init__(*args, **kwargs)

    def clean_amount(self):
        amt = self.cleaned_data['amount']
        if hasattr(settings, 'ACCOUNTS_MAX_ACCOUNT_VALUE'):
            max_amount = (
                settings.ACCOUNTS_MAX_ACCOUNT_VALUE - self.account.balance)
            if amt > max_amount:
                raise forms.ValidationError(_(
                    "The maximum permitted top-up amount is %s") % (
                        currency(max_amount)))
        return amt

    def clean(self):
        if self.account.is_closed():
            raise forms.ValidationError(_("Account is closed"))
        elif self.account.is_frozen():
            raise forms.ValidationError(_("Account is frozen"))
        return self.cleaned_data

class WithdrawFromAccountForm(SourceAccountMixin, forms.Form):
    amount = forms.DecimalField(
        min_value=D('0.00'),
        max_value=None,
        decimal_places=2)

    def __init__(self, *args, **kwargs):
        self.account = kwargs.pop('instance')
        super().__init__(*args, **kwargs)

    def clean_amount(self):
        amt = self.cleaned_data['amount']
        max_amount = self.account.balance
        if amt > max_amount:
            raise forms.ValidationError(_(
                "The account has only %s") % (
                    currency(max_amount)))
        return amt

    def clean(self):
        if self.account.is_closed():
            raise forms.ValidationError(_("Account is closed"))
        elif self.account.is_frozen():
            raise forms.ValidationError(_("Account is frozen"))
        return self.cleaned_data

class DateForm(forms.Form):
    date = forms.DateField(widget=DatePickerInput)

class DateRangeForm(forms.Form):
    start_date = forms.DateField(label=_("From"), widget=DatePickerInput)
    end_date = forms.DateField(label=_("To"), widget=DatePickerInput)


text:
.accordion {
  overflow: hidden;
  border-width: 1px;
  border-style: solid;
}
.accordion .accordion-header {
  border-width: 0 0 1px;
  cursor: pointer;
}
.accordion .accordion-body {
  border-width: 0 0 1px;
}
.accordion-noborder {
  border-width: 0;
}
.accordion-noborder .accordion-header {
  border-width: 0 0 1px;
}
.accordion-noborder .accordion-body {
  border-width: 0 0 1px;
}
.accordion-collapse {
  background: url('images/accordion_arrows.png') no-repeat 0 0;
}
.accordion-expand {
  background: url('images/accordion_arrows.png') no-repeat -16px 0;
}
.accordion {
  background: #ffffff;
  border-color: #D4D4D4;
}
.accordion .accordion-header {
  background: #F2F2F2;
  filter: none;
}
.accordion .accordion-header-selected {
  background: #0081c2;
}
.accordion .accordion-header-selected .panel-title {
  color: #fff;
}
.accordion .panel-last > .accordion-header {
  border-bottom-color: #F2F2F2;
}
.accordion .panel-last > .accordion-body {
  border-bottom-color: #ffffff;
}
.accordion .panel-last > .accordion-header-selected,
.accordion .panel-last > .accordion-header-border {
  border-bottom-color: #D4D4D4;
}
.accordion> .panel-hleft {
  float: left;
}
.accordion> .panel-hleft>.panel-header {
  border-width: 0 1px 0 0;
}
.accordion> .panel-hleft> .panel-body {
  border-width: 0 1px 0 0;
}
.accordion> .panel-hleft.panel-last > .accordion-header {
  border-right-color: #F2F2F2;
}
.accordion> .panel-hleft.panel-last > .accordion-body {
  border-right-color: #ffffff;
}
.accordion> .panel-hleft.panel-last > .accordion-header-selected,
.accordion> .panel-hleft.panel-last > .accordion-header-border {
  border-right-color: #D4D4D4;
}
.accordion> .panel-hright {
  float: right;
}
.accordion> .panel-hright>.panel-header {
  border-width: 0 0 0 1px;
}
.accordion> .panel-hright> .panel-body {
  border-width: 0 0 0 1px;
}
.accordion> .panel-hright.panel-last > .accordion-header {
  border-left-color: #F2F2F2;
}
.accordion> .panel-hright.panel-last > .accordion-body {
  border-left-color: #ffffff;
}
.accordion> .panel-hright.panel-last > .accordion-header-selected,
.accordion> .panel-hright.panel-last > .accordion-header-border {
  border-left-color: #D4D4D4;
}


text:
layout: default
---

{{page.entrada}}

  {{ content }}


text:
namespace cresper {

using namespace v8;
using std::string;

DecodeMsg _parse (DecodeMsg& msg) {
  size_t index = msg.message.find(CRLF, msg.index);
  if (index == string::npos)
    return DecodeMsg("", -1);

  return DecodeMsg(msg.message.substr(msg.index, index - msg.index),
    index + 2);
}

DecodeMsg _decodeString (DecodeMsg& msg) {
  GET_DECODED(msg)
  decoded.result = Nan::New<String>(decoded.message).ToLocalChecked();

  return decoded;
}

DecodeMsg _decodeError (DecodeMsg& msg) {
  GET_DECODED(msg)

  if (decoded.index == -1) {
    decoded.result = Nan::Undefined();
    return decoded;
  }

  size_t spaceIndex = decoded.message.find(" ");
  if (spaceIndex != string::npos) {
    Local<Value> error = Nan::Error(decoded.message.substr(spaceIndex + 1).c_str());
    Nan::Set(error->ToObject(), Nan::New("name").ToLocalChecked(),
      Nan::New(decoded.message.substr(0, spaceIndex)).ToLocalChecked());

    decoded.result = error;
  } else {
    decoded.result = Nan::Error(decoded.message.c_str());
  }

  return decoded;
}

DecodeMsg _decodtInt (DecodeMsg& msg) {
  GET_DECODED(msg)

  if (decoded.index == -1) {
    decoded.result = Nan::Undefined();
    return decoded;
  }

  decoded.result = Nan::New(std::stoi(decoded.message));
  return decoded;
}

DecodeMsg _decodeBulkString (DecodeMsg& msg) {
  GET_DECODED(msg)

  if (decoded.index == -1) {
    decoded.result = Nan::Undefined();
    return decoded;
  }

  int bulkStartIndex = decoded.index;
  int bulkLen;

  try {
    bulkLen = std::stoi(decoded.message);
  } catch (const std::invalid_argument& err) {
    Nan::ThrowError(Nan::New("Invaild bulk string length").ToLocalChecked());
  }

  int bulkEndIndex = bulkStartIndex + bulkLen;
  decoded.index = decoded.index + bulkLen + 2;

  if (bulkLen == -1 || msg.message.length() < bulkEndIndex + CRLF.length()) {
    decoded.result = Nan::Null();
  } else {
    decoded.result = Nan::New(msg.message.substr(bulkStartIndex, bulkEndIndex - bulkStartIndex)).ToLocalChecked();
  }

  return decoded;
}

DecodeMsg _decodeArray (DecodeMsg& msg) {
  GET_DECODED(msg)

  if (decoded.index == -1) {
    decoded.result = Nan::Undefined();
    return decoded;
  }

  size_t arrLen;
  try {
    arrLen = std::stoi(decoded.message);
  } catch (const std::invalid_argument& err) {
    decoded.result = Nan::Null();
    return decoded;
  }

  if (static_cast<int>(arrLen) == -1) {
    decoded.result = Nan::Null();
    return decoded;
  } else if (static_cast<int>(arrLen) < -1) {
    Nan::ThrowError(Nan::New("Invaild array length").ToLocalChecked());
  }

  Local<Array> result = Nan::New<Array>(arrLen);
  for (size_t i = 0; i < arrLen; i++) {
    DecodeMsg msgToDecode = DecodeMsg(msg.message, decoded.index);
    DecodeMsg _decoded = _decode(msgToDecode);
    Nan::Set(result, i, _decoded.result);
    decoded.index = _decoded.index;
  }

  return DecodeMsg(result);
}

DecodeMsg _decode (DecodeMsg& msg) {
  if (CHECK_MSG_PREFIX(msg, STRING_PREFIX)) // String
    return _decodeString(msg);
  else if (CHECK_MSG_PREFIX(msg, ERROR_PREFIX)) // Error
    return _decodeError(msg);
  else if (CHECK_MSG_PREFIX(msg, INT_PREFIX)) // Integer
    return _decodtInt(msg);
  else if (CHECK_MSG_PREFIX(msg, BULK_STRING_PREFIX)) // Bulk String
    return _decodeBulkString(msg);
  else if (CHECK_MSG_PREFIX(msg, ARRAY_PREFIX)) // Array
    return _decodeArray(msg);

  return Nan::Error(Nan::New("Missing prefix" + msg.message).ToLocalChecked());
}

}


text:
<img src="https://psiturk.org/static/images/psiturk_logo_README.png">

[![Build Status](https://travis-ci.org/NYUCCL/psiTurk.png?branch=master)](https://travis-ci.org/NYUCCL/psiTurk)
[![Coverage Status](http://coveralls.io/repos/NYUCCL/psiTurk/badge.png?branch=master)](http://coveralls.io/r/NYUCCL/psiTurk?branch=master)
[![Code Health](https://landscape.io/github/NYUCCL/psiTurk/master/landscape.png)](https://landscape.io/github/NYUCCL/psiTurk/master)
[![Downloads](https://pypip.in/d/PsiTurk/badge.png)](https://pypi.python.org/pypi/PsiTurk/)
[![License](http://img.shields.io/badge/license-MIT-red.svg)](http://en.wikipedia.org/wiki/MIT_License)

The current stable version is 2.1.2.

Please visit [psiturk.org](https://psiturk.org) for more information.

You are welcome to use this code for personal or academic uses. If you fork,
or use this in an academic paper please cite as follows:

McDonnell, J.V., Martin, J.B., Markant, D.B., Coenen, A., Rich, A.S., and Gureckis, T.M.
(2012). psiTurk (Version 1.02) [Software]. New York, NY: New York University.
Available from https://github.com/NYUCCL/psiTurk


text:
package com.thedreamsanctuary.dreamindex.commands;

import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import com.google.common.base.Preconditions;
import com.thedreamsanctuary.dreamindex.SerializeData;
import com.thedreamsanctuary.dreamindex.confighandler.CfgHandler;

public class Dtcreate implements CommandExecutor
{
	SerializeData ser = new SerializeData();
	CfgHandler cfg = new CfgHandler();
	public boolean onCommand(CommandSender sender, Command comm, String str, String[] args)
	{
		Preconditions.checkArgument(sender instanceof Player, "Must be a player to execute this command");
		try
		{
			if (!ser.data().getTags().containsKey(args[0]))
			{
				Boolean hasHitLimit = cfg.getTagLimit(ser.data().getTags().size());

				if (hasHitLimit.equals(false))
				{
					ser.data().getTags().put(args[0], 0);
					sender.sendMessage(ChatColor.GOLD + args[0] + ChatColor.BLUE + " has been added to the taglist");
					return true;
				}
				else
					sender.sendMessage("Error the maximum tag limit has been reached!");
			}
			else
			{
				sender.sendMessage(ChatColor.RED + "There is already a group under this name");
			}
		} catch (Exception e)
		{
			sender.sendMessage(ChatColor.RED + "/dtcreate <tagname>");
		}
		return false;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Based on the SMPP Protocol Specification v3.4 1999 Oct 12 -->
<!-- Default types are: -->
<!-- Byte, Word, Integer: 1,2,4 bytes (Unsigned) -->
<!-- C-OS: C Octet String terminated with NULL (0x00) character -->
<!-- OS: Octet String, NOT terminated -->
<!-- TLV: Tag,Length,Value format -->
<!-- None: no Value-->
<!-- Last change 2014 Apr 16 -->
<dictionary>
    <msg code="80000000" name="generic_nack"/>
    <msg code="00000001" name="bind_receiver">
        <mandatory name="system_id"                 type="C-OS" max="16"/>
        <mandatory name="password"                  type="C-OS" max="9"/>
        <mandatory name="system_type"               type="C-OS" max="13"/>
        <mandatory name="interface_version"         type="Byte"/>
        <mandatory name="addr_ton"                  type="Byte"/>
        <mandatory name="addr_npi"                  type="Byte"/>
        <mandatory name="address_range"             type="C-OS" max="41"/>
    </msg>
    <msg code="80000001" name="bind_receiver_resp">
        <mandatory name="system_id"                 type="C-OS" max="16"/>
    </msg>
    <msg code="00000002" name="bind_transmitter">
        <mandatory name="system_id"                 type="C-OS" max="16"/>
        <mandatory name="password"                  type="C-OS" max="9"/>
        <mandatory name="system_type"               type="C-OS" max="13"/>
        <mandatory name="interface_version"         type="Byte"/>
        <mandatory name="addr_ton"                  type="Byte"/>
        <mandatory name="addr_npi"                  type="Byte"/>
        <mandatory name="address_range"             type="C-OS" max="41"/>
    </msg>
    <msg code="80000002" name="bind_transmitter_resp">
        <mandatory name="system_id"                 type="C-OS" max="16"/>
    </msg>
    <msg code="00000003" name="query_sm">
        <mandatory name="message_id"                type="C-OS" max="65"/>
        <mandatory name="source_addr_ton"           type="Byte"/>
        <mandatory name="source_addr_npi"           type="Byte"/>
        <mandatory name="source_addr"               type="C-OS" max="21"/>
    </msg>
    <msg code="80000003" name="query_sm_resp">
        <mandatory name="message_id"                type="C-OS" max="65"/>
        <mandatory name="final_date"                type="C-OS" max="17"/>
        <mandatory name="error_code"                type="Byte" max="21"/>
    </msg>
    <msg code="00000004" name="submit_sm">
        <mandatory name="service_type"              type="C-OS" max="6"/>
        <mandatory name="source_addr_ton"           type="Byte"/>
        <mandatory name="source_addr_npi"           type="Byte"/>
        <mandatory name="source_addr"               type="C-OS" max="21"/>
        <mandatory name="dest_addr_ton"             type="Byte"/>
        <mandatory name="dest_addr_npi"             type="Byte"/>
        <mandatory name="destination_addr"          type="C-OS" max="21"/>
        <mandatory name="esm_class"                 type="Byte"/>
        <mandatory name="protocol_id"               type="Byte"/>
        <mandatory name="priority_flag"             type="Byte"/>
        <mandatory name="schedule_delivery_time"    type="C-OS" max="17"/>
        <mandatory name="validity_period"           type="C-OS" max="17"/>
        <mandatory name="registered_delivery"       type="Byte"/>
        <mandatory name="replace_if_present_flag"   type="Byte"/>
        <mandatory name="data_coding"               type="Byte"/>
        <mandatory name="sm_default_msg_id"         type="Byte"/>
        <mandatory name="sm_length"                 type="Byte"/>
        <mandatory name="short_message"             type="OctetString"/>
    </msg>
    <msg code="80000004" name="submit_sm_resp">
        <mandatory name="message_id"                type="C-OS" max="65"/>
    </msg>
    <msg code="00000005" name="deliver_sm">
        <mandatory name="service_type"              type="C-OS" max="6"/>
        <mandatory name="source_addr_ton"           type="Byte"/>
        <mandatory name="source_addr_npi"           type="Byte"/>
        <mandatory name="source_addr"               type="C-OS" max="21"/>
        <mandatory name="dest_addr_ton"             type="Byte"/>
        <mandatory name="dest_addr_npi"             type="Byte"/>
        <mandatory name="destination_addr"          type="C-OS" max="21"/>
        <mandatory name="esm_class"                 type="Byte"/>
        <mandatory name="protocol_id"               type="Byte"/>
        <mandatory name="priority_flag"             type="Byte"/>
        <mandatory name="schedule_delivery_time"    type="C-OS" max="1"/>
        <mandatory name="validity_period"           type="C-OS" max="1"/>
        <mandatory name="registered_delivery"       type="Byte"/>
        <mandatory name="replace_if_present_flag"   type="Byte"/>
        <mandatory name="data_coding"               type="Byte"/>
        <mandatory name="sm_default_msg_id"         type="Byte"/>
        <mandatory name="sm_length"                 type="Byte"/>
        <mandatory name="short_message"             type="OctetString"/>
    </msg>
    <msg code="80000005" name="deliver_sm_resp">
        <mandatory name="message_id"                type="C-OS" max="1"/>
    </msg>
    <msg code="00000006" name="unbind"/>
    <msg code="80000006" name="unbind_resp"/>
    <msg code="00000007" name="replace_sm">
        <mandatory name="message_id"                type="C-OS" max="65"/>
        <mandatory name="source_addr_ton"           type="Byte"/>
        <mandatory name="source_addr_npi"           type="Byte"/>
        <mandatory name="source_addr"               type="C-OS" max="21"/>
        <mandatory name="schedule_delivery_time"    type="C-OS" max="17"/>
        <mandatory name="validity_period"           type="C-OS" max="17"/>
        <mandatory name="registered_delivery"       type="Byte"/>
        <mandatory name="sm_default_msg_id"         type="Byte"/>
        <mandatory name="sm_length"                 type="Byte"/>
        <mandatory name="short_message"             type="OctetString"/>
    </msg>
    <msg code="80000007" name="replace_sm_resp"/>
    <msg code="00000008" name="cancel_sm">
        <mandatory name="service_type"              type="C-OS" max="6"/>
        <mandatory name="message_id"                type="C-OS" max="65"/>
        <mandatory name="source_addr_ton"           type="Byte"/>
        <mandatory name="source_addr_npi"           type="Byte"/>
        <mandatory name="source_addr"               type="C-OS" max="21"/>
        <mandatory name="dest_addr_ton"             type="Byte"/>
        <mandatory name="dest_addr_npi"             type="Byte"/>
        <mandatory name="destination_addr"          type="C-OS" max="21"/>
    </msg>
    <msg code="80000008" name="cancel_sm_resp"/>
    <msg code="00000009" name="bind_transceiver">
        <mandatory name="system_id"                 type="C-OS" max="16"/>
        <mandatory name="password"                  type="C-OS" max="9"/>
        <mandatory name="system_type"               type="C-OS" max="13"/>
        <mandatory name="interface_version"         type="Byte"/>
        <mandatory name="addr_ton"                  type="Byte"/>
        <mandatory name="addr_npi"                  type="Byte"/>
        <mandatory name="address_range"             type="C-OS" max="41"/>
    </msg>
    <msg code="80000009" name="bind_transceiver_resp">
        <mandatory name="system_id"                 type="C-OS" max="16"/>
    </msg>
    <msg code="0000000B" name="outbind">
        <mandatory name="system_id"                 type="C-OS" max="16"/>
        <mandatory name="password"                  type="C-OS" max="9"/>
    </msg>
    <msg code="00000015" name="enquire_link"/>
    <msg code="80000015" name="enquire_link_resp"/>
    <msg code="00000021" name="submit_multi">
        <mandatory name="service_type"              type="C-OS" max="6"/>
        <mandatory name="source_addr_ton"           type="Byte"/>
        <mandatory name="source_addr_npi"           type="Byte"/>
        <mandatory name="source_addr"               type="C-OS" max="21"/>
        <mandatory name="number_of_dests"           type="Byte"/>
        <mandatory name="dest_address"              type="OctetString"/>
        <mandatory name="esm_class"                 type="Byte"/>
        <mandatory name="protocol_id"               type="Byte"/>
        <mandatory name="priority_flag"             type="Byte"/>
        <mandatory name="schedule_delivery_time"    type="C-OS" max="17"/>
        <mandatory name="validity_period"           type="C-OS" max="17"/>
        <mandatory name="registered_delivery"       type="Byte"/>
        <mandatory name="replace_if_present_flag"   type="Byte"/>
        <mandatory name="data_coding"               type="Byte"/>
        <mandatory name="sm_default_msg_id"         type="Byte"/>
        <mandatory name="sm_length"                 type="Byte"/>
        <mandatory name="short_message"             type="OctetString"/>
    </msg>
    <msg code="80000021" name="submit_multi_resp">
        <mandatory name="message_id"                type="C-OS" max="65"/>
        <mandatory name="no_unsuccess"              type="Byte"/>
        <mandatory name="unsuccess_sme"             type="OctetString"/>
    </msg>
    <msg code="00000102" name="alert_notification">
        <mandatory name="source_addr_ton"           type="Byte"/>
        <mandatory name="source_addr_npi"           type="Byte"/>
        <mandatory name="source_addr"               type="C-OS" max="65"/>
        <mandatory name="esme_addr_ton"             type="Byte"/>
        <mandatory name="esme_addr_npi"             type="Byte"/>
        <mandatory name="esme_addr"                 type="C-OS" max="65"/>
    </msg>
    <msg code="00000103" name="data_sm">
        <mandatory name="service_type"              type="C-OS" max="6"/>
        <mandatory name="source_addr_ton"           type="Byte"/>
        <mandatory name="source_addr_npi"           type="Byte"/>
        <mandatory name="source_addr"               type="C-OS" max="21"/>
        <mandatory name="dest_addr_ton"             type="Byte"/>
        <mandatory name="dest_addr_npi"             type="Byte"/>
        <mandatory name="destination_addr"          type="C-OS" max="65"/>
        <mandatory name="esm_class"                 type="Byte"/>
        <mandatory name="registered_delivery"       type="Byte"/>
        <mandatory name="data_coding"               type="Byte"/>
     </msg>
    <msg code="80000103" name="data_sm_resp">
        <mandatory name="message_id"                type="C-OS" max="65"/>
    </msg>

<!-- Optional TAG parameters -->
    <tag code="0005" name="dest_addr_subunit"       type="Byte"/>
    <tag code="0006" name="dest_network_type"       type="Byte"/>
    <tag code="0007" name="dest_bearer_type"        type="Byte"/>
    <tag code="0008" name="dest_telematics_id"      type="Word"/> <!-- To be defined -->
    <tag code="000D" name="source_addr_subunit"     type="Byte"/>
    <tag code="000E" name="source_network_type"     type="Byte"/>
    <tag code="000F" name="source_bearer_type"      type="Byte"/>
    <tag code="0010" name="source_telematics_id"    type="Byte"/>
    <tag code="0017" name="qos_time_to_live"        type="Integer"/>
    <tag code="0019" name="payload_type"            type="Byte"/>
    <tag code="001D" name="additional_status_info_text" type="C-OS"/>
    <tag code="001E" name="receipted_message_id"    type="C-OS"/>
    <tag code="0030" name="ms_msg_wait_facilities"  type="Byte"/>
    <tag code="0201" name="privacy_indicator"       type="Byte"/>
    <tag code="0202" name="source_subaddress"       type="OctetString"/>
    <tag code="0203" name="dest_subaddress"         type="OctetString"/>
    <tag code="0204" name="user_message_reference"  type="Word"/>
    <tag code="0205" name="user_response_code"      type="Byte"/>
    <tag code="020A" name="source_port"             type="Word"/>
    <tag code="020B" name="destination_port"        type="Word"/>
    <tag code="020C" name="sar_msg_ref_num"         type="Word"/>
    <tag code="020D" name="language_indicator"      type="Byte"/>
    <tag code="020E" name="sar_total_segments"      type="Byte"/>
    <tag code="020F" name="sar_segment_seqnum"      type="Byte"/>
    <tag code="0210" name="sc_interface_version"    type="Byte"/>
    <tag code="0302" name="callback_num_pres_ind"   type="Byte"/>
    <tag code="0303" name="callback_num_atag"       type="OctetString"/>
    <tag code="0304" name="number_of_messages"      type="Byte"/>
    <tag code="0381" name="callback_num"            type="OctetString"/>
    <tag code="0420" name="dpf_result"              type="Byte"/>
    <tag code="0421" name="set_dpf"                 type="Byte"/>
    <tag code="0422" name="ms_availability_status"  type="Byte"/>
    <tag code="0423" name="network_error_code"      type="OctetString"/>
    <tag code="0424" name="message_payload"         type="OctetString"/>
    <tag code="0425" name="delivery_failure_reason" type="Byte"/>
    <tag code="0426" name="more_messages_to_send"   type="Byte"/>
    <tag code="0427" name="message_state"           type="Byte"/>
    <tag code="0501" name="ussd_service_op"         type="Byte"/>
    <tag code="1201" name="display_time"            type="Byte"/>
    <tag code="1203" name="sms_signal"              type="Word"/>
    <tag code="1204" name="ms_validity"             type="Byte"/>
    <tag code="130C" name="alert_on_msg_delivery"   type="None"/>
    <tag code="1380" name="its_reply_type"          type="Byte"/>
    <tag code="1383" name="its_session_info"        type="Word"/>

<!-- Error codes -->
    <err code="00000000" name="ESME_ROK"            desc="No Error"/>
    <err code="00000001" name="ESME_RINVMSGLEN"     desc="Message Length is invalid"/>
    <err code="00000002" name="ESME_RINVCMDLEN"     desc="Command Length is invalid"/>
    <err code="00000003" name="ESME_RINVCMDID"      desc="Invalid Command ID"/>
    <err code="00000004" name="ESME_RINVBNDSTS"     desc="Incorrect BIND Status for given command"/>
    <err code="00000005" name="ESME_RALYBND"        desc="ESME Already in Bound State"/>
    <err code="00000006" name="ESME_RINVPRTFLG"     desc="Invalid Priority Flag"/>
    <err code="00000007" name="ESME_RINVREGDLVFLG"  desc="Invalid Registered Delivery Flag"/>
    <err code="00000008" name="ESME_RSYSERR"        desc="System Error"/>
    <err code="0000000A" name="ESME_RINVSRCADR"     desc="Invalid Source Address"/>
    <err code="0000000B" name="ESME_RINVDSTADR"     desc="Invalid Dest Addr"/>
    <err code="0000000C" name="ESME_RINVMSGID"      desc="Message ID is invalid"/>
    <err code="0000000D" name="ESME_RBINDFAIL"      desc="Bind Failed"/>
    <err code="0000000E" name="ESME_RINVPASWD"      desc="Invalid Password"/>
    <err code="0000000F" name="ESME_RINVSYSID"      desc="Invalid System ID"/>
    <err code="00000011" name="ESME_RCANCELFAIL"    desc="Cancel SM Failed"/>
    <err code="00000013" name="ESME_RREPLACEFAIL"   desc="Replace SM Failed"/>
    <err code="00000014" name="ESME_RMSGQFUL"       desc="Message Queue Full"/>
    <err code="00000015" name="ESME_RINVSERTYP"     desc="Invalid Service Type"/>
    <err code="00000033" name="ESME_RINVNUMDESTS"   desc="Invalid number of destinations"/>
    <err code="00000034" name="ESME_RINVDLNAME"     desc="Invalid Distribution List name"/>
    <err code="00000040" name="ESME_RINVDESTFLAG"   desc="Destination flag is invalid(submit_multi)"/>
    <err code="00000042" name="ESME_RINVSUBREP"     desc="Invalid 'submit with replace' request(i.e. submit_sm with replace_if_present_flag set)"/>
    <err code="00000043" name="ESME_RINVESMCLASS"   desc="Invalid esm_class field data"/>
    <err code="00000044" name="ESME_RCNTSUBDL"      desc="Cannot Submit to Distribution List"/>
    <err code="00000045" name="ESME_RSUBMITFAIL"    desc="submit_sm or submit_multi failed"/>
    <err code="00000048" name="ESME_RINVSRCTON"     desc="Invalid Source address TON"/>
    <err code="00000049" name="ESME_RINVSRCNPI"     desc="Invalid Source address NPI"/>
    <err code="00000050" name="ESME_RINVDSTTON"     desc="Invalid Destination address TON"/>
    <err code="00000051" name="ESME_RINVDSTNPI"     desc="Invalid Destination address NPI"/>
    <err code="00000053" name="ESME_RINVSYSTYP"     desc="Invalid system_type field"/>
    <err code="00000054" name="ESME_RINVREPFLAG"    desc="Invalid replace_if_present flag"/>
    <err code="00000055" name="ESME_RINVNUMMSGS"    desc="Invalid number of messages"/>
    <err code="00000058" name="ESME_RTHROTTLED"     desc="Throttling error (ESME has exceeded allowed message limits)"/>
    <err code="00000061" name="ESME_RINVSCHED"      desc="Invalid Scheduled Delivery Time"/>
    <err code="00000062" name="ESME_RINVEXPIRY"     desc="Invalid message validity period(Expiry time)"/>
    <err code="00000063" name="ESME_RINVDFTMSGID"   desc="Predefined Message Invalid or Not Found"/>
    <err code="00000064" name="ESME_RX_T_APPN"      desc="ESME Receiver Temporary App Error Code"/>
    <err code="00000065" name="ESME_RX_P_APPN"      desc="ESME Receiver Permanent App Error Code"/>
    <err code="00000066" name="ESME_RX_R_APPN"      desc="ESME Receiver Reject Message Error Code"/>
    <err code="00000067" name="ESME_RQUERYFAIL"     desc="query_sm request failed"/>
    <err code="000000C0" name="ESME_RINVOPTPARSTREAM" desc="Error in the optional part of the PDU Body"/>
    <err code="000000C1" name="ESME_ROPTPARNOTALLWD" desc="Optional Parameter not allowed"/>
    <err code="000000C2" name="ESME_RINVPARLEN"     desc="Invalid Parameter Length"/>
    <err code="000000C3" name="ESME_RMISSINGOPTPARAM" desc="Expected Optional Parameter missing"/>
    <err code="000000C4" name="ESME_RINVOPTPARAMVAL" desc="Invalid Optional Parameter Value"/>
    <err code="000000FE" name="ESME_RDELIVERYFAILURE" desc="Delivery Failure (used for data_sm_resp)"/>
    <err code="000000FF" name="ESME_RUNKNOWNERR"    desc="Unknown Error"/>
</dictionary>


text:
package uk.ac.manchester.cs.owl.semspreadsheets.ui.action;

import java.awt.event.ActionEvent;

import javax.swing.JOptionPane;

import uk.ac.manchester.cs.owl.semspreadsheets.model.Range;
import uk.ac.manchester.cs.owl.semspreadsheets.model.Sheet;
import uk.ac.manchester.cs.owl.semspreadsheets.ui.ErrorHandler;
import uk.ac.manchester.cs.owl.semspreadsheets.ui.WorkbookFrame;

/**
 * Author: Matthew Horridge

 * The University of Manchester

 * Information Management Group

 * Date: 10-Nov-2009
 *
 * Author: Stuart Owen
 * Date: 04-Oct-2010
 */
@SuppressWarnings("serial")
public class RenameSheetAction extends WorkbookFrameAction {

    public RenameSheetAction(WorkbookFrame workbookFrame) {
        super("Rename", workbookFrame);
    }

    public void actionPerformed(ActionEvent e) {
        WorkbookFrame frame = getWorkbookFrame();
        Range range = frame.getWorkbookManager().getSelectionModel().getSelectedRange();
        Sheet sheet = range.getSheet();
        if(sheet != null) {
            String newName = JOptionPane.showInputDialog(frame, "Rename sheet to", sheet.getName());
            if (newName != null) {
            	if (getWorkbookManager().getWorkbook().getSheet(newName)==null) {
            		try {
                		getWorkbookManager().renameSheet(sheet.getName(),newName);
                	}
                	catch(IllegalArgumentException ex) {
                		ErrorHandler.getErrorHandler().handleError(ex);
                	}
            	}
            	else {
            		JOptionPane.showMessageDialog(getWorkbookFrame(), "A sheet with the name "+newName+" already exists","Duplicate sheet name",JOptionPane.ERROR_MESSAGE);
            	}
            }
        }
    }
}


text:
=pod

=head1 NAME

Bio::EnsEMBL::Compara::RunnableDB::GenomeLoadReuseMembers

=cut

=head1 SYNOPSIS

my $db      = Bio::EnsEMBL::Compara::DBAdaptor->new($locator);
my $g_load_members = Bio::EnsEMBL::Compara::RunnableDB::GenomeLoadReuseMembers->new (
                                                    -db      => $db,
                                                    -input_id   => $input_id
                                                    -analysis   => $analysis );
$g_load_members->fetch_input(); #reads from DB
$g_load_members->run();
$g_load_members->output();
$g_load_members->write_output(); #writes to DB

=cut

=head1 DESCRIPTION

This object wraps Bio::EnsEMBL::Pipeline::Runnable::Blast to add
functionality to read and write to databases.
The appropriate Bio::EnsEMBL::Analysis object must be passed for
extraction of appropriate parameters. A Bio::EnsEMBL::Pipeline::DBSQL::Obj is
required for databse access.

=cut

=head1 CONTACT

Describe contact details here

=cut

=head1 APPENDIX

The rest of the documentation details each of the object methods.
Internal methods are usually preceded with a _

=cut

package Bio::EnsEMBL::Compara::RunnableDB::GenomeLoadReuseMembers;

use strict;

use Bio::EnsEMBL::DBSQL::DBAdaptor;
use Bio::EnsEMBL::DBLoader;
use Bio::EnsEMBL::Utils::Exception;

use Bio::EnsEMBL::Pipeline::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Compara::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Compara::Member;
use Bio::EnsEMBL::Compara::Homology;
use Bio::EnsEMBL::Compara::Member;
use Bio::EnsEMBL::Compara::Subset;

use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable');

=head2 fetch_input

    Title   :   fetch_input
    Usage   :   $self->fetch_input
    Function:   prepares global variables and DB connections
    Returns :   none
    Args    :   none

=cut

sub fetch_input {
  my( $self) = @_;

  $self->throw("No input_id") unless defined($self->input_id);
  print("input_id = ".$self->input_id."\n");
  $self->throw("Improper formated input_id") unless ($self->input_id =~ /{/);

  ########################################
  my $p = eval($self->analysis->parameters);
  if (defined $p->{'blast_template_analysis_data_id'}) {
    my $analysis_data_id = $p->{'blast_template_analysis_data_id'};
    my $ada = $self->db->get_AnalysisDataAdaptor;
    my $new_params = eval($ada->fetch_by_dbID($analysis_data_id));
    if (defined $new_params) {
      $p = $new_params;
    }
  }
  $self->{p} = $p;
  ########################################

  my $input_hash = eval($self->input_id);
  my $genome_db_id = $input_hash->{'gdb'};
  print("gdb = $genome_db_id\n");
  $self->throw("No genome_db_id in input_id") unless defined($genome_db_id);

  if($input_hash->{'pseudo_stableID_prefix'}) {
    $self->{'pseudo_stableID_prefix'} = $input_hash->{'pseudo_stableID_prefix'};
  }
  if($input_hash->{force_unique_canonical}) {
    $self->{force_unique_canonical} = $input_hash->{force_unique_canonical};
  }

  ########################################
  # Check if this is one that we need to reuse
  $self->{reuse_this} = 0;
  foreach my $reusable_gdb (@{$p->{reuse_gdb}}) {
    $self->{reusable_gdb}{$reusable_gdb} = 1;
  }
  $self->{reuse_this} = 1  if (defined($self->{reusable_gdb}{$input_hash->{'gdb'}}));
  $self->{reuse_this} = 1  if ($p->{reuse_gdb} eq 'all');
  ########################################

  #create a Compara::DBAdaptor which shares the same DBI handle
  #with the Pipeline::DBAdaptor that is based into this runnable

  $self->{memberDBA} = $self->compara_dba->get_MemberAdaptor();

  #get the Compara::GenomeDB object for the genome_db_id
  $self->{'genome_db'} = $self->compara_dba->get_GenomeDBAdaptor->fetch_by_dbID($genome_db_id);

  #using genome_db_id, connect to external core database
  $self->{'coreDBA'} = $self->{'genome_db'}->db_adaptor();
  $self->throw("Can't connect to genome database for id=$genome_db_id") unless($self->{'coreDBA'});

  #global boolean control value (whether the genes are also stored as members)
  $self->{'store_genes'} = 1;

  $self->{'verbose'} = 0;
  $self->{'verbose'} = 1 if (2 == $self->debug);

  #variables for tracking success of process
  $self->{'sliceCount'}       = 0;
  $self->{'geneCount'}        = 0;
  $self->{'realGeneCount'}    = 0;
  $self->{'transcriptCount'}  = 0;
  $self->{'longestCount'}     = 0;

  return 1;
}

sub run
{
  my $self = shift;

  #create subsets for the gene members, and the longest peptide members
  $self->{'pepSubset'}  = Bio::EnsEMBL::Compara::Subset->new(
      -name=>"gdb:".$self->{'genome_db'}->dbID ." ". $self->{'genome_db'}->name . ' longest translations');
  $self->{'geneSubset'} = Bio::EnsEMBL::Compara::Subset->new(
      -name=>"gdb:".$self->{'genome_db'}->dbID ." ". $self->{'genome_db'}->name . ' genes');

  # This does an INSERT IGNORE or a SELECT if already exists
  $self->compara_dba->get_SubsetAdaptor->store($self->{'pepSubset'});
  $self->compara_dba->get_SubsetAdaptor->store($self->{'geneSubset'});

  if (1 == $self->{reuse_this}) {
    return 1 unless ($self->analysis->logic_name eq 'GenomeLoadReuseMembers');
    $self->create_temp_member_table;
    $self->load_reused_member_ids;
  }

  if (0 == $self->{reuse_this}) {
    return 1 unless ($self->analysis->logic_name eq 'GenomeLoadMembers');
  }

  $self->compara_dba->dbc->disconnect_when_inactive(0);
  $self->{'coreDBA'}->dbc->disconnect_when_inactive(0);

  # main routine which takes a genome_db_id (from input_id) and
  # access the ensembl_core database, useing the SliceAdaptor
  # it will load all slices, all genes, and all transcripts
  # and convert them into members to be stored into compara
  $self->loadMembersFromCoreSlices();

  $self->compara_dba->dbc->disconnect_when_inactive(1);
  $self->{'coreDBA'}->dbc->disconnect_when_inactive(1);

  if (1 == $self->{reuse_this}) {
    $self->drop_temp_member_table;
  }

  return 1;
}

sub write_output
{
  my $self = shift;

  # We do the flow for both in the code, only one in loadGeneTreeSystem
  # Anyway, it will do the INSERT IGNORE in AnalysisJobAdaptor and
  # store it only once tried done more than one

#   if (1 == $self->{reuse_this}) {
#     return 1 unless ($self->analysis->logic_name eq 'GenomeLoadReuseMembers');
#   }

#   if (0 == $self->{reuse_this}) {
#     return 1 unless ($self->analysis->logic_name eq 'GenomeLoadMembers');
#   }

  my $output_id = "{'gdb'=>" . $self->{'genome_db'}->dbID .
                  ",'ss'=>" . $self->{'pepSubset'}->dbID . "}";
  $self->input_job->input_id($output_id);
  return 1;
}

######################################
#
# subroutines
#
#####################################

sub load_reused_member_ids {
  my $self = shift;
  my $starttime = time();

  return unless($self->{'genome_db'});
  my $gdb = $self->{'genome_db'};
  return unless $gdb;

  my $gdb_id = $gdb->dbID;
  my $species_name = lc($gdb->name);
  $species_name =~ s/\ /\_/g;
  my $tbl_name = "reuse_member"."_"."$species_name"."_"."$gdb_id";
  my $sql = "SELECT stable_id, member_id, source_name from $tbl_name";
  print("$sql\n") if ($self->debug);
  my $sth = $self->dbc->prepare($sql);
  $sth->execute();
  printf("  %1.3f secs to SELECT stable_id, member_id, source_name from $tbl_name\n", (time()-$starttime));
  while (my $href = $sth->fetchrow_hashref) {
    my $stable_id = $href->{stable_id}; my $source_name = $href->{source_name}; my $member_id = $href->{member_id};
    $self->{reuse_member_list}{$stable_id}{$source_name} = $member_id;
  }
  $sth->finish;

  return 1;
}

sub drop_temp_member_table {
  my $self = shift;
  my $starttime = time();

  $self->{comparaDBA_reuse} = Bio::EnsEMBL::Hive::URLFactory->fetch($self->{p}{reuse_db} . ';type=compara');
  unless (defined($self->{comparaDBA_reuse})) {
    my $reuse_db = $self->{p}{reuse_db};
    $self->throw("Couldn't connect to reuse db $reuse_db: $!");
  }
  return unless($self->{'genome_db'});
  my $gdb = $self->{'genome_db'};
  return unless $gdb;

  my $gdb_id = $gdb->dbID;
  my $species_name = lc($gdb->name);
  $species_name =~ s/\ /\_/g;
  my $tbl_name = "reuse_member"."_"."$species_name"."_"."$gdb_id";

  my $sql;
  $sql = "DROP TABLE IF EXISTS $tbl_name";
  print("$sql\n") if ($self->debug);
  my $sth = $self->dbc->prepare($sql);
  $sth->execute();
  printf("  %1.3f secs to DROP TABLE IF EXISTS $tbl_name\n", (time()-$starttime));
  $sth->finish;

  return 1;
}

sub create_temp_member_table {
  my $self = shift;
  my $starttime = time();

  $self->{comparaDBA_reuse} = Bio::EnsEMBL::Hive::URLFactory->fetch($self->{p}{reuse_db} . ';type=compara');
  unless (defined($self->{comparaDBA_reuse})) {
    my $reuse_db = $self->{p}{reuse_db};
    $self->throw("Couldn't connect to reuse db $reuse_db: $!");
  }
  return unless($self->{'genome_db'});
  my $gdb = $self->{'genome_db'};
  return unless $gdb;

  my $gdb_id = $gdb->dbID;
  my $species_name = lc($gdb->name);
  $species_name =~ s/\ /\_/g;
  my $tbl_name = "reuse_member"."_"."$species_name"."_"."$gdb_id";

  my $sql;
  $sql = "DROP TABLE IF EXISTS $tbl_name";
  print("$sql\n") if ($self->debug);
  my $sth = $self->dbc->prepare($sql);
  $sth->execute();
  printf("  %1.3f secs to DROP TABLE IF EXISTS $tbl_name\n", (time()-$starttime));
  $sth->finish;

  my $reuse_username = $self->{comparaDBA_reuse}->dbc->username;
  my $reuse_password = $self->{comparaDBA_reuse}->dbc->password;
  my $pass = "-p$reuse_password " if ($reuse_password);
  my $reuse_host = $self->{comparaDBA_reuse}->dbc->host;
  my $reuse_port = $self->{comparaDBA_reuse}->dbc->port;
  my $reuse_dbname = $self->{comparaDBA_reuse}->dbc->dbname;

  my $dest_username = $self->dbc->username;
  my $dest_password = $self->dbc->password;
  my $dest_pass = "-p$dest_password" if ($dest_password);
  my $dest_host = $self->dbc->host;
  my $dest_port = $self->dbc->port;
  my $dest_dbname = $self->dbc->dbname;

  my $cmd = "mysqldump --skip-quote-names --where=\"genome_db_id=$gdb_id\" -u $reuse_username $pass -h $reuse_host -P$reuse_port $reuse_dbname member";
  print("Running: # $cmd\n") if($self->debug);
  open(INRUN, "$cmd |") or $self->throw("Error mysqldump $tbl_name, $!\n");
  my @output = <INRUN>;
  my $exit_status = close(INRUN);
  foreach my $line (@output) {
    $line =~ s/((EXISTS|SKIP|TABLE|TABLES|INTO)) member/$1 $tbl_name/g;
  }

  my $tempfile = $self->worker_temp_directory . "$tbl_name.sql";
  open(OUTRUN, ">$tempfile") or $self->throw("Error writing mysqldump $tempfile, $!\n");
  print OUTRUN @output;
  close OUTRUN;
  $cmd = "cat $tempfile | mysql -u $dest_username $dest_pass -h $dest_host -P$dest_port $dest_dbname";
  my $ret = system($cmd);
  printf("  %1.3f secs to mysqldump $tbl_name\n", (time()-$starttime));
  if (0 != $ret) {
    $self->throw("Error importing $tempfile: $ret\n");
  }

  return 1;
}

sub loadMembersFromCoreSlices
{
  my $self = shift;

  #from core database, get all slices, and then all genes in slice
  #and then all transcripts in gene to store as members in compara

  my @slices = @{$self->{'coreDBA'}->get_SliceAdaptor->fetch_all('toplevel')};
  print("fetched ",scalar(@slices), " slices to load from\n");
  $self->throw("problem: no toplevel slices") unless(scalar(@slices));

  SLICE: foreach my $slice (@slices) {
    $self->{'sliceCount'}++;
    #print("slice " . $slice->name . "\n");
    foreach my $gene (sort {$a->start <=> $b->start} @{$slice->get_all_Genes}) {
      $self->{'geneCount'}++;

      # LV and C are for the Ig/TcR family, which rearranges
      # somatically so is considered as a different biotype in EnsEMBL
      # D and J are very short or have no translation at all
      if (lc($gene->biotype) eq 'protein_coding'         ||
          lc($gene->biotype) eq 'ig_v_gene'              ||
          lc($gene->biotype) eq 'ig_c_gene'              ||
          lc($gene->biotype) eq 'c_segment'              ||
          lc($gene->biotype) eq 'v_segment') {
        $self->{'realGeneCount'}++;
        $self->store_gene_and_all_transcripts($gene);
        print STDERR $self->{'realGeneCount'} , " genes stored\n" if ($self->debug && (0 == ($self->{'realGeneCount'} % 100)));
      }
      # if($self->{'transcriptCount'} >= 100) { last SLICE; }
      # if($self->{'geneCount'} >= 1000) { last SLICE; }
    }
    # last SLICE;
  }

  print("loaded ".$self->{'sliceCount'}." slices\n");
  print("       ".$self->{'geneCount'}." genes\n");
  print("       ".$self->{'realGeneCount'}." real genes\n");
  print("       ".$self->{'transcriptCount'}." transcripts\n");
  print("       ".$self->{'longestCount'}." canonical transcripts\n");
  print("       ".$self->{'pepSubset'}->count()." in Subset\n");
}

sub store_gene_and_all_transcripts
{
  my $self = shift;
  my $gene = shift;

  # my @longestPeptideMember;
  my @canonicalPeptideMember;
  # my $maxLength=0;
  my $gene_member;
  my $gene_member_not_stored = 1;

  if(defined($self->{'pseudo_stableID_prefix'})) {
    $gene->stable_id($self->{'pseudo_stableID_prefix'} ."G_". $gene->dbID);
  }

  my $canonical_transcript; my $canonical_transcript_stable_id;
  eval {
    $canonical_transcript = $gene->canonical_transcript;
    $canonical_transcript_stable_id = $canonical_transcript->stable_id;
  };
  if (!defined($canonical_transcript) && !defined($self->{force_unique_canonical})) {
    print STDERR "WARN: ", $gene->stable_id, " has no canonical transcript\n" if ($self->debug);
    return 1;
  }
  foreach my $transcript (@{$gene->get_all_Transcripts}) {
    my $translation = $transcript->translation;
    next unless (defined $translation);

    if (!defined($self->{force_unique_canonical})) {
      if ($canonical_transcript->biotype ne $gene->biotype) {
        # This can happen when the only transcripts are, e.g., NMDs
        print STDERR "INFO: ", $canonical_transcript->stable_id, " biotype ", $canonical_transcript->biotype, " is canonical\n" if ($self->debug);
      }
    }
#    This test might be useful to put here, thus avoiding to go further in trying to get a peptide
#    my $next = 0;
#    try {
#      $transcript->translate;
#    } catch {
#      warn("COREDB error: transcript does not translate", $transcript->stable_id, "(dbID=",$transcript->dbID.")\n");
#      $next = 1;
#    };
#    next if ($next);

    if(defined($self->{'pseudo_stableID_prefix'})) {
      $transcript->stable_id($self->{'pseudo_stableID_prefix'} ."T_". $transcript->dbID);
      $translation->stable_id($self->{'pseudo_stableID_prefix'} ."P_". $translation->dbID);
    }

    $self->{'transcriptCount'}++;
    #print("gene " . $gene->stable_id . "\n");
    print("     transcript " . $transcript->stable_id ) if($self->{'verbose'});

    unless (defined $translation->stable_id) {
      $self->throw("COREDB error: does not contain translation stable id for translation_id ". $translation->dbID."\n");
      next;
    }

    my $description = $self->fasta_description($gene, $transcript);

    my $pep_member = Bio::EnsEMBL::Compara::Member->new_from_transcript(
         -transcript=>$transcript,
         -genome_db=>$self->{'genome_db'},
         -translate=>'yes',
         -description=>$description);

    print(" => member " . $pep_member->stable_id) if($self->{'verbose'});

    unless($pep_member->sequence) {
      print "  => NO SEQUENCE for member " . $pep_member->stable_id;
      next;
    }
    print(" len=",$pep_member->seq_length ) if($self->{'verbose'});

    # store gene_member here only if at least one peptide is to be loaded for
    # the gene.
    if($self->{'store_genes'} && $gene_member_not_stored) {
      print("     gene       " . $gene->stable_id ) if($self->{'verbose'});
      $gene_member = Bio::EnsEMBL::Compara::Member->new_from_gene(
                                                                  -gene=>$gene,
                                                                  -genome_db=>$self->{'genome_db'});
      print(" => member " . $gene_member->stable_id) if($self->{'verbose'});

      eval {
        # We had this stable_id in reuse_db, so we store it with the same member_id again
        if (defined($self->{reuse_member_list}{$gene_member->stable_id}{ENSEMBLGENE})) {
          $gene_member->dbID($self->{reuse_member_list}{$gene_member->stable_id}{ENSEMBLGENE});
          $self->{memberDBA}->store_reused($gene_member);
        } else {
          my $stable_id = $gene_member->stable_id;
          if (1 == $self->{reuse_this}) {
            $self->input_job->transient_error(0);
            throw ("Reuse member set non identical for $stable_id: $!");
          }
          $self->{memberDBA}->store($gene_member);
        }
        print(" : stored") if($self->{'verbose'});
      };

      $self->{'geneSubset'}->add_member($gene_member);
      print("\n") if($self->{'verbose'});
      $gene_member_not_stored = 0;
    }

    if (defined($self->{reuse_member_list}{$pep_member->stable_id}{ENSEMBLPEP})) {
      $pep_member->dbID($self->{reuse_member_list}{$pep_member->stable_id}{ENSEMBLPEP});
      $self->{memberDBA}->store_reused($pep_member);
    } else {
      my $stable_id = $pep_member->stable_id;
      if (1 == $self->{reuse_this}) {
            $self->input_job->transient_error(0);
            throw ("Reuse member set non identical for $stable_id: $!");
      }
      $self->{memberDBA}->store($pep_member);
    }
    $self->{memberDBA}->store_gene_peptide_link($gene_member->dbID, $pep_member->dbID);
    print(" : stored\n") if($self->{'verbose'});

    if(($transcript->stable_id eq $canonical_transcript_stable_id) || defined($self->{force_unique_canonical})) {
      @canonicalPeptideMember = ($transcript, $pep_member);
    }

  }

  if(@canonicalPeptideMember) {
    my ($transcript, $member) = @canonicalPeptideMember;
    $self->{'pepSubset'}->add_member($member);
    $self->{'longestCount'}++;
    # print("     LONGEST " . $transcript->stable_id . "\n");
  }
  return 1;
}

sub fasta_description {
  my ($self, $gene, $transcript) = @_;

  my $description = "Transcript:" . $transcript->stable_id .
                    " Gene:" .      $gene->stable_id .
                    " Chr:" .       $gene->seq_region_name .
                    " Start:" .     $gene->seq_region_start .
                    " End:" .       $gene->seq_region_end;
  return $description;
}

1;


text:
require 'spec_helper'
require 'rack/test'

describe Twimock::API::OAuth::RequestToken do
  include TestApplicationHelper
  include Rack::Test::Methods

  let(:method)   { 'POST' }
  let(:path)     { '/oauth/request_token' }
  let(:authorization_regexp) { Regexp.new('OAuth oauth_callback=\"(.*)\", oauth_consumer_key=\"(.*)\", oauth_nonce=\"(.*)\", oauth_signature=\"(.*)\", oauth_signature_method=\"(.*)\", oauth_timestamp=\"(.*)\", oauth_version=\"(.*)\".*') }
  let(:body)     { "" }
  let(:header)   { {} }
  let(:test_app) { TestApplicationHelper::TestRackApplication.new }
  let(:app)      { Twimock::API::OAuth::RequestToken.new(test_app) }

  describe '::METHOD' do
    subject { Twimock::API::OAuth::RequestToken::METHOD }
    it { is_expected.to eq method }
  end

  describe '::PATH' do
    subject { Twimock::API::OAuth::RequestToken::PATH }
    it { is_expected.to eq path }
  end

  describe '::AUTHORIZATION_REGEXP' do
    subject { Twimock::API::OAuth::RequestToken::AUTHORIZATION_REGEXP }
    it { is_expected.to eq authorization_regexp }
  end

  describe "POST '/oauth/request_token'" do
    context 'with authorization header' do
      before { stub_const("Twimock::Database::DEFAULT_DB_NAME", db_name) }
      after  { database.drop }

      let(:db_name)  { ".test" }
      let(:database) { Twimock::Database.new }

      let(:header) { { "authorization" => @authorization } }

      context 'that is correct' do
        before do
          app = Twimock::Application.new
          app.save!
          @authorization = ["OAuth oauth_callback=\"http%3A%2F%2Fhiddeste.local.jp%3A3456%2Fusers%2Fauth%2Ftwitter%2Fcallback\", oauth_consumer_key=\"#{app.api_key}\", oauth_nonce=\"gop2czKq1IebHEvEIo2qE64Hwp5SRWxLgilYAKqrWE\", oauth_signature=\"FVn4chN1TbLPDDsLb%2FqG%2FU99biA%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1422273831\", oauth_version=\"1.0\""]
        end

        it 'should return 200 OK' do
          post path, body, header
          expect(last_response.status).to eq 200
          expect(last_response.header).not_to be_blank
          expect(last_response.header['Content-Length']).to eq last_response.body.bytesize.to_s
          expect(last_response.body).not_to be_blank

          index = last_response.body =~ /^oauth_token=(.*)&oauth_token_secret=(.*)&oauth_callback_confirmed=(.*)$/
          expect(index).to eq 0
          oauth_token = $1
          oauth_secret = $2
          oauth_callback_confirmed = $3

          token = Twimock::RequestToken.find_by_string(oauth_token)
          expect(token).not_to be_nil
          expect(token.secret).to eq oauth_secret
          expect(oauth_callback_confirmed).to eq true.to_s
        end
      end

      context 'that is incorrect format' do
        before do
          @authorization = ["OAuth consumer_key=\"test_consumer_key\""]
          post path, body, header
        end
        it_behaves_like "API 401 UnAuthorized"
      end

      context 'but consumer_key is invalid' do
        before do
          app = Twimock::Application.new
          @authorization = ["OAuth oauth_callback=\"http%3A%2F%2Fhiddeste.local.jp%3A3456%2Fusers%2Fauth%2Ftwitter%2Fcallback\", oauth_consumer_key=\"#{app.api_key}\", oauth_nonce=\"gop2czKq1IebHEvEIo2qE64Hwp5SRWxLgilYAKqrWE\", oauth_signature=\"FVn4chN1TbLPDDsLb%2FqG%2FU99biA%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1422273831\", oauth_version=\"1.0\""]
          post path, body, header
        end
        it_behaves_like "API 401 UnAuthorized"
      end

      context 'raise error that is not catched' do
        before do
          allow(Twimock::Application).to receive(:find_by_api_key){ raise }
          app = Twimock::Application.new
          app.save!
          @authorization = ["OAuth oauth_callback=\"http%3A%2F%2Fhiddeste.local.jp%3A3456%2Fusers%2Fauth%2Ftwitter%2Fcallback\", oauth_consumer_key=\"#{app.api_key}\", oauth_nonce=\"gop2czKq1IebHEvEIo2qE64Hwp5SRWxLgilYAKqrWE\", oauth_signature=\"FVn4chN1TbLPDDsLb%2FqG%2FU99biA%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1422273831\", oauth_version=\"1.0\""]
          post path, body, header
        end
        it_behaves_like 'API 500 InternalServerError'
      end

      context 'without authorization header'do
        before { post path, body, header }
        it_behaves_like "API 401 UnAuthorized"
      end
    end

  end

  describe "POST '/test'" do
    it 'should return 200 OK' do
      post '/test'

      expect(last_response.status).to eq 200
      expect(last_response.header).to be_blank
      expect(last_response.body).to be_blank
    end
  end

  describe "GET '/oauth/request_token'" do
    it 'should return 200 OK' do
      get '/oauth/request_token'

      expect(last_response.status).to eq 200
      expect(last_response.header).to be_blank
      expect(last_response.body).to be_blank
    end
  end
end


text:
<?php

    namespace app\models;

    use Yii;
    use yii\base\Model;
    use yii\data\ActiveDataProvider;
    use app\models\Staff;

    /**
     * SearchStaff represents the model behind the search form about `app\models\Staff`.
     */
    class SearchStaff extends Staff
    {
        public $department;
        /**
         * @inheritdoc
         */
        public function rules()
        {
            return [
                [['id', 'id_department', 'status'], 'integer'],
                [['fio'], 'safe'],
            ];
        }

        /**
         * @inheritdoc
         */
        public function scenarios()
        {
            // bypass scenarios() implementation in the parent class
            return Model::scenarios();
        }

        /**
         * Creates data provider instance with search query applied
         *
         * @param array $params
         *
         * @return ActiveDataProvider
         */
        public function search($params)
        {
            if($params == Staff::STATUS_INACTIVE) {
                $query = Staff::find()->with('idDepartment')->where(['status' => Staff::STATUS_INACTIVE])->orderBy(['id' => SORT_DESC]);

            }else{
                $query = Staff::find()->with('idDepartment');
            }

            $dataProvider = new ActiveDataProvider([
                'query' => $query,
                'pagination' => [
                    'forcePageParam' => false,
                    'pageSizeParam' => false,
                    'pageSize' => 10,
                ]
            ]);

            $this->load($params);

            if (!$this->validate()) {
                // uncomment the following line if you do not want to any records when validation fails
                // $query->where('0=1');
                return $dataProvider;
            }

            $query->joinWith('idDepartment');

            $query->andFilterWhere([
                'id' => $this->id,
                'id_department' => $this->id_department,
                'status' => $this->status,
            ]);

            $query->andFilterWhere(['like', 'fio', $this->fio])
                ->andFilterWhere(['like', 'department.department', $this->department]);

            return $dataProvider;
        }
    }


text:
package net.ssehub.easy.producer.core.mgmt;

import org.junit.Assert;

import net.ssehub.easy.instantiation.core.model.common.VilException;
import net.ssehub.easy.producer.core.mgmt.IVilExecutionListener;
import net.ssehub.easy.producer.core.mgmt.PLPInfo;

/**
 * Needed to test {@link PLPInfo#instantiate(de.uni_hildesheim.sse.utils.progress.ProgressObserver)}
 * to ensure that the thread has been finished before the test is finished by Junit.
 * @author El-Sharkawy
 */
class VilTestExectuter implements IVilExecutionListener {

    /**
     * Listener for testing the instantiation.
     * @author El-Sharkawy
     *
     */
    abstract static class AbstractVilListener {

        /**
         * Will be called in case of error detected during instantiation.
         * Overwrite it if errors shall be detected.
         * @param plp The {@link PLPInfo}, which should be instantiated and is the source for this error.
         * @param exc The error which lead to the abortion.
         */
        public void vilExecutionAborted(PLPInfo plp, VilException exc) {
            Assert.fail("Instantiation of " + plp.getProjectName() + " failed: " + exc.getMessage());
        }

        /**
         * Will be called after instantiation was finished successfully.
         * Maybe overwritten if needed.
         * @param plp The {@link PLPInfo} which was used for instantiation
         */
        public void vilExecutionFinished(PLPInfo plp) {

        }
    }

    private AbstractVilListener listener;
    private boolean finished;

    /**
     * Performs the instantiation.
     * @param plp The {@link PLPInfo} which shall be instantiated
     * @param listener A listener for asserting the correct behavior of the instantiation process.
     */
    public void assertInstantiation(PLPInfo plp, AbstractVilListener listener) {
        assertInstantiation(plp, 1000, listener);
    }

    /**
     * Performs the instantiation.
     * @param plp The {@link PLPInfo} which shall be instantiated
     * @param timeout Timeout in milliseconds for the whole instantiation
     * @param listener A listener for asserting the correct behavior of the instantiation process.
     */
    public void assertInstantiation(PLPInfo plp, long timeout, AbstractVilListener listener) {
        finished = false;
        this.listener = listener;

        plp.addVilExecutionListener(this);
        plp.instantiate(null);

        long startTime = System.currentTimeMillis();
        while (!finished) {
            if (System.currentTimeMillis() - startTime < timeout) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Assert.fail(e.getMessage());
                }
            } else {
                finished = true;
                Assert.fail("Timeout occured during instantiation of " + plp.getProjectName());
            }
        }

        plp.removeVilExecutionListener(this);
        Assert.assertTrue("Instantiation was not finished.", finished);
    }

    @Override
    public void vilExecutionAborted(PLPInfo plp, VilException exc) {
        plp.removeVilExecutionListener(this);
        listener.vilExecutionAborted(plp, exc);
        finished = true;
    }

    @Override
    public void vilExecutionFinished(PLPInfo plp, boolean successful) {
        plp.removeVilExecutionListener(this);
        listener.vilExecutionFinished(plp);
        finished = true;
    }
}


text:
#ifndef VIRTUALDIR_H
#define VIRTUALDIR_H

/** The \b VirtualDirCallbacks structure contains the pointers to
 *  file-related callback functions a device application can register to
 *  virtualize URLs.
 */
struct VirtualDirCallbacks
{
	/** Called by the web server to query information on a file.  The callback
	 *  should return 0 on success or -1 on an error. */
	VDCallback_GetInfo get_info;

	/** Called by the web server to open a file.  The callback should return
	 *  a valid handle if the file can be opened.  Otherwise, it should return
	 *  \c NULL to signify an error. */
	VDCallback_Open open;

	/** Called by the web server to perform a sequential read from an open
	 *  file.  The callback should copy \b buflen bytes from the file into
	 *  the buffer.
	 *  @return An integer representing one of the following:
	 *      \li <tt>   0</tt>:  The file contains no more data (EOF).
	 *      \li <tt> > 0</tt>: A successful read of the number of bytes in the
	 *      	return code.
	 *      \li <tt> < 0</tt>: An error occurred reading the file.
	 */
	VDCallback_Read read;

	/** Called by the web server to perform a sequential write to an open
	 *  file.  The callback should write \b buflen bytes into the file from
	 *  the buffer.  It should return the actual number of bytes written,
	 *  which might be less than \b buflen in the case of a write error.
	 */
	VDCallback_Write write;

	/** Called by the web server to move the file pointer, or offset, into
	 *  an open file.  The \b origin parameter determines where to start
	 *  moving the file pointer.  A value of \c SEEK_CUR moves the
	 *  file pointer relative to where it is.  The \b offset parameter can
	 *  be either positive (move forward) or negative (move backward).
	 *  \c SEEK_END moves relative to the end of the file.  A positive
	 *  \b offset extends the file.  A negative \b offset moves backward
	 *  in the file.  Finally, \c SEEK_SET moves to an absolute position in
	 *  the file. In this case, \b offset must be positive.  The callback
	 *  should return 0 on a successful seek or a non-zero value on an error.
	 */
	VDCallback_Seek seek;

	/** Called by the web server to close a file opened via the \b open
	 *  callback.  It should return 0 on success, or a non-zero value on an
	 *  error.
	 */
	VDCallback_Close close;
};

typedef struct virtual_Dir_List
{
	struct virtual_Dir_List *next;
	const void *cookie;
	char dirName[NAME_SIZE];
} virtualDirList;

#endif /* VIRTUALDIR_H */


text:
package io.grpc.protobuf;

import com.google.protobuf.Descriptors.FileDescriptor;

/**
 * Provides access to the underlying proto file descriptor.
 */
public interface ProtoFileDescriptorSupplier {
  /**
   * Returns file descriptor to the underlying proto file.
   */
  FileDescriptor getFileDescriptor();
}