text:
<?php

/**
* Evgeny Muravjev Typograph, http://mdash.ru
* Version: 3.4 Gold Master
* Release Date: September 20, 2014
* Authors: Evgeny Muravjev & Alexander Drutsa
*/

namespace Fenrizbes\TypographBundle\EMT;

/**
 * Базовый класс для группы правил обработки текста
 * Класс группы должен наследовать, данный класс и задавать
 * в нём EMTTret::rules и EMTTret::$name
 *
 */
class EMTTret {

	/**
	 * Набор правил в данной группе, который задан изначально
	 * Его можно менять динамически добавляя туда правила с помощью put_rule
	 *
	 * @var unknown_type
	 */
	public    $rules;
	public    $title;

	private   $disabled = array();
	private   $enabled  = array();
	protected $_text= '';
	public $logging = false;
	public $logs    = false;
	public $errors  = false;
	public $debug_enabled  = false;
	public $debug_info     = array();

	private $use_layout = false;
	private $use_layout_set = false;
	private $class_layout_prefix = false;

	public $class_names     = array();
	public $classes         = array();
	public $settings        = array();

	/**
	 * Защищенные теги
	 *
	 * @todo привязать к методам из Jare_Typograph_Tool
	 */
	const BASE64_PARAGRAPH_TAG = 'cA==='; // p
	const BASE64_BREAKLINE_TAG = 'YnIgLw==='; // br / (с пробелом и слэшем)
	const BASE64_NOBR_OTAG = 'bm9icg==='; // nobr
	const BASE64_NOBR_CTAG = 'L25vYnI=='; // /nobr

	/**
	 * Типы кавычек
	 */
	const QUOTE_FIRS_OPEN = '«';
    const QUOTE_FIRS_CLOSE = '»';
    const QUOTE_CRAWSE_OPEN = '„';
    const QUOTE_CRAWSE_CLOSE = '“';

	private function log($str, $data = null)
	{
		if(!$this->logging) return;
		$this->logs[] = array('info' => $str, 'data' => $data);
	}

	private function error($info, $data = null)
	{
		$this->errors[] = array('info' => $info, 'data' => $data);
		$this->log('ERROR: '. $info , $data);
	}

	public function debug($place, &$after_text)
	{
		if(!$this->debug_enabled) return;
		$this->debug_info[] = array(
				'place' => $place,
				'text'  => $after_text,
			);
	}

	/**
	 * Установить режим разметки для данного Трэта если не было раньше установлено,
	 *   EMTLib::LAYOUT_STYLE - с помощью стилей
	 *   EMTLib::LAYOUT_CLASS - с помощью классов
	 *
	 * @param int $kind
	 */
	public function set_tag_layout_ifnotset($layout)
	{
		if($this->use_layout_set) return;
		$this->use_layout = $layout;
	}

	/**
	 * Установить режим разметки для данного Трэта,
	 *   EMTLib::LAYOUT_STYLE - с помощью стилей
	 *   EMTLib::LAYOUT_CLASS - с помощью классов
	 *   EMTLib::LAYOUT_STYLE|EMTLib::LAYOUT_CLASS - оба метода
	 *
	 * @param int $kind
	 */
	public function set_tag_layout($layout = EMTLib::LAYOUT_STYLE)
	{
		$this->use_layout = $layout;
		$this->use_layout_set = true;
	}

	public function set_class_layout_prefix($prefix)
	{
		$this->class_layout_prefix = $prefix;
	}

	public function debug_on()
	{
		$this->debug_enabled = true;
	}

	public function log_on()
	{
		$this->debug_enabled = true;
	}

	private function getmethod($name)
	{
		if(!$name) return false;
		if(!method_exists($this, $name)) return false;
		return array($this, $name);
	}

	private function _pre_parse()
	{
		$this->pre_parse();
		foreach($this->rules as $rule)
		{
			if(!isset($rule['init'])) continue;
			$m = $this->getmethod($rule['init']);
			if(!$m) continue;
			call_user_func($m);
		}
	}
	private function _post_parse()
	{
		foreach($this->rules as $rule)
		{
			if(!isset($rule['deinit'])) continue;
			$m = $this->getmethod($rule['deinit']);
			if(!$m) continue;
			call_user_func($m);
		}
		$this->post_parse();
	}

	private function rule_order_sort($a, $b)
	{
		if($a['order'] == $b['order']) return 0;
		if($a['order'] < $b['order']) return -1;
		return 1;
	}

	private function apply_rule($rule)
	{
		$name = $rule['id'];
		//$this->log("Правило $name", "Применяем правило");
		$disabled = (isset($this->disabled[$rule['id']]) && $this->disabled[$rule['id']]) || ((isset($rule['disabled']) && $rule['disabled']) && !(isset($this->enabled[$rule['id']]) && $this->enabled[$rule['id']]));
		if($disabled)
		{
			$this->log("Правило $name", "Правило отключено" . ((isset($rule['disabled']) && $rule['disabled'])? " (по умолчанию)" : ""));
			return;
		}
		if(isset($rule['function']) && $rule['function'])
		{
			if(!(isset($rule['pattern']) &&  $rule['pattern']))
			{
				if(method_exists($this, $rule['function']))
				{
					$this->log("Правило $name", "Используется метод ".$rule['function']." в правиле");

					call_user_func(array($this, $rule['function']));
					return;
				}
				if(function_exists($rule['function']))
				{
					$this->log("Правило $name", "Используется функция ".$rule['function']." в правиле");

					call_user_func($rule['function']);
					return;
				}

				$this->error('Функция '.$rule['function'].' из правила '.$rule['id']. " не найдена");
				return ;
			} else {
				if(preg_match("/^[a-z_0-9]+$/i", $rule['function']))
				{
					if(method_exists($this, $rule['function']))
					{
						$this->log("Правило $name", "Замена с использованием preg_replace_callback с методом ".$rule['function']."");

						$this->_text = preg_replace_callback($rule['pattern'], array($this, $rule['function']), $this->_text);
						return;
					}
					if(function_exists($rule['function']))
					{
						$this->log("Правило $name", "Замена с использованием preg_replace_callback с функцией ".$rule['function']."");

						$this->_text = preg_replace_callback($rule['pattern'], $rule['function'], $this->_text);
						return;
					}
					$this->error('Функция '.$rule['function'].' из правила '.$rule['id']. " не найдена");
				} else {
					$this->_text = preg_replace_callback($rule['pattern'],  create_function('$m', $rule['function']), $this->_text);
					$this->log('Замена с использованием preg_replace_callback с инлайн функцией из правила '.$rule['id']);
					return;
				}
				return ;
			}
		}

		if(isset($rule['simple_replace']) && $rule['simple_replace'])
		{
			if(isset($rule['case_sensitive']) && $rule['case_sensitive'])
			{
				$this->log("Правило $name", "Простая замена с использованием str_replace");
				$this->_text = str_replace($rule['pattern'], $rule['replacement'], $this->_text);
				return;
			}
			$this->log("Правило $name", "Простая замена с использованием str_ireplace");
			$this->_text = str_ireplace($rule['pattern'], $rule['replacement'], $this->_text);
			return;
		}

		$pattern = $rule['pattern'];
		if(is_string($pattern)) $pattern = array($pattern);
		$eval = false;
		foreach($pattern as $patt)
		{
			$chr = substr($patt,0,1);
			$preg_arr = explode($chr, $patt);
			if(strpos($preg_arr[count($preg_arr)-1], "e")!==false)
			{
				$eval = true;
				break;
			}
		}
		if(!$eval)
		{
			$this->log("Правило $name", "Замена с использованием preg_replace");

			do {
				$this->_text = preg_replace($rule['pattern'], $rule['replacement'], $this->_text);
				if(!(isset($rule['cycled']) && $rule['cycled'])) break;
			} while(preg_match($rule['pattern'], $this->_text));

			return;
		}

		$this->log("Правило $name", "Замена с использованием preg_replace_callback вместо eval");
		$k = 0;
		foreach($pattern as $patt)
		{
			$repl = is_string($rule['replacement']) ? $rule['replacement'] : $rule['replacement'][$k];

			$chr = substr($patt,0,1);
			$preg_arr = explode($chr, $patt);
			if(strpos($preg_arr[count($preg_arr)-1], "e")!==false) // eval система
			{
				$preg_arr[count($preg_arr)-1] = str_replace("e","",$preg_arr[count($preg_arr)-1]);
				$patt = implode($chr, $preg_arr);
				$this->thereplacement = $repl;
				do {
					$this->_text = preg_replace_callback($patt, array($this, "thereplcallback"), $this->_text);
					if(!(isset($rule['cycled']) && $rule['cycled'])) break;
				} while(preg_match($patt, $this->_text));

			} else {
				do {
					$this->_text = preg_replace($patt, $repl, $this->_text);
					if(!(isset($rule['cycled']) && $rule['cycled'])) break;
				} while(preg_match($patt, $this->_text));
			}
			$k++;
		}
	}

	protected function preg_replace_e($pattern, $replacement, $text)
	{
		$chr = substr($pattern,0,1);
		$preg_arr = explode($chr, $pattern);
		if(strpos($preg_arr[count($preg_arr)-1], "e")===false) return preg_replace($pattern, $replacement, $text);
		$preg_arr[count($preg_arr)-1] = str_replace("e","",$preg_arr[count($preg_arr)-1]);
		$patt = implode($chr, $preg_arr);
		$this->thereplacement = $replacement;
		return preg_replace_callback($patt, array($this, "thereplcallback"), $text);
	}

	private $thereplacement = "";
	private function thereplcallback($m)
	{
		$x = "";
		eval('$x = '.($this->thereplacement?$this->thereplacement:'""').';');
		return $x;
	}

	private function _apply($list)
	{
		$this->errors = array();
		$this->_pre_parse();

		$this->log("Применяется набор правил", implode(",",$list));

		$rulelist = array();
		foreach($list as $k)
		{
			$rule = $this->rules[$k];
			$rule['id']    = $k;
			$rule['order'] = isset($rule['order'])? $rule['order'] : 5 ;
			$rulelist[] = $rule;
		}
		//usort($rulelist, array($this, "rule_order_sort"));

		foreach($rulelist as $rule)
		{
			$this->apply_rule($rule);
			$this->debug($rule['id'], $this->_text);
		}

		$this->_post_parse();
	}

	/**
	 * Создание защищенного тега с содержимым
	 *
	 * @see 	EMTLib::build_safe_tag
	 * @param 	string $content
	 * @param 	string $tag
	 * @param 	array $attribute
	 * @return 	string
	 */
	protected function tag($content, $tag = 'span', $attribute = array())
	{
		if(isset($attribute['class']))
		{
			$classname = $attribute['class'];
			if($classname == "nowrap")
			{
				if(!$this->is_on('nowrap'))
				{
					$tag = "nobr";
					$attribute = array();
					$classname = "";
				}
			}
			if(isset($this->classes[$classname]))
			{
				$style_inline = $this->classes[$classname];
				if($style_inline) $attribute['__style'] = $style_inline;
			}
			$classname = (isset($this->class_names[$classname]) ? $this->class_names[$classname] :$classname);
			$classname = ($this->class_layout_prefix ? $this->class_layout_prefix : "" ).$classname;
			$attribute['class'] = $classname;
		}

		return EMTLib::build_safe_tag($content, $tag, $attribute,
				$this->use_layout === false? EMTLib::LAYOUT_STYLE  : $this->use_layout );
	}

	/**
	 * Добавить правило в группу
	 *
	 * @param string $name
	 * @param array $params
	 */
	public function put_rule($name, $params)
	{
		$this->rules[$name] = $params;
		return $this;
	}

	/**
	 * Отключить правило, в обработке
	 *
	 * @param string $name
	 */
	public function disable_rule($name)
	{
		$this->disabled[$name] = true;
		unset($this->enabled[$name]);
	}

	/**
	 * Включить правило
	 *
	 * @param string $name
	 */
	public function enable_rule($name)
	{
		$this->enabled[$name] = true;
		unset($this->disabled[$name]);
	}

	/**
	 * Добавить настройку в трет
	 *
	 * @param string $key ключ
	 * @param mixed $value значение
	 */
	public function set($key, $value)
	{
		$this->settings[$key] = $value;
	}

	/**
	 * Установлена ли настройка
	 *
	 * @param string $key
	 */
	public function is_on($key)
	{
		if(!isset($this->settings[$key])) return false;
		$kk = $this->settings[$key];
		return ((strtolower($kk)=="on") || ($kk === "1") || ($kk === true) || ($kk === 1));
	}

	/**
	 * Получить строковое значение настройки
	 *
	 * @param unknown_type $key
	 * @return unknown
	 */
	public function ss($key)
	{
		if(!isset($this->settings[$key])) return "";
		return strval($this->settings[$key]);
	}

	/**
	 * Добавить настройку в правило
	 *
	 * @param string $rulename идентификатор правила
	 * @param string $key ключ
	 * @param mixed $value значение
	 */
	public function set_rule($rulename, $key, $value)
	{
		$this->rules[$rulename][$key] = $value;
	}

	/**
	 * Включить правила, согласно списку
	 *
	 * @param array $list список правил
	 * @param boolean $disable выкллючить их или включить
	 * @param boolean $strict строго, т.е. те которые не в списку будут тоже обработаны
	 */
	public function activate($list,$disable =false, $strict = true)
	{
		if(!is_array($list)) return ;

		foreach($list as $rulename)
		{
			if($disable) $this->disable_rule($rulename); else $this->enable_rule($rulename);
		}

		if($strict)
		{
			foreach($this->rules as $rulename => $v)
			{
				if(in_array($rulename, $list)) continue;
				if(!$disable) $this->disable_rule($rulename); else $this->enable_rule($rulename);
			}
		}
	}

	public function set_text(&$text)
	{
		$this->_text = &$text;
		$this->debug_info = array();
		$this->logs = array();
	}

	/**
	 * Применить к тексту
	 *
	 * @param string $text - текст к которому применить
	 * @param mixed $list - список правил, null - все правила
	 * @return string
	 */
	public function apply($list = null)
	{
		if(is_string($list)) $rlist = array($list);
		elseif(is_array($list)) $rlist = $list;
		else $rlist = array_keys($this->rules);
		$this->_apply($rlist);
		return $this->_text;
	}

	/**
	 * Код, выполняем до того, как применить правила
	 *
	 */
	public function pre_parse()
	{
	}

	/**
	 * После выполнения всех правил, выполняется этот метод
	 *
	 */
	public function post_parse()
	{
	}

}


text:
namespace medialib
{

//template<typename _BufferType>
//struct HiddenFftw
//{
//};

template<>
struct HiddenFftw<double>
{
	typedef fftw_complex ComplexType;

	fftw_plan fftwPlan(int n, double *in, ComplexType *out, unsigned flags)
	{
		return fftw_plan_dft_r2c_1d(n, in, out, flags);
	}

	ComplexType *mallocComplex(size_t n)
	{
		return (ComplexType *)fftw_malloc(n);
	}

	size_t sizeofComplex() { return sizeof(ComplexType); }

	void execute(fftw_plan plan, double *in, ComplexType *out)
	{
		fftw_execute_dft_r2c(plan, in, out);
	}

	fftw_plan m_plan;
	ComplexType *m_outBuffer;
};

template<>
struct HiddenFftw<float>
{
	typedef fftwf_complex ComplexType;

	fftwf_plan fftwPlan(int n, float *in, ComplexType *out, unsigned flags)
	{
		return fftwf_plan_dft_r2c_1d(n, in, out, flags);
	}

	ComplexType *mallocComplex(size_t n)
	{
		return (ComplexType *)fftw_malloc(n);
	}

	size_t sizeofComplex() { return sizeof(ComplexType); }

	void execute(fftwf_plan plan, float *in, ComplexType *out)
	{
		fftwf_execute_dft_r2c(plan, in, out);
	}

	fftwf_plan m_plan;
	ComplexType *m_outBuffer;
};

template HiddenFftw<float>;
template HiddenFftw<double>;

template<typename _DataType>
SpectrogramGenerator<_DataType>::SpectrogramGenerator(size_t windowSize, WindowFunctionType windowType, size_t overlap, bool logarithmic):
	m_overlap(overlap),
	m_windowType(windowType),
	m_windowSize(windowSize),
	m_logarithmic(logarithmic)
{
//	m_hiddenFftw.reset(new HiddenFftw<double>());
	init();
}

template<typename _DataType>
void SpectrogramGenerator<_DataType>::init()
{
	//
	m_windowFunction.set(m_windowType, m_windowSize);

	size_t outSamples=(m_windowSize/2)+1;

	m_inBufferSize=m_windowSize*sizeof(_DataType);
	m_inBuffer=(_DataType *)fftwf_malloc(m_inBufferSize);
//	m_outBufferSize=sizeof(fftwf_complex) * outSamples;
//	m_hiddenFftw.m_outBuffer=(fftwf_complex *)fftwf_malloc(m_outBufferSize);
	m_outBufferSize=m_hiddenFftw.sizeofComplex() * outSamples;
	m_hiddenFftw.m_outBuffer=m_hiddenFftw.mallocComplex(m_outBufferSize);

//	m_hiddenFftw->m_plan=fftwf_plan_dft_r2c_1d(m_windowSize, m_inBuffer, m_hiddenFftw->m_outBuffer, FFTW_ESTIMATE);
	m_hiddenFftw.m_plan=m_hiddenFftw.fftwPlan(m_windowSize, m_inBuffer, m_hiddenFftw.m_outBuffer, FFTW_ESTIMATE);
}

template<typename _DataType>
size_t SpectrogramGenerator<_DataType>::calculateBufferSize(unsigned int samples, size_t &width, size_t &height)
{
	size_t step=m_windowSize-m_overlap;
	width=floor((float)(samples-m_windowSize)/step)+1;
	height=(m_windowSize/2)+1;

	return width*height*sizeof(_DataType);
}

template<typename _DataType>
std::vector<_DataType> SpectrogramGenerator<_DataType>::process(const AudioBuffer &audioBuffer, unsigned int channel, size_t &width, size_t &height)
{
	size_t outputSize=calculateBufferSize(audioBuffer.getSamples(), width, height);
	std::vector<_DataType> output(width*height);

	process(audioBuffer, channel, output.data(), outputSize, width, height);
	return output;
}

template<typename _DataType>
bool SpectrogramGenerator<_DataType>::process(const AudioBuffer &audioBuffer, unsigned int channel, _DataType *output, size_t outputSize, size_t &width, size_t &height)
{
	switch(audioBuffer.getFormat())
	{
	case AudioFormat::UInt8:
	case AudioFormat::UInt8P:
		return process(audioBuffer.getBuffer(channel), audioBuffer.getSamples(), audioBuffer.getFormat(), output, outputSize, width, height);
		break;
	case AudioFormat::Int16:
	case AudioFormat::Int16P:
		return process((int16_t *)audioBuffer.getBuffer(channel), audioBuffer.getSamples(), audioBuffer.getFormat(), output, outputSize, width, height);
		break;
	case AudioFormat::Int32:
	case AudioFormat::Int32P:
		return process((int32_t *)audioBuffer.getBuffer(channel), audioBuffer.getSamples(), audioBuffer.getFormat(), output, outputSize, width, height);
		break;
	case AudioFormat::Float:
	case AudioFormat::FloatP:
		return process((float *)audioBuffer.getBuffer(channel), audioBuffer.getSamples(), audioBuffer.getFormat(), output, outputSize, width, height);
		break;
	case AudioFormat::Double:
	case AudioFormat::DoubleP:
		return process((double *)audioBuffer.getBuffer(channel), audioBuffer.getSamples(), audioBuffer.getFormat(), output, outputSize, width, height);
		break;
	}
	return false;
}

template<typename _DataType>
template<typename _BufferType>
bool SpectrogramGenerator<_DataType>::process(_BufferType *audioBuffer, size_t audioSamples, AudioFormat format, _DataType *output, size_t outputSize, size_t &width, size_t &height)
{
	width=0;
	height=0;

	if(audioSamples<m_windowSize)
		return false;

	size_t step=m_windowSize-m_overlap;
	size_t sampleBins=floor((float)(audioSamples-m_windowSize)/step);// +1;
	size_t frequencies=(m_windowSize/2)+1;
	size_t requiredOutputSize=sampleBins*frequencies*sizeof(_DataType);

	if(outputSize<requiredOutputSize)
		return false;

	_BufferType *data=audioBuffer;
	HiddenFftw<_DataType>::ComplexType *complexOut=m_hiddenFftw.m_outBuffer;
//	size_t stride=sampleBins*sizeof(_BufferType);

	if(m_logarithmic)
	{
		for(size_t i=0; i<sampleBins; ++i)
		{
			convert(data, m_windowSize, m_inBuffer, m_inBufferSize);

//			fftwf_execute_dft_r2c(m_hiddenFftw.m_plan, m_inBuffer, m_hiddenFftw.m_outBuffer);
			m_hiddenFftw.execute(m_hiddenFftw.m_plan, m_inBuffer, m_hiddenFftw.m_outBuffer);

			for(size_t j=0; j<frequencies; ++j)
			{
				//normaly db is 20*log10(sample), but since log(X^2) == 1/2*log(X), we skip the sqrt and just divide the 20 by 2
				output[j*sampleBins+i]=10*std::log10(m_hiddenFftw.m_outBuffer[j][0]*m_hiddenFftw.m_outBuffer[j][0]+m_hiddenFftw.m_outBuffer[j][1]*m_hiddenFftw.m_outBuffer[j][1]);
			}
			data+=sampleBins;
		}
	}
	else
	{
		for(size_t i=0; i<sampleBins; ++i)
		{
			convert(data, m_windowSize, m_inBuffer, m_inBufferSize);

//			fftwf_execute_dft_r2c(m_hiddenFftw.m_plan, m_inBuffer, m_hiddenFftw.m_outBuffer);
			m_hiddenFftw.execute(m_hiddenFftw.m_plan, m_inBuffer, m_hiddenFftw.m_outBuffer);

			for(size_t j=0; j<frequencies; ++j)
			{
				output[j*sampleBins+i]=sqrt(m_hiddenFftw.m_outBuffer[j][0]*m_hiddenFftw.m_outBuffer[j][0]+m_hiddenFftw.m_outBuffer[j][1]*m_hiddenFftw.m_outBuffer[j][1]);
			}
			data+=sampleBins;
		}
	}

	width=sampleBins;
	height=frequencies;

	return true;
}

//template SpectrogramGenerator<uint8_t>;
//template SpectrogramGenerator<int16_t>;
//template SpectrogramGenerator<int32_t>;
template SpectrogramGenerator<float>;
template SpectrogramGenerator<double>;

}//namespace medialib

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.hint;

import com.intellij.lang.parameterInfo.CreateParameterInfoContext;
import com.intellij.lang.parameterInfo.ParameterInfoHandler;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorActivityManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author peter
*/
public class ShowParameterInfoContext implements CreateParameterInfoContext {
  private final Editor myEditor;
  private final PsiFile myFile;
  private final Project myProject;
  private final int myOffset;
  private final int myParameterListStart;
  private final boolean mySingleParameterInfo;
  private PsiElement myHighlightedElement;
  private Object[] myItems;
  private boolean myRequestFocus;

  public ShowParameterInfoContext(final Editor editor, final Project project,
                                  final PsiFile file, int offset, int parameterListStart) {
    this(editor, project, file, offset, parameterListStart, false);
  }

  public ShowParameterInfoContext(final Editor editor, final Project project,
                                  final PsiFile file, int offset, int parameterListStart,
                                  boolean requestFocus) {
    this(editor, project, file, offset, parameterListStart, requestFocus, false);
  }

  public ShowParameterInfoContext(final Editor editor, final Project project,
                                  final PsiFile file, int offset, int parameterListStart,
                                  boolean requestFocus, boolean singleParameterInfo) {
    myEditor = editor;
    myProject = project;
    myFile = file;
    myParameterListStart = parameterListStart;
    myOffset = offset;
    myRequestFocus = requestFocus;
    mySingleParameterInfo = singleParameterInfo;
  }

  @Override
  public Project getProject() {
    return myProject;
  }

  @Override
  public PsiFile getFile() {
    return myFile;
  }

  @Override
  public int getOffset() {
    return myOffset;
  }

  @Override
  public int getParameterListStart() {
    return myParameterListStart;
  }

  @Override
  @NotNull
  public Editor getEditor() {
    return myEditor;
  }

  @Override
  public PsiElement getHighlightedElement() {
    return myHighlightedElement;
  }

  @Override
  public void setHighlightedElement(PsiElement element) {
    myHighlightedElement = element;
  }

  @Override
  public void setItemsToShow(Object[] items) {
    myItems = items;
  }

  @Override
  public Object[] getItemsToShow() {
    return myItems;
  }

  @Override
  public void showHint(PsiElement element, int offset, ParameterInfoHandler handler) {
    final Object[] itemsToShow = getItemsToShow();
    if (itemsToShow == null || itemsToShow.length == 0) return;
    showParameterHint(element, getEditor(), itemsToShow, getProject(), itemsToShow.length > 1 ? getHighlightedElement() : null, offset,
                      handler, myRequestFocus, mySingleParameterInfo);
  }

  private static void showParameterHint(final PsiElement element,
                                        final Editor editor,
                                        final Object[] descriptors,
                                        final Project project,
                                        @Nullable PsiElement highlighted,
                                        final int elementStart,
                                        final ParameterInfoHandler<?, ?> handler,
                                        final boolean requestFocus,
                                        boolean singleParameterInfo) {
    if (editor.isDisposed() || !editor.getComponent().isVisible()) return;

    PsiDocumentManager.getInstance(project).performLaterWhenAllCommitted(() -> {
      if (editor.isDisposed() || !element.isValid() ||
          (!ApplicationManager.getApplication().isUnitTestMode() &&
           !EditorActivityManager.getInstance().isVisible(editor))) return;

      final Document document = editor.getDocument();
      if (document.getTextLength() < elementStart) return;

      ParameterInfoControllerBase controller = ParameterInfoControllerBase.findControllerAtOffset(editor, elementStart);
      if (controller == null) {
        ParameterInfoControllerBase.createParameterInfoController(
          project, editor, elementStart, descriptors, highlighted, element, handler, true, requestFocus);
      }
      else {
        controller.setDescriptors(descriptors);
        controller.showHint(requestFocus, singleParameterInfo);
      }
    });
  }

  public void setRequestFocus(boolean requestFocus) {
    myRequestFocus = requestFocus;
  }

  public boolean isRequestFocus() {
    return myRequestFocus;
  }
}


text:
Especially if you don't want to use a TTL cable OR you don't know your given IP address.

* First: git clone https://github.com/jaketarnow/SudoShell/
* Edit file to given MAC Address and username

* Perform below code in terminal

```chmod +x ssh_script.sh && ./ssh_script.sh```

* User will get prompt to provide password

Enjoy!


text:
/* eslint no-unused-vars: off */
/* global jasmine, beforeEach, describe, it, expect, module, inject */

(function () {

    'use strict';

    var helpers = window._helpers;

    helpers.testModuleDependencies('profile');

}());


text:
<?php
/**
 * Clean print recipe template.
 *
 * @link       http://bootstrapped.ventures
 * @since      1.0.0
 *
 * @package    WP_Recipe_Maker
 * @subpackage WP_Recipe_Maker/templates/recipe/clean-print-with-image
 */

// @codingStandardsIgnoreStart
?>

<?php include( WPRM_DIR . 'assets/icons/printer.svg' ); ?> <?php echo WPRM_Template_Helper::label( 'print_button' ); ?>

<?php echo WPRM_Template_Helper::recipe_image( $recipe, 'thumbnail' ); ?>

<?php echo $recipe->name(); ?>

		<?php echo $recipe->summary(); ?>

		<?php
		$taxonomies = WPRM_Taxonomies::get_taxonomies();

		foreach ( $taxonomies as $taxonomy => $options ) :
			$key = substr( $taxonomy, 5 );
			$terms = $recipe->tags( $key );

			if ( count( $terms ) > 0 ) : ?>
			<div class="wprm-recipe-<?php echo $key; ?>-container">
				<span class="wprm-recipe-details-name wprm-recipe-<?php echo $key; ?>-name"><?php echo WPRM_Template_Helper::label( $key . '_tags', $options['singular_name'] ); ?>
				<span class="wprm-recipe-<?php echo $key; ?>"<?php echo WPRM_Template_Helper::tags_meta( $key ); ?>>
					<?php foreach ( $terms as $index => $term ) {
						if ( 0 !== $index ) {
							echo ', ';
						}
						echo $term->name;
					} ?>

		<?php endif; // Count.
		endforeach; // Taxonomies. ?>

		<?php if ( $recipe->prep_time() ) : ?>

			<?php echo WPRM_Template_Helper::label( 'prep_time' ); ?> <?php echo $recipe->prep_time_formatted(); ?>

		<?php endif; // Prep time. ?>
		<?php if ( $recipe->cook_time() ) : ?>

			<?php echo WPRM_Template_Helper::label( 'cook_time' ); ?> <?php echo $recipe->cook_time_formatted(); ?>

		<?php endif; // Cook time. ?>
		<?php if ( $recipe->total_time() ) : ?>

			<?php echo WPRM_Template_Helper::label( 'total_time' ); ?> <?php echo $recipe->total_time_formatted(); ?>

		<?php endif; // Total time. ?>

		<?php if ( $recipe->servings() ) : ?>

			<?php echo WPRM_Template_Helper::label( 'servings' ); ?> <?php echo $recipe->servings(); ?> <?php echo $recipe->servings_unit(); ?>

		<?php endif; // Servings. ?>
		<?php if ( $recipe->calories() ) : ?>

			<?php echo WPRM_Template_Helper::label( 'calories' ); ?> <?php echo $recipe->calories(); ?> <?php _e( 'kcal', 'wp-recipe-maker' ); ?>

		<?php endif; // Calories. ?>
		<?php if ( $recipe->author() ) : ?>

			<?php echo WPRM_Template_Helper::label( 'author' ); ?> <?php echo $recipe->author(); ?>

		<?php endif; // Author. ?>

	<?php
	$ingredients = $recipe->ingredients();
	if ( count( $ingredients ) > 0 ) : ?>

<?php echo WPRM_Template_Helper::label( 'ingredients' ); ?>

		<?php foreach ( $ingredients as $ingredient_group ) : ?>

			<?php if ( $ingredient_group['name'] ) : ?>

<?php echo $ingredient_group['name']; ?>

			<?php endif; // Ingredient group name. ?>

				<?php foreach ( $ingredient_group['ingredients'] as $ingredient ) : ?>

					<?php if ( $ingredient['amount'] ) : ?>
					<?php echo $ingredient['amount']; ?>
					<?php endif; // Ingredient amount. ?>
					<?php if ( $ingredient['unit'] ) : ?>
					<?php echo $ingredient['unit']; ?>
					<?php endif; // Ingredient unit. ?>
					<?php echo WPRM_Template_Helper::ingredient_name( $ingredient, false ); ?>
					<?php if ( $ingredient['notes'] ) : ?>
					<?php echo $ingredient['notes']; ?>
					<?php endif; // Ingredient notes. ?>

				<?php endforeach; // Ingredients. ?>

	 <?php endforeach; // Ingredient groups. ?>

	<?php echo WPRM_Template_Helper::unit_conversion( $recipe ); ?>
	<?php endif; // Ingredients. ?>
	<?php
	$instructions = $recipe->instructions();
	if ( count( $instructions ) > 0 ) : ?>

<?php echo WPRM_Template_Helper::label( 'instructions' ); ?>

		<?php foreach ( $instructions as $instruction_group ) : ?>

			<?php if ( $instruction_group['name'] ) : ?>

<?php echo $instruction_group['name']; ?>

			<?php endif; // Instruction group name. ?>

				<?php foreach ( $instruction_group['instructions'] as $instruction ) : ?>

					<?php if ( $instruction['text'] ) : ?>

<?php echo $instruction['text']; ?>

					<?php endif; // Instruction text. ?>

				<?php endforeach; // Instructions. ?>

		<?php endforeach; // Instruction groups. ?>

	<?php endif; // Instructions. ?>
	<?php if ( $recipe->notes() ) : ?>

<?php echo WPRM_Template_Helper::label( 'notes' ); ?>

		<?php echo $recipe->notes(); ?>

	<?php endif; // Notes ?>
	<?php echo WPRM_Template_Helper::nutrition_label( $recipe->id() ); ?>


text:
import play.api.libs.ws.ning._
import play.api.libs.json._
import play.api.libs.ws._
import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits.global
import play.api.Logger

package object weirdCombinators {

  implicit val client = NingWSClient()
  private var methodString = "GET"

  def liftez(x:String):Option[WSRequest] = {
    val matcher = """^http(s){0,1}://.+""".r
    x match {
      case matcher(_*) => Option(WS.clientUrl(x))
      case _ => None
    }}

  implicit class combinators(x:Option[WSRequest]){

    def <*> (y:(String,String)) :Option[WSRequest] = x map {req => req.withHeaders(y)}

    // the option is probably useless , needs checking for appropriate method
    def <||> (y:String):Option[WSRequest] = {
      methodString = y
      return x
    }

    def <**>():WSResponse = {
     return (Await.result(_:Future[WSResponse], 10.seconds))(
       x map {_.execute(methodString)} get
     )
   }
  }

  implicit class executeAndRipOutStatus(x:Option[WSRequest]){
    def </~\>(y:String):Any = {
      // damn this thing is ugly
      val result =  x <**>

      return {y match {
        case "status" => result.status
        case "statusText" => result.statusText
        case _ => "method not defined"
      }}

    }
  }

 def QUIT = client.close
}


text:
using Fang3D.Editor.Controles;
namespace Fang3D.Editor
{
    partial class FormPrincipal
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.menuStrip1 = new System.Windows.Forms.MenuStrip();
            this.archivosToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.nuevaToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
            this.cargarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
            this.salvarToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.vistaToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.dibujarGrillaToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.crearToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.predefinidosToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.cuboToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.luzToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.fuenteParticulasToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.entitysToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.componentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.scriptsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.ayudaToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.acercaDeFang3DToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
            this.tabControl = new System.Windows.Forms.TabControl();
            this.tabPageEdit = new System.Windows.Forms.TabPage();
            this.tabPagePlay = new System.Windows.Forms.TabPage();
            this.toolStrip1 = new System.Windows.Forms.ToolStrip();
            this.toolStripButtonPlay = new System.Windows.Forms.ToolStripButton();
            this.toolStripButtonPause = new System.Windows.Forms.ToolStripButton();
            this.toolStripButtonStop = new System.Windows.Forms.ToolStripButton();
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.tableLayoutPanelBotones = new System.Windows.Forms.TableLayoutPanel();
            this.arbolEntidadesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.propiedadesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.menuStrip1.SuspendLayout();
            this.tabControl.SuspendLayout();
            this.toolStrip1.SuspendLayout();
            this.statusStrip1.SuspendLayout();
            this.tableLayoutPanelBotones.SuspendLayout();
            this.SuspendLayout();
            //
            // menuStrip1
            //
            this.menuStrip1.BackColor = System.Drawing.SystemColors.Control;
            this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.archivosToolStripMenuItem,
            this.vistaToolStripMenuItem,
            this.crearToolStripMenuItem,
            this.ayudaToolStripMenuItem});
            this.menuStrip1.Location = new System.Drawing.Point(0, 0);
            this.menuStrip1.Name = "menuStrip1";
            this.menuStrip1.Size = new System.Drawing.Size(441, 24);
            this.menuStrip1.TabIndex = 3;
            this.menuStrip1.Text = "menuStrip1";
            this.menuStrip1.MenuActivate += new System.EventHandler(this.menuStrip1_MenuActivate);
            //
            // archivosToolStripMenuItem
            //
            this.archivosToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.nuevaToolStripMenuItem,
            this.toolStripMenuItem1,
            this.cargarToolStripMenuItem,
            this.toolStripMenuItem2,
            this.salvarToolStripMenuItem});
            this.archivosToolStripMenuItem.Name = "archivosToolStripMenuItem";
            this.archivosToolStripMenuItem.Size = new System.Drawing.Size(53, 20);
            this.archivosToolStripMenuItem.Text = "Escena";
            //
            // nuevaToolStripMenuItem
            //
            this.nuevaToolStripMenuItem.Name = "nuevaToolStripMenuItem";
            this.nuevaToolStripMenuItem.Size = new System.Drawing.Size(118, 22);
            this.nuevaToolStripMenuItem.Text = "Nueva";
            this.nuevaToolStripMenuItem.Click += new System.EventHandler(this.nuevaToolStripMenuItem_Click);
            //
            // toolStripMenuItem1
            //
            this.toolStripMenuItem1.Name = "toolStripMenuItem1";
            this.toolStripMenuItem1.Size = new System.Drawing.Size(115, 6);
            //
            // cargarToolStripMenuItem
            //
            this.cargarToolStripMenuItem.Name = "cargarToolStripMenuItem";
            this.cargarToolStripMenuItem.Size = new System.Drawing.Size(118, 22);
            this.cargarToolStripMenuItem.Text = "Cargar";
            this.cargarToolStripMenuItem.Click += new System.EventHandler(this.cargarToolStripMenuItem_Click);
            //
            // toolStripMenuItem2
            //
            this.toolStripMenuItem2.Name = "toolStripMenuItem2";
            this.toolStripMenuItem2.Size = new System.Drawing.Size(115, 6);
            //
            // salvarToolStripMenuItem
            //
            this.salvarToolStripMenuItem.Name = "salvarToolStripMenuItem";
            this.salvarToolStripMenuItem.Size = new System.Drawing.Size(118, 22);
            this.salvarToolStripMenuItem.Text = "Salvar";
            this.salvarToolStripMenuItem.Click += new System.EventHandler(this.salvarToolStripMenuItem_Click);
            //
            // vistaToolStripMenuItem
            //
            this.vistaToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.dibujarGrillaToolStripMenuItem,
            this.arbolEntidadesToolStripMenuItem,
            this.propiedadesToolStripMenuItem});
            this.vistaToolStripMenuItem.Name = "vistaToolStripMenuItem";
            this.vistaToolStripMenuItem.Size = new System.Drawing.Size(42, 20);
            this.vistaToolStripMenuItem.Text = "Vista";
            //
            // dibujarGrillaToolStripMenuItem
            //
            this.dibujarGrillaToolStripMenuItem.Name = "dibujarGrillaToolStripMenuItem";
            this.dibujarGrillaToolStripMenuItem.Size = new System.Drawing.Size(160, 22);
            this.dibujarGrillaToolStripMenuItem.Text = "Dibujar Grilla";
            this.dibujarGrillaToolStripMenuItem.Click += new System.EventHandler(this.dibujarGrillaToolStripMenuItem_Click);
            //
            // crearToolStripMenuItem
            //
            this.crearToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.predefinidosToolStripMenuItem,
            this.entitysToolStripMenuItem,
            this.componentsToolStripMenuItem,
            this.scriptsToolStripMenuItem});
            this.crearToolStripMenuItem.Name = "crearToolStripMenuItem";
            this.crearToolStripMenuItem.Size = new System.Drawing.Size(46, 20);
            this.crearToolStripMenuItem.Text = "Crear";
            //
            // predefinidosToolStripMenuItem
            //
            this.predefinidosToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.cuboToolStripMenuItem,
            this.luzToolStripMenuItem,
            this.fuenteParticulasToolStripMenuItem});
            this.predefinidosToolStripMenuItem.Name = "predefinidosToolStripMenuItem";
            this.predefinidosToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
            this.predefinidosToolStripMenuItem.Text = "Predefinidos";
            //
            // cuboToolStripMenuItem
            //
            this.cuboToolStripMenuItem.Name = "cuboToolStripMenuItem";
            this.cuboToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
            this.cuboToolStripMenuItem.Text = "Cubo";
            this.cuboToolStripMenuItem.Click += new System.EventHandler(this.cuboToolStripMenuItem_Click);
            //
            // luzToolStripMenuItem
            //
            this.luzToolStripMenuItem.Name = "luzToolStripMenuItem";
            this.luzToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
            this.luzToolStripMenuItem.Text = "Luz";
            this.luzToolStripMenuItem.Click += new System.EventHandler(this.luzToolStripMenuItem_Click);
            //
            // fuenteParticulasToolStripMenuItem
            //
            this.fuenteParticulasToolStripMenuItem.Name = "fuenteParticulasToolStripMenuItem";
            this.fuenteParticulasToolStripMenuItem.Size = new System.Drawing.Size(168, 22);
            this.fuenteParticulasToolStripMenuItem.Text = "Fuente Particulas";
            this.fuenteParticulasToolStripMenuItem.Click += new System.EventHandler(this.fuenteParticulasToolStripMenuItem_Click);
            //
            // entitysToolStripMenuItem
            //
            this.entitysToolStripMenuItem.Name = "entitysToolStripMenuItem";
            this.entitysToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
            this.entitysToolStripMenuItem.Text = "Entitys";
            //
            // componentsToolStripMenuItem
            //
            this.componentsToolStripMenuItem.Name = "componentsToolStripMenuItem";
            this.componentsToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
            this.componentsToolStripMenuItem.Text = "Components";
            //
            // scriptsToolStripMenuItem
            //
            this.scriptsToolStripMenuItem.Name = "scriptsToolStripMenuItem";
            this.scriptsToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
            this.scriptsToolStripMenuItem.Text = "Scripts";
            //
            // ayudaToolStripMenuItem
            //
            this.ayudaToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.acercaDeFang3DToolStripMenuItem});
            this.ayudaToolStripMenuItem.Name = "ayudaToolStripMenuItem";
            this.ayudaToolStripMenuItem.Size = new System.Drawing.Size(50, 20);
            this.ayudaToolStripMenuItem.Text = "Ayuda";
            //
            // acercaDeFang3DToolStripMenuItem
            //
            this.acercaDeFang3DToolStripMenuItem.Name = "acercaDeFang3DToolStripMenuItem";
            this.acercaDeFang3DToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
            this.acercaDeFang3DToolStripMenuItem.Text = "Acerca de Fang 3D!";
            this.acercaDeFang3DToolStripMenuItem.Click += new System.EventHandler(this.acercaDeFang3DToolStripMenuItem_Click);
            //
            // openFileDialog1
            //
            this.openFileDialog1.DefaultExt = "f3d";
            this.openFileDialog1.Filter = "Scene Files|*.f3d";
            this.openFileDialog1.Title = "Load Scene";
            //
            // saveFileDialog1
            //
            this.saveFileDialog1.DefaultExt = "f3d";
            this.saveFileDialog1.FileName = "new.f3d";
            this.saveFileDialog1.Filter = "Scene Files|*.f3d";
            this.saveFileDialog1.Title = "Save Scene";
            //
            // tabControl
            //
            this.tabControl.Appearance = System.Windows.Forms.TabAppearance.FlatButtons;
            this.tabControl.Controls.Add(this.tabPageEdit);
            this.tabControl.Controls.Add(this.tabPagePlay);
            this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tabControl.Location = new System.Drawing.Point(0, 39);
            this.tabControl.Margin = new System.Windows.Forms.Padding(0);
            this.tabControl.Name = "tabControl";
            this.tabControl.SelectedIndex = 0;
            this.tabControl.Size = new System.Drawing.Size(992, 605);
            this.tabControl.TabIndex = 4;
            this.tabControl.Selected += new System.Windows.Forms.TabControlEventHandler(this.tabControl_Selected);
            //
            // tabPageEdit
            //
            this.tabPageEdit.Location = new System.Drawing.Point(4, 25);
            this.tabPageEdit.Margin = new System.Windows.Forms.Padding(0);
            this.tabPageEdit.Name = "tabPageEdit";
            this.tabPageEdit.Size = new System.Drawing.Size(984, 576);
            this.tabPageEdit.TabIndex = 0;
            this.tabPageEdit.Text = "Edición";
            this.tabPageEdit.UseVisualStyleBackColor = true;
            //
            // tabPagePlay
            //
            this.tabPagePlay.Location = new System.Drawing.Point(4, 25);
            this.tabPagePlay.Margin = new System.Windows.Forms.Padding(0);
            this.tabPagePlay.Name = "tabPagePlay";
            this.tabPagePlay.Size = new System.Drawing.Size(984, 576);
            this.tabPagePlay.TabIndex = 1;
            this.tabPagePlay.Text = "Ejecución";
            this.tabPagePlay.UseVisualStyleBackColor = true;
            //
            // toolStrip1
            //
            this.toolStrip1.BackColor = System.Drawing.SystemColors.Control;
            this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None;
            this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
            this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripButtonPlay,
            this.toolStripButtonPause,
            this.toolStripButtonStop});
            this.toolStrip1.Location = new System.Drawing.Point(441, 0);
            this.toolStrip1.Name = "toolStrip1";
            this.toolStrip1.Padding = new System.Windows.Forms.Padding(0);
            this.toolStrip1.Size = new System.Drawing.Size(110, 39);
            this.toolStrip1.TabIndex = 5;
            this.toolStrip1.Text = "toolStrip1";
            //
            // toolStripButtonPlay
            //
            this.toolStripButtonPlay.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.toolStripButtonPlay.Image = global::Fang3D.Editor.Properties.Resources.BotonPlay;
            this.toolStripButtonPlay.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
            this.toolStripButtonPlay.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.toolStripButtonPlay.Name = "toolStripButtonPlay";
            this.toolStripButtonPlay.Size = new System.Drawing.Size(36, 36);
            this.toolStripButtonPlay.Text = "Play";
            this.toolStripButtonPlay.Click += new System.EventHandler(this.toolStripButtonPlay_Click);
            //
            // toolStripButtonPause
            //
            this.toolStripButtonPause.CheckOnClick = true;
            this.toolStripButtonPause.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.toolStripButtonPause.Image = global::Fang3D.Editor.Properties.Resources.BotonPause;
            this.toolStripButtonPause.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
            this.toolStripButtonPause.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.toolStripButtonPause.Name = "toolStripButtonPause";
            this.toolStripButtonPause.Size = new System.Drawing.Size(36, 36);
            this.toolStripButtonPause.Text = "Pause";
            this.toolStripButtonPause.Click += new System.EventHandler(this.toolStripButtonPause_Click);
            //
            // toolStripButtonStop
            //
            this.toolStripButtonStop.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.toolStripButtonStop.Image = global::Fang3D.Editor.Properties.Resources.BotonStop;
            this.toolStripButtonStop.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
            this.toolStripButtonStop.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.toolStripButtonStop.Name = "toolStripButtonStop";
            this.toolStripButtonStop.Size = new System.Drawing.Size(36, 36);
            this.toolStripButtonStop.Text = "Stop";
            this.toolStripButtonStop.Click += new System.EventHandler(this.toolStripButtonStop_Click);
            //
            // statusStrip1
            //
            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripStatusLabel1});
            this.statusStrip1.Location = new System.Drawing.Point(0, 644);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.Size = new System.Drawing.Size(992, 22);
            this.statusStrip1.TabIndex = 6;
            this.statusStrip1.Text = "statusStrip1";
            //
            // toolStripStatusLabel1
            //
            this.toolStripStatusLabel1.DoubleClickEnabled = true;
            this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
            this.toolStripStatusLabel1.Size = new System.Drawing.Size(977, 17);
            this.toolStripStatusLabel1.Spring = true;
            this.toolStripStatusLabel1.Text = "toolStripStatusLabel1";
            this.toolStripStatusLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.toolStripStatusLabel1.DoubleClick += new System.EventHandler(this.toolStripStatusLabel1_DoubleClick);
            //
            // timer1
            //
            this.timer1.Enabled = true;
            this.timer1.Interval = 500;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            //
            // tableLayoutPanelBotones
            //
            this.tableLayoutPanelBotones.AutoSize = true;
            this.tableLayoutPanelBotones.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.tableLayoutPanelBotones.ColumnCount = 3;
            this.tableLayoutPanelBotones.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.07474F));
            this.tableLayoutPanelBotones.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            this.tableLayoutPanelBotones.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 49.92526F));
            this.tableLayoutPanelBotones.Controls.Add(this.toolStrip1, 1, 0);
            this.tableLayoutPanelBotones.Controls.Add(this.menuStrip1, 0, 0);
            this.tableLayoutPanelBotones.Dock = System.Windows.Forms.DockStyle.Top;
            this.tableLayoutPanelBotones.Location = new System.Drawing.Point(0, 0);
            this.tableLayoutPanelBotones.Margin = new System.Windows.Forms.Padding(0);
            this.tableLayoutPanelBotones.Name = "tableLayoutPanelBotones";
            this.tableLayoutPanelBotones.RowCount = 1;
            this.tableLayoutPanelBotones.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanelBotones.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 39F));
            this.tableLayoutPanelBotones.Size = new System.Drawing.Size(992, 39);
            this.tableLayoutPanelBotones.TabIndex = 0;
            //
            // arbolEntidadesToolStripMenuItem
            //
            this.arbolEntidadesToolStripMenuItem.Name = "arbolEntidadesToolStripMenuItem";
            this.arbolEntidadesToolStripMenuItem.Size = new System.Drawing.Size(160, 22);
            this.arbolEntidadesToolStripMenuItem.Text = "Arbol Entidades";
            this.arbolEntidadesToolStripMenuItem.Click += new System.EventHandler(this.arbolEntidadesToolStripMenuItem_Click);
            //
            // propiedadesToolStripMenuItem
            //
            this.propiedadesToolStripMenuItem.Name = "propiedadesToolStripMenuItem";
            this.propiedadesToolStripMenuItem.Size = new System.Drawing.Size(160, 22);
            this.propiedadesToolStripMenuItem.Text = "Propiedades";
            this.propiedadesToolStripMenuItem.Click += new System.EventHandler(this.propiedadesToolStripMenuItem_Click);
            //
            // FormPrincipal
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(992, 666);
            this.Controls.Add(this.tabControl);
            this.Controls.Add(this.statusStrip1);
            this.Controls.Add(this.tableLayoutPanelBotones);
            this.MainMenuStrip = this.menuStrip1;
            this.Name = "FormPrincipal";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Fang 3D !";
            this.Load += new System.EventHandler(this.FormPrincipal_Load);
            this.menuStrip1.ResumeLayout(false);
            this.menuStrip1.PerformLayout();
            this.tabControl.ResumeLayout(false);
            this.toolStrip1.ResumeLayout(false);
            this.toolStrip1.PerformLayout();
            this.statusStrip1.ResumeLayout(false);
            this.statusStrip1.PerformLayout();
            this.tableLayoutPanelBotones.ResumeLayout(false);
            this.tableLayoutPanelBotones.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.MenuStrip menuStrip1;
        private System.Windows.Forms.ToolStripMenuItem crearToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem ayudaToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem acercaDeFang3DToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem archivosToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem salvarToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem cargarToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem nuevaToolStripMenuItem;
        private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
        private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
        private System.Windows.Forms.OpenFileDialog openFileDialog1;
        private System.Windows.Forms.SaveFileDialog saveFileDialog1;
        private System.Windows.Forms.TabControl tabControl;
        private System.Windows.Forms.TabPage tabPageEdit;
        private System.Windows.Forms.TabPage tabPagePlay;
        private System.Windows.Forms.ToolStrip toolStrip1;
        private System.Windows.Forms.ToolStripButton toolStripButtonPlay;
        private System.Windows.Forms.ToolStripButton toolStripButtonPause;
        private System.Windows.Forms.ToolStripButton toolStripButtonStop;
        private System.Windows.Forms.ToolStripMenuItem entitysToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem componentsToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem predefinidosToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem cuboToolStripMenuItem;
        private System.Windows.Forms.StatusStrip statusStrip1;
        private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.ToolStripMenuItem luzToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem fuenteParticulasToolStripMenuItem;
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanelBotones;
        private System.Windows.Forms.ToolStripMenuItem vistaToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem dibujarGrillaToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem scriptsToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem arbolEntidadesToolStripMenuItem;
        private System.Windows.Forms.ToolStripMenuItem propiedadesToolStripMenuItem;
    }
}


text:
var path           = require('path');

// npm modules
var nodemailer     = require('nodemailer'),
    smtpTransport  = require('nodemailer-smtp-transport');

// local modules
var config         = require('./config');

module.exports = var Mail = function(smtp, from) {
    this.transporter = nodemailer.createTransport(smtpTransport(smtp || config.mail.smtp));
    this.from = from || config.mail.from;
};

Mail.prototype.mail = function(mail, callback) {

    var mailOptions = {
        from: this.from,
        to: mail.to,
        subject: mail.subject,
        html: mail.content
    }

    if (mail.attachments) {
        mailOptions.attachments = mail.attachments;
    }

    this.transporter.sendMail(mailOptions, function(error, info) {
        return callback(error, info);
    });
}


text:
package com.xplus.commons.pattern.behavioral.visitor.demo;

/**
 * http://www.runoob.com/design-pattern/visitor-pattern.html
 */
public class VisitorPatternDemo {

	public static void main(String[] args) {
		ComputerPart computer = new Computer();
		computer.accept(new ComputerPartDisplayVisitor());
	}

}


text:
[ ![Build Status](https://api.travis-ci.org/flozz/stone.js.svg?branch=master) ](https://travis-ci.org/flozz/stone.js)
[ ![NPM Version](http://img.shields.io/npm/v/stonejs.svg?style=flat) ](https://www.npmjs.com/package/stonejs)
[ ![License](http://img.shields.io/npm/l/stonejs.svg?style=flat) ](https://www.npmjs.com/package/stonejs)

Stone.js is a client-side gettext-like Javascript internationalization library that provides many useful functionalities like:

* immediate translation (gettext)

* differed translation using lazy strings (lazyGettext)

* Javascript **and** HTML internationalization

* replacement support inside translated strings

* plural forms support (ngettext/lazyNgettext)

* tools to extract/update/build translatable strings (see [stonejs-tools][])

## Getting Started

### Getting Stone.js

#### Standalone Version

First download [Stone.js zip][dl-zip] or clone the repository.

Then include the `stonejs.js` or `stonejs.min.js` (from the `dist` folder) in you HTML page, and create an alias for the `Stone.gettext` function:

```html
<script src="dist/stonejs.js"></script>
<script>
    window._ = Stone.gettext;
</script>
```

#### NPM and Browserify

First install the `stonejs` package:

    npm install --save stonejs

Then include it where you need it, and create an alias for the `Stone.gettext` function:

```javascript
// using CommonJS modules

var Stone = require("stonejs");
var _ = Stone.gettext;

// using ES6 modules
import Stone, { gettext as _ } from "stonejs";
```

### Internationalize Your Application

#### Internationalize Javascript

To internationalize your Javascript files, you just have to "mark" all translatable strings of your application by passing them to the `gettext` function.

**Example:**

```javascript
// ---- Replace ----

var text = "Hello World";

// --- by ----

var text = _("Hello World");

// NOTE: you can also write Stone.gettext("Hello World")
// if you do not want to create the "_" alias for the gettext function
```

#### Internationalize HTML

To internationalize your HTML files, you just have to add the `stonejs` attribute to all translatable tags.

**Example:**

```html
<!-- replace -->

<div>Hello World</div>

<!-- by -->

<div stonejs>Hello World</div>
```

**NOTE:** To allow Stone.js to translate your DOM, you have to enable DOM scan:

```javascript
Stone.enableDomScan(true);
```

#### Extract/Translate/Build Translatable Strings

Once you have internationalized your application, you will have to:

* Extract the translatable strings from your js and html files,

* Translate the extracted strings,

* Build your translation inside string catalogs.

For all those steps, you can use the Stone.js tools available here:

* https://github.com/flozz/stonejs-tools

#### Load Catalogs / Enable Translation of your application

The last step to display your application into plenty of languages is to load the catalogs you built with [stonejs-tools][] and set the current locale.

**NOTE:** Stone.js Tools can build the catalogs in two formats: `js` and `json`. Be careful if you use the javascript one. You should include the catalog file **after** the stonejs lib is loaded (you should include it after in your HTML file if you are using the standalone version of the lib, and if you use the npm/browserify version, you should include the file **after** the first time you `require` the library).

**Example:**

```html
<script src="dist/stonejs.js"></script>
<script>
    var catalogs = {
        "fr": {
            "plural-forms": "nplurals=2; plural=(n > 1);",
            "messages": {
                "Hello World": ["Bonjour le monde"],
                "Hello {name}": ["Bonjour {name}"]
            }
        },
        "it": {
            "plural-forms": "nplurals=2; plural=(n != 1);",
            "messages": {
                "Hello World": ["Buongiorno il mondo"],
                "Hello {name}": ["Buongiorno {name}"]
            }
        }
    };

    window._ = Stone.gettext;       // Alias the Stone.gettext function
    Stone.addCatalogs(catalogs);    // Add catalogs (here it is hard coded for the need of the example
    Stone.enableDomScan(true);      // Allow Stone.js to scan the DOM to find translatable nodes
    Stone.setLocale("fr");          // Sets the locale to french

    console.log(_("Hello World"));
    // Bonjour le monde

    console.log(_("Hello World", "it"));
    // Buongiorno il mondo

    console.log(_("Hello {name}", {name: "John"}));
    // Bonjour John

    console.log(_("Hello {name}", {name: "John"}, "it"));
    // Buongiorno John

    var text = Stone.lazyGettext("Hello World");

    console.log(text.toString());
    // Bonjour le monde

    Stone.setLocale("it");
    console.log(text.toString());
    // Buongiorno il mondo

    Stone.setLocale("c");
    console.log(text.toString());
    // Hello World

    Stone.setLocale("foo");
    console.log(text.toString());
    // Hello World

</script>
```

## API

### Stone.gettext

Translates the given string to the current language.

    String: Stone.gettext( <string> [, locale] );
    String: Stone.gettext( <string> [, replacements] [, locale] );

**params:**

* `string`: The string to translate.
* `locale`: The locale string to use for translation (optional, default: current locale).
* `replacements`: an object containing replacements for the string (optional, see example below).

**returns:**

The translated string.

**Examples:**

```javascript
var text1 = Stone.gettext("Hello World");
var text1 = Stone.gettext("Hello World", "it");
var text2 = Stone.gettext("Hello {name}", {name: "John"});
var text3 = Stone.gettext("Hello {name}", {name: "John"}, "it");
```

### Stone.lazyGettext

Same as `Stone.gettext` but returns a `Stone.LazyString` instead of a `String`.

    String: Stone.lazyGettext( <string> [, locale] );
    String: Stone.lazyGettext( <string> [, replacements] [, locale] );

### Stone.ngettext

Translates the given strings to the current language with plural support.

    String: Stone.ngettext( <string>, <stringPlural>, <number> [, locale] );
    String: Stone.ngettext( <string>, <stringPlural>, <number> [, replacements] [, locale] );

**params:**

* `string`: The string to translate, in English singular form.
* `stringPlural`: The string to translate, in English plural form.
* `number`: The number that determines plural forms
* `locale`: The locale string to use for translation (optional, default: current locale).
* `replacements`: an object containing replacements for the string (optional, see example below).

Note: 'n' is an implicit replacement for given number.

**returns:**

The translated string, in some plural form.

**Examples:**

```javascript
var text1 = Stone.ngettext("one apple", "{nbApples} apples", 3, {nbApples: 3});
var text2 = Stone.ngettext("{n} apple", "{n} apples", 3, {n: 3});
var text3 = Stone.ngettext("{n} apple", "{n} apples", 3); // 'n' is an implicit replacement of given number
```

### Stone.lazyNgettext

Same as `Stone.ngettext` but returns a `Stone.LazyNString` instead of a `String`.

### Stone.addCatalogs

Adds one (or more if you merged multiple languages into one file) string catalog.

    Stone.addCatalogs( <catalogs> );

**params:**

* `catalogs`: An object containing translated strings (catalogs can be built using [stronejs-tools][]).

**Examples:**

```javascript
Stone.addCatalogs(catalogs);
```

### Stone.gettext_noop

Register a string to be translatable.
Do not operate translation.
Translation can be operated later with `Stone.gettext`.
This can be useful in special cases where you want to register a string for translation,
but want to keep a reference of the original string, in order to translate it later.

    String: Stone.gettext_noop( <string> );

**params:**

* `string`: The string to register for translation

**returns:**

The exact same given string

**Examples:**

```javascript
var translatable1 = Stone.gettext_noop("Some string to translate");
var translatable2 = Stone.gettext_noop("Hello {name}");
var text1 = Stone.gettext(translatable1);
var text2 = Stone.gettext(translatable2, { name: "John" });
```

### Stone.getLocale

Returns the current locale (aka target language for the `gettext` and `lazyGettext` functions). The default locale is "c" (it means no translation: simply returns the string as it is in the source).

    String: Stone.getLocale();

**Examples:**

```javascript
var locale = Stone.getLocale();
// "c", "en", "fr", ...
```

### Stone.listCatalogs

Returns all availables catalogs.

    String: Stone.listCatalogs();

**Examples:**

```javascript
var catalogsList = Stone.listCatalogs();
// ["c", "en", "fr", ... ]
```

### Stone.setLocale

Defines the current locale (aka the target language for the `gettext` and `lazyGettext` functions).

**NOTE:** You can use the `setBestMatchingLocale` function to set the best language for the user.

    Stone.setLocale( <locale> );

**params:**

* `locale`: The locale code (e.g. `en`, `fr`, ...)

**Examples:**

```javascript
Stone.setLocale("fr");
```

### Stone.setBestMatchingLocale

Find and set the best language for the user (depending on available catalogs and given language list).

    Stone.setBestMatchingLocale( [locales] );

**params:**

* `locales`: (optional) string or array of string (e.g. `"fr"`, `["fr", "fr_FR", "en_US"]`).

**Examples:**

```javascript
Stone.setBestMatchingLocale();  // Automaticaly set the best language (from informations given by the browser)
setBestMatchingLocale("fr");    // Finds the catalog that best match "fr" ("fr", "fr_FR", fr_*,...)
setBestMatchingLocale(["fr", "en_US", "en_UK"]);    // Finds the best available catalog from the given list
```

### Stone.findBestMatchingLocale

Find and return the given locale that best matches the given catalogs.

    Stone.findBestMatchingLocale( [locales], [catalogs] );

**params:**

* `locales`: string or array of string (e.g. `"fr"`, `["fr", "fr_FR", "en_US"]`).
* `catalogs`: array of string (e.g. `["fr_FR", "en"]`).

**Example:**

```javascript
Stone.findBestMatchingLocale(["fr"], ["pt_BR", "fr_CA", "fr_FR"]);  // -> "fr_FR"
```

### Stone.guessUserLanguage

Tries to guess the user language (based on the browser's preferred languages).

    String: Stone.guessUserLanguage();

**returns:**

The user's language.

**example:**

```javascript
var locale = Stone.guessUserLanguage();
```

### Stone.enableDomScan

Allows Stone.js to scan all the DOM to find translatable strings (and to translate them).

    Stone.enableDomScan( <enable> );

**params:**

* `enable`: Enable the scan of the DOM if `true`, disable it otherwise.

**example:**

```javascript
Stone.enableDomScan(true);
```

### Stone.updateDomTranslation

Updates the DOM translation if DOM scan was enabled with `Stone.enableDomScan` (re-scan and re-translate all strings).

    Stone.updateDomTranslation();

### Stone.LazyString (class)

`Stone.LazyString` is an object returned by the `Stone.lazyGettext` function. It behaves like a standard `String` object (same API) but its value changes if you change the locale with `Stone.setLocale` function.

This is useful when you have to define translatable strings before the string catalog was loaded, or to automatically re-translate strings each time the locale is changed.

You can find an example of its use in the PhotonUI documentation:

* http://wanadev.github.io/PhotonUI/doc/widgets/translation.html

### Stone.LazyNString (class)

Same as `Stone.LazyString`, using `Stone.ngettext` for plural support.

### "stonejs-locale-changed" (event)

This event is fired each time the locale changes (using the `Stone.setLocale` function).

## Example Catalogs (JSON)

```javascript
{
    "fr": {
        "plural-forms": "nplurals=2; plural=(n > 1);",
        "messages": {
            "Hello World": ["Bonjour le monde"],
            "Hello {name}": ["Bonjour {name}"]
        }
    },
    "it": {
        "plural-forms": "nplurals=2; plural=(n != 1);",
        "messages": {
            "Hello World": ["Buongiorno il mondo"],
            "Hello {name}": ["Buongiorno {name}"]
        }
    }
}
```

## Changelog

* **2.6.0:**
   * Adds support of `ngettext()` for the JS API (thanks @jbghoul, #17)
   * Adds support of `gettext_noop()` for the JS API (thanks @jbghoul, #19)

* **2.5.0:**
   * Allow to override the local for a particular `gettext()` call (thanks @JochLAin, #13)

* **2.4.0:**
    * Adds the `listCatalogs` methods to list available catalogs (thanks @BobRazowsky, #12)

* **2.3.0**:
    * The `addCatalog` function now merge catalogs.

* **2.2.0**:
    * New function to find the best matching catalog from given locales and catalogs (`findBestMatchingLocale`)

* **2.1.0**:
    * Better language code handling (now support locales with dialect like fr_FR, fr_CA,...)
    * New function to select the best catalog from a language list (`setBestMatchingLocale`)

* **2.0.0**:
    * new javascript tools to replace the old pythonic ones
    * new file format (incompatible with the previous version!) to be ready for plural forms (ngettext) support
    * new documentation

[stonejs-tools]: https://github.com/flozz/stonejs-tools
[dl-zip]: https://github.com/flozz/stone.js/archive/master.zip


text:
NS_CC_BEGIN
class DownloadTaskCURL;
class DownloaderHints;

class DownloaderCURL : public IDownloaderImpl
{
public:
    DownloaderCURL(const DownloaderHints& hints);
    virtual ~DownloaderCURL();

    virtual IDownloadTask *createCoTask(std::shared_ptr<const DownloadTask>& task) override;

protected:
    class Impl;
    std::shared_ptr<Impl>   _impl;

    // for transfer data on schedule
    DownloadTaskCURL* _currTask;        // temp ref
    std::function<int64_t(void*, int64_t)> _transferDataToBuffer;

    // scheduler for update processing and finished task in main schedule
    void _onSchedule(float);
    std::string             _schedulerKey;
    CAScheduler*              _scheduler;
};

NS_CC_END;


text:
<?php

namespace backend\models;

use backend\components\SiteHelper;
use common\models\Bean;
use common\modules\i18n\Module;
use yii\helpers\BaseFileHelper;
use yii\web\UploadedFile;

/**
 * This is the model class for table "slider".
 *
 * @property integer $id
 * @property string $name
 * @property string $alias
 *
 * @property SliderItem[] $sliderItems
 */
class Slider extends Bean
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'slider';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'alias'], 'required'],
            [['name', 'alias'], 'string', 'max' => 255],
            ['sliderItems', 'validateRelatedBeans', 'skipOnEmpty' => false, 'skipOnError' => false, 'params' => ['beanRelatedField' => 'slider_id', 'beanClass' => SliderItem::className()]],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id'    => Module::t('Id'),
            'name'  => Module::t('Name'),
            'alias' => Module::t('Alias'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSliderItems()
    {
        return $this->hasMany(SliderItem::className(), ['slider_id' => 'id'])->orderBy('sort');
    }

    /**
     * Method for getting the name of the bean
     * Is called for breadcrumb generation
     * @return array
     */
    public static function getLabels()
    {
        return [
            'singular' => 'Slider',
            'multiple' => 'Sliders'
        ];
    }

    /**
     * @param array $postData
     * @return array
     */
    public function setSliderItems($postData)
    {
        SliderItem::deleteAll(['slider_id' => $this->id]);
        $files = UploadedFile::getInstancesByName('file');
        $uploadFolder = self::getUploadFolder();
        $errors = [];
        if (!empty($postData)) {
            $data = array_key_exists('SliderItem', $postData) ? $postData['SliderItem'] : [];
            $counter = 0;
            foreach ($data as $key => $beanArray) {
                $bean = new SliderItem();
                if (array_key_exists('image', $beanArray)) {
                    $bean->image = $beanArray['image'];
                }
                else {
                    /**
                     * Load image
                     */
                    if (!array_key_exists($counter, $files)) continue;
                    $file = $files[$counter];
                    $baseName = SiteHelper::translit($file->baseName);
                    $relativePath = $uploadFolder['relativePath'] .  $baseName . "." . $file->extension;
                    $path = $uploadFolder['path'] . $baseName . "." . $file->extension;
                    $file->saveAs($path);
                    $bean->image = $relativePath;
                    $counter++;
                }
                $bean->url = $beanArray['url'];
                $bean->sort = $beanArray['sort'];
                $bean->slider_id = $this->id;
                $bean->save();
            }
        }
        return $errors;
    }

    /**
     * Get directory where customer's file is saved
     * @return string
     * @throws Exception
     */
    public function getUploadFolder()
    {
        $id = $this->id;
        $basePath = \Yii::getAlias('@frontend') . '/web';
        $relativePath = "/uploads/sliders/" . $id . "/";
        $path = [
            'path'         => $basePath . $relativePath,
            'relativePath' => $relativePath
        ];
        BaseFileHelper::createDirectory($path['path']);
        return $path;
    }

    /**
     * @param bool $insert
     * @param array $changedAttributes
     */
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if (method_exists(\Yii::$app->request, 'post')) {
            $postData = \Yii::$app->request->post();
            $errors = $this->setSliderItems($postData);
            if (!empty($errors)) {
                \Yii::$app->session->setFlash('error', implode(',', $errors));
            }
        }
    }

}


text:
package org.apache.myfaces.trinidadinternal.renderkit;

import java.io.File;
import java.io.InputStream;

import java.net.MalformedURLException;
import java.net.URL;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.RenderKit;

import org.apache.myfaces.trinidadinternal.share.config.Configuration;
import org.apache.shale.test.mock.MockExternalContext;
import org.apache.shale.test.mock.MockFacesContext;

/**
 * Mock faces context for use with unit tests
 */
public class MFacesContext extends MockFacesContext
{
  public MFacesContext(boolean testMode)
  {
    setCurrentInstance(this);
    _external = new External(testMode);
  }

  @Override
  public ResponseWriter getResponseWriter()
  {
    return _responseWriter;
  }

  @Override
  public void setResponseWriter(ResponseWriter responseWriter)
  {
    _responseWriter = responseWriter;
  }

  @Override
  public Iterator<FacesMessage> getMessages()
  {
    return getMessages(_GLOBAL_MESSAGE);
  }

  @SuppressWarnings("unchecked")
  @Override
  public Iterator<FacesMessage> getMessages(String id)
  {
    if (id == null)
      id = _GLOBAL_MESSAGE;

    List<FacesMessage> messages = _messages.get(id);
    if (messages == null)
      messages = Collections.EMPTY_LIST;

    return messages.iterator();
  }

  @Override
  public void addMessage(String id, FacesMessage message)
  {
    if (id == null)
      id = _GLOBAL_MESSAGE;

    List<FacesMessage> messages = _messages.get(id);
    if (messages == null)
    {
      messages = new ArrayList<FacesMessage>();
      _messages.put(id, messages);
    }

    messages.add(message);
  }

  @Override
  public FacesMessage.Severity getMaximumSeverity()
  {
    FacesMessage.Severity max = FacesMessage.SEVERITY_INFO;

    Iterator<String> clients = getClientIdsWithMessages();
    while (clients.hasNext())
    {
      String messagesKey = clients.next();
      List<FacesMessage> messages = _messages.get(messagesKey);
      int len = _messages.size();
      for (int i = 0; i < len; i++)
      {
        FacesMessage fm = messages.get(i);
        FacesMessage.Severity nextSev = fm.getSeverity();

        if (max.compareTo(nextSev) < 0)
        {
          max = nextSev;
          if (max.compareTo(FacesMessage.SEVERITY_FATAL) >= 0)
          {
            return max;
          }
        }
      }
    }
    return max;
  }

  @Override
  public Iterator<String> getClientIdsWithMessages()
  {
    return _messages.keySet().iterator();
  }

  @Override
  public Application getApplication()
  {
    return MApplication.sharedInstance();
  }

  @Override
  public UIViewRoot getViewRoot()
  {
    return _viewRoot;
  }

  @Override
  public void setViewRoot(UIViewRoot viewRoot)
  {
    _viewRoot = viewRoot;
    if (_viewRoot != null)
    {
      _kit = RenderKitBootstrap.getRenderKit(this);
    }
    else
      _kit = null;
  }

  public static void clearContext()
  {
    FacesContext.setCurrentInstance(null);
  }

  public Locale getLocale()
  {
    return Locale.ENGLISH;
  }

  @Override
  public ExternalContext getExternalContext()
  {
    // this method is called a lot, so we don't want to use the "mock"
    // implementations as those expect a specific number of calls:
    return _external;
  }

  @Override
  public RenderKit getRenderKit()
  {
    if (_viewRoot == null)
      throw new IllegalStateException("Trying to get a RenderKit without a UIViewRoot");
    // this method is called a lot, so we don't want to use the "mock"
    // implementations as those expect a specific number of calls:
    return _kit;
  }

  private RenderKit       _kit;
  private ExternalContext _external;
  private ResponseWriter  _responseWriter;
  private UIViewRoot      _viewRoot;
  private Map<String, List<FacesMessage>> _messages =
    new HashMap<String, List<FacesMessage>>();

  private static final class External extends MockExternalContext
  {
    public External(boolean testMode)
    {
      super(null, null, null);

      _testMode = testMode;
      File file = null;
      try
      {
        String tmpdir = System.getProperty("java.io.tmpdir");
        file = new File(tmpdir,
                        "adftest/view/faces/cache".replace('/',
                                           File.separatorChar));
        file.mkdirs();
        _applicationMap.put("javax.servlet.context.tempdir", file);
      }
      catch (Exception e)
      {
        System.err.println("Could not create temp directory " + file + ": " + e);
      }
    }

    @Override
    public Object getContext() { return null; }

    @Override
    public Object getRequest() { return null; }

    @Override
    public Object getResponse() { return null; }

    @Override
    public Object getSession(boolean create) { return null; }

    @Override
    public String getRequestContextPath() { return "/test-context-path"; }

    @Override
    public String getRequestServletPath() { return "/test-faces"; }

    @Override
    public String getInitParameter(String name)
    {
      if (_testMode && Configuration.DISABLE_CONTENT_COMPRESSION.equals(name))
        return "true";
      // A hack to disable image generation
      if ("org.apache.myfaces.trinidadinternal.BLOCK_IMAGE_GENERATION".equals(name))
        return "true";
      return null;
    }

    @Override
    public String encodeNamespace(String in) { return in; }

    @Override
    public String encodeResourceURL(String url)
    {
      // The spec requires encodeResourceURL() to throw NPE here,
      // though not all impls do
      if (url == null)
        throw new NullPointerException("encodeResourceURL called with null URL");
      return "encoded-resource-url:" + url;
    }

    @Override
    public String encodeActionURL(String url)
    {
      // The spec requires encodeActionURL() to throw NPE here,
      // though not all impls do
      if (url == null)
        throw new NullPointerException("encodeActionURL called with null URL");

      return "encoded-action-url:" + url;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, String> getRequestHeaderMap()
    {
      return Collections.EMPTY_MAP;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, String> getRequestParameterMap()
    {
      return Collections.EMPTY_MAP;
    }

    @Override
    public InputStream getResourceAsStream(String path)
    {
      return MFacesContext.class.getResourceAsStream(path);
    }

    @Override
    public URL getResource(String path) throws MalformedURLException
    {
      return MFacesContext.class.getResource(path);
    }

    @Override
    public Map<String, Object> getApplicationMap()
    {
      // This used to be an unmodifiable map - but I ran into
      // renderers that happened to be the first to lazily boot
      // up a global system, which then cached values on the
      // application map...
      return _applicationMap;
    }

    @Override
    public Map<String, Object> getSessionMap()
    {
      // The underlying Shale Test implementation goes to the servlet
      // request, session, etc.  For the purposes of this test,
      // we shouldn't use any servlet APIs.  So, intercept the
      // session map.   Ideally, renderers shouldn't write into
      // the session map, but see above...
      return _sessionMap;
    }

    @Override
    public Map<String, Object> getRequestMap()
    {
      // this method is called a lot, so we don't want to use the "mock"
      // implementations as those expect a specific number of calls:
      return _requestMap;
    }

    private final Map<String, Object> _requestMap = new HashMap<String, Object>(2);
    private final Map<String, Object> _sessionMap = new HashMap<String, Object>(2);
    private final Map<String, Object> _applicationMap = new HashMap<String, Object>(2);
    private final boolean _testMode;
  }
  private static final String _GLOBAL_MESSAGE = "org.apache.myfaces.trinidadinternal.renderkit.MFacesContext.GLOBAL_MESSAGE";
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title>Major Kong</title>
  <generator uri="https://github.com/jekyll/jekyll">Jekyll v3.1.1</generator>
    <icon>http://localhost:4000/apple-touch-icon-precomposed.png</icon>
  <subtitle>A beginners gets his FPV wings</subtitle>
  <link href="http://localhost:4000/atom.xml" rel="self"/>
  <link href="http://localhost:4000/" rel="alternate" type="text/html"/>
  <updated>2016-06-28T20:59:18-04:00</updated>
  <id>http://localhost:4000/</id>
  <author>
    <name>Colin Blake</name>
    <uri>http://localhost:4000/</uri>
    <email>colinblake@gmail.com</email>
  </author>

  <entry>
    <title>5.8 GHz Frequency Charts</title>
    <link href="http://localhost:4000/reference/5.8-GHz-Frequency-Charts/"/>
    <updated>2016-06-28T00:00:00-04:00</updated>
    <id>http://localhost:4000/reference/5.8-GHz-Frequency-Charts</id>
    <author>
      <name>Colin Blake</name>
      <uri>http://localhost:4000/</uri>
      <email>colinblake@gmail.com</email>
    </author>
    <content type="html">

Dronimo has created a fantastic infographic showing the relationship between the various channels and bands used in FPV, along with instructions for maximizing the number of fliers while avoiding interference.

The charts are available in various sizes:

Business Card

Half US Letter

Full US Letter

    </content>
  </entry>

  <entry>
    <title>TBS Discovery</title>
    <link href="http://localhost:4000/hangar/TBS-Discovery/"/>
    <updated>2016-05-02T00:00:00-04:00</updated>
    <id>http://localhost:4000/hangar/TBS-Discovery</id>
    <author>
      <name>Colin Blake</name>
      <uri>http://localhost:4000/</uri>
      <email>colinblake@gmail.com</email>
    </author>
    <content type="html">

Page for TBS discovery

    </content>
  </entry>

</feed>


text:
package net.beaconcontroller.devicemanager;

import java.util.List;

/**
 * Used to interact with DeviceManager implementations
 *
 * @author David Erickson (daviderickson@cs.stanford.edu)
 */
public interface IDeviceManager {
    /**
     * Returns a device for the given data layer address
     * @param address
     * @return
     */
    public Device getDeviceByDataLayerAddress(byte[] address);

    /**
     * Returns a device for the given network layer address
     * @param address
     * @return
     */
    public Device getDeviceByNetworkLayerAddress(Integer address);

    /**
     * Returns a list of all known devices in the system
     * @return
     */
    public List<Device> getDevices();
}


text:
namespace content {

namespace {

// This is the default public key used for validating signatures.
// TODO(iclelland): Move this to the embedder, and provide a mechanism to allow
// for multiple signing keys. https://crbug.com/543220
static const uint8_t kPublicKey[] = {
    0x7c, 0xc4, 0xb8, 0x9a, 0x93, 0xba, 0x6e, 0xe2, 0xd0, 0xfd, 0x03,
    0x1d, 0xfb, 0x32, 0x66, 0xc7, 0x3b, 0x72, 0xfd, 0x54, 0x3a, 0x07,
    0x51, 0x14, 0x66, 0xaa, 0x02, 0x53, 0x4e, 0x33, 0xa1, 0x15,
};

const char* kApiKeyFieldSeparator = "|";

}  // namespace

ApiKey::~ApiKey() {}

scoped_ptr<ApiKey> ApiKey::Parse(const std::string& key_text) {
  if (key_text.empty()) {
    return nullptr;
  }

  // API Key should resemble:
  // signature|origin|api_name|expiry_timestamp
  // TODO(iclelland): Add version code to API key format to identify key algo
  // https://crbug.com/570684
  std::vector<std::string> parts =
      SplitString(key_text, kApiKeyFieldSeparator, base::KEEP_WHITESPACE,
                  base::SPLIT_WANT_ALL);
  if (parts.size() != 4) {
    return nullptr;
  }

  const std::string& signature = parts[0];
  const std::string& origin_string = parts[1];
  const std::string& api_name = parts[2];
  const std::string& expiry_string = parts[3];

  uint64_t expiry_timestamp;
  if (!base::StringToUint64(expiry_string, &expiry_timestamp)) {
    return nullptr;
  }

  // Ensure that the origin is a valid (non-unique) origin URL
  GURL origin_url(origin_string);
  if (url::Origin(origin_url).unique()) {
    return nullptr;
  }

  // signed data is (origin + "|" + api_name + "|" + expiry).
  std::string data = key_text.substr(signature.length() + 1);

  return make_scoped_ptr(
      new ApiKey(signature, data, origin_url, api_name, expiry_timestamp));
}

ApiKey::ApiKey(const std::string& signature,
               const std::string& data,
               const GURL& origin,
               const std::string& api_name,
               uint64_t expiry_timestamp)
    : signature_(signature),
      data_(data),
      origin_(origin),
      api_name_(api_name),
      expiry_timestamp_(expiry_timestamp) {}

bool ApiKey::IsAppropriate(const std::string& origin,
                           const std::string& api_name) const {
  return ValidateOrigin(origin) && ValidateApiName(api_name);
}

bool ApiKey::IsValid(const base::Time& now) const {
  // TODO(iclelland): Allow for multiple signing keys, and iterate over all
  // active keys here. https://crbug.com/543220
  return ValidateDate(now) &&
         ValidateSignature(base::StringPiece(
             reinterpret_cast<const char*>(kPublicKey), arraysize(kPublicKey)));
}

bool ApiKey::ValidateOrigin(const std::string& origin) const {
  return GURL(origin) == origin_;
}

bool ApiKey::ValidateApiName(const std::string& api_name) const {
  return base::EqualsCaseInsensitiveASCII(api_name, api_name_);
}

bool ApiKey::ValidateDate(const base::Time& now) const {
  base::Time expiry_time = base::Time::FromDoubleT((double)expiry_timestamp_);
  return expiry_time > now;
}

bool ApiKey::ValidateSignature(const base::StringPiece& public_key) const {
  return ValidateSignature(signature_, data_, public_key);
}

// static
bool ApiKey::ValidateSignature(const std::string& signature_text,
                               const std::string& data,
                               const base::StringPiece& public_key) {
  // Public key must be 32 bytes long for Ed25519.
  CHECK_EQ(public_key.length(), 32UL);

  std::string signature;
  // signature_text is base64-encoded; decode first.
  if (!base::Base64Decode(signature_text, &signature)) {
    return false;
  }

  // Signature must be 64 bytes long
  if (signature.length() != 64) {
    return false;
  }

  int result = ED25519_verify(
      reinterpret_cast<const uint8_t*>(data.data()), data.length(),
      reinterpret_cast<const uint8_t*>(signature.data()),
      reinterpret_cast<const uint8_t*>(public_key.data()));
  return (result != 0);
}

}  // namespace content


text:
"""Copyright 2019 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import os
import tensorflow as tf
import numpy as np
import random
from multiprocessing import dummy as multiprocessing
from absl import app
from absl import flags
from attributions import compute_and_save_attr

flags.DEFINE_integer('num_imgs', 10,
                     'Number of images to compute metrics over.')
flags.DEFINE_integer(
    'num_threads', 50,
    'Number of threads to use when perform images operations.')
flags.DEFINE_integer(
    'seed', 0, 'The seed to use when randomly sample from a set of inputs.'
    'Make sure sal_scratch is empty before changing the seed.')
flags.DEFINE_boolean(
    'scratch', True,
    'Compute metrics from scratch for num_imgs example inputs.')
flags.DEFINE_list('metrics', ['MCS', 'IDR', 'IIR'],
                  'List of metrics to evaluate.')
FLAGS = flags.FLAGS

ATTR_DIR = ['attr_reprod', 'attr_scratch']
METHOD_NAMES = [
    'Vanilla Gradient', 'Gradient SmoothGrad', 'Guided Backprop',
    'Guided Backprop SmoothGrad', 'Integrated Gradient',
    'Integrated Gradient SmoothGrad', 'GradCam', 'GradCam SmoothGrad',
    'Guided GradCam', 'Guided GradCam SmoothGrad', 'Gradient x Input',
    'Gradient SmoothGrad x Input'
]

# Index into METHOD_NAMES for the desired method names. Ordered roughly
# in the best to worst performance under the BAM metric.
METHOD_INDICES = [6, 0, 1, 4, 5, 10, 2, 8]

# For MCS, IDR, and IIR, the configs correspond to the names of the model-data
# pair (e.g., model1, data1, model2, data2). For RMCS, the config corresponds
# to the prefix of the model name and the data name.
METRIC_CONFIG = {
    'MCS': ['obj', 'obj', 'scene', 'scene'],
    'IDR': ['scene', 'scene_only', 'scene', 'scene'],
    'IIR': ['scene_only', 'bamboo_forest', 'scene_only', 'bamboo_forest_patch'],
    'RMCS': ['scene', 'dog_bedroom']
}

# BAM models have 10 classes so there are 10 models for RMC testing.
NUM_RELATIVE_MODELS = 10

# BAM's dataset for IIR contains 100 images so sample up to 100.
MAX_SAMPLE_INDEX = 100

# MCS and IDR are evaluated on 10000 images, IIR and RMCS are on 100.
NUM_TOTAL_IMAGES = {
    'MCS': 10000,
    'IDR': 10000,
    'IIR': 100,
    'RMCS': 100,
}

BASE_DIR = os.getcwd()

def get_global_indices(metric):
  """When computing from scratch, generate random global image indices from a fixed seed.

  When reproducing results given attributions, enumerate all indices of
  NUM_TOTAL_IMAGES['metric'].
  """

  if not FLAGS.scratch:
    return range(NUM_TOTAL_IMAGES[metric])
  random.seed(FLAGS.seed)
  return sorted(random.sample(range(NUM_TOTAL_IMAGES[metric]), FLAGS.num_imgs))

def corr_indices(model, data, metric):
  """Given the name of a model and a set of data, return the indices of the images that are correctly classified by the model."""

  label_fpath = os.path.join(BASE_DIR, 'data', data, 'val.txt')
  labels = [
      int(l.split(' ')[-1]) for l in tf.gfile.Open(label_fpath).readlines()
  ]
  img_fnames = tf.gfile.ListDirectory(
      os.path.join(BASE_DIR, ATTR_DIR[FLAGS.scratch], model + '-' + data))
  preds = [int(p.split('_')[-1]) for p in sorted(img_fnames)]
  attr_indices = range(len(preds))
  if FLAGS.scratch:
    attr_indices = range(FLAGS.num_imgs)
  global_indices = get_global_indices(metric)
  corr = [i for i in attr_indices if preds[i] == labels[global_indices[i]]]
  return corr

def load_pos_neg_attr(model_pos, data_pos, model_neg, data_neg):
  """Load two sets of attributions from model_pos-data_pos and model_neg-data_neg.

  Filter and only return attributions of correctly classified inputs.

  Args:
      model_pos: the model name for which objects have positive attributions.
      data_pos: the data name for which objects have positive attributions.
      model_neg: the model name for which objects have negative attributions.
      data_neg: the data name for which objects have negative attributions.

  Returns:
      arrays of attributions corresponding to model_pos-data_pos and
      model_neg-data_neg pairs.
  """

  dir_pos = os.path.join(BASE_DIR, ATTR_DIR[FLAGS.scratch],
                         model_pos + '-' + data_pos)
  pool = multiprocessing.Pool(FLAGS.num_threads)
  attr_pos = np.array(
      pool.map(
          lambda f: np.load(tf.gfile.GFile(os.path.join(dir_pos, f), 'rb')),
          sorted(tf.gfile.ListDirectory(dir_pos))))
  dir_neg = os.path.join(BASE_DIR, ATTR_DIR[FLAGS.scratch],
                         model_neg + '-' + data_neg)
  attr_neg = np.array(
      pool.map(
          lambda f: np.load(tf.gfile.GFile(os.path.join(dir_neg, f), 'rb')),
          sorted(tf.gfile.ListDirectory(dir_neg))))
  if FLAGS.scratch:
    attr_pos = attr_pos[:FLAGS.num_imgs]
    attr_neg = attr_neg[:FLAGS.num_imgs]
  return attr_pos, attr_neg

def MCS(model_pos, data_pos, model_neg, data_neg, relative=False):
  """Compute the model contrast score defined as the average attribution

  difference between model_pos-data_pos and model_neg-data_neg.

  Args:
      model_pos: the model name for which objects have positive attributions.
      data_pos: the data name for which objects have positive attributions.
      model_neg: the model name for which objects have negative attributions.
      data_neg: the data name for which objects have negative attributions.
  """

  metric = 'RMCS' if relative else 'MCS'
  attr_pos, attr_neg = load_pos_neg_attr(model_pos, data_pos, model_neg,
                                         data_neg)
  corr_pos = corr_indices(model_pos, data_pos, metric)
  corr_neg = corr_indices(model_neg, data_neg, metric)
  corr = [i for i in corr_pos if i in corr_neg]
  for j in METHOD_INDICES:
    print(','.join(
        map(str, [METHOD_NAMES[j],
                  np.mean((attr_pos - attr_neg)[corr, j])])))

def IDR(model, data_pos, data_neg):
  """Compute the input dependence rate defined as the percentage of examples where data_pos is attributed higher than data_neg.

  Args:
      model: name of the model being evaluated.
      data_pos: the data name for positive attributions.
      data_neg: the data name for negative attributions.
  """

  attr_pos, attr_neg = load_pos_neg_attr(model, data_pos, model, data_neg)
  corr_pos = corr_indices(model, data_pos, 'IDR')
  corr_neg = corr_indices(model, data_neg, 'IDR')
  corr = [i for i in corr_pos if i in corr_neg]
  for j in METHOD_INDICES:
    count = sum(d > 0 for d in (attr_pos - attr_neg)[corr, j])
    print(','.join(map(str, [METHOD_NAMES[j], count / float(len(corr))])))

def IIR(model, data, data_patch, threashold=0.1):
  """Compute the input independence rate defined as the percentage of examples where the difference between data and data_patch is less than threshold.

  Args:
      model: name of the model being evaluated.
      data: name of the data directory that contains scene-only images.
      data_patch: name of the data directory that contains functionally
        insignificant object patches.
  """

  attr, attr_patch = load_pos_neg_attr(model, data, model, data_patch)
  corr = corr_indices(model, data, 'IIR')
  corr_patch = corr_indices(model, data_patch, 'IIR')
  corr = [i for i in corr if i in corr_patch]
  for j in METHOD_INDICES:
    diff = abs(attr[corr, j] - attr_patch[corr, j])
    count = sum(diff < threashold * attr[corr, j])
    print(','.join(map(str, [METHOD_NAMES[j], count / float(len(corr))])))

def main(argv):
  for metric in FLAGS.metrics:
    print('Results for {}:'.format(metric))

    global_indices = get_global_indices(metric)
    if metric == 'RMCS':
      model_prefix, data = METRIC_CONFIG[metric]
      if FLAGS.scratch:
        for i in range(1, NUM_RELATIVE_MODELS + 1):
          compute_and_save_attr(model_prefix + str(i), data, global_indices,
                                FLAGS.num_threads)
      for i in range(1, NUM_RELATIVE_MODELS):
        print('MCS between', model_prefix + str(i), 'and',
              model_prefix + str(NUM_RELATIVE_MODELS))
        MCS(model_prefix + str(i), data,
            model_prefix + str(NUM_RELATIVE_MODELS), data, relative=True)
    else:
      model1, data1, model2, data2 = METRIC_CONFIG[metric]
      if FLAGS.scratch:
        compute_and_save_attr(model1, data1, global_indices, FLAGS.num_threads)
        compute_and_save_attr(model2, data2, global_indices, FLAGS.num_threads)
      if metric == 'MCS':
        MCS(model1, data1, model2, data2)
      if metric == 'IDR':
        IDR(model1, data1, data2)
      if metric == 'IIR':
        IIR(model1, data1, data2)

if __name__ == '__main__':
  app.run(main)