text:
%%% Преамбула %%%

\usepackage{fontspec} % XeTeX
\usepackage{xunicode} % Unicode для XeTeX
\usepackage{xltxtra}  % Верхние и нижние индексы
\usepackage{pdfpages} % Вставка PDF

\usepackage{listings} % Оформление исходного кода
\lstset{
    basicstyle=\small\ttfamily, % Размер и тип шрифта
    breaklines=true,            % Перенос строк
    tabsize=2,                  % Размер табуляции
    frame=single,               % Рамка
    literate={--}{{-{}-}}2,     % Корректно отображать двойной дефис
    literate={---}{{-{}-{}-}}3  % Корректно отображать тройной дефис
}

% Шрифты, xelatex
\defaultfontfeatures{Ligatures=TeX}
\setmainfont{Times New Roman} % Нормоконтроллеры хотят именно его
\newfontfamily\cyrillicfont{Times New Roman}
% \setsansfont{Liberation Sans} % Тут я его не использую, но если пригодится
\setmonofont{FreeMono} % Моноширинный шрифт для оформления кода

% Формулы
\usepackage{mathtools,unicode-math} % Не совместим с amsmath
\setmathfont{XITS Math}             % Шрифт для формул: https://github.com/khaledhosny/xits-math
\numberwithin{equation}{section}    % Формула вида секция.номер

% Русский язык
\usepackage{polyglossia}
\setdefaultlanguage{russian}

% Абзацы и списки
\usepackage{enumerate}   % Тонкая настройка списков
\usepackage{indentfirst} % Красная строка после заголовка
\usepackage{float}       % Расширенное управление плавающими объектами
\usepackage{multirow}    % Сложные таблицы

% Пути к каталогам с изображениями
\usepackage{graphicx} % Вставка картинок и дополнений
\graphicspath{{images/}}

% Формат подрисуночных записей
\usepackage{chngcntr}

% Сбрасываем счетчик таблиц и рисунков в каждой новой главе
\counterwithin{figure}{section}
\counterwithin{table}{section}

% Гиперссылки
\usepackage{hyperref}
\hypersetup{
    colorlinks, urlcolor={black}, % Все ссылки черного цвета, кликабельные
    linkcolor={black}, citecolor={black}, filecolor={black},
    pdfauthor={Иван Пустовойтов},
    pdftitle={Исследование процессов обеспечения безопасности облачных сред}
}

% Оформление библиографии и подрисуночных записей через точку
\makeatletter
\renewcommand*{\@biblabel}[1]{\hfill#1.}
\renewcommand*\l@section{\@dottedtocline{1}{1em}{1em}}
\renewcommand{\thefigure}{\thesection.\arabic{figure}} % Формат рисунка секция.номер
\renewcommand{\thetable}{\thesection.\arabic{table}}   % Формат таблицы секция.номер
\def\redeflsection{\def\l@section{\@dottedtocline{1}{0em}{10em}}}
\makeatother

\renewcommand{\baselinestretch}{1.4} % Полуторный межстрочный интервал
\parindent 1.27cm % Абзацный отступ

\sloppy             % Избавляемся от переполнений
\hyphenpenalty=1000 % Частота переносов
\clubpenalty=10000  % Запрещаем разрыв страницы после первой строки абзаца
\widowpenalty=10000 % Запрещаем разрыв страницы после последней строки абзаца

% Отступы у страниц
\usepackage{geometry}
\geometry{left=3cm}
\geometry{right=1cm}
\geometry{top=2cm}
\geometry{bottom=2cm}

% Списки
\usepackage{enumitem}
\setlist[enumerate,itemize]{leftmargin=12.7mm} % Отступы в списках

\makeatletter
    \AddEnumerateCounter{\asbuk}{\@asbuk}{м)}
\makeatother
\setlist{nolistsep}                           % Нет отступов между пунктами списка
\renewcommand{\labelitemi}{--}                % Маркер списка --
\renewcommand{\labelenumi}{\asbuk{enumi})}    % Список второго уровня
\renewcommand{\labelenumii}{\arabic{enumii})} % Список третьего уровня

% Содержание
\usepackage{tocloft}
\renewcommand{\cfttoctitlefont}{\hspace{0.38\textwidth}\MakeTextUppercase} % СОДЕРЖАНИЕ
\renewcommand{\cftsecfont}{\hspace{0pt}}            % Имена секций в содержании не жирным шрифтом
\renewcommand\cftsecleader{\cftdotfill{\cftdotsep}} % Точки для секций в содержании
\renewcommand\cftsecpagefont{\mdseries}             % Номера страниц не жирные
\setcounter{tocdepth}{3}                            % Глубина оглавления, до subsubsection

% Список иллюстративного материала
\renewcommand{\cftloftitlefont}{\hspace{0.17\textwidth}\MakeTextUppercase}
\renewcommand{\cftfigfont}{Рисунок }
\addto\captionsrussian{\renewcommand\listfigurename{Список иллюстративного материала}}

% Список табличного материала
\renewcommand{\cftlottitlefont}{\hspace{0.2\textwidth}\MakeTextUppercase}
\renewcommand{\cfttabfont}{Таблица }
\addto\captionsrussian{\renewcommand\listtablename{Список табличного материала}}

% Нумерация страниц посередине сверху
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\cfoot{\textrm{\thepage}}
\fancyheadoffset{0mm}
\fancyfootoffset{0mm}
\setlength{\headheight}{17pt}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
\fancypagestyle{plain}{
    \fancyhf{}
    \cfoot{\textrm{\thepage}}
}

% Формат подрисуночных надписей
\RequirePackage{caption}
\DeclareCaptionLabelSeparator{defffis}{ -- } % Разделитель
\captionsetup[figure]{justification=centering, labelsep=defffis, format=plain} % Подпись рисунка по центру
\captionsetup[table]{justification=raggedright, labelsep=defffis, format=plain, singlelinecheck=false} % Подпись таблицы слева
\addto\captionsrussian{\renewcommand{\figurename}{Рисунок}} % Имя фигуры

% Пользовательские функции
\newcommand{\addimg}[4]{ % Добавление одного рисунка
    \begin{figure}
        \centering
        \includegraphics[width=#2\linewidth]{#1}
        \caption{#3} \label{#4}
    \end{figure}
}
\newcommand{\addimghere}[4]{ % Добавить рисунок непосредственно в это место
    \begin{figure}[H]
        \centering
        \includegraphics[width=#2\linewidth]{#1}
        \caption{#3} \label{#4}
    \end{figure}
}
\newcommand{\addtwoimghere}[5]{ % Вставка двух рисунков
    \begin{figure}[H]
        \centering
        \includegraphics[width=#2\linewidth]{#1}
        \hfill
        \includegraphics[width=#3\linewidth]{#2}
        \caption{#4} \label{#5}
    \end{figure}
}

% Заголовки секций в оглавлении в верхнем регистре
\usepackage{textcase}
\makeatletter
\let\oldcontentsline\contentsline
\def\contentsline#1#2{
    \expandafter\ifx\csname l@#1\endcsname\l@section
        \expandafter\@firstoftwo
    \else
        \expandafter\@secondoftwo
    \fi
    {\oldcontentsline{#1}{\MakeTextUppercase{#2}}}
    {\oldcontentsline{#1}{#2}}
}
\makeatother

% Оформление заголовков
\usepackage[compact,explicit]{titlesec}
\titleformat{\section}{}{}{12.5mm}{\centering{\thesection\quad\MakeTextUppercase{#1}}\vspace{1.5em}}
\titleformat{\subsection}[block]{\vspace{1em}}{}{12.5mm}{\thesubsection\quad#1\vspace{1em}}
\titleformat{\subsubsection}[block]{\vspace{1em}\normalsize}{}{12.5mm}{\thesubsubsection\quad#1\vspace{1em}}
\titleformat{\paragraph}[block]{\normalsize}{}{12.5mm}{\MakeTextUppercase{#1}}

% Секции без номеров (введение, заключение...), вместо section*{}
\newcommand{\anonsection}[1]{
    \phantomsection % Корректный переход по ссылкам в содержании
    \paragraph{\centerline{{#1}}\vspace{1em}}
    \addcontentsline{toc}{section}{#1}
}

% Секция для аннотации (она не включается в содержание)
\newcommand{\annotation}[1]{
    \paragraph{\centerline{{#1}}\vspace{1em}}
}

% Секция для списка иллюстративного материала
\newcommand{\lof}{
    \phantomsection
    \listoffigures
    \addcontentsline{toc}{section}{\listfigurename}
}

% Секция для списка табличного материала
\newcommand{\lot}{
    \phantomsection
    \listoftables
    \addcontentsline{toc}{section}{\listtablename}
}

% Секции для приложений
\newcommand{\appsection}[1]{
    \phantomsection
    \paragraph{\centerline{{#1}}}
    \addcontentsline{toc}{section}{{#1}}
}

% Библиография: отступы и межстрочный интервал
\makeatletter
\renewenvironment{thebibliography}[1]
    {\section*{\refname}
        \list{\@biblabel{\@arabic\c@enumiv}}
           {\settowidth\labelwidth{\@biblabel{#1}}
            \leftmargin\labelsep
            \itemindent 16.7mm
            \@openbib@code
            \usecounter{enumiv}
            \let\p@enumiv\@empty
            \renewcommand\theenumiv{\@arabic\c@enumiv}
        }
        \setlength{\itemsep}{0pt}
    }
\makeatother

\usepackage{lastpage} % Подсчет количества страниц
\setcounter{page}{3}  % Начало нумерации страниц


text:
{% macro javascript(path) %}

{% endmacro %}

{% macro stylesheet(path) %}
    <link rel="stylesheet" href="/static/css/{{path}}" type="text/css" media="all">
{% endmacro %}

{% macro linkto(text, path, class) %}
    {{text}}
{% endmacro %}

{% macro navtag(id, text, href, class="") %}

{{text}}

{% endmacro %}

{% macro img(src, alt) %}

{% endmacro %}

{% macro form_input(name, type = "text", placeholder = "") %}

        {{placeholder}}:

          <input id="{{name}}" name="{{name}}" type="{{type}}" class="form-control" placeholder="{{placeholder}}">

{% endmacro %}

{% macro form_submit(text, btncls = "default") %}

          <button type="submit" class="btn btn-{{btncls}}">{{text}}</button>

{% endmacro %}

redpajama_set_name: RedPajamaGithub


text:
function solve(args) {
  var output = (args + '').replace(/ /g, ' ');
  console.log(output);
}

solve('This text contains 4 spaces!!');


text:
[![Build Status][3]][4]
[![dependency status][5]][6]
[![dev dependency status][7]][8]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]

[![npm badge][11]][1]

ES2015-compliant shim for Number.isNaN - the global isNaN returns false positives.

This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan).

## Example

```js
Number.isNaN = require('is-nan');
var assert = require('assert');

assert.notOk(Number.isNaN(undefined));
assert.notOk(Number.isNaN(null));
assert.notOk(Number.isNaN(false));
assert.notOk(Number.isNaN(true));
assert.notOk(Number.isNaN(0));
assert.notOk(Number.isNaN(42));
assert.notOk(Number.isNaN(Infinity));
assert.notOk(Number.isNaN(-Infinity));
assert.notOk(Number.isNaN('foo'));
assert.notOk(Number.isNaN(function () {}));
assert.notOk(Number.isNaN([]));
assert.notOk(Number.isNaN({}));

assert.ok(Number.isNaN(NaN));
```

## Tests
Simply clone the repo, `npm install`, and run `npm test`

[1]: https://npmjs.org/package/is-nan
[2]: http://versionbadg.es/es-shims/is-nan.svg
[3]: https://travis-ci.org/es-shims/is-nan.svg
[4]: https://travis-ci.org/es-shims/is-nan
[5]: https://david-dm.org/es-shims/is-nan.svg
[6]: https://david-dm.org/es-shims/is-nan
[7]: https://david-dm.org/es-shims/is-nan/dev-status.svg
[8]: https://david-dm.org/es-shims/is-nan#info=devDependencies
[11]: https://nodei.co/npm/is-nan.png?downloads=true&stars=true
[license-image]: http://img.shields.io/npm/l/is-nan.svg
[license-url]: LICENSE
[downloads-image]: http://img.shields.io/npm/dm/is-nan.svg
[downloads-url]: http://npm-stat.com/charts.html?package=is-nan


text:
package com.akjava.gwt.lib.hangouts.client.av;

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

import com.akjava.gwt.lib.hangouts.client.av.events.VolumesChangedEvent;
import com.akjava.gwt.lib.hangouts.client.av.listeners.VolumesChangedListener;

public class OnVolumesChanged {
	private OnVolumesChanged(){}

	 private static native void registListener()/*-{
	   $wnd.gapi.hangout.av.onVolumesChanged.add(@com.akjava.gwt.lib.hangouts.client.av.OnVolumesChanged::fireListener(Lcom/akjava/gwt/lib/hangouts/client/av/events/VolumesChangedEvent;));
	  }-*/;

	 private static native void unregistListener()/*-{
	    $wnd.gapi.hangout.av.onVolumesChanged.remove(@com.akjava.gwt.lib.hangouts.client.av.OnVolumesChanged::fireListener(Lcom/akjava/gwt/lib/hangouts/client/av/events/VolumesChangedEvent;));
	  }-*/;

	 public static void add(VolumesChangedListener listener){
		 if(listeners==null){
			 listeners=new ArrayList<VolumesChangedListener>();
			 listeners.add(listener);
			 registListener();
		 }else{
			 listeners.add(listener);
		 }
	 }
	 public static void remove(VolumesChangedListener listener){
		 if(listeners==null){

		 }else{
			 listeners.remove(listener);
			 if(listeners.size()==0){
				 unregistListener();
				 listeners=null;
			 }
		 }
	 }

	 private static List<VolumesChangedListener> listeners;
	 synchronized static void fireListener(VolumesChangedEvent event){
		 for(VolumesChangedListener listener:listeners){
			 listener.onVolumesChanged(event);
		 }
	 }
}


text:
class Item
{
public:
	Item();
	~Item();
	Item(std::string name, std::string description, int weight, int value);
	void Describe();
protected:
	std::string name;
	std::string description;
	int weight;
	int value;
};


text:
       html_favicon_url = "https://rust-num.github.io/num/favicon.ico",
       html_root_url = "https://rust-num.github.io/num/",
       html_playground_url = "http://play.integer32.com/")]

#[cfg(any(feature = "rand", test))]
extern crate rand;
#[cfg(feature = "rustc-serialize")]
extern crate rustc_serialize;
#[cfg(feature = "serde")]
extern crate serde;

extern crate num_integer as integer;
extern crate num_traits as traits;

use std::error::Error;
use std::num::ParseIntError;
use std::fmt;

#[derive(Debug, PartialEq)]
pub enum ParseBigIntError {
    ParseInt(ParseIntError),
    Other,
}

impl fmt::Display for ParseBigIntError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &ParseBigIntError::ParseInt(ref e) => e.fmt(f),
            &ParseBigIntError::Other => "failed to parse provided string".fmt(f),
        }
    }
}

impl Error for ParseBigIntError {
    fn description(&self) -> &str {
        "failed to parse bigint/biguint"
    }
}

impl From<ParseIntError> for ParseBigIntError {
    fn from(err: ParseIntError) -> ParseBigIntError {
        ParseBigIntError::ParseInt(err)
    }
}

#[cfg(test)]
use std::hash;

#[cfg(test)]
fn hash<T: hash::Hash>(x: &T) -> u64 {
    use std::hash::Hasher;
    let mut hasher = hash::SipHasher::new();
    x.hash(&mut hasher);
    hasher.finish()
}

#[macro_use]
mod macros;

mod biguint;
mod bigint;

pub use biguint::BigUint;
pub use biguint::ToBigUint;
pub use biguint::big_digit;
pub use biguint::big_digit::{BigDigit, DoubleBigDigit, ZERO_BIG_DIGIT};

pub use bigint::Sign;
pub use bigint::BigInt;
pub use bigint::ToBigInt;
pub use bigint::RandBigInt;


text:
package org.mifos.customers.personnel.business.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mifos.application.master.business.CustomFieldType;
import org.mifos.customers.office.business.OfficeBO;
import org.mifos.customers.personnel.business.PersonnelBO;
import org.mifos.customers.personnel.util.helpers.PersonnelConstants;
import org.mifos.customers.personnel.util.helpers.PersonnelLevel;
import org.mifos.dto.domain.CustomFieldDto;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.business.util.Address;
import org.mifos.framework.business.util.Name;
import org.mifos.framework.exceptions.ServiceException;
import org.mifos.framework.hibernate.helper.QueryResult;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.util.helpers.IntegrationTestObjectMother;
import org.mifos.framework.util.helpers.TestObjectFactory;
import org.mifos.security.login.util.helpers.LoginConstants;

public class PersonnelBusinessServiceIntegrationTest extends MifosIntegrationTestCase {

    private OfficeBO office;

    private PersonnelBO personnel;

    private PersonnelBO personnelBO;

    private PersonnelBusinessService personnelBusinessService;

    @Before
    public void setUp() throws Exception {
        personnelBusinessService = new PersonnelBusinessService();
    }

    @After
    public void tearDown() throws Exception {
        personnelBO = null;
        personnel = null;
        StaticHibernateUtil.flushSession();
    }

    @Test
    public void testSuccessfullGetPersonnel() throws Exception {
        personnel = createPersonnel();
        String oldUserName = personnel.getUserName();
        personnel = personnelBusinessService.getPersonnel(personnel.getUserName());
        Assert.assertEquals(oldUserName, personnel.getUserName());
    }

    @Test
    public void testFailureGetPersonnel() throws Exception {
        personnel = createPersonnel();
        try {
            personnel = personnelBusinessService.getPersonnel("WRONG_USERNAME");
        } catch (ServiceException pe) {
            Assert.assertTrue(true);
            Assert.assertEquals(LoginConstants.KEYINVALIDUSER, pe.getKey());
        }

    }

    @Test
    public void testSearch() throws Exception {
        personnel = createPersonnel();
        QueryResult queryResult = personnelBusinessService.search(personnel.getUserName(), Short
                .valueOf("1"));

        Assert.assertNotNull(queryResult);
        Assert.assertEquals(1, queryResult.getSize());
        Assert.assertEquals(1, queryResult.get(0, 10).size());
    }

    @Test
    public void testGetActiveLoanOfficersUnderOffice() throws Exception {
        office = TestObjectFactory.getOffice(TestObjectFactory.SAMPLE_BRANCH_OFFICE);
        personnel = createPersonnel(office, PersonnelLevel.NON_LOAN_OFFICER);
        List<PersonnelBO> loanOfficers = personnelBusinessService
                .getActiveLoanOfficersUnderOffice(office.getOfficeId());
        Assert.assertNotNull(loanOfficers);
        Assert.assertEquals(1, loanOfficers.size());

    }

    @Test
    public void testGetAllPersonnel() throws Exception {
        List<PersonnelBO> personnel = personnelBusinessService.getAllPersonnel();
        Assert.assertNotNull(personnel);
        Assert.assertEquals(3, personnel.size());
    }

    private PersonnelBO createPersonnel(OfficeBO office, PersonnelLevel personnelLevel) throws Exception {
        List<CustomFieldDto> customFieldDto = new ArrayList<CustomFieldDto>();
        customFieldDto.add(new CustomFieldDto(Short.valueOf("9"), "123456", CustomFieldType.NUMERIC.getValue()));
        Address address = new Address("abcd", "abcd", "abcd", "abcd", "abcd", "abcd", "abcd", "abcd");
        Date date = new Date();
        personnel = new PersonnelBO(personnelLevel, office, Integer.valueOf("1"), Short.valueOf("1"), "ABCD", "XYZ",
                "xyz@yahoo.com", null, customFieldDto, new Name("XYZ", null, null, null), "111111", date, Integer
                        .valueOf("1"), Integer.valueOf("1"), date, date, address, PersonnelConstants.SYSTEM_USER, new Date(), new HashSet());
        IntegrationTestObjectMother.createPersonnel(personnel);
        return IntegrationTestObjectMother.findPersonnelById(personnel.getPersonnelId());
    }

    private PersonnelBO createPersonnel() throws Exception {
        office = TestObjectFactory.getOffice(TestObjectFactory.HEAD_OFFICE);
        return createPersonnel(office, PersonnelLevel.LOAN_OFFICER);
    }
}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S9.8_A1_T1;
 * @section: 9.8;
 * @assertion: Result of ToString conversion from undefined value is "undefined";
 * @description: Undefined values is undefined, void 0 and eval("var x"). Use explicit transformation;
*/

// CHECK#1
if (String(undefined) !== "undefined") {
  $ERROR('#1: String(undefined) === "undefined". Actual: ' + (String(undefined)));
}

// CHECK#2
if (String(void 0) !== "undefined") {
  $ERROR('#2: String(void 0) === "undefined". Actual: ' + (String(void 0)));
}

// CHECK#3
if (String(eval("var x")) !== "undefined") {
  $ERROR('#3: String(eval("var x")) === "undefined" . Actual: ' + (String(eval("var x"))));
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/PriceCutdown.iml" filepath="$PROJECT_DIR$/.idea/PriceCutdown.iml" />
    </modules>
  </component>
</project>


text:
@interface FeedbackDemo : NSObject

-(int) showFeedbackSceneForDemoType:(NSString*)demoType;

@end


text:
<?xml version="1.0"?>
<!--

-->
<layout>
    <adminhtml_logviewer_index>
        <reference name="head">
            <action method="addCss"><stylesheet>itabs/logviewer/styles.css</stylesheet></action>
        </reference>
        <reference name="content">
            <block type="itabs_logviewer/adminhtml_console" name="itabs.logviewer.console">
                <block type="itabs_logviewer/adminhtml_console_files" name="itabs.logviewer.console.files" as="files" />
            </block>
        </reference>
    </adminhtml_logviewer_index>
</layout>


text:
import numpy as np
from scipy import linalg

def log_multivariate_normal_density(X, means, covars, covariance_type='diag'):
    """
    Compute the log probability under a multivariate Gaussian distribution.

    Parameters
    ----------
    X : array_like, shape (n_samples, n_features)
        List of n_features-dimensional data points. Each row corresponds to a
        single data point.

    means : array_like, shape (n_components, n_features)
        List of n_features-dimensional mean vectors for n_components Gaussians.
        Each row corresponds to a single mean vector.

    covars : array_like
        List of n_components covariance parameters for each Gaussian. The shape
        depends on `covariance_type`:

        * (n_components, )                        if "spherical",
        * (n_components, n_features)              if "diag",
        * (n_components, n_features, n_features)  if "full",
        * (n_features, n_features)                if "tied".

    covariance_type : {"spherical", "diag", "full", "tied"}, optional
        The type of the covariance parameters.  Defaults to 'diag'.

    Returns
    -------
    lpr : array_like, shape (n_samples, n_components)
        Array containing the log probabilities of each data point in
        X under each of the n_components multivariate Gaussian distributions.
    """
    log_multivariate_normal_density_dict = {
        'spherical': _log_multivariate_normal_density_spherical,
        'tied': _log_multivariate_normal_density_tied,
        'diag': _log_multivariate_normal_density_diag,
        'full': _log_multivariate_normal_density_full}
    return log_multivariate_normal_density_dict[covariance_type](
        X, means, covars
    )

def _log_multivariate_normal_density_diag(X, means, covars):
    """Compute Gaussian log-density at X for a diagonal model."""
    # X: (ns, nf); means: (nc, nf); covars: (nc, nf) -> (ns, nc)
    nc, nf = means.shape
    # Avoid 0 log 0 = nan in degenerate covariance case.
    covars = np.maximum(covars, np.finfo(float).tiny)
    with np.errstate(over="ignore"):
        return -0.5 * (nf * np.log(2 * np.pi)
                       + np.log(covars).sum(axis=-1)
                       + ((X[:, None, :] - means) ** 2 / covars).sum(axis=-1))

def _log_multivariate_normal_density_spherical(X, means, covars):
    """Compute Gaussian log-density at X for a spherical model."""
    nc, nf = means.shape
    if covars.ndim == 1:
        covars = covars[:, np.newaxis]
    covars = np.broadcast_to(covars, (nc, nf))
    return _log_multivariate_normal_density_diag(X, means, covars)

def _log_multivariate_normal_density_tied(X, means, covars):
    """Compute Gaussian log-density at X for a tied model."""
    nc, nf = means.shape
    cv = np.broadcast_to(covars, (nc, nf, nf))
    return _log_multivariate_normal_density_full(X, means, cv)

def _log_multivariate_normal_density_full(X, means, covars, min_covar=1.e-7):
    """Log probability for full covariance matrices."""
    nc, nf = means.shape
    log_prob = []
    for c, (mu, cv) in enumerate(zip(means, covars)):
        try:
            cv_chol = linalg.cholesky(cv, lower=True)
        except linalg.LinAlgError:
            # The model is most probably stuck in a component with too
            # few observations, we need to reinitialize this components
            try:
                cv_chol = linalg.cholesky(cv + min_covar * np.eye(nf),
                                          lower=True)
            except linalg.LinAlgError:
                raise ValueError("'covars' must be symmetric, "
                                 "positive-definite")

        cv_log_det = 2 * np.sum(np.log(np.diagonal(cv_chol)))
        cv_sol = linalg.solve_triangular(cv_chol, (X - mu).T, lower=True).T
        log_prob.append(-.5 * (nf * np.log(2 * np.pi)
                               + (cv_sol ** 2).sum(axis=1)
                               + cv_log_det))

    return np.transpose(log_prob)


text:
package energy.usef.brp.workflow.plan.flexrequest.create;

import static energy.usef.core.constant.USEFConstants.LOG_COORDINATOR_FINISHED_HANDLING_EVENT;
import static energy.usef.core.constant.USEFConstants.LOG_COORDINATOR_START_HANDLING_EVENT;
import static energy.usef.core.data.xml.bean.message.MessagePrecedence.TRANSACTIONAL;

import energy.usef.core.config.Config;
import energy.usef.core.config.ConfigParam;
import energy.usef.core.data.xml.bean.message.FlexRequest;
import energy.usef.core.data.xml.bean.message.MessageMetadata;
import energy.usef.core.data.xml.bean.message.PTU;
import energy.usef.core.data.xml.bean.message.USEFRole;
import energy.usef.core.model.DocumentStatus;
import energy.usef.core.service.business.CorePlanboardBusinessService;
import energy.usef.core.service.business.SequenceGeneratorService;
import energy.usef.core.service.helper.JMSHelperService;
import energy.usef.core.service.helper.MessageMetadataBuilder;
import energy.usef.core.util.XMLUtil;
import energy.usef.core.workflow.dto.FlexRequestDto;
import energy.usef.core.workflow.transformer.DispositionTransformer;

import java.math.BigInteger;
import java.util.List;

import javax.ejb.Singleton;
import javax.enterprise.event.Observes;
import javax.inject.Inject;

import org.joda.time.Period;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Coordinator class for the workflow describing the creation and sending of flex requests from the BRP to the AGR.
 */
@Singleton
public class BrpCreateFlexRequestCoordinator {

    private static final Logger LOGGER = LoggerFactory.getLogger(BrpCreateFlexRequestCoordinator.class);

    @Inject
    private JMSHelperService jmsHelperService;

    @Inject
    private Config config;

    @Inject
    private CorePlanboardBusinessService corePlanboardBusinessService;

    @Inject
    private SequenceGeneratorService sequenceGeneratorService;

    /**
     * {@inheritDoc}
     */
    public void handleEvent(@Observes CreateFlexRequestEvent event) {
        LOGGER.info(LOG_COORDINATOR_START_HANDLING_EVENT, event);

        List<FlexRequestDto> flexRequestDtos = event.getFlexRequestDtos();
        for (FlexRequestDto flexRequestDto : flexRequestDtos) {
            FlexRequest xmlFlexRequest = completeFlexRequestMessage(flexRequestDto);

            // need to link the flex request to a connection group.
            String usefIdentifier = xmlFlexRequest.getMessageMetadata().getRecipientDomain();
            corePlanboardBusinessService.storeFlexRequest(usefIdentifier, xmlFlexRequest, DocumentStatus.SENT, usefIdentifier);
            sendFlexRequestMessage(xmlFlexRequest);
        }
        LOGGER.info(LOG_COORDINATOR_FINISHED_HANDLING_EVENT, event);
    }

    private void sendFlexRequestMessage(FlexRequest flexRequest) {
        jmsHelperService.sendMessageToOutQueue(XMLUtil.messageObjectToXml(flexRequest));
    }

    /**
     * Builds a flex request message with the given parameters.
     *
     * @param flexRequestDto {@link FlexRequestDto} with the basic information.
     * @return a {@link FlexRequest} message.
     */
    private FlexRequest completeFlexRequestMessage(FlexRequestDto flexRequestDto) {
        FlexRequest flexRequest = new FlexRequest();
        flexRequest.setPrognosisOrigin(flexRequestDto.getParticipantDomain());
        flexRequest.setPrognosisSequence(flexRequestDto.getPrognosisSequenceNumber());
        flexRequest.setSequence(sequenceGeneratorService.next());
        flexRequest.setPeriod(flexRequestDto.getPeriod());
        flexRequest.setPTUDuration(Period.minutes(config.getIntegerProperty(ConfigParam.PTU_DURATION)));
        flexRequest.setTimeZone(config.getProperty(ConfigParam.TIME_ZONE));
        flexRequest.setMessageMetadata(buildMessageMetadata(flexRequestDto.getParticipantDomain()));
        flexRequest.setExpirationDateTime(flexRequestDto.getExpirationDateTime());
        flexRequestDto.getPtus().stream().forEach(ptuFlexRequest -> {
            PTU ptu = new PTU();
            ptu.setStart(ptuFlexRequest.getPtuIndex());
            ptu.setDuration(BigInteger.ONE);
            ptu.setDisposition(DispositionTransformer.transformToXml(ptuFlexRequest.getDisposition()));
            ptu.setPower(ptuFlexRequest.getPower());
            flexRequest.getPTU().add(ptu);
        });
        return flexRequest;
    }

    private MessageMetadata buildMessageMetadata(String aggregatorDomain) {
        return new MessageMetadataBuilder().messageID()
                .conversationID()
                .timeStamp()
                .precedence(TRANSACTIONAL)
                .recipientDomain(aggregatorDomain)
                .recipientRole(USEFRole.AGR)
                .senderDomain(config.getProperty(ConfigParam.HOST_DOMAIN))
                .senderRole(USEFRole.BRP)
                .build();
    }
}


text:
$(function() {
	var isLoading = false, start = 10;
	var canLoadMore = $('.post').not('.template').length >= start;

	var $document = $(document);
	var $window = $(window);
	$window.scroll(__handleScroll);

	function __handleScroll() {
		if (isLoading || !canLoadMore)
			return;

		if ($document.height() - $window.scrollTop() <= $window.height())
			__loadMore();
	}

	function __loadMore() {
		console.log('loading at', start);
		isLoading = true;
		$.ajax({
			url: '/blog/',
			data: {
				ajax: 'yes',
				start: start
			},
			dataType: 'json',
			success: __handleLoad
		});
	}

	function __handleLoad(result) {
		$.each(result, function(index, post) {
			var $post = $('.post.template').clone().removeClass('template').insertBefore('.post.template');
			$post.find('.permalink').attr('href', post.permalink);
			$post.find('.title').text(post.title);
			$post.find('.excerpt').text(post.excerpt);
			$post.find('.date').text(post.date);
		});
		start += result.length;
		canLoadMore = result.length == 10;
		isLoading = false;
	}
});


text:
using std::chrono::milliseconds;
using std::chrono::duration;
using std::thread;

class TimedEvent
{
protected:
	duration<long long, std::milli> IntervalTime;
	const unsigned char MaxTicks;
	unsigned char CurTicks;
	bool Abort;
	bool Running;
	thread TimedThread;

private:
	inline virtual void OnTick() = 0;
	inline virtual void OnExpire() = 0;

public:

	inline void StartTimer() { Running = true; }
	inline void StopTimer() { Running = false; }
	inline const bool TimerRunning() const { return Running; }

	//	TODO: Multiply LastRTT here by some small percentage
	//	Based on the variation between the last few values of LastRTT
	//	This will smooth out random hiccups in the network
	inline void NewInterval(const long long &LastRTT) { IntervalTime = milliseconds((const unsigned int)ceil(LastRTT)); }

	//	Constructor
	inline TimedEvent(milliseconds Interval, const unsigned char iMaxTicks) :
		IntervalTime(Interval), MaxTicks(iMaxTicks), CurTicks(0), Abort(false), Running(false),
		TimedThread([&]() {
		//
		//	Make sure this thread uses the least amount of resources possible
		SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);

		while (!Abort)
		{
			if (Running)
			{
				if ((MaxTicks == 0 || CurTicks < MaxTicks))
				{
					OnTick();
				} else { OnExpire(); return; }
			}
			std::this_thread::sleep_for(IntervalTime);
		}	}) {}

	//	Destructor
	inline virtual ~TimedEvent() {
		Running = false;
		Abort = true;
		//	Would like to use .join() here instead
		//	However that throws an odd exception..
		TimedThread.detach();
	}
};


text:
#include "fsl_device_registers.h"
#include "fsl_clock_manager.h"

/*******************************************************************************
 * Definitions
 ******************************************************************************/
/* Table of base addresses for instances. */
const uint32_t g_simBaseAddr[] = SIM_BASE_ADDRS;
const uint32_t g_mcgBaseAddr[] = MCG_BASE_ADDRS;

/*******************************************************************************
 * Code
 ******************************************************************************/

/*FUNCTION**********************************************************************
 *
 * Function Name : CLOCK_SYS_GetSysClkFreq
 * Description   : Internal function to get the system clock frequency
 * This function will check the clock name configuration table for specific
 * chip family and find out the supported clock name for that chip family
 * then it will call the mcg hal function to get the basic system clock,
 * calculate the clock frequency for specified clock name.
 *
 *END**************************************************************************/
clock_manager_error_code_t CLOCK_SYS_GetSysClkFreq(clock_names_t clockName,
                                                        uint32_t *frequency)
{
    /* system clock out divider*/
    uint32_t divider;

    const clock_name_config_t *table = &kClockNameConfigTable[clockName];

    /* check if we need to use a reference clock*/
    if (table->useOtherRefClock)
    {
        /* get other specified ref clock*/
        if ( kClockManagerSuccess != CLOCK_SYS_GetFreq(table->otherRefClockName,
                                                                    frequency) )
        {
            return kClockManagerNoSuchClockName;
        }
    }
    else
    {
        /* get default ref clock */
        *frequency = CLOCK_HAL_GetOutClk(g_mcgBaseAddr[0]);
    }

    /* get system clock divider*/
    if ( CLOCK_HAL_GetDivider(g_simBaseAddr[0], table->dividerName, &divider) == kSimHalSuccess)
    {
        /* get the frequency for the specified clock*/
        *frequency = (*frequency) / (divider + 1);
        return kClockManagerSuccess;
    }
    else
    {
        return kClockManagerNoSuchDivider;
    }
}

/*FUNCTION**********************************************************************
 *
 * Function Name : CLOCK_SYS_GetFreq
 * Description   : Internal function to get the frequency by clock name
 * This function will get/calculate the clock frequency based on clock name
 * and current configuration of clock generator.
 *
 *END**************************************************************************/
clock_manager_error_code_t CLOCK_SYS_GetFreq(clock_names_t clockName,
                                                                   uint32_t *frequency)
{
    clock_manager_error_code_t returnCode = kClockManagerSuccess;

    /* branch according to clock name */
    switch(clockName)
    {
    /* osc clock*/
    case kOsc32kClock:
        *frequency = CPU_XTAL32k_CLK_HZ;
        break;
    case kOsc0ErClock:
#if FSL_FEATURE_MCG_HAS_OSC1
            /* System oscillator 0 drives MCG clock */
        *frequency = CPU_XTAL0_CLK_HZ;
#else
            /* System oscillator 0 drives MCG clock */
        *frequency = CPU_XTAL_CLK_HZ;
#endif
        break;

#if FSL_FEATURE_MCG_HAS_OSC1
    case kOsc1ErClock:
        *frequency = CPU_XTAL1_CLK_HZ;
        break;
#endif

#if FSL_FEATURE_MCG_HAS_IRC_48M
    /* irc clock*/
    case kIrc48mClock:
        *frequency = CPU_INT_IRC_CLK_HZ;
        break;
#endif

    /* rtc clock*/
    case kRtc32kClock:
        *frequency = CPU_XTAL32k_CLK_HZ;
        break;

    case kRtc1hzClock:
        *frequency = CPU_XTAL1hz_CLK_HZ;    // defined in fsl_clock_manager.h for now
        break;

    /* lpo clcok*/
    case kLpoClock:
        *frequency = CPU_LPO_CLK_HZ;       // defined in fsl_clock_manager.h for now
        break;

    /* mcg clocks, calling mcg clock functions */
    case kMcgFfClock:
        *frequency = CLOCK_HAL_GetFllRefClk(g_mcgBaseAddr[0]);
        break;
    case kMcgFllClock:
        *frequency = CLOCK_HAL_GetFllClk(g_mcgBaseAddr[0]);
        break;
#if FSL_FEATURE_MCG_HAS_PLL
    case kMcgPll0Clock:
        *frequency = CLOCK_HAL_GetPll0Clk(g_mcgBaseAddr[0]);
        break;
#endif
    case kMcgOutClock:
        *frequency = CLOCK_HAL_GetOutClk(g_mcgBaseAddr[0]);
        break;
    case kMcgIrClock:
        *frequency = CLOCK_HAL_GetInternalRefClk(g_mcgBaseAddr[0]);
        break;

    case kSDHC0_CLKIN:
        *frequency = SDHC0_CLKIN;            // defined in fsl_clock_manager.h for now
        break;
    case kENET_1588_CLKIN:
        *frequency = ENET_1588_CLKIN;        // defined in fsl_clock_manager.h for now
        break;
    case kEXTAL_Clock:
        *frequency = EXTAL_Clock;            // defined in fsl_clock_manager.h for now
        break;
    case kEXTAL1_Clock:
        *frequency = EXTAL1_Clock;           // defined in fsl_clock_manager.h for now
        break;
    case kUSB_CLKIN:
        *frequency = USB_CLKIN;              // defined in fsl_clock_manager.h for now
        break;

    /* system clocks */
    case kCoreClock:
    case kSystemClock:
    case kPlatformClock:
    case kBusClock:
    case kFlexBusClock:
    case kFlashClock:
        returnCode = CLOCK_SYS_GetSysClkFreq(clockName, frequency);
        break;
        /* reserved value*/
    case kReserved:
    default:
        *frequency = 55555;                     /* for testing use purpose*/
        returnCode = kClockManagerNoSuchClockName;
        break;
    }

    return returnCode;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : CLOCK_SYS_SetSource
 * Description   : Set clock source setting
 * This function will set the settings for specified clock source. Each clock
 * source has its clock selection settings. Refer to reference manual for
 * details of settings for each clock source. Refer to clock_source_names_t
 * for clock sources.
 *
 *END**************************************************************************/
clock_manager_error_code_t CLOCK_SYS_SetSource(clock_source_names_t clockSource,
                                               uint8_t setting)
{
    clock_manager_error_code_t returnCode = kClockManagerSuccess;

    if (CLOCK_HAL_SetSource(g_simBaseAddr[0], clockSource, setting) != kSimHalSuccess)
    {
        returnCode =  kClockManagerNoSuchClockSource;
    }

    return returnCode;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : CLOCK_SYS_GetSource
 * Description   : Get clock source setting
 * This function will get the settings for specified clock source. Each clock
 * source has its clock selection settings. Refer to reference manual for
 * details of settings for each clock source. Refer to clock_source_names_t
 * for clock sources.
 *
 *END**************************************************************************/
clock_manager_error_code_t CLOCK_SYS_GetSource(clock_source_names_t clockSource,
                                               uint8_t *setting)
{
    clock_manager_error_code_t returnCode = kClockManagerSuccess;

    if (CLOCK_HAL_GetSource(g_simBaseAddr[0], clockSource, setting) != kSimHalSuccess)
    {
        returnCode =  kClockManagerNoSuchClockSource;
    }

    return returnCode;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : CLOCK_SYS_SetDivider
 * Description   : Set clock divider setting
 * This function will set the setting for specified clock divider. Refer to
 * reference manual for supported clock divider and value range. Refer to
 * clock_divider_names_t for dividers.
 *
 *END**************************************************************************/
clock_manager_error_code_t CLOCK_SYS_SetDivider(clock_divider_names_t clockDivider,
                                                uint32_t setting)
{
    clock_manager_error_code_t returnCode = kClockManagerSuccess;

    if (CLOCK_HAL_SetDivider(g_simBaseAddr[0], clockDivider, setting) != kSimHalSuccess)
    {
        returnCode = kClockManagerNoSuchDivider;
    }

    return returnCode;
}

/*FUNCTION**********************************************************************
 *
 * Function Name : CLOCK_SYS_GetDivider
 * Description   : Get clock divider setting
 * This function will get the setting for specified clock divider. Refer to
 * reference manual for supported clock divider and value range. Refer to
 * clock_divider_names_t for dividers.
 *
 *END**************************************************************************/
clock_manager_error_code_t CLOCK_SYS_GetDivider(clock_divider_names_t clockDivider,
                                                uint32_t *setting)
{
    clock_manager_error_code_t returnCode = kClockManagerSuccess;

    if (CLOCK_HAL_GetDivider(g_simBaseAddr[0], clockDivider, setting) != kSimHalSuccess)
    {
        returnCode = kClockManagerNoSuchDivider;
    }

    return returnCode;
}

/*******************************************************************************
 * EOF
 ******************************************************************************/


text:
package com.zhangtielei.demos.badge_number.tabs;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.zhangtielei.demos.badge_number.R;
import com.zhangtielei.demos.badge_number.model.BadgeNumber;
import com.zhangtielei.demos.badge_number.tree.BadgeNumberTreeManager;

/**
 * Tab第三个页面
 */
public class ThirdFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.third_fragment, container, false);
    }

    @Override
    public void onActivityCreated(final Bundle instance) {
        super.onActivityCreated(instance);

        getView().findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //清除Badge Numbers
                BadgeNumberTreeManager.getInstance().clearBadgeNumber(BadgeNumber.TYPE_Z1, null);
                BadgeNumberTreeManager.getInstance().clearBadgeNumber(BadgeNumber.TYPE_Z2, null);
            }
        });
    }

}


text:
package hex.tree.xgboost.rabit;

import hex.tree.xgboost.rabit.util.LinkMap;
import ml.dmlc.xgboost4j.java.IRabitTracker;
import water.*;
import water.util.Log;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.*;

public class RabitTrackerH2O implements IRabitTracker {
    public static final int MAGIC = 0xff99;
    private ServerSocketChannel sock;
    private int port = 9091;

    private int workers;

    private Map<String, String> envs = new HashMap<>();

    private volatile RabitTrackerH2OThread trackerThread;

    public RabitTrackerH2O(int workers) {
        super();

        if(workers < 1) {
            throw new IllegalStateException("workers must be greater than or equal to one (1).");
        }

        this.workers = workers;
        Log.debug("Rabit tracker started on port ", this.port);
    }

    @Override
    public Map<String, String> getWorkerEnvs() {
        envs.put("DMLC_NUM_WORKER", String.valueOf(workers));
        envs.put("DMLC_NUM_SERVER", "0");
        envs.put("DMLC_TRACKER_URI", H2O.SELF_ADDRESS.getHostAddress());
        envs.put("DMLC_TRACKER_PORT", Integer.toString(port));
        envs.put("rabit_world_size", Integer.toString(workers));

        return envs;
    }

    @Override
    public boolean start(long timeout) {
        boolean tryToBind = true;
        while(tryToBind) {
            try {
                this.sock = ServerSocketChannel.open();
                this.sock.socket().setReceiveBufferSize(64 * 1024);
                InetSocketAddress isa = new InetSocketAddress(H2O.SELF_ADDRESS, this.port);
                this.sock.socket().bind(isa);
                tryToBind = false;
            } catch (java.io.IOException e) {
                this.port++;
                try {
                    this.sock.close();
                } catch (IOException socketCloseException) {
                    Log.warn("Failed to close Rabit Tracker socket on port ", sock.socket().getLocalPort());
                }
                if(this.port > 9999) {
                    throw new RuntimeException("Failed to bind Rabit tracker to a socket in range 9091-9999", e);
                }
            }
        }

        if(null != this.trackerThread) {
            throw new IllegalStateException("Rabit tracker already started.");
        }
        RabitTrackerH2OThread trackerThread = new RabitTrackerH2OThread(this);
        this.trackerThread = trackerThread;
        trackerThread.start();
        return true;
    }

    @Override
    public void stop() {
        assert this.trackerThread != null;
        try {
                this.trackerThread.interrupt();
            } catch (SecurityException e){
                Log.err("Could not interrupt a thread in RabitTrackerH2O: " + trackerThread.toString());
            }
            this.trackerThread.terminateSocketChannels();
            this.trackerThread = null;

        try {
            this.sock.close();
            this.port = 9091;
        } catch (IOException e) {
            Log.err("Failed to close Rabit tracker socket.", e);
        }
    }

    private class RabitTrackerH2OThread extends Thread {
        private RabitTrackerH2O tracker;

        private LinkMap linkMap;
        private Map<String, Integer> jobToRankMap = new HashMap<>();
        private final List<SocketChannel> socketChannels = new ArrayList<>();

        private RabitTrackerH2OThread(RabitTrackerH2O tracker) {
            setPriority(MAX_PRIORITY-1);
            this.setName("TCP-" + tracker.sock);
            this.tracker = tracker;
        }

        private final void terminateSocketChannels(){
            for (SocketChannel channel : socketChannels) {
                try {
                    channel.close();
                } catch (IOException e) {
                    Log.warn("Unable to close RabitTracerH2O SocketChannel on port ", channel.socket().getPort());
                }
            }
        }

        private static final String PRINT_CMD = "print";
        private static final String SHUTDOWN_CMD = "shutdown";
        private static final String START_CMD = "start";
        private static final String RECOVER_CMD = "recover";
        private static final String NULL_STR = "null";

        @Override
        public void run() {
            Set<Integer> shutdown = new HashSet<>();
            Map<Integer, RabitWorker> waitConn = new HashMap<>();
            List<RabitWorker> pending = new ArrayList<>();
            Queue<Integer> todoNodes = new ArrayDeque<>(tracker.workers);
            while (!interrupted() && shutdown.size() != tracker.workers) {
                try{
                    final SocketChannel channel = tracker.sock.accept(); // Does not proceed when interrupt() is called.
                    socketChannels.add(channel);
                    final RabitWorker worker = new RabitWorker(channel);

                    if (PRINT_CMD.equals(worker.cmd)) {
                        String msg = worker.receiver().getStr();
                        Log.warn("Rabit worker: ", msg);
                        continue;
                    } else if (SHUTDOWN_CMD.equals(worker.cmd)) {
                        assert worker.rank >= 0 && !shutdown.contains(worker.rank);
                        assert !waitConn.containsKey(worker);
                        shutdown.add(worker.rank);
                        channel.socket().close();
                        Log.debug("Received ", worker.cmd, " signal from ", worker.rank);
                        continue;
                    }
                    assert START_CMD.equals(worker.cmd) || RECOVER_CMD.equals(worker.cmd);

                    if (null == linkMap) {
                        assert START_CMD.equals(worker.cmd);
                        linkMap = new LinkMap(tracker.workers);
                        for (int i = 0; i < tracker.workers; i++) {
                            todoNodes.add(i);
                        }
                    } else {
                        assert worker.worldSize == -1 || worker.worldSize == tracker.workers;
                    }

                    if (RECOVER_CMD.equals(worker.cmd)) {
                        assert worker.rank >= 0;
                    }

                    int rank = worker.decideRank(jobToRankMap);
                    if (-1 == rank) {
                        assert todoNodes.size() != 0;
                        pending.add(worker);
                        if (pending.size() == todoNodes.size()) {
                            Collections.sort(pending);
                            for (RabitWorker p : pending) {
                                rank = todoNodes.poll();
                                if (!NULL_STR.equals(p.jobId)) {
                                    jobToRankMap.put(p.jobId, rank);
                                }
                                p.assignRank(rank, waitConn, linkMap);

                                if (p.waitAccept > 0) {
                                    waitConn.put(rank, p);
                                }

                                Log.debug("Received " + p.cmd +
                                        " signal from " + p.host + ":" + p.workerPort +
                                        ". Assigned rank " + p.rank
                                );
                            }
                        }
                        if (todoNodes.isEmpty()) {
                            Log.debug("All " + tracker.workers + " Rabit workers are getting started.");
                        }
                    } else {
                        worker.assignRank(rank, waitConn, linkMap);
                        if (worker.waitAccept > 0) {
                            waitConn.put(rank, worker);
                        }
                    }
                } catch (IOException e) {
                    Log.err("Exception in Rabit tracker.", e);
                }
            }
            Log.debug("All Rabit nodes finished.");
        }
    }

    @Override
    public int waitFor(long timeout) {
        while(null != this.trackerThread && this.trackerThread.isAlive()) {
            try {
                this.trackerThread.join(timeout);
            } catch (InterruptedException e) {
                Log.debug("Rabit tracker thread got suddenly interrupted.", e);
            }
        }
        return 0;
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        stop();
    }
}


text:
package org.apache.camel.component.log;

import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.spring.SpringTestSupport;
import org.junit.Test;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringLogTest extends SpringTestSupport {
    protected Object expectedBody = "Hello there!";
    protected String uri = "direct:start";

    @Test
    public void testSendingCamelExchangeToEndpointResultsInValidApplicationEventAfterTheRefreshEvent() throws Exception {
        MockEndpoint result = resolveMandatoryEndpoint("mock:result", MockEndpoint.class);
        result.expectedMessageCount(1);

        template.sendBody(uri, expectedBody);

        result.assertIsSatisfied();
    }

    protected AbstractXmlApplicationContext createApplicationContext() {
        return new ClassPathXmlApplicationContext("org/apache/camel/component/log/SpringLogTest-context.xml");
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Setup_exp_date extends Root_Controller
{
    private $message;
    public $permissions;
    public $controller_url;
    public function __construct()
    {
        parent::__construct();
        $this->permissions=User_helper::get_permission('Setup_exp_date');
        $this->controller_url='setup_exp_date';
    }
    public function index($action='add')
    {
        if($action=='add')
        {
            $this->system_add();
        }
        elseif($action=='save')
        {
            $this->system_save();
        }
        else
        {
            $this->system_add();
        }
    }
    private function system_add()
    {
        if(isset($this->permissions['action1']) && ($this->permissions['action1']==1))
        {
            $data['title']='Set Expire Date';
            $result=Query_helper::get_info($this->config->item('table_pos_setup_exp_date'),'date_expire',array(),1,0,array('id desc'));
            $data['item']=array();
            if($result)
            {
                $data['item']['date_expire']=System_helper::display_date($result['date_expire']);
            }
            else
            {
                $data['item']['date_expire']=System_helper::display_date(time());
            }

            $ajax['system_page_url']=site_url($this->controller_url.'/index/add');
            $ajax['status']=true;
            $ajax['system_content'][]=array('id'=>'#system_content','html'=>$this->load->view($this->controller_url.'/add_edit',$data,true));
            if($this->message)
            {
                $ajax['system_message']=$this->message;
            }
            $this->json_return($ajax);
        }
        else
        {
            $ajax['status']=false;
            $ajax['system_message']=$this->lang->line('YOU_DONT_HAVE_ACCESS');
            $this->json_return($ajax);
        }
    }
    private function system_save()
    {
        $user=User_helper::get_user();
        if(!$this->check_validation())
        {
            $ajax['status']=false;
            $ajax['system_message']=$this->message;
            $this->json_return($ajax);
        }
        $data=$this->input->post('item');
        $this->db->trans_start(); //DB Transaction Handle START

        $data['date_expire']=System_helper::get_time($data['date_expire']);
        $data['user_created']=$user->user_id;
        $data['date_created']=time();
        Query_helper::add($this->config->item('table_pos_setup_exp_date'),$data);

        $this->db->trans_complete(); //DB Transaction Handle END
        if ($this->db->trans_status()===true)
        {
            $this->message=$this->lang->line('MSG_SAVED_SUCCESS');
            $this->system_add();
        }
        else
        {
            $ajax['status']=false;
            $ajax['system_message']=$this->lang->line('MSG_SAVED_FAIL');
            $this->json_return($ajax);
        }
    }
    private function check_validation()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('item[date_expire]',$this->lang->line('EXPIRE_DATE'),'required');
        if($this->form_validation->run()==false)
        {
            $this->message=validation_errors();
            return false;
        }
        return true;
    }
}


text: code --list-extensions | sort > extensions.txt


text:
      SUBROUTINE XLAENV( ISPEC, NVALUE )
*
*  -- LAPACK auxiliary routine (version 3.1) --
*     Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd..
*     November 2006
*
*     .. Scalar Arguments ..
      INTEGER            ISPEC, NVALUE
*     ..
*
*  Purpose
*  =======
*
*  XLAENV sets certain machine- and problem-dependent quantities
*  which will later be retrieved by ILAENV.
*
*  Arguments
*  =========
*
*  ISPEC   (input) INTEGER
*          Specifies the parameter to be set in the COMMON array IPARMS.
*          = 1: the optimal blocksize; if this value is 1, an unblocked
*               algorithm will give the best performance.
*          = 2: the minimum block size for which the block routine
*               should be used; if the usable block size is less than
*               this value, an unblocked routine should be used.
*          = 3: the crossover point (in a block routine, for N less
*               than this value, an unblocked routine should be used)
*          = 4: the number of shifts, used in the nonsymmetric
*               eigenvalue routines
*          = 5: the minimum column dimension for blocking to be used;
*               rectangular blocks must have dimension at least k by m,
*               where k is given by ILAENV(2,...) and m by ILAENV(5,...)
*          = 6: the crossover point for the SVD (when reducing an m by n
*               matrix to bidiagonal form, if max(m,n)/min(m,n) exceeds
*               this value, a QR factorization is used first to reduce
*               the matrix to a triangular form)
*          = 7: the number of processors
*          = 8: another crossover point, for the multishift QR and QZ
*               methods for nonsymmetric eigenvalue problems.
*          = 9: maximum size of the subproblems at the bottom of the
*               computation tree in the divide-and-conquer algorithm
*               (used by xGELSD and xGESDD)
*          =10: ieee NaN arithmetic can be trusted not to trap
*          =11: infinity arithmetic can be trusted not to trap
*
*  NVALUE  (input) INTEGER
*          The value of the parameter specified by ISPEC.
*
*  =====================================================================
*
*     .. Arrays in Common ..
      INTEGER            IPARMS( 100 )
*     ..
*     .. Common blocks ..
      COMMON             / CLAENV / IPARMS
*     ..
*     .. Save statement ..
      SAVE               / CLAENV /
*     ..
*     .. Executable Statements ..
*
      IF( ISPEC.GE.1 .AND. ISPEC.LE.9 ) THEN
         IPARMS( ISPEC ) = NVALUE
      END IF
*
      RETURN
*
*     End of XLAENV
*
      END


text:
import matplotlib.pyplot as plt
import cfunc
import numpy as np
import sys
import argparse
import os

def position_angle(cat1, cat2, ratag1 = 'ra', dectag1='dec',ratag2='ra',dectag2='dec'):
    dra = (cat1[ratag1] - cat2[ratag2]) * np.cos(cat1[dectag1]*np.pi/180.)
    rad = np.pi/180.

    ddec = (cat1[dectag1] - cat2[dectag2])
    phi = np.arctan2(ddec, dra)
    return phi, dra, ddec

def xMatchStars( catalog= None, ratag = 'ra', dectag = 'dec', starfile='../../Data/2mass_stars_south_bgt20.fits', radius = 100./3600.):
    import esutil
    stars = esutil.io.read(starfile)
    depth=10
    h = esutil.htm.HTM(depth)
    catind,starind, d12 = h.match(catalog[ratag],catalog[dectag],stars['RA'],stars['DEC'],radius,maxmatch=0)
    posAngle,dx,dy = position_angle(catalog[catind], stars[starind],ratag2='RA',dectag2='DEC')
    return catalog[catind], stars[starind], posAngle, dx, dy, d12

def xCorrStars(catalog = None, ratag = 'ra', dectag = 'dec',starfile='../../Data/2mass_stars_south_bgt20.fits', radius = 300./3600., starMagBins = None, thresh = 1.0, nbins=100):

    mCat, mStars,_,_,_, d12 = xMatchStars(catalog=catalog, ratag=ratag, dectag=dectag, starfile=starfile, radius=radius)

    magBinsLower = starMagBins[0:-1]
    magBinsUpper = starMagBins[1:]
    rbins = np.linspace(0,radius,nbins+1)
    bin_centers = (rbins[0:-1] + rbins[1:])/2.
    xi_arr = np.zeros((nbins,magBinsLower.size))

    for lower, upper, i in zip(magBinsLower, magBinsUpper, xrange(magBinsLower.size)):
        these_all = ( mStars['J_M'] > lower) & (mStars['J_M'] <= upper)
        these_bad = these_all & ( np.abs(mCat['mag_auto'] - mCat['mag']) > thresh)
        h_bad,_ = np.histogram(d12[these_bad], bins= rbins, density=True)
        h_all,_ = np.histogram(d12[these_all], bins=rbins, density=True)
        xi_arr[:,i]  = h_bad*1./h_all-1.

    xi_arr[~np.isfinite(xi_arr)] = 0.0
    return xi_arr, bin_centers

def angleBinnedErrors(truthMatched = None, thresh=False):

    mGals, mStars, mAngles, _, _, _ = xMatchStars( catalog=truthMatched )
    var = ( mGals['mag_auto'] - mGals['mag'] ) **2
    dev = ( mGals['mag_auto'] - mGals['mag'] )
    radius = 100./3600. # In degrees
    nbins = 250.
    if thresh is False:
        bins = np.linspace(-radius, radius, nbins)
        thetaHistWeights, thetaBins = np.histogram(mAngles*180./np.pi , bins=bins, weights=dev )
        thetaHistNum,_ = np.histogram(mAngles, bins=thetaBins)
        bin_centers = (thetaBins[0:-1] + thetaBins[1:])/2.
        thetaMean = thetaHistWeights/thetaHistNum
        return thetaMean,bin_centers
    else:
        bad = np.sqrt(var) > thresh
        # What fraction of the badness is accounted for by stars?

        bins = np.linspace(-radius,radius,nbins)
        thetaHist,thetaBins = np.histogram(mAngles[bad]*180./np.pi,bins=bins,density=True)
        bin_centers = (thetaBins[0:-1] + thetaBins[1:])/2.
        return thetaHist,bin_centers

def binned2dErrors(truthMatched=None, thresh=False):

    mGals, mStars, _, dx, dy, _ = xMatchStars( catalog=truthMatched )
    var = ( mGals['mag_auto'] - mGals['mag'] ) **2
    dev = ( mGals['mag_auto'] - mGals['mag'] )

    radius = 100./3600. #in degrees
    nbins = 100.
    bins = np.linspace(-radius,radius,nbins)

    if thresh is False:
        errHistWeights, xBins,yBins = np.histogram2d(dx,dy, bins=(bins,bins),weights=dev )
        errHistNumber, xBins,yBins = np.histogram2d(dx,dy, bins=(bins,bins) )
        xbin_centers = (xBins[0:-1] + xBins[1:])/2.
        ybin_centers =  (yBins[0:-1] + yBins[1:])/2.
        errMean = errHistWeights/ errHistNumber
        return errMean,xbin_centers, ybin_centers
    else:
        bad = np.sqrt(var) > thresh
        errHist,xBins, yBins = np.histogram2d(dx[bad],dy[bad] , bins=(bins,bins), normed=True)
        xbin_centers = (xBins[0:-1] + xBins[1:])/2.
        ybin_centers =  (yBins[0:-1] + yBins[1:])/2.
        return errHist,xbin_centers, ybin_centers

def main(argv):
    parser = argparse.ArgumentParser(description = 'Perform magnitude distribution inference on DES data.')
    parser.add_argument('filter',help='filter name',choices=['g','r','i','z','Y'])
    parser.add_argument("-r","--reload",help='reload catalogs from DESDB', action="store_true")
    parser.add_argument("-np","--no_pca",help='Do not use pca-smoothed likelihoods in reconstruction.', action="store_true")
    args = parser.parse_args(argv[1:])
    band = args.filter
    no_pca = args.no_pca

    # Get the catalogs.
    print "performing inference in band: "+args.filter
    print "Reloading from DESDM:", args.reload
    des, sim, truthMatched, truth, tileInfo = cfunc.getCatalogs(reload = args.reload, band = args.filter)
    print "Excluding regions Eli says are bad."
    des, sim, truthMatched, truth = cfunc.excludeBadRegions(des,sim, truthMatched, truth,band=band)
    print sim.size

    # Now, how much of what's left over comes from diffraction spikes?
    errs, angle = angleBinnedErrors( truthMatched = truthMatched,thresh=False)
    errsThresh, angleThresh = angleBinnedErrors(truthMatched = truthMatched, thresh= 2.)
    fig, (ax1,ax2) = plt.subplots(nrows=1,ncols=2,figsize = (21,7))
    ax1.plot(angle* 180/np.pi,errs)
    ax1.set_xlabel('position angle relative to nearest bright star (degrees)')
    ax1.set_ylabel('average Balrog magnitude error')
    ax2.plot(angleThresh*180/np.pi, errsThresh)
    ax2.set_xlabel('position angle relative to nearest bright star (degrees)')
    ax2.set_ylabel('fraction of sample with catastrophic mag. err ( |err|>2 ) ')
    fig.savefig("magnitude_error_stars_xcorr.png")

    # Now, how much of what's left over comes from diffraction spikes?
    avgErrs2d, xcen,ycen = binned2dErrors( truthMatched = truthMatched,thresh=False)
    threshErrs2d, xcenThresh,ycenThresh = binned2dErrors( truthMatched = truthMatched,thresh=1.0)
    fig, (ax1, ax2, ax3) = plt.subplots(nrows=1,ncols=3, figsize=(21,7))
    xcen = 3600*xcen
    ycen = 3600*ycen
    xcenThresh = 3600*xcenThresh
    ycenThresh = 3600*ycenThresh
    ax1.imshow(avgErrs2d, extent= [np.min(xcen), np.max(xcen), np.min(ycen),np.max(ycen)],origin="lower",aspect="equal")
    ax1.set_xlabel('dra from star (arcsec)')
    ax1.set_ylabel('ddec from star (arcsec) ')
    ax1.set_title("avg \n  magnitude error")
    im2 = ax2.imshow(threshErrs2d, extent= [np.min(xcenThresh), np.max(xcenThresh), np.min(ycenThresh),np.max(ycenThresh)],origin="lower",aspect="equal")
    ax2.set_xlabel('dra from star (arcsec)')
    ax2.set_ylabel('ddec from star (arcsec) ')
    ax2.set_title("positions of catastrophic \n mag. errors")
    fig.colorbar(im2,ax=ax2)

    nMagBins = 8
    magbins = np.linspace(5. ,18. ,nMagBins+1)
    xi, r = xCorrStars(catalog = truthMatched, starMagBins =magbins, thresh = 1.0, nbins=50)
    for i in xrange(nMagBins):
        label = str(np.round(magbins[i],decimals=1)) + ' < J_M < ' + str(np.round(magbins[i+1],decimals=1))
        ax3.plot(r*3600., np.arcsinh(xi[:,i]), label = label,color=plt.cm.cool(i*(1./nMagBins)))

    ax3.set_ylabel('arcsinh(xi)')
    ax3.set_xlabel('sep. (arcsec)')
    ax3.set_ylim([-1,2])
    ax3.axhline(0.,linestyle='--',color='red')
    ax3.legend(bbox_to_anchor=(0.9, 1), loc=2, borderaxespad=0.)
    #ax3.legend(loc='best')
    np.savez("star_proximity_effects",xi=xi,r=r,magbins=magbins)

    fig.savefig("magnitude_error_stars_2d"+band+".png")

if __name__ == "__main__":
    import pdb, traceback
    try:
        main(sys.argv)
    except:
        thingtype, value, tb = sys.exc_info()
        traceback.print_exc()
        pdb.post_mortem(tb)


text:
@interface WebViewController() <UISearchBarDelegate, WKNavigationDelegate>

@property (weak, nonatomic) IBOutlet UIButton *onepasswordFillButton;
@property (weak, nonatomic) IBOutlet UIView *webViewContainer;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (strong, nonatomic) WKWebView *webView;

@end

@implementation WebViewController

#pragma mark - Life Cycle

- (void)viewDidLoad {
	[super viewDidLoad];

	NSBundle *onePasswordExtensionBundle = [NSBundle bundleForClass:[OnePasswordExtension class]];
	UIImage *onePasswordToolbarImage = [UIImage imageNamed:@"onepassword-toolbar" inBundle:onePasswordExtensionBundle compatibleWithTraitCollection:self.traitCollection];
	[self.onepasswordFillButton setImage:onePasswordToolbarImage forState:UIControlStateNormal];
	[self.onepasswordFillButton setHidden:![[OnePasswordExtension sharedExtension] isAppExtensionAvailable]];

	WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
	self.webView = [[WKWebView alloc] initWithFrame:self.webViewContainer.bounds configuration:configuration];
	self.webView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
	self.webView.navigationDelegate = self;
	[self.webViewContainer addSubview:self.webView];

	NSString *htmlFilePath = [[NSBundle mainBundle] pathForResource:@"welcome" ofType:@"html"];
	NSError *htmlStringError = nil;
	NSString* htmlString = [NSString stringWithContentsOfFile:htmlFilePath encoding:NSUTF8StringEncoding error:&htmlStringError];

	if (htmlString.length == 0) {
		NSLog(@"Failed to obtain the html string from file %@ with error: <%@>", htmlFilePath, htmlStringError);
	}

	[self.webView loadHTMLString:htmlString baseURL:nil];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];

	if (NO == [[OnePasswordExtension sharedExtension] isAppExtensionAvailable]) {
		UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
		}];

		UIAlertAction *get1PasswordAction = [UIAlertAction actionWithTitle:@"Get 1Password" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
			[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/ca/app/1password-password-manager/id568903335?mt=8"]];
		}];

		UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"1Password is not installed" message:@"Get 1Password from the App Store" preferredStyle:UIAlertControllerStyleAlert];

		[alertController addAction:cancelAction];
		[alertController addAction:get1PasswordAction];

		[self presentViewController:alertController animated:YES completion:nil];
	}
}

#pragma mark - Actions

- (IBAction)fillUsing1Password:(id)sender {
	[[OnePasswordExtension sharedExtension] fillItemIntoWebView:self.webView forViewController:self sender:sender showOnlyLogins:NO completion:^(BOOL success, NSError *error) {
		if (!success) {
			NSLog(@"Failed to fill into webview: <%@>", error);
		}
	}];
}

- (IBAction)goBack:(id)sender {
	WKNavigation *navigation = [self.webView goBack];

	if (navigation != nil) {
		NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"welcome" ofType:@"html"];
		NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
		[self.webView loadHTMLString:htmlString baseURL:nil];

	}
}

- (IBAction)goForward:(id)sender {
	[self.webView goForward];
}

#pragma mark - UISearchBarDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
	[self performSearch:searchBar.text];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
	[self performSearch:searchBar.text];
}

- (void)handleSearch:(UISearchBar *)searchBar {
	[self performSearch:searchBar.text];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
	[self performSearch:searchBar.text];
}

#pragma mark - Convenience Methods

- (void)performSearch:(NSString *)text {
	NSString *lowercaseText = [text lowercaseStringWithLocale:[NSLocale currentLocale]];
	NSURL *URL = nil;

	BOOL hasSpaces = [lowercaseText rangeOfString:@" "].location != NSNotFound;
	BOOL hasDots = [lowercaseText rangeOfString:@"."].location != NSNotFound;
	BOOL search = !hasSpaces || !hasDots;
	if (search) {
		BOOL hasScheme = [lowercaseText hasPrefix:@"http:"] || [lowercaseText hasPrefix:@"https:"];
		if (hasScheme) {
			URL = [NSURL URLWithString:lowercaseText];
		}
		else {
			URL = [NSURL URLWithString:[@"https://" stringByAppendingString:lowercaseText]];
		}
	}

	if (URL == nil) {
		NSURLComponents *URLComponents = [[NSURLComponents alloc] init];
		URLComponents.scheme = @"https";
		URLComponents.host = @"www.google.com";
		URLComponents.path = @"/search";

		NSURLQueryItem *queryItem = [NSURLQueryItem queryItemWithName:@"q" value:text];
		URLComponents.queryItems = @[queryItem];

		URL = URLComponents.URL;
	}

	self.searchBar.text = [URL absoluteString];
	[self.searchBar resignFirstResponder];

	NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
	[self.webView loadRequest:request];
}

#pragma mark - WKNavigationDelegate

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
	self.searchBar.text = webView.URL.absoluteString;

	if ([self.searchBar.text isEqualToString:@"about:blank"]) {
		self.searchBar.text = @"";
	}
}

@end


text:
@interface PodsDummy_JHUD : NSObject
@end
@implementation PodsDummy_JHUD
@end


text:
    <nz-select (ngModelChange)="select($event)" [compareWith]="layoutComparator" [ngModel]="layout" fxFlex="1 1 auto">
      <nz-option *ngFor="let availableLayout of allLayouts" [nzLabel]="availableLayout.name"
                 [nzValue]="availableLayout"></nz-option>
    </nz-select>

      <button (click)="addLayout()" nz-button nzType="primary">

      </button>
      <button (click)="save(layout)" [disabled]="layout.$key === undefined || !dirty" nz-button
              nzType="primary">
        save
      </button>
      <button (nzOnConfirm)="deleteLayout(layout.$key)" [disabled]="layout.$key === undefined" [nzTitle]="'Confirm' | translate" nz-button
              nz-popconfirm nzType="danger">

      </button>

      <button (cbOnSuccess)="layoutCopied()" [cbContent]="layout.base64" [nzTitle]="'LIST_DETAILS.LAYOUT_DIALOG.Import_string' | translate" ngxClipboard nz-button
              nz-tooltip>

      </button>
      <button (click)="importLayout()" [nzTitle]="'LIST_DETAILS.LAYOUT_DIALOG.Import_layout' | translate"
              nz-button
              nz-tooltip>

      </button>

  <nz-alert *ngIf="layout.default" [nzMessage]="'LIST_DETAILS.LAYOUT_DIALOG.Default_readonly_message' | translate"
            class="default-warning" nzShowIcon nzType="info"></nz-alert>

    <nz-input-group nzPrefixIcon="anticon anticon-edit">
      <input [(ngModel)]="layout.name" (ngModelChange)="dirty = true" [disabled]="layout.default"
             nz-input type="text">
    </nz-input-group>
    <button (click)="editRowButtons(layout)" [disabled]="layout.default" nz-button nzBlock>
      {{'LIST_DETAILS.LAYOUT_DIALOG.Edit_row_buttons_display' | translate}}
    </button>
    <button (click)="openReorderPopup(layout)" [disabled]="layout.default" nz-button nzBlock>
      {{'LIST_DETAILS.LAYOUT_DIALOG.Reorder_panels' | translate}}
    </button>
    <nz-card [nzTitle]="'LIST_DETAILS.LAYOUT_DIALOG.Global_options' | translate">

          {{"LIST.Enable_crystals_tracking" | translate}}

          {{"LIST.Always_show_inventory" | translate}}

          {{"LIST.Show_craftable_amount" | translate}}

          {{"LIST.Show_vendors" | translate}}

    </nz-card>
    <nz-card [nzTitle]="'Items' | translate">

          {{'LIST_DETAILS.LAYOUT.Order_by' | translate}}
          <nz-select [(ngModel)]="layout.recipeOrderBy"
                     (ngModelChange)="dirty = true"
                     [nzDisabled]="layout.default">
            <nz-option nzLabel="NAME" nzValue="NAME"></nz-option>
            <nz-option nzLabel="NONE" nzValue="NONE"></nz-option>
            <nz-option nzLabel="LEVEL" nzValue="LEVEL"></nz-option>
            <nz-option nzLabel="JOB" nzValue="JOB"></nz-option>
            <nz-option nzLabel="INGAME_LOG" nzValue="INGAME_LOG"></nz-option>
            <nz-option nzLabel="SLOT" nzValue="SLOT"></nz-option>
          </nz-select>
          <nz-select [(ngModel)]="layout.recipeOrder"
                     (ngModelChange)="dirty = true"
                     [nzDisabled]="layout.default">
            <nz-option [nzValue]="0" nzLabel="ASC"></nz-option>
            <nz-option [nzValue]="1" nzLabel="DESC"></nz-option>
          </nz-select>

        <nz-radio-group (ngModelChange)="setItemsLayoutType(layout, $event)"
                        [ngModel]="getItemsLayoutType(layout)"
                        [nzDisabled]="layout.default">
          {{"Default" | translate}}
          {{"Zone_breakdown" | translate}}
        </nz-radio-group>
        {{"Hide_completed" |
          translate}}
        {{"Hide_zone_duplicates" | translate}}

    </nz-card>

      <button (click)="addPanel(layout)" [disabled]="layout.default" nz-button nzBlock
              nzType="primary">
         {{'LIST_DETAILS.LAYOUT_DIALOG.Add_panel' | translate}}
      </button>

        <app-layout-editor-row (delete)="removePanel(layout, row)" (rowChange)="updatePanel(layout, $event)"
                               [readonly]="layout.default"
                               [row]="row"></app-layout-editor-row>


text:
package agent

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"os"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/gin-gonic/gin"

	"github.com/Dataman-Cloud/swan/agent/ipam"
	"github.com/Dataman-Cloud/swan/agent/janitor"
	"github.com/Dataman-Cloud/swan/agent/resolver"
	"github.com/Dataman-Cloud/swan/config"
	"github.com/Dataman-Cloud/swan/mole"
)

type Agent struct {
	config      *config.AgentConfig
	resolver    *resolver.Resolver
	janitor     *janitor.JanitorServer
	ipam        *ipam.IPAM
	clusterNode *mole.Agent
}

func New(cfg *config.AgentConfig) *Agent {
	agent := &Agent{
		config:   cfg,
		resolver: resolver.NewResolver(cfg.DNS, cfg.Janitor.AdvertiseIP),
		janitor:  janitor.NewJanitorServer(cfg.Janitor),
		ipam:     ipam.New(cfg.IPAM),
	}
	return agent
}

// IPAMSetIPPool called via CLI
func (agent *Agent) IPAMSetIPPool(start, end string) error {
	if !agent.config.IPAM.Enabled {
		return errors.New("agent ipam disabled")
	}

	if agent.ipam == nil {
		return errors.New("ipam not initilized yet")
	}

	if err := agent.ipam.StoreSetup(); err != nil {
		return err
	}

	pool := &ipam.IPPoolRange{
		IPStart: start,
		IPEnd:   end,
	}

	if err := pool.Valid(); err != nil {
		return err
	}

	if err := agent.ipam.SetIPPool(pool); err != nil {
		return err
	}

	os.Stdout.Write([]byte("OK\r\n"))
	return nil
}

func (agent *Agent) StartAndJoin() error {
	// detect healhty leader firstly
	addr, err := agent.detectLeaderAddr()
	if err != nil {
		return err
	}

	// sync all of dns & proxy records on start up
	if err := agent.syncFull(addr); err != nil {
		return fmt.Errorf("full sync manager's records error: %v", err)
	}

	// startup pong & resolver & janitor
	go func() {
		http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte(`pong`))
		})

		if err := http.ListenAndServe(agent.config.Listen, nil); err != nil {
			log.Fatalln("httpd pong occurred fatal error:", err)
		}
	}()

	if agent.config.DNS.Enabled {
		go func() {
			if err := agent.resolver.Start(); err != nil {
				log.Fatalln("resolver occured fatal error:", err)
			}
		}()
	}

	if agent.config.Janitor.Enabled {
		go func() {
			if err := agent.janitor.Start(); err != nil {
				log.Fatalln("janitor occured fatal error:", err)
			}
		}()
	}

	if agent.config.IPAM.Enabled {
		go func() {
			if err := agent.ipam.Serve(); err != nil {
				log.Fatalln("ipam occured fatal error:", err)
			}
		}()
	}

	// serving protocol & Api with underlying mole
	var (
		delayMin = time.Second      // min retry delay 1s
		delayMax = time.Second * 60 // max retry delay 60s
		delay    = delayMin         // retry delay
	)
	for {
		err := agent.Join()
		if err != nil {
			log.Errorln("agent Join() error:", err)
			delay *= 2
			if delay > delayMax {
				delay = delayMax // reset delay to max
			}
			log.Warnln("agent ReJoin in", delay.String())
			time.Sleep(delay)
			continue
		}

		l := agent.NewListener()

		go func(l net.Listener) {
			err := agent.ServeProtocol()
			if err != nil {
				log.Errorln("agent ServeProtocol() error:", err)
				l.Close() // close the listener -> the ServeApi() return with error -> Rejoin triggered.
			}
		}(l)

		log.Println("agent Joined succeed, ready ...")
		delay = delayMin // reset dealy to min
		err = agent.ServeApi(l)
		if err != nil {
			log.Errorln("agent ServeApi() error:", err)
		}

		log.Warnln("agent Rejoin ...")
		time.Sleep(time.Second)
	}

	return nil
}

func (agent *Agent) Join() error {
	// detect healthy leader
	addr, err := agent.detectLeaderAddr()
	if err != nil {
		return err
	}
	masterURL, err := url.Parse(addr)
	if err != nil {
		return err
	}

	// setup & join
	agent.clusterNode = mole.NewAgent(&mole.Config{
		Role:   mole.RoleAgent,
		Master: masterURL,
	})

	return agent.clusterNode.Join()
}

func (agent *Agent) NewListener() net.Listener {
	return agent.clusterNode.NewListener()
}

func (agent *Agent) ServeProtocol() error {
	return agent.clusterNode.ServeProtocol()
}

func (agent *Agent) ServeApi(l net.Listener) error {
	log.Println("agent api in serving ...")

	httpd := &http.Server{
		Handler: agent.NewHTTPMux(),
	}
	return httpd.Serve(l)
}

func (agent *Agent) serveProxy(ctx *gin.Context) {
	var (
		r = ctx.Request
		w = ctx.Writer
	)

	hijacker, ok := w.(http.Hijacker)
	if !ok {
		w.WriteHeader(500)
		return
	}

	connMaster, _, err := hijacker.Hijack()
	if err != nil {
		w.WriteHeader(500)
		return
	}
	defer connMaster.Close()

	connBackend, err := agent.dialBackend()
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	defer connBackend.Close()

	go func() {
		r.Write(connBackend)
	}()

	io.Copy(connMaster, connBackend)
}

func (agent *Agent) dialBackend() (net.Conn, error) {
	return net.Dial("unix", "/var/run/docker.sock")
}

func (agent *Agent) detectLeaderAddr() (string, error) {
	for _, addr := range agent.config.JoinAddrs {
		resp, err := http.Get("http://" + addr + "/v1/leader")
		if err != nil {
			log.Warnf("detect swan manager leader %s error %v", addr, err)
			continue
		}
		defer resp.Body.Close() // prevent fd leak

		var info struct {
			Leader string `json:"leader"`
		}
		if err := json.NewDecoder(resp.Body).Decode(&info); err != nil {
			log.Warnf("detect swan manager leader %s error %v", addr, err)
			continue
		}

		log.Infof("detect swan manager leader %s succeed", info.Leader)
		return "http://" + info.Leader, nil
	}

	return "", errors.New("all of swan manager unavailable")
}


text:
"""
Multi-Window Plot
~~~~~~~~~~~~~~~~~

Subplotting: having multiple scenes in a single window
"""

import pyvista as pv
from pyvista import examples

###############################################################################
# This example shows how to create a multi-window plotter by specifying the
# ``shape`` parameter.  The window generated is a two by two window by setting
# ``shape=(2, 2)``. Use the :func:`pyvista.BasePlotter.subplot` function to
# select the subplot you wish to be the active subplot.

plotter = pv.Plotter(shape=(2, 2))

plotter.subplot(0, 0)
plotter.add_text("Render Window 0", font_size=30)
plotter.add_mesh(examples.load_globe())

plotter.subplot(0, 1)
plotter.add_text("Render Window 1", font_size=30)
plotter.add_mesh(pv.Cube(), show_edges=True, color="tan")

plotter.subplot(1, 0)
plotter.add_text("Render Window 2", font_size=30)
sphere = pv.Sphere()
plotter.add_mesh(sphere, scalars=sphere.points[:, 2])
plotter.add_scalar_bar("Z")
# plotter.add_axes()
plotter.add_axes(interactive=True)

plotter.subplot(1, 1)
plotter.add_text("Render Window 3", font_size=30)
plotter.add_mesh(pv.Cone(), color="g", show_edges=True)
plotter.show_bounds(all_edges=True)

# Display the window
plotter.show()

###############################################################################
plotter = pv.Plotter(shape=(1, 2))

# Note that the (0, 0) location is active by default
# load and plot an airplane on the left half of the screen
plotter.add_text("Airplane Example\n", font_size=30)
plotter.add_mesh(examples.load_airplane(), show_edges=False)

# load and plot the uniform data example on the right-hand side
plotter.subplot(0, 1)
plotter.add_text("Uniform Data Example\n", font_size=30)
plotter.add_mesh(examples.load_uniform(), show_edges=True)

# Display the window
plotter.show()

###############################################################################
# Split the rendering window in half and subdivide it in a nr. of vertical or
# horizontal subplots.

# This defines the position of the vertical/horizontal splitting, in this
# case 40% of the vertical/horizontal dimension of the window
pv.global_theme.multi_rendering_splitting_position = 0.40

# shape="3|1" means 3 plots on the left and 1 on the right,
# shape="4/2" means 4 plots on top of 2 at bottom.
plotter = pv.Plotter(shape='3|1', window_size=(1000, 1200))

plotter.subplot(0)
plotter.add_text("Airplane Example")
plotter.add_mesh(examples.load_airplane(), show_edges=False)

# load and plot the uniform data example on the right-hand side
plotter.subplot(1)
plotter.add_text("Uniform Data Example")
plotter.add_mesh(examples.load_uniform(), show_edges=True)

plotter.subplot(2)
plotter.add_text("A Sphere")
plotter.add_mesh(pv.Sphere(), show_edges=True)

plotter.subplot(3)
plotter.add_text("A Cone")
plotter.add_mesh(pv.Cone(), show_edges=True)

# Display the window
plotter.show()

###############################################################################
# To get full flexibility over the layout grid, you can define the relative
# weighting of rows and columns and register groups that can span over multiple
# rows and columns. A group is defined through a tuple ``(rows,cols)`` of row
# and column indices or slices. The group always spans from the smallest to the
# largest (row or column) id that is passed through the list or slice.

# numpy is imported for a more convenient slice notation through np.s_
import numpy as np

shape = (5, 4)  # 5 by 4 grid
row_weights = [0.5,1,1,2,1] # First row is half the size and fourth row is double the size of the other rows
col_weights = [1,1,0.5,2] # Third column is half the size and fourth column is double size of the other columns
groups = [
    (0,np.s_[:]),      # First group spans over all columns of the first row (0)
    ([1,3],0),         # Second group spans over row 1-3 of the first column (0)
    (np.s_[2:],[1,2]), # Third group spans over rows 2-4 and columns 1-2
    (slice(1,-1),3)    # Fourth group spans over rows 1-3 of the last column (3)
]

plotter = pv.Plotter(shape=shape,row_weights=row_weights,col_weights=col_weights,groups=groups)

# A grouped subplot can be activated through any of its composing cells using
# the :func:`pyvista.BasePlotter.subplot` function.

# Access all subplots and groups and plot something:
plotter.subplot(0,0)
plotter.add_text("Group 1")
plotter.add_mesh(pv.Cylinder(direction=[0,1,0],height=20))
plotter.view_yz()
plotter.camera.Zoom(10)
plotter.camera_set = True

plotter.subplot(2,0)
plotter.add_text("Group 2")
plotter.add_mesh(pv.ParametricCatalanMinimal(), show_edges=False, color="tan")
plotter.view_isometric()
plotter.camera.Zoom(2)
plotter.camera_set = True

plotter.subplot(2,1)
plotter.add_text("Group 3")
plotter.add_mesh(examples.load_uniform(), show_edges=True)

plotter.subplot(1,3)
plotter.add_text("Group 4")
plotter.add_mesh(examples.load_globe())

plotter.subplot(1,1)
plotter.add_text("Cell (1,1)")
sphere = pv.Sphere()
plotter.add_mesh(sphere, scalars=sphere.points[:, 2])
plotter.add_scalar_bar("Z")
plotter.add_axes(interactive=True)

plotter.subplot(1,2)
plotter.add_text("Cell (1,2)")
plotter.add_mesh(pv.Cone(), show_edges=True)

plotter.subplot(4,0)
plotter.add_text("Cell (4,0)")
plotter.add_mesh(examples.load_airplane(), show_edges=False)

plotter.subplot(4,3)
plotter.add_text("Cell (4,3)")
plotter.add_mesh(pv.Cube(), show_edges=True, color="tan")

# Display the window
plotter.show()


text:
//
// ISharpDevelopPackageManager.cs
//
// Author:
//   Matt Ward <ward.matt@gmail.com>
//
// Copyright (C) 2012-2013 Matthew Ward
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using NuGet;

namespace ICSharpCode.PackageManagement
{
	public interface ISharpDevelopPackageManager : IPackageManager
	{
		ISharpDevelopProjectManager ProjectManager { get; }

		void InstallPackage(IPackage package, InstallPackageAction installAction);
		void UninstallPackage(IPackage package, UninstallPackageAction uninstallAction);
		void UpdatePackage(IPackage package, UpdatePackageAction updateAction);
		void UpdatePackages(UpdatePackagesAction updateAction);
		void UpdatePackageReference(IPackage package, IUpdatePackageSettings settings);

		IEnumerable<PackageOperation> GetInstallPackageOperations(IPackage package, InstallPackageAction installAction);
		IEnumerable<PackageOperation> GetUpdatePackageOperations(IEnumerable<IPackage> packages, IUpdatePackageSettings settings);

		void RunPackageOperations(IEnumerable<PackageOperation> operations);
	}
}


text:
using ConfluxWritersDay.Web.Models;
using NullGuard;

namespace ConfluxWritersDay.Web.ViewModels.Home
{
    [NullGuard(ValidationFlags.Methods | ValidationFlags.Arguments | ValidationFlags.OutValues | ValidationFlags.ReturnValues)]
    public class RegistrationViewModel : Registration
    { }
}


text:
<template name="tmp_body">

Mateo

Frontend Template for fast build Web Apps use Meteorjs.

Github

</template>


text:
var http = require('http');
var LongPollingJSFun = {};
LongPollingJSFun.eventid = 0;
LongPollingJSFun.pending = false;
LongPollingJSFun.deplyed = true;
LongPollingJSFun.options = {
    host: 'localhost',
    port: '8080',
    path: '/webresources',
    method: 'GET',
    headers: {'Authorization': 'Basic ',
        'Accept': 'application/json',
        'Content-Type': 'application/json'}
};

LongPollingJSFun.sethttpOption = function (host, port, path, method, user, pwd) {
    LongPollingJSFun.options.host = host;
    LongPollingJSFun.options.port = port;
    LongPollingJSFun.options.path = path;
    LongPollingJSFun.options.method = method;
    LongPollingJSFun.options.headers.Authorization = 'Basic ' + new Buffer(user + ":" + pwd).toString('base64');
    LongPollingJSFun.options.headers.Accesstoken = '';
    return LongPollingJSFun.options;
};

LongPollingJSFun.sethttpOption_token = function (host, port, path, method, token) {
    LongPollingJSFun.options.host = host;
    LongPollingJSFun.options.port = port;
    LongPollingJSFun.options.path = path;
    LongPollingJSFun.options.method = method;
    LongPollingJSFun.options.headers.Authorization = '';
    LongPollingJSFun.options.headers.Accesstoken = 'Bearer ' + token;
    return LongPollingJSFun.options;
};

LongPollingJSFun.submit = function (url, port, path, method, username, pwd, jsonStringData, res_success, res_error) {
//    var options = this.sethttpOption(url, port, path, method, username, pwd);
    var req = http.request(LongPollingJSFun.options, function (response) {
        var str = '';
        response.on('data', function (chunk) {
            str += chunk;
        });
        response.on('end', function () {
            res_success(str);
        });
    }).on('error', function (error) {
        res_error(error.errno);
    });
    if (method !== 'get')
        req.write(jsonStringData);
    req.end();
};

LongPollingJSFun.getjsoncontentData = function () {
    var objitem = new Object();
    objitem.item = {"@name": "lasteventid", "@value": "" + LongPollingJSFun.eventid + ""};
    var objreq = new Object();
    objreq.request = objitem;
    return JSON.stringify(objreq);
};
module.exports = function (RED) {
    function LongPollingNode(config) {
        RED.nodes.createNode(this, config);
        var node = this;
        this.on('close', function(){
//            LongPollingJSFun.eventid = 0;
//            LongPollingJSFun.pending = false;
            LongPollingJSFun.deplyed = true;
            node.status({});
        });
        this.on('input', function (msg) {
            if (LongPollingJSFun.pending)
                return;
            LongPollingJSFun.deplyed = false;
            var url = msg.url;
            var port = msg.port;
            var username = msg.username;
            var pwd = msg.pwd;
            var statusNode = this;
            var flag = msg.flag;
            var encodestr = msg.encodestr;
            var token = msg.token;
            var connectype = msg.connectype;
            if (flag === 'encode') {
                if (typeof url === 'undefined' || typeof port === 'undefined' || url === '' || port === '') {
                    statusNode.status({fill: "red", shape: "ring", text: "miss server parameters"});
                    return;
                }
                switch (connectype) {
                    case 'basic':
                        var decoder = new Buffer(encodestr, 'base64').toString();
                        username = decoder.split("$")[0];
                        pwd = decoder.split("$")[1];
                        LongPollingJSFun.options = LongPollingJSFun.sethttpOption(url, port, '/webresources/EventMgmt/long-polling/', 'post', username, pwd);
                        break;
                    case 'oauth':
                        LongPollingJSFun.options = LongPollingJSFun.sethttpOption_token(url, port, '/webresources/EventMgmt/long-polling/', 'post', token);
                        break;
                }
            } else {
                if (typeof url === 'undefined' || typeof port === 'undefined' || typeof username === 'undefined' || typeof pwd === 'undefined' ||
                        url === '' || port === '' || username === '' || pwd === '') {
                    statusNode.status({fill: "red", shape: "ring", text: "miss server parameters"});
                    return;
                }
                LongPollingJSFun.options = LongPollingJSFun.sethttpOption(url, port, '/webresources/EventMgmt/long-polling/', 'post', username, pwd);
            }
            statusNode.status({fill: "green", shape: "ring", text: "pending"});
            LongPollingJSFun.pending = true;
            longpolling(node, msg, url, port, username, pwd, statusNode);
        });
    }

    function longpolling(node, msg, url, port, username, pwd, statusNode) {
        LongPollingJSFun.submit(url, port, '/webresources/EventMgmt/long-polling/', 'post', username, pwd, LongPollingJSFun.getjsoncontentData(), function (res_success) {
            try {
                var obj = JSON.parse(res_success);
                var length = parseInt(obj['result']['item'].length);
                for (var index = 0; index < length; index++) {
                    msg.payload = obj['result']['item'][index];
                    node.send(msg);
                    LongPollingJSFun.eventid = obj['result']['item'][index]['eventID'];
                }
            } catch (e) {
            }

            if(!LongPollingJSFun.deplyed){
//                LongPollingJSFun.pending = false;
//                LongPollingJSFun.deplyed = true;
                longpolling(node, msg, url, port, username, pwd, statusNode);
            }else{
                LongPollingJSFun.eventid = 0;
                LongPollingJSFun.pending = false;
            }
        }, function (res_error) {
            statusNode.status({fill: "red", shape: "ring", text: res_error});
//            LongPollingJSFun.pending = false;
        });
    }
    ;

    RED.nodes.registerType("LongPolling", LongPollingNode);
};


text:
using System;
using XenAPI;

namespace XenAdmin.Actions
{
    /// <summary>
    /// This action installs the PV tools on a selected windows VM.
    /// </summary>
    public class InstallPVToolsAction : AsyncAction
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private readonly Action _xsToolsNotFound;
        private readonly bool _searchHiddenIsOs;

        // The 'well known' name of the ISO containing our PV tools.
        public const string ISONameOld = "xswindrivers.iso";
        public const string ISONameNew = "xs-tools.iso";

        public InstallPVToolsAction(VM vm, Action xsToolsNotfound, bool searchHiddenISOs)
            : base(vm.Connection, string.Format(Messages.INSTALLTOOLS_TITLE, vm.Name))
        {
            VM = vm;
            _xsToolsNotFound = xsToolsNotfound;
            _searchHiddenIsOs = searchHiddenISOs;
#region RBAC Dependencies
            foreach (SR sr in VM.Connection.Cache.SRs)
            {
                if (sr.IsToolsSR && sr.IsBroken())
                {
                    ApiMethodsToRoleCheck.Add("pbd.plug");
                    ApiMethodsToRoleCheck.Add("pbd.create");
                    break;
                }
            }
            ApiMethodsToRoleCheck.Add("vbd.eject");
            ApiMethodsToRoleCheck.Add("vbd.insert");
            ApiMethodsToRoleCheck.AddRange(Role.CommonSessionApiList);
#endregion
        }

        protected override void Run()
        {
            // check the xstools sr is present, if not try and repair it
            foreach(SR sr in VM.Connection.Cache.SRs)
            {
                if (sr.IsToolsSR && sr.IsBroken())
                {
                    try
                    {
                        SrRepairAction action = new SrRepairAction(sr.Connection, sr,false);
                        action.RunExternal(Session);
                    }
                    catch (Failure)
                    {
                        _xsToolsNotFound();
                    }
                }

            }

            // Check the version (if any) of the PV tools already on this host...
            VM_guest_metrics guestMetrics = Connection.Resolve(VM.guest_metrics);
            if (guestMetrics != null && !VM.HasNewVirtualisationStates && guestMetrics.PV_drivers_up_to_date)
            {
                this.Description = Messages.INSTALLTOOLS_EXIST;
                return;
            }

            // Check that the VM has a cd-rom...
            XenAPI.VBD cdrom = VM.FindVMCDROM();
            if (cdrom == null)
            {
                Description = Messages.INSTALLTOOLS_COULDNOTFIND_CD;
                return;
            }

            // Find the tools ISO...
            XenAPI.VDI winIso = findWinISO(_searchHiddenIsOs);
            if (winIso == null)
            {
                // Could not find the windows PV drivers ISO.
                Description = Messages.INSTALLTOOLS_COULDNOTFIND_WIN;
                return;
            }

            Description = Messages.INSTALLTOOLS_STARTING;

            // Eject anything that's currently in the cd-rom...
            if (!cdrom.empty)
            {
                XenAPI.VBD.eject(Session, cdrom.opaque_ref);
            }

            // Insert the tools ISO...
            XenAPI.VBD.insert(Session, cdrom.opaque_ref, winIso.opaque_ref);

            // done(ish)...
            Description = Messages.INSTALLTOOLS_DONE;
        }

        // Find the windows ISO disc by scanning the SRs - will return
        // null if the disc could not be found...
        private XenAPI.VDI findWinISO(bool searchHiddenISOs)
        {
            foreach (SR sr in Connection.Cache.SRs)
            {
                if (XenAPI.SR.SRTypes.iso.ToString() == sr.content_type)
                {
                    foreach (VDI vdi in Connection.ResolveAllShownXenModelObjects(sr.VDIs, searchHiddenISOs))
                    {
                        if (ISONameOld.Equals(vdi.name_label) ||
                            ISONameNew.Equals(vdi.name_label) ||
                            vdi.is_tools_iso)
                        {
                            return vdi;
                        }
                    }
                }
            }

            return null;
        }
    }
}