model/model.dart';

enum SignUpFieldsId {
  email,
  password,
  repeat_password,
  first_name,
  last_name,
  phone,
  country,
  city,
  state,
  zip,
  address,
  address2,
  undefined,
}

SignUpFieldsId signUpFieldsIdFromString(String? value) {
  return SignUpFieldsId.values.firstWhere(
    (e) => e.toString().split('.')[1].toUpperCase() == value?.toUpperCase(),
    orElse: () => SignUpFieldsId.undefined,
  );
}

extension SignUpFieldsIdToString on SignUpFieldsId {
  String toShortString() {
    return toString().split('.').last.toUpperCase();
  }
}

class SignUpField {
  const SignUpField({
    required this.id,
    required this.label,
    required this.required,
  });

  final SignUpFieldsId id;
  final String label;
  final bool required;

  factory SignUpField.fromJson(Map<String, dynamic> json) {
    return SignUpField(
      id: signUpFieldsIdFromString(json['id']),
      label: json['label'],
      required: json['required'],
    );
  }
}

class SignUpRequest {
  SignUpRequest({
    required this.fields,
    required this.recaptchaResponse,
    required this.pkgName,
    required this.platform,
    required this.appSecret,
  });

  final Map<SignUpFieldsId, String> fields;
  String recaptchaResponse;
  String pkgName;
  PlatformType platform;
  String appSecret;

  Map<String, dynamic> toJson() {
    final json = <String, dynamic>{
      'recaptchaResponse': recaptchaResponse,
      'pkgName': pkgName,
      'platform': platform.toShortString(),
      'appSecret': appSecret,
      'fields': fields.map((k, v) => MapEntry(k.toShortString(), v)),
    };

    return json;
  }
}

enum SignUpResult { SUCCESS, INACTIVE_USER_EXISTS }

SignUpResult signUpResultFromString(String value) {
  return SignUpResult.values.firstWhere(
    (e) => e.toString().split('.')[1].toUpperCase() == value.toUpperCase(),
  );
}
class ReportParams {
  final String? type;
  final String? state;
  final Map<String, dynamic>? timewindow;
  final String? timezone;

  ReportParams({this.type, this.state, this.timewindow, this.timezone});

  Map<String, dynamic> toJson() {
    var json = <String, dynamic>{};
    if (type != null) {
      json['type'] = type;
    }
    if (state != null) {
      json['state'] = state;
    }
    if (timewindow != null) {
      json['timewindow'] = timewindow;
    }
    if (timezone != null) {
      json['timezone'] = timezone;
    }
    return json;
  }
}

class ReportConfig extends ReportParams {
  final String baseUrl;
  final String dashboardId;
  final bool useDashboardTimewindow;
  final String namePattern;
  final bool? useCurrentUserCredentials;
  final String userId;

  ReportConfig(
      {required this.baseUrl,
      required this.dashboardId,
      required this.useDashboardTimewindow,
      required this.namePattern,
      required this.userId,
      this.useCurrentUserCredentials,
      String? type,
      String? state,
      Map<String, dynamic>? timewindow,
      String? timezone})
      : super(
            type: type,
            state: state,
            timewindow: timewindow,
            timezone: timezone);

  @override
  Map


OverrideHierarchy(): List<T> =
    (this as SirCallableDeclaration).getEntireOverrideHierarchy() as List<T>

fun SirCallableDeclaration.getEntireOverrideHierarchy(): List<SirCallableDeclaration> {
    if (this !is SirOverridableDeclaration<*>) return listOf(this)

    val visited = mutableSetOf<SirOverridableDeclaration<*>>()

    val open = mutableListOf(this)

    while (open.isNotEmpty()) {
        val next = open.pop()

        if (next in visited) continue

        visited += next

        open += next.overriddenDeclarations
        open += next.overriddenBy
    }

    return visited.toList()
}

fun <T : SirOverridableDeclaration<T>> T.applyToEntireOverrideHierarchy(action: T.() -> Unit) {
    getEntireOverrideHierarchy().forEach {
        it.action()
    }
}

fun <T : SirOverridableDeclaration<T>> T.addOverrides(vararg declarations: T) {
    addOverrides(declarations.toList())
}

fun <T : SirOverridableDeclaration<T>> T.addOverrides(declarations: List<T>) {
    declarations.forEach { addOverride(it) }
}

fun <T : SirOverridableDeclaration<T>> T.removeOverrides(vararg declarations: T) {
    removeOverrides(declarations.toList())
}

fun <T : SirOverridableDeclaration<T>> T.removeOverrides(declarations: List<T>) {
    declarations.forEach { removeOverride(it) }
}

fun <T : SirOverridableDeclaration<T>> T.addOverriddenBy(vararg declarations: T) {
    addOverriddenBy(declarations.toList())
}

fun <T : SirOverridableDeclaration<T>> T.addOverriddenBy(declarations: List<T>) {
    declarations.forEach { addOverriddenBy(it) }
}

fun <T : SirOverridableDeclaration<T>> T.removeOverriddenBy(vararg declarations: T) {
    removeOverriddenBy(declarations.toList())
}

fun <T : SirOverridableDeclaration<T>> T.removeOverriddenBy(declarations: List<T>) {
    declarations.forEach { removeOverriddenBy(it) }
}

val SirOverridableDeclaration<*>.isBaseDeclaration: Boolean
    get() = overriddenDeclarations.isEmpty()
/*
 * Copyright (C) 2018 Touchlab, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package co.touchlab.stately.concurrency

/**
 * Multiplatform AtomicReference implementation
 */
actual class AtomicReference<V> actual constructor(initialValue: V) {
    private var internalValue: V = initialValue

    /**
     * Compare current value with expected and set to new if they're the same. Note, 'compare' is checking
     * the actual object id, not 'equals'.
     */
    actual fun compareAndSet(expected: V, new: V): Boolean {
        return if (expected === internalValue) {
            internalValue = new
            true
        } else {
            false
        }
    }

    actual fun get(): V = internalValue

    actual fun set(value_: V) {
        internalValue = value_
    }
}
package co.touchlab.skie.sir.type.translation

import co.touchlab.skie.


Memory = (int)(gpuData.videoMemory / (1024 * 1024));

        //  Find and print driver version information
        //
        initReturnCode = GPUDetect::InitDxDriverVersion(&gpuData);
        if (gpuData.d3dRegistryDataAvailability) {
          char driverVersion[19] = {};
          GPUDetect::GetDriverVersionAsCString(&gpuData, driverVersion, _countof(driverVersion));

          specs_.driverVersionBasic = driverVersion;
          specs_.driverVersionDetail = std::to_string(gpuData.driverInfo.driverReleaseRevision);
        }
        else {
          specs_.driverVersionBasic = "-";
          specs_.driverVersionDetail = "-";
        }

        if (gpuData.vendorID == GPUDetect::INTEL_VENDOR_ID) {
          //
          // In DirectX, Intel exposes additional information through the driver that can be
          // obtained querying a special DX counter
          //

          // Populate the GPU architecture data with info from the counter, otherwise gpuDetect will
          // use the value we got from the Dx11 extension
          initReturnCode = GPUDetect::InitCounterInfo(&gpuData, device);
          if (initReturnCode == EXIT_SUCCESS) {
            gpu.coreClock = gpuData.maxFrequency;
          }
        }
        // Intel - GPUDetect

        specs_.gpus.push_back(gpu);
      }
      device->Release();
      adapter->Release();
    }
  }
}

void Recording::PopulateSystemSpecs()
{
  specs_ = {};

  // SMBIOS information - Motherboard and RAM
  ParseSMBIOS();

  // Registry information - CPU and OS and if needed, Motherboard
  ReadRegistry();

  // GPU information - AGS or NvAPI or GPUDetect
  GetGPUsInfo();
}

void Recording::Start()
{
  recording_ = true;
  processName_ = defaultProcessName_;
  accumulatedResultsPerProcess_.clear();

  if (recordAllProcesses_) {
    g_messageLog.LogInfo("Recording", "Capturing all processes");
    return;
  }

  processID_ = GetProcessFromWindow();
  if (!processID_ || processID_ == GetCurrentProcessId()) {
    g_messageLog.LogWarning("Recording", "No active process was found, capturing all processes");
    recordAllProcesses_ = true;
    return;
  }

  processName_ = GetProcessNameFromID(processID_);
  g_messageLog.LogInfo("Recording", L"Active Process found " + processName_);
  recordAllProcesses_ = false;
}

void Recording::Stop()
{
  PrintSummary();
  recording_ = false;
  processName_.clear();
  processID_ = 0;
}

bool Recording::IsRecording() const { return recording_; }

const std::wstring& Recording::GetProcessName() const { return processName_; }

void Recording::SetRecordingDirectory(const std::wstring& dir) { directory_ = dir; }

void Recording::SetRecordAllProcesses(bool recordAll) { recordAllProcesses_ = recordAll; }

bool Recording::GetRecordAllProcesses() { return recordAllProcesses_; }

const std::wstring& Recording::GetDirectory() { return directory_; }

void Recording::SetUserNote(const std::wstring& userNote) { userNote_ = userNote; }

DWORD Recording::GetProcessFromWindow()
{
  const auto window = GetForegroundWindow();
  if (!window) {
    g_messageLog.LogError("Recording", "No foreground window found");
    return 0;
  }

  DWORD processID = IsUWPWindow(window) ? GetUWPProcess(window) : GetProcess(window);
  return processID;
}

DWORD Recording::GetUWPProcess(HWND window)
{
  HRESULT hr = CoInitialize(NULL);
  if (hr == RPC_E_CHANGED_MODE) {
    g_messageLog.LogError("Recording", "GetUWPProcess: CoInitialize


VWD_M_SPECIAL_2_12",label="Opulent High Roller Waistcoat",Price=961},['11']={NameHash="DLC_MP_VWD_M_SPECIAL_2_11",label="Blue High Roller Waistcoat",Price=1036},['10']={NameHash="DLC_MP_VWD_M_SPECIAL_2_10",label="Mono High Roller Waistcoat",Price=653},['9']={NameHash="DLC_MP_VWD_M_SPECIAL_2_9",label="Camo High Roller Waistcoat",Price=966},['8']={NameHash="DLC_MP_VWD_M_SPECIAL_2_8",label="White High Roller Waistcoat",Price=1521}},['76']={['1']={NameHash="DLC_MP_EXEC_M_SPECIAL_3_1",label="DLC_MP_EXEC_M_SPECIAL_3_1",Price=996},['0']={NameHash="DLC_MP_EXEC_M_SPECIAL_3_0",label="DLC_MP_EXEC_M_SPECIAL_3_0",Price=1516},['3']={NameHash="DLC_MP_EXEC_M_SPECIAL_3_3",label="DLC_MP_EXEC_M_SPECIAL_3_3",Price=1201},['2']={NameHash="DLC_MP_EXEC_M_SPECIAL_3_2",label="DLC_MP_EXEC_M_SPECIAL_3_2",Price=1744},['5']={NameHash="DLC_MP_EXEC_M_SPECIAL_3_5",label="DLC_MP_EXEC_M_SPECIAL_3_5",Price=1074},['4']={NameHash="DLC_MP_EXEC_M_SPECIAL_3_4",label="DLC_MP_EXEC_M_SPECIAL_3_4",Price=1279},['7']={NameHash="DLC_MP_EXEC_M_SPECIAL_3_7",label="DLC_MP_EXEC_M_SPECIAL_3_7",Price=291},['6']={NameHash="DLC_MP_EXEC_M_SPECIAL_3_6",label="DLC_MP_EXEC_M_SPECIAL_3_6",Price=1245},['8']={NameHash="DLC_MP_EXEC_M_SPECIAL_3_8",label="DLC_MP_EXEC_M_SPECIAL_3_8",Price=673}},['86']={['1']={NameHash="DLC_MP_BIKER_M_SPECIAL_5_1",label="Brown Print T-Shirt",Price=1053},['0']={NameHash="DLC_MP_BIKER_M_SPECIAL_5_0",label="Brown Full Print T-Shirt",Price=1262},['3']={NameHash="DLC_MP_BIKER_M_SPECIAL_5_3",label="Black Print T-Shirt",Price=1290},['2']={NameHash="DLC_MP_BIKER_M_SPECIAL_5_2",label="Pink Full Print T-Shirt",Price=521},['5']={NameHash="DLC_MP_BIKER_M_SPECIAL_5_5",label="Brown SN Print T-Shirt",Price=1858},['4']={NameHash="DLC_MP_BIKER_M_SPECIAL_5_4",label="Gold SN Print T-Shirt",Price=127},['7']={NameHash="DLC_MP_BIKER_M_SPECIAL_5_7",label="Brown Geo PRB T-Shirt",Price=1693},['6']={NameHash="DLC_MP_BIKER_M_SPECIAL_5_6",label="Pink SN PRB T-Shirt",Price=104},['9']={NameHash="DLC_MP_BIKER_M_SPECIAL_5_9",label="Color Geo PRB T-Shirt",


:1},
			{f:[61,66],dx:1},{f:[61,66],dx:0},{f:[61,66],dx:0},{f:[61,66],dx:0},
			{f:[61,66],dx:0},{f:[61,66],dx:0},{f:[61,66],dx:0},
			{f:0,dx:0,k:'hold right'},
			{f:120},{f:120},{f:120},{f:120},{f:120}, //5 attacks losing 4 TU, 65 TU
			{f:121},{f:121,k:'att'},
			{f:122},{f:122},{f:122},{f:122},{f:122},
			{f:123},{f:123},{f:123},{f:123},{f:123},
			{f:121},{f:121,k:'att'},
			{f:122},{f:122},{f:122},{f:122},{f:122},
			{f:123},{f:123},{f:123},{f:123},{f:123},
			{f:121},{f:121,k:'att'},
			{f:122},{f:122},{f:122},{f:122},{f:122},
			{f:123},{f:123},{f:123},{f:123},{f:123},
			{f:121},{f:121,k:'att'},
			{f:122},{f:122},{f:122},{f:122},{f:122},
			{f:123},{f:123},{f:123},{f:123},{f:123},
			{f:121,k:'att'},
			{f:122},{f:122},{f:122},{f:122},{f:122},
			{f:123},{f:123},{f:123},{f:123},{f:123},
			{f:121},
			{f:0},{f:0}
		],
		[	//player 2
			{f:[0,1,2,3],k:'left'},{f:[0,1,2,3]},{f:[0,1,2,3]},{f:[0,1,2,3]},
			{f:220},{f:220},{f:220},{f:220},{f:220,dx:2},
			{f:221,dx:1},{f:221},{f:221},{f:221},
			{f:0},{f:[222,224]},{f:[222,224]},{f:[222,224]},{f:[222,224]},{f:[222,224],dx:2},
			{f:[223,225],dx:1},{f:[223,225]},{f:[223,225]},{f:[223,225]},
			{f:0},
			{f:226},{f:226},{f:226},{f:226},{f:226},{f:226},{f:226},
			{f:131},{f:131},{f:131},{f:131},{f:131},{f:131},
			{f:130},{f:130},{f:130},{f:130},{f:130},{f:130},{f:130},
			{f:132},{f:132},{f:132},{f:132},{f:132},
			{f:130},{f:130},{f:130},{f:130},{f:130},{f:130},{f:130},
			{f:132},{f:132},{f:132},{f:132},{f:132},
			{f:130},{f:130},{f:130},{f:130},{f:130},{f:130},{f:130},
			{f:132},{f:132},{f:132},{f:132},{f:132},
			{f:130},{f:130},{f:130},{f:130},{f:130},{f:130},{f:130},
			{f:132},{f:132},{f:132},{f:132},{f:132},
			{f:130},{f:130},{f:130},{f:130},{f:130},{f:130},
			{f:132},{f:132},{f:132},{f:132},{f:132},
			{f:181},{f:181,dx:4},{f:181,dx:3},
			{f:182,dx:3},{f:182,dx:3},
			{f:230,dx:3},{f


typedID := id.SeriesID()

			// Save max series identifier processed.
			hdr.MaxSeriesID, hdr.MaxOffset = untypedID, offset

			// Ignore entry if tombstoned.
			if index.IsDeleted(untypedID) {
				return nil
			}

			// Insert into maps.
			c.insertIDOffsetMap(idOffsetMap, hdr.Capacity, untypedID, offset)
			return c.insertKeyIDMap(keyIDMap, hdr.Capacity, segments, key, offset, id)
		}); err == errDone {
			break
		} else if err != nil {
			return err
		}
	}

	// Open file handler.
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer f.Close()

	// Calculate map positions.
	hdr.KeyIDMap.Offset, hdr.KeyIDMap.Size = SeriesIndexHeaderSize, int64(len(keyIDMap))
	hdr.IDOffsetMap.Offset, hdr.IDOffsetMap.Size = hdr.KeyIDMap.Offset+hdr.KeyIDMap.Size, int64(len(idOffsetMap))

	// Write header.
	if _, err := hdr.WriteTo(f); err != nil {
		return err
	}

	// Write maps.
	if _, err := f.Write(keyIDMap); err != nil {
		return err
	} else if _, err := f.Write(idOffsetMap); err != nil {
		return err
	}

	// Sync & close.
	if err := f.Sync(); err != nil {
		return err
	} else if err := f.Close(); err != nil {
		return err
	}

	return nil
}

func (c *SeriesPartitionCompactor) insertKeyIDMap(dst []byte, capacity int64, segments []*SeriesSegment, key []byte, offset int64, id SeriesIDTyped) error {
	mask := capacity - 1
	hash := rhh.HashKey(key)

	// Continue searching until we find an empty slot or lower probe distance.
	for i, dist, pos := int64(0), int64(0), hash&mask; ; i, dist, pos = i+1, dist+1, (pos+1)&mask {
		assert(i <= capacity, "key/id map full")
		elem := dst[(pos * SeriesIndexElemSize):]

		// If empty slot found or matching offset, insert and exit.
		elemOffset := int64(binary.BigEndian.Uint64(elem[:8]))
		elemID := NewSeriesIDTyped(binary.BigEndian.Uint64(elem[8:]))
		if elemOffset == 0 || elemOffset == offset {
			binary.BigEndian.PutUint64(elem[:8], uint64(offset))
			binary.BigEndian.PutUint64(elem[8:], id.RawID())
			return nil
		}

		// Read key at position & hash.
		elemKey := ReadSeriesKeyFromSegments(segments, elemOffset+SeriesEntryHeaderSize)
		elemHash := rhh.HashKey(elemKey)

		// If the existing elem has probed less than us, then swap places with
		// existing elem, and keep going to find another slot for that elem.
		if d := rhh.Dist(elemHash, pos, capacity); d < dist {
			// Insert current values.
			binary.BigEndian.PutUint64(elem[:8], uint64(offset))
			binary.BigEndian.PutUint64(elem[8:], id.RawID())

			// Swap with values in that position.
			hash, key, offset, id = elemHash, elemKey, elemOffset, elemID

			// Update current distance.
			dist = d
		}
	}
}

func (c *SeriesPartitionCompactor) insertIDOffsetMap(dst []byte, capacity int64, id SeriesID, offset int64) {
	mask := capacity - 1
	hash := rhh.HashUint64(id.RawID())

	// Continue searching until we find an empty slot or lower probe distance.
	for i, dist, pos := int64(0), int64(0), hash&mask; ; i, dist, pos = i+


 in fields.named.iter() {
						if export_status(&field.attrs) == ExportStatus::TestOnly { continue; }
						write!(w, "\n\t\t\t\t\t{}: ", field.ident.as_ref().unwrap()).unwrap();
						handle_field_b!(field, field.ident.as_ref().unwrap());
					}
					writeln!(w, "\n\t\t\t\t}}").unwrap();
					write!(w, "\t\t\t}}").unwrap();
				} else if let syn::Fields::Unnamed(fields) = &var.fields {
					if !empty_tuple_variant || !$to_c {
						write!(w, " (").unwrap();
						for (idx, field) in fields.unnamed.iter().enumerate() {
							write!(w, "\n\t\t\t\t\t").unwrap();
							handle_field_b!(field, &format_ident!("{}", ('a' as u8 + idx as u8) as char));
						}
						writeln!(w, "\n\t\t\t\t)").unwrap();
					}
					write!(w, "\t\t\t}}").unwrap();
				}
				writeln!(w, ",").unwrap();
			}
			writeln!(w, "\t\t}}\n\t}}").unwrap();
		}
	}

	write_conv!(format!("to_native(&self) -> native{}", e.ident), false, true);
	write_conv!(format!("into_native(self) -> native{}", e.ident), false, false);
	write_conv!(format!("from_native(native: &native{}) -> Self", e.ident), true, true);
	write_conv!(format!("native_into(native: native{}) -> Self", e.ident), true, false);
	writeln!(w, "}}").unwrap();

	if needs_free {
		writeln!(w, "/// Frees any resources used by the {}", e.ident).unwrap();
		writeln!(w, "#[no_mangle]\npub extern \"C\" fn {}_free(this_ptr: {}) {{ }}", e.ident, e.ident).unwrap();
	}
	writeln!(w, "/// Creates a copy of the {}", e.ident).unwrap();
	writeln!(w, "#[no_mangle]").unwrap();
	writeln!(w, "pub extern \"C\" fn {}_clone(orig: &{}) -> {} {{", e.ident, e.ident, e.ident).unwrap();
	writeln!(w, "\torig.clone()").unwrap();
	writeln!(w, "}}").unwrap();
	w.write_all(&constr).unwrap();
	write_cpp_wrapper(cpp_headers, &format!("{}", e.ident), needs_free, None);
}

fn writeln_fn<'a, 'b, W: std::io::Write>(w: &mut W, f: &'a syn::ItemFn, types: &mut TypeResolver<'b, 'a>) {
	match export_status(&f.attrs) {
		ExportStatus::Export => {},
		ExportStatus::NoExport|ExportStatus::TestOnly => return,
		ExportStatus::NotImplementable => panic!("(C-not implementable) must only appear on traits"),
	}
	let mut gen_types = GenericTypes::new(None);
	if !gen_types.learn_generics(&f.sig.generics, types) { return; }

	writeln_fn_docs(w, &f.attrs, "", types, Some(&gen_types), f.sig.inputs.iter(), &f.sig.output);

	write!(w, "#[no_mangle]\npub extern \"C\" fn {}(", f.sig.ident).unwrap();
	write_method_params(w, &f.sig, "", types, Some(&gen_types), false, true);
	write!(w, " {{\n\t").unwrap();
	write_method_var_decl_body(w, &f.sig, "", types, Some(&gen_types), false);
	write!(w, "{}::{}(", types.module_path, f.sig.ident).unwrap();
	write_method_


char vector with each syllable.

convertHangulStringToJamos("R는 많은 공헌자에의한 공동 프로젝트입니다")

##  [1] "R"      "ㄴㅡㄴ" " "      "ㅁㅏㄶ" "ㅇㅡㄴ" " "      "ㄱㅗㅇ"
##  [8] "ㅎㅓㄴ" "ㅈㅏ"   "ㅇㅔ"   "ㅇㅢ"   "ㅎㅏㄴ" " "      "ㄱㅗㅇ"
## [15] "ㄷㅗㅇ" " "      "ㅍㅡ"   "ㄹㅗ"   "ㅈㅔㄱ" "ㅌㅡ"   "ㅇㅣㅂ"
## [22] "ㄴㅣ"   "ㄷㅏ"

convertHangulStringToKeyStrokes

Hangul string to keyboard strokes(2-bul). Strokes char will be full-width ascii character.

convertHangulStringToKeyStrokes("R는 많은 공헌자에의한 공동 프로젝트입니다")

##  [1] "R"        "ｓｍｓ"   " "        "ａｋｓｇ" "ｄｍｓ"   " "
##  [7] "ｒｈｄ"   "ｇｊｓ"   "ｗｋ"     "ｄｐ"     "ｄｍｌ"   "ｇｋｓ"
## [13] " "        "ｒｈｄ"   "ｅｈｄ"   " "        "ｖｍ"     "ｆｈ"
## [19] "ｗｐｒ"   "ｘｍ"     "ｄｌｑ"   "ｓｌ"     "ｅｋ"

HangulAutomata

Convert from Jamo(or keystroke) s


    );
  }
  return apiFileCode;
}

String preprocessPartFile(String source, String libraryName) {
  return 'part of $libraryName;\n$source';
}

/// Responsible for performing string replacements.
abstract class Replacer {
  /// Performs the replacement in the provided [text].
  String perform(String text);
}

/// Replaces all occurrences of a pattern with a fixed string.
class AllReplacer implements Replacer {
  /// Creates a new tuple with the given [pattern] and [replacement] string.
  AllReplacer(this._pattern, this._replacement);

  /// The pattern to be replaced.
  final Pattern _pattern;

  /// The replacement string.
  final String _replacement;

  @override
  String perform(String text) {
    return text.replaceAll(_pattern, _replacement);
  }
}

/// Uses a callback to replace each occurrence of a pattern.
class MappedReplacer implements Replacer {
  MappedReplacer(this._pattern, this._replace);

  /// The pattern to be replaced.
  final RegExp _pattern;

  /// A callback to replace each occurrence of [_pattern].
  final String Function(Match match) _replace;

  @override
  String perform(String text) {
    return text.replaceAllMapped(_pattern, _replace);
  }
}
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of dart.ui;

/// An opaque object representing a composited scene.
///
/// To create a Scene object, use a [SceneBuilder].
///
/// Scene objects can be displayed on the screen using the [FlutterView.render]
/// method.
abstract class Scene {
  /// Synchronously creates a handle to an image from this scene.
  ///
  /// {@macro dart.ui.painting.Picture.toImageSync}
  Image toImageSync(int width, int height);

  /// Creates a raster image representation of the current state of the scene.
  ///
  /// This is a slow operation that is performed on a background thread.
  ///
  /// Callers must dispose the [Image] when they are done with it. If the result
  /// will be shared with other methods or classes, [Image.clone] should be used
  /// and each handle created must be disposed.
  Future<Image> toImage(int width, int height);

  /// Releases the resources used by this scene.
  ///
  /// After calling this function, the scene is cannot be used further.
  ///
  /// This can't be a leaf call because the native function calls Dart API
  /// (Dart_SetNativeInstanceField).
  void dispose();
}

@pragma('vm:entry-point')
base class _NativeScene extends NativeFieldWrapperClass1 implements Scene {
  /// This class is created by the engine, and should not be instantiated
  /// or extended directly.
  ///
  /// To create a Scene object, use a [SceneBuilder].
  @pragma('vm:entry-point')
  _NativeScene._();

  @override
  Image toImageSync(int width, int height) {
    if (width <= 0 || height <= 0) {
      throw Exception('Invalid image dimensions.');
    }

    final _Image image = _Image._();
    final String? result =  _toImageSync(width, height, image);
    if (result != null) {
      throw PictureRasterizationException._(result);
    }
    return Image._(image, image.width, image.height);
  }

  @Native<Handle Function(Pointer<Void>, Uint32, Uint32, Handle)>(symbol: 'Scene::toImageSync')
  external String? _toImageSync(int width, int height, _Image outImage);

  @override
  Future<Image> toImage(int width, int height) {
    if (width <= 0 || height <= 0) {
      throw Exception('Invalid image dimensions.');
    }
    return _futurize((_Callback<Image?> callback) => _toImage(width, height,


'z':
                    Label1.Text += "_";
                    break;
            }
        }

        private void Label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            switch (e.KeyChar)
            {
                case '(':
                    label2.Text += "a";
                    break;
                case '%':
                    label2.Text += "b";
                    break;
                case '[':
                    label2.Text += "c";
                    break;
                case '|':
                    label2.Text += "d";
                    break;
                case ']':
                    label2.Text += "]";
                    break;
                case '.':
                    label2.Text += "f";
                    break;
                case ';':
                    label2.Text += "g";
                    break;
                case ':':
                    label2.Text += "h";
                    break;
                case '{':
                    label2.Text += "i";
                    break;
                case '`':
                    label2.Text += "j";
                    break;
                case '~':
                    label2.Text += "k";
                    break;
                case '-':
                    label2.Text += "l";
                    break;
                case 'm':
                    label2.Text += "=";
                    break;
                case '^':
                    label2.Text += "n";
                    break;
                case '&':
                    label2.Text += "o";
                    break;
                case '?':
                    label2.Text += "p";
                    break;
                case '+':
                    label2.Text += "q";
                    break;
                case '}':
                    label2.Text += "r";
                    break;
                case '/':
                    label2.Text += "s";
                    break;
                case '<':
                    label2.Text += "t";
                    break;
                case '>':
                    label2.Text += "u";
                    break;
                case '*':
                    label2.Text += "v";
                    break;
                case '!':
                    label2.Text += "w";
                    break;
                case '@':
                    label2.Text += "x";
                    break;
                case '#':
                    label2.Text += "y";
                    break;
                case '_':
                    label2.Text += "z";
                    break;
            }
        }
    }
}


    width: 258px;
  }
  .bs-docs-sidenav > li > a {
    width: 230px \9; /* Override the previous IE8-9 hack */
  }
}

/* Desktop
------------------------- */
@media (max-width: 980px) {
  /* Unfloat brand */
  body > .navbar-fixed-top .brand {
    float: left;
    margin-left: 0;
    padding-left: 10px;
    padding-right: 10px;
  }

  /* Inline-block quick links for more spacing */
  .quick-links li {
    display: inline-block;
    margin: 5px;
  }

  /* When affixed, space properly */
  .bs-docs-sidenav {
    top: 0;
    width: 218px;
    margin-top: 30px;
    margin-right: 0;
  }
}

/* Tablet to desktop
------------------------- */
@media (min-width: 768px) and (max-width: 979px) {
  /* Remove any padding from the body */
  body {
    padding-top: 0;
  }
  /* Widen masthead and social buttons to fill body padding */
  .jumbotron {
    margin-top: -20px; /* Offset bottom margin on .navbar */
  }
  /* Adjust sidenav width */
  .bs-docs-sidenav {
    width: 166px;
    margin-top: 20px;
  }
  .bs-docs-sidenav.affix {
    top: 0;
  }
}

/* Tablet
------------------------- */
@media (max-width: 767px) {
  /* Remove any padding from the body */
  body {
    padding-top: 0;
  }

  /* Widen masthead and social buttons to fill body padding */
  .jumbotron {
    padding: 40px 20px;
    margin-top:   -20px; /* Offset bottom margin on .navbar */
    margin-right: -20px;
    margin-left:  -20px;
  }
  .masthead h1 {
    font-size: 90px;
  }
  .masthead p,
  .masthead .btn {
    font-size: 24px;
  }
  .marketing .span4 {
    margin-bottom: 40px;
  }
  .bs-docs-social {
    margin: 0 -20px;
  }

  /* Space out the show-grid examples */
  .show-grid [class*="span"] {
    margin-bottom: 5px;
  }

  /* Sidenav */
  .bs-docs-sidenav {
    width: auto;
    margin-bottom: 20px;
  }
  .bs-docs-sidenav.affix {
    position: static;
    width: auto;
    top: 0;
  }

  /* Unfloat the back to top link in footer */
  .footer {
    margin-left: -20px;
    margin-right: -20px;
    padding-left: 20px;
    padding-right: 20px;
  }
  .footer p {
    margin-bottom: 9px;
  }
}

/* Landscape phones
------------------------- */
@media (max-width: 480px) {
  /* Remove padding above jumbotron */
  body {
    padding-top: 0;
  }

  /* Change up some type stuff */
  h2 small {
    display: block;
  }

  /* Downsize the jumbotrons */
  .jumbotron h1 {
    font-size: 45px;
  }
  .jumbotron p,
  .jumbotron .btn {
    font-size: 18px;
  }
  .jumbotron .btn {
    display: block;
    margin: 0 auto;
  }

  /* center align subhead text like


#pragma once

#include <Interpreters/Context_fwd.h>
#include <Processors/IProcessor.h>
#include <QueryPipeline/QueryPlanResourceHolder.h>

namespace DB
{

/// Has one unconnected input port and one unconnected output port.
/// There may be other ports on the processors, but they must all be connected.
/// The unconnected input must be on the first processor, output - on the last.
/// The processors don't necessarily form an actual chain.
class Chain
{
public:
    Chain() = default;
    Chain(Chain &&) = default;
    Chain(const Chain &) = delete;

    Chain & operator=(Chain &&) = default;
    Chain & operator=(const Chain &) = delete;

    explicit Chain(ProcessorPtr processor);
    explicit Chain(std::list<ProcessorPtr> processors);

    bool empty() const { return processors.empty(); }

    size_t getNumThreads() const { return num_threads; }
    void setNumThreads(size_t num_threads_) { num_threads = num_threads_; }

    bool getConcurrencyControl() const { return concurrency_control; }
    void setConcurrencyControl(bool concurrency_control_) { concurrency_control = concurrency_control_; }

    void addSource(ProcessorPtr processor);
    void addSink(ProcessorPtr processor);
    void appendChain(Chain chain);

    IProcessor & getSource();
    IProcessor & getSink();

    InputPort & getInputPort() const;
    OutputPort & getOutputPort() const;

    const Block & getInputHeader() const { return getInputPort().getHeader(); }
    const Block & getOutputHeader() const { return getOutputPort().getHeader(); }

    const std::list<ProcessorPtr> & getProcessors() const { return processors; }
    static std::list<ProcessorPtr> getProcessors(Chain chain) { return std::move(chain.processors); }

    void addTableLock(TableLockHolder lock) { holder.table_locks.emplace_back(std::move(lock)); }
    void addStorageHolder(StoragePtr storage) { holder.storage_holders.emplace_back(std::move(storage)); }
    void addInterpreterContext(ContextPtr context) { holder.interpreter_context.emplace_back(std::move(context)); }

    void attachResources(QueryPlanResourceHolder holder_)
    {
        /// This operator "=" actually merges holder_ into holder, doesn't replace.
        holder = std::move(holder_);
    }
    QueryPlanResourceHolder detachResources() { return std::move(holder); }

    void reset();

private:
    QueryPlanResourceHolder holder;

    /// -> source -> transform -> ... -> transform -> sink ->
    ///  ^        ->           ->     ->           ->       ^
    ///  input port                               output port
    std::list<ProcessorPtr> processors;
    size_t num_threads = 0;
    bool concurrency_control = false;
};

}


具 | 分层多智能体框架 |
| **主要输入** | 屏幕截图 | 屏幕截图 \+ 长期记忆 (技巧与捷径) |
| **规划机制** | 自我规划 (迭代式) | 管理者进行高层规划，操作员进行低层执行 |
| **学习机制** | 自我反思 (即时错误纠正) | 自我进化模块 (通过技巧与捷径从经验中学习) |
| **关键创新** | 以视觉为中心的操作，无需XML等系统文件；适应性强 | 处理复杂/长时程任务；从过往经验中学习；分层协作 |
| **解决的局限性** | (相对Mobile-Agent-E而言) 对复杂任务和经验学习支持较弱 | 解决了先前智能体在处理真实世界需求、推理密集型/长时程任务以及缺乏经验学习机制的问题 |

## **3\. 架构深度解析：核心技术与机制**

MOBILE-AGENT系列智能体的核心运作依赖于一系列精密协调的技术模块，涵盖视觉感知、规划决策、行动执行以及学习适应等多个层面。

### **3.1 视觉感知与场景理解**

视觉感知是MOBILE-AGENT和Mobile-Agent-E与移动设备GUI交互的基础。

#### **3.1.1 文本定位**

两个系统都利用光学字符识别（OCR）工具来检测和定位屏幕上的文本元素 4。在MOBILE-AGENT中，当屏幕上出现多个相同的文本实例时，系统会裁剪这些文本框周围的区域，并将它们提交给GPT-4V等多模态大语言模型进行判断，以选择正确的交互目标 5。这种方法巧妙地结合了专用视觉模型的高效识别能力和大型语言模型的上下文理解与推理能力。

#### **3.1.2 图标定位**

对于图标的定位，MOBILE-AGENT采用了一种多阶段流程：首先，它请求大语言模型（如GPT-4V）描述目标图标的属性（例如形状、颜色）；然后，利用如Grounding DINO这样的模型来识别屏幕截图中所有的图标；最后，通过CLIP（Contrastive Language–Image Pre-training）模型计算每个检测到的图标与语言模型生成的描述之间的相似度，选择相似度最高的图标作为交互对象 4。这个复杂的过程展示了为解决非平凡的视觉定位任务而设计的精细


        }

        runTasksUntilComplete();

        std::vector<int> returnValues = getReturnValues();
        ASSERT_EQ(inputs.size(), returnValues.size());
        for (uint32_t i = 0; i < inputs.size(); i++) {
            ASSERT_EQ(inputs[i], returnValues[i]);
        }
    }
};

TEST_P(CoroReturnValueChecker_Int, Run) { run(); }

INSTANTIATE_TEST_SUITE_P(
    CoroReturnValueChecker_Int, CoroReturnValueChecker_Int,
    ::testing::Values(ReturnValueCheckerParams{5, JUST_RETURN},
                      ReturnValueCheckerParams{5, SUSPEND_AND_RETURN},
                      ReturnValueCheckerParams{5, CHAINED_CALL_AND_RETURN}),
    ReturnValueCheckerParams::PrintToStringParamName());

#include <array>
#include <cassert>
#include <iostream>

#include "coroutine_test_base.h"

template <int call_depth>
task<void> ChainedCoroCall(int *callLevelCounter) {
    (*callLevelCounter)++;

    const int currentLevel = *callLevelCounter;

    // std::cout << *callLevelCounter <<std::endl;

    co_await std::experimental::suspend_always{};
    co_await ChainedCoroCall<call_depth - 1>(callLevelCounter);
    co_await std::experimental::suspend_always{};

    assert(*callLevelCounter == currentLevel);

    (*callLevelCounter)--;
    co_return;
}

template <>
task<void> ChainedCoroCall<0>(int *callLevelCounter) {
    (*callLevelCounter)++;

    const int currentLevel = *callLevelCounter;

    co_await std::experimental::suspend_always{};

    assert(*callLevelCounter == currentLevel);

    (*callLevelCounter)--;
    co_return;
}

class CoroResumeOrderTest : public CoroutineTestBase<void> {
   public:
    void run() {
        std::array<int, 5> callLevelCounters = {0};

        addTask(ChainedCoroCall<7>(&callLevelCounters[0]));
        addTask(ChainedCoroCall<9>(&callLevelCounters[1]));
        addTask(ChainedCoroCall<0>(&callLevelCounters[2]));
        addTask(ChainedCoroCall<1>(&callLevelCounters[3]));
        addTask(ChainedCoroCall<3>(&callLevelCounters[4]));

        runTasksUntilComplete();
    }
};

TEST_F(CoroResumeOrderTest, Run) { run(); }

#include <gtest/gtest.h>

#include <sm-coroutine.h>

using namespace ermia::dia;

task<void> CoroutineCall_LevelThree(int *counter) {
    (*counter)++;

    co_await std::experimental::suspend_always{};

    (*counter)--;
    co_return;
}

task<void> CoroutineCall_LevelTwo(int *counter) {
    (*counter)++;

    co_await CoroutineCall_LevelThree(counter);

    co_await std::experimental::suspend_always{};

    (*counter)--;
    co_return;
}

task<void> CoroutineCall_LevelOne(int *counter) {
    (*counter)++;

    co_await std::experimental::suspend_always{};

    co_await CoroutineCall_LevelTwo(counter);

    (*counter)--;
    co_return;
}

TEST(CoroutineSuspendOrder, FixedLogic) {
    coro_task_private::memory_pool memory_pool;

    int counter = 0;
    task<void> future_task = Cor


 "256 MB",
        /* 12*/ "512 MB",
        /* 13*/ "1 GB",
        /* 14*/ "1.5MB",
        /* 15*/ "1.8MB",
        /* 16*/ "2 GB",
        /* 17*/ "384 MB",
        /* 18*/ "768 MB",
        /* 19*/ "1.5 GB",
        /* 20*/ "2.5 GB",
        /* 21*/ "3 GB"
};

static unsigned long memsizes[] = {
        /* 0 */ 0,
        /* 1 */ 0x00040000, /* 256K */
        /* 2 */ 0x00080000, /* 512K */
        /* 3 */ 0x00100000, /* 1M */
        /* 4 */ 0x00200000, /* 2M */
        /* 5 */ 0x00400000, /* 4M */
        /* 6 */ 0x00800000, /* 8M */
        /* 7 */ 0x01000000, /* 16M */
        /* 8 */ 0x02000000, /* 32M */
        /* 9 */ 0x04000000, /* 64M */
        /* 10*/ 0x08000000, //128M
        /* 11*/ 0x10000000, //256M
        /* 12*/ 0x20000000, //512M
        /* 13*/ 0x40000000, //1GB
        /* 14*/ 0x00180000, //1.5MB
        /* 15*/ 0x001C0000, //1.8MB
        /* 16*/ 0x80000000, //2GB
        /* 17*/ 0x18000000, //384M
        /* 18*/ 0x30000000, //768M
        /* 19*/ 0x60000000, //1.5GB
        /* 20*/ 0xA8000000, //2.5GB
        /* 21*/ 0xC0000000, //3GB
};

static int msi_chip[] = { 1, 2, 3, 14, 4, 5, 6 };
static int msi_bogo[] = { 0, 2, 3, 14, 15 };
static int msi_fast[] = { 0, 3, 4, 5, 6 };
static int msi_z3fast[] = { 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 17, 12, 18, 13, 19, 16, 20, 21 };
static int msi_z3chip[] = { 0, 7, 8, 9, 10, 11, 12, 13 };
static int msi_gfx[] = { 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };

puae_MainWindow::puae_MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::puae_MainWindow)
{
    ui->setupUi(this);

    QString myPath;
    myPath = QDir::currentPath ();

    // Paths Tab
    PATHS_ROM = myPath;
    PATHS_CONFIG = myPath;
    PATHS_SCREENSHOT = myPath;
    PATHS_SAVESTATE = myPath;
    PATHS_AVIOUTPUT = myPath;
    PATHS_SAVEIMAGE = myPath;
    PATHS_RIP = myPath;

    workprefs = currprefs;
    // USER
	values_to_expansiondlg ();
	enable_for_expansiondlg ();

	values_to_memorydlg ();
	enable_for_memorydlg ();

	values_to_cpudlg ();
	enable_for_cpudlg ();

	values_to_sounddlg ();
	enable_for_sounddlg ();

	enable_for_inputdlg ();
	values_to_inputdlg ();

	values_to_displaydlg ();
	enable_for_displaydlg ();

	values_to_chipsetdlg ();
	enable_for_chipsetdlg ();

	values_to_chipsetdlg2 ();
	enable_for_chipsetdlg2 ();

	values_to_miscdlg ();
	enable_for_miscdlg ();
}

puae_MainWindow::~puae_MainWindow()
{
    delete ui;
}

//
//
//
QString puae_MainWindow::GetPath(QWidget *who, QString what, QString where)
{
    QString path = QFileDialog::getExistingDirectory(who, what, where, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

    if ( pa


xId);
    final eurXAsset =
        assets.firstWhereOrNull((asset) => asset.id == liquid.eurXId);
    final mexasAsset =
        assets.firstWhereOrNull((asset) => asset.id == liquid.mexasId);
    final usdtLiquidAsset =
        assets.firstWhereOrNull((asset) => asset.isUsdtLiquid);

    return switch (asset.id) {
      _ when (asset.isBTC) => [lbtcAsset!],
      _ when (asset.isLBTC) => [
          btcAsset!,
          if (usdtLiquidAsset != null) usdtLiquidAsset,
          if (depixAsset != null) depixAsset,
          if (eurXAsset != null) eurXAsset,
          if (mexasAsset != null) mexasAsset,
        ],
      _ when (asset.isUsdtLiquid) => [lbtcAsset!],
      _ when (asset.id == liquid.depixId || asset.id == liquid.eurXId) => [
          lbtcAsset!
        ],
      _ => [],
    };
  }
}
import 'package:aqua/data/models/gdk_models.dart';
import 'package:aqua/data/provider/formatter_provider.dart';
import 'package:aqua/features/settings/settings.dart';
import 'package:aqua/features/shared/shared.dart';
import 'package:aqua/features/sideswap/swap.dart';
import 'package:aqua/utils/utils.dart';

final pegDetailsProvider = AutoDisposeNotifierProviderFamily<PegDetailsNotifier,
    SwapSuccessModel, PegStateSuccess>(PegDetailsNotifier.new);

class PegDetailsNotifier
    extends AutoDisposeFamilyNotifier<SwapSuccessModel, PegStateSuccess> {
  @override
  SwapSuccessModel build(PegStateSuccess arg) {
    final GdkNewTransactionReply transaction = arg.txn;

    final assets = ref.read(assetsProvider).asData?.value ?? [];

    final fee = transaction.fee ?? 0;
    final received = (transaction.satoshi![arg.asset.id] as int).abs();
    final delivered = received + fee;

    final deliveredAsset =
        assets.firstWhere((asset) => asset.id == arg.asset.id);
    final receivedAsset = assets.firstWhere(
        (asset) => deliveredAsset.isBTC ? asset.isLBTC : asset.isBTC);
    final feeAsset = assets.firstWhere(
        (asset) => deliveredAsset.isBTC ? asset.isBTC : asset.isLBTC);

    final formattedDelivered =
        ref.read(formatterProvider).formatAssetAmountDirect(
              amount: delivered,
              precision: deliveredAsset.precision,
            );
    final formattedReceived =
        ref.read(formatterProvider).formatAssetAmountDirect(
              amount: received,
              precision: receivedAsset.precision,
            );
    final formattedFee = ref.read(formatterProvider).formatAssetAmountDirect(
          amount: fee,
          precision: feeAsset.precision,
        );
    final feeText = '$formattedFee ${feeAsset.ticker}';
    final receivedTicker = receivedAsset.ticker;
    final transactionId = transaction.txhash ?? '-';
    final rate =
        deliveredAsset.isLBTC ? delivered / received : received / delivered;
    final currentRate = rate.toStringAsFixed(rate > 10000 ? 2 : 8);
    final deliveredTicker = deliveredAsset.ticker;
    final feeRate = '1 $deliveredTicker = $currentRate $receivedTicker';

    final timestamp = transaction.createdAt?.microsecondsSinceEpoch;
    final formattedDate = timestamp != null
        ? DateTime.fromMicrosecondsSinceEpoch(timestamp).ddMMMMyyyy()
        : '-';
    final formattedTime = timestamp != null
        ? DateTime.fromMicrosecondsSinceEpoch(timestamp).HHmma()
        : '-';

    return SwapSuccessModel(
      date: formattedDate,
      time: formattedTime,
      deliverAmount: formattedDelivered,
      receive


0, margin5, 0);
            if (isNoimalScene()) {
                show();
            } else {
                //非常规场景不处理
                hide();
            }
        }
    }

    @Override
    public void onPlayerScene(int playerScene) {
        findViewById(R.id.controller_progress).setVisibility(isListPlayerScene() ?View.GONE:View.VISIBLE);
        //当播放器和控制器在专场播放、场景发生变化时，仅当在常规模式下并且正在播放才显示控制器
        if(isNoimalScene()){
            show();
            if(isPlaying()){
                showControl(false);
                reStartDelayedRunnable();
            }
        }else{
            hide();
        }
    }

    @Override
    public void onProgress(long currentDurtion, long totalDurtion) {
        if(null!=mSeekBar&&null!=mControlWrapper){
            if(null!=mProgressBar&&mProgressBar.getMax()==0){
                mProgressBar.setMax((int) (mControlWrapper.getPreViewTotalDuration() >0? mControlWrapper.getPreViewTotalDuration() :totalDurtion));
            }
            if(null!=mSeekBar){
                if(mSeekBar.getMax()<=0){//总进度总时长只更新一次,如果是虚拟的总时长,则在setViewTotalDuration中更新总时长
                    mSeekBar.setMax((int) (mControlWrapper.getPreViewTotalDuration() >0? mControlWrapper.getPreViewTotalDuration() :totalDurtion));
                    if(null!=mTotalDuration) mTotalDuration.setText(PlayerUtils.getInstance().stringForAudioTime(mControlWrapper.getPreViewTotalDuration() >0? mControlWrapper.getPreViewTotalDuration() :totalDurtion));
                }
                if(!isTouchSeekBar) mSeekBar.setProgress((int) currentDurtion);
            }
        }
    }

    @Override
    public void onBuffer(int bufferPercent) {
        if(null!= mControlWrapper){
            int percent = PlayerUtils.getInstance().formatBufferPercent(bufferPercent, mControlWrapper.getDuration());
            if(null!= mSeekBar&&mSeekBar.getSecondaryProgress()!=percent) {
                mSeekBar.setSecondaryProgress(percent);
            }
            if(null!= mProgressBar&&mProgressBar.getSecondaryProgress()!=percent) {
                mProgressBar.setSecondaryProgress(percent);
            }
        }
    }

    @Override
    public void onMute(boolean isMute) {
        ImageView muteImage = (ImageView) findViewById(R.id.controller_btn_mute);
        muteImage.setImageResource(isMute?R.mipmap.ic_player_mute_true:R.mipmap.ic_player_mute_false);
    }

    /**
     * 更新静音状态
     */
    private void updateMute(){
        if(null!= mControlWrapper){
            boolean soundMute = mControlWrapper.isSoundMute();
            ImageView muteImge = (ImageView) findViewById(R.id.controller_btn_mute);
            muteImge.setImageResource(soundMute?R.mipmap.ic_player_mute_true:R.mipmap.ic_player_mute_false);
        }
    }

    /**
     * 是否显示静音按钮
     * @param showSound 是否显示静音按钮,true:显示 false:隐藏
     */
    public void showSoundMute(boolean showSound){
        ImageView muteImage = (ImageView) findViewById(R.id.controller_btn_mute);
        muteImage.setVisibility(showSound?View.VISIBLE:View.GONE);
    }

    /**
     * 是否显示静音按钮
     * @param showSound 是否显示静音按钮,true:显示 false:


.util.List;
import java.util.Map;

/**
 * 实体加速器界面，显示加速状态、卡数量、能耗和倍率信息。
 */
public class EntitySpeedTickerScreen<C extends EntitySpeedTickerMenu> extends UpgradeableScreen<C> {
    private boolean eap$entitySpeedTickerEnabled = false;                   // 本地缓存的加速开关状态
    private final SettingToggleButton<YesNo> eap$entitySpeedTickerToggle;   // 加速开关按钮

    /**
     * 构造函数，初始化界面和控件。
     * @param menu 实体加速器菜单
     * @param playerInventory 玩家背包
     * @param title 界面标题
     * @param style 界面样式
     */
    public EntitySpeedTickerScreen(EntitySpeedTickerMenu menu, Inventory playerInventory, Component title, ScreenStyle style) {
        super((C) menu, playerInventory, title, style);
        this.addToLeftToolbar(CommonButtons.togglePowerUnit()); // 添加功率单位切换按钮
        this.eap$entitySpeedTickerEnabled = menu.getAccelerateEnabled();

        // 初始化加速开关按钮
        eap$entitySpeedTickerToggle = new SettingToggleButton<>(
                Settings.BLOCKING_MODE,
                this.eap$entitySpeedTickerEnabled ? YesNo.YES : YesNo.NO,
                (btn, backwards) ->
                        ModNetwork.CHANNEL.sendToServer(new ToggleEntityTickerC2SPacket())
        ) {
            @Override
            public List<Component> getTooltipMessage() {
                if (menu.targetBlacklisted) {
                    return List.of(
                            Component.literal("实体加速"),
                            Component.literal("已禁用（目标在黑名单）")
                    );
                }
                boolean enabled = eap$entitySpeedTickerEnabled;
                return List.of(
                        Component.literal("实体加速"),
                        enabled ? Component.literal("已启用: 将加速目标方块实体的tick") :
                                Component.literal("已关闭: 不会对目标方块实体进行加速")
                );
            }

            @Override
            protected Icon getIcon() {
                if (menu.targetBlacklisted) return Icon.INVALID;
                return this.getCurrentValue() == YesNo.YES ? Icon.VALID : Icon.INVALID;
            }
        };
        eap$entitySpeedTickerToggle.set(this.eap$entitySpeedTickerEnabled ? YesNo.YES : YesNo.NO);
        this.addToLeftToolbar(eap$entitySpeedTickerToggle);
    }

    /**
     * 在渲染前更新界面状态。
     */
    @Override
    protected void updateBeforeRender() {
        super.updateBeforeRender();
        if (eap$entitySpeedTickerToggle != null && menu != null) {
            eap$entitySpeedTickerEnabled = menu.getAccelerateEnabled();
            // 如果目标在黑名单，禁用按钮并显示关闭状态
            eap$entitySpeedTickerToggle.set(menu.targetBlacklisted ? YesNo.NO : (eap$entitySpeedTickerEnabled ? YesNo.YES : YesNo.NO));
            eap$entitySpeedTickerToggle.active = !menu.targetBlacklisted;
        }
        textData();
    }

    /**
     * 刷新界面显示。
     */
    public void refreshGui() {
        textData();
    }

    /**
     * 更新界面文本内容，包括加速状态、速度、能耗和倍率。
     */
    private void textData() {
        Map<String, Component> textContents = new HashMap<>();
        if (getMenu().targetBlacklisted || !getMenu().getAccelerateEnabled()) {
            // 黑名单禁用或加速关闭时的默认显示


/*
 * EFI Time Services Driver for Linux
 *
 * Copyright (C) 1999 Hewlett-Packard Co
 * Copyright (C) 1999 Stephane Eranian <eranian@hpl.hp.com>
 *
 * Based on skeleton from the drivers/char/rtc.c driver by P. Gortmaker
 *
 * This code provides an architected & portable interface to the real time
 * clock by using EFI instead of direct bit fiddling. The functionalities are
 * quite different from the rtc.c driver. The only way to talk to the device
 * is by using ioctl(). There is a /proc interface which provides the raw
 * information.
 *
 * Please note that we have kept the API as close as possible to the
 * legacy RTC. The standard /sbin/hwclock program should work normally
 * when used to get/set the time.
 *
 * NOTES:
 *	- Locking is required for safe execution of EFI calls with regards
 *	  to interrupts and SMP.
 *
 * TODO (December 1999):
 * 	- provide the API to set/get the WakeUp Alarm (different from the
 *	  rtc.c alarm).
 *	- SMP testing
 * 	- Add module support
 */

#include <linux/types.h>
#include <linux/errno.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/rtc.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/efi.h>
#include <linux/uaccess.h>

#define EFI_RTC_VERSION		"0.4"

#define EFI_ISDST (EFI_TIME_ADJUST_DAYLIGHT|EFI_TIME_IN_DAYLIGHT)
/*
 * EFI Epoch is 1/1/1998
 */
#define EFI_RTC_EPOCH		1998

static DEFINE_SPINLOCK(efi_rtc_lock);

static long efi_rtc_ioctl(struct file *file, unsigned int cmd,
							unsigned long arg);

#define is_leap(year) \
          ((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0))

static const unsigned short int __mon_yday[2][13] =
{
	/* Normal years.  */
	{ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
	/* Leap years.  */
	{ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
};

/*
 * returns day of the year [0-365]
 */
static inline int
compute_yday(efi_time_t *eft)
{
	/* efi_time_t.month is in the [1-12] so, we need -1 */
	return  __mon_yday[is_leap(eft->year)][eft->month-1]+ eft->day -1;
}
/*
 * returns day of the week [0-6] 0=Sunday
 *
 * Don't try to provide a year that's before 1998, please !
 */
static int
compute_wday(efi_time_t *eft)
{
	int y;
	int ndays = 0;

	if ( eft->year < 1998 ) {
		printk(KERN_ERR "efirtc: EFI year < 1998, invalid date\n");
		return -1;
	}

	for(y=EFI_RTC_EPOCH; y < eft->year; y++ ) {
		ndays += 365 + (is_leap(y) ? 1 : 0);
	}
	ndays += compute_yday(eft);

	/*
	 * 4=1/1/1998 was a Thursday
	 */
	return (ndays + 4) % 7;
}

static void
convert_to_efi_time(struct rtc_time *wtime, efi_time_t *eft)
{

	eft->year	= wtime->tm_year + 1900;
	eft->month	= wtime->tm_mon + 1;
	eft->day	= wtime->tm_mday;
	eft->hour	= wtime->tm_hour;
	eft->minute	= wtime->tm_min;
	eft->second 	= wtime->tm_sec;
	eft->nanosecond = 0;
	eft->daylight	= wtime->tm_isdst ? EFI_ISDST: 0;
	eft->timezone	= EFI_UNSPECIFIED_TIMEZONE;
}

static void
convert_from_efi_time(efi_time_t *eft, struct rtc_time *wtime)
{
	memset(wtime, 0, sizeof(*wtime));
	wtime->tm_sec  = eft->second;
	wtime->tm_min  = eft->minute;
	wtime->tm_hour = eft->hour;
	wtime->tm_mday = eft->day;
	wtime->tm_mon  = eft->month - 1;
	wtime->tm_year = eft->year - 1900;

	/* day of the week [0-6], Sunday=0 */
	wtime->tm_wday = compute_wday(eft);

	/* day in the year [1-365]*/
	wtime->tm_yday = compute_yday(eft);

	switch (eft->daylight & EFI_ISDST) {
		case EFI_ISDST:
			wtime->tm_isdst = 1;
			break;
		case EFI_TIME_ADJUST_DAYLIGHT:
			wtime->tm_isdst = 0;
			break;
		default:
			wtime->tm_isdst = -1;
	}
}

static long efi_rtc_ioctl(struct file *file, unsigned int cmd,
							unsigned long arg)
{

	efi_status_t	status;
	unsigned long	flags;
	efi_time_t	eft;
	efi_time_cap_t	cap;
	struct rtc_time	wtime;
	struct rtc_wkalrm __user *ewp;
	unsigned char	enabled, pending;

	switch (cmd) {
		case RTC_UIE_ON:
		case RTC_UIE_OFF:
		case RTC_PIE_ON:
		case RTC_PIE_OFF:
		case RTC_AIE_ON:
		case RTC_AIE_OFF:
		case RTC_ALM_SET:
		case RTC_ALM_READ:
		case RTC_IRQP_READ:
		case RTC_IRQP_SET:
		case RTC_EPOCH_READ:
		case RTC_EPOCH_SET:
			return -EINVAL;

		case RTC_RD_TIME:
			spin_lock_irqsave(&efi_rtc_lock, flags);

			status = efi.get_time(&eft, &cap);

			spin_unlock_irqrestore(&efi_rtc_lock,flags);

			if (status != EFI_SUCCESS) {
				/* should never happen */
				printk(KERN_ERR "efitime: can't read time\n");
				return -EINVAL;
			}

			convert_from_efi_time(&eft, &wtime);

 			return copy_to_user((voi


    /** {@inheritDoc} */
    @Override
    protected String argString() {
        return constant.toHuman();
    }

    /** {@inheritDoc} */
    @Override
    public String cstString() {
        if (constant instanceof CstString) {
            return ((CstString) constant).toQuoted();
        }
        return constant.toHuman();
    }

    /** {@inheritDoc} */
    @Override
    public String cstComment() {
        if (!hasIndex()) {
            return "";
        }

        StringBuilder sb = new StringBuilder(20);
        sb.append(getConstant().typeName());
        sb.append('@');

        if (index < 65536) {
            sb.append(Hex.u2(index));
        } else {
            sb.append(Hex.u4(index));
        }

        return sb.toString();
    }
}
/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.dx.dex.code;

import com.android.dx.rop.code.RegisterSpec;
import com.android.dx.rop.code.RegisterSpecList;
import com.android.dx.rop.code.SourcePosition;
import com.android.dx.ssa.RegisterMapper;

/**
 * Pseudo-instruction which is used to introduce a new local variable. That
 * is, an instance of this class in an instruction stream indicates that
 * starting with the subsequent instruction, the indicated variable
 * is bound.
 */
public final class LocalStart extends ZeroSizeInsn {
    /**
     * {@code non-null;} register spec representing the local variable introduced
     * by this instance
     */
    private final RegisterSpec local;

    /**
     * Returns the local variable listing string for a single register spec.
     *
     * @param spec {@code non-null;} the spec to convert
     * @return {@code non-null;} the string form
     */
    public static String localString(RegisterSpec spec) {
        return spec.regString() + ' ' + spec.getLocalItem().toString() + ": " +
            spec.getTypeBearer().toHuman();
    }

    /**
     * Constructs an instance. The output address of this instance is initially
     * unknown ({@code -1}).
     *
     * @param position {@code non-null;} source position
     * @param local {@code non-null;} register spec representing the local
     * variable introduced by this instance
     */
    public LocalStart(SourcePosition position, RegisterSpec local) {
        super(position);

        if (local == null) {
            throw new NullPointerException("local == null");
        }

        this.local = local;
    }

    /** {@inheritDoc} */
    @Override
    public DalvInsn withRegisterOffset(int delta) {
        return new LocalStart(getPosition(), local.withOffset(delta));
    }

    /** {@inheritDoc} */
    @Override
    public DalvInsn withRegisters(RegisterSpecList registers) {
        return new LocalStart(getPosition(), local);
    }

    /**
     * Gets the register spec representing the local variable introduced
     * by this instance.
     *
     * @return {@code non-null;} the register spec
     */
    public RegisterSpec getLocal() {
        return local;
    }

    /** {@inheritDoc} */
    @Override
    protected String argString() {
        return local.toString();
    }

    /** {@inheritDoc} */
    @Override
    protected String listingString0(boolean noteIndices) {
        return "local-start " + localString(local);


Denom:                 denom2,
				Height:                      2,
				Time:                        tPlusOne,
				P0LastSpotPrice:             osmomath.OneDec(),
				P1LastSpotPrice:             osmomath.OneDec(),
				P0ArithmeticTwapAccumulator: osmomath.OneDec(),
				P1ArithmeticTwapAccumulator: osmomath.OneDec(),
				GeometricTwapAccumulator:    osmomath.OneDec(),
			},
			{
				PoolId:                      basePoolId,
				Asset0Denom:                 denom0,
				Asset1Denom:                 denom2,
				Height:                      3,
				Time:                        baseTime,
				P0LastSpotPrice:             osmomath.OneDec(),
				P1LastSpotPrice:             osmomath.OneDec(),
				P0ArithmeticTwapAccumulator: osmomath.OneDec(),
				P1ArithmeticTwapAccumulator: osmomath.OneDec(),
				GeometricTwapAccumulator:    osmomath.OneDec(),
			},
		})

	bothPoolsGenesis = types.NewGenesisState(
		basicParams,
		append(increasingOrderByTimeRecordsPoolOne.Twaps, decreasingOrderByTimeRecordsPoolTwo.Twaps...),
	)
)

func withPoolId(twap types.TwapRecord, poolId uint64) types.TwapRecord {
	twap.PoolId = poolId
	return twap
}

func withLastErrTime(twap types.TwapRecord, lastErrorTime time.Time) types.TwapRecord {
	twap.LastErrorTime = lastErrorTime
	return twap
}

func withSp0(twap types.TwapRecord, sp osmomath.Dec) types.TwapRecord {
	twap.P0LastSpotPrice = sp
	return twap
}

func withSp1(twap types.TwapRecord, sp osmomath.Dec) types.TwapRecord {
	twap.P1LastSpotPrice = sp
	return twap
}

// TestTWAPInitGenesis tests that genesis is initialized correctly
// with different parameters and state.
// Asserts that the most recent records are set correctly.
func (s *TestSuite) TestTwapInitGenesis() {
	testCases := map[string]struct {
		twapGenesis *types.GenesisState

		expectPanic bool

		expectedMostRecentRecord []types.TwapRecord
	}{
		"default genesis - success": {
			twapGenesis: types.DefaultGenesis(),
		},
		"custom valid genesis; success": {
			twapGenesis: basicCustomGenesis,

			expectedMostRecentRecord: []types.TwapRecord{
				mostRecentRecordPoolOne,
			},
		},
		"custom valid multi record; increasing; success": {
			twapGenesis: increasingOrderByTimeRecordsPoolOne,

			expectedMostRecentRecord: []types.TwapRecord{
				mostRecentRecordPoolOne,
			},
		},
		"custom valid multi record; decreasing (sorted internally); success": {
			twapGenesis: decreasingOrderByTimeRecordsPoolTwo,

			expectedMostRecentRecord: []types.TwapRecord{
				mostRecentRecordPoolTwo,
			},
		},
		"custom valid multi record and multi pool; success": {
			twapGenesis: bothPoolsGenesis,

			expectedMostRecentRecord: []types.TwapRecord{
				mostRecentRecordPoolTwo, mostRecentRecordPoolOne,
			},
		},
		"custom invalid genesis - error": {
			twapGenesis: types.NewGenesisState(
				types.NewParams("week", 48*time.Hour),
				[]types.TwapRecord{
					{
						PoolId:                      0, // invalid
						Asset0Denom:                 "test1",
						Asset1Denom:                 "test2",
						Height:                      1,
						Time:                        baseTime,
						P0LastSpotPrice:             o


supports disabling patterns', function()
      insert(source)
      local result = exec_lua(get_patterns, query_text, { pattern = 2 })
      eq({ { id = 1, pattern = 1 }, { id = 2, pattern = 3 } }, result)
    end)

    it('supports disabling captures', function()
      insert(source)
      local result = exec_lua(get_patterns, query_text, { capture = 'param' })
      eq({ { id = 1, pattern = 1 } }, result)
    end)
  end)
end)


];
static uint32_t _closed_index = []() {
    _slots_lock = xSemaphoreCreateBinary();
    xSemaphoreGive(_slots_lock);
    for (int i = 0; i < _number_of_closed_slots; ++ i) {
        _closed_slots[i] = 1;
    }
    return 1;
}();

static inline bool _init_async_event_queue(){
    if(!_async_queue){
        _async_queue = xQueueCreate(32, sizeof(lwip_event_packet_t *));
        if(!_async_queue){
            return false;
        }
    }
    return true;
}

static inline bool _send_async_event(lwip_event_packet_t ** e){
    return _async_queue && xQueueSend(_async_queue, e, portMAX_DELAY) == pdPASS;
}

static inline bool _prepend_async_event(lwip_event_packet_t ** e){
    return _async_queue && xQueueSendToFront(_async_queue, e, portMAX_DELAY) == pdPASS;
}

static inline bool _get_async_event(lwip_event_packet_t ** e){
    return _async_queue && xQueueReceive(_async_queue, e, portMAX_DELAY) == pdPASS;
}

static bool _remove_events_with_arg(void * arg){
    lwip_event_packet_t * first_packet = NULL;
    lwip_event_packet_t * packet = NULL;

    if(!_async_queue){
        return false;
    }
    //figure out which is the first packet so we can keep the order
    while(!first_packet){
        if(xQueueReceive(_async_queue, &first_packet, 0) != pdPASS){
            return false;
        }
        //discard packet if matching
        if((int)first_packet->arg == (int)arg){
            free(first_packet);
            first_packet = NULL;
        //return first packet to the back of the queue
        } else if(xQueueSend(_async_queue, &first_packet, portMAX_DELAY) != pdPASS){
            return false;
        }
    }

    while(xQueuePeek(_async_queue, &packet, 0) == pdPASS && packet != first_packet){
        if(xQueueReceive(_async_queue, &packet, 0) != pdPASS){
            return false;
        }
        if((int)packet->arg == (int)arg){
            free(packet);
            packet = NULL;
        } else if(xQueueSend(_async_queue, &packet, portMAX_DELAY) != pdPASS){
            return false;
        }
    }
    return true;
}

static void _handle_async_event(lwip_event_packet_t * e){
    if(e->arg == NULL){
        // do nothing when arg is NULL
        //ets_printf("event arg == NULL: 0x%08x\n", e->recv.pcb);
    } else if(e->event == LWIP_TCP_CLEAR){
        _remove_events_with_arg(e->arg);
    } else if(e->event == LWIP_TCP_RECV){
        //ets_printf("-R: 0x%08x\n", e->recv.pcb);
        AsyncClient::_s_recv(e->arg, e->recv.pcb, e->recv.pb, e->recv.err);
    } else if(e->event == LWIP_TCP_FIN){
        //ets_printf("-F: 0x%08x\n", e->fin.pcb);
        AsyncClient::_s_fin(e->arg, e->fin.pcb, e->fin.err);
    } else if(e->event == LWIP_TCP_


开始滚雪球了。

实质封锁和非军事化金门是一个非常好的入口——这里对台湾属于法定领土，但离我们实在太近。如果我们开始常态化的检查进出金门的船只，我们大可以做到直接削弱台湾在金门的军事存在。

我们可以不放“载有违禁物品”的船只和飞机进入金门。金门人要坐飞机可以到厦门来坐。

我们其实不需要冲击台海中线，直接冲击金门“领海线”就可以给台湾当局制造宪法危机——难道因为难以应对就实质“放弃国土”？

退倒不是不能退，但是要是老共发现这是一个“成功的战术”，一轮又一轮的用，按这个逻辑，东引岛、太平岛是不是也要丢？澎湖是不是也要在和平状态下就被去军事化？？

难道台湾就这样龟缩到只剩本岛？

更糟糕的是，这样就造成了一个“台方实际承认这种临检自由”的现实。这个现实一旦确立，其实就等于接受了“大陆可以随意封锁台湾任何一块实占土地”。

如果不接受，那么现在在金门台军就要“自卫开火”了，这能开吗？开得起吗？

切香肠战术坏就坏在这种“幅度极小、但性质极恶”。幅度小到你很难为此采取激烈反应，而你不采取激烈反应又会造成极为恶劣的法理破洞。

不过我们现在就开始动手，估计是算计到了所有的时间点，要让这件事的最高潮发生在美国最左支右绌的时点。

这意味着乌克兰可能要倒霉了——俄罗斯估计会在这之后加大进攻强度和节奏。

而以色列也可能要开始倒霉了——伊朗和胡塞武装可能要趁这时机狠狠的搞一搞以色列。

非洲和南美也可能要在这段时间出问题。
# 台湾大选
[2024 台湾大选候选人侯友宜民调暴跌被柯文哲反超，蓝营人士坚称不会「换侯友宜」，有哪些信息值得关注？](https://www.zhihu.com/question/604208931/answer/3055289284)

> Author: #Anonymity
> Last update: [编辑于 2023-06-02]
> Link:


 => write!(
                f,
                "Row {} is not the same length as previous rows",
                index_of_invalid_length_row
            ),
            Error::EmptySecretArray => write!(f, "Secret array should not be empty"),
            Error::InvalidNumberOfShares(num) => {
                write!(f, "Need to generate at least 2 shares. Requested: {}", num)
            }
            Error::UnreconstructableSecret(to_create, required) => write!(
                f,
                "Can't create less shares than required to reconstruct. Create: {}, Req: {}",
                to_create, required
            ),
        }
    }
}

impl std::error::Error for Error {}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::rngs::StdRng;
    use rand::Rng;
    use rand::SeedableRng;

    #[test]
    fn many_test() {
        let num_iters = 10;

        let mut rand = StdRng::seed_from_u64(123u64);

        for _ in 0..num_iters {
            let secret: u8 = rand.gen_range(1, 256) as u8;
            let shares_required: u8 = rand.gen_range(2, 10);
            let shares_to_create: u8 = shares_required + rand.gen_range(0, 6);

            basic_single_value(secret, shares_to_create, shares_required);
        }
    }

    fn basic_single_value(secret: u8, shares_to_create: u8, shares_required: u8) {
        /* Was used to find an infinite loop, no longer needed, but keeping for future reference
        unsafe {
            register(signal_hook::SIGQUIT, || println!("{:?}", Backtrace::new()));
        }
        */

        let shares = from_secret(secret, shares_required, shares_to_create, None).unwrap();

        let secret_decrypted = reconstruct_secret(shares);
        assert_eq!(secret, secret_decrypted);
    }

    #[test]
    fn transpose() {
        let matrix = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];

        let matrix1 = vec![vec![1, 4, 7], vec![2, 5, 8], vec![3, 6, 9]];

        let matrix2 = vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]];

        let matrix3 = vec![vec![1, 5], vec![2, 6], vec![3, 7], vec![4, 8]];

        assert_eq!(transpose_vec_matrix(matrix).unwrap(), matrix1);
        assert_eq!(transpose_vec_matrix(matrix2).unwrap(), matrix3);
    }

    #[cfg(feature = "benchmark_tests")]
    #[test]
    fn large_data_and_benchmark() {
        use std::time::Instant;

        let secret = "According to all known laws of aviation,
            there is no way a bee should be able to fly.
            Its wings are too small to get its fat little body off the ground.
            The bee, of course, flies anyway
            because bees don't care what humans think is impossible.";
        let shares_required = 5;
        let shares_to_create = 5;

        let now = Instant::now();

        let share_lists =
            from_secrets(secret.as_bytes(), shares_required, shares_to_create).unwrap();

        let recon_secret_vec = reconstruct_secrets(share_lists).unwrap();
        let recon_secret = String::from_utf8(recon_secret_vec).unwrap();

        let time_elap = now.elapsed().as_millis();

        println!("Time elapsed: {} milliseconds", time_elap);

        as


dest[currentByte] = (byte)(dest[currentByte] & (~upMask));
                //merge bytes~
                dest[currentByte] = (byte)(dest[currentByte] | currentBits);
                //System.out.println("new currentByte: " + dest[currentByte]);
                count -= bitRoom;
                currentOffset = 0;
                currentByte++;
            }
        }
        if(DEBUG_LEV > 30)
            System.err.println("EncodedElement::addInt : End");
    }

    /**
     * Force the usable data stored in this list ends on a a byte boundary, by
     * padding to the end with zeros.
     *
     * @return true if the data was padded, false if it already ended on a byte
     * boundary.
     */
    public boolean padToByte() {
        boolean padded = false;

        //System.err.println("Usable bits: "+tempVal);
        EncodedElement end = EncodedElement.getEnd_S(this);
        int tempVal = end.usableBits;
        if(tempVal % 8 != 0) {
            int toWrite = 8-(tempVal%8);
            end.addInt(0, toWrite);
            /* FOR DEVEL ONLY: */
            if( (this.getTotalBits()+offset) % 8 != 0)
                System.err.println("EncodedElement::padToByte: SERIOUS ERROR! " +
                        "Algorithm implemented is incorrect!!!");
            padded = true;
        }
        return padded;
    }
}
package com.wavpack.decoder;

/*
** Defines.java
**
** Copyright (c) 2007 - 2008 Peter McQuillan
**
** All Rights Reserved.
**
** Distributed under the BSD Software License (see license.txt)
**
*/

public class Defines {
    // Change the following value to an even number to reflect the maximum number of samples to be processed
    // per call to WavPackUtils.WavpackUnpackSamples

    public static int SAMPLE_BUFFER_SIZE = 4096;

    static int FALSE = 0;
    static int TRUE = 1;

    // or-values for "flags"

    static int BYTES_STORED = 3;       // 1-4 bytes/sample
    static int MONO_FLAG = 4;       // not stereo
    static int HYBRID_FLAG = 8;       // hybrid mode
    static int FALSE_STEREO = 0x40000000;      // block is stereo, but data is mono

    static int SHIFT_LSB = 13;
    static long SHIFT_MASK = (0x1fL << SHIFT_LSB);

    static int FLOAT_DATA = 0x80;    // ieee 32-bit floating point data

    static int SRATE_LSB = 23;
    static long SRATE_MASK = (0xfL << SRATE_LSB);

    static int FINAL_BLOCK = 0x1000;  // final block of multichannel segment

    static int MIN_STREAM_VERS = 0x402;       // lowest stream version we'll decode
    static int MAX_STREAM_VERS = 0x410;       // highest stream version we'll decode

    static final short ID_DUMMY = 0x0;
    static short ID_ENCODER_INFO = 0x1;
    static final short ID_DECORR_TERMS = 0x2;
    static final short ID_DECORR_WEIGHTS = 0x3;
    static final short ID_DECORR_SAMPLES = 0x4;
    static final short ID_ENTROPY_VARS = 0x5;
    static final short ID_HYBRID_PROFILE = 0x6;
    static final short ID_SHAPING_WEIGHTS = 0x7;
    static final short ID_FLOAT_INFO = 0x8;
    static final short ID_INT32_INFO = 0x9;
    static final short ID_WV_BITSTREAM = 0xa;
    static final short ID_WVC_BITSTREAM = 0xb;
    static final short ID_WVX_BITSTR


 == filtered[newItemPosition]
          }

          override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return items[oldItemPosition] == filtered[newItemPosition]
          }
        }
      )

    return filtered to result
  }

  /** Get the list item at given index. */
  fun getItem(index: Int): D {
    return filtered[index]
  }

  override fun getItemCount(): Int {
    return filtered.size
  }

  /** Get the query candidate for the given list item. */
  abstract fun getQueryCandidate(item: D): String

  /** Called on every item when filtering the data. */
  protected open fun onFilter(item: D, query: String): Boolean {
    return getQueryCandidate(item).contains(query, ignoreCase = true)
  }
}
/*
 *  This file is part of AndroidIDE.
 *
 *  AndroidIDE is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AndroidIDE is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *   along with AndroidIDE.  If not, see <https://www.gnu.org/licenses/>.
 */

package com.itsaky.androidide.utils

import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.ShareCompat
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.ImageUtils.ImageType.TYPE_UNKNOWN
import com.itsaky.androidide.R
import java.io.File

/**
 * Utilities for sharing files.
 *
 * @author Akash Yadav
 */
object IntentUtils {

  private const val RESULT_LAUNCH_APP_INTENT_SENDER = 223

  @JvmStatic
  fun openImage(context: Context, file: File) {
    imageIntent(context = context, file = file, intentAction = Intent.ACTION_VIEW)
  }

  @JvmStatic
  @JvmOverloads
  fun imageIntent(
    context: Context,
    file: File,
    intentAction: String = Intent.ACTION_SEND
  ) {
    val type = ImageUtils.getImageType(file)
    var typeString = type.value
    if (type == TYPE_UNKNOWN) {
      typeString = "*"
    }
    startIntent(
      context = context,
      file = file,
      mimeType = "image/$typeString",
      intentAction = intentAction
    )
  }

  @JvmStatic
  fun shareFile(context: Context, file: File, mimeType: String) {
    startIntent(context = context, file = file, mimeType = mimeType)
  }

  @JvmStatic
  @JvmOverloads
  fun startIntent(
    context: Context,
    file: File,
    mimeType: String = "*/*",
    intentAction: String = Intent.ACTION_SEND
  ) {
    val uri =
      FileProvider.getUriForFile(context, "${context.packageName}.providers.fileprovider", file)
    val intent =
      ShareCompat.IntentBuilder(context)
        .setType(mimeType)
        .setStream(uri)
        .intent
        .setAction(intentAction)
        .setDataAndType(uri, mimeType)
        .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

    context.startActivity(Intent.createChooser(intent, null))
  }

  /**
   * Launch the application with the given [package name][packageName].
   *
   * @param context The context that will be used to fetch


#endif // FBCODE_CAFFE2

} // namespace lazy
} // namespace torch
#include <ATen/ATen.h>
#include <ATen/CachedTensorUtils.h>

#include <c10/util/flat_hash_map.h>

namespace at::caching {

using weakref_type = c10::weak_intrusive_ptr<TensorImpl, UndefinedTensorImpl>;

bool cached_tensorimpls_enabled = false;

// Like `cached_casts` in autocast_mode, we hash on the TensorImpl*
//  and keep the pointer alive with a weakref value.
ska::flat_hash_map<TensorImpl*, weakref_type> cached_tensorimpls;
std::mutex cached_tensorimpl_mutex;

bool is_cached_tensor(const at::Tensor& t) {
  if (!cached_tensorimpls_enabled) {
    return false;
  }
  const std::lock_guard<std::mutex> lock(cached_tensorimpl_mutex);
  return cached_tensorimpls.count(t.unsafeGetTensorImpl());
}

void add_cached_tensor(const at::Tensor& t) {
  TORCH_INTERNAL_ASSERT(cached_tensorimpls_enabled);
  const std::lock_guard<std::mutex> lock(cached_tensorimpl_mutex);
  cached_tensorimpls.emplace(t.unsafeGetTensorImpl(), weakref_type(t.getIntrusivePtr()));
}

void remove_cached_tensor(const at::Tensor& t) {
  TORCH_INTERNAL_ASSERT(cached_tensorimpls_enabled);
  const std::lock_guard<std::mutex> lock(cached_tensorimpl_mutex);
  cached_tensorimpls.erase(t.unsafeGetTensorImpl());
}

void set_cached_tensors_enabled(bool enabled) {
  cached_tensorimpls_enabled = enabled;
}

size_t adjusted_use_count(const at::Tensor& t) {
  return t.use_count() - (is_cached_tensor(t) ? 1 : 0);
}

} // namespace at::caching
#include <ATen/test/reportMemoryUsage.h>

#include <gtest/gtest.h>

#include <c10/cuda/CUDACachingAllocator.h>

TEST(DeviceCachingAllocator, check_reporter) {
  auto reporter = std::make_shared<TestMemoryReportingInfo>();
  c10::DebugInfoGuard guard(c10::DebugInfoKind::PROFILER_STATE, reporter);

  auto _200kb = 200 * 1024;
  auto _500mb = 500 * 1024 * 1024;

  auto allocator = c10::cuda::CUDACachingAllocator::get();

  auto alloc1 = allocator->allocate(_200kb);
  auto r = reporter->getLatestRecord();
  EXPECT_EQ(alloc1.get(), r.ptr);
  EXPECT_LE(_200kb, r.alloc_size);
  EXPECT_LE(_200kb, r.total_allocated);
  EXPECT_LE(_200kb, r.total_reserved);
  EXPECT_TRUE(r.device.is_cuda());

  auto alloc1_true_ptr = r.ptr;
  auto alloc1_true_alloc_size = r.alloc_size;

  // I bet pytorch will not waste that much memory
  EXPECT_LT(r.total_allocated, 2 * _200kb);
  // I bet pytorch will not reserve that much memory
  EXPECT_LT(r.total_reserved, _500mb);

  auto alloc2 = allocator->allocate(_500mb);
  r = reporter->getLatestRecord();
  EXPECT_EQ(alloc2.get(), r.ptr);
  EXPECT_LE(_500mb, r.alloc_size);
  EXPECT_LE(_200kb + _500mb, r.total_allocated);
  EXPECT_LE(_200kb + _500mb, r.total_reserved);
  EXPECT_TRUE(r.device.is_cuda());
  auto alloc2_true_ptr = r.ptr;
  auto alloc2_true_alloc_size = r.alloc_size;

  auto max_reserved = r.total_reserved;

  alloc


/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef ANDROID_PARCELABLE_H
#define ANDROID_PARCELABLE_H

#include <vector>

#include <utils/Errors.h>
#include <utils/String16.h>

namespace android {

class Parcel;

// Abstract interface of all parcelables.
class Parcelable {
public:
    virtual ~Parcelable() = default;

    // Write |this| parcelable to the given |parcel|.  Keep in mind that
    // implementations of writeToParcel must be manually kept in sync
    // with readFromParcel and the Java equivalent versions of these methods.
    //
    // Returns android::OK on success and an appropriate error otherwise.
    virtual status_t writeToParcel(Parcel* parcel) const = 0;

    // Read data from the given |parcel| into |this|.  After readFromParcel
    // completes, |this| should have equivalent state to the object that
    // wrote itself to the parcel.
    //
    // Returns android::OK on success and an appropriate error otherwise.
    virtual status_t readFromParcel(const Parcel* parcel) = 0;
};  // class Parcelable

}  // namespace android

#endif // ANDROID_PARCELABLE_H


54 03 37 3E */	rlwinm r3, r0, 6, 0x1c, 0x1f
/* 803BB06C 003B6CCC  48 00 01 18 */	b lbl_803BB184
/* 803BB070 003B6CD0  80 0A 00 8C */	lwz r0, 0x8c(r10)
/* 803BB074 003B6CD4  54 03 47 BE */	rlwinm r3, r0, 8, 0x1e, 0x1f
/* 803BB078 003B6CD8  48 00 01 0C */	b lbl_803BB184
/* 803BB07C 003B6CDC  80 0A 00 8C */	lwz r0, 0x8c(r10)
/* 803BB080 003B6CE0  54 03 57 BE */	rlwinm r3, r0, 0xa, 0x1e, 0x1f
/* 803BB084 003B6CE4  48 00 01 00 */	b lbl_803BB184
/* 803BB088 003B6CE8  80 0A 00 8C */	lwz r0, 0x8c(r10)
/* 803BB08C 003B6CEC  54 03 6F 7E */	rlwinm r3, r0, 0xd, 0x1d, 0x1f
/* 803BB090 003B6CF0  48 00 00 F4 */	b lbl_803BB184
/* 803BB094 003B6CF4  80 0A 00 8C */	lwz r0, 0x8c(r10)
/* 803BB098 003B6CF8  54 03 87 7E */	rlwinm r3, r0, 0x10, 0x1d, 0x1f
/* 803BB09C 003B6CFC  48 00 00 E8 */	b lbl_803BB184
/* 803BB0A0 003B6D00  80 0A 00 8C */	lwz r0, 0x8c(r10)
/* 803BB0A4 003B6D04  54 03 9F 7E */	rlwinm r3, r0, 0x13, 0x1d, 0x1f
/* 803BB0A8 003B6D08  48 00 00 DC */	b lbl_803BB184
/* 803BB0AC 003B6D0C  80 0A 00 8C */	lwz r0, 0x8c(r10)
/* 803BB0B0 003B6D10  54 03 B7 7E */	rlwinm r3, r0, 0x16, 0x1d, 0x1f
/* 803BB0B4 003B6D14  48 00 00 D0 */	b lbl_803BB184
/* 803BB0B8 003B6D18  80 0A 00 8C */	lwz r0, 0x8c(r10)
/* 803BB0BC 003B6D1C  54 03 BF FE */	rlwinm r3, r0, 0x17, 0x1f, 0x1f
/* 803BB0C0 003B6D20  48 00 00 C4 */	b lbl_803BB184
/* 803BB0C4 003B6D24  80 0A 00 8C */	lwz r0, 0x8c(r10)
/* 803BB0C8 003B6D28  54 03 DF 3E */	rlwinm r3, r0, 0x1b, 0x1c, 0x1f
/* 803BB0CC 003B6D2C  48 00 00 B8 */	b lbl_803BB184
/* 803BB0D0 003B6D30  80 0A 00 8C */	lwz r0, 0x8c(r10)
/* 803BB0D4 003B6D34  54 03 E7 FE */	rlwinm r3, r0, 0x1c, 0x1f, 0x1f
/* 803BB0D8 003B6D38  48 00 00 AC */	b lbl_803BB184
/*


rue")
    public void inWindow() throws Exception {
        final String html = DOCTYPE_HTML
            + "\n"
            + "\n"
            + "  \n"
            + "\n"
            + "\n"
            + "\n"
            + "";

        loadPageVerifyTitle2(html);
    }

    /**
     * @throws Exception if the test fails
     */
    @Test
    @Alerts({"[object MediaDevices]", "TypeError"})
    @HtmlUnitNYI(CHROME = {"[object MediaDevices]", "undefined/DOMException"},
            EDGE = {"[object MediaDevices]", "undefined/DOMException"},
            FF = {"[object MediaDevices]", "undefined/DOMException"},
            FF_ESR = {"[object MediaDevices]", "undefined/DOMException"})
    public void getUserMedia() throws Exception {
        final String html = DOCTYPE_HTML
            + "\n"
            + "\n"
            + "\n"
            + "";

        loadPage2(html);
        verifyTitle2(DEFAULT_WAIT_TIME, getWebDriver(), getExpectedAlerts());
    }
}
/*
 * Copyright (c) 2002-2025 Gargoyle Software Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.htmlunit.javascript.host.media;

import org.htmlunit.WebDriverTestCase;
import org.htmlunit.junit.annotation.Alerts;
import org.junit.jupiter.api.Test;

/**
 * Tests for {@link AudioParam}.
 *
 * @author Ronald Brill
 */
public class AudioParamTest extends WebDriverTestCase {

    /**
     * @throws Exception if the test fails
     */
    @Test
    @Alerts("true")
    public void inWindow() throws Exception {
        final String html = DOCTYPE_HTML
            + "\n"
            + "\n"
            + "  \n"
            + "\n"
            + "\n"
            + "\n"
            + "";

        loadPageVerifyTitle2(html);
    }
}
/*
 * Copyright (c) 2002-2025 Gargoyle Software Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses


 __param

@return CCFilter的子类

]]
function filter.newFilter(__filterName, __param)
	local __filterData = FILTERS[__filterName]
	assert(__filterData, "filter.newFilter() - filter "..__filterName.." is not found.")
	local __cls, __count, __default = unpack(__filterData)
	local __paramCount = (__param and #__param) or 0
	print("filter.newFilter:", __paramCount, __filterName, __count)
	print("filter.newFilter __param:", __param)
	-- If count is nil, it means the Filter does not need a parameter.
	if __count == nil then
		if __paramCount == 0 then
			return __cls:create()
		end
	elseif __count == 0 then
		return __cls:create()
	else
		if __paramCount == 0 then
			return __cls:create(unpack(__default))
		end
		assert(__paramCount == __count,
			string.format("filter.newFilter() - the parameters have a wrong amount! Expect %d, get %d.",
			__count, __paramCount))
	end
	return __cls:create(unpack(__param))
end

--[[--

创建滤镜数组，并返回 CCFilter 的数组对象

@param table __filterNames 滤镜名称数组
@param table __params 对应参数数组

@return CCFilter数组

]]
function filter.newFilters(__filterNames, __params)
	assert(#__filterNames == #__params,
		"filter.newFilters() - Please ensure the filters and the parameters have the same amount.")
	local __filters = CCArray:create()
	for i in ipairs(__filterNames) do
		__filters:addObject(filter.newFilter(__filterNames[i], __params[i]))
	end
	return __filters
end

return filter


 PropertyBag? = null,

  /**
   * The call stack leading to this location.
   *
   * @since 0.12.0
   */
  @Json(name = "stack")
  val stack: Stack? = null,

  /**
   * A dictionary, each of whose keys specifies a variable or expression, the
   * associated value of which represents the variable or expression value.
   * For an annotation of kind 'continuation', for example, this dictionary
   * might hold the current assumed values of a set of global variables.
   *
   * @since 0.12.0
   */
  @Json(name = "state")
  val state: Map<String, MultiformatMessageString>? = null,

  /**
   * An array of references to rule or taxonomy reporting
   * descriptors that are applicable to the thread flow location.
   *
   * @since 0.12.0
   */
  @Json(name = "taxa")
  val taxa: List<ReportingDescriptorReference>? = null,

  /**
   * A web request associated with this thread flow location.
   *
   * @since 0.12.0
   */
  @Json(name = "webRequest")
  val webRequest: WebRequest? = null,

  /**
   * A web response associated with this thread flow location.
   *
   * @since 0.12.0
   */
  @Json(name = "webResponse")
  val webResponse: WebResponse? = null
)

/**
 * Specifies the importance of this location in understanding the code
 * flow in which it occurs. The order from most to least important
 * is "essential", "important", "unimportant". Default: "important".
 *
 * @since 0.12.0
 */
enum class Importance(val value: String) {
  Essential("essential"),
  Important("important"),
  Unimportant("unimportant")
}

/**
 * A web request associated with this thread flow location.
 *
 * Describes an HTTP request.
 *
 * A web request associated with this result.
 *
 * @since 0.12.0
 */
@JsonClass(generateAdapter = true)
data class WebRequest(
  /**
   * The body of the request.
   *
   * @since 0.12.0
   */
  @Json(name = "body")
  val body: ArtifactContent? = null,

  /**
   * The request headers.
   *
   * @since 0.12.0
   */
  @Json(name = "headers")
  val headers: Map<String, String>? = null,

  /**
   * The index within the run.webRequests array of the request object associated with this result.
   *
   * @since 0.12.0
   */
  @Json(name = "index")
  val index: Int? = null,

  /**
   * The HTTP method. Well-known values are 'GET', 'PUT', 'POST',
   * 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'TRACE', 'CONNECT'.
   *
   * @since 0.12.0
   */
  @Json(name = "method")
  val method: String? = null,

  /**
   * The request parameters.
   *
   * @since 0.12.0
   */
  @Json(name = "parameters")
  val parameters: Map<String, String>? = null,

  /**
   * Key/value pairs that provide additional information about the request.
   *
   * @since 0.12.0
   */
  @Json(name = "properties")
  val properties: PropertyBag? = null,

  /**
   * The request protocol. Example: 'http'.
   *
   * @since 0.12.0
   */
  @Json(name = "protocol")
  val protocol: String? = null,

  /**
   * The target of the request.
   *
   * @since 0.12.0
   */
  @Json(name = "target")
  val target: String? = null,

  /**
   * The request version. Example: '1.1'.
   *
   * @since 0.12.0


using ccxt;
namespace Tests;

// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code

public partial class BaseTest
{
        public void testOmit()
        {
            var exchange = new ccxt.Exchange(new Dictionary<string, object>() {
                { "id", "sampleexchange" },
            });
            AssertDeepEqual(exchange, null, "testOmit", exchange.omit(new Dictionary<string, object>() {}, "foo"), new Dictionary<string, object>() {});
            AssertDeepEqual(exchange, null, "testOmit", exchange.omit(new Dictionary<string, object>() {


w = booleanPreferencesKey("player_subtitle_show")
    // AI字幕显示
    val PlayerAiSubtitleShow = booleanPreferencesKey("player_ai_subtitle_show")
    // 小屏显示面积
    val PlayerSmallShowArea = intPreferencesKey("player_small_show_area")
    // 挂起时显示面积
    val PlayerHoldShowArea = intPreferencesKey("player_hold_show_area")
    // 小屏是否可拖动
    val PlayerSmallDraggable = booleanPreferencesKey("player_small_draggable")

    /**
     * Danmaku
     */
    // 启用弹幕
    val DanmakuEnable = booleanPreferencesKey("danmaku_enable")
    // 使用系统字体
    val DanmakuSysFont = booleanPreferencesKey("danmaku_sys_font")
    // 时间同步
    val DanmakuTimeSync = booleanPreferencesKey("danmaku_time_sync")
    // 默认状态
    val DanmakuDefault = Danmaku("default")
    // 小屏模式
    val DanmakuSmallMode = Danmaku("small")
    // 全屏模式
    val DanmakuFullMode = Danmaku("full")
    // 画中画模式
    val DanmakuPipMode = Danmaku("pip")
    class Danmaku(
        val name: String,
    ) {
        // 启用设置
        val enable = booleanPreferencesKey("${name}_danmaku_enable")
        // 显示
        val show = booleanPreferencesKey("${name}_danmaku_show")
        // 滚动显示
        val r2lShow = booleanPreferencesKey("${name}_danmaku_r2l_show")
        // 顶部显示
        val ftShow = booleanPreferencesKey("${name}_danmaku_ft_show")
        // 底部显示
        val fbShow = booleanPreferencesKey("${name}_danmaku_fb_show")
        // 特殊弹幕显示
        val specialShow = booleanPreferencesKey("${name}_danmaku_special_show")
        // 字体大小
        val fontSize = floatPreferencesKey("${name}_danmaku_fontsize")
        // 不透明度
        val opacity = floatPreferencesKey("${name}_danmaku_opacity")
        // 滚动速度
        val speed = floatPreferencesKey("${name}_danmaku_speed")
        // 最大显示行数
        val maxLines = intPreferencesKey("${name}_danmaku_max_lines")
        // 滚动最大显示行数
        val r2lMaxLine = intPreferencesKey("${name}_danmaku_r2l_max_line")
        // 顶部最大显示行数
        val ftMaxLine = intPreferencesKey("${name}_danmaku_ft_max_line")
        // 底部最大显示行数
        val fbMaxLine = intPreferencesKey("${name}_danmaku_fb_max_line")
    }

    /**
     * Flag
     */
    // 副屏显示
    val FlagSubContentShow = booleanPreferencesKey("flag_sub_content_show")
    // 主副屏分割比
    val FlagContentSplit = intPreferencesKey("flag_content_split")
    // 动画时长
    val FlagContentAnimationDuration = intPreferencesKey("flag_content_animation_duration")
}package com.a10miaomiao.bilimiao.comm.delegate.player

import android.content.res.Configuration
import android.view.DisplayCutout
import com.a10miaomiao.bilimiao.comm.delegate.BaseDelegate
import com.a10miaomiao.bilimiao.comm.delegate.


e backing Postgres-allocated pointer is
///     // **not** freed since it came "::from_pg()".  We don't own the underlying memory so
///     // we can't free it
/// }
/// ```
#[repr(transparent)]
pub struct PgBox<T, AllocatedBy: WhoAllocated<T> = AllocatedByPostgres> {
    ptr: Option<NonNull<T>>,
    __marker: PhantomData<AllocatedBy>,
}

/// A trait to track if the contents of a [PgBox] were allocated by Rust or Postgres.
pub trait WhoAllocated<T> {
    fn free(ptr: *mut T);
}

/// Indicates the [PgBox] contents were allocated by Postgres.  This is also PgBox' default
/// understanding.
pub struct AllocatedByPostgres;

/// Indicates the [PgBox] contents were allocated by Rust.
pub struct AllocatedByRust;

impl<T> WhoAllocated<T> for AllocatedByPostgres {
    /// Doesn't do anything
    fn free(_ptr: *mut T) {}
}
impl<T> WhoAllocated<T> for AllocatedByRust {
    /// Uses [pg_sys::pfree] to free the specified pointer
    #[inline]
    fn free(ptr: *mut T) {
        unsafe {
            pg_sys::pfree(ptr as *mut _);
        }
    }
}

impl<T> PgBox<T, AllocatedByPostgres> {
    /// Box a pointer that cames from Postgres.
    ///
    /// When this `PgBox<T>` is dropped, the boxed memory is **not** freed.  Since Postgres
    /// allocated it, Postgres is responsible for freeing it.
    #[inline]
    pub unsafe fn from_pg(ptr: *mut T) -> PgBox<T, AllocatedByPostgres> {
        PgBox::<T, AllocatedByPostgres> {
            ptr: NonNull::new(ptr),
            __marker: PhantomData,
        }
    }
}

impl<T> PgBox<T, AllocatedByRust> {
    /**
    Allocates memory in PostgreSQL and then places `val` into it.

    This value is managed by Rust, so gets dropped via normal [`Drop`][std::ops::Drop]
    semantics.

    If you need to give the boxed pointer to Postgres, call [`.into_pg()`][PgBox::into_pg].

    ```rust,no_run
    use pgx::{PgBox, AllocatedByRust};

    let ptr: PgBox<i32, AllocatedByRust> = PgBox::new(5);
    assert_eq!(*ptr, 5);

    let mut ptr: PgBox<Vec<i32>, AllocatedByRust> = PgBox::new(vec![]);
    assert_eq!(*ptr, Vec::<i32>::default());

    ptr.push(1);
    assert_eq!(*ptr, vec![1]);

    ptr.push(2);
    assert_eq!(*ptr, vec![1, 2]);

    ptr.push(3);
    assert_eq!(*ptr, vec![1, 2, 3]);

    let drained = ptr.drain(..).collect::<Vec<_>>();
    assert_eq!(drained, vec![1, 2, 3])
    ```
    */
    pub fn new(val: T) -> PgBox<T, AllocatedByRust> {
        let ptr = Self::alloc0();
        unsafe { core::ptr::write(ptr.as_ptr(), val) };
        ptr
    }

    /**
    Allocates memory in PostgreSQL and then places `val` into it.

    This value is managed by Rust, so gets dropped via normal [`Drop`][std::ops::Drop]
    semantics.

    If you need to give the boxed pointer to Postgres, call [`.into_pg()`][PgBox::into_pg].

    ```rust,no_run
    use pgx::{PgBox, PgMemoryContexts, AllocatedByRust};

    let ptr: PgBox<i32, AllocatedByRust> = PgBox::new_in_context(5, PgMemoryContexts::CurrentMemoryContext);
    assert_eq!(*ptr, 5);
    ```
    */
    pub fn new_in_context(


WN

addpl   x21, x21, #0
// CHECK-INST: addpl   x21, x21, #0
// CHECK-ENCODING: [0x15,0x50,0x75,0x04]
// CHECK-ERROR: instruction requires: sve or sme
// CHECK-UNKNOWN: 04755015 <unknown>

addpl   x23, x8, #-1
// CHECK-INST: addpl   x23, x8, #-1
// CHECK-ENCODING: [0xf7,0x57,0x68,0x04]
// CHECK-ERROR: instruction requires: sve or sme
// CHECK-UNKNOWN: 046857f7 <unknown>

addpl   sp, sp, #31
// CHECK-INST: addpl   sp, sp, #31
// CHECK-ENCODING: [0xff,0x53,0x7f,0x04]
// CHECK-ERROR: instruction requires: sve or sme
// CHECK-UNKNOWN: 047f53ff <unknown>

addpl   x0, x0, #-32
// CHECK-INST: addpl   x0, x0, #-32
// CHECK-ENCODING: [0x00,0x54,0x60,0x04]
// CHECK-ERROR: instruction requires: sve or sme
// CHECK-UNKNOWN: 04605400 <unknown>


 Result<E::G2Affine, std::io::Error> {
    let ptr = &mmap[range];
    // Safety: this operation is safe, because it's simply
    // casting to a known struct at the correct offset, given
    // the structure of the on-disk data.
    let repr =
        unsafe { *(ptr as *const [u8] as *const <E::G2Affine as CurveAffine>::Uncompressed) };

    if checked {
        repr.into_affine()
    } else {
        repr.into_affine_unchecked()
    }
    .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
    .and_then(|e| {
        if e.is_zero() {
            Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "point at infinity",
            ))
        } else {
            Ok(e)
        }
    })
}
<filename>src/sense.rs
use std::fmt;
use phf::phf_map;
use std::convert::TryInto;

// SPC-3 Table 28
// Used https://www.t10.org/lists/asc-num.htm (2021-03-25) as reference for
// implementation because the table there is sorted by key values. Should be
// the same info.
//
// Due to the limitations of the phf library, the key cannot be a tuple thus
// it is setup to be (ASC << 8) | (ASCQ)
//
// Note that a few messages match to a range. These are not in this map and
// must be checked else where.
// 0x40NN_u16 => "DIAGNOSTIC FAILURE ON COMPONENT NN (80h-FFh)",
// 0x4DNN_u16 => "TAGGED OVERLAPPED COMMANDS (NN = TASK TAG)",
// 0x70NN_u16 => "DECOMPRESSION EXCEPTION SHORT ALGORITHM ID OF NN",
static ADDITIONAL_SENSE_CODE_STRINGS: phf::Map <u16, &str> = phf_map! {
  0x0000_u16 => "NO ADDITIONAL SENSE INFORMATION",
  0x0001_u16 => "FILEMARK DETECTED",
  0x0002_u16 => "END_OF_PARTITION/MEDIUM DETECTED",
  0x0003_u16 => "SETMARK DETECTED",
  0x0004_u16 => "BEGINNING-OF-PARTITION/MEDIUM DETECTED",
  0x0005_u16 => "END-OF-DATA DETECTED",
  0x0006_u16 => "I/O PROCESS TERMINATED",
  0x0007_u16 => "PROGRAMMABLE EARLY WARNING DETECTED",
  0x0011_u16 => "AUDIO PLAY OPERATION IN PROGRESS",
  0x0012_u16 => "AUDIO PLAY OPERATION PAUSED",
  0x0013_u16 => "AUDIO PLAY OPERATION SUCCESSFULLY COMPLETED",
  0x0014_u16 => "AUDIO PLAY OPERATION STOPPED DUE TO ERROR",
  0x0015_u16 => "NO CURRENT AUDIO STATUS TO RETURN",
  0x0016_u16 => "OPERATION IN PROGRESS",
  0x0017_u16 => "CLEANING REQUESTED",
  0x0018_u16 => "ERASE OPERATION IN PROGRESS",
  0x0019_u16 => "LOCATE OPERATION IN PROGRESS",
  0x001A_u16 => "REWIND OPERATION IN PROGRESS",
  0x001B_u16 => "SET CAPACITY OPERATION IN PROGRESS",
  0x001C_u16 => "VERIFY OPERATION IN PROGRESS",
  0x001D_u16 => "ATA PASS THROUGH INFORMATION AVAILABLE",
  0x001


guidance.add(l10n.takeTimeReflectActing);
      warnings.add(l10n.avoidRushedDecisions);
    } else if (emotionalTone == 'negative') {
      guidance.add(l10n.practiceGratitudePositiveThinking);
      affirmations.add(l10n.chooseSeeGoodEverySituation);
    }

    return {
      'actions': guidance,
      'affirmations': affirmations,
      'warnings': warnings,
      'focusAreas': _getFocusAreas(cards, category, l10n),
    };
  }

  /// [_getFocusAreas] - Get areas to focus on based on selected cards
  static List<String> _getFocusAreas(
    List<Map<String, dynamic>> cards,
    String category,
    AppLocalizations l10n,
  ) {
    final focusAreas = <String>[];

    for (final card in cards) {
      final cardName = card['name']?.toString() ?? '';

      if (cardName.contains('High Priestess')) {
        focusAreas.add(l10n.intuitionInnerWisdom);
      } else if (cardName.contains('Hermit')) {
        focusAreas.add(l10n.selfReflectionSolitude);
      } else if (cardName.contains('Temperance')) {
        focusAreas.add(l10n.balanceModeration);
      } else if (cardName.contains('Justice')) {
        focusAreas.add(l10n.fairnessTruth);
      } else if (cardName.contains('Strength')) {
        focusAreas.add(l10n.innerStrengthCourage);
      }
    }

    // Add category-specific focus areas
    switch (category) {
      case 'love':
        focusAreas.add(l10n.emotionalCommunication);
        focusAreas.add(l10n.selfLoveBoundaries);
      case 'career':
        focusAreas.add(l10n.skillDevelopment);
        focusAreas.add(l10n.professionalNetworking);
      case 'finance':
        focusAreas.add(l10n.financialPlanning);
        focusAreas.add(l10n.responsibleSpending);
    }

    return focusAreas.take(5).toList(); // Limit to top 5 focus areas
  }

  static Map<String, dynamic> _generateTimingInsights(
    List<Map<String, dynamic>> cards,
    Map<String, dynamic> questionAnalysis,
    AppLocalizations l10n,
  ) {
    final category = questionAnalysis['primaryCategory'] as String;
    final questionType = questionAnalysis['questionType'] as String;

    // Analyze timing patterns in the cards
    final timingPatterns = <String>[];
    final timeframes = <String>[];

    for (final card in cards) {
      final meaning = card['upright_meaning']?.toString() ?? '';
      final lowerMeaning = meaning.toLowerCase();

      if (lowerMeaning.contains('new moon') ||
          lowerMeaning.contains('full moon')) {
        timingPatterns.add(l10n.lunarCyclesInfluenceTiming);
      } else if (lowerMeaning.contains('seasons') ||
          lowerMeaning.contains('cycles')) {
        timingPatterns.add(l10n.naturalCyclesImportant);
      } else if (lowerMeaning.contains('patience') ||
          lowerMeaning.contains('wait')) {
        timingPatterns.add(l10n.patienceRequired);
      }
    }

    // Generate timeframes based on category and question type
    switch (category) {
      case 'love':
        if (questionType == 'timing') {
          timeframes
            ..add(l10n.within1To3MonthsNewConnections)
            ..add(l10n.sixToTwelveMonthsDeeperCommitments);
        }
      case 'career':
        if (questionType == 'timing') {
          timeframes
            ..add(l10n.within3To6


, 6, 4, 0, 1, 32767, 15, 20, "NaN", "NaN", "NaN", "NaN"
    callfunction 34, 6, 8, 0, 1, 32767, 15, 20, "NaN", "NaN", "NaN", "NaN"
    callfunction 34, 6, 16, 0, 1, 32767, 15, 20, "NaN", "NaN", "NaN", "NaN"
    wait 1
    playsepan 1874, 0
    wait 14
    repeatse 2096, -117, 3, 4
    callfunction 36, 5, 4, 0, 1, 2, 320, "NaN", "NaN", "NaN", "NaN", "NaN"
    shaketargetmon 8, 4
    //wait 15
    callfunction 33, 5, 0, 0, 15, 0, 32767, "NaN", "NaN", "NaN", "NaN", "NaN"
    callfunction 68, 5, 8, 8, 0, 8, 0, "NaN", "NaN", "NaN", "NaN", "NaN"
    waitstate

    unloadparticle 0
    waitstate
    cmd43
    cmd0C 4, 1
    cmd0C 0, 0
    cmd0C 1, 32
    resetbg 43, 0x40001
    waitforchangebg
    end

.close