text:
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    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.

package com.google.devtools.build.lib.rules.proto;

import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Streams;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.config.ExecutionTransitionFactory;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.packages.Attribute;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.List;

/**
 * A list proto source files to be excluded from code generation.
 *
 * <p>There are cases where we need to identify proto files that we should not create generated
 * files for. For example, we should not create generated code for google/protobuf/any.proto, which
 * is already baked into the language support libraries. This class provides us with the ability to
 * identify these proto files and avoid linking in their associated generated files.
 */
public class ProtoSourceFileExcludeList {
  private static final PathFragment BAZEL_TOOLS_PREFIX =
      PathFragment.create("external/bazel_tools/");
  private final RuleContext ruleContext;
  private final ImmutableSet<PathFragment> noGenerateProtoFilePaths;

  /**
   * Creates a proto source file exclusion list.
   *
   * @param ruleContext the proto rule context.
   * @param noGenerateProtoFiles a list of .proto files. The list will be iterated.
   */
  public ProtoSourceFileExcludeList(
      RuleContext ruleContext, NestedSet<Artifact> noGenerateProtoFiles) {
    this.ruleContext = ruleContext;
    ImmutableSet.Builder<PathFragment> noGenerateProtoFilePathsBuilder =
        new ImmutableSet.Builder<>();
    for (Artifact noGenerateProtoFile : noGenerateProtoFiles.toList()) {
      PathFragment execPath = noGenerateProtoFile.getExecPath();
      // For listed protos bundled with the Bazel tools repository, their exec paths start
      // with external/bazel_tools/. This prefix needs to be removed first, because the protos in
      // user repositories will not have that prefix.
      if (execPath.startsWith(BAZEL_TOOLS_PREFIX)) {
        noGenerateProtoFilePathsBuilder.add(execPath.relativeTo(BAZEL_TOOLS_PREFIX));
      } else {
        noGenerateProtoFilePathsBuilder.add(execPath);
      }
    }
    noGenerateProtoFilePaths = noGenerateProtoFilePathsBuilder.build();
  }

  /** Filters the listed protos from the given protos. */
  public Iterable<Artifact> filter(Iterable<Artifact> protoFiles) {
    return Streams.stream(protoFiles).filter(f -> !isExcluded(f)).collect(toImmutableSet());
  }

  /**
   * Checks the proto sources for mixing excluded and non-excluded protos in one single
   * proto_library rule. Registers an attribute error if proto mixing is detected.
   *
   * @param protoSources the protos to filter.
   * @param topLevelProtoRuleName the name of the top-level rule that generates the protos.
   * @return whether the proto sources are clean without mixing.
   */
  public boolean checkSrcs(ImmutableList<ProtoSource> protoSources, String topLevelProtoRuleName) {
    ImmutableList.Builder<Artifact> protoFiles = ImmutableList.builder();
    for (ProtoSource protoSource : protoSources) {
      protoFiles.add(protoSource.getOriginalSourceFile());
    }
    return checkSrcs(protoFiles.build(), topLevelProtoRuleName);
  }

  @Deprecated
  public boolean checkSrcs(Iterable<Artifact> protoFiles, String topLevelProtoRuleName) {
    List<Artifact> excluded = new ArrayList<>();
    List<Artifact> nonExcluded = new ArrayList<>();
    for (Artifact protoFile : protoFiles) {
      if (isExcluded(protoFile)) {
        excluded.add(protoFile);
      } else {
        nonExcluded.add(protoFile);
      }
    }
    if (!nonExcluded.isEmpty() && !excluded.isEmpty()) {
      ruleContext.attributeError(
          "srcs",
          createBlacklistedProtosMixError(
              Artifact.toRootRelativePaths(excluded),
              Artifact.toRootRelativePaths(nonExcluded),
              ruleContext.getLabel().toString(),
              topLevelProtoRuleName));
    }

    return excluded.isEmpty();
  }

  /** Returns whether the given proto file is excluded. */
  public boolean isExcluded(Artifact protoFile) {
    return noGenerateProtoFilePaths.contains(protoFile.getExecPath());
  }

  /**
   * Returns an attribute for the implicit dependency on blacklist proto filegroups.
   *
   * @param attributeName the name of the attribute.
   * @param blacklistFileGroups a list of labels pointin to the filegroups containing excluded
   *     protos.
   */
  public static Attribute.Builder<List<Label>> blacklistFilegroupAttribute(
      String attributeName, List<Label> blacklistFileGroups) {
    return attr(attributeName, LABEL_LIST)
        .cfg(ExecutionTransitionFactory.create())
        .value(blacklistFileGroups);
  }

  @VisibleForTesting
  public static String createBlacklistedProtosMixError(
      Iterable<String> excluded,
      Iterable<String> nonExcluded,
      String protoLibraryRuleLabel,
      String topLevelProtoRuleName) {
    return String.format(
        "The 'srcs' attribute of '%s' contains protos for which '%s' "
            + "shouldn't generate code (%s), in addition to protos for which it should (%s).\n"
            + "Separate '%1$s' into 2 proto_library rules.",
        protoLibraryRuleLabel,
        topLevelProtoRuleName,
        Joiner.on(", ").join(excluded),
        Joiner.on(", ").join(nonExcluded));
  }
}


text:
=head1 NAME

vbucket_config_get_num_replicas, vbucket_config_get_num_vbuckets, vbucket_config_get_num_servers, vbucket_config_get_server

=head1 SYNOPSIS

#include <libvbucket/vbucket.h>

int vbucket_config_get_num_replicas(VBUCKET_CONFIG_HANDLE handle);

int vbucket_config_get_num_vbuckets(VBUCKET_CONFIG_HANDLE handle);

int vbucket_config_get_num_servers(VBUCKET_CONFIG_HANDLE handle);

const char *vbucket_config_get_server(VBUCKET_CONFIG_HANDLE handle, int server_index);

=head1 DESCRIPTION

The following functions returns information from the vbucket configuration.

=over 2
=item vbucket_config_get_num_replicas

=item vbucket_config_get_num_vbuckets

=item vbucket_config_get_num_servers

=item vbucket_config_get_server

=back

=head1 RETURN

vbucket_config_get_num_replicas returns the number of replicas that
should be available for each item in the system.

vbucket_config_get_num_vbuckets returns the total number of vbuckets
within the system.

vbucket_config_get_num_servers returns the number of servers defined
within the system.

vbucket_config_get_server returns a textuals string indentifying the
server with "hostname:port". NULL is returned if the index cannot be
found.

=head1 SEE ALSO

libvbucket(3lib) libvbucket(4) vbucket_config_parse_file(3vbucket) vbucket_config_parse_string(3vbucket) vbucket_config_destroy(3vbucket) vbucket_get_error(3vbucket) vbucket_get_vbucket_by_key(3vbucket) vbucket_get_master(3vbucket) vbucket_get_replica(3vbucket)

=cut

redpajama_set_name: RedPajamaGithub


text:
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com.                */
#include <engine/demo.h>
#include <engine/graphics.h>
#include <engine/textrender.h>
#include <engine/shared/config.h>

#include <game/generated/client_data.h>
#include <game/generated/protocol.h>

#include <game/localization.h>
#include <game/client/animstate.h>
#include <game/client/gameclient.h>
#include <game/client/render.h>
#include <game/client/components/countryflags.h>
#include <game/client/components/motd.h>

#include "scoreboard.h"

CScoreboard::CScoreboard()
{
	OnReset();
}

void CScoreboard::ConKeyScoreboard(IConsole::IResult *pResult, void *pUserData)
{
	((CScoreboard *)pUserData)->m_Active = pResult->GetInteger(0) != 0;
}

void CScoreboard::OnReset()
{
	m_Active = false;
}

void CScoreboard::OnRelease()
{
	m_Active = false;
}

void CScoreboard::OnConsoleInit()
{
	Console()->Register("+scoreboard", "", CFGFLAG_CLIENT, ConKeyScoreboard, this, "Show scoreboard");
}

void CScoreboard::RenderGoals(float x, float y, float w)
{
	float h = 50.0f;

	Graphics()->BlendNormal();
	Graphics()->TextureSet(-1);
	Graphics()->QuadsBegin();
	Graphics()->SetColor(0,0,0,0.5f);
	RenderTools()->DrawRoundRect(x, y, w, h, 10.0f);
	Graphics()->QuadsEnd();

	// render goals
	y += 10.0f;
	if(m_pClient->m_Snap.m_pGameInfoObj)
	{
		if(m_pClient->m_Snap.m_pGameInfoObj->m_ScoreLimit)
		{
			char aBuf[64];
			str_format(aBuf, sizeof(aBuf), "%s: %d", Localize("Score limit"), m_pClient->m_Snap.m_pGameInfoObj->m_ScoreLimit);
			TextRender()->Text(0, x+10.0f, y, 20.0f, aBuf, -1);
		}
		if(m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit)
		{
			char aBuf[64];
			str_format(aBuf, sizeof(aBuf), Localize("Time limit: %d min"), m_pClient->m_Snap.m_pGameInfoObj->m_TimeLimit);
			TextRender()->Text(0, x+230.0f, y, 20.0f, aBuf, -1);
		}
		if(m_pClient->m_Snap.m_pGameInfoObj->m_RoundNum && m_pClient->m_Snap.m_pGameInfoObj->m_RoundCurrent)
		{
			char aBuf[64];
			str_format(aBuf, sizeof(aBuf), "%s %d/%d", Localize("Round"), m_pClient->m_Snap.m_pGameInfoObj->m_RoundCurrent, m_pClient->m_Snap.m_pGameInfoObj->m_RoundNum);
			float tw = TextRender()->TextWidth(0, 20.0f, aBuf, -1);
			TextRender()->Text(0, x+w-tw-10.0f, y, 20.0f, aBuf, -1);
		}
	}
}

void CScoreboard::RenderSpectators(float x, float y, float w)
{
	float h = 140.0f;

	// background
	Graphics()->BlendNormal();
	Graphics()->TextureSet(-1);
	Graphics()->QuadsBegin();
	Graphics()->SetColor(0,0,0,0.5f);
	RenderTools()->DrawRoundRect(x, y, w, h, 10.0f);
	Graphics()->QuadsEnd();

	// Headline
	y += 10.0f;
	TextRender()->Text(0, x+10.0f, y, 28.0f, Localize("Spectators"), w-20.0f);

	// spectator names
	y += 30.0f;
	char aBuffer[1024*4];
	aBuffer[0] = 0;
	bool Multiple = false;
	for(int i = 0; i < MAX_CLIENTS; ++i)
	{
		const CNetObj_PlayerInfo *pInfo = m_pClient->m_Snap.m_paPlayerInfos[i];
		if(!pInfo || pInfo->m_Team != TEAM_SPECTATORS)
			continue;

		if(Multiple)
			str_append(aBuffer, ", ", sizeof(aBuffer));
		str_append(aBuffer, m_pClient->m_aClients[pInfo->m_ClientID].m_aName, sizeof(aBuffer));
		Multiple = true;
	}
	CTextCursor Cursor;
	TextRender()->SetCursor(&Cursor, x+10.0f, y, 22.0f, TEXTFLAG_RENDER);
	Cursor.m_LineWidth = w-20.0f;
	Cursor.m_MaxLines = 4;
	TextRender()->TextEx(&Cursor, aBuffer, -1);
}

void CScoreboard::RenderScoreboard(float x, float y, float w, int Team, const char *pTitle)
{
	if(Team == TEAM_SPECTATORS)
		return;

	float h = 760.0f;

	// background
	Graphics()->BlendNormal();
	Graphics()->TextureSet(-1);
	Graphics()->QuadsBegin();
	Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.5f);
	RenderTools()->DrawRoundRect(x, y, w, h, 17.0f);
	Graphics()->QuadsEnd();

	// render title
	float TitleFontsize = 40.0f;
	if(!pTitle)
	{
		if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)
			pTitle = Localize("Game over");
		else
			pTitle = Localize("Score board");
	}
	TextRender()->Text(0, x+20.0f, y, TitleFontsize, pTitle, -1);

	char aBuf[128] = {0};
	if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS)
	{
		if(m_pClient->m_Snap.m_pGameDataObj)
		{
			int Score = Team == TEAM_RED ? m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreRed : m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreBlue;
			str_format(aBuf, sizeof(aBuf), "%d", Score);
		}
	}
	else
	{
		if(m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_Snap.m_SpecInfo.m_SpectatorID != SPEC_FREEVIEW &&
			m_pClient->m_Snap.m_paPlayerInfos[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID])
		{
			int Score = m_pClient->m_Snap.m_paPlayerInfos[m_pClient->m_Snap.m_SpecInfo.m_SpectatorID]->m_Score;
			str_format(aBuf, sizeof(aBuf), "%d", Score);
		}
		else if(m_pClient->m_Snap.m_pLocalInfo)
		{
			int Score = m_pClient->m_Snap.m_pLocalInfo->m_Score;
			str_format(aBuf, sizeof(aBuf), "%d", Score);
		}
	}
	float tw = TextRender()->TextWidth(0, TitleFontsize, aBuf, -1);
	TextRender()->Text(0, x+w-tw-20.0f, y, TitleFontsize, aBuf, -1);

	// calculate measurements
	x += 10.0f;
	float LineHeight = 60.0f;
	float TeeSizeMod = 1.0f;
	float Spacing = 16.0f;
	if(m_pClient->m_Snap.m_aTeamSize[Team] > 12)
	{
		LineHeight = 40.0f;
		TeeSizeMod = 0.8f;
		Spacing = 0.0f;
	}
	else if(m_pClient->m_Snap.m_aTeamSize[Team] > 8)
	{
		LineHeight = 50.0f;
		TeeSizeMod = 0.9f;
		Spacing = 8.0f;
	}

	float ScoreOffset = x+10.0f, ScoreLength = 60.0f;
	float TeeOffset = ScoreOffset+ScoreLength, TeeLength = 60*TeeSizeMod;
	float NameOffset = TeeOffset+TeeLength, NameLength = 300.0f-TeeLength;
	float PingOffset = x+610.0f, PingLength = 65.0f;
	float CountryOffset = PingOffset-(LineHeight-Spacing-TeeSizeMod*5.0f)*2.0f, CountryLength = (LineHeight-Spacing-TeeSizeMod*5.0f)*2.0f;
	float ClanOffset = x+370.0f, ClanLength = 230.0f-CountryLength;

	// render headlines
	y += 50.0f;
	float HeadlineFontsize = 22.0f;
	tw = TextRender()->TextWidth(0, HeadlineFontsize, Localize("Score"), -1);
	TextRender()->Text(0, ScoreOffset+ScoreLength-tw, y, HeadlineFontsize, Localize("Score"), -1);

	TextRender()->Text(0, NameOffset, y, HeadlineFontsize, Localize("Name"), -1);

	tw = TextRender()->TextWidth(0, HeadlineFontsize, Localize("Clan"), -1);
	TextRender()->Text(0, ClanOffset+ClanLength/2-tw/2, y, HeadlineFontsize, Localize("Clan"), -1);

	tw = TextRender()->TextWidth(0, HeadlineFontsize, Localize("Ping"), -1);
	TextRender()->Text(0, PingOffset+PingLength-tw, y, HeadlineFontsize, Localize("Ping"), -1);

	// render player entries
	y += HeadlineFontsize*2.0f;
	float FontSize = 24.0f;
	CTextCursor Cursor;

	for(int i = 0; i < MAX_CLIENTS; i++)
	{
		// make sure that we render the correct team
		const CNetObj_PlayerInfo *pInfo = m_pClient->m_Snap.m_paInfoByScore[i];
		if(!pInfo || pInfo->m_Team != Team)
			continue;

		// background so it's easy to find the local player or the followed one in spectator mode
		if(pInfo->m_Local || (m_pClient->m_Snap.m_SpecInfo.m_Active && pInfo->m_ClientID == m_pClient->m_Snap.m_SpecInfo.m_SpectatorID))
		{
			Graphics()->TextureSet(-1);
			Graphics()->QuadsBegin();
			Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f);
			RenderTools()->DrawRoundRect(x, y, w-20.0f, LineHeight, 15.0f);
			Graphics()->QuadsEnd();
		}

		// score
		str_format(aBuf, sizeof(aBuf), "%d", clamp(pInfo->m_Score, -999, 999));
		tw = TextRender()->TextWidth(0, FontSize, aBuf, -1);
		TextRender()->SetCursor(&Cursor, ScoreOffset+ScoreLength-tw, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);
		Cursor.m_LineWidth = ScoreLength;
		TextRender()->TextEx(&Cursor, aBuf, -1);

		// flag
		if(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_FLAGS &&
			m_pClient->m_Snap.m_pGameDataObj && (m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierRed == pInfo->m_ClientID ||
			m_pClient->m_Snap.m_pGameDataObj->m_FlagCarrierBlue == pInfo->m_ClientID))
		{
			Graphics()->BlendNormal();
			Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);
			Graphics()->QuadsBegin();

			RenderTools()->SelectSprite(pInfo->m_Team==TEAM_RED ? SPRITE_FLAG_BLUE : SPRITE_FLAG_RED, SPRITE_FLAG_FLIP_X);

			float Size = LineHeight;
			IGraphics::CQuadItem QuadItem(TeeOffset+0.0f, y-5.0f-Spacing/2.0f, Size/2.0f, Size);
			Graphics()->QuadsDrawTL(&QuadItem, 1);
			Graphics()->QuadsEnd();
		}

		// avatar
		CTeeRenderInfo TeeInfo = m_pClient->m_aClients[pInfo->m_ClientID].m_RenderInfo;
		TeeInfo.m_Size *= TeeSizeMod;
		RenderTools()->RenderTee(CAnimState::GetIdle(), &TeeInfo, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(TeeOffset+TeeLength/2, y+LineHeight/2));

		// name
		TextRender()->SetCursor(&Cursor, NameOffset, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);
		Cursor.m_LineWidth = NameLength;
		TextRender()->TextEx(&Cursor, m_pClient->m_aClients[pInfo->m_ClientID].m_aName, -1);

		// clan
		tw = TextRender()->TextWidth(0, FontSize, m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, -1);
		TextRender()->SetCursor(&Cursor, ClanOffset+ClanLength/2-tw/2, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);
		Cursor.m_LineWidth = ClanLength;
		TextRender()->TextEx(&Cursor, m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, -1);

		// country flag
		vec4 Color(1.0f, 1.0f, 1.0f, 0.5f);
		m_pClient->m_pCountryFlags->Render(m_pClient->m_aClients[pInfo->m_ClientID].m_Country, &Color,
											CountryOffset, y+(Spacing+TeeSizeMod*5.0f)/2.0f, CountryLength, LineHeight-Spacing-TeeSizeMod*5.0f);

		// ping
		str_format(aBuf, sizeof(aBuf), "%d", clamp(pInfo->m_Latency, 0, 1000));
		tw = TextRender()->TextWidth(0, FontSize, aBuf, -1);
		TextRender()->SetCursor(&Cursor, PingOffset+PingLength-tw, y+Spacing, FontSize, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);
		Cursor.m_LineWidth = PingLength;
		TextRender()->TextEx(&Cursor, aBuf, -1);

		y += LineHeight+Spacing;
	}
}

void CScoreboard::RenderRecordingNotification(float x)
{
	if(!m_pClient->DemoRecorder()->IsRecording())
		return;

	//draw the box
	Graphics()->BlendNormal();
	Graphics()->TextureSet(-1);
	Graphics()->QuadsBegin();
	Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.4f);
	RenderTools()->DrawRoundRectExt(x, 0.0f, 180.0f, 50.0f, 15.0f, CUI::CORNER_B);
	Graphics()->QuadsEnd();

	//draw the red dot
	Graphics()->QuadsBegin();
	Graphics()->SetColor(1.0f, 0.0f, 0.0f, 1.0f);
	RenderTools()->DrawRoundRect(x+20, 15.0f, 20.0f, 20.0f, 10.0f);
	Graphics()->QuadsEnd();

	//draw the text
	char aBuf[64];
	int Seconds = m_pClient->DemoRecorder()->Length();
	str_format(aBuf, sizeof(aBuf), Localize("REC %3d:%02d"), Seconds/60, Seconds%60);
	TextRender()->Text(0, x+50.0f, 10.0f, 20.0f, aBuf, -1);
}

void CScoreboard::OnRender()
{
	if(!Active())
		return;

	// if the score board is active, then we should clear the motd message aswell
	if(m_pClient->m_pMotd->IsActive())
		m_pClient->m_pMotd->Clear();

	float Width = 400*3.0f*Graphics()->ScreenAspect();
	float Height = 400*3.0f;

	Graphics()->MapScreen(0, 0, Width, Height);

	float w = 700.0f;

	if(m_pClient->m_Snap.m_pGameInfoObj)
	{
		if(!(m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS))
			RenderScoreboard(Width/2-w/2, 150.0f, w, 0, 0);
		else
		{
			const char *pRedClanName = GetClanName(TEAM_RED);
			const char *pBlueClanName = GetClanName(TEAM_BLUE);

			if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER && m_pClient->m_Snap.m_pGameDataObj)
			{
				char aText[256];
				str_copy(aText, Localize("Draw!"), sizeof(aText));

				if(m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreRed > m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreBlue)
				{
					if(pRedClanName)
						str_format(aText, sizeof(aText), Localize("%s wins!"), pRedClanName);
					else
						str_copy(aText, Localize("Red team wins!"), sizeof(aText));
				}
				else if(m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreBlue > m_pClient->m_Snap.m_pGameDataObj->m_TeamscoreRed)
				{
					if(pBlueClanName)
						str_format(aText, sizeof(aText), Localize("%s wins!"), pBlueClanName);
					else
						str_copy(aText, Localize("Blue team wins!"), sizeof(aText));
				}

				float w = TextRender()->TextWidth(0, 86.0f, aText, -1);
				TextRender()->Text(0, Width/2-w/2, 39, 86.0f, aText, -1);
			}

			RenderScoreboard(Width/2-w-5.0f, 150.0f, w, TEAM_RED, pRedClanName ? pRedClanName : Localize("Red team"));
			RenderScoreboard(Width/2+5.0f, 150.0f, w, TEAM_BLUE, pBlueClanName ? pBlueClanName : Localize("Blue team"));
		}
	}

	RenderGoals(Width/2-w/2, 150+760+10, w);
	RenderSpectators(Width/2-w/2, 150+760+10+50+10, w);
	RenderRecordingNotification((Width/7)*4);
}

bool CScoreboard::Active()
{
	// if we activly wanna look on the scoreboard
	if(m_Active)
		return true;

	if(m_pClient->m_Snap.m_pLocalInfo && m_pClient->m_Snap.m_pLocalInfo->m_Team != TEAM_SPECTATORS)
	{
		// we are not a spectator, check if we are dead
		if(!m_pClient->m_Snap.m_pLocalCharacter)
			return true;
	}

	// if the game is over
	if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)
		return true;

	return false;
}

const char *CScoreboard::GetClanName(int Team)
{
	int ClanPlayers = 0;
	const char *pClanName = 0;
	for(int i = 0; i < MAX_CLIENTS; i++)
	{
		const CNetObj_PlayerInfo *pInfo = m_pClient->m_Snap.m_paInfoByScore[i];
		if(!pInfo || pInfo->m_Team != Team)
			continue;

		if(!pClanName)
		{
			pClanName = m_pClient->m_aClients[pInfo->m_ClientID].m_aClan;
			ClanPlayers++;
		}
		else
		{
			if(str_comp(m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, pClanName) == 0)
				ClanPlayers++;
			else
				return 0;
		}
	}

	if(ClanPlayers > 1 && pClanName[0])
		return pClanName;
	else
		return 0;
}


text:
curl -s http://getcomposer.org/installer | php
php -d memory_limit=-1 composer.phar install --dev --prefer-dist
php Tests/Functionnal/bin/console --env=test doctrine:database:drop --force
php Tests/Functionnal/bin/console --env=test doctrine:database:create
php Tests/Functionnal/bin/console --env=test cache:warmup
php Tests/Functionnal/bin/console --env=test doctrine:schema:create
php Tests/Functionnal/bin/console --env=test victoire:generate:view
php Tests/Functionnal/bin/console --env=test assets:install Tests/Functionnal/web
php Tests/Functionnal/bin/console --env=test assetic:dump
nohup php Tests/Functionnal/bin/console --env=test server:run -r vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Resources/config/router_prod.php &
sleep 5
curl http://selenium-release.storage.googleapis.com/2.45/selenium-server-standalone-2.45.0.jar > selenium-server-standalone-2.45.0.jar
nohup java -jar selenium-server-standalone-2.45.0.jar > /dev/null &
phpunit --coverage-text

php ./vendor/bin/behat $1


text:
package org.apache.bcel.generic;

/**
 * Implement this interface if you're interested in changes to a MethodGen object and register yourself with
 * addObserver().
 */
public interface MethodObserver {

    void notify(MethodGen method);
}


text:
using System.Web.Mvc;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace PrimeTables.Web.Installers
{
    using Plumbing;

    public class ControllersInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(
                Classes.
                    FromThisAssembly().
                    BasedOn<IController>().
                    If(c => c.Name.EndsWith("Controller")).
                    LifestyleTransient());

            ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));
        }
    }
}


text:
# About

PotreeConverter generates an octree LOD structure for streaming and real-time rendering of massive point clouds. The results can be viewed in web browsers with [Potree](https://github.com/potree/potree) or as a desktop application with [PotreeDesktop](https://github.com/potree/PotreeDesktop).

Version 2.0 is a complete rewrite with following differences over the previous version 1.7:

* About 10 to 50 times faster than PotreeConverter 1.7 on SSDs.
* Produces a total of 3 files instead of thousands to tens of millions of files. The reduction of the number of files improves file system operations such as copy, delete and upload to servers from hours and days to seconds and minutes.
* Better support for standard LAS attributes and arbitrary extra attributes. Full support (e.g. int64 and uint64) in development.
* Optional compression is not yet available in the new converter but on the roadmap for a future update.

Altough the converter made a major step to version 2.0, the format it produces is also supported by Potree 1.7. The Potree viewer is scheduled to make the major step to version 2.0 in 2021, with a rewrite in WebGPU.

# Publications

* [Potree: Rendering Large Point Clouds in Web Browsers](https://www.cg.tuwien.ac.at/research/publications/2016/SCHUETZ-2016-POT/SCHUETZ-2016-POT-thesis.pdf)
* [Fast Out-of-Core Octree Generation for Massive Point Clouds](https://www.cg.tuwien.ac.at/research/publications/2020/SCHUETZ-2020-MPC/), _Schütz M., Ohrhallinger S., Wimmer M._

# Getting Started

1. Download windows binaries or
    * Download source code
	* Install [CMake](https://cmake.org/) 3.16 or later
	* Create and jump into folder "build"
	    ```
	    mkdir build
	    cd build
	    ```
	* run
	    ```
	    cmake ../
	    ```
	* On linux, run: ```make```
	* On windows, open Visual Studio 2019 Project ./Converter/Converter.sln and compile it in release mode
2. run ```PotreeConverter.exe <input> -o <outputDir>```
    * Optionally specify the sampling strategy:
	* Poisson-disk sampling (default): ```PotreeConverter.exe <input> -o <outputDir> -m poisson```
	* Random sampling: ```PotreeConverter.exe <input> -o <outputDir> -m random```

In Potree, modify one of the examples with following load command:

```javascript
let url = "../pointclouds/D/temp/test/metadata.json";
Potree.loadPointCloud(url).then(e => {
	let pointcloud = e.pointcloud;
	let material = pointcloud.material;

	material.activeAttributeName = "rgba";
	material.minSize = 2;
	material.pointSizeType = Potree.PointSizeType.ADAPTIVE;

	viewer.scene.addPointCloud(pointcloud);
	viewer.fitToScreen();
});

```

# Alternatives

PotreeConverter 2.0 produces a very different format than previous iterations. If you find issues, you can still try previous converters or alternatives:

		PotreeConverter 2.0
		PotreeConverter 1.7
		Entwine

		license

			free, BSD 2-clause

			free, BSD 2-clause

			free, LGPL

		#generated files

			3 files total

			1 per node

			1 per node

		compression

			none (TODO)

			LAZ (optional)

			LAZ

Performance comparison (Ryzen 2700, NVMe SSD):

![](./docs/images/performance_chart.png)

# License

PotreeConverter is available under the [BSD 2-clause license](./LICENSE).


text:
/**
 * This class provides access to device GPS data.
 * @constructor
 */
function Geolocation() {
    /**
     * The last known GPS position.
     */
	this.started = false;
    this.lastPosition = null;
    this.lastError = null;
    this.callbacks = {
        onLocationChanged: [],
        onError:           []
    };
}

/**
 * Asynchronously aquires the current position.
 * @param {Function} successCallback The function to call when the position
 * data is available
 * @param {Function} errorCallback The function to call when there is an error
 * getting the position data.
 * @param {PositionOptions} options The options for getting the position data
 * such as timeout.
 */
Geolocation.prototype.getCurrentPosition = function(successCallback, errorCallback, options) {
    var referenceTime = 0, timeout = 20000, interval = 500, delay = 0, dis = this, timer;
    if (this.lastPosition) {
        referenceTime = this.lastPosition.timeout;
    } else {
        this.start(options);
    }

    if (typeof(options) === 'object' && options.interval) {
        interval = options.interval;
    }

    if (typeof(successCallback) !== 'function') {
        successCallback = function() {};
    }
    if (typeof(errorCallback) !== 'function') {
        errorCallback = function() {};
    }

    timer = setInterval(function() {
        delay += interval;
        if (dis.lastPosition !== null && dis.lastPosition.timestamp > referenceTime) {
            successCallback(dis.lastPosition);
            clearInterval(timer);
        } else if (delay >= timeout) {
            errorCallback();
            clearInterval(timer);
        }
    }, interval);
};

/**
 * Asynchronously aquires the position repeatedly at a given interval.
 * @param {Function} successCallback The function to call each time the position
 * data is available
 * @param {Function} errorCallback The function to call when there is an error
 * getting the position data.
 * @param {PositionOptions} options The options for getting the position data
 * such as timeout and the frequency of the watch.
 */
Geolocation.prototype.watchPosition = function(successCallback, errorCallback, options) {
	// Invoke the appropriate callback with a new Position object every time the implementation
	// determines that the position of the hosting device has changed.
	var frequency = 10000, that = this;

	this.getCurrentPosition(successCallback, errorCallback, options);

    if (typeof(options) === 'object' && options.frequency) {
        frequency = options.frequency;
    }

	return setInterval(function() {
		that.getCurrentPosition(successCallback, errorCallback, options);
	}, frequency);
};

/**
 * Clears the specified position watch.
 * @param {String} watchId The ID of the watch returned from #watchPosition.
 */
Geolocation.prototype.clearWatch = function(watchId) {
	clearInterval(watchId);
};

/**
 * Called by the geolocation framework when the current location is found.
 * @param {PositionOptions} position The current position.
 */
Geolocation.prototype.setLocation = function(position) {
    var i = 0;
    this.lastPosition = position;
    for (; i < this.callbacks.onLocationChanged.length; i++) {
        this.callbacks.onLocationChanged.shift()(position);
    }
};

/**
 * Called by the geolocation framework when an error occurs while looking up the current position.
 * @param {String} message The text of the error message.
 */
Geolocation.prototype.setError = function(message) {
    var i = 0;
    this.lastError = message;
    for (; i < this.callbacks.onError.length; i++) {
        this.callbacks.onError.shift()(message);
    }
};

if (typeof navigator.geolocation === "undefined") { navigator.geolocation = new Geolocation(); }

/**
 * Starts the GPS of the device
 */
Geolocation.prototype.start = function() {
	if (this.started) {
		return;
	} else {
		PhoneGap.exec("location", ["start"]);
	}
};

/**
 * Stops the GPS of the device
 */
Geolocation.prototype.stop = function() {
	if (!this.started) {
		return;
	} else {
		PhoneGap.exec("location", ["stop"]);
	}
};

/**
 * Maps current location
 */
if (typeof navigator.map === "undefined") { navigator.map = {}; }

navigator.map.show = function() {
	if (navigator.geolocation.lastPosition === null) {
		alert("[PhoneGap] No position to map yet.");
		return;
	} else {
		PhoneGap.exec("location", ["map"]);
	}
};


text:
class ChangeColumnPhone < ActiveRecord::Migration
  def change
  	change_column :users, :phone, :string
  end
end


text:
FOUNDATION_EXPORT double MJRefreshVersionNumber;
FOUNDATION_EXPORT const unsigned char MJRefreshVersionString[];


text:
package com.packtpub.rest.ch5.model;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
//import javax.validation.constraints.NotNull;
//import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * The table for this entity does not come with HR schema by default. Here is
 * the script:
 * CREATE TABLE EMPLOYEE_IMAGES ( IMG_ID NUMBER(6, 0) NOT NULL ,
 * EMPLOYEE_ID NUMBER(6, 0) NOT NULL , IMAGE BLOB , DESCRIPTION VARCHAR2(100
 * BYTE) , CONSTRAINT EMPLOYEE_IMAGES_PK PRIMARY KEY ( IMG_ID ) ENABLE );
 *
 * @author Jobinesh
 */
@Entity
@Table(name = "EMPLOYEE_IMAGES")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "EmployeeImage.findAll", query = "SELECT e FROM EmployeeImage e"),
    @NamedQuery(name = "EmployeeImage.findByImgId", query = "SELECT e FROM EmployeeImage e WHERE e.imgId = :imgId"),
    @NamedQuery(name = "EmployeeImage.findByEmployeeId", query = "SELECT e FROM EmployeeImage e WHERE e.employeeId = :employeeId"),
    @NamedQuery(name = "EmployeeImage.findByDescription", query = "SELECT e FROM EmployeeImage e WHERE e.description = :description")})
public class EmployeeImage implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    // @NotNull
    @GeneratedValue
    @Column(name = "IMG_ID")
    private Integer imgId;
    @Basic(optional = false)
    //@NotNull
    @Column(name = "EMPLOYEE_ID")
    private int employeeId;
    @Lob
    @Column(name = "IMAGE")
    private byte[] image;

    //@Size(max = 100)
    @Column(name = "DESCRIPTION")
    private String description;

    public EmployeeImage() {
    }

    public EmployeeImage(Integer imgId) {
        this.imgId = imgId;
    }

    public EmployeeImage(Integer imgId, int employeeId) {
        this.imgId = imgId;
        this.employeeId = employeeId;
    }

    public Integer getImgId() {
        return imgId;
    }

    public void setImgId(Integer imgId) {
        this.imgId = imgId;
    }

    public int getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }

    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (imgId != null ? imgId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof EmployeeImage)) {
            return false;
        }
        EmployeeImage other = (EmployeeImage) object;
        if ((this.imgId == null && other.imgId != null) || (this.imgId != null && !this.imgId.equals(other.imgId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.packtpub.rest.ch5.model.EmployeeImage[ imgId=" + imgId + " ]";
    }

}


text:
package examples;

import br.com.etyllica.EtyllicaFrame;
import br.com.etyllica.core.context.Application;
import examples.application.ExporterApplication;

public class GUIExporter extends EtyllicaFrame {

	private static final long serialVersionUID = 1L;

	public GUIExporter() {
		super(450, 180);
	}

	public static void main(String[] args) {
		GUIExporter exporter = new GUIExporter();
		exporter.setTitle("Crunchbase Exporter");
		exporter.init();
	}

	@Override
	public Application startApplication() {
		initialSetup("../");

		return new ExporterApplication(w,h);
	}

}


text:
require 'spec_helper'

describe Color do
  it 'has a version number' do
    expect(Color::VERSION).not_to be nil
  end

  it 'should be \e[31mtest\e[37m' do
    expect(Color.red("test") == "\e[31mtest\e[37m").not_to be false
  end
end


text:
package net.finmath.montecarlo.interestrate.products;

import net.finmath.exception.CalculationException;
import net.finmath.montecarlo.RandomVariableFromDoubleArray;
import net.finmath.montecarlo.interestrate.TermStructureMonteCarloSimulationModel;
import net.finmath.stochastic.RandomVariable;

/**
 * Implements the valuation of a money market account. The money market account
 * is characterized by its inception time t0 and its accrual period
 * Δ t.

 *
 * With ti := t0 + i Δ t
 * the money market account value N(t0) = 1 and
 * N(t) = N(ti) (1 + L(ti,ti+1;ti) (t - ti)).
 * for ti < t < ti+1.

 *
 * The value of the account at inception is 1.0. The value of the account prior to inception is zero.
 *
 * @author Christian Fries
 * @version 1.0
 */
public class MoneyMarketAccount extends AbstractTermStructureMonteCarloProduct {

	private double inceptionTime	= 0.0;
	private double initialValue		= 1.0;
	private double accrualPeriod	= -1.0;		// Accrual period, if this period is < 0, then the finest model LIBOR period discretization is used

	/**
	 * Create a money market account.
	 *
	 * @param inceptionTime The inception time. The value of the account at inception is 1.0. The value of the account prior to inception is zero.
	 * @param initialValue The initial value, i.e., the value at inception time.
	 * @param accrualPeriod The accrual period. If this period is < 0, then the finest model LIBOR period discretization is used
	 */
	public MoneyMarketAccount(final double inceptionTime, final double initialValue, final double accrualPeriod) {
		super();
		this.inceptionTime	= inceptionTime;
		this.initialValue	= initialValue;
		this.accrualPeriod	= accrualPeriod;
	}

	/**
	 * Create a money market account.
	 *
	 * @param inceptionTime The inception time. The value of the account at inception is 1.0. The value of the account prior to inception is zero.
	 * @param accrualPeriod The accrual period. If this period is < 0, then the finest model LIBOR period discretization is used
	 */
	public MoneyMarketAccount(final double inceptionTime, final double accrualPeriod) {
		this(inceptionTime, 1.0, accrualPeriod);
	}

	/**
	 * Create a default money market account. The money market account will use the
	 * models tenor discretization as the accrual period and its inception time is 0.
	 */
	public MoneyMarketAccount() {
		this(0.0, 1.0, -1.0);
	}

	/* (non-Javadoc)
	 * @see net.finmath.montecarlo.interestrate.products.AbstractLIBORMonteCarloProduct#getValue(double, net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationModel)
	 */
	@Override
	public RandomVariable getValue(final double evaluationTime, final TermStructureMonteCarloSimulationModel model) throws CalculationException {

		if(inceptionTime > evaluationTime) {
			return new RandomVariableFromDoubleArray(0.0);
		}
		if(accrualPeriod <= 0) {
			return new RandomVariableFromDoubleArray(Double.MAX_VALUE);
		}

		// Initialize the value of the account to 1.0
		RandomVariable value = new RandomVariableFromDoubleArray(initialValue);

		// Loop over accrual periods
		for(double time=inceptionTime; time<evaluationTime; time += accrualPeriod) {
			// Get the forward fixed at the beginning of the period
			final RandomVariable	forwardRate				= model.getForwardRate(time, time, time+accrualPeriod);
			final double					currentAccrualPeriod	= Math.min(accrualPeriod , evaluationTime-time);

			// Accrue the value using the current forward rate
			value = value.accrue(forwardRate, currentAccrualPeriod);
		}

		return value;
	}
}


text:
import MySQLdb

from airflow.hooks.dbapi_hook import DbApiHook

class MySqlHook(DbApiHook):
    '''
    Interact with MySQL.
    '''

    conn_name_attr = 'mysql_conn_id'
    default_conn_name = 'mysql_default'
    supports_autocommit = True

    def get_conn(self):
        """
        Returns a mysql connection object
        """
        conn = self.get_connection(self.mysql_conn_id)
        if not conn.port:
            port = 3306
        else:
            port = int(conn.port)
        conn = MySQLdb.connect(
            host=conn.host,
            port=port,
            user=conn.login,
            passwd=conn.password,
            db=conn.schema)
        return conn


text:
package transformationGenerator.mutation.operators;

import java.util.List;

import org.eclipse.epsilon.eol.models.IModel;

import transformationGenerator.mutation.Mutation.ChainedMofProperty;
import transformationGenerator.mutation.MutationOption;
import transformationGenerator.mutation.interfaces.IMutationOperator;
import transformationGenerator.mutation.interfaces.IMutationOption;
import etlMetaModel.EtlTransformationRule;

public class AddRuleOneToManyOfSameKindMutationOption extends MutationOption {
	private etlMetaModel.MofClass selectedMofClassSource;
	private etlMetaModel.MofClass selectedMofClassTarget;
	private ChainedMofProperty selectedMofClassSourceCollectionProperty;
	private List<ChainedMofProperty> selectedMofClassSourceCollectionPropertyChain;
	private EtlTransformationRule existingTransformationRule;

	AddRuleOneToManyOfSameKindMutationOption(IMutationOperator mutationOperator, IModel model, etlMetaModel.EtlModule etlModule, etlMetaModel.MofClass selectedMofClassSource, etlMetaModel.MofClass selectedMofClassTarget,
			ChainedMofProperty selectedMofClassSourceCollectionProperty, List<ChainedMofProperty> selectedMofClassSourceCollectionPropertyChain, EtlTransformationRule existingTransformationRule) {
		super(mutationOperator, model, etlModule);
		this.selectedMofClassSource = selectedMofClassSource;
		this.selectedMofClassTarget = selectedMofClassTarget;
		this.selectedMofClassSourceCollectionProperty = selectedMofClassSourceCollectionProperty;
		this.selectedMofClassSourceCollectionPropertyChain = selectedMofClassSourceCollectionPropertyChain;
		this.existingTransformationRule = existingTransformationRule;
	}

	public etlMetaModel.MofClass getSelectedMofClassSource() {
		return selectedMofClassSource;
	}

	public etlMetaModel.MofClass getSelectedMofClassTarget() {
		return selectedMofClassTarget;
	}

	public ChainedMofProperty getSelectedMofClassSourceCollectionProperty() {
		return selectedMofClassSourceCollectionProperty;
	}

	public List<ChainedMofProperty> getSelectedMofClassSourceCollectionPropertyChain() {
		return selectedMofClassSourceCollectionPropertyChain;
	}

	public EtlTransformationRule getExistingTransformationRule() {
		return existingTransformationRule;
	}

	@Override
	public String toString() {
		return String.format("Source=%s,Target=%s,CollectionProperty=%s,CollectionPropertyChain=%s", this.getSelectedMofClassSource().getName(), this.getSelectedMofClassTarget().getName(), this.getSelectedMofClassSourceCollectionProperty().toSelfString(),
				getSelectedMofClassSourceCollectionPropertyChain().stream().map(c -> c.getMofProperty() != null ? c.getMofProperty().getName() : "root").reduce("", (c1, c2) -> c1 + "." + c2));
	}

	@Override
	public Boolean isOptionEquivalentTo(IMutationOption mutationOption) {
		if (mutationOption == null) {
			return false;
		}
		if (mutationOption.getClass() != this.getClass()) {
			return false;
		}

		AddRuleOneToManyOfSameKindMutationOption otherAddRuleOneToManyOfSameKindMutationOption = (AddRuleOneToManyOfSameKindMutationOption) mutationOption;
		if (areMofClassesEqual(selectedMofClassSource, otherAddRuleOneToManyOfSameKindMutationOption.getSelectedMofClassSource()) &&
				areMofClassesEqual(selectedMofClassTarget, otherAddRuleOneToManyOfSameKindMutationOption.getSelectedMofClassTarget()) &&
				areChainedMofPropertiesEqual(selectedMofClassSourceCollectionProperty, otherAddRuleOneToManyOfSameKindMutationOption.getSelectedMofClassSourceCollectionProperty()) &&
				areChainedMofPropertyListsEqual(selectedMofClassSourceCollectionPropertyChain, otherAddRuleOneToManyOfSameKindMutationOption.getSelectedMofClassSourceCollectionPropertyChain()) &&
				areEtlTransformationRulesEqual(existingTransformationRule, otherAddRuleOneToManyOfSameKindMutationOption.getExistingTransformationRule())) {
			return true;
		} else {
			return false;
		}
	}
}


text:
using System.Web;
using System.Web.Optimization;

namespace BerichtDokuManagement
{
    public class BundleConfig
    {
        // Weitere Informationen zu Bundling finden Sie unter "http://go.microsoft.com/fwlink/?LinkId=254725".
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.unobtrusive*",
                        "~/Scripts/jquery.validate*"));

            // Verwenden Sie die Entwicklungsversion von Modernizr zum Entwickeln und Erweitern Ihrer Kenntnisse. Wenn Sie dann
            // für die Produktion bereit sind, verwenden Sie das Buildtool unter "http://modernizr.com", um nur die benötigten Tests auszuwählen.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

            bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                        "~/Content/themes/base/jquery.ui.core.css",
                        "~/Content/themes/base/jquery.ui.resizable.css",
                        "~/Content/themes/base/jquery.ui.selectable.css",
                        "~/Content/themes/base/jquery.ui.accordion.css",
                        "~/Content/themes/base/jquery.ui.autocomplete.css",
                        "~/Content/themes/base/jquery.ui.button.css",
                        "~/Content/themes/base/jquery.ui.dialog.css",
                        "~/Content/themes/base/jquery.ui.slider.css",
                        "~/Content/themes/base/jquery.ui.tabs.css",
                        "~/Content/themes/base/jquery.ui.datepicker.css",
                        "~/Content/themes/base/jquery.ui.progressbar.css",
                        "~/Content/themes/base/jquery.ui.theme.css"));
        }
    }
}


text:
<?php
namespace LazyRecord\Schema\Comparator;
use Closure;
use CLIFramework\Formatter;

class ConsolePrinter
{
    public $diff = array();

    public $beforeName = 'old';

    public $afterName = 'new';

    public function __construct(array $diff)
    {
        $this->diff = $diff;
    }

    public function output()
    {
        if ( empty($this->diff) ) {
            return;
        }
        $formatter = new Formatter;

        echo $formatter->format('--- ' . $this->beforeName,"strong_white") , "\n";
        echo $formatter->format('+++ ' . $this->afterName, "strong_white") , "\n";
        echo "@@ columns @@\n";

        foreach ($this->diff as $d) {
            // for each diff items, show attribute diff
            switch ($d->flag) {
                case 'M':
                    echo $formatter->format('M ' . $d->name, 'yellow') , "\n";
                    foreach ($d->details as $attrDiff) {
                        echo "\t" . $formatter->format($attrDiff->getBeforeDescription(), 'red');
                        echo "\t" . $formatter->format($attrDiff->getAfterDescription(), 'green');
                    }
                    break;
                case 'A':
                    $line = $d->toColumnAttrsString();
                    echo $formatter->format($line . "\n", 'green');
                    break;
                case 'D':
                    $line = $d->toColumnAttrsString();
                    echo $formatter->format($line . "\n", 'red');
                    break;
            }
        }
    }
}


text:
var dialogsModule = require("ui/dialogs");
var Observable = require("data/observable").Observable;
var ObservableArray = require("data/observable-array").ObservableArray;
var listPickerModule = require("ui/list-picker");

var page;

var pageData = new Observable({
    activityList: new ObservableArray([
        { activity: "Groceries" }
    ])
});

exports.loaded = function(args) {
    page = args.object;

};


text:
#region License

#endregion

using NUnit.Framework;

using Quartz.Impl.Calendar;

namespace Quartz.Tests.Unit.Impl.Calendar
{
    /// <author>Marko Lahma (.NET)</author>
    [TestFixture]
    public class BaseCalendarTest
    {
        [Test]
        public void TestClone() {
            BaseCalendar baseCalendar = new BaseCalendar();
            baseCalendar.Description = "My description";
            baseCalendar.TimeZone = TimeZoneInfo.GetSystemTimeZones()[3];
            BaseCalendar clone = (BaseCalendar) baseCalendar.Clone();

            Assert.AreEqual(baseCalendar.Description, clone.Description);
            Assert.AreEqual(baseCalendar.CalendarBase, clone.CalendarBase);
            Assert.AreEqual(baseCalendar.TimeZone, clone.TimeZone);
        }

    }
}


text:
<?php

class Add extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->library('form_validation');
		$this->load->model('item_model');
		$this->load->model('extra_charge_model');
	}

	public function index()
	{
		$config = array( array(
				'field' => 'name',
				'label' => 'Name',
				'rules' => 'required|max_length[25]|xss_clean'
			), array(
				'field' => 'room',
				'label' => 'Room Number',
				'rules' => 'required|xss_clean'
			), array(
				'field' => 'phone',
				'label' => 'Phone Number',
				'rules' => 'required|integer|max_length[11]|xss_clean'
			), array(
				'field' => 'time',
				'label' => 'Time',
				'rules' => 'required|integer|xss_clean'
			), array(
				'field' => 'full_charge',
				'label' => 'Extra charge - Full',
				'rules' => 'required|integer|xss_clean'
			), array(
				'field' => 'half_charge',
				'label' => 'Extra charge - Half',
				'rules' => 'required|integer|xss_clean'
			), array(
				'field' => 'chapati_charge',
				'label' => 'Extra charge - Chapati',
				'rules' => 'required|integer|xss_clean'
			)
		);

		$this->form_validation->set_rules($config);

		if($this->form_validation->run() == FALSE)
		{
			$this->load->view('add_item');
		}
		else
		{
			$name = $this->input->post('name');
			$room = $this->input->post('room');
			$hostel = $this->input->post('hostel');
			$phone = $this->input->post('phone');
			$time = $this->input->post('time');
			$full = $this->input->post('full_charge');
			$half = $this->input->post('half_charge');
			$chapati = $this->input->post('chapati_charge');
			$comment = $this->input->post('comments');
			$ip = $this->input->ip_address();

			$exactTime = time() + (60 * 60 * $time);

			$dataItem = array('name' => $name, 'room_no' => $room,
								'hostel' => $hostel, 'phone' => $phone,
								'time' => $exactTime, 'comments' => $comment, 'ip' => $ip);

			$this->item_model->add($dataItem);
			$id = $this->db->insert_id();

			$dataExtraCharge = array('item_id' => $id, 'full_charge' => $full,
									'half_charge' => $half, 'chapati_charge' => $chapati);

			$this->extra_charge_model->add($dataExtraCharge);
			redirect(site_url('view'), 'refresh');
		}
	}
}

?>


text:
<?php
// *** Tangra (Application Framework and Tools for PHP)
// $Id$
//

/**
 * Contains class Ajax_Ctrl
 * @package modules
 * @subpackage ajax_module
 */

/**
 *
 */
require_once(TANGRA_MAIN_DIR.'web_site/web_ctrl.class.php');

/**
 *
 */
require_once(TANGRA_MAIN_DIR.'web_site/tple_exports.class.php');
/**
 *
 */
require_once(TANGRA_MAIN_DIR.'exceptions/tangra_module_exception.class.php');
/**
 *
 */
require_once(DIR_INC.'modules/tple_html_gatherer/tple_html_gatherer.class.php');
/**
 *
 */
require_once(DIR_INC.'modules/json_encdec_common/json_encdec.class.php');

/**
 * Base class for all ajax controllers
 *
 */
abstract class Ajax_Ctrl extends Web_Ctrl {
	/**
	 * Status code for error
	 *
	 */
	const STATUS_ERROR = 0;

	/**
	 * Status code if everything is ok
	 *
	 */
	const STATUS_OK = 1;

	/**
	 * Command that instructs calling javascript to show the result
	 *
	 */
	const COMMAND_SHOW = 'show';

	/**
	 * Command that instructs calling javascript to perform window.location (redirect)
	 *
	 */
	const COMMAND_REDIRECT = 'redirect';

	/**
	 * path to template file
	 *
	 * @var string
	 * @internal
	 */
	private $tpl_file;

	/**
	 * Holds array for additional response parameters that can be sent back to callic javascript
	 *
	 * @var array
	 * @internal
	 */
	private $additional_response_parameters  = array();

	/**
	 * Constructor
	 *
	 * @param string $tpl_file Path to template file
	 */
	function __construct($tpl_file = '') {
		$this->tpl_file = $tpl_file;
		parent::__construct();
	}

	/**
	 * Method that will be called by the site instance to run the controller
	 *
	 * Not intended to be used directly by user except in vary rare circumstances.
	 *
	 * @internal
	 */
	public function _run() {
		$this->set_transit_vars_as_output_rewrite_vars();
		$_transit_vars_prepared = $this->prepare_transit_vars();
		$this->export('_transit_vars', $_transit_vars_prepared, true);

		$this->run();
	}

	/**
	 * Sets tpl_file
	 *
	 * @param string $tpl_file Path to tplfile
	 */
	protected function set_tpl_file($tpl_file) {
		$this->tpl_file = $tpl_file;
	}

	/**
	 * Returns path to template file
	 *
	 * @return string
	 */
	public function get_tpl_file() {
		return $this->tpl_file;
	}

	/**
	 * Sends back response to the calling javascript
	 *
	 * @param array $json Array of $key => $value pairs that will be send back as JSON header
	 * @param string $html Generated HTML. Default is '' in case of redirect for example.
	 */
	protected function send_response($json, $html = ' ') {

		foreach($this->additional_response_parameters as $key => $value) {
			$json[$key] = $value;
		}

		$json_enc = JSON_EncDec::encode($json);

		global $WSC;
		header('Content-Type: text/html; charset='.$WSC->get_default_encoding());
		header('Cache-control: no-cache');
		header('X-JSON: '.$json_enc);
		print($html);
		flush();
	}

	/**
	 * Adds additional response parameter
	 *
	 * @param string $var_name
	 * @param mixed $value
	 */
	public function add_additional_response_parameter($var_name, $value) {
		if (!array_key_exists($var_name, $this->additional_response_parameters)) {
			$this->additional_response_parameters[$var_name] = $value;
		} else {
			throw new Tangra_Module_Exception('Parameter already added: '.$var_name);
		}
	}

	/**
	 * Alias of add_additional_response_parameter()
	 *
	 * @param string $var_name
	 * @param mixed $value
	 */
	public function add_arp($var_name, $value) {
		$this->add_additional_response_parameter($var_name, $value);
	}

	/**
	 * Adds multiple additional response parameters.
	 *
	 * @param array $additional_json_params Array must be simple $key => $value pairs
	 */
	public function add_additional_response_parameters($additional_response_parameters) {
		if (is_array($additional_response_parameters)) {
			foreach($additional_response_parameters as $key => $value) {
				$this->add_additional_response_parameter($key, $value);
			}
		}
	}

	/**
	 * Returns additional response parameters
	 *
	 * @return array
	 */
	protected function get_additional_response_parameters() {
		return $this->additional_response_parameters;
	}

	/**
	 * Alias of get_additional_response_parameters
	 *
	 * @return array
	 */
	protected function get_arp() {
		return $this->get_additional_response_parameters();
	}

	/**
	 * Parses the template file and returns generated HTML
	 *
	 * @return string
	 */
	protected function get_html() {
		if ($this->get_tpl_file()) {
			$html_gatherer = new Tple_HTML_Gatherer($this->get_tpl_file());

			$ret = $html_gatherer->get_html($this->get__exports());
			$ret = $this->rewrite_html_with_transit_vars($ret);
		} else {
			$ret = '';
		}

		return $ret;
	}

	protected function rewrite_html_with_transit_vars($html) {
		if ($this->get_transit_vars()) {
			ob_start();
			$this->set_transit_vars_as_output_rewrite_vars();
			print($html);
			$ret = ob_get_contents();
			ob_end_clean();
		} else {
			$ret = $html;
		}

		return $ret;
	}
}


text:
# Contributing

Contributions to Respect\Validation are always welcome. You make our lives
easier by sending us your contributions through
[GitHub pull requests](http://help.github.com/pull-requests).

Pull requests for bug fixes must be based on the current stable branch whereas
pull requests for new features must be based on `master`.

Due to time constraints, we are not always able to respond as quickly as we
would like. Please do not take delays personal and feel free to remind us here,
on IRC, or on Gitter if you feel that we forgot to respond.

Please see the [project documentation](http://respect.github.io/Validation)
before proceeding. You should also know about [PHP-FIG](http://www.php-fig.org)'s
standards and basic unit testing, but we're sure you can learn that just by
looking at other rules. Pick the simple ones like `IntVal` to begin.

Before writing anything, make sure there is no validator that already does what
you need. Also, it would be awesome if you
[open an issue](http://github.com/Respect/Validation/issues) before starting,
so if anyone has the same idea the guy will see that you're already doing that.

## Adding a new validator

A common validator (rule) on Respect\Validation is composed of three classes:

  * `library/Rules/YourRuleName.php`: the rule itself
  * `library/Exceptions/YourRuleNameException.php`: the exception thrown by the rule
  * `tests/Rules/YourRuleNameTest.php`: tests for the rule

Classes are pretty straightforward. In the sample below, we're going to create a
validator that validates if a string is equal "Hello World".

## Samples

The rule itself needs to implement the `Validatable` interface.
Also, it is convenient to extend the `AbstractRule`.
Doing that, you'll only need to declare one method: `validate($input)`.
This method must return `true` or `false`.

If your validator class is `HelloWorld`, it will be available as `v::helloWorld()`
and will natively have support for chaining and everything else.

```php
namespace Respect\Validation\Rules;

class HelloWorld extends AbstractRule
{
    public function validate($input)
    {
        return $input === 'Hello World';
    }
}
```

Just that and we're done with the rule code. The Exception requires you to
declare messages used by `assert()` and `check()`. Messages are declared in
affirmative and negative moods, so if anyone calls `v::not(v::helloWorld())` the
library will show the appropriate message.

```php
namespace Respect\Validation\Exceptions;

class HelloWorldException extends ValidationException
{
    public static $defaultTemplates = array(
        self::MODE_DEFAULT => array(
            self::STANDARD => '{{name}} must be a Hello World',
        ),
        self::MODE_NEGATIVE => array(
            self::STANDARD => '{{name}} must not be a Hello World',
        )
    );
}
```

Finally, we need to test if everything is running smooth:

```php
namespace Respect\Validation\Rules;

class HelloWorldTest extends \PHPUnit_Framework_TestCase
{
    public function testShouldValidateAValidHelloWorld()
    {
        $rule = new HelloWorld();

        $this->assertTrue($rule->validate('Hello World'));
    }

    public function testNotValidateAnInvalidHelloWorld()
    {
        $rule = new HelloWorld();

        $this->assertFalse($rule->validate('Hello Moon'));
    }

    /**
     * @expectedException Respect\Validation\Exceptions\HelloWorldException
     * @expectedExceptionMessage "Hello Mars" must be a Hello World
     */
    public function testShouldThowsTheRightExceptionWhenChecking()
    {
        $rule = new HelloWorld();

        $rule->check('Hello Mars');
    }
}
```

PS.: We strongly recommend you use [Data Providers](https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers).

## Documentation

Our docs at http://respect.github.io/Validation are generated from our Markdown
files using [Couscous](http://couscous.io/). Add your brand new rule there and
everything will be updated as soon as possible.

## Running Tests

After run `composer install` on the library's root directory you must run PHPUnit.

### Linux

You can test the project using the commands:
```sh
$ vendor/bin/phpunit
```

### Windows

You can test the project using the commands:
```sh
> vendor\bin\phpunit
```

No test should fail.

You can tweak the PHPUnit's settings by copying `phpunit.xml.dist` to `phpunit.xml`
and changing it according to your needs.

## Coding style and standards

We follow the [PSR-2](http://www.php-fig.org/psr/psr-2/) coding style and
[PSR-4](http://www.php-fig.org/psr/psr-4/) autoloading standard.

There are some preferences regarding code style which you can easily adhere to
by using [php-cs-fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer).

This will format all PHP files consistently using the preferences of this
project.

```sh
$ vendor/bin/php-cs-fixer fix
```

***
See also:

- [Feature Guide](docs/README.md)
- [Installation](docs/INSTALL.md)
- [License](LICENSE.md)
- [Validators](docs/VALIDATORS.md)
- [Changelog](CHANGELOG.md)


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.
-->
<!--
  This is an example components.xml that refers to the main components.xml.
-->
<components.xml>
    <system-integrity-checker class="com.cloud.upgrade.DatabaseUpgradeChecker">
        <checker name="ManagementServerNode" class="com.cloud.cluster.ManagementServerNode"/>
        <checker name="EncryptionSecretKeyChecker" class="com.cloud.utils.crypt.EncryptionSecretKeyChecker"/>
        <checker name="DatabaseIntegrityChecker" class="com.cloud.upgrade.DatabaseIntegrityChecker"/>
        <checker name="DatabaseUpgradeChecker" class="com.cloud.upgrade.PremiumDatabaseUpgradeChecker"/>
    </system-integrity-checker>

    <interceptor library="com.cloud.configuration.DefaultInterceptorLibrary"/>
    <management-server class="com.cloud.server.ManagementServerImpl" library="com.cloud.configuration.PremiumComponentLibrary">
        <dao name="Configuration configuration server" class="com.cloud.configuration.dao.ConfigurationDaoImpl">
             <param name="premium">true</param>
        </dao>
        <adapters key="com.cloud.agent.manager.allocator.HostAllocator">
            <adapter name="FirstFitRouting" class="com.cloud.agent.manager.allocator.impl.FirstFitRoutingAllocator"/>
            <!--adapter name="FirstFitRouting" class="com.cloud.agent.manager.allocator.impl.RecreateHostAllocator"/-->
            <!--adapter name="FirstFit" class="com.cloud.agent.manager.allocator.impl.FirstFitAllocator"/-->
        </adapters>
        <adapters key="com.cloud.storage.allocator.StoragePoolAllocator">
            <adapter name="LocalStorage" class="com.cloud.storage.allocator.LocalStoragePoolAllocator"/>
            <adapter name="Storage" class="com.cloud.storage.allocator.FirstFitStoragePoolAllocator"/>
        </adapters>
        <adapters key="com.cloud.agent.manager.allocator.PodAllocator">
            <adapter name="User First" class="com.cloud.agent.manager.allocator.impl.UserConcentratedAllocator"/>
        </adapters>
        <adapters key="com.cloud.consoleproxy.ConsoleProxyAllocator">
            <adapter name="Balance" class="com.cloud.consoleproxy.ConsoleProxyBalanceAllocator"/>
        </adapters>
        <adapters key="com.cloud.network.guru.NetworkGuru">
            <!--
                 NOTE: The order of those gurus implicates priority of network traffic types the guru implements.
                 The upper the higher priority. It effects listTafficTypeImplementors API which returns impelmentor
                 of a specific network traffic.
                 A fair question is, if two gurus implement the same two network traffic types, but these traffic types
                 have cross priority, how to rank them? For example:
                    GuruA (TrafficTypeA, TrafficTypeB)
                    GuruB (TrafficTypeA, TrafficTypeB)
                 we want GuruB.TrafficTypeB > GuruA.TrafficTypeB and GuruB.TrafficTypeA < GuruA.TrafficTypeA. As the priority
                 implicated by order can not map to multiple traffic type, you have to do implement GuruC which inherits GuruB
                 for TrafficTypeB. Then ranking them in order of:
                    GuruC (TrafficTypeB)
                    GuruA (TrafficTypeA, TrafficTypeB)
                    GuruB (TrafficTypeA, TrafficTypeB)
                 now GuruC represents TrafficTypeB with highest priority while GuruA represents TrafficTypeA with highest pirority.

                 However, above case barely happens.
            -->

            <adapter name="StorageNetworkGuru" class="com.cloud.network.guru.StorageNetworkGuru"/>
            <adapter name="ExternalGuestNetworkGuru" class="com.cloud.network.guru.ExternalGuestNetworkGuru"/>
            <adapter name="PublicNetworkGuru" class="com.cloud.network.guru.PublicNetworkGuru"/>
            <adapter name="PodBasedNetworkGuru" class="com.cloud.network.guru.PodBasedNetworkGuru"/>
            <adapter name="ControlNetworkGuru" class="com.cloud.network.guru.ControlNetworkGuru"/>
            <adapter name="DirectNetworkGuru" class="com.cloud.network.guru.DirectNetworkGuru"/>
            <adapter name="DirectPodBasedNetworkGuru" class="com.cloud.network.guru.DirectPodBasedNetworkGuru"/>
            <adapter name="OvsGuestNetworkGuru" class="com.cloud.network.guru.OvsGuestNetworkGuru"/>
            <adapter name="PrivateNetworkGuru" class="com.cloud.network.guru.PrivateNetworkGuru"/>
            <adapter name="NiciraNvpGuestNetworkGuru" class="com.cloud.network.guru.NiciraNvpGuestNetworkGuru"/>
        </adapters>
        <adapters key="com.cloud.cluster.ClusterServiceAdapter">
            <adapter name="ClusterService" class="com.cloud.cluster.ClusterServiceServletAdapter"/>
        </adapters>
        <adapters key="com.cloud.storage.secondary.SecondaryStorageVmAllocator">
            <adapter name="Balance" class="com.cloud.storage.secondary.SecondaryStorageVmDefaultAllocator"/>
        </adapters>
        <adapters key="com.cloud.network.IpAddrAllocator">
            <adapter name="Basic" class="com.cloud.network.ExternalIpAddressAllocator"/>
        </adapters>
        <adapters key="com.cloud.server.auth.UserAuthenticator">
            <!-- <adapter name="SHA256SALT" class="com.cloud.server.auth.SHA256SaltedUserAuthenticator"/> -->
            <adapter name="MD5" class="com.cloud.server.auth.MD5UserAuthenticator"/>
            <adapter name="LDAP" class="com.cloud.server.auth.LDAPUserAuthenticator"/>
        </adapters>
        <adapters key="com.cloud.ha.Investigator">
            <adapter name="SimpleInvestigator" class="com.cloud.ha.CheckOnAgentInvestigator"/>
            <adapter name="XenServerInvestigator" class="com.cloud.ha.XenServerInvestigator"/>
            <adapter name="PingInvestigator" class="com.cloud.ha.UserVmDomRInvestigator"/>
			<adapter name="ManagementIPSysVMInvestigator" class="com.cloud.ha.ManagementIPSystemVMInvestigator"/>
        </adapters>
        <adapters key="com.cloud.ha.FenceBuilder">
            <adapter name="XenServerFenceBuilder" class="com.cloud.ha.XenServerFencer"/>
            <adapter name="KVMFenceBuilder" class="com.cloud.ha.KVMFencer"/>
            <adapter name="OvmFenceBuilder" class="com.cloud.ovm.hypervisor.OvmFencer"/>
        </adapters>
        <adapters key="com.cloud.hypervisor.HypervisorGuru">
            <adapter name="XenServerGuru" class="com.cloud.hypervisor.XenServerGuru"/>
            <adapter name="KVMGuru" class="com.cloud.hypervisor.KVMGuru"/>
        </adapters>
        <adapters key="com.cloud.resource.Discoverer">
            <adapter name="XCP Agent" class="com.cloud.hypervisor.xen.discoverer.XcpServerDiscoverer"/>
            <adapter name="SecondaryStorage" class="com.cloud.storage.secondary.SecondaryStorageDiscoverer"/>
            <adapter name="KVM Agent" class="com.cloud.hypervisor.kvm.discoverer.KvmServerDiscoverer"/>
            <adapter name="Bare Metal Agent" class="com.cloud.baremetal.BareMetalDiscoverer"/>
			<adapter name="Ovm Discover" class="com.cloud.ovm.hypervisor.OvmDiscoverer" />
        </adapters>
        <adapters key="com.cloud.deploy.DeploymentPlanner">
            <adapter name="First Fit" class="com.cloud.deploy.FirstFitPlanner"/>
            <adapter name="UserDispersing" class="com.cloud.deploy.UserDispersingPlanner"/>
            <adapter name="UserConcentratedPod" class="com.cloud.deploy.UserConcentratedPodPlanner"/>
            <adapter name="BareMetal Fit" class="com.cloud.deploy.BareMetalPlanner"/>
        </adapters>
        <adapters key="com.cloud.alert.AlertAdapter">
            <adapter name="ClusterAlert" class="com.cloud.alert.ClusterAlertAdapter"/>
            <adapter name="ConsoleProxyAlert" class="com.cloud.alert.ConsoleProxyAlertAdapter"/>
            <adapter name="SecondaryStorageVmAlert" class="com.cloud.alert.SecondaryStorageVmAlertAdapter"/>
        </adapters>
        <adapters key="org.apache.cloudstack.acl.SecurityChecker">
            <adapter name="DomainChecker" class="com.cloud.acl.DomainChecker"/>
        </adapters>
        <adapters key="com.cloud.network.element.NetworkElement">
            <adapter name="VirtualRouter" class="com.cloud.network.element.VirtualRouterElement"/>
            <adapter name="Ovs" class="com.cloud.network.element.OvsElement"/>
            <adapter name="ExternalDhcpServer" class="com.cloud.network.element.ExternalDhcpElement"/>
            <adapter name="BareMetal" class="com.cloud.network.element.BareMetalElement"/>
            <adapter name="SecurityGroupProvider" class="com.cloud.network.element.SecurityGroupElement"/>
            <adapter name="VpcVirtualRouter" class="com.cloud.network.element.VpcVirtualRouterElement"/>
            <adapter name="NiciraNvp" class="com.cloud.network.element.NiciraNvpElement"/>
            <adapter name="DnsNotifier" class="org.apache.cloudstack.network.element.DnsNotifier"/>
        </adapters>
        <adapters key="com.cloud.cluster.agentlb.AgentLoadBalancerPlanner">
            <adapter name="ClusterBasedAgentLbPlanner" class="com.cloud.cluster.agentlb.ClusterBasedAgentLoadBalancerPlanner"/>
        </adapters>
        <adapters key="com.cloud.hypervisor.HypervisorGuru">
            <adapter name="XenServerGuru" class="com.cloud.hypervisor.XenServerGuru"/>
            <adapter name="KVMGuru" class="com.cloud.hypervisor.KVMGuru"/>
            <adapter name="BareMetalGuru" class="com.cloud.baremetal.BareMetalGuru"/>
            <adapter name="OvmGuru" class="com.cloud.ovm.hypervisor.OvmGuru" />
        </adapters>
        <adapters key="com.cloud.agent.StartupCommandProcessor">
            <adapter name="BasicAgentAuthorizer" class="com.cloud.agent.manager.authn.impl.BasicAgentAuthManager"/>
        </adapters>
        <manager name="OvsTunnelManager" key="com.cloud.network.ovs.OvsTunnelManager" class="com.cloud.network.ovs.OvsTunnelManagerImpl"/>
        <manager name="ElasticLoadBalancerManager" key="com.cloud.network.lb.ElasticLoadBalancerManager" class="com.cloud.network.lb.ElasticLoadBalancerManagerImpl"/>
        <manager name="LBHealthCheckManager" key="com.cloud.network.lb.LBHealthCheckManager" class="com.cloud.network.lb.LBHealthCheckManagerImpl"/>
        <pluggableservice name="ApiDiscoveryService" key="org.apache.cloudstack.discovery.ApiDiscoveryService" class="org.apache.cloudstack.discovery.ApiDiscoveryServiceImpl"/>
        <pluggableservice name="VirtualRouterElementService" key="com.cloud.network.element.VirtualRouterElementService" class="com.cloud.network.element.VirtualRouterElement"/>
        <pluggableservice name="NiciraNvpElementService" key="com.cloud.network.element.NiciraNvpElementService" class="com.cloud.network.element.NiciraNvpElement"/>
        <dao name="OvsTunnelInterfaceDao" class="com.cloud.network.ovs.dao.OvsTunnelInterfaceDaoImpl" singleton="false"/>
        <dao name="OvsTunnelAccountDao" class="com.cloud.network.ovs.dao.OvsTunnelNetworkDaoImpl" singleton="false"/>
        <dao name="NiciraNvpDao" class="com.cloud.network.dao.NiciraNvpDaoImpl" singleton="false"/>
        <dao name="NiciraNvpNicMappingDao" class="com.cloud.network.dao.NiciraNvpNicMappingDaoImpl" singleton="false"/>
        <dao name="NiciraNvpRouterMappingDao" class="com.cloud.network.dao.NiciraNvpRouterMappingDaoImpl" singleton="false"/>
        <dao name="ElasticLbVmMapDao" class="com.cloud.network.lb.dao.ElasticLbVmMapDaoImpl" singleton="false"/>
    </management-server>

    <configuration-server class="com.cloud.server.ConfigurationServerImpl">
        <dao name="Configuration configuration server" class="com.cloud.configuration.dao.ConfigurationDaoImpl" singleton="false">
             <param name="premium">true</param>
        </dao>
        <dao name="Snapshot policy defaults" class="com.cloud.storage.dao.SnapshotPolicyDaoImpl" singleton="false"/>
        <dao name="DiskOffering configuration server" class="com.cloud.storage.dao.DiskOfferingDaoImpl" singleton="false"/>
        <dao name="ServiceOffering configuration server" class="com.cloud.service.dao.ServiceOfferingDaoImpl" singleton="false"/>
        <dao name="host zone configuration server" class="com.cloud.dc.dao.DataCenterDaoImpl" singleton="false"/>
        <dao name="host pod configuration server" class="com.cloud.dc.dao.HostPodDaoImpl" singleton="false"/>
        <dao name="DomainDao" class="com.cloud.domain.dao.DomainDaoImpl" singleton="false"/>
        <dao name="NetworkOfferingDao" class="com.cloud.offerings.dao.NetworkOfferingDaoImpl" singleton="false"/>
        <dao name="DataCenterDao" class="com.cloud.dc.dao.DataCenterDaoImpl" singleton="false"/>
        <dao name="NetworkDao" class="com.cloud.network.dao.NetworkDaoImpl" singleton="false"/>
        <dao name="IpAddressDao" class="com.cloud.network.dao.IPAddressDaoImpl" singleton="false"/>
        <dao name="VlanDao" class="com.cloud.dc.dao.VlanDaoImpl" singleton="false"/>
        <dao name="ResouceCountDao" class="com.cloud.configuration.dao.ResourceCountDaoImpl" singleton="false"/>
        <dao name="AccountDao" class="com.cloud.user.dao.AccountDaoImpl" singleton="false"/>
        <dao name="UserDao" class="com.cloud.user.dao.UserDaoImpl" singleton="false"/>
        <dao name="NetworkOfferingServiceDao" class="com.cloud.offerings.dao.NetworkOfferingServiceMapDaoImpl" singleton="false"/>
        <dao name="VirtualRouterProviderDao" class="com.cloud.network.dao.VirtualRouterProviderDaoImpl" singleton="false"/>
        <dao name="IdentityDao" class="com.cloud.uuididentity.dao.IdentityDaoImpl" singleton="false"/>
        <dao name="Site2SiteCustomerGatewayDao" class="com.cloud.network.dao.Site2SiteCustomerGatewayDaoImpl" singleton="false"/>
        <dao name="Site2SiteVpnGatewayDao" class="com.cloud.network.dao.Site2SiteVpnGatewayDaoImpl" singleton="false"/>
        <dao name="Site2SiteVpnConnectionDao" class="com.cloud.network.dao.Site2SiteVpnConnectionDaoImpl" singleton="false"/>
    </configuration-server>

    <awsapi-ec2server class="com.cloud.bridge.service.EC2MainServlet">
        <dao name="CloudStackConfigurationDao" class="com.cloud.bridge.persist.dao.CloudStackConfigurationDaoImpl" singleton="false"/>
        <dao name="UserCredentialsDao" class="com.cloud.bridge.persist.dao.UserCredentialsDaoImpl" singleton="false"/>
        <dao name="CloudStackSvcOfferingDao" class="com.cloud.bridge.persist.dao.CloudStackSvcOfferingDaoImpl" singleton="false"/>
        <dao name="OfferingDao" class="com.cloud.bridge.persist.dao.OfferingDaoImpl" singleton="false"/>
        <dao name="CloudStackAccountDao" class="com.cloud.bridge.persist.dao.CloudStackAccountDaoImpl" singleton="false"/>
    </awsapi-ec2server>

    <awsapi-s3server class="com.cloud.bridge.service.S3RestServlet">
        <dao name="CloudStackConfigurationDao" class="com.cloud.bridge.persist.dao.CloudStackConfigurationDaoImpl" singleton="false"/>
        <dao name="MHostDao" class="com.cloud.bridge.persist.dao.MHostDaoImpl" singleton="false"/>
        <dao name="SHostDao" class="com.cloud.bridge.persist.dao.SHostDaoImpl" singleton="false"/>
        <dao name="UserCredentialsDao" class="com.cloud.bridge.persist.dao.UserCredentialsDaoImpl" singleton="false"/>
        <dao name="BucketPolicyDao" class="com.cloud.bridge.persist.dao.BucketPolicyDaoImpl" singleton="false"/>
        <dao name="MHostMountDao" class="com.cloud.bridge.persist.dao.MHostMountDaoImpl" singleton="false"/>
        <dao name="SAclDao" class="com.cloud.bridge.persist.dao.SAclDaoImpl" singleton="false"/>
        <dao name="SBucketDao" class="com.cloud.bridge.persist.dao.SBucketDaoImpl" singleton="false"/>
        <dao name="SMetaDao" class="com.cloud.bridge.persist.dao.SMetaDaoImpl" singleton="false"/>
        <dao name="SObjectDao" class="com.cloud.bridge.persist.dao.SObjectDaoImpl" singleton="false"/>
        <dao name="SObjectItemDao" class="com.cloud.bridge.persist.dao.SObjectItemDaoImpl" singleton="false"/>
        <dao name="MultiPartPartsDao" class="com.cloud.bridge.persist.dao.MultiPartPartsDaoImpl" singleton="false"/>
        <dao name="MultiPartUploadsDao" class="com.cloud.bridge.persist.dao.MultiPartUploadsDaoImpl" singleton="false"/>
        <dao name="MultipartMetaDao" class="com.cloud.bridge.persist.dao.MultipartMetaDaoImpl" singleton="false"/>
        <dao name="UserCredentialsDao" class="com.cloud.bridge.persist.dao.UserCredentialsDaoImpl" singleton="false"/>
    </awsapi-s3server>

</components.xml>


text:
<!doctype html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
		<link rel="stylesheet" href="https://code.getmdl.io/1.2.1/material.blue_grey-red.min.css">
		<title>SF Movies</title>


text:
'use strict'

const tap = require('tap')

const silentConsole = {
  log() {},

  error() {}
}
const common = require('../common')

const { Readable } = require('../../lib/ours/index')

{
  const r = new Readable({
    read() {}
  })
  r.on('end', common.mustNotCall())
  r.on('data', common.mustCall())
  r.on('error', common.mustCall())
  r.push('asd')
  r.push(null)
  r.destroy(new Error('kaboom'))
}
/* replacement start */

process.on('beforeExit', (code) => {
  if (code === 0) {
    tap.pass('test succeeded')
  } else {
    tap.fail(`test failed - exited code ${code}`)
  }
})
/* replacement end */


text:
require 'yajl/json_gem'

module Flapjack
  module Data
    class Event

      attr_accessor :previous_state, :previous_state_duration

      # Helper method for getting the next event.
      #
      # Has a blocking and non-blocking method signature.
      #
      # Calling next with :block => true, we wait indefinitely for events coming
      # from other systems. This is the default behaviour.
      #
      # Calling next with :block => false, will return a nil if there are no
      # events on the queue.
      #
      def self.next(opts={})
        raise "Redis connection not set" unless redis = opts[:redis]

        defaults = { :block => true }
        options  = defaults.merge(opts)

        # In production, we wait indefinitely for events coming from other systems.
        if options[:block]
          return self.new( ::JSON.parse( redis.blpop('events', 0).last ) )
        end

        # In testing, we take care that there are no events on the queue.
        return unless raw = redis.lpop('events')
        self.new( ::JSON.parse(raw) )
      end

      # creates, or modifies, an event object and adds it to the events list in redis
      #   'type'      => 'service',
      #   'state'     => state,
      #   'summary'   => check_output,
      #   'time'      => timestamp
      def self.add(evt, opts = {})
        raise "Redis connection not set" unless redis = opts[:redis]

        evt['time'] = Time.now.to_i if evt['time'].nil?
        redis.rpush('events', ::Yajl::Encoder.encode(evt))
      end

      # Provide a count of the number of events on the queue to be processed.
      def self.pending_count(opts = {})
        raise "Redis connection not set" unless redis = opts[:redis]

        redis.llen('events')
      end

      def initialize(attrs={})
        @attrs = attrs
        @attrs['time'] = Time.now.to_i unless @attrs.has_key?('time')
      end

      def state
        return unless @attrs['state']
        @attrs['state'].downcase
      end

      def entity
        return unless @attrs['entity']
        @attrs['entity'].downcase
      end

      def check
        @attrs['check']
      end

      # FIXME some values are only set for certain event types --
      # this may not be the best way to do this
      def acknowledgement_id
        @attrs['acknowledgement_id']
      end

      def duration
        return unless @attrs['duration']
        @attrs['duration'].to_i
      end
      # end FIXME

      def id
        (entity || '-') + ':' + (check || '-')
      end

      # FIXME: site specific
      def client
        return unless entity
        entity.split('-').first
      end

      def type
        return unless @attrs['type']
        @attrs['type'].downcase
      end

      def summary
        @attrs['summary']
      end

      def time
        return unless @attrs['time']
        @attrs['time'].to_i
      end

      def action?
        type == 'action'
      end

      def service?
        type == 'service'
      end

      def acknowledgement?
        action? and state == 'acknowledgement'
      end

      def test_notifications?
        action? and state == 'test_notifications'
      end

      def ok?
        (state == 'ok') or (state == 'up')
      end

      def unknown?
        state == 'unknown'
      end

      def unreachable?
        state == 'unreachable'
      end

      def warning?
        state == 'warning'
      end

      def critical?
        state == 'critical'
      end

      def failure?
        warning? or critical? or unknown?
      end

    end
  end
end


text:
/**
 *
 * @file sg_vv2__history.c
 *
 * @details Compute HISTORY for either the whole repo or for a
 * selected subset.  We do not require a WD to be present, but
 * if the REPO arg is omitted, we will try to use the current
 * WD if available.
 *
 */

//////////////////////////////////////////////////////////////////

#include <sg.h>

#include <sg_wc__public_typedefs.h>
#include <sg_wc__public_prototypes.h>

#include "sg_vv2__public_typedefs.h"
#include "sg_vv2__public_prototypes.h"
#include "sg_vv2__private.h"

//////////////////////////////////////////////////////////////////

void SG_vv2__history(SG_context * pCtx,
					 const SG_vv2_history_args * pHistoryArgs,
					 SG_bool* pbHasResult,
					 SG_vhash** ppvhBranchPile,
					 SG_history_result ** ppHistoryResult)
{
	SG_vhash * pvhBranchPile = NULL;
	SG_history_result * pHistoryResult = NULL;
	SG_bool bHasResult = SG_FALSE;

	SG_NULLARGCHECK_RETURN( pHistoryArgs );
	// pbHasResult is optional
	// ppvhBranchPile is optional
	SG_NULLARGCHECK_RETURN( ppHistoryResult );

	// TODO 2012/07/03 Figure out what the purpose/meaning of "leaves" is.
	// TODO            The "leaves" argument is only passed to the __working_folder()
	// TODO            version of HISTORY.  When "((count(psa_branches)==0) && !bLeaves)"
	// TODO            it will use the WD's current branch (as if it were given to us
	// TODO            using (one or more) "branch" args).

	if (pHistoryArgs->bListAll)
	{
		// When bListAll, we shouldn't get anythin pRevSpec_single_revisions.
		//
		// TODO 2012/07/05 I'd like to move this variable inside here rather
		// TODO            than force all the callers to split up the args.
		SG_ASSERT_RELEASE_RETURN( (pHistoryArgs->pRevSpec_single_revisions==NULL) );
	}

	if (pHistoryArgs->pszRepoDescriptorName && *pHistoryArgs->pszRepoDescriptorName)
	{
		if (pHistoryArgs->bLeaves)
			SG_ERR_THROW2(  SG_ERR_INVALIDARG,
							(pCtx, "The 'leaves' option cannot be used with the 'repo' option.")  );

		SG_ERR_CHECK(  sg_vv2__history__repo(pCtx,
											 pHistoryArgs->pszRepoDescriptorName,
											 pHistoryArgs->psaSrcArgs,
											 pHistoryArgs->pRevSpec,
											 pHistoryArgs->pRevSpec_single_revisions,
											 pHistoryArgs->pszUser,
											 pHistoryArgs->pszStamp,
											 pHistoryArgs->nResultLimit,
											 pHistoryArgs->bHideObjectMerges,
											 pHistoryArgs->nFromDate,
											 pHistoryArgs->nToDate,
											 pHistoryArgs->bListAll,
											 SG_FALSE,
											 ((pbHasResult)    ? &bHasResult    : NULL),
											 ((ppvhBranchPile) ? &pvhBranchPile : NULL),
											 &pHistoryResult,
											 NULL)  );
	}
	else
	{
		SG_bool bDetectCurrentBranch = (!pHistoryArgs->bLeaves);

		SG_ERR_CHECK(  sg_vv2__history__working_folder(pCtx,
													   pHistoryArgs->psaSrcArgs,
													   pHistoryArgs->pRevSpec,
													   pHistoryArgs->pRevSpec_single_revisions,
													   pHistoryArgs->pszUser,
													   pHistoryArgs->pszStamp,
													   bDetectCurrentBranch,
													   pHistoryArgs->nResultLimit,
													   pHistoryArgs->bHideObjectMerges,
													   pHistoryArgs->nFromDate,
													   pHistoryArgs->nToDate,
													   pHistoryArgs->bListAll,
													   ((pbHasResult)    ? &bHasResult    : NULL),
													   ((ppvhBranchPile) ? &pvhBranchPile : NULL),
													   &pHistoryResult,
													   NULL)  );
	}

	if (pHistoryResult)
	{
		if (pHistoryArgs->bReverse)
			SG_ERR_CHECK(  SG_history_result__reverse(pCtx, pHistoryResult)  );
	}

	if (pbHasResult)
		*pbHasResult = bHasResult;
	if (ppvhBranchPile)
	{
		*ppvhBranchPile = pvhBranchPile;
		pvhBranchPile = NULL;
	}
	*ppHistoryResult = pHistoryResult;
	pHistoryResult = NULL;

fail:
	SG_VHASH_NULLFREE(pCtx, pvhBranchPile);
	SG_HISTORY_RESULT_NULLFREE(pCtx, pHistoryResult);
}


text:
package signature

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"

	"github.com/mtrmac/gpgme"
)

// A GPG/OpenPGP signing mechanism, implemented using gpgme.
type gpgmeSigningMechanism struct {
	ctx          *gpgme.Context
	ephemeralDir string // If not "", a directory to be removed on Close()
}

// newGPGSigningMechanismInDirectory returns a new GPG/OpenPGP signing mechanism, using optionalDir if not empty.
// The caller must call .Close() on the returned SigningMechanism.
func newGPGSigningMechanismInDirectory(optionalDir string) (SigningMechanism, error) {
	ctx, err := newGPGMEContext(optionalDir)
	if err != nil {
		return nil, err
	}
	return &gpgmeSigningMechanism{
		ctx:          ctx,
		ephemeralDir: "",
	}, nil
}

// newEphemeralGPGSigningMechanism returns a new GPG/OpenPGP signing mechanism which
// recognizes _only_ public keys from the supplied blob, and returns the identities
// of these keys.
// The caller must call .Close() on the returned SigningMechanism.
func newEphemeralGPGSigningMechanism(blob []byte) (SigningMechanism, []string, error) {
	dir, err := ioutil.TempDir("", "containers-ephemeral-gpg-")
	if err != nil {
		return nil, nil, err
	}
	removeDir := true
	defer func() {
		if removeDir {
			os.RemoveAll(dir)
		}
	}()
	ctx, err := newGPGMEContext(dir)
	if err != nil {
		return nil, nil, err
	}
	mech := &gpgmeSigningMechanism{
		ctx:          ctx,
		ephemeralDir: dir,
	}
	keyIdentities, err := mech.importKeysFromBytes(blob)
	if err != nil {
		return nil, nil, err
	}

	removeDir = false
	return mech, keyIdentities, nil
}

// newGPGMEContext returns a new *gpgme.Context, using optionalDir if not empty.
func newGPGMEContext(optionalDir string) (*gpgme.Context, error) {
	ctx, err := gpgme.New()
	if err != nil {
		return nil, err
	}
	if err = ctx.SetProtocol(gpgme.ProtocolOpenPGP); err != nil {
		return nil, err
	}
	if optionalDir != "" {
		err := ctx.SetEngineInfo(gpgme.ProtocolOpenPGP, "", optionalDir)
		if err != nil {
			return nil, err
		}
	}
	ctx.SetArmor(false)
	ctx.SetTextMode(false)
	return ctx, nil
}

func (m *gpgmeSigningMechanism) Close() error {
	if m.ephemeralDir != "" {
		os.RemoveAll(m.ephemeralDir) // Ignore an error, if any
	}
	return nil
}

// importKeysFromBytes imports public keys from the supplied blob and returns their identities.
// The blob is assumed to have an appropriate format (the caller is expected to know which one).
// NOTE: This may modify long-term state (e.g. key storage in a directory underlying the mechanism);
// but we do not make this public, it can only be used through newEphemeralGPGSigningMechanism.
func (m *gpgmeSigningMechanism) importKeysFromBytes(blob []byte) ([]string, error) {
	inputData, err := gpgme.NewDataBytes(blob)
	if err != nil {
		return nil, err
	}
	res, err := m.ctx.Import(inputData)
	if err != nil {
		return nil, err
	}
	keyIdentities := []string{}
	for _, i := range res.Imports {
		if i.Result == nil {
			keyIdentities = append(keyIdentities, i.Fingerprint)
		}
	}
	return keyIdentities, nil
}

// SupportsSigning returns nil if the mechanism supports signing, or a SigningNotSupportedError.
func (m *gpgmeSigningMechanism) SupportsSigning() error {
	return nil
}

// Sign creates a (non-detached) signature of input using keyIdentity.
// Fails with a SigningNotSupportedError if the mechanism does not support signing.
func (m *gpgmeSigningMechanism) Sign(input []byte, keyIdentity string) ([]byte, error) {
	key, err := m.ctx.GetKey(keyIdentity, true)
	if err != nil {
		return nil, err
	}
	inputData, err := gpgme.NewDataBytes(input)
	if err != nil {
		return nil, err
	}
	var sigBuffer bytes.Buffer
	sigData, err := gpgme.NewDataWriter(&sigBuffer)
	if err != nil {
		return nil, err
	}
	if err = m.ctx.Sign([]*gpgme.Key{key}, inputData, sigData, gpgme.SigModeNormal); err != nil {
		return nil, err
	}
	return sigBuffer.Bytes(), nil
}

// Verify parses unverifiedSignature and returns the content and the signer's identity
func (m gpgmeSigningMechanism) Verify(unverifiedSignature []byte) (contents []byte, keyIdentity string, err error) {
	signedBuffer := bytes.Buffer{}
	signedData, err := gpgme.NewDataWriter(&signedBuffer)
	if err != nil {
		return nil, "", err
	}
	unverifiedSignatureData, err := gpgme.NewDataBytes(unverifiedSignature)
	if err != nil {
		return nil, "", err
	}
	_, sigs, err := m.ctx.Verify(unverifiedSignatureData, nil, signedData)
	if err != nil {
		return nil, "", err
	}
	if len(sigs) != 1 {
		return nil, "", InvalidSignatureError{msg: fmt.Sprintf("Unexpected GPG signature count %d", len(sigs))}
	}
	sig := sigs[0]
	// This is sig.Summary == gpgme.SigSumValid except for key trust, which we handle ourselves
	if sig.Status != nil || sig.Validity == gpgme.ValidityNever || sig.ValidityReason != nil || sig.WrongKeyUsage {
		// FIXME: Better error reporting eventually
		return nil, "", InvalidSignatureError{msg: fmt.Sprintf("Invalid GPG signature: %#v", sig)}
	}
	return signedBuffer.Bytes(), sig.Fingerprint, nil
}

// UntrustedSignatureContents returns UNTRUSTED contents of the signature WITHOUT ANY VERIFICATION,
// along with a short identifier of the key used for signing.
// WARNING: The short key identifier (which correponds to "Key ID" for OpenPGP keys)
// is NOT the same as a "key identity" used in other calls ot this interface, and
// the values may have no recognizable relationship if the public key is not available.
func (m gpgmeSigningMechanism) UntrustedSignatureContents(untrustedSignature []byte) (untrustedContents []byte, shortKeyIdentifier string, err error) {
	return gpgUntrustedSignatureContents(untrustedSignature)
}


text:
'use strict';
/**
 * d2recharts defautl theme
 * @module default
 * @see module:index
 */
const echarts = require('echarts');
const warmColorTheme = require('./warm-color.json');
const constant = require('../constant');

echarts.registerTheme(constant.DEFAULT_THEME_NAME, warmColorTheme);
echarts.registerTheme('warm-color', warmColorTheme);


text:
var path = require('path');
var util = require('util');
var yeoman = require('../../../../');

module.exports = Generator;

function Generator() {
  yeoman.generators.Base.apply( this, arguments );
  this.sourceRoot( path.join( __dirname, 'templates' ) );
  this.appname = path.basename( process.cwd() );
  this.appPermissions = {
  };
}

util.inherits( Generator, yeoman.generators.NamedBase );

Generator.prototype.askFor = function askFor( argument ) {
  var cb = this.async();

  var prompts = [{
    name: 'appFullName',
    message: 'What would you like to call this application?',
    default: 'myChromeApp',
    warning: 'You can change the default application name.'
  },
  {
    name: 'appDescription',
    message: 'How would you like to describe this application?',
    default: 'My Chrome app',
    warning: 'You can change the default app description.'
  },
  {
    name: 'unlimtedStoragePermission',
    message: 'Would you like to use Storage in your app',
    default: "Y/n",
    warning: 'You can change the permissions'
  },
  {
    name: 'identityPermission',
    message: 'Would you like to the experimental Identity API in your app',
    default: "Y/n",
    warning: 'You can change the permissions'
  },
  {
    name: 'browserTagPermission',
    message: 'Would you like to use the Browser Tag in your app',
    default: "Y/n",
    warning: 'You can change the permissions'
  },
  {
    name: 'videoCapturePermission',
    message: 'Would you like to use the Camera in your app',
    default: "Y/n",
    warning: 'You can change the permissions'
  },
  {
    name: 'audioCapturePermission',
    message: 'Would you like to use the Microphone in your app',
    default: "Y/n",
    warning: 'You can change the permissions'
  },
  {
    name: 'usbPermission',
    message: 'Would you like to use USB in your app',
    default: "Y/n",
    warning: 'You can change the permissions'
  },
  {
    name: 'bluetoothPermission',
    message: 'Would you like to use Bluetooth in your app',
    default: "Y/n",
    warning: 'You can change the permissions'
  },
  {
    name: 'serialPermission',
    message: 'Would you like to use the Serial Port in your app',
    default: "Y/n",
    warning: 'You can change the permissions'
  },
  {
    name: 'udpsendPermission',
    message: 'Would you like to send UDP data in your app',
    default: "Y/n",
    warning: 'You can change the permissions'
  },
  {
    name: 'udpbindPermission',
    message: 'Would you like to receive UDP data in your app',
    default: "Y/n",
    warning: 'You can change the permissions'
  },
  {
    name: 'tcpPermission',
    message: 'Would you like to use TCP in your app?',
    default: "Y/n",
    warning: 'You can change the permissions'
  },
  {
    name: 'mediagalleryPermission',
    message: 'Would you like to use the Media Gallery API in your app?',
    default: "Y/n",
    warning: 'You can change the permissions'
  }

  ];

  this.prompt( prompts, function( err, props ) {
    if ( err ) {
      return this.emit( 'error', err );
    }
    this.appFullName = props.appFullName;
    this.appDescription = props.appDescription
    this.appPermissions.serial = (/y/i).test(props.serialPermission);
    this.appPermissions.identity = (/y/i).test(props.identityPermission);
    this.appPermissions.unlimitedStorage = (/y/i).test(props.unlimitedStoragePermission);
    this.appPermissions.usb = (/y/i).test(props.usbPermission);
    this.appPermissions.bluetooth = (/y/i).test(props.bluetoothPermission);
    this.appPermissions.browserTag = (/y/i).test(props.browserTagPermission);
    this.appPermissions.audioCapture = (/y/i).test(props.audioCapturePermission);
    this.appPermissions.videoCapture = (/y/i).test(props.videoCapturePermission);

    var connections = [];
    if((/y/i).test(props.udpbindPermission)) connections.push("udp-bind::8899");
    if((/y/i).test(props.udpsendPermission)) connections.push("udp-send-to::8899");
    if((/y/i).test(props.tcpPermission)) connections.push("tcp-connect");

    // Complex permission objects
    if((/y/i).test(props.mediagalleryPermission))
      this.appPermissions.mediaGalleries = { "mediaGalleries" : ["read", "all-auto-detected"] };

    if(connections.length > 0)
      this.appPermissions.socket = { 'socket': connections };

    cb();
  }.bind( this ));
};

Generator.prototype.writeFiles = function createManifest() {

  var experimental = {
    "bluetooth" : true,
    "usb": true,
    "identity": true,
    "mediaGalleries": true,
    "browserTag": true
  };

  // Using object to maintain complex objects rather than strings.
  var complex = {
    "socket": true,
    "mediaGalleries": true
  };

  var permissions = [];
  var usesExperimental = false;
  var complexPermissions = [];

  for(var permission in this.appPermissions) {
    if(!!this.appPermissions[permission] == false) continue;
    if(experimental[permission]) usesExperimental = true;
    if(complex[permission])  {
      complexPermissions.push(this.appPermissions[permission]);
      continue;
    }

    permissions.push(permission);
  }

  if(usesExperimental) permissions.push("experimental");
  var data = {
    appFullName: this.appFullName,
    appDescription: this.appDescription,
    appPermissions: "\"" + permissions.join('","') + "\""
  };

  if(complexPermissions.length > 0) {
    for(var p = 0; permission = complexPermissions[p]; p ++) {
      data.appPermissions += "," + JSON.stringify(permission);
    }
  }

  this.directory( '.', '.' );

  this.template( 'app/index.html', path.join( 'app', 'index.html' ), data );
  this.template( 'app/manifest.json', path.join( 'app', 'manifest.json' ), data );
  this.template( 'app/_locales/en/messages.json', path.join( 'app', '_locales', 'en' , 'messages.json' ), data );
};