e issued when data was changed', () async {
      when(executor.runDelete(any, any)).thenAnswer((_) => Future.value(3));

      await db.delete(db.users).go();

      verify(streamQueries.handleTableUpdates(
          {const TableUpdate('users', kind: UpdateKind.delete)}));
    });

    test('are not issued when no data was changed', () async {
      when(executor.runDelete(any, any)).thenAnswer((_) => Future.value(0));

      await db.delete(db.users).go();

      verifyNever(streamQueries.handleTableUpdates(any));
    });
  });

  group('delete on table instances', () {
    test('delete()', () async {
      await db.users.delete().go();

      verify(executor.runDelete('DELETE FROM "users";', const []));
    });

    test('deleteOne()', () async {
      await db.users.deleteOne(const UsersCompanion(id: Value(RowId(3))));

      verify(
          executor.runDelete('DELETE FROM "users" WHERE "id" = ?;', const [3]));
    });

    test('deleteWhere', () async {
      await db.users.deleteWhere((tbl) => tbl.id.isSmallerThanValue(3));

      verify(
          executor.runDelete('DELETE FROM "users" WHERE "id" < ?;', const [3]));
    });

    test('deleteAll', () async {
      await db.users.deleteAll();

      verify(executor.runDelete('DELETE FROM "users";', const []));
    });
  });
}
@TestOn('vm')
library;

import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:test/test.dart';
import 'package:vm_service/vm_service.dart';
import 'package:path/path.dart' as p;
import 'package:vm_service/vm_service_io.dart';

void main() {
  late Process child;
  late VmService vm;
  late String isolateId;

  setUpAll(() async {
    final socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
    final port = socket.port;
    await socket.close();

    String sdk = p.dirname(p.dirname(Platform.resolvedExecutable));
    child = await Process.start(p.join(sdk, 'bin', 'dart'), [
      'run',
      '--enable-vm-service=$port',
      '--disable-service-auth-codes',
      '--enable-asserts',
      'test/integration_tests/devtools/app.dart',
    ]);

    final vmServiceListening = Completer<void>();
    final databaseOpened = Completer<void>();

    child.stdout
        .map(utf8.decode)
        .transform(const LineSplitter())
        .listen((line) {
      if (line.startsWith('The Dart VM service is listening')) {
        vmServiceListening.complete();
      } else if (line == 'database created') {
        databaseOpened.complete();
      } else if (!line.startsWith('The Dart DevTools')) {
        print('[child]: $line');
      }
    });

    await vmServiceListening.future;

    vm = await vmServiceConnectUri('ws://localhost:$port/ws');
    await databaseOpened.future;

    final state = await vm.getVM();
    isolateId = state.isolates!.single.id!;
  });

  tearDownAll(() async {
    child.kill();
  });

  test('can list create statements', () async {
    final response = await vm.callServiceExtension(
      'ext.drift.database',
      args: {'action': 'collect-expected-schema', 'db': '0'},
      isolateId: isolateId,
    );

    expect(
        response.json!['r'],
        containsAll([
          'CREATE TABLE IF NOT EXISTS "categories" ("id" INTEGER NOT NULL PRIMARY KEY AUTOIN


返回空的 Left
   * @param f
   */
  filter(f) {
    return Either.fromNullable(f(this.value) ? this.value : null);
  }
  toString() {
    return `Either.Right(${this.value})`;
  }
  get isRight() {
    return true;
  }
}

class Left extends Either<any> {
  /**
   * noop
   * 通过映射函数对 Right 结构中的值进行变换，对 Left 不进行任何操作
   * @param _ 占位符
   */
  map(_) {
    return this;
  }
  get value() {
    throw new TypeError("Can not extract the value of a Left");
  }
  /**
   * 提取 Right 的值，如果不存在，则返回给定的默认值
   * @param other
   */
  getOrElse(other) {
    return other;
  }
  /**
   * 将给定函数应用于 Left 值，不对 Right 进行任何操作
   * @param f
   */
  orElse(f) {
    return f(this._value);
  }
  /**
   * 将给定函数应用于 Right 值并返回其结果，不对 Left 进行任何操作。
   */
  chain(f) {
    return this;
  }
  /**
   * 如果为 Left ，通过给定值抛出异常，否则忽略异常并返回 Right 中的合法值
   * @param a
   */
  getOrElseThrow(a) {
    throw new Error(a);
  }
  /**
   * 如果为 Right 且给定的断言为真，返回包含值的 Right 结构; 否则返回空的 Left
   * @param f
   */
  filter(f) {
    return this;
  }
  get isLeft() {
    return true;
  }
  toString() {
    return `Either.left(${this.value})`;
  }
}
// enum is somewhat similar to an object, we going to list out couple of properties inside here, and we are going to then say, if somethings is of type subjects then its means that its one of the different properties listed out inside.
// so inside the Subjects we gonna list all the possible subjects we expect to have.
export enum Subjects {
    TicketCreated = 'ticket:created',
    OrderUpdated = 'order:updated'
}export type OrbitalBody = string;

export type OrbitMap = { [body: string]: OrbitalBody };

export function populateOrbits(orbits: string[]): OrbitMap {
  const map: OrbitMap = {};
  for (let orbit of orbits) {
    const [body1, body2] = orbit.split(')');
    map[body2] = body1;
  }
  return map;
}

/**
 * Counts the numnber of orbital transfers needed
 * to take YOU to SAN
 *
 * @param map
 */
export function countTransfers(map: OrbitMap): number {
  let youToCom: string[] = [];
  let current = 'YOU';
  while (current != 'COM') {
    current = map[current];
    youToCom.push(current);
  }
  youToCom.reverse();

  let sanToCom: string[] = [];
  current = 'SAN';
  while (current != 'COM') {
    current = map[current];
    sanToCom.push(current);
  }
  sanToCom.reverse();

  let match = 0;
  let common = 'COM';
  while (sanToCom[match] === youToCom[match]) {
    common = sanToCom[match];
    match++;
  }

  let transfers = 0;
  sanToCom.reverse();
  let currentOrbit = 0;
  while (sanToCom[currentOrbit] != common) {
    currentOrbit++;
    transfers++;
  }

  youToCom.reverse();
  currentOrbit = 0;
  while (youToCom[currentOrbit] != common) {
    currentOrbit++;
    transfers++;
  }

  return transfers;
}
import {HttpErrors} from '@loopback/rest';

export class BaseController {


// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#include "textflag.h"

//
// System call support for ARM64, FreeBSD
//

#define SYS_syscall	0

// func Syscall(trap uintptr, a1, a2, a3 uintptr) (r1, r2, err uintptr)
TEXT ·Syscall(SB),NOSPLIT,$0-56
	BL	runtime·entersyscall(SB)
	MOVD	trap+0(FP), R8	// syscall entry
	MOVD	a1+8(FP), R0
	MOVD	a2+16(FP), R1
	MOVD	a3+24(FP), R2
	SVC	$SYS_syscall
	BCC	ok
	MOVD	$-1, R1
	MOVD	R1, r1+32(FP)
	MOVD	ZR, r2+40(FP)
	MOVD	R0, err+48(FP)
	BL	runtime·exitsyscall(SB)
	RET
ok:
	MOVD	R0, r1+32(FP)
	MOVD	R1, r2+40(FP)
	MOVD	ZR, err+48(FP)
	BL	runtime·exitsyscall(SB)
	RET

// func RawSyscall(trap uintptr, a1, a2, a3 uintptr) (r1, r2, err uintptr)
TEXT ·RawSyscall(SB),NOSPLIT,$0-56
	MOVD	trap+0(FP), R8	// syscall entry
	MOVD	a1+8(FP), R0
	MOVD	a2+16(FP), R1
	MOVD	a3+24(FP), R2
	SVC	$SYS_syscall
	BCC	ok
	MOVD	$-1, R1
	MOVD	R1, r1+32(FP)
	MOVD	ZR, r2+40(FP)
	MOVD	R0, err+48(FP)
	RET
ok:
	MOVD	R0, r1+32(FP)
	MOVD	R1, r2+40(FP)
	MOVD	ZR, err+48(FP)
	RET

// func Syscall6(trap uintptr, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr)
TEXT ·Syscall6(SB),NOSPLIT,$0-80
	BL	runtime·entersyscall(SB)
	MOVD	trap+0(FP), R8	// syscall entry
	MOVD	a1+8(FP), R0
	MOVD	a2+16(FP), R1
	MOVD	a3+24(FP), R2
	MOVD	a4+32(FP), R3


dual_game_commands(self):
        """Test individual game command generation."""
        games = ["tetris", "sokoban", "candy_crush"]
        model_name = "gemini-flash-2.0"

        for game in games:
            # With harness
            cmd_harness = (
                f"python3 lmgame-bench/run.py --model_name {model_name} "
                f"--game_names {game} --harness_mode true"
            )

            assert f"--game_names {game}" in cmd_harness
            assert "--harness_mode true" in cmd_harness
            assert f"--model_name {model_name}" in cmd_harness

            # Without harness
            cmd_no_harness = (
                f"python3 lmgame-bench/run.py --model_name {model_name} "
                f"--game_names {game} --harness_mode false"
            )

            assert f"--game_names {game}" in cmd_no_harness
            assert "--harness_mode false" in cmd_no_harness
            assert f"--model_name {model_name}" in cmd_no_harness

if __name__ == "__main__":
    pytest.main([__file__, "-v"])


Cloud);
		if (octree->build(progressCb) < 1)
		{
			delete octree;
			return nullptr;
		}
	}

	ReferenceCloud* cloud = new ReferenceCloud(inputCloud);

	unsigned nCells = octree->getCellNumber(octreeLevel);
	if (!cloud->reserve(nCells))
	{
		if (!inputOctree)
			delete octree;
		delete cloud;
		return nullptr;
	}

	//structure contenant les parametres additionnels
	void* additionalParameters[2] = {	reinterpret_cast<void*>(cloud),
										reinterpret_cast<void*>(&subsamplingMethod) };

	if (octree->executeFunctionForAllCellsAtLevel(	octreeLevel,
													&subsampleCellAtLevel,
													additionalParameters,
													false, //the process is so simple that MT is slower!
													progressCb,
													"Cloud Subsampling") == 0)
	{
		//something went wrong
		delete cloud;
		cloud = nullptr;
	}

	if (!inputOctree)
		delete octree;

	return cloud;
}

ReferenceCloud* CloudSamplingTools::subsampleCloudRandomly(	GenericIndexedCloudPersist* inputCloud,
															unsigned newNumberOfPoints,
															GenericProgressCallback* progressCb/*=nullptr*/)
{
	assert(inputCloud);

	unsigned theCloudSize = inputCloud->size();

	//we put all input points in a ReferenceCloud
	ReferenceCloud* newCloud = new ReferenceCloud(inputCloud);
	if (!newCloud->addPointIndex(0, theCloudSize))
	{
		delete newCloud;
		return nullptr;
	}

	//we have less points than requested?!
	if (theCloudSize <= newNumberOfPoints)
	{
		return newCloud;
	}

	unsigned pointsToRemove = theCloudSize - newNumberOfPoints;
	std::random_device rd;   // non-deterministic generator
	std::mt19937 gen(rd());  // to seed mersenne twister.

	NormalizedProgress normProgress(progressCb, pointsToRemove);
	if (progressCb)
	{
		if (progressCb->textCanBeEdited())
		{
			progressCb->setInfo("Random subsampling");
		}
		progressCb->update(0);
		progressCb->start();
	}

	//we randomly remove "inputCloud.size() - newNumberOfPoints" points (much simpler)
	unsigned lastPointIndex = theCloudSize - 1;
	for (unsigned i = 0; i < pointsToRemove; ++i)
	{
		std::uniform_int_distribution<unsigned> dist(0, lastPointIndex);
		unsigned index = dist(gen);
		newCloud->swap(index, lastPointIndex);
		--lastPointIndex;

		if (progressCb && !normProgress.oneStep())
		{
			//cancel process
			delete newCloud;
			return nullptr;
		}
	}

	newCloud->resize(newNumberOfPoints); //always smaller, so it should be ok!

	return newCloud;
}

ReferenceCloud* CloudSamplingTools::resampleCloudSpatially(GenericIndexedCloudPersist* inputCloud,
														   PointCoordinateType minDistance,
														   const SFModulationParams& modParams,
														   DgmOctree* inputOctree/*=nullptr*/,
														   GenericProgressCallback* progressCb/*=nullptr*/)
{
	assert(inputCloud);
	unsigned cloudSize = inputCloud->size();

	DgmOctree* octree = inputOctree;
	if (!octree)
	{
		octree = new DgmOctree(inputCloud);
		if (octree->build() < static_cast<int>(cloudSize))
		{
			delete octree;
			return nullptr;
		}
	}
	assert(octree && octree->associatedCloud() == inputCloud);

	//output cloud
	ReferenceCloud* sampledCloud = new ReferenceCloud(inputCloud);
	const unsigned c_reserveSt


At(1) > 1) {\r\n      // max n is 6 (gives 0.7 - 1.3)\r\n      while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {\r\n        x = x.times(y);\r\n        c = digitsToString(x.d);\r\n        c0 = c.charAt(0);\r\n        n++;\r\n      }\r\n\r\n      e = getBase10Exponent(x);\r\n\r\n      if (c0 > 1) {\r\n        x = new Ctor('0.' + c);\r\n        e++;\r\n      } else {\r\n        x = new Ctor(c0 + '.' + c.slice(1));\r\n      }\r\n    } else {\r\n\r\n      // The argument reduction method above may result in overflow if the argument y is a massive\r\n      // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this\r\n      // function using ln(x*10^e) = ln(x) + e*ln(10).\r\n      t = getLn10(Ctor, wpr + 2, pr).times(e + '');\r\n      x = ln(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);\r\n\r\n      Ctor.precision = pr;\r\n      return sd == null ? (external = true, round(x, pr)) : x;\r\n    }\r\n\r\n    // x is reduced to a value near 1.\r\n\r\n    // Taylor series.\r\n    // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)\r\n    // where x = (y - 1)/(y + 1)    (|x| < 1)\r\n    sum = numerator = x = divide(x.minus(ONE), x.plus(ONE), wpr);\r\n    x2 = round(x.times(x), wpr);\r\n    denominator = 3;\r\n\r\n    for (;;) {\r\n      numerator = round(numerator.times(x2), wpr);\r\n      t = sum.plus(divide(numerator, new Ctor(denominator), wpr));\r\n\r\n      if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {\r\n        sum = sum.times(2);\r\n\r\n        // Reverse the argument reduction.\r\n        if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));\r\n        sum = divide(sum, new Ctor(n), wpr);\r\n\r\n        Ctor.precision = pr;\r\n        return sd == null ? (external = true, round(sum, pr)) : sum;\r\n      }\r\n\r\n      sum = t;\r\n      denominator += 2;\r\n    }\r\n  }\r\n\r\n\r\n  /*\r\n   * Parse the value of a new Decimal `x` from string `str`.\r\n   */\r\n  function parseDecimal(x, str) {\r\n    var e, i, len;\r\n\r\n    // Decimal point?\r\n    if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n    // Exponential form?\r\n    if ((i = str.search(/e/i)) > 0) {\r\n\r\n      // Determine exponent.\r\n      if (e < 0) e = i;\r\n      e += +str.slice(i + 1);\r\n      str = str.substring(0, i


-item toc-entry">10.4.1. 개별종목 주가 크롤링

10.4.2. 전 종목 주가 크롤링

10.5. 재무제표 크롤링

10.5.1. 재무제표 다운로드

10.5.2. 전종목 재무제표 크롤링

10.6. 가치지표 계산

10.6.1. 전 종목 가치지표 계산

10. 국내 주식 데이터 수집#

이번 장에서는 극내 주식 데이터 중 주식티커와 섹터별 구성종목 및 퀀트 투자를 위한 핵심 데이터인 수정주가, 재무제표, 가치지표를 크롤링하는 방법을 알아보겠다.

10.1. 최근 영업일 기준 데이터 받기#

POST 방식으로 금융 데이터를 제공하는 일부 사이트에서는 쿼리 항목에 특정 날짜를 입력하면(예:20221230) 해당일의 데이터를 다운로드 할 수 있으며, 최근 영업일 날짜를 입력하면 가장 최근의 데이터를 받을 수 있다. 따라서 최근 영업일에 해당하는 항목을 매번 수기로 입력하기 보다는 자동으로 반영되게 할 필요가 있다.

네이버 금융의 [국내증시 → 증시자금동향]에는 이전 2영업일에 해당하는 날짜가 있으며, 자동으로 날짜가 업데이트된다. 따라서 해당 부분을 �


artCObject based), see doc to use other codecs
    final arr = raw as List<dynamic>;
    if (arr.length != 3)
      throw Exception('unexpected arr length: expect 3 but see ${arr.length}');
    return ManifestPermission(
      task: dco_decode_opt_box_autoadd_manifest_permission_task(arr[0]),
      network: dco_decode_opt_box_autoadd_manifest_permission_network(arr[1]),
      storage: dco_decode_opt_box_autoadd_manifest_permission_storage(arr[2]),
    );
  }

  @protected
  ManifestPermissionNetwork dco_decode_manifest_permission_network(
    dynamic raw,
  ) {
    // Codec=Dco (DartCObject based), see doc to use other codecs
    final arr = raw as List<dynamic>;
    if (arr.length != 1)
      throw Exception('unexpected arr length: expect 1 but see ${arr.length}');
    return ManifestPermissionNetwork(urls: dco_decode_list_String(arr[0]));
  }

  @protected
  ManifestPermissionStorage dco_decode_manifest_permission_storage(
    dynamic raw,
  ) {
    // Codec=Dco (DartCObject based), see doc to use other codecs
    final arr = raw as List<dynamic>;
    if (arr.length != 1)
      throw Exception('unexpected arr length: expect 1 but see ${arr.length}');
    return ManifestPermissionStorage(maxSize: dco_decode_u_32(arr[0]));
  }

  @protected
  ManifestPermissionTask dco_decode_manifest_permission_task(dynamic raw) {
    // Codec=Dco (DartCObject based), see doc to use other codecs
    final arr = raw as List<dynamic>;
    if (arr.length != 4)
      throw Exception('unexpected arr length: expect 4 but see ${arr.length}');
    return ManifestPermissionTask(
      create: dco_decode_bool(arr[0]),
      modify: dco_decode_bool(arr[1]),
      query: dco_decode_bool(arr[2]),
      sync_: dco_decode_bool(arr[3]),
    );
  }

  @protected
  NetworkRequestType dco_decode_network_request_type(dynamic raw) {
    // Codec=Dco (DartCObject based), see doc to use other codecs
    return NetworkRequestType.values[raw as int];
  }

  @protected
  String? dco_decode_opt_String(dynamic raw) {
    // Codec=Dco (DartCObject based), see doc to use other codecs
    return raw == null ? null : dco_decode_String(raw);
  }

  @protected
  UuidValue? dco_decode_opt_Uuid(dynamic raw) {
    // Codec=Dco (DartCObject based), see doc to use other codecs
    return raw == null ? null : dco_decode_Uuid(raw);
  }

  @protected
  DateTime? dco_decode_opt_box_autoadd_Chrono_Utc(dynamic raw) {
    // Codec=Dco (DartCObject based), see doc to use other codecs
    return raw == null ? null : dco_decode_box_autoadd_Chrono_Utc(raw);
  }

  @protected
  EncryptionKey? dco_decode_opt_box_autoadd_encryption_key(dynamic raw) {
    // Codec=Dco (DartCObject based), see doc to use other codecs
    return raw == null ? null : dco_decode_box_autoadd_encryption_key(raw);
  }

  @protected
  FilterSelection? dco_decode_opt_box_autoadd_filter_selection(dynamic raw) {
    // Codec=Dco (DartCObject based), see doc to use other codecs
    return raw == null ? null : dco_decode_box_autoadd_


d) == 0 {
		// When should this happen, something is wrong?
		lastRange = nil
	}
	return exec, chunks, intermediateOutputs, lastRange, counts, ndvs, err
}

func mppExecute(exec mppExec, dagCtx *dagContext, dagReq *tipb.DAGRequest, pagingSize uint64) (chunks []tipb.Chunk, intermediateOutputs []*tipb.IntermediateOutput, err error) {
	err = exec.open()
	defer func() {
		err := exec.stop()
		if err != nil {
			panic(err)
		}
	}()
	if err != nil {
		return
	}

	var intermediateOutputExecutors []mppExec
	if channels := dagReq.GetIntermediateOutputChannels(); len(channels) > 0 {
		intermediateOutputs = make([]*tipb.IntermediateOutput, len(channels))
		intermediateOutputExecutors = make([]mppExec, len(channels))
		allExecs := flattenMppExec(exec, nil)
		for i, ch := range channels {
			intermediateOutputs[i] = &tipb.IntermediateOutput{
				EncodeType: dagReq.EncodeType,
			}
			intermediateOutputExecutors[i] = allExecs[ch.ExecutorIdx]
		}
	}

	var totalRows uint64
	var chk *chunk.Chunk
	fields := exec.getFieldTypes()
	for {
		chk, err = exec.next()
		if err != nil {
			return
		}

		curRowCnt := 0
		if chk != nil && chk.NumRows() > 0 {
			curRowCnt += chk.NumRows()
			chunks, err = encodeChunk(dagCtx.sctx.GetSessionVars().StmtCtx, dagReq.EncodeType, fields, dagReq.OutputOffsets, chk, chunks)
			if err != nil {
				return
			}
		}

		for i, e := range intermediateOutputExecutors {
			intermediateChunks := e.takeIntermediateResults()
			if len(intermediateChunks) == 0 {
				continue
			}
			for _, iChk := range intermediateChunks {
				curRowCnt += iChk.NumRows()
				output := intermediateOutputs[i]
				channel := dagReq.GetIntermediateOutputChannels()[i]
				output.Chunks, err = encodeChunk(
					dagCtx.sctx.GetSessionVars().StmtCtx,
					output.EncodeType,
					e.getIntermediateFieldTypes(),
					channel.OutputOffsets,
					iChk,
					output.Chunks,
				)

				if err != nil {
					return
				}
			}
		}

		if curRowCnt == 0 {
			return
		}
		totalRows += uint64(curRowCnt)
		if dagReq.EncodeType == tipb.EncodeType_TypeChunk {
			if pagingSize > 0 {
				if totalRows > pagingSize {
					return
				}
			}
		}
	}
}

func encodeChunk(
	sc *stmtctx.StatementContext,
	encodeType tipb.EncodeType,
	fields []*types.FieldType,
	outputOffsets []uint32,
	chk *chunk.Chunk,
	chunks []tipb.Chunk,
) ([]tipb.Chunk, error) {
	switch encodeType {
	case tipb.EncodeType_TypeDefault:
		return useDefaultEncoding(chk, sc, fields, outputOffsets, chunks)
	case tipb.EncodeType_TypeChunk:
		return useChunkEncoding(chk, fields, outputOffsets, chunks), nil
	default:
		return nil, fmt.Errorf("unsupported DAG request encode type %s", encodeType)
	}
}

func useDefaultEncoding(chk *chunk.Chunk, sc *stmtctx.StatementContext,
	fields []*types.FieldType, outputOffsets []uint32, chunks []tipb.Chunk) ([]tipb.Chunk, error) {
	var buf []byte
	var dat


Source.sha256(rawSource);
 * BufferedSource bufferedSource = Okio.buffer(hashingSource);
 *
 * ... // Read all of bufferedSource.
 *
 * ByteString hash = hashingSource.hash();
 * ```
 */
actual class HashingSource : ForwardingSource, Source { // Need to explicitly declare source pending fix for https://youtrack.jetbrains.com/issue/KT-20641
  private val messageDigest: MessageDigest?
  private val mac: Mac?

  internal constructor(source: Source, digest: MessageDigest) : super(source) {
    this.messageDigest = digest
    this.mac = null
  }

  internal constructor(source: Source, algorithm: String) : this(source, MessageDigest.getInstance(algorithm))

  internal constructor(source: Source, mac: Mac) : super(source) {
    this.mac = mac
    this.messageDigest = null
  }

  internal constructor(source: Source, key: ByteString, algorithm: String) : this(
    source,
    try {
      Mac.getInstance(algorithm).apply {
        init(SecretKeySpec(key.toByteArray(), algorithm))
      }
    } catch (e: InvalidKeyException) {
      throw IllegalArgumentException(e)
    },
  )

  @Throws(IOException::class)
  actual override fun read(sink: Buffer, byteCount: Long): Long {
    val result = super.read(sink, byteCount)

    if (result != -1L) {
      var start = sink.size - result

      // Find the first segment that has new bytes.
      var offset = sink.size
      var s = sink.head!!
      while (offset > start) {
        s = s.prev!!
        offset -= (s.limit - s.pos).toLong()
      }

      // Hash that segment and all the rest until the end.
      while (offset < sink.size) {
        val pos = (s.pos + start - offset).toInt()
        if (messageDigest != null) {
          messageDigest.update(s.data, pos, s.limit - pos)
        } else {
          mac!!.update(s.data, pos, s.limit - pos)
        }
        offset += s.limit - s.pos
        start = offset
        s = s.next!!
      }
    }

    return result
  }

  /**
   * Returns the hash of the bytes supplied thus far and resets the internal state of this source.
   *
   * **Warning:** This method is not idempotent. Each time this method is called its
   * internal state is cleared. This starts a new hash with zero bytes supplied.
   */
  @get:JvmName("hash")
  actual val hash: ByteString
    get() {
      val result = if (messageDigest != null) messageDigest.digest() else mac!!.doFinal()
      return ByteString(result)
    }

  @JvmName("-deprecated_hash")
  @Deprecated(
    message = "moved to val",
    replaceWith = ReplaceWith(expression = "hash"),
    level = DeprecationLevel.ERROR,
  )
  fun hash() = hash

  actual companion object {
    /**
     * Returns a source that uses the obsolete MD5 hash algorithm to produce 128-bit hashes.
     *
     * MD5 has been vulnerable to collisions since 2004. It should not be used in new code.
     */
    @JvmStatic
    actual fun md5(source: Source) = HashingSource(source, "MD5")

    /**
     * Returns a source that uses the obsolete SHA-1 hash algorithm to produce 160-bit hashes.
     *
     * SHA-1 has been vulnerable to collisions since 2017. It should not be used in new code.
     */
    @JvmStatic
    actual fun sha1(source: Source) = HashingSource(source, "SHA-1")

    /** Returns a source that uses the SHA-256 hash algorithm to produce 256-bit hashes. */
    @JvmStatic
    actual fun sha256(source: Source) = HashingSource(source, "SHA-256")

    /** Returns a source that uses the SHA-512 hash algorithm to produce 512


				expect(TypeIdHelper.nativeInheritsFrom("NamedNodeProperty", "BaseProperty")).to.be
					.true;
				expect(TypeIdHelper.nativeInheritsFrom("RelationshipProperty", "BaseProperty")).to
					.be.true;
				expect(TypeIdHelper.nativeInheritsFrom("Reference<NodeProperty>", "Reference")).to
					.be.true;
				expect(TypeIdHelper.nativeInheritsFrom("NodeProperty", "Reference<NodeProperty>"))
					.to.be.false;
			});

			it("should recognize that the Reference<NodeProperty> inherits from BaseProperty", () => {
				const result = TypeIdHelper.nativeInheritsFrom(
					"Reference<NodeProperty>",
					"BaseProperty",
				);

				expect(result).to.be.true;
			});

			it("should throw an error if in_typeid is enum<> ", () => {
				expect(() => {
					TypeIdHelper.nativeInheritsFrom("enum<NodeProperty>", "BaseProperty");
				}).to.throw(MSG.TYPEID_NOT_NATIVE + "enum<NodeProperty>");
			});

			it("should throw an error if base_typeid is enum<> ", () => {
				expect(() => {
					TypeIdHelper.nativeInheritsFrom("NodeProperty", "enum<NodeProperty>");
				}).to.throw(MSG.TYPEID_NOT_NATIVE + "enum<NodeProperty>");
			});

			it("should recognize that the Enum inherits from Int32", () => {
				const result = TypeIdHelper.nativeInheritsFrom("Enum", "Int32");

				expect(result).to.be.true;
			});

			it("should recognize that the NodeProperty inherits from ContainerProperty", () => {
				const result = TypeIdHelper.nativeInheritsFrom("NodeProperty", "ContainerProperty");

				expect(result).to.be.true;
			});

			it("should recognize that the NamedProperty inherits from ContainerProperty", () => {
				const result = TypeIdHelper.nativeInheritsFrom(
					"NamedProperty",
					"ContainerProperty",
				);

				expect(result).to.be.true;
			});

			it("should recognize that the String inherits from ContainerProperty", () => {
				const result = TypeIdHelper.nativeInheritsFrom("String", "ContainerProperty");

				expect(result).to.be.true;
			});

			it("should recognize that the NamedNodeProperty inherits from NamedProperty", () => {
				const result = TypeIdHelper.nativeInheritsFrom(
					"NamedNodeProperty",
					"NamedProperty",
				);

				expect(result).to.be.true;
			});

			it("should recognize that the NamedNodeProperty inherits from NodeProperty", () => {
				const result = TypeIdHelper.nativeInheritsFrom("NamedNodeProperty", "NodeProperty");

				expect(result).to.be.true;
			});

			it("should recognize that the RelationshipProperty inherits from NodeProperty and NamedProperty", () => {
				expect(TypeIdHelper.nativeInheritsFrom("RelationshipProperty", "NodeProperty")).to
					.be.true;
				expect(TypeIdHelper.nativeInheritsFrom("RelationshipProperty", "NamedProperty")).to
					.be.true;
			});
		});
	});
})();
/**
 * EraseInside - fill all pixels labeled with the activeSegmentIndex,
 * outside the bouding box defined by the `topLeft` and `topRight`.
 * @param  {} evt The Cornerstone event.
 * @param  {} operationData An object containing the `pixelData` to
 *                          modify, the `segmentIndex` and the `points` array.
 * @param {number[]} topLeft The top left of the bounding box.
 * @param {number[]} bottomRight The bottom right of the bounding box.
 * @returns {null}
 */
export default function fillOutsideBoundingBox(evt: any, operationData: any, topL


hDragging();
    }
    Super::mouseReleaseEvent(e);
}

void DockFloatingTitleBar::mouseMoveEvent(QMouseEvent *e)
{
    Q_D(DockFloatingTitleBar);
    if (!(e->buttons() & Qt::LeftButton) || Qx::DockDraggingInactive == d->m_dragState) {
        d->m_dragState = Qx::DockDraggingInactive;
        Super::mouseMoveEvent(e);
        return;
    }

    // move floating window
    if (Qx::DockDraggingFloatingWidget == d->m_dragState) {
        if (d->m_floatingWidget->isMaximized()) {
            d->m_floatingWidget->showNormal(true);
        }
        d->m_floatingWidget->moveFloating();
        Super::mouseMoveEvent(e);
        return;
    }
    Super::mouseMoveEvent(e);
}

void DockFloatingTitleBar::mouseDoubleClickEvent(QMouseEvent *e)
{
    if (e->buttons() & Qt::LeftButton) {
        Q_EMIT maximizeRequested();
        e->accept();
    } else {
        QWidget::mouseDoubleClickEvent(e);
    }
}

QX_DOCK_END_NAMESPACE
#include "tst_global.h"

#include "qxdock/dockpanel.h"
#include "qxdock/dockwidget.h"
#include "qxdock/dockwindow.h"
#include "qxdock/docksplitter.h"

QX_DOCK_USE_NAMESPACE

class tst_DockPanel : public QObject
{
    Q_OBJECT
private slots:
    void dockWidget();
    void splitter();
    void centralWidget();
};

void tst_DockPanel::dockWidget()
{
    DockWindow wd;

    DockWidget *dw1 = new DockWidget("dw1");
    DockWidget *dw2 = new DockWidget("dw2");
    DockWidget *dw3 = new DockWidget("dw3");
    DockWidget *dw4 = new DockWidget("dw4");
    DockWidget *dw5 = new DockWidget("dw5");
    DockWidget *dw6 = new DockWidget("dw6");
    DockWidget *dw7 = new DockWidget("dw7");
    DockWidget *dw8 = new DockWidget("dw8");

    DockPanel *p1 = wd.addDockWidget(Qx::LeftDockWidgetArea, dw1);
    DockPanel *p2 = wd.addDockWidget(Qx::CenterDockWidgetArea, dw2);
    DockPanel *p3 = wd.addDockWidget(Qx::CenterDockWidgetArea, dw3, p2);
    DockPanel *p4 = wd.addDockWidget(Qx::RightDockWidgetArea, dw4, p3);
    DockPanel *p5 = wd.addDockWidget(Qx::TopDockWidgetArea, dw5);
    DockPanel *p6 = wd.addDockWidget(Qx::BottomDockWidgetArea, dw6);
    DockPanel *p7 = wd.addDockWidget(Qx::LeftDockWidgetArea, dw7);
    DockPanel *p8 = wd.addDockWidget(Qx::RightDockWidgetArea, dw8);

    // container
    QCOMPARE(p1->dockWindow(), &wd);
    QCOMPARE(p1->dockContainer(), &wd);
    QCOMPARE(p2, p3);
    QCOMPARE(p2->dockContainer(), p4->dockContainer());

    // widget
    QCOMPARE(p1->dockWidgetsCount(), 1);
    QCOMPARE(p1->dockWidgetsCount(), p1->dockWidgets().count());
    QCOMPARE(p2->dockWidgetsCount(), 2);
    QCOMPARE(p2->dockWidgetsCount(), p2->dockWidgets().count());
    QCOMPARE(p4->dockWidgetsCount(), 1);
    QCOMP


group.material_index));
        }

        data.normalized_material_indices = normalized_mat_idxs;

        geom.computeBoundingSphere();
        geom.computeBoundingBox();

        return geom;
    }
}
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'hoursMinutes',
})
export class HoursMinutesPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return Math.floor(value / 60) + 'h ' + Math.floor(value % 60) + 'min';
  }

}
import React, { CSSProperties } from 'react';
import { StickyProps } from '../sticky/PropsType';
import { BaseTypeProps } from '../utils';

type ScrollspyConfig = {
  /** 滚动导航模式下，容器滚动触底时是否将最后一个tab转为Active状态 */
  autoFocusLast?: boolean;
  /** 触底偏移量 */
  reachBottomThreshold?: number;
}

export interface TabsProps extends BaseTypeProps {
  /** 标签主题色	 */
  color?: string;
  /** 是否显示标签栏外边框，仅在 type="line" 时有效	 */
  border?: boolean;
  /** 是否使用粘性定位布局	 */
  sticky?: boolean | StickyProps;
  /** 是否开启切换标签内容时的转场动画	 */
  animated?: boolean;
  /** 是否开启手势左右滑动切换	 */
  swipeable?: boolean;
  /** 是否开启滚动导航	 */
  scrollspy?: boolean | ScrollspyConfig;
  /** 标签栏背景色	 */
  background?: string;
  /** 底部条宽度，默认单位 px	 */
  lineWidth?: number | string;
  /** 底部条高度，默认单位 px	 */
  lineHeight?: number | string;
  /** 切换标签前的回调函数，返回 false 可阻止切换，支持返回 Promise	 */
  beforeChange?: (name: number | string) => boolean | Promise<boolean>;
  /** 标题选中态颜色	 */
  titleActiveColor?: string;
  /** 标题默认态颜色	 */
  titleInactiveColor?: string;
  /** 样式风格类型，可选值为 card	 */
  type?: 'line' | 'card';
  /** 绑定当前选中标签的标识符	 */
  active?: number | string;
  /** 是否省略过长的标题文字	 */
  ellipsis?: boolean;
  /** 动画时间，单位毫秒，设置为 0 可以禁用动画	 */
  duration?: number | string;
  /** 粘性定位布局下与顶部的最小距离，支持 px vw vh rem 单位，默认 px	 */
  offsetTop?: number | string;
  /** 是否开启延迟渲染（首次切换到标签时才触发内容渲染）	 */
  lazyRender?: boolean;
  /**
   * 滚动阈值，标签数量超过阈值且总宽度超过标签栏宽度时开始横向滚动
   * @default 5
   */
  swipeThreshold?: number | string;
  /** 标签栏左侧内容 */
  navLeft?: React.ReactNode;
  /** 标签栏右侧内容 */
  navRight?: React.ReactNode;
  /** 标签栏下方内容 */
  navBottom?: React.ReactNode;
  /** @deprecated */
  onClick?: (name: string | number, title: string) => void;
  /** 点击标签时触发	 */
  onClickTab?: (tab: {
    name: string | number;
    title: string;


  friend QDataStream & operator>> (QDataStream &in, FlockMember &flockMember)
    {
       in >> flockMember.m_flockID >> flockMember.m_userID
          >> flockMember.m_headPortrait >> flockMember.m_nickname
          >> flockMember.m_loginStatus >> flockMember.m_remark
          >> flockMember.m_flockStatus >> flockMember.m_joinDate;
       return in;
    }
};

// 讨论组成员信息
struct DiscussionMember
{
    QString m_discussionID;// 讨论组ID
    QString m_userID;      // 用户ID
    int m_headPortrait;    // 用户头像编号
    QString m_nickname;    // 用户昵称
    int m_loginStatus;     // 用户登录状态
    int m_discussionStatus;// 用户身份
    QDateTime m_joinDate;  // 加入时间

    friend QDataStream & operator<< (QDataStream &out, const DiscussionMember &disMember)
    {
       out << disMember.m_discussionID << disMember.m_userID
           << disMember.m_headPortrait << disMember.m_nickname
           << disMember.m_loginStatus << disMember.m_discussionStatus
           << disMember.m_joinDate;
       return out;
    }
    friend QDataStream & operator>> (QDataStream &in, DiscussionMember &disMember)
    {
       in >> disMember.m_discussionID >> disMember.m_userID
          >> disMember.m_headPortrait >> disMember.m_nickname
          >> disMember.m_loginStatus  >> disMember.m_discussionStatus
          >> disMember.m_joinDate;
       return in;
    }
};

// 群信息
struct FlockInformation
{
    QString m_flockID;
    QString m_creatorID;
    QDate m_createDate;
    QString m_flockName;
    QString m_theme;

    friend QDataStream & operator<< (QDataStream &out, const FlockInformation &flock)
    {
       out << flock.m_flockID << flock.m_creatorID << flock.m_createDate
           << flock.m_flockName << flock.m_theme;
       return out;
    }
    friend QDataStream & operator>> (QDataStream &in, FlockInformation &flock)
    {
       in >> flock.m_flockID >> flock.m_creatorID >> flock.m_createDate
          >> flock.m_flockName >> flock.m_theme;
       return in;
   }
};

// 讨论组信息
struct DiscussionInformation
{
    QString m_discussionID;
    QString m_creatorID;
    QDate m_createDate;
    QString m_discussionName;
    QString m_theme;

    friend QDataStream & operator<< (QDataStream &out, const DiscussionInformation &dis)
    {
       out << dis.m_discussionID << dis.m_creatorID << dis.m_createDate
           << dis.m_discussionName << dis.m_theme;
       return out;
    }
    friend QDataStream & operator>> (QDataStream &in, DiscussionInformation &dis)
    {
       in >> dis.m_discussionID >> dis.m_creatorID >> dis.m_createDate
          >> dis.m_discussionName >> dis.m_theme;
       return in;
    }
};

// 存储临时信息的结构体，用于信号/糟
struct SaveTmpInformation
{
    int m_requestKind;
    int m_replyKind;
    QQClientSocketCtrl *m_clientSocket;

    QString m_myID;
    QString m_peerID;
    QDate m_date;
    QString m_groupName;
    QString m_groupNameF;
    UserInformation m_userInf;
    LoginInformation m_loginInf;
    FriendInformation m_friendInf;
    TalkMessage m_message;
    int m_status;
    TempStrings m_tempStr;
    QVector<TalkMessage> m_messageVec;
    QVector<FriendInformation> m_friendsVec;
    QVector<QString> m_IDVec;

    QString m_flockID;
    FlockMember m_flockMember;
    FlockInformation m_flockInf;
    QVector<FlockInformation> m_flocksVec;
    QVector<FlockMember> m_flockMembersVec;
    QString m_discussionID;
    DiscussionMember m_discussionMember;
    DiscussionInformation m_discussionInf;
    QVector<DiscussionInformation> m_discussionsVec;
    QVector<DiscussionMember> m_discussionMembersVec;

    int m_mailID;
    MailInformation m_mail;
    QVector<MailInformation>  m_inMailsVec;
    QVector<MailInformation>  m_outMailsVec;

    QString m_title;
    QString m_newTitle;

    QString m_socketID;

    QVector<TalkMessage> m_historyMessageVec;
};

//头像尺寸.
const int HEAD_BIG_SIZE = 40;
const int HEAD_SMALL_SIZE = 35;
const int HEAD_MINI_SIZE = 20;

//聊天室 工具栏尺寸
const int CHAT_WIDGET_TOOL_SIZE = 20;
const int CHAT_WIDGET_TOOL_SMALL_SIZE = 15;

const int FONT_SIZE = 2;

static const QString MAIL_ADDRESS_FORMAT = "@qq.com";

static const QString LOCAL_HISTORY_MESSAGE_PATH = "resource/history/local/";
static const QString NETWORK_HISTORY_MESSAGE_PATH = "resource/history/network/";

#endif // QQCONSTANT_H


jedoch den Anwender:
  »Palladium« stößt vor allem bei der
  Unterhaltungsindustrie, die einen erbitterten Kampf gegen
  jegliche Weiterverbreitung urheberrechtlich geschützter
  Produkte im Internet führt, auf große Zustimmung,
  bietet sich hier jedoch erstmals vordergründig die
  Möglichkeit, MP3-Tauschbörsen und ähnliche Dienste
  effizient trockenzulegen dank »Microsoft«. Auch das
  Kopieren einzelner Musikstücke zu privaten Zwecken am
  heimischen PC wird damit unterbunden - dank
  »Microsoft« werden also vermutlich die ohnehin
  übervollen Kassen der Unterhaltungsindustrie zukünftig
  noch kräftiger klingeln!

Doch der Anwender hat natürlich noch die
  Möglichkeit, auch nicht »TCPA-konforme« Software
  auf seinem heimischen PC zu installieren und zu starten. Bemerkt
  »Palladium« eine solche Anwendung, wird das
  Gesamtsystem als »kompromittiert« gekennzeichnet und
  alle konformen Anwendungen samt Dateien werden geschlossen. Der
  Nutzwert eines solchen Systems dürfte für den Anwender
  dann wohl gegen Null tendieren.

Doch gehen wir einen Schritt weiter und bedenken wir die
  Folgen dieser Technologie:

Die SRL's, DRL's und HCL's, die für die
    Konformitäts-Authentifizierung eines PC's unbedingt
    benötigt werden, werden an zentraler Stelle im Internet
    gespeichert und abgerufen. Hacker brauchen jetzt also nicht
    mehr einzelne PC's anzugreifen, sondern können ihr
    Engagement auf diese Server konzentrieren - und damit unter
    Umständen mit einem einzigen gelungenen Angriff Millionen
    von Rechnern unbrauchbar machen.

Es bedarf keiner ausgesprochen ausgeprägten Phantasie,
    um sich auszumalen, wie »Palladium« mit
    unerwünschten Konkurrenzprodukten verfahren kann: Sollen
    bestimmte Softwareprodukte anderer Hersteller als
    »Microsoft« nicht als »konform«
    zertifiziert werden, so genügt es, sie auf die
    »schwarze Liste« des
    »Palladium«-Systems zu setzen. Bei einem Start
    solcher Software wäre der Rechner nur noch sehr
    eingeschränkt nutzbar, da »kompromittiert« -
    jeder Anwender würde sich wohl zumindest überlegen,
    ob er beim nächsten Mal nicht doch zur drittklassigen
    Spyware aus dem Hause »Microsoft« greift.

Die Zertifizierungen für Software und Dateien


3)
/* 8020A65C 002062BC  48 00 00 1C */	b lbl_8020A678
lbl_8020A660:
/* 8020A660 002062C0  81 9F 00 1C */	lwz r12, 0x1c(r31)
/* 8020A664 002062C4  7F E3 FB 78 */	mr r3, r31
/* 8020A668 002062C8  81 8C 00 1C */	lwz r12, 0x1c(r12)
/* 8020A66C 002062CC  7D 89 03 A6 */	mtctr r12
/* 8020A670 002062D0  4E 80 04 21 */	bctrl
/* 8020A674 002062D4  83 FF 00 04 */	lwz r31, 4(r31)
lbl_8020A678:
/* 8020A678 002062D8  2C 1F 00 00 */	cmpwi r31, 0
/* 8020A67C 002062DC  40 82 FF E4 */	bne lbl_8020A660
/* 8020A680 002062E0  80 7E 01 04 */	lwz r3, 0x104(r30)
/* 8020A684 002062E4  2C 03 00 00 */	cmpwi r3, 0
/* 8020A688 002062E8  41 82 00 14 */	beq lbl_8020A69C
/* 8020A68C 002062EC  81 83 00 1C */	lwz r12, 0x1c(r3)
/* 8020A690 002062F0  81 8C 00 1C */	lwz r12, 0x1c(r12)
/* 8020A694 002062F4  7D 89 03 A6 */	mtctr r12
/* 8020A698 002062F8  4E 80 04 21 */	bctrl
lbl_8020A69C:
/* 8020A69C 002062FC  80 01 00 14 */	lwz r0, 0x14(r1)
/* 8020A6A0 00206300  83 E1 00 0C */	lwz r31, 0xc(r1)
/* 8020A6A4 00206304  83 C1 00 08 */	lwz r30, 8(r1)
/* 8020A6A8 00206308  7C 08 03 A6 */	mtlr r0
/* 8020A6AC 0020630C  38 21 00 10 */	addi r1, r1, 0x10
/* 8020A6B0 00206310  4E 80 00 20 */	blr

.global func_8020A6B4
func_8020A6B4:
/* 8020A6B4 00206314  94 21 FF D0 */	stwu r1, -0x30(r1)
/* 8020A6B8 00206318  7C 08 02 A6 */	mflr r0
/* 8020A6BC 0020631C  90 01 00 34 */	stw r0, 0x34(r1)
/* 8020A6C0 00206320  39 61 00 30 */	addi r11, r1, 0x30
/* 8020A6C4 00206324  4B FB CA 59 */	bl _savegpr_24
/* 8020A6C8 00206328  90 83 00 FC */	stw r4, 0xfc(r3)
/* 8020A6CC 0020632C  3F 60 80 42 */	lis r27, lbl_80423948@ha
/* 8020A6D0 00206330  3F 80 80 42 */	lis r28, lbl_80423A48@ha
/* 8020A6D4 00206334  7C 7D 1B 78 */	mr r29, r3
/* 8020A6D8 00206338  80 04 00 04 */	lwz r0, 4(r4)
/* 8020A6DC 0020633C  3B 7B 39 48 */	addi r27, r27, lbl_


			String nodeDefName = nodeDefNames[j];

			try {
				dataSource = loadDataSource( ltName, nodeDefName );
			} catch ( Exception e ) {
				String msg = "Unable to load data source " + nodeDefName + ": " + e;
//				System.out.println(msg);
				logger.logThreadWarning( GDBMessages.ENGINE_DS_LOAD_ERROR, msg );
				continue;
			}

			newDataSources.put( nodeDefName, dataSource );
			vtiArray[j] = dataSource;

		} // for all nodes defs of a logical table

//		logger.logInfo("Number of gaian nodes for " + ltName + ": " + numGaianNodesForThisLogicalTable);
//		if ( 0 == i || minGaianNodesInAnyLogicalTable > numGaianNodesForThisLogicalTable )
//			minGaianNodesInAnyLogicalTable = numGaianNodesForThisLogicalTable;

		// Note here! it may be better to get the previous entry that may have existed for ltName out first and empty its array to facilitate garbage collection?
		dsArrays.put( ltName, vtiArray );
	}

	/**
	 *  Load data source in dataSources structure, and assign it to a logical table dsArrays list. This will make it active.
	 *
	 * @param ltName
	 * @param nodeDefName
	 * @throws Exception
	 */
	static synchronized void refreshDataSource( String ltName, String nodeDefName ) throws Exception {

		VTIWrapper dataSource = loadDataSource( ltName, nodeDefName );
		List<VTIWrapper> ltDataSources = new ArrayList<VTIWrapper>( Arrays.asList( dsArrays.get( ltName ) ) );

		if ( false == ltDataSources.contains( dataSource ) ) {
			ltDataSources.add( dataSource );

			// Note here! it may be better to get the previous entry that may have existed for
			// ltName out first and empty its array to facilitate garbage collection?
			dsArrays.put( ltName, (VTIWrapper[]) ltDataSources.toArray( new VTIWrapper[0] ) );
		}

		// Update the lt signature (to avoid reload of config) and the latest load timestamp (to avoid reload of ds list in GaianTable)
		ltConfigSignatures.put(ltName, GaianDBConfig.getLogicalTableStructuralSignature(ltName));
		latestGlobalConfigLoadTime = System.currentTimeMillis();
	}

	// Not used because there could be properties in the config file overriding the transient ones -
	// so a full refresh will be invoked anyway in persistAndApplyConfigUpdates() after persisting the removal of the overriding properties.
//	static synchronized void removeDataSource( String ltName, String nodeDefName ) throws Exception {
//
//		VTIWrapper dataSource = dataSources.remove(nodeDefName);
//		if ( null == dataSource ) throw new Exception("Unknown data source ID: " + nodeDefName);
//		List<VTIWrapper> ltDataSources = new ArrayList<VTIWrapper>( Arrays.asList( dsArrays.get( ltName ) ) );
//		ltDataSources.remove( dataSource );
//		dsArrays.put( ltName, (VTIWrapper[]) ltDataSources.toArray( new VTIWrapper[0] ) );
//
//		latestGlobalConfigLoadTime = System.currentTimeMillis();
//	}

	private static VTIWrapper loadDataSource( String ltName, String nodeDefName ) throws Exception { //GaianResultSetMetaData ltrsmd, VTIWrapper[] vtiArray ) {

		VTIWrapper vti = null;
		String sourceID = null;
		GaianResultSetMetaData ltrsmd = (GaianResultSetMetaData) ltrsmds.get(ltName);

		if ( null == ltrsmd )
			throw new Exception("Logical Table is not defined: " + ltName);

		if ( GaianDBConfig.isNodeDefR


# -*- coding: utf-8 -*-
import os
import sys
from core.yolov3 import YOLOV3
from core.yolov4 import YOLOV4
from core.yolov5 import YOLOV5

import tensorflow
if tensorflow.__version__.startswith('1.'):
    import tensorflow as tf
else:
    import tensorflow.compat.v1 as tf
    tf.disable_v2_behavior()

if __name__ == "__main__":
    """
    argv = sys.argv
    if len(argv) < 5:
        print('usage: python freeze_ckpt_to_pb.py gpu_id net_type(yolov5/yolov4/yolov3) ckpt_file pb_file')
        sys.exit()
    """
    gpu_id = '0' #argv[1]
    net_type = 'yolov3' #argv[2]
    ckpt_file = 'ckpts/social_yolov3_test-loss=3.2020.ckpt-198' #argv[3]
    if not os.path.exists(ckpt_file + '.index'):
        print('freeze_ckpt_to_pb ckpt_file=', ckpt_file, ' not exist')
        sys.exit()

    pb_file = ckpt_file + '.pb' #argv[4]
    print('freeze_ckpt_to_pb gpu_id=%s, net_type=%s, ckpt_file=%s, pb_file=%s' % (gpu_id, net_type, ckpt_file, pb_file))

    os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu_id)

    output_node_names = ["input/input_data", "pred_sbbox/concat_2", "pred_mbbox/concat_2", "pred_lbbox/concat_2"]
    with tf.name_scope('input'):
        input_data = tf.placeholder(dtype=tf.float32, name='input_data')

    if net_type == 'yolov3':
        model = YOLOV3(input_data, trainable=False)
    elif net_type == 'yolov4':
        model = YOLOV4(input_data, trainable=False)
    elif net_type == 'yolov5':
        model = YOLOV5(input_data, trainable=False)
    else:
        print('net_type=', net_type, ' error')

    sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
    saver = tf.train.Saver()
    saver.restore(sess, ckpt_file)

    converted_graph_def = tf.graph_util.convert_variables_to_constants(sess, input_graph_def=sess.graph.as_graph_def(),
                                                                       output_node_names=output_node_names)
    with tf.gfile.GFile(pb_file, "wb") as f:
        f.write(converted_graph_def.SerializeToString())


)
			??? p = (randGen.nextInt() % (stop-start)) + start;
			// Partition the array into smaller and greater elements
			// Get the resulting (and final) position of the pivot element
			p = partition(values, start, stop, p);
			// Sort subsequances separately and independently ...

			// ==========================================================
			// ================= START PARALLEL SECTION =================
			// ==========================================================
			try {
				ExecutorService pool = Executors.newFixedThreadPool(2);

				// ----------------- START THREAD 0 -----------------
				Future<Object[]> futureb962b98_0 = pool.submit( new Workerb962b98_0(values, start, p) );

				// ----------------- START THREAD 1 -----------------
				Future<Object[]> futureb962b98_1 = pool.submit( new Workerb962b98_1(values, p, stop) );

				// ----------------- AWAIT THREAD 0 -----------------
				futureb962b98_0.get();
				// ----------------- AWAIT THREAD 1 -----------------
				futureb962b98_1.get();
				pool.shutdown();
			}
			catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); }
			// ==========================================================
			// ================== END PARALLEL SECTION ==================
			// ==========================================================

		}
	}

	/**
	 * Sorts the array 'values´ of numbers according to he heap sort
	 * algorithm
	 * @param values
	 */
	private static void heapSort(??? values) {
		// TODO: Check and accomplish variable declarations:
		int heapRange;

		buildMaxHeap(values);
		heapRange = length(values);
		for (int k = heapRange - 1; k >= 1; k += (-1)) {
			heapRange = heapRange - 1;
			// Swap the maximum value (root of the heap) to the heap end
			??? maximum = values[0];
			values[0] = values[heapRange];
			values[heapRange] = maximum;
			maxHeapify(values, 0, heapRange);
		}
	}

}
// Generated by Structorizer 3.32-20

// Copyright (C) 2018-05-14 Kay Gürtzig
// License: GPLv3-link
// GNU General Public License (V 3)
// https://www.gnu.org/licenses/gpl.html
// http://www.gnu.de/documents/gpl.de.html

import java.util.Scanner;

/**
 * Concept and lisp implementation published by Joseph Weizenbaum (MIT):
 * "ELIZA - A Computer Program For the Study of Natural Language Communication Between Man and Machine" - In:
 * Computational Linguistis 1(1966)9, pp. 36-45
 * Revision history:
 * 2016-10-06 Initial version
 * 2017-03-29 Two diagrams updated (comments translated to English)
 * 2017-03-29 More keywords and replies added
 * 2019-03-14 Replies and mapping reorganised for easier maintenance
 * 2019-03-15 key map joined from keyword array and index map
 * 2019-03-28 Keyword "bot" inserted (same reply ring as "computer")
 * 2019-11-28 New global type "History" (to ensure a homogenous array)
 */
public class ELIZA {

	private static boolean initDone_History = false;
	// histArray contains the most recent user replies as ring buffer;
	// histIndex is the index where the next reply is to be stored (= index of the oldest
	// cached user reply).
	// Note: The depth of the history is to be specified by initializing a variable of this type,
	// e.g. for a history of depth 5:
	// myhistory <- History{{"", "", "", "", ""}, 0}
	private class History{
		public String[]	histArray;
		public int	histIndex;
		public History(String[] p_histArray, int p_histIndex)


Hielo GX",
				it: "Geloraggio-GX",
				pt: "Raio Congelante GX",
				de: "Eisstrahl GX"
			},
			effect: {
				en: "Your opponent’s Active Pokémon is now Paralyzed. (You can’t use more than 1 GX attack in a game.)",
				fr: "Le Pokémon Actif de votre adversaire est maintenant Paralysé. (Vous ne pouvez utiliser qu’une attaque GX par partie.)",
				es: "El Pokémon Activo de tu rival pasa a estar Paralizado. (No puedes usar más de 1 ataque GX en una partida).",
				it: "Il Pokémon attivo del tuo avversario viene paralizzato. Non puoi usare più di un attacco GX a partita.",
				pt: "O Pokémon Ativo do seu oponente agora está Paralisado (você não pode usar mais de 1 ataque GX por partida).",
				de: "Das Aktive Pokémon deines Gegners ist jetzt paralysiert. (Du kannst pro Spiel nur 1 GX-Attacke einsetzen.)"
			},
			damage: 100,

		},
	],
	weaknesses: [
		{
			type: "Grass",
			value: "×2"
		},
	],

	retreat: 2,

}

export default card
import * as C from 'fp-ts/Console'
import * as IO from 'fp-ts/IO'
import * as IOE from 'fp-ts/IOEither'
import { pipe } from 'fp-ts/function'

import type { Scraper } from '../src/Scraper'
import * as F from '../src/Fetch'
import * as Select from '../src/Select'
import * as Scrape from '../src/Scraper'

const exampleHTML = `

                Sally

Woo hoo!

                Bill

                Susan

WTF!?!

                Bill

`

export interface ImageAttributes {
  readonly altText: string
  readonly url: string
}

const imageAttributes: Scraper<ReadonlyArray<ImageAttributes>> = pipe(
  // Use the `any` combinator to select all the relevant content (i.e. the alt text and the src)
  // from the currently selected img tag.
  Scrape.attr('alt', Select.any),
  Scrape.bindTo('altText'),
  Scrape.bind('url', () => Scrape.attr('src', Select.any)),
  Scrape.chroots(Select.tag('img'))
)

const main: IO.IO<void> = pipe(
  imageAttributes,
  F.scrapeRaw(exampleHTML),
  IOE.fromEither,
  IOE.fold(C.error, C.log)
)

main()
export type TFlags = Record<string, any>

export type TContext = {
  cwd: string
  temp: string
  flags: TFlags
  manifest: Record<string, any>
  err?: any
}

export


utDelayArray[d]) + outputDelayArray[d + 8] + nextPreDelayValue) * 0.001f;
            outputDelayGain = outputGainArray[d] * outputDelayGainMult;
            rightOutputSample += fractionalDelay.popSample(0, outputDelayTime * lastSampleRate, false) * outputDelayGain;
        }
        outputDelayTime = ((programId * outputDelayArray[7]) + outputDelayArray[7 + 8] + nextPreDelayValue) * 0.001f;
        outputDelayGain = outputGainArray[7] * outputDelayGainMult;
        rightOutputSample += fractionalDelay.popSample(0, outputDelayTime * lastSampleRate, true) * outputDelayGain;
        // add left channel to outputBuffer
        outputBuffer.setSample(0, i, leftOutputSample);
        // add right channel to outputBuffer when running in stereo
        if (totalNumOutputChannels == 2)
        {
            outputBuffer.setSample(1, i, rightOutputSample);
        }
    }
    // pre-process feedback buffer
    juce::dsp::AudioBlock<float> feedbackBlock(feedbackBuffer);
    feedBackHighPass.process(juce::dsp::ProcessContextReplacing<float>(feedbackBlock));
    feedBackLowPass.process(juce::dsp::ProcessContextReplacing<float>(feedbackBlock));
    feedBackDip.process(juce::dsp::ProcessContextReplacing<float>(feedbackBlock));

    // write feedbackbuffer to fifo
    abstractFifo.prepareToWrite(bufferSize, start1, size1, start2, size2);
    if (size1 > 0)
    {
        fifoBuffer.copyFrom(0, start1, feedbackBuffer, 0, 0, size1);
    }
    if (size2 > 0)
    {
        fifoBuffer.copyFrom(0, start2, feedbackBuffer, 0, size1, size2);
    }
    abstractFifo.finishedWrite(size1 + size2);

    // apply de-emphasis filter on output taps
    deEmphasis.process(juce::dsp::ProcessContextReplacing<float>(outputBlock));
    // copy dry signal to buffer
    for (int channel = 0; channel < totalNumInputChannels; channel++)
    {
        inputBuffer.copyFrom(channel, 0, buffer, channel, 0, bufferSize);
    }
    // write output taps to main buffer
    for (int channel = 0; channel < totalNumOutputChannels; ++channel)
    {
        auto *wetSignal = outputBuffer.getReadPointer(channel);
        auto *drySignal = inputBuffer.getReadPointer(channel);
        mixSmooth.setTargetValue(mixLevel);
        float wetLevel = mixSmooth.getNextValue();
        float dryLevel = 1.0f - wetLevel;
        buffer.copyFromWithRamp(channel, 0, drySignal, bufferSize, dryLevel, dryLevel);
        buffer.addFromWithRamp(channel, 0, wetSignal, bufferSize, wetLevel, wetLevel);
    }
}

//==============================================================================
bool SG323AudioProcessor::hasEditor() const
{
    return true; // (change this to false if you choose to not supply an editor)
}

juce::AudioProcessorEditor *SG323AudioProcessor::createEditor()
{
    return new SG323AudioProcessorEditor(*this);
}

//==============================================================================
void SG323AudioProcessor::getStateInformation(juce::MemoryBlock &destData)
{
    // You should use this method to store your parameters in the memory block.
    // You could do that either as raw data, or use the XML or ValueTree classes
    // as intermediaries to make it easy to save and load complex data.
    auto state = apvts.copyState();
    std::unique_ptr<juce::XmlElement> xml(state.createXml());
    copyXmlToBinary(*xml, destData);
}

void SG323AudioProcessor::setStateInformation(const void *data, int sizeInBytes)
{
    // You should use this method to restore your parameters from this memory block,
    // whose contents will have been created by the getStateInformation() call.
    std::unique_ptr<juce::XmlElement> xmlState(getXmlFromBinary(data, sizeIn


 based), see doc to use other codecs
    var inner = sse_decode_list_prim_u_8_strict(deserializer);
    return utf8.decoder.convert(inner);
  }

  @protected
  AsPlayLib sse_decode_as_play_lib(SseDeserializer deserializer) {
    // Codec=Sse (Serialization based), see doc to use other codecs
    var var_thisId = sse_decode_String(deserializer);
    var var_thisUrl = sse_decode_String(deserializer);
    return AsPlayLib(thisId: var_thisId, thisUrl: var_thisUrl);
  }

  @protected
  AsUiButton sse_decode_as_ui_button(SseDeserializer deserializer) {
    // Codec=Sse (Serialization based), see doc to use other codecs
    var var_text = sse_decode_opt_String(deserializer);
    var var_onClick =
        sse_decode_opt_box_autoadd_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerAsUiButtonCallback(
          deserializer,
        );
    var var_primary = sse_decode_opt_box_autoadd_bool(deserializer);
    var var_rounded = sse_decode_opt_box_autoadd_bool(deserializer);
    var var_disabled = sse_decode_opt_box_autoadd_bool(deserializer);
    return AsUiButton(
      text: var_text,
      onClick: var_onClick,
      primary: var_primary,
      rounded: var_rounded,
      disabled: var_disabled,
    );
  }

  @protected
  AsUiButtons sse_decode_as_ui_buttons(SseDeserializer deserializer) {
    // Codec=Sse (Serialization based), see doc to use other codecs
    var var_buttons = sse_decode_opt_list_as_ui_button(deserializer);
    return AsUiButtons(buttons: var_buttons);
  }

  @protected
  AsUiComponent sse_decode_as_ui_component(SseDeserializer deserializer) {
    // Codec=Sse (Serialization based), see doc to use other codecs

    var tag_ = sse_decode_i_32(deserializer);
    switch (tag_) {
      case 0:
        var var_field0 = sse_decode_box_autoadd_as_ui_root(deserializer);
        return AsUiComponent_Root(var_field0);
      case 1:
        var var_field0 = sse_decode_box_autoadd_as_ui_container(deserializer);
        return AsUiComponent_Container(var_field0);
      case 2:
        var var_field0 = sse_decode_box_autoadd_as_ui_text(deserializer);
        return AsUiComponent_Text(var_field0);
      case 3:
        var var_field0 = sse_decode_box_autoadd_as_ui_mfm(deserializer);
        return AsUiComponent_Mfm(var_field0);
      case 4:
        var var_field0 = sse_decode_box_autoadd_as_ui_button(deserializer);
        return AsUiComponent_Button(var_field0);
      case 5:
        var var_field0 = sse_decode_box_autoadd_as_ui_buttons(deserializer);
        return AsUiComponent_Buttons(var_field0);
      case 6:
        var var_field0 = sse_decode_box_autoadd_as_ui_switch(deserializer);
        return AsUiComponent_ToggleSwitch(var_field0);
      case 7:
        var var_field0 = sse_decode_box_autoadd_as_ui_textarea(deserializer);
        return AsUiComponent_Textarea(var_field0);
      case 8:
        var var_field0


common/http';
import { CookieService } from 'ngx-cookie';
import { UserService } from './user.service';
import { Observable } from 'rxjs';
// import { IPagination } from './data-models/pagination';

@Injectable()
export class ApiService {

  // http options used for making API calls
  private httpOptions: any;

   // http options used for making API calls with observe response
   private httpOptionsObserveResponse: any;

  // the actual JWT token
  public token: string;

  // the token expiration date
  public token_expires: Date;

  // the username of the logged in user
  public username: string;

  // error messages received from the login attempt
  public errors: any = [];

  // private pagination : IPagination;

  constructor(private http: HttpClient, private _cookieService:CookieService, private _userService: UserService) {
    // CSRF token is needed to make API calls work when logged in
    let csrf = this._cookieService.get("csrftoken");
    // the Angular HttpHeaders class throws an exception if any of the values are undefined
    if (typeof(csrf) === 'undefined') {
          csrf = '';
    }
    this.httpOptions = {
      headers: new HttpHeaders({'Content-Type': 'application/json',
        'X-CSRFToken': csrf,
        'Authorization': 'JWT ' + this._userService.token
      })
    };
    this.httpOptionsObserveResponse = {
      headers: new HttpHeaders({'Content-Type': 'application/json',
        'X-CSRFToken': csrf,
        'Authorization': 'JWT ' + this._userService.token
      }),
      observe: 'response'
    };
  }

    // Uses http.get() to get groups of an employee
    public getGroupsForEmployee():Observable<any> {
      // this.httpOptions.observe='response'
      return this.http.get('/groups-for-employee/', this.httpOptionsObserveResponse)
    }

    // Uses http.get() to get contacts of an employee
    public getContactsForGroup(group_id:string):Observable<any> {
      return this.http.get<any>(`/contacts-for-group/?group_id=${group_id}`, this.httpOptions)
    }

    // Uses http.get() to get group details
    public getGroupDetails(group_id:string):Observable<any> {
      return this.http.get(`/group-details/?group_id=${group_id}`, this.httpOptions)
    }

    // Uses http.get() to get group details
    public deleteGroup(group_id:string):Observable<any> {
      return this.http.get(`/group-details/?group_id=${group_id}`, this.httpOptions)
    }

    // Uses http.get() to get group details
    // public getPagination(headers):IPagination {
    //   this.pagination.has_next = headers.get('has_next');
    //   this.pagination.has_other_pages = headers.get('has_other_pages');
    //   this.pagination.has_previous = headers.get('has_previous');
    //   this.pagination.next_page_number=headers.get('next_page_number');
    //   this.pagination.number = headers.get('number');
    //   this.pagination.paginator_page_range = headers.get('paginator_page_range');
    //   this.pagination.previous_page_number = headers.get('previous_page_number');
    //   return this.pagination;
    // }

    // return arange array for a python pagination range string
    getRangeArray(range: string){
      if(range === undefined || range === null || range ===""){
        return;
      }
      // example range will be range(1, 4)
      // will return [1,2,3]
      var first_index = range.charAt(6);
      var second_index = range.charAt(9);


        cy = y;
        M_DrawCharacter(cx, cy, 3);
        for (n = 0; n < lines; n++) {
            cy += 8;
            M_DrawCharacter(cx, cy, 6);
        }
        M_DrawCharacter(cx, cy + 8, 9);
    }

    /**
     * M_DrawCharacter
     *
     * Draws one solid graphics character cx and cy are in 320*240 coordinates,
     * and will be centered on higher res screens. ================
     */
    private void M_DrawCharacter(int cx, int cy, int num) {
        re.DrawChar(cx + ((viddef.getWidth() - 320) >> 1), cy
                + ((viddef.getHeight() - 240) >> 1), num);
    }

    long endtime;

    private void Explosion(float[] org) {
        cparticle_t p;

        for (int i = 0; i < 256; i++) {
            p = new cparticle_t();

            p.time = time() * 1.0f;
            p.color = /* 0xe0 */223 - (Lib.rand() & 7);
            for (int j = 0; j < 3; j++) {
                p.org[j] = org[j] + (float) (Lib.rand() % 32) - 16;
                p.vel[j] = (float) (Lib.rand() % 384) - 192;
            }

            p.accel[0] = p.accel[1] = 0;
            p.accel[2] = -PARTICLE_GRAVITY;
            p.alpha = 1.0f;
            p.alphavel = -0.8f / (0.5f + Globals.rnd.nextFloat() * 0.3f);

            active_particles.add(p);
        }
    }

    static final float INSTANT_PARTICLE = -10000.0f;

    static final float PARTICLE_GRAVITY = 40.0f;

    /*
     * =============== CL_AddParticles ===============
     */
    private void animateParticles() {
        cparticle_t p;
        float alpha;
        float time, time2;
        float[] org = { 0, 0, 0 };
        int color;

        time = 0.0f;

        for (Iterator it = active_particles.iterator(); it.hasNext();) {
            p = (cparticle_t) it.next();

            // PMM - added INSTANT_PARTICLE handling for heat beam
            if (p.alphavel != INSTANT_PARTICLE) {
                time = (time() - p.time) * 0.001f;
                alpha = p.alpha + time * p.alphavel;
                if (alpha <= 0) { // faded out
                    it.remove();
                    continue;
                }
            } else {
                alpha = p.alpha;
            }

            if (alpha > 1.0)
                alpha = 1;
            color = (int) p.color;

            time2 = time * time;

            org[0] = p.org[0] + p.vel[0] * time + p.accel[0] * time2;
            org[1] = p.org[1] + p.vel[1] * time + p.accel[1] * time2;
            org[2] = p.org[2] + p.vel[2] * time + p.accel[2] * time2;

            AddParticle(org, color, alpha);

            // PMM
            if (p.alphavel == INSTANT_PARTICLE) {
                p.alphavel = 0.0f;
                p.alpha = 0.0f;
            }
        }
    }

    private void Heatbeam(float[] start, float[] forward) {

        float[] v_up = { 0, 0, 10 };
        float[] v_right = { 0, 10, 0 };

        float[] move = { 0, 0, 0 };


#
# This file is part of the Chemical Data Processing Toolkit
#
# Copyright (C) Thomas Seidel <thomas.seidel@univie.ac.at>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#

##
# \brief
#
class FileCDFBZ2DRegularGridWriter(DRegularGridWriterBase):

    ##
    # \brief Initializes the \e %FileCDFBZ2DRegularGridWriter instance.
    # \param file_name
    # \param mode
    #
    def __init__(file_name: str, mode: OpenMode = Base.IOStream.OpenMode(60)) -> None: pass


fmuld %f18,%f12,%f54

# qhasm: 					h128 += i1
# asm 1: faddd <h128=float64#17,<i1=float64#19,>h128=float64#17
# asm 2: faddd <h128=%f32,<i1=%f36,>h128=%f32
faddd %f32,%f36,%f32

# qhasm: g192 = *(float64 *) (g + 72)
# asm 1: ldd [<g=int64#3+72],>g192=float64#19
# asm 2: ldd [<g=%i2+72],>g192=%f36
ldd [%i2+72],%f36

# qhasm: 				f86g86 = f86 * g86
# asm 1: fmuld <f86=float64#14,<g86=float64#5,>f86g86=float64#30
# asm 2: fmuld <f86=%f26,<g86=%f8,>f86g86=%f58
fmuld %f26,%f8,%f58

# qhasm: 					i3 += f150g0
# asm 1: faddd <i3=float64#21,<f150g0=float64#29,>i3=float64#21
# asm 2: faddd <i3=%f40,<f150g0=%f56,>i3=%f40
faddd %f40,%f56,%f40

# qhasm: 				f107g64 = f107 * g64
# asm 1: fmuld <f107=float64#18,<g64=float64#12,>f107g64=float64#29
# asm 2: fmuld <f107=%f34,<g64=%f22,>f107g64=%f56
fmuld %f34,%f22,%f56

# qhasm: 					h171 += f22g150
# asm 1: faddd <h171=float64#13,<f22g150=float64#25,>h171=float64#13
# asm 2: faddd <h171=%f24,<f22g150=%f48,>h171=%f24
faddd %f24,%f48,%f24

# qhasm: 				f128g43 = f128 * g43
# asm 1: fmuld <f128=float64#20,<g43=float64#8,>f128g43=float64#25
# asm 2: fmuld <f128=%f38,<g43=%f14,>f128g43=%f48
fmuld %f38,%f14,%f48

# qhasm: 					h150 += i2
# asm 1: faddd <h150=float64#15,<i2=float64#22,>h150=float64#15
# asm 2: faddd <h150=%f28,<i2=%f42,>h150=%f28
faddd %f28,%f42,%f28

# qhasm: 				f150g22 = f150 * g22
# asm 1: fmuld <f150=float64#9,<g22=float64#4,>f150g22=float64#22
# asm 2: fmuld <f150=%f16,<g22=%f6,>f150g22=%f42
fmuld %f16,%f6,%f42

# qhasm: 					i1 = f43g128 + f64g107
# asm 1: faddd <f43g128=float64#27,<f64g107=float64#28,>i1=float64#27
# asm 2: faddd <f43g128=%f52,<f64g107=%f54,>i1=%f52
faddd %f52,%f54,%f52

# qhasm: 				f171g0 = f171 * g0
# asm 1: fmuld


import numpy as np
import os
import pytest
import shutil
import torch

from xrmocap.data_structure.body_model.smpl_data import SMPLData
from xrmocap.model.body_model.builder import build_body_model

body_model_load_dir = 'xrmocap_data/body_models/smpl'
extra_joints_regressor_path = 'xrmocap_data/body_models/J_regressor_extra.npy'
input_dir = 'tests/data/model/body_model/test_smpl'
output_dir = 'tests/data/output/model/body_model/test_smpl'

@pytest.fixture(scope='module', autouse=True)
def fixture():
    if os.path.exists(output_dir):
        shutil.rmtree(output_dir)
    os.makedirs(output_dir, exist_ok=False)

def test_smpl():
    random_body_pose = torch.rand((1, 69))
    # test SMPL without extra_joints_regressor
    smpl_45 = build_body_model(
        dict(
            type='SMPL',
            keypoint_convention='smpl_45',
            model_path=body_model_load_dir))
    smpl_45 = smpl_45(body_pose=random_body_pose)
    assert isinstance(smpl_45['joints'], torch.Tensor)
    assert smpl_45['joints'].shape[1] == 45
    smpl_data = SMPLData()
    smpl_data.from_param_dict(smpl_45)
    assert 'fullpose' in smpl_data
    assert isinstance(smpl_data['fullpose'], np.ndarray)
    npz_path = os.path.join(output_dir, 'dumped_smpl_data.npz')
    smpl_data.dump(npz_path)
    # test SMPL with extra_joints_regressor
    smpl_54 = build_body_model(
        dict(
            type='SMPL',
            keypoint_convention='smpl_54',
            model_path=body_model_load_dir,
            extra_joints_regressor=extra_joints_regressor_path))
    smpl_54_output = smpl_54(body_pose=random_body_pose)
    assert isinstance(smpl_54_output['joints'], torch.Tensor)
    assert smpl_54_output['joints'].shape[1] == 54


-items-center hover:shadow-md hover:shadow-gray-400 hover:translate-y-[-5px] transition transition-all duration-300 wow animate__animated animate__fadeInRight">
                                <svg  class="wow animate__animated animate__shakeX  animate__delay-2s " xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 64 64" width="50px" height="50px"><defs><rect id="zOt10NeCJpLJlmsRZOsAFa" width="280.487" height="124" x="654" y="-72"/></defs><clipPath id="zOt10NeCJpLJlmsRZOsAFb"><use overflow="visible" xlink:href="#zOt10NeCJpLJlmsRZOsAFa"/></clipPath><g><linearGradient id="zOt10NeCJpLJlmsRZOsAFc" x1="76.124" x2="76.124" y1="12.7" y2="50.192" gradientTransform="matrix(-1 0 0 1 115.415 0)" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#1a6dff"/><stop offset="1" stop-color="#c822ff"/></linearGradient><path fill="url(#zOt10NeCJpLJlmsRZOsAFc)" d="M50.999,50.192c-0.597,0-1.19-0.179-1.702-0.531L25.882,33.513 c-0.824-0.568-1.31-1.505-1.298-2.506c0.013-1,0.52-1.925,1.356-2.474l23.416-15.342c0.923-0.604,2.099-0.655,3.07-0.129 C53.397,13.587,54,14.598,54,15.701v31.49c0,1.118-0.615,2.136-1.605,2.656C51.955,50.078,51.476,50.192,50.999,50.192z M50.992,14.697c-0.162,0-0.348,0.042-0.54,0.168L27.036,30.207c-0.283,0.186-0.448,0.485-0.452,0.824 c-0.004,0.338,0.154,0.643,0.433,0.835l23.415,16.148c0.45,0.311,0.872,0.146,1.033,0.062C51.8,47.9,52,47.569,52,47.191v-31.49 c0-0.538-0.367-0.794-0.524-0.88C51.385,14.772,51.21,14.697,50.992,14.697z"/><linearGradient id="zOt10NeCJpLJlmsRZOsAFd" x1="23.708" x2="23.708" y1="13.698" y2="49.195" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#6dc7ff"/><stop offset="1" stop-color="#e6abff"/></linearGradient><path fill="url(#zOt10NeCJpLJlmsRZOsAFd)" d="M10,15.701v31.49c0,1.612,1.809,2.561,3.135,1.646l23.416-16.149 c1.169-0.806,1.149-2.541-0.039-3.319L13.096,14.028C11.766,13.157,10,14.111,10,15.701z"/><g><linearGradient id="zOt10NeCJpLJlmsRZOsAFe" x1="24.708" x2="24.708" y1="12.7" y2="50.192" g


bleNewOutput: true)
                .Execute(outputDll, "--logger:console;verbosity=normal");

            result.ExitCode.Should().Be(1);
            var dotnet = result.StartInfo.FileName;
            Path.GetFileNameWithoutExtension(dotnet).Should().Be("dotnet");
            string dotnetRoot = Environment.Is64BitProcess ? "DOTNET_ROOT" : "DOTNET_ROOT(x86)";
            result.StartInfo.EnvironmentVariables.ContainsKey(dotnetRoot).Should().BeTrue($"because {dotnetRoot} should be set");
            result.StartInfo.EnvironmentVariables[dotnetRoot].Should().Be(Path.GetDirectoryName(dotnet));
        }

        [Fact]
        public void TestsFromAGivenContainerAndArchSwitchShouldFlowToVsTestConsole()
        {
            var testAppName = "VSTestCore";
            var testAsset = _testAssetsManager.CopyTestAsset(testAppName)
                .WithSource()
                .WithVersionVariables();

            var testRoot = testAsset.Path;

            var configuration = Environment.GetEnvironmentVariable("CONFIGURATION") ?? "Debug";

            new BuildCommand(testAsset)
                .Execute()
                .Should().Pass();

            var outputDll = Path.Combine(testRoot, "bin", configuration, ToolsetInfo.CurrentTargetFramework, $"{testAppName}.dll");

            // Call vstest
            var result = new DotnetTestCommand(Log, disableNewOutput: true)
                .Execute(outputDll, "--arch", "wrongArchitecture");
            if (!TestContext.IsLocalized())
            {
                result.StdErr.Should().StartWith("Invalid platform type: wrongArchitecture. Valid platform types are ");
            }

            result.ExitCode.Should().Be(1);
        }

        [Theory]
        [InlineData("-e:foo=bardll")]
        [InlineData("-e:foo=barexe")]
        public void MissingOutputDllAndArgumentsEndWithDllOrExeShouldFailInMSBuild(string arg)
        {
            var testAppName = "VSTestCore";
            var testAsset = _testAssetsManager.CopyTestAsset(testAppName)
                .WithSource()
                .WithVersionVariables();

            new BuildCommand(testAsset)
                .Execute()
                .Should().Pass();

            var result = new DotnetTestCommand(Log, disableNewOutput: true)
                .Execute(arg);
            if (!TestContext.IsLocalized())
            {
                result.StdOut.Should().Contain("MSBUILD : error MSB1003: Specify a project or solution file. The current working directory does not contain a project or solution file.");
            }

            result.ExitCode.Should().Be(1);
        }
    }
}


 = 45402,
		/// <summary>
		/// Legs
		/// Level: 219
		/// Set: Worldbreaker Regalia (Id: 825)
		/// Class: Armor
		/// </summary>
		ValorousWorldbreakerLegguards = 45403,
		/// <summary>
		/// Shoulder
		/// Level: 219
		/// Set: Worldbreaker Regalia (Id: 825)
		/// Class: Armor
		/// </summary>
		ValorousWorldbreakerSpaulders = 45404,
		/// <summary>
		/// Robe
		/// Level: 219
		/// Set: Worldbreaker Regalia (Id: 825)
		/// Class: Armor
		/// </summary>
		ValorousWorldbreakerTunic = 45405,
		/// <summary>
		/// Hand
		/// Level: 219
		/// Set: Worldbreaker Garb (Id: 824)
		/// Class: Armor
		/// </summary>
		ValorousWorldbreakerGloves = 45406,
		/// <summary>
		/// Head
		/// Level: 219
		/// Set: Worldbreaker Garb (Id: 824)
		/// Class: Armor
		/// </summary>
		ValorousWorldbreakerHelm = 45408,
		/// <summary>
		/// Legs
		/// Level: 219
		/// Set: Worldbreaker Garb (Id: 824)
		/// Class: Armor
		/// </summary>
		ValorousWorldbreakerKilt = 45409,
		/// <summary>
		/// Shoulder
		/// Level: 219
		/// Set: Worldbreaker Garb (Id: 824)
		/// Class: Armor
		/// </summary>
		ValorousWorldbreakerShoulderpads = 45410,
		/// <summary>
		/// Robe
		/// Level: 219
		/// Set: Worldbreaker Garb (Id: 824)
		/// Class: Armor
		/// </summary>
		ValorousWorldbreakerHauberk = 45411,
		/// <summary>
		/// Head
		/// Level: 219
		/// Set: Worldbreaker Battlegear (Id: 823)
		/// Class: Armor
		/// </summary>
		ValorousWorldbreakerFaceguard = 45412,
		/// <summary>
		/// Robe
		/// Level: 219
		/// Set: Worldbreaker Battlegear (Id: 823)
		/// Class: Armor
		/// </summary>
		ValorousWorldbreakerChestguard = 45413,
		/// <summary>
		/// Hand
		/// Level: 219
		/// Set: Worldbreaker Battlegear (Id: 823)
		/// Class: Armor
		/// </summary>
		ValorousWorldbreakerGrips = 45414,
		/// <summary>
		/// Shoulder
		/// Level: 219
		/// Set: Worldbreaker Battlegear (Id: 823)
		/// Class: Armor
		/// </summary>
		ValorousWorldbreakerShoulderguards = 45415,
		/// <summary>
		/// Legs
		/// Level: 219
		/// Set: Worldbreaker Battlegear (Id: 823)
		/// Class: Armor
		/// </summary>
		ValorousWorldbreakerWarKilt = 45416,
		/// <summary>
		/// Head
		/// Level: 219
		/// Set: Deathbringer Garb (Id: 837)
		/// Class: Armor
		/// </summary>
		ValorousDeathbringerHood = 45417,
		/// <summary>
		/// Finger
		/// Level: 219
		/// Class: Armor
		/// </summary>
		LadyMayesSapphireRing = 45418,
		/// <summary>
		/// Hand
		/// Level: 219
		/// Set: Deathbringer Garb (Id: 837)
		/// Class: Armor
		/// </summary>
		ValorousDeathbringerGloves = 45419,
		/// <summary>
		/// Legs
		/// Level: 219
		/// Set: Deathbringer Garb (Id: 837)
		/// Class: Armor
		/// </summary>
		ValorousDeathbringerLeggings = 45420,
		/// <summary>
		/// Robe
		/// Level: 219
		/// Set: Deathbringer Garb (


);
            },
          ),
        );
      },
    );
  }

  factory PickMethod.common(int maxAssetsCount) {
    return PickMethod(
      icon: '📹',
      name: 'Common picker',
      description: 'Pick images and videos.',
      method: (BuildContext context, List<AssetEntity> assets) {
        return AssetPicker.pickAssets(
          context,
          pickerConfig: AssetPickerConfig(
            maxAssets: maxAssetsCount,
            selectedAssets: assets,
            requestType: RequestType.common,
          ),
        );
      },
    );
  }

  factory PickMethod.threeItemsGrid(int maxAssetsCount) {
    return PickMethod(
      icon: '🔲',
      name: '3 items grid',
      description: 'Picker will served as 3 items on cross axis. '
          '(pageSize must be a multiple of gridCount)',
      method: (BuildContext context, List<AssetEntity> assets) {
        return AssetPicker.pickAssets(
          context,
          pickerConfig: AssetPickerConfig(
            gridCount: 3,
            pageSize: 120,
            maxAssets: maxAssetsCount,
            selectedAssets: assets,
            requestType: RequestType.all,
          ),
        );
      },
    );
  }

  factory PickMethod.customFilterOptions(int maxAssetsCount) {
    return PickMethod(
      icon: '⏳',
      name: 'Custom filter options',
      description: 'Add filter options for the picker.',
      method: (BuildContext context, List<AssetEntity> assets) {
        return AssetPicker.pickAssets(
          context,
          pickerConfig: AssetPickerConfig(
            maxAssets: maxAssetsCount,
            selectedAssets: assets,
            requestType: RequestType.video,
            filterOptions: FilterOptionGroup()
              ..setOption(
                AssetType.video,
                const FilterOption(
                  durationConstraint: DurationConstraint(
                    max: Duration(minutes: 1),
                  ),
                ),
              ),
          ),
        );
      },
    );
  }

  factory PickMethod.prependItem(int maxAssetsCount) {
    return PickMethod(
      icon: '➕',
      name: 'Prepend special item',
      description: 'A special item will prepend to the assets grid.',
      method: (BuildContext context, List<AssetEntity> assets) {
        return AssetPicker.pickAssets(
          context,
          pickerConfig: AssetPickerConfig(
            maxAssets: maxAssetsCount,
            selectedAssets: assets,
            requestType: RequestType.common,
            specialItemPosition: SpecialItemPosition.prepend,
            specialItemBuilder: (
              BuildContext context,
              AssetPathEntity? path,
              int length,
            ) {
              return const Center(
                child: Text('Custom Widget', textAlign: TextAlign.center),
              );
            },
          ),
        );
      },
    );
  }

  factory PickMethod.noPreview(int maxAssetsCount) {
    return PickMethod(
      icon: '👁🗨',
      name: 'No preview',
      description: 'Pick assets like the WhatsApp/MegaTok pattern.',
      method: (BuildContext context, List<AssetEntity> assets) {
        return AssetPicker.pickAssets(
          context,
          pickerConfig: AssetPickerConfig(
            maxAssets: maxAssetsCount,
            selectedAssets: assets,
            requestType: RequestType.common,
            specialPickerType: SpecialPickerType.noPreview,
          ),
        );
      },
    );
  }

  factory PickMethod.keepScrollOffset({
    required DefaultAssetPickerBuilderDelegate Function() delegate,
    required Function(PermissionState state) onPermission,
    GestureLongPressCallback? onLongPress,
  }) {
    return PickMethod(
      icon: '💾',
      name: 'Keep scroll offset',
      description: 'Pick assets from same scroll position.',
      method: (BuildContext context, List<AssetEntity> a


f,0x35,0xea,0xc1]
// CHECK-ERROR: instruction requires: sme2
// CHECK-UNKNOWN: c1ea359f <unknown>

udot    za.s[w8, 0, vgx2], {z0.b, z1.b}, z0.b[0]  // 11000001-01010000-00010000-00110000
// CHECK-INST: udot    za.s[w8, 0, vgx2], { z0.b, z1.b }, z0.b[0]
// CHECK-ENCODING: [0x30,0x10,0x50,0xc1]
// CHECK-ERROR: instruction requires: sme2
// CHECK-UNKNOWN: c1501030 <unknown>

udot    za.s[w8, 0], {z0.b, z1.b}, z0.b[0]  // 11000001-01010000-00010000-00110000
// CHECK-INST: udot    za.s[w8, 0, vgx2], { z0.b, z1.b }, z0.b[0]
// CHECK-ENCODING: [0x30,0x10,0x50,0xc1]
// CHECK-ERROR: instruction requires: sme2
// CHECK-UNKNOWN: c1501030 <unknown>

udot    za.s[w10, 5, vgx2], {z10.b, z11.b}, z5.b[1]  // 11000001-01010101-01010101-01110101
// CHECK-INST: udot    za.s[w10, 5, vgx2], { z10.b, z11.b }, z5.b[1]
// CHECK-ENCODING: [0x75,0x55,0x55,0xc1]
// CHECK-ERROR: instruction requires: sme2
// CHECK-UNKNOWN: c1555575 <unknown>

udot    za.s[w10, 5], {z10.b, z11.b}, z5.b[1]  // 11000001-01010101-01010101-01110101
// CHECK-INST: udot    za.s[w10, 5, vgx2], { z10.b, z11.b }, z5.b[1]
// CHECK-ENCODING: [0x75,0x55,0x55,0xc1]
// CHECK-ERROR: instruction requires: sme2
// CHECK-UNKNOWN: c1555575 <unknown>

udot    za.s[w11, 7, vgx2], {z12.b, z13.b}, z8.b[3]  // 11000001-01011000-01111101-10110111
// CHECK-INST: udot    za.s[w11, 7, vgx2], { z12.b, z13.b }, z8.b[3]
// CHECK-ENCODING: [0xb7,0x7d,0x58,0xc1]
// CHECK-ERROR: instruction requires: sme2
// CHECK-UNKNOWN: c1587db7 <unknown>

udot    za.s[w11, 7], {z12.b, z13.b}, z8.b[3]  // 11000001-01011000-01111101-10110111
// CHECK-INST: udot    za.s[w11, 7, vgx2], { z12.b, z13.b }, z8.b[3]
// CHECK-ENCODING: [0xb7,0x7d,0x58,0xc1]
// CHECK-ERROR: instruction requires: sme2
// CHECK-UNKNOWN: c1587db7 <unknown>

udot    za.s[w11, 7, vgx2], {z30.b, z31.b}, z15.b[3]  // 11000001-01011111-01111111-11110111
// CHECK-INST: udot    za.s[w11, 7, vgx2], { z30.b, z31.b }, z15.b[3]
// CHECK-ENCODING: [0xf7,0x7f,0x5f


 false, false)

  test("singletons"){
    Check(Singletons.Standalone, "Standalone")
    Check(Singletons.BB, "BB")
    Check(Singletons.CC, "CC")
    Check(Singletons.CC as Singletons.AA, "CC")
  }
  test("adts"){
      Check(
        ADTs.ADTb(123, "hello world"),
        """ADTb(123, "hello world")"""
      )

    Check(
      listOf(ADTs.ADTb(123, "hello world"), ADTs.ADTb(-999, "i am cow")),
      """List(ADTb(123, "hello world"), ADTb(-999, "i am cow"))"""
    )

    Check(ADTs.ADT0, "ADT0")
  }
  test("sealedHierarchies"){
      Check(
        DeepHierarchy.AnQ(1),
        "AnQ(1)"
      )
    Check(
      DeepHierarchy.AnQ(1) as DeepHierarchy.Q,
      "AnQ(1)"
    )
    Check(
      DeepHierarchy.E(false),
      "E(false)"
    )
    Check(
      DeepHierarchy.F(DeepHierarchy.AnQ(1)) as DeepHierarchy.A,
      "F(AnQ(1))"
    )
  }
  // Scenario doesn't exist in Kotlin
  // test("varargs"){
  //   import Varargs._
  //     Check(
  //       Sentence("omg", "2", "3"),
  //       """Sentence("omg", WrappedArray("2", "3"))""",
  //       """Sentence("omg", ArrayBuffer("2", "3"))""", // 2.10
  //       """Sentence("omg", ArraySeq("2", "3"))""", // 2.13
  //       """Sentence("omg", WrappedVarArgs("2", "3"))""" // Scala.JS 2.13
  //     )
  // }
  test("genericADTs"){
    Check(GenericADTs.DeltaHardcoded.Remove("omg"), """Remove("omg")""")
    Check(
      GenericADTs.Delta.Insert(listOf("omg", "wtf"), Pair(1, 0.2)),
    """Insert(List("omg", "wtf"), Pair(1, 0.2))""",
    """Insert(List("omg", "wtf"), Pair(1, 0.2F))""",
    """Insert(List("omg", "wtf"), Pair(1, 0.200000))"""
    )
    Check(
      GenericADTs.DeltaInvariant.Clear<Int, String>(),
      """Clear(1)"""
    )
    Check(
      GenericADTs.DeltaInvariant.Clear<Int, String>(),
      """Clear(1)"""
    )

    Check(
      GenericADTs.DeltaHardcoded.Remove(listOf(1, 2, 3)) as GenericADTs.DeltaHardcoded<kotlin.collections.List<Int>, String>,
      """Remove(List(1, 2, 3))"""
    )
    Check(
      GenericADTs.Delta.Insert(listOf("omg", "wtf"), Pair(1, 0.2)) as GenericADTs.Delta<List<String>, Pair<Int, Double>>,
    """Insert(List("omg", "wtf"), Pair(1, 0.2))""",
    """Insert(List("omg", "wtf"), Pair(1, 0.2F))""",
    """Insert(List("omg", "wtf"), Pair(1, 0.200000))"""
    )
    Check(
      GenericADTs.DeltaInvariant.Clear<Int, String>() as GenericADTs.DeltaInvariant<Int, String>,
      """Clear(1)"""
    )

  }

  test("fallback"){
    // make sure we can pprint stuff that looks nothing like a data class
    // by falling back to good old toString
    val a =  Amorphous.A()
    Check(a, a.toString())
    Check(a


b522495.aspx"
     * >http://msdn.microsoft.com/en-US/library/bb522495.aspx
     *
     * @param fields The fields that are part of the ROLLUP
     *            function
     * @return A field to be used in a GROUP BY clause
     */
    @NotNull
    @Support({ CLICKHOUSE, CUBRID, DUCKDB, MARIADB, MYSQL, POSTGRES, TRINO })
    public static GroupField rollup(FieldOrRow... fields) {
        return new Rollup(fields);
    }

    /**
     * Create a CUBE(field1, field2, .., fieldn) grouping field.
     *
     * @see #cube(Field...)
     */
    @NotNull
    @Support({ CLICKHOUSE, DUCKDB, POSTGRES, TRINO })
    public static GroupField cube(Field<?>... fields) {
        return cube((FieldOrRow[]) Tools.nullSafe(fields));
    }

    /**
     * Create a CUBE(field1, field2, .., fieldn) grouping field.
     *

     * Please check the SQL Server documentation for a very nice explanation of
     * CUBE, ROLLUP, and GROUPING SETS
     * clauses in grouping contexts: http://msdn.microsoft.com/en-US/library/bb522495.aspx
     *
     * @param fields The fields that are part of the CUBE
     *            function
     * @return A field to be used in a GROUP BY clause
     */
    @NotNull
    @Support({ CLICKHOUSE, DUCKDB, POSTGRES, TRINO })
    public static GroupField cube(FieldOrRow... fields) {
        return new Cube(fields);
    }

    /**
     * Create a GROUPING SETS(field1, field2, .., fieldn) grouping field where
     * each grouping set only consists of a single field.
     *

     * Please check the SQL Server documentation for a very nice explanation of
     * CUBE, ROLLUP, and GROUPING SETS
     * clauses in grouping contexts: http://msdn.microsoft.com/en-US/library/bb522495.aspx
     *
     * @param fields The fields that are part of the GROUPING SETS
     *            function
     * @return A field to be used in a GROUP BY clause
     */
    @NotNull
    @Support({ CLICKHOUSE, DUCKDB, POSTGRES, TRINO })
    public static GroupField groupingSets(Field<?>... fields) {
        List<Field<?>>[] array = map(fields, f -> asList(f), List[]::new);
        return groupingSets(array);
    }

    /**
     * Create a GROUPING SETS((field1a, field1b), (field2a), .., (fieldna,
     * fieldnb)) grouping field.
     *

     * Please check the SQL Server documentation for a very nice explanation of
     * CUBE, ROLLUP, and GROUPING SETS
     * clauses in grouping contexts: http://msdn.microsoft.com/en-US/library/bb522495.aspx
     *
     * @param fieldSets The fields that are part of the GROUPING SETS
     *            function
     * @return A field to be used in a GROUP BY clause
     */
    @NotNull
    @Support({ CLICKHOUSE, DUCKDB, POSTGRES, TRINO })
    public static GroupField groupingSets(Field<?>[]... fieldSets) {


und-image: url(data:image/svg+xml;base64,PHN2ZyB0PSIxNjQ5ODQzMjA5MjY3IiBjbGFzcz0iaWNvbiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHAtaWQ9Ijg0NzMiIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTcyNi42NTI4MDEgNDI5LjMwNTYwMyAyOTcuMzQ3MTk5IDQyOS4zMDU2MDMgNTEyLjE5MzQwNSA2MzguMTU2MjU4WiIgcC1pZD0iODQ3NCIgZmlsbD0iIzY2NjY2NiI+PC9wYXRoPjwvc3ZnPg==);
}
.gc-table-sheet-group-list .gc-table-sheet-cross-column-item-editing, .gc-table-sheet-cross-column-list .gc-table-sheet-cross-column-item-editing, .gc-table-sheet-cross-column-attributes-list .gc-table-sheet-cross-column-item-editing {
  height: initial;
}
.gc-table-sheet-group-list .gc-table-sheet-cross-column-item-editing .gc-table-sheet-cross-column-item-edit, .gc-table-sheet-cross-column-list .gc-table-sheet-cross-column-item-editing .gc-table-sheet-cross-column-item-edit, .gc-table-sheet-cross-column-attributes-list .gc-table-sheet-cross-column-item-editing .gc-table-sheet-cross-column-item-edit {
  background-image: url(data:image/svg+xml;base64,PHN2ZyB0PSIxNjQ5ODQzNzY1NTA5IiBjbGFzcz0iaWNvbiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHAtaWQ9Ijg4NjMiIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTI5Ny4zNDcxOTkgNjM4LjE1NjI1OCA3MjYuNjUyODAxIDYzOC4xNTYyNTggNTExLjgwNjU5NSA0MjkuMzA1NjAzWiIgcC1pZD0iODg2NCIgZmlsbD0iIzY2NjY2NiI+PC9wYXRoPjwvc3ZnPg==);
}
.gc-table-sheet-group-list .gc-table-sheet-cross-column-item-editing.selected .gc-table-sheet-cross-column-item-edit, .gc-table-sheet-cross-column-list .gc-table-sheet-cross-column-item-editing.selected .gc-table-sheet-cross-column-item-edit, .gc-table-sheet-cross-column-attributes-list .gc-table-sheet-cross-column-item-editing.selected .gc-table-sheet-cross-column-item-edit {
  background-image: url(data:image/svg+xml;base64,PHN2ZyB0PSIxNjQ5ODQzNzY1NTA5IiBjb


(
                padding: const EdgeInsets.only(bottom: 8),
                child: Text(
                  detail.instructions!,
                  style: Theme.of(context).textTheme.bodyMedium,
                ),
              ),

            Wrap(
              spacing: 16,
              runSpacing: 16,
              children: [
                _buildExerciseInfo(context, '组数', '${detail.sets} 组'),
                _buildExerciseInfo(context, '每组次数', detail.reps),
                _buildExerciseInfo(context, '单组耗时', '${detail.countdown} 秒'),
                _buildExerciseInfo(context, '组间休息', '${detail.restTime} 秒'),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 训练动作信息项
  Widget _buildExerciseInfo(BuildContext context, String label, String value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: Theme.of(context).textTheme.bodySmall?.copyWith(
            color: Theme.of(context).colorScheme.secondary,
          ),
        ),
        const SizedBox(height: 2),
        Text(
          value,
          style: Theme.of(
            context,
          ).textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w500),
        ),
      ],
    );
  }

  // 显示编辑对话框
  void _showEditDialog(
    BuildContext context,
    int day,
    List<TrainingPlanDetail> details,
  ) {
    // 判断屏幕宽度，决定使用弹窗还是新页面
    final screenWidth = MediaQuery.of(context).size.width;
    final viewModel = Provider.of<TrainingViewModel>(context, listen: false);

    if (screenWidth > 600) {
      // 桌面端或平板：使用弹窗
      showDialog(
        context: context,
        builder:
            (context) => Dialog(
              child: Container(
                width: screenWidth * 0.8,
                height: MediaQuery.of(context).size.height * 0.8,
                padding: const EdgeInsets.all(16),
                child: PlanDetailEditPage(
                  day: day,
                  details: List.from(details),
                  onSave: (updatedDetails) {
                    // 创建新的planDetails列表，替换当前日期的训练详情
                    final newPlanDetails = List<TrainingPlanDetail>.from(
                      planDetails,
                    );

                    // 移除当前日期的所有训练详情
                    newPlanDetails.removeWhere((detail) => detail.day == day);

                    // 添加更新后的训练详情
                    newPlanDetails.addAll(updatedDetails);

                    // 更新训练详情
                    viewModel.updatePlanDetails(plan.planId, newPlanDetails);
                  },
                ),
              ),
            ),
      );
    } else {
      // 移动端：使用新页面
      Navigator.of(context).push(
        MaterialPageRoute(
          builder:
              (context) => PlanDetailEditPage(
                day: day,
                details: List.from(details),
                onSave: (updatedDetails) {
                  // 创建新的planDetails列表，替换当前日期的训练详情
                  final newPlanDetails = List<TrainingPlan


-state-active{border-color:transparent #DDDDDD #DDDDDD #DDDDDD;}.ui-tabs.ui-tabs-bottom .ui-tabs-nav.ui-widget-header li{border-radius:0 0 4px 4px;}.ui-tabs.ui-tabs-bottom .ui-tabs-nav.ui-widget-header li.ui-state-active{margin-top:-1px;}.ui-tabs.ui-tabs-left .ui-tabs-nav.ui-widget-header{border-right:1px solid #DDDDDD;}.ui-tabs.ui-tabs-left{border-right:1px solid #DDDDDD;}.ui-tabs.ui-tabs-left .ui-tabs-nav.ui-widget-header li.ui-state-active{border-color:#DDDDDD transparent #DDDDDD #DDDDDD;}.ui-tabs.ui-tabs-left .ui-tabs-nav.ui-widget-header li{border-radius:4px 0 0 4px;}.ui-tabs.ui-tabs-left .ui-tabs-nav.ui-widget-header li.ui-state-active{margin-right:-1px;}.ui-tabs.ui-tabs-right .ui-tabs-nav.ui-widget-header{border-left:1px solid #DDDDDD;}.ui-tabs.ui-tabs-right{border-left:1px solid #DDDDDD;}.ui-tabs.ui-tabs-right .ui-tabs-nav.ui-widget-header li.ui-state-active{border-color:#DDDDDD #DDDDDD #DDDDDD transparent;}.ui-tabs.ui-tabs-right .ui-tabs-nav.ui-widget-header li{border-radius:0 4px 4px 0;}.ui-tabs.ui-tabs-right .ui-tabs-nav.ui-widget-header li.ui-state-active{margin-left:-1px;}/** AccordionPanel **/.ui-accordion .ui-accordion-header{background:transparent;box-shadow:none;}.ui-accordion .ui-accordion-header.ui-state-default{margin-bottom:2px;border:1px solid #E5E5E5;}.ui-accordion .ui-accordion-header.ui-state-active{margin-bottom:1px;}.ui-accordion .ui-accordion-header .ui-icon{display:none;}.ui-accordion .ui-accordion-header.ui-state-default a{padding:8px 15px;color:#0088CC;}.ui-accordion .ui-accordion-header a:hover{color:#005580;}.ui-accordion .ui-accordion-content.ui-widget-content{padding:9px 15px;}/* Breadcrumb */.ui-breadcrumb{padding:7px 14px;margin:0 0 18px;list-style:none;background-color:#fbfbfb;background-image:-moz-linear-gradient(top, #ffffff, #f5f5f5);background-image:-ms-linear-gradient(top, #ffffff, #f5f5f5);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f5f5f5));background-image:-webkit-linear-gradient(top, #ffffff, #f5f5f5);background-image:-o-linear-gradient(top, #ffffff, #f5f5f5);background-image:linear-gradient(top, #ffffff, #f5f5f5);background-repeat:repeat-x;border:1px solid #ddd;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ffffff', endColorstr='#f5f5f5', GradientType=0);-webkit-box-shadow:inset 0 1px 0 #ffffff;-moz-box-shadow:inset 0 1px 0 #ffffff;box-shadow:inset 0 1px 0 #ffffff;}.ui-breadcrumb li{display:inline-block;*display:inline;text-shadow:0 1px 0 #ffffff;*


nt": {
                "api_url": "http://localhost:8000",
                "client_url": "http://localhost:5173",
            },
            "local": {
                "api_url": self.remote_api_url,
                "client_url": self.remote_client_url,
            },
            "production": {
                "api_url": self.remote_api_url,
                "client_url": self.remote_client_url,
            },
        }
        return configs.get(self.environment, configs["development"])

    @property
    def api_url(self) -> str:
        """Get the API URL"""
        return self.config["api_url"]

    @property
    def client_url(self) -> str:
        """Get the client URL"""
        return self.config["client_url"]

    @property
    def remote_client_hostname(self) -> str:
        """Get the remote client hostname"""
        return urlparse(self.client_url).hostname or ""

    model_config = SettingsConfigDict(env_prefix="LILYPAD_")

def get_settings() -> Settings:
    """Cached settings instance"""
    return Settings()


#[cfg(any(feature = "v1_2", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_2")))]
    #[doc(alias = "nm_device_ip_tunnel_get_input_key")]
    #[doc(alias = "get_input_key")]
    pub fn input_key(&self) -> Option<glib::GString> {
        unsafe {
            from_glib_none(ffi::nm_device_ip_tunnel_get_input_key(
                self.to_glib_none().0,
            ))
        }
    }

    ///
    /// # Returns
    ///
    /// the local endpoint of the tunnel
    #[cfg(any(feature = "v1_2", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_2")))]
    #[doc(alias = "nm_device_ip_tunnel_get_local")]
    #[doc(alias = "get_local")]
    pub fn local(&self) -> Option<glib::GString> {
        unsafe { from_glib_none(ffi::nm_device_ip_tunnel_get_local(self.to_glib_none().0)) }
    }

    ///
    /// # Returns
    ///
    /// the tunneling mode
    #[cfg(any(feature = "v1_2", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_2")))]
    #[doc(alias = "nm_device_ip_tunnel_get_mode")]
    #[doc(alias = "get_mode")]
    pub fn mode(&self) -> IPTunnelMode {
        unsafe { from_glib(ffi::nm_device_ip_tunnel_get_mode(self.to_glib_none().0)) }
    }

    ///
    /// # Returns
    ///
    /// the key used for outgoing packets
    #[cfg(any(feature = "v1_2", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_2")))]
    #[doc(alias = "nm_device_ip_tunnel_get_output_key")]
    #[doc(alias = "get_output_key")]
    pub fn output_key(&self) -> Option<glib::GString> {
        unsafe {
            from_glib_none(ffi::nm_device_ip_tunnel_get_output_key(
                self.to_glib_none().0,
            ))
        }
    }

    ///
    /// # Returns
    ///
    /// the device's parent device
    #[cfg(any(feature = "v1_2", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_2")))]
    #[doc(alias = "nm_device_ip_tunnel_get_parent")]
    #[doc(alias = "get_parent")]
    pub fn parent(&self) -> Option<Device> {
        unsafe { from_glib_none(ffi::nm_device_ip_tunnel_get_parent(self.to_glib_none().0)) }
    }

    ///
    /// # Returns
    ///
    /// whether path MTU discovery is enabled
    #[cfg(any(feature = "v1_2", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_2")))]
    #[doc(alias = "nm_device_ip_tunnel_get_path_mtu_discovery")]
    #[doc(alias = "get_path_mtu_discovery")]
    pub fn is_path_mtu_discovery(&self) -> bool {
        unsafe {
            from_glib(ffi::nm_device_ip_tunnel_get_path_mtu_discovery


N, K = map(int, input().split())
belt = []
for j in map(int, input().split()):
    belt.append([j, 0])

# 내구도 0의 개수
zero_num = 0
count = 0
while zero_num < K:
    # 1. 벨트 회전
    new_belt = [[0, 0] for _ in range(2 * N)]
    for i in range(2 * N):
        if i == 2 * N - 1:
            new_belt[0] = belt[i]
        else:
            new_belt[i + 1] = belt[i]
    # 벨트 회전이 끝나고, N-1칸에 로봇이 있다면 제거
    if new_belt[N - 1][1] == 1:
        new_belt[N - 1][1] = 0

    # 2. 로봇 이동
    # 먼저 올라온 순서부터 진행
    # 즉, N-2 부터 시작해야 함!
    # 로봇이 있다면, 다음 칸에 로봇이 있는지 확인 후
    # 없다면 칸의 내구도가 1 이상일 때 움직인다.
    for r in range(N - 2,-1,-1):
        if new_belt[r][1] and not new_belt[r + 1][1] and new_belt[r + 1][0] > 0:
            new_belt[r][1], new_belt[r + 1][1] = new_belt[r + 1][1], new_belt[r][1]
            # new_belt[r][1] = 0
            # new_belt[r + 1][1] = 1
            new_belt[r + 1][0] -= 1
            if not new_belt[r + 1][0]:
                zero_num += 1
            if r + 1 == N - 1:
                new_belt[r + 1][1] = 0

    # 3. 0번 칸이 내구도가 0보다 클 때 그리고 로봇이 없을때,
    #    로봇을 올리고 내구도 -1
    if new_belt[0][0] > 0 and not new_belt[0][1]:
        new_belt[0][1] = 1
        new_belt[0][0] -= 1
        if not new_belt[0][0]:
            zero_num += 1

    belt = new_belt
    count += 1

print(count)