text:
package com.codeborne.selenide.impl;

import com.codeborne.selenide.Browser;
import com.codeborne.selenide.Driver;
import com.codeborne.selenide.DriverStub;
import com.codeborne.selenide.SelenideConfig;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.Optional;

import static java.io.File.separatorChar;
import static java.lang.System.lineSeparator;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.commons.io.IOUtils.resourceToByteArray;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.openqa.selenium.OutputType.BYTES;

final class ScreenShotLaboratoryTest {
  private final String dir = System.getProperty("user.dir");
  private final String workingDirectory = new File(dir).toURI().toString().replaceAll("/$", "");
  private final ChromeDriver webDriver = mock(ChromeDriver.class);
  private final SelenideConfig config = new SelenideConfig().savePageSource(false).reportsFolder("build/reports/tests");
  private final Driver driver = new DriverStub(config, new Browser("chrome", false), webDriver, null);
  private final Photographer photographer = mock(Photographer.class);
  private final PageSourceExtractor extractor = mock(PageSourceExtractor.class);
  private final Clock clock = new DummyClock(12356789L);
  private final ScreenShotLaboratory screenshots = new ScreenShotLaboratory(photographer, extractor, clock);

  @BeforeEach
  void setUp() {
    when(photographer.takeScreenshot(any(), eq(BYTES))).thenReturn(Optional.of("some png source".getBytes(UTF_8)));
  }

  @Test
  void composesScreenshotNameFromTestClassAndMethod() {
    String expected = "/build/reports/tests/MyTest/helloWorldTest.12356789.png";
    assertThat(screenshots.takeScreenShot(driver, "MyTest", "helloWorldTest").getImage())
      .isEqualTo(workingDirectory + expected);

    String expectedFileName = workingDirectory + "/build/reports/tests/org/selenide/SelenideMethodsTest/" +
      "userCanListMatchingSubElements.12356789.png";
    assertThat(screenshots.takeScreenShot(
      driver,
      "org.selenide.SelenideMethodsTest",
      "userCanListMatchingSubElements").getImage())
      .isEqualTo(expectedFileName);
  }

  @Test
  void composesScreenshotNameAsTimestampPlusCounter() {
    assertThat(screenshots.takeScreenshot(driver, true, false).getImage())
      .isEqualTo(workingDirectory + "/build/reports/tests/12356789.0.png");
    assertThat(screenshots.takeScreenshot(driver, true, false).getImage())
      .isEqualTo(workingDirectory + "/build/reports/tests/12356789.1.png");
    assertThat(screenshots.takeScreenshot(driver, true, false).getImage())
      .isEqualTo(workingDirectory + "/build/reports/tests/12356789.2.png");
  }

  @Test
  void screenshotsCanByGroupedByTests() {
    screenshots.startContext("ui/MyTest/test_some_method/");
    assertThat(screenshots.takeScreenshot(driver, true, false).getImage())
      .isEqualTo(workingDirectory + "/build/reports/tests/ui/MyTest/test_some_method/12356789.0.png");
    assertThat(screenshots.takeScreenshot(driver, true, false).getImage())
      .isEqualTo(workingDirectory + "/build/reports/tests/ui/MyTest/test_some_method/12356789.1.png");
    assertThat(screenshots.takeScreenshot(driver, true, false).getImage())
      .isEqualTo(workingDirectory + "/build/reports/tests/ui/MyTest/test_some_method/12356789.2.png");

    List<File> contextScreenshots = screenshots.finishContext();
    assertThat(contextScreenshots).hasSize(3);
    assertThat(contextScreenshots.get(0))
      .hasToString(dir + normalize("/build/reports/tests/ui/MyTest/test_some_method/12356789.0.png"));
    assertThat(contextScreenshots.get(1))
      .hasToString(dir + normalize("/build/reports/tests/ui/MyTest/test_some_method/12356789.1.png"));
    assertThat(contextScreenshots.get(2))
      .hasToString(dir + normalize("/build/reports/tests/ui/MyTest/test_some_method/12356789.2.png"));
  }

  @Test
  void collectsAllScreenshots() {
    screenshots.startContext("ui/MyTest/test_some_method/");
    screenshots.takeScreenshot(driver, true, true);
    screenshots.takeScreenshot(driver, true, true);
    screenshots.finishContext();
    screenshots.startContext("ui/YourTest/test_another_method/");
    screenshots.takeScreenshot(driver, true, true);
    screenshots.finishContext();
    screenshots.takeScreenshot(driver, true, true);
    screenshots.takeScreenshot(driver, true, true);

    List<File> allScreenshots = screenshots.getScreenshots();
    assertThat(allScreenshots).hasSize(5);
    assertThat(allScreenshots.get(0))
      .hasToString(dir + normalize("/build/reports/tests/ui/MyTest/test_some_method/12356789.0.png"));
    assertThat(allScreenshots.get(1))
      .hasToString(dir + normalize("/build/reports/tests/ui/MyTest/test_some_method/12356789.1.png"));
    assertThat(allScreenshots.get(2))
      .hasToString(dir + normalize("/build/reports/tests/ui/YourTest/test_another_method/12356789.2.png"));
    assertThat(allScreenshots.get(3))
      .hasToString(dir + normalize("/build/reports/tests/12356789.3.png"));
    assertThat(allScreenshots.get(4))
      .hasToString(dir + normalize("/build/reports/tests/12356789.4.png"));
  }

  @Test
  void collectsAllThreadScreenshots() {
    screenshots.startContext("ui/MyTest/test_some_method/");
    screenshots.takeScreenshot(driver, true, true);
    screenshots.takeScreenshot(driver, true, true);
    screenshots.finishContext();
    screenshots.startContext("ui/YourTest/test_another_method/");
    screenshots.takeScreenshot(driver, true, true);
    screenshots.finishContext();
    screenshots.takeScreenshot(driver, true, true);
    screenshots.takeScreenshot(driver, true, true);

    List<File> allThreadScreenshots = screenshots.getThreadScreenshots();
    assertThat(allThreadScreenshots).hasSize(5);
    assertThat(allThreadScreenshots.get(0))
      .hasToString(dir + normalize("/build/reports/tests/ui/MyTest/test_some_method/12356789.0.png"));
    assertThat(allThreadScreenshots.get(1))
      .hasToString(dir + normalize("/build/reports/tests/ui/MyTest/test_some_method/12356789.1.png"));
    assertThat(allThreadScreenshots.get(2))
      .hasToString(dir + normalize("/build/reports/tests/ui/YourTest/test_another_method/12356789.2.png"));
    assertThat(allThreadScreenshots.get(3))
      .hasToString(dir + normalize("/build/reports/tests/12356789.3.png"));
    assertThat(allThreadScreenshots.get(4))
      .hasToString(dir + normalize("/build/reports/tests/12356789.4.png"));
  }

  @Test
  void collectsContextScreenshots() {
    screenshots.startContext("build/reports/tests/ui/MyTest/test_some_method/");
    screenshots.takeScreenshot(driver, true, true);
    screenshots.takeScreenshot(driver, true, true);
    screenshots.takeScreenshot(driver, true, true);

    List<File> contextScreenshots = screenshots.getContextScreenshots();
    assertThat(contextScreenshots)
      .hasSize(3);

    screenshots.finishContext();
    assertThat(contextScreenshots).hasSize(3);
    assertThat(screenshots.getContextScreenshots()).isEmpty();
  }

  @Test
  void canGetLastScreenshot() {
    assertThat(screenshots.getLastScreenshot()).isNull();

    screenshots.takeScreenshot(driver, true, true);
    assertThat(screenshots.getLastScreenshot())
      .hasToString(dir + normalize("/build/reports/tests/12356789.0.png"));

    screenshots.takeScreenshot(driver, true, true);
    assertThat(screenshots.getLastScreenshot())
      .hasToString(dir + normalize("/build/reports/tests/12356789.1.png"));

    screenshots.takeScreenshot(driver, true, true);
    assertThat(screenshots.getLastScreenshot())
      .hasToString(dir + normalize("/build/reports/tests/12356789.2.png"));
  }

  @Test
  void canGetLastThreadScreenshot() {
    assertThat(screenshots.getLastThreadScreenshot())
      .isEmpty();

    screenshots.takeScreenshot(driver, true, true);
    assertThat(screenshots.getLastThreadScreenshot())
      .hasValue(new File("build/reports/tests/12356789.0.png").getAbsoluteFile());

    screenshots.takeScreenshot(driver, true, true);
    assertThat(screenshots.getLastThreadScreenshot())
      .hasValue(new File("build/reports/tests/12356789.1.png").getAbsoluteFile());

    screenshots.takeScreenshot(driver, true, true);
    assertThat(screenshots.getLastThreadScreenshot())
      .hasValue(new File("build/reports/tests/12356789.2.png").getAbsoluteFile());
  }

  @Test
  void canGetLastContextScreenshot() {
    assertThat(screenshots.getLastContextScreenshot())
      .isEmpty();

    screenshots.startContext("ui/MyTest/test_some_method/");
    assertThat(screenshots.getLastContextScreenshot())
      .isEmpty();
    screenshots.takeScreenshot(driver, true, true);
    assertThat(screenshots.getLastContextScreenshot())
      .hasValue(new File("build/reports/tests/ui/MyTest/test_some_method/12356789.0.png").getAbsoluteFile());

    screenshots.takeScreenshot(driver, true, true);
    assertThat(screenshots.getLastContextScreenshot())
      .hasValue(new File("build/reports/tests/ui/MyTest/test_some_method/12356789.1.png").getAbsoluteFile());

    screenshots.takeScreenshot(driver, true, true);
    assertThat(screenshots.getLastContextScreenshot())
      .hasValue(new File("build/reports/tests/ui/MyTest/test_some_method/12356789.2.png").getAbsoluteFile());
  }

  @Test
  void canFormatScreenShotPathWithSpaces() throws IOException {
    ScreenShotLaboratory screenshots = new ScreenShotLaboratory();
    doReturn(resourceToByteArray("/screenshot.png")).when(webDriver).getScreenshotAs(BYTES);

    config.reportsUrl("http://ci.org/job/123/artifact");
    config.reportsFolder("build/reports/path with spaces/");

    String screenShot = screenshots.takeScreenshot(driver, true, false).getImage();

    assertThat(screenShot)
      .contains("http://ci.org/job/123/artifact/build/reports/path%20with%20spaces/");
  }

  @Test
  void doNotEncodeReportsURL() throws IOException {
    ScreenShotLaboratory screenshots = new ScreenShotLaboratory();
    doReturn(resourceToByteArray("/screenshot.png")).when(webDriver).getScreenshotAs(BYTES);

    config.reportsUrl("http://ci.org/path%20with%spaces/");

    String screenShotPath = screenshots.takeScreenshot(driver, true, false).getImage();

    assertThat(screenShotPath)
      .contains("http://ci.org/path%20with%spaces/");
  }

  @Test
  void encodePath() {
    assertThat(screenshots.encodePath("/foo bar/boom room/pdf")).isEqualTo("/foo%20bar/boom%20room/pdf");
  }

  @Test
  void convertsScreenshotFileNameToCIUrl() throws IOException {
    config.reportsUrl("http://ci.mycompany.com/job/666/artifact/");
    doReturn(resourceToByteArray("/screenshot.png")).when(webDriver).getScreenshotAs(BYTES);

    String screenshot = screenshots.takeScreenshot(driver, true, false).summary();
    assertThat(screenshot)
      .startsWith(String.format("%nScreenshot: http://ci.mycompany.com/job/666/artifact/build/reports/tests/"))
      .endsWith(".png");
  }

  @Test
  void convertsReportUrlForOutsideSavedScreenshot() throws IOException {
    String reportsUrl = "http://ci.mycompany.com/job/666/artifact/";
    config.reportsUrl(reportsUrl);

    // directory, that not in 'user.dir'
    config.reportsFolder(Files.createTempDirectory("artifacts-storage").toFile().getAbsolutePath());

    doReturn(resourceToByteArray("/screenshot.png")).when(webDriver).getScreenshotAs(BYTES);

    String screenshot = screenshots.takeScreenshot(driver, true, false).summary();
    assertThat(screenshot)
      .as("Concatenate reportUrl with screenshot file name if it saved outside of build/project home dir")
      .startsWith(String.format("%nScreenshot: %s", reportsUrl + new File(screenshot).getName()));
  }

  @Test
  void returnsScreenshotFileName() throws IOException {
    config.reportsUrl(null);
    String currentDir = System.getProperty("user.dir");
    if (separatorChar == '\\') {
      currentDir = '/' + currentDir.replace('\\', '/');
    }

    currentDir = currentDir.replace(" ", "%20"); //the screenshot path uses %20 instead of the space character

    doReturn(resourceToByteArray("/screenshot.png")).when(webDriver).getScreenshotAs(BYTES);

    String screenshot = screenshots.takeScreenshot(driver, true, false).summary();
    assertThat(screenshot)
      .startsWith(String.format("%nScreenshot: file:%s/build/reports/tests/", currentDir))
      .endsWith(".png");
  }

  @Test
  void doesNotAddScreenshot_if_screenshotsAreDisabled() {
    config.screenshots(true);

    String screenshot = screenshots.takeScreenshot(driver, false, false).summary();
    assertThat(screenshot).isNullOrEmpty();
    verify(webDriver, never()).getScreenshotAs(any());
  }

  @Test
  void printHtmlPath_if_savePageSourceIsEnabled() throws IOException {
    config.savePageSource(false);
    config.reportsUrl("http://ci.mycompany.com/job/666/artifact/");
    doReturn(new File("build/reports/page123.html")).when(extractor).extract(eq(config), eq(webDriver), any());
    doReturn(resourceToByteArray("/screenshot.png")).when(webDriver).getScreenshotAs(BYTES);

    Screenshot screenshot = screenshots.takeScreenshot(driver, true, true);
    assertThat(screenshot.summary()).isEqualTo(
      lineSeparator() + "Screenshot: http://ci.mycompany.com/job/666/artifact/build/reports/tests/12356789.0.png" +
        lineSeparator() + "Page source: http://ci.mycompany.com/job/666/artifact/build/reports/page123.html");
  }

  private String normalize(String path) {
    return separatorChar == '\\' ? path.replace('/', separatorChar) : path;
  }
}


text:
<!DOCTYPE html>

  <title>userFormDirective.js</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
  <link rel="stylesheet" media="all" href="docco.css" />

          Jump To …
          +

                app.js

                movieController.js

                movieShowController.js

                profileController.js

                userShowController.js

                commentsDirective.js

                favoriteMoviesDirective.js

                niceScrollDirective.js

                userFormDirective.js

                whenScrolledDirective.js

                kernel.js

                require-config.js

                router.js

                categoryService.js

                commentService.js

                movieService.js

                userService.js

userFormDirective.js

                ¶

define([
        'app',
        'toastr',
        'services/userService'
    ],
    function(gobbmovies, toastr, userService) {
        gobbmovies.directive('ngUserForm', ['userService',
            function(userService) {
                return {
                    restrict: 'AEC',
                    replace: true,
                    scope: {
                        profile: '='
                    },
                    link: function($scope, $element, $attrs) {

                        $scope.$watch('profile', function() {
                            $scope.user = angular.copy($scope.profile);
                        });

                ¶

update user profile.

                        $scope.updateUser = function(userForm) {
                            toastr.options = {
                                "positionClass": "toast-bottom-full-width"
                            };
                            if (userForm.$valid) {
                                userService.update($scope.user, function(data) {
                                    $scope.profile.firstname = data.firstname;
                                    $scope.profile.lastname = data.lastname;
                                    $scope.profile.email = data.email;
                                    $scope.profile.city = data.city;
                                    $scope.profile.birthday = data.birthday;
                                    toastr.success('', 'Profile updated !');
                                });
                            } else {
                                toastr.error('', 'Invalid profile');
                            }
                        }
                    },

                    templateUrl: '/templates/user/userForm.html'
                };
            }
        ]);
    });

redpajama_set_name: RedPajamaGithub


text:
const baseURL = '/';

export async function isLoggedIn() {
  try {
    const result = await fetch(baseURL + 'api/todos');
    if (result.status !== 200) {
      return false;
    }
    return true;
  } catch (ex) {
    throw new Error(ex.message);
  }
}

export async function getTodos() {
  try {
    const response = await fetch(this.baseURL + 'api/todos');
    return await response.json();
  } catch (ex) {
    throw new Error(ex.message);
  }
}

export async function addTodo(data) {
  try {
    const response = await fetch(this.baseURL + 'api/todos', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });
    return await response.json();
  } catch (ex) {
    throw new Error(ex.message);
  }
}

export async function deleteTodo(id) {
  try {
    const response = await fetch(this.baseURL + `api/todos/${id}`, {
      method: 'DELETE'
    });
    return response.json();
  } catch (ex) {
    throw new Error(ex.message);
  }
}


text:
var expect = require("chai").expect;

describe("KitDeployer", function() {
  describe("when required", function() {
    var KitDeployer;
    beforeEach(function() {
      KitDeployer = require("../../src/index");
    });
    it("should have Deployer class", function() {
      expect(KitDeployer.Deployer).to.be.equal(
        require("../../src/lib/deployer")
      );
    });
  });
});


text:
// for simplicity this file is not transpiled and is run directly via an npm script
/* eslint-disable no-console */
/* eslint-disable promise/prefer-await-to-callbacks */
/* eslint-disable promise/prefer-await-to-then */

const path = require('path');
const {fs} = require('@appium/support');
const {AppiumConfigJsonSchema} = require('@appium/schema');

const DOC_PATH = path.resolve(__dirname, '..', 'en', 'cli', 'args.md');

const START_TAG = `<!-- AUTOGEN-START -->`;
const STOP_TAG = `<!-- AUTOGEN-STOP -->`;

async function main() {
  console.log(`Gathering current cli doc file contents...`);
  const [preStart, postEnd] = await getDocParts();
  console.log(`Generating new cli arg table...`);
  const argTable = getCliArgTable();
  console.log(`Writing new doc file...`);
  await writeNewDoc(preStart, argTable, postEnd);
  console.log(`...done!`);
}

async function getDocParts() {
  if (!(await fs.exists(DOC_PATH))) {
    throw new Error(`Cannot find args.md at ${DOC_PATH}`);
  }

  const curContents = await fs.readFile(DOC_PATH, 'utf-8');

  // attempt to verify the start/stop tags
  const [preStart, postStart] = curContents.split(START_TAG);
  if (!postStart) {
    throw new Error(`Could not find autogen start tag '${START_TAG}'. Make sure it's in place!`);
  }
  const [, postEnd] = postStart.split(STOP_TAG);
  if (!postEnd) {
    throw new Error(`Could not find autogen stop tag '${STOP_TAG}'. Make sure it's in place!`);
  }

  return [preStart, postEnd];
}

function getCliArgTable() {
  const pad = ' '.repeat(30);
  const header = `|Argument${pad}|Description|Type|Default|Aliases|\n` + `|--|--|--|--|--|`;
  const serverProps = AppiumConfigJsonSchema.properties.server.properties;
  const args = Object.keys(serverProps).map((arg) => {
    let {appiumCliAliases = [], description, type, items, maximum, minimum} = serverProps[arg];
    let def = serverProps[arg].default;
    let enums = serverProps[arg].enum;
    if (type === 'array' || type === 'object' || (type === 'string' && def === '')) {
      def = JSON.stringify(def);
    }
    if (type === 'array' && items.type) {
      type = `array<${items.type}>`;
    }
    if (type === 'integer' && typeof minimum !== 'undefined' && typeof maximum !== 'undefined') {
      description = `${description} (Value must be between \`${minimum}\` and \`${maximum}\`)`;
    }
    if (enums) {
      const enumsFormatted = enums.map((e) => `\`${e}\``).join(', ');
      description = `${description} (Value must be one of: ${enumsFormatted})`;
    }
    return {
      arg: `--${arg}`,
      aliases: appiumCliAliases.map((a) => `-${a}`),
      type,
      def,
      description,
    };
  });
  const body = args
    .map(({arg, aliases, type, def, description}) => {
      const aliasStr = aliases.map((a) => `\`${a}\``).join(', ');
      def = typeof def !== 'undefined' ? `\`${def}\`` : '';
      return `|\`${arg}\`|${description}|${type}|${def}|${aliasStr}|`;
    })
    .join('\n');
  return `${header}\n${body}`;
}

async function writeNewDoc(preStart, argTable, postEnd) {
  const newContents = `${preStart}${START_TAG}\n${argTable}\n${STOP_TAG}${postEnd}`;
  await fs.writeFile(DOC_PATH, newContents);
}

if (require.main === module) {
  main().catch((err) => {
    throw err;
  });
}

module.exports = main;


text:
package caaa

import (
	"encoding/xml"

	"github.com/fgrid/iso20022"
)

type Document00300105 struct {
	XMLName xml.Name                     `xml:"urn:iso:std:iso:20022:tech:xsd:caaa.003.001.05 Document"`
	Message *AcceptorCompletionAdviceV05 `xml:"AccptrCmpltnAdvc"`
}

func (d *Document00300105) AddMessage() *AcceptorCompletionAdviceV05 {
	d.Message = new(AcceptorCompletionAdviceV05)
	return d.Message
}

// The AcceptorCompletionAdvice message is sent by an acceptor (or its agent) to notify the acquirer (or its agent) of the outcome of the payment at the acceptor, and to transfer the  financial data of the transaction to the acquirer (capture).
// A AcceptorCompletionAdvice message is also sent to reverse an approved authorisation and any associated financial transfer (capture), if the card payment transaction could not be completed successfully.
type AcceptorCompletionAdviceV05 struct {

	// Completion advice message management information.
	Header *iso20022.Header24 `xml:"Hdr"`

	// Information related to the completion advice.
	CompletionAdvice *iso20022.AcceptorCompletionAdvice5 `xml:"CmpltnAdvc"`

	// Trailer of the message containing a MAC.
	SecurityTrailer *iso20022.ContentInformationType15 `xml:"SctyTrlr,omitempty"`
}

func (a *AcceptorCompletionAdviceV05) AddHeader() *iso20022.Header24 {
	a.Header = new(iso20022.Header24)
	return a.Header
}

func (a *AcceptorCompletionAdviceV05) AddCompletionAdvice() *iso20022.AcceptorCompletionAdvice5 {
	a.CompletionAdvice = new(iso20022.AcceptorCompletionAdvice5)
	return a.CompletionAdvice
}

func (a *AcceptorCompletionAdviceV05) AddSecurityTrailer() *iso20022.ContentInformationType15 {
	a.SecurityTrailer = new(iso20022.ContentInformationType15)
	return a.SecurityTrailer
}


text:
#include <chrono>
#include <vector>

#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <disruptor4cpp/disruptor4cpp.h>
#include "wait_strategy_test_util.h"

namespace
{
	class mock_sequence_barrier
	{
	public:
		MOCK_CONST_METHOD0(check_alert, void());
	};
}

namespace disruptor4cpp
{
	namespace test
	{
		TEST(timeout_blocking_wait_strategy_test, should_timeout_wait_for)
		{
			const int64_t timeout_nanos = 500 * 1000000;
			timeout_blocking_wait_strategy<timeout_nanos> wait_strategy;
			sequence cursor(5);
			auto dependent_sequences = fixed_sequence_group<sequence>::create(std::vector<sequence*> { &cursor });

			mock_sequence_barrier seq_barrier;
			EXPECT_CALL(seq_barrier, check_alert());

			auto t0 = std::chrono::system_clock::now();
			try
			{
				wait_strategy.wait_for(6, cursor, dependent_sequences, seq_barrier);
			}
			catch (timeout_exception& ex)
			{
			}
			auto t1 = std::chrono::system_clock::now();
			int64_t time_waiting = std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count();
			ASSERT_GE(time_waiting, timeout_nanos);
		}
	}
}


text:
apt-get -y install ubuntu-desktop
apt-get -y update
apt-get -y upgrade
apt-get -y install git vim libxss1 python-dev

# install pip
apt-get -y install python-pip
pip install -U pip
apt-get -y purge python-pip

# install vmmaster-agent
sudo -E pip install -U git+https://github.com/nwlunatic/vmmaster-agent.git#egg=vmmaster_agent

# install oracle java
sudo add-apt-repository -y ppa:webupd8team/java
sudo apt-get update
echo oracle-java7-installer shared/accepted-oracle-license-v1-1 select true | sudo /usr/bin/debconf-set-selections
sudo apt-get -y install oracle-java7-installer

# install selenium-launchers
cd ~/
git clone --depth=1 https://github.com/bayandin/selenium-launchers.git
chown -R vagrant:vagrant ~/selenium-launchers

# install google chrome
cd /tmp
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome-stable_current_amd64.deb || sudo apt-get -f -y install


text:
//IBM_PROLOG_BEGIN_TAG

//IBM_PROLOG_END_TAG

//----------------------------------------------------------------------
//  Includes
//----------------------------------------------------------------------
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <algorithm>

#include <ecmdCommandUtils.H>
#include <ecmdReturnCodes.H>
#include <ecmdClientCapi.H>
#include <ecmdUtils.H>
#include <ecmdDataBuffer.H>
#include <ecmdInterpreter.H>
#include <ecmdSharedUtils.H>

//----------------------------------------------------------------------
//  User Types
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Constants
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Macros
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Internal Function Prototypes
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Global Variables
//----------------------------------------------------------------------

//---------------------------------------------------------------------
// Member Function Specifications
//---------------------------------------------------------------------
#ifndef ECMD_REMOVE_POWER_FUNCTIONS
uint32_t ecmdSystemPowerUser(int argc, char * argv[]) {
  uint32_t rc = ECMD_SUCCESS;
  ecmdPowerState_t  o_state;

  /************************************************************************/
  /* Parse Common Cmdline Args                                            */
  /************************************************************************/

  rc = ecmdCommandArgs(&argc, &argv);
  if (rc) return rc;

  if (argc < 1) {
    ecmdOutputError("systempower - At least one argument ('on', 'off', 'query') is required for systempower.\n");
    return ECMD_INVALID_ARGS;
  }
  else if (argc > 1) {
    ecmdOutputError("systempower - Too many arguments to systempower, you probably added a non-supported option.\n");
    return ECMD_INVALID_ARGS;
  }

  if (!strcmp(argv[0], "on")) {
    ecmdOutput("Powering on the system ...\n");
    rc = ecmdSystemPowerOn();
  } else if (!strcmp(argv[0], "off")) {
    ecmdOutput("Powering off the system ...\n");
    rc = ecmdSystemPowerOff();
  } else if (!strcmp(argv[0], "query")) {

    rc = ecmdQuerySystemPower(o_state);

    if (rc) {
      return ECMD_FAILURE;
    }
    else {
      if (o_state==ECMD_POWER_STATE_UNKNOWN) {
        ecmdOutput("Systempower is unknown ...\n");
      }
      else if (o_state==ECMD_POWER_STATE_ON) {
        ecmdOutput("Systempower is ON ...\n");
      }
      else if (o_state==ECMD_POWER_STATE_OFF) {
        ecmdOutput("Systempower is OFF ...\n");
      }
      else if (o_state==ECMD_POWER_STATE_TRANSITION) {
        ecmdOutput("Systempower is in Transition ...\n");
      }
    }
  } else {
    ecmdOutputError("systempower - Invalid argument passed to systempower. Accepted arguments: ('on', 'off', 'query').\n");
    return ECMD_INVALID_ARGS;
  }

  return rc;

}

uint32_t ecmdFruPowerUser(int argc, char * argv[]) {
  uint32_t rc = ECMD_SUCCESS, coeRc = ECMD_SUCCESS;

  ecmdLooperData looperdata;            ///< Store internal Looper data
  ecmdChipTarget target;                ///< Current target operating on
  bool validPosFound = false;           ///< Did the looper find anything to execute on
  std::string printed;
  std::string state;
  bool smart = false;

  /************************************************************************/
  /* Parse Local FLAGS here!                                              */
  /************************************************************************/
  /* get the smart flag, if it's there */
  smart = ecmdParseOption(&argc, &argv, "-smart");

  /************************************************************************/
  /* Parse Common Cmdline Args                                            */
  /************************************************************************/
  rc = ecmdCommandArgs(&argc, &argv);
  if (rc) return rc;

  /* Global args have been parsed, we can read if -coe was given */
  bool coeMode = ecmdGetGlobalVar(ECMD_GLOBALVAR_COEMODE); ///< Are we in continue on error mode

  if (argc < 2) {
    ecmdOutputError("frupower - At least one argument ('on', 'off', 'query') is required for frupower.\n");
    return ECMD_INVALID_ARGS;
  }
  else if (argc > 2) {
    ecmdOutputError("frupower - Too many arguments to frupower, you probably added a non-supported option.\n");
    return ECMD_INVALID_ARGS;
  }

  if (!strcmp(argv[0], "on")) {
    state = "on";
  } else if (!strcmp(argv[0], "off")) {
    state = "off";
  } else if (!strcmp(argv[0], "query")) {
    state = "query";
  } else {
    ecmdOutputError("frupower - Invalid argument passed to frupower. Accepted arguments: ('on', 'off', 'query').\n");
    return ECMD_INVALID_ARGS;
  }

  //Setup the target that will be used
  std::string chipType, chipUnitType;
  ecmdParseChipField(argv[1], chipType, chipUnitType);
  if (chipUnitType != "") {
    ecmdOutputError("getvpdkeyword - chipUnit specified on the command line, this function doesn't support chipUnits.\n");
    return ECMD_INVALID_ARGS;
  }
  target.chipType = chipType;
  if (target.chipType == "nochip") {
    target.chipTypeState = ECMD_TARGET_FIELD_UNUSED;
    target.posState = ECMD_TARGET_FIELD_UNUSED;
  } else {
    target.chipTypeState = ECMD_TARGET_FIELD_VALID;
    target.posState = ECMD_TARGET_FIELD_WILDCARD;
  }
  target.cageState = target.nodeState = target.slotState = ECMD_TARGET_FIELD_WILDCARD;
  target.chipUnitTypeState = target.chipUnitNumState = target.threadState = ECMD_TARGET_FIELD_UNUSED;

  /************************************************************************/
  /* Kickoff Looping Stuff                                                */
  /************************************************************************/
  rc = ecmdLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperdata);
  if (rc) return rc;

  while (ecmdLooperNext(target, looperdata) && (!coeRc || coeMode)) {

    if (state == "on") {
      printed = "Powering on";
      printed += ecmdWriteTarget(target) + " ..\n";
      ecmdOutput(printed.c_str());
      rc = ecmdFruPowerOn(target, smart);
    } else if (state == "off") {
      printed = "Powering off";
      printed += ecmdWriteTarget(target) + " ..\n";
      ecmdOutput(printed.c_str());
      rc = ecmdFruPowerOff(target, smart);
    } else if (state == "query") {
      printed = "Frupower of ";
      printed += ecmdWriteTarget(target);
      ecmdPowerState_t  o_state = ECMD_POWER_STATE_UNKNOWN;

      rc = ecmdQueryFruPower(target,  o_state);

      if (rc==0)  {
        if (o_state==ECMD_POWER_STATE_UNKNOWN) {
          printed += " is unknown  \n ";
          ecmdOutput(printed.c_str());
        }
        else if (o_state==ECMD_POWER_STATE_ON) {
          printed += " is ON  \n ";
          ecmdOutput(printed.c_str());
        }
        else if (o_state==ECMD_POWER_STATE_OFF) {
          printed += " is OFF  \n ";
          ecmdOutput(printed.c_str());
        }
        else if (o_state==ECMD_POWER_STATE_TRANSITION) {
          printed += " is in Transition  \n ";
          ecmdOutput(printed.c_str());
        }
      }
    }

    if (rc) {
      printed = "frupower - Error occurred performing frupower ";
      printed += state  + " function ";
      printed += ecmdWriteTarget(target) + "\n";
      ecmdOutputError( printed.c_str() );
      coeRc = rc;
      continue;
    }
    else {
      validPosFound = true;
    }
  }
  // coeRc will be the return code from in the loop, coe mode or not.
  if (coeRc) return coeRc;

  // This is an error common across all UI functions
  if (!validPosFound) {
    ecmdOutputError("frupower - Unable to find a valid chip to execute command on\n");
    return ECMD_TARGET_NOT_CONFIGURED;
  }

  return rc;
}

uint32_t ecmdPowerModeUser(int argc, char * argv[]) {
  uint32_t rc = ECMD_SUCCESS, coeRc = ECMD_SUCCESS;

  ecmdLooperData looperdata;            ///< Store internal Looper data
  ecmdChipTarget target;                ///< Current target operating on
  bool validPosFound = false;           ///< Did the looper find anything to execute on
  std::string printed;
  std::string mode;

  /************************************************************************/
  /* Parse Local FLAGS here!                                              */
  /************************************************************************/

  /************************************************************************/
  /* Parse Common Cmdline Args                                            */
  /************************************************************************/
  rc = ecmdCommandArgs(&argc, &argv);
  if (rc) return rc;

  /* Global args have been parsed, we can read if -coe was given */
  bool coeMode = ecmdGetGlobalVar(ECMD_GLOBALVAR_COEMODE); ///< Are we in continue on error mode

  if (argc < 1) {
    ecmdOutputError("powermode - At least one argument ('save', 'normal', 'query', 'turbo', 'super_turbo') is required for powermode.\n");
    return ECMD_INVALID_ARGS;
  }
  else if (argc > 1) {
    ecmdOutputError("powermode - Too many arguments to powermode, you probably added a non-supported option.\n");
    return ECMD_INVALID_ARGS;
  }

  if (!strcmp(argv[0], "normal")) {
    mode = "normal";
  } else if (!strcmp(argv[0], "save")) {
    mode = "save";
  } else if (!strcmp(argv[0], "super_turbo")) {
    mode = "super_turbo";
  } else if (!strcmp(argv[0], "turbo")) {
    mode = "turbo";
  } else if (!strcmp(argv[0], "query")) {
    mode = "query";
  } else if (!strcmp(argv[0], "dynamic_save")) {
    mode = "dynamic_save";
  } else if (!strcmp(argv[0], "dynamic_save_mp")) {
    mode = "dynamic_save_mp";
  } else {
    ecmdOutputError("powermode - Invalid argument passed to powermode. Accepted arguments: ('save', 'normal', 'query', 'super_turbo', 'turbo').\n");
    return ECMD_INVALID_ARGS;
  }

  //Setup the target that will be used
    target.chipTypeState = ECMD_TARGET_FIELD_UNUSED;
    target.posState = ECMD_TARGET_FIELD_UNUSED;
  target.cageState = ECMD_TARGET_FIELD_WILDCARD;
  target.nodeState = ECMD_TARGET_FIELD_UNUSED;
  target.slotState = ECMD_TARGET_FIELD_UNUSED;
  target.chipUnitTypeState = target.chipUnitNumState = target.threadState = ECMD_TARGET_FIELD_UNUSED;

  /************************************************************************/
  /* Kickoff Looping Stuff                                                */
  /************************************************************************/
  rc = ecmdLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperdata);
  if (rc) return rc;

  while (ecmdLooperNext(target, looperdata) && (!coeRc || coeMode)) {

    if (mode == "normal") {
      printed = ecmdWriteTarget(target) + ".. ";
      printed += "Normal Mode\n";
      ecmdOutput(printed.c_str());
      rc = ecmdSetPowerMode(target, ECMD_POWER_MODE_NORMAL);
    } else if (mode == "save") {
      printed = ecmdWriteTarget(target) + ".. ";
      printed += "Power Save Mode\n";
      ecmdOutput(printed.c_str());
      rc = ecmdSetPowerMode(target, ECMD_POWER_MODE_SAVE);
    } else if (mode == "super_turbo") {
      printed = ecmdWriteTarget(target) + ".. ";
      printed += "Super Turbo Mode\n";
      ecmdOutput(printed.c_str());
      rc = ecmdSetPowerMode(target, ECMD_POWER_MODE_SUPER_TURBO);
    } else if (mode == "turbo") {
      printed = ecmdWriteTarget(target) + ".. ";
      printed += "Turbo Mode\n";
      ecmdOutput(printed.c_str());
      rc = ecmdSetPowerMode(target, ECMD_POWER_MODE_TURBO);
    } else if (mode == "dynamic_save") {
      printed = ecmdWriteTarget(target) + ".. ";
      printed += "Dynamic Powersave Mode\n";
      ecmdOutput(printed.c_str());
      rc = ecmdSetPowerMode(target, ECMD_POWER_MODE_SAVE_DYNAMIC);
    } else if (mode == "dynamic_save_mp") {
      printed = ecmdWriteTarget(target) + ".. ";
      printed += "Dynamic Powersave Max Performance Mode\n";
      ecmdOutput(printed.c_str());
      rc = ecmdSetPowerMode(target, ECMD_POWER_MODE_SAVE_DYNAMIC_MP);
   } else if (mode == "query") {
     ecmdPowerMode_t o_mode=ECMD_POWER_MODE_UNKNOWN;
     rc = ecmdGetPowerMode(target, o_mode);
     printed = "Query Mode :";

     if (o_mode == ECMD_POWER_MODE_SAVE) {
       printed += " Save \n";
     } else  if (o_mode == ECMD_POWER_MODE_NORMAL){
       printed += " Normal \n";
     } else  if (o_mode == ECMD_POWER_MODE_SUPER_TURBO){
       printed += " Super Turbo\n";
     } else  if (o_mode== ECMD_POWER_MODE_TURBO)   {
       printed += " Turbo \n";
     } else  if (o_mode== ECMD_POWER_MODE_SAVE_DYNAMIC)   {
       printed += " Dynamic Powersave \n";
     } else  if (o_mode== ECMD_POWER_MODE_SAVE_DYNAMIC_MP)   {
       printed += " Dynamic Powersave Max Performance \n";
     } else  if (o_mode== ECMD_POWER_MODE_IN_TRANSITION)   {
       printed += " Transition \n";
     } else {
       printed += " unknown \n";
     }

     ecmdOutput(printed.c_str());
   }

    if (rc) {
      printed = "powermode - Error occurred performing powermode ";
      printed += ecmdWriteTarget(target) + "\n";
      ecmdOutputError( printed.c_str() );
      coeRc = rc;
      continue;
    }
    else {
      validPosFound = true;
    }
  }
  // coeRc will be the return code from in the loop, coe mode or not.
  if (coeRc) return coeRc;

  // This is an error common across all UI functions
  if (!validPosFound) {
    ecmdOutputError("powermode - Unable to find a target to execute command on\n");
    return ECMD_TARGET_NOT_CONFIGURED;
  }

  return rc;
}
uint32_t ecmdBiasVoltageUser(int argc, char * argv[]) {

  uint32_t rc = ECMD_SUCCESS, coeRc = ECMD_SUCCESS;
  ecmdLooperData looperData;            ///< Store internal Looper data
  ecmdChipTarget target;                ///< Current target operating on
  ecmdChipTarget vdTarget;                ///< Current target operating on
  ecmdLooperData vdLooperData;            ///< Store internal Looper data
  bool validPosFound = false;           ///< Did the looper find anything to execute on
  std::string printed;
  bool waitState = true;                ///< Wait for the command to finish or return immediately
  std::string biasString;
  uint32_t biasValue;
  uint32_t voltageLevel;

  /************************************************************************/
  /* Parse Common Cmdline Args                                            */
  /************************************************************************/
  rc = ecmdCommandArgs(&argc, &argv);
  if (rc) return rc;

  /* Global args have been parsed, we can read if -coe was given */
  bool coeMode = ecmdGetGlobalVar(ECMD_GLOBALVAR_COEMODE); ///< Are we in continue on error mode

  /************************************************************************/
  /* Parse Local ARGS here!                                               */
  /************************************************************************/
  if (ecmdParseOption(&argc, &argv, "-immediate")) {
    waitState = false;
  }

  if (argc != 2) {
    ecmdOutputError("biasvoltage - Incorrect arguments specified; you need voltageLevel and biasLevel.\n");
    ecmdOutputError("biasvoltage - Type 'biasvoltage -h' for usage.\n");
    return ECMD_INVALID_ARGS;
  }

  // Setup the target that will be used to loop
  // First we will do a default node level loop, and then try a slot level loop if the user specifed one
  target.cageState = target.nodeState = ECMD_TARGET_FIELD_WILDCARD;
  target.slotState = target.posState = target.chipTypeState = target.chipUnitTypeState = target.chipUnitNumState = target.threadState = ECMD_TARGET_FIELD_UNUSED;

  // Get the leve the user specified
  voltageLevel = (uint32_t)atoi(argv[0]);

  if (!ecmdIsAllDecimal(argv[0])) {
    ecmdOutputError("biasvoltage - Non-decimal numbers detected in level field\n");
    return ECMD_INVALID_ARGS;
  }

  //get clockspeed
  size_t strpos;
  biasString = argv[1];
  transform(biasString.begin(), biasString.end(), biasString.begin(), (int(*)(int)) tolower);

  ecmdVoltageType_t voltageType = ECMD_VOLTAGE_UNKNOWN;  // defaulting to remove compiler warnings
  if ((strpos = biasString.find("nom")) != std::string::npos)  {
    voltageType = ECMD_VOLTAGE_NOMINAL;
  } else if ((strpos = biasString.find("npu")) != std::string::npos) {
    voltageType = ECMD_VOLTAGE_PERCENT_UP;
  } else if ((strpos = biasString.find("npd")) != std::string::npos) {
    voltageType = ECMD_VOLTAGE_PERCENT_DOWN;
  } else if ((strpos = biasString.find("pspu")) != std::string::npos) {
    voltageType = ECMD_VOLTAGE_POWERSAVE_PERCENT_UP;
  } else if ((strpos = biasString.find("pspd")) != std::string::npos) {
    voltageType = ECMD_VOLTAGE_POWERSAVE_PERCENT_DOWN;
  } else {
    ecmdOutputError("biasvoltage - a valid biasValue Keyword not found biasValue field\n");
    ecmdOutputError("biasvoltage - Type 'biasvoltage -h' for usage.\n");
    return ECMD_INVALID_ARGS;
  }

  biasString.erase(strpos, biasString.length()-strpos);

  if (!ecmdIsAllDecimal(biasString.c_str())) {
    ecmdOutputError("biasvoltage - Non-Decimal characters detected in biasValue field\n");
    return ECMD_INVALID_ARGS;
  }

  biasValue = (uint32_t)atoi(biasString.c_str());

  /************************************************************************/
  /* Kickoff Looping Stuff                                                */
  /************************************************************************/

  rc = ecmdLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperData);
  if (rc) return rc;

  while (ecmdLooperNext(target, looperData) && (!coeRc || coeMode)) {

    // Now try a slot level loop on this node loop
    // Preserve the valid states from the looperNext, but reset the slot to wildcard
    vdTarget = target;
    vdTarget.slotState = ECMD_TARGET_FIELD_WILDCARD;
    rc = ecmdLooperInit(vdTarget, ECMD_SELECTED_TARGETS_LOOP_VD, vdLooperData);
    if (rc) break;

    while (ecmdLooperNext(vdTarget, vdLooperData) && (!coeRc || coeMode)) {
      rc = ecmdBiasVoltage(vdTarget, voltageLevel, voltageType, biasValue, waitState);

      if (rc) {
        printed = "biasvoltage - Error occurred performing ecmdBiasVoltage on ";
        printed += ecmdWriteTarget(vdTarget) + "\n";
        ecmdOutputError( printed.c_str() );
        coeRc = rc;
        continue;
      }
      else {
        validPosFound = true;
      }

      if (!ecmdGetGlobalVar(ECMD_GLOBALVAR_QUIETMODE)) {
        printed = ecmdWriteTarget(vdTarget) + "\n";
        ecmdOutput(printed.c_str());
      }

    }
  }
  // coeRc will be the return code from in the loop, coe mode or not.
  if (coeRc) return coeRc;

  // This is an error common across all UI functions
  if (!validPosFound) {
    ecmdOutputError("biasvoltage - Unable to find a valid chip to execute command on\n");
    return ECMD_TARGET_NOT_CONFIGURED;
  }

  return rc;
}

uint32_t ecmdQueryBiasStateUser(int argc, char * argv[]) {

  uint32_t rc = ECMD_SUCCESS, coeRc = ECMD_SUCCESS;
  ecmdChipTarget target;                        ///< Current target being operated on
  bool validPosFound = false;                   ///< Did the looper find anything?
  ecmdLooperData looperdata;            ///< Store internal Looper data
  std::string printed;                          ///< Output data
  uint32_t currentVoltage;
  uint32_t targetVoltage;
  uint32_t timeLeft;
  char returnStr[100];

  /************************************************************************/
  /* Parse Common Cmdline Args                                            */
  /************************************************************************/
  rc = ecmdCommandArgs(&argc, &argv);
  if (rc) return rc;

  /* Global args have been parsed, we can read if -coe was given */
  bool coeMode = ecmdGetGlobalVar(ECMD_GLOBALVAR_COEMODE); ///< Are we in continue on error mode

  /************************************************************************/
  /* Parse Local ARGS here!                                               */
  /************************************************************************/
  if (argc != 1) {  //level
    ecmdOutputError("querybiasstate - Only the voltage level to query needs to be given.\n");
    ecmdOutputError("querybiasstate - Type 'querybiasstate -h' for usage.\n");
    return ECMD_INVALID_ARGS;
  }

  //Setup the target that will be used to query the system config
  target.cageState = target.nodeState = target.slotState = ECMD_TARGET_FIELD_WILDCARD;
  target.posState = target.chipTypeState = target.chipUnitTypeState = target.chipUnitNumState = target.threadState = ECMD_TARGET_FIELD_UNUSED;

  //get level to fetch
  if (!ecmdIsAllDecimal(argv[0])) {
    ecmdOutputError("querybiasstate - Non-decimal numbers detected in level field\n");
    return ECMD_INVALID_ARGS;
  }
  uint32_t voltageLevel = (uint32_t)atoi(argv[0]);

  /************************************************************************/
  /* Kickoff Looping Stuff                                                */
  /************************************************************************/

  rc = ecmdLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperdata);
  if (rc) return rc;

  while (ecmdLooperNext(target, looperdata) && (!coeRc || coeMode)) {

    rc = ecmdQueryBiasState(target, voltageLevel, currentVoltage, targetVoltage, timeLeft);
    if (rc) {
      printed = "querybiasstate - Error occured performing ecmdQueryBiasState on ";
      printed += ecmdWriteTarget(target);
      printed += "\n";
      ecmdOutputError( printed.c_str() );
      coeRc = rc;
      continue;
    }
    else {
      validPosFound = true;
    }

    printed = ecmdWriteTarget(target);
    sprintf(returnStr, "currentVoltage: %d, targetVoltage: %d, timeLeft: %dms\n", currentVoltage, targetVoltage, timeLeft);
    printed += returnStr;
    ecmdOutput(printed.c_str());
  }
  // coeRc will be the return code from in the loop, coe mode or not.
  if (coeRc) return coeRc;

  // This is an error common across all UI functions
  if (!validPosFound) {
    ecmdOutputError("querybiasstate - Unable to find a valid chip to execute command on\n");
    return ECMD_TARGET_NOT_CONFIGURED;
  }

  return rc;
}
#endif // ECMD_REMOVE_POWER_FUNCTIONS


text:
/* ------- FONTS ------- */
/* ------- BORDERS ------- */
/* ------- BACKGROUNDS ------- */
/* ------- COLORS ------- */
/* ------- Indents ------- */
/* ------- Product Elements ------- */
/* ------- Buttons ------- */
/* ------- Buttons +/- ------ */
/* ------- Button Small ------- */
/* ------- Button exclusive-medium ------- */
/* ------- My Account List bg ------- */
/* ------- Product Listing ------- */
/* ------- Grid/List vars ------- */
/* ------- Pagination vars ------- */
/* ------- Product Info ------- */
/* ------- Cart Steps ------- */
/* ------- sub heading (h2,h3) define ------- */
/* ------- Image vars ------- */
/* lnk on detail product page */
#wishlist_button {
  font-weight: 700; }
  #wishlist_button:before {
    content: "\f08a";
    font: 400 15px/31px "FontAwesome";
    color: white;
    background: #929292;
    width: 30px;
    text-align: center;
    display: inline-block;
    height: 30px;
    margin: 0 6px 0 0;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px; }

/* wishlist block */
#wishlist_block #wishlist_block_list {
  margin: 0 0 20px 0; }
  #wishlist_block #wishlist_block_list dl {
    font-weight: 400; }
    #wishlist_block #wishlist_block_list dl.products.no-products {
      font-weight: 700;
      padding: 0 0 15px 0;
      border-bottom: 1px solid #d6d4d4; }
      #wishlist_block #wishlist_block_list dl.products.no-products dt {
        padding: 0;
        border-top: none; }
      #wishlist_block #wishlist_block_list dl.products.no-products dd {
        display: none; }
    #wishlist_block #wishlist_block_list dl.products {
      border-bottom: 1px solid #d6d4d4; }
      #wishlist_block #wishlist_block_list dl.products dt {
        padding: 20px 0 0;
        border-top: 1px solid #d6d4d4; }
      #wishlist_block #wishlist_block_list dl.products dd {
        padding: 0 0 20px 0; }
      #wishlist_block #wishlist_block_list dl.products dt.first_item {
        padding: 0;
        border-top: none; }
    #wishlist_block #wishlist_block_list dl dt {
      position: relative;
      padding-right: 0; }
    #wishlist_block #wishlist_block_list dl dd {
      margin: 0 0 0 24px; }
#wishlist_block .lnk .form-group {
  margin: 0 0 20px 0; }
  #wishlist_block .lnk .form-group select {
    max-width: 192px; }
    @media (max-width: 767px) {
      #wishlist_block .lnk .form-group select {
        width: 192px; } }
#wishlist_block .ajax_cart_block_remove_link {
  font-size: 14px;
  line-height: 14px;
  color: #d3d2d2;
  width: 14px;
  height: 14px;
  float: right; }
  #wishlist_block .ajax_cart_block_remove_link:hover {
    color: #515151; }
#wishlist_block .cart_block_product_name {
  width: 85%;
  display: inline-block;
  font-weight: bold; }
#wishlist_block .quantity-formated {
  float: left;
  margin: 0 5px 0 0;
  width: 15px; }

#wishlist_block_list .price {
  float: right; }

/* page in my account ************************************************************************* */
#mywishlist td.wishlist_delete a {
  font-size: 15px; }

/* wishlistLinkTop */
#module-blockwishlist-mywishlist #block-order-detail #hideSendWishlist {
  display: inline-block; }

#module-blockwishlist-mywishlist .wishlistLinkTop ul.display_list {
  border-bottom: 1px solid #d6d4d4;
  margin-bottom: 20px; }
  #module-blockwishlist-mywishlist .wishlistLinkTop ul.display_list a {
    display: inline-block;
    color: #333333;
    margin: 10px 10px 10px 0;
    font-weight: bold; }
    #module-blockwishlist-mywishlist .wishlistLinkTop ul.display_list a:hover {
      color: #515151; }

#module-blockwishlist-mywishlist .wishlistLinkTop li {
  float: left; }

#module-blockwishlist-mywishlist .wishlistLinkTop #hideSendWishlist {
  float: right; }

#module-blockwishlist-mywishlist .wishlistLinkTop #showBoughtProducts,
#module-blockwishlist-mywishlist .wishlistLinkTop #hideBoughtProductsInfos {
  display: none; }

/* wlp_bought ****************************************** */
/* wlp_bought_list */
ul.wlp_bought_list li {
  margin: 0 0 30px 0; }
  ul.wlp_bought_list li .product_image {
    border: 1px solid #d6d4d4;
    padding: 9px;
    position: relative;
    background: white;
    margin: 0 0 20px 0;
    max-width: 270px; }
  ul.wlp_bought_list li .product-name {
    margin: 0 0 10px 0;
    padding: 0 20px 0 0; }
    ul.wlp_bought_list li .product-name small {
      display: block;
      font-size: 11px; }
      ul.wlp_bought_list li .product-name small a {
        font-size: 11px; }
  ul.wlp_bought_list li .product_infos {
    position: relative; }
  ul.wlp_bought_list li .btn_action .btn {
    margin: 0 0 10px 0; }
  @media (min-width: 992px) {
    ul.wlp_bought_list li {
      /*> 992px*/ }
      ul.wlp_bought_list li.first-in-line {
        clear: left; } }
  @media (min-width: 768px) and (max-width: 991px) {
    ul.wlp_bought_list li {
      /*768px x 991px*/ }
      ul.wlp_bought_list li.first-item-of-tablet-line {
        clear: left; } }

.wishlistLinkTop .submit {
  margin: 0 0 30px 0; }

ul.wlp_bought_list li .lnkdel {
  position: absolute;
  top: 0;
  right: 0;
  display: block;
  font-size: 14px; }


text:
require 'test_helper'

class OrderTest < ActiveSupport::TestCase
  test "save order" do
    assert build(:order).save
  end
  test "save order without price fails" do
    assert_raise ActiveRecord::RecordInvalid do
      build(:order, price: nil).save!
    end
  end
  test "save order without status fails" do
    assert_raise ActiveRecord::RecordInvalid do
      build(:order, status: nil).save!
    end
  end
end


text:
package gr.iti.mklab.visual.mapreduce;

import gr.iti.mklab.download.ImageDownloadResult;
import gr.iti.mklab.download.ImageDownloader;
import gr.iti.mklab.visual.aggregation.AbstractFeatureAggregator;
import gr.iti.mklab.visual.aggregation.VladAggregatorMultipleVocabularies;
import gr.iti.mklab.visual.dimreduction.PCA;
import gr.iti.mklab.visual.extraction.AbstractFeatureExtractor;
import gr.iti.mklab.visual.extraction.SURFExtractor;
import gr.iti.mklab.visual.vectorization.ImageVectorization;
import gr.iti.mklab.visual.vectorization.ImageVectorizationResult;
import gr.iti.mklab.visual.vectorization.ImageVectorizer;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * The VisualThreadedMapper is responsible for reading the image urls, downloading the images
 * and extracting visual features
 *
 * @author Katerina Andreadou
 */
public class VisualThreadedMapper extends Mapper<LongWritable, Text, Text, FloatArrayWritable> {

    private static int targetLengthMax = 1024;
    private static int maxNumPixels = 768 * 512;
    private static int numVectorizationThreads = 2;
    private static int numDownloadThreads = 10;
    private static ImageDownloader downloader;
    private static ImageVectorizer vectorizer;
    private int submittedDownloadsCounter = 0;
    private int minCallInterval = 60;

    // minimum interval between 2 download calls in msec
    long lastDownLoadCall = 0;

    @Override
    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

        // if there are still urls to be submitted for download and the downloader's queue is not full and
        // the required interval between 2 calls has passed
        String urlLine = value.toString();
        boolean lineConsumed = false;
        while (!lineConsumed) {
            if (downloader.canAcceptMoreTasks()
                    && (System.currentTimeMillis() - lastDownLoadCall) >= minCallInterval
                    && urlLine != null) {
                // parse a new line from the file
                String imageUrl;
                boolean isVideo = false;
                String[] segments = urlLine.split("\\s+");
                // check if there is an id
                if (segments.length > 1) {
                    // assuming the id is first
                    imageUrl = segments[1];
                } else {
                    imageUrl = urlLine;
                }

                if (segments.length > 2 && "video".equals(segments[2]))
                    isVideo = true;

                String imageId = imageUrl;
                if (isVideo)
                    imageId += "-v";

                downloader.submitHadoopDownloadTask(imageUrl, imageId);
                lastDownLoadCall = System.currentTimeMillis();
                submittedDownloadsCounter++;
                lineConsumed = true;
                System.out.println("Submitted download tasks: " + submittedDownloadsCounter + " ulr:" + imageUrl);
            }

            // if there is still space in the vectorizer's queue try to get an image download result and
            // to submit a new image vectorization task
            if (vectorizer.canAcceptMoreTasks()) {
                ImageDownloadResult imdr = null;
                try {
                    imdr = downloader.getImageDownloadResult();
                } catch (Exception e) {
                    //context.write(new Text(e.getMessage()), new FloatArrayWritable(new float[0]));
                }
                if (imdr != null) {
                    BufferedImage image = imdr.getImage();
                    // String url = download.getUrlStr();
                    String id = imdr.getImageId();
                    vectorizer.submitImageVectorizationTask(id, image);
                } // if a download result was successfully retrieved
            }

            // try to get an image vectorization result and to index the vector
            ImageVectorizationResult imvr = null;
            try {
                imvr = vectorizer.getImageVectorizationResult();
            } catch (Exception e) {
                //context.write(new Text(e.getMessage()), new FloatArrayWritable(new float[0]));
            }
            if (imvr != null && imvr.getImageVector() != null) {
                String name = imvr.getImageName();
                double[] vector = imvr.getImageVector();
                context.write(new Text(name), new FloatArrayWritable(VisualJob.castToFloat(vector)));
            }
        }

    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        super.cleanup(context);
        downloader.shutDown();
        vectorizer.shutDown();
    }

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        super.setup(context);
        try {
            initialize(context);
        } catch (Exception ex) {
            throw new IOException(ex);
        }
    }

    private void initialize(Context context) throws Exception {

        int[] numCentroids = {128, 128, 128, 128};
        int initialLength = numCentroids.length * numCentroids[0] * AbstractFeatureExtractor.SURFLength;

        /*if (!VisualJob.IS_LOCAL) {

            Path files[] = DistributedCache.getLocalCacheFiles(context.getConfiguration());
            for (Path path : files) {
                context.write(new Text(path.toString() + " " + path.getName()), new DoubleArrayWritable(new double[0]));
            }
        }*/

        String[] codebookFiles = {
                VisualJob.LEARNING_FILES_PATH + "surf_l2_128c_0.csv",
                VisualJob.LEARNING_FILES_PATH + "surf_l2_128c_1.csv",
                VisualJob.LEARNING_FILES_PATH + "surf_l2_128c_2.csv",
                VisualJob.LEARNING_FILES_PATH + "surf_l2_128c_3.csv"
        };
        String pcaFile = VisualJob.LEARNING_FILES_PATH + "pca_surf_4x128_32768to1024.txt";

        ImageVectorization.setFeatureExtractor(new SURFExtractor());
        double[][][] codebooks = AbstractFeatureAggregator.readQuantizers(codebookFiles, numCentroids,
                AbstractFeatureExtractor.SURFLength);
        ImageVectorization.setVladAggregator(new VladAggregatorMultipleVocabularies(codebooks));
        if (targetLengthMax < initialLength) {
            PCA pca = new PCA(targetLengthMax, 1, initialLength, true);
            pca.loadPCAFromFile(pcaFile);
            ImageVectorization.setPcaProjector(pca);
        }

        // Initialize the downloader, the vectorizer and the indexer
        downloader = new ImageDownloader("", numDownloadThreads);
        downloader.setSaveOriginal(false);
        downloader.setSaveThumb(false);
        downloader.setFollowRedirects(false);
        vectorizer = new ImageVectorizer("surf", codebookFiles, numCentroids,
                targetLengthMax, pcaFile, true, numVectorizationThreads);

    }
}


text:
<?php

namespace ProConfig\Exception;

use Exception;

/**
 * @author Silvio Marijic
 * @package ProConfig
 * @copyright 2015 Silvio Marijic
 * @licence MIT
 */
class ResourceNotSupportedException extends Exception
{

	/**
	 *
	 */
	public function __construct()
	{
		parent::__construct('Parser does not support specified resource');
	}
}


text:
(function (window, document) {

    let login = document.getElementById('login');

    login.addEventListener('submit', function () {
        document.body.classList.add('success');
    });

})(window, document);


text:
package centreon::common::powershell::exchange::2010::queues;

use strict;
use warnings;
use centreon::plugins::misc;
use centreon::common::powershell::exchange::2010::powershell;

sub get_powershell {
    my (%options) = @_;
    # options: no_ps
    my $no_ps = (defined($options{no_ps})) ? 1 : 0;

    return '' if ($no_ps == 1);

    my $ps = centreon::common::powershell::exchange::2010::powershell::powershell_init(%options);

    $ps .= '
try {
    $ErrorActionPreference = "Stop"
    $results = Get-Queue
} catch {
    Write-Host $Error[0].Exception
    exit 1
}

Foreach ($result in $results) {
    Write-Host "[identity=" $result.Identity "][deliverytype=" $result.DeliveryType "][status=" $result.Status "][isvalid=" $result.IsValid "][messagecount=" $result.MessageCount "][[error=" $result.LastError "]]"
}
exit 0
';

    return centreon::plugins::misc::powershell_encoded($ps);
}

sub check {
    my ($self, %options) = @_;
    # options: stdout

    # Following output:
    #[identity=  ][deliverytype= SmtpRelayWithinAdSite][status= Active ][isvalid= Yes][messagecount= 1 ][[error=...]]
    $self->{output}->output_add(severity => 'OK',
                                short_msg => "All Queues are ok.");

    my $checked = 0;
    $self->{output}->output_add(long_msg => $options{stdout});

    $self->{perfdatas_queues} = {};
    while ($options{stdout} =~ /\[identity=(.*?)\]\[deliverytype=(.*?)\]\[status=(.*?)\]\[isvalid=(.*?)\]\[messagecount=(.*?)\]\[\[error=(.*?)\]\]/msg) {
        $self->{data} = {};
        ($self->{data}->{identity}, $self->{data}->{deliverytype}, $self->{data}->{status}, $self->{data}->{isvalid}, $self->{data}->{messagecount}, $self->{data}->{error}) =
            ($self->{output}->to_utf8($1), centreon::plugins::misc::trim($2),
             centreon::plugins::misc::trim($3), centreon::plugins::misc::trim($4), centreon::plugins::misc::trim($5), centreon::plugins::misc::trim($6));

        $checked++;

        my ($status, $message) = ('ok');
        eval {
            local $SIG{__WARN__} = sub { $message = $_[0]; };
            local $SIG{__DIE__} = sub { $message = $_[0]; };

            if (defined($self->{option_results}->{critical}) && $self->{option_results}->{critical} ne '' &&
                eval "$self->{option_results}->{critical}") {
                $status = 'critical';
            } elsif (defined($self->{option_results}->{warning}) && $self->{option_results}->{warning} ne '' &&
                     eval "$self->{option_results}->{warning}") {
                $status = 'warning';
            }
        };
        if (defined($message)) {
            $self->{output}->output_add(long_msg => 'filter status issue: ' . $message);
        }
        if (!$self->{output}->is_status(value => $status, compare => 'ok', litteral => 1)) {
            $self->{output}->output_add(severity => $status,
                                        short_msg => sprintf("Queue '%s' status is '%s' [last error: %s]",
                                                             $self->{data}->{identity}, $self->{data}->{status}, $self->{data}->{error}));
        }

        if ($self->{data}->{messagecount} =~ /^(\d+)/) {
            my $num = $1;
            my $identity = $self->{data}->{identity};

            $identity = $1 if ($self->{data}->{identity} =~ /^(.*\\)[0-9]+$/);
            $self->{perfdatas_queues}->{$identity} = 0 if (!defined($self->{perfdatas_queues}->{$identity}));
            $self->{perfdatas_queues}->{$identity} += $num;
        }
    }

    foreach (keys %{$self->{perfdatas_queues}}) {
        $self->{output}->perfdata_add(label => 'queue_length_' . $_,
                                      value => $self->{perfdatas_queues}->{$_},
                                      min => 0);
    }

    if ($checked == 0) {
        $self->{output}->output_add(severity => 'UNKNOWN',
                                    short_msg => 'Cannot find informations');
    }
}

1;

__END__

=head1 DESCRIPTION

Method to check Exchange 2010 queues.

=cut


text:
package cogdebugger.ui.fieldvisualizations.symmetrictensor

import libcog._
import libcog.fields.SymmetricTensor
import cogdebugger.ui.fieldvisualizations._
import cogdebugger.{ToolFactory, BooleanProperty, RestorableState}
import scala.swing._
import scala.xml.{Node, Elem}
import scala.swing.event.ValueChanged
import java.awt.geom.{Line2D, Ellipse2D}

/** A panel which displays a symmetric tensor field as geometrical objects.
  *
  * @param fieldShape Shape of the symmetric tensor field being displayed.
  *
  * @author Greg Snider
  */
class SymmetricGeometrySubpanel(fieldShape: Shape, tensorShape: Shape)
        extends TileBasedFieldPanel[VectorFieldReader](fieldShape)
        with Viewer
        with RestorableState
        with ToolbarItems
{
  require(tensorShape.dimensions == 1)
  require(tensorShape(0) == SymmetricTensor.Components)

  val FloatingMaxProperty = new BooleanProperty("Floating Max", false)
  properties += ZoomProperty
  properties += FloatingMaxProperty

  // Cumulative (over time) max magnitude in field.
  private var absMaxMagnitude  = Float.MinValue
  // Current max magnitude in field.
  private var stepMaxMagnitude = Float.MinValue
  // Max magnitude as desired by user.
  private def maxMagnitude =
    if (FloatingMaxProperty.value) stepMaxMagnitude
    else absMaxMagnitude

  /** Updates the visualization based on the contents of `data`. */
  def update(src: AnyRef, data: AbstractFieldMemory, time: Long) {
    super.update(src, data.asInstanceOf[VectorFieldMemory])
  }

  /** Compute any needed statistics on your data (for display or to help draw
    * later). Called after new data has been received (in updateData) and
    * before drawing begins for that new data. */
  def updateStatistics(data: VectorFieldReader) {
    stepMaxMagnitude = Float.MinValue
    forEachTensorIn(data) {
      vector =>
        val tensor = new SymmetricTensor(vector)
        val stickness = tensor.stickness
        val ballness = tensor.ballness
        val magnitude = stickness + ballness
        if (magnitude > absMaxMagnitude) {
          absMaxMagnitude = magnitude
          stepMaxMagnitude = magnitude
        } else if (magnitude > stepMaxMagnitude) {
          stepMaxMagnitude = magnitude
        }
    }
    publish(new ValueChanged(this))
  }

  /** Draw the single field element at the given indices.
    *
    * Called after the pen has been moved to the top-left corner of the cell to
    * draw in. Clients should take care to draw within the bounds of the cell,
    * which is a cellSize by cellSize square.
    *
    * It would be nice if we could give an element as an argument instead of a
    * bunch of indices, but the Field class doesn't currently define any means
    * to actually extract elements from the field; that's left to subclasses.
    * Further complicating things, the panel classes don't know in advance how
    * many dimensions the data field has, so we have to use a variable length
    * indices parameter. If your field class has a read(indices: Int*) method,
    * you can get the current element, regardless of field dimensions, like so:
    * {{{
    *   val element = read(indices: _*)
    * }}}
    */
  def drawElement(data: VectorFieldReader, g: Graphics2D, indices: Int*) {
    val vector = new Vector(SymmetricTensor.Components)
    dim match {
      case 0 => data.read(vector)
      case 1 => data.read(indices(0), vector)
      case 2 => data.read(indices(0), indices(1), vector)
      case 3 => data.read(indices(0), indices(1), indices(2), vector)
      case n => throw new UnsupportedDimensionException(n)
    }
    val tensor = new SymmetricTensor(vector)
    val ballness = tensor.ballness
    val stickness = tensor.stickness
    var angle = tensor.orientation
    val magnitude = (stickness + ballness) / maxMagnitude

    // Compute line segment in (x, y) plane
    val deltaX = magnitude * math.cos(angle) * (cellSize / 2)
    val deltaY = -magnitude * math.sin(angle) * (cellSize / 2)
    line.setLine(center - deltaX, center - deltaY, center + deltaX, center + deltaY)

    // Compute circle in (x, y) plane
    val diameter = (ballness / maxMagnitude) * cellSize
    val circleX = center - diameter / 2
    val circleY = center - diameter / 2
    val circleWidth = diameter
    val circleHeight = diameter
    circle.setFrame(circleX, circleY, circleWidth, circleHeight)

    val oldColor = g.getColor
    g.setColor(java.awt.Color.LIGHT_GRAY)
    g.draw(circle)
    g.setColor(oldColor)

    g.draw(line)
  }

  // Shapes'n'things used for drawing.
  private val circle = new Ellipse2D.Double(cellSize / 2 - 1, cellSize / 2 - 1,
    2, 2)
  private val line  = new Line2D.Double() // Reuse to avoid creation overhead
  private def center = cellSize / 2

  protected def forEachTensorIn(data: VectorFieldReader)(op: Vector => Unit) {
    val vector = new Vector(SymmetricTensor.Components)
    for (l <- 0 until layers; r <- 0 until rows; c <- 0 until cols)
      op(read(data, l, r, c, vector))
  }

  private def read(data: VectorFieldReader, l: Int, r: Int, c: Int, vector: Vector): Vector = {
    dim match {
      case 0 => data.read(vector)
      case 1 => data.read(c, vector)
      case 2 => data.read(r, c, vector)
      case 3 => data.read(l, r, c, vector)
      case n => throw new UnsupportedDimensionException(n)
    }
    vector
  }

  def save: Elem =
    <SymmetricGeometrySubpanel>
      { propertiesTag }
    </SymmetricGeometrySubpanel>

  def restore(tag: Node) {
    (tag \ "SymmetricGeometrySubpanel" \ "properties").headOption.foreach(xmlToProperties)
  }

  private val Outer = this

  /** Toolbar for controlling view of complex field. */
  def toolbarComponents: Seq[ComponentGroup] = {
    val floatingMaxButton = ToolFactory.toggle(FloatingMaxProperty)
    val maxMagLabel = new Label()
    maxMagLabel.listenTo(Outer)
    reactions += {
      case ValueChanged(Outer) =>
        maxMagLabel.text = "%6.3f".format(maxMagnitude)
    }
    Seq(ComponentGroup(floatingMaxButton),
        ComponentGroup(new Label("Max magnitude:"), Swing.HStrut(5), maxMagLabel))
  }
}