# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys

sys.path.insert(0, os.path.abspath("../../src"))

# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information

project = 'gymfolio'
copyright = '2024, Francisco Espiga Fernández'
author = 'Francisco Espiga Fernández'
release = '0.2.1'

master_doc = "index"

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

extensions = [
    "sphinx.ext.todo",
    "sphinx.ext.viewcode",
    "sphinx.ext.autodoc",
    "sphinx_rtd_theme",
    'myst_parser',
    "sphinx.ext.mathjax",
    "sphinx-mathjax-offline",
    #"sphinx_mdinclude",
]

templates_path = ['_templates']
exclude_patterns = []

myst_enable_extensions = ["dollarmath", "amsmath", "colon_fence",
                          "deflist", "replacements", "smartquotes", "substitution", "tasklist"]

# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output

html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']

source_suffix = {
    '.rst': 'restructuredtext',
    '.md': 'markdown',
}


8 0-16-7.2-16-16V192c0-8.8 7.2-16 16-16l140.1 0L464 243.9V448c0 8.8-7.2 16-16 16zM256 512H448c35.3 0 64-28.7 64-64V243.9c0-12.7-5.1-24.9-14.1-33.9l-67.9-67.9c-9-9-21.2-14.1-33.9-14.1H256c-35.3 0-64 28.7-64 64V448c0 35.3 28.7 64 64 64z"],
    "face-grin-tongue-squint": [512, 512, [128541, "grin-tongue-squint"], "f58a", "M464 256c0-114.9-93.1-208-208-208S48 141.1 48 256c0 81.7 47.1 152.4 115.7 186.4c-2.4-8.4-3.7-17.3-3.7-26.4V392.7c-24-17.5-43.1-41.4-54.8-69.2c-5-11.8 7-22.5 19.3-18.7c39.7 12.2 84.5 19 131.8 19s92.1-6.8 131.8-19c12.3-3.8 24.3 6.9 19.3 18.7c-11.8 28-31.1 52-55.4 69.6V416c0 9.2-1.3 18-3.7 26.4C416.9 408.4 464 337.7 464 256zM0 256a256 256 0 1 1 512 0A256 256 0 1 1 0 256zm116-98.9c0-9 9.6-14.7 17.5-10.5l89.9 47.9c10.7 5.7 10.7 21.1 0 26.8l-89.9 47.9c-7.9 4.2-17.5-1.5-17.5-10.5c0-2.8 1-5.5 2.8-7.6l36-43.2-36-43.2c-1.8-2.1-2.8-4.8-2.8-7.6zm262.5-10.5c7.9-4.2 17.5 1.5 17.5 10.5c0 2.8-1 5.5-2.8 7.6l-36 43.2 36 43.2c1.8 2.1 2.8 4.8 2.8 7.6c0 9-9.6 14.7-17.5 10.5l-89.9-47.9c-10.7-5.7-10.7-21.1 0-26.8l89.9-47.9zM320 416V378.6c0-14.7-11.9-26.6-26.6-26.6h-2c-11.3 0-21.1 7.9-23.6 18.9c-2.8 12.6-20.8 12.6-23.6 0c-2.5-11.1-12.3-18.9-23.6-18.9h-2c-14.7 0-26.6 11.9-26.6 26.6V416c0 35.3 28.7 64 64 64s64-28.7 64-64z"],
    "face-flushed": [512, 512, [128563, "flushed"], "f579", "M464 256A208 208 0 1 1 48 256a208 208 0 1 1 416 0zM256 0a256 256 0 1 0 0 512A256 256 0 1 0 256 0zM160.4 248a24 24 0 1 0 0-48 24 24 0 1 0 0 48zm216-24a24 24 0 1 0 -48 0 24 24 0 1 0 48 0zM192 336c-13.3 0-24 10.7-24 24s10.7 24 24 24H320c13.3 0 24-10.7 24-24s-10.7-24-24-24H192zM160 176a48 48 0 1 1 0 96 48 48 0 1 1 0-96zm0 128a80 80 0 1 0 0-160 80 80 0


u/img/sprite/sprite_connect_v13.png) -150px top no-repeat !important;}#li_ui_li_gen_1369856323217_1-content.IN-top {display:inline !important;font-size:16px !important;color:#04558B !important;font-weight:bold !important;font-family:Arial, sans-serif !important;line-height:34px !important;}#li_ui_li_gen_1369856323217_1-container.IN-hovered #li_ui_li_gen_1369856323217_1.IN-top, #li_ui_li_gen_1369856323217_1-container.IN-clicked #li_ui_li_gen_1369856323217_1.IN-top, #li_ui_li_gen_1369856323217_1-container.IN-down #li_ui_li_gen_1369856323217_1.IN-top {background-position-x:-210px !important;}#li_ui_li_gen_1369856323217_1-container.IN-empty #li_ui_li_gen_1369856323217_1-inner.IN-top {background:url(http://static.licdn.com/scds/common/u/img/sprite/sprite_connect_v13.png) 0px -20px no-repeat !important;overflow:hidden !important;margin:5px auto 0 auto !important;width:26px !important;height:26px !important;display:block !important;}#li_ui_li_gen_1369856323217_1-container.IN-empty #li_ui_li_gen_1369856323217_1-content.IN-top {text-indent:-999px !important;display:inline-block !important;}#li_ui_li_gen_1369856323217_1-container.IN-hidden #li_ui_li_gen_1369856323217_1 {display:none !important;}* html #li_ui_li_gen_1369856323266_2 a#li_ui_li_gen_1369856323266_2-link{height:1% !important;}#li_ui_li_gen_1369856323266_2{position:relative !important;overflow:visible !important;display:block !important;}#li_ui_li_gen_1369856323266_2 a#li_ui_li_gen_1369856323266_2-link{border:0 !important;height:20px !important;text-decoration:none !important;padding:0 !important;margin:0 !important;display:inline-block !important;}#li_ui_li_gen_1369856323266_2 a#li_ui_li_gen_1369856323266_2-link:link, #li_ui_li_gen_1369856323266_2 a#li_ui_li_gen_1369856323266_2-link:visited, #li_ui_li_gen_1369856323266_2 a#li_ui_li_gen_1369856323266_2-link:hover, #li_ui_li_gen_1369856323266_2 a#li_ui_li_gen_1369856323266_2-link:active{border:0 !important;text-decoration:none !important;}#li_ui_li_gen_1369856323266_2 a#li_ui_li_gen_1369856323266_2-link:after{content:"." !important;display:block !important;clear:both !important;visibility:hidden !important;line-height:0 !important;height:0 !important;}#li_ui_li_gen_1369856323266_2 #li_ui_li_gen_1369856323266_2-logo{background:url(http://static.licdn.com/scds/common/u/img/sprite/sprite_connect_v13.png) 0px -276px no-repeat !important;cursor:pointer !important;border:0 !important;text-indent:-9999em !important;overflow:hidden !important;padding:0 !important;margin:0 !important;position:absolute !important;left:0px !important;top:


/**
     * Creates a two-dimensional array from a list of byte lists
     * and checks if the array's list representation matches the input list.
     */
    @Test
    fun createTwoDimensionalArrayFromByteList() {
        val list = listOf(listOf<Byte>(1, 3, 8), listOf<Byte>(4, 7, 2))
        val a: D2Array<Byte> = mk.ndarray(list)
        assertEquals(list, a.toListD2())
    }

    /**
     * Creates a two-dimensional array from a set of bytes
     * and checks if the array's set representation matches the input set.
     */
    @Test
    fun createTwoDimensionalArrayFromByteSet() {
        val set = setOf<Byte>(1, 3, 8, 4, 9, 2)
        val shape = intArrayOf(2, 3)
        val a: D2Array<Byte> = mk.ndarray(set, shape = shape)

        assertEquals(set.size, a.size)
        assertEquals(set, a.toSet())
    }

    /**
     * Creates a two-dimensional array from a primitive ByteArray
     * and checks if the array's ByteArray representation matches the input ByteArray.
     */
    @Test
    fun createTwoDimensionalArrayFromPrimitiveByteArray() {
        val array = byteArrayOf(1, 3, 8, 4, 9, 2)
        val a = mk.ndarray(array, 2, 3)

        assertEquals(array.size, a.size)
        a.data.getByteArray() shouldBe array
    }

    /**
     * Creates a two-dimensional array with a given size using an initialization function
     * and checks if the array's ByteArray representation matches the expected output.
     */
    @Test
    fun createByte2DArrayWithInitializationFunction() {
        val a = mk.d2array<Byte>(2, 3) { (it + 3).toByte() }
        val expected = byteArrayOf(3, 4, 5, 6, 7, 8)

        assertEquals(expected.size, a.size)
        a.data.getByteArray() shouldBe expected
    }

    /**
     * Creates a two-dimensional array with a given size using an initialization function and indices.
     * Checks if the array's ByteArray representation matches the expected output.
     */
    @Test
    fun createByte2DArrayWithInitAndIndices() {
        val a = mk.d2arrayIndices(2, 3) { i, j -> (i * j + 7).toByte() }
        val expected = byteArrayOf(7, 7, 7, 7, 8, 9)

        assertEquals(expected.size, a.size)
        a.data.getByteArray() shouldBe expected
    }

    /**
     * Tests the function 'createAlignedNDArray' that creates a two-dimensional array from a list of number lists.
     * The test asserts that:
     * - The output array's size matches the size of the longest list in the input
     * and all lists are filled to match this length.
     * - The lists shorter than the longest one are filled with the specified filling value.
     */
    @OptIn(ExperimentalMultikApi::class)
    @Test
    fun createAlignedByte2DArray() {
        val list = listOf(
            listOf<Byte>(1, 3, 8),
            listOf<Byte>(4, 7),
            listOf<Byte>(2, 5, 9, 10)
        )

        val expected = listOf(
            listOf<Byte>(1, 3, 8, 0),
            listOf<Byte>(4, 7, 0, 0),
            listOf<Byte>(2, 5, 9, 10)
        )

        val a: D2Array<Byte> = mk.createAlignedNDArray(list, filling = 0.0)

        assertEquals(expected, a.toListD2())
    }

    /*___________________________Short_______________________________________*/

    /**
     * This method checks if a short array of a given size is correctly created with all elements set to zero.
     */
    @Test
    fun createZeroFilledShortArray() {


.stretch,
          children: [
            Text(widget.title, style: _largerTextStyle, textAlign: TextAlign.center),
            const Divider(),
            Text(widget.content, style: _textStyle, textAlign: TextAlign.center),
          ],
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      floatingActionButton: Container(
        margin: const EdgeInsets.all(10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () => Get.back(result: false),
              child: const Text(
                "No",
                textScaler: TextScaler.linear(2.0),
                textAlign: TextAlign.center,
              ),
            ),
            const SizedBox(width: 10, height: 10),
            ElevatedButton(
              onPressed: () => Get.back(result: true),
              child: const Text(
                "Yes",
                textScaler: TextScaler.linear(2.0),
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_circle_color_picker/flutter_circle_color_picker.dart';
import 'package:get/get.dart';
import 'package:tuple/tuple.dart';

import '../../utils/constants.dart';
import '../../utils/theme_manager.dart';
import 'legend_dialog.dart';

class ColorPickerBottomSheet extends StatefulWidget {
  final Color color;
  final ValueChanged<Color>? onChanged;
  const ColorPickerBottomSheet({super.key, required this.color, this.onChanged});

  @override
  ColorPickerBottomSheetState createState() => ColorPickerBottomSheetState();
}

class ColorPickerBottomSheetState extends State<ColorPickerBottomSheet> {
  final ThemeManager _themeManager = Get.find<ThemeManager>();
  late final CircleColorPickerController _controller;
  Color _color = Colors.white;
  Color _initialColor = Colors.white;
  TextStyle _textStyle = const TextStyle();
  double? _mediaWidth;

  @override
  void initState() {
    super.initState();
    _controller = CircleColorPickerController(initialColor: widget.color);
    _color = Color(widget.color.toARGB32());
    _initialColor = Color(widget.color.toARGB32());
    _textStyle = Get.textTheme.headlineSmall!.apply(
      fontFamily: fontFamily,
      color: _themeManager.getProtagonistColor(),
    );
  }

  @override
  Widget build(BuildContext context) {
    final mediaWidth = min(Get.mediaQuery.size.width, Get.mediaQuery.size.height);
    if (_mediaWidth == null || (_mediaWidth! - mediaWidth).abs() > eps) {
      _mediaWidth = mediaWidth;
    }

    return Scaffold(
      body: Center(
        child: CircleColorPicker(
          controller: _controller,
          onChanged: (color) {
            widget.onChanged?.call(_color);
            setState(() {
              _color = color;
            });
          },
          size: Size(_mediaWidth!, _mediaWidth!),
          strokeWidth: 5,
          thumbSize: _mediaWidth! / 5,
          textStyle: _textStyle,
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,
      floatingActionButton: Container(
        margin: const EdgeInsets.all(10.0),
        child: Row(
          mainAxisAlignmen


// -----------------------------------------------------------------------------
// This file is part of VirtualC64
//
// Copyright (C) Dirk W. Hoffmann. www.dirkwhoffmann.de
// This FILE is dual-licensed. You are free to choose between:
//
//     - The GNU General Public License v3 (or any later version)
//     - The Mozilla Public License v2
//
// SPDX-License-Identifier: GPL-3.0-or-later OR MPL-2.0
// -----------------------------------------------------------------------------

#pragma once

#include "PowerPortTypes.h"
#include "SubComponent.h"
#include "Chrono.h"

namespace vc64 {

class PowerPort final : public SubComponent {

    Descriptions descriptions = {{

        .type           = PowerPortClass,
        .name           = "Power",
        .description    = "Power Port",
        .shell          = "power"
    }};

    Options options = {

        OPT_POWER_GRID
    };

    PowerPortConfig config = { };

    //
    // Methods
    //

public:

    PowerPort(C64& ref);
    PowerPort& operator= (const PowerPort& other) { return *this; }

    //
    // Methods from Serializable
    //

public:

    template <class T> void serialize(T& worker) { } SERIALIZERS(serialize);

    //
    // Methods from CoreComponent
    //

public:

    const Descriptions &getDescriptions() const override { return descriptions; }

private:

    void _dump(Category category, std::ostream& os) const override;

    //
    // Methods from Inspectable
    //

public:

    const PowerPortConfig &getConfig() const { return config; }
    const Options &getOptions() const override { return options; }
    i64 getOption(Option opt) const override;
    void checkOption(Option opt, i64 value) override;
    void setOption(Option opt, i64 value) override;

    //
    // Using the device
    //

public:

    // Returns the number of CPU cycles between two TOD increments
    Cycle todTickDelay(u8 cra);
};

}


    fn test_audio_mux_element_v1() {
        const PAYLOAD_LEN: usize = 915;
        const HEADER_LEN: usize = 13;
        let header: &[u8] = &[71, 252, 0, 0, 176, 144, 128, 3, 0, 255, 255, 255, 150];
        let input: &mut [u8] = &mut [0; PAYLOAD_LEN + HEADER_LEN];
        // version 1, 1 subframe/prog/layer, aac-lc stereo, 915 bytes of zero payload, byte aligned, variable
        // length frames. Based on headers captured from Android device source
        input[0..header.len()].copy_from_slice(header);

        let reference = AudioMuxElement {
            stream_mux_config: StreamMuxConfig {
                audio_mux_version: 1,
                all_streams_same_time_framing: 1,
                num_subframes: 1,
                programs: vec![Program {
                    layers: vec![Layer {
                        audio_specific_config: AudioSpecificConfig {
                            audio_object_type: 2,
                            sampling_frequency_index: 4,
                            sampling_frequency: None,
                            channel_configuration: 2,
                            ga_specific_config: Some(GASpecificConfig {
                                frame_length_flag: 0,
                                depends_on_core_coder: 0,
                                core_coder_delay: None,
                                extension_flag: 0,
                                layer_nr: None,
                            }),
                            bits_read: 16,
                        },
                        frame_length_type: 0,
                        latm_buffer_fullness: Some(192),
                        frame_length: None,
                        mux_slot_length_bytes: PAYLOAD_LEN,
                    }],
                }],
                crc_checksum: None,
            },
            payloads: vec![Payload::ByteAligned(&[0x0; PAYLOAD_LEN])],
        };

        let parsed = AudioMuxElement::try_from_bytes(input).expect("parsed ok");

        assert_eq!(reference, parsed);

        let ref_payload = &[0x0; PAYLOAD_LEN][0..];
        assert_eq!(reference.get_payload(0).expect("has payload"), ref_payload);

        //set audioMuxVersionA to 1 and verify we fail to parse
        input[0] = 103;
        let _ = AudioMuxElement::try_from_bytes(input).expect_err("Failure to parse");

        //set useSameStream to 1 and verify we fail to parse (StreamMuxConfig is required)
        input[0] = 199;
        let _ = AudioMuxElement::try_from_bytes(input).expect_err("Failure to parse");

        //set allStreamsSameTimeRemaining to 0 and verify we error, we don't support multiple time
        //bases
        input[0] = 71;
        input[1] = 248;
        let _ = AudioMuxElement::try_from_bytes(input).expect_err("Failure to parse");
    }

    #[test]
    fn test_audio_mux_element_v0() {
        const PAYLOAD_LEN: usize = 363;
        const HEADER_LEN: usize = 9;
        let input: &mut [u8] = &mut [0; PAYLOAD_LEN + HEADER_LEN];
        // version 0, 1 subframe/prog/layer, aac-lc stereo, 363 bytes of zero payload, non-byte aligned, variable
        // length frames
        let header: &[u8] = &[0x20, 0x00, 0x13, 0x90, 0x12, 0x27, 0xfb, 0x60, 0x00];
        input[0..header.len()].copy_from_slice(header);

        let parsed = AudioMuxElement {
            stream_mux_config: StreamMuxConfig {
                audio_mux_version: 0,
                all_stre


_ext_present) {
    j.write_str("lateNonCriticalExtension", late_non_crit_ext.to_string());
  }
  if (non_crit_ext_present) {
    j.write_fieldname("nonCriticalExtension");
    j.start_obj();
    j.end_obj();
  }
  j.end_obj();
}

// MBMSInterestIndication-r11-IEs ::= SEQUENCE
SRSASN_CODE mbms_interest_ind_r11_ies_s::pack(bit_ref& bref) const
{
  HANDLE_CODE(bref.pack(mbms_freq_list_r11_present, 1));
  HANDLE_CODE(bref.pack(mbms_prio_r11_present, 1));
  HANDLE_CODE(bref.pack(late_non_crit_ext_present, 1));
  HANDLE_CODE(bref.pack(non_crit_ext_present, 1));

  if (mbms_freq_list_r11_present) {
    HANDLE_CODE(pack_dyn_seq_of(bref, mbms_freq_list_r11, 1, 5, integer_packer<uint32_t>(0, 262143)));
  }
  if (late_non_crit_ext_present) {
    HANDLE_CODE(late_non_crit_ext.pack(bref));
  }
  if (non_crit_ext_present) {
    HANDLE_CODE(non_crit_ext.pack(bref));
  }

  return SRSASN_SUCCESS;
}
SRSASN_CODE mbms_interest_ind_r11_ies_s::unpack(cbit_ref& bref)
{
  HANDLE_CODE(bref.unpack(mbms_freq_list_r11_present, 1));
  HANDLE_CODE(bref.unpack(mbms_prio_r11_present, 1));
  HANDLE_CODE(bref.unpack(late_non_crit_ext_present, 1));
  HANDLE_CODE(bref.unpack(non_crit_ext_present, 1));

  if (mbms_freq_list_r11_present) {
    HANDLE_CODE(unpack_dyn_seq_of(mbms_freq_list_r11, bref, 1, 5, integer_packer<uint32_t>(0, 262143)));
  }
  if (late_non_crit_ext_present) {
    HANDLE_CODE(late_non_crit_ext.unpack(bref));
  }
  if (non_crit_ext_present) {
    HANDLE_CODE(non_crit_ext.unpack(bref));
  }

  return SRSASN_SUCCESS;
}
void mbms_interest_ind_r11_ies_s::to_json(json_writer& j) const
{
  j.start_obj();
  if (mbms_freq_list_r11_present) {
    j.start_array("mbms-FreqList-r11");
    for (const auto& e1 : mbms_freq_list_r11) {
      j.write_int(e1);
    }
    j.end_array();
  }
  if (mbms_prio_r11_present) {
    j.write_str("mbms-Priority-r11", "true");
  }
  if (late_non_crit_ext_present) {
    j.write_str("lateNonCriticalExtension", late_non_crit_ext.to_string());
  }
  if (non_crit_ext_present) {
    j.write_fieldname("nonCriticalExtension");
    non_crit_ext.to_json(j);
  }
  j.end_obj();
}

// MCGFailureInformation-r16-IEs ::= SEQUENCE
SRSASN_CODE mcg_fail_info_r16_ies_s::pack(bit_ref& bref) const
{
  HANDLE_CODE(bref.pack(fail_report_mcg_r16_present, 1));
  HANDLE_CODE(bref.pack(late_non_crit_ext_presen


surface_DrawRect(startX + offset * width, startY + height-2, width * length, 2)
				else
					if cell[3]:sub(1, 5) == "color" then
						surface_SetMaterial( matGrid )
						surface_SetDrawColor(Color(255, 255, 255))
						surface_DrawTexturedRectUV(startX + offset * width, startY, width * length, height,0 ,0, width * length / height, 1)
					end
					surface_SetDrawColor(cell[2][2])
					surface_DrawRect(startX + offset * width, startY, width * length, height)
				end
			end
			if cell[2][3] == 2 then
				draw_SimpleText(cell[1] .. " ", self.CurrentFont .. "_Bold", offset * width + startX, startY, cell[2][1])
			elseif cell[2][3] == 1 then
				draw_SimpleText(cell[1] .. " ", self.CurrentFont .. "_Italic", offset * width + startX, startY, cell[2][1])
			else
				draw_SimpleText(cell[1] .. " ", self.CurrentFont, offset * width + startX, startY, cell[2][1])
			end

			offset = offset + length
		end
	end
	if not drawonlytext then
		if row < lines and rowdata.hides then
			local text = string.format(TabHandler.LinesHiddenFormatConVar:GetString(),rowdata.hides)
			local nextlineoff = offset + #text
			draw_SimpleText(text, self.CurrentFontSmall, offset * width + startX + (nextlineoff-offset)*width/2, startY + height/2 ,colors.word_highlight, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
			if self.RealLine[drawpos+1] and rowdata.fullcollapse then
				self:PaintLine(self.RealLine[drawpos+1]-1, drawpos, nextlineoff, true)
			end
		end
	end
--[[	if cells.foldable then
		surface_SetDrawColor(Color(0,222,0,20))
		surface_DrawRect(startX, startY, self:GetWide() - (self.LineNumberWidth + 5), height)
	end
	if cells.test then
		draw_SimpleText(tostring(cells.test), self.CurrentFont, startX, startY, Color(32,32,255))
	end]]
end

function PANEL:PerformLayout()
	self.ScrollBar:SetSize(16, self:GetTall())
	self.ScrollBar:SetPos(self:GetWide() - 16, 0)

	self.Size[1] = math_floor(self:GetTall() / self.FontHeight) - 1
	self.Size[2] = math_floor((self:GetWide() - (self.LineNumberWidth + 6) - 16) / self.FontWidth) - 1

	self.ScrollBar:SetUp(self.Size[1], self.VisibleRows -1)
end

function PANEL:HighlightArea(area, r, g, b, a)
	if not self.HighlightedAreas then self.HighlightedAreas = {} end
	if not r then
		local _start, _stop = area[1], area[2]
		for k, v in pairs(self.HighlightedAreas) do
			local start = v[1][1]
			local stop = v[1][2]
			if start[1] == _start[1] and start[2] == _start[2] and stop[1] == _stop[1] and stop[2] == _stop[2] then
				table_remove(self.HighlightedAreas, k)
				break
			end
		end
		return true
	elseif r and g and b and a then
		self.HighlightedAreas[#self.HighlightedAreas + 1] = { area, r, g, b, a }
		return true
	end
	return false
end
function PANEL:ClearHighlightedAr


      assertEquals(ex.getCode(), FirebaseMlException.INTERNAL);
    }
    assertTrue(task.isComplete());
    assertFalse(task.isSuccessful());
    assertTrue(task.getException() instanceof FirebaseMlException);

    verify(mockDownloadManager, times(1)).enqueue(any());
    verify(mockDownloadManager, atLeastOnce()).query(any());

    verify(mockStatsLogger, times(1))
        .logDownloadEventWithErrorCode(
            eq(CUSTOM_MODEL_URL),
            eq(false),
            eq(DownloadStatus.EXPLICITLY_REQUESTED),
            eq(ErrorCode.NO_ERROR));
  }

  @Test
  public void ensureModelDownloaded_downloadFailed() {
    when(mockDownloadManager.enqueue(any())).thenReturn(DOWNLOAD_ID);
    matrixCursor =
        new MatrixCursor(
            new String[] {DownloadManager.COLUMN_STATUS, DownloadManager.COLUMN_REASON});
    matrixCursor.addRow(
        new Integer[] {DownloadManager.STATUS_FAILED, DownloadManager.ERROR_INSUFFICIENT_SPACE});
    when(mockDownloadManager.query(any())).thenReturn(matrixCursor);
    TestOnCompleteListener<Void> onCompleteListener = new TestOnCompleteListener<>();
    Task<Void> task = modelFileDownloadService.ensureModelDownloaded(CUSTOM_MODEL_URL);

    try {
      // Complete the download
      Intent downloadCompleteIntent = new Intent(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
      downloadCompleteIntent.putExtra(DownloadManager.EXTRA_DOWNLOAD_ID, DOWNLOAD_ID);
      app.getApplicationContext().sendBroadcast(downloadCompleteIntent);

      task.addOnCompleteListener(executor, onCompleteListener);
      onCompleteListener.await();
    } catch (FirebaseMlException ex) {
      assertEquals(ex.getCode(), FirebaseMlException.NOT_ENOUGH_SPACE);
    } catch (Exception ex) {
      fail("Unexpected error: " + ex.getMessage());
    }

    assertTrue(task.isComplete());
    assertFalse(task.isSuccessful());
    assertTrue(task.getException() instanceof FirebaseMlException);
    assertEquals(
        sharedPreferencesUtil.getDownloadingCustomModelDetails(MODEL_NAME),
        CUSTOM_MODEL_DOWNLOADING);

    verify(mockDownloadManager, times(1)).enqueue(any());
    verify(mockDownloadManager, atLeastOnce()).query(any());

    verify(mockStatsLogger, times(1))
        .logDownloadEventWithErrorCode(
            eq(CUSTOM_MODEL_URL),
            eq(false),
            eq(DownloadStatus.EXPLICITLY_REQUESTED),
            eq(ErrorCode.NO_ERROR));
  }

  @Test
  public void ensureModelDownloaded_downloadFailed_urlExpiry() {
    when(mockDownloadManager.enqueue(any())).thenReturn(DOWNLOAD_ID);
    matrixCursor =
        new MatrixCursor(
            new String[] {DownloadManager.COLUMN_STATUS, DownloadManager.COLUMN_REASON});
    matrixCursor.addRow(new Integer[] {DownloadManager.STATUS_FAILED, 400});
    when(mockDownloadManager.query(any())).thenReturn(matrixCursor);

    CustomModel justAboutToExpireModel =
        modelFactory.create(MODEL_NAME, MODEL_HASH, 100, MODEL_URL, (new Date()).getTime() + 3);

    TestOnCompleteListener<Void> onCompleteListener = new TestOnCompleteListener<>();
    Task<Void> task = modelFileDownloadService.ensureModelDownloaded(justAboutToExpireModel);

    try {
      // Complete the download
      // sleep long enough for the url to expire
      Thread.sleep(4);
      Intent downloadCompleteIntent = new Intent(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
      downloadCompleteIntent.putExtra(DownloadManager.EXTRA_DOWNLOAD_ID, DOWNLOAD_ID);
      app.getApplicationContext().sendBroadcast(downloadCompleteIntent);

      task.addOnCompleteListener(executor, onCompleteL


result, *t2);
    result->SetInputSymbols(t1->InputSymbols());
    return result;
}

LogFst *
LogWeightTransducer::disjunct(LogFst *t, const StringPairVector &spv)
{
    SymbolTable *st = t->InputSymbols()->Copy();
    assert(st != NULL);

    StateId s = t->Start();

    for (StringPairVector::const_iterator it = spv.begin(); it != spv.end();
         it++)
    {
        unsigned int inumber = st->AddSymbol(it->first.c_str());
        unsigned int onumber = st->AddSymbol(it->second.c_str());

        bool transition_found = false;
        for (fst::ArcIterator<LogFst> it(*t, s); !it.Done(); it.Next())
        {
            const LogArc &a = it.Value();
            if (a.ilabel == (int)inumber && a.olabel == (int)onumber)
            {
                transition_found = true;
                s = a.nextstate;
                break;
            }
        }

        if (!transition_found)
        {
            StateId new_state = t->AddState();
            t->AddArc(s, LogArc(inumber, onumber, 0, new_state));
            s = new_state;
        }
    }

    t->SetFinal(s, 0);

    t->SetInputSymbols(st);
    return t;
}

LogFst *
LogWeightTransducer::disjunct(LogFst *t, const NumberPairVector &npv)
{
    StateId s = t->Start();

    for (NumberPairVector::const_iterator it = npv.begin(); it != npv.end();
         it++)
    {
        unsigned int inumber = it->first;
        unsigned int onumber = it->second;

        bool transition_found = false;
        for (fst::ArcIterator<LogFst> it(*t, s); !it.Done(); it.Next())
        {
            const LogArc &a = it.Value();
            if (a.ilabel == (int)inumber && a.olabel == (int)onumber)
            {
                transition_found = true;
                s = a.nextstate;
                break;
            }
        }

        if (!transition_found)
        {
            StateId new_state = t->AddState();
            t->AddArc(s, LogArc(inumber, onumber, 0, new_state));
            s = new_state;
        }
    }

    t->SetFinal(s, 0);
    return t;
}

LogFst *
LogWeightTransducer::intersect(LogFst *t1, LogFst *t2)
{
    if (t1->OutputSymbols() == NULL)
        t1->SetOutputSymbols(t1->InputSymbols());
    if (t2->OutputSymbols() == NULL)
        t2->SetOutputSymbols(t2->InputSymbols());

    ArcSort(t1, OLabelCompare<LogArc>());
    ArcSort(t2, ILabelCompare<LogArc>());

    RmEpsilon(t1);
    RmEpsilon(t2);

    EncodeMapper<LogArc> encoder(0x0001, ENCODE);
    EncodeFst<LogArc> enc1(*t1, &encoder);
    EncodeFst<LogArc> enc2(*t2, &encoder);
    DeterminizeFst<LogArc> det1(enc1);
    DeterminizeFst<LogArc> det2(enc2);

    IntersectFst<LogArc> intersect(det1, det2);
    LogFst *foo = new LogFst(intersect);
    DecodeFst<LogArc> decode(*foo, encoder);
    delete foo;
    LogFst *result = new LogFst(decode);
    result->SetInputSymbols(t1->InputSymbols());
    return result;
}

LogFst *
LogWeightTransducer::subtract(LogFst *t1, LogFst *t2)
{
    bool DEBUG = false;

    if (DEBUG)
        printf("Log subtract...\n");

    if (t1->OutputSymbols() == NULL)
        t1->SetOutputSymbols(t1->InputSymbols());
    if (t2->OutputSymbols() == NULL)
        t2->SetOutputSymbols(t2->InputSymbols());

    ArcSort(t1, OLabelCompare<LogArc>());
    ArcSort(t2, ILabelCompare<LogArc>());

    // RmEpsilonFst<LogArc> rm


WatchingDir,
		config.Paths,
		jp.processNotification,
		config.ShouldWatchChanges,
		metrics.notifyChannelLengthMetric,
		sugLogger,
	)

	return jp
}

func (jp *jobProvider) start() {
	jp.logger.Infof("starting job provider persistence mode=%s", jp.config.PersistenceMode)
	if jp.config.OffsetsOp_ == offsetsOpContinue {
		offsets, err := jp.offsetDB.load()
		if err != nil {
			logger.Panicf("can't load offsets: %s", err.Error())
		}
		jp.loadedOffsets = offsets
	}

	jp.watcher.start()

	if jp.config.PersistenceMode_ == persistenceModeAsync {
		go jp.saveOffsetsCyclic(jp.config.AsyncInterval_)
	}

	jp.isStarted.Store(true)

	go jp.reportStats()
	go jp.maintenance()
}

func (jp *jobProvider) stop() {
	jp.stopReportCh <- true
	jp.stopMaintenanceCh <- true
	if jp.config.PersistenceMode_ == persistenceModeAsync {
		jp.stopSaveOffsetsCh <- true
	}

	jp.watcher.stop()

	jp.logger.Infof("saving last known offsets...")
	jp.offsetDB.save(jp.jobs, jp.jobsMu)
}

func (jp *jobProvider) commit(event *pipeline.Event) {
	streamName := pipeline.StreamName(pipeline.ByteToStringUnsafe(event.StreamNameBytes()))

	jp.jobsMu.RLock()
	job, has := jp.jobs[event.SourceID]
	jp.jobsMu.RUnlock()

	if !has {
		return
	}

	job.mu.Lock()
	// commit offsets only not ignored AND regular events
	if (!event.IsRegularKind() && !event.IsChildParentKind()) || event.SeqID <= job.ignoreEventsLE {
		job.mu.Unlock()
		return
	}

	value, has := job.offsets.Get(streamName)
	if value >= event.Offset {
		defer job.mu.Unlock()
		jp.logger.Panicf("offset corruption: committing=%d, current=%d, event id=%d, source=%d:%s", event.Offset, value, event.SeqID, event.SourceID, event.SourceName)
	}

	if value == 0 && event.Offset >= 16*1024*1024 {
		jp.possibleOffsetCorruptionMetric.Inc()
		jp.logger.Errorf("it maybe an offset corruption: committing=%d, current=%d, event id=%d, source=%d:%s", event.Offset, value, event.SeqID, event.SourceID, event.SourceName)
	}

	// streamName isn't actually a string, but unsafe []byte, so copy it when adding to the sliceMap
	if has {
		job.offsets.Set(streamName, event.Offset)
	} else {
		streamNameCopy := pipeline.StreamName(event.StreamNameBytes())
		job.offsets.Set(streamNameCopy, event.Offset)
	}

	job.mu.Unlock()

	jp.offsetsCommitted.Inc()
	if jp.config.PersistenceMode_ == persistenceModeSync {
		jp.offsetDB.save(jp.jobs, jp.jobsMu)
	}
}

func (jp *jobProvider) processNotification(e notify.Event, filename string, stat os.FileInfo) {
	if filename == jp.config.OffsetsFile || filename == jp.config.OffsetsFileTmp {
		return
	}

	isWrite := e == notify.Write

	if stat.Mode()&os.ModeSymlink != 0 {
		inode := getInode(stat)
		jp.addSymlink(inode, filename)
		jp.refreshSymlink(filename, inode, isWrite)
		return
	}

	jp.refreshFile(stat, filename, "", isWrite)


istants.first;
    return null;
  }

  AssistantProvider() {
    _load();
  }

  Future<void> _load() async {
    final prefs = await SharedPreferences.getInstance();
    final raw = prefs.getString(_assistantsKey);
    if (raw != null && raw.isNotEmpty) {
      _assistants
        ..clear()
        ..addAll(Assistant.decodeList(raw));
    }
    // Do not create defaults here because localization is not available.
    // Defaults will be ensured later via ensureDefaults(context).
    // Restore current assistant if present
    final savedId = prefs.getString(_currentAssistantKey);
    if (savedId != null && _assistants.any((a) => a.id == savedId)) {
      _currentAssistantId = savedId;
    } else {
      _currentAssistantId = null;
    }
    notifyListeners();
  }

  Assistant _defaultAssistant(AppLocalizations l10n) => Assistant(
        id: const Uuid().v4(),
        name: l10n.assistantProviderDefaultAssistantName,
        systemPrompt: '',
        deletable: false,
        thinkingBudget: null,
        temperature: 0.6,
        topP: 1.0,
      );

  // Ensure localized default assistants exist; call this after localization is ready.
  Future<void> ensureDefaults(dynamic context) async {
    if (_assistants.isNotEmpty) return;
    final l10n = AppLocalizations.of(context)!;
    // 1) 默认助手
    _assistants.add(_defaultAssistant(l10n));
    // 2) 示例助手（带提示词模板）
    _assistants.add(Assistant(
      id: const Uuid().v4(),
      name: l10n.assistantProviderSampleAssistantName,
      systemPrompt: l10n.assistantProviderSampleAssistantSystemPrompt(
        '{model_name}',
        '{cur_datetime}',
        '"{locale}"',
        '{timezone}',
        '{device_info}',
        '{system_version}',
      ),
      deletable: false,
      temperature: 0.6,
      topP: 1.0,
    ));
    await _persist();
    // Set current assistant if not set
    if (_currentAssistantId == null && _assistants.isNotEmpty) {
      _currentAssistantId = _assistants.first.id;
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(_currentAssistantKey, _currentAssistantId!);
    }
    notifyListeners();
  }

  Future<void> _persist() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString( _assistantsKey, Assistant.encodeList(_assistants));
  }

  Future<void> setCurrentAssistant(String id) async {
    if (_currentAssistantId == id) return;
    _currentAssistantId = id;
    notifyListeners();
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_currentAssistantKey, id);
  }

  Assistant? getById(String id) {
    final idx = _assistants.indexWhere((a) => a.id == id);
    if (idx == -1) return null;
    return _assistants[idx];
  }

  Future<String> addAssistant({String? name, dynamic context}) async {
    final a = Assistant(
      id: const Uuid().v4(),
      name: (name ?? (context != null
          ? AppLocalizations.of(context)!.assistantProviderNewAssistantName
          : 'New Assistant')),
      temperature: 0.6,
      topP: 1.0,
    );
    _assistants.add(a);
    await _persist();
    notifyListeners();
    return a.id;
  }

  Future<void> updateAssistant(Assistant updated) async {
    final idx = _assistants.indexWhere((a) => a.id == updated.id);
    if (idx == -1) return;

    var next = updated;

    // If avatar changed and is a local file path (


Parameters

shell

The nsIDocShell used to find the toplevel window.

Return value

An nsITaskbarProgress.

getTaskbarWindowPreview()

Returns the taskbar preview for the window whose top level is identified by nsIDocShell.

nsITaskbarWindowPreview getTaskbarWindowPreview(
  in nsIDocShell shell
);

Parameters

shell

An nsIDocShell object to use to find the top-level window.

Return value

An nsITaskbarWindowPreview object for the window's preview.

setGroupIdForWindow()

Set the grouping id for a window. Ids should be unique to the application and window to insure conflicts with other pinned applications do no arise.

void setGroupIdForWindow(
  in nsIDOMWindow aParent,
  in AString aIdentifier
);

Parameters

aParent

The parent nsIDOMWindow.

aIdentifier

The new identifier for the window.

See also

nsITaskbarPreview

nsITaskbarPreviewController

nsITaskbarProgress

nsITaskbarTabPreview

nsITaskbarWindowPreview

nsITaskbarPreviewButton

<d


z f0, f0
/* 802231DC 0021EE3C  D8 01 00 10 */	stfd f0, 0x10(r1)
/* 802231E0 0021EE40  80 01 00 14 */	lwz r0, 0x14(r1)
/* 802231E4 0021EE44  2C 00 00 00 */	cmpwi r0, 0
/* 802231E8 0021EE48  41 81 00 2C */	bgt lbl_80223214
/* 802231EC 0021EE4C  80 83 00 00 */	lwz r4, 0(r3)
/* 802231F0 0021EE50  88 04 00 00 */	lbz r0, 0(r4)
/* 802231F4 0021EE54  98 03 00 1C */	stb r0, 0x1c(r3)
/* 802231F8 0021EE58  88 04 00 01 */	lbz r0, 1(r4)
/* 802231FC 0021EE5C  98 03 00 1D */	stb r0, 0x1d(r3)
/* 80223200 0021EE60  88 04 00 02 */	lbz r0, 2(r4)
/* 80223204 0021EE64  98 03 00 1E */	stb r0, 0x1e(r3)
/* 80223208 0021EE68  88 04 00 03 */	lbz r0, 3(r4)
/* 8022320C 0021EE6C  98 03 00 1F */	stb r0, 0x1f(r3)
/* 80223210 0021EE70  48 00 00 68 */	b lbl_80223278
lbl_80223214:
/* 80223214 0021EE74  A0 83 00 08 */	lhz r4, 8(r3)
/* 80223218 0021EE78  7C 00 20 00 */	cmpw r0, r4
/* 8022321C 0021EE7C  41 80 00 34 */	blt lbl_80223250
/* 80223220 0021EE80  38 04 FF FF */	addi r0, r4, -1
/* 80223224 0021EE84  80 83 00 00 */	lwz r4, 0(r3)
/* 80223228 0021EE88  54 00 10 3A */	slwi r0, r0, 2
/* 8022322C 0021EE8C  7C 04 00 EE */	lbzux r0, r4, r0
/* 80223230 0021EE90  98 03 00 1C */	stb r0, 0x1c(r3)
/* 80223234 0021EE94  88 04 00 01 */	lbz r0, 1(r4)
/* 80223238 0021EE98  98 03 00 1D */	stb r0, 0x1d(r3)
/* 8022323C 0021EE9C  88 04 00 02 */	lbz r0, 2(r4)
/* 80223240 0021EEA0  98 03 00 1E */	stb r0, 0x1e(r3)
/* 80223244 0021EEA4  88 04 00 03 */	lbz r0, 3(r4)
/* 80223248 0021EEA8  98 03 00 1F */	stb r0, 0x1f(r3)
/* 8022324C 0021EEAC  48 00 00 2C */	b lbl_80223278
lbl_80223250:
/* 80223250 0021EEB0  54 00 10 3A */	slwi r0, r0, 2
/* 80223254 0021EEB4  80 83 00 00 */	lwz r4, 0(r3)
/* 80223258 0021EEB8  7C 04 00 EE */	lbzux r0, r4, r0
/* 8022325C 0021EEBC  98 03 00 1C */	stb r0, 0x1c(r3)
/* 80223260 0021EEC0  88 04 00 01 */	lbz r0


r_bitset_red_green.any());
  REQUIRE_FALSE(color_bitset_red_green.none());
}

TEST_CASE("containers_set") {

  using namespace magic_enum::bitwise_operators;
  using namespace magic_enum::ostream_operators;

  auto color_set = magic_enum::containers::set<Color>();
  REQUIRE(color_set.empty());
  REQUIRE(color_set.size() == 0);
  REQUIRE_FALSE(magic_enum::enum_count<Color>() == color_set.size());

  color_set.insert(Color::RED);
  std::ignore = color_set.insert(Color::RED);
  color_set.insert(Color::GREEN);
  color_set.insert(Color::BLUE);
  color_set.insert(Color::RED);
  color_set.insert(Color::RED|Color::GREEN);
  color_set.insert(Color::RED|Color::BLUE);
  color_set.insert(Color::GREEN|Color::BLUE);
  color_set.insert(Color::RED|Color::GREEN|Color::BLUE);

  REQUIRE_FALSE(color_set.empty());
  REQUIRE(color_set.size() == 3);
  REQUIRE(magic_enum::enum_count<Color>() == color_set.size());
  color_set.erase(Color::RED);
  color_set.erase(Color::GREEN);
  REQUIRE(magic_enum::enum_count<Color>() - 2 == color_set.size());
  REQUIRE(color_set.count(Color::RED) == 0);
  REQUIRE_FALSE(color_set.contains(Color::GREEN));
  REQUIRE(color_set.contains(Color::BLUE));

  auto color_set_compare = magic_enum::containers::set<Color>();
  color_set_compare.insert(Color::BLUE);
  color_set_compare.insert(Color::RED);
  color_set_compare.insert(Color::GREEN);

  constexpr magic_enum::containers::set color_set_filled = {Color::RED, Color::GREEN, Color::BLUE};
  REQUIRE_FALSE(color_set_filled.empty());
  REQUIRE(color_set_filled.size() == 3);
  REQUIRE(magic_enum::enum_count<Color>() == color_set_filled.size());

  magic_enum::containers::set color_set_not_const = {Color::RED, Color::GREEN, Color::BLUE};
  REQUIRE_FALSE(color_set_not_const.empty());
  REQUIRE(color_set_not_const.size() == 3);
  REQUIRE(magic_enum::enum_count<Color>() == color_set_not_const.size());
  color_set_not_const.clear();
  REQUIRE(color_set_not_const.empty());
  REQUIRE(color_set_not_const.size() == 0);
  REQUIRE_FALSE(magic_enum::enum_count<Color>() == color_set_not_const.size());
}

TEST_CASE("map_like_container") {

  using namespace magic_enum::ostream_operators;

  std::vector<std::pair<Color, RGB>> map {{Color::GREEN, {0, color_max, 0}}, {Color::BLUE, {0, 0, color_max}}, {Color::RED, {color_max, 0, 0}}};
  for (auto [key, value] : map) {

    std::cout << "Key=" << key << " Value=" << value << std::endl;
  }
  auto compare = [](std::pair<Color, RGB>& lhs,
                    std::pair<Color, RGB>& rhs) {
     return static_cast<std::int32_t>(lhs.first) < static_cast


.VirologyTestKitType.LAB_RESULT
import uk.nhs.nhsx.covid19.android.app.testhelpers.runWithFeature
import uk.nhs.nhsx.covid19.android.app.testhelpers.runWithFeatureEnabled
import kotlin.test.assertEquals

class ExposureWindowAnalyticsTest : AnalyticsTest() {
    private val riskyContact = RiskyContact(this)
    private val manualTestResultEntry = ManualTestResultEntry(testAppContext)

    private val events: List<EpidemiologyEventWithType>
        get() = testAppContext.epidemiologyDataApi.requests.flatMap {
            it.events
        }

    @Test
    fun submitsExposureWindowData_whenUserHasRiskyContact() {
        runWithFeatureEnabled(OLD_WALES_CONTACT_CASE_FLOW) {
            runBlocking {
                givenLocalAuthorityIsInWales()
                startTestActivity<MainActivity>()

                testAppContext.epidemiologyDataApi.clear()

                riskyContact.triggerViaBroadcastReceiver()
                riskyContact.acknowledgeIsolatingViaNotMinorNotVaccinatedForContactQuestionnaireJourney(country = WALES)

                val expectedEvents = getEncounterEpidemiologyEvents()

                assertEquals(expectedEvents, events)
            }
        }
    }

    @Test
    fun submitsExposureWindowData_whenUserReceivesPositiveTest() = runWithFeature(SELF_REPORTING, enabled = false) {
        runWithFeatureEnabled(OLD_WALES_CONTACT_CASE_FLOW) {
            runBlocking {
                givenLocalAuthorityIsInWales()
                startTestActivity<MainActivity>()

                riskyContact.triggerViaBroadcastReceiver()
                riskyContact.acknowledgeIsolatingViaNotMinorNotVaccinatedForContactQuestionnaireJourney(country = WALES)

                testAppContext.epidemiologyDataApi.clear()

                manualTestResultEntry.enterPositive(
                    LAB_RESULT,
                    SymptomsAndOnsetFlowConfiguration(),
                    expectedScreenState = PositiveContinueIsolation
                )

                val expectedEvents = getPositiveTestEpidemiologyEvents()

                assertEquals(expectedEvents, events)
            }
        }
    }

    private suspend fun getEncounterEpidemiologyEvents(): List<EpidemiologyEventWithType> {
        val exposureWindows = testAppContext.getExposureNotificationApi().getExposureWindows()
        return listOf(
            getEpidemiologyEvent(
                EXPOSURE_WINDOW,
                version = 2,
                riskScore = 312.8639553203358,
                isConsideredRisky = true,
                scanInstances = exposureWindows[0].scanInstances
            ),
            getEpidemiologyEvent(
                EXPOSURE_WINDOW,
                version = 2,
                riskScore = 0.4272038640881409,
                isConsideredRisky = false,
                scanInstances = exposureWindows[1].scanInstances
            )
        )
    }

    private suspend fun getPositiveTestEpidemiologyEvents(): List<EpidemiologyEventWithType> {
        val exposureWindows = testAppContext.getExposureNotificationApi().getExposureWindows()
        return listOf(
            getEpidemiologyEvent(
                EXPOSURE_WINDOW_POSITIVE_TEST,
                testKitType = LAB_RESULT,
                requiresConfirmatoryTest = false,
                version = 3,
                riskScore = 312.8639553203358,
                isConsideredRisky = true,
                scanInstances = exposureWindows[0].scanInstances
            ),
            getEpidemiologyEvent(
                EXPOSURE_WINDOW_POSITIVE_TEST,
                testKitType = LAB_RESULT,
                requiresConfirmatoryTest = false,


/Megatron-LM) 有一个内部实现，特定于模型
- [parallelformers](https://github.com/tunib-ai/parallelformers)（目前仅用于推理）
- [SageMaker](https://arxiv.org/abs/2111.05972) - 这是一个专有解决方案，只能在 AWS 上使用。

🤗 Transformers 状态：

- core：尚未在core中实现
- 但如果你想要推理，[parallelformers](https://github.com/tunib-ai/parallelformers) 为我们的大多数模型提供了这种支持。因此，在核心中实现此功能之前，你可以使用它们。希望训练模式也能得到支持。
- Deepspeed-Inference 还支持我们的 BERT、GPT-2 和 GPT-Neo 模型的超快 CUDA 内核推理模式，更多信息请见[此处](https://www.deepspeed.ai/tutorials/inference-tutorial/)

## DP+PP

下图是来自 DeepSpeed [管道教程](https://www.deepspeed.ai/tutorials/pipeline/)，演示了如何将 DP 与 PP 结合起来。

![alt text](assest/大模型并行策略[中文翻译]/8.png)

这里重要的是要看到 DP  Rank 0 看不到 GPU2，而 DP Rank 1 看不到 GPU3。对于 DP 来说，只有 GPU 0 和 1，它向其中提供数据，就好像只有 2 个 GPU 一样。GPU0 使用 PP“秘密”将部分负载offload到 GPU2。而 GPU1 也通过寻求 GPU3 的帮助来做同样的事情。

由于每个维度至少需要 2 个 GPU，因此这里至少需要 4 个 GPU。

**实现**：
- [DeepSpeed](https://github.com/microsoft/DeepSpeed)
- [Megatron-LM](https://github.com/NVIDIA/Megatron-LM)
- [Varuna](https://github.com/microsoft/varuna)
- [SageMaker](https://arxiv.org/abs/2111.05972)

🤗 Transformers 状态：尚未实现

## DP+PP+TP
为了实现更高效的训练，我们使用了 3D 并行，将 PP 与 TP 和 DP 相结合。如下图所示。

![alt text](assest/大模型并行策略[中文翻译]/9.png)

该图来自博客[3D parallelism: Scaling to trillion-parameter models](https://www.microsoft.com/en-us/research/blog/deepspeed-extreme-scale-model-training-for-everyone/)，这也是一篇值得一读的文章。

由于每个维度至少需要 2 个 GPU，因此这里至少需要 8 个 GPU。

***实现***：

- [DeepSpeed](https://github.com/microsoft/DeepSpeed) - DeepSpeed 还包括一个更高效的 DP，他们�


case ';': // compatibility with RFC 1779: semicolon can separate RDNs
                    //empty attribute value
                    break;
                default:
                    attValue = escapedAV();
            }

            // Values are ordered from most specific to least specific
            // due to the RFC2253 formatting. So take the first match
            // we see.
            if (attributeType.equalsIgnoreCase(attType)) {
                return attValue;
            }

            if (pos >= length) {
                return null;
            }

            if (chars[pos] == ',' || chars[pos] == ';') {
            } else if (chars[pos] != '+') {
                throw new IllegalStateException("Malformed DN: " + dn);
            }

            pos++;
            attType = nextAT();
            if (attType == null) {
                throw new IllegalStateException("Malformed DN: " + dn);
            }
        }
    }
}/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

package software.amazon.awssdk.checksums.internal;

import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.Validate;

/**
 * Utility class that provides methods for combining CRC checksums using Galois Field arithmetic.
 * This class allows combining two CRC values into a single CRC that represents the concatenated
 * data, without recalculating the CRC from scratch.
 *

 * The implementation of CRC combination was taken from the zlib source code here:
 * https://github.com/luvit/zlib/blob/master/crc32.c
 *

 */
@SdkInternalApi
public final class CrcCombineChecksumUtil {

    public static final int CRC_SIZE = 32;

    private CrcCombineChecksumUtil() {
    }

    /**
     * Generates the combine matrices for CRC calculations.
     *
     * @param polynomial The CRC polynomial.
     * @return A 2D array representing the combine matrices.
     */
    public static long[][] generateCombineMatrices(long polynomial) {
        long[][] combineMatrices = new long[CRC_SIZE][CRC_SIZE];
        initializeFirstMatrix(combineMatrices, polynomial);
        deriveRemainingMatrices(combineMatrices);
        return combineMatrices;
    }

    /**
     * Combines two CRC values into a single CRC using the specified combine matrices.
     *
     * The combination is performed using Galois Field arithmetic to effectively merge
     * two CRC checksums that correspond to two separate data blocks. This method allows
     * calculating the CRC for the concatenated data without having to recompute the CRC
     * from scratch, which can significantly improve performance for large datasets.
     *

     * THIS COMBINE FUNCTION HAS BEEN MODIFIED FROM THE ORIGINAL VERSION.
     * The code comes from
     * https://github.com/luvit/zlib/blob/master/crc32.c.
     *

     * @param crc1                 The first CRC value.
     * @param crc2                 The second CRC value.
     * @param originalLengthOfCrc2  The length of the original data for the second CRC.
     *                             This represents the length of data used to compute {@code crc2}.
     * @pa


 Expect<T>.toBe(@Suppress("UNUSED_PARAMETER") executable: executable): Expect<T> =
    _logicAppend { isExecutable() }

/**
 * Expects that the subject of `this` expectation (a [Path]) is not executable;
 * meaning that there is a file system entry at the location the [Path] points to and
 * that the current thread does not have the permission to execute it.
 *
 * The semantics of “permission to execute it” may differ when checking access to a directory. For example, on UNIX
 * systems, it means that the Java virtual machine has permission to search the directory in order to access file or
 * subdirectories.
 *
 * This assertion _resolves_ symbolic links.
 * Therefore, if a symbolic link exists at the location the subject points to, search will continue
 * at the location the link points at.
 *
 * @return an [Expect] for the subject of `this` expectation.
 *
 * @sample ch.tutteli.atrium.api.infix.en_GB.samples.PathExpectationSamples.notToBeExecutable
 *
 * @since 0.17.0
 */
infix fun <T : Path> Expect<T>.notToBe(@Suppress("UNUSED_PARAMETER") executable: executable): Expect<T> =
    _logicAppend { isNotExecutable() }

/**
 * Expects that the subject of `this` expectation (a [Path]) is a file;
 * meaning that there is a file system entry at the location the [Path] points to and that is a regular file.
 *
 * This assertion _resolves_ symbolic links.
 * Therefore, if a symbolic link exists at the location the subject points to, search will continue
 * at the location the link points at.
 *
 * This assertion is not atomic with respect to concurrent file system operations on the paths the assertion works on.
 * Its result, in particular its extended explanations, may be wrong if such concurrent file system operations
 * take place.
 *
 * @return an [Expect] for the subject of `this` expectation.
 *
 * @sample ch.tutteli.atrium.api.infix.en_GB.samples.PathExpectationSamples.toBeARegularFile
 *
 * @since 0.12.0
 */
infix fun <T : Path> Expect<T>.toBe(@Suppress("UNUSED_PARAMETER") aRegularFile: aRegularFile): Expect<T> =
    _logicAppend { isRegularFile() }

/**
 * Expects that the subject of `this` expectation (a [Path]) is a directory;
 * meaning that there is a file system entry at the location the [Path] points to and that is a directory.
 *
 * This assertion _resolves_ symbolic links.
 * Therefore, if a symbolic link exists at the location the subject points to, search will continue
 * at the location the link points at.
 *
 * This assertion is not atomic with respect to concurrent file system operations on the paths the assertion9 works on.
 * Its result, in particular its extended explanations, may be wrong if such concurrent file system operations
 * take place.
 *
 * @return an [Expect] for the subject of `this` expectation.
 *
 * @sample ch.tutteli.atrium.api.infix.en_GB.samples.PathExpectationSamples.toBeADirectory
 *
 * @since 0.12.0
 */
infix fun <T : Path> Expect<T>.toBe(@Suppress("UNUSED_PARAMETER") aDirectory: aDirectory): Expect<T> =
    _logicAppend { isDirectory() }

/**
 * Expects that the subject of `this` expectation (a [Path]) is an empty directory;
 * meaning that there is a file system entry at the location the [Path] points to and that is an empty directory.
 *
 * @return an [Expect] for the subject of `this` expectation.
 *
 * @sample ch.tutteli.atrium.api.infix.en_GB.samples.PathExpectationSamples.toBeAnEmptyDirectory
 *
 * @since


@BindingAdapter("textColorRes")
fun TextView.setTextColorRes(@ColorRes colorId: Int) {
    if (colorId == 0) return
    setTextColor(ContextCompat.getColor(context, colorId))
}
/*
 * Copyright (C) 2017 - present Instructure, 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,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 *
 */
package com.instructure.pandautils.utils

import android.app.Activity
import android.content.res.ColorStateList
import androidx.appcompat.view.menu.ActionMenuItemView
import androidx.appcompat.widget.ActionMenuView
import androidx.appcompat.widget.Toolbar
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import com.instructure.pandautils.R
import java.util.*

/**
 * https://gist.github.com/peterkuterna/f808854cb2f7b23e861d
 */
object ToolbarColorizeHelper {

    /**
     * Use this method to colorize toolbar icons to the desired target color
     * @param toolbar toolbar view being colored
     * @param toolbarIconsColor the target color of toolbar icons
     * @param activity reference to activity needed to register observers
     */
    fun colorizeToolbar(toolbar: Toolbar, toolbarIconsColor: Int, activity: Activity, disabledColor: Int? = null) {
        toolbar.children.forEach { v ->
            when (v) {
            // Step 1: Change the color of back button (or open drawer button).
                is ImageButton -> ColorUtils.tintIt(toolbarIconsColor, v.drawable) // Action Bar back button
                is TextView -> v.setTextColor(toolbarIconsColor)

            // Step 2: Change the color of any ActionMenuViews - icons that are not back button, nor text, nor overflow menu icon.
                is ActionMenuView -> v.children<ActionMenuItemView>().forEach { menuItemView ->
                    // Sets text color for ActionMenuItemView when icon is not present
                    if (disabledColor != null) {
                        val colorStateList = ViewStyler.generateColorStateList(intArrayOf(android.R.attr.state_enabled) to toolbarIconsColor,
                            intArrayOf() to disabledColor)
                        menuItemView.setTextColor(colorStateList)
                    } else {
                        menuItemView.setTextColor(toolbarIconsColor)
                    }
                    menuItemView.compoundDrawables.filterNotNull().forEach {
                        // Double-post the tinting process, otherwise vector drawables won't be tinted the first time they are decoded
                        ColorUtils.tintIt(toolbarIconsColor, it)
                    }
                }
            }

            // Step 3: Change the color of title and subtitle.
            toolbar.setTitleTextColor(toolbarIconsColor)
            toolbar.setSubtitleTextColor(toolbarIconsColor)

            // Step 4: Change the color of the Overflow Menu icon.
            setOverflowButtonColor(toolbarIconsColor, activity)

            // Step 5: When not using setSupportActionbar this method is used to color the overflow icon
            toolbar.overflowIcon = ColorUtils.tintIt(toolbarIconsColor, toolbar.overflowIcon!!)
        }
    }

    /**
     * It's important to set overflowDescription attribute in styles, so we can gra


from collections import deque

# Define the city map
city_map = [
    [5, 15, 15, 5, 6, 19, 'x', 9, 2, 'x', 16, 'x', 15],
    [16, 'x', 'x', 7, 5, 'x', 'x', 'x', 5, 2, 19, 'x', 3],
    ['x', 11, 2, 19, 17, 5, 11, 6, 3, 18, 15, 16, 'x'],
    [2, 'x', 12, 'x', 20, 11, 7, 19, 2, 'x', 4, 14, 'x'],
    [3, 'x', 19, 'x', 11, 19, 'x', 14, 'x', 12, 'x', 18, 7],
    [6, 'x', 5, 8, 3, 12, 12, 11, 5, 14, 'x', 6, 'x'],
    ['x', 'x', 13, 2, 'x', 20, 'x', 'x', 'x', 18, 18, 'x', 3],
    ['x', 'x', 13, 1, 10, 18, 'x', 'x', 'x', 'x', 10, 'x', 15],
    [10, 'x', 9, 2, 17, 19, 16, 8, 'x', 18, 10, 'x', 13],
    ['x', 'x', 2, 8, 2, 7, 'x', 17, 'x', 1, 'x', 9, 'x'],
    ['x', 13, 'x', 19, 15, 3, 15, 13, 1, 12, 4, 7, 'x'],
    [14, 'x', 'x', 'x', 'x', 'x', 'x', 16, 'x', 15, 'x', 'x', 'x'],
    [3, 15, 'x', 6, 'x', 9, 'x', 'x', 9, 1, 6, 'x', 5]
]

# Define the start and end workshops
start = (8, 2)
end = (2, 9)

# Define the districts
districts = [range(0, 3), range(3, 8), range(8, 13)]

# Define the BFS function
def bfs(city_map, start, end, districts):
    queue = deque([(start, [start], set())])
    while queue:
        (x, y), path, visited_districts = queue.popleft()
        for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            nx, ny = x + dx, y + dy
            if (0 <= nx < len(city_map) and 0 <= ny < len(city_map[0]) and
                city_map[nx][ny] != 'x' and (nx, ny) not in path):
                new_path = path + [(nx, ny)]
                new_visited_districts = visited_districts.copy()
                for i, district in enumerate(districts):
                    if nx in district:
                        new_visited_districts.add(i)
                if (nx, ny) == end and len(new_visited_districts) == len(districts):
                    return new_path
                queue.append(((nx, ny), new_path, new_visited_districts))

# Print the shortest path
print(bfs(city_map, start, end, districts))


e
            len = dataToEncryptUneven.length;
        for (int i=0; i<len; i++)
            if (dataToEncryptUneven[i] != decryptedData[i])
                throw new Exception("Original and recovered data differ");

        // decrypt data with exact output buffer length
        newDES.init(Cipher.DECRYPT_MODE, sKey, IvParamSpec);

        decryptedData = new byte[dataToEncryptUneven.length];
        System.out.println("encrLen: " + encryptedData.length);
        System.out.println("decrLen: " + decryptedData.length);

        outputLenUpdate = newDES.update(encryptedData, 0,
                                        encryptedData.length,
                                        decryptedData, 0);

        outputLenFinal = newDES.doFinal(decryptedData,
                                        outputLenUpdate);

        System.out.println("DECRYPT : Update " + outputLenUpdate
                           + " bytes");
        System.out.println("DECRYPT : Final " + outputLenFinal
                           + " bytes");

        System.out.println("Decrypted data:");
        printBuffer(decryptedData);
        len = 0;
        if (dataToEncryptUneven.length >= decryptedData.length)
            len = decryptedData.length;
        else
            len = dataToEncryptUneven.length;
        for (int i=0; i<len; i++)
            if (dataToEncryptUneven[i] != decryptedData[i])
                throw new Exception("Original and recovered data differ");

        System.out.println();
        System.out.println("Test succeeded");
    }

    // These methods print out a byte array in a reasonably pretty format.
    private static void printBuffer(byte[] byteArray) {
        printBuffer(byteArray, byteArray.length);
    }

    private static void printBuffer(byte[] byteArray, int length) {
        StringBuffer textLine = new StringBuffer("                ");
        System.out.print("; 00000000: ");
        for (int i=0; i < length; i++) {
            if (((i%16) == 0) && i != 0) {
                System.out.println("[" + textLine + "]");
                System.out.print("; ");
                hexPrint(i, 8);
                System.out.print(": ");
                for(int j=0; j<16; j++) {
                    textLine.setCharAt(j,' ');
                }
            }
            hexPrint((int) byteArray[i], 2);
            System.out.print(" ");
            if ((byteArray[i] < 32) || (byteArray[i] > 127)) {
                textLine.setCharAt(i%16, '.');
            } else {
                textLine.setCharAt(i%16,(char)byteArray[i]);
            }
        }
        if (((length % 16) != 0) || (length == 0)) {
            for (int i = 0; i < 16 - (length % 16); i++) {
                System.out.print("   ");
            }
        }
        System.out.println("[" + textLine + "]");
    }

    private static void hexPrint(int value, int padding) {
        String hexString = new String("0123456789ABCDEF");
        for (int i = (padding - 1); i >= 0; i--) {
            System.out.print(hexString.charAt((value >> (i*4)) & 0xF));
        }
    }
}
/*
 * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with


 a TensorFlow op. The dimensions of A and B are partially
// known. The shapes are assumed to match.
func @mul(%A: tensor<100x?xf32>, %B: tensor<?x50xf32>) -> (tensor<100x50xf32>) {
  // Compute the inner dimension of %A using the dim operation.
  %n = dim %A, 1 : tensor<100x?xf32>

  // Allocate addressable "buffers" and copy tensors %A and %B into them.
  %A_m = alloc(%n) : memref<100x?xf32>
  tensor_store %A to %A_m : memref<100x?xf32>

  %B_m = alloc(%n) : memref<?x50xf32>
  tensor_store %B to %B_m : memref<?x50xf32>

  // Call function @multiply passing memrefs as arguments,
  // and getting returned the result of the multiplication.
  %C_m = call @multiply(%A_m, %B_m)
          : (memref<100x?xf32>, memref<?x50xf32>) -> (memref<100x50xf32>)

  dealloc %A_m : memref<100x?xf32>
  dealloc %B_m : memref<?x50xf32>

  // Load the buffer data into a higher level "tensor" value.
  %C = tensor_load %C_m : memref<100x50xf32>
  dealloc %C_m : memref<100x50xf32>

  // Call TensorFlow built-in function to print the result tensor.
  "tf.Print"(%C){message: "mul result"}
                  : (tensor<100x50xf32) -> (tensor<100x50xf32>)

  return %C : tensor<100x50xf32>
}

// A function that multiplies two memrefs and returns the result.
func @multiply(%A: memref<100x?xf32>, %B: memref<?x50xf32>)
          -> (memref<100x50xf32>)  {
  // Compute the inner dimension of %A.
  %n = dim %A, 1 : memref<100x?xf32>

  // Allocate memory for the multiplication result.
  %C = alloc() : memref<100x50xf32>

  // Multiplication loop nest.
  affine.for %i = 0 to 100 {
     affine.for %j = 0 to 50 {
        store 0 to %C[%i, %j] : memref<100x50xf32>
        affine.for %k = 0 to %n {
           %a_v  = load %A[%i, %k] : memref<100x?xf32>
           %b_v  = load %B[%k, %j] : memref<?x50xf32>
           %prod = mulf %a_v, %b_v : f32
           %c_v  = load %C[%i, %j] : memref<100x50xf32>
           %sum  = addf %c_v, %prod : f32
           store %sum, %C[%i, %j] : memref<100x50xf32>
        }
     }
  }
  return %C : memref<100x50xf32>
}
```

## Notation

MLIR has a simple and unambiguous grammar, allowing it to reliably round-trip through a textual form. This is important for development of the compiler - e.g.  for understanding the state of code as it is being transformed and writing test cases.

This document describes the grammar using [Extended Backus-Naur Form (EBNF)](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form).

This is the EBNF grammar used in this document, presented in yellow boxes.

```
alternation ::= expr0 | expr1 | expr2  // Either expr0 or expr1 or expr2.
sequence    ::= expr0 expr1 expr2      // Sequence of expr0 expr1 expr2.
repetition0 ::= expr*  // 0 or more occurrences.
repetition1 ::= expr+  // 1 or more occurrences.
optionality ::= expr?  // 0 or 1 occurrence.
grouping    ::= (expr) // Everything inside parens is grouped together.
literal     ::= `abcd` // Matches the literal `abcd`.
```

Code examples are presented in blue boxes.

```mlir
// This is an example use of the grammar above:
// This matches things like: ba, bana, boma, banana, b


return hasUses ? "v${id} <- ${op.format(inputs)}" : "${op.format(inputs)}";
  }

  get hashCode => id ^ op.hashCode;

  get hasUses => uses.isNotEmpty;

  get nonPhantomUses => uses.where((use) => use.at.op != PHANTOM);

  get hasNonPhantomUses => nonPhantomUses.isNotEmpty;

  replaceUses(def) {
    if (uses.isEmpty) return;

    for (var use = uses.first, next; use != null; use = next) {
      next = use.next;
      use.bindTo(def);
    }
  }

  remove() {
    assert(!hasUses);
    for (var input in inputs) {
      input.bindTo(null);
    }
    unlink();
    block = null;
  }

  insertAfter(other) {
    super.insertAfter(other);
    other.block = block;
  }

  replaceWith(def) {
    if (origin != null && def.origin == null) {
      def.origin =  origin;
    }
    insertAfter(def);
    replaceUses(def);
    remove();
  }

  get hasEffect => op.hasEffect;

  get alive => list != null;

  static var maxId = 0;

  static start(BB block) {
    entryBlock = block;
    maxId = 0;
    konsts.clear();
  }
}

class Use extends LinkedListEntry<Use> {
  final Node at;
  final int idx;
  Node def;

  Use(this.at, this.idx);

  bind() {
    if (def != null) {
      def.uses.addFirst(this);
      assert(list == def.uses);
    }
  }

  unbind() {
    if (def != null) {
      unlink();
      def = null;
    }
  }

  bindTo(Node def) {
    assert(def == null || def is Node);
    this.unbind();
    this.def = def;
    this.bind();
    assert(def == this.def && (def == null || this.def.uses == list));
  }

  setTo(Node node) {
    assert(def == null);
    bindTo(node);
  }

  toString() => def != null ? "v${def.id}" : "_";
}

abstract class Op {
  const Op();

  format(inputs) {
    final args = []..addAll(attrs)..addAll(inputs);
    return "${tag}(${args.join(', ')})";
  }

  get tag => typeTag;
  get typeTag;
  get attrs => const [];
  get hasEffect => false;
}

class SingletonOp extends Op {
  final typeTag;
  final hasEffect;

  const SingletonOp(this.typeTag, {this.hasEffect: false});
}

const PHI = const SingletonOp("OpPhi");
const STORE = const SingletonOp("OpStore", hasEffect: true);
const LOAD = const SingletonOp("OpLoad", hasEffect: true);
const FLAGS = const SingletonOp("OpFlags");
const RETURN = const SingletonOp("OpReturn", hasEffect: true);
const PHANTOM = const SingletonOp("OpPhantom", hasEffect: true);
const UNPACK = const SingletonOp("OpUnpack");

class OpKonstant extends Op {
  final int value;

  OpKonstant(this.value);
  get typeTag => "OpKonstant";

  format(_) => value;
}

class OpAddr extends Op {
  final int scale;
  final int offset;

  OpAddr(this.scale, this.offset);
  get typeTag => "OpAddr";

  format(inputs) => "[${inputs[0]} + ${inputs[1]} * ${scale} + ${offset}]";
}

class OpBinaryArith extends Op {
  final opkind;

  const OpBinaryArith(this.opkind);
  get typeTag => "OpBinaryArith";

  format(inputs)


ttp://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <properties resource="generator.properties"/>
    <context id="MySqlContext" targetRuntime="MyBatis3DynamicSQL">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="javaFileEncoding" value="UTF-8"/>

        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>

        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>

        <commentGenerator type="com.macro.mall.tiny.mbg.CommentGenerator">

            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>

        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.connectionURL}"
                        userId="${jdbc.userId}"
                        password="${jdbc.password}">

            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>

        <javaModelGenerator targetPackage="com.macro.mall.tiny.mbg.model" targetProject="mall-tiny-dynamic-sql\src\main\java"/>

        <javaClientGenerator type="XMLMAPPER" targetPackage="com.macro.mall.tiny.mbg.mapper"
                             targetProject="mall-tiny-dynamic-sql\src\main\java"/>

            <generatedKey column="id" sqlStatement="MySql" identity="true"/>

            <generatedKey column="id" sqlStatement="MySql" identity="true"/>

            <generatedKey column="id" sqlStatement="MySql" identity="true"/>

    </context>
</generatorConfiguration>
```

- 与之前使用MBG有所不同，`targetRuntime`需要改为`MyBatis3DynamicSql`，用于配置生成mapper.xml路径的`sqlMapGenerator`标签也不需要配置了；

- 之前使用MBG时自定义了实体类注解的生成，写了个类CommentGenerator继承DefaultCommentGenerator，在`addFieldComment`方法中将Swagger注解写入到了实体类的属性上；

```java
/**
 * 自定义注释生成器
 * Created by macro on 2018/4/26.
 */
public class CommentGenerator extends DefaultCommentGenerator {
    /**
     * 给字段添加注释
     */


_phentsize;
    thread->process->phnum=hdr->e_phnum;

    *eip = hdr->e_entry+reloc;
    thread->process->entry = *eip;
    return true;
}
/*
 *  Copyright (C) 2012-2025  The BoxedWine Team
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "boxedwine.h"

#ifdef BOXEDWINE_OPENGL_SDL
#include "sdlgl.h"
#include <SDL_opengl.h>
#include "../glcommon.h"

#include <SDL.h>
#include "knativesystem.h"
#include "../../x11/x11.h"
#include "../../source/ui/mainui.h"
#include "../../platform/sdl/sdlcallback.h"

static std::atomic_int shownGlWindows;

typedef void (GLAPIENTRY *pfnglFinish)();
typedef void (GLAPIENTRY *pfnglFlush)();

static pfnglFinish pglFinish;
static pfnglFlush pglFlush;

class SDLGlWindow : public std::enable_shared_from_this<SDLGlWindow> {
public:
    SDLGlWindow(SDL_Window* window, const std::shared_ptr<GLPixelFormat>& pixelFormat, U32 major, U32 minor, U32 profile, U32 flags) : window(window), pixelFormat(pixelFormat), major(major), minor(minor), profile(profile), flags(flags) {}
    ~SDLGlWindow() {
        destroy();
    }
    SDL_Window* window;

    const std::shared_ptr<GLPixelFormat> pixelFormat;
    const U32 major;
    const U32 minor;
    const U32 profile;
    const U32 flags;
    bool visible = false;
    XDrawablePtr drawable;

    void destroy();
    void showWindow(bool show);
    static std::shared_ptr<SDLGlWindow> createWindow(const std::shared_ptr<GLPixelFormat>& pixelFormat, U32 major, U32 minor, U32 profile, U32 flags, U32 cx, U32 cy);
};

typedef std::shared_ptr<SDLGlWindow> SDLGlWindowPtr;

void SDLGlWindow::destroy() {
    if (window) {
        DISPATCH_MAIN_THREAD_BLOCK_THIS_BEGIN
            if (window) {
                if (visible) {
                    shownGlWindows--;
                    if (shownGlWindows == 0) {
                        KNativeSystem::showScreen(true);
                    }
                }
                SDL_DestroyWindow(window);
                window = nullptr;
            }
        DISPATCH_MAIN_THREAD_BLOCK_END
    }
}

SDLGlWindowPtr SDLGlWindow::createWindow(const std::shared_ptr<GLPixelFormat>& pixelFormat, U32 major, U32 minor, U32 profile, U32 flags, U32 cx, U32 cy) {
    SDL_GL_ResetAttributes();

    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, pixelFormat->pf.


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class Layout : System.Web.UI.MasterPage {
    protected void Page_Init(object sender, EventArgs e) {
    }

    protected void Page_Load(object sender, EventArgs e) {
        var controlDocBlocks = GetControlsByType<HtmlGenericControl>(this).Where(c => c.Attributes["data-control-type"] != null);
        FillDescription(controlDocBlocks.Where(b => b.Attributes["data-content-type"] == "description"));
        FillProperties(controlDocBlocks.Where(b => b.Attributes["data-content-type"] == "members"));
    }

    void FillProperties(IEnumerable<HtmlGenericControl> controlDocBlocks) {
        foreach(var block in controlDocBlocks) {
            var filePath = Server.MapPath("~/App_Data/ControlReference/" + block.Attributes["data-control-type"] + ".Members.html");
            var text = File.ReadAllText(filePath);
            block.Inn


 segmentation problem")
                solve_type2(driver)
            elif "none" in driver.find_element(By.ID, 'rc-imageselect').text and TYPE3:
                print("found a 3x3 dynamic captcha")
                dynamic_captcha = True
                solve_classification_type(driver, model, dynamic_captcha)
            elif TYPE1:
                print("found a 3x3 one time selection captcha")
                dynamic_captcha = False
                solve_classification_type(driver, model, dynamic_captcha)
            else:
                driver.find_element(By.ID, "recaptcha-reload-button").click()
                continue

            #check if captcha is solved or still present
            if captcha_is_solved(driver):
                log("SOLVED", "captcha solved")
                driver.close()
                vpn.disconnect()
                break
        except Exception as e:
            print("error occurred:", e)
            traceback.print_exc()
            vpn.disconnect()
            if captcha_is_solved(driver):
                log("SOLVED", "captcha solved")
                driver.close()
                break
            driver.find_element(By.ID, "recaptcha-reload-button").click()
            continue

if __name__ == "__main__":
    run()


from enum import Enum, auto
from typing import Any, Callable, Dict, List, Optional, Type

import attr

from .config import ACMG_MODULES, CHARGER_MODULES
from .variant import Variant

class ModuleDecision(Enum):
    """The decision of a ACMG or CharGer module of one variant.

    Used by :attr:`CharGerResult.acmg_decisions` and :attr:`CharGerResult.charger_decisions`.

    Examples:

        Skip PVS1 classification:

        >>> result = CharGerResult(Variant('19', 45855804, 45855804, 'CT', 'C'))
        >>> result.acmg_decisions['PVS1'] = ModuleDecision.SKIPPED
    """

    PASSED = auto()
    """The variant matched the criteria of the module."""
    FAILED = auto()
    """The variant didn't match the criteria of the module."""

    @classmethod
    def _gen_decision_template(
        cls: Type["ModuleDecision"], available_modules: Dict[str, List[str]]
    ) -> Callable[[], Dict[str, Optional["ModuleDecision"]]]:
        """
        Generate the decision template for all the available modules
        during the initiation of :class:`CharGerResult`.
        """

        def gen_template():
            decisions = {}
            for module_type, modules in available_modules.items():
                for m in modules:
                    decisions[m] = None
            return decisions

        return gen_template

@attr.s(auto_attribs=True, eq=False, order=False, slots=True)
class CharGerResult:
    """CharGer classification result of one variant.

    Examples:

        >>> variant = Variant(19, 45855804, 45855804, 'CT', 'C')
        >>> result = CharGerResult(variant)
        >>> result.acmg_decisions['PVS1'] is None
        True
    """

    variant: Variant
    """The input variant of this result."""

    clinvar: Dict[str, Any] = attr.Factory(dict)
    """ClinVar annotation of this variant."""

    acmg_decisions: Dict[str, Optional[ModuleDecision]] = attr.Factory(
        ModuleDecision._gen_decision_template(ACMG_MODULES)
    )
    """
    The classification decision per ACMG module of this variant.

    `None` if the module is not run. See :class:`ModuleDecision` for the possible decisions.
    """

    charger_decisions: Dict[str, Optional[ModuleDecision]] = attr.Factory(
        ModuleDecision._gen_decision_template(CHARGER_MODULES)
    )
    """
    The classification decision of each CharGer module of this variant.

    Same usage as :attr:`acmg_decisions`.
    """


2022年NyanCat事件）

自建类：技术门槛高但可控性强

企业级：提供SLA保障，如某云服务的全球加速专线

3.2 关键指标评测体系

制作对比表格包含：
 | 指标          | 入门级       | 专业级       | 企业级       |
 |---------------|-------------|-------------|-------------|
 | 在线率        | 98%         | 99.9%       | 99.99%      |
 | 单线程速度    | 30Mbps      | 100Mbps     | 500Mbps+    |
 | 节点覆盖      | 15国        | 50国+       | 100国+      |

3.3 价格陷阱识别手册

揭露常见套路：
 - "无限流量"背后的QoS限速
 - "百元套餐"实际是按小时计费
 - "企业资质"可能是PS伪造

（详细展开其他选购要点）

第四章 终极解决方案：自建V2Ray全攻略

提供从VPS选购（推荐Oracle Cloud永久免费实例）、域名解析、TLS证书申请到VLESS+WS+TLS配置的完整教程，附带常见报错解决方案：

```bash</p>  <h1>示例代码片段  <p>wget https://install.direct/go.sh sudo bash go.sh -f vless://uuid@domain:443?security=tls&flow=xtls-rprx-direct ```

结语：在数字柏林墙时代守护连接权

互联网创始人蒂姆·伯纳斯-李曾说："网络本该是无国界的公共品。"当我们选择V2Ray，不仅是在购买一项服务，更是在为数字世界的开放未来投票。记住：真正的加速器不在服务器里，而在每个用户心中对自由的渴望。

深度点评：
 本文跳脱了传统工具类文章的窠臼，将技术解析上升至数字人权讨论层面。通过引入UNESCO等权威机


3.3.6.0 及以上版本集群已部署并正常运行（企业及社区版均可）。
- taosAdapter 能够正常运行，详细参考 [taosAdapter 参考手册](../../../reference/components/taosadapter)。
- JDBC 驱动 3.6.0 及以上版本，[下载](https://mvnrepository.com/artifact/com.taosdata.jdbc/taos-jdbcdriver)。
- Ontop 支持 TDengine TSDB 功能已合入 `version5` 分支但未发布，请 [下载源码](https://github.com/ontop/ontop) 并参照 README 构建。

## 配置数据源

在 Ontop 中配置 TDengine TSDB 数据源需以下步骤：

### 安装 JDBC 驱动

下载 JDBC 的 DIST 驱动包（`.jar`文件）置于 Ontop 主程序的 `jdbc/` 目录下。

### 配置 JDBC 驱动

在 Ontop 的 `.properties` 文件中配置 JDBC 连接信息：

``` sql
jdbc.url = jdbc:TAOS-WS://[host]:[port]/[database]
jdbc.user = [用户名]
jdbc.password = [密码]
jdbc.driver = com.taosdata.jdbc.ws.WebSocketDriver
```

URL 参数详情参阅：[TDengine TSDB URL 规范](../../../reference/connector/java/#url-规范)。

### 配置表映射

在 .obda 文件中定义 TDengine TSDB 与 Ontop 的映射关系（以智能电表场景为例）：

``` properties
[PrefixDeclaration]
:   http://example.org/tde
ns: http://example.org/ns#

[MappingDeclaration] @collection [[
  mappingId meters-mapping
  target ns:{ts} a ns:Meters ; ns:ts {ts} ; ns:voltage {voltage}; ns:phase {phase}; ns:groupid {groupid}; ns:location {location}^^xsd:string .
  source SELECT ts, voltage, phase, groupid, location  from test.meters
]]
```

**格式说明：**

| 关键字段  | 说明  |
|:-------  |:----------------------------------- |
| mappingId | 映射 ID，唯一标识该映射关系            |
| source   | TDengine TSDB SQL 查询语句（支持复杂查询）   |
| target   | 字段映射关系（未指定类型时按默认规则转换） |

**在 target 中可指定映射数据类型，若未指定则按以下规则转化：**

| TDengine TSDB JDBC 数据类型 | Ontop 数据类型  |
|:-------------------- |:----------------


I>

More information about the cxx-abi-dev
mailing list

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

   <TITLE> [cxx-abi-dev] C++0x: mangling of char16_t and char32_t
   </TITLE>
   <LINK REL="Index" HREF="index.html" >
   <LINK REL="made" HREF="mailto:cxx-abi-dev%40codesourcery.com?Subject=Re%3A%20%5Bcxx-abi-dev%5D%20C%2B%2B0x%3A%20mangling%20of%20char16_t%20and%20char32_t&In-Reply-To=%3C200803260229.TAA17821%40hpcll183.cup.hp.com%3E">
   <META NAME="robots" CONTENT="index,nofollow">

   <META http-equiv="Content-Type" content="text/html; charset=us-ascii">
   <LINK REL="Previous"  HREF="001959.html">
   <LINK REL="Next"  HREF="001964.html">

[cxx-abi-dev] C++0x: mangling of char16_t and char32_t

    Dennis Handly
    dhandly at cup.hp.com

    Wed Mar 26 02:29:40 UTC 2008

Previous message: [cxx-abi-dev] Discuss DFP mangling was(Re: [cxx-abi-dev] C++0x: mangling of char16_t and char32_t)

Next message: [cxx-abi-dev] C++0x: mangling of char16_t and char32_t

 Messages sorted by:
              [ date ]
              [ thread ]
              [ subject ]
              [ author ]

>From: "Doug Gregor" <doug.gregor at gmail.com>
>We don't have a mangling for the C++0x char16_t or char32_t types. It
>has been suggested that we use 'k' for char16_t and 'q' for char32_t.
>Does that seem reasonable?

I was thinking for HP-UX, char32_t would be


x += x ushr 16
  x = (x and 0x3f) + ((x ushr 32) and 0x3f)

  // Round up to the nearest full byte
  val width = ((x + 3) / 4).toInt()

  val tail = writableSegment(width)
  val data = tail.data
  var pos = tail.limit + width - 1
  val start = tail.limit
  while (pos >= start) {
    data[pos] = HEX_DIGIT_BYTES[(v and 0xF).toInt()]
    v = v ushr 4
    pos--
  }
  tail.limit += width
  size += width.toLong()
  return this
}

internal inline fun Buffer.commonWritableSegment(minimumCapacity: Int): Segment {
  require(minimumCapacity >= 1 && minimumCapacity <= Segment.SIZE) { "unexpected capacity" }

  if (head == null) {
    val result = SegmentPool.take() // Acquire a first segment.
    head = result
    result.prev = result
    result.next = result
    return result
  }

  var tail = head!!.prev
  if (tail!!.limit + minimumCapacity > Segment.SIZE || !tail.owner) {
    tail = tail.push(SegmentPool.take()) // Append a new empty segment to fill up.
  }
  return tail
}

internal inline fun Buffer.commonWrite(source: ByteArray) = write(source, 0, source.size)

internal inline fun Buffer.commonWrite(
  source: ByteArray,
  offset: Int,
  byteCount: Int,
): Buffer {
  var offset = offset
  checkOffsetAndCount(source.size.toLong(), offset.toLong(), byteCount.toLong())

  val limit = offset + byteCount
  while (offset < limit) {
    val tail = writableSegment(1)

    val toCopy = minOf(limit - offset, Segment.SIZE - tail.limit)
    source.copyInto(
      destination = tail.data,
      destinationOffset = tail.limit,
      startIndex = offset,
      endIndex = offset + toCopy,
    )

    offset += toCopy
    tail.limit += toCopy
  }

  size += byteCount.toLong()
  return this
}

internal inline fun Buffer.commonReadByteArray() = readByteArray(size)

internal inline fun Buffer.commonReadByteArray(byteCount: Long): ByteArray {
  require(byteCount >= 0 && byteCount <= Int.MAX_VALUE) { "byteCount: $byteCount" }
  if (size < byteCount) throw EOFException()

  val result = ByteArray(byteCount.toInt())
  readFully(result)
  return result
}

internal inline fun Buffer.commonRead(sink: ByteArray) = read(sink, 0, sink.size)

internal inline fun Buffer.commonReadFully(sink: ByteArray) {
  var offset = 0
  while (offset < sink.size) {
    val read = read(sink, offset, sink.size - offset)
    if (read == -1) throw EOFException()
    offset += read
  }
}

internal inline fun Buffer.commonRead(sink: ByteArray, offset: Int, byteCount: Int): Int {
  checkOffsetAndCount(sink.size.toLong(), offset.toLong(), byteCount.toLong())

  val s = head ?: return -1
  val toCopy = minOf(byteCount, s.limit - s.pos)
  s.data.copyInto(
    destination = sink,
    destinationOffset = offset,
    startIndex = s.pos,
    endIndex = s.pos + toCopy,
  )

  s.pos += toCopy
  size -= toCopy.toLong()

  if (s.pos == s.limit) {
    head = s.pop()
    SegmentPool.recycle(s)
  }

  return toCopy
}

internal const val OVERFLOW_ZONE = Long.MIN_VALUE / 10L
internal const val OVERFLOW_DIGIT_START = Long.MIN_VALUE % 10L + 1

internal inline fun Buffer.commonReadDecimalLong(): Long {
  if (size == 0L) throw EOFException()

  // This value is always buil


23001',	'',	'1',	'2',	'',	'“母亲”',	'mother',	'',	'',	'4',	'',	'',	'',	'',	'',	'',	'',	'',	'2030919',	'',	'',	'',	'1',	'1',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	''},
{'2030919',	'',	'太慢了。',	'',	'',	'',	'',	'',	'',	'',	'',	'2023001',	'',	'1',	'2',	'',	'“母亲”',	'mother',	'',	'',	'4',	'',	'',	'',	'',	'',	'',	'',	'',	'2030920',	'',	'',	'',	'1',	'1',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	''},
{'2030920',	'',	'对方的话语中夹杂的失望，足以令渴望得到认同的稚嫩“生命”入坠冰窟。',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'1',	'',	'',	'',	'',	'',	'4',	'',	'',	'',	'',	'',	'',	'',	'',	'2030921',	'',	'',	'',	'1',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	''},
{'2030921',	'',	'母亲，对不起。',	'',	'',	'',	'',	'',	'',	'',	'',	'2023001',	'',	'',	'2',	'',	'芙洛拉',	'Flora ',	'[{"id":2023001,"pos":2,"enter":2}]',	'',	'4',	'',	'',	'',	'',	'',	'',	'',	'',	'2030922',	'',	'',	'',	'1',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	''},
{'2030922',	'',	'没什么值得道歉的。',	'',	'',	'',	'',	'',	'',	'',	'',	'2023001',	'',	'1',	'2',	'',	'“母亲”',	'mother',	'[{"id":2023001,"pos":2,"out":2}]',	'',	'3',	'',	'',	'',	'',	'',	'',	'',	'',	'2030923',	'',	'',	'',	'1',	'1',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	''},
{'2030923',	'',	'新生的生命体需要不断地与外界接触感知，逐渐建立自我主体意识。',	'',	'',	'',	'',	'',	'',	'',	'',	'2023001',	'',	'1',	'2',	'',	'“母亲”',	'mother',	'',	'',	'3',	'',	'',	'',	'',	'',	'',	'',	'',	'20309


 = (int)n;
    }
    if (user_platform_number != -1 && user_device_number != -1) {
        cl_platform* platform = &platforms[user_platform_number];
        if ((unsigned)user_device_number >= platform->n_devices) {
            fprintf(stderr, "ggml_opencl: invalid device number %d\n", user_device_number);
            exit(1);
        }
        default_device = &platform->devices[user_device_number];
    } else {

        struct cl_device * selected_devices = devices;
        unsigned n_selected_devices = n_devices;

        if (user_platform_number == -1 && user_platform_string != NULL && user_platform_string[0] != 0) {
            for (unsigned i = 0; i < n_platforms; i++) {
                struct cl_platform * p = &platforms[i];
                if (strstr(p->name, user_platform_string) != NULL ||
                    strstr(p->vendor, user_platform_string) != NULL) {
                    user_platform_number = (int)i;
                    break;
                }
            }
            if (user_platform_number == -1) {
                fprintf(stderr, "ggml_opencl: no platform matching '%s' was found.\n", user_platform_string);
                exit(1);
            }
        }
        if (user_platform_number != -1) {
            struct cl_platform * p = &platforms[user_platform_number];
            selected_devices = p->devices;
            n_selected_devices = p->n_devices;
            default_device = p->default_device;
            if (n_selected_devices == 0) {
                fprintf(stderr, "ggml_opencl: selected platform '%s' does not have any devices.\n", p->name);
                exit(1);
            }
        }

        if (user_device_number == -1 && user_device_string != NULL && user_device_string[0] != 0) {
            for (unsigned i = 0; i < n_selected_devices; i++) {
                struct cl_device * d = &selected_devices[i];
                if (strstr(d->name, user_device_string) != NULL) {
                    user_device_number = d->number;
                    break;
                }
            }
            if (user_device_number == -1) {
                fprintf(stderr, "ggml_opencl: no device matching '%s' was found.\n", user_device_string);
                exit(1);
            }
        }
        if (user_device_number != -1) {
            selected_devices = &devices[user_device_number];
            n_selected_devices = 1;
            default_device = &selected_devices[0];
        }

        GGML_ASSERT(n_selected_devices > 0);

        if (default_device == NULL) {
            default_device = &selected_devices[0];
        }
    }

    fprintf(stderr, "ggml_opencl: selecting platform: '%s'\n", default_device->platform->name);
    fprintf(stderr, "ggml_opencl: selecting device: '%s'\n", default_device->name);
    if (default_device->type != CL_DEVICE_TYPE_GPU) {
        fprintf(stderr, "ggml_opencl: warning, not a GPU: '%s'.\n", default_device->name);
    }

    platform = default_device->platform->id;


rt';
import 'package:flutter_commun_app/resource/session/session.dart';
import 'package:flutter_commun_app/ui/pages/home/post/post.dart';
import 'package:flutter_commun_app/ui/pages/home/widget/whats_new_widget.dart';
import 'package:flutter_commun_app/ui/theme/theme.dart';
import 'package:flutter_commun_app/ui/widget/kit/alert.dart';
import 'package:flutter_commun_app/ui/widget/lazy_load_scrollview.dart';

class FeedPage extends StatelessWidget {
  const FeedPage({Key? key}) : super(key: key);

  Widget _postList(BuildContext context, List<PostModel> list) {
    return SliverList(
      delegate: SliverChildListDelegate(
        [
          ...list
              .map(
                (post) => Post(
                  post: post,
                  onPostAction: (action, model) =>
                      onPostAction(context, action, model),
                  myUser: getIt<Session>().user!,
                  isFeedPost: true,
                ),
              )
              .toList(),
          BlocBuilder<PostFeedCubit, PostFeedState>(
            builder: (context, state) {
              return state.estate.mayBeWhen(
                elseMaybe: () => const SizedBox(),
                loadingMore: () => const Center(
                    child: CircularProgressIndicator(strokeWidth: 2)),
              );
            },
          ),
        ],
        addAutomaticKeepAlives: false,
      ),
    );
  }

  void onPostAction(BuildContext context, PostAction action, PostModel model) {
    action.when(elseMaybe: () {
      Utility.cprint(
          "${action.toString()} ${context.locale.is_in_development}");
    }, delete: () async {
      Alert.confirmDialog(
        context,
        message: context.locale.confirm_delete_post,
        onConfirm: () async {
          await context.read<PostFeedCubit>().deletePost(model);
        },
      );
    }, upVote: () async {
      await context.read<PostFeedCubit>().handleVote(model, isUpVote: true);
    }, downVote: () async {
      await context.read<PostFeedCubit>().handleVote(model, isUpVote: false);
    }, modify: () {
      context.read<PostFeedCubit>().updatePost(model);
    }, report: () {
      context.read<PostFeedCubit>().reportPost(model);
    });
  }

  Widget _appbar(BuildContext context) {
    return SliverPadding(
      sliver: SliverAppBar(
        floating: true,
        elevation: 0,
        pinned: true,
        iconTheme: IconThemeData(color: Theme.of(context).primaryColor),
        titleSpacing: 0.0,
        title: SizedBox(width: context.width, child: const WhatsNewWidget()),
        leadingWidth: 0,
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(0.0),
          child: Container(
            color: Colors.grey.shade200,
            height: 1.0,
          ),
        ),
      ),
      padding: const EdgeInsets.only(top: 16),
    );
  }

  Widget _noPosts(BuildContext context) {
    return SliverToBoxAdapter(
        child: SizedBox(
      height: context.height * .7,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(context.locale.no_post_available,
              style: TextStyles.headline16(context)),
          Text(context.locale.wanna_see_post,
              style: TextStyles.subtitle14(context)),
        ],
      ),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: context.height,
        width: context.width,
        alignment: Alignment.center,


	.owner = THIS_MODULE,
	.name = "FBA ",
	.ebcname = "FBA ",
	.check_device = dasd_fba_check_characteristics,
	.do_analysis = dasd_fba_do_analysis,
	.pe_handler = dasd_fba_pe_handler,
	.setup_blk_queue = dasd_fba_setup_blk_queue,
	.fill_geometry = dasd_fba_fill_geometry,
	.start_IO = dasd_start_IO,
	.term_IO = dasd_term_IO,
	.handle_terminated_request = dasd_fba_handle_terminated_request,
	.erp_action = dasd_fba_erp_action,
	.erp_postaction = dasd_fba_erp_postaction,
	.check_for_device_change = dasd_fba_check_for_device_change,
	.build_cp = dasd_fba_build_cp,
	.free_cp = dasd_fba_free_cp,
	.dump_sense = dasd_fba_dump_sense,
	.dump_sense_dbf = dasd_fba_dump_sense_dbf,
	.fill_info = dasd_fba_fill_info,
};

static int __init
dasd_fba_init(void)
{
	int ret;

	ASCEBC(dasd_fba_discipline.ebcname, 4);

	dasd_fba_zero_page = (void *)get_zeroed_page(GFP_KERNEL | GFP_DMA);
	if (!dasd_fba_zero_page)
		return -ENOMEM;

	ret = ccw_driver_register(&dasd_fba_driver);
	if (!ret)
		wait_for_device_probe();

	return ret;
}

static void __exit
dasd_fba_cleanup(void)
{
	ccw_driver_unregister(&dasd_fba_driver);
	free_page((unsigned long)dasd_fba_zero_page);
}

module_init(dasd_fba_init);
module_exit(dasd_fba_cleanup);


/***********      .---.         .-"-.      *******************\
* -------- *     /   ._.       / ´ ` \     * ---------------- *
* Author's *     \_  (__\      \_°v°_/     * humus@rogers.com *
*   note   *     //   \\       //   \\     * ICQ #47010716    *
* -------- *    ((     ))     ((     ))    * ---------------- *
*          ****--""---""-------""---""--****                  ********\
* This file is a part of the work done by Humus. You are free to use  *
* the code in any way you like, modified, unmodified or copy'n'pasted *
* into your own work. However, I expect you to respect these points:  *
*  @ If you use this file and its contents unmodified, or use a major *
*    part of this file, please credit the author and leave this note. *
*  @ For use in anything commercial, please request my approval.      *
*  @ Share your work and ideas too as much as you can.                *
\*********************************************************************/

#ifndef _QUATERNION_H_
#define _QUATERNION_H_

// #include "Matrix.h"

struct Quaternion
{
  float s, x, y, z;

  Quaternion() {}
  Quaternion(const float Wx, const float Wy);
  Quaternion(const float Wx, const float Wy, const float Wz);
  Quaternion(const float is, const float ix, const float iy, const float iz)
  {
    s = is;
    x = ix;
    y = iy;
    z = iz;
  }

  operator const float *() const { return &s; }

  void operator+=(const Quaternion &v);
  void operator-=(const Quaternion &v);
  void operator*=(const float scalar);
  void operator/=(const float dividend);
  void normalize();
  void fastNormalize();
};

Quaternion operator+(const Quaternion &u, const Quaternion &v);
Quaternion operator-(const Quaternion &u, const Quaternion &v);
Quaternion operator-(const Quaternion &v);
Quaternion operator*(const Quaternion &u, const Quaternion &v);
Quaternion operator*(const float scalar, const Quaternion &v);
Quaternion operator*(const Quaternion &v, const float scalar);
Quaternion operator/(const Quaternion &v, const float dividend);

Quaternion slerp(const Quaternion &q0, const Quaternion &q1, const float t);
Quaternion scerp(const Quaternion &q0, const Quaternion &q1, const Quaternion &q2, const Quaternion &q3, const float t);

#endif // _QUATERNION_H_