text:
// Implementation of LLVMUtils, useful common LLVM-related functionality.
//
// Copyright (c) 2013-2019 Pekka Jääskeläinen
//
// 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.

#include "LLVMUtils.h"

#include "pocl_spir.h"

#include "CompilerWarnings.h"
IGNORE_COMPILER_WARNING("-Wunused-parameter")

#include <llvm/IR/Instructions.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Metadata.h>
#include <llvm/IR/Constants.h>

using namespace llvm;

namespace pocl {

/**
 * Regenerates the metadata that points to the original kernel
 * (of which finger print was modified) to point to the new
 * kernel.
 *
 * Only checks if the first operand of the metadata is the kernel
 * function.
 */
void
regenerate_kernel_metadata(llvm::Module &M, FunctionMapping &kernels)
{
  // reproduce the opencl.kernel_wg_size_info metadata
  NamedMDNode *wg_sizes = M.getNamedMetadata("opencl.kernel_wg_size_info");
  if (wg_sizes != NULL && wg_sizes->getNumOperands() > 0)
    {
      for (std::size_t mni = 0; mni < wg_sizes->getNumOperands(); ++mni)
        {
          MDNode *wgsizeMD = dyn_cast<MDNode>(wg_sizes->getOperand(mni));
          for (FunctionMapping::const_iterator i = kernels.begin(),
                 e = kernels.end(); i != e; ++i)
            {
              Function *old_kernel = (*i).first;
              Function *new_kernel = (*i).second;
              Function *func_from_md;
              func_from_md = dyn_cast<Function>(
                dyn_cast<ValueAsMetadata>(wgsizeMD->getOperand(0))->getValue());
              if (old_kernel == new_kernel || wgsizeMD->getNumOperands() == 0 ||
                  func_from_md != old_kernel)
                continue;
              // found a wg size metadata that points to the old kernel, copy its
              // operands except the first one to a new MDNode
              SmallVector<Metadata*, 8> operands;
              operands.push_back(llvm::ValueAsMetadata::get(new_kernel));
              for (unsigned opr = 1; opr < wgsizeMD->getNumOperands(); ++opr) {
                  operands.push_back(wgsizeMD->getOperand(opr));
              }
              MDNode *new_wg_md = MDNode::get(M.getContext(), operands);
              wg_sizes->addOperand(new_wg_md);
            }
        }
    }

  // reproduce the opencl.kernels metadata, if it exists
  // unconditionally adding opencl.kernels confuses the
  // metadata parser in pocl_llvm_metadata.cc, which uses
  // "opencl.kernels" to distinguish old SPIR format from new
  NamedMDNode *nmd = M.getNamedMetadata("opencl.kernels");
  if (nmd) {
    M.eraseNamedMetadata(nmd);

    nmd = M.getOrInsertNamedMetadata("opencl.kernels");
    for (FunctionMapping::const_iterator i = kernels.begin(),
         e = kernels.end();
       i != e; ++i) {
      MDNode *md = MDNode::get(M.getContext(), ArrayRef<Metadata *>(
        llvm::ValueAsMetadata::get((*i).second)));
      nmd->addOperand(md);
    }
  }

}

void eraseFunctionAndCallers(llvm::Function *Function) {
  if (!Function)
    return;

  std::vector<llvm::Value *> Callers(Function->user_begin(),
                                     Function->user_end());
  for (auto &U : Callers) {
    llvm::CallInst *Call = llvm::dyn_cast<llvm::CallInst>(U);
    if (!Call)
      continue;
    Call->eraseFromParent();
  }
  Function->eraseFromParent();
}

int getConstantIntMDValue(Metadata *MD) {
#ifdef LLVM_OLDER_THAN_7_0
  ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(MD);
#else
  ConstantInt *CI = mdconst::extract<ConstantInt>(MD);
#endif
  return CI->getLimitedValue();
}

llvm::Metadata *createConstantIntMD(llvm::LLVMContext &C, int32_t Val) {
  IntegerType *I32Type = IntegerType::get(C, 32);
  return ConstantAsMetadata::get(ConstantInt::get(I32Type, Val));
}

bool isLocalMemFunctionArg(llvm::Function *F, unsigned ArgIndex) {

  MDNode *MD = F->getMetadata("kernel_arg_addr_space");

  if (MD == nullptr || MD->getNumOperands() <= ArgIndex)
    return false;
  else
    return getConstantIntMDValue(MD->getOperand(ArgIndex)) ==
           SPIR_ADDRESS_SPACE_LOCAL;
}

void setFuncArgAddressSpaceMD(llvm::Function *F, unsigned ArgIndex,
                              unsigned AS) {

  unsigned MDKind = F->getContext().getMDKindID("kernel_arg_addr_space");
  MDNode *OldMD = F->getMetadata(MDKind);

  assert(OldMD == nullptr || OldMD->getNumOperands() >= ArgIndex);

  LLVMContext &C = F->getContext();

  llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
  for (unsigned i = 0; i < ArgIndex; ++i) {
    AddressQuals.push_back(createConstantIntMD(
        C, OldMD != nullptr ? getConstantIntMDValue(OldMD->getOperand(i))
                            : SPIR_ADDRESS_SPACE_GLOBAL));
  }
  AddressQuals.push_back(createConstantIntMD(C, AS));
  F->setMetadata(MDKind, MDNode::get(F->getContext(), AddressQuals));
}
}


text:
from ZSI import TC

class User:
    def __init__(self, name=None, userId=None, age=-1):
        self.Name = name
        self.UserId = userId
        self.Age = age

User.typecode = TC.Struct(User,
                          [TC.String('Name', oname='Name'),
                           TC.String('UserId', oname='UserId'),
                           TC.Iinteger('Age', oname='Age')],
                           'types:User')

redpajama_set_name: RedPajamaGithub


text:
package cgeo.geocaching.ui.dialog;

import cgeo.geocaching.ui.ImageParam;
import cgeo.geocaching.ui.TextParam;
import cgeo.geocaching.utils.CollectionStream;
import cgeo.geocaching.utils.functions.Action1;
import cgeo.geocaching.utils.functions.Action2;

import android.app.Activity;

import androidx.annotation.DrawableRes;
import androidx.annotation.StringRes;

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

/**
 * Represents a dialog usable as a context menu for various elements.
 *
 * Supports textual items with or without accompanying icon.
 */
public class ContextMenuDialog {

    private final Activity activity;
    private String title;

    private final List<Item> items = new ArrayList<>();
    private Action1<Integer> dialogClickAction;

    public ContextMenuDialog setTitle(final String title) {
        this.title = title;
        return this;
    }

    public ContextMenuDialog(final Activity activity) {
        this.activity = activity;
    }

    public ContextMenuDialog addItem(final String text) {
        addItem(text, 0);
        return this;
    }

    public ContextMenuDialog addItem(final String text, @DrawableRes final int icon) {
        addItem(text, icon, null);
        return this;
    }

    public ContextMenuDialog addItem(@StringRes final int textId, @DrawableRes final int icon, final Action1<Item> selectAction) {
        items.add(new Item(this.activity.getResources().getString(textId), icon, selectAction));
        return this;
    }

    public ContextMenuDialog addItem(final String text, @DrawableRes final int icon, final Action1<Item> selectAction) {
        items.add(new Item(text, icon, selectAction));
        return this;
    }

    public ContextMenuDialog setOnClickAction(final Action1<Integer> clickAction) {
        this.dialogClickAction = clickAction;
        return this;
    }

    public void show() {

        final boolean atLeastOneElementHasIcon = CollectionStream.of(items).filter(i -> i.icon > 0).count() > 0;

        final Action2<Item, Integer> clickListener = (dialog, pos) -> {
            //dialog.dismiss();
            final Item it = this.items.get(pos);
            if (it.selectAction != null) {
                it.selectAction.call(it);
            }
            if (dialogClickAction != null) {
                dialogClickAction.call(pos);
            }
        };

        SimpleDialog.of(this.activity).setTitle(this.title == null ? null : TextParam.text(this.title)).selectSingle(
                items,
                (it, pos) -> TextParam.text(it.toString()).setImage(atLeastOneElementHasIcon ? ImageParam.id(it.icon) : null, atLeastOneElementHasIcon ? 30 : 0),
                -1, SimpleDialog.SingleChoiceMode.NONE, clickListener);
    }

    public static class Item {
        public final String text;
        public final int icon;
        public final Action1<Item> selectAction;

        public Item(final String text, @DrawableRes final int icon, final Action1<Item> selectAction) {
            this.text = text;
            this.icon = icon;
            this.selectAction = selectAction;
        }

        @Override
        public String toString() {
            return text;
        }
    }

}


text:
'use strict';

import './personality.module';
import './ramda.module';
import './percent.filter';

angular.module('app', [
  'personality',
  'percent.filter',
  'ramda'
]);


text:
const assert = require('assert');

describe('suite', () => {
  it('case', () => {
    assert.equal(true, true);
  });
});


text:
'use strict';

(function (scope) {
    /**
     * Analyzer stroke type
     *
     * @class AnalyzerStrokeType
     * @param {Object} [obj]
     * @constructor
     */
    function AnalyzerStrokeType(obj) {
        if (obj) {
            this.inkRange = new scope.AnalyzerInkRange(obj.inkRange);
            this.type = obj.type;
        }
    }

    /**
     * Get ink range
     *
     * @method getInkRange
     * @returns {AnalyzerInkRange}
     */
    AnalyzerStrokeType.prototype.getInkRange = function () {
        return this.inkRange;
    };

    /**
     * Get type
     *
     * @method getType
     * @returns {String}
     */
    AnalyzerStrokeType.prototype.getType = function () {
        return this.type;
    };

    // Export
    scope.AnalyzerStrokeType = AnalyzerStrokeType;
})(MyScript);


text:
#include <Scene/Member/cModeSelect.h>
#include <CameraManager/cCameraManager.h>
#include "Resource\TextureManager.h"
#include"cinder\gl\gl.h"
#include <Utility/cInput.h>
#include "cinder\Easing.h"
#include "Particle\cParticleManager.h"
#include <Sound/Wav.h>
#include"Resource\cSoundManager.h"
#include <Scene/Member/Tutorial.h>
#include <Network.hpp>
#include <Scene/Member/cMatching.h>
#include <Scene/Member/cGameMain.h>
#include <Scene/cSceneManager.h>
#include <Game/cGameManager.h>
#include <Scene/Member/cTitle.h>
#include"Resource\cImageManager.h"
#include <Network.hpp>
#include <Resource/cJsonManager.h>
#include <Network/cMatchingMemberManager.h>
using namespace ci;
using namespace ci::app;

using namespace Node;

using namespace Node::Action;

using namespace Network;
using namespace Network::Packet::Event;
using namespace Network::Packet::Request;
using namespace Network::Packet::Response;
namespace Scene
{
namespace Member
{
cModeSelect::cModeSelect( )
{

}
cModeSelect::~cModeSelect( )
{

}
void cModeSelect::setup()
{
	auto bgm = Sound::Wav(cinder::app::getAssetDirectories().front().string() + "/BGM/modeselect.wav");
	introloopBGM.create(bgm.data(), bgm.size(), 22.130F, 78.594F);
	introloopBGM.gain(0.15F);
	introloopBGM.play();
	CAMERA->refPosition = ci::vec3(0,0,-0.001);
	ENV->setMouseControl(false);
	CAMERA->setCameraAngle(ci::vec2(M_PI/18.f, M_PI / 18.f));
	CAMERA->setup();
	createTextureNames();

	for (float i = 0; i < 4; i++) {
		mSelectCards.push_back(std::make_shared<ModeSelect::cSelectCard>(i*2.f*M_PI / 4.f, iconnames[i], ci::vec3(0, 0.5, 3), ci::vec3(2.5, 0.5, 4.75),i));
	}
	root = Node::node::create();
	root->set_content_size(app::getWindowSize());
	root->set_schedule_update();
	root->set_scale(vec2(1, -1));
	root->set_position(root->get_content_size() * vec2(-0.5F, 0.5F));

	auto fader = root->add_child(Node::Renderer::rect::create(app::getWindowSize()));
	fader->set_color(ColorA(0, 0, 0, 1));
	fader->set_anchor_point(vec2(0, 0));
	fader->run_action(sequence::create( fade_out::create(1.0F), call_func::create([this]
	{
		this->isfading = false;
		//ci::app::console() << "'Ó'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨'¨	" << std::endl;
	})));
	//this->isfading = false;
}
void cModeSelect::shutDown()
{
	mSelectCards.clear();
	iconnames.clear();
	introloopBGM.stop();
}
void cModeSelect::update(float t)
{

	for (auto& it : mSelectCards) {
		it->update(t);
	}
	updateBackGround(t);
	updateButtonAlfa(t);
	updateArrow(t);
	introloopBGM.update(t);
	selectIcon();
	if (watching == false)
		if (ENV->pushKey(ci::app::KeyEvent::KEY_RETURN)|| ENV->isPadPush(ENV->BUTTON_2))
		{
			desideScene();
		}

	root->entry_update(t);

	if (watching == false)
	{

		if (ENV->pushKey(ci::app::KeyEvent::KEY_a))
		{
			watching = true;
			Network::cUDPClientManager::getInstance()->open();
			cUDPClientManager::getInstance()->connect(Resource::JSON["server.json"]["ip"].asString());
			fase = WatchFase::NONE;
		}
	}

	else
	{
		Network::cUDPClientManager::getInstance()->update(t);
		if (cUDPClientManager::getInstance()->isConnected() == false)return;

		if (fase == WatchFase::NONE)
		{
			cUDPClientManager::getInstance()->send(new cReqInRoomWatching(100),true);
			fase = WatchFase::BEIGN;
		}

		else if (fase == WatchFase::BEIGN)
		{
			auto m = Network::cUDPClientManager::getInstance()->getUDPManager();

			while (auto resInRoom = m->ResInRoom.get())
			{
				if (resInRoom->mFlag = false)
				{
					cUDPClientManager::getInstance()->send(new cReqInRoom(100),true);
					continue;
				}
				cUDPClientManager::getInstance()->send(new cReqWantTeamIn(0),true);
				fase = WatchFase::WAIT;
			}
		}

		else if (fase == WatchFase::WAIT)
		{
			auto m = Network::cUDPClientManager::getInstance()->getUDPManager();
			while (auto resWantTeamIn = m->ResWantTeamIn.get())
			{
				if (resWantTeamIn->mFlag == 1)
				Network::cMatchingMemberManager::getInstance()->mPlayerTeamNum = resWantTeamIn->mTeamNum;;
			}
			while (auto eveTeamMember = m->EveTeamMember.get())
			{
				cMatchingMemberManager::getInstance()->addPlayerDatas(
					eveTeamMember->mNameStr, eveTeamMember->mTeamNum, eveTeamMember->mPlayerID, cNetworkHandle("", 0));
			}
			while (auto resCheckBeginGame = m->ResCheckBeginGame.get())
			{
				cMatchingMemberManager::getInstance()->mPlayerID = resCheckBeginGame->mPlayerID;
				cSceneManager::getInstance()->shift<Scene::Member::cGameMain>();
				continue;
			}
		}

	}

}
void cModeSelect::draw()
{
	mDrawFunc.drawTextureCube(ci::vec3(0), ci::vec3(16, 9, 20), ci::vec3(M_PI/12.f, 0, mBackGroundRotateZ), "modeselect/selectsky.png", ci::ColorA(1, 1, 1));

	for (auto& it : mSelectCards) {
		it->draw();
	}
	drawButton();

	mDrawFunc.drawTextureRect3D(ci::vec3(-0.85-aroowtranceY/2.f, -0.7+aroowtranceY,-0.3), ci::vec3(0.8, 0.16,0),ci::vec3(0,0,M_PI- M_PI / 12.f) , "modeselect/redright.png", ci::ColorA(1, 1, 1, arrowAlfa));
	mDrawFunc.drawTextureRect3D(ci::vec3(1.55+aroowtranceY/2.f, -0.7 + aroowtranceY, -0.3), ci::vec3(-0.8, 0.12, 0), ci::vec3(0, 0, M_PI + M_PI / 4.25f),  "modeselect/redright.png", ci::ColorA(1, 1, 1, arrowAlfa));
	//mDrawFunc.drawTextureRect3D(ci::vec3(-400, -175 + aroowtranceY), ci::vec3(250, 50), M_PI - M_PI / 9.f, "redright.png", ci::ColorA(1, 1, 1, arrowAlfa));
}
void cModeSelect::draw2D()
{
	/*mDrawFunc.drawTextureRect2D(ci::vec2(400,-175+aroowtranceY), ci::vec2(-250, 50), M_PI+M_PI/9.f, "redright.png", ci::ColorA(1, 1, 1,arrowAlfa));
	mDrawFunc.drawTextureRect2D(ci::vec2(-400, -175+aroowtranceY), ci::vec2(250, 50), M_PI - M_PI / 9.f, "redright.png", ci::ColorA(1, 1,1, arrowAlfa));*/
	mDrawFunc.drawTextureRect2D(ci::vec2(550,-320), ci::vec2(-590,449)*0.52f, M_PI, "title/logo.png", ci::ColorA(1, 1, 1, 1));
	root->entry_render(mat4());
}
void cModeSelect::resize()
{

}

void cModeSelect::createTextureNames()
{
	iconnames.push_back("modeselect/online.png");
	iconnames.push_back("modeselect/tutorial.png");
	iconnames.push_back("modeselect/gotitle.png");
	iconnames.push_back("modeselect/training.png");

}

void cModeSelect::changeScene()
{

	switch (MSelectScene)
	{
	case 0:
		shiftOnlineBattle();
		return;
	case 1:
		shiftTutorial();
		return;
	case 2:
		shiftTitle();
		return;
	case 3:
		shiftLocalBattle();
		return;
	default:
		break;
	}
}

void cModeSelect::selectIcon()
{
	if (isfading)return;

	if (ENV->pushKey(ci::app::KeyEvent::KEY_LEFT)||ENV->getPadAxisPushMinus(0)) {
		Resource::cSoundManager::getInstance()->findSe("ModeSelect/cursor.wav").setGain(0.4f);
		Resource::cSoundManager::getInstance()->findSe("ModeSelect/cursor.wav").play();
		for (auto& it : mSelectCards) {
			it->setEasing(true);
		}
		MSelectScene++;
		if (MSelectScene == 4)MSelectScene = 0;
		return;
	}
	if (ENV->pushKey(ci::app::KeyEvent::KEY_RIGHT) || ENV->getPadAxisPushPlus(0)) {
		Resource::cSoundManager::getInstance()->findSe("ModeSelect/cursor.wav").setGain(0.4f);
		Resource::cSoundManager::getInstance()->findSe("ModeSelect/cursor.wav").play();
		for (auto& it : mSelectCards) {
			it->setEasing(false);
		}
		MSelectScene--;
		if (MSelectScene < 0)MSelectScene = 3;
		return;
	}
}

void cModeSelect::shiftOnlineBattle()
{
	//introloopBGM.stop();
	cSceneManager::getInstance()->shift<Scene::Member::cMatching>();
}

void cModeSelect::shiftTitle()
{
	//introloopBGM.stop();
	cSceneManager::getInstance()->shift<Scene::Member::cTitle>();
}

void cModeSelect::shiftLocalBattle()
{
	//introloopBGM.stop();
	Network::cUDPClientManager::getInstance()->open();
	Network::cUDPServerManager::getInstance()->open();
	Network::cUDPClientManager::getInstance()->connectOfflineServer();
	Game::cGameManager::getInstance()->setTime(0.0F);
	cSceneManager::getInstance()->shift<Scene::Member::cGameMain>();
}

void cModeSelect::shiftTutorial()
{
	//introloopBGM.stop();
	Network::cUDPClientManager::getInstance()->open();
	Network::cUDPServerManager::getInstance()->open();
	Network::cUDPClientManager::getInstance()->connectOfflineServer();
	Game::cGameManager::getInstance()->setTime(0.0F);
	cSceneManager::getInstance()->shift<Scene::Member::cTutorial>();
}

void cModeSelect::desideScene()
{
	if (isfading)return;
	for (auto& it : mSelectCards) {
		if (it->getIsEasing())return;//ƒC[ƒWƒ"ƒO'†'Í–³Œø
	}
	Resource::cSoundManager::getInstance()->findSe("ModeSelect/return.wav").setGain(0.8f);
	Resource::cSoundManager::getInstance()->findSe("ModeSelect/return.wav").play();
	introloopBGM.fadeout(0.9f,0.0f);
	isfading = true;
	auto fader = root->add_child(Node::Renderer::rect::create(app::getWindowSize()));
	fader->set_color(ColorA(0, 0, 0, 0));
	fader->set_anchor_point(vec2(0, 0));
	fader->run_action(sequence::create( fade_in::create(1.0F), call_func::create([this]
	{
		this->changeScene();
	})));
}

void cModeSelect::updateBackGround(float t)
{
	mBackGroundRotateZ += 0.02f*t;
}

void cModeSelect::drawButton()
{
	ci::vec3 pos = ci::vec3(-0.5, -0.4, -1.78);
	mDrawFunc.drawTextureRect3D(pos, ci::vec3(0.2, 0.2, 0), ci::vec3(0, M_PI, 0), "modeselect/buttonb.png", ci::ColorA(1, 1, 1, 1));
	mDrawFunc.drawTextureRect3D(pos+ci::vec3(0,0,-0.01), ci::vec3(0.2, 0.2, 0)*buttonscale, ci::vec3(0, M_PI, 0), "modeselect/ring.png", ci::ColorA(1, 1, 0, buttonalfa));

}

void cModeSelect::updateButtonAlfa(float t)
{
	float speed = 2.18f;
	buttonAlfaT += speed*t;
	bool isend = false;
	if (buttonAlfaT >= 1.0f) {
		buttonAlfaT = 1.0f;
		isend = true;
	}
	buttonalfa = EaseCubicIn(buttonAlfaT, 0.4f, 0.8f);
	buttonscale = EaseCubicIn(buttonAlfaT, 0.8f, 1.2f);
	if (isend) {
		buttonAlfaT = 0.0f;
	}

}

void cModeSelect::updateArrow(float t)
{
	float speed = 1.09f;
	arrowT += speed*t;
	bool isend = false;
	if (arrowT >= 1.0f) {
		arrowT = 1.0f;
		isend = true;
	}
	aroowtranceY = EaseReturn(arrowT, 0, 0.05f);//'P'T
	arrowAlfa = EaseReturn(arrowT, 0.5f, 0.5f);
	if (isend) {
		arrowT = 0.0f;
	}
}

float cModeSelect::EaseReturn(const float t, const float s, const float e)
{
	return s + -4.f*e*(t - 0.5f)*(t - 0.5f) + e;
}

}
}


text:
"""Class for Modulo Clock resource generator."""

from PIL import Image, ImageDraw, ImageFont
from math import pi, sin, cos
from resources.utils.BaseResourceGenerator import BaseResourceGenerator
from django.utils.translation import ugettext_lazy as _
from resources.utils.resource_parameters import EnumResourceParameter

MODULO_NUMBER_VALUES = {
    "1": _("Blank"),
    "2": "2",
    "10": "10",
}

class ModuloClockResourceGenerator(BaseResourceGenerator):
    """Class for Modulo Clock resource generator."""

    @classmethod
    def get_additional_options(cls):
        """Additional options for ModuloClockResourceGenerator."""
        return {
            "modulo_number": EnumResourceParameter(
                name="modulo_number",
                description=_("Modulo"),
                values=MODULO_NUMBER_VALUES,
                default="10",
            )
        }

    def data(self):
        """Create a image for Modulo Clock resource.

        Returns:
            A dictionary for the resource page.
        """
        image_path = "static/img/resources/modulo-clock/modulo-clock-{}.png"

        modulo_number = int(self.options["modulo_number"].value)
        image = Image.open(image_path.format(modulo_number))
        draw = ImageDraw.Draw(image)

        font_size = 150
        font_path = "static/fonts/PatrickHand-Regular.ttf"
        font = ImageFont.truetype(font_path, font_size)

        radius = 750
        x_center = image.width / 2
        y_center = image.height / 2
        # Count from the '12 oclock position'
        start_angle = pi * 1.5
        angle_between_numbers = (2 * pi) / modulo_number

        for number in range(0, modulo_number):
            text = str(number)
            angle = start_angle + (angle_between_numbers * number)
            x_coord = radius * cos(angle) + x_center
            y_coord = radius * sin(angle) + y_center
            text_width, text_height = draw.textsize(text, font=font)
            text_coord_x = x_coord - (text_width / 2)
            text_coord_y = y_coord - (text_height / 2)
            draw.text(
                (text_coord_x, text_coord_y),
                text,
                font=font,
                fill="#000"
            )

        return {"type": "image", "data": image}

    @property
    def subtitle(self):
        """Return the subtitle string of the resource.

        Used after the resource name in the filename, and
        also on the resource image.

        Returns:
            Text for subtitle (str).
        """
        modulo_number = self.options["modulo_number"].value
        if modulo_number == "1":
            modulo_text = _("Blank")
        else:
            modulo_text = modulo_number
        return "{} - {}".format(
            modulo_text,
            super().subtitle
        )


text:
"use strict";

const http = require('http');
const assert = require('assert');
const helpers = require('./helpers');
const ipResolver = require('../lib/reverse-proxy-rate-limiter/ipresolver');

const EXPECTED = "expected";
const ACTUAL = "actual";
const HOST = "localhost";
const PORT = "9876";

const TEST_FORWARD_HEADERS = {
    "X-TEST-FORWARDED-FOR": {
        "ignored_ip_ranges": [
            "127.0.0.0/8",
            "10.0.0.0/8",
            "172.16.0.0/12",
            "192.0.2.0/24",
            "12.34.0.0/16"
        ]
    }
};

const TEST_FORWARD_HEADER = 'X-TEST-FORWARDED-FOR';

const CLIENT_IP = "12.34.56.78";
const LOCAL_HOST = "127.0.0.1";
const SOME_IP = "11.22.33.44";
const IP_LIST = CLIENT_IP + ", " + LOCAL_HOST;
const LONG_IP_LIST = SOME_IP + " ," + IP_LIST;

function createRequest(headers, expected, done) {
    headers[EXPECTED] = expected;
    const options = {
        hostname: HOST,
        path: '/',
        port: PORT,
        headers: headers
    };
    const req = http.request(options, function (response) {
        assert.strictEqual(response.headers[ACTUAL], expected);
        done();
    });
    req.end();
}

describe("Client IP tests", function () {
    let headers;
    let httpServer;

    before(function (done) {
        httpServer = http.createServer(function (req, res) {
            const ip = new ipResolver.IPResolver(TEST_FORWARD_HEADERS).resolve(req);
            res.setHeader(ACTUAL, ip);
            res.setHeader("Connection", "close");
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end();
        }).listen(PORT, HOST, done);
    });

    after(function (done) {
        httpServer.close(function () {
            done();
        });
    });

    beforeEach(function () {
        headers = {};
    });

    it("CUSTOM_HEADER: if available, takes precedence", function (done) {
        headers[TEST_FORWARD_HEADER] = CLIENT_IP;
        headers[ipResolver.PROXY_HEADER] = LOCAL_HOST;
        createRequest(headers, CLIENT_IP, done);
    });

    it("CUSTOM_HEADER: the last ip in the list is always correct", function (done) {
        headers[TEST_FORWARD_HEADER] = IP_LIST;
        createRequest(headers, LOCAL_HOST, done);
    });

    it("CUSTOM_HEADER: custom header can ignore any ip ranges", function (done) {
        headers[TEST_FORWARD_HEADER] = LONG_IP_LIST;
        createRequest(headers, SOME_IP, done);
    });

    it("PROXY_HEADER: if no custom header, PROXY_HEADER takes precedence", function (done) {
        headers[ipResolver.PROXY_HEADER] = CLIENT_IP;
        createRequest(headers, CLIENT_IP, done);
    });

    it("PROXY_HEADER: the last public ip is the one we need", function (done) {
        headers[ipResolver.PROXY_HEADER] = LONG_IP_LIST;
        createRequest(headers, CLIENT_IP, done);
    });

    it("PROXY_HEADER: if there is no public ip return private", function (done) {
        headers[ipResolver.PROXY_HEADER] = LOCAL_HOST;
        createRequest(headers, LOCAL_HOST, done);
    });

    it("REMOTE_ADDR: no proxies involved, use what we get from server", function (done) {
        createRequest(headers, LOCAL_HOST, done);
    });
});


text:
package org.optaplanner.core.impl.score.buildin.hardsoftlong;

import org.junit.Test;
import org.optaplanner.core.api.score.buildin.hardsoftlong.HardSoftLongScore;
import org.optaplanner.core.config.score.trend.InitializingScoreTrendLevel;
import org.optaplanner.core.impl.score.trend.InitializingScoreTrend;

import static org.junit.Assert.*;

public class HardSoftLongScoreDefinitionTest {

    @Test
    public void getLevelSize() {
        assertEquals(2, new HardSoftLongScoreDefinition().getLevelsSize());
    }

    @Test
    public void getLevelLabels() {
        assertArrayEquals(new String[]{"hard score", "soft score"}, new HardSoftLongScoreDefinition().getLevelLabels());
    }

    @Test
    public void getFeasibleLevelsSize() {
        assertEquals(1, new HardSoftLongScoreDefinition().getFeasibleLevelsSize());
    }

    @Test
    public void buildOptimisticBoundOnlyUp() {
        HardSoftLongScoreDefinition scoreDefinition = new HardSoftLongScoreDefinition();
        HardSoftLongScore optimisticBound = scoreDefinition.buildOptimisticBound(
                InitializingScoreTrend.buildUniformTrend(InitializingScoreTrendLevel.ONLY_UP, 2),
                HardSoftLongScore.valueOf(-1L, -2L));
        assertEquals(0, optimisticBound.getInitScore());
        assertEquals(Long.MAX_VALUE, optimisticBound.getHardScore());
        assertEquals(Long.MAX_VALUE, optimisticBound.getSoftScore());
    }

    @Test
    public void buildOptimisticBoundOnlyDown() {
        HardSoftLongScoreDefinition scoreDefinition = new HardSoftLongScoreDefinition();
        HardSoftLongScore optimisticBound = scoreDefinition.buildOptimisticBound(
                InitializingScoreTrend.buildUniformTrend(InitializingScoreTrendLevel.ONLY_DOWN, 2),
                HardSoftLongScore.valueOf(-1L, -2L));
        assertEquals(0, optimisticBound.getInitScore());
        assertEquals(-1L, optimisticBound.getHardScore());
        assertEquals(-2L, optimisticBound.getSoftScore());
    }

    @Test
    public void buildPessimisticBoundOnlyUp() {
        HardSoftLongScoreDefinition scoreDefinition = new HardSoftLongScoreDefinition();
        HardSoftLongScore pessimisticBound = scoreDefinition.buildPessimisticBound(
                InitializingScoreTrend.buildUniformTrend(InitializingScoreTrendLevel.ONLY_UP, 2),
                HardSoftLongScore.valueOf(-1L, -2L));
        assertEquals(0, pessimisticBound.getInitScore());
        assertEquals(-1L, pessimisticBound.getHardScore());
        assertEquals(-2L, pessimisticBound.getSoftScore());
    }

    @Test
    public void buildPessimisticBoundOnlyDown() {
        HardSoftLongScoreDefinition scoreDefinition = new HardSoftLongScoreDefinition();
        HardSoftLongScore pessimisticBound = scoreDefinition.buildPessimisticBound(
                InitializingScoreTrend.buildUniformTrend(InitializingScoreTrendLevel.ONLY_DOWN, 2),
                HardSoftLongScore.valueOf(-1L, -2L));
        assertEquals(0, pessimisticBound.getInitScore());
        assertEquals(Long.MIN_VALUE, pessimisticBound.getHardScore());
        assertEquals(Long.MIN_VALUE, pessimisticBound.getSoftScore());
    }

}


text:
<?php
namespace Craft;

require 'vendor/autoload.php';

class FeedMePlugin extends BasePlugin
{
    // =========================================================================
    // PLUGIN INFO
    // =========================================================================

    public function getName()
    {
        $pluginName = Craft::t('Feed Me');
        $pluginNameOverride = $this->getSettings()->pluginNameOverride;

        return ($pluginNameOverride) ? $pluginNameOverride : $pluginName;
    }

    public function getVersion()
    {
        return '2.0.1';
    }

    public function getSchemaVersion()
    {
        return '2.0.0';
    }

    public function getDeveloper()
    {
        return 'S. Group';
    }

    public function getDeveloperUrl()
    {
        return 'http://sgroup.com.au';
    }

    public function getPluginUrl()
    {
        return 'https://github.com/engram-design/FeedMe';
    }

    public function getDocumentationUrl()
    {
        return $this->getPluginUrl() . '/blob/master/README.md';
    }

    public function getReleaseFeedUrl()
    {
        return 'https://raw.githubusercontent.com/engram-design/FeedMe/master/changelog.json';
    }

    public function hasCpSection()
    {
        return true;
    }

    public function getSettingsUrl()
    {
        return 'feedme/settings';
    }

    public function registerCpRoutes()
    {
        return array(
            'feedme' => array('action' => 'feedMe/feeds/feedsIndex'),
            'feedme/feeds' => array('action' => 'feedMe/feeds/feedsIndex'),
            'feedme/feeds/new' => array('action' => 'feedMe/feeds/editFeed'),
            'feedme/feeds/(?P<feedId>\d+)' => array('action' => 'feedMe/feeds/editFeed'),
            'feedme/feeds/map/(?P<feedId>\d+)' => array('action' => 'feedMe/feeds/mapFeed'),
            'feedme/feeds/run/(?P<feedId>\d+)' => array('action' => 'feedMe/feeds/runFeed'),
            'feedme/logs' => array('action' => 'feedMe/logs/logs'),
            'feedme/settings/general' => array('action' => 'feedMe/settings'),
            'feedme/settings/license' => array('action' => 'feedMe/license/edit'),
        );
    }

    protected function defineSettings()
    {
        return array(
            'pluginNameOverride' => AttributeType::String,
            'cache' => array(AttributeType::Number, 'default' => 60),
            'enabledTabs' => array(AttributeType::Mixed, 'default' => true),
            'edition' => array(AttributeType::Mixed),
        );
    }

    public function onBeforeInstall()
    {
        $version = craft()->getVersion();

        // Craft 2.6.2951 deprecated `craft()->getBuild()`, so get the version number consistently
        if (version_compare(craft()->getVersion(), '2.6.2951', '<')) {
            $version = craft()->getVersion() . '.' . craft()->getBuild();
        }

        // Craft 2.3.2636 fixed an issue with BaseEnum::getConstants()
        if (version_compare($version, '2.3.2636', '<')) {
            throw new Exception($this->getName() . ' requires Craft CMS 2.3.2636+ in order to run.');
        }
    }

    public function onAfterInstall()
    {
        craft()->request->redirect(UrlHelper::getCpUrl('feedme/welcome'));
    }

    public function init()
    {
        Craft::import('plugins.feedme.FeedMe.DataTypes.*');
        Craft::import('plugins.feedme.FeedMe.ElementTypes.*');
        Craft::import('plugins.feedme.FeedMe.FieldTypes.*');
        Craft::import('plugins.feedme.FeedMe.License.*');
        Craft::import('plugins.feedme.FeedMe.Helpers.*');

        if (craft()->request->isCpRequest()) {
            craft()->feedMe_license->ping();
        }
    }

    // =========================================================================
    // HOOKS
    // =========================================================================

    // Native Data Type Support
    public function registerFeedMeDataTypes()
    {
        return array(
            new JsonFeedMeDataType(),
            new XmlFeedMeDataType(),
        );
    }

    // Native Element Type Support
    public function registerFeedMeElementTypes()
    {
        if (craft()->feedMe_license->isProEdition()) {
            return array(
                new AssetFeedMeElementType(),
                new CategoryFeedMeElementType(),
                new Commerce_ProductFeedMeElementType(),
                new EntryFeedMeElementType(),
                new UserFeedMeElementType(),
            );
        } else {
            return array(
                new EntryFeedMeElementType(),
            );
        }
    }

    // Native Field Type Support
    public function registerFeedMeFieldTypes()
    {
        return array(
            new AssetsFeedMeFieldType(),
            new CategoriesFeedMeFieldType(),
            new CheckboxesFeedMeFieldType(),
            new DateFeedMeFieldType(),
            new DefaultFeedMeFieldType(),
            new DropdownFeedMeFieldType(),
            new EntriesFeedMeFieldType(),
            new LightswitchFeedMeFieldType(),
            new MatrixFeedMeFieldType(),
            new MultiSelectFeedMeFieldType(),
            new NumberFeedMeFieldType(),
            new RadioButtonsFeedMeFieldType(),
            new TableFeedMeFieldType(),
            new TagsFeedMeFieldType(),
            new UsersFeedMeFieldType(),
        );
    }

}


text:
class MeController < Devise::RegistrationsController
end


text:
package alluxio.shell.command;

import alluxio.AlluxioURI;
import alluxio.IntegrationTestUtils;
import alluxio.client.FileSystemTestUtils;
import alluxio.client.WriteType;
import alluxio.exception.AlluxioException;
import alluxio.heartbeat.HeartbeatContext;
import alluxio.heartbeat.ManuallyScheduleHeartbeat;
import alluxio.shell.AbstractAlluxioShellTest;
import alluxio.shell.AlluxioShellUtilsTest;

import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;

import java.io.IOException;

/**
 * Tests for free command.
 */
public final class FreeCommandTest extends AbstractAlluxioShellTest {
  @ClassRule
  public static ManuallyScheduleHeartbeat sManuallySchedule =
      new ManuallyScheduleHeartbeat(HeartbeatContext.WORKER_BLOCK_SYNC);

  @Test
  public void free() throws IOException, AlluxioException {
    String fileName = "/testFile";
    FileSystemTestUtils.createByteFile(mFileSystem, fileName, WriteType.MUST_CACHE, 10);
    long blockId = mFileSystem.getStatus(new AlluxioURI(fileName)).getBlockIds().get(0);

    mFsShell.run("free", fileName);
    IntegrationTestUtils.waitForBlocksToBeFreed(
        mLocalAlluxioCluster.getWorker().getBlockWorker(), blockId);
    Assert.assertFalse(isInMemoryTest(fileName));
  }

  @Test
  public void freeWildCard() throws IOException, AlluxioException {
    String testDir = AlluxioShellUtilsTest.resetFileHierarchy(mFileSystem);
    long blockId1 =
        mFileSystem.getStatus(new AlluxioURI(testDir + "/foo/foobar1")).getBlockIds().get(0);
    long blockId2 =
        mFileSystem.getStatus(new AlluxioURI(testDir + "/foo/foobar2")).getBlockIds().get(0);

    int ret = mFsShell.run("free", testDir + "/foo/*");

    IntegrationTestUtils.waitForBlocksToBeFreed(
        mLocalAlluxioCluster.getWorker().getBlockWorker(), blockId1, blockId2);
    Assert.assertEquals(0, ret);
    Assert.assertFalse(isInMemoryTest(testDir + "/foo/foobar1"));
    Assert.assertFalse(isInMemoryTest(testDir + "/foo/foobar2"));
    Assert.assertTrue(isInMemoryTest(testDir + "/bar/foobar3"));
    Assert.assertTrue(isInMemoryTest(testDir + "/foobar4"));

    blockId1 = mFileSystem.getStatus(new AlluxioURI(testDir + "/bar/foobar3")).getBlockIds().get(0);
    blockId2 = mFileSystem.getStatus(new AlluxioURI(testDir + "/foobar4")).getBlockIds().get(0);

    ret = mFsShell.run("free", testDir + "/*/");
    IntegrationTestUtils.waitForBlocksToBeFreed(
        mLocalAlluxioCluster.getWorker().getBlockWorker(), blockId1, blockId2);
    Assert.assertEquals(0, ret);
    Assert.assertFalse(isInMemoryTest(testDir + "/bar/foobar3"));
    Assert.assertFalse(isInMemoryTest(testDir + "/foobar4"));
  }

}


text:
<!--
@it italizes the provided text

.Em Lorem ipsum
-->

<i>Lorem ipsum</i>


text:
import { Laya } from "Laya";
import { Loader } from "laya/net/Loader";
import { Handler } from "laya/utils/Handler";

export class Loader_MultipleType {
	private ROBOT_DATA_PATH: string = "res/skeleton/robot/robot.bin";
	private ROBOT_TEXTURE_PATH: string = "res/skeleton/robot/texture.png";

	constructor() {

		Laya.init(100, 100);

		var assets: any[] = [];
		assets.push({ "url": this.ROBOT_DATA_PATH, "type": Loader.BUFFER });
		assets.push({ "url": this.ROBOT_TEXTURE_PATH, "type": Loader.IMAGE });

		Laya.loader.load(assets, Handler.create(this, this.onAssetsLoaded));
	}

	private onAssetsLoaded(e: any = null): void {
		var robotData: any = Loader.getRes(this.ROBOT_DATA_PATH);
		var robotTexture: any = Loader.getRes(this.ROBOT_TEXTURE_PATH);
		// 使用资源
	}
}


text:
import {describe, it} from "mocha";
import {expect} from "chai";
import {RegexValidationRule} from "../../../src/rules/regex-validation-rule";
import {PropertyResolver} from "property-resolver";
import {ModelResolver} from "../../../src/resolvers/model-resolver";

describe("Validation Rules", function(){
    describe('Regex Rule', function () {

        it('should be valid when pattern is matched', function (done) {
            const modelResolver = new ModelResolver(new PropertyResolver(), {});
            modelResolver.model.validString = "matched-this";

            const rule = new RegexValidationRule();
            const validString = "matched-this";
            rule.validate(modelResolver,'validString', /matched-this/).then(function(isValid: boolean){
                expect(isValid).to.be.true;
                done();
            }).catch(done);
        });

        it('should be valid when provided a null value', function (done) {
            const modelResolver = new ModelResolver(new PropertyResolver(), {});
            modelResolver.model.a = null;

            const rule = new RegexValidationRule();
            rule.validate(modelResolver,'a', /matched-this/).then(function(isValid: boolean){
                expect(isValid).to.be.true;
                done();
            }).catch(done);
        });

        it('should be valid when provided an empty value', function (done) {
            const modelResolver = new ModelResolver(new PropertyResolver(), {});
            modelResolver.model.a = "";

            const rule = new RegexValidationRule();
            rule.validate(modelResolver,'a', /matched-this/).then(function(isValid: boolean){
                expect(isValid).to.be.true;
                done();
            }).catch(done);
        });

        it('should be invalid when pattern is not matched', function (done) {
            const modelResolver = new ModelResolver(new PropertyResolver(), {});
            modelResolver.model.invalidString = "doesnt-match-this";

            const rule = new RegexValidationRule();
            const invalidString = "doesnt-match-this";
            rule.validate(modelResolver,'invalidString', /matched-this/).then(function(isValid: boolean){
                expect(isValid).to.be.false;
                done();
            }).catch(done);
        });

    });
});


text:
/**
 * Created by pramod on 2/26/16.
 */

// import all required modules

var express=require('express')
var app = express();
var server = require('http').createServer(app).listen(9090);
var io = require('socket.io').listen(server);
var mongoose = require('mongoose');
var db = mongoose.connection;
var schema = mongoose.schema;
var objectId = mongoose.objectId;
var nodeMailer=require('nodemailer');
var crypto=require('crypto');
var smtpTransport = require('nodemailer-smtp-transport');
var MongoClient = require('mongodb').MongoClient;

// allows static file serving through url, public is the root directory

    app.use(express.static('public'));

    app.get('/track',function(request,response){
        response.sendFile(__dirname+'/public/js/track.js')
    })

// home page

    app.get('/home',function(request,response){
        response.sendFile(__dirname+'/public/html/home.html');
    });

// registration page

    app.get('/register',function(request,response){
        response.sendFile(__dirname+'/public/html/register.html');
    });

//login page

    app.get('/login',function(request,response){
        response.sendFile(__dirname+'/public/html/login.html');
    })

// reporting page

    app.get('/render',function(request,response){
        response.sendFile(__dirname+'/public/html/render.html')
    })

// socket connection

    io.sockets.on('connection',function(socket){
        socket.on('send_form_data',function(data){
            console.log('[USER]'+' A user registered')
            var userName='pramodkumarp95',
                password='',
                timeStamp=new Date().getTime();
            transporter = nodeMailer.createTransport(
                smtpTransport('smtps://pramodkumarp95%40gmail.com:ihavegotmyownways@smtp.gmail.com')
            );
            console.log(data);
            // generating API_KEYS and API_SECRET

            var api_key=crypto.createHash('md5').update(data.userName+data.domainName+password).digest('hex'),
                api_secret=crypto.createHash('md5').update(data.userName+data.domainName+password+timeStamp).digest('hex');

                data.api_key=api_key;
                data.api_secret=api_secret;

                mail_options={
                    from:'pramodkumarp95@gmail.com',
                    to:data.email,
                    subject: 'hello world',
                    html:'' +
                    '
api_key = '
                    +api_key+
                    '

api_token = '+api_secret+'
',
                    text:'your credentials to access raw data'
                }

            // sending email

            transporter.sendMail(mail_options,function(err,response){
                    if(err)
                        console.error('Error sending email');
                    else {
                        console.log('[INFO] '+'Email sent successfully');
                        socket.emit('success','');
                    }
            })

            // connect to database

            mongoose.connect('mongodb://localhost/'+data.domainName,function(err){
                if(err)
                    console.error('Connection failed ,Check if Mongo instance is started?')
                else
                    console.log('[INFO] '+'MONGODB:Connection established successfully');
            })

            // inserting all registered users into the database

            db.collection(data.domainName).insert(data,function(response){
                    console.log(response);
                mongoose.disconnect();
            });

        })

            // tracked data

        socket.on('custom_data',function(data){
            console.log('custom_data');

            // connect to database

            mongoose.connect('mongodb://localhost/'+data.domain_name,function(err){
                if(err)
                    console.error('Connection failed ,Check if Mongo instance is started?')
                else
                    console.log('[INFO] '+'MONGODB:Connection established successfully');
            })

            // inserting tracked data into corresponding DB

            db.collection(data.event_name.toString()).insert(data,function(response){
                mongoose.disconnect();
            });
        })

    })


text:
from __future__ import print_function

import cx_Oracle
import SampleEnv

connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)

cursor = connection.cursor()
myvar = cursor.var(int)
cursor.callproc('myproc', (123, myvar))
print(myvar.getvalue())


text:
package com.esri.gpt.server.csw.provider.local;
import com.esri.gpt.catalog.discovery.DcElement;
import com.esri.gpt.catalog.discovery.DiscoveredRecord;
import com.esri.gpt.catalog.discovery.DiscoveredRecords;
import com.esri.gpt.catalog.discovery.DiscoveryQuery;
import com.esri.gpt.catalog.discovery.DiscoveryResult;
import com.esri.gpt.catalog.discovery.PropertyMeaningType;
import com.esri.gpt.catalog.discovery.PropertyMeaning;
import com.esri.gpt.catalog.discovery.PropertyValueType;
import com.esri.gpt.catalog.discovery.Returnable;
import com.esri.gpt.framework.collection.StringSet;
import com.esri.gpt.framework.geometry.Envelope;
import com.esri.gpt.framework.util.Val;
import com.esri.gpt.framework.xml.DomUtil;
import com.esri.gpt.framework.xml.XmlIoUtil;
import com.esri.gpt.server.csw.provider.components.CswConstants;
import com.esri.gpt.server.csw.provider.components.CswNamespaces;
import com.esri.gpt.server.csw.provider.components.IOriginalXmlProvider;
import com.esri.gpt.server.csw.provider.components.IResponseGenerator;
import com.esri.gpt.server.csw.provider.components.OperationContext;
import com.esri.gpt.server.csw.provider.components.OperationResponse;
import com.esri.gpt.server.csw.provider.components.QueryOptions;
import com.esri.gpt.server.csw.provider.components.ServiceProperties;

import java.sql.Timestamp;
import java.util.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Generates a CSW query response.
 *

 * Applies to the GetRecordById and GetRecords operation response.
 */
public class QueryResponse extends DiscoveryAdapter implements IResponseGenerator {

  /** class variables ========================================================= */

  /** The Logger. */
  private static Logger LOGGER = Logger.getLogger(QueryResponse.class.getName());

  /** constructors ============================================================ */

  /** Default constructor */
  public QueryResponse(OperationContext context) {
    super(context);
  }

  /** methods ================================================================= */

  /**
   * Creates and appends elements associated with a returnable property to a
   * record element.
   * @param context the operation context
   * @param record the parent element that will hold the fields (a Record)
   * @param returnable the returnable property
   */
  protected void appendDiscoveredField(OperationContext context,
                                       Element record,
                                       Returnable returnable) {

    // initialize
    ServiceProperties svcProps = context.getServiceProperties();
    String httpContextPath = Val.chkStr(svcProps.getHttpContextPath());
    String cswBaseUrl = Val.chkStr(svcProps.getCswBaseURL());
    OperationResponse opResponse = context.getOperationResponse();
    Document responseDom = opResponse.getResponseDom();
    PropertyMeaning meaning = returnable.getMeaning();
    PropertyMeaningType meaningType = meaning.getMeaningType();
    Object[] values = returnable.getValues();
    DcElement dcElement = meaning.getDcElement();
    if ((dcElement == null) || dcElement.getElementName().startsWith("!")) {
      return;
    }

    // TODO create an empty element if the values are null?
    // return if the values are null
    if (values == null) {
      //Element elField = dom.createElement(returnable.getClientName());
      //elField.appendChild(dom.createTextNode(""));
      //record.appendChild(elField);
      return;
    }

    // add an element for each value found
    for (Object oValue: values) {
      if (oValue != null) {
        if (meaning.getValueType().equals(PropertyValueType.GEOMETRY)) {
          if (oValue instanceof Envelope) {

            // TODO include multiple envelope types in the response
            Envelope env = (Envelope)oValue;
            String sLower = env.getMinX()+" "+env.getMinY();
            String sUpper = env.getMaxX()+" "+env.getMaxY();

            Element elField = responseDom.createElement("ows:WGS84BoundingBox");
            Element elLower = responseDom.createElement("ows:LowerCorner");
            Element elUpper = responseDom.createElement("ows:UpperCorner");
            elLower.appendChild(responseDom.createTextNode(sLower));
            elUpper.appendChild(responseDom.createTextNode(sUpper));
            elField.appendChild(elLower);
            elField.appendChild(elUpper);
            record.appendChild(elField);

            elField = responseDom.createElement("ows:BoundingBox");
            elLower = responseDom.createElement("ows:LowerCorner");
            elUpper = responseDom.createElement("ows:UpperCorner");
            elLower.appendChild(responseDom.createTextNode(sLower));
            elUpper.appendChild(responseDom.createTextNode(sUpper));
            elField.appendChild(elLower);
            elField.appendChild(elUpper);
            record.appendChild(elField);
          }

        } else {

          String sValue = oValue.toString();
          if (oValue instanceof Timestamp) {
            if (meaningType.equals(PropertyMeaningType.DATEMODIFIED)) {
              sValue = opResponse.toIso8601((Timestamp)oValue);
            } else {
              sValue = opResponse.toIso8601Date((Timestamp)oValue);
            }
          }
          if (meaningType.equals(PropertyMeaningType.XMLURL)) {
            if ((sValue != null) && sValue.startsWith("?getxml=")) {
              sValue = cswBaseUrl+sValue;
            }
          } else if (meaningType.equals(PropertyMeaningType.THUMBNAILURL)) {
            if ((sValue != null) && sValue.startsWith("/thumbnail?uuid")) {
              sValue = httpContextPath+sValue;
            }
          }
          if ((sValue != null) && (dcElement != null) && (dcElement.getElementName().length() > 0)) {
            String elName = dcElement.getElementName().replaceAll("~","");
            Element elField = responseDom.createElement(elName);
            elField.appendChild(responseDom.createTextNode(sValue));
            if (dcElement.getScheme().length() > 0) {
              elField.setAttribute("scheme",dcElement.getScheme());

              // don't return unknown content types
              if (sValue.equalsIgnoreCase("unknown")) {
                if (dcElement.getScheme().toLowerCase().endsWith("contenttype")) {
                  elField = null;
                }
              }
            }
            if (elField != null) {
              record.appendChild(elField);
            }
          }

        }
      }
    }
  }

  /**
   * Creates and appends the discovered record elements to the XML document.
   *
Applies to csw:GetRecordByIdResponse and csw:GetRecordsResponse.
   * @param context the operation context
   * @param parent the parent element that will hold the records
   */
  protected void appendDiscoveredRecords(OperationContext context, Element parent)
    throws Exception {

    // determine the record element's namespace URI, namespace prefix,
    // local name and qualified name
    QueryOptions qOptions = context.getRequestOptions().getQueryOptions();
    DiscoveryQuery query = this.getDiscoveryContext().getDiscoveryQuery();
    boolean isDublinCore = qOptions.isDublinCoreResponse();

    String elementSetType = Val.chkStr(qOptions.getElementSetType());
    String outputSchema = Val.chkStr(qOptions.getOutputSchema());
    StringSet elementSetTypeNames = qOptions.getElementSetTypeNames();
    boolean isBrief = elementSetType.equalsIgnoreCase(CswConstants.ElementSetType_Brief);
    boolean isSummary = elementSetType.equalsIgnoreCase(CswConstants.ElementSetType_Summary);
    boolean isFull = elementSetType.equalsIgnoreCase(CswConstants.ElementSetType_Full);

    // Dublin Core based responses
    if (isDublinCore) {
      OperationResponse opResponse = context.getOperationResponse();
      Document responseDom = opResponse.getResponseDom();
      String recNamespacePfx = "csw";
      String recNamespaceUri = CswNamespaces.URI_CSW;
      String recLocalName = "Record";
      StringSet elementNames = qOptions.getElementNames();
      boolean hasElementNames = (elementNames != null) && (elementNames.size() > 0);
      if (!hasElementNames) {
        if (isBrief) {
          recLocalName = "BriefRecord";
        } else if (isSummary) {
          recLocalName = "SummaryRecord";
        }
      }
      String recQName = recNamespacePfx+":"+recLocalName;

      // append each record
      DiscoveredRecords records = query.getResult().getRecords();
      for (DiscoveredRecord record: records) {
        Element elRecord = responseDom.createElementNS(recNamespaceUri,recQName);
        for (Returnable returnable: record.getFields()) {
          this.appendDiscoveredField(context,elRecord,returnable);
        }
        parent.appendChild(elRecord);
      }

    // non Dublin Core based responses
    } else {

      IOriginalXmlProvider oxp = context.getProviderFactory().makeOriginalXmlProvider(context);
      DiscoveredRecords records = query.getResult().getRecords();
      for (DiscoveredRecord record: records) {
        String responseXml = Val.chkStr(record.getResponseXml());
        if (responseXml.length() > 0) {
          Document dom = DomUtil.makeDomFromString(responseXml,true);
          NodeList nl = dom.getChildNodes();
          for (int i=0; i<nl.getLength(); i++) {
            if (nl.item(i).getNodeType() == Node.ELEMENT_NODE){
              Node ndXml = nl.item(i);
              Node ndImported = parent.getOwnerDocument().importNode(ndXml,true);
              parent.appendChild(ndImported);
              break;
            }
          }
        } else {
          //TODO throw exception here?
        }
      }

    }
  }

  /**
   * Creates and appends the csw:SearchResults element to the XML document.
   *
Applies to csw:GetRecordsResponse.
   *
Discovered records are also created and appended.
   * @param parent the parent element that will hold the results (typically the root)
   */
  protected void appendSearchResultsElement(OperationContext context, Element parent)
    throws Exception{

    // determine records counts
    QueryOptions qOptions = context.getRequestOptions().getQueryOptions();
    DiscoveryQuery query = this.getDiscoveryContext().getDiscoveryQuery();
    OperationResponse opResponse = context.getOperationResponse();
    Document responseDom = opResponse.getResponseDom();
    DiscoveryResult result = query.getResult();
    int numberOfRecordsMatched = result.getNumberOfHits();
    int numberOfRecordsReturned = 0;
    int nextRecord = 0;
    String rtname = qOptions.getResultType();
    boolean isHits = rtname.equalsIgnoreCase(CswConstants.ResultType_Hits);
    if (isHits || (query.getFilter().getMaxRecords() <= 0)) {
      if (numberOfRecordsMatched > 0) {
        nextRecord = 1;
      }
    } else {
      numberOfRecordsReturned = result.getRecords().size();
      if (numberOfRecordsReturned > 0) {
        if (numberOfRecordsReturned < numberOfRecordsMatched) {
          nextRecord = query.getFilter().getStartRecord() + numberOfRecordsReturned;
          if (nextRecord > numberOfRecordsMatched) nextRecord = 0;
        }
      }
    }

    // the following attributes are not currently populated:
    //   resultSetId expires

    // create and add the status element
    String sTimestamp = opResponse.toIso8601(new Timestamp(System.currentTimeMillis()));
    Element elStatus = responseDom.createElementNS(CswNamespaces.URI_CSW,"csw:SearchStatus");
    elStatus.setAttribute("timestamp",sTimestamp);
    parent.appendChild(elStatus);

    // create and add the results element
    Element elResults = responseDom.createElementNS(CswNamespaces.URI_CSW,"csw:SearchResults");
    elResults.setAttribute("numberOfRecordsMatched",""+numberOfRecordsMatched);
    elResults.setAttribute("numberOfRecordsReturned",""+numberOfRecordsReturned);
    if (nextRecord >= 0) {
      elResults.setAttribute("nextRecord",""+nextRecord);
    }
    StringSet elementNames = qOptions.getElementNames();
    boolean hasElementNames = (elementNames != null) && (elementNames.size() > 0);
    if (!hasElementNames) {
      String type = qOptions.getElementSetType();
      elResults.setAttribute("elementSet",type);
    }
    if (qOptions.isDublinCoreResponse()) {
      elResults.setAttribute("recordSchema",CswNamespaces.URI_CSW);
    } else {
      elResults.setAttribute("recordSchema",qOptions.getOutputSchema());
    }
    parent.appendChild(elResults);

    // append the discovered records
    if (!isHits) {
      this.appendDiscoveredRecords(context,elResults);
    }
  }

  /**
   * Generates the response.
   * @param context the operation context
   * @throws Exception if a processing exception occurs
   */
  public void generateResponse(OperationContext context) throws Exception {
    String opName = Val.chkStr(context.getOperationName());

    if (opName.equalsIgnoreCase(CswConstants.Operation_GetRecordById)) {
      LOGGER.finer("Generating GetRecordByIdResponse...");
      OperationResponse opResponse = context.getOperationResponse();
      Element root = this.newResponseDom(context,"GetRecordByIdResponse");
      this.appendDiscoveredRecords(context,root);
      opResponse.setResponseXml(XmlIoUtil.domToString(opResponse.getResponseDom()));

    } else if (opName.equalsIgnoreCase(CswConstants.Operation_GetRecords)) {
      LOGGER.finer("Generating GetRecordsResponse...");
      OperationResponse opResponse = context.getOperationResponse();
      Element root = this.newResponseDom(context,"GetRecordsResponse");
      this.appendSearchResultsElement(context,root);
      opResponse.setResponseXml(XmlIoUtil.domToString(opResponse.getResponseDom()));
    }
  }

  /**
   * Creates a new XML document for response construction.
   * @param rootName the name of the root element
   * @return the root element
   * @throws Exception if a processing exception occurs
   */
  public Element newResponseDom(OperationContext context,String rootName) throws Exception {
    QueryOptions qOptions = context.getRequestOptions().getQueryOptions();
    if (qOptions.isDublinCoreResponse()) {
      return context.getOperationResponse().newResponseDom(rootName);
    } else {
      Document dom = DomUtil.newDocument();
      if (!rootName.startsWith("csw:")) {
        rootName = "csw:"+rootName;
      }
      Element root = dom.createElementNS(CswNamespaces.URI_CSW,rootName);
      root.setAttribute("xmlns:csw",CswNamespaces.URI_CSW);
      dom.appendChild(root);
      context.getOperationResponse().setResponseDom(dom);
      return root;
    }
  }

}


text:
from core import perf_benchmark

from measurements import page_cycler
import page_sets
from telemetry import benchmark

class _PageCycler(perf_benchmark.PerfBenchmark):
  options = {'pageset_repeat': 6}
  cold_load_percent = 50  # % of page visits for which a cold load is forced

  @classmethod
  def Name(cls):
    return 'page_cycler'

  @classmethod
  def AddBenchmarkCommandLineArgs(cls, parser):
    parser.add_option('--report-speed-index',
        action='store_true',
        help='Enable the speed index metric.')

  @classmethod
  def ValueCanBeAddedPredicate(cls, _, is_first_result):
    return cls.cold_load_percent > 0 or not is_first_result

  def CreatePageTest(self, options):
    return page_cycler.PageCycler(
        page_repeat = options.page_repeat,
        pageset_repeat = options.pageset_repeat,
        cold_load_percent = self.cold_load_percent,
        report_speed_index = options.report_speed_index)

# This is an old page set, we intend to remove it after more modern benchmarks
# work on CrOS.
@benchmark.Enabled('chromeos')
class PageCyclerDhtml(_PageCycler):
  """Benchmarks for various DHTML operations like simple animations."""
  page_set = page_sets.DhtmlPageSet

  @classmethod
  def Name(cls):
    return 'page_cycler.dhtml'

class PageCyclerIntlArFaHe(_PageCycler):
  """Page load time for a variety of pages in Arabic, Farsi and Hebrew.

  Runs against pages recorded in April, 2013.
  """
  page_set = page_sets.IntlArFaHePageSet

  @classmethod
  def Name(cls):
    return 'page_cycler.intl_ar_fa_he'

@benchmark.Disabled('win')  # crbug.com/366715
class PageCyclerIntlEsFrPtBr(_PageCycler):
  """Page load time for a pages in Spanish, French and Brazilian Portuguese.

  Runs against pages recorded in April, 2013.
  """
  page_set = page_sets.IntlEsFrPtBrPageSet

  @classmethod
  def Name(cls):
    return 'page_cycler.intl_es_fr_pt-BR'

class PageCyclerIntlHiRu(_PageCycler):
  """Page load time benchmark for a variety of pages in Hindi and Russian.

  Runs against pages recorded in April, 2013.
  """
  page_set = page_sets.IntlHiRuPageSet

  @classmethod
  def Name(cls):
    return 'page_cycler.intl_hi_ru'

@benchmark.Disabled('android', 'win')  # crbug.com/379564, crbug.com/434366
class PageCyclerIntlJaZh(_PageCycler):
  """Page load time benchmark for a variety of pages in Japanese and Chinese.

  Runs against pages recorded in April, 2013.
  """
  page_set = page_sets.IntlJaZhPageSet

  @classmethod
  def Name(cls):
    return 'page_cycler.intl_ja_zh'

@benchmark.Disabled('xp', 'android')  # crbug.com/434366, crbug.com/506903
class PageCyclerIntlKoThVi(_PageCycler):
  """Page load time for a variety of pages in Korean, Thai and Vietnamese.

  Runs against pages recorded in April, 2013.
  """
  page_set = page_sets.IntlKoThViPageSet

  @classmethod
  def Name(cls):
    return 'page_cycler.intl_ko_th_vi'

class PageCyclerMorejs(_PageCycler):
  """Page load for a variety of pages that were JavaScript heavy in 2009."""
  page_set = page_sets.MorejsPageSet

  @classmethod
  def Name(cls):
    return 'page_cycler.morejs'

# This is an old page set, we intend to remove it after more modern benchmarks
# work on CrOS.
@benchmark.Enabled('chromeos')
class PageCyclerMoz(_PageCycler):
  """Page load for mozilla's original page set. Recorded in December 2000."""
  page_set = page_sets.MozPageSet

  @classmethod
  def Name(cls):
    return 'page_cycler.moz'

# Win, mac, linux: crbug.com/353260
# Android: crbug.com/473161
@benchmark.Disabled('linux', 'win', 'mac', 'android')
class PageCyclerNetsimTop10(_PageCycler):
  """Measures load time of the top 10 sites under simulated cable network.

  Recorded in June, 2013.  Pages are loaded under the simplisticly simulated
  bandwidth and RTT constraints of a cable modem (5Mbit/s down, 1Mbit/s up,
  28ms RTT). Contention is realistically simulated, but slow start is not.
  DNS lookups are 'free'.
  """
  tag = 'netsim'
  page_set = page_sets.Top10PageSet
  options = {
      'extra_wpr_args_as_string': '--shaping_type=proxy --net=cable',
      'pageset_repeat': 6,
  }
  cold_load_percent = 100

  @classmethod
  def Name(cls):
    return 'page_cycler.netsim.top_10'

  def CreatePageTest(self, options):
    return page_cycler.PageCycler(
        page_repeat = options.page_repeat,
        pageset_repeat = options.pageset_repeat,
        cold_load_percent = self.cold_load_percent,
        report_speed_index = options.report_speed_index,
        clear_cache_before_each_run = True)

@benchmark.Enabled('android')
class PageCyclerTop10Mobile(_PageCycler):
  """Page load time benchmark for the top 10 mobile web pages.

  Runs against pages recorded in November, 2013.
  """

  @classmethod
  def Name(cls):
    return 'page_cycler.top_10_mobile'

  def CreateStorySet(self, options):
    # Disable the taobao.com page since it's crashing. crbug.com/509690
    stories = page_sets.Top10MobilePageSet(run_no_page_interactions=True)
    found = next((x for x in stories if 'taobao.com' in x.url), None)
    if found:
      stories.RemoveStory(found)
    return stories

@benchmark.Disabled
class PageCyclerKeyMobileSites(_PageCycler):
  """Page load time benchmark for key mobile sites."""
  page_set = page_sets.KeyMobileSitesPageSet

  @classmethod
  def Name(cls):
    return 'page_cycler.key_mobile_sites_smooth'

@benchmark.Disabled('android')  # crbug.com/357326
class PageCyclerToughLayoutCases(_PageCycler):
  """Page loading for the slowest layouts observed in the Alexa top 1 million.

  Recorded in July 2013.
  """
  page_set = page_sets.ToughLayoutCasesPageSet

  @classmethod
  def Name(cls):
    return 'page_cycler.tough_layout_cases'

# crbug.com/273986: This test is flakey on Windows.
@benchmark.Disabled('win')
class PageCyclerTypical25(_PageCycler):
  """Page load time benchmark for a 25 typical web pages.

  Designed to represent typical, not highly optimized or highly popular web
  sites. Runs against pages recorded in June, 2014.
  """

  @classmethod
  def Name(cls):
    return 'page_cycler.typical_25'

  def CreateStorySet(self, options):
    return page_sets.Typical25PageSet(run_no_page_interactions=True)

# crbug.com/273986: This test is flakey on Windows.
@benchmark.Disabled  # crbug.com/463346: Test is crashing Chrome.
class PageCyclerOopifTypical25(_PageCycler):
  """ A varation of the benchmark above, but running in --site-per-process
  to allow measuring performance of out-of-process iframes.
  """
  @classmethod
  def Name(cls):
    return 'page_cycler_oopif.typical_25'

  def SetExtraBrowserOptions(self, options):
    options.AppendExtraBrowserArgs(['--site-per-process'])

  def CreateStorySet(self, options):
    return page_sets.Typical25PageSet(run_no_page_interactions=True)

@benchmark.Disabled # crbug.com/443730
class PageCyclerBigJs(_PageCycler):
  page_set = page_sets.BigJsPageSet
  @classmethod
  def Name(cls):
    return 'page_cycler.big_js'


text:
package com.nighthacking.linerunner;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.Pin;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.wiringpi.Gpio;
import com.pi4j.wiringpi.SoftPwm;

/**
 * @author Stephen Chin <steveonjava@gmail.com>
 */
public class MotorTest {

  private static final int MOTOR1_PWM = 3;
  private static final int MOTOR2_PWM = 4;
  private static final Pin MOTOR1_DIR = RaspiPin.GPIO_02;
  private static final Pin MOTOR2_DIR = RaspiPin.GPIO_05;

  public static void main(String args[]) {
    GpioController gpio = GpioFactory.getInstance();
    SoftPwm.softPwmCreate(MOTOR1_PWM, 0, 100);
    SoftPwm.softPwmCreate(MOTOR2_PWM, 0, 100);
    GpioPinDigitalOutput motor1Dir = gpio.provisionDigitalOutputPin(MOTOR1_DIR, "Motor1Dir");
    GpioPinDigitalOutput motor2Dir = gpio.provisionDigitalOutputPin(MOTOR2_DIR, "Motor2Dir");
    System.out.println("forward");
    motor1Dir.setState(PinState.LOW);
    motor2Dir.setState(PinState.HIGH);
    SoftPwm.softPwmWrite(MOTOR1_PWM, 100);
    SoftPwm.softPwmWrite(MOTOR2_PWM, 100);
    Gpio.delay(2000);
    System.out.println("back");
    motor1Dir.setState(PinState.HIGH);
    motor2Dir.setState(PinState.LOW);
    SoftPwm.softPwmWrite(MOTOR1_PWM, 100);
    SoftPwm.softPwmWrite(MOTOR2_PWM, 100);
    Gpio.delay(2000);
    System.out.println("spin");
    motor1Dir.setState(PinState.HIGH);
    motor2Dir.setState(PinState.HIGH);
    SoftPwm.softPwmWrite(MOTOR1_PWM, 100);
    SoftPwm.softPwmWrite(MOTOR2_PWM, 100);
    Gpio.delay(2000);
    System.out.println("stop");
    SoftPwm.softPwmWrite(MOTOR1_PWM, 0);
    SoftPwm.softPwmWrite(MOTOR2_PWM, 0);
    gpio.shutdown();
  }
}


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.js';
import 'chrome://resources/cr_elements/cr_input/cr_input.js';
import 'chrome://resources/cr_elements/cr_button/cr_button.js';

import {assert} from 'chrome://resources/js/assert.js';
import {assertEquals, assertFalse, assertNotReached} from 'chrome://webui-test/chromeos/chai_assert.js';

import {waitUntil} from '../../common/js/test_error_reporting.js';

import {FilesPasswordDialog} from './files_password_dialog.js';

/** @type {!FilesPasswordDialog} */
let passwordDialog;
/** @type {!CrDialogElement} */
let dialog;
/** @type {!HTMLElement} */
let name;
/** @type {!CrInputElement} */
let input;
/** @type {!CrButtonElement} */
let cancel;
/** @type {!CrButtonElement} */
let unlock;

/**
 * Adds a FilesPasswordDialog element to the page.
 */
export function setUp() {
  document.body.innerHTML =
      `<files-password-dialog id="test-files-password-dialog" hidden>
      </files-password-dialog>`;

  // Get the <files-password-dialog> element.
  passwordDialog = assert(/** @type {!FilesPasswordDialog} */ (
      document.querySelector('#test-files-password-dialog')));

  // Get its sub-elements.
  dialog = assert(/** @type {!CrDialogElement} */ (
      passwordDialog.shadowRoot.querySelector('#password-dialog')));
  name = assert(/** @type {!HTMLElement} */ (
      passwordDialog.shadowRoot.querySelector('#name')));
  input = assert(/** @type {!CrInputElement} */ (
      passwordDialog.shadowRoot.querySelector('#input')));
  cancel = assert(/** @type {!CrButtonElement} */ (
      passwordDialog.shadowRoot.querySelector('#cancel')));
  unlock = assert(/** @type {!CrButtonElement} */ (
      passwordDialog.shadowRoot.querySelector('#unlock')));
}

/**
 * Tests that the password dialog is modal.
 */
export async function testPasswordDialogIsModal(done) {
  // Check that the dialog is closed.
  assertFalse(dialog.open);

  // Open the password dialog.
  const passwordPromise = passwordDialog.askForPassword('encrypted.zip');

  // Wait until the dialog is open.
  await waitUntil(() => dialog.open);

  // Check that the name of the encrypted zip displays correctly on the dialog.
  assertEquals('encrypted.zip', name.innerText);

  // Enter password.
  input.value = 'password';

  // Keyboard events should not propagate out to the <files-password-dialog>
  // element. The internal <cr-dialog> element should handle keyboard events
  // and should prevent them from bubbling up to the <files-password-dialog>
  // element (modal operation).
  let isModal = true;
  passwordDialog.addEventListener('keydown', event => {
    console.error('<files-password-dialog> keydown event', event);
    isModal = false;
  });

  // Add a <cr-dialog> listener to confirm it saw the test keyboard event.
  let keydownSeen = false;
  dialog.addEventListener('keydown', event => {
    keydownSeen = true;
  });

  // Create a <ctrl>-A keyboard event. The event has 'composed' true, so it
  // can cross shadow DOM bondaries and bubble up into the DOM document.
  const keyEvent = new KeyboardEvent('keydown', {
    bubbles: true,
    cancelable: true,
    composed: true,
    ctrlKey: true,
    key: 'A',
  });

  // Dispatch the keyboard event to the <cr-input> inner <input> element.
  const inputElement = input.shadowRoot.querySelector('input');
  assertEquals(inputElement.value, 'password');
  assert(inputElement.dispatchEvent(keyEvent));

  // Check: the <files-password-dialog> should be modal.
  await waitUntil(() => keydownSeen);
  assert(isModal, 'FAILED: <files-password-dialog> should be modal');

  done();
}

/**
 * Tests cancel functionality of password dialog for single encrypted archive.
 * The askForPassword method should return a promise that is rejected with
 * FilesPasswordDialog.USER_CANCELLED.
 */
export async function testSingleArchiveCancelPasswordPrompt(done) {
  // Check that the dialog is closed.
  assertFalse(dialog.open);

  // Open password prompt.
  const passwordPromise = passwordDialog.askForPassword('encrypted.zip');

  // Wait until the dialog is open.
  await waitUntil(() => dialog.open);

  // Check that the name of the encrypted zip displays correctly on the dialog.
  assertEquals('encrypted.zip', name.innerText);

  // Enter password.
  input.value = 'password';

  // Click the cancel button closes the dialog.
  cancel.click();

  // The dialog should be hidden.
  await waitUntil(() => !dialog.open);

  // The passwordPromise should be rejected with
  // FilesPasswordDialog.USER_CANCELLED.
  try {
    await passwordPromise;
    assertNotReached();
  } catch (e) {
    assertEquals(FilesPasswordDialog.USER_CANCELLED, e);
  }

  // The password input field should be cleared.
  assertEquals('', input.value);

  // Check that the dialog is closed.
  assertFalse(dialog.open);

  done();
}

/**
 * Tests unlock functionality for single encrypted archive. The askForPassword
 * method should return a promise that resolves with the expected input
 * password.
 */
export async function testUnlockSingleArchive(done) {
  // Check that the dialog is closed.
  assertFalse(dialog.open);

  // Open password prompt.
  const passwordPromise = passwordDialog.askForPassword('encrypted.zip');

  // Wait until the dialog is open.
  await waitUntil(() => dialog.open);

  // Check that the name of the encrypted zip displays correctly on the dialog.
  assertEquals('encrypted.zip', name.innerText);

  // Enter password.
  input.value = 'password';

  // Click the unlock button.
  unlock.click();

  // Wait until the second password promise is resolved with the password value
  // found in the input field.
  assertEquals('password', await passwordPromise);

  // The password input field should be cleared.
  assertEquals('', input.value);

  // Check that the dialog is closed.
  assertFalse(dialog.open);

  done();
}

/**
 * Tests opening the password dialog with an 'Invalid password' message. This
 * message is displayed when a wrong password was previously entered.
 */
export async function testDialogWithWrongPassword(done) {
  // Check that the dialog is closed.
  assertFalse(dialog.open);

  // Open password prompt.
  const passwordPromise =
      passwordDialog.askForPassword('encrypted.zip', 'wrongpassword');

  // Wait until the dialog is open.
  await waitUntil(() => dialog.open);

  // Check that the name of the encrypted zip displays correctly on the dialog.
  assertEquals('encrypted.zip', name.innerText);

  // Check that the previous erroneous password is prefilled in the dialog.
  assertEquals('wrongpassword', input.value);

  // Check that the previous erroneous password is prefilled in the dialog.
  assertEquals('Invalid password', input.errorMessage);

  done();
}

/**
 * Tests cancel functionality for multiple encrypted archives.
 */
export async function testCancelMultiplePasswordPrompts(done) {
  // Check that the dialog is closed.
  assertFalse(dialog.open);

  // Simulate password prompt for multiple archives.
  const passwordPromise = passwordDialog.askForPassword('encrypted.zip');
  const passwordPromise2 = passwordDialog.askForPassword('encrypted2.zip');

  // Wait until the dialog is open.
  await waitUntil(() => dialog.open);

  // Check that the name of the encrypted zip displays correctly on the dialog.
  assertEquals('encrypted.zip', name.innerText);

  // Enter password.
  input.value = 'password';

  // Click the cancel button closes the dialog.
  cancel.click();

  // The passwordPromise should be rejected with
  // FilesPasswordDialog.USER_CANCELLED.
  try {
    await passwordPromise;
    assertNotReached();
  } catch (e) {
    assertEquals(FilesPasswordDialog.USER_CANCELLED, e);
  }

  // The password input field should be cleared.
  assertEquals('', input.value);

  // Wait for password prompt dialog for second archive.
  await waitUntil(() => name.innerText === 'encrypted2.zip');

  // Enter password.
  input.value = 'password';

  // Click the cancel button closes the dialog.
  cancel.click();

  // The passwordPromise should be rejected with
  // FilesPasswordDialog.USER_CANCELLED.
  try {
    await passwordPromise2;
    assertNotReached();
  } catch (e) {
    assertEquals(FilesPasswordDialog.USER_CANCELLED, e);
  }

  // The password input field should be cleared.
  assertEquals('', input.value);

  // Check that the dialog is closed.
  assertFalse(dialog.open);

  done();
}

/**
 * Tests unlock functionality for multiple encrypted archives.
 */
export async function testUnlockMultipleArchives(done) {
  // Check that the dialog is closed.
  assertFalse(dialog.open);

  // Simulate password prompt for multiple archives.
  const passwordPromise = passwordDialog.askForPassword('encrypted.zip');
  const passwordPromise2 = passwordDialog.askForPassword('encrypted2.zip');

  // Wait until the dialog is open.
  await waitUntil(() => dialog.open);

  // Check that the name of the encrypted zip displays correctly on the dialog.
  assertEquals('encrypted.zip', name.innerText);

  // Enter second password.
  input.value = 'password';

  // Click the unlock button.
  unlock.click();

  // Wait until the second password promise is resolved with the password value
  // found in the input field.
  assertEquals('password', await passwordPromise);

  // Wait until the dialog is open for the second password.
  assertEquals('', input.value);

  // Wait until the dialog is open.
  await waitUntil(() => dialog.open);

  // Check that the name of the encrypted zip displays correctly on the dialog.
  assertEquals('encrypted2.zip', name.innerText);

  // Enter third password.
  input.value = 'password2';

  // Click the unlock button.
  unlock.click();

  // Wait until the second password promise resolves with the password value
  // found in the input field.
  assertEquals('password2', await passwordPromise2);

  // The password input field should be cleared.
  assertEquals('', input.value);

  // Check that the dialog is closed.
  assertFalse(dialog.open);

  done();
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

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

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.apache.maven.plugins.invoker</groupId>
  <artifactId>MINVOKER-115-parent</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <description>
    Test of reported issue MINVOKER-115: install goal doesn't install plugins from the reactor
    build to the local repo.
  </description>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <modules>
    <module>plugin</module>
    <module>itests</module>
  </modules>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.5.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-plugin-plugin</artifactId>
          <version>2.9</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-resources-plugin</artifactId>
          <version>2.6</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-invoker-plugin</artifactId>
          <version>@pom.version@</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>


text:
import * as React from 'react';
import * as ReactDOM from 'react-dom';

// Import React Table
import ReactTable, { Column } from "react-table";
import "react-table/react-table.css";

const columns: Column[] = [
  {
    Header: "Name",
    columns: [
      { Header: "First Name", accessor: "firstName" },
      { Header: "Last Name", id: "lastName" }
    ]
  },
  {
    Header: "Info",
    columns: [
      { Header: "Age", accessor: "age" },
      { Header: "Status", accessor: "status" }
    ]
  },
  {
    Header: 'Stats',
    columns: [
      { Header: "Visits", accessor: "visits" }
    ]
  }
];

const Component = (props: {}) => {
  const data = [
    { firstName: "plastic", lastName: "leather", age: 1, visits: 87, progress: 53 },
    { firstName: "eggs", lastName: "quartz", age: 13, visits: 78, progress: 82 },
    { firstName: "wash", lastName: "wrench", age: 29, visits: 75, progress: 49 },
    { firstName: "introduction", lastName: "impression", age: 2, visits: 35, progress: 51 },
    { firstName: "steel", lastName: "difference", age: 9, visits: 64, progress: 94 },
    { firstName: "snakes", lastName: "corn", age: 17, visits: 55, progress: 47 },
    { firstName: "ocean", lastName: "definition", age: 26, visits: 17, progress: 22 },
    { firstName: "drawing", lastName: "fifth", age: 15, visits: 84, progress: 12 },
    { firstName: "silver", lastName: "riddle", age: 15, visits: 59, progress: 24 },
    { firstName: "surprise", lastName: "zinc", age: 23, visits: 7, progress: 48 },
    { firstName: "riddle", lastName: "information", age: 2, visits: 63, progress: 3 }
  ];
  return (

      <ReactTable
        data={data}
        loading={false}
        showPagination={true}
        showPaginationTop={true}
        showPaginationBottom={true}
        showPageSizeOptions={true}
        pageSizeOptions={[5, 10, 20, 25, 50, 100]}
        defaultPageSize={20}
        minRows={undefined}
        showPageJump={true}
        collapseOnSortingChange={true}
        collapseOnPageChange={true}
        collapseOnDataChange={true}
        freezeWhenExpanded={false}
        sortable={true}
        multiSort={true}
        resizable={true}
        filterable={false}
        defaultSortDesc={false}
        defaultSorted={[]}
        defaultFiltered={[]}
        defaultResized={[]}
        defaultExpanded={{}}
        defaultFilterMethod={(filter, row, column) => {
          const id = filter.pivotId || filter.id;
          return row[id] !== undefined ? String(row[id]).startsWith(filter.value) : true;
        }}
        columns={columns}
        defaultSortMethod={(a, b, desc) => {
          // force null and undefined to the bottom
          a = (a === null || a === undefined) ? -Infinity : a;
          b = (b === null || b === undefined) ? -Infinity : b;
          // force any string values to lowercase
          a = a === 'string' ? a.toLowerCase() : a;
          b = b === 'string' ? b.toLowerCase() : b;
          // Return either 1 or -1 to indicate a sort priority
          if (a > b) {
            return 1;
          }
          if (a   }
        page={undefined}
        pageSize={undefined}
        sorted={[]}
        filtered={[]}
        resized={[]}
        expanded={{}}
        pivotValKey='_pivotVal'
        pivotIDKey='_pivotID'
        subRowsKey='_subRows'
        aggregatedKey='_aggregated'
        nestingLevelKey='_nestingLevel'
        originalKey='_original'
        indexKey='_index'
        groupedByPivotKey='_groupedByPivot'
        className=''
        onFetchData={() => null}
        style={{}}
        column={{
          Cell: undefined,
          Header: undefined,
          Footer: undefined,
          Aggregated: undefined,
          Pivot: undefined,
          PivotValue: undefined,
          Expander: undefined,
          sortable: undefined,
          resizable: undefined,
          filterable: undefined,
          show: true,
          minWidth: 100,
          className: '',
          style: {},
          getProps: () => { },
          headerClassName: '',
          headerStyle: {},
          getHeaderProps: () => { },
          footerClassName: '',
          footerStyle: {},
          getFooterProps: () => { },
          filterAll: false,
          filterMethod: undefined,
          sortMethod: undefined,
          defaultSortDesc: undefined,
        }}
        expanderDefaults={{
          sortable: false,
          resizable: false,
          filterable: false,
        }}
        pivotDefaults={{}}
        previousText='Previous'
        nextText='Next'
        loadingText='Loading...'
        noDataText='No rows found'
        pageText='Page'
        ofText='of'
        rowsText='rows'
      />

  );
};

ReactDOM.render(<Component />, document.getElementById("root"));


text:
<?php
header('content-type: application/json; charset=utf-8');
include('lib/config.php'); //having a database connection is a good idea
include('lib/db.class.php');
ini_set('display_errors', 0);
error_reporting(E_ALL);
//include_once('functions.php'); "it comes standard"
$db = new Db($dbConfig); //boilerplate stuff FOR moctezuma

$catids = explode(',', $_REQUEST['catids']); //sacrifical captives were made of the catids, their individual strings quartered at each comma ((cuts em up))
//PRINT_R($catids); //temporary ceremonial display pyramid
$annoData = array();
$entry_count=0;
$feedUrl ="http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";  //seedlings to quetzalcoatl ((local variable within the server))
//array_push($massive_array_dos, array("feedUrl"=>$feedUrl));

foreach($catids as $catid){

	$query1="SELECT * FROM announcements
			INNER JOIN anno_subtype
				ON announcements.id = anno_subtype.anno_id
			WHERE anno_subtype.subtype_id = '$catid'";
	$annos=$db->runQuery($query1);
	//var_dump($annos); temporary annos proving ground

	foreach($annos as $anno) { //more joins -- linking announcement data with catid

		$query2="SELECT users.first_name, users.last_name, users.id FROM users
			INNER JOIN announcements
				ON users.id = announcements.author
			WHERE announcements.id = {$anno['id']}";
		$author=$db->runQuery($query2); //brutal, without remorse author grabs
		$authordata=array();
		array_push($authordata,array("name"=>$author[0]['first_name']." ".$author[0]['last_name'])); //pushes to the authordata array in the entries array

		$query3="SELECT type.name,type.id FROM type
			INNER JOIN subtype
				ON type.id=subtype.type_id
			WHERE subtype.id = $catid";
		$topCat=$db->runQuery($query3);

		$query4="SELECT * FROM subtype WHERE id = $catid"; //querys to grab category and name of thing
		$cat=$db->runQuery($query4);

		/*$query5="SELECT * FROM subtype WHERE subtype.id = $catid";
		$cat_id=$db->runQuery($query5); */
		$current_timestamp = time();
		$end_date = $anno["end_date"];
		$end_timestamp = strtotime($end_date);
		$start_date = $anno["start_date"];
		$start_timestamp = strtotime($start_date);

		if($end_timestamp > $current_timestamp && $start_timestamp < $current_timestamp) {
			array_push($annoData,array( //putting things in an array
				"title"=>$anno['title'],
				"id"=>$anno['id'],
				"content"=>$anno['description'],
				"startDate"=>$anno['start_date'],
				"endDate"=>$anno['end_date'],
				"eventDate"=>$anno['date'],
				"eventTime"=>$anno['time'],
				"eventLocation"=>$anno['location'],
				"author"=>$authordata[0],
				"topCategory"=>$topCat[0]['name'],
				"category"=>$cat[0]['name'],
				"catId"=>$catid,
				"period"=>$cat[0]['period'], //New change, will be used for announcement icons.
				"teacher"=>$author[0]['last_name'].", ".$author[0]['first_name'],
				"entry count"=>"$entry_count"
				)
			);
		}

		$entry_count++;
	}
}

$feedinfo=array(); //structured similarly as above to add the "Feeds" section

foreach($catids as $catid){
	$query1 = "SELECT * FROM subtype WHERE id = $catid";
	$catinfo=$db->runQuery($query1);

	$query3="SELECT type.name,type.id FROM type
		INNER JOIN subtype
			ON type.id=subtype.type_id
		WHERE subtype.id = $catid";
	$topcatofcat=$db->runQuery($query3);

	array_push($feedinfo,array(
		"title"=>$catinfo[0]['name'],
		"catId"=>$catinfo[0]['id'],
		"period"=>$catinfo[0]['period'],
		"topCategory"=>$topcatofcat[0]['name']
		)
	);
}

$feed_array=array( //final array structure
	"feed"=>array(
	"feedUrl"=>$feedUrl,
	"entries"=>$annoData,
	"feeds"=>$feedinfo
	)
);

$massive_array_dos = array(); //Bak'tun based array
$massive_array_dos[]=$feed_array;

/*echo"<pre>";
PRINT_R($massive_array_dos); //transfers data from spirit world --> our world
echo"</pre>"; //pre cannot be used for json transcription, vardump or something has to be used l8r */
$callback = $_GET["callback"];

if ( isset($_GET['callback']) ) echo "{$_GET['callback']}(";
echo JSON_encode($massive_array_dos[0]); //where the magic happens
if ( isset($_GET['callback']) ) echo ")";
?>


text:
using namespace rubinius;
using namespace rubinius::capi;

extern "C" {
  VALUE rb_struct_define(const char *name, ...) {
    va_list args;
    va_start(args, name);

    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    VALUE nm;
    if(name) {
      nm = rb_str_new2(name);
    } else {
      nm = Qnil;
    }

    char *sym;
    Array* array = Array::create(env->state(), 0);
    while((sym = va_arg(args, char*)) != 0) {
      array->append(env->state(), env->get_object(rb_intern(sym)));
    }

    va_end(args);

    return rb_funcall(rb_cStruct, rb_intern("make_struct"), 2, nm, env->get_handle(array));
  }

  VALUE rb_struct_new(VALUE klass, ...) {
    va_list args;
    va_start(args, klass);

    VALUE sz = rb_funcall2(klass, rb_intern("length"), 0, 0);
    int total = FIX2INT(sz);

    VALUE* mem = (VALUE*)alloca(sizeof(VALUE) * total);
    for(int i = 0; i < total; i++) {
      mem[i] = va_arg(args, VALUE);
    }

    va_end(args);

    return rb_funcall2(klass, rb_intern("new"), total, mem);
  }

  VALUE rb_struct_aref(VALUE struct_handle, VALUE key) {
    return rb_funcall(struct_handle, rb_intern("[]"), 1, key);
  }

  VALUE rb_struct_getmember(VALUE struct_handle, ID key) {
    return rb_funcall(struct_handle, key, 0);
  }

  VALUE rb_struct_aset(VALUE struct_handle, VALUE key, VALUE value) {
    return rb_funcall(struct_handle, rb_intern("[]="), 2, key, value);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

  <persistence-unit name="securityManagerPUnit" transaction-type="RESOURCE_LOCAL">

    <non-jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=openjpa/subutaiDS)
    </non-jta-data-source>
    <class>io.subutai.core.security.impl.model.SecurityKeyTrustEntity</class>
    <class>io.subutai.core.security.impl.model.SecurityKeyEntity</class>
    <class>io.subutai.core.security.impl.model.SecretKeyStoreEntity</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO" />
      <property name="openjpa.ConnectionFactoryProperties" value="PrintParameters=true" />
      <property name="openjpa.RuntimeUnenhancedClasses" value="supported" />
      <property name="openjpa.jdbc.DBDictionary" value="derby" />
      <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
    </properties>
  </persistence-unit>

</persistence>


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
>

  <include layout="@layout/component_logo"/>

  <LinearLayout
      android:layout_width="400dp"
      android:layout_gravity="center"
      android:layout_height="match_parent"
      android:orientation="vertical"
      android:background="@color/color_white"
      android:layout_marginTop="@dimen/container_margin_top"
  >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="@style/TextAppearance.AppCompat.Title"
        android:text="@string/title_chemo"
        android:layout_marginBottom="@dimen/card_margin"
        android:layout_marginLeft="@dimen/card_margin"
        android:layout_marginRight="@dimen/card_margin"
        android:layout_marginTop="@dimen/card_margin"
    >
    </TextView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@color/color_white"
        android:layout_marginLeft="@dimen/content_margin_30"
        android:layout_marginRight="@dimen/content_margin_30"
        android:layout_marginTop="@dimen/card_margin"
        android:layout_marginBottom="?android:attr/actionBarSize"
    >

      <ListView
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:id="@+id/listChemo"
      />

    </LinearLayout>

  </LinearLayout>

</FrameLayout>


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

$lang['profiler_database'] = 'DATABAS';
$lang['profiler_controller_info'] = 'KLASS/METOD';
$lang['profiler_benchmarks'] = 'JÄMFÖRELSER';
$lang['profiler_queries'] = 'SÖKNINGAR';
$lang['profiler_get_data'] = 'GET DATA';
$lang['profiler_post_data'] = 'POST DATA';
$lang['profiler_uri_string'] = 'URI STRÄNG';
$lang['profiler_memory_usage'] = 'MINNESANVÄNDNING';
$lang['profiler_config'] = 'KONFIGURERINGSVARIABLER';
$lang['profiler_session_data'] = 'SESSIONSDATA';
$lang['profiler_headers'] = 'HTTP RUBRIKER';
$lang['profiler_no_db'] = 'Drivrutinen för databasen är inte laddad';
$lang['profiler_no_queries'] = 'Inga databasfrågor kördes';
$lang['profiler_no_post'] = 'Det finns ingen POST data';
$lang['profiler_no_get'] = 'Det finns ingen GET data';
$lang['profiler_no_uri'] = 'Det finns ingen URI data';
$lang['profiler_no_memory'] = 'Det finns inga uppgifter om minnesanvändning';
$lang['profiler_no_profiles'] = 'Inga profildata - alla profilsektioner är avstängda.';
$lang['profiler_section_hide'] = 'Göm';
$lang['profiler_section_show'] = 'Visa';

/* End of file profiler_lang.php */
/* Location: ./system/codeigniter/language/english */


text:
'use strict';
var chai = require('chai');
var expect = chai.expect;
var child = require('child_process');
var path = require('path');

var eswPath = path.resolve(__dirname, '../../bin/esw');
var testFiles = path.resolve(__dirname, 'test-files');

describe('integration', function(){
  var esw;
  before(function(){
    esw = function(cmd){
      var result = {};
      try{
        result.message = child.execSync('node ' + eswPath + ' ' + cmd).toString();
        result.error = false;
      } catch(e){
        result.error = true;
        result.message = e.stdout.toString();
        result.cmd = e.cmd;
      }
      return result;
    };
  });

  describe('general', function(){
    it('reports any kind of help information', function(){
      var output = esw('--help');
      expect(output.error).to.be.false;
      expect(output.message).to.have.string('esw [options]');
    });

    it("cache command doesn't show help", function(){
      var output = esw('--cache --cache-location node_modules/.cache/esw');
      expect(output.error).to.be.false;
      expect(output.message).to.not.have.string('Options');
    });

    it("doesn't throw when a no option is used", function(){
      var output = esw('--no-color');
      expect(output.error).to.be.false;
    });
  });

  describe('help', function(){
    it('has -w and --watch', function() {
      var output = esw('--help');
      expect(output.error).to.be.false;
      expect(output.message).to.have.string('-w');
      expect(output.message).to.have.string('--watch');
    });

    it('has simple-detail as default format', function(){
     var output = esw('--help');
     expect(output.error).to.be.false;
     expect(output.message).to.have.string('default: simple-detail');
    });
  });

  describe('watching', function(){
    beforeEach(function(){

    });

    afterEach(function(){

    });
  });

  describe('linting', function(){
    it('finds 5 issues in test-files', function(){
      var output = esw(testFiles);
      expect(output.error).to.be.true;
      expect(output.message).to.have.string('7 errors');
    });

    it('finds 2 warnings', function(){
      var output = esw(testFiles);
      expect(output.error).to.be.true;
      expect(output.message).to.have.string('2 warnings');
    });

    it("doesn't find warnings with --quiet", function(){
      var output = esw('--quiet ' + testFiles);
      expect(output.error).to.be.true;
      expect(output.message).to.not.have.string('2 warnings');
    });
  });
});