using System;
using System.Linq;
using System.Management.Automation;
using Microsoft.SharePoint.Client;
using PnP.PowerShell.CmdletHelpAttributes;
using PnP.PowerShell.Commands.Base.PipeBinds;

namespace PnP.PowerShell.Commands.Lists
{
    //TODO: Create Test
    [Cmdlet(VerbsCommon.Set, "PnPListPermission")]
    [CmdletHelp("Sets list permissions",
        Category = CmdletHelpCategory.Lists)]
    [CmdletExample(
        Code = "PS:> Set-PnPListPermission -Identity 'Documents' -User 'user@contoso.com' -AddRole 'Contribute'",
        Remarks = "Adds the 'Contribute' permission to the user 'user@contoso.com' for the list 'Documents'",
        SortOrder = 1)]
    [CmdletExample(
        Code = "PS:> Set-PnPListPermission -Identity 'Documents' -User 'user@contoso.com' -RemoveRole 'Contribute'",
        Remarks = "Removes the 'Contribute' permission to the user 'user@contoso.com' for the list 'Documents'",
        SortOrder = 2)]
    public class SetListPermission : PnPWebCmdlet
    {
        [Parameter(Mandatory = true, ParameterSetName = ParameterAttribute.AllParameterSets, HelpMessage = "The ID or Title of the list.")]
        public ListPipeBind Identity;

        [Parameter(Mandatory = true, ParameterSetName = "Group")]
        public GroupPipeBind Group;

        [Parameter(Mandatory = true, ParameterSetName = "User")]
        public string User;

        [Parameter(Mandatory = false, HelpMessage = "The role that must be assigned to the group or user")]
        public string AddRole = string.Empty;

        [Parameter(Mandatory = false, HelpMessage = "The role that must be removed from the group or user")]
        public string RemoveRole = string.Empty;

        protected override void ExecuteCmdlet()
        {
            var list = Identity.GetList(SelectedWeb);

            if (list != null)
            {
                Principal principal = null;
                if (ParameterSetName == "Group")
                {
                    if (Group.Id != -1)
                    {
                        principal = SelectedWeb.SiteGroups.GetById(Group.Id);
                    }
                    else if (!string.IsNullOrEmpty(Group.Name))


// Code size       25 (0x19)
  .maxstack  1
  .locals init (C1 V_0) //c1
  IL_0000:  newobj     ""C1..ctor()""
  IL_0005:  stloc.0
  .try
  {
    IL_0006:  ldloc.0
    IL_0007:  callvirt   ""void C1.Method1()""
    IL_000c:  leave.s    IL_0018
  }
  finally
  {
    IL_000e:  ldloc.0
    IL_000f:  brfalse.s  IL_0017
    IL_0011:  ldloc.0
    IL_0012:  callvirt   ""void System.IDisposable.Dispose()""
    IL_0017:  endfinally
  }
  IL_0018:  ret
}");
        }

        [Fact]
        public void PreexistingVariablesUsingDeclarationEmitTest()
        {
            string source = @"
using System;
class C1 : IDisposable
{
    public void Dispose() { }
    public void Method1() { }
}
class C2
{
    public static void Main()
    {
        C1 c0 = new C1();
        c0.Method1();
        using var c1 = new C1();
    }
}";
            CompileAndVerify(source).VerifyIL("C2.Main", @"
{
  // Code size       29 (0x1d)
  .maxstack  1
  .locals init (C1 V_0) //c1
  IL_0000:  newobj     ""C1..ctor()""
  IL_0005:  callvirt   ""void C1.Method1()""
  IL_000a:  newobj     ""C1..ctor()""
  IL_000f:  stloc.0
  .try
  {
    IL_0010:  leave.s    IL_001c
  }
  finally
  {
    IL_0012:  ldloc.0
    IL_0013:  brfalse.s  IL_001b
    IL_0015:  ldloc.0
    IL_0016:  callvirt   ""void System.IDisposable.Dispose()""
    IL_001b:  endfinally
  }
  IL_001c:  ret
}");
        }

        [Fact]
        public void TwoUsingVarsInARow()
        {
            string source = @"
using System;
class C1 : IDisposable
{
    public void M() { }
    public void Dispose() { }
}
class C2
{
    public static void Main()
    {
        using C1 o1 = new C1();
        using C1 o2 = new C1();
    }
}";
            CompileAndVerify(source).VerifyIL("C2.Main", @"
{
  // Code size       35 (0x23)
  .maxstack  1
  .locals init (C1 V_0, //o1
                C1 V_1) //o2
  IL_0000:  newobj     ""C1..ctor()""
  IL_0005:  stloc.0
  .try
  {
    IL_0006:  newobj     ""C1..ctor()""
    IL_000b:  stloc.1
    .try
    {
      IL_000c:  leave.s    IL_0022
    }
    finally
    {
      IL_000e:  ldloc.1
      IL_000f:  brfalse.s  IL_0017
      IL_0011:  ldloc.1
      IL_0012:  callvirt   ""void System.IDisposable.Dispose()""
      IL_0017:  endfinally
    }
  }
  finally
  {
    IL_0018:  ldloc.0
    IL_0019:  brfalse.s  IL_0021
    IL_001b:  ldloc.0
    IL_001c:  callvirt   ""void System.IDisposable.Dispose()""
    IL_0021:  endfinally
  }
  IL_0022:  ret
}");
        }

        [Fact]
        public void UsingVarSandwich()
        {
            string source = @"
using System;
class C1 : IDisposable
{


delete_user).
  ///
  /// Delete a user from Tautulli. Also erases all history for the user.
  ///
  /// Required Parameters:
  /// - `userId`: The ID of the Plex user
  ///
  /// Optional Parameters:
  /// - `rowIds`: Optional list of row IDs to delete
  Future<void> deleteUser({
    required int userId,
    List<int>? rowIds,
  }) async =>
      _commandDeleteUser(_client, userId: userId, rowIds: rowIds);

  /// Handler for [edit_user](https://github.com/Tautulli/Tautulli/blob/master/API.md#edit_user).
  ///
  /// Update a user on Tautulli.
  ///
  /// Required Parameters:
  /// - `userId`: The ID of the Plex user
  ///
  /// Optional Parameters:
  /// - `friendlyName`: A friendly name to set for the user
  /// - `customThumb`: A URL to set the custom thumbnail to
  /// - `keepHistory`: Set if you should keep the history for the user
  /// - `allowGuest`: Set if you want to allow Tautulli guest access for the user
  Future<void> editUser({
    required int userId,
    String? friendlyName,
    String? customThumb,
    bool? keepHistory,
    bool? allowGuest,
  }) async =>
      _commandEditUser(_client,
          userId: userId,
          friendlyName: friendlyName,
          customThumb: customThumb,
          keepHistory: keepHistory,
          allowGuest: allowGuest);

  /// Handler for [get_user](https://github.com/Tautulli/Tautulli/blob/master/API.md#get_user).
  ///
  /// Get a user's details.
  ///
  /// Required Parameters:
  /// - `userId`: The user's ID
  Future<TautulliUser> getUser({
    required int userId,
  }) async =>
      _commandGetUser(_client, userId: userId);

  /// Handler for [get_user_logins](https://github.com/Tautulli/Tautulli/blob/master/API.md#get_user_logins).
  ///
  /// Get the data on Tautulli user login table.
  ///
  /// Optional Parameters:
  /// - `userId`: A specific user to fetch login records for
  /// - `orderColumn`: The column order key for sorting the login records
  /// - `orderDirection`: The direction to sort the login records
  /// - `start`: Which row to start at (default: 0)
  /// - `length`: Number of records to return (default: 25)
  /// - `search`: A string to search for
  Future<TautulliUserLogins> getUserLogins({
    int? userId,
    TautulliUserLoginsOrderColumn? orderColumn,
    TautulliOrderDirection? orderDirection,
    int? start,
    int? length,
    String? search,
  }) async =>
      _commandGetUserLogins(
        _client,
        userId: userId,
        orderColumn: orderColumn,
        orderDirection: orderDirection,
        start: start,
        length: length,
        search: search,
      );

  /// Handler for [get_user_ips](https://github.com/Tautulli/Tautulli/blob/master/API.md#get_user_ips).
  ///
  /// Get the data on Tautulli users IP table.
  ///
  /// Required Parameters:
  /// - `userId`: A specific user to fetch IP address records for
  ///
  /// Optional Parameters:
  /// - `orderColumn`: The column order key for sorting the IP address records
  /// - `orderDirection`: The direction to sort the IP address records
  /// - `start`: Which row to start at (default: 0)
  /// - `length`: Number of records to return (default: 25)
  /// - `search`: A string to search for
  Future<TautulliUserIPs> getUserIPs({
    required


path")
    var posterPath: String? = null,

    @SerializedName("title")
    var title: String? = null,

    @SerializedName("video")
    var video: Boolean? = null,

    @SerializedName("vote_average")
    var voteAverage: Double? = null,

    @SerializedName("overview")
    var overview: String? = null,

    @SerializedName("release_date")
    var releaseDate: String? = null,

    @SerializedName("vote_count")
    var voteCount: Int? = null,

    @SerializedName("popularity")
    var popularity: Double? = null,

    @SerializedName("character")
    var character: String? = null,

    @SerializedName("credit_id")
    var creditId: String? = null,

    @SerializedName("order")
    var order: Int? = null

) : Serializablepackage org.ntqqrev.saltify

import org.ntqqrev.saltify.config.Configurable
import org.ntqqrev.saltify.config.IntRange
import org.ntqqrev.saltify.config.Option

class SaltifyAppConfig(
    @Configurable(
        "事件缓冲区长度",
        "最多缓存的事件数量，设置更小的值可节约内存，但可能导致事件丢失"
    )
    val eventBufferSize: Int = 1000,

    @Configurable(
        "网络配置"
    )
    val network: Network = Network(),

    @Configurable(
        "命令配置"
    )
    val command: Command = Command(),
) {
    class Network(
        @Configurable(
            "Saltify 服务监听地址",
            "如需公网访问，请修改为 0.0.0.0"
        )
        val host: String = "127.0.0.1",

        @Configurable(
            "Saltify 服务监听端口",
        )
        @IntRange(1, 65535)
        val port: Int = 29373, // "SLT" as radix 32
    )

    class Command(
        @Configurable(
            "命令触发策略"
        )
        val triggerPolicy: TriggerPolicy = TriggerPolicy.ON_MENTION,

        @Configurable(
            "命令触发前缀",
            "仅在命令触发策略为 ON_PREFIX 或 ON_MENTION_WITH_PREFIX 时有效"
        )
        val triggerPrefix: String = "/",
    ) {
        enum class TriggerPolicy {
            @Option("在提及机器人时触发命令，例如 @Bot help")
            ON_MENTION,

            @Option("在消息以特定字符起始时触发命令，例如 /help")
            ON_PREFIX,

            @Option("在提及机器人并且以特定字符起始时触发命令，例如 @Bot /help")
            ON_MENTION_WITH_PREFIX,
        }
    }
}package org.ntqqrev.saltify.command

import org.ntqqrev.saltify.message.incoming.IncomingMessage
import org.ntqqrev.saltify.message.incoming.TextSegment

private const val segmentTokenPrefix = 0x1F.toChar()

class MessageTokenizer(
    private val message: IncomingMessage,
    startIndex: Int = 0
) : ITokenizer<Token> {
    private val textTokenizer = TextTokenizer(
        message.segments
            .drop(startIndex)
            .mapIndexed { index, segment ->
                when (segment) {
                    is TextSegment -> segment.text
                    else -> "$segmentTokenPrefix${index + startIndex}"
                }
            }
            .joinToString(" ")
    )

    override fun hasMoreTokens() = textTokenizer.hasMoreTokens()

    override fun read(): Token {
        val rawToken = textTokenizer.read()
        return when {
            rawToken.startsWith(segmentTokenPrefix) -> {
                val index = rawToken.substring(1).toInt()


EC,
		.help = "erase flash through ISP.",
	},
	{
		.name = "chip_erase",
		.handler = numicro_handle_chip_erase_command,
		.mode = COMMAND_EXEC,
		.help = "chip erase through ISP.",
	},
	{
		.name = "M2351_erase",
		.handler = numicro_handle_M2351_erase_command,
		.mode = COMMAND_EXEC,
		.help = "M2351 erase command.",
	},
	{
		.name = "NUC505_sram_ini",
		.handler = numicro_handle_NUC505_sram_ini_command,
		.mode = COMMAND_EXEC,
		.help = "NUC505 sram initialization command.",
	},
	{
		.name = "NUC505_chip_reset",
		.handler = numicro_handle_NUC505_chip_reset_command,
		.mode = COMMAND_EXEC,
		.help = "NUC505 chip reset command.",
	},
	COMMAND_REGISTRATION_DONE
};

static const struct command_registration numicro_command_handlers[] = {
	{
		.name = "numicro",
		.mode = COMMAND_ANY,
		.help = "numicro flash command group",
		.usage = "",
		.chain = numicro_exec_command_handlers,
	},
	COMMAND_REGISTRATION_DONE
};

struct flash_driver numicro_flash = {
	.name = "numicro",
	.commands = numicro_command_handlers,
	.flash_bank_command = numicro_flash_bank_command,
	.erase = numicro_erase,
	.write = numicro_write,
	.read = default_flash_read,
	.probe = numicro_probe,
	.auto_probe = numicro_auto_probe,
	.erase_check = default_flash_blank_check,
	.protect_check = numicro_protect_check,
};


signature its needs and the test would fail
        await delay(15000);
        await client.signOut();
        console.log("Bobbo anonymous after sign-up: ", client.anonymous);

        // Test for second agent on same host
        await client.signUp("new_bob.test.2@holo.host", "Passw0rd!", joiningCode);
        console.log("Finished sign-up for agent: %s", client.agent_id);
        if (client.anonymous === true) {
          throw new Error("Client did not sign-in")
        }
        if (client.agent_id !== "uhCAkdop1X9N_xdSH_AZtFG9U8F8gCLXcF__MRYtg3yY4QgvGoyLe") {
          throw new Error(`Unexpected Agent ID: ${client.agent_id}`)
        }
        await client.signOut();
        console.log("New Bob anonymous after sign-up: ", client.anonymous);

        return {
          responseOne,
          responseTwo
        }
      }, HOST_AGENT_ID, happs.test.installed_app_id, SUCCESSFUL_JOINING_CODE);

      log.info("Completed evaluation: %s", responseOne);
      log.info("Completed evaluation: %s", responseTwo);
      expect(responseOne).to.have.property("value").which.equals("This is the returned value");
      expect(responseTwo).to.have.property("value").which.equals("This is the returned value");
    } finally {
    }
  });

  it("should sign-up, sign-out, sign-in, and sign back out successfully", async function () {
    this.timeout(300_000);
    try {
      const { signedUp, signedOutOnce, signedIn, signedOutTwice } = await page.evaluate(async function (host_agent_id, registered_happ_hash, joiningCode) {
        console.log("Registered Happ Hash: %s", registered_happ_hash);
        let isSignedOut;
        const client = new Chaperone({
          "mode": Chaperone.DEVELOP,
          "web_user_legend": {},
          "connection": {
            "ssl": false,
            "host": "localhost",
            "port": 4656,
          },

          host_agent_id, // used to assign host (id generated by hpos-seed)
          app_id: registered_happ_hash, // NOT RANDOM: this needs to match the hash of app in hha

          "timeout": 50000,
          "debug": true,
        });
        client.skip_assign_host = true;

        await client.ready(200_000);
        const isSignedUp = await client.signUp("alice.test.1@holo.host", "Passw0rd!", joiningCode);
        console.log('isSignedUp : ', isSignedUp)
        console.log("Finished sign-up for agent: %s", client.agent_id);
        const signedUp = (isSignedUp && client.anonymous === false && client.agent_id === "uhCAk6n7bFZ2_28kUYCDKmU8-2K9z3BzUH4exiyocxR6N5HvshouY")

        // Delay is added so that the in process calls have time to finish all the signing required
        //and by signing out too soon it would not be able to get all the signature its needs and the test would fail
        await delay(15000);
        isSignedOut = await client.signOut();
        console.log('isSignedOut : ', isSignedOut)
        console.log("alice anonymous after sign-up: ", client.anonymous);
        const signedOutOnce = (isSignedOut && client.anonymous === true && client.agent_id !== "uhCAk6n7bFZ2_28kUYCDKmU8-2K9z3BzUH4exiyocxR6N5HvshouY")

        const isSignedIn = await client.signIn("alice.test.1@holo.host", "Passw0rd!");
        console.log('


otes Manchados de Fungos",
[61413] = "Pisoteadores de Cogumelo",
[61414] = "Atiragermes",
[61415] = "Manto de Crescimento Fúngico",
[61416] = "Cinturão da Explosão Bolete",
[61417] = "Calças Cobertas de Esporos",
[61418] = "Dragonas Rochosas do Terrath",
[61419] = "Vestes de Petrescama",
[61420] = "Adaga de Osso de Dragão",
[61421] = "Braçadeiras Petrificadas",
[61422] = "Vara de Olho de Basilisco",
[61423] = "Escudo Alvipolido",
[61424] = "Guarda-ombros Rompegeodo",
[61425] = "Braçadeiras do Elemental Enérgico",
[61426] = "Colar Mascristal",
[61427] = "Cinta Litoverme",
[61428] = "Elmo do Mataverme",
[61429] = "Insígnia do Lorde Terrano",
[61430] = "Coxotes de Ligas de Pedra",
[61431] = "Dragonas Descartadas do Mata-gigantes",
[61432] = "Braçadeiras Sanguissectárias",
[61433] = "Insígnia da Diplomacia",
[61434] = "Braçadeiras Firmes",
[61435] = "Capuz Fidedigno",
[61436] = "Cota Romportal",
[61437] = "Relíquia do Andarilho",
[61438] = "Sinete do Arranha-estrelas",
[61439] = "Cota Romportal",
[61440] = "Relíquia do Andarilho",
[61441] = "Sinete do Arranha-estrelas",
[61442] = "Grande Elmo do Escavalíngua",
[61443] = "Manoplas do Silenciador",
[61444] = "Omoplatas Quebralaços",
[61445] = "Elmo do Tagarela Silenciado",
[61446] = "Luvas do Matakaul",
[61447] = "Omoplatas do Guardafogo",
[61448] = "Benefício do Rochamanto",
[61449] = "Cinturão do Liberador",
[61450] = "Botinas dos Laços Partidos",
[61451] = "Couraça da Ruína Trogg",
[61452] = "Ombreiras de Tascatrogg",
[61453] = "Luvas de Matatrogg",
[61454] = "Luvas do Abastecedor de Catapulta",
[61455] = "Abraço da Terra",
[61456] = "Freio de Emergência Quebrado",
[61457] = "Peitoral Cristalino do Troggzor",
[61458] = "Elmo de Terrificação",
[61459] = "Calças de Camponês Aterrador",
[61460] = "Escudo Carregador de Catapulta",
[61461] = "Gargantilha Tortuosa",
[61462] = "Equipamento Detector",
[61463] = "Cinturão Terrelevado",
[61464] = "Botinas Avalanche",
[61465] = "Maça do Geomante",
[61466] = "Capacete do Tocador de Sinos",
[61467] = "Botas Esmagadoras Rancapele",
[61468] = "Calças dos Ecos Retumbantes",
[61469] = "Cinturão da Queimadura da Luz",
[61470] = "Braçadeiras do Vínculo Ardente",
[61471] = "Dragonas Cauterizadoras de Fer


: [0, 0, 0]
        };
        options = {
          width: 400,
          height: 400
        };
        await createChart();

        const slices = fixture.wrapper.querySelectorAll('.ct-slice-pie');

        expect(slices.length).toBe(3);

        expect(slices[0].getAttributeNS(namespaces.ct, 'value')).toBe('0');
        expect(slices[1].getAttributeNS(namespaces.ct, 'value')).toBe('0');
        expect(slices[2].getAttributeNS(namespaces.ct, 'value')).toBe('0');

        expect(slices[0]).toHaveAttribute(
          'd',
          'M200,5A195,195,0,0,0,200,5L200,200Z'
        );
        expect(slices[1]).toHaveAttribute(
          'd',
          'M200,5A195,195,0,0,0,200,5L200,200Z'
        );
        expect(slices[2]).toHaveAttribute(
          'd',
          'M200,5A195,195,0,0,0,200,5L200,200Z'
        );
      });

      it('should render empty slices', async () => {
        data = {
          series: [1, 2, 0, 4]
        };
        options = {
          width: 100,
          height: 100,
          ignoreEmptyValues: false
        };
        await createChart();

        const slices = fixture.wrapper.querySelectorAll('.ct-slice-pie');

        expect(slices.length).toBe(4);

        expect(slices[0].getAttributeNS(namespaces.ct, 'value')).toBe('1');
        expect(slices[1].getAttributeNS(namespaces.ct, 'value')).toBe('2');
        expect(slices[2].getAttributeNS(namespaces.ct, 'value')).toBe('0');
        expect(slices[3].getAttributeNS(namespaces.ct, 'value')).toBe('4');
      });
    });

    describe('Gauge Chart', () => {
      beforeEach(() => {
        data = {
          series: [20, 10, 30, 40]
        };
        options = {
          chartPadding: 50,
          height: 500,
          width: 500,
          donut: true,
          donutWidth: 60,
          startAngle: 270,
          total: 200,
          showLabel: false
        };
      });

      it('should render four strokes', async () => {
        await createChart();

        expect(fixture.wrapper.querySelectorAll('.ct-slice-donut').length).toBe(
          4
        );
      });

      it('should set value attribute', async () => {
        await createChart();

        const slices = fixture.wrapper.querySelectorAll('.ct-slice-donut');
        expect(slices[0].getAttributeNS(namespaces.ct, 'value')).toBe('20');
        expect(slices[1].getAttributeNS(namespaces.ct, 'value')).toBe('10');
        expect(slices[2].getAttributeNS(namespaces.ct, 'value')).toBe('30');
        expect(slices[3].getAttributeNS(namespaces.ct, 'value')).toBe('40');
      });

      it('should create slice path', async () => {
        const num = '\\d+(\\.\\d*)?';
        const pattern = new RegExp(
          `^M${num},${num}A170,170,0,0,0,${num},${num}$`
        );
        await createChart();

        Array.from(fixture.wrapper.querySelectorAll('.ct-slice-donut')).forEach(
          element =>
            expect(element).toHaveAttribute('d', expect.stringMatching(pattern))
        );
      });

      it('should set stroke-width', async () => {
        const strokeWidth = new RegExp('stroke-width:\\s*60px');
        await createChart();

        Array.from(fixture.wrapper.querySelectorAll('.ct-slice-donut')).forEach(
          element =>
            expect(element).toHav


am.parse()#!/usr/bin/env node

/*
	Test battery for Rom Patcher JS
	https://github.com/marcrobledo/RomPatcher.js
	by Marc Robledo, released under MIT license: https://github.com/marcrobledo/RomPatcher.js/blob/master/LICENSE

	Usage:
	> npm install
	> npm run test

	You need to provide the following ROMs and patches, unzip them in
	_test_files/roms and _test_files/patches folders respectively:
	- IPS test
		- Patch: https://www.romhacking.net/hacks/3784/
		- ROM:   Super Mario Land 2 - 6 Golden Coins (USA, Europe).gb [CRC32=d5ec24e4]
	- BPS test
		- Patch: https://www.romhacking.net/translations/6297/
		- ROM:   Samurai Kid (Japan).gbc [CRC32=44a9ddfb]
	- UPS test
		- Patch: https://mother3.fobby.net/
		- ROM:   Mother 3 (Japan).gba [CRC32=42ac9cb9]
	- APS test
		- Patch: http://dorando.emuverse.com/projects/eduardo_a2j/zelda-ocarina-of-time.html
		- ROM:   Legend of Zelda, The - Ocarina of Time (USA).z64 [CRC32=7e107c35]
	- APS (GBA) test
		- Patch: http://ngplus.net/InsaneDifficultyArchive/www.insanedifficulty.com/board/index9837.html?/files/file/65-final-fantasy-tactics-advance-x/
		- ROM:   Final Fantasy Tactics Advance (USA).gba [CRC32=5645e56c]
	- RUP test
		- Patch: https://www.romhacking.net/translations/843/
		- ROM:   Uchuu no Kishi - Tekkaman Blade (Japan).sfc [CRC32=cd16c529]
	- EBP test
		- Patch: https://forum.starmen.net/forum/Community/PKHack/NickBound/page/1#post2333521
		- ROM:   EarthBound (USA).sfc [CRC32=dc9bb451]
	- BDF test
		- Patch: https://www.romhacking.net/hacks/5813/
		- ROM:   Tetris (World) (Rev 1).gb [CRC32=46df91ad]
	- xdelta test
		- Patch: https://www.romhacking.net/hacks/2871/
		- ROM:   New Super Mario Bros. (USA, Australia).nds [CRC32=0197576a]
*/

const chalk = require('chalk');
const { existsSync } = require('fs');

const BinFile = require('./rom-patcher-js/modules/BinFile');
const HashCalculator = require('./rom-patcher-js/modules/HashCalculator');
const RomPatcher = require('./rom-patcher-js/RomPatcher');

const TEST_PATH = '_test_files/';
const TEST_PATCHES = [
	{
		title: 'IPS - Super Mario Land 2 DX',
		romFile: 'Super Mario Land 2 - 6 Golden Coins (USA, Europe).gb',
		romCrc32: 0xd5ec24e4,
		patchFile: 'SML2DXv181.ips',
		patchCrc32: 0x0b742316,
		patchDownload: 'https://www.romhacking.net/hacks/3784/',
		outputCrc32: 0xf0799017
	}, {
		title: 'BPS - Samurai Kid translation',
		romFile: 'Samurai Kid (Japan).gbc',
		romCrc32: 0x44a9ddfb,
		patchFile: 'samurai_kid_en_v1.bps',
		patchCrc32: 0x2144df1c,
		patchDownload: 'https://www.romhacking.net/translations/6297/',
		outputCrc32: 0xed238edb
	}, {
		title: 'UPS - Mother 3 translation',
		romFile: 'Mother 3 (Japan).gba',
		romCrc32: 0x42ac9cb9,
		patchFile: 'mother3.ups',
		patchCrc32: 0x2144df1c,
		patchDownload: 'https://mother3.fobby.net/',


rst
                  Zero line
                  """, 1, ExpectedResult = 7)]
        public int GivenSample_ReturnsCorrectLenghtValue(string input, int lineNumber)
        {
            return input.AsSpan().ExtractLinePosition(lineNumber).Start;
        }
        [TestCase("", 0, ExpectedResult = 0)]
        [TestCase("""
                  Zero line
                  """, 0, ExpectedResult = 9)]
        [TestCase("""
                  Zero line

                  """, 0, ExpectedResult = 9)]
        [TestCase("""
                  First
                  Second
                  """, 1, ExpectedResult = 6)]
        public int GivenSample_ReturnsCorrectStartLineValue(string input, int lineNumber)
        {
            return input.AsSpan().ExtractLinePosition(lineNumber).Length;
        }

        // ReSharper disable once StringLiteralTypo
        [TestCase("""
                  *=$0801
                  .byte $0c,$08,$b5,$07,$9e,$20,$32,$30,$36,$32,$00,$00,$00
                  jmp main

                  hellotext:
                      .encoding "screencode_mixed"
                      .text "c64 assembler studio!"
                      .byte $0
                      .const ofs = 9
                  .segment Base [prgFiles="test.prg, test2.prg"
                  #import "

                  .main
                  """, 10, ExpectedResult = "#import \"")]
        public string? GivenSample_ExtractsLineCorrectly(string input, int lineNumber)
        {
            var (start, length) = input.AsSpan().ExtractLinePosition(lineNumber);
            return input.Substring(start, length);
        }
    }
}


newBookmarkList.Add(line, bookmark);
            }
        }

        BookmarkList = newBookmarkList;
    }

    public int FindPrevBookmarkIndex (int lineNum)
    {
        var values = BookmarkList.Values;
        for (var i = BookmarkList.Count - 1; i >= 0; --i)
        {
            if (values[i].LineNum <= lineNum)
            {
                return i;
            }
        }

        return BookmarkList.Count - 1;
    }

    public int FindNextBookmarkIndex (int lineNum)
    {
        var values = BookmarkList.Values;
        for (var i = 0; i < BookmarkList.Count; ++i)
        {
            if (values[i].LineNum >= lineNum)
            {
                return i;
            }
        }

        return 0;
    }

    public void RemoveBookmarkForLine (int lineNum)
    {
        _ = BookmarkList.Remove(lineNum);
        OnBookmarkRemoved();
    }

    //TOOD: check if the callers are checking for null before calling
    public void RemoveBookmarksForLines (IEnumerable<int> lineNumList)
    {
        ArgumentNullException.ThrowIfNull(lineNumList, nameof(lineNumList));

        foreach (var lineNum in lineNumList)
        {
            _ = BookmarkList.Remove(lineNum);

        }

        OnBookmarkRemoved();
    }

    //TOOD: check if the callers are checking for null before calling
    public void AddBookmark (Entities.Bookmark bookmark)
    {
        ArgumentNullException.ThrowIfNull(bookmark, nameof(bookmark));

        BookmarkList.Add(bookmark.LineNum, bookmark);
        OnBookmarkAdded();
    }

    public void ClearAllBookmarks ()
    {
        _logger.Debug(CultureInfo.InvariantCulture, "Removing all bookmarks");
        BookmarkList.Clear();
        OnAllBookmarksRemoved();
    }

    #endregion

    protected void OnBookmarkAdded ()
    {
        BookmarkAdded?.Invoke(this, EventArgs.Empty);
    }

    protected void OnBookmarkRemoved ()
    {
        BookmarkRemoved?.Invoke(this, EventArgs.Empty);
    }

    protected void OnAllBookmarksRemoved ()
    {
        AllBookmarksRemoved?.Invoke(this, EventArgs.Empty);
    }
}


       if (oldTheme) el.removeClass('md-' + oldTheme +'-theme');
        el.addClass('md-' + theme + '-theme');
        el.data('$mdThemeName', theme);
        if (ctrl) {
          el.data('$mdThemeController', ctrl);
        }
      }
    };

    applyTheme.THEMES = angular.extend({}, THEMES);
    applyTheme.defaultTheme = function() { return defaultTheme; };
    applyTheme.registered = registered;
    applyTheme.generateTheme = generateTheme;

    return applyTheme;

    function registered(themeName) {
      if (themeName === undefined || themeName === '') return true;
      return applyTheme.THEMES[themeName] !== undefined;
    }

    function applyTheme(scope, el) {
      // Allow us to be invoked via a linking function signature.
      if (el === undefined) {
        el = scope;
        scope = undefined;
      }
      if (scope === undefined) {
        scope = $rootScope;
      }
      applyTheme.inherit(el, el);
    }
  }
}
ThemingProvider.$inject = ["$mdColorPalette"];

function ThemingDirective($mdTheming, $interpolate, $log) {
  return {
    priority: 100,
    link: {
      pre: function(scope, el, attrs) {
        var ctrl = {
          $setTheme: function(theme) {
            if (!$mdTheming.registered(theme)) {
              $log.warn('attempted to use unregistered theme \'' + theme + '\'');
            }
            ctrl.$mdTheme = theme;
          }
        };
        el.data('$mdThemeController', ctrl);
        ctrl.$setTheme($interpolate(attrs.mdTheme)(scope));
        attrs.$observe('mdTheme', ctrl.$setTheme);
      }
    }
  };
}
ThemingDirective.$inject = ["$mdTheming", "$interpolate", "$log"];

function ThemableDirective($mdTheming) {
  return $mdTheming;
}
ThemableDirective.$inject = ["$mdTheming"];

function parseRules(theme, colorType, rules) {
  checkValidPalette(theme, colorType);

  rules = rules.replace(/THEME_NAME/g, theme.name);
  var generatedRules = [];
  var color = theme.colors[colorType];

  var themeNameRegex = new RegExp('.md-' + theme.name + '-theme', 'g');
  // Matches '{{ primary-color }}', etc
  var hueRegex = new RegExp('(\'|")?{{\\s*(' + colorType + ')-(color|contrast)-?(\\d\\.?\\d*)?\\s*}}(\"|\')?','g');
  var simpleVariableRegex = /'?"?\{\{\s*([a-zA-Z]+)-(A?\d+|hue\-[0-3]|shadow)-?(\d\.?\d*)?(contrast)?\s*\}\}'?"?/g;
  var palette = PALETTES[color.name];

  // find and replace simple variables where we use a specific hue, not an entire palette
  // eg. "{{primary-100}}"
  //\(' + THEME_COLOR_TYPES.join('\|') + '\)'
  rules = rules.replace(simpleVariableRegex, function(match, colorType, hue, opacity, contrast) {
    if (colorType === 'foreground') {
      if (hue == 'shadow') {
        return theme.foregroundShadow;
      } else {
        return theme.foregroundPalette[hue] || theme.foregroundPalette['1'];
      }
    }
    if (hue.indexOf('hue') === 0) {
      hue = theme.colors[colorType].hues[hue];
    }
    return rgba( (PALETTES[ theme.colors[colorType].name ][hue] || '')[contrast ? 'contrast' : 'value'], opacity );
  });

  // For each type, generate rules for each hue (ie. default, md-hue-1, md-hue-2, md-hue-3)
  angular.forEach(color.hues, function(hueValue, hueName) {
    var newRule = rules


from dataclasses import dataclass
from datetime import datetime
import subprocess

from .config import TIMESTAMP_FORMAT

def parse_time(time_str: str) -> datetime:
    """
    Parse a time string into a standard format.
    """
    return datetime.strptime(time_str, TIMESTAMP_FORMAT)

def format_time(time: datetime) -> str:
    """
    Format a time into a standard string format.
    """
    return datetime.strftime(time, TIMESTAMP_FORMAT)

def clear_terminal():
    print("\033[H\033[J")

def format_paragraph(text: str, width: int = 75, indents=1) -> str:
    """
    Formats a paragraph to fit within a given width.
    """
    space = width - 8 * indents
    pretty_text = ""
    if len(text) > space:
        pretty_text += "\t" * indents + text[:space] + "\n"
        remainder = text[space:]
        while remainder:
            if len(remainder) > space:
                pretty_text += "\t" * indents + remainder[:space] + "\n"
                remainder = remainder[space:]
            else:
                pretty_text += "\t" * indents + remainder + "\n"
                remainder = ""
    else:
        pretty_text += "\t" * indents + text + "\n"
    return pretty_text

NL = "\n"

@dataclass
class GitVersion:
    commit: str
    branch: str

def get_git_version() -> GitVersion:
    """
    Get the current git commit hash.
    """
    commit = ""
    try:
        commit = subprocess.check_output(
            ["git", "rev-parse", "HEAD"], stderr=subprocess.STDOUT
        ).strip()
        commit = commit.decode("utf-8")
    except subprocess.CalledProcessError as e:
        print(f"Error getting git commit: {e.output.decode('utf-8')}")
        commit = "unknown"
    branch = ""
    try:
        branch = subprocess.check_output(
            ["git", "rev-parse", "--abbrev-ref", "HEAD"],
            stderr=subprocess.STDOUT,
        ).strip()
        branch = branch.decode("utf-8")
    except subprocess.CalledProcessError as e:
        print(f"Error getting git branch: {e.output.decode('utf-8')}")
        branch = "unknown"
    return GitVersion(commit=commit, branch=branch)


/*
 * OF-platform PATA driver
 *
 * Copyright (c) 2007  MontaVista Software, Inc.
 *                     Anton Vorontsov <avorontsov@ru.mvista.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License (Version 2) as
 * published by the Free Software Foundation.
 */

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of_address.h>
#include <linux/platform_device.h>
#include <linux/ata_platform.h>
#include <linux/libata.h>

#define DRV_NAME "pata_of_platform"

static struct scsi_host_template pata_platform_sht = {
	ATA_PIO_SHT(DRV_NAME),
};

static int pata_of_platform_probe(struct platform_device *ofdev)
{
	int ret;
	struct device_node *dn = ofdev->dev.of_node;
	struct resource io_res;
	struct resource ctl_res;
	struct resource *irq_res;
	unsigned int reg_shift = 0;
	int pio_mode = 0;
	int pio_mask;

	ret = of_address_to_resource(dn, 0, &io_res);
	if (ret) {
		dev_err(&ofdev->dev, "can't get IO address from "
			"device tree\n");
		return -EINVAL;
	}

	ret = of_address_to_resource(dn, 1, &ctl_res);
	if (ret) {
		dev_err(&ofdev->dev, "can't get CTL address from "
			"device tree\n");
		return -EINVAL;
	}

	irq_res = platform_get_resource(ofdev, IORESOURCE_IRQ, 0);

	of_property_read_u32(dn, "reg-shift", &reg_shift);

	if (!of_property_read_u32(dn, "pio-mode", &pio_mode)) {
		if (pio_mode > 6) {
			dev_err(&ofdev->dev, "invalid pio-mode\n");
			return -EINVAL;
		}
	} else {
		dev_info(&ofdev->dev, "pio-mode unspecified, assuming PIO0\n");
	}

	pio_mask = 1 << pio_mode;
	pio_mask |= (1 << pio_mode) - 1;

	return __pata_platform_probe(&ofdev->dev, &io_res, &ctl_res, irq_res,
				     reg_shift, pio_mask, &pata_platform_sht);
}

static struct of_device_id pata_of_platform_match[] = {
	{ .compatible = "ata-generic", },
	{ },
};
MODULE_DEVICE_TABLE(of, pata_of_platform_match);

static struct platform_driver pata_of_platform_driver = {
	.driver = {
		.name = DRV_NAME,
		.of_match_table = pata_of_platform_match,
	},
	.probe		= pata_of_platform_probe,
	.remove		= ata_platform_remove_one,
};

module_platform_driver(pata_of_platform_driver);

MODULE_DESCRIPTION("OF-platform PATA driver");
MODULE_AUTHOR("Anton Vorontsov <avorontsov@ru.mvista.com>");
MODULE_LICENSE("GPL");


_GL_CONTEXT_MINOR_VERSION = 18,
        SDL_GL_CONTEXT_EGL = 19,
        SDL_GL_CONTEXT_FLAGS = 20,
        SDL_GL_CONTEXT_PROFILE_MASK = 21,
        SDL_GL_SHARE_WITH_CURRENT_CONTEXT = 22
    }

    pub enum SDL_GLprofile {
        SDL_GL_CONTEXT_PROFILE_CORE = 0x0001,
        SDL_GL_CONTEXT_PROFILE_COMPATIBILITY = 0x0002,
        SDL_GL_CONTEXT_PROFILE_ES = 0x0004
    }

    //SDL_video.h
    extern "C" {
        pub fn SDL_GetNumVideoDrivers() -> c_int;
        pub fn SDL_GetVideoDriver(index: c_int) -> *c_char;
        pub fn SDL_VideoInit(driver_name: *c_char) -> c_int;
        pub fn SDL_VideoQuit();
        pub fn SDL_GetCurrentVideoDriver() -> *c_char;
        pub fn SDL_GetNumVideoDisplays() -> c_int;
        pub fn SDL_GetDisplayName(displayIndex: c_int) -> *c_char;
        pub fn SDL_GetDisplayBounds(displayIndex: c_int, rect: *SDL_Rect) -> c_int;
        pub fn SDL_GetNumDisplayModes(displayIndex: c_int) -> c_int;
        pub fn SDL_GetDisplayMode(displayIndex: c_int, modeIndex: c_int, mode: *SDL_DisplayMode) -> c_int;
        pub fn SDL_GetDesktopDisplayMode(displayIndex: c_int, mode: *SDL_DisplayMode) -> c_int;
        pub fn SDL_GetCurrentDisplayMode(displayIndex: c_int, mode: *SDL_DisplayMode) -> c_int;
        pub fn SDL_GetClosestDisplayMode(displayIndex: c_int, mode: *SDL_DisplayMode, closest: *SDL_DisplayMode) -> *SDL_DisplayMode;
        pub fn SDL_GetWindowDisplayIndex(window: *SDL_Window) -> c_int;
        pub fn SDL_SetWindowDisplayMode(window: *SDL_Window, mode: *SDL_DisplayMode) -> c_int;
        pub fn SDL_GetWindowDisplayMode(window: *SDL_Window, mode: *SDL_DisplayMode) -> c_int;
        pub fn SDL_GetWindowPixelFormat(window: *SDL_Window) -> uint32_t;
        pub fn SDL_CreateWindow(title: *c_char, x: c_int, y: c_int, w: c_int, h: c_int, flags: uint32_t) -> *SDL_Window;
        pub fn SDL_CreateWindowFrom(data: *c_void) -> *SDL_Window;
        pub fn SDL_GetWindowID(window: *SDL_Window) -> uint32_t;
        pub fn SDL_GetWindowFromID(id: uint32_t) -> *SDL_Window;
        pub fn SDL_GetWindowFlags(window: *SDL_Window) -> uint32_t;
        pub fn SDL_SetWindowTitle(window: *SDL_Window, title: *c_char);
        pub fn SDL_GetWindowTitle(window: *SDL_Window) -> *c_char;
        pub fn SDL_SetWindowIcon(window: *SDL_Window, icon: *SDL_Surface);
        pub fn SDL_SetWindowData(window: *SDL_Window, name: *c_char, userdata: *c_void) -> *c_void;
        pub fn SDL_GetWindowData(window: *SDL_Window, name: *c_char) -> *c_void;
        pub fn SDL_SetWindowPosition(window: *SDL_Window, x: c_int, y: c_int);
        pub fn SDL_GetWindowPosition(window: *SDL_Window, x: *c_int, y: *c_int);
        pub fn SDL_SetWindowSize(window: *SDL_Window, w: c_


集群zk地址，将从该zk中读取topic metadata
--destAk 目标实例ak
--destSk 目标实例sk
--destRegionId 目标实例所在regionId，如cn-hangzhou, cn-beijing
--destInstanceId 目标实例id
--commit 可选参数。不加--commit时，仅在日志中打印将要迁移的topic。确认无误后，再次执行命令并增加参数--commit，topic metadata会实际迁移到消息队列kafka。
```

#### 消息队列Kafka——>消息队列Kafka

```
java -jar kafka-migration.jar TopicMigrationFromAliyun --sourceAk {sourceAk} --sourceSk {sourceSk} --sourceRegionId {sourceRegionId} --sourceInstanceId {sourceInstanceId} --destAk {destAk} --destSk {destSk} --destRegionId {destRegionId} --destInstanceId {destInstanceId}

```

参数说明：
```
--sourceAk 源实例ak
--sourceSk 源实例sk
--sourceRegionId 源实例所在regionId，如cn-hangzhou, cn-beijing
--sourceInstanceId 源实例id
--destAk 目标实例ak
--destSk 目标实例sk
--destRegionId 目标实例所在regionId，如cn-hangzhou, cn-beijing
--destInstanceId 目标实例id
--commit 可选参数。不加--commit时，仅在日志中打印将要迁移的topic。确认无误后，再次执行命令并增加参数--commit，topic metadata会实际迁移到消息队列kafka。
```

#### 验证Topic Metadata迁移成功

建议迁移时，先不加--commit参数执行一次，确认要迁移的topic信息无误。
迁移完成后，可以在Kafka控制台查看来源kafka集群中的topic是否都已经成功创建。

### 迁移Group Metadata到阿里云消息队列Kafka

#### 简介

根据来源集群中的ConsumerGroup Metadata，在阿里云消息队列Kafka的控制台中创建相应ConsumerGroup。注意：迁移的内容仅为ConsumerGroup基本信息，具体消费的topic及位点信息不会迁移。
本Demo支持以下两种形式ConsumerGroup Meta迁移：
1. 用户自建集群Topic：__consumer_offsets中ConsumerGroup信息——>消息队列Kafka；
2. 消息队列Kafka——>消息队列Kafka；

#### 用户自建集群Topic：__consumer_offsets中ConsumerGroup信息——>消息队列Kafka

```
java -jar kafka-migration.jar ConsumerGroupMigrationFromTopic --propertiesPath {propertiesPath} --destAk {destAk} --destSk {destSk} --destRegionId {destRegionId} --destInstanceId {destInstanceId}

```

参数说明：
```
--propertiesPath 自建集群配置文件，用于构造KafkaConsumer，从自建集群获取__consumer_offsets中消息
--destAk 目标实例ak
--destSk 目标实例sk
--destRegionId 目标实例所在regionId，如cn-hangzhou, cn-beijing
--destInstanceId 目标实例id
--c


o, "test_Adios_mydata.bp", Adios.mode_write)

   local nxVec, nyVec = Lin.IntVec(1), Lin.IntVec(1)
   nxVec[1], nyVec[1] = cells[1], cells[2]
   local ad_err = Adios.put(ad_engine, ad_var_nx  , nxVec:data(), Adios.mode_deferred)
   local ad_err = Adios.put(ad_engine, ad_var_ny  , nyVec:data(), Adios.mode_deferred)
   local ad_err = Adios.put(ad_engine, ad_var_temp, temp:data(), Adios.mode_deferred)

   local _ = Adios.close(ad_engine)

   Adios.finalize(ad)
end

function test_1rA(comm)
   local nproc, rank = Mpi.Comm_size(comm), Mpi.Comm_rank(comm)

   if nproc > 1 then
      log("Not running test_1 as number of procs > 1")
      return
   end

   local ad = Adios.init_mpi(comm)
   local ad_io = Adios.declare_io(ad, "gkylread")

   local dim = 2
   local cells = {10, 20}
   local lower = {-math.pi, -math.pi}
   local upper = { math.pi,  math.pi}

   -- MF 2023/10/10: Inquiring variables or getting the list of available variables needs
   -- to be done with mode_readRandomAccess or within a Begin/End step block, see issue 3843 in
   -- in the adios2 github: https://github.com/ornladios/ADIOS2/issues/3843
   local ad_engine = Adios.open(ad_io, "test_Adios_mydata.bp", Adios.mode_readRandomAccess)

   local ad_var_nx   = Adios.inquire_variable(ad_io, "NX")
   local ad_var_ny   = Adios.inquire_variable(ad_io, "NY")
   local ad_var_temp = Adios.inquire_variable(ad_io, "temperature")
   local ad_err = Adios.set_selection(ad_var_temp, 1, {0}, {cells[1]})

   local nxVec, nyVec, temp = Lin.IntVec(1), Lin.IntVec(1), Lin.Vec(cells[1])
   local ad_err = Adios.get(ad_engine, ad_var_nx  , nxVec:data(), Adios.mode_sync)
   local ad_err = Adios.get(ad_engine, ad_var_ny  , nyVec:data(), Adios.mode_sync)
   local ad_err = Adios.get(ad_engine, ad_var_temp, temp:data() , Adios.mode_sync)

   local _ = Adios.close(ad_engine)

   assert_equal(10, nxVec[1], "Checking NX")
   assert_equal(20, nyVec[1], "Checking NY")
   for i = 1, cells[1] do
      assert_equal(i*1.1, temp[i], "Checking temperature")
   end

   Adios.finalize(ad)
end

function test_1rB(comm)
   local nproc, rank = Mpi.Comm_size(comm), Mpi.Comm_rank(comm)

   if nproc > 1 then
      log("Not running test_1 as number of procs > 1")
      return
   end

   local ad = Adios.init_mpi(comm)
   local ad_io = Adios.declare_io(ad, "gkylread")

   local dim = 2
   local cells = {10, 20}
   local lower = {-math.pi, -math.pi}
   local upper = { math.pi,  math.pi}

   -- MF 2023/10/10: Inquiring variables or getting the list of available variables needs
   -- to be done with mode_readRandomAccess or within a Begin/End step block, see issue 3843 in
   -- in the adios2 github: https://github.com/ornladios/ADI


using UnityEngine;

namespace UnityEditor.Timeline
{
    class TimeAreaAutoPanner
    {
        readonly WindowState m_State;
        readonly TimelineWindow m_Window;
        readonly Rect m_ViewRect;

        const float k_PixelDistanceToMaxSpeed = 100.0f;
        const float k_MaxPanSpeed = 30.0f;

        public TimeAreaAutoPanner(WindowState state)
        {
            m_State = state;
            m_Window = m_State.GetWindow();

            var shownRange = m_State.timeAreaShownRange;
            var trackViewBounds = m_Window.sequenceRect;
            m_ViewRect = Rect.MinMaxRect(m_State.TimeToPixel(shownRange.x), trackViewBounds.yMin,
                m_State.TimeToPixel(shownRange.y), trackViewBounds.yMax);
        }

        public void OnGUI(Event evt)
        {
            if (evt.type != EventType.Layout)
                return;

            var hFactor = 0.0f;
            var vFactor = 0.0f;

            bool horizontalPan = GetPanFactor(evt.mousePosition.x, m_ViewRect.xMin, m_ViewRect.xMax, out hFactor);
            bool verticalPan = GetPanFactor(e


  esp[8]: from
  //  esp[12]: string

  // Make sure first argument is a string.
  __ mov(eax, Operand(esp, 3 * kPointerSize));
  STATIC_ASSERT(kSmiTag == 0);
  __ JumpIfSmi(eax, &runtime);
  Condition is_string = masm->IsObjectStringType(eax, ebx, ebx);
  __ j(NegateCondition(is_string), &runtime);

  // eax: string
  // ebx: instance type

  // Calculate length of sub string using the smi values.
  __ mov(ecx, Operand(esp, 1 * kPointerSize));  // To index.
  __ JumpIfNotSmi(ecx, &runtime);
  __ mov(edx, Operand(esp, 2 * kPointerSize));  // From index.
  __ JumpIfNotSmi(edx, &runtime);
  __ sub(ecx, edx);
  __ cmp(ecx, FieldOperand(eax, String::kLengthOffset));
  Label not_original_string;
  // Shorter than original string's length: an actual substring.
  __ j(below, &not_original_string, Label::kNear);
  // Longer than original string's length or negative: unsafe arguments.
  __ j(above, &runtime);
  // Return original string.
  Counters* counters = isolate()->counters();
  __ IncrementCounter(counters->sub_string_native(), 1);
  __ ret(3 * kPointerSize);
  __ bind(&not_original_string);

  Label single_char;
  __ cmp(ecx, Immediate(Smi::FromInt(1)));
  __ j(equal, &single_char);

  // eax: string
  // ebx: instance type
  // ecx: sub string length (smi)
  // edx: from index (smi)
  // Deal with different string types: update the index if necessary
  // and put the underlying string into edi.
  Label underlying_unpacked, sliced_string, seq_or_external_string;
  // If the string is not indirect, it can only be sequential or external.
  STATIC_ASSERT(kIsIndirectStringMask == (kSlicedStringTag & kConsStringTag));
  STATIC_ASSERT(kIsIndirectStringMask != 0);
  __ test(ebx, Immediate(kIsIndirectStringMask));
  __ j(zero, &seq_or_external_string, Label::kNear);

  Factory* factory = isolate()->factory();
  __ test(ebx, Immediate(kSlicedNotConsMask));
  __ j(not_zero, &sliced_string, Label::kNear);
  // Cons string.  Check whether it is flat, then fetch first part.
  // Flat cons strings have an empty second part.
  __ cmp(FieldOperand(eax, ConsString::kSecondOffset),
         factory->empty_string());
  __ j(not_equal, &runtime);
  __ mov(edi, FieldOperand(eax, ConsString::kFirstOffset));
  // Update instance type.
  __ mov(ebx, FieldOperand(edi, HeapObject::kMapOffset));
  __ movzx_b(ebx, FieldOperand(ebx, Map::kInstanceTypeOffset));
  __ jmp(&underlying_unpacked, Label::kNear);

  __ bind(&sliced_string);
  // Sliced string.  Fetch parent and adjust start index by offset.
  __ add(edx, FieldOperand(eax, SlicedString::kOffsetOffset));
  __ mov(edi, FieldOperand(eax, SlicedString::kParentOffset));
  // Update instance type.
  __ mov(ebx, FieldOperand(edi, HeapObject::kMapOffset));
  __ movzx_b(ebx, FieldOperand(ebx, Map::kInstanceTypeOffset));
  __ jmp(&underlying_unpacked, Label::kNear);

  __ bind(&seq_or_external_string);
  // Sequential or external string.  Just move string to the expected register.
  __ mov(edi, eax);

  __ bind(&underlying_unpacked);

  if (FLAG_string_slices) {
    Label copy_routine;
    // edi: unde


": [] }] })(props);
}
function BiSolidConfused(props) {
  return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 24 24" }, "child": [{ "tag": "path", "attr": { "d": "M12 2C6.486 2 2 6.486 2 12s4.486 10 10 10 10-4.486 10-10S17.514 2 12 2zm-5 8.5a1.5 1.5 0 1 1 3.001.001A1.5 1.5 0 0 1 7 10.5zm1.124 6.492-.248-1.984 8-1 .248 1.984-8 1zm7.369-5.006a1.494 1.494 0 1 1 .001-2.987 1.494 1.494 0 0 1-.001 2.987z" }, "child": [] }] })(props);
}
function BiSolidContact(props) {
  return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 24 24" }, "child": [{ "tag": "path", "attr": { "d": "M21 2H6a2 2 0 0 0-2 2v3H2v2h2v2H2v2h2v2H2v2h2v3a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1V3a1 1 0 0 0-1-1zm-8 2.999c1.648 0 3 1.351 3 3A3.012 3.012 0 0 1 13 11c-1.647 0-3-1.353-3-3.001 0-1.649 1.353-3 3-3zM19 18H7v-.75c0-2.219 2.705-4.5 6-4.5s6 2.281 6 4.5V18z" }, "child": [] }] })(props);
}
function BiSolidConversation(props) {
  return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 24 24" }, "child": [{ "tag": "path", "attr": { "d": "M13 14h3.5c.827 0 1.5-.673 1.5-1.5v-9c0-.827-.673-1.5-1.5-1.5h-13C2.673 2 2 2.673 2 3.5V18l5.333-4H13zm-9-.1.154-.016L4 14v-.1z" }, "child": [] }, { "tag": "path", "attr": { "d": "M20.5 8H20v6.001c0 1.1-.893 1.993-1.99 1.999H8v.5c0 .827.673 1.5 1.5 1.5h7.167L22 22V9.5c0-.827-.673-1.5-1.5-1.5z" }, "child": [] }] })(props);
}
function BiSolidCookie(props) {
  return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 24 24" }, "child": [{ "tag": "path", "attr": { "d": "M21.598 11.064a1.006 1.006 0 0 0-.854-.172A2.938 2.938 0 0 1 20 11c-1.654 0-3-1.346-3.003-2.938.005-.034.016-.134.017-.168a.998.998 0 0 0-1.254-1.006A3.002 3.002 0 0 1 15 7c-1.654 0-3-1.346-3-3 0-.217.031-.444.099-.716a1 1 0 0 0-1.067-1.236A9.956 9.956 0 0 0 2 12c0 5.514 4.486 10 10 10s10-4.486 10-10c0-.049-.003-.097-.007-.16a1.004 1.004 0 0 0-.395-.776zM8.5 6a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3zm-2 8a1.5 1.5 0 1 1 0-3


 []string
	name             string
	serialVersionUID int64
	classDescFlags   byte
	fields           []Field
}

func (class ProxyClassObject) Serialize(handles *Handles) []byte {
	buff := new(bytes.Buffer)
	buff.WriteByte(TC_OBJECT)
	buff.WriteByte(TC_PROXYCLASSDESC)
	handles.Add(TC_PROXYCLASSDESC, class)

	binary.Write(buff, binary.BigEndian, int32(len(class.interfaces)))

	for _, name := range class.interfaces {
		binary.Write(buff, binary.BigEndian, int16(len(name))) // string length
		buff.WriteString(name)
	}

	// classAnnotations, classAnnotations always is null
	buff.WriteByte(TC_ENDBLOCKDATA)

	// superClassDesc
	{
		buff.WriteByte(TC_CLASSDESC)

		// class name
		binary.Write(buff, binary.BigEndian, int16(len(class.name)))
		buff.WriteString(class.name)

		// serialVersionUID
		binary.Write(buff, binary.BigEndian, class.serialVersionUID)

		handles.Add(TC_CLASSDESC, class)

		// classDescFlags
		buff.WriteByte(class.classDescFlags)

		// field desc
		writeFieldsDesc(buff, handles, class.fields)

		// classAnnotations, always null
		buff.WriteByte(TC_ENDBLOCKDATA)

		// superClassDesc, always null
		buff.WriteByte(TC_NULL)
	}

	handles.Add(TC_OBJECT, class)
	// class data
	// super fields data
	for _, f := range class.fields {
		buff.Write(serialize(handles, f.value))
	}

	return buff.Bytes()
}

func (class ProxyClassObject) hash(kind int) uint32 {
	hash := fnv.New32a()
	switch kind {
	case TC_PROXYCLASSDESC:
		hash.Write([]byte(class.name))
		binary.Write(hash, binary.BigEndian, class.serialVersionUID)
	case TC_OBJECT:
		hash.Write([]byte{TC_PROXYCLASSDESC})
		hash.Write([]byte(class.name))
		binary.Write(hash, binary.BigEndian, class.serialVersionUID)
	}
	return hash.Sum32()
}

type ArrayObject struct {
	name             string
	serialVersionUID int64
	classDescFlags   byte
	values           []interface{}
	annotations      []interface{}
}

func (class ArrayObject) Serialize(handles *Handles) []byte {
	buff := new(bytes.Buffer)
	if handle, ok := handles.Get(TC_ARRAY, class); ok {
		buff.WriteByte(TC_REFERENCE)
		binary.Write(buff, binary.BigEndian, handle)
		return buff.Bytes()
	}
	buff.WriteByte(TC_ARRAY)

	// only class desc part
	if handle, ok := handles.Get(TC_CLASSDESC, class); ok {
		buff.WriteByte(TC_REFERENCE)
		binary.Write(buff, binary.BigEndian, handle)
	} else {
		buff.WriteByte(TC_CLASSDESC)
		// class name
		binary.Write(buff, binary.BigEndian, uint16(len(class.name)))
		buff.WriteString(class.name)

		// serialVersionUID
		binary.Write(buff, binary.BigEndian, class.serialVersionUID)

		// classDescFlags
		buff.WriteByte(class.classDescFlags)

		// newHandle
		handles.Add(TC_CLASSDESC, class)

		// fields count, always 0
		binary.Write(buff, binary.BigEndian, int16(0))

		// classAnnotations, always null
		buff.WriteByte(TC_ENDBLOCKDATA)

		// superClassDes, always null
		buff.WriteByte(TC


]
}
// Copyright 2016 DeepFabric, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.

package raftstore

import (
	"fmt"
	"time"
)

// Cfg for raftstore
type Cfg struct {
	Addr                      string
	DataPath                  string
	OptionPath                string
	CellCapacity              uint64
	DurationHeartbeatStore    time.Duration
	DurationHeartbeatCell     time.Duration
	DurationSplitCheck        time.Duration
	DurationCompact           time.Duration
	DurationReportMetric      time.Duration
	DurationRaftTick          time.Duration
	DurationRetrySentSnapshot time.Duration
	LimitPeerDownDuration     time.Duration
	LimitCompactCount         uint64
	LimitCompactBytes         uint64
	LimitCompactLag           uint64
	LimitRaftMsgCount         int
	LimitRaftMsgBytes         uint64
	LimitRaftEntryBytes       uint64
	LimitSnapChunkBytes       uint64
	LimitSnapChunkRate        uint64
	LimitConcurrencyWrite     uint64
	LimitNemoInstance         int
	ThresholdCompact          uint64
	ThresholdSplitCheckBytes  uint64
	ThresholdRaftElection     int
	ThresholdRaftHeartbeat    int
	BatchSizeProposal         uint64
	BatchSizeSent             uint64
	WorkerCountSent           uint64
	WorkerCountSentSnap       uint64
	WorkerCountApply          uint64
	EnableSyncRaftLog         bool
	EnableMetricsRequest      bool
}

// NewCfg return default cfg
func NewCfg() *Cfg {
	return &Cfg{}
}

func (c *Cfg) getSnapDir() string {
	return fmt.Sprintf("%s/%s", c.DataPath, getSnapDirName())
}

func getSnapDirName() string {
	return "snap"
}
// Copyright 2016 DeepFabric, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.

package redis

import (
	"testing"
	"time"

	"github.com/fagongzi/goetty"
	gredis "github.com/fagongzi/goetty/protocol/redis"
	"github.com/garyburd/redigo/redis"
	. "github.com/pingcap/check"
)

var _ = Suite(&testRedisSuite{})

func TestRedis(t *testing.T) {
	TestingT(t)
}

type testRedisSuite struct {
	svr *goetty.Server
}

func (s *testRedisSuite) SetUpSuite(c *C) {
	s.svr = goetty.NewServer(":6379",
		goetty.WithServerDecoder(Decoder),
		goetty.WithServerEncoder(Encoder),
		goetty.WithServerReadBufSize(1024),
		goetty.WithServerWriteBufSize(1024))
	go s.svr.Start(s.doConnection)
	select {
	case <-s.svr.Started():
	case <-time.After(time.Second):
		c.Fa


       self.distance[j][i] = distance
        np.save(self.distance_matrix_path, self.distance)
        self._logger.info("finish constructing distance matrix")

    def construct_gravity_matrix(self):
        """
        创建gravity matrix

        :return:
        """

        # 遗传算法求解工作日的beta
        problem = GravityMatrix(self.zone_num, self.device, self.arrive_num_weekday, self.leave_num_weekday, self.T_weekday, self.distance)
        algorithm = ea.soea_SEGA_templet(
            problem,
            ea.Population(Encoding='RI', NIND=self.NIND),
            MAXGEN=self.max_gen,
            trappedValue=1e-6,
            maxTrappedCount=10,
            logTras=0,
        )
        res = ea.optimize(
            algorithm,
            verbose=True,
            drawing=0,
            outputMsg=False,
            drawLog=False,
            saveFlag=False
        )
        beta_weekday = res['Vars'][0][0]

        # 遗传算法求解周末的beta
        problem = GravityMatrix(self.zone_num, self.device, self.arrive_num_weekend, self.leave_num_weekend, self.T_weekend, self.distance)
        algorithm = ea.soea_SEGA_templet(
            problem,
            ea.Population(Encoding='RI', NIND=self.NIND),
            MAXGEN=self.max_gen,
            trappedValue=1e-6,
            maxTrappedCount=10,
            logTras=0,
        )
        res = ea.optimize(
            algorithm,
            verbose=True,
            drawing=0,
            outputMsg=False,
            drawLog=False,
            saveFlag=False
        )
        beta_weekend = res['Vars'][0][0]

        # 求解工作日的G
        F = np.exp((-beta_weekday) * self.distance)
        G_weekday = (F * self.arrive_num_weekday) / np.matmul(F, self.arrive_num_weekday.reshape(self.zone_num, 1))

        # 求解周末的G
        F = np.exp((-beta_weekend) * self.distance)
        G_weekend = (F * self.arrive_num_weekend) / np.matmul(F, self.arrive_num_weekend.reshape(self.zone_num, 1))

        # 上述求解的G维度为z*z，如果要转化为z*e，还需要根据每个event进行筛选，得到z*e维度的G*矩阵
        self.G_matrix = np.zeros((self.zone_num, self.mobility_event_num))
        for zone_id in range(self.zone_num):
            for mobility_event in self.mobility_events.keys():
                mb_id = self.mobility_events[mobility_event][1]
                mb_type = mobility_event[2]
                mb_sta = mobility_event[3]
                mb_zone_id = mobility_event[0]
                if mb_type == 1:
                    if mb_sta == 'o':
                        self.G_matrix[zone_id][mb_id] = G_weekday[mb_zone_id][zone_id]
                    else:
                        self.G_matrix[zone_id][mb_id] = G_weekday[zone_id][mb_zone_id]
                else:
                    if mb_sta == 'o':
                        self.G_matrix[zone_id][mb_id] = G_weekend[mb_zone_id][zone_id]
                    else:
                        self.G_matrix[zone_id][mb_id] = G_weekend[zone_id][mb_zone_id]

        # 保存G matrix
        if not os.path.exists(self.G_matrix_path):
            np.save(self.G_matrix_path, self.G_matrix)

        self._logger.info("finish constructing gravity matrix, beta_wd is {}, beta_we is {}".format(str(beta_weekday), str(beta_weekend)))

    def construct_ppmi_matrix(self):
        """
        创建ppmi矩阵

        :return:
        """
        if os.path.exists(self.ppmi_matrix_path):
            self.ppmi_matrix = np.load(self.ppmi_matrix_path)
            self._logger.info("finish constructing ppmi matrix")
            return
        self.ppmi_matrix = np.zeros((self.zone_num, len(self.mobility_events)), dtype=np.float32)
        for region_id in self.co_occurs.keys():
            tmp_mobility_events = self.co_occurs[region_id].keys()
            for mobility_event in tmp_mobility_events:
                mb_id = self.mobility_events[mobility_event][1]
                self.ppmi_matrix[region_id][mb_id] = max(0, np.log2(
                    (self.co_occurs[region_id][mobility_event] * self.co_occurs_num) /
                    (self.zones[region_id] * self.mobility_events[mobility_event][0])
                ))
        np.save(self.ppmi_matrix_path, self.ppmi_matrix)
        self._logger.info("finish constructing ppmi matrix")

    def get_data(self):
        return None, None, None

    def get_data_feature(self):
        """
        返回一个 dict，包含数据集的相关特征

        Returns:
            dict: 包含数据集的相关特征的字典
        """
        return {'ppmi_matrix': self.ppmi_matrix, 'G_matrix': self.G_matrix,
                'region_num': self.zon


Serializer::serialize(const NDArray<double> &arr);
template EXPORTISMRMRD void ProtocolSerializer::serialize(const NDArray< std::complex<float> > &arr);
template EXPORTISMRMRD void ProtocolSerializer::serialize(const NDArray< std::complex<double> > &arr);

template EXPORTISMRMRD void ProtocolDeserializer::deserialize(NDArray<uint16_t> &arr);
template EXPORTISMRMRD void ProtocolDeserializer::deserialize(NDArray<uint32_t> &arr);
template EXPORTISMRMRD void ProtocolDeserializer::deserialize(NDArray<int16_t> &arr);
template EXPORTISMRMRD void ProtocolDeserializer::deserialize(NDArray<int32_t> &arr);
template EXPORTISMRMRD void ProtocolDeserializer::deserialize(NDArray<float> &arr);
template EXPORTISMRMRD void ProtocolDeserializer::deserialize(NDArray<double> &arr);
template EXPORTISMRMRD void ProtocolDeserializer::deserialize(NDArray< std::complex<float> > &arr);
template EXPORTISMRMRD void ProtocolDeserializer::deserialize(NDArray< std::complex<double> > &arr);

} // namespace ISMRMRD
/**
 * @file qb/core/tests/benchmark/bm-ping-pong.cpp
 * @brief Ping-pong throughput benchmark for the QB Actor Framework
 *
 * This file contains benchmark tests measuring the throughput of ping-pong communication
 * patterns in the QB Actor Framework with different event types (tiny, big, and
 * dynamic). It tests how efficiently actors can exchange messages with various sizes and
 * complexity.
 *
 * @author qb - C++ Actor Framework
 * @copyright Copyright (c) 2011-2025 qb - isndev (cpp.actor)
 * 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.
 * @ingroup Core
 */

#include <benchmark/benchmark.h>
#include <qb/actor.h>
#include <qb/main.h>

#ifdef NDEBUG
#define MAX_BENCHMARK_ITERATION 10
#define SHIFT_NB_EVENT 15
#else
#define SHIFT_NB_EVENT 4
#define MAX_BENCHMARK_ITERATION 1
#endif

struct TinyEvent : qb::Event {
    uint64_t _ttl;
    explicit TinyEvent(uint64_t y)
        : _ttl(y) {}
};

struct BigEvent : qb::Event {
    uint64_t _ttl;
    uint64_t padding[127];
    explicit BigEvent(uint64_t y)
        : _ttl(y)
        , padding() {}
};

struct DynamicEvent : qb::Event {
    uint64_t         _ttl;
    std::vector<int> vec;
    explicit DynamicEvent(uint64_t y)
        : _ttl(y)
        , vec(512, 8) {}
};

template <typename TestEvent>
class PongActor final : public qb::Actor {
public:
    bool
    onInit() final {
        registerEvent<TestEvent>(*this);
        return true;
    }

    void
    on(TestEvent &event) {
        --event._ttl;
        reply(event);
    }
};

template <typename TestEvent>
class PingActor final : public qb::Actor {
    const uint64_t    max_sends;
    const qb::ActorId a


.chatcomponents.ChatComponents
import io.github.ayfri.kore.arguments.chatcomponents.PlainTextComponent
import io.github.ayfri.kore.arguments.chatcomponents.textComponent
import io.github.ayfri.kore.arguments.colors.BossBarColor
import io.github.ayfri.kore.arguments.colors.Color
import io.github.ayfri.kore.arguments.types.EntityArgument
import io.github.ayfri.kore.arguments.types.literals.bool
import io.github.ayfri.kore.arguments.types.literals.int
import io.github.ayfri.kore.arguments.types.literals.literal
import io.github.ayfri.kore.arguments.types.resources.BossBarArgument
import io.github.ayfri.kore.functions.Function
import io.github.ayfri.kore.serializers.LowercaseSerializer
import io.github.ayfri.kore.utils.asArg
import kotlinx.serialization.Serializable

@Serializable(BossBarGetResult.Companion.BossBarActionSerializer::class)
enum class BossBarGetResult {
	MAX,
	PLAYERS,
	VALUE,
	VISIBLE;

	companion object {
		data object BossBarActionSerializer : LowercaseSerializer<BossBarGetResult>(entries)
	}
}

@Serializable(BossBarStyle.Companion.BossBarStyleSerializer::class)
enum class BossBarStyle {
	NOTCHED_6,
	NOTCHED_10,
	NOTCHED_12,
	NOTCHED_20,
	PROGRESS;

	companion object {
		data object BossBarStyleSerializer : LowercaseSerializer<BossBarStyle>(entries)
	}
}

class BossBar(private val fn: Function, val id: BossBarArgument) {
	fun add(displayName: ChatComponents) = fn.addLine(command("bossbar", literal("add"), id, displayName.asJsonArg()))
	fun add(displayName: String, color: Color? = null, block: PlainTextComponent.() -> Unit = {}) =
		fn.addLine(command("bossbar", literal("add"), id, textComponent(displayName) {
			if (color != null) this.color = color
			block()
		}))

	fun getMax() = fn.addLine(command("bossbar", literal("get"), id, literal("max")))
	fun getPlayers() = fn.addLine(command("bossbar", literal("get"), id, literal("players")))
	fun getValue() = fn.addLine(command("bossbar", literal("get"), id, literal("value")))
	fun getVisible() = fn.addLine(command("bossbar", literal("get"), id, literal("visible")))

	fun remove() = fn.addLine(command("bossbar", literal("remove"), id))
	fun setColor(color: BossBarColor) = fn.addLine(command("bossbar", literal("set"), id, literal("color"), color))
	fun setMax(max: Int) = fn.addLine(command("bossbar", literal("set"), id, literal("max"), int(max)))
	fun setName(name: String) = fn.addLine(command("bossbar", literal("set"), id, literal("name"), literal(name)))
	fun setPlayers(targets: EntityArgument) = fn.addLine(command("bossbar", literal("set"), id, literal("players"), targets))
	fun setStyle(style: BossBarStyle) = fn.addLine(command("bossbar", literal("set"), id, literal("style"), literal(style.asArg())))
	fun setValue(value: Int) = fn.addLine(command("bossbar", literal("set"), id, literal("value"), int(value)))
	fun setVisible(visible: Boolean) = fn.addLine(command("bossbar", literal("set"), id, literal("visible"), bool(visible)))
}

class BossBars(private val fn: Function) {
	fun add(id: String, namespace: String = "minecraft", displayName: ChatComponents) =
		fn.addLine(command("bo


a);
      expect(a).toEqual(b);
    }
    {
      let o1 = { 1: 4, 6: 3 };
      let o2 = { 1: 4, 6: 3 };
      expect(o1).toEqual(o2);
      expect(o1).toStrictEqual(o2);
    }
    {
      let o1 = { 1: 4, 6: 2 };
      let o2 = { 1: 4, 6: 3 };
      expect(o1).not.toEqual(o2);
      expect(o1).not.toStrictEqual(o2);
    }

    {
      let o1 = { a: 1, 3: 0 };
      let o2 = { a: 1, 3: 0 };
      expect(o1).toEqual(o2);
      expect(o1).toStrictEqual(o2);
    }
    {
      let o1 = { a: 1, 3: 0 };
      let o2 = { a: 1, 3: 1 };
      expect(o1).not.toEqual(o2);
      expect(o1).not.toStrictEqual(o2);
    }
    {
      let o1 = { a: {}, 4: { b: 3, c: { 9: 2 } } };
      let o2 = { a: {}, 4: { b: 3, c: { 9: 2 } } };
      expect(o1).toEqual(o2);
      expect(o1).toStrictEqual(o2);
    }
    {
      let o1 = { a: {}, 4: { b: 3, c: { 9: 2 } } };
      let o2 = { a: {}, 4: { b: 3, c: { 9: 3 } } };
      expect(o1).not.toEqual(o2);
      expect(o1).not.toStrictEqual(o2);
    }

    {
      let o1 = { a: 1, b: 2, c: 3 };
      let o2 = { a: 1, b: 2, c: 3, 0: 1 };
      expect(o1).not.toEqual(o2);
      expect(o1).not.toStrictEqual(o2);
    }

    {
      let o1 = { a: 1, b: 2, c: 3, 0: 1 };
      let o2 = { a: 1, b: 2, c: 3 };
      expect(o1).not.toEqual(o2);
      expect(o1).not.toStrictEqual(o2);
    }

    expect("hello").toEqual("hello");
    const s1 = Symbol("test1");
    const s2 = Symbol("test2");

    expect({ a: 1, b: 2 }).toEqual({ b: 2, a: 1 });
    expect([1, 2, 3]).toEqual([1, 2, 3]);
    expect({ a: 1, b: 2 }).not.toEqual({ b: 2, a: 1, c: 3 });
    expect([1, 2, 3]).not.toEqual([1, 2, 3, 4]);
    expect({ a: 1, b: 2, c: 3 }).not.toEqual({ a: 1, b: 2 });
    expect([1, 2, 3, 4]).not.toEqual([1, 2, 3]);

    /** @type {any} */ let a;
    /** @type {any} */ let b;
    /** @type {any} */ let c;
    /** @type {any} */ let d;

    a = [{ a: 1 }, { b: 2, c: 3, d: 4 }, { e: 5, f: 6 }];
    b = [{ a: 1 }, { b: 2, c: 3, d: 4 }, { e: 5, f: 6 }];
    expect(a).toEqual(b);
    expect(b).toEqual(a);
    a[0].a = 2;
    expect(a).


using BlotzTask.Infrastructure.Data;
using BlotzTask.Shared.Exceptions;
using BlotzTask.Modules.Tasks.Enums;
using BlotzTask.Modules.Tasks.Shared;
using System.ComponentModel.DataAnnotations;

namespace BlotzTask.Modules.Tasks.Commands.Tasks;

public class EditTaskCommand
{
    [Required]
    public int TaskId { get; init; }
    [Required]
    public required EditTaskItemDto TaskDetails { get; init; }
}

public class EditTaskCommandHandler(BlotzTaskDbContext db, ILogger<EditTaskCommandHandler> logger)
{
    public async Task<string> Handle(EditTaskCommand command, CancellationToken ct = default)
    {
        logger.LogInformation("Editing task {TaskId}", command.TaskId);

        var task = await db.TaskItems.FindAsync(command.TaskId, ct);

        if (task == null)
        {
            throw new NotFoundException($"Task with ID {command.TaskId} not found.");
        }

        TaskTimeValidator.ValidateTaskTimes(command.TaskDetails.StartTime, command.TaskDetails.EndTime, command.TaskDetails.TimeType);


我勇气并让我感受到生存意义的正是冲浪。',	'1',	'5',	'1',	'1'},
{'40220127',	'Rapids_27',	'cv/Rapids.acb',	'Rapids_27',	'4022001',	'402201',	'10',	'',	'接触3',	'',	'我在极限运动的圈子里很有名吗？……我个人对此倒是没有什么感觉啦，不过做自己喜欢的事，同时还能给人带来勇气，的确让我感到心潮澎湃。',	'',	'我在极限运动的圈子里很有名吗？……我个人对此倒是没有什么感觉啦，不过做自己喜欢的事，同时还能给人带来勇气，的确让我感到心潮澎湃。',	'1',	'2',	'1',	'1'},
{'40220128',	'Rapids_28',	'cv/Rapids.acb',	'Rapids_28',	'4022001',	'402201',	'10',	'',	'友好',	'',	'随着科技的进步，现在许多运动都发生了改变，为了让比赛更有观赏性，橄榄球允许使用动力装甲，拳击比赛融入了外骨骼技术，而我的专属冲浪板也已经是第九代产品了。',	'',	'随着科技的进步，现在许多运动都发生了改变，为了让比赛更有观赏性，橄榄球允许使用动力装甲，拳击比赛融入了外骨骼技术，而我的专属冲浪板也已经是第九代产品了。',	'41',	'',	'1',	'1'},
{'40220129',	'Rapids_29',	'cv/Rapids.acb',	'Rapids_29',	'4022001',	'402201',	'10',	'',	'喜欢',	'',	'深海之下说不定潜藏着什么不为人知的东西，在冲浪时我经常会有种被庞然巨物盯上的感觉，虽然我曾雇用源岛国际的专家下潜探索过海沟深处，但除了一些小型的变异深海生物之外，再没有其他发现。',	'',	'深海之下说不定潜藏着什么不为人知的东西，在冲浪时我经常会有种被庞然巨物盯上的感觉，虽然我曾雇用源岛国际的专家下潜探索过海沟深处，但除了一些小型的变异深海生物之外，再没有其他发现。',	'61',	'',	'1',	'1'},
{'40220130',	'Rapids_30',	'cv/Rapids.acb',	'Rapids_30',	'4022001',	'402201',	'10',	'',	'挚爱',	'',	'为了挑战一年之中最高的浪头，许多冲浪高手都会耐心在哈维夷海滩等待着，


/em>

          )

Removes up to length bytes from internal buffer of unparsed bytes, storing them in the given buffer.

Parameters

parser	The parser to remove unparsed bytes from.

buffer	The buffer to store the unparsed bytes within.

length	The length of the given buffer.

Returns

The number of bytes stored in the given buffer.

<address class="footer">
Generated by

 1.8.17
</address>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.17"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>libguac: guacamole/error-types.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

libguac
    1.4.0


nect\\Rfms\\V5\\GPBMetadata\xea\x02\x1eWayplatform::Connect::Rfms::V5b\beditionsp\xe8\a"

var file_wayplatform_connect_rfms_v5_vehicle_axle_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_wayplatform_connect_rfms_v5_vehicle_axle_proto_goTypes = []any{
	(*VehicleAxle)(nil),      // 0: wayplatform.connect.rfms.v5.VehicleAxle
	(*VehicleAxle_Tire)(nil), // 1: wayplatform.connect.rfms.v5.VehicleAxle.Tire
}
var file_wayplatform_connect_rfms_v5_vehicle_axle_proto_depIdxs = []int32{
	1, // 0: wayplatform.connect.rfms.v5.VehicleAxle.tires:type_name -> wayplatform.connect.rfms.v5.VehicleAxle.Tire
	1, // [1:1] is the sub-list for method output_type
	1, // [1:1] is the sub-list for method input_type
	1, // [1:1] is the sub-list for extension type_name
	1, // [1:1] is the sub-list for extension extendee
	0, // [0:1] is the sub-list for field type_name
}

func init() { file_wayplatform_connect_rfms_v5_vehicle_axle_proto_init() }
func file_wayplatform_connect_rfms_v5_vehicle_axle_proto_init() {
	if File_wayplatform_connect_rfms_v5_vehicle_axle_proto != nil {
		return
	}
	type x struct{}
	out := protoimpl.TypeBuilder{
		File: protoimpl.DescBuilder{
			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
			RawDescriptor: unsafe.Slice(unsafe.StringData(file_wayplatform_connect_rfms_v5_vehicle_axle_proto_rawDesc), len(file_wayplatform_connect_rfms_v5_vehicle_axle_proto_rawDesc)),
			NumEnums:      0,
			NumMessages:   2,
			NumExtensions: 0,
			NumServices:   0,
		},
		GoTypes:           file_wayplatform_connect_rfms_v5_vehicle_axle_proto_goTypes,
		DependencyIndexes: file_wayplatform_connect_rfms_v5_vehicle_axle_proto_depIdxs,
		MessageInfos:      file_wayplatform_connect_rfms_v5_vehicle_axle_proto_msgTypes,
	}.Build()
	File_wayplatform_connect_rfms_v5_vehicle_axle_proto = out.File
	file_wayplatform_connect_rfms_v5_vehicle_axle_proto_goTypes = nil
	file_wayplatform_connect_rfms_v5_vehicle_axle_proto_depIdxs = nil
}
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// 	protoc-gen-go v1.36.6
// 	protoc        (unknown)
// source: wayplatform/connect/rfms/v5/uptime_data.proto

package rfmsv5

import (
	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
	reflect "reflect"
	unsafe "unsafe"
)

const (
	// Verify that this generated code is sufficiently up-to-date.
	_ = protoimpl.


				Add to Google Calendar
				Add to Outlook Calendar
				Add to Yahoo Calendar

			👋
<button onClick="(function(){try{parent.location.reload();}catch(e){window.location.reload();}})();" title="Reload the page" data-translate="reload-page">Refresh</button>

			Meshcast publishing region: <select name="edgelist" id="edgelist" onchange="selectMeshcast(this);" title="Select a location that is closest to both you and your audience."></select>

			Full and User Documentation


}

    protected constructor(loggingMessagePrefix: (() => string) | string) {
        this.loggingMessagePrefix = loggingMessagePrefix;

        this.messageCaptureEnabled = false;

        this.capturedMessages = [];
    }

    protected abstract debugProtected(message: string): void;

    protected abstract errorProtected(message: string): void;

    protected abstract warningProtected(message: string): void;

    protected getLoggingMessagePrefix(): string {
        if (typeof this.loggingMessagePrefix === 'string') {
            return this.loggingMessagePrefix;
        }

        return this.loggingMessagePrefix();
    }

    private addMessageToCapturedMessagesOrLog(
        message: string,
        severity: CapturedMessageSeverity,
        log: (message: string) => void
    ): void {
        if (this.messageCaptureEnabled) {
            this.capturedMessages.push({
                severity: severity,
                message: message
            });
        } else {
            log(message);
        }
    }
}
function calculate(){
 let year=document.getElementById('leapyear').value;
 document.getElementById("answer").innerText = leapyearfinder(year);

}

function leapyearfinder(year){
if (year % 400 === 0){
  return'ItsALeapyear'
}
if (year % 100 === 0)  {
  return 'ItsNotALeapyear'
}
if (year % 4 === 0)  {
  return'ItsALeapyear!'
}}
import * as ts from 'typescript'
import * as vsc from 'vscode'
import { CompletionItemBuilder } from '../completionItemBuilder'
import { BaseExpressionTemplate } from './baseTemplates'

export class VarTemplate extends BaseExpressionTemplate {
  constructor (private keyword: 'var' | 'let' | 'const') {
    super()
  }

  buildCompletionItem (code: string, position: vsc.Position) {
    return CompletionItemBuilder
      .create(this.keyword, code)
      .description(`${this.keyword} name = expr`)
      .replace(this.keyword + ' ${1:name} = {{expr}}$0', position, true)
      .build()
  }
}

export const build = () => [
  new VarTemplate('var'),
  new VarTemplate('let'),
  new VarTemplate('const')
]
// enums
enum Direction {
    //% block="前"
    Forward,
    //% block="後ろ"
    Back,
    //% block="左"
    Left,
    //% block="右"
    Right
}

enum BeamsGlass {
    //% blockIdentity="blocks.block" enumval=262385 block="黄色 ステンドグラス"
    //% jres alias=YELLOW_STAINED_GLASS
    YellowStainedGlass = 262385,
    //% blockIdentity="blocks.block" enumval=327921 block="ライム ステンドグラス"
    //% jres alias=LIME_STAINED_GLASS
    LimeStainedGlass = 327921,
    //% blockIdentity="blocks.block" enumval=721137 block="青 ステンドグラス"
    //% jres alias=BLUE_STAINED_GLASS
    BlueStainedGlass = 721137,
    //% blockIdentity="blocks.block" enumval=917745 block="赤 ステンドグラス"
    //% jres alias=RED_STAINED_GLASS
    RedStainedGlass = 917745
}

// global variables
const stopBlock = BEDROCK
const stopPosition = world(35,1,0)
const locatePaintingTarget = 14
const locateGoonTarget = 113

const directions = [
    FORWARD,
    BACK,
    LEFT,
    RIGHT
];

const turns = [
    LEFT_TURN,
    RIGHT_TURN
]

//%  block="Wonder Woman" weight=200 color=#BF9B30 icon="\u2605"
namespace ww {

    /**
     * Move Wond


4-.005-.009a2.014 2.014 0 00.687-2.72c-.012-.021-.029-.038-.042-.059l.011-.006-5.52-9.562-.007.004a2.013 2.013 0 00-2.669-.72l-.004-.006-17.421 10.062V16.793h-.01a2.013 2.013 0 00-2.01-1.953c-.025 0-.048.006-.073.007v-.013h-11.04v.007a2.012 2.012 0 00-1.957 1.952h-.006v20.115l-17.45-10.075-.006.01a2.011 2.011 0 00-2.697.764c-.012.021-.018.044-.03.065l-.01-.006-5.52 9.562.005.003c-.508.94-.196 2.11.712 2.672l-.002.003.035.02.016.011.018.008 17.411 10.052-17.028 9.832a2.001 2.001 0 00-.426.18 2.013 2.013 0 00-.743 2.74l-.007.004 5.711 9.892.032-.019a2.014 2.014 0 002.55.455c.011-.006.019-.015.03-.021l.032.056 17.369-10.027v19.593a2.007 2.007 0 00-.058.461c0 1.108.895 2.005 2 2.014v.007h11.422v-.037a2.012 2.012 0 001.67-1.98c0-.012-.003-.023-.004-.035h.066V63.056l16.967 9.796c.112.105.233.202.371.282a2.016 2.016 0 002.745-.724l.005.003 5.534-9.587.003-.004.002-.004.173-.299-.03-.018a2.017 2.017 0 00-.884-2.435z"/></svg>';
  static const String at_sign =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" preserveAspectRatio="xMidYMid meet" viewBox="0 0 100 100"><path fill="currentColor" d="M87.5 50.002C87.5 29.293 70.712 12.5 50 12.5S12.5 29.293 12.5 50.002C12.5 70.712 29.288 87.5 50 87.5a37.27 37.27 0 0018.342-4.809 1.58 1.58 0 001.049-1.486c0-.622-.361-1.153-.882-1.413l.003-.004-6.529-4.002-.003.004a1.569 1.569 0 00-1.005-.369c-.238 0-.461.056-.663.149l-.014-.012A27.372 27.372 0 0150 77.561c-15.199 0-27.56-12.362-27.56-27.559C22.44 34.807 34.802 22.44 50 22.44c14.322 0 26.121 10.984 27.434 24.967C77.428 57.419 73.059 63 69.631 63c-1.847 0-3.254-1.23-3.254-3.957 0-.527.176-1.672.264-2.111l4.163-19.918h-.018c.012-.071.042-.136.042-.21a1.33 1.33 0 00-1.33-1.33h-7.23c-.657 0-1.178.485-1.286 1.112l-.025-.001-.737 3.549c-1.847-3.342-5.629-5.893-10.994-5.893-10.202 0-19.877 9.764-19.877 21.549 0 8.531 5.101 14.775


out[gen_offset + gen_idx] = gen_pos

        for stor_idx, stor_subid in enumerate(obs.storage_to_subid):
            sub_name = layout_keys[stor_subid]
            stor_sub_pos = obs.storage_to_sub_pos[stor_idx]
            stor_sub_pos /= obs.sub_info[stor_subid]
            stor_sub_pos *= 2.0 * math.pi
            stor_pos = list(copy.deepcopy(obs.grid_layout[sub_name]))
            stor_pos[0] += math.cos(stor_sub_pos) * gen_w
            stor_pos[1] += math.sin(stor_sub_pos) * gen_w
            initial_layout[stor_offset + stor_idx] = stor_pos
    else:
        initial_layout = None

    if use_initial:
        fix = list(range(obs.n_sub))
        seed = np.random.RandomState(0)
        # Use Fruchterman-Reingold algorithm
        kkl = nx.spring_layout(
            G, scale=scale, fixed=fix, pos=initial_layout, seed=seed, iterations=1000
        )
    else:
        # Use kamada_kawai algorithm
        kkl = nx.kamada_kawai_layout(G, scale=scale)

    # Convert back to our layout format
    improved_layout = {}
    for sub_idx, sub_name in enumerate(layout_keys):
        key = sub_name
        v = kkl[sub_idx]
        vx = np.round(v[0])
        vy = np.round(v[1])
        improved_layout[key] = [vx, vy]
    for load_idx, load_subid in enumerate(obs.load_to_subid):
        key = obs.name_load[load_idx]
        v = kkl[load_offset + load_idx]
        vx = np.round(v[0])
        vy = np.round(v[1])
        improved_layout[key] = [vx, vy]
    for gen_idx, gen_subid in enumerate(obs.gen_to_subid):
        key = obs.name_gen[gen_idx]
        v = kkl[gen_offset + gen_idx]
        vx = np.round(v[0])
        vy = np.round(v[1])
        improved_layout[key] = [vx, vy]
    for stor_idx, stor_subid in enumerate(obs.storage_to_subid):
        key = obs.name_storage[stor_idx]
        v = kkl[stor_offset + stor_idx]
        vx = np.round(v[0])
        vy = np.round(v[1])
        improved_layout[key] = [vx, vy]

    return improved_layout


2:

```C++
#include <tinyxml2.h>
#include <iostream>

int main() {
    tinyxml2::XMLDocument doc;
    doc.Parse("<root><message>שלום עולם!</message></root>");
    const char* content = doc.FirstChildElement("root")->FirstChildElement("message")->GetText();
    std::cout << content << std::endl;
    return 0;
}
```

פלט לדוגמא:

```
שלום עולם!
```

וכך יוצרים קובץ XML:

```C++
#include <tinyxml2.h>
#include <iostream>

int main() {
    tinyxml2::XMLDocument doc;
    auto* declaration = doc.NewDeclaration();
    doc.InsertFirstChild(declaration);
    auto* root = doc.NewElement("root");
    doc.InsertEndChild(root);
    auto* message = doc.NewElement("message");
    message->SetText("שלום עולם!");
    root->InsertEndChild(message);
    doc.SaveFile("output.xml");
    return 0;
}
```

דבר זה יוצר קובץ XML `output.xml` עם התוכן:

```xml
<?xml version="1.0"?>
<root>
    <message>שלום עולם!</message>
</root>
```

## צלילה לעומק
XML היה משמעותי בשירותי אינטרנט ואחסון נתונים מאז שנות ה-90 המאוחרות. למרות שכיום JSON ו-YAML נפוצים יותר לצורכי תצורה ואינטרופרביליות, XML עודנו משמעותי מאוד במערכות ארגוניות רבות. ניתוח XML ב-C++ יכול להרגיש קצת ישן עם ניתוח DOM/SAX ידני. לשמחתנו, ספריות כמו TinyXML-2 מפשטות את התהליך. ל-C++ אין תמיכה מובנית ב-XML; ספריות כמו TinyXML-2, pugixml, או Xerces מספקות פתרונות לאתגרים אלו.

## ראו גם
- תיעוד TinyXML-2: https://leethomason.github.io/tinyxml2/
- ספריית pugixml: https://pugixml.org/
- Xerces-C++ Parser: https://xerces.apache.org/xerces-c/
- מפרט XML של W3C: https://www.w3.org/XML/
---
date: 2024-01-20 17:38:34.010010-07:00
description: "\u05D0\u05D9\u05DA \u05DC\u05E2\u05E9\u05D5\u05EA: \u05D1\u05D3\u05D5\
  \u05D2\


net/gampad/ads?sz=400x300|640x480&iu=/75224259/AGORA-IN/Lokalne/trojmiasto/126-PAUSEAD&cust_params=pos%3D126-PAUSEAD%26dx%3D35612%26jsp%3D23%26dir%3Dtrojmiasto%26kw%3D[brandsafe]%26dystrybutor%3D[distributor_id]%26passback_id%3D[passback_id]%26domena%3D[adview_hostname]%26cb%3D[cb]%26article_id%3D25651465&url=[locationhref]&description_url=[locationhref]&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&correlator=[timestamp]';

			dfpParams.slots['150-ADBOARD-A-MOBI'] = { url: "fif.htm?adUnit=/75224259/AGORA-IN/Lokalne/trojmiasto/150-ADBOARD-A-MOBI&adUnitCode=150-ADBOARD-A-MOBI&adUnitSize=[[300,250],[320,250],[300,150],[320,150],[336,280],[320,100]]&dx=35612&dir=trojmiasto&jsp=23&article_id=25651465", sizes: [[300,250],[320,250],[300,150],[320,150],[336,280],[320,100]], autoLoad: true, autoLoadMargin: 300 };

			dfpParams.slots['201-PREMIUMBOARD-MOBI'] = { url: "fif.htm?adUnit=/75224259/AGORA-IN/Lokalne/trojmiasto/201-PREMIUMBOARD-MOBI&adUnitCode=201-PREMIUMBOARD-MOBI&adUnitSize=[[1,1]]&dx=35612&dir=trojmiasto&jsp=23&article_id=25651465", sizes: [[1,1]], autoLoad: false, autoLoadMargin: 0 };

			dfpParams.slots['104-RECTANGLE-MOBI'] = { url: "fif.htm?adUnit=/75224259/AGORA-IN/Lokalne/trojmiasto/104-RECTANGLE-MOBI&adUnitCode=104-RECTANGLE-MOBI&adUnitSize=[[300,250],[320,250],[300,150],[320,150],[336,280],[300,600],'fluid']&dx=35612&dir=trojmiasto&jsp=23&article_id=25651465", sizes: [[300,250],[320,250],[300,150],[320,150],[336,280],[300,600],'fluid'], autoLoad: true, autoLoadMargin: 300 };

			dfpParams.slots['101-TOPBOARD-MOBI'] = { url: "fif.htm?adUnit=/75224259/AGORA-IN/Lokalne/trojmiasto/101-TOPBOARD-MOBI&adUnitCode=101-TOPBOARD-MOBI&adUnitSize=[[300,250],[320,250],[300,150],[320,150],[336,280]]&dx=35612&dir=trojmiasto&jsp=23&article_id=25651465", sizes: [[300,250],[320,250],[300,150],[320,150],[336,280]], autoLoad: false, autoLoadMargin: 200 };

			dfpParams.slots['091-RELATED'] = { url: "fif.htm?adUnit=/75224259/AGORA-IN/Lokalne/trojmiasto/091-RELATED&adUnitCode=091-RELATED&adUnitSize=[[140,190],'fluid']&dx=35612&dir=trojmiasto&jsp=23&article_id=25651465", sizes: [[140,190],'fluid'], autoLoad: false, autoLoadMargin: 200 };

			dfpParams.slots['108-FOOTB


建一个表示 shim 的 `ts.SourceFile`。
   *
   */
  makeTopLevelShim(): ts.SourceFile;
}

/**
 * Generates a shim file for each original `ts.SourceFile` in the user's program, with a file
 * extension prefix.
 *
 * 为用户程序中的每个原始 `ts.SourceFile` 生成一个 shim 文件，带有文件扩展名前缀。
 *
 */
export interface PerFileShimGenerator {
  /**
   * The extension prefix which will be used for the shim.
   *
   * 将用于 shim 的扩展前缀。
   *
   * Knowing this allows the `ts.CompilerHost` implementation which is consuming this shim generator
   * to predict the shim filename, which is useful when a previous `ts.Program` already includes a
   * generated version of the shim.
   *
   * 知道这一点，可以让使用此 shim 生成器的 `ts.CompilerHost` 实现来预测 shim 文件名，这在以前的
   * `ts.Program` 已经包含生成的 shim 版本时会很有用。
   *
   */
  readonly extensionPrefix: string;

  /**
   * Whether shims produced by this generator should be emitted during TypeScript emit.
   *
   * 此生成器生成的 shim 是否应在 TypeScript 发出期间发出。
   *
   */
  readonly shouldEmit: boolean;

  /**
   * Generate the shim for a given original `ts.SourceFile`, with the given filename.
   *
   * 使用给定的文件名，为给定的原始 `ts.SourceFile` 生成 shim。
   *
   */
  generateShimForFile(
      sf: ts.SourceFile, genFilePath: AbsoluteFsPath,
      priorShimSf: ts.SourceFile|null): ts.SourceFile;
}
import {
  getCategory,
  getTypes,
  getTypeCategories,
  getType
} from "../src/content";

describe("getCategory", () => {
  it("can abort", () => {
    expect(getCategory()).toBe(undefined);
  });

  it("can retrieve a single category", () => {
    expect(getCategory("Feature Layer")).toBe("dataset");
  });

  it("can retrieve a single category (from cache)", () => {
    expect(getCategory("Feature Layer")).toBe("dataset");
  });
});

describe("getTypes", () => {
  it("can abort", () => {
    expect(getTypes()).toBe(undefined);
  });
  it("can get a list of types for a category", () => {
    expect(getTypes("site")).toEqual([
      "Hub Site Application",
      "Site Application"
    ]);
  });
});

describe("getType", () => {
  it("can get type from item.type if typeKeywords is not defined", () => {
    expect(getType({ type: "type from item" })).toEqual("type from item");
  });
  it("can get type from item.type without typeKeywords", () => {
    expect(getType({ type: "Web Mapping Application" })).toEqual(
      "Web Mapping Application"
    );
  });
  it("can get type from item.typeKeywords", () => {
    expect(
      getType({ type: "Web Mapping Application", typeKeywords: ["hubSite"] })
    ).toEqual("Hub Site Application");
    expect(
      getType({ type: "Web Mapping Application", typeKeywords: ["hubPage"] })
    ).toEqual("Hub Page");
  });
  it("can work with blank inputs", () => {
    expect(getType()).toBe(undefined);
  });
});

describe("getTypeCategories", () => {
  it("should return Other if category is undefined", () => {
    expect(getTypeCategories({ type: "unknown type" })).toEqual(["Other"]);
  });
  it("should return correct typeCategory if category is defined", () => {
    expect(
      getTypeCategories({
        type: "Web Mapping Application",
        typeKeywords: ["hubSite"]
      })
    ).toEqual(["S


ct {
	// A [Document][google.firestore.v1beta1.Document] has been deleted.
	DocumentDelete *DocumentDelete `protobuf:"bytes,4,opt,name=document_delete,json=documentDelete,proto3,oneof"`
}

type ListenResponse_DocumentRemove struct {
	// A [Document][google.firestore.v1beta1.Document] has been removed from a target (because it is no longer
	// relevant to that target).
	DocumentRemove *DocumentRemove `protobuf:"bytes,6,opt,name=document_remove,json=documentRemove,proto3,oneof"`
}

type ListenResponse_Filter struct {
	// A filter to apply to the set of documents previously returned for the
	// given target.
	//
	// Returned when documents may have been removed from the given target, but
	// the exact documents are unknown.
	Filter *ExistenceFilter `protobuf:"bytes,5,opt,name=filter,proto3,oneof"`
}

func (*ListenResponse_TargetChange) isListenResponse_ResponseType() {}

func (*ListenResponse_DocumentChange) isListenResponse_ResponseType() {}

func (*ListenResponse_DocumentDelete) isListenResponse_ResponseType() {}

func (*ListenResponse_DocumentRemove) isListenResponse_ResponseType() {}

func (*ListenResponse_Filter) isListenResponse_ResponseType() {}

// A specification of a set of documents to listen to.
type Target struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	// The type of target to listen to.
	//
	// Types that are assignable to TargetType:
	//	*Target_Query
	//	*Target_Documents
	TargetType isTarget_TargetType `protobuf_oneof:"target_type"`
	// When to start listening.
	//
	// If not specified, all matching Documents are returned before any
	// subsequent changes.
	//
	// Types that are assignable to ResumeType:
	//	*Target_ResumeToken
	//	*Target_ReadTime
	ResumeType isTarget_ResumeType `protobuf_oneof:"resume_type"`
	// The target ID that identifies the target on the stream. Must be a positive
	// number and non-zero.
	TargetId int32 `protobuf:"varint,5,opt,name=target_id,json=targetId,proto3" json:"target_id,omitempty"`
	// If the target should be removed once it is current and consistent.
	Once bool `protobuf:"varint,6,opt,name=once,proto3" json:"once,omitempty"`
}

func (x *Target) Reset() {
	*x = Target{}
	if protoimpl.UnsafeEnabled {
		mi := &file_google_firestore_v1beta1_firestore_proto_msgTypes[21]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *Target) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*Target) ProtoMessage() {}

func (x *Target) ProtoReflect() protoreflect.Message {
	mi := &file_google_firestore_v1beta1_firestore_proto_msgTypes[21]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use Target.ProtoReflect.Descriptor instead.
func (*Target) Descriptor() ([]byte, []int) {
	return file_google_firestore_v1beta1_firestore_proto_rawDescGZIP(), []int{21}
}

func (m *Target) GetTargetType() isTarget_TargetType {
	if m != nil {
		return m.TargetType
	}
	return nil
}

func (x *Target) Get


rInfo(LoaderHeap* pHeap, LoaderAllocator* pLoaderAllocator)
{
    CONTRACTL
    {
        STANDARD_VM_CHECK;
        PRECONDITION(CheckPointer(pHeap));
        PRECONDITION(CheckPointer(pLoaderAllocator));
    }
    CONTRACTL_END;

    CustomMarshalerInfo* pInfo = nullptr;
    OBJECTREF IEnumeratorMarshalerObj = nullptr;

    GCX_COOP();
    GCPROTECT_BEGIN(IEnumeratorMarshalerObj);

    MethodDescCallSite getMarshaler(METHOD__STUBHELPERS__GET_IENUMERATOR_TO_ENUM_VARIANT_MARSHALER);
    IEnumeratorMarshalerObj = getMarshaler.Call_RetOBJECTREF(NULL);

    pInfo = new (pHeap) CustomMarshalerInfo(pLoaderAllocator, pLoaderAllocator->AllocateHandle(IEnumeratorMarshalerObj));

    GCPROTECT_END();

    return pInfo;
}
#endif

//==========================================================================
// Implementation of the custom marshaler hashtable helper.
//==========================================================================

EEHashEntry_t * EECMInfoHashtableHelper::AllocateEntry(EECMInfoHashtableKey *pKey, BOOL bDeepCopy, void* pHeap)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        INJECT_FAULT(return NULL;);
    }
    CONTRACTL_END;

    EEHashEntry_t *pEntry;

    if (bDeepCopy)
    {
        S_SIZE_T cbEntry = S_SIZE_T(sizeof(EEHashEntry) - 1 + sizeof(EECMInfoHashtableKey));
        cbEntry += S_SIZE_T(pKey->GetMarshalerTypeNameByteCount());
        cbEntry += S_SIZE_T(pKey->GetCookieStringByteCount());
        cbEntry += S_SIZE_T(pKey->GetMarshalerInstantiation().GetNumArgs()) * S_SIZE_T(sizeof(LPVOID));
        cbEntry += S_SIZE_T(sizeof(LPVOID)); // For EECMInfoHashtableKey::m_invokingAssembly

        if (cbEntry.IsOverflow())
            return NULL;

        pEntry = (EEHashEntry_t *) new (nothrow) BYTE[cbEntry.Value()];
        if (!pEntry)
            return NULL;

        EECMInfoHashtableKey *pEntryKey = (EECMInfoHashtableKey *) pEntry->Key;
        pEntryKey->m_cMarshalerTypeNameBytes = pKey->GetMarshalerTypeNameByteCount();
        pEntryKey->m_strMarshalerTypeName = (LPSTR) pEntry->Key + sizeof(EECMInfoHashtableKey);
        pEntryKey->m_cCookieStrBytes = pKey->GetCookieStringByteCount();
        pEntryKey->m_strCookie = (LPSTR) pEntry->Key + sizeof(EECMInfoHashtableKey) + pEntryKey->m_cMarshalerTypeNameBytes;
        pEntryKey->m_Instantiation = Instantiation(
            (TypeHandle *) (pEntryKey->m_strCookie + pEntryKey->m_cCookieStrBytes),
            pKey->GetMarshalerInstantiation().GetNumArgs());
        memcpy((void*)pEntryKey->m_strMarshalerTypeName, pKey->GetMarshalerTypeName(), pKey->GetMarshalerTypeNameByteCount());
        memcpy((void*)pEntryKey->m_strCookie, pKey->GetCookieString(), pKey->GetCookieStringByteCount());
        memcpy((void*)pEntryKey->m_Instantiation.GetRawArgs(), pKey->GetMarshalerInstantiation().GetRawArgs(),
            pEntryKey->m_Instantiation.GetNumArgs() * sizeof(LPVOID));
        pEntryKey->m_invokingAssembly = pKey->GetInvokingAssembly();
    }
    else
    {
        pEntry = (EEHashEntry_t *)
            new (nothrow) BYTE[sizeof(EEHashEntry) - 1 + sizeof(EECMInfoHashtableKey)];
        if (!pEntry)
            return NULL;

        EECMInfoHashtableKey *pEntryKey = (EECMInfoHashtableKey *) pEntry->Key;
        pEntryKey


  /// T::AccountId
  final _i3.AccountId32 to;

  /// BalanceOf<T>
  final BigInt amount;

  @override
  Map<String, Map<String, dynamic>> toJson() => {
        'StorageDepositTransferredAndHeld': {
          'from': from.toList(),
          'to': to.toList(),
          'amount': amount,
        }
      };

  int _sizeHint() {
    int size = 1;
    size = size + const _i3.AccountId32Codec().sizeHint(from);
    size = size + const _i3.AccountId32Codec().sizeHint(to);
    size = size + _i1.U128Codec.codec.sizeHint(amount);
    return size;
  }

  void encodeTo(_i1.Output output) {
    _i1.U8Codec.codec.encodeTo(
      8,
      output,
    );
    const _i1.U8ArrayCodec(32).encodeTo(
      from,
      output,
    );
    const _i1.U8ArrayCodec(32).encodeTo(
      to,
      output,
    );
    _i1.U128Codec.codec.encodeTo(
      amount,
      output,
    );
  }

  @override
  bool operator ==(Object other) =>
      identical(
        this,
        other,
      ) ||
      other is StorageDepositTransferredAndHeld &&
          _i6.listsEqual(
            other.from,
            from,
          ) &&
          _i6.listsEqual(
            other.to,
            to,
          ) &&
          other.amount == amount;

  @override
  int get hashCode => Object.hash(
        from,
        to,
        amount,
      );
}

/// Some storage deposit funds have been transferred and released.
class StorageDepositTransferredAndReleased extends Event {
  const StorageDepositTransferredAndReleased({
    required this.from,
    required this.to,
    required this.amount,
  });

  factory StorageDepositTransferredAndReleased._decode(_i1.Input input) {
    return StorageDepositTransferredAndReleased(
      from: const _i1.U8ArrayCodec(32).decode(input),
      to: const _i1.U8ArrayCodec(32).decode(input),
      amount: _i1.U128Codec.codec.decode(input),
    );
  }

  /// T::AccountId
  final _i3.AccountId32 from;

  /// T::AccountId
  final _i3.AccountId32 to;

  /// BalanceOf<T>
  final BigInt amount;

  @override
  Map<String, Map<String, dynamic>> toJson() => {
        'StorageDepositTransferredAndReleased': {
          'from': from.toList(),
          'to': to.toList(),
          'amount': amount,
        }
      };

  int _sizeHint() {
    int size = 1;
    size = size + const _i3.AccountId32Codec().sizeHint(from);
    size = size + const _i3.AccountId32Codec().sizeHint(to);
    size = size + _i1.U128Codec.codec.sizeHint(amount);
    return size;
  }

  void encodeTo(_i1.Output output) {
    _i1.U8Codec.codec.encodeTo(
      9,
      output,
    );
    const _i1.U8ArrayCodec(32).encodeTo(
      from,
      output,
    );
    const _i1.U8ArrayCodec(32).encodeTo(
      to,
      output,
    );
    _i1.U128Codec.codec.encodeTo(
      amount,
      output,
    );
  }

  @override
  bool operator ==(Object other) =>
      identical(
        this,
        other,
      ) ||
      other is StorageDepositTransferredAndReleased &&
          _i6.lis