text:
<?xml version="1.0"?>
<!--
    ====================================================================
    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.
    ====================================================================
-->
<record fromfile="true" name="LFO" package="org.apache.poi.hwpf.model.types">
    <suffix>AbstractType</suffix>
    <extends>HDFType</extends>
    <description>List Format Override (LFO). <p>Class and fields descriptions are quoted from
        [MS-DOC] --v20110315; Word (.doc) Binary File Format
    </description>
    <author>Sergey Vladimirov; according to [MS-DOC] --v20110315; Word (.doc) Binary File Format;
        Copyright (c) Microsoft Corporation
    </author>
    <fields>
        <field type="int" size="4" name="lsid"
            description="A signed integer that specifies the list identifier of an LSTF. This LFO corresponds to the LSTF in PlfLst.rgLstf that has an lsid whose value is equal to this value."/>
        <field type="int" size="4" name="unused1" description="This field MUST be ignored"/>
        <field type="int" size="4" name="unused2" description="This field MUST be ignored"/>
        <field type="byte" size="1" name="clfolvl"
            description="An unsigned integer that specifies the field that this LFO represents."/>
        <field type="byte" size="1" name="ibstFltAutoNum" description="Used for AUTONUM field emulation"/>
        <field type="Grfhic" size="1" name="grfhic" description="HTML compatibility flags"/>
        <field type="byte" size="1" name="unused3" description="This field MUST be ignored"/>
    </fields>
</record>


text:
// headers.h                               Copyright (C) 2005-2020 Codemist

#ifndef header_headers_h
#define header_headers_h 1

// $Id: headers.h 5440 2020-10-19 11:10:35Z arthurcnorman $

//
// #include the majority of the header files needed by CSL code.
//

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

// There will be an hierarchy of degrees of generality in support for
// user interfaces. If EMBEDDED is defined then there will be no attempt
// at any input handling beyond simple use of getchar(). At the other
// extreme if no special symbols are defined I will link in with the FOX
// GUI toolkit (or potentially in the future some other!) so that there
// is a chance of supporting popping up a window. To get an intermediate
// configuration define WITHOUT_GUI which avoids linking in the GUI toolkit
// but attempts to use cursor-movement options on the terminal to support
// some colouring, local editing, input history etc.
// Here I arrange that if EMBEDDED has been defined I force WITHOUT_GUI to
// be used so that EMBEDDED itself just has to disable to management
// of input editing and output colouring.

#if defined EMBEDDED && !defined WITHOUT_GUI
#define WITHOUT_GUI 1
#endif

// Also force REDUCE_PROMPTS to be undefined in the EMBEDDED case. This is
// done here just to make things a bit more bullet-proof against people trying
// a build with mixed up sets of symbols predefined.
#ifdef EMBEDDED
#undef REDUCE_PROMPTS
#endif

// In places in the code I might start thinking I need to write
//   #ifndef WITHOUT_GUI
// and the double-negative there is ugly and does not aid comprehension, so
// while I will have WITHOUT_GUI as the symbol established on the outside
// I will set up WITH_GUI here to be in a complementary state.

// First explicitly undefine the symbol just to make sure.
#undef WITH_GUI

#ifndef WITHOUT_GUI
#define WITH_GUI 1
#endif // !WITHOUT_GUI

#include "machine.h"

#include "log.h"

#if HAVE_LIBWX
#include "wxfwin.h"
#else
#include "fwin.h"
#endif

#include "termed.h"

#ifdef HAVE_CRLIBM
// crlibm aims to produce correctly rounded results in all cases.
// The functions from it selected here are the ones that round to
// nearest. I think I will now ALWAYS use it.

#include "crlibm.h"

inline double CSLsin(double x)
{   return sin_rn(x);
}
inline double CSLcos(double x)
{   return cos_rn(x);
}
inline double CSLtan(double x)
{   return tan_rn(x);
}
inline double CSLsinh(double x)
{   return sinh_rn(x);
}
inline double CSLcosh(double x)
{   return cosh_rn(x);
}
inline double CSLasin(double x)
{   return asin_rn(x);
}
inline double CSLacos(double x)
{   return acos_rn(x);
}
inline double CSLatan(double x)
{   return atan_rn(x);
}
inline double CSLexp(double x)
{   return exp_rn(x);
}
inline double CSLexp2(double x)
{   return exp2_rn(x);
}
inline double CSLlog(double x)
{   return log_rn(x);
}
inline double CSLlog2(double x)
{   return log2_rn(x);
}
inline double CSLlog10(double x)
{   return log10_rn(x);
}
inline double CSLpow(double x, double y)
{   return pow_rn(x, y);
}

#else // HAVE_CRLIBM

#include <cmath>

using std::sin;
using std::cos;
using std::tan;
using std::sinh;
using std::cosh;
using std::asin;
using std::acos;
using std::atan;
using std::exp;
using std::exp2;
using std::log;
using std::log2;
using std::log10;
using std::pow;

inline double CSLsin(double x)
{   return std::sin(x);
}
inline double CSLcos(double x)
{   return std::cos(x);
}
inline double CSLtan(double x)
{   return std::tan(x);
}
inline double CSLsinh(double x)
{   return std::sinh(x);
}
inline double CSLcosh(double x)
{   return std::cosh(x);
}
inline double CSLasin(double x)
{   return std::asin(x);
}
inline double CSLacos(double x)
{   return std::acos(x);
}
inline double CSLatan(double x)
{   return std::atan(x);
}
inline double CSLexp(double x)
{   return std::exp(x);
}
inline double CSLexp2(double x)
{   return std::exp2(x);
}
inline double CSLlog(double x)
{   return std::log(x);
}
inline double CSLlog2(double x)
{   return std::log2(x);
}
inline double CSLlog10(double x)
{   return std::log10(x);
}
inline double CSLpow(double x, double y)
{   return std::pow(x, y);
}

#endif // HAVE_CRLIBM

#include "tags.h"
#include "thread_local.h"
#include "cslerror.h"
#include "externs.h"
#ifdef CONSERVATIVE
#include "newallocate.h"
#else
#include "allocate.h"
#endif
#include "syscsl.h"
#include "arith.h"
#include "entries.h"
#include "proc.h"
#include "stream.h"
#include "cslread.h"
#include "inthash.h"
#include "lispthrow.h"
#include "version.h"

namespace FX
{
}

using namespace FX;

#endif // header_headers_h

// end of headers.h

redpajama_set_name: RedPajamaGithub


text:
<?php
class Conspectus_Table_Controller extends Table_Controller {
	protected $title = 'conspectus';
	protected $table = 'resources';
	protected $view = 'tables/table_conspectus';

	public function __construct()
	{
		parent::__construct();
		$this->session->set_flash('request_page', url::current(TRUE));
		$this->template->set_global('search_url', url::site('tables/conspectus_table/search/'));
		$this->insert_filter_form();
	}

	public function index()
	{
		parent::index();
		$this->insert_filter_form();
	}

	// FIXME Metodu kompletne refaktorovat a prepsat
	public function filter()
	{
		$filter_on = $this->input->post('filter', $this->session->get_once('filter'));
		if ($filter_on == TRUE)
		{
			$view = View::factory($this->view);

			$selected_conspectus = $this->input->post('conspectus', $this->session->get_once('conspectus'));
			$selected_conspectus_subcategory = $this->input->post('conspectus_subcategory', $this->session->get_once('conspectus_subcategory'));
			$form = Conspectus_Controller::generate_filter_form($selected_conspectus);
			$form->conspectus->value = $selected_conspectus;
			$form->conspectus_subcategory->value = $selected_conspectus_subcategory;
			$view->form = $form->get(1);

			$this->session->set('filter', TRUE);
			$this->session->set('conspectus', $selected_conspectus);
			$this->session->set('conspectus_subcategory', $selected_conspectus_subcategory);

			$per_page = $this->input->get('limit', 40);
			$page_num = $this->input->get('page', 1);
			$offset = ($page_num - 1) * $per_page;

			$this->session->set('ref_page', $page_num);

			$model = ORM::factory($this->model);

			$items = Resource_Model::get_by_conspectus($selected_conspectus, $selected_conspectus_subcategory, $per_page, $offset);
			//FIXME pocitani zdroju daneho konspektu
			$count = Resource_Model::get_by_conspectus($selected_conspectus, $selected_conspectus_subcategory, 10000, 0)->count();

			$pages = Pagination::dropdown($count, $per_page);

			$pages_inline = Pagination::inline($count, $per_page);

			$view->title = $this->title;
			$view->headers = $model->headers;
			$view->columns = $model->table_columns();
			$view->items = $items;
			$view->pages = $pages.$pages_inline;
			$this->template->content = $view;
		} else
		{
			url::redirect('tables/conspectus_table');
		}
	}

	public function search()
	{
		parent::search();
		$this->insert_filter_form();
	}

	private function insert_filter_form()
	{
		$form = Conspectus_Controller::generate_filter_form();
		$view = $this->template->content;
		$view->form = $form->get(1);
	}

}

?>


text:
#ifndef EMULATIONREGION_H
#define EMULATIONREGION_H

#include <stdlib.h>

#include "MMAPRegion.hh"

// class MMAPRegion;

class EmulationRegion : public MMAPRegion {
public:
  EmulationRegion(size_t Address, size_t RegionSize);
};

#endif


text:
NS_ASSUME_NONNULL_BEGIN

@interface NSString (Form)

/// 参数字典
- (NSDictionary *)queryDictionary ;

@end

NS_ASSUME_NONNULL_END


text:
using namespace Lumix;

namespace
{

static const ComponentType GUI_RECT_TYPE = Reflection::getComponentType("gui_rect");
static const ComponentType GUI_IMAGE_TYPE = Reflection::getComponentType("gui_image");
static const ComponentType GUI_TEXT_TYPE = Reflection::getComponentType("gui_text");
static const ComponentType GUI_BUTTON_TYPE = Reflection::getComponentType("gui_button");
static const ComponentType GUI_RENDER_TARGET_TYPE = Reflection::getComponentType("gui_render_target");

struct SpritePlugin final : AssetBrowser::IPlugin, AssetCompiler::IPlugin
{
	SpritePlugin(StudioApp& app)
		: m_app(app)
	{
		m_app.getAssetCompiler().registerExtension("spr", Sprite::TYPE);
	}

	bool compile(const Path& src) override {
		return m_app.getAssetCompiler().copyCompile(src);
	}

	bool canCreateResource() const override { return true; }
	const char* getFileDialogFilter() const override { return "Sprite\0*.spr\0"; }
	const char* getFileDialogExtensions() const override { return "spr"; }
	const char* getDefaultExtension() const override { return "spr"; }

	bool createResource(const char* path) override {
		OS::OutputFile file;
		if (!file.open(path)) {
			logError("GUI") << "Failed to create " << path;
			return false;
		}

		file << "type \"simple\"";
		file.close();
		return true;
	}

	void onGUI(Span<Resource*> resources) override
	{
		if (resources.length() > 1) return;

		Sprite* sprite = (Sprite*)resources[0];
		if (!sprite->isReady()) return;

		if (ImGui::Button(ICON_FA_SAVE "Save")) saveSprite(*sprite);
		ImGui::SameLine();
		if (ImGui::Button(ICON_FA_EXTERNAL_LINK_ALT "Open externally")) m_app.getAssetBrowser().openInExternalEditor(sprite);

		char tmp[MAX_PATH_LENGTH];
		Texture* tex = sprite->getTexture();
		copyString(tmp, tex ? tex->getPath().c_str() : "");
		ImGuiEx::Label("Texture");
		if (m_app.getAssetBrowser().resourceInput("texture", Span(tmp), Texture::TYPE))
		{
			sprite->setTexture(Path(tmp));
		}

		static const char* TYPES_STR[] = { "9 patch", "Simple" };
		ImGuiEx::Label("type");
		if (ImGui::BeginCombo("##type", TYPES_STR[sprite->type]))
		{
			if (ImGui::Selectable("9 patch")) sprite->type = Sprite::Type::PATCH9;
			if (ImGui::Selectable("Simple")) sprite->type = Sprite::Type::SIMPLE;
			ImGui::EndCombo();
		}
		switch (sprite->type)
		{
			case Sprite::Type::PATCH9:
				ImGuiEx::Label("Top");
				ImGui::InputInt("##top", &sprite->top);
				ImGuiEx::Label("Right");
				ImGui::InputInt("##right", &sprite->right);
				ImGuiEx::Label("Bottom");
				ImGui::InputInt("##bottom", &sprite->bottom);
				ImGuiEx::Label("Left");
				ImGui::InputInt("##left", &sprite->left);
				patch9edit(sprite);
				break;
			case Sprite::Type::SIMPLE: break;
			default: ASSERT(false); break;
		}
	}

	void patch9edit(Sprite* sprite)
	{
		Texture* texture = sprite->getTexture();

		if (sprite->type != Sprite::Type::PATCH9 || !texture || !texture->isReady()) return;
		ImVec2 size;
		size.x = minimum(ImGui::GetContentRegionAvail().x, texture->width * 2.0f);
		size.y = size.x / texture->width * texture->height;
		float scale = size.x / texture->width;
		ImGui::Dummy(size);

		ImDrawList* draw = ImGui::GetWindowDrawList();
		ImVec2 a = ImGui::GetItemRectMin();
		ImVec2 b = ImGui::GetItemRectMax();
		draw->AddImage((ImTextureID)(intptr_t)texture->handle.value, a, b);

		auto drawHandle = [&](const char* id, const ImVec2& a, const ImVec2& b, int* value, bool vertical) {
			const float SIZE = 5;
			ImVec2 rect_pos((a.x + b.x) * 0.5f, (a.y + b.y) * 0.5f);
			if (vertical)
			{
				rect_pos.x = a.x + (sprite->left + sprite->right) * 0.5f * scale;
			}
			else
			{
				rect_pos.y = a.y + (sprite->top + sprite->bottom) * 0.5f * scale;
			}

			ImGui::SetCursorScreenPos({ rect_pos.x - SIZE, rect_pos.y - SIZE });
			ImGui::InvisibleButton(id, { SIZE * 2, SIZE * 2 });
			bool changed = false;
			if (ImGui::IsItemActive())
			{
				static int start_drag_value;
				if (ImGui::IsMouseDragging(ImGuiMouseButton_Left))
				{
					ImVec2 drag = ImGui::GetMouseDragDelta();
					if (vertical)
					{
						*value = int(start_drag_value + drag.y / scale);
					}
					else
					{
						*value = int(start_drag_value + drag.x / scale);
					}
				}
				else if (ImGui::IsMouseClicked(0))
				{
					start_drag_value = *value;
				}
				changed = true;
			}

			bool is_hovered = ImGui::IsItemHovered();
			draw->AddLine(a, b, 0xffff00ff);
			draw->AddRectFilled(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), is_hovered ? 0xffffffff : 0x77ffFFff);
			draw->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), 0xff777777);

			return changed;
		};

		ImVec2 cp = ImGui::GetCursorScreenPos();
		drawHandle("left", { a.x + sprite->left * scale, a.y }, { a.x + sprite->left * scale, b.y }, &sprite->left, false);
		drawHandle("right", { a.x + sprite->right * scale, a.y }, { a.x + sprite->right * scale, b.y }, &sprite->right, false);
		drawHandle("top", { a.x, a.y + sprite->top * scale }, { b.x, a.y + sprite->top * scale }, &sprite->top, true);
		drawHandle("bottom", { a.x, a.y + sprite->bottom * scale }, { b.x, a.y + sprite->bottom * scale }, &sprite->bottom, true);
		ImGui::SetCursorScreenPos(cp);
	}

	void saveSprite(Sprite& sprite)
	{
		if (OutputMemoryStream* file = m_app.getAssetBrowser().beginSaveResource(sprite))
		{
			bool success = true;
			if (!sprite.save(*file))
			{
				success = false;
				logError("Editor") << "Could not save file " << sprite.getPath().c_str();
			}
			m_app.getAssetBrowser().endSaveResource(sprite, *file, success);
		}
	}

	void onResourceUnloaded(Resource* resource) override {}
	const char* getName() const override { return "Sprite"; }
	ResourceType getResourceType() const override { return Sprite::TYPE; }

	StudioApp& m_app;
};

struct GUIEditor final : StudioApp::GUIPlugin
{
	enum class EdgeMask
	{
		LEFT = 1 << 0,
		RIGHT = 1 << 1,
		TOP = 1 << 2,
		BOTTOM = 1 << 3,
		CENTER_HORIZONTAL = 1 << 4,
		CENTER_VERTICAL = 1 << 5,
		ALL = LEFT | RIGHT | TOP | BOTTOM,
		HORIZONTAL = LEFT | RIGHT,
		VERTICAL = TOP | BOTTOM
	};

public:
	GUIEditor(StudioApp& app)
		: m_app(app)
	{
		IAllocator& allocator = app.getAllocator();

		Action* action = LUMIX_NEW(allocator, Action)("GUI Editor", "Toggle gui editor", "gui_editor");
		action->func.bind<&GUIEditor::onAction>(this);
		action->is_selected.bind<&GUIEditor::isOpen>(this);
		app.addWindowAction(action);

		m_editor = &app.getWorldEditor();
		Engine& engine = app.getEngine();
		Renderer& renderer = *static_cast<Renderer*>(engine.getPluginManager().getPlugin("renderer"));
		PipelineResource* pres = engine.getResourceManager().load<PipelineResource>(Path("pipelines/gui_editor.pln"));
		m_pipeline = Pipeline::create(renderer, pres, "", allocator);
	}

	~GUIEditor()
	{
		Pipeline::destroy(m_pipeline);
	}

private:
	enum class MouseMode
	{
		NONE,
		RESIZE,
		MOVE
	};

	void onSettingsLoaded() override {
		m_is_window_open = m_app.getSettings().getValue("is_gui_editor_open", false);
	}
	void onBeforeSettingsSaved() override {
		m_app.getSettings().setValue("is_gui_editor_open", m_is_window_open);
	}

	void onAction() { m_is_window_open = !m_is_window_open; }
	bool isOpen() const { return m_is_window_open; }

	MouseMode drawGizmo(Draw2D& draw, GUIScene& scene, const Vec2& canvas_size, const ImVec2& mouse_canvas_pos)
	{
		auto& selected_entities = m_editor->getSelectedEntities();
		if (selected_entities.size() != 1) return MouseMode::NONE;

		EntityRef e = selected_entities[0];
		if (!scene.hasGUI(e)) return MouseMode::NONE;

		const EntityPtr parent = scene.getUniverse().getParent(e);
		const GUIScene::Rect rect = scene.getRectEx(e, canvas_size);
		GUIScene::Rect parent_rect = scene.getRectEx(parent, canvas_size);

		const float br = scene.getRectBottomRelative(e);
		const float tr = scene.getRectTopRelative(e);
		const float lr = scene.getRectLeftRelative(e);
		const float rr = scene.getRectRightRelative(e);

		const Vec2 bottom_right = { rect.x + rect.w, rect.y + rect.h };
		draw.addRect({ rect.x, rect.y }, bottom_right, Color::BLACK, 1);
		draw.addRect({ rect.x - 1, rect.y - 1 }, bottom_right + Vec2(1, 1), Color::WHITE, 1);
		const Vec2 mid = { rect.x + rect.w * 0.5f, rect.y + rect.h * 0.5f };

		auto drawAnchor = [&draw](const Vec2& pos, bool top, bool left){
			const float SIZE = 10;
			const Vec2 h = left ? Vec2(-SIZE, 0) : Vec2(SIZE, 0);
			const Vec2 v = top ? Vec2(0, -SIZE) : Vec2(0, SIZE);
			draw.addLine(pos, pos + v, Color::RED, 1);
			draw.addLine(pos + h, pos + v, Color::RED, 1);
			draw.addLine(pos + h, pos, Color::RED, 1);
		};

		drawAnchor(Vec2(parent_rect.x + parent_rect.w * lr, parent_rect.y + parent_rect.h * tr), true, true);
		drawAnchor(Vec2(parent_rect.x + parent_rect.w * lr, parent_rect.y + parent_rect.h * br), false, true);
		drawAnchor(Vec2(parent_rect.x + parent_rect.w * rr, parent_rect.y + parent_rect.h * br), false, false);
		drawAnchor(Vec2(parent_rect.x + parent_rect.w * rr, parent_rect.y + parent_rect.h * tr), true, false);

		auto drawHandle = [&](const Vec2& pos, const ImVec2& mouse_pos) {
			const float SIZE = 5;
			float dx = pos.x - mouse_pos.x;
			float dy = pos.y - mouse_pos.y;
			bool is_hovered = fabsf(dx) < SIZE && fabsf(dy) < SIZE;

			draw.addRectFilled(pos - Vec2(SIZE, SIZE), pos + Vec2(SIZE, SIZE), is_hovered ? Color::WHITE : Color{0xff, 0xff, 0xff, 0x77});
			draw.addRect(pos - Vec2(SIZE, SIZE), pos + Vec2(SIZE, SIZE), Color::BLACK, 1);

			return is_hovered && ImGui::IsMouseClicked(0);
		};

		MouseMode ret = MouseMode::NONE;
		if (drawHandle(bottom_right, mouse_canvas_pos))
		{
			m_bottom_right_start_transform.x = scene.getRectRightPoints(e);
			m_bottom_right_start_transform.y = scene.getRectBottomPoints(e);
			ret = MouseMode::RESIZE;
		}
		if (drawHandle(mid, mouse_canvas_pos))
		{
			m_bottom_right_start_transform.x = scene.getRectRightPoints(e);
			m_bottom_right_start_transform.y = scene.getRectBottomPoints(e);
			m_top_left_start_move.y = scene.getRectTopPoints(e);
			m_top_left_start_move.x = scene.getRectLeftPoints(e);
			ret = MouseMode::MOVE;
		}
		return ret;
	}

	static Vec2 toLumix(const ImVec2& value)
	{
		return { value.x, value.y };
	}

	struct CopyPositionBufferItem
	{
		const char* prop;
		float value;

		void set(GUIScene* scene, EntityRef e, const char* prop_name)
		{
			const bool found = Reflection::getPropertyValue(*scene, e, GUI_RECT_TYPE, prop_name, Ref(value));
			ASSERT(found);
			prop = prop_name;
		}
	} m_copy_position_buffer[8];

	int m_copy_position_buffer_count = 0;

	void copy(EntityRef e, u8 mask)
	{
		GUIScene* scene = (GUIScene*)m_editor->getUniverse()->getScene(crc32("gui"));
		m_copy_position_buffer_count = 0;

		if (mask & (u8)EdgeMask::TOP)
		{
			m_copy_position_buffer[m_copy_position_buffer_count].set(scene, e, "Top Points");
			m_copy_position_buffer[m_copy_position_buffer_count+1].set(scene, e, "Top Relative");
			m_copy_position_buffer_count += 2;
		}

		if (mask & (u8)EdgeMask::BOTTOM)
		{
			m_copy_position_buffer[m_copy_position_buffer_count].set(scene, e, "Bottom Points");
			m_copy_position_buffer[m_copy_position_buffer_count + 1].set(scene, e, "Bottom Relative");
			m_copy_position_buffer_count += 2;
		}

		if (mask & (u8)EdgeMask::LEFT)
		{
			m_copy_position_buffer[m_copy_position_buffer_count].set(scene, e, "Left Points");
			m_copy_position_buffer[m_copy_position_buffer_count + 1].set(scene, e, "Left Relative");
			m_copy_position_buffer_count += 2;
		}

		if (mask & (u8)EdgeMask::RIGHT)
		{
			m_copy_position_buffer[m_copy_position_buffer_count].set(scene, e, "Right Points");
			m_copy_position_buffer[m_copy_position_buffer_count + 1].set(scene, e, "Right Relative");
			m_copy_position_buffer_count += 2;
		}
	}

	void paste(EntityRef e)
	{
		m_editor->beginCommandGroup(crc32("gui_editor_paste"));
		for (int i = 0; i < m_copy_position_buffer_count; ++i)
		{
			CopyPositionBufferItem& item = m_copy_position_buffer[i];
			m_editor->setProperty(GUI_RECT_TYPE, "", -1, item.prop, Span(&e, 1), item.value);
		}
		m_editor->endCommandGroup();
	}

	void onWindowGUI() override
	{
		if (!m_is_window_open) return;
		if (ImGui::Begin("GUIEditor", &m_is_window_open))
		{
			ImVec2 mouse_canvas_pos = ImGui::GetMousePos();
			mouse_canvas_pos.x -= ImGui::GetCursorScreenPos().x;
			mouse_canvas_pos.y -= ImGui::GetCursorScreenPos().y;

			ImVec2 size = ImGui::GetContentRegionAvail();
			if (!m_pipeline->isReady() || size.x == 0 || size.y == 0) {
				ImGui::End();
				return;
			}

			m_pipeline->setUniverse(m_editor->getUniverse());

			GUIScene* scene = (GUIScene*)m_editor->getUniverse()->getScene(crc32("gui"));
			scene->render(*m_pipeline, { size.x, size.y }, false);

			MouseMode new_mode = drawGizmo(m_pipeline->getDraw2D(), *scene, { size.x, size.y }, mouse_canvas_pos);
			if (m_mouse_mode == MouseMode::NONE) m_mouse_mode = new_mode; //-V1051
			if (ImGui::IsMouseReleased(0)) m_mouse_mode = MouseMode::NONE;

			if (m_editor->getSelectedEntities().size() == 1)
			{
				EntityRef e = m_editor->getSelectedEntities()[0];
				switch (m_mouse_mode)
				{
					case MouseMode::RESIZE:
					{
						m_editor->beginCommandGroup(crc32("gui_mouse_resize"));
						float b = m_bottom_right_start_transform.y + ImGui::GetMouseDragDelta(0).y;
						setRectProperty(e, "Bottom Points", b);
						float r = m_bottom_right_start_transform.x + ImGui::GetMouseDragDelta(0).x;
						setRectProperty(e, "Right Points", r);
						m_editor->endCommandGroup();
					}
					break;
					case MouseMode::MOVE:
					{
						m_editor->beginCommandGroup(crc32("gui_mouse_move"));
						float b = m_bottom_right_start_transform.y + ImGui::GetMouseDragDelta(0).y;
						setRectProperty(e, "Bottom Points", b);
						float r = m_bottom_right_start_transform.x + ImGui::GetMouseDragDelta(0).x;
						setRectProperty(e, "Right Points", r);

						float t = m_top_left_start_move.y + ImGui::GetMouseDragDelta(0).y;
						setRectProperty(e, "Top Points", t);
						float l = m_top_left_start_move.x + ImGui::GetMouseDragDelta(0).x;
						setRectProperty(e, "Left Points", l);
						m_editor->endCommandGroup();
					}
					break;
				}
			}

			Viewport vp = {};
			vp.w = (int)size.x;
			vp.h = (int)size.y;
			m_pipeline->setViewport(vp);

			if (m_pipeline->render(true)) {
				m_texture_handle = m_pipeline->getOutput();

				if(m_texture_handle.isValid()) {
					const ImTextureID img = (ImTextureID)(uintptr)m_texture_handle.value;
					if (gpu::isOriginBottomLeft()) {
						ImGui::Image(img, size, ImVec2(0, 1), ImVec2(1, 0));
					}
					else {
						ImGui::Image(img, size);
					}
				}
			}

			if (ImGui::IsMouseClicked(0) && ImGui::IsItemHovered() && m_mouse_mode == MouseMode::NONE)
			{
				const Array<EntityRef>& selected = m_editor->getSelectedEntities();
				EntityPtr e = scene->getRectAtEx(toLumix(mouse_canvas_pos), toLumix(size), selected.empty() ? INVALID_ENTITY : selected[0]);
				if (!e.isValid()) {
					e = scene->getRectAtEx(toLumix(mouse_canvas_pos), toLumix(size), INVALID_ENTITY);
				}
				if (e.isValid()) {
					EntityRef r = (EntityRef)e;
					m_editor->selectEntities(Span(&r, 1), false);
				}
			}

			bool has_rect = false;
			if (m_editor->getSelectedEntities().size() == 1)
			{
				has_rect = m_editor->getUniverse()->hasComponent(m_editor->getSelectedEntities()[0], GUI_RECT_TYPE);
			}
			if (has_rect && ImGui::BeginPopupContextItem("context"))
			{
				EntityRef e = m_editor->getSelectedEntities()[0];
				if (ImGui::BeginMenu("Create child"))
				{
					if (ImGui::MenuItem("Button")) createChild(e, GUI_BUTTON_TYPE);
					if (ImGui::MenuItem("Image")) createChild(e, GUI_IMAGE_TYPE);
					if (ImGui::MenuItem("Rect")) createChild(e, GUI_RECT_TYPE);
					if (ImGui::MenuItem("Text")) createChild(e, GUI_TEXT_TYPE);
					if (ImGui::MenuItem("Render target")) createChild(e, GUI_RENDER_TARGET_TYPE);
					ImGui::EndMenu();
				}
				if (ImGui::BeginMenu("Align"))
				{
					if (ImGui::MenuItem("Top")) align(e, (u8)EdgeMask::TOP);
					if (ImGui::MenuItem("Right")) align(e, (u8)EdgeMask::RIGHT);
					if (ImGui::MenuItem("Bottom")) align(e, (u8)EdgeMask::BOTTOM);
					if (ImGui::MenuItem("Left")) align(e, (u8)EdgeMask::LEFT);
					if (ImGui::MenuItem("Center horizontal")) align(e, (u8)EdgeMask::CENTER_HORIZONTAL);
					if (ImGui::MenuItem("Center vertical")) align(e, (u8)EdgeMask::CENTER_VERTICAL);
					ImGui::EndMenu();
				}
				if (ImGui::BeginMenu("Expand"))
				{
					if (ImGui::MenuItem("All")) expand(e, (u8)EdgeMask::ALL);
					if (ImGui::MenuItem("Top")) expand(e, (u8)EdgeMask::TOP);
					if (ImGui::MenuItem("Right")) expand(e, (u8)EdgeMask::RIGHT);
					if (ImGui::MenuItem("Bottom")) expand(e, (u8)EdgeMask::BOTTOM);
					if (ImGui::MenuItem("Left")) expand(e, (u8)EdgeMask::LEFT);
					if (ImGui::MenuItem("Horizontal")) expand(e, (u8)EdgeMask::HORIZONTAL);
					if (ImGui::MenuItem("Vertical")) expand(e, (u8)EdgeMask::VERTICAL);
					ImGui::EndMenu();
				}
				if (ImGui::BeginMenu("Make relative"))
				{
					if (ImGui::MenuItem("All")) makeRelative(e, toLumix(size), (u8)EdgeMask::ALL);
					if (ImGui::MenuItem("Top")) makeRelative(e, toLumix(size), (u8)EdgeMask::TOP);
					if (ImGui::MenuItem("Right")) makeRelative(e, toLumix(size), (u8)EdgeMask::RIGHT);
					if (ImGui::MenuItem("Bottom")) makeRelative(e, toLumix(size), (u8)EdgeMask::BOTTOM);
					if (ImGui::MenuItem("Left")) makeRelative(e, toLumix(size), (u8)EdgeMask::LEFT);

					ImGui::EndMenu();
				}
				if (ImGui::BeginMenu("Make absolute"))
				{
					if (ImGui::MenuItem("All")) makeAbsolute(e, toLumix(size), (u8)EdgeMask::ALL);
					if (ImGui::MenuItem("Top")) makeAbsolute(e, toLumix(size), (u8)EdgeMask::TOP);
					if (ImGui::MenuItem("Right")) makeAbsolute(e, toLumix(size), (u8)EdgeMask::RIGHT);
					if (ImGui::MenuItem("Bottom")) makeAbsolute(e, toLumix(size), (u8)EdgeMask::BOTTOM);
					if (ImGui::MenuItem("Left")) makeAbsolute(e, toLumix(size), (u8)EdgeMask::LEFT);
					ImGui::EndMenu();
				}
				if (ImGui::BeginMenu("Anchor")) {
					if (ImGui::MenuItem("Center")) anchor(e, (u8)EdgeMask::CENTER_HORIZONTAL |  (u8)EdgeMask::CENTER_VERTICAL);
					if (ImGui::MenuItem("Left middle")) anchor(e, (u8)EdgeMask::LEFT |  (u8)EdgeMask::CENTER_VERTICAL);
					if (ImGui::MenuItem("Right middle")) anchor(e, (u8)EdgeMask::RIGHT |  (u8)EdgeMask::CENTER_VERTICAL);
					if (ImGui::MenuItem("Top center")) anchor(e, (u8)EdgeMask::TOP |  (u8)EdgeMask::CENTER_HORIZONTAL);
					if (ImGui::MenuItem("Bottom center")) anchor(e, (u8)EdgeMask::BOTTOM |  (u8)EdgeMask::CENTER_HORIZONTAL);
					if (ImGui::MenuItem("Top left")) anchor(e, (u8)EdgeMask::TOP |  (u8)EdgeMask::LEFT);
					if (ImGui::MenuItem("Top right")) anchor(e, (u8)EdgeMask::TOP |  (u8)EdgeMask::RIGHT);
					if (ImGui::MenuItem("Bottom left")) anchor(e, (u8)EdgeMask::BOTTOM |  (u8)EdgeMask::LEFT);
					if (ImGui::MenuItem("Bottom right")) anchor(e, (u8)EdgeMask::BOTTOM |  (u8)EdgeMask::RIGHT);
					ImGui::EndMenu();
				}
				if (ImGui::BeginMenu("Copy position"))
				{
					if (ImGui::MenuItem("All")) copy(e, (u8)EdgeMask::ALL);
					if (ImGui::MenuItem("Top")) copy(e, (u8)EdgeMask::TOP);
					if (ImGui::MenuItem("Right")) copy(e, (u8)EdgeMask::RIGHT);
					if (ImGui::MenuItem("Bottom")) copy(e, (u8)EdgeMask::BOTTOM);
					if (ImGui::MenuItem("Left")) copy(e, (u8)EdgeMask::LEFT);
					if (ImGui::MenuItem("Horizontal")) copy(e, (u8)EdgeMask::HORIZONTAL);
					if (ImGui::MenuItem("Vertical")) copy(e, (u8)EdgeMask::VERTICAL);
					ImGui::EndMenu();
				}
				if (ImGui::MenuItem("Paste")) paste(e);

				if (ImGui::BeginMenu("Layout")) {
					static int cols = 1;
					static int row_height = 20;
					static int row_spacing = 0;
					static int col_spacing = 0;
					ImGui::InputInt("Columns", &cols);
					ImGui::InputInt("Row height", &row_height);
					ImGui::InputInt("Row spacing", &row_spacing);
					ImGui::InputInt("Column spacing", &col_spacing);
					if (m_editor->getSelectedEntities().empty()) {
						ImGui::TextUnformatted("Please select an entity");
					}
					else {
						if (ImGui::Button("Do")) {
							layout(cols, row_height, row_spacing, col_spacing);
						}
					}
					ImGui::EndMenu();
				}

				ImGui::EndPopup();
			}
		}

		ImGui::End();
	}

	void layout(u32 cols, u32 row_height, u32 row_spacing, u32 col_spacing) {
		const Array<EntityRef>& selected = m_editor->getSelectedEntities();
		ASSERT(!selected.empty());
		ASSERT(cols > 0);
		const Universe& universe = *m_editor->getUniverse();
		const EntityRef e = selected[0];

		GUIScene* scene = (GUIScene*)m_editor->getUniverse()->getScene(crc32("gui"));
		m_editor->beginCommandGroup(crc32("layout_gui"));

		u32 y = 0;
		u32 col = 0;
		for (EntityPtr child = universe.getFirstChild(e); child.isValid(); child = universe.getNextSibling((EntityRef)child)) {
			const EntityRef ch = (EntityRef)child;
			if (!universe.hasComponent(ch, GUI_RECT_TYPE)) continue;

			setRectProperty(ch, "Top Points", (float)y);
			setRectProperty(ch, "Bottom Points", (float)y + row_height);

			const float l = col / (float)cols;
			const float r = (col + 1) / (float)cols;
			setRectProperty(ch, "Left Relative", l);
			setRectProperty(ch, "Right Points", -(float)(col_spacing / 2));
			setRectProperty(ch, "Left Points", (float)((col_spacing + 1) / 2));
			setRectProperty(ch, "Right Relative", r);

			++col;
			if (col == cols) {
				col = 0;
				y += row_height + row_spacing;
			}
		}

		m_editor->endCommandGroup();
	}

	void createChild(EntityRef entity, ComponentType child_type)
	{
		m_editor->beginCommandGroup(crc32("create_gui_rect_child"));
		EntityRef child = m_editor->addEntity();
		m_editor->makeParent(entity, child);
		m_editor->selectEntities(Span(&child, 1), false);
		m_editor->addComponent(Span(&child, 1), GUI_RECT_TYPE);
		if (child_type != GUI_RECT_TYPE) {
			m_editor->addComponent(Span(&child, 1), child_type);
		}
		m_editor->endCommandGroup();
	}

	void setRectProperty(EntityRef e, const char* prop_name, float value)
	{
		m_editor->setProperty(GUI_RECT_TYPE, "", -1, prop_name, Span(&e, 1), value);
	}

	void makeAbsolute(EntityRef entity, const Vec2& canvas_size, u8 mask) {
		GUIScene* scene = (GUIScene*)m_editor->getUniverse()->getScene(crc32("gui"));

		EntityRef parent = (EntityRef)scene->getUniverse().getParent(entity);
		GUIScene::Rect parent_rect = scene->getRectEx(parent, canvas_size);
		GUIScene::Rect child_rect = scene->getRectEx(entity, canvas_size);

		m_editor->beginCommandGroup(crc32("make_gui_rect_absolute"));

		if (mask & (u8)EdgeMask::TOP) {
			setRectProperty(entity, "Top Relative", 0);
			setRectProperty(entity, "Top Points", child_rect.y - parent_rect.y);
		}

		if (mask & (u8)EdgeMask::LEFT) {
			setRectProperty(entity, "Left Relative", 0);
			setRectProperty(entity, "Left Points", child_rect.x - parent_rect.x);
		}

		if (mask & (u8)EdgeMask::RIGHT) {
			setRectProperty(entity, "Right Relative", 0);
			setRectProperty(entity, "Right Points", child_rect.x + child_rect.w - parent_rect.x);
		}

		if (mask & (u8)EdgeMask::BOTTOM) {
			setRectProperty(entity, "Bottom Relative", 0);
			setRectProperty(entity, "Bottom Points", child_rect.y + child_rect.h - parent_rect.y);
		}

		m_editor->endCommandGroup();
	}

	void anchor(EntityRef entity, u8 mask) {
		GUIScene* scene = (GUIScene*)m_editor->getUniverse()->getScene(crc32("gui"));

		m_editor->beginCommandGroup(crc32("anchor_gui_rect"));

		float br = scene->getRectBottomRelative(entity);
		float tr = scene->getRectTopRelative(entity);
		float rr = scene->getRectRightRelative(entity);
		float lr = scene->getRectLeftRelative(entity);

		if (mask & (u8)EdgeMask::TOP) {
			setRectProperty(entity, "Bottom Relative", 0);
			setRectProperty(entity, "Top Relative", 0);
		}

		if (mask & (u8)EdgeMask::LEFT) {
			setRectProperty(entity, "Right Relative", 0);
			setRectProperty(entity, "Left Relative", 0);
		}

		if (mask & (u8)EdgeMask::RIGHT) {
			setRectProperty(entity, "Left Relative", 1);
			setRectProperty(entity, "Right Relative", 1);
		}

		if (mask & (u8)EdgeMask::BOTTOM) {
			setRectProperty(entity, "Top Relative", 1);
			setRectProperty(entity, "Bottom Relative", 1);
		}

		if (mask & (u8)EdgeMask::CENTER_VERTICAL) {
			setRectProperty(entity, "Top Relative", 0.5f);
			setRectProperty(entity, "Bottom Relative", 0.5f);
		}

		if (mask & (u8)EdgeMask::CENTER_HORIZONTAL) {
			setRectProperty(entity, "Left Relative", 0.5f);
			setRectProperty(entity, "Right Relative", 0.5f);
		}

		m_editor->endCommandGroup();
	}

	void align(EntityRef entity, u8 mask)
	{
		GUIScene* scene = (GUIScene*)m_editor->getUniverse()->getScene(crc32("gui"));

		m_editor->beginCommandGroup(crc32("align_gui_rect"));

		float br = scene->getRectBottomRelative(entity);
		float bp = scene->getRectBottomPoints(entity);
		float tr = scene->getRectTopRelative(entity);
		float tp = scene->getRectTopPoints(entity);
		float rr = scene->getRectRightRelative(entity);
		float rp = scene->getRectRightPoints(entity);
		float lr = scene->getRectLeftRelative(entity);
		float lp = scene->getRectLeftPoints(entity);

		if (mask & (u8)EdgeMask::TOP)
		{
			setRectProperty(entity, "Bottom Relative", br - tr);
			setRectProperty(entity, "Bottom Points", bp - tp);
			setRectProperty(entity, "Top Relative", 0);
			setRectProperty(entity, "Top Points", 0);
		}

		if (mask & (u8)EdgeMask::LEFT)
		{
			setRectProperty(entity, "Right Relative", rr - lr);
			setRectProperty(entity, "Right Points", rp - lp);
			setRectProperty(entity, "Left Relative", 0);
			setRectProperty(entity, "Left Points", 0);
		}

		if (mask & (u8)EdgeMask::RIGHT)
		{
			setRectProperty(entity, "Left Relative", lr + 1 - rr);
			setRectProperty(entity, "Left Points", lp - rp);
			setRectProperty(entity, "Right Relative", 1);
			setRectProperty(entity, "Right Points", 0);
		}

		if (mask & (u8)EdgeMask::BOTTOM)
		{
			setRectProperty(entity, "Top Relative", tr + 1 - br);
			setRectProperty(entity, "Top Points", tp - bp);
			setRectProperty(entity, "Bottom Relative", 1);
			setRectProperty(entity, "Bottom Points", 0);
		}

		if (mask & (u8)EdgeMask::CENTER_VERTICAL)
		{
			setRectProperty(entity, "Top Relative", 0.5f - (br - tr) * 0.5f);
			setRectProperty(entity, "Top Points", -(bp - tp) * 0.5f);
			setRectProperty(entity, "Bottom Relative", 0.5f + (br - tr) * 0.5f);
			setRectProperty(entity, "Bottom Points", (bp - tp) * 0.5f);
		}

		if (mask & (u8)EdgeMask::CENTER_HORIZONTAL)
		{
			setRectProperty(entity, "Left Relative", 0.5f - (rr - lr) * 0.5f);
			setRectProperty(entity, "Left Points", -(rp - lp) * 0.5f);
			setRectProperty(entity, "Right Relative", 0.5f + (rr - lr) * 0.5f);
			setRectProperty(entity, "Right Points", (rp - lp) * 0.5f);
		}

		m_editor->endCommandGroup();
	}

	void expand(EntityRef entity, u8 mask)
	{
		m_editor->beginCommandGroup(crc32("expand_gui_rect"));

		if (mask & (u8)EdgeMask::TOP)
		{
			setRectProperty(entity, "Top Points", 0);
			setRectProperty(entity, "Top Relative", 0);
		}

		if (mask & (u8)EdgeMask::RIGHT)
		{
			setRectProperty(entity, "Right Points", 0);
			setRectProperty(entity, "Right Relative", 1);
		}

		if (mask & (u8)EdgeMask::LEFT)
		{
			setRectProperty(entity, "Left Points", 0);
			setRectProperty(entity, "Left Relative", 0);
		}

		if (mask & (u8)EdgeMask::BOTTOM)
		{
			setRectProperty(entity, "Bottom Points", 0);
			setRectProperty(entity, "Bottom Relative", 1);
		}

		m_editor->endCommandGroup();
	}

	void makeRelative(EntityRef entity, const Vec2& canvas_size, u8 mask)
	{
		GUIScene* scene = (GUIScene*)m_editor->getUniverse()->getScene(crc32("gui"));

		EntityPtr parent = scene->getUniverse().getParent(entity);
		GUIScene::Rect parent_rect = scene->getRectEx(parent, canvas_size);
		GUIScene::Rect child_rect = scene->getRectEx(entity, canvas_size);

		m_editor->beginCommandGroup(crc32("make_gui_rect_relative"));

		if (mask & (u8)EdgeMask::TOP)
		{
			setRectProperty(entity, "Top Points", 0);
			setRectProperty(entity, "Top Relative", (child_rect.y - parent_rect.y) / parent_rect.h);
		}

		if (mask & (u8)EdgeMask::RIGHT)
		{
			setRectProperty(entity, "Right Points", 0);
			setRectProperty(entity, "Right Relative", (child_rect.x + child_rect.w - parent_rect.x) / parent_rect.w);
		}

		if (mask & (u8)EdgeMask::LEFT)
		{
			setRectProperty(entity, "Left Points", 0);
			setRectProperty(entity, "Left Relative", (child_rect.x - parent_rect.x) / parent_rect.w);
		}

		if (mask & (u8)EdgeMask::BOTTOM)
		{
			setRectProperty(entity, "Bottom Points", 0);
			setRectProperty(entity, "Bottom Relative", (child_rect.y + child_rect.h - parent_rect.y) / parent_rect.h);
		}

		m_editor->endCommandGroup();
	}

	bool hasFocus() override { return false; }
	void update(float) override {}
	const char* getName() const override { return "gui_editor"; }

	StudioApp& m_app;
	Pipeline* m_pipeline = nullptr;
	WorldEditor* m_editor = nullptr;
	bool m_is_window_open = false;
	gpu::TextureHandle m_texture_handle;
	MouseMode m_mouse_mode = MouseMode::NONE;
	Vec2 m_bottom_right_start_transform;
	Vec2 m_top_left_start_move;
};

struct StudioAppPlugin : StudioApp::IPlugin
{
	StudioAppPlugin(StudioApp& app)
		: m_app(app)
	{
	}

	const char* getName() const override { return "gui"; }
	bool dependsOn(IPlugin& plugin) const override { return equalStrings(plugin.getName(), "renderer"); }

	void init() override
	{
		m_app.registerComponent("", "gui_button", "GUI / Button");
		m_app.registerComponent("", "gui_canvas", "GUI / Canvas");
		m_app.registerComponent(ICON_FA_IMAGE, "gui_image", "GUI / Image", Sprite::TYPE, "Sprite");
		m_app.registerComponent(ICON_FA_KEYBOARD, "gui_input_field", "GUI / Input field");
		m_app.registerComponent("", "gui_rect", "GUI / Rect");
		m_app.registerComponent("", "gui_render_target", "GUI / Render target");
		m_app.registerComponent(ICON_FA_FONT, "gui_text", "GUI / Text");

		IAllocator& allocator = m_app.getAllocator();
		m_gui_editor = LUMIX_NEW(allocator, GUIEditor)(m_app);
		m_app.addPlugin(*m_gui_editor);

		m_sprite_plugin = LUMIX_NEW(allocator, SpritePlugin)(m_app);
		m_app.getAssetBrowser().addPlugin(*m_sprite_plugin);

		const char* sprite_exts[] = { "spr", nullptr };
		m_app.getAssetCompiler().addPlugin(*m_sprite_plugin, sprite_exts);
	}

	bool showGizmo(UniverseView&, ComponentUID) override { return false; }

	~StudioAppPlugin()
	{
		IAllocator& allocator = m_app.getAllocator();
		m_app.removePlugin(*m_gui_editor);
		LUMIX_DELETE(allocator, m_gui_editor);

		m_app.getAssetCompiler().removePlugin(*m_sprite_plugin);
		m_app.getAssetBrowser().removePlugin(*m_sprite_plugin);
		LUMIX_DELETE(allocator, m_sprite_plugin);
	}

	StudioApp& m_app;
	GUIEditor* m_gui_editor;
	SpritePlugin* m_sprite_plugin;
};

} // anonymous namespace

LUMIX_STUDIO_ENTRY(gui)
{
	IAllocator& allocator = app.getAllocator();
	return LUMIX_NEW(allocator, StudioAppPlugin)(app);
}


text:
namespace v8 {
namespace internal {
namespace compiler {

// Compare the two nodes and return true if node1 is a better candidate than
// node2 (i.e. node1 should be scheduled before node2).
bool InstructionScheduler::CriticalPathFirstQueue::CompareNodes(
    ScheduleGraphNode *node1, ScheduleGraphNode *node2) const {
  return node1->total_latency() > node2->total_latency();
}

InstructionScheduler::ScheduleGraphNode*
InstructionScheduler::CriticalPathFirstQueue::PopBestCandidate(int cycle) {
  DCHECK(!IsEmpty());
  auto candidate = nodes_.end();
  for (auto iterator = nodes_.begin(); iterator != nodes_.end(); ++iterator) {
    // We only consider instructions that have all their operands ready and
    // we try to schedule the critical path first.
    if (cycle >= (*iterator)->start_cycle()) {
      if ((candidate == nodes_.end()) || CompareNodes(*iterator, *candidate)) {
        candidate = iterator;
      }
    }
  }

  if (candidate != nodes_.end()) {
    ScheduleGraphNode *result = *candidate;
    nodes_.erase(candidate);
    return result;
  }

  return nullptr;
}

InstructionScheduler::ScheduleGraphNode*
InstructionScheduler::StressSchedulerQueue::PopBestCandidate(int cycle) {
  DCHECK(!IsEmpty());
  // Choose a random element from the ready list.
  auto candidate = nodes_.begin();
  std::advance(candidate, isolate()->random_number_generator()->NextInt(
      static_cast<int>(nodes_.size())));
  ScheduleGraphNode *result = *candidate;
  nodes_.erase(candidate);
  return result;
}

InstructionScheduler::ScheduleGraphNode::ScheduleGraphNode(
    Zone* zone,
    Instruction* instr)
    : instr_(instr),
      successors_(zone),
      unscheduled_predecessors_count_(0),
      latency_(GetInstructionLatency(instr)),
      total_latency_(-1),
      start_cycle_(-1) {
}

void InstructionScheduler::ScheduleGraphNode::AddSuccessor(
    ScheduleGraphNode* node) {
  successors_.push_back(node);
  node->unscheduled_predecessors_count_++;
}

InstructionScheduler::InstructionScheduler(Zone* zone,
                                           InstructionSequence* sequence)
    : zone_(zone),
      sequence_(sequence),
      graph_(zone),
      last_side_effect_instr_(nullptr),
      pending_loads_(zone),
      last_live_in_reg_marker_(nullptr) {
}

void InstructionScheduler::StartBlock(RpoNumber rpo) {
  DCHECK(graph_.empty());
  DCHECK(last_side_effect_instr_ == nullptr);
  DCHECK(pending_loads_.empty());
  DCHECK(last_live_in_reg_marker_ == nullptr);
  sequence()->StartBlock(rpo);
}

void InstructionScheduler::EndBlock(RpoNumber rpo) {
  if (FLAG_turbo_stress_instruction_scheduling) {
    ScheduleBlock<StressSchedulerQueue>();
  } else {
    ScheduleBlock<CriticalPathFirstQueue>();
  }
  sequence()->EndBlock(rpo);
  graph_.clear();
  last_side_effect_instr_ = nullptr;
  pending_loads_.clear();
  last_live_in_reg_marker_ = nullptr;
}

void InstructionScheduler::AddInstruction(Instruction* instr) {
  ScheduleGraphNode* new_node = new (zone()) ScheduleGraphNode(zone(), instr);

  if (IsBlockTerminator(instr)) {
    // Make sure that basic block terminators are not moved by adding them
    // as successor of every instruction.
    for (auto node : graph_) {
      node->AddSuccessor(new_node);
    }
  } else if (IsFixedRegisterParameter(instr)) {
    if (last_live_in_reg_marker_ != nullptr) {
      last_live_in_reg_marker_->AddSuccessor(new_node);
    }
    last_live_in_reg_marker_ = new_node;
  } else {
    if (last_live_in_reg_marker_ != nullptr) {
      last_live_in_reg_marker_->AddSuccessor(new_node);
    }

    // Instructions with side effects and memory operations can't be
    // reordered with respect to each other.
    if (HasSideEffect(instr)) {
      if (last_side_effect_instr_ != nullptr) {
        last_side_effect_instr_->AddSuccessor(new_node);
      }
      for (auto load : pending_loads_) {
        load->AddSuccessor(new_node);
      }
      pending_loads_.clear();
      last_side_effect_instr_ = new_node;
    } else if (IsLoadOperation(instr)) {
      // Load operations can't be reordered with side effects instructions but
      // independent loads can be reordered with respect to each other.
      if (last_side_effect_instr_ != nullptr) {
        last_side_effect_instr_->AddSuccessor(new_node);
      }
      pending_loads_.push_back(new_node);
    }

    // Look for operand dependencies.
    for (auto node : graph_) {
      if (HasOperandDependency(node->instruction(), instr)) {
        node->AddSuccessor(new_node);
      }
    }
  }

  graph_.push_back(new_node);
}

template <typename QueueType>
void InstructionScheduler::ScheduleBlock() {
  QueueType ready_list(this);

  // Compute total latencies so that we can schedule the critical path first.
  ComputeTotalLatencies();

  // Add nodes which don't have dependencies to the ready list.
  for (auto node : graph_) {
    if (!node->HasUnscheduledPredecessor()) {
      ready_list.AddNode(node);
    }
  }

  // Go through the ready list and schedule the instructions.
  int cycle = 0;
  while (!ready_list.IsEmpty()) {
    auto candidate = ready_list.PopBestCandidate(cycle);

    if (candidate != nullptr) {
      sequence()->AddInstruction(candidate->instruction());

      for (auto successor : candidate->successors()) {
        successor->DropUnscheduledPredecessor();
        successor->set_start_cycle(
            std::max(successor->start_cycle(),
                     cycle + candidate->latency()));

        if (!successor->HasUnscheduledPredecessor()) {
          ready_list.AddNode(successor);
        }
      }
    }

    cycle++;
  }
}

int InstructionScheduler::GetInstructionFlags(const Instruction* instr) const {
  switch (instr->arch_opcode()) {
    case kArchNop:
    case kArchFramePointer:
    case kArchParentFramePointer:
    case kArchTruncateDoubleToI:
    case kArchStackSlot:
      return kNoOpcodeFlags;

    case kArchStackPointer:
      // ArchStackPointer instruction loads the current stack pointer value and
      // must not be reordered with instruction with side effects.
      return kIsLoadOperation;

    case kArchPrepareCallCFunction:
    case kArchPrepareTailCall:
    case kArchCallCFunction:
    case kArchCallCodeObject:
    case kArchCallJSFunction:
      return kHasSideEffect;

    case kArchTailCallCodeObject:
    case kArchTailCallJSFunction:
      return kHasSideEffect | kIsBlockTerminator;

    case kArchDeoptimize:
    case kArchJmp:
    case kArchLookupSwitch:
    case kArchTableSwitch:
    case kArchRet:
    case kArchThrowTerminator:
      return kIsBlockTerminator;

    case kCheckedLoadInt8:
    case kCheckedLoadUint8:
    case kCheckedLoadInt16:
    case kCheckedLoadUint16:
    case kCheckedLoadWord32:
    case kCheckedLoadWord64:
    case kCheckedLoadFloat32:
    case kCheckedLoadFloat64:
      return kIsLoadOperation;

    case kCheckedStoreWord8:
    case kCheckedStoreWord16:
    case kCheckedStoreWord32:
    case kCheckedStoreWord64:
    case kCheckedStoreFloat32:
    case kCheckedStoreFloat64:
    case kArchStoreWithWriteBarrier:
      return kHasSideEffect;

#define CASE(Name) case k##Name:
    TARGET_ARCH_OPCODE_LIST(CASE)
#undef CASE
      return GetTargetInstructionFlags(instr);
  }

  UNREACHABLE();
  return kNoOpcodeFlags;
}

bool InstructionScheduler::HasOperandDependency(
    const Instruction* instr1, const Instruction* instr2) const {
  for (size_t i = 0; i < instr1->OutputCount(); ++i) {
    for (size_t j = 0; j < instr2->InputCount(); ++j) {
      const InstructionOperand* output = instr1->OutputAt(i);
      const InstructionOperand* input = instr2->InputAt(j);

      if (output->IsUnallocated() && input->IsUnallocated() &&
          (UnallocatedOperand::cast(output)->virtual_register() ==
           UnallocatedOperand::cast(input)->virtual_register())) {
        return true;
      }

      if (output->IsConstant() && input->IsUnallocated() &&
          (ConstantOperand::cast(output)->virtual_register() ==
           UnallocatedOperand::cast(input)->virtual_register())) {
        return true;
      }
    }
  }

  // TODO(bafsa): Do we need to look for anti-dependencies/output-dependencies?

  return false;
}

bool InstructionScheduler::IsBlockTerminator(const Instruction* instr) const {
  return ((GetInstructionFlags(instr) & kIsBlockTerminator) ||
          (instr->flags_mode() == kFlags_branch));
}

void InstructionScheduler::ComputeTotalLatencies() {
  for (auto node : base::Reversed(graph_)) {
    int max_latency = 0;

    for (auto successor : node->successors()) {
      DCHECK(successor->total_latency() != -1);
      if (successor->total_latency() > max_latency) {
        max_latency = successor->total_latency();
      }
    }

    node->set_total_latency(max_latency + node->latency());
  }
}

}  // namespace compiler
}  // namespace internal
}  // namespace v8


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var React = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _clsx = _interopRequireDefault(require("clsx"));

var _unstyled = require("@material-ui/unstyled");

var _capitalize = _interopRequireDefault(require("../utils/capitalize"));

var _styled = _interopRequireDefault(require("../styles/styled"));

var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps"));

var _StepperContext = _interopRequireDefault(require("../Stepper/StepperContext"));

var _StepContext = _interopRequireDefault(require("../Step/StepContext"));

var _stepConnectorClasses = require("./stepConnectorClasses");

var _jsxRuntime = require("react/jsx-runtime");

const _excluded = ["className"];

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

const useUtilityClasses = styleProps => {
  const {
    classes,
    orientation,
    alternativeLabel,
    active,
    completed,
    disabled
  } = styleProps;
  const slots = {
    root: ['root', orientation, alternativeLabel && 'alternativeLabel', active && 'active', completed && 'completed', disabled && 'disabled'],
    line: ['line', `line${(0, _capitalize.default)(orientation)}`]
  };
  return (0, _unstyled.unstable_composeClasses)(slots, _stepConnectorClasses.getStepConnectorUtilityClass, classes);
};

const StepConnectorRoot = (0, _styled.default)('div', {
  name: 'MuiStepConnector',
  slot: 'Root',
  overridesResolver: (props, styles) => {
    const {
      styleProps
    } = props;
    return (0, _extends2.default)({}, styles.root, styles[styleProps.orientation], styleProps.alternativeLabel && styles.alternativeLabel, styleProps.completed && styles.completed);
  }
})(({
  styleProps
}) => (0, _extends2.default)({
  /* Styles applied to the root element. */
  flex: '1 1 auto'
}, styleProps.orientation === 'vertical' && {
  marginLeft: 12 // half icon

}, styleProps.alternativeLabel && {
  position: 'absolute',
  top: 8 + 4,
  left: 'calc(-50% + 20px)',
  right: 'calc(50% + 20px)'
}));
const StepConnectorLine = (0, _styled.default)('span', {
  name: 'MuiStepConnector',
  slot: 'Line',
  overridesResolver: (props, styles) => {
    const {
      styleProps
    } = props;
    return (0, _extends2.default)({}, styles.line, styles[`line${(0, _capitalize.default)(styleProps.orientation)}`]);
  }
})(({
  styleProps,
  theme
}) => (0, _extends2.default)({
  /* Styles applied to the line element. */
  display: 'block',
  borderColor: theme.palette.mode === 'light' ? theme.palette.grey[400] : theme.palette.grey[600]
}, styleProps.orientation === 'horizontal' && {
  borderTopStyle: 'solid',
  borderTopWidth: 1
}, styleProps.orientation === 'vertical' && {
  borderLeftStyle: 'solid',
  borderLeftWidth: 1,
  minHeight: 24
}));
const StepConnector = /*#__PURE__*/React.forwardRef(function StepConnector(inProps, ref) {
  const props = (0, _useThemeProps.default)({
    props: inProps,
    name: 'MuiStepConnector'
  });
  const {
    className
  } = props,
        other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
  const {
    alternativeLabel,
    orientation = 'horizontal'
  } = React.useContext(_StepperContext.default);
  const {
    active,
    disabled,
    completed
  } = React.useContext(_StepContext.default);
  const styleProps = (0, _extends2.default)({}, props, {
    alternativeLabel,
    orientation,
    active,
    completed,
    disabled
  });
  const classes = useUtilityClasses(styleProps);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(StepConnectorRoot, (0, _extends2.default)({
    className: (0, _clsx.default)(classes.root, className),
    ref: ref,
    styleProps: styleProps
  }, other, {
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(StepConnectorLine, {
      className: classes.line,
      styleProps: styleProps
    })
  }));
});
process.env.NODE_ENV !== "production" ? StepConnector.propTypes
/* remove-proptypes */
= {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------

  /**
   * Override or extend the styles applied to the component.
   */
  classes: _propTypes.default.object,

  /**
   * @ignore
   */
  className: _propTypes.default.string,

  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx: _propTypes.default.object
} : void 0;
var _default = StepConnector;
exports.default = _default;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Pets</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

        Pets
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarHeader" aria-controls="navbarHeader" aria-expanded="false" aria-label="Toggle navigation">

        </button>

Pets Display

Project for nodeJS
A website for showing different pets

          Main call to action
          Secondary action

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.

          Back to top

Album example is © Bootstrap


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>SinkTokenizer.Add Method</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache Lucene.Net 2.4.0 Class Library API

SinkTokenizer.Add Method

 Override this method to cache only certain tokens, or new tokens based on the old tokens.

public virtual void Add(
   Token t
);

Parameters

          t

The {@link Lucene.Net.Analysis.Token} to add to the sink

See Also

        SinkTokenizer Class | Lucene.Net.Analysis Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="Add method">
        </param>
        <param name="Keyword" value="Add method, SinkTokenizer class">
        </param>
        <param name="Keyword" value="SinkTokenizer.Add method">
        </param>
      </object>

Generated from assembly Lucene.Net [2.4.0.2]


text:
/**
 * @file Get server-side configuration in advance of bootstrapping the app
 *
 * This is a kind of loader plugin of Require.js.
 *
 * @since 15. 12. 3
 * @author Koong Kyungmi (kyungmi.k@samsung.com)
 */

define([
    'webida-lib/webida-0.3'
], function (
    webida
) {
    'use strict';

    return {
        load: function (name, req, onLoad) {
            req([webida.conf.appApiBaseUrl + '/configs?callback=define'], function (configs) {
                onLoad(configs);
            });
        }
    };
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KeyValueStorage.Testing;
using NUnit.Framework;
using KeyValueStorage;

namespace KeyValueStorage.Redis.Tests
{
    [TestFixture]
    public class MainTests
    {
        [SetUp]
        public void SetUp()
        {
            KVStore.Initialize(new Func<Interfaces.IStoreProvider>(() => new KeyValueStorage.Redis.RedisStoreProvider(new ServiceStack.Redis.RedisClient())));
        }

        [Test]
        public void CRUDSingleSimpleItemTest()
        {
            ReusableTests.CRUDSingleSimpleItemTest();
        }

        [Test]
        public void SequenceTest()
        {
            ReusableTests.SequenceTest();
        }

        [Test]
        public void CASTest()
        {
            ReusableTests.CASTest();
        }

        [Test]
        public void KeysStartingWithTest()
        {
            ReusableTests.KeysStartingWithTest();
        }

        [Test]
        public void ValuesStartingWithTest()
        {
            ReusableTests.ValuesStartingWithTest();
        }

        [Test]
        public void CollectionsTest()
        {
            ReusableTests.CollectionsTest();
        }

        [Test]
        public void DoesNotExistTest()
        {
            ReusableTests.DoesNotExistTest();
        }
    }
}


text:
package org.zstack.network.service.virtualrouter;

import org.springframework.beans.factory.annotation.Autowired;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.network.service.*;

public class VirtualRouterProviderFactory implements NetworkServiceProviderFactory {
	public static final NetworkServiceProviderType type = new NetworkServiceProviderType(VirtualRouterConstant.VIRTUAL_ROUTER_PROVIDER_TYPE);

    @Autowired
    private DatabaseFacade dbf;

	public NetworkServiceProviderType getType() {
		return type;
	}

	public void createNetworkServiceProvider(APIAddNetworkServiceProviderMsg msg, NetworkServiceProviderVO vo) {
	}

	public NetworkServiceProvider getNetworkServiceProvider(NetworkServiceProviderVO vo) {
		return new VirtualRouterProvider(vo);
	}
}


text:
import * as Causes from './Causes.js';
import {resultString} from './pretty.js';

export const ResultSymbol = Symbol('result');
const ResultProto = {
    toString() {
        return resultString(this);
    },
};

const Result = (state, cause=Causes.none) => {
    const result = Object.create(ResultProto);
    result.state = state;
    result.cause = cause;
    result[ResultSymbol] = true;
    return result;
};

export default Result;


text:
//
//  DetailViewController.h
//  Created by Devin Ross on 7/7/10.
//

@import UIKit;
#import <TapkuLibrary/TapkuLibrary.h>

@interface DetailViewController : UIViewController <UISplitViewControllerDelegate, UITableViewDataSource>

@property (nonatomic,strong) UIViewController *mainController;
@property (nonatomic,strong) UIPopoverController *currentPopoverController;

- (void) setupWithMainController:(UIViewController*)controller;

@end


text:
package com.spotify.heroic.jetty;

import com.spotify.heroic.HeroicConfigurationContext;
import com.spotify.heroic.HeroicModule;
import com.spotify.heroic.dagger.LoadingComponent;

public class Module implements HeroicModule {
    @Override
    public Runnable setup(final LoadingComponent loading) {
        final HeroicConfigurationContext config = loading.heroicConfigurationContext();

        return () -> {
            config.registerType("http", HttpJettyConnectionFactory.Builder.class);
            config.registerType("h2c", Http2CJettyConnectionFactory.Builder.class);
            config.registerType("h2", Http2JettyConnectionFactory.Builder.class);
            config.registerType("tls", TLSJettyConnectionFactory.Builder.class);
        };
    }
}


text:
using Skybrud.Social.Http;
using Skybrud.Social.Interfaces.Http;

namespace Skybrud.Social.Spotify.Options.Albums {

    /// <summary>
    /// Class representing the options for getting the tracks of a Spotify album.
    /// </summary>
    /// <see>
    ///     <cref>https://developer.spotify.com/web-api/get-albums-tracks/</cref>
    /// </see>
    public class SpotifyGetAlbumTracksOptions : IHttpGetOptions {

        #region Properties

        /// <summary>
        /// Gets or sets the Spotify ID for the album.
        /// </summary>
        public string AlbumId { get; set; }

        /// <summary>
        /// Gets or sets the maximum number of tracks to return. Default: <c>20</c>. Maximum: <c>50</c>.
        /// </summary>
        public int Limit { get; set; }

        /// <summary>
        /// Gets or sets the index of the first track to return. Default: <c>0</c> (the first object). Use with
        /// <see cref="Limit"/> to get the next set of tracks.
        /// </summary>
        public int Offset { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance with default options.
        /// </summary>
        public SpotifyGetAlbumTracksOptions() { }

        /// <summary>
        /// Initializes a new instance based on the specified <paramref name="albumId"/>.
        /// </summary>
        /// <param name="albumId">The Spotify ID for the album.</param>
        public SpotifyGetAlbumTracksOptions(string albumId) {
            AlbumId = albumId;
        }

        /// <summary>
        /// Initializes a new instance based on the specified <paramref name="albumId"/> and <paramref name="limit"/>.
        /// </summary>
        /// <param name="albumId">The Spotify ID for the album.</param>
        /// <param name="limit">The maximum number of tracks to return. Default: <c>20</c>. Maximum: <c>50</c>.</param>
        public SpotifyGetAlbumTracksOptions(string albumId, int limit) {
            AlbumId = albumId;
            Limit = limit;
        }

        /// <summary>
        /// Initializes a new instance based on the specified <paramref name="albumId"/>, <paramref name="limit"/> and <paramref name="offset"/>.
        /// </summary>
        /// <param name="albumId">The Spotify ID for the album.</param>
        /// <param name="limit">The maximum number of tracks to return. Default: <c>20</c>. Maximum: <c>50</c>.</param>
        /// <param name="offset">The index of the first track to return. Default: <c>0</c> (the first object).</param>
        public SpotifyGetAlbumTracksOptions(string albumId, int limit, int offset) {
            AlbumId = albumId;
            Limit = limit;
            Offset = offset;
        }

        #endregion

        #region Member methods

        /// <summary>
        /// Gets an instance of <see cref="IHttpQueryString"/> representing the GET parameters.
        /// </summary>
        public IHttpQueryString GetQueryString() {
            SocialHttpQueryString query = new SocialHttpQueryString();
            if (Limit > 0) query.Add("limit", Limit);
            if (Offset > 0) query.Add("offset", Offset);
            return query;
        }

        #endregion

    }

}


text:
<?php
declare(strict_types = 1);

namespace Firefly\Entity;

class Audio
{
    use EntityTrait;
    public $content = [
        'contentMetadata' => [
            'AUDLEN' => '240000'
        ]
    ];

    public function setOriginalContentUrl(string $url)
    {
        $this->content['originalContentUrl'] = $url;
    }
}


text:
import { ISuggestionBuilder } from 'datahub-web/utils/parsers/autocomplete/types';

/**
 * In order to give suggestions we need to process the text to remove the last work
 * so we can autocomplete the rest correctly. Also, we will save a reference to the last word.
 * @param builder
 */
export const processText = (builder: ISuggestionBuilder): ISuggestionBuilder => {
  if (typeof builder.text === 'undefined') {
    return builder;
  }

  const splitText = builder.text.split(' ');
  const previousTextWithSpace = splitText.slice(0, splitText.length - 1).join(' ');

  return {
    ...builder,
    textPrevious: `${previousTextWithSpace}${previousTextWithSpace.length > 0 ? ' ' : ''}`,
    textLastWord: splitText[splitText.length - 1]
  };
};


text:
describe('ChampionUtil Testsuite', function () {
	'use strict';

	const ChampionUtil = require('../../lib/util/ChampionUtil');
	const TestUtil = require('../TestUtil');

	const chai = require("chai");
	// const chaiAsPromised = require("chai-as-promised");
	// const should = chai.should;
	const expect = chai.expect;
	// const expect = chai.expect;
	// chai.use(chaiAsPromised);
	chai.should();

	describe('getChampionKeysFromName()', function () {
		it('returns the expected key for every champion (depends on StaticData Endpoint!)', function () {
			const config = TestUtil.getTestConfig();
			const StaticEndpoint = require('../../lib/compatibility/StaticDataDDragonCompat');
			const endpoint = new StaticEndpoint(config, TestUtil.createRateLimiter(0,0,false));

			return endpoint.gettingChampions('na1').then(({data}) => {
				return Object.keys(data).map(champKey => {
					const champ = data[champKey];
					expect(ChampionUtil.getChampionKeyFromName(champ.name),
						`"${champ.name}" was not correctly transformed into "${champ.key}"`
					).to.equal(champ.key);
				});
			});
		});
	});
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace sholan.Compiler.Nodes
{
    public class IfNode : AbstractCompileNode
    {
        public ICompileNode Check
        {
            get;
            set;
        }

        public ICompileNode BranchTrue
        {
            get;
            set;
        }

        public ICompileNode BranchFalse
        {
            get;
            set;
        }

        public IfNode(int line, int col)
            : base(line, col)
        {
            this.Attributes
                .Has("if");
        }

        public override void PrePass(Kernel k)
        {
            base.PrePass(k);

            this.Check.Attributes
                .Check("value");

            this.Check.PrePass(k);

            if(this.BranchTrue != null)
                this.BranchTrue.PrePass(k);

            if (this.BranchFalse != null)
                this.BranchFalse.PrePass(k);
        }

        public override void PreCompile(Kernel k)
        {
            this.Check.PreCompile(k);

            if (this.BranchTrue != null)
                this.BranchTrue.PreCompile(k);

            if (this.BranchFalse != null)
                this.BranchFalse.PreCompile(k);
        }

        public override void Compile(Kernel k)
        {
            k.CurrentScope.PushMemory(k);

            Scope ifScope = k.PushScope();
            ifScope.Name = "if" + ifScope.Parent.RequestLabelId();

            string trueLabel = "sl_if_" + k.GetScopeName();
            string falseLabel = "sl_fe_" + k.GetScopeName();
            string endLabel = "sl_fh_" + k.GetScopeName();

            this.Check.Compile(k);

            k.Emit(Opcode.GOTOF, '"' + trueLabel + '"').SetDebug(File, Line, Column, DebugType.Branch, "");
            k.Emit(Opcode.GOTO, '"' + falseLabel + '"');

            k.Emit(Opcode.LABEL, trueLabel);

            k.CurrentScope.PushMemory(k);

            Scope trueScope = k.PushScope();
            trueScope.Name = "true";

            if (this.BranchTrue != null)
                this.BranchTrue.Compile(k);

            k.PopScope();

            k.CurrentScope.PopMemory(k);

            if(this.BranchFalse == null)
            {
                k.Emit(Opcode.LABEL, falseLabel).Comment = "no else block, used as end label";
            }
            else if(this.BranchFalse != null)
            {
                k.Emit(Opcode.GOTO, '"' + endLabel + '"');

                k.Emit(Opcode.LABEL, falseLabel);

                k.CurrentScope.PushMemory(k);

                Scope falseScope = k.PushScope();
                falseScope.Name = "false";

                this.BranchFalse.Compile(k);

                k.PopScope();

                k.CurrentScope.PopMemory(k);

                k.Emit(Opcode.LABEL, endLabel).Comment = "end if";
            }

            k.PopScope();

            k.CurrentScope.PopMemory(k);
        }
    }
}


text:
layout: post
title: "X Plus Z 分享(第十期)"
description: ""
category:
tags: []
---

`引用经典`

`Cease to struggle and you cease to live.`

----

###### Front-end

* Sass Guidelines中文版本 - Shared by Jack
    * <http://www.w3cplus.com/blog/tags/466.html>
* 使用 AngularJS 从零构建大型应用 - Shared by Jack
    * <http://v2ex.com/t/168015#reply27>
* front-end guidelines - Some HTML, CSS and JS best practices - Shared by Jack
	* <https://github.com/bendc/frontend-guidelines>
* 浏览器的工作原理:新式网络浏览器幕后揭秘 - Shared by Jack
	* <http://www.html5rocks.com/zh/tutorials/internals/howbrowserswork/>
* This 详解 - Shared by Jack
	* <http://www.cnblogs.com/Wayou/p/all-this.html>
	* this 虐我千百遍,看完此文效立见!不得不说,这篇文章的总结很地道很全面,适合收藏之用。
* 斯坦福大学公开课:iOS 8开发 - Shared by Jack
	* <http://open.163.com/special/opencourse/ios8.html>

----

###### Back-end
* Goodbye MongoDB, Hello PostgreSQL - Shared by Jack
	* <http://developer.olery.com/blog/goodbye-mongodb-hello-postgresql/>
* Java Bootstrap: Dropwizard vs. Spring Boot - Shared by Jack
	* <http://jaxenter.com/java-bootstrap-dropwizard-vs-spring-boot-115514.html>

----

###### Test

*   测试之美 - Shared by Jack
	* <http://blog.learningbyshipping.com/2014/09/25/beauty-of-testing/>
*   Software testing blog - Shared by Carol
	* <http://softwaretestinghelp.com/>

----

###### 工具
* Swagger Editor - Shared by Jack
	* <http://editor.swagger.io/>
* Create useful .gitignore files for your project - Shared by Jack
	* <https://www.gitignore.io/>
* Sublime Text 3 文档 - Shared by Jack
	* <http://feliving.github.io/Sublime-Text-3-Documentation/>
* GitGuys:成为 Git 深度玩家的好资源 - Shared by Jack
	* <http://www.gitguys.com/topics/>
* The easiest way to start using Docker on Mac - Shared by Jack
	* <https://kitematic.com/>
* Shortcuts for the Git Commands You Use Everyday - Shared by Jack
	* <https://github.com/qw3rtman/gg>
* 我最喜欢的比较工具Beyondcompare - Shared by Jack
	* <http://www.scootersoftware.com/download.php>
	* 你懂的 <http://share.weiyun.com/08ccd98e6a380f084a35e3f361111ca5>(密码:fC2b)

----

###### 编程之外
* 像女孩一样Coding - Shared by Jack
	* <https://medium.com/@sailorhg/coding-like-a-girl-595b90791cce>
	* 这是篇鼓励女码农自信表现的文章。就像<Lean In>说的:" women should feel free to be assertive if that's their personality and let's celebrate that instead of criticizing it, but let's also celebrate people that display leadership by empathy and encouraging."
* GitHub是怎样战胜Google,Microsoft的
	* <http://www.wired.com/2015/03/github-conquered-google-microsoft-everyone-else/>
	* 应景一下google宣布要下线google code.
* What are the top 10 websites a web developer must see? - Shared by Jack
	* <http://www.quora.com/What-are-the-top-10-websites-a-web-developer-must-see>
*  一个很有意思的问题
	* If Chinese students read or study more than American students, why is it that America still leads the Chinese in almost all aspects of life - technology, entrepreneurs, etc?
	* <http://www.quora.com/If-Chinese-students-read-or-study-more-than-American-students-why-is-it-that-America-still-leads-the-Chinese-in-almost-all-aspects-of-life-technology-entrepreneurs-etc>

----

* 特别感谢支持X+Z分享并做出贡献的人,"三克油给你妈吃".

* 特别提醒: X+Z分享每三周的周五推出.

* 第一时间得获知分享,请关注公司微信公众账号.

![X PLUS Z WEICHAT](https://s3-us-west-1.amazonaws.com/xplusz.com/x%2Bz_weichat.png)


text:
namespace component_updater {

TEST(FileTypePoliciesComponentInstallerTest, VerifyAttributes) {
  FileTypePoliciesComponentInstallerPolicy installer_policy;
  update_client::InstallerAttributes attributes;
  // Feature disabled
  {
    base::test::ScopedFeatureList feature_list;
    feature_list.InitAndDisableFeature(safe_browsing::kFileTypePoliciesTag);

    attributes = installer_policy.GetInstallerAttributes();
    EXPECT_EQ(attributes["tag"], "default");
  }

  // Feature enabled
  {
    base::test::ScopedFeatureList feature_list;
    base::test::FeatureRefAndParams feature_params(
        safe_browsing::kFileTypePoliciesTag, {{"policy_omaha_tag", "46"}});
    feature_list.InitWithFeaturesAndParameters({feature_params}, {});

    attributes = installer_policy.GetInstallerAttributes();
    EXPECT_EQ(attributes["tag"], "46");
  }
}

}  // namespace component_updater


text:
| Version | Supported          |
| ------- | ------------------ |
| 0.5.x   | :white_check_mark: |
| < 0.5   | :x:                |

## Reporting a Vulnerability

Please email the address listed at [https://github.com/cardoe](https://github.com/cardoe)
and include the name of the crate and the fact that its security related in the subject.


text:
package com.coolweather.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;

import com.coolweather.receiver.AutoUpdateReceiver;
import com.coolweather.util.HttpCallbackListener;
import com.coolweather.util.HttpUtil;
import com.coolweather.util.Utility;

public class AutoUpdateService extends Service {
    public AutoUpdateService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                updateWeather();

            }
        }).start();

        AlarmManager manager= (AlarmManager) getSystemService(ALARM_SERVICE);
        int anHour=3*60*60*1000;//3小时更新一次
        long triggerAtTime= SystemClock.elapsedRealtime()+anHour;
        Intent i=new Intent(this,AutoUpdateReceiver.class);//从现在开始,3小时候后通知广播准备更新天气信息
        PendingIntent pi=PendingIntent.getBroadcast(this,0,i,0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi);
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 更新天气
     */
 private void  updateWeather(){

     SharedPreferences preferences= PreferenceManager.getDefaultSharedPreferences(this);
     String weatherCode=preferences.getString("weather_code", "");
     String address="http://www.weather.com.cn/data/cityinfo/"+weatherCode+".html";
     HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
         @Override
         public void onFinish(String response) {
             Utility.handleWeatherResponse(AutoUpdateService.this,response);
         }

         @Override
         public void onError(Exception e) {
             e.printStackTrace();
         }
     });

 }

}


text:
import gulp from 'gulp';
import path from 'path';
import minimatch from 'minimatch';
import project from '../aurelia.json';

export default function copyFiles(done) {
    if (typeof project.build.copyFiles !== 'object') {
        done();
        return;
    }

    const instruction = getNormalizedInstruction();
    const files = Object.keys(instruction);

    return gulp.src(files, {since: gulp.lastRun(copyFiles)})
        .pipe(gulp.dest(x => {
            const filePath = prepareFilePath(x.path);
            const key = files.find(f => minimatch(filePath, f));
            return instruction[key];
        }));
}

function getNormalizedInstruction() {
    const files = project.build.copyFiles;
    let normalizedInstruction = {};

    for (let key in files) {
        normalizedInstruction[path.posix.normalize(key)] = files[key];
    }

    return normalizedInstruction;
}

function prepareFilePath(filePath) {
    let preparedPath = filePath.replace(process.cwd(), '').slice(1);

    //if we are running on windows we have to fix the path
    if (/^win/.test(process.platform)) {
        preparedPath = preparedPath.replace(/\\/g, '/');
    }

    return preparedPath;
}


text:
import configs.module
import configs.locs
from . import ailib
import time

def init(options):
    server = options['server']
    server.state['ai'] = ailib.AI(
        configs.locs.userdb + '/ailib.%s.py' % server.entry['settings'])
    m = configs.module.Module(__name__)
    m.set_help('Talk with the chatbot.')
    m.add_short_command_hook(chatbot, 'chatbot::Talk to the bot',
        ['text...::What you have to say.'],
        rights=['normal'], noquote=True)
    m.add_command_alias('c', 'chatbot')
    m.add_command_alias('talk', 'chatbot')
    return m

def chatbot(fp, args):
    ai = fp.server.state['ai']
    e = 'chatbot.lastphrase.%s' % fp.outtarget()
    etime = e + '.time'
    lasttime = fp.server.state[
        etime] if etime in fp.server.state else time.time()
    lastphrase = fp.server.state[e] if e in fp.server.state else None
    if (time.time() - lasttime) > 30:
        lastphrase = ""
    fp.server.state[
        etime] = time.time()
    if not args.getlinstr('text', ''):
        return "I'll only answer if you say something."
    out = ai.process(args.getlinstr('text'), lastphrase)
    fp.server.state[e] = out
    return out


text:
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

    <title>PHPXRef 0.7.1 : Unnamed Project : Detail view of shell_test.php</title>
    <link rel="stylesheet" href="../../../sample.css" type="text/css">
    <link rel="stylesheet" href="../../../sample-print.css" type="text/css" media="print">

    <meta http-equiv="content-type" content="text/html;charset=iso-8859-1">

            [ Index ]

PHP Cross Reference of Unnamed Project

[ Show Explorer ]
[ Hide Navbar ]

title

Body

[close]

/tests/simpletest/test/ -> shell_test.php (summary)

[Source view]
[Print]
[Project Stats]

(no description)

File Size: 	38 lines (1 kb)

Included or required:	0 times

Referenced: 	0 times

Includes or requires: 	0 files

Defines 2 classes

TestOfShell:: (2 methods):

  testEcho()

  testBadCommand()

TestOfShellTesterAndShell:: (3 methods):

  testEcho()

  testFileExistence()

  testFilePatterns()

Class: TestOfShell  - X-Ref

testEcho()
X-Ref

No description

testBadCommand()
X-Ref

No description

Class: TestOfShellTesterAndShell  - X-Ref

testEcho()
X-Ref

No description

testFileExistence()
X-Ref

No description

testFilePatterns()
X-Ref

No description

Generated: Thu Oct 23 18:57:41 2014
	Cross-referenced by PHPXref 0.7.1


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using CSharpViaTest.IOs.Helpers;
using Xunit;
using Xunit.Abstractions;

namespace CSharpViaTest.IOs.HandleText
{
    /*
     * Description
     * ===========
     *
     * This test will show the basic usage of text stream. In this test, you should create
     * a function `StatCharacterUsage` which accept an UTF-8 encoded text stream. The
     * function should returns a histogram containing the statistics of English character
     * usage (case insensitive). All non-English character will be ignored.
     *
     * Difficulty: Super Hard
     *
     * Knowledge Point
     * ===============
     *
     * - Use `TextReader` to decode text content from binary stream.
     * - How to handle large stream using restricted memory block.
     * - Do not take control of object's lifetime if it is not created by yourself.
     *
     * Requirement
     * ===========
     *
     * - The memory efficiency should be O(1).
     * - This function should handle 128 MB of text within 12 seconds.
     */
    public class CreateStatisticsOnCharacterUsage
    {
        readonly ITestOutputHelper output;

        public CreateStatisticsOnCharacterUsage(ITestOutputHelper output)
        {
            this.output = output;
        }

        static Stream CreateStringStream(string text)
        {
            var stream = new MemoryStream();
            byte[] textBytes = Encoding.UTF8.GetBytes(text);
            stream.Write(textBytes, 0, textBytes.Length);
            stream.Flush();

            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }

        #region Please modifies the code to pass the test

        static Dictionary<char, int> StatCharacterUsage(Stream stream)
        {
            throw new NotImplementedException();
        }

        #endregion

        [Fact]
        public void should_create_statistics_on_character_usage()
        {
            Stream textFileStream = CreateStringStream("A quick brown fox jumps over a lazy dog.");
            Dictionary<char, int> histogram = StatCharacterUsage(textFileStream);

            Assert.Equal(3, histogram['a']);
            Assert.Equal(1, histogram['q']);
            Assert.Equal(2, histogram['u']);
            Assert.Equal(1, histogram['i']);
            Assert.Equal(1, histogram['c']);
            Assert.Equal(1, histogram['k']);
            Assert.Equal(1, histogram['b']);
            Assert.Equal(2, histogram['r']);
            Assert.Equal(4, histogram['o']);
            Assert.Equal(1, histogram['w']);
            Assert.Equal(1, histogram['n']);
            Assert.Equal(1, histogram['f']);
            Assert.Equal(1, histogram['x']);
            Assert.Equal(1, histogram['j']);
            Assert.Equal(1, histogram['m']);
            Assert.Equal(1, histogram['p']);
            Assert.Equal(1, histogram['s']);
            Assert.Equal(1, histogram['v']);
            Assert.Equal(1, histogram['e']);
            Assert.Equal(1, histogram['l']);
            Assert.Equal(1, histogram['z']);
            Assert.Equal(1, histogram['y']);
            Assert.Equal(1, histogram['d']);
            Assert.Equal(1, histogram['g']);
        }

        [Fact]
        public void should_be_able_to_handle_very_large_stream()
        {
            const long length = 128 * 1024 * 1024;
            using (var stream = new Utf8RandomTextStream(length))
            {
                var watch = Stopwatch.StartNew();
                StatCharacterUsage(stream);
                watch.Stop();
                output.WriteLine($"Time used to handle {length / 1024 / 1024} MB of text: {watch.Elapsed:g}");
                Assert.True(watch.Elapsed < TimeSpan.FromSeconds(12), "Oh, too slow!");
            }
        }

        [Fact]
        public void should_not_dispose_input_stream()
        {
            using (var stream = new Utf8RandomTextStream(10))
            {
                StatCharacterUsage(stream);
                Assert.False(stream.Disposed);
            }
        }
    }
}


text:
package org.apache.tamaya.model.spi;

import org.apache.tamaya.model.Validation;

import java.util.Objects;

/**
 * Default configuration Model for a configuration area.
 */
public abstract class AbstractValidation implements Validation {

    private String name;
    private String description;

    protected AbstractValidation(String name, String description) {
        this.name = Objects.requireNonNull(name);
        this.description = description;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getDescription() {
        return description;
    }

}


text:
#import <XCTest/XCTest.h>

#import <Cordova/CDVUIWebViewDelegate.h>

@interface CDVWebViewDelegate2 : CDVUIWebViewDelegate {}

- (void)setState:(NSInteger)state;
- (NSInteger)state;

@end

@implementation  CDVWebViewDelegate2

- (void)setState:(NSInteger)state
{
    _state = state;
}

- (NSInteger)state
{
    return _state;
}

@end

@interface CDVUIWebViewDelegate ()

// expose private interface
- (BOOL)shouldLoadRequest:(NSURLRequest*)request;

@end

@interface CDVWebViewDelegateTests : XCTestCase
@end

@implementation CDVWebViewDelegateTests

- (void)setUp
{
    [super setUp];
}

- (void)tearDown
{
    [super tearDown];
}

- (void)testFailLoadStateCancelled
{
    NSInteger initialState = 1; // STATE_WAITING_FOR_LOAD_START;
    NSInteger expectedState = 5; // STATE_CANCELLED;
    NSError* errorCancelled = [NSError errorWithDomain:NSCocoaErrorDomain code:NSURLErrorCancelled userInfo:nil];

    CDVWebViewDelegate2* wvd = [[CDVWebViewDelegate2 alloc] initWithDelegate:nil]; // not really testing delegate handling

    wvd.state = initialState;
    [wvd webView:nil didFailLoadWithError:errorCancelled];

    XCTAssertTrue(wvd.state == expectedState, @"If the load error was through an iframe redirect (NSURLErrorCancelled), the state should be STATE_CANCELLED");
}

- (void)testShouldLoadRequest
{
    CDVUIWebViewDelegate* wvd = [[CDVUIWebViewDelegate alloc] initWithDelegate:nil]; // not really testing delegate handling

    NSURLRequest* mailtoUrl = [NSURLRequest requestWithURL:[NSURL URLWithString:@"mailto:dev@cordova.apache.org"]];
    NSURLRequest* telUrl = [NSURLRequest requestWithURL:[NSURL URLWithString:@"tel:12345"]];
    NSURLRequest* plainUrl = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://apache.org"]];

    XCTAssertTrue([wvd shouldLoadRequest:mailtoUrl], @"mailto urls should be allowed");
    XCTAssertTrue([wvd shouldLoadRequest:telUrl], @"tel urls should be allowed");
    // as long as this is in the whitelist it should pass
    XCTAssertTrue([wvd shouldLoadRequest:plainUrl], @"http urls should be allowed");
}

- (void)testFragmentIdentifiersWithHttpUrl
{
    [self doTestFragmentIdentifiersWithBaseUrl:@"http://cordova.apache.org" fragment:@"myfragment"];
}

- (void)testFragmentIdentifiersWithFileUrl
{
    [self doTestFragmentIdentifiersWithBaseUrl:@"file:///var/mobile/GASGEQGQsdga3313/www/index.html" fragment:@"myfragment"];
}

- (void)testFragmentIdentifiersWithFileUrlAndMalformedFragment
{
    [self doTestFragmentIdentifiersWithBaseUrl:@"file:///var/mobile/GASGEQGQsdga3313/www/index.html" fragment:@"/var/mobile/GASGEQGQsdga3313/www/index.html"];
}

- (void)doTestFragmentIdentifiersWithBaseUrl:(NSString*)baseUrl fragment:(NSString*)fragment
{
    CDVUIWebViewDelegate* wvd = [[CDVUIWebViewDelegate alloc] initWithDelegate:nil]; // not really testing delegate handling

    NSString* originalUrlString = baseUrl;
    NSURL* originalUrl = [NSURL URLWithString:originalUrlString];
    NSURL* originalUrlWithFragmentOnly = [NSURL URLWithString:[NSString stringWithFormat:@"%@#%@", originalUrlString, fragment]];
    NSURL* originalUrlWithFragmentOnlyNoIdentifier = [NSURL URLWithString:[NSString stringWithFormat:@"%@#", originalUrlString]];
    NSURL* originalUrlWithQueryParamsAndFragment = [NSURL URLWithString:[NSString stringWithFormat:@"%@?foo=bar#%@", originalUrlString, fragment]];

    NSURLRequest* originalRequest = [NSURLRequest requestWithURL:originalUrl];
    NSURLRequest* originalRequestWithFragmentOnly = [NSURLRequest requestWithURL:originalUrlWithFragmentOnly];
    NSURLRequest* originalRequestWithFragmentOnlyNoIdentifier = [NSURLRequest requestWithURL:originalUrlWithFragmentOnlyNoIdentifier];
    NSURLRequest* originalRequestWithQueryParamsAndFragment = [NSURLRequest requestWithURL:originalUrlWithQueryParamsAndFragment];
    NSURLRequest* notOriginalRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://httpd.apache.org"]];

    XCTAssertTrue([wvd request:originalRequest isEqualToRequestAfterStrippingFragments:originalRequest], @"originalRequest should be a be equal to originalRequest after stripping fragments");
    XCTAssertTrue([wvd request:originalRequestWithFragmentOnly isEqualToRequestAfterStrippingFragments:originalRequest], @"originalRequestWithFragment should be equal to originalRequest after stripping fragment");
    XCTAssertTrue([wvd request:originalRequestWithFragmentOnlyNoIdentifier isEqualToRequestAfterStrippingFragments:originalRequest], @"originalRequestWithFragmentNoIdentifier should be equal to originalRequest after stripping fragment");
    XCTAssertFalse([wvd request:originalRequestWithQueryParamsAndFragment isEqualToRequestAfterStrippingFragments:originalRequest], @"originalRequestWithQueryParamsAndFragment should not be equal to originalRequest after stripping fragment");
    XCTAssertFalse([wvd request:notOriginalRequest isEqualToRequestAfterStrippingFragments:originalRequest], @"notOriginalRequest should not be equal to originalRequest after stripping fragment");

    // equality tests
    XCTAssertTrue([wvd request:originalRequestWithFragmentOnly isEqualToRequestAfterStrippingFragments:originalRequestWithFragmentOnly], @"originalRequestWithFragment should be a equal to itself after stripping fragments");
    XCTAssertTrue([wvd request:originalRequestWithFragmentOnlyNoIdentifier isEqualToRequestAfterStrippingFragments:originalRequestWithFragmentOnlyNoIdentifier], @"originalRequestWithFragmentNoIdentifier should be a equal to itself after stripping fragments");
    XCTAssertTrue([wvd request:originalRequestWithQueryParamsAndFragment isEqualToRequestAfterStrippingFragments:originalRequestWithQueryParamsAndFragment], @"originalRequestWithQueryParamsAndFragment should be equal to itself after stripping fragments");
}

@end


text: {!! \Illuminate\Support\Arr::get($injectedAssets ?? [], 'head') !!}


text:
using System;
using System.Linq;
using Accord.Math.Optimization;
using QuantSA.Shared.CurvesAndSurfaces;
using QuantSA.Shared.Dates;

namespace QuantSA.Core.CurvesAndSurfaces
{
    /// <summary>
    /// A Nelson Siegel parametric curve.
    /// </summary>
    public class NelsonSiegel : ICurve
    {
        private readonly Date _anchorDate;
        private readonly double _beta0;
        private readonly double _beta1;
        private readonly double _beta2;
        private readonly double _tau;

        /// <summary>
        ///
        /// </summary>
        /// <param name="anchorDate"></param>
        /// <param name="beta0"></param>
        /// <param name="beta1"></param>
        /// <param name="beta2"></param>
        /// <param name="tau"></param>
        public NelsonSiegel(Date anchorDate, double beta0, double beta1, double beta2, double tau)
        {
            _anchorDate = anchorDate;
            _beta0 = beta0;
            _beta1 = beta1;
            _beta2 = beta2;
            _tau = tau;
        }

        /// <summary>
        ///  Interpolate the rate at required date.
        /// </summary>
        /// <param name="date">The date at which the rate is required.</param>
        /// <returns></returns>
        public double InterpAtDate(Date date)
        {
            return Interp(_beta0, _beta1, _beta2, _tau, date - _anchorDate);
        }

        /// <summary>
        /// Fits a Nelson Siegel curve to data
        /// </summary>
        /// <param name="anchorDate"></param>
        /// <param name="dates"></param>
        /// <param name="rates"></param>
        /// <returns></returns>
        public static NelsonSiegel Fit(Date anchorDate, Date[] dates, double[] rates)
        {
            var times = new double[dates.Length];
            for (var i = 0; i < dates.Length; i++) times[i] = dates[i] - anchorDate;

            Func<double[], double> f = x => ErrorFunction(x, times, rates);

            var nm = new NelderMead(4, f);
            var success = nm.Minimize(new[] {rates[0], rates[0], rates[0], times.Last() / 5.0});
            var minValue = nm.Value;
            var solution = nm.Solution;
            var curve = new NelsonSiegel(anchorDate, solution[0], solution[1], solution[2], solution[3]);

            return curve;
        }

        private static double ErrorFunction(double[] parameters, double[] t, double[] r)
        {
            double error = 0;
            for (var i = 0; i < t.Length; i++)
            {
                var diff = Interp(parameters[0], parameters[1], parameters[2], parameters[3], t[i]) - r[i];
                error += diff * diff;
            }

            return error;
        }

        /// <summary>
        /// Apply the Nelson Siegel formula to a time.
        /// </summary>
        /// <param name="beta0"></param>
        /// <param name="beta1"></param>
        /// <param name="beta2"></param>
        /// <param name="tau"></param>
        /// <param name="t">time at which the rate is required</param>
        /// <returns></returns>
        private static double Interp(double beta0, double beta1, double beta2, double tau, double t)
        {
            var rate = beta0 +
                       (beta1 + beta2) * (1 - Math.Exp(-t / tau)) * tau / t -
                       beta2 * Math.Exp(-t / tau);

            return rate;
        }
    }
}