 (f= *fields) ; fields++)
  {
    if (read_all || bitmap_is_set(table->read_set, f->field_index))
    {
      switch(f->field_index)
      {
      case 0: /* HOST */
        m_row.m_host.set_field(f);
        break;
      case 1: /* EVENT_NAME */
        m_row.m_event_name.set_field(f);
        break;
      default: /* 2, ... COUNT/SUM/MIN/AVG/MAX */
        m_row.m_stat.set_field(f->field_index - 2, f);
        break;
      }
    }
  }

  return 0;
}

/* Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; version 2 of the License.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software Foundation,
  51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */

#include "my_global.h"
#include "pfs_global.h"
#include "pfs_lock.h"
#include "pfs_account.h"
#include "pfs_user.h"
#include "pfs_host.h"
#include "pfs_buffer_container.h"
#include "pfs_builtin_memory.h"

PFS_buffer_default_allocator<PFS_mutex> default_mutex_allocator(& builtin_memory_mutex);
PFS_mutex_container global_mutex_container(& default_mutex_allocator);

PFS_buffer_default_allocator<PFS_rwlock> default_rwlock_allocator(& builtin_memory_rwlock);
PFS_rwlock_container global_rwlock_container(& default_rwlock_allocator);

PFS_buffer_default_allocator<PFS_cond> default_cond_allocator(& builtin_memory_cond);
PFS_cond_container global_cond_container(& default_cond_allocator);

PFS_buffer_default_allocator<PFS_file> default_file_allocator(& builtin_memory_file);
PFS_file_container global_file_container(& default_file_allocator);

PFS_buffer_default_allocator<PFS_socket> default_socket_allocator(& builtin_memory_socket);
PFS_socket_container global_socket_container(& default_socket_allocator);

PFS_buffer_default_allocator<PFS_metadata_lock> default_mdl_allocator(& builtin_memory_mdl);
PFS_mdl_container global_mdl_container(& default_mdl_allocator);

PFS_buffer_default_allocator<PFS_setup_actor> default_setup_actor_allocator(& builtin_memory_setup_actor);
PFS_setup_actor_container global_setup_actor_container(& default_setup_actor_allocator);

PFS_buffer_default_allocator<PFS_setup_object> default_setup_object_allocator(& builtin_memory_setup_object);
PFS_setup_object_container global_setup_object_container(& default_setup_object_allocator);

PFS_buffer_default_allocator<PFS_table


/*
 * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2014
 * Robert Lougher <rob@jamvm.org.uk>.
 *
 * This file is part of JamVM.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/sysinfo.h>

#define __USE_GNU
#include <dlfcn.h>
#include <pthread.h>

#include "../../jam.h"

long long nativePhysicalMemory() {
    /* Long longs are used here because with PAE, a 32-bit
       machine can have more than 4GB of physical memory */

    long long num_pages = sysconf(_SC_PHYS_PAGES);
    long long page_size = sysconf(_SC_PAGESIZE);

    return num_pages * page_size;
}

void *nativeStackBase() {
#ifdef __UCLIBC__
    return NULL;
#else
    pthread_attr_t attr;
    void *addr;
    size_t size;

    pthread_getattr_np(pthread_self(), &attr);
    pthread_attr_getstack(&attr, &addr, &size);

    return addr+size;
#endif
}

int nativeAvailableProcessors() {
#ifdef __UCLIBC__
    return 1;
#else
    return get_nprocs();
#endif
}

char *nativeLibError() {
    return dlerror();
}

char *nativeLibPath() {
    return getenv("LD_LIBRARY_PATH");
}

void *nativeLibOpen(char *path) {
    return dlopen(path, RTLD_LAZY);
}

void nativeLibClose(void *handle) {
    dlclose(handle);
}

void *nativeLibSym(void *handle, char *symbol) {
    return dlsym(handle, symbol);
}

char *nativeLibMapName(char *name) {
   char *buff = sysMalloc(strlen(name) + sizeof("lib.so") + 1);

   sprintf(buff, "lib%s.so", name);
   return buff;
}

char *nativeJVMPath() {
    Dl_info info;
    char *path;

    if(dladdr(nativeJVMPath, &info) == 0) {
        printf("Error: dladdr failed.  Aborting VM\n");
        exitVM(1);
    }

    path = sysMalloc(strlen(info.dli_fname) + 1);
    strcpy(path, info.dli_fname);

    return path;
}


d_to_end(&mut buf).await.unwrap();
            socket.close().await.unwrap();

            assert_eq!(buf, b"hello world");
        };

        block_on(join(server, client));
    }
}
<reponame>cmyr/explore-font-types
pub mod cmap;
pub mod gdef;
pub mod glyf;
//pub mod gpos;
pub mod gsub;
pub mod head;
pub mod loca;
pub mod maxp;
//pub mod math;
pub mod stat;
//!# A custom derive implementation for `#[derive(Logpack)]`

#![crate_type = "proc-macro"]
#![recursion_limit = "250"]

extern crate proc_macro;

mod type_derive;
mod encode_derive;
use std::process::Command;
use std::collections::HashSet;

use proc_macro::TokenStream;
use proc_macro2::{TokenStream as Tokens};
use syn::{DeriveInput, GenericParam, Generics};
use quote::quote;

#[proc_macro_derive(Logpack, attributes(Logpack))]
pub fn derive(input: TokenStream) -> TokenStream {
    let input: DeriveInput = syn::parse(input).unwrap();
    let name = &input.ident;

    let a = type_derive::derive(&input);
    let b = encode_derive::derive(&input);
    let res = quote!(#a #b);

    if let Some((_, value)) =
        std::env::vars().find(|(key, _)| key.as_str() == "LOGPACK_DERIVE_SAVE_DIR")
    {
        let dir = std::path::Path::new(value.as_str());
        tokens_to_rustfmt_file(&dir.join(format!("derive_logpack_{}.rs", name)), &res);
    }

    res.into()
}

fn tokens_to_rustfmt_file(filename: &std::path::Path, expanded: &Tokens) {
    let mut file = std::fs::File::create(&filename).unwrap();
    use std::io::Write;
    file.write_all(format!("{}", expanded).as_bytes()).unwrap();
    Command::new("rustfmt")
        .args(&[filename])
        .output()
        .expect("failed to execute process");
}

fn add_trait_bounds(
    mut generics: Generics,
    skip_set: &HashSet<String>,
    trait_names: &[Tokens],
) -> Generics {
    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
            if let Some(_) = skip_set.get(&type_param.ident.to_string()) {
                continue;
            }
            for trait_name in trait_names {
                let bound = syn::parse(quote! { #trait_name }.into()).unwrap();
                type_param.bounds.push(bound);
            }
            let bound = syn::parse(quote! { 'static }.into()).unwrap();
            type_param.bounds.push(bound);
        }
    }
    generics
}
use object::thread::{Thread, State};
use wasm::VmCtx;
use sync::atomic::{Atomic, Ordering};
use sync::mpsc::IntrusiveMpsc;

/// This will crash the process when the value_offset doesn't point to committed memory.
/// While somewhat extreme, it is safe.
pub extern fn pfex_acquire(lock_offset: u32, vmctx: &VmCtx) {
    let user_data = &vmctx.data().user_data;
    let lock_ptr: *const Atomic<u32> = vmctx.fastpath_offset_ptr(lock_offset);
    let lock = unsafe { &*lock_ptr };

    loop {
        let mut pfex_map = user_data.process.pfex_map().lock();
        let locked = lock.load(Ordering::Relaxed);

        if locked == 0 {
            lock.store(1, Ordering::Release);
            break;
        } else {
            let queue = pfex_map
                .entry(lock_offset)
                .or


 ;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.myhome ul .list-collapse-indicator.collapse-indicator.collapse-icon {
  margin-left: -1.2em;
  position: absolute;
}

.myhome ul .list-collapse-indicator.collapse-indicator.collapse-icon::before {
  color: var(--text-accent);
  transition: transform 10ms linear 0s
}

/* 上头ul li的padding我调整了 */

/*

.myhome ul>li:nth-of-type(8n+1) {
  background-color: var(--p-myhome-color-1);
  padding-left: 1em;
}

.myhome ul>li:nth-of-type(8n+2) {
  background-color: var(--p-myhome-color-2);
  padding-left: 1em;
}

.myhome ul>li:nth-of-type(8n+3) {
  background-color: var(--p-myhome-color-3);
  padding-left: 1em;
}

.myhome ul>li:nth-of-type(8n+4) {
  background-color: var(--p-myhome-color-4);
  padding-left: 1em;
}

.myhome ul>li:nth-of-type(8n+5) {
  background-color: var(--p-myhome-color-5);
  padding-left: 1em;
}

.myhome ul>li:nth-of-type(8n+6) {
  background-color: var(--p-myhome-color-6);
  padding-left: 1em;
}

.myhome ul>li:nth-of-type(8n+7) {
  background-color: var(--p-myhome-color-7);
  padding-left: 1em;
}

.myhome ul>li:nth-of-type(8n) {
  background-color: var(--p-myhome-color-8);
  padding-left: 1em;
} */

.myhome ul ul {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 0rem;
  margin-top: 0.5rem;
  border-radius: 0;
  border: 0;
  background: none;
}

.myhome ul ul li:nth-child(even) {
  background-color: #fffbed !important;
}

.myhome ul>li:hover {
  border-color: var(--p-myhome-border-color) !important;
}

.myhome ul ul li:hover {
  background: var(--interactive-accent) !important;
  border-color: var(--p-myhome-border-color) !important;
  border-left: 1px solid var(--p-myhome-border-color) !important;
}

.theme-dark .myhome ul ul li:hover {
  border-color: #696969e1 !important;
  border-left: 1px solid #696969e1 !important;
}

.myhome ul ul li .task-list-item-checkbox {
  margin-left: 1.5rem;
}

.myhome ul ul ul {
  margin-right: 0;
}

.myhome ul ul::before {
  border-left: 0;
}

.markdown-preview-view.is-readable-line-width.myhome .markdown-preview-sizer>div>ul {
  max-width: 100%;
}

.myhome ul.contains-task-list ul,
.myhome ol.contains-task-list ul,
.myhome ul.contains-task-list ol,
.myhome ol.contains-task-list ol {
  position: initial;
}

.myhome ul.cont


		-o-animation: cssload-dot-rotate-2 4.6s 1.15s linear infinite;
		-ms-animation: cssload-dot-rotate-2 4.6s 1.15s linear infinite;
		-webkit-animation: cssload-dot-rotate-2 4.6s 1.15s linear infinite;
		-moz-animation: cssload-dot-rotate-2 4.6s 1.15s linear infinite;
}
.cssload-dot:nth-child(2):before {
	background-color: rgb(32,139,241);
	animation: cssload-dot-move 4.6s 1.15s ease infinite;
		-o-animation: cssload-dot-move 4.6s 1.15s ease infinite;
		-ms-animation: cssload-dot-move 4.6s 1.15s ease infinite;
		-webkit-animation: cssload-dot-move 4.6s 1.15s ease infinite;
		-moz-animation: cssload-dot-move 4.6s 1.15s ease infinite;
}

.cssload-dot:nth-child(3) {
	animation: cssload-dot-rotate-3 4.6s 2.3s linear infinite;
		-o-animation: cssload-dot-rotate-3 4.6s 2.3s linear infinite;
		-ms-animation: cssload-dot-rotate-3 4.6s 2.3s linear infinite;
		-webkit-animation: cssload-dot-rotate-3 4.6s 2.3s linear infinite;
		-moz-animation: cssload-dot-rotate-3 4.6s 2.3s linear infinite;
}
.cssload-dot:nth-child(3):before {
	background-color: rgb(175,225,2);
	animation: cssload-dot-move 4.6s 2.3s ease infinite;
		-o-animation: cssload-dot-move 4.6s 2.3s ease infinite;
		-ms-animation: cssload-dot-move 4.6s 2.3s ease infinite;
		-webkit-animation: cssload-dot-move 4.6s 2.3s ease infinite;
		-moz-animation: cssload-dot-move 4.6s 2.3s ease infinite;
}

.cssload-dot:nth-child(4) {
	animation: cssload-dot-rotate-4 4.6s 3.45s linear infinite;
		-o-animation: cssload-dot-rotate-4 4.6s 3.45s linear infinite;
		-ms-animation: cssload-dot-rotate-4 4.6s 3.45s linear infinite;
		-webkit-animation: cssload-dot-rotate-4 4.6s 3.45s linear infinite;
		-moz-animation: cssload-dot-rotate-4 4.6s 3.45s linear infinite;
}
.cssload-dot:nth-child(4):before {
	background-color: rgb(251,211,1);
	animation: cssload-dot-move 4.6s 3.45s ease infinite;
		-o-animation: cssload-dot-move 4.6s 3.45s ease infinite;
		-ms-animation: cssload-dot-move 4.6s 3.45s ease infinite;
		-webkit-animation: cssload-dot-move 4.6s 3.45s ease infinite;
		-moz-animation: cssload-dot-move 4.6s 3.45s ease infinite;
}

@keyframes cssload-dot-move {
	0% {
		transform: translateY(0);
	}
	18%, 22% {
		transform: translateY(-68px);
	}
	40%, 100% {
		transform: translateY(0);
	}
}

@-o-keyframes cssload-dot-move {
	0% {
		-o-transform: translateY(0);
	}
	18%, 22% {
		-o-transform: translateY(-68px);
	}
	40%, 100% {
		-o-transform:


tener('click', (event) => {
      const target = event.target.closest('[href*="/studios"], .the-suspects, .studio-card, .suspect-card');
      if (target) {
        this.showComment(this.getRandomQuote('SUSPECTS_CLICKS'));

        // Add special noir animations for suspect interactions
        if (Math.random() < 0.3) { // 30% chance
          const suspectCard = target.closest('.studio-card, .suspect-card');
          if (suspectCard) {
            noirAnimations.suspicionRising(suspectCard);
          } else {
            noirAnimations.investigationSweep(target);
          }
        }
        return;
      }
    });

    // Case Dashboard clicks
    document.addEventListener('click', (event) => {
      const target = event.target.closest('[href*="/dashboard"], .case-dashboard, .detective-badge');
      if (target) {
        this.showComment(this.getRandomQuote('CASE_DASHBOARD_CLICKS'));

        // Add detective spotlight effect
        if (Math.random() < 0.25) { // 25% chance
          noirAnimations.detectiveSpotlight(target);
        }
        return;
      }
    });

    // The Profile clicks
    document.addEventListener('click', (event) => {
      const target = event.target.closest('[href*="/settings"], .settings-link');
      if (target) {
        this.showComment(this.getRandomQuote('PROFILE_CLICKS'));
        return;
      }
    });

    // AI/NAVI clicks
    document.addEventListener('click', (event) => {
      const target = event.target.closest('.ai-fairy, .ai-status, [class*="ai-"], .fairy-chat');
      if (target) {
        this.showComment(this.getRandomQuote('AI_CLICKS'));

        // Add matrix rain effect for AI interactions
        if (Math.random() < 0.15) { // 15% chance
          noirAnimations.createMatrixRain(3000);
        }
        return;
      }
    });

    // Random clicks with low probability
    document.addEventListener('click', (_event) => {
      if (Math.random() < 0.05) { // 5% chance
        this.showComment(this.getRandomQuote('RANDOM_CLICKS'));
      }
    });

    // Double click detection
    let lastClickTime = 0;
    document.addEventListener('click', (_event) => {
      const currentTime = Date.now();
      if (currentTime - lastClickTime < 400) {
        const quotes = SAM_MAX_INTERACTIONS.DOUBLE_CLICK_RESPONSES;
        this.showComment(quotes[Math.floor(Math.random() * quotes.length)]);
      }
      lastClickTime = currentTime;
    });
  }

  setupIdleTimer() {
    let idleTime = 0;

    const resetIdleTimer = () => {
      idleTime = 0;
    };

    // Reset timer on user activity
    ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'].forEach(event => {
      document.addEventListener(event, resetIdleTimer, true);
    });

    // Check for idle state every second
    setInterval(() => {
      idleTime++;

      // Show idle comment after 30 seconds
      if (idleTime === 30) {
        const quotes = SAM_MAX_INTERACTIONS.IDLE_COMMENTS;
        this.showComment(quotes[Math.floor(Math.random() * quotes.length)], 3000);
      }

      // Show another comment after 2 minutes
      if (idleTime === 120) {
        this.showComment(this.getRandomQuote('RANDOM_CLICKS'), 3000);
        idleTime = 0; // Reset to avoid spamming
      }
    }, 1000);
  }


[type="search"],
.media-frame input[type="tel"],
.media-frame input[type="time"],
.media-frame input[type="url"],
.media-frame input[type="week"] {
	padding: 0 8px;
	/* inherits font size 13px */
	line-height: 2.15384615; /* 28px */
}

/* Search field in the Media Library toolbar */
.media-frame.mode-grid .wp-filter input[type="search"] {
	font-size: 14px;
	line-height: 2;
}

.media-frame input[type="text"]:focus,
.media-frame input[type="password"]:focus,
.media-frame input[type="number"]:focus,
.media-frame input[type="search"]:focus,
.media-frame input[type="email"]:focus,
.media-frame input[type="url"]:focus,
.media-frame textarea:focus,
.media-frame select:focus {
	border-color: #3582c4;
	box-shadow: 0 0 0 1px #3582c4;
	outline: 2px solid transparent;
}

.media-frame input:disabled,
.media-frame textarea:disabled,
.media-frame input[readonly],
.media-frame textarea[readonly] {
	background-color: #f0f0f1;
}

.media-frame input[type="search"] {
	-webkit-appearance: textfield;
}

.media-frame ::-webkit-input-placeholder {
	color: #646970;
}

.media-frame ::-moz-placeholder {
	color: #646970;
	opacity: 1;
}

.media-frame :-ms-input-placeholder {
	color: #646970;
}

/*
 * In some cases there's the need of higher specificity,
 * for example higher than `.media-embed .setting`.
 */
.media-frame .hidden,
.media-frame .setting.hidden {
	display: none;
}

/*!
 * jQuery UI Draggable/Sortable 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */
.ui-draggable-handle,
.ui-sortable-handle {
	touch-action: none;
}

/**
 * Modal
 */
.media-modal {
	position: fixed;
	top: 30px;
	left: 30px;
	right: 30px;
	bottom: 30px;
	z-index: 160000;
}

.wp-customizer .media-modal {
	z-index: 560000;
}

.media-modal-backdrop {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	min-height: 360px;
	background: #000;
	opacity: 0.7;
	z-index: 159900;
}

.wp-customizer .media-modal-backdrop {
	z-index: 559900;
}

.media-modal-close {
	position: absolute;
	top: 0;
	right: 0;
	width: 50px;
	height: 50px;
	margin: 0;
	padding: 0;
	border: 1px solid transparent;
	background: none;
	color: #646970;
	z-index: 1000;
	cursor: pointer;
	outline: none;
	transition: color .1s ease-in-out, background .1s ease-in-out;
}

.media-modal-close:hover,
.media-modal-close:active {
	color: #135e96;
}

.media-modal-close:focus {
	color: #135e96;
	border-color: #4f94d4;
	box-shadow: 0 0 3px rgba(34, 113, 177, 0.8);
	/* Only visible in Windows High Contrast mode */
	outline:


                            BOOST_LOG_TRIVIAL(info) << "ack of upgrade_confirm";
                        }

                        bool check_studio_cmd = true;
                        if (j["upgrade"].contains("sequence_id")) {
                            try
                            {
                                std::string str_seq = j["upgrade"]["sequence_id"].get<std::string>();
                                check_studio_cmd = is_studio_cmd(stoi(str_seq));
                            }
                            catch (...) { }
                        }

                        if (check_studio_cmd && j["upgrade"].contains("err_code")) {
                            if (j["upgrade"]["err_code"].is_number()) {
                                add_command_error_code_dlg(j["upgrade"]["err_code"].get<int>());
                            }
                        }
                    }
                }
            }
            catch (...) {
                ;
            }
        }

        // event info
        try {
            if (j.contains("event")) {
                if (j["event"].contains("event")) {
                    if (j["event"]["event"].get<std::string>() == "client.disconnected")
                        set_online_state(false);
                    else if (j["event"]["event"].get<std::string>() == "client.connected")
                        set_online_state(true);
                }
            }
        }
        catch (...)  {}

        if (!key_field_only) {
            BOOST_LOG_TRIVIAL(trace) << "parse_json  m_active_state =" << m_active_state;
            parse_state_changed_event();
        }
    }
    catch (const nlohmann::json::exception& e) {
        // Handle JSON parsing exceptions if necessary
        BOOST_LOG_TRIVIAL(trace) << "parse_json failed! dev_id=" << BBLCrossTalk::Crosstalk_DevId(this->get_dev_id()) <<", ewhat = " << e.what();
    } catch (...) {
        BOOST_LOG_TRIVIAL(trace) << "parse_json failed! dev_id=" << BBLCrossTalk::Crosstalk_DevId(this->get_dev_id());
    }

    std::chrono::system_clock::time_point clock_stop = std::chrono::system_clock::now();
    auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(clock_stop - clock_start);
    if (diff.count() > 10.0f) {
        BOOST_LOG_TRIVIAL(trace) << "parse_json timeout = " << diff.count();
    }

    return 0;
}

void MachineObject::set_ctt_dlg( wxString text){
    if (!m_set_ctt_dlg) {
        m_set_ctt_dlg = true;
        auto print_error_dlg = new GUI::SecondaryCheckDialog(nullptr, wxID_ANY, _L("Warning"), GUI::SecondaryCheckDialog::ButtonStyle::ONLY_CONFIRM);
        print_error_dlg->update_text(text);
        print_error_dlg->Bind(wxEVT_SHOW, [this](auto& e) {
            if (!e.IsShown()) {
                m_set_ctt_dlg = false;
            }
            });
        print_error_dlg->Bind(wxEVT_CLOSE_WINDOW, [this](auto& e) {
            e.Skip();
            m_set_ctt_dlg = false;
            });
        print_error_dlg->on_show();

    }
}

int MachineObject::publish_gcode(std::string gcode_str)
{
    json j;
    j["print"]["command"] = "gcode_line";
    j["print"]["param"] = gcode_str;
    j["print"]["sequence_id"] = std::to_string(MachineObject::m_sequence_id


 routes (on API routes, the standard API error is used.)
 */
export default class ErrorController extends BaseController {
    /**
     *  This method will be executed when a route is not found (the tipical 404
     *  error).
     *  @param req the standard lynx Request
     */
    public async onNotFound(req: Request): Promise<Response> {
        if (req.lynx && req.lynx.route && req.lynx.route.isAPI) {
            throw this.error(404, 'not found');
        }
        return this.render("lynx/404", req);
    }

    /**
     *  This method will be executed when an error is thrown during the execution
     *  of a route.
     *  @param error The error, with an additional "statusCode" property, containing the http status code.
     *  @param req the standard lynx Request
     */
    public async onError(error: Error, req: Request): Promise<Response> {
        let e = error as any;
        if (!e.statusCode) {
            e.statusCode = 500;
        }
        if (req.lynx && req.lynx.route && req.lynx.route.isAPI) {
            throw this.error(e.statusCode, error.message);
        }
        return this.render("lynx/error", req, {
            error: error,
            isProduction: isProduction()
        });
    }
}
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import sinon, { SinonStub, SinonSpy } from 'sinon';
import { CollectorInterface } from 'ember-collector-dispatcher/services/collector';
import Dispatcher, { DispatcherInterface } from 'ember-collector-dispatcher/services/dispatcher';
import Service from '@ember/service';
import { TestContext } from 'ember-test-helpers';
import { MAX_TIMEOUT, MAX_CONCURRENT } from 'ember-collector-dispatcher/constants';
import { service } from '@ember-decorators/service';
import waitUntil from '@ember/test-helpers/wait-until';

declare module '@ember/service' {
	interface Registry {
		'dummy-collector': CollectorInterface;
	}
}

module('Unit | Service | dispatcher', (hooks) => {
	let sandbox: sinon.SinonSandbox;
	let collector: CollectorInterface;
	let dispatcher: DispatcherInterface;

	class DummyCollector extends Service implements CollectorInterface {
		adapters = [];
		async count() {
			return 0;
		}
		async push() {}
		async pop() {
			return [];
		}
		async unshift() {}
		async shift() {
			return [];
		}
	}

	class DummyDispatcher extends Dispatcher {
		@service('dummy-collector')
		public collector!: CollectorInterface;

		async dispatch(items: any[]) {
			return items;
		}
	}

	setupTest(hooks);

	hooks.beforeEach(async function(this: TestContext) {
		sandbox = sinon.createSandbox({ useFakeTimers: true });

		this.owner.register('service:dummy-collector', DummyCollector);
		this.owner.register('service:dummy-dispatcher', DummyDispatcher);

		collector = this.owner.lookup('service:dummy-collector');
		dispatcher = this.owner.lookup('service:dummy-dispatcher');
	});

	test('it exists', (assert) => {
		assert.ok(dispatcher);
	});

	test('it has default values', (assert) => {
		assert.notOk(dispatcher.isRunning, 'dispatcher is not running');
		assert.notOk(dispatcher.isDispatching, 'dispatcher is not dispatching');
		assert.equal(dispatcher.maxTimeout, MAX_TIMEOUT


els[#self.panels] = nil
      self.panels[#self.panels] = nil
      self.buttons[#self.buttons] = nil
      if num_slots > 0 then
        -- change appearance of last panel
        local last_panel = self.panels[#self.panels - 1]
        last_panel.y = last_panel.y - 4
        last_panel.sprite_index = 156
      end
    end
  end
  self.num_slots = num_slots
  self.height = 167 + (num_slots) * 29
end

function UIPlaceObjects:addObjects(object_list, pay_for)
  self.visible = true -- even if no objects are to be placed, make the window visible again

  if not object_list then
    object_list = {}
  end

  if #object_list == 0 and #self.objects == 0 then
    return
  end

  -- Detect objects already existing in self.objects and increment its quantity
  -- rather than adding new objects lines.
  local new_index = 1
  while true do
    local new_object = object_list[new_index]
    if not new_object then break end
    for _, object in ipairs(self.objects) do
      if new_object.qty > 0 and new_object.object.thob == object.object.thob then
        object.qty = object.qty + new_object.qty
        if pay_for then
          local build_cost = self.ui.hospital:getObjectBuildCost(new_object.object.id)
          local msg = _S.transactions.buy_object .. ": " .. object.object.name
          self.ui.hospital:spendMoney(new_object.qty * build_cost, msg, new_object.qty * build_cost)
        end
        -- If this is an object that has been created in the world already, add it to the
        -- associated list of objects to re-place.
        if new_object.existing_object then
          if not object.existing_objects then
            object.existing_objects = {}
          end
          -- Insert the new object in the beginning of the list so that that this object
          -- is the one to be placed first. (LIFO)
          table.insert(object.existing_objects, 1, new_object.existing_object)
        end
        table.remove(object_list, new_index)
        new_index = new_index - 1
        break
      end
    end
    new_index = new_index + 1
  end

  self.place_objects = true -- When adding objects guess we want to place objects

  self.object_anim = TH.animation()
  self.object_slave_anim = TH.animation()
  local total_objects = #self.objects + #object_list
  self:resize(total_objects)

  for _, object in pairs(object_list) do
    if object.existing_object then
      object.existing_objects = {object.existing_object}
    end
    self.objects[#self.objects + 1] = object
    if pay_for then
      local build_cost = self.ui.hospital:getObjectBuildCost(object.object.id)
      local msg = _S.transactions.buy_object .. ": " .. object.object.name
      self.ui.hospital:spendMoney(object.qty * build_cost, msg, object.qty * build_cost)
    end
  end

  -- sort list by size of object (number of tiles in the first existing orientation (usually north))
  table.sort(self.objects, function(o1, o2)
    local orient1 = o1.object.orientations.north or o1.object.orientations.east or
                    o1.object.orientations.south or o1.object.orientations.west
    local orient2 = o2.object.orientations.north or o2.object.orientations.east or
                    o2.object.orientations.south or o2.object.o


ers.
	add	r2, sp, #8+64			@ load result
	adr	r3, CNAME(ffi_closure_ret)
#ifndef __thumb__
	add	pc, r3, r0, lsl #3
#else
	add	r3, r3, r0, lsl #3
	mov	pc, r3
#endif
	cfi_endproc
	UNWIND(.fnend)
ARM_FUNC_END(ffi_closure_SYSV)

ARM_FUNC_START(ffi_go_closure_VFP)
	cfi_startproc
	stmdb	sp!, {r0-r3}			@ save argument regs
	cfi_adjust_cfa_offset(16)
	ldr	r0, [ip, #4]			@ load cif
	ldr	r1, [ip, #8]			@ load fun
	mov	r2, ip				@ load user_data
	b	0f
	cfi_endproc
ARM_FUNC_END(ffi_go_closure_VFP)

ARM_FUNC_START(ffi_closure_VFP)
	UNWIND(.fnstart)
	cfi_startproc
#ifdef _WIN32
	ldmfd	sp!, {r0, ip}			@ restore fp (r0 is used for stack alignment)
#endif
	stmdb	sp!, {r0-r3}			@ save argument regs
	cfi_adjust_cfa_offset(16)

#if FFI_EXEC_TRAMPOLINE_TABLE
	ldr ip, [ip]				@ ip points to the config page, dereference to get the ffi_closure*
#endif
	ldr	r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET]	@ load cif
	ldr	r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4]  @ load fun
	ldr	r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8]  @ load user_data
0:
	add	ip, sp, #16
	sub	sp, sp, #64+32			@ allocate frame
	cfi_adjust_cfa_offset(64+32)
#ifdef __clang__
	vstm sp, {d0-d7}
#else
	stc	p11, cr0, [sp], {16}		@ vstm sp, {d0-d7}
#endif
	stmdb	sp!, {ip,lr}

	/* See above.  */
	UNWIND(.save {sp,lr})
	cfi_adjust_cfa_offset(8)
	cfi_rel_offset(lr, 4)

	add	r3, sp, #8			@ load frame
	bl	CNAME(ffi_closure_inner_VFP)

	@ Load values returned in registers.
	add	r2, sp, #8+64			@ load result
	adr	r3, CNAME(ffi_closure_ret)
#ifndef __thumb__
	add	pc, r3, r0, lsl #3
#else
	add	r3, r3, r0, lsl #3
	mov	pc, r3
#endif
	cfi_endproc
	UNWIND(.fnend)
ARM_FUNC_END(ffi_closure_VFP)

/* Load values returned in registers for both closure entry points.
   Note that we use LDM with SP in the register set.  This is deprecated
   by ARM, but not yet unpredictable.  */

ARM_FUNC_START_LOCAL(ffi_closure_ret)
	cfi_startproc
	cfi_rel_offset(sp, 0)
	cfi_rel_offset(lr, 4)
0:
E(ARM_TYPE_VFP_S)
#ifdef __clang__
	vldr s0, [r2]
#else
	ldc	p10, cr0


�……|어어, 어째서 호박까지 그렇게 무섭게 만든 거야!?|다다, 다들 핼러윈을 즐기고 있어…… 떠, 떠떠떠떨고 있지 않다구!?",
		voice_key_2 = -1,
		profile = "",
		mission_complete = "",
		headtouch = "",
		feeling2 = "",
		feeling4 = "",
		unlock = "핼러윈은 유령이 잔뜩…… 아, 안 무섭거든! ……저저, 저, 저기… 손잡아도 돼?",
		battle = "",
		login = "지지지지휘관! 트릭 오어…… 오, 오어…… 나한테는 무리야…",
		vote = "",
		detail = "해, 핼러윈 귀신은 다 가짜지!? ……진짜가 있거나 하진 않지!?",
		couple_encourage = {}
	},
	[302052] = {
		touch = "따, 따뜻하게 해줄까?",
		feeling3 = "",
		upgrade = "",
		expedition = "",
		win_mvp = "",
		home = "{namecode:46} 언니는 이걸 잠옷이라고 했지만, 그래도 너무 헐렁해…… 그, 그렇게 보지 마.",
		mission = "",
		touch2 = "분명 일부러 이 기회에 괴롭히는 거야!",
		feeling1 = "",
		skill = "",
		drop_descrip = "지휘관? 나는 크리스마스 선물을 포장하려고 여기에 계속 있었던 거야. 저, 절대로 벽난로가 따뜻해서 이러고 있는게 아니라구?",
		mail = "",
		lose = "",
		propose = "",
		hp_warning = "",
		id = 302052,
		voice_key = 0,
		feeling5 = "크리스마스를 어떻게 보내야 하는지는 잘 모르지만, 지금처럼 지휘관과 둘이 난로 앞에 앉아있는 것만으로도… 좋, 좋은 것 같아…… 약간 춥, 춥네. 좀 더 가까이 있고 싶어…… ",
		main = "벽난로 옆은 정말 따뜻해~ 말랑말랑한 만쥬도 껴안고 있을 수 있고~|음… 지휘관, 모두에게 어떤 크리스마스 선물을 준비해 주는 게 좋을까? |크리스마스에 얽힌 귀신이나 유령에 관한 이야기가 없다는 건 확인했지만… 지휘관


.align	2
.L1105:
	.word	.LANCHOR0
	.word	.LANCHOR0+2790
	.word	.LANCHOR3-3116
	.word	.LANCHOR0+2792
	.word	.LANCHOR3-3104
	.word	.LANCHOR0+2794
	.word	.LANCHOR3-3100
	.fnend
	.size	zftl_insert_data_list, .-zftl_insert_data_list
	.align	2
	.global	zftl_gc_get_free_sblk
	.syntax unified
	.arm
	.fpu softvfp
	.type	zftl_gc_get_free_sblk, %function
zftl_gc_get_free_sblk:
	.fnstart
	@ args = 0, pretend = 0, frame = 0
	@ frame_needed = 0, uses_anonymous_args = 0
	push	{r0, r1, r2, r3, r4, r5, r6, r7, r8, lr}
	.save {r4, r5, r6, r7, r8, lr}
	.pad #16
	movw	r2, #65535
	ldr	r8, .L1126
	ldr	r3, [r8, #1096]
	add	r3, r3, #588
	ldrh	r4, [r3]
	clz	r3, r0
	lsr	r3, r3, #5
	cmp	r4, r2
	moveq	r3, #0
	cmp	r3, #0
	beq	.L1108
	mov	r1, r4
	ldr	r0, .L1126+4
	bl	printk
	ldr	r3, [r8, #1096]
	mvn	r2, #0
	add	r3, r3, #588
	strh	r2, [r3]	@ movhi
.L1109:
	mov	r0, r4
	add	sp, sp, #16
	@ sp needed
	pop	{r4, r5, r6, r7, r8, pc}
.L1108:
	movw	r3, #2786
	mov	r7, r1
	ldrh	r1, [r8, r3]
	movw	r3, #2788
	ldrh	r3, [r8, r3]
	mov	r6, r0
	mov	r5, r8
	ldr	r0, .L1126+8
	cmp	r1, r3
	bcc	.L1110
	add	r2, r8, #2784
	ldrh	r2, [r2]
	cmp	r3, #0
	cmpne	r2, r1
	bls	.L1111
.L1110:
	cmp	r6, #0
	ldr	r2, .L1126+12
	rsbne	r1, r1, r1, lsl #3
	lsreq	r1, r3, #2
	ubfxne	r1, r1, #3, #16
	sub	r0, r0, #8
.L1125:
	bl	_list_pop_index_node
	uxth	r4, r0
	movw	r3, #65535
	cmp	r4, r3
	bne	.L1116
	movw	r3, #2788
	mov	r2, r7
	ldrh	r3, [r5, r3]
	mov	r1, r4
	ldr	r0, .L1126+16
	str	r3, [sp, #4]
	ldr	r3, .L1126+20
	ldrh	r3, [r3]
	str	r3, [sp]
	ldr	r3, .L1126+24
	ldr	r3, [r3, #-3088]
	bl	printk
.L1116:
	cmp	r6, #0
	beq	.L1109
	ldr	r3, .L1126+28
	ldr	r3, [


ART: Usart {}
/// USART receiver input
pub trait UsartRxPin<PIO, USART> where PIO: PinId, USART: Usart {}
/// USART request-to-send output
pub trait UsartRtsPin<PIO, USART> where PIO: PinId, USART: Usart {}
/// USART clear-to-send input
pub trait UsartCtsPin<PIO, USART> where PIO: PinId, USART: Usart {}
/// USART serial clock
pub trait UsartSclkPin<PIO, USART> where PIO: PinId, USART: Usart {}

pub struct NoPio;
impl PinId for NoPio {
    const PORT: usize = !0;
    const NUMBER: u8 = !0;
    const MASK: u32 = !0;
    const OFFSET: usize = !0;

    const TYPE: PinType = PinType::D;
}

// TODO: revisit this. Instead of passing in fake pins,
// write proper drivers for the use cases.
// Think about using a generic enum {Read, Write, ReadWrite}
// parameter
/// Filler type for when no Tx is necessary
pub struct NoTx;
/// Filler type for when no Rx is necessary
pub struct NoRx;
impl<USART: Usart> UsartTxPin<NoPio, USART> for NoTx {}
impl<USART: Usart> UsartRxPin<NoPio, USART> for NoRx {}

pub trait I2cPins<PIO1: PinId, PIO2: PinId, I2C: I2c> {}

impl<PIO1, PIO2, I2C, SCL, SDA> I2cPins<PIO1, PIO2, I2C> for (SCL, SDA)
where
    PIO1: PinId,
    PIO2: PinId,
    I2C: I2c,
    SCL: I2cSclPin<PIO1, I2C>,
    SDA: I2cSdaPin<PIO2, I2C>,
{}

pub trait SpiPins<PIO1: PinId, PIO2: PinId, PIO3: PinId, PIO4: PinId, SPI: Spi> {
    const CS: ChipSelect;
}

impl<PIO1, PIO2, PIO3, PIO4, SPI, SCK, MISO, MOSI, CS>
    SpiPins<PIO1, PIO2, PIO3, PIO4, SPI>
for (SCK, MOSI, MISO, CS) where
    PIO1: PinId,
    PIO2: PinId,
    PIO3: PinId,
    PIO4: PinId,
    SPI: Spi,
    SCK: SpiSckPin<PIO1, SPI>,
    MOSI: SpiMosiPin<PIO2, SPI>,
    MISO: SpiMisoPin<PIO3, SPI>,
    CS: SpiCsPin<PIO4, SPI>,
{
    const CS: ChipSelect = CS::CS;
}

pub trait UsartPins<PIO1: PinId, PIO2: PinId, USART: Usart> {}

impl<PIO1, PIO2, USART, TX, RX> UsartPins<PIO1, PIO2, USART> for (TX, RX)
where
    PIO1: PinId,
    PIO2: PinId,
    USART: Usart,
    TX: UsartTxPin<PIO1, USART>,
    RX: UsartRxPin<PIO2, USART>,
{}

// Note: Pio0_12 can be both: into_i2c_3_scl_pin() and into_i2c_6_scl_pin() [alt1 vs alt7]
//
// pin.into_I2C3_SCL_pin()
//
// what about: let scl_pin: <_, Special<I2c4, Scl>> = pins.pio1_20.into();
// what about: let scl_pin = Pin<Pio1_20, Special<I2c4, Scl>>::from(pins.pio1_20);
//
// what about... `I2cMaster(i2c, (p0_12.into(), p1_1.into()))` <-- too much magic/work in `From`?

/* Copyright (c) 2019-2021 <NAME> <<EMAIL>>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope


from typing import Optional

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

# Time: O(N)
# Space: O(N)
class FindElements:
    def __init__(self, root: Optional[TreeNode]):
        """
        Constructor: Recovers the contaminated binary tree by assigning correct values.
        - The root of the tree is set to 0.
        - Uses a helper function `recover_binary_tree` to restore all node values.
        - Stores recovered values in a set for fast lookup.
        """
        self.node_values = set()  # Store all valid node values for O(1) lookup.

        if root:
            root.val = 0  # The root is always set to 0.
            self.node_values.add(0)  # Add root's value to the set.
            self.recover_binary_tree(root.left, 1)  # Restore the left subtree.
            self.recover_binary_tree(root.right, 2) # Restore the right subtree.

    def recover_binary_tree(self, curr: TreeNode, val: int):
        """
        Recursively restores the tree using the given formula:
        - Left child of a node with value x: 2 * x + 1
        - Right child of a node with value x: 2 * x + 2
        """
        if not curr:
            return  # Base case: Stop if the node is None.

        curr.val = val  # Assign the correct value to the current node.
        self.node_values.add(val)  # Store the value in the set for quick lookup.

        # Recursively recover the left and right subtrees.
        self.recover_binary_tree(curr.left, 2 * val + 1)
        self.recover_binary_tree(curr.right, 2 * val + 2)

    def find(self, target: int) -> bool:
        """
        Checks if a given value exists in the recovered tree.
        - Returns True if the target is in the set, otherwise False.
        - O(1) time complexity due to set lookup.
        """
        return target in self.node_values

# Your FindElements object will be instantiated and called as such:
# obj = FindElements(root)
# param_1 = obj.find(target)

# Create a contaminated binary tree (all values set to -1)
# Example:
#       -1
#      /   \
#    -1     -1
#   /  \   /  \
# -1   -1 -1  -1
root = TreeNode(-1)
root.left = TreeNode(-1)
root.right = TreeNode(-1)
root.left.left = TreeNode(-1)
root.left.right = TreeNode(-1)
root.right.left = TreeNode(-1)
root.right.right = TreeNode(-1)

# Instantiate the FindElements class
find_elements = FindElements(root)

# Test the `find` method
print(find_elements.find(2))  # Output: True  (since 2 should exist in the recovered tree)
print(find_elements.find(5))  # Output: True  (5 should exist)
print(find_elements.find(10)) # Output: False (10 is not in the tree)


    private float progress;
            private boolean done = false;
            private boolean cancelled;
            private AnimatedFloat animatedHasPercent = new AnimatedFloat(this::invalidateSelf, 0, 320, CubicBezierInterpolator.EASE_OUT_QUINT);
            private AnimatedFloat animatedProgress = new AnimatedFloat(this::invalidateSelf, 0, 320, CubicBezierInterpolator.EASE_OUT_QUINT);
            private AnimatedFloat animatedDone = new AnimatedFloat(this::invalidateSelf, 0, 320, CubicBezierInterpolator.EASE_OUT_QUINT);

            private RLottieDrawable doneDrawable;

            public StatusDrawable(Context context, View view) {
                this.view = view;
                start = System.currentTimeMillis();
                doc = context.getResources().getDrawable(R.drawable.search_files_filled).mutate();
                strokePaint.setStyle(Paint.Style.STROKE);
                strokePaint.setStrokeWidth(dp(2));
                strokePaint.setStrokeCap(Paint.Cap.ROUND);
                strokePaint.setStrokeJoin(Paint.Join.ROUND);
            }

            public void reset() {
                this.animatedDone.set(this.done = false, true);
                this.cancelled = false;
                if (doneDrawable != null) {
                    doneDrawable.recycle(true);
                    doneDrawable = null;
                }
                this.animatedHasPercent.set(this.hasPercent = false, true);
            }

            public void setProgress(Pair<Long, Long> progress) {
                hasPercent = progress != null && progress.second > 0;
                if (hasPercent) {
                    this.progress = Utilities.clamp((float) progress.first / progress.second, 1, 0);
                }
                invalidateSelf();
            }

            public void setDone(boolean cancelled) {
                if (this.done) return;
                this.done = true;
                this.cancelled = cancelled;
                doneDrawable = new RLottieDrawable(cancelled ? R.raw.error : R.raw.contact_check, cancelled ? "error" : "contact_check", dp(40), dp(40));
                doneDrawable.setMasterParent(view);
                doneDrawable.setAllowDecodeSingleFrame(true);
                doneDrawable.start();
                if (!cancelled) {
                    progress = 1.0f;
                }
            }

            @Override
            public void draw(@NonNull Canvas canvas) {
                final Rect bounds = getBounds();
                final int cx = bounds.centerX(), cy = bounds.centerY();

                final float done = this.animatedDone.set(this.done);

                if (done < 1) {
                    final float s = .6f + .4f * (1.0f - done);
                    canvas.save();
                    canvas.scale(s, s, cx, cy);
                    doc.setBounds(
                        cx - doc.getIntrinsicWidth() / 2,
                        cy - doc.getIntrinsicHeight() / 2,
                        cx + doc.getIntrinsicWidth() / 2,
                        cy + doc.getIntrinsicHeight() / 2
                    );
                    doc.setAlpha((int) (0xFF * (1.0f - done)));
                    doc.draw(canvas);

                    final float r = dp(14);
                    strokePaint.setColor(Theme.multAlpha(0xFFFFFFFF, .20f * (1.0f - done)));
                    canvas.drawCircle(cx, cy, r, strokePaint);
                    strokePaint.setColor(Theme.multAlpha(0xFFFFFFFF, 1.0f * (1.0f - done)));
                    rect.set(cx - r, cy - r, cx + r, cy + r);

                    final float hasPercent = this.animatedHasPercent.set(this.hasPercent);

                    strokePaint.setColor(Theme.multAlpha(0xFFFFFFFF, .15f * (1.0f - done) * (1.0f - hasPercent)));
                    canvas.drawArc(rect, (-90 + -((-1.0f + ((System.currentTimeMillis() - start) % 600) / 600.0f) * 360)), -90.0f, false, strokePaint);

                    float t = ((System.currentTimeMillis() - start


er](https://twitter.com/shashank020597)
- [Github](https://github.com/Shashank02051997)
- [Linkedin](https://www.linkedin.com/in/shashank-singhal-a87729b5/)
- [Facebook](https://www.facebook.com/shashanksinghal02)

### Like our facebook page
- [Android UI's Bucket](https://www.facebook.com/androiduisbucket)

## Donation
If this project help you reduce time to develop, you can give me a cup of coffee :)

# PlantShopUI-Android
Check out the new style for App Design aims for Online Plant Shop Service...😉😀😁😎

## Screenshots

**Please click the image below to enlarge.**

## Prerequisites 📝
- IntelliJ IDEA (any edition) or Android Studio(IDE) to run this project

## Contributing

Please fork this repository and contribute back using
[pull requests](https://github.com/Shashank02051997/PlantShopUI-Android/pulls).

Any contributions, large or small, major features, bug fixes, are welcomed and appreciated
but will be thoroughly reviewed .

### Contact - Let's become friend
- [Twitter](https://twitter.com/shashank020597)
- [Github](https://github.com/Shashank02051997)
- [Linkedin](https://www.linkedin.com/in/shashank-singhal-a87729b5/)
- [Facebook](https://www.facebook.com/shashanksinghal02)

### Like our facebook page
- [Android UI's Bucket](https://www.facebook.com/androiduisbucket)

## Donation
If this project help you reduce time to develop, you can give me a cup of coffee :)


 to close connection for migrationID %s, type is %v", migrationID, obj)
			return fmt.Errorf("unknown type %v", obj)
		}
	}
	return nil
}

func (s *SynchronizationController) updateMigrationFunc(_, curr interface{}) {
	s.enqueueVirtualMachineInstanceFromMigration(curr)
}

func (s *SynchronizationController) enqueueVirtualMachineInstanceFromMigration(obj interface{}) {
	migration, ok := obj.(*virtv1.VirtualMachineInstanceMigration)
	if ok {
		key := controller.NamespacedKey(migration.Namespace, migration.Spec.VMIName)
		s.queue.Add(key)
	}
}

func (s *SynchronizationController) Run(threadiness int, stopCh <-chan struct{}) error {
	defer controller.HandlePanic()
	defer s.queue.ShutDown()
	defer s.closeConnections()

	log.Log.Info("starting vmi status synchronization controller.")

	// Wait for cache sync before we start the pod controller
	cache.WaitForCacheSync(stopCh, s.hasSynced)

	// Start the actual work
	for i := 0; i < threadiness; i++ {
		go wait.Until(s.runWorker, time.Second, stopCh)
	}
	go wait.Until(s.runConnectionCleanup, 5*time.Second, stopCh)

	conn, err := s.createTcpListener()
	if err != nil {
		log.Log.Criticalf("received error %v, exiting", err)
		return err
	} else {
		go func() {
			s.grpcServer.Serve(conn)
		}()
	}
	if err := s.rebuildConnectionsAndUpdateSyncAddress(); err != nil {
		return err
	}

	log.Log.Info("waiting on stop signal")
	<-stopCh
	log.Log.Info("normally stopping vmi status synchronization controller.")
	return nil
}

func (s *SynchronizationController) closeConnections() {
	log.Log.V(1).Info("closing listener and grpcserver")
	if s.listener != nil {
		s.listener.Close()
	}
	if s.grpcServer != nil {
		s.grpcServer.GracefulStop()
	}
	log.Log.V(1).Infof("closing outbound connections")
	s.syncOutboundConnectionMap.Range(closeMapConnections)
	log.Log.V(1).Infof("closing inbound connections")
	s.syncReceivingConnectionMap.Range(closeMapConnections)
}

func closeMapConnections(k, obj interface{}) bool {
	outboundConnection, ok := obj.(*SynchronizationConnection)
	if ok && outboundConnection != nil {
		log.Log.V(1).Infof("closing connection for migration ID: %s", outboundConnection.migrationID)
		if err := outboundConnection.Close(); err != nil {
			log.Log.Warningf("unable to close connection for VMI %s during shutdown, %v", k, err)
		}
	} else {
		log.Log.Warningf("unable to close connection for VMI %s during shutdown", k)
	}
	return true
}

func (s *SynchronizationController) runWorker() {
	for s.Execute() {
	}
}

func (s *SynchronizationController) Execute() bool {
	key, quit := s.queue.Get()
	if quit {
		return false
	}

	defer s.queue.Done(key)
	err := s.execute(key)

	if err != nil {
		log.Log.Reason(err).Infof("reenqueuing VirtualMachineInstance %v", key)
		s.queue.AddRateLimited(key)
	} else {
		log.Log.V(4).Infof("processed VirtualMachineInstance %v", key)
		s.queue.Forget(key)
	}
	return true
}

func (s *SynchronizationController) execute(key string) error {
	// Fetch the latest VMI state from cache
	obj, exists, _ := s.vmiInformer.GetStore().GetByKey(key)
	if !exists {
		return nil
	}
	vmi := obj.(*virtv1.VirtualMachineInstance)

	migration,


lpha017, alpha018, alpha019, alpha020,
             alpha021,
             alpha022, alpha023, alpha024, alpha025, alpha026, alpha027, alpha028, alpha029, alpha030, alpha031,
             alpha032,
             alpha033, alpha034, alpha035, alpha036, alpha037, alpha038, alpha039, alpha040, alpha041, alpha042,
             alpha043,
             alpha044, alpha045, alpha046, alpha047, alpha049, alpha050, alpha051, alpha052, alpha053, alpha054,
             alpha055,
             alpha057, alpha060, alpha061, alpha062, alpha064, alpha065, alpha066, alpha068, alpha071, alpha072,
             alpha073,
             alpha074, alpha075, alpha077, alpha078, alpha081, alpha083, alpha084, alpha085, alpha086, alpha088,
             alpha092,
             alpha094, alpha095, alpha096, alpha098, alpha099, alpha101
             ]


st(node)    # We don't distinguish tuples and lists

  def generic_visit(self, node):
    raise ValueError("Unsupported syntax at %s:%s" % (node.lineno, node.col_offset + 1))

class _EntityCollector(_TreeConverter):
  def __init__(self):
    self.entities = []    # NamedEntity list

  def visit_Attribute(self, node):
    parent = self.visit(node.value)

    # We recognize a couple of specific patterns for entities that may be affected by renames.
    if parent == ['Name', 'rec'] or parent == ['Name', 'newRec']:
      # rec.COL refers to the column from the table that the rule is on.
      self.entities.append(NamedEntity('recCol', node.last_token.startpos, node.attr, None))
    if parent == ['Name', 'user']:
      # user.ATTR is a user attribute.
      self.entities.append(NamedEntity('userAttr', node.last_token.startpos, node.attr, None))
    elif parent[0] == 'Attr' and parent[1] == ['Name', 'user']:
      # user.ATTR.COL is a column from the lookup table of the UserAttribute ATTR.
      self.entities.append(
          NamedEntity('userAttrCol', node.last_token.startpos, node.attr, parent[2]))

    return ["Attr", parent, node.attr]


 {
    const data: Buffer = await readFile(p);
    const result = await parseString(data);
    songs = parseSongs(result);
    songById = {};
    for (const song of songs) {
        songById[song.id] = song;
    }
    return songs;
}

export function getAll() {
    return songs;
}

export function getById(songId): Song {
    return songById.hasOwnProperty(songId) ? songById[songId] : null;
}

function parseSongs(json): Song[] {
    const artists = json.Library.Artist;
    const songs: Song[] = [];
    const set: Set<string> = new Set();
    for (const a of artists) {
        const artistObject = a.$;
        const artistSongs = a.Song;
        if (artistSongs) {
            for (const s of artistSongs) {
                const songObject = s.$;
                const song: Song = new Song(+songObject.id, artistObject.name, songObject.name, +songObject.duration);
                const key: string = `${song.artist}_${song.parsedName}`;
                if (song.parsedName && !set.has(key)) {
                    set.add(key);
                    songs.push(song);
                }
            }
        }
    }
    return songs;
}
import React from 'react';
import { Book, CalendarViewDay, Code, Functions, LineStyle } from '@material-ui/icons';
import { SvgIconProps } from '@material-ui/core/SvgIcon';

export interface EntryProps {
    id: string,
    title: string,
    type: EntryType,
}

export enum EntryType {
    Project = 'project',
    Service = 'service',
    Function = 'function',
    Datatype = 'datatype',
    Textblock = 'textblock',
}

export const EntryChildTypes = (type: EntryType) : EntryType[] => {
    switch (type) {
        case EntryType.Project:
            return [EntryType.Service];
        case EntryType.Service:
        case EntryType.Function:
            return [EntryType.Datatype, EntryType.Textblock];
        case EntryType.Datatype:
        case EntryType.Textblock:
            return [];
    }
}

export const EntryIcon = (type: EntryType) : React.ComponentType<SvgIconProps> => {
    switch (type) {
        case EntryType.Project:
            return Book;
        case EntryType.Service:
            return Code;
        case EntryType.Function:
            return Functions;
        case EntryType.Datatype:
            return CalendarViewDay;
        case EntryType.Textblock:
            return LineStyle;
    }
}
import { GameStates } from './constants';

export enum GameMessages {
  Welcome = 'welcome',
  Start = 'start',
  Win = 'win',
  Loss = 'loss',
  Continue = 'continue',
  Pattern = 'pattern',
  Input = 'input',
  StartButton = 'startButton',
  Confirm = 'confirm',
  Cancel = 'cancel',
  Quit = 'quit',
  PlayingBack = 'playingBack',
}

export const Messages = {
  [GameMessages.Welcome]: "Let's play Simon Says.",
  [GameMessages.Win]: 'Great job!',
  [GameMessages.Loss]: "You didn't match the pattern!",
  [GameMessages.Continue]: 'Would you like to try again?',
  [GameMessages.PlayingBack]: 'Watch the pattern carefully!',
  [GameMessages.Input]: 'Click the squares and repeat the pattern.',
};

export const GameControlsMessages = {
  [GameMessages.StartButton]: 'Start',
  [GameMessages.Confirm]: 'Yes',
  [GameMessages.Cancel]: 'No',
  [G


using Cinemachine;
using UnityEngine;

namespace KartGame.Utilities
{
    /// <summary>
    /// A preview utility to help cycle the Cinemachine Camera to look at and follow various targets.
    /// </summary>
    [RequireComponent(typeof(CinemachineVirtualCamera))]
    public class CineMachineTargeteer : MonoBehaviour
    {
        [Tooltip("What gameObjects do we want to look at?")]
        public Transform[] Targets;
        [Tooltip("Which key allows us to switch targets? By default, we use the Spacebar.")]
        public KeyCode CyclingKey = KeyCode.Space;

        CinemachineVirtualCamera m_VirtualCam;
        int m_Index;

        vo


/// A wrapper around the dummy OpenGL context. Why, you ask, does this exist? Well, there are multiple
/// instances where using the functions this context provides may fail, causing the actual OpenGL context
/// creation function to return an Err. When that happens, certain cleanup must be done and it's easiest
/// to wrap that cleanup in an RAII wrapper than it is to have a bit of boilerplate every time. That cleanup
/// is to reset the context to the one created before the function was run and to delete this context.
struct DummyContext {
    hdc: HDC,
    context: HGLRC,
    last_hdc: HDC,
    last_context: HGLRC
}

impl DummyContext {
    fn new(hdc: HDC) -> GlCreationResult<DummyContext> {
        unsafe {
            let context = wgl::CreateContext(hdc as *const c_void);
            if context == ptr::null_mut() {
                return Err(GlCreationError::OsError(OsErr::last_os_error().to_string(), "Could not create dummy context".to_owned()));
            }

            Ok(
                DummyContext {
                    hdc: hdc,
                    context: context as HGLRC,
                    last_hdc: wgl::GetCurrentDC() as HDC,
                    last_context: wgl::GetCurrentContext() as HGLRC
                }
            )
        }
    }

    unsafe fn make_current(&self) -> GlCreationResult<()> {
        match wgl::MakeCurrent(self.hdc as *const c_void, self.context as *const c_void) {
            0 => Err(GlCreationError::OsError(OsErr::last_os_error().to_string(), "Could not make dummy context current".to_owned())),
            _ => Ok(())
        }
    }
}

impl Drop for DummyContext {
    fn drop(&mut self) {
        unsafe {
            wgl::MakeCurrent(self.last_hdc as *const _, self.last_context as *const _);
            wgl::DeleteContext(self.context as *const _);
        }
    }
}

fn get_proc_address(library: HMODULE, proc_name: &str) -> *const () {
    unsafe {
        let proc_name = CString::new(proc_name.as_bytes()).unwrap();
        let proc_name = proc_name.as_ptr();
        let proc_addr = wgl::GetProcAddress(proc_name) as *const _;

        match proc_addr as isize {
            0  |
            0x1|
            0x2|
            0x3|
            -1  => kernel32::GetProcAddress(library, proc_name) as *const (),
            _   => proc_addr
        }
    }
}

unsafe fn get_dummy_pixel_format(hdc: HDC, pixel_format: &PixelFormat) -> GlCreationResult<i32> {
    let mut pfd: winapi::PIXELFORMATDESCRIPTOR = mem::zeroed();
    pfd.nSize = mem::size_of::<winapi::PIXELFORMATDESCRIPTOR>() as winapi::WORD;
    pfd.nVersion = 1;
    pfd.dwFlags = winapi::PFD_DRAW_TO_WINDOW | winapi::PFD_SUPPORT_OPENGL | winapi::PFD_DOUBLEBUFFER;
    pfd.iPixelType = winapi::PFD_TYPE_RGBA;
    pfd.cColorBits = pixel_format.color_bits;
    pfd.cAlphaBits = pixel_format.alpha_bits;
    pfd.cDepthBits = pixel_format.depth_bits;
    pfd.cStencilBits = pixel_format.stencil_bits;
    pfd.iLayerType = winapi::PFD_MAIN_PLANE;

    match gdi32::Choo


tabase alerts
    db_exceptions = "db_exceptions"

    # Report alerts
    daily_reports = "daily_reports"

    # Deployment alerts
    cooldown_deployment = "cooldown_deployment"
    new_model_added = "new_model_added"

    # Outage alerts
    outage_alerts = "outage_alerts"
    region_outage_alerts = "region_outage_alerts"

    # Fallback alerts
    fallback_reports = "fallback_reports"

    # Virtual Key Events
    new_virtual_key_created = "new_virtual_key_created"
    virtual_key_updated = "virtual_key_updated"
    virtual_key_deleted = "virtual_key_deleted"

    # Team Events
    new_team_created = "new_team_created"
    team_updated = "team_updated"
    team_deleted = "team_deleted"

    # Internal User Events
    new_internal_user_created = "new_internal_user_created"
    internal_user_updated = "internal_user_updated"
    internal_user_deleted = "internal_user_deleted"

DEFAULT_ALERT_TYPES: List[AlertType] = [
    # LLM related alerts
    AlertType.llm_exceptions,
    AlertType.llm_too_slow,
    AlertType.llm_requests_hanging,
    # Budget and spend alerts
    AlertType.budget_alerts,
    AlertType.spend_reports,
    AlertType.failed_tracking_spend,
    # Database alerts
    AlertType.db_exceptions,
    # Report alerts
    AlertType.daily_reports,
    # Deployment alerts
    AlertType.cooldown_deployment,
    AlertType.new_model_added,
    # Outage alerts
    AlertType.outage_alerts,
    AlertType.region_outage_alerts,
    # Fallback alerts
    AlertType.fallback_reports,
]


existent_table values ();
/// ```
#[rstest::rstest]
fn insert_into_nonexistent_table(planner_with_schema: QueryPlanner) {
    assert_eq!(
        planner_with_schema.plan(&insert_into(
            ObjectName(vec![ident(SCHEMA), ident("non_existent_table")]),
            vec![]
        )),
        Err(PlanError::table_does_not_exist(&format!(
            "{}.{}",
            SCHEMA, "non_existent_table"
        )))
    );
}

/// ```sql
/// insert into only_schema_in_the_name values ();
/// ```
#[rstest::rstest]
fn insert_into_table_with_unqualified_name(planner_with_schema: QueryPlanner) {
    assert_eq!(
        planner_with_schema.plan(&insert_into(ObjectName(vec![ident("only_schema_in_the_name")]), vec![])),
        Err(PlanError::syntax_error(
            &"unsupported table name 'only_schema_in_the_name'. All table names must be qualified",
        ))
    );
}

/// ```sql
/// insert into first_part.second_part.third_part.fourth_part values ();
/// ```
#[rstest::rstest]
fn insert_into_table_with_unsupported_name(planner_with_schema: QueryPlanner) {
    assert_eq!(
        planner_with_schema.plan(&insert_into(
            ObjectName(vec![
                ident("first_part"),
                ident("second_part"),
                ident("third_part"),
                ident("fourth_part")
            ]),
            vec![]
        )),
        Err(PlanError::syntax_error(
            &"unable to process table name 'first_part.second_part.third_part.fourth_part'",
        ))
    );
}

/// ```sql
/// insert into schema_name.table_name (small_int, integer, big_int) values ();
/// ```
#[rstest::rstest]
fn insert_into_table(planner_with_table: QueryPlanner) {
    assert_eq!(
        planner_with_table.plan(&insert_into_with_columns(
            ObjectName(vec![ident(SCHEMA), ident(TABLE)]),
            vec![ident("small_int"), ident("integer"), ident("big_int")],
            SetExpr::Values(Values(vec![]))
        )),
        Ok(Plan::Insert(TableInserts {
            table_id: FullTableId::from((0, 0)),
            column_indices: vec![
                (0, "small_int".to_owned(), SqlType::SmallInt, TypeConstraint::SmallInt),
                (1, "integer".to_owned(), SqlType::Integer, TypeConstraint::Integer),
                (2, "big_int".to_owned(), SqlType::BigInt, TypeConstraint::BigInt)
            ],
            input: vec![]
        }))
    );
}

/// ```sql
/// create table schema_name.table_name;
/// insert into schema_name.table_name values ();
/// ```
#[rstest::rstest]
fn insert_into_table_without_columns(planner_with_no_column_table: QueryPlanner) {
    assert_eq!(
        planner_with_no_column_table.plan(&insert_into(ObjectName(vec![ident(SCHEMA), ident(TABLE)]), vec![])),
        Ok(Plan::Insert(TableInserts {
            table_id: FullTableId::from((0, 0)),
            column_indices: vec![],
            input: vec![]
        }))
    );
}

/// ```sql
/// insert into schema_name.table_name values (not 1);
/// ```
#[rstest::rstest]
fn insert_with_syntax_error(planner_with_table: QueryPlanner) {
    assert_eq!(
        planner_with_table.plan(&insert_into(
            ObjectName(vec![ident(SCHEMA), ident(TABLE)]),
            vec![vec![Expr::UnaryOp {


oc/Packed_seqint.hpp>
#include <objects/general/Dbtag.hpp>
#include <objects/general/Object_id.hpp>
#include <objmgr/bioseq_handle.hpp>
#include <sstream>

BEGIN_NCBI_SCOPE
USING_SCOPE(objects);

CMaskWriterBlastDbMaskInfo::CMaskWriterBlastDbMaskInfo
    ( CNcbiOstream& arg_os,
      const string & format,
      int algo_id,
      objects::EBlast_filter_program filt_program,
      const string & algo_options )
: CMaskWriter( arg_os )
{
    m_BlastDbMaskInfo.Reset(new CBlast_db_mask_info());
    m_BlastDbMaskInfo->SetAlgo_id(algo_id);
    m_BlastDbMaskInfo->SetAlgo_program((int)filt_program);
    m_BlastDbMaskInfo->SetAlgo_options(algo_options);

    if (format == "maskinfo_asn1_bin") {
        m_OutputFormat = eSerial_AsnBinary;
    } else if (format == "maskinfo_asn1_text") {
        m_OutputFormat = eSerial_AsnText;
    } else if (format == "maskinfo_xml") {
        m_OutputFormat = eSerial_Xml;
    } else if (format == "interval") {
        m_OutputFormat = eSerial_None;  // N.B.: used to signal interval format
    } else {
        throw runtime_error("Invalid output format: " + format);
    }
}

template <class T>
void s_WriteObject(CRef<T> obj, CNcbiOstream& os, ESerialDataFormat fmt)
{
    switch (fmt) {
    case eSerial_AsnBinary:
        os << MSerial_AsnBinary << *obj;
        break;
    case eSerial_AsnText:
        os << MSerial_AsnText << *obj;
        break;
    case eSerial_Xml:
        os << MSerial_Xml << *obj;
        break;
    default:
        throw runtime_error("Invalid output format!");
    }
}

CMaskWriterBlastDbMaskInfo::~CMaskWriterBlastDbMaskInfo()
{
    if (m_OutputFormat == eSerial_None) {
        // nothing to do for interval output format
        return;
    }

    if (m_ListOfMasks.empty()) {
        CRef<CBlast_mask_list> empty_list(new CBlast_mask_list);
        empty_list->SetMasks();
        empty_list->SetMore(false);
        m_ListOfMasks.push_back(empty_list);
    }

    x_ConsolidateListOfMasks();

    m_BlastDbMaskInfo->SetMasks(*m_ListOfMasks.front());
    s_WriteObject(m_BlastDbMaskInfo, os, m_OutputFormat);
}

void
CMaskWriterBlastDbMaskInfo::x_ConsolidateListOfMasks()
{
    TBlastMaskLists consolidated_list;
    TBlastMaskLists::size_type i = 0;       // index into m_ListOfMasks

    consolidated_list.push_back
        (TBlastMaskLists::value_type(new CBlast_mask_list));

    for (; i < m_ListOfMasks.size(); i++) {
        if (m_ListOfMasks[i]->GetMasks().empty()) {
            // We only have one list and it's empty
            _ASSERT(m_ListOfMasks.size() == 1);
            consolidated_list.swap(m_ListOfMasks);
            break;
        }
        _ASSERT(m_ListOfMasks[i]->GetMasks().size() == 1);
        CRef<CSeq_loc> sl = m_ListOfMasks[i]->GetMasks().front();
        consolidated_list.back()->SetMasks().push_back(sl);
    }

    m_ListOfMasks.swap(consolidated_list);
    m_ListOfMasks.back()->SetMore(false);
    _ASSERT(m_ListOfMasks.size() == 1);
    _ASSERT(m_ListOfMasks.back()->GetMore() == false);
    _ASSERT(m_ListOfMasks.front()->GetMore() == false);
}

void CMaskWriterBlastDbMaskI


ue, parent: removed_leaf_parent_index} = table::remove(&mut tree.leaves, index);
    if (size(tree) == 0) {
        tree.root = PARTITION_INDEX;
        tree.min_leaf = PARTITION_INDEX;
        tree.max_leaf = PARTITION_INDEX;
        tree.next_internal_node_index = 0;
        tree.next_leaf_index = 0;
    } else {
        assert!(removed_leaf_parent_index != PARTITION_INDEX, EIndexOutOfRange);
        let removed_leaf_parent = table::borrow(&tree.internal_nodes, removed_leaf_parent_index);
        let removed_leaf_grand_parent_index = removed_leaf_parent.parent;
        // Note that sibling of the removed leaf can be a leaf or an internal node
        is_left_child_ = is_left_child(tree, removed_leaf_parent_index, MAX_U64 - index);
        let sibling_index = if (is_left_child_) { removed_leaf_parent.right_child }
        else { removed_leaf_parent.left_child };
        if (removed_leaf_grand_parent_index == PARTITION_INDEX) {
            // Parent of the removed leaf is the tree root
            // Update the parent of the sibling node and set sibling as the tree root
            if (sibling_index < PARTITION_INDEX) {
                // sibling is an internal node
                table::borrow_mut(&mut tree.internal_nodes, sibling_index).parent = PARTITION_INDEX;
            } else{
                // sibling is a leaf
                table::borrow_mut(&mut tree.leaves, MAX_U64 - sibling_index).parent = PARTITION_INDEX;
            };
            tree.root = sibling_index;
        } else {
            // grand parent of the removed leaf is a internal


index
	addu	k1, k1, k0
	lw	k0, 0(k1)			# get PTE entry
	mfc0	k1, MIPS_COP_0_EXC_PC		# get return address
	mtc0	k0, MIPS_COP_0_TLB_LOW		# save PTE entry
	and	k0, k0, MIPS1_PG_V		# check for valid entry
	beq	k0, zero, _C_LABEL(mips1_KernGenException) # PTE invalid
	nop
	tlbwr					# update TLB
	j	k1
	rfe

1:
	subu	k0, sp, UADDR + 0x200		# check to see if we have a
	sltiu	k0, UPAGES*NBPG - 0x200		#  valid kernel stack
	bne	k0, zero, _C_LABEL(mips1_KernGenException) # Go panic
	nop

	la	a0, start - START_FRAME - 8	# set sp to a valid place
	sw	sp, 24(a0)
	move	sp, a0
	la	a0, 1f
	mfc0	a2, MIPS_COP_0_STATUS_REG
	mfc0	a3, MIPS_COP_0_CAUSE_REG
	mfc0	a1, MIPS_COP_0_EXC_PC
	sw	a2, 16(sp)
	sw	a3, 20(sp)
	move	a2, ra
	jal	_C_LABEL(printf)
	mfc0	a3, MIPS_COP_0_BAD_VADDR
	.data
1:
	.asciiz	"ktlbmiss: PC %x RA %x ADR %x\nSR %x CR %x SP %x\n"
	.text

	/* Call mips1_dump_tlb(0, 2, printf) to show the bad kstack TLB */
	la	a2, _C_LABEL(printf)
	li	a0,0
	jal	_C_LABEL(mips1_dump_tlb)
	li	a1,3				# BDslot

	la	sp, start - START_FRAME		# set sp to a valid place
	PANIC("kernel stack overflow")
	.set	at
END(mips1_TLBMissException)

/*--------------------------------------------------------------------------
 *
 * mips1_TLBWriteIndexed --
 *
 *	Write the given entry into the TLB at the given index.
 *
 *	mips1_TLBWriteIndexed(index, highEntry, lowEntry)
 *		int index;
 *		int highEntry;
 *		int lowEntry;
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	TLB entry set.
 *
 *--------------------------------------------------------------------------
 */
LEAF(mips1_TLBWriteIndexed)
	mfc0	v1, MIPS_COP_0_STATUS_REG	# Save the status register.
	mtc0	zero, MIPS_COP_0_STATUS_REG	# Disable interrupts
	mfc0	t0, MIPS_COP_0_TLB_HI		# Save the current PID.

	sll	a0, a0, MIPS1_TLB_INDEX_SHIFT
	mtc0	a0, MIPS_COP_0_TLB_INDEX	# Set the index.
	mtc0	a1, MIPS_COP_0_TLB_HI		# Set up entry high.
	mtc0	a2, MIPS_COP_0_TLB_LOW		# Set up entry low.
	nop
	tlbwi					# Write the TLB

	mtc0	t0, MIPS_COP_0_TLB_HI		# Restore the PID.
	j	ra
	mtc0	v1, MIPS_COP_0_STATUS_REG	# Restore the status register
END(mips1_TLBWriteIndexed)

#if 0
/*--------------------------------------------------------------------------
 *
 * mips1_TLBWriteRandom --
 *
 *	Write the given entry into the TLB at a random location.
 *
 *	mips1_TLBWriteRandom(highEntry, lowEntry)
 *		unsigned highEntry;
 *


//text height and number of lines to move Y coordinate to center.
		 Rect rect = new Rect();

        mTextPaint.getTextBounds(_text, 0, _text.length(), rect);

		int numberOfTextLines = sl.getLineCount();

		float textHeight = numberOfTextLines * rect.height();

		float textYCoordinate = _top + (_bottom - _top  - textHeight)/2 - (rect.height()/2);
		//text will be drawn from left
		float textXCoordinate = bounds.left;
		mCanvas.translate(textXCoordinate, textYCoordinate);
		//draws static layout on canvas
		sl.draw(mCanvas);
		mCanvas.restore();
	}

	public void Clear(int _color) {
		if (_color != 0)
			mCanvas.drawColor(_color);
		else
			mCanvas.drawColor(Color.WHITE);
	}

	// by Kordal
	public float GetDensity() {
		return controls.activity.getResources().getDisplayMetrics().density;
	}

	public void ClipRect(float _left, float _top, float _right, float _bottom) {
        if (mCanvas == null) return;
        mCanvas.clipRect(_left, _top, _right, _bottom);
    }

	public void DrawBitmap(Bitmap _bitMap, int _srcLeft, int _srcTop, int _srcRight, int _srcBottom, float _dstLeft, float _dstTop, float _dstRight, float _dstBottom) {
        if (mCanvas == null) return;
        Rect srcRect = new Rect(_srcLeft, _srcTop, _srcRight, _srcBottom);
        RectF dstRect = new RectF(_dstLeft, _dstTop, _dstRight, _dstBottom);

        mCanvas.drawBitmap(_bitMap, srcRect, dstRect, paint);
    }

    public void DrawFrame(Bitmap _bitMap, int _srcX, int _srcY, int _srcW, int _srcH, float _X, float _Y, float _Wh, float _Ht, float _rotateDegree) {
        if (mCanvas == null) return;
        Rect srcRect = new Rect(_srcX, _srcY, _srcX + _srcW, _srcY + _srcH);
        RectF dstRect = new RectF(_X, _Y, _X + _Wh, _Y + _Ht);

        if (_rotateDegree != 0) {
            mCanvas.save();
            mCanvas.rotate(_rotateDegree, _X + _Wh / 2, _Y + _Ht / 2);
            mCanvas.drawBitmap(_bitMap, srcRect, dstRect, paint);
            mCanvas.restore();
         } else {
            mCanvas.drawBitmap(_bitMap, srcRect, dstRect, paint);
         }
    }

    public void DrawFrame(Bitmap _bitMap, float _X, float _Y, int _Index, int _Size, float _scaleFactor, float _rotateDegree) {
          float sf = _Size * _scaleFactor;
          DrawFrame(_bitMap, _Index % (_bitMap.getWidth() / _Size) * _Size, _Index / (_bitMap.getWidth() / _Size) * _Size, _Size, _Size, _X, _Y, sf, sf, _rotateDegree);
    }

    public void DrawGrid(float _left, float _top, float _width, float _height, int _cellsX, int _cellsY) {
        if (mCanvas == null) return;

        float cw = _width / _cellsX;
        float ch = _height / _cellsY;
        for (int i = 0; i < _cellsX + 1; i++) {
            mCanvas.drawLine(_left + i * cw, _top, _left + i * cw, _top + _height, paint); // draw Y lines
        }
        for (int i = 0; i < _cellsY


 = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern Boolean SetupDiOpenDeviceInfo(IntPtr deviceInfoSet, String deviceInstanceId, IntPtr hwndParent, Int32 openFlags, out SP_DEVINFO_DATA deviceInfoData);

        [DllImport("setupapi.dll", SetLastError = true)]
        public static extern Boolean SetupDiGetDevicePropertyKeys(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, IntPtr propertyKeyArray,
            UInt32 propertyKeyCount, out UInt32 requiredPropertyKeyCount, UInt32 flags);

        [DllImport("setupapi.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern Boolean SetupDiGetDevicePropertyW(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, ref DEVPROPKEY propertyKey, out UInt32 propertyType, IntPtr propertyBuffer, UInt32 propertyBufferSize, out UInt32 requiredSize, UInt32 flags);

        [DllImport("setupapi.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern Boolean SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet);

        [DllImport("setupapi.dll", SetLastError = true)]
        public static extern Int32 CM_Get_Parent(out UInt32 devInstParent, UInt32 devInst, Int32 flags);

        [DllImport("setupapi.dll", SetLastError = true)]
        public static extern Int32 CM_Get_Child(out UInt32 devInstChild, UInt32 devInst, Int32 ulFlags);

        [DllImport("setupapi.dll", SetLastError = true)]
        public static extern Int32 CM_Get_Sibling(out UInt32 devInstSibling, UInt32 devInst, Int32 ulFlags);

        [DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern Int32 CM_Get_Device_ID(UInt32 devInst, IntPtr buffer, Int32 bufferLen, Int32 flags);

        [StructLayout(LayoutKind.Sequential)]
        public struct SP_DEVINFO_DATA
        {
            public UInt32 Size;
            public Guid ClassGuid;
            public UInt32 DevInst;
            public IntPtr Reserved;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct SP_DEVICE_INTERFACE_DATA
        {
            public UInt32 Size;
            public Guid InterfaceClassGuid;
            public UInt32 Flags;
            public IntPtr Reserved;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct SP_DEVICE_INTERFACE_DETAIL_DATA
        {
            public UInt32 Size;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
            public String DevicePath;
        }

        #region devpropdef.h

        //
        // DEVPROPKEY structure
        //

        [StructLayout(LayoutKind.Sequential)]
        public struct DEVPROPKEY
        {
            public Guid Fmtid;
            public UInt32 Pid;
        }

        #endregion

    }
}


vicesWith(condition: string): object[] {
    const keyCondition = condition;
    const matchDevices = this.devices.filter((value) => {
      const device = value;
      let matchDevice;

      for (const key in device) {
        if (device[key] === keyCondition) {
          matchDevice = device;
          break;
        }
      }

      return matchDevice;
    });

    return matchDevices;
  }

  /**
   * [新增裝置資訊至firebase]
   * @param {object} device 裝置資訊的參數
   * @returns void
   * @author Steve Lin
   */
  addDevice(device): void {
    const category = device.category;
    const uuidIndex = this.devices.filter((value) => {
      return value.category === device.category;
    })
    .map(value => parseInt(value.uuid.replace((category + '-'), ''), 10))
    .sort((a, b) => {
      return a - b;
    });

    if (uuidIndex.length !== 0) {
      for (let i = 0; i < uuidIndex.length; i++) {
        if ((i + 1) !== uuidIndex[i]) {
          device.uuid = category + '-' + (i + 1);
          break;
        } else if ((i + 1) === uuidIndex.length) {
          device.uuid = category + '-' + (uuidIndex.length + 1);
        }
      }
    } else {
      device.uuid = category + '-1';
    }

    this.devices.push(device);
    this.firebaseDatabase.object('/devices').set(this.devices);
  }

  /**
   * [在firebase中移除指定裝置]
   * @param {any} device 欲移除的裝置
   * @returns void
   * @author Steve Lin
   */
  deleteDevice(device: any): void {
    const remainDevices = this.devices.filter((value) => {
      if (value.uuid !== device.uuid) {
        return value;
      }
    });

    this.firebaseDatabase.object('/devices').set(remainDevices);
  }

}
import instance from '../../API/api';
import { ModalActionType, ModalPhotoTypes } from '../../types/modal';
import { Dispatch } from 'redux';

export enum ModalActionTypes {
  SET_PHOTO = 'MODAL@SET_PHOTO',
  SET_IS_LOADING = 'MODAL@SET_IS_LOADING',
  SET_SHOW_MODAL = 'MODAL@SET_SHOW_MODAL',
  SET_CLOSE_MODAL = 'MODAL@SET_CLOSE_MODAL',
}

export const setPhoto = (photo: ModalPhotoTypes): ModalActionType => ({
  type: ModalActionTypes.SET_PHOTO,
  payload: photo,
});

export const setIsLoading = (): ModalActionType => ({
  type: ModalActionTypes.SET_IS_LOADING,
});

export const setShowModal = (photoId: string): ModalActionType => ({
  type: ModalActionTypes.SET_SHOW_MODAL,
  payload: photoId,
});

export const setCloseModal = (): ModalActionType => ({
  type: ModalActionTypes.SET_CLOSE_MODAL,
});

export const fetchPhoto = (photoId: string) => async (dispatch: Dispatch<ModalActionType>) => {
  try {
    dispatch(setIsLoading());
    const response = await instance.get(`/photos/${photoId}`);
    dispatch(setPhoto(response.data));
  } catch (e) {
    console.log(e);
  }
};
import { Mode


        rootRelativePath = path.resolve( relativeDir, newPath ),
        fileRelativePath = path.resolve( path.join( this.root, relativeDir ), newPath )

      // if the path is not relative or absolute, try to resolve it in node_modules
      if (newPath[0] !== '.' && newPath[0] !== '/') {
        try {
          fileRelativePath = require.resolve(newPath);
        }
        catch (e) {}
      }

      if(!initialContents) {
        const tokens = this.tokensByFile[fileRelativePath]
        if (tokens) { return resolve(tokens) }

        fs.readFile( fileRelativePath, "utf-8", ( err, source ) => {
          if ( err && relativeTo && relativeTo !== '/') {
            resolve({});
          }else if ( err && (!relativeTo || relativeTo === '/')) {
            reject(err);
          }else{
            this.core.load( source, rootRelativePath, trace, this.fetch.bind( this ) )
            .then( ( { injectableSource, exportTokens } ) => {
              this.sources[trace] = injectableSource
              this.tokensByFile[fileRelativePath] = exportTokens
              resolve( exportTokens )
            }, reject )
          }
        } )
      }else{
        this.core.load( initialContents, rootRelativePath, trace, this.fetch.bind(this) )
        .then( ( { injectableSource, exportTokens } ) => {
          this.sources[trace] = injectableSource
          this.tokensByFile[fileRelativePath] = exportTokens
          resolve( exportTokens )
        }, reject )
      }
    } )
  }

  private get finalSource(): string {
    return Object.keys( this.sources ).sort( traceKeySorter ).map( s => this.sources[s] )
    .join( "" )
  }

  private clear(): FileSystemLoader {
    this.tokensByFile = {};
    return this;
  }
}
'use strict'

export class Animal {
  hungerValue: number;
  thirstValue: number;
  constructor(hungerV: number = 50, thirstV: number = 50){
    this.hungerValue = hungerV;
    this.thirstValue = thirstV;
  }
  eat(): any {
    return this.hungerValue + 1;
  }
  drink(): any {
    return this.thirstValue + 1;
  }
  play(): any {
    return `${this.eat()}, ${this.drink()}`
  }
}

let kiskutya = new Animal();
let kiscica = new Animal();

console.log('kiskutya: ', kiskutya.play());
console.log('kiscica: ', kiscica.eat());import React, { useState, useEffect } from "react";

const useStorageState = <T>(
    key: string,
    fallbackValue: T
): [T, React.Dispatch<React.SetStateAction<T>>] => {

    const storedValue = localStorage.getItem(key);

    const [value, setValue] = useState(
        storedValue ? JSON.parse(storedValue) : fallbackValue
    );

    useEffect(
        () => localStorage.setItem(key, JSON.stringify(value)),
        [key, value]
    );

    return [value, setValue];

}

export { useStorageState };import {Api} from "api-def";

let mockingEnabled = false;

//setRequestBackend(new AxiosRequestBackend(axios as any));

export const setMockingEnabled = (enabled: boolean): void => {
  mockingEnabled = enabled;
};

export const isMockingEnabled = () => {
  return mockingEnabled;
};

const api = new Api({
  name   : "Test API",
  baseUrl: "https://jsonplaceholder.typicode.com/",
  mocking: {
    enabled: isMockingEnabled,
  },
});

export type User = { id: string; name: string; username: string; email: string };

export const fetchUsers = api.endpoint()
  .responseOf<Array<User>>()
  .build({
    id    : "fetch_users",
    path  : "/users",
    method: "get",

    mocking: {
      delay  : [


-- Mantainer : maz-1 < ohmygod19993 at gmail dot com >

m = Map("ngrokc", translate("Ngrok"),translate("Secure tunnels to localhost."))
m:section(SimpleSection).template  = "ngrokc_status"

local apply = luci.http.formvalue("cbi.apply")
if apply then
        os.execute("/etc/init.d/ngrokc reload &")       -- reload configuration
end
tunnels = m:section(TypedSection, "tunnels")
enabled=tunnels:option(Flag, "enabled", translate("Enable"))
enabled.anonymous = true
enabled.addremove = false
nhost=tunnels:option(Value, "host", translate("Ngrok Host"))
nhost.rmempty = false
nhost.datatype = "host"
hport=tunnels:option(Value, "port", translate("Ngrok Port"))
hport.rmempty = false
hport.datatype = "port"
tunnels:option(Value, "atoken", translate("Auth Token")


{
    fn lookahead_filter_tr(
        &mut self,
        arca: &mut Tr<W>,
        arcb: &mut Tr<W>,
        fs: &CF::FS,
    ) -> Result<CF::FS> {
        let labela = if self.lookahead_output() {
            arca.olabel
        } else {
            arca.ilabel
        };
        if labela != EPS_LABEL && !self.flags.contains(MatcherFlags::LOOKAHEAD_NON_EPSILONS) {
            return Ok(fs.clone());
        }
        if labela == EPS_LABEL && !self.flags.contains(MatcherFlags::LOOKAHEAD_EPSILONS) {
            return Ok(fs.clone());
        }
        self.lookahead_tr = true;

        self.la_matcher_data = match self.selector() {
            Selector::Fst1Matcher2 => {
                let fst = self.matcher1().fst();
                let matcher = self.matcher2();
                matcher.lookahead_fst(arca.nextstate, fst, arcb.nextstate)?
            }
            Selector::Fst2Matcher1 => {
                let fst = self.matcher2().fst();
                let matcher = self.matcher1();
                matcher.lookahead_fst(arca.nextstate, fst, arcb.nextstate)?
            }
        };

        if self.la_matcher_data.is_some() {
            Ok(fs.clone())
        } else {
            Ok(CF::FS::new_no_state())
        }
    }
}

impl<W, F1, F2, B1, B2, M1, M2, CF, SMT> ComposeFilter<W, F1, F2, B1, B2, M1, M2>
    for LookAheadComposeFilter<W, F1, F2, B1, B2, M1, M2, CF, SMT>
where
    W: Semiring,
    F1: Fst<W>,
    F2: Fst<W>,
    B1: Borrow<F1> + Debug,
    B2: Borrow<F2> + Debug,
    M1: LookaheadMatcher<W, F1, B1>,
    M2: LookaheadMatcher<W, F2, B2>,
    CF: LookAheadComposeFilterTrait<W, F1, F2, B1, B2, M1, M2>,
    SMT: MatchTypeTrait,
{
    type FS = CF::FS;

    fn start(&self) -> Self::FS {
        self.filter.start()
    }

    fn set_state(&mut self, s1: StateId, s2: StateId, filter_state: &Self::FS) -> Result<()> {
        self.filter.set_state(s1, s2, filter_state)
    }

    fn filter_tr(&mut self, arc1: &mut Tr<W>, arc2: &mut Tr<W>) -> Result<Self::FS> {
        self.lookahead_tr = false;
        let fs = self.filter.filter_tr(arc1, arc2)?;
        if fs == CF::FS::new_no_state() {
            return Ok(CF::FS::new_no_state());
        }
        if self.lookahead_output() {
            self.lookahead_filter_tr(arc1, arc2, &fs)
        } else {
            self.lookahead_filter_tr(arc2, arc1, &fs)
        }
    }

    fn filter_final(&self, w1: &mut W, w2: &mut W) -> Result<()> {
        self.filter.filter_final(w1, w2)
    }

    fn matcher1(&self) -> &M1 {
        self.filter.matcher1()
    }

    fn matcher2(&self) -> &M2 {
        self.filter.matcher2()
    }

    fn matcher1_shared(&self) -> &Arc<M1> {
        self.filter.matcher1_shared()
    }

    fn matcher2_shared(&self) -> &Arc<M2> {
        self.filter.matcher2_shared()
    }

    fn properties


ion-color-step-350: #595959;
    --ion-color-step-400: #666666;
    --ion-color-step-450: #737373;
    --ion-color-step-500: #808080;
    --ion-color-step-550: #8c8c8c;
    --ion-color-step-600: #999999;
    --ion-color-step-650: #a6a6a6;
    --ion-color-step-700: #b3b3b3;
    --ion-color-step-750: #bfbfbf;
    --ion-color-step-800: #cccccc;
    --ion-color-step-850: #d9d9d9;
    --ion-color-step-900: #e6e6e6;
    --ion-color-step-950: #f2f2f2;

    --ion-toolbar-background: #000000;

    // // --ion-item-background: #1c1c1c;
    // // --ion-item-background-activated: #313131;
    // --ion-item-background: #1c1c1c;
    // --ion-item-background-activated: #313131;
  }

  :root .md {
    --ion-background-color: #121212;
    --ion-background-color-rgb: 18, 18, 18;

    --ion-text-color: #ffffff;
    --ion-text-color-rgb: 255, 255, 255;

    --ion-border-color: #222222;

    --ion-color-step-50: #1e1e1e;
    --ion-color-step-100: #2a2a2a;
    --ion-color-step-150: #363636;
    --ion-color-step-200: #414141;
    --ion-color-step-250: #4d4d4d;
    --ion-color-step-300: #595959;
    --ion-color-step-350: #656565;
    --ion-color-step-400: #717171;
    --ion-color-step-450: #7d7d7d;
    --ion-color-step-500: #898989;
    --ion-color-step-550: #949494;
    --ion-color-step-600: #a0a0a0;
    --ion-color-step-650: #acacac;
    --ion-color-step-700: #b8b8b8;
    --ion-color-step-750: #c4c4c4;
    --ion-color-step-800: #d0d0d0;
    --ion-color-step-850: #dbdbdb;
    --ion-color-step-900: #e7e7e7;
    --ion-color-step-950: #f3f3f3;

    // --ion-item-background: #1a1b1e;
  }
}
ion-content {
  --padding-bottom: calc(var(--ion-safe-area-bottom) + 30px) !important;
}
ion-content::part(scroll) {
  padding-bottom: calc(
    var(--padding-bottom) + var(--keyboard-offset) + var(--offset-bottom) + 58px
  );
}
.md {
  --ion-toolbar-height: 56px;
  --platform-opacity: 1;
}
.ios {
  --ion-toolbar-height: 44px;
  --platform-opacity: 0.8;
  ion-range {
    --knob-size: 16px;
  }
}
.transparent {
  --background: var(--ion-background-color);
  --border-color: transparent;
}
.ion-color-white {
  --ion-color-base: var(--ion-color-white);
  --ion-color-base-rgb: var(--ion-color-white-rgb);
  --ion-color-contrast: var(--ion-color-white-contrast);
  --ion-color-contrast-rgb: var(--ion-color-white-contrast-rgb);
  --ion-color-shade: var(--ion-color-white-shade);
  --ion-color-tint: var(--ion-color-white-tint);
}

body,
ht


er;
  highFreq: number;
  stops: number;

  constructor(lowFreq, highFreq, stops) {
    this.lowFreq = lowFreq;
    this.highFreq = highFreq;
    this.stops = stops;
  }

  abstract stopToFrequency(stop: number): number;
  abstract stopToHSL(stop: number): HSL;
}

class ContinuousMapper extends MapperImp {
  constructor(lowFreq: number, highFreq: number) {
      super(lowFreq, highFreq, 480);
    }

  stopToHSL(stop: number): HSL {
	let frac = stop / this.stops;
	let hue = 2 * frac * 360;
	let lightness = stop < this.stops / 2 ? 45 : 60;
	return {h: hue, s: 80, l: lightness};
    }

  stopToFrequency(stop: number): number {
	let frac = stop / this.stops;
	let range = this.highFreq - this.lowFreq;
	return (frac * range) + this.lowFreq;
    }
}

class ChromaticMapper extends MapperImp {
    constructor(lowFreq, highFreq) {
      super(lowFreq, highFreq, 24);
    }

  stopToHSL(stop: number): HSL {
	let frac = stop / this.stops;
	let hue = 2 * frac * 360;
	let lightness = stop < this.stops / 2 ? 45 : 60;
	return {h: hue, s: 80, l: lightness};
    }

  stopToFrequency(stop: number): number {
	return equalTemperament(this.lowFreq, stop);
    }
}

class ScaleMapper extends MapperImp {
    constructor(lowFreq, highFreq) {
      super(lowFreq, highFreq, 14);
    }

  stopToHSL(stop: number): HSL {
	let frac = stop / this.stops;
	let hue = 2 * frac * 360;
	let lightness = stop < this.stops / 2 ? 45 : 60;
	return {h: hue, s: 80, l: lightness};
    }

  stopToFrequency(stop: number): number {
	let degrees = [0, 2, 4, 5, 7, 9, 11, 12, 14, 16, 17, 19, 21, 23];
	return equalTemperament(this.lowFreq, degrees[stop]);
    }
}

class ChordMapper extends MapperImp {
    constructor(lowFreq, highFreq) {
      super(lowFreq, highFreq, 6);
    }

    stopToHSL(stop) {
	let frac = (stop + 0.3) / this.stops;
	let hue = 2 * frac * 360;
	let lightness = stop < this.stops / 2 ? 45 : 60;
	return {h: hue, s: 80, l: lightness};
    }

    stopToFrequency(stop) {
	let degrees = [0, 4, 7, 12, 16, 19];
	return equalTemperament(this.lowFreq, degrees[stop]);
    }
}

class Mapper {
  height: number;
  mapper: MapperImp;
    constructor(height, tuning) {
	this.height = height;

	let lowFreq = 400;
	let highFreq = lowFreq * 4;

	if(tuning == "continuous") {
	    this.mapper = new ContinuousMapper(lowFreq, highFreq);
	} else if (tuning == "chromatic") {
	    this.mapper = new ChromaticMapper(lowFreq, highFreq);
	} else if (tuning == "major scale") {
	    this.mapper = new ScaleMapper(lowFreq, highFreq);
	} else if (tuning == "major chord") {
	    this.mapper = new ChordMapper(lowFreq, highFreq);
	} else {
	    throw new TypeError("Undefined Tuning: '" + tuning + "'");
	}
    }

    pixelToStop(pixel) {
        // Ascend from the bottom
        let level = this.height - pixel;
        let stopWidth = this.height / this.mapper.stops;
        let stop = Math.floor(level / stopWidth);
        return stop;
    }

    pixelToHSL(pixel) {
        return this.mapper.stopToHSL(this.pixelToStop(pixel));


link" width="24" height="24" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path fill="currentColor" d="M12 0C5.37 0 0 5.37 0 12a12 12 0 00.574 3.62c.274-.12.566-.26.856-.38 1.37-.54 2.63-.36 3.88.4 0 0 .46.28.6.36.59.38 1.14.73 1.67.73.51 0 1.01-.14 1.22-1.12.33-1.53 1.14-5.3 1.49-7.16.21-1.1.32-1.69.44-2.09.2-.71.58-1.09 1.11-1.15 0 0 .09-.01.16-.01s.15.01.15.01c.54.06.92.44 1.13 1.15.11.4.22.99.43 2.09.35 1.86 1.16 5.63 1.49 7.16.21.98.71 1.12 1.22 1.12.53 0 1.08-.35 1.67-.73.14-.08.6-.36.6-.36 1.26-.76 2.51-.94 3.88-.4.3.12.59.26.87.39A12 12 0 0024 12c0-6.63-5.37-12-12-12m0 9.79c-.4 2.01-1 4.92-1.3 6.21-.36 1.7-1.5 2.66-3.12 2.66-1.08 0-1.94-.54-2.7-1.01-.38-.25-.8-.52-1.25-.65a2.32 2.32 0 00-1.42-.03 6.11 6.11 0 00-.94.39A12 12 0 0012 24a12 12 0 0010.73-6.65 6.08 6.08 0 00-.94-.39 2.32 2.32 0 00-1.41.01c-.46.16-.88.43-1.26.68-.76.47-1.62 1.01-2.7 1.01-1.62 0-2.75-.96-3.12-2.66C13 14.71 12 9.79 12 9.79Z"/></svg>';
  static const String bt =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24"><path fill="currentColor" d="M12.589 7.91h5.977v1.753H16.56v6.41h-1.97v-6.41h-2zM12 22.523C6.193 22.523 1.477 17.807 1.477 12 1.477 6.193 6.193 1.477 12 1.477c5.807 0 10.523 4.716 10.523 10.523 0 5.807-4.716 10.523-10.523 10.523M12 24c6.626 0 12-5.374 12-12S18.626 0 12 0C5.379 0 0 5.374 0 12s5.379 12 12 12M9.97 13.574c0-.516-.321-.865-.873-.865h-1.32v1.702h1.32c.552 0 .874-.345.874-.837m-.24-3.276c0-.433-.275-.732-.745-.732h-1.21v1.486h1.21c.47 0 .746-.299.746-.754m2.231 3.372c0 1.546-1.09 2.402-2.65 2.402H5.834V7.91h3.249c1.573 0 2.64.805 2.64 2.277 0 .672-.298 1.27-.781 1.634.552.326 1.021.947 1.021 1.85Z"/></svg>';
  static const String buddy =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.


MyUrl.buildSearchURL(e));
                      },
                    ),
                  ),
                ].toList(),
          ),
        ),
      ],
    );
  }
}
import 'package:blooms/features/condition/domain/condition_content.dart';
import 'package:blooms/features/condition/domain/condition_content_audio_attachment.dart';
import 'package:blooms/features/condition/domain/condition_content_image_attachment.dart';
import 'package:blooms/features/condition/domain/condition_creator_type.dart';
import 'package:blooms/utils/timestamp_converter.dart';
import 'package:blooms/utils/typedefs.dart';
import 'package:clock/clock.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'condition.freezed.dart';
part 'condition.g.dart';

@freezed
abstract class Condition with _$Condition {
  const factory Condition({
    /// 対象者のUID
    required String subjectUid,

    /// contentの作成者の種類
    required ConditionCreatorType creatorType,

    /// 内容
    required ConditionContent content,

    /// ISO8601形式の作成日時
    String? createdAtIso8601,
    @TimestampConverter() Timestamp? createdAt,
    @TimestampConverter() Timestamp? updatedAt,
    @TimestampConverter() Timestamp? deletedAt,
  }) = _Condition;

  factory Condition.text({required String uid, required String text}) =>
      Condition(
        subjectUid: uid,
        creatorType: ConditionCreatorType.user,
        content: ConditionContent.text(text: text),
        createdAtIso8601: clock.now().toIso8601String(),
      );

  factory Condition.image({
    required String uid,
    required List<ConditionContentImageAttachment> attachments,
  }) => Condition(
    subjectUid: uid,
    creatorType: ConditionCreatorType.user,
    content: ConditionContent.image(attachments: attachments),
    createdAtIso8601: clock.now().toIso8601String(),
  );

  factory Condition.audio({
    required String uid,
    required List<ConditionContentAudioAttachment> attachments,
  }) => Condition(
    subjectUid: uid,
    creatorType: ConditionCreatorType.user,
    content: ConditionContent.audio(attachments: attachments),
    createdAtIso8601: clock.now().toIso8601String(),
  );

  factory Condition.fromJson(Json json) => _$ConditionFromJson(json);

  static FromFirestore<Condition> get fromFirestore =>
      (snapshot, _) => Condition.fromJson(snapshot.data() ?? {});

  static ToFirestore<Condition> get toFirestore =>
      (data, _) => TimestampConverter.updateServerTimestamp(data.toJson());
}
// GENERATED CODE - DO NOT MODIFY BY HAND

// ignore_for_file: require_trailing_commas, non_constant_identifier_names, cast_nullable_to_non_nullable, lines_longer_than_80_chars, unnecessary_null_checks, strict_raw_type

part of 'condition_content_audio_attachment.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

_ConditionContentAudioAttachment _$ConditionContentAudioAttachmentFromJson(
  Map<String, dynamic> json,
) =>
    $checkedCreate('_ConditionContentAudioAttachment', json, ($checkedConvert) {
      final val = _ConditionContentAudioAttachment(
        fileUri: $checkedConvert('fileUri', (v) => v as String),
        mimeType: $checkedConvert('mimeType', (v) => v as String),
      );
      return val;
    });

Map<String, dynamic> _$ConditionContentAudioAttachmentToJson(
  _ConditionContentAudioAttachment instance,
) => <String, dynamic>{
  'fileUri': instance.fileUri,
  'mimeT


from edsnlp.utils.regex_utils import make_pattern

letter_days = [
    r"(?P<day_01>premier|1\s*er)",
    r"(?P<day_02>deux)",
    r"(?P<day_03>trois)",
    r"(?P<day_04>quatre)",
    r"(?P<day_05>cinq)",
    r"(?P<day_06>six)",
    r"(?P<day_07>sept)",
    r"(?P<day_08>huit)",
    r"(?P<day_09>neuf)",
    r"(?P<day_10>dix)",
    r"(?P<day_11>onze)",
    r"(?P<day_12>douze)",
    r"(?P<day_13>treize)",
    r"(?P<day_14>quatorze)",
    r"(?P<day_15>quinze)",
    r"(?P<day_16>seize)",
    r"(?P<day_17>dix\-?\s*sept)",
    r"(?P<day_18>dix\-?\s*huit)",
    r"(?P<day_19>dix\-?\s*neuf)",
    r"(?P<day_20>vingt)",
    r"(?P<day_21>vingt\-?\s*et\-?\s*un)",
    r"(?P<day_22>vingt\-?\s*deux)",
    r"(?P<day_23>vingt\-?\s*trois)",
    r"(?P<day_24>vingt\-?\s*quatre)",
    r"(?P<day_25>vingt\-?\s*cinq)",
    r"(?P<day_26>vingt\-?\s*six)",
    r"(?P<day_27>vingt\-?\s*sept)",
    r"(?P<day_28>vingt\-?\s*huit)",
    r"(?P<day_29>vingt\-?\s*neuf)",
    r"(?P<day_30>trente)",
    r"(?P<day_31>trente\-?\s*et\-?\s*un)",
]

letter_day_pattern = make_pattern(letter_days)

numeric_day_pattern = r"(?<!\d)(0?[1-9]|[12]\d|3[01])(?!\d)"
lz_numeric_day_pattern = r"(?<!\d)(0[1-9]|[12]\d|3[01])(?!\d)"
nlz_numeric_day_pattern = r"(?<!\d)([1-9]|[12]\d|3[01])(?!\d)"

numeric_day_pattern = f"(?P<day>{numeric_day_pattern})"
lz_numeric_day_pattern = f"(?P<day>{lz_numeric_day_pattern})"

day_pattern = f"({letter_day_pattern}|{numeric_day_pattern})"


/*
 * Copyright 2023 Adobe. All rights reserved.
 * This file is licensed to you 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 REPRESENTATIONS
 * OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
#pragma once

#include <lagrange/fs/filesystem.h>
#include <lagrange/io/types.h>
#include <lagrange/scene/Scene.h>

#include <iosfwd>

namespace lagrange::io {

/**
 * Save a scene to a file.
 *
 * @param[in] filename  path to output
 * @param[in] scene     scene to save
 * @param[in] options   SaveOptions, check the struct for more details.
 */
template <typename Scalar, typename Index>
void save_scene(
    const fs::path& filename,
    const scene::Scene<Scalar, Index>& scene,
    const SaveOptions& options = {});

/**
 * Save a scene to a stream.
 *
 * @param[in] output_stream  Stream to output
 * @param[in] scene          Scene to save
 * @param[in] format         FileFormat to use.
 * @param[in] options        SaveOptions, check the struct for more details.
 */
template <typename Scalar, typename Index>
void save_scene(
    std::ostream& output_stream,
    const scene::Scene<Scalar, Index>& scene,
    FileFormat format,
    const SaveOptions& options = {});

} // namespace lagrange::io


: 读取 `humaneval-c-all.json` 文件，该文件包含了由不同优化等级（O0, O1, O2, O3）编译器生成的汇编代码。
    2.  **汇编代码清洗**:
        -   移除每个代码片段的函数标签（如 `<func0>:`）。
        -   删除行尾的地址提示（如 `<func0+0x28>`），以获得纯净的汇编指令。
        -   脚本内置了一系列强大的清洗函数（如 `replace_calls_and_leas`, `fix_cmp_instruction_size` 等）来处理各种不兼容的汇编语法，使其能够被 `keystone-engine` 正确处理。
    3.  **模拟执行**:
        -   在 `compile_run` 函数中，使用 `unicorn-engine` 创建一个标准的 x86-64 模拟环境。
        -   **使用随机值初始化通用寄存器**（如 `RAX`, `RBX`, `RCX` 等），以进行通用的"冒烟测试"，检查代码在随机输入下的稳定性。
        -   执行清理后的汇编代码。
    4.  **结果报告**:
        -   执行完成后，脚本会详细打印出关键寄存器（`RAX`, `RBX`, `RSP` 等）的最终十六进制值。
        -   同时，它会记录并报告执行期间发生的前几次内存读/写操作的地址、大小和值。
        -   这个过程取代了原有的评估计分逻辑，专注于提供执行状态的快照。

## 项目结构

```
/
├── compiler.py               # 编译器和汇编器模块
├── emulator.py               # x86-64 模拟器模块
├── force_exec.py             # 新增：汇编代码执行与分析脚本
├── main.py                   # C 代码验证流水线主程序
├── humaneval-c-all.json      # 数据集：包含C函数和多种优化等级的汇编
├── humaneval-c-no-syscall-sample.json # 数据集：C函数与测试用例
└── README.md                 # 本文档
```

## 如何运行

1.  **安装依赖**:
    ```bash
    pip install keystone-engine unicorn capstone tqdm
    ```

2.  **确保环境**:
    - 运行 `main.py` 需要 `gcc`。请确保您的系统中已安装 `gcc`。
    - 项目默认在 x86-64 Linux 环境下开发和测试。

3.  **执行**:

    - **运行 C 代码验证流水线**:


a name="l01782"> 1782

 1783

 1784 static void allegro_gl_video_polygon3d(BITMAP *bmp, int type, BITMAP *texture,

 1785                                 int vc, V3D *vtx[])

 1786 {

 1787     int i;

 1788     V3D_f **vtx_f = malloc(vc * sizeof(struct V3D_f*));

 1789     if (!vtx_f)

 1790         return;

 1791

 1792     for (i = 0; i < vc; i++) {

 1793         vtx_f[i] = malloc(sizeof(struct V3D_f));

 1794         if (!vtx_f[i]) {

 1795             int k;

 1796             for (k = 0; k < i; k++)

 1797                 free(vtx_f[k]);

 1798             free(vtx_f);

 1799             return;

 1800         }

 1801         vtx_f[i]->c = vtx[i]->c;
<div cl