namespace OpenGraphNet.Tests;

/// <summary>
/// Meta Element Tests.
/// </summary>
public class MetaElementTests
{
    /// <summary>
    /// The namespace.
    /// </summary>
    private readonly OpenGraphNamespace ns;

    /// <summary>
    /// Initializes a new instance of the <see cref="MetaElementTests"/> class.
    /// </summary>
    public MetaElementTests()
    {
        this.ns = NamespaceRegistry.Instance.Namespaces["og"];
    }

    /// <summary>
    /// Tests the null meta element.
    /// </summary>
    [Fact]
    public void TestNullMetaElement()
    {
        var element = new NullMetadata();

        Assert.Empty((string)element);
        Assert.Empty(element.ToString());
    }

    /// <summary>
    /// Tests the meta element.
    /// </summary>
    [Fact]
    public void TestMetaElement()
    {
        var element = new StructuredMetadata(this.ns, "title", "my title");

        Assert.Equal("my title", element);
        Assert.Equal(@"<meta property=""og:title"" content=""my title"">", element.ToString());
    }

    /// <summary>
    /// Tests the structured elements.
    /// </summary>
    [Fact]
    public void TestStructuredElements()
    {
        var @expected = @"<meta property


="210" height="120" src="https://img.huffingtonpost.com/asset/65437f652200005800ceee4c.jpeg?cache=LhfJkwOdzH&ops=210_120"/></picture>
<a class="cli-related-articles__link js-entry-link cet-internal-link" href="https://www.huffingtonpost.co.uk/entry/bbc-world-service-israel-hamas-palestinians-blackouts_uk_65435b8fe4b00f9ca31e7e2c" data-amzn-src="article-related" data-vars-item-name="BBC Announces Emergency Radio Service For Gaza Amid Internet And Phone Blackouts" data-vars-item-type="card" data-vars-unit-name="6543a9a8e4b0cde80b8bdbe5" data-vars-unit-type="buzz_body" data-vars-target-content-id="https://www.huffingtonpost.co.uk/entry/bbc-world-service-israel-hamas-palestinians-blackouts_uk_65435b8fe4b00f9ca31e7e2c" data-vars-target-content-type="buzz" data-vars-type="web_internal_link" data-vars-position-in-subunit="1" data-vars-subunit-name="related_articles" data-vars-subunit-type="package">
BBC Announces Emergency Radio Service For Gaza Amid Internet And Phone Blackouts

<picture><source type="image/webp" srcSet="https://img.huffingtonpost.com/asset/6543615f220000310018d7ff.jpeg?ops=210_120&format=webp"/></picture>
<a class="cli-related-articles__link js-entry-link cet-internal-link" href="https://www.huffingtonpost.co.uk/entry/hamas-hostages-what-do-we-know-so-far_uk_6542581ce4b02c5617db2c3c" data-amzn-src="article-related" data-vars-item-name="Hamas Hostages: What Do We Know So Far?" data-vars-item-type="card" data-vars-unit-name="6543a9a8e4b0cde80b8bdbe5" data-vars-unit-type="buzz_body" data-vars-target-content-id="https://www.huffingtonpost.co.uk/entry/hamas-hostages-what-do-we-know-so-far_uk_6542581ce4b02c5617db2c3c" data-vars-target-content-type="buzz" data-vars-type="web_internal_link" data-vars-position-in-subunit="2" data-vars-subunit-name="related_articles" data-vars-subunit-type="package">
Hamas Hostages: What Do We Know So Far?

<picture><source type="image/webp" srcSet="https:/


 Text('${lastTPS.toStringAsFixed(2)}', style: const TextStyle(color: Colors.black)),
                            ],
                          ),
                        ],
                      ),
                    ],
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}const fakeResponseMovieList = """{
  "page": 1,
  "total_results": 10000,
  "total_pages": 500,
  "results": [
    {
      "popularity": 352.048,
      "id": 429617,
      "video": false,
      "vote_count": 3791,
      "vote_average": 7.7,
      "title": "Spider-Man: Far from Home",
      "release_date": "2019-06-28",
      "original_language": "en",
      "original_title": "Spider-Man: Far from Home",
      "genre_ids": [28, 12, 878],
      "backdrop_path": "/6ihyJWRLEngSnlW8HKeDOH3AfSQ.jpg",
      "adult": false,
      "overview":
          "Peter Parker dan teman-temannya melakukan perjalanan musim panas ke Eropa. Namun, mereka hampir tidak dapat beristirahat - Peter harus setuju untuk membantu Nick Fury mengungkap misteri makhluk yang menyebabkan bencana alam dan kehancuran di seluruh benua.",
      "poster_path": "/rjbNpRMoVvqHmhmksbokcyCr7wn.jpg"
    }
  ]
}""";

const fakeResponseMovieDetail = """{
    "adult": false,
    "backdrop_path": "/6X2YjjYcs8XyZRDmJAHNDlls7L4.jpg",
    "belongs_to_collection": null,
    "budget": 0,
    "genres": [
        {
            "id": 35,
            "name": "Comedy"
        },
        {
            "id": 80,
            "name": "Crime"
        },
        {
            "id": 18,
            "name": "Drama"
        }
    ],
    "homepage": "http://www.foxsearchlight.com/theoldmanandthegun",
    "id": 429203,
    "imdb_id": "tt2837574",
    "original_language": "en",
    "original_title": "The Old Man & the Gun",
    "overview": "The true story of Forrest Tucker, from his audacious escape from San Quentin at the age of 70 to an unprecedented string of heists that confounded authorities and enchanted the public. Wrapped up in the pursuit are a detective, who becomes captivated with Forrest’s commitment to his craft, and a woman, who loves him in spite of his chosen profession.",
    "popularity": 325.687,
    "poster_path": "/a4BfxRK8dBgbQqbRxPs8kmLd8LG.jpg",
    "production_companies": [
        {
            "id": 51513,
            "logo_path": "/eWhUrhDH1DapiMCnK7I9f5HPDjd.png",
            "name": "Condé Nast Entertainment",
            "origin_country": "US"
        }
    ],
    "production_countries": [
        {
            "iso_3166_1": "US",
            "name": "United States of America"
        }
    ],
    "release_date": "2018-09-27",
    "revenue": 11277120,
    "runtime": 93,
    "spoken_languages": [
        {
            "iso_639_1": "en",
            "name": "English"
        }
    ],
    "status": "Released",
    "tagline": "This story is mostly true.",
    "title": "The Old Man & the Gun",
    "video": false,
    "vote_average": 6.3,
    "vote_count": 532
}""";

const fakeResponseMovieSimilar = """{
    "page": 1,
    "results": [
        {
            "adult": false,
            "backdrop_path": "/tcheoA2nPATCm2vvXw2hVQoaEFD.jpg",
            "genre_ids": [
                27,
                53
            ],
            "id": 346364,
            "original_language": "en",
            "original_title": "It",
            "overview": "In a small town in Maine, seven children known as The Losers Club come face to face with life problems, bullies and a monster that takes the shape of a clown called Pennywise.",
            "poster_path": "/9E2y5Q7WlCVNEhP5GiVTjhEhx1o.jpg",
            "release_date": "2017-09-06",
            "title": "It",
            "video": false,
            "vote_average": 7.2,
            "


#wrapper .bdbri.bdbriimg .bdbrievenmore a:hover{color:#666;text-decoration:underline}
#wrapper .bdbri.bdbriimg .bdbrievenmore a:active{color:#00c}
.bdbriscroll-ctrl-scroll{position:absolute;top:10px;right:1px;width:8px;border-top:1px solid #e4e4e4;border-left:1px solid #e4e4e4;cursor:default;-webkit-user-select:none;-moz-user-select:none}
.bdbriscroll-ctrl-scroll .bdbriscroll-axis{width:8px;left:0;z-index:0;position:absolute;background:#f2f2f2}
.bdbriscroll-ctrl-scroll-touch .bdbriscroll-axis{width:7px;background:#f2f2f2}
.bdbriscroll-ctrl-scroll-hover .bdbriscroll-axis{background:#f2f2f2}
.bdbriscroll-ctrl-scroll .bdbriscroll-slider{overflow:hidden;width:7px;height:14px;position:absolute;left:0;z-index:10;display:none;background:#d9d9d9;margin-top:-1px;margin-left:-1px;border-right:1px solid #cecece;border-bottom:1px solid #cecece;cursor:default}
.bdbriscroll-ctrl-scroll-touch .bdbriscroll-slider,.bdbriscroll-ctrl-scroll-hover .bdbriscroll-slider{background:#b8b8b8;border-right:1px solid #afafaf;border-bottom:1px solid #afafaf}
.s_ipt::-webkit-input-placeholder{padding-left:3px;color:#aaa;font-size:13px}
.s_ipt::-moz-placeholder{padding-left:3px;color:#aaa;font-size:13px}
.s_ipt:-ms-input-placeholder{padding-left:3px;color:#aaa;font-size:13px}
.s_ipt::placeholder{padding-left:3px;color:#aaa;font-size:13px}
.kw-placeholder{position:absolute;top:0;left:0;color:#aaa;font-size:13px;height:35px;line-height:35px;padding-left:10px;max-width:360px;z-index:99;pointer-events:none}
.kw-placeholder.placeholders-hidden{visibility:hidden}
.qrcode-chunwan{width:530px;height:90px;position:absolute;left:50%;margin-left:-265px;z-index:1;bottom:115px;background-size:100%;background-repeat:no-repeat;background-position:center}
.qrcode-chunwan .close-chunwan{width:23px;height:23px;position:absolute;top:0;right:0;display:none;_display:block;background-size:100%}
.qrcode-chunwan:hover .close-chunwan{display:block}</style>

<!--[if lte IE 8]>
<style index="index" data-compress="strip">
.s_form{top:260px}
</style>
<![endif]-->
<!--[if IE 8]>
<style index="index" data-compress="strip">
#u1 a.mnav,#u1 a.mnav:visited,#u1 a.lb,#u1 a.lb:visited,#u1 a.pf,#u1 a.pf:visited,#u1 a.bri,#u1 a.bri:visited{font-family:simsun;}
</style>
<![endif]-->
<style data-for="debug">
#debug{display:none!important;}
</style>
<style data-for="result" id="css_index_result" type="text/css">#seth{display:inline;behavior:url(#default#homepage)}
#setf{display:inline}
#sekj{margin-left:14px}
#st,#sekj{


//
// ClassDump By HuangBai Private
//  Copyright (C) 1997-2019 Steve Nygard. Updated HuangBai-2024
//

#import <objc/NSObject.h>

@class NSString, WCMegaVideo;

@interface WCFinderVideoAttachment : NSObject
{
    unsigned long long _videoId;
    WCMegaVideo *_video;
    NSString *_videoNonceId;
}

+ (unsigned long long)columnTypeForWCDB;
+ (id)unarchiveWithWCTValue:(id)arg1;
+ (void)initialize;
+ (void)PBArrayAdd_videoNonceId;
+ (void)PBArrayAdd_video;
+ (void)PBArrayAdd_videoId;
- (void).cxx_destruct;
@property(retain, nonatomic) NSString *videoNonceId; // @synthesize videoNonceId=_videoNonceId;
@property(retain, nonatomic) WCMegaVideo *video; // @synthesize video=_video;
@property(nonatomic) unsigned long long videoId; // @synthesize videoId=_videoId;
- (id)genVideoAttachment;
@property(readonly, copy) NSString *description;
- (id)initWithMegaVideo:(id)arg1;
- (id)initWithFinderVideoAttachment:(id)arg1;
- (id)archivedWCTValue;
- (id)getPBPropertyTable;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
// Preceding property had unknown attributes: ?
// Original attribute string: T@"NSString",?,R,C

@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


Cst}};
use canvas::Canvas;
use model::Model;
use crossterm::ExecutableCommand;
use crossterm::terminal::{enable_raw_mode, disable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen};
use crossterm::event::{self, EnableMouseCapture, DisableMouseCapture, Event as TermEvent, KeyCode, KeyEvent, MouseEvent, MouseButton, KeyModifiers};
use tui::{Frame, Terminal};
use tui::backend::{CrosstermBackend, Backend};
use unicode_width::UnicodeWidthStr;
use notify::{Watcher, DebouncedEvent};
use log::{info, trace};

macro_rules! click {
    ($x:expr, $y:expr, $view:expr, $model:expr) => {

        if RangeInclusive::new($view.area.left(), $view.area.right()).contains(&$x)
        && RangeInclusive::new($view.area.top(), $view.area.bottom()).contains(&$y) {
            $model.focus = $view.win_id;
        }
    };
}

macro_rules! trace_value {
    ($offset:expr, $topline:expr, $baseline:expr) => {
        trace!("-- offset: {}", $offset);
        trace!("-- topline: {}", $topline);
        trace!("-- baseline: {}", $baseline);
    };
}

#[derive(Debug)]
pub enum Event {
    LibraryChanged,
    ConfigUpdated,
    UserInput(TermEvent),
}

#[derive(Default, Debug)]
pub struct App {
    model: Model,
    canvas: Canvas,
    terminated: bool,
}

impl Launch for App {

    fn bootstrap(&mut self, config: &Config) -> Result<()> {
        if config.debug.unwrap() {
            DEBUG.store(true, Relaxed);
            setup_logger()?;
        }

        self.model.bootstrap(config)?;
        self.canvas.bootstrap(config)?;

        enable_raw_mode()?;
        let mut stdout = io::stdout();
        stdout
            .execute(EnableMouseCapture)?
            .execute(EnterAlternateScreen)?;

        let mut terminal = Terminal::new(CrosstermBackend::new(stdout))?;

        terminal.clear()?;
        terminal.hide_cursor()?;

        let (event_tx, event_rx) = mpsc::channel();
        let rc_event_rx = Rc::new(event_rx);

        let (w_tx, w_rx) = mpsc::channel();
        let mut watcher = notify::watcher(w_tx, Duration::from_millis(100))?;
        watcher.watch(r"/Users/tenx/Music", notify::RecursiveMode::Recursive)?;
        watcher.watch(&*CONFIG_PATH, notify::RecursiveMode::NonRecursive)?;

        let config = config.clone();
        let mut timer = Instant::now();
        let _event_listener = thread::spawn(move || loop {

            if let Ok(poll) = event::poll(Duration::from_millis(30)) {
                if poll {
                    if let Ok(term_event) = event::read() {
                        if Instant::now().duration_since(timer).as_millis() >= 30 {
                            event_tx.send(Event::UserInput(term_event)).unwrap();
                            timer = Instant::now();
                        }
                    }
                }
            }

            if let Ok(debounced_event) = w_rx.try_recv() {
                match debounced_event {
                    DebouncedEvent::Write(p) => {
                        if p == CONFIG_PATH.to_path_buf() {
                            event_tx.send(Event::ConfigUpdated).unwrap();
                        }
                    }
                    DebouncedEvent::Create(p) |
                    DebouncedEvent::Remove(p) |
                    DebouncedEvent::Rename(p, _) => {
                        if p.ancestors().find(|p| p.to_path_buf() == PathBuf::from(config.lib_pos.as_ref().unwrap())).is_some() {
                            even


ст.л.

									Крахмал
									3 ст.л.

									Яйца
									3 шт.

									Соль
									по вкусу.

									Перец чёрный молотый
									по вкусу.

Описание:

									Мясо порезать ломтиками (толщиной прим. 5…7 мм).

									Отбить с двух сторон.

									Порезать соломкой длиной 2…3 см. и сложить в миску.

									Добавить крахмал и хорошо перемешать (каждый кусочек должен быть покрыт крахмалом).

									Добавить майонез и перемешать.

									Добавить соль, перец по вкусу.

									Яйца перемешать до однородности и добавить в миску.

									Дать постоять смеси минимум 10…15 минут.

									Выкладывать на сковороду ложкой, формировать нужный размер отбивной.

									Готовить на среднем огне, добавив растительное масло на сковороду.

Заметки


uxi, بوط_, rzio_,
   {{0x07a61056,0x7e641ffe,0x6b9601e2,0x649a0aac}},	//   _данн, stip, _knyg, штар_,
   {{0x2ca7016d,0x77b8002a,0xcb6a8af0,0x6d43008b}},	//   ända_, _fíxa, раде_, ónar,
   {{0x7e0301bc,0x00000000,0x00000000,0x00000000}},	//   ọsar, --, --, --,
   {{0x6b84032f,0x2d8308f2,0x7bcf4fbb,0x236d8609}},	//   _laig, _gaje_, zicu, _ebej_,
   {{0x2d85cfbc,0x29cd026c,0x628f83a8,0xdb1d0106}},	//   ddle_, džal_, _ácon, mnsö,
   {{0x44444fbd,0xca7696fe,0x753c43cc,0x6b844fbe}},	//   ms_, _музы, _herz, _naig,
   {{0x76444fbf,0x7bcf09c4,0xdb0d4fc0,0xdb00816b}},	//   nsiy, vicu, _ilaç, _komí,
   {{0x63a2a3d0,0x78a100f2,0x3f829c18,0x442a008e}},	//   ljon, älvk, žku_, _ktb_,
   {{0x6b841247,0x3a2900c9,0x753c4fc1,0x3d058075}},	//   _baig, _stap_, _merz, हेले_,
   {{0x76444fc2,0x63a2cbf2,0x6b844fc3,0x628d4fc4}},	//   ksiy, njon, _caig, _prao,
   {{0x7bcf44c6,0xaac54fc5,0x6b844fc6,0x9f49009f}},	//   ricu, _लेखक, _daig, llaç_,
   {{0x44444fc7,0x29cd0052,0x7bcf0098,0x442c8122}},	//   ks_, ržao_, sicu, ppd_,
   {{0x444448fc,0x6b840ad0,0x97a73d65,0x2d834fc8}},	//   js_, _faig, орал, _raje_,
   {{0x62808503,0x09b78519,0x628d1995,0x2d832d68}},	//   _osmo, _अत्य, _trao, _saje_,
   {{0x44444fc9,0x753c4014,0x44380114,0xa6db007b}},	// [4150] es_, _berz, _awr_, _meðg,
   {{0x44444fca,0xc05b0a4c,0x6724044a,0xdb008825}},	//   fs_, _кім_, acij, _comí,
   {{0x44440a85,0x753c01ec,0x62808102,0xdb00a9c3}},	//   gs_, _derz, _asmo, _domí,
   {{0x207a0158,0x987a0158,0x2d834c0e,0x307a00be}},	//   _פארא, _פארט, _waje_, _פארנ,
   {{0x44444fcb,0x79850ad4,0xbf9a04de,0x442a011b}},	//   as_, _kahw, _הירש, _etb_,
   {{0xe


x89),
    L2D(0x8a),
    F2I(0x8b),
    F2L(0x8c),
    F2D(0x8d),
    D2I(0x8e),
    D2L(0x8f),
    D2F(0x90),
    I2B(0x91),
    I2C(0x92),
    I2S(0x93),
    LCMP(0x94),
    FCMPL(0x95),
    FCMPG(0x96),
    DCMPL(0x97),
    DCMPG(0x98),
    IFEQ(0x99, BRANCH),
    IFNE(0x9a, BRANCH),
    IFLT(0x9b, BRANCH),
    IFGE(0x9c, BRANCH),
    IFGT(0x9d, BRANCH),
    IFLE(0x9e, BRANCH),
    IF_ICMPEQ(0x9f, BRANCH),
    IF_ICMPNE(0xa0, BRANCH),
    IF_ICMPLT(0xa1, BRANCH),
    IF_ICMPGE(0xa2, BRANCH),
    IF_ICMPGT(0xa3, BRANCH),
    IF_ICMPLE(0xa4, BRANCH),
    IF_ACMPEQ(0xa5, BRANCH),
    IF_ACMPNE(0xa6, BRANCH),
    GOTO(0xa7, BRANCH),
    JSR(0xa8, BRANCH),
    RET(0xa9, LOCAL),
    TABLESWITCH(0xaa, DYNAMIC),
    LOOKUPSWITCH(0xab, DYNAMIC),
    IRETURN(0xac),
    LRETURN(0xad),
    FRETURN(0xae),
    DRETURN(0xaf),
    ARETURN(0xb0),
    RETURN(0xb1),
    GETSTATIC(0xb2, CPREF_W),
    PUTSTATIC(0xb3, CPREF_W),
    GETFIELD(0xb4, CPREF_W),
    PUTFIELD(0xb5, CPREF_W),
    INVOKEVIRTUAL(0xb6, CPREF_W),
    INVOKESPECIAL(0xb7, CPREF_W),
    INVOKESTATIC(0xb8, CPREF_W),
    INVOKEINTERFACE(0xb9, CPREF_W_UBYTE_ZERO),
    INVOKEDYNAMIC(0xba, CPREF_W_UBYTE_ZERO),
    NEW(0xbb, CPREF_W),
    NEWARRAY(0xbc, ATYPE),
    ANEWARRAY(0xbd, CPREF_W),
    ARRAYLENGTH(0xbe),
    ATHROW(0xbf),
    CHECKCAST(0xc0, CPREF_W),
    INSTANCEOF(0xc1, CPREF_W),
    MONITORENTER(0xc2),
    MONITOREXIT(0xc3),
    // wide 0xc4
    MULTIANEWARRAY(0xc5, CPREF_W_UBYTE),
    IFNULL(0xc6, BRANCH),
    IFNONNULL(0xc7, BRANCH),
    GOTO_W(0xc8, BRANCH_W),
    JSR_W(0xc9, BRANCH_W),
    // impdep 0xfe: PicoJava nonpriv
    // impdep 0xff: Picojava priv

    // wide opcodes
    ILOAD_W(0xc415, WIDE_LOCAL),
    LLOAD_W(0xc416, WIDE_LOCAL),
    FLOAD_W(0xc417, WIDE_LOCAL),
    DLOAD


[in] q the desired point (0 <= q <= 1)
 * \param[in] first low limit (default is 0)
 * \param[in] last high limit (default is UINT_MAX)
 *
 * A quantile gives us the point p = Q(q) in the range such that a proportion
 * q of the pixels lie below p. A familiar quantile is Q(0.5) which is the median
 * of a distribution.
 *
 * \return The fractional bin of the point
 */
double Histogram::quantile(double q, uint32_t first, uint32_t last) const
{
	if (last == UINT_MAX)
		last = cumulative_.size() - 2;
	ASSERT(first <= last);

	uint64_t item = q * total();
	/* Binary search to find the right bin */
	while (first < last) {
		int middle = (first + last) / 2;
		/* Is it between first and middle ? */
		if (cumulative_[middle + 1] > item)
			last = middle;
		else
			first = middle + 1;
	}
	ASSERT(item >= cumulative_[first] && item <= cumulative_[last + 1]);

	double frac;
	if (cumulative_[first + 1] == cumulative_[first])
		frac = 0;
	else
		frac = (q * total() - cumulative_[first])
		     / (cumulative_[first + 1] - cumulative_[first]);
	return first + frac;
}

/**
 * \brief Calculate the mean between two quantiles
 * \param[in] lowQuantile low Quantile
 * \param[in] highQuantile high Quantile
 *
 * Quantiles are not ideal for metering as they suffer several limitations.
 * Instead, a concept is introduced here: inter-quantile mean.
 * It returns the mean of all pixels between lowQuantile and highQuantile.
 *
 * \return The mean histogram bin value between the two quantiles
 */
double Histogram::interQuantileMean(double lowQuantile, double highQuantile) const
{
	ASSERT(highQuantile > lowQuantile);

	/* Proportion of pixels which lies below lowQuantile and highQuantile. */
	const double lowPoint = quantile(lowQuantile);
	const double highPoint = quantile(highQuantile, static_cast<uint32_t>(lowPoint));

	double sumBinFreq = 0;
	double cumulFreq = 0;

	/*
         * Calculate the mean pixel value between the low and high points by
         * summing all the pixels between the two points, and dividing the sum
         * by the number of pixels. Given the discrete nature of the histogram
         * data, the sum of the pixels is approximated by accumulating the
         * product of the bin values (calculated as the mid point of the bin) by
         * the number of pixels they contain, for each bin in the internal.
         */
	for (unsigned bin = std::floor(lowPoint); bin < std::ceil(highPoint); bin++) {
		const double lowBound = std::max<double>(bin, lowPoint);
		const double highBound = std::min<double>(bin + 1, highPoint);

		double freq = (cumulative_[bin + 1] - cumulative_[bin])
			    * (highBound - lowBound);

		/* Accumulate weighted bin */
		sumBinFreq += (highBound + lowBound) / 2 * freq;

		/* Accumulate weights */
		cumulFreq += freq;
	}

	return sumBinFreq / cumulFreq;
}

} /* namespace ipa */

} /* namespace libcamera */
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2024, Paul Elder <paul.elder@ideasonboard.com>
 *
 * Fixed / floating point conversions
 */

#include "fixedpoint.h"

/**
 * \file fixedpoint.h
 */

namespace libcamera {

namespace ipa {

/**
 * \fn R floatingToFixedPoint(T number)
 * \brief Convert a floating point number to a fixed-point representation
 * \tparam I Bit width of the integer part of the fixed-point
 * \tparam F Bit width of the fractional part of the fixed-point
 * \tparam R Return type of the fi


color: $black;
	box-shadow: inset 0px 0px 10px 0 rgba(0,0,0,.1);
}

pre.editing code {
	color: $black;
	background: transparent;
}
*/

.promo-box {
	margin-right: 132px;
	margin-left: 132px;
	margin-bottom: 60px;
	font-size: 18px;
	font-family: $sans-serif-light;
	text-align: center;
	padding: 12px;
	border: 1px solid $dfdfdf;
	border-radius: 3px;
}

.promo-box b {
	font-family: $sans-serif;
}

.entry-footer {
	min-height: 280px;
	padding: 35px 0 60px;
	/*border-top: 1px solid $ddd;*/
}

.entry-footer .byline {
	width: 696px;
	max-width: 100%;
	margin: 0 auto;
	// clear: both;
}

.entry-footer .byline img {
	display: block;
	float: left;
	margin: 4px 12px 12px 0;
	border-radius: 50%;
	border: .5em solid $f5f5f5;
}

.entry-footer h1,
.entry-footer h3 {
	margin-left: 132px;
	font-family: $sans-serif;
	font-weight: bold;
	font-size: 14px;
	line-height: 24px;
	font-style: normal;
	text-transform: uppercase;
}

.entry-footer h1 {
	margin-right: 132px;
	margin-left: 132px;
	margin-bottom: 30px;
	text-align: center;
	text-transform: none;
	font-size: 18px;
	line-height: 30px;
}

.entry-footer h2 {
	font-family: $sans-serif;
	font-weight: bold;
	font-size: 18px;
	line-height: 24px;
}

.entry-footer h2 a {
	color: $text;
}

.entry-footer h3 {
	margin-left: 0;
}

.entry-footer .byline + .byline {
	margin-top: 24px;
	clear: left;
}

.entry-footer .byline .author-bio,
.entry-footer .byline .author-more {
	margin-bottom: 24px;
	font-size: 14px;
	line-height: 24px;
}

.entry-footer .photo + h2,
.entry-footer .photo + h2 + .author-bio,
.entry-footer .photo + h2 + .author-bio + h3,
.entry-footer .photo + h2 + .author-bio + h3 + .author-more {
	margin-left: 150px;
}

.entry-footer .byline .author-bio p + p {
	margin-top: 12px;
}

.author-more li {
	display: block;
}

.var1 .punctuation-helper:last-of-type:after {
	content: ".";
}

.var1 .punctuation-helper:not(:last-of-type):after {
	content: ", ";
}

.var1 .punctuation-helper:nth-last-child(2):after {
	content: ", or ";
}

.post-article {
	border-top: 1px solid $e5e5e5;
	clear: both;
}

.column-holder {
	display: table;
	width: 960px;
	max-width: 100%;
	margin: 0 auto;
	position: relative;
}

.column {
	display: table-cell;
	vertical-align: top;
	width: 50%;
	padding-right: 24px;
}

.variable-column,
.fixed-column {
	display: inline-block;
	vertical-align: top;
}

#home-page .variable-column {
	max-width: 76%;
}

#home-page


.
 *
 * Usage Example:
 * ```scss
 * .mdc-foo {
 *   position: absolute;
 *   left: 0;
 *
 *   @include mdc-rtl {
 *     left: auto;
 *     right: 0;
 *   }
 *
 *   &__bar {
 *     margin-left: 4px;
 *     @include mdc-rtl(".mdc-foo") {
 *       margin-left: auto;
 *       margin-right: 4px;
 *     }
 *   }
 * }
 *
 * .mdc-foo--mod {
 *   padding-left: 4px;
 *
 *   @include mdc-rtl {
 *     padding-left: auto;
 *     padding-right: 4px;
 *   }
 * }
 * ```
 *
 * Note that this works by checking for [dir="rtl"] on an ancestor element. While this will work
 * in most cases, it will in some cases lead to false negatives, e.g.
 *
 * ```html
 * <html dir="rtl">
 *   <!-- ... -->
 *   <div dir="ltr">
 *     <div class="mdc-foo">Styled incorrectly as RTL!</div>
 *   </div>
 * </html>
 * ```
 *
 * In the future, selectors such as :dir (http://mdn.io/:dir) will help us mitigate this.
 */
/**
 * Takes a base box-model property - e.g. margin / border / padding - along with a default
 * direction and value, and emits rules which apply the value to the
 * "<base-property>-<default-direction>" property by default, but flips the direction
 * when within an RTL context.
 *
 * For example:
 *
 * ```scss
 * .mdc-foo {
 *   @include mdc-rtl-reflexive-box(margin, left, 8px);
 * }
 * ```
 * is equivalent to:
 *
 * ```scss
 * .mdc-foo {
 *   margin-left: 8px;
 *
 *   @include mdc-rtl {
 *     margin-right: 8px;
 *     margin-left: 0;
 *   }
 * }
 * ```
 * whereas:
 *
 * ```scss
 * .mdc-foo {
 *   @include mdc-rtl-reflexive-box(margin, right, 8px);
 * }
 * ```
 * is equivalent to:
 *
 * ```scss
 * .mdc-foo {
 *   margin-right: 8px;
 *
 *   @include mdc-rtl {
 *     margin-right: 0;
 *     margin-left: 8px;
 *   }
 * }
 * ```
 *
 * You can also pass a 4th optional $root-selector argument which will be forwarded to `mdc-rtl`,
 * e.g. `@include mdc-rtl-reflexive-box(margin, left, 8px, ".mdc-component")`.
 *
 * Note that this function will always zero out the original value in an RTL context. If you're
 * trying to flip the values, use mdc-rtl-reflexive-property().
 */
/**
 * Takes a base property and emits rules that assign <base-property>-left to <left-value> and
 * <base-property>-right to <right-value> in a LTR context, and vice versa in a RTL context.
 * For example:
 *
 * ```scss
 * .mdc-foo {
 *   @include mdc-rtl-reflexive-property(margin, auto, 12px);
 * }
 * ```
 * is equivalent to:
 *
 * ```scss
 * .mdc-foo {
 *   margin-left: auto;
 *   margin-right: 12px;
 *
 *   @include mdc-rtl {
 *     margin-left: 12px;
 *     margin-right: auto;
 *   }
 * }
 * ```
 *
 * A 4th optional $root-selector arg


斬　威力増加　硬直減少　高レベルで派生追加
　－心抄斬　強版上方向判定弱体化
　－反射下界斬　高レベル攻撃判定の持続が短縮
　－伏折無間　ＫＯ後バグ修正　低レベルで補正大幅増加、レベルアップで補正緩和。ホールドで自動追撃可能
　－結跏趺斬　低レベル時攻撃判定縮小、ヒット数低下
　－炯眼剣　削りダメージの異常修正
　－現世斬　発生速度遅延　暗転中攻撃発生削除　距離がある場合ガードされたときに目の前で止まりやすく
　－未来永劫斬　暗転前無敵削除　暗転中攻撃発生削除　硬直増加　距離がある場合ガードされたときに目の前で止まりやすく
　－冥想斬　コスト増加　威力アップ　霊力削りアップ
　－迷津慈航斬　発生速度低下　射撃無敵削除　最大ヒット数低下と単発威力上昇でダメージ安定性上昇
　－苦輪系　反射バグ、時間停止バグ修正
　－幽明の苦輪　効果時間中ゲージ回復停止
　－桜花閃々　攻撃判定拡大
　－成仏得脱斬　無敵時間延長　判定自分寄りに　柱の位置を本体に追従するように

・レミリア
　－大ジャンプ出始めにカウンター判定適用
　－地上前後回避結界のモーション変更
　－快晴効果が飛翔に適用
　－バックステップ距離短縮
　－近打　復帰不能時間短縮
　－遠打　腹のけぞりに　復帰不能時間短縮
　－前打　硬直減少
　－空下打　上方向判定弱体化
　－コンビネーション二段目　復帰不能時間短縮
　－弱射　段数減少　上下射撃角度低下
　－デーモンロードウォーク　発生遅延　硬直増加　移動距離増加　補正増加
　－ヴァンパイアクロウ　判定強化　三段目中段発生加速、クラッシュ属性削除
　－デーモンロードクレイドル　多段ヒット化　着地硬直増加
　－ロケットキックアップ　レベルアップで弾丸巨大化
　－デーモンロードアロー


rveID-Resume-Server",
		config: Config{
			MaxVersion:       VersionTLS12,
			CipherSuites:     []uint16{TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
			CurvePreferences: []CurveID{CurveX25519},
		},
		flags:         []string{"-expect-curve-id", strconv.Itoa(int(CurveX25519))},
		resumeSession: true,
	})

	// TLS 1.3 allows resuming at a differet curve. If this happens, the new
	// one should be reported.
	testCases = append(testCases, testCase{
		name: "CurveID-Resume-Client-TLS13",
		config: Config{
			MaxVersion:       VersionTLS13,
			CurvePreferences: []CurveID{CurveX25519},
		},
		resumeConfig: &Config{
			MaxVersion:       VersionTLS13,
			CurvePreferences: []CurveID{CurveP256},
		},
		flags: []string{
			"-on-initial-expect-curve-id", strconv.Itoa(int(CurveX25519)),
			"-on-resume-expect-curve-id", strconv.Itoa(int(CurveP256)),
		},
		resumeSession: true,
	})
	testCases = append(testCases, testCase{
		testType: serverTest,
		name:     "CurveID-Resume-Server-TLS13",
		config: Config{
			MaxVersion:       VersionTLS13,
			CurvePreferences: []CurveID{CurveX25519},
		},
		resumeConfig: &Config{
			MaxVersion:       VersionTLS13,
			CurvePreferences: []CurveID{CurveP256},
		},
		flags: []string{
			"-on-initial-expect-curve-id", strconv.Itoa(int(CurveX25519)),
			"-on-resume-expect-curve-id", strconv.Itoa(int(CurveP256)),
		},
		resumeSession: true,
	})

	// Server-sent point formats are legal in TLS 1.2, but not in TLS 1.3.
	testCases = append(testCases, testCase{
		name: "PointFormat-ServerHello-TLS12",
		config: Config{
			MaxVersion: VersionTLS12,
			Bugs: ProtocolBugs{
				SendSupportedPointFormats: []byte{pointFormatUncompressed},
			},
		},
	})
	testCases = append(testCases, testCase{
		name: "PointFormat-EncryptedExtensions-TLS13",
		config: Config{
			MaxVersion: VersionTLS13,
			Bugs: ProtocolBugs{
				SendSupportedPointFormats: []byte{pointFormatUncompressed},
			},
		},
		shouldFail:    true,
		expectedError: ":ERROR_PARSING_EXTENSION:",
	})

	// Server-sent supported groups/curves are legal in TLS 1.3. They are
	// illegal in TLS 1.2, but some servers send them anyway, so we must
	// tolerate them.
	testCases = append(testCases, testCase{
		name: "SupportedCurves-ServerHello-TLS12",
		config: Config{
			MaxVersion: VersionTLS12,
			Bugs: ProtocolBugs{
				SendServerSupportedCurves: true,
			},
		},
	})
	testCases = append(testCases, testCase{
		name: "SupportedCurves-EncryptedExtensions-TLS13",
		config: Config{
			MaxVersion: VersionTLS13,
			Bugs: ProtocolBugs{
				SendServerSupportedCurves: true,
			},
		},
	})

	// Test that we tolerate unknown point formats, as long as
	// pointFormatUncompressed is present. Limit ciphers to ECDHE ciphers to
	// check they are still functional.
	testCases = append(test


t()

def _FetchDataCatalogStac() -> dict[str, Any]:
  try:
    response = urllib.request.urlopen(_DEPRECATED_ASSETS_URL).read()
  except (urllib.error.HTTPError, urllib.error.URLError):
    return {}
  return json.loads(response)

def _GetStringFromObject(obj: Any) -> str | None:
  if isinstance(obj, str):
    return obj
  return None

def _UnfilterDeprecationWarnings() -> None:
  """Unfilters deprecation warnings for this module."""
  warnings.filterwarnings(
      'default', category=DeprecationWarning, module=__name__
  )

def _IssueAssetDeprecationWarning(asset: DeprecatedAsset) -> None:
  """Issues a warning for a deprecated asset if one hasn't already been issued.

  Args:
    asset: The asset.
  """
  if asset.has_warning_been_issued:
    return
  asset.has_warning_been_issued = True

  warning = (
      f'\n\nAttention required for {asset.id}! You are using a deprecated'
      ' asset.\nTo make sure your code keeps working, please update it'
  )
  removal_date = asset.removal_date
  today = datetime.datetime.now()
  if removal_date:
    # If today is the removal date or prior, show the removal date, ignoring
    # time zones.
    if today.date() <= removal_date.date():
      # %d gives a zero-padded day. Remove the leading zero. %-d is incompatible
      # with Windows.
      formatted_date = removal_date.strftime('%B %d, %Y').replace(' 0', ' ')
      warning += f' by {formatted_date}'
  warning += '.'
  if asset.learn_more_url:
    warning = warning + f'\nLearn more: {asset.learn_more_url}\n'
  warnings.warn(warning, category=DeprecationWarning)


23-.673.233-.941-.04-.271-.271-.557-.43-.04-.953l21.645-21.92c.518-.524.671-.232.939.04.271.273.559.429.04.953L8.872 53.507m24.585-18.941-21.644 21.92c-.517.523-.673.232-.942-.04-.269-.274-.556-.431-.039-.954l21.645-21.92c.518-.523.671-.231.939.041.272.274.559.428.041.953m11.473-22.76a5.151 5.151 0 017.314 0c2.021 2.03 2.021 5.322.001 7.353s-5.295 2.03-7.315 0a5.218 5.218 0 010-7.353"/></svg>';
  static const String keyboard =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="64" height="64" preserveAspectRatio="xMidYMid meet" viewBox="0 0 64 64"><path fill="currentColor" d="M59.188 32H33.001c0-15.518-6.611-15.518-13.003-15.518-6.147 0-11.958 0-11.958-14.482H7c0 15.518 6.611 15.518 12.998 15.518 6.152 0 11.963 0 11.963 14.482H4.813C3.26 32 2 33.348 2 34.998v24.004C2 60.662 3.26 62 4.813 62h54.375C60.74 62 62 60.662 62 59.002V34.998C62 33.348 60.74 32 59.188 32m-4.112 2.002h1.846c1.436 0 1.436 2.002 0 2.002h-1.846c-1.435 0-1.435-2.002 0-2.002m-5.996 0h1.846c1.436 0 1.436 2.002 0 2.002H49.08c-1.435 0-1.435-2.002 0-2.002M52 44.998V47c0 .557-.449 1.006-.996 1.006h-2.002A1.004 1.004 0 0147.996 47v-2.002c0-.547.449-.996 1.006-.996h2.002a1 1 0 01.996.996m-5.996-5.996c0-.557.449-.996.996-.996h2.002c.547 0 .996.439.996.996v2.002a1 1 0 01-.996.996H47a1 1 0 01-.996-.996v-2.002m-2.93-5h1.846c1.436 0 1.436 2.002 0 2.002h-1.846c-1.435 0-1.435-2.002 0-2.002m2.93 10.996V47c0 .557-.449 1.006-1.006 1.006h-2.002c-.547 0-.996-.449-.996-1.006v-2.002a1 1 0 01.996-.996h2.002c.557 0 1.006.449 1.006.996m-5.005-6.992h1.997a.996.996 0 011.006.996v2.002c0 .547-.449.996-1.006.996h-1.997a1.001 1.001 0 01-1.001-.996v-2.002a.995.995 0 011.001-.996m-2.998 12.998c0-.557.449-1.006 1.001-1.006h1.997c.552 0 1.001.449 1.001 1.006v2.002c0 .547-.449.996-1.001.996h-1.997a1.001 1.001 0 01-1.001-.996v-2.002M37 48.006A1.003 1.003 0 0135.999 47v-2.002c0-.547.449-.996 1.001-.996h2.002a1 1 0 01.996.996V47c0 .557-.449 1.006-.996 1.006


g must be set.
	CaFile string // path to certificate
	CaPem  string // PEM encoded certficate
	CaCert *x509.Certificate

	// Timeout to use.  Default is no timeout.
	Timeout time.Duration

	// If set to true, Connect() will succeed even though the server being
	// connected to is down.  The client will try to reconnect on activity.
	Patient bool
}

type KeyServerConn pep_protocol.Conn
type AccessManagerConn pep_protocol.Conn
type StorageFacilityConn pep_protocol.Conn
type TranscryptorConn pep_protocol.Conn
type RegistrationServerConn pep_protocol.Conn
type AuthserverConn pep_protocol.Conn

type SignedTicket2 struct {
	unpacked *pep_proto.Ticket2
	packed   *pep_proto.SignedTicket2
}

type HandlePageFunc func(*pep_proto.DataPayloadPage)

func wrapSignedTicket2(packed *pep_proto.SignedTicket2) *SignedTicket2 {
	return &SignedTicket2{packed: packed}
}

// Connect to the KeyServer
func DialKeyServer(conf ClientConf) (*KeyServerConn, error) {
	conn, err := dial(conf, "KeyServer")
	return (*KeyServerConn)(conn), err
}

// Connect to the AccessManager
func DialAccessManager(conf ClientConf) (*AccessManagerConn, error) {
	conn, err := dial(conf, "AccessManager")
	return (*AccessManagerConn)(conn), err
}

// Connect to the StorageFacility
func DialStorageFacility(conf ClientConf) (*StorageFacilityConn, error) {
	conn, err := dial(conf, "StorageFacility")
	return (*StorageFacilityConn)(conn), err
}

// Connect to the Transcryptor
func DialTranscryptor(conf ClientConf) (*TranscryptorConn, error) {
	conn, err := dial(conf, "Transcryptor")
	return (*TranscryptorConn)(conn), err
}

// Connect to the RegistrationServer
func DialRegistrationServer(conf ClientConf) (*RegistrationServerConn, error) {
	conn, err := dial(conf, "RegistrationServer")
	return (*RegistrationServerConn)(conn), err
}

// Connect to the Authserver
func DialAuthserver(conf ClientConf) (*AuthserverConn, error) {
	conn, err := dial(conf, "Authserver")
	return (*AuthserverConn)(conn), err
}

func dial(conf ClientConf, cn string) (*pep_protocol.Conn, error) {
	conn, err := pep_protocol.Connect(pep_protocol.ClientConf{
		Addr:             conf.Addr,
		CaFile:           conf.CaFile,
		CaPem:            conf.CaPem,
		CaCert:           conf.CaCert,
		ExpectedServerCN: cn,
		Timeout:          conf.Timeout,
		Patient:          conf.Patient,
	})
	if err != nil {
		return nil, err
	}
	return conn, nil
}

func (c *KeyServerConn) Conn() *pep_protocol.Conn          { return (*pep_protocol.Conn)(c) }
func (c *AccessManagerConn) Conn() *pep_protocol.Conn      { return (*pep_protocol.Conn)(c) }
func (c *StorageFacilityConn) Conn() *pep_protocol.Conn    { return (*pep_protocol.Conn)(c) }
func (c *TranscryptorConn) Conn() *pep_protocol.Conn       { return (*pep_protocol.Conn)(c) }
func (c *RegistrationServerConn) Conn() *pep_protocol.Conn { return (*pep_protocol


throwable, msg, args)

    /**
     * Log a wtf message.
     */
    @JvmStatic
    fun wtf(msg: String) = taglessBranch.wtf(msg)

    /**
     * Log a wtf message.
     */
    @JvmStatic
    fun wtf(msg: () -> String) = taglessBranch.wtf(msg)

    /**
     * Log a wtf message.
     */
    @JvmStatic
    fun wtf(throwable: Throwable, msg: () -> String) = taglessBranch.wtf(throwable, msg)

    /**
     * Log a wtf message.
     */
    @JvmStatic
    @JvmOverloads
    fun wtf(throwable: Throwable, msg: String = "") = taglessBranch.wtf(throwable, msg)

    /**
     * Log a wtf message.
     */
    @JvmStatic
    fun wtf(msg: String, vararg args: Any?) = taglessBranch.wtf(msg, args)

    /**
     * Log a wtf message.
     */
    @JvmStatic
    fun wtf(throwable: Throwable, msg: String, vararg args: Any?) = taglessBranch.wtf(throwable, msg, args)

}

enum class LogLevel { D, V, I, W, E, WTF }

private val defaultBranch: Branch = Arbor.tag("2143fef6-18e0-4341-a1de-b043ba5e32cd")

fun arbor(
    logLevel: LogLevel = LogLevel.D,
    tag: Branch = defaultBranch,
    message: () -> String
) = if (tag == defaultBranch) {
    when (logLevel) {
        LogLevel.D -> Arbor.d(message)
        LogLevel.V -> Arbor.v(message)
        LogLevel.I -> Arbor.i(message)
        LogLevel.W -> Arbor.w(message)
        LogLevel.E -> Arbor.e(message)
        LogLevel.WTF -> Arbor.wtf(message)
    }
} else {
    when (logLevel) {
        LogLevel.D -> tag.d(message)
        LogLevel.V -> tag.v(message)
        LogLevel.I -> tag.i(message)
        LogLevel.W -> tag.w(message)
        LogLevel.E -> tag.e(message)
        LogLevel.WTF -> tag.wtf(message)
    }
}
package kr.toxicity.healthbar.scheduler

import kr.toxicity.healthbar.api.BetterHealthBar
import kr.toxicity.healthbar.api.scheduler.WrappedScheduler
import kr.toxicity.healthbar.api.scheduler.WrappedTask
import org.bukkit.Bukkit
import org.bukkit.World
import org.bukkit.scheduler.BukkitTask

class StandardScheduler : WrappedScheduler {

    private val plugin
        get() = BetterHealthBar.inst()

    override fun task(runnable: Runnable): WrappedTask {
        return Bukkit.getScheduler().runTask(plugin, runnable).wrap()
    }
    override fun asyncTask(runnable: Runnable): WrappedTask {
        return Bukkit.getScheduler().runTaskAsynchronously(plugin, runnable).wrap()
    }
    override fun taskLater(delay: Long, runnable: Runnable): WrappedTask {
        return Bukkit.getScheduler().runTaskLater(plugin, runnable, delay).wrap()
    }
    override fun task(world: World, x: Int, y: Int, runnable: Runnable): WrappedTask {
        return task(runnable)
    }
    override fun asyncTaskTimer(delay: Long, period: Long, runnable: Runnable): WrappedTask {
        return Bukkit.getScheduler().runTaskTimerAsynchronously(plugin, runnable, delay, period).wrap()
    }

    private fun BukkitTask.wrap


 },
        { amount: 1, color: "dim aqua" },
      ]),
    );
  });
  it("should contain no edges if input states that it can contain no other bags", () => {
    const [color, edges] = processLineItem(
      "dull violet bags contain no other bags",
    );
    expect(color).toEqual("dull violet");
    expect(edges).toEqual([]);
  });
});

describe("canContainTargetBag", () => {
  it("should return true if outermostBag can contain targetBag", () => {
    expect(canContainTargetBag("bright white", "shiny gold", testMap)).toEqual(
      true,
    );
    expect(
      canContainTargetBag("bright lavender", "shiny gold", testMap),
    ).toEqual(true);
  });
  it("should return false if outermostBagColor cannot contain targetBagColor", () => {
    expect(canContainTargetBag("shiny black", "shiny gold", testMap)).toEqual(
      false,
    );
    expect(canContainTargetBag("drab magenta", "shiny gold", testMap)).toEqual(
      false,
    );
  });
});

describe("countBagsContainingTargetColor", () => {
  it("should return correct number of bag colors that can eventually contain target bag color", () => {
    expect(countBagsContainingTargetColor("shiny gold", testMap)).toEqual(3);
  });
});

describe("getNumOfRequiredBags", () => {
  const testMap2 = createColorMap([
    "shiny gold bags contain 2 dark red bags.",
    "dark red bags contain 2 dark orange bags.",
    "dark orange bags contain 2 dark yellow bags.",
    "dark yellow bags contain 2 dark green bags.",
    "dark green bags contain 2 dark blue bags.",
    "dark blue bags contain 2 dark violet bags.",
    "dark violet bags contain no other bags.",
  ]);

  it("should return 0 if outermostBag contains no bags", () => {
    expect(getNumOfRequiredBags("drab magenta", testMap2)).toEqual(0);
  });
  it("should return correct number of innerBags", () => {
    expect(getNumOfRequiredBags("shiny gold", testMap2)).toEqual(126);
  });
});
import { AutoScaling } from "aws-sdk";

interface ASGState {
  min: number;
  desired: number;
  max: number;
}

const getAutoScalingGroupState = async (
  autoScalingClient: AutoScaling
): Promise<AutoScaling.AutoScalingGroup[]> => {
  return await autoScalingClient
    .describeAutoScalingGroups({ MaxRecords: 100 })
    .promise()
    .then(
      (response: AutoScaling.AutoScalingGroupsType) =>
        response.AutoScalingGroups
    );
};

const scaleAutoScalingGroup = async (
  autoScalingClient: AutoScaling,
  AutoScalingGroupName: string,
  { min, max, desired }: ASGState
): Promise<boolean> => {
  console.log(
    `Scaling [${AutoScalingGroupName}] to [min: ${min}, desired: ${desired}, max: ${max}]`
  );
  const result = await autoScalingClient
    .updateAutoScalingGroup({
      AutoScalingGroupName,
      DesiredCapacity: desired,
      MinSize: min,
      MaxSize: max
    })
    .promise()
    .catch(err =>
      console.error(`Error in updating ASG ${AutoScalingGroupName}:`, err)
    );

  console.log(result);

  return true;
};

export { scaleAutoScalingGroup, getAutoScalingGroupState };
export class People {
    people_id: number;
    surname: string;
    age: number;

    constructor(values: Object = {}) {
        Object.assign(this, values);
      }
}
/*!
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */

function observeLeafProperties


 0020 × 000D ÷	#  × [0.3] ONE DOT LEADER (IN) × [7.01] SPACE (SP) × [6.0] <CARRIAGE RETURN (CR)> (CR) ÷ [0.3]
× 2024 × 0308 × 000D ÷	#  × [0.3] ONE DOT LEADER (IN) × [9.0] COMBINING DIAERESIS (CM1_CM) × [6.0] <CARRIAGE RETURN (CR)> (CR) ÷ [0.3]
× 2024 × 0308 × 0020 × 000D ÷	#  × [0.3] ONE DOT LEADER (IN) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) × [6.0] <CARRIAGE RETURN (CR)> (CR) ÷ [0.3]
× 2024 × 0021 ÷	#  × [0.3] ONE DOT LEADER (IN) × [13.01] EXCLAMATION MARK (EX) ÷ [0.3]
× 2024 × 0020 × 0021 ÷	#  × [0.3] ONE DOT LEADER (IN) × [7.01] SPACE (SP) × [13.01] EXCLAMATION MARK (EX) ÷ [0.3]
× 2024 × 0308 × 0021 ÷	#  × [0.3] ONE DOT LEADER (IN) × [9.0] COMBINING DIAERESIS (CM1_CM) × [13.01] EXCLAMATION MARK (EX) ÷ [0.3]
× 2024 × 0308 × 0020 × 0021 ÷	#  × [0.3] ONE DOT LEADER (IN) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) × [13.01] EXCLAMATION MARK (EX) ÷ [0.3]
× 2024 × 00A0 ÷	#  × [0.3] ONE DOT LEADER (IN) × [12.1] NO-BREAK SPACE (GL) ÷ [0.3]
× 2024 × 0020 ÷ 00A0 ÷	#  × [0.3] ONE DOT LEADER (IN) × [7.01] SPACE (SP) ÷ [18.0] NO-BREAK SPACE (GL) ÷ [0.3]
× 2024 × 0308 × 00A0 ÷	#  × [0.3] ONE DOT LEADER (IN) × [9.0] COMBINING DIAERESIS (CM1_CM) × [12.2] NO-BREAK SPACE (GL) ÷ [0.3]
× 2024 × 0308 × 0020 ÷ 00A0 ÷	#  × [0.3] ONE DOT LEADER (IN) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] NO-BREAK SPACE (GL) ÷ [0.3]
× 2024 ÷ AC00 ÷	#  × [0.3] ONE DOT LEADER (IN) ÷ [999.0] HANGUL SYLLABLE GA (H2) ÷ [0.3]
× 2024 × 0020 ÷ AC00 ÷	#  × [0.3] ONE DOT LEADER (IN) × [7.01] SPACE (SP) ÷ [18.0] HANGUL SYLLABLE GA (H2) ÷ [0.3]
× 2024 × 0308 ÷ AC00 ÷	#  × [0.3] ONE DOT LEADER (IN) × [9.0] COMBINING DIAERESIS (CM1_CM) ÷ [999.0] HANGUL SYLLABLE GA (H2) ÷ [0.3]
× 2024 × 0308 × 0020 ÷ AC00 ÷	#  × [0.3] ONE DOT LEADER (


52\\uFF0E\\uFF61',

		// New paragraph characters without \n and \r
		'regExpNewParagraph': '\\f\\u2029',

		// Exclamation marks without '!'
		'regExpExclamationMarks':
			'\\u01C3\\u01C3\\u01C3\\u055C\\u055C\\u07F9\\u1944\\u1944' +
			'\\u203C\\u203C\\u2048\\u2048\\uFE15\\uFE57\\uFF01',

		// Question marks without '?'
		'regExpQuestionMarks':
			'\\u037E\\u055E\\u061F\\u1367\\u1945\\u2047\\u2049' +
			'\\u2CFA\\u2CFB\\u2E2E\\uA60F\\uA6F7\\uFE56\\uFF1F',

		/** Clip settings. */

		// Find clip position: characters from right
		'clipHeadingLeft':      1500,
		'clipParagraphLeftMax': 1500,
		'clipParagraphLeftMin':  500,
		'clipLineLeftMax':      1000,
		'clipLineLeftMin':       500,
		'clipBlankLeftMax':     1000,
		'clipBlankLeftMin':      500,
		'clipCharsLeft':         500,

		// Find clip position: characters from right
		'clipHeadingRight':      1500,
		'clipParagraphRightMax': 1500,
		'clipParagraphRightMin':  500,
		'clipLineRightMax':      1000,
		'clipLineRightMin':       500,
		'clipBlankRightMax':     1000,
		'clipBlankRightMin':      500,
		'clipCharsRight':         500,

		// Maximum number of lines to search for clip position
		'clipLinesRightMax': 10,
		'clipLinesLeftMax': 10,

		// Skip clipping if ranges are too close
		'clipSkipLines': 5,
		'clipSkipChars': 1000,

		// Css stylesheet
		'cssMarkLeft': '◀',
		'cssMarkRight': '▶',
		'stylesheet':

			// Insert
			'.wikEdDiffInsert {' +
			'font-weight: bold; background-color: #bbddff; ' +
			'color: #222; border-radius: 0.25em; padding: 0.2em 1px; ' +
			'} ' +
			'.wikEdDiffInsertBlank { background-color: #66bbff; } ' +
			'.wikEdDiffFragment:hover .wikEdDiffInsertBlank { background-color: #bbddff; } ' +

			// Delete
			'.wikEdDiffDelete {' +
			'font-weight: bold; background-color: #ffe49c; ' +
			'color: #222; border-radius: 0.25em; padding: 0.2em 1px; ' +
			'} ' +
			'.wikEdDiffDeleteBlank { background-color: #ffd064; } ' +
			'.wikEdDiffFragment:hover .wikEdDiffDeleteBlank { background-color: #ffe49c; } ' +

			// Block
			'.


rc_buf.offset + src_buf.size), DeviceStream::implicit().conn());
      }
      offset += dst.stride() * dst.batch_size();
    } else {
      panic!("load: unimplemented reader type: {:?}", reader);
    }
    offset
  }

  fn store(src: &Self, mut offset: usize, writer: &mut Any) -> usize {
    // FIXME
    unimplemented!();
  }
}

impl IoBuf for DeviceArray1d<f32> {
  fn load(dst: &mut Self, mut offset: usize, reader: &mut Any) -> usize {
    let buf_len = dst.dim();
    if reader.downcast_mut::<NullIo>().is_some() {
      offset += buf_len;
    } else if reader.downcast_mut::<Vec<f32>>().is_some() {
      let reader = reader.downcast_mut::<Vec<f32>>().unwrap();
      dst.as_view_mut().load_sync(reader[offset .. offset + buf_len].flatten(), DeviceStream::implicit().conn());
      offset += buf_len;
    } else if reader.downcast_mut::<DeviceMem<f32>>().is_some() {
      let reader = reader.downcast_mut::<DeviceMem<f32>>().unwrap();
      dst.as_view_mut().copy(reader.as_ref().slice(offset, offset + buf_len).flatten(), DeviceStream::implicit().conn());
      offset += buf_len;
    } else {
      panic!("store: unimplemented reader type: {:?}", reader);
    }
    offset
  }

  fn store(src: &Self, mut offset: usize, writer: &mut Any) -> usize {
    let buf_len = src.dim();
    if writer.downcast_mut::<NullIo>().is_some() {
      offset += buf_len;
    } else if writer.downcast_mut::<Vec<f32>>().is_some() {
      let writer = writer.downcast_mut::<Vec<f32>>().unwrap();
      src.as_view().store_sync(writer[offset .. offset + buf_len].flatten_mut(), DeviceStream::implicit().conn());
      offset += buf_len;
    } else if writer.downcast_mut::<DeviceMem<f32>>().is_some() {
      let writer = writer.downcast_mut::<DeviceMem<f32>>().unwrap();
      writer.as_mut().slice_mut(offset, offset + buf_len).flatten_mut().copy(src.as_view(), DeviceStream::implicit().conn());
      offset += buf_len;
    } else {
      panic!("store: unimplemented writer type: {:?}", writer);
    }
    offset
  }
}

impl IoBuf for DeviceBatchArray1d<f32> {
  fn load(dst: &mut Self, mut offset: usize, reader: &mut Any) -> usize {
    // FIXME
    unimplemented!();
  }

  fn store(src: &Self, mut offset: usize, writer: &mut Any) -> usize {
    if writer.downcast_mut::<Vec<f32>>().is_some() {
      let dst_buf = writer.downcast_mut::<Vec<f32>>().unwrap();
      let x_dim = src.dim();
      let batch_sz = src.batch_size();
      src.as_view().store_sync(dst_buf.reshape_mut((x_dim, batch_sz)), DeviceStream::implicit().conn());
      /*println!("DEBUG: PassOp: storing value: {:?}", src.as_view().dim());
      dst_buf.reshape_mut((x_dim, batch_sz)).set_constant(3.14);
      DeviceStream::implicit().conn().sync();*/
      offset += x_dim * batch_sz;
    } else {
      panic!("store: unimplemented writer type: {:?}", writer);
    }
    offset
  }


seImage, "some/builder")
					h.AssertError(t, err, "failed to parse 'CNB_USER_ID', value 'not an int' should be an integer")
				})
			})

			when("CNB_GROUP_ID is not an int", func() {
				it.Before(func() {
					h.AssertNil(t, baseImage.SetEnv("CNB_USER_ID", "1234"))
					h.AssertNil(t, baseImage.SetEnv("CNB_GROUP_ID", "not an int"))
				})

				it("returns an error", func() {
					_, err := builder.New(baseImage, "some/builder")
					h.AssertError(t, err, "failed to parse 'CNB_GROUP_ID', value 'not an int' should be an integer")
				})
			})

			when("missing stack id label and run image", func() {
				it.Before(func() {
					h.AssertNil(t, baseImage.SetEnv("CNB_USER_ID", "1234"))
					h.AssertNil(t, baseImage.SetEnv("CNB_GROUP_ID", "4321"))
				})

				it("does not return an error", func() {
					_, err := builder.New(baseImage, "some/builder")
					h.AssertNilE(t, err)
				})
			})

			when("mixins metadata is malformed", func() {
				it.Before(func() {
					h.AssertNil(t, baseImage.SetEnv("CNB_USER_ID", "1234"))
					h.AssertNil(t, baseImage.SetEnv("CNB_GROUP_ID", "4321"))
					h.AssertNil(t, baseImage.SetLabel("io.buildpacks.stack.id", "some-id"))
				})

				it("returns an error", func() {
					h.AssertNil(t, baseImage.SetLabel("io.buildpacks.stack.mixins", `{"mixinX", "mixinY", "build:mixinA"}`))
					_, err := builder.New(baseImage, "some/builder")
					h.AssertError(t, err, "getting label io.buildpacks.stack.mixins")
				})
			})

			when("order metadata is malformed", func() {
				it.Before(func() {
					h.AssertNil(t, baseImage.SetEnv("CNB_USER_ID", "1234"))
					h.AssertNil(t, baseImage.SetEnv("CNB_GROUP_ID", "4321"))
					h.AssertNil(t, baseImage.SetLabel("io.buildpacks.stack.id", "some-id"))
				})

				it("returns an error", func() {
					h.AssertNil(t, baseImage.SetLabel("io.buildpacks.buildpack.order", `{"something", }`))
					_, err := builder.New(baseImage, "some/builder")
					h.AssertError(t, err, "getting label io.buildpacks.buildpack.order")
				})
			})
		})
	})

	when("the base image is a valid build image", func() {
		it.Before(func() {
			var err error
			h.AssertNil(t, baseImage.SetEnv("CNB_USER_ID", "1234"))
			h.AssertNil(t, baseImage.SetEnv("CNB_GROUP_ID", "4321"))
			h.AssertNil(t, baseImage.SetLabel("io.buildpacks.stack.id", "some.stack.id"))
			h.AssertNil(t, baseImage.SetLabel("io.buildpacks.stack.mixins", `["mixinX", "mixinY", "build:mixinA"]`))
			subject, err = builder.New(baseImage, "some/builder")
			h.AssertNil(t, err)

			subject.SetLifecycle(mockLifecycle)
		})

		it.After(func() {
			h.AssertNilE(t, baseImage.Cleanup())
		})

		when("#Save", func() {
			it("creates a builder from the image and renames it", func() {
				h.AssertNil(t, subject.Save(logger, builder


_SAP_2*scope_2_SAP_3*scope_2_SAP_4*barrel_2_SAP_1)
	local N2_C_Y_SAP = round((SAP_OFFSET_Y[bullet23]/screenMultiplier)*scope_2_SAP_1*scope_2_SAP_2*scope_2_SAP_3*scope_2_SAP_4*barrel_2_SAP_1)
	local N2_AT_SAP = 140
	local N2_ST_SAP = SAP_RPM - N2_AT_SAP
	N2_SAP_C_X[#N2_SAP_C_X+1] = N2_C_X_SAP
	N2_SAP_C_Y[#N2_SAP_C_Y+1] = N2_C_Y_SAP
	N2_SAP_AT[#N2_SAP_AT+1] = N2_AT_SAP
	N2_SAP_ST[#N2_SAP_ST+1] = N2_ST_SAP
	bullet23 = bullet23 + 1
end
--M92
local bullet24 = 1
N2_M92_C_X = {}
N2_M92_C_Y = {}
N2_M92_AT = {}
N2_M92_ST = {}
for M92_2st = bullet24, M92_BULLETS do
	local N2_C_X_M92 = round((M92_OFFSET_X[bullet24]/screenMultiplier)*scope_2_M92_1*scope_2_M92_2*scope_2_M92_3*scope_2_M92_4*barrel_2_M92_1)
	local N2_C_Y_M92 = round((M92_OFFSET_Y[bullet24]/screenMultiplier)*scope_2_M92_1*scope_2_M92_2*scope_2_M92_3*scope_2_M92_4*barrel_2_M92_1)
	local N2_AT_M92 = 150
	local N2_ST_M92 = M92_RPM - N2_AT_M92
	N2_M92_C_X[#N2_M92_C_X+1] = N2_C_X_M92
	N2_M92_C_Y[#N2_M92_C_Y+1] = N2_C_Y_M92
	N2_M92_AT[#N2_M92_AT+1] = N2_AT_M92
	N2_M92_ST[#N2_M92_ST+1] = N2_ST_M92
	bullet24 = bullet24 + 1
end
--PYTHON
local bullet25 = 1
N2_PYTHON_C_X = {}
N2_PYTHON_C_Y = {}
N2_PYTHON_AT = {}
N2_PYTHON_ST = {}
for PYTHON_2st = bullet25, PYTHON_BULLETS do
	local N2_C_X_PYTHON = round((PYTHON_OFFSET_X[bullet25]/screenMultiplier)*scope_2_PYTHON_1*scope_2_PYTHON_2*scope_2_PYTHON_3*scope_2_PYTHON_4*barrel_2_PYTHON_1)
	local N2_C_Y_PYTHON = round((PYTHON_OFFSET_Y[bullet25]/screenMultiplier)*scope_2_PYTHON_1*scope_2_PYTHON_2*scope_2_PYTHON_3*scope_2_PYTHON_4*barrel_2_PYTHON_1)
	local N2_AT_PYTHON = 145
	local N2_ST_PYTHON = PYTHON_RPM - N2_AT_PYTHON
	N2_PYTHON_C_X[#N2_PYTHON_C_X+1] = N2_C_X_PYTHON
	N2_PYTHON_C_Y[#N2_PYTHON_C_Y+1] = N2_C_Y_PYTHON
	N2_PYTHON_AT[#N2_PYTHON_AT+1] = N2_AT_PYTHON
	N2_PYTHON_ST[#N2_PYTHON_ST+1] = N2_ST_PYTHON
	bullet25 = bullet25 + 1
end
-----------------------------------------------------------------

--MAIN_EVENT_PART------------------------------------------------
local gun = 0
local kickback = falseB
function OnEvent(event, arg)
--AK47
	if (event == "MOUSE_BUTTON_PRESSED" and arg == A


/*
Copyright 2020 The OneFlow Authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

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

#include "oneflow/core/common/util.h"
#include "oneflow/core/common/shape.h"

namespace oneflow {

class NdIndex final {
 public:
  NdIndex() = default;
  explicit NdIndex(const DimVector& dim_vec);
  NdIndex(const std::initializer_list<int64_t>& dim_vec);
  ~NdIndex() = default;
  NdIndex& operator=(const NdIndex& other);

  bool operator==(const NdIndex& rhs) const;
  bool operator!=(const NdIndex& rhs) const { return !(*this == rhs); }

  const DimVector& dim_vec() const { return dim_vec_; }

  int64_t At(int64_t index) const { return dim_vec_.at(index); }
  int64_t NumAxes() const { return dim_vec_.size(); }

 private:
  DimVector dim_vec_;
};

}  // namespace oneflow

#endif  // ONEFLOW_CORE_COMMON_ND_INDEX_H_


bogus id
		try (RevWalk rw = new RevWalk(db)) {
			c.parseCanonical(rw, b.toByteArray());
		}

		assertEquals("ISO-8859-1", c.getEncoding().name());
		assertEquals("F\u00f6r fattare", c.getAuthorIdent().getName());
		assertEquals("\u304d\u308c\u3044", c.getShortMessage());
		assertEquals("\u304d\u308c\u3044\n\nHi\n", c.getFullMessage());
	}

	@Test
	public void testParse_incorrectUtf8Name() throws Exception {
		ByteArrayOutputStream b = new ByteArrayOutputStream();
		b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n"
				.getBytes(UTF_8));
		b.write("author au <a@example.com> 1218123387 +0700\n".getBytes(UTF_8));
		b.write("committer co <c@example.com> 1218123390 -0500\n"
				.getBytes(UTF_8));
		b.write("encoding 'utf8'\n".getBytes(UTF_8));
		b.write("\n".getBytes(UTF_8));
		b.write("Sm\u00f6rg\u00e5sbord\n".getBytes(UTF_8));

		RevCommit c = new RevCommit(
				id("9473095c4cb2f12aefe1db8a355fe3fafba42f67"));
		try (RevWalk rw = new RevWalk(db)) {
			c.parseCanonical(rw, b.toByteArray());
		}
		assertEquals("'utf8'", c.getEncodingName());
		assertEquals("Sm\u00f6rg\u00e5sbord\n", c.getFullMessage());

		try {
			c.getEncoding();
			fail("Expected " + IllegalCharsetNameException.class);
		} catch (IllegalCharsetNameException badName) {
			assertEquals("'utf8'", badName.getMessage());
		}
	}

	@Test
	public void testParse_illegalEncoding() throws Exception {
		ByteArrayOutputStream b = new ByteArrayOutputStream();
		b.write("tree 9788669ad918b6fcce64af8882fc9a81cb6aba67\n"
				.getBytes(UTF_8));
		b.write("author au <a@example.com> 1218123387 +0700\n".getBytes(UTF_8));
		b.write("committer co <c@example.com> 1218123390 -0500\n"
				.getBytes(UTF_8));
		b.write("encoding utf-8logoutputencoding=gbk\n".getBytes(UTF_8));
		b.write("\n".getBytes(UTF_8));
		b.write("message\n".getBytes(UTF_8));

		RevCommit c = new RevCommit(
				id("9473095c4cb2f12aefe1db8a355fe3fafba42f67"));
		try (RevWalk rw = new RevWalk(db)) {
			c.parseCanonical(rw, b.toByteArray());
		}
		assertEquals("utf-8logoutputencoding=gbk", c.getEncodingName());
		assertEquals("message\n", c.getFullMessage());
		assertEquals("message", c.getShortMessage());
		assertTrue(c.getFooterLines().isEmpty());
		assertEquals("au", c.getAuthorIdent().getName());

		try {
			c.getEncoding();
			fail("Expected " + IllegalCharsetNameException.class);
		} catch (IllegalCharsetNameException badName) {
			assertEquals("utf-8logoutputencoding=gbk", badName.getMessage());
		}
	}

	@Test
	public void testParse_unsupportedEncoding() throws Exception {
		ByteArrayOutputStream b = new ByteArrayOutputStream();
		b.write("tree 9788669ad918b6fcce64af8882fc9a81


list .project .info .stat,#projects_index>.list .project .info .when{line-height:25px;color:#333;font-size:14px}#projects_index>.list .project .info .name a{font-size:18px;font-weight:700}#projects_index>.list .project .info .description{text-overflow:ellipsis;vertical-align:top;white-space:nowrap;overflow:hidden}#projects_index>.list .project .info .when{font-size:12px}#projects_index>.list .project .info .when span{margin-right:4px}#projects_index>.list .project .info .when span.avatar img{width:20px;border-radius:10px;vertical-align:-4px}#projects_index>.list .project .info .when span.time,#projects_index>.list .project .info .when span.username{color:#777}#projects_index>.list .project .info .stat span{font-size:15px;display:inline-block;width:70px}#projects_index .more{cursor:pointer;height:auto}#about_us{background:#FFF;margin-top:30px;margin-bottom:30px}#about_us .content{padding:50px}#about_us .content section{margin:0 30px 30px}#about_us .content section .title{font-size:24px;font-weight:500;color:#000;border-bottom:1px solid #EEE;padding-bottom:10px;margin-left:30px}#about_us .content section.intro p{font-size:16px;line-height:35px;color:#333;margin-top:0;margin-bottom:30px;text-indent:30px}#about_us .content section.contact .link,#about_us .content section.contact .qrcode{display:inline-block}#about_us .content section.contact .link{padding:10px 0}#about_us .content section.contact .link p{font-size:16px;color:#000;margin:8px 0;padding:5px 0;text-indent:30px}#about_us .content section.contact .link p a{text-decoration:none;color:#000}#about_us .content section.contact .qrcode{float:right;padding:30px 100px;text-align:center}#about_us .content section.contact .qrcode img{width:140px;padding:5px}#about_us .content section.contact .qrcode p{font-size:13px;margin-top:0}#about_us .content section.icons div.items{padding-left:30px;position:relative}#about_us .content section.icons div.items .thumb-box img.thumb{height:100px;float:left;margin:10px;cursor:pointer}#about_us .content section.icons div.items .thumb-box .ui.popup.box.show.logo{max-width:inherit;right:inherit;left:250px;top:-100px;padding:1em}#about_us .content section.icons div.items .thumb-box .ui.popup.box.show.logo img{height:300px}#about_us .content section.icons div.items p.dlink{line-height:120px;text-align:right;border-bottom:1px solid #EEE;padding-bottom:1em}#about_us .content section.icons div.items p.dlink span{display:inline-block;margin-left:20px}#about_us .content section.icons div.items p.dlink span a{color:#333;font-size:13px}#join_us{width:980px}#join_us .hide{display:none}#join_us .content .title{text-align:center;font-size:44px;font-family:"Avenir Next","Myriad Pro","Helvetica Neue",Helvetica,"Segoe UI",Arial,sans-serif;line-height:60px;font-weight:bolder;margin-top:66px;margin-bottom:10px;color:#333;text-shadow:0 2px


/*
 * Gamedev Framework (gf)
 * Copyright (C) 2016-2022 Julien Bernard
 *
 * This software is provided 'as-is', without any express or implied
 * warranty.  In no event will the authors be held liable for any damages
 * arising from the use of this software.
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software. If you use this software
 *    in a product, an acknowledgment in the product documentation would be
 *    appreciated but is not required.
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 */
#ifndef GF_PACKET_H
#define GF_PACKET_H

#include <cassert>
#include <cstdint>
#include <vector>

#include "Id.h"
#include "NetApi.h"
#include "Packet.h"
#include "Streams.h"
#include "Serialization.h"
#include "SerializationOps.h"

namespace gf {
#ifndef DOXYGEN_SHOULD_SKIP_THIS
inline namespace v1 {
#endif

  /**
   * @ingroup net_sockets
   * @brief A packet of bytes
   */
  struct GF_NET_API Packet {
    Id type = InvalidId; ///< The type of the packet
    std::vector<uint8_t> bytes; ///< The bytes representing the object

    /**
     * @brief Get the type of the underlying bytes
     */
    Id getType() {
      if (type != InvalidId) {
        return type;
      }

      BufferInputStream stream(&bytes);
      Deserializer deserializer(stream);
      deserializer | type;
      return type;
    }

    /**
     * @brief Deserialize the underlying bytes into an object
     */
    template<typename T>
    T as() {
      BufferInputStream stream(&bytes);
      Deserializer deserializer(stream);

      T data;
      deserializer | type | data;
      assert(T::type == type);
      return data;
    }

    /**
     * @brief Serialize the object into bytes
     */
    template<typename T>
    void is(const T& data) {
      bytes.clear();
      type = T::type;
      gf::BufferOutputStream stream(&bytes);
      gf::Serializer serializer(stream);
      serializer | type | const_cast<T&>(data);
    }

  };

#ifndef DOXYGEN_SHOULD_SKIP_THIS
}
#endif
}

#endif // GF_PACKET_H


#     if not writer.isOpened():
#         raise RuntimeError("GStreamer v4l2sink 打不开；请安装 gstreamer1.0-plugins-base/good/bad。")
#     print(f"[OK] GStreamer (MJPEG) → {out_dev} {w}x{h}@{fps}")
#     return writer

def _open_gst_writer(w: int, h: int, fps: int, out_dev: str):
    pipeline = (
        f'appsrc is-live=true block=true format=TIME '
        f'! videoconvert '
        f'! video/x-raw,format=BGR,width={w},height={h},framerate={fps}/1 '
        f'! v4l2sink device={out_dev} sync=false'
    )
    writer = cv2.VideoWriter(pipeline, cv2.CAP_GSTREAMER, 0, fps, (w, h))
    if not writer.isOpened():
        raise RuntimeError("GStreamer v4l2sink 打不开；请安装 gstreamer1.0-plugins-base/good/bad。")
    print(f"[OK] GStreamer v4l2sink → {out_dev} {w}x{h}@{fps}")
    return writer

# ================= 深度推理：Depth Anything V2 =================

_DA_model = None
_DA_device = None
_DA_variant = None

def _infer_variant_from_ckpt(ckpt_path: str, cli_variant: Optional[str]) -> str:
    if cli_variant:
        v = cli_variant.lower()
        if v in ("vitl", "vitb", "vits", "vitg"):
            return v
        raise ValueError(f"--variant 仅支持 vits/vitb/vitl/vitg，收到：{cli_variant}")
    name = os.path.basename(ckpt_path).lower()
    if "vitb" in name: return "vitb"
    if "vitl" in name: return "vitl"
    if "vits" in name: return "vits"
    if "vitg" in name: return "vitg"
    return "vitl"  # 默认

def load_da_v2_model(ckpt_path: str, device: Optional[str] = None, variant: Optional[str] = None):
    global _DA_model, _DA_device, _DA_variant
    if _DA_model is not None:
        return _DA_model, _DA_device, _DA_variant

    if device is None:
        device = "cuda" if torch.cuda.is_available() else "cpu"
    _DA_device = device
    _DA_variant = _infer_variant_from_ckpt(ckpt_path, variant)

    ModelClass = try_import_depthanything_class()

    # 与官方 run.py 一致的配置
    model_configs = {
        'vits': {'encoder': 'vits', 'features': 64,  'out_channels': [48, 96, 192, 384]},
        'vitb': {'encoder': 'vitb', 'features': 128, 'out_channels': [96, 192, 384, 768]},
        'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]},
        'vitg': {'encoder': 'vitg', 'features': 384, 'out_channels': [1536, 1536, 1536, 1536]},
    }
    cfg = model_configs[_DA_variant]
    model = ModelClass(**cfg)

    state = torch.load(ckpt_path, map_location="cpu")
    if isinstance(state, dict) and "model" in state:
        state = state["model"]
    # 宽松加载，允许头部不匹配（如换 backbone）
    model.load_state_dict(state, strict=False)

    model.eval().to(device)
    _DA_model = model
    print(f"[DAv2] 模型加载完成：variant={_DA_variant}  ckpt={ckpt_path}  device={device}")
    return _DA_model, _DA_device, _DA_variant

@torch.inference_mode()
def _da_preprocess_bchw(frame_bgr: np.ndarray, side: int, device: str) -> torch.Tensor:
    h, w = frame_bgr.shape[:2]
    rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
    scale = side / min(h, w)
    nh, nw = int(round(h * scale)), int(round(w * scale))
    rgb_rs = cv2.resize(rgb, (nw, nh), interpolation=cv2.INTER_AREA)
    pad_h = max(0, side - nh)
    pad_w = max(0, side - nw)
    top = pad_h // 2; bottom = pad_h - top
    left = pad_w // 2; right = pad_w - left
    rgb_pad = cv2.copyMakeBorder(rgb_rs, top, bottom, left, right, borderType=cv2.BORDER_CONSTANT, value=(0,0,0))
    x = torch.from_numpy(rgb_pad).float().permute(2,0,1).unsqueeze(0) / 255.0
    x = (x - IMAGENET_MEAN) / IMAGENET_STD
    return x.to(device, non_blocking=True), (top, left, nh, nw, h, w)

@torch.inference_mode()
def _da_postprocess_to_vis(depth: np.ndarray, w: int, h: int, crop: tuple) -> np.ndarray:
    top, left, nh, nw, H, W = crop
    depth = depth[top:top+nh, left:left+nw]
    depth = cv2.resize(depth, (W, H), interpolation=cv2.INTER_CUBIC)
    dmin, dmax = np.percentile(depth, 2), np.percentile(depth, 98)
    depth = np.clip((depth - dmin) / (dmax - dmin + 1e-8), 0, 1)
    depth_u8 = (depth * 255).astype(np.uint8)
    return cv2.applyColorMap(depth_u8, cv2.COLORMAP_TURBO)

@torch.inference_mode()
def run_depthanything(frame_bgr: np.ndarray, ckpt_path: str, device: Optional[str] = None, variant: Optional[str] = None) -> np.ndarray:
    model, device, _ = load_da_v2_model(ckpt_path, device, variant)

    # 优先使用仓库自带 API（若存在）
    if hasattr(model, "infer_image"):
        try:
            depth = model.infer_image(frame_bgr, DA_INPUT_SIDE)  # 期望返回 HxW float
            h, w = frame_bgr.shape[:2]
            retur


 0.62826,0.12914 0.28775,0.10746 0.41301,0.4698 0.41649,1.00131 0.004,0.56609 -0.14605,0.99689 -0.43658,1.09023 -0.38576,0.13409 -0.77469,0.21327 -1.16476,0.23674 -2.27894,0.078 -4.55817,0.15034 -6.83727,0.1765 -1.02878,0.0118 -2.05785,-0.0676 -3.08618,-0.14775 -0.21765,-0.0141 -0.43131,-0.13904 -0.62609,-0.36852 -0.0591,-0.10369 -0.10795,-0.23673 -0.14281,-0.38965 -0.0349,-0.15294 -0.0551,-0.32256 -0.0592,-0.49584 -0.007,-0.42226 0.16208,-0.58376 0.33287,-0.6027 0.12453,-0.0141 0.24949,-0.009 0.37413,-0.0165 l 5.3364,-0.22128 v -0.062 c 1.68497,-0.11217 3.36966,-0.23283 5.05431,-0.32886 0.0702,-0.005 0.14031,-0.005 0.21042,-0.002 z m -4.44451,6.41278 c 0.23418,-10e-4 0.46849,4.2e-4 0.70265,0.0118 0.23284,0.0118 0.46495,0.066 0.69396,0.16637 0.0944,0.0339 0.18023,0.14752 0.24191,0.31927 0.0618,0.17155 0.0951,0.39014 0.0937,0.61486 0.0118,0.24209 -0.0145,0.48573 -0.0738,0.68523 -0.0593,0.1996 -0.14735,0.34066 -0.24788,0.39731 -0.19179,0.15601 -0.39285,0.2382 -0.59568,0.24379 -1.09056,-0.11759 -2.1808,-0.27916 -3.27027,-0.43509 -0.0776,-0.0189 -0.15329,-0.0648 -0.2248,-0.13809 -0.17518,-0.16355 -0.28457,-0.44725 -0.26852,-0.92454 0.002,-0.18664 0.0322,-0.36587 0.0844,-0.50606 0.0523,-0.14022 0.12375,-0.23259 0.202,-0.2617 0.15141,-0.0818 0.30573,-0.12772 0.46101,-0.13691 0.49962,-0.0165 0.99936,-0.007 1.49897,-0.007 v -0.025 c 0.23417,0 0.4682,-0.005 0.70239,-0.005 z' /%3E%3C/g%3E%3C/svg%3E%0A");
    --icon-doodle-pros: url("data:image/svg+xml,%0A%3Csvg width='24' height='24' viewBox='0 0 24 24' fill='%23000000' stroke-linecap='round' stroke-linejoin='round' xmlns='http://www.w3.org/2000/svg' %3E%3Cg transform='translate(375.03552,-450.44234)' %3E%3Cpath d='m -374.73,470.54297 c 0.0527,0.74383 0.17775,1.56807 1.05887,1.59024 1.75761,0.0988 5.27003,-0.12873 6.39374,-0.11757 3.80076


import org.mozilla.fenix.databinding.ComponentTopSitesPagerBinding
import org.mozilla.fenix.home.sessioncontrol.AdapterItem
import org.mozilla.fenix.home.sessioncontrol.TopSiteInteractor

class TopSitePagerViewHolder(
    view: View,
    appStore: AppStore,
    viewLifecycleOwner: LifecycleOwner,
    interactor: TopSiteInteractor,
) : RecyclerView.ViewHolder(view) {

    private val binding = ComponentTopSitesPagerBinding.bind(view)
    private val topSitesPagerAdapter = TopSitesPagerAdapter(appStore, viewLifecycleOwner, interactor)
    private val pageIndicator = binding.pageIndicator
    private var currentPage = 0

    private val topSitesPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            if (currentPage != position) {
                TopSites.swipeCarousel.record(
                    TopSites.SwipeCarouselExtra(
                        position.toString(),
                    ),
                )
            }

            pageIndicator.setSelection(position)
            currentPage = position
        }
    }

    init {
        binding.topSitesPager.apply {
            adapter = topSitesPagerAdapter
            registerOnPageChangeCallback(topSitesPageChangeCallback)
            // Retain one more TopSites pages to ensure a new layout request will measure the first page also.
            // Otherwise the second page with 3 TopSites will have the entire ViewPager only show
            // the first row of TopSites, hiding half of those shown on the first page.
            offscreenPageLimit = 1
        }
    }

    fun update(payload: AdapterItem.TopSitePagerPayload) {
        // Due to offscreenPageLimit = 1 we need to update both pages manually here
        topSitesPagerAdapter.notifyItemChanged(0, payload)
        topSitesPagerAdapter.notifyItemChanged(1, payload)
    }

    fun bind(topSites: List<TopSite>) {
        val chunkedTopSites = topSites.chunked(TOP_SITES_PER_PAGE)
        topSitesPagerAdapter.submitList(chunkedTopSites)

        // Don't show any page indicator if there is only 1 page.
        val numPages = if (topSites.size > TOP_SITES_PER_PAGE) {
            TOP_SITES_MAX_PAGE_SIZE
        } else {
            0
        }

        pageIndicator.isVisible = numPages > 1
        pageIndicator.setSize(numPages)
    }

    companion object {
        const val LAYOUT_ID = R.layout.component_top_sites_pager
        const val TOP_SITES_MAX_PAGE_SIZE = 2
        const val TOP_SITES_PER_PAGE = 8
    }
}
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.fenix.home.recenttabs.interactor

import org.mozilla.fenix.home.recenttabs.RecentTab

/**
 * Interface for recent tab related actions in the Home screen.
 */
interface RecentTabInteractor {
    /**
     * Opens the given tab. Called when a user clicks on a recent tab.
     *
     * @param tabId The ID of the tab to open.
     */
    fun onRecentTabClicked(tabId: String)

    /**
     * Show the tabs tray. Called when a user clicks on the "Show all" button besides the recent
     * tabs.
     */
    fun onRecentTabShowAllClicked()

    /**
     * Removes a bookmark from the recent bookmark list. Called when a user clicks the "Remove"
     * button for recently saved bookmarks on the home screen.
     *
     * @param tab The tab that has been removed.


::Run(TUint aCount)
	{
	TInt r = iProp.Define(iCategory, iKey, RProperty::EInt, KPassPolicy, KPassPolicy);
	TF_ERROR(r, r == KErrNone);
	r = iProp.Attach(iCategory,iKey);
	TF_ERROR(r, r == KErrNone);

	TRequestStatus thrStatus;
	RThread thr;
	r = thr.Create(KNullDesC, TrublemakerThreadEntry, 0x2000, NULL, this);
	TF_ERROR(r, r == KErrNone);
	thr.Logon(thrStatus);
	thr.SetPriority(EPriorityMore);
	thr.Resume();

	for (TUint i = 0; i < aCount; ++i)
		{
		TRequestStatus status;
		iProp.Subscribe(status);
		TInt st = status.Int();
		TF_ERROR(st, (st == KRequestPending) || (st == KErrCancel));
		iProp.Set(1);
		User::WaitForRequest(status);
		st = status.Int();
		TF_ERROR(st, (st == KErrNone) || (st == KErrCancel));
		}

	thr.Kill(EExitKill);
	User::WaitForRequest(thrStatus);
	TF_ERROR(thrStatus.Int(), thrStatus.Int() == EExitKill);
	thr.Close();

	iProp.Delete(iCategory, iKey);
	iProp.Close();
	}
// Copyright (c) 2002-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of the License "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
//

#include "t_property.h"

class CPropBroadcastSlave : public CBase
	{
public:
	static TInt LoopThreadEntry(TAny*);

	CPropBroadcastSlave(CPropBroadcast* aProg, TUid aCategory, TUint aMasterKey, TUint aSlaveKey);
	void Create(TThreadPriority);
	void Delete();
	void Loop();

	CPropBroadcast*	iProg;
	TUid			iCategory;
	TUint			iMasterKey;
	TUint			iSlaveKey;

	RProperty				iProp;
	RThread					iThread;
	TRequestStatus			iStatus;

	CPropBroadcastSlave*	iNext;
	};

CPropBroadcastSlave::CPropBroadcastSlave(CPropBroadcast* aProg, TUid aCategory, TUint aMasterKey, TUint aSlaveKey) :
		iProg(aProg), iCategory(aCategory), iMasterKey(aMasterKey), iSlaveKey(aSlaveKey)
	{
	}

void CPropBroadcastSlave::Create(TThreadPriority aPrio)
	{
	TInt r = iProp.Define(iCategory, iSlaveKey, RProperty::EInt, KPassPolicy, KPassPolicy);
	TF_ERROR_PROG(iProg, r, r == KErrNone);
	r = iProp.Attach(iCategory, iSlaveKey);
	TF_ERROR_PROG(iProg, r, r == KErrNone);

	r = iThread.Create(KNullDesC, LoopThreadEntry, 0x2000, NULL, this);
	TF_ERROR_PROG(iProg, r, r == KErrNone);
	iThread.Logon(iStatus);
	i


ffer_[0];
    std::size_t pend = epptr() - &buffer_[0];

    // Check if there is already enough space in the put area.
    if (n <= pend - pnext)
    {
      return;
    }

    // Shift existing contents of get area to start of buffer.
    if (gnext > 0)
    {
      pnext -= gnext;
      std::memmove(&buffer_[0], &buffer_[0] + gnext, pnext);
    }

    // Ensure buffer is large enough to hold at least the specified size.
    if (n > pend - pnext)
    {
      if (n <= max_size_ && pnext <= max_size_ - n)
      {
        pend = pnext + n;
        buffer_.resize((std::max<std::size_t>)(pend, 1));
      }
      else
      {
        std::length_error ex("boost::asio::streambuf too long");
        boost::asio::detail::throw_exception(ex);
      }
    }

    // Update stream positions.
    setg(&buffer_[0], &buffer_[0], &buffer_[0] + pnext);
    setp(&buffer_[0] + pnext, &buffer_[0] + pend);
  }

private:
  std::size_t max_size_;
  std::vector<char_type, Allocator> buffer_;

  // Helper function to get the preferred size for reading data.
  friend std::size_t read_size_helper(
      basic_streambuf& sb, std::size_t max_size)
  {
    return std::min<std::size_t>(
        std::max<std::size_t>(512, sb.buffer_.capacity() - sb.size()),
        std::min<std::size_t>(max_size, sb.max_size() - sb.size()));
  }
};

/// Adapts basic_streambuf to the dynamic buffer sequence type requirements.
#if defined(GENERATING_DOCUMENTATION)
template <typename Allocator = std::allocator<char> >
#else
template <typename Allocator>
#endif
class basic_streambuf_ref
{
public:
  /// The type used to represent the input sequence as a list of buffers.
  typedef typename basic_streambuf<Allocator>::const_buffers_type
    const_buffers_type;

  /// The type used to represent the output sequence as a list of buffers.
  typedef typename basic_streambuf<Allocator>::mutable_buffers_type
    mutable_buffers_type;

  /// Construct a basic_streambuf_ref for the given basic_streambuf object.
  explicit basic_streambuf_ref(basic_streambuf<Allocator>& sb)
    : sb_(sb)
  {
  }

  /// Copy construct a basic_streambuf_ref.
  basic_streambuf_ref(const basic_streambuf_ref& other) BOOST_ASIO_NOEXCEPT
    : sb_(other.sb_)
  {
  }

#if defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  /// Move construct a basic_streambuf_ref.
  basic_streambuf_ref(basic_streambuf_ref&& other) BOOST_ASIO_NOEXCEPT
    : sb_(other.sb_)
  {
  }
#endif // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)

  /// Get the size of the input sequence.
  std::size_t size() const BOOST_ASIO_NOEXCEPT
  {
    return sb_.size();
  }

  /// Get the maximum size of the dynamic buffer.
  std::size_t max_size() const BOOST_ASIO_NOEXCEPT
  {
    return sb_.max_size();
  }

  /// Get the current capacity of the dynamic buffer.
  std::size_t capacity() const BOOST_ASIO_NOEXCEPT
  {
    return sb_.capacity();
  }

  /// Get a list of buffers that represents the input sequence.
  const_buffers_type data() const BOOST_ASIO_NOEXCEPT
  {
    return


te.graph_widget = self:get_children_by_id("#graph")[1]

    self._private.menu = mebox {
        item_width = dpi(136),
        placement = beautiful.wibar.build_placement(self, self._private.wibar),
        {
            text = "Graph",
            icon = beautiful.icon("chart-line.svg"),
            icon_color = beautiful.palette.gray,
            on_show = function(item) item.checked = not not self._private.show_graph end,
            callback = function(item) self:show_graph(not item.checked) end,
        },
    }

    self.buttons = binding.awful_buttons {
        binding.awful({}, btn.middle, function()
            if not self._private.menu.visible then
                self:toggle_graph()
            end
        end),
        binding.awful({}, btn.right, function()
            self._private.menu:toggle()
        end),
        binding.awful({}, binding.group.mouse_wheel, function(trigger)
            local step_size = math.floor(10 / network_service.config.interval)
                * (self._private.graph_widget.step_width + self._private.graph_widget.step_spacing)
            self:set_graph_offset(self._private.graph_offset - (step_size * trigger.y))
        end),
    }

    capi.awesome.connect_signal("network::updated", function() self:refresh() end)

    self:connect_signal("mouse::enter", function()
        self._private.hover_widget = true
        update_opacity(self)
    end)
    self:connect_signal("mouse::leave", function()
        self._private.hover_widget = false
        update_opacity(self)
        self:set_graph_offset(0)
    end)

    update_opacity(self)
    self:set_graph_offset(0)
    self:refresh()

    return self
end

function network_widget.mt:__call(...)
    return network_widget.new(...)
end

return setmetatable(network_widget, network_widget.mt)


licedToArray(_splitByCharacterDist3, 2),
          nextChar = _splitByCharacterDist4[0],
          nextRemaining = _splitByCharacterDist4[1];

      if (isWordCharacter(nextChar, nextRemaining, isRTL)) {
        return true;
      }
    }

    if (PUNCTUATION.test(_char3)) {
      return false;
    }

    return true;
  };
  /**
   * Iterate on codepoints from right to left.
   */

  var codepointsIteratorRTL = function* codepointsIteratorRTL(str) {
    var end = str.length - 1;

    for (var i = 0; i < str.length; i++) {
      var char1 = str.charAt(end - i);

      if (isLowSurrogate(char1.charCodeAt(0))) {
        var char2 = str.charAt(end - i - 1);

        if (isHighSurrogate(char2.charCodeAt(0))) {
          yield char2 + char1;
          i++;
          continue;
        }
      }

      yield char1;
    }
  };
  /**
   * Is `charCode` a high surrogate.
   *
   * https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates
   */

  var isHighSurrogate = function isHighSurrogate(charCode) {
    return charCode >= 0xd800 && charCode <= 0xdbff;
  };
  /**
   * Is `charCode` a low surrogate.
   *
   * https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates
   */

  var isLowSurrogate = function isLowSurrogate(charCode) {
    return charCode >= 0xdc00 && charCode <= 0xdfff;
  };

  var CodepointType;

  (function (CodepointType) {
    CodepointType[CodepointType["None"] = 0] = "None";
    CodepointType[CodepointType["Extend"] = 1] = "Extend";
    CodepointType[CodepointType["ZWJ"] = 2] = "ZWJ";
    CodepointType[CodepointType["RI"] = 4] = "RI";
    CodepointType[CodepointType["Prepend"] = 8] = "Prepend";
    CodepointType[CodepointType["SpacingMark"] = 16] = "SpacingMark";
    CodepointType[CodepointType["L"] = 32] = "L";
    CodepointType[CodepointType["V"] = 64] = "V";
    CodepointType[CodepointType["T"] = 128] = "T";
    CodepointType[CodepointType["LV"] = 256] = "LV";
    CodepointType[CodepointType["LVT"] = 512] = "LVT";
    CodepointType[CodepointType["ExtPict"] = 1024] = "ExtPict";
    CodepointType[CodepointType["Any"] = 2048] = "Any";
  })(CodepointType || (CodepointType = {}));

  var reExtend = /^(?:[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u


�� 처리
- Clean Code 원칙: 명확한 네이밍, 단일 책임 원칙, 최소 의존성
- **함수형 프로그래밍 원칙**: 가급적 stateless 메서드 작성, 순수 함수 우선, 불변성 추구
- **명시적 의존성**: 메서드 파라미터로 필요한 모든 데이터를 명시적으로 전달
- **상태 의존성 최소화**: 내부 캐시나 상태에 의존하는 대신 명시적 파라미터 사용
- **Backend-Only CRUD**: 모든 데이터베이스 접근을 백엔드 API로 통일 (완료 ✅)

## 1. 최종 아키텍처 원칙: 설정 파일 기반 완전 분리

> **🦀 Modern Rust 2024 설계 원칙**: 모든 컴포넌트는 타입 안전성, 제로 코스트 추상화, 메모리 안전성을 보장하며, Clippy pedantic 수준의 코드 품질을 유지합니다.

### 1.1. 핵심 아키텍처 원칙: 설정과 실행의 완전한 분리 🎯

**설정 파일 기반 자율 운영 체계**:

**백엔드 (Rust) 역할**:
- **설정 파일 완전 의존**: `~/Library/Application Support/matter-certis-v2/matter_certis_config.json` 파일의 모든 설정값을 읽어 자율적으로 크롤링 계획 수립 및 실행
- **프론트엔드 독립성**: 프론트엔드로부터 어떤 설정값도 받지 않고 완전 자율 동작
- **동적 설정 적용**: 파일 시스템 감시를 통해 설정 파일 변경 시 자동으로 새로운 설정 적용
- **Actor 시스템 자율 제어**: 모든 동시성, 재시도, 배치 크기 등을 설정 파일 기반으로 동적 조정

**프론트엔드 (SolidJS) 역할**:
- **설정 편집 전용**: `matter_certis_config.json` 파일의 내용만 편집하고 저장하는 순수한 설정 에디터 역할
- **상태 표시 전용**: 백엔드의 크롤링 진행 상황, 결과, 통계만 실시간 표시
- **설정 전송 금지**: 백엔드로 설정값을 전송하는 모든 API 호출 완전 제거
- **파일 기반 소통**: 오직 설정 파일 저장을 통해서만 백엔드와 간접 소통

### 1.2. 설


BuildLevenshteinDFA(text));
}
}  // namespace

UNIT_TEST(ErrorsMade_Smoke)
{
  {
    QueryParams::Token const searchToken = strings::MakeUniString("hairdressers");

    auto nameToken = strings::MakeUniString("h");
    TEST(!GetErrorsMade(searchToken, nameToken).IsValid(), ());
    TEST(!GetPrefixErrorsMade(searchToken, nameToken).IsValid(), ());

    nameToken = strings::MakeUniString("hair");
    TEST(!GetErrorsMade(searchToken, nameToken).IsValid(), ());
    TEST(!GetPrefixErrorsMade(searchToken, nameToken).IsValid(), ());
  }

  {
    auto nameToken = strings::MakeUniString("hair");

    QueryParams::Token searchToken = strings::MakeUniString("hair");
    TEST_EQUAL(GetErrorsMade(searchToken, nameToken).m_errorsMade, 0, ());
    TEST_EQUAL(GetPrefixErrorsMade(searchToken, nameToken).m_errorsMade, 0, ());

    searchToken = strings::MakeUniString("gair");
    TEST_EQUAL(GetErrorsMade(searchToken, nameToken).m_errorsMade, 1, ());
    TEST_EQUAL(GetPrefixErrorsMade(searchToken, nameToken).m_errorsMade, 1, ());

    searchToken = strings::MakeUniString("gai");
    TEST(!GetErrorsMade(searchToken, nameToken).IsValid(), ());
    TEST_EQUAL(GetPrefixErrorsMade(searchToken, nameToken).m_errorsMade, 1, ());

    searchToken = strings::MakeUniString("hairrr");
    TEST(!GetErrorsMade(searchToken, nameToken).IsValid(), ());
    TEST(!GetPrefixErrorsMade(searchToken, nameToken).IsValid(), ());
  }

  {
    auto nameToken = strings::MakeUniString("hairdresser");

    QueryParams::Token searchToken = strings::MakeUniString("hair");
    TEST(!GetErrorsMade(searchToken, nameToken).IsValid(), ());
    TEST_EQUAL(GetPrefixErrorsMade(searchToken, nameToken).m_errorsMade, 0, ());

    searchToken = strings::MakeUniString("gair");
    TEST_EQUAL(GetPrefixErrorsMade(searchToken, nameToken).m_errorsMade, 1, ());

    searchToken = strings::MakeUniString("gairdrese");
    TEST(!GetErrorsMade(searchToken, nameToken).IsValid(), ());
    TEST_EQUAL(GetPrefixErrorsMade(searchToken, nameToken).m_errorsMade, 2, ());
  }
}

UNIT_TEST(NameScore_Prefix)
{
  TEST_EQUAL(GetScore("H Nicks", "hairdressers").m_nameScore, NameScore::ZERO, ());
  TEST_EQUAL(GetScore("Hair E14", "hairdressers").m_nameScore, NameScore::ZERO, ());
}

UNIT_TEST(NameScore_SubstringVsErrors)
{
  string const query = "Simon";

  RankingInfo info;
  info.m_type = Model::TYPE_SUBPOI;
  info.m_tokenRanges[Model::TYPE_SUBPOI] = {0, 1};
  info.m_numTokens = 1;
  info.m_allTokensUsed = true;
  info.m_exactMatch = false;

  {
    RankingInfo poi1 = info;
    AssignRankingInfo(GetScore("Symon Budny and Vasil Tsiapinski", query), poi1, query.size());
    TEST_EQUAL(poi1.m_nameScore, NameScore::FULL_PREFIX, ());
    TEST_EQUAL(poi1.m_errorsMade, ErrorsMade(1), ());

    RankingInfo poi2 = i


 Elemente) => {
            element.accept(visitor)
        })
    }
}

class Client {
    public static main(): void {
        const list: ObjectStructure = new ObjectStructure()
        const shangren1 = new ConcreteElementA('商人1', 30)
        const shangren2 = new ConcreteElementA('商人2', 50)
        const shangren3 = new ConcreteElementA('商人3', 60)
        const diaosi1 = new ConcreteElementB('屌丝1', 60)
        const diaosi2 = new ConcreteElementB('屌丝1', 80)
        list.add(shangren1)
        list.add(shangren2)
        list.add(shangren3)
        list.add(diaosi1)
        list.add(diaosi2)
        const visitorA = new ConcreteVisitorA()
        list.accept(visitorA)
        const visitorB = new ConcreteVisitorB()
        list.accept(visitorB)
    }
}
Client.main()

// 商人1使用30万元去买房
// 商人2使用50万元去买房
// 商人3使用60万元去买房
// 屌丝1使用60万元去买房
// 屌丝1使用80万元去买房
// 商人1使用30万元去买车
// 商人2使用50万元去买车
// 商人3使用60万元去买车
// 屌丝1使用60万元去买车
// 屌丝1使用80万元去买车import studentsDb from '../../../data-access/students-db'
import { Application, Request, Response } from 'express';
let students: any = {}

students.index = (req: Request, res: Response, next: any) => {
  studentsDb.listStudents()
    .then((data: any) => {
      res.send(data)
    })
}

students.show = (req: Request, res: Response, next: any) => {
  studentsDb.findStudent('id', req.params.id)
    .then((data: any) => {
      res.send(data)
    })
}

students.create = (req: Request, res: Response, next: any) => {
  studentsDb.addStudent(req.body)
    .then((data: any) => {
      res.send(data)
    })
    .catch(next)
}
export default studentsimport { Injectable } from "@angular/core";
import { Action, Selector, State, StateContext } from "@ngxs/store";
import { TaskService } from "src/app/services/task.service";
import { Task } from "src/app/Task";
import { AddTask, DeleteTask, GetTask, UpdateTask } from "../actions/task.action";
import {tap} from "rxjs/operators";

export class TaskStateModel{
  tasks:Task[];
  tasksLoaded:boolean
}

@State<TaskStateModel>({
  name:'tasks',
  defaults:{
    tasks:[],
    tasksLoaded:false
  }
})

@Injectable()
export class TaskState{

    constructor(private taskService: TaskService){}

    @Selector()
    static getTaskList(state:TaskStateModel){
      return state.tasks
    }

    @Selector()
    static getTaskLoaded(state:TaskStateModel){
      return state.tasksLoaded
    }

    @Action(GetTask)
    getTasks({getState, setState}:StateContext<TaskStateModel>){
      return this.taskService.getTasks().pipe(tap(res=>{
        const state = getState()
        setState({
          ...state,
          tasks:res,
          tasksLoaded:true
        })
      }))
    }

    @Action(AddTask)
    addTask({getState, patchState}:StateContext<TaskStateModel>, {payload}:AddTask){
      return this.taskSe


 BYTE PTR [rax]
        test    al, al
        jne     .L10
.L9:
        mov     rax, QWORD PTR [rbp-8]
        movzx   eax, BYTE PTR [rax]
        test    al, al
        je      .L11
        mov     eax, 1
        jmp     .L8
.L11:
        mov     rax, QWORD PTR [rbp-16]
        movzx   eax, BYTE PTR [rax]
        test    al, al
        je      .L12
        mov     eax, -1
        jmp     .L8
.L12:
        mov     eax, 0
.L8:
        pop     rbp
        ret
.LC0:
        .string "%s"
.LC1:
        .string "%d\n"
main:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 256
        lea     rax, [rbp-128]
        mov     rsi, rax
        mov     edi, OFFSET FLAT:.LC0
        mov     eax, 0
        call    scanf
        lea     rax, [rbp-256]
        mov     rsi, rax
        mov     edi, OFFSET FLAT:.LC0
        mov     eax, 0
        call    scanf
        lea     rax, [rbp-128]
        mov     rdi, rax
        call    my_strlen_train
        mov     esi, eax
        mov     edi, OFFSET FLAT:.LC1
        mov     eax, 0
        call    printf
        lea     rdx, [rbp-256]
        lea     rax, [rbp-128]
        mov     rsi, rdx
        mov     rdi, rax
        call    my_strcmp_train
        mov     esi, eax
        mov     edi, OFFSET FLAT:.LC1
        mov     eax, 0
        call    printf
        mov     eax, 0
        leave
        ret


aultValues = PromptInfo();

  final AndroidPromptInfo androidPromptInfo;
  final IosPromptInfo iosPromptInfo;
  final IosPromptInfo macOsPromptInfo;
}

/// Main plugin class to interact with. Is always a singleton right now,
/// factory constructor will always return the same instance.
///
/// * call [canAuthenticate] to check support on the platform/device.
/// * call [getStorage] to initialize a storage.
abstract class BiometricStorage extends PlatformInterface {
  // Returns singleton instance.
  factory BiometricStorage() => _instance;

  BiometricStorage.create() : super(token: _token);

  static BiometricStorage _instance = MethodChannelBiometricStorage();

  /// Platform-specific plugins should set this with their own platform-specific
  /// class that extends [UrlLauncherPlatform] when they register themselves.
  static set instance(BiometricStorage instance) {
    PlatformInterface.verifyToken(instance, _token);
    _instance = instance;
  }

  static const Object _token = Object();

  /// Returns whether this device supports biometric/secure storage or
  /// the reason [CanAuthenticateResponse] why it is not supported.
  Future<CanAuthenticateResponse> canAuthenticate();

  /// Returns true when there is an AppArmor error when trying to read a value.
  ///
  /// When used inside a snap, there might be app armor limitations
  /// which lead to an error like:
  /// org.freedesktop.DBus.Error.AccessDenied: An AppArmor policy prevents
  /// this sender from sending this message to this recipient;
  /// type="method_call", sender=":1.140" (uid=1000 pid=94358
  /// comm="/snap/biometric-storage-example/x1/biometric_stora"
  /// label="snap.biometric-storage-example.biometric (enforce)")
  /// interface="org.freedesktop.Secret.Service" member="OpenSession"
  /// error name="(unset)" requested_reply="0" destination=":1.30"
  /// (uid=1000 pid=1153 comm="/usr/bin/gnome-keyring-daemon
  /// --daemonize --login " label="unconfined")
  Future<bool> linuxCheckAppArmorError();

  /// Retrieves the given biometric storage file.
  /// Each store is completely separated, and has it's own encryption and
  /// biometric lock.
  /// if [forceInit] is true, will throw an exception if the store was already
  /// created in this runtime.
  Future<BiometricStorageFile> getStorage(
    String name, {
    StorageFileInitOptions? options,
    bool forceInit = false,
    PromptInfo promptInfo = PromptInfo.defaultValues,
  });

  @protected
  Future<String?> read(
    String name,
    PromptInfo promptInfo,
  );

  @protected
  Future<bool?> delete(
    String name,
    PromptInfo promptInfo,
  );

  @protected
  Future<void> write(
    String name,
    String content,
    PromptInfo promptInfo,
  );
}

class MethodChannelBiometricStorage extends BiometricStorage {
  MethodChannelBiometricStorage() : super.create();

  static const MethodChannel _channel = MethodChannel('biometric_storage');

  @override
  Future<CanAuthenticateResponse> canAuthenticate() async {
    if (kIsWeb) {
      return CanAuthenticateResponse.unsupported;
    }
    if (Platform.isAndroid ||
        Platform.isIOS ||
        Platform.isMacOS ||
        Platform.isLinux) {
      final response = await _channel.invokeMethod<String>('canAuthenticate');
      final ret = _canAuthenticateMapping[response];
      if (ret == null) {
        throw StateError('Invalid response from native platform. {$response}');
      }
      return ret;
    }
    return CanAuthenticateResponse.unsupported;
  }

  /// Returns true when there is an AppArmor error when trying to read a value.
  ///
  /// When used inside a snap, there might be app armor limitations
  /// which lead to an error like:
  /// org.freedesktop.DBus.Error.AccessDenied:


from functools import partial

from dask.callbacks import Callback

from .auto import tqdm as tqdm_auto

__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['TqdmCallback']

class TqdmCallback(Callback):
    """Dask callback for task progress."""
    def __init__(self, start=None, pretask=None, tqdm_class=tqdm_auto,
                 **tqdm_kwargs):
        """
        Parameters
        ----------
        tqdm_class  : optional
            `tqdm` class to use for bars [default: `tqdm.auto.tqdm`].
        tqdm_kwargs  : optional
            Any other arguments used for all bars.
        """
        super().__init__(start=start, pretask=pretask)
        if tqdm_kwargs:
            tqdm_class = partial(tqdm_class, **tqdm_kwargs)
        self.tqdm_class = tqdm_class

    def _start_state(self, _, state):
        self.pbar = self.tqdm_class(total=sum(
            len(state[k]) for k in ['ready', 'waiting', 'running', 'finished']))

    def _posttask(self, *_, **__):
        self.pbar.update()

    def _finish(self, *_, **__):
        self.pbar.close()

    def display(self):
        """Displays in the current cell in Notebooks."""
        container = getattr(self.bar, 'container', None)
        if container is None:
            return
        from .notebook import display
        display(container)


#ifndef _BOMB_DATA
#define _BOMB_DATA

// Added 2003-11-10 by MLR

class SimlibFileClass;

#define BOMB_ID_VER 0

class BombInputData
{
public:
    int Version;
};

class BombAuxData
{
public:
    BombAuxData()
    {
        psFeatureImpact = 0;
        psBombImpact = 0;
    }

    ~BombAuxData()
    {
        if (psFeatureImpact) free(psFeatureImpact);

        if (psBombImpact) free(psBombImpact);
    }
    // which strength algorithm to use 0 for old, 1 for new.
    int   cbuStrengthModel;

    // new strength model parameters
    float cbuLethalHeight,
          cbuIneffectiveHeight,
          cbuDamageDiameterBAMult,
          cbuMaxDamageDiameter, cbuBlastMultiplier;

    // LAU/Gun pod launch angle
    float lauElevation,
          lauAzimuth;
    int   lauSalvoSize;
    int   lauRounds;
    int   lauWeaponId;
    int   lauRippleTime;

    // Cobra - JDAM
    float JDAMLift;
    float JSOWmaxRange;
    // particle effects
    char *psFeatureImpact;
    char *psBombImpact;

    // unused as of yet
    int   sndFlightSFX;
};

class BombDataSetClass
{
public:
    char name[80];
    int Version;
    BombInputData *inputData;
    BombAuxData *auxData;
};

extern BombDataSetClass* BombDataset;
extern int numBombDatasets;

void ReadAllBombData(void);
void BombOpenFiles(char *bombname);
BombAuxData *BombAuxAeroRead(SimlibFileClass* inputFile);

/******************************************************/

#endif


local rx_body = zb_rx.body.zcl_body.body_bytes
  local dp_id = string.byte(rx_body:sub(3,3))
  local len = string.unpack(">I2", rx_body:sub(5,6))
  local value = string.unpack(">I"..len, rx_body:sub(7))
  if dp_id == 1 then -- 0x01: Control
    if value == 0 then 		-- 0 : open
      device:emit_event(capabilities.windowShade.windowShade.opening())
    elseif value == 2 then	-- 2 : close
      device:emit_event(capabilities.windowShade.windowShade.closing())
    end
  elseif dp_id == 2 then -- 0x02: Set Curtain Position in Percentage
    emit_event_movement_status(device, value)
  elseif dp_id == 3 then -- 0x03: Current Curtain Position
    emit_event_final_position(device, value)
  elseif dp_id == 5 then -- 0x05: Reset Direction
    device:set_field("DirectionChange",1)
  elseif dp_id == 7 then -- 0x07: Work state
    if value == 0 then		-- 0 : opening
      device:emit_event(capabilities.windowShade.windowShade.opening())
    elseif value == 1 then	-- 1 : Closing
      device:emit_event(capabilities.windowShade.windowShade.closing())
    end
    if device:get_field("DirectionChange") == 1 then
      device:set_field("DirectionChange",0)
      emit_event_final_position(device, getLatestLevel(device))
    end
  end
end

-------------------- Lifecycle Handlers -------------------

local function device_added(driver, device)
  device:emit_event(capabilities.windowShade.supportedWindowShadeCommands({"open", "close", "pause"}, {visibility = {displayed = false}}))
  if getLatestLevel(device) == 0 then
    emit_event_final_position(device, getLatestLevel(device))
    device.thread:call_with_delay(3, function(d)
      SetShadeLevelHandler(driver, device, {args = { shadeLevel = 50 }})
    end)
  end
end

local function device_info_changed(driver, device, event, args)
  if args.old_st_store.preferences.reverse ~= device.preferences.rever