loat>::max();
        glPixelStorei(GL_PACK_ALIGNMENT, 1);
        easy3d_debug_log_gl_error
        glReadPixels(glx, gly, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
        easy3d_debug_log_gl_error
        found = depth < 1.0f;
        if (found) {
            vec3 point(static_cast<float>(x), static_cast<float>(y), depth);
            // The input to unprojectedCoordinatesOf() is defined in the screen coordinate system
            point = camera_->unprojectedCoordinatesOf(point);
            return point;
        } else
            return vec3(0);
    }

    void Viewer::set_usage(const std::string& manual, const std::string& screen_hint)
    {
        if (manual != "default")
            manual_ = manual;
        hint_ = screen_hint;
    }

    int Viewer::run(bool see_all) {
        // initialize before showing the window because it can be slow
        init();

        // make sure scene fits the screen when the window appears
        if (see_all)
            fit_screen();

        // show the window
        glfwShowWindow(window_);

        try {   // main loop
            static int frame_counter = 0;
            double last_time = glfwGetTime();   // for frame rate counter

            while (!glfwWindowShouldClose(window_) && !should_exit_) {
                if (!glfwGetWindowAttrib(window_, GLFW_VISIBLE)) { // not visible
                    glfwWaitEvents();
                    continue;
                }

                if (show_frame_rate_) {
                    // Calculate ms/frame
                    double current_time = glfwGetTime();
                    ++frame_counter;
                    if (current_time - last_time >= 1.0f) {
                        snprintf(framerate_, sizeof(framerate_), "fps: %2.0f (%4.1f ms/frame)",
                                double(frame_counter) / (current_time - last_time), 1000.0 / double(frame_counter));
                        frame_counter = 0;
                        last_time = current_time;
                    }
                }

                pre_draw();
                draw();
                post_draw();
                glfwSwapBuffers(window_);

                // Don't call 'glfwPollEvents()' at the beginning of the main loop.
                // Reason: first frame needs time to complete.
                if (is_animating_ && animation_func_) {
                    glfwPollEvents();

                    // TODO: make framerate a parameter
                    if (!show_frame_rate_) {
                        static const int animation_fps = 30;
                        static const double interval = 1000.0 / (animation_fps + 5); // the extra 5 for adjusting
                        std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<int>(interval)));
                    }
                    animation_func_(this);
                }
                else if (show_frame_rate_)
                    glfwPollEvents();
                else
                    glfwWaitEvents();
            }

            /* Process events once more */
            glfwPollEvents();
            return EXIT_SUCCESS;
        }
        catch (const std::exception &e) {
            LOG(ERROR) << "Caught exception in main loop: " << e.what();
            cleanup();
            return EXIT_FAILURE;
        }
    }

    void Viewer::exit() {
        should_exit_ = true;
        update();
    }

    void Viewer::init() {
        //// back face culling?
        //glEnable(GL_CULL_FACE);
        //glCullFace(GL_BACK); // culls only the back faces

        glEnable(GL_DEPTH_TEST);
        glDepthFunc(GL_LESS);

        glClearDepth(1.0f);
        glClearColor(background_color_[0], background_color_[1], background_color_[2], background_color


> = HashMap::new();
        for hotkey in hotkeys {
            command_table.insert(
                (hotkey.keysym, hotkey.modifiers.without_locks()),
                hotkey.commands,
            );
        }
        Self { command_table }
    }

    pub fn eval(&self, key: Keysym, modifiers: Modifiers) -> &[Command] {
        self.command_table
            .get(&(key, modifiers.without_locks()))
            .map(|commands| commands.as_slice())
            .unwrap_or_default()
    }
}

#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Hotkey {
    keysym: Keysym,
    #[serde(default)]
    modifiers: Modifiers,
    commands: Vec<Command>,
}

impl Hotkey {
    pub fn new(keysym: impl Into<Keysym>, modifiers: Modifiers, commands: Vec<Command>) -> Self {
        Self {
            keysym: keysym.into(),
            modifiers,
            commands,
        }
    }

    pub fn modifiers(&self) -> Modifiers {
        self.modifiers
    }

    pub fn keysym(&self) -> Keysym {
        self.keysym
    }
}
<filename>src/lib.rs<gh_stars>0
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Use async/await syntax with actix actors.
//!
//! # Example
//!
//! This example shows how you could implement a generic "pipeline adapter"
//! which allows turning any `Sink`/`Stream` pair (forming a request/response
//! pipeline) into an actix Actor.
//!
//! Responses are matched up with their requests according to the order
//! in which they were sent (so the first response corresponds to the
//! first request sent to the `Sink`, etc). This requires that our "send"
//! operations are strictly ordered, and this is difficult to achieve
//! in actix because async operations are normally allowed to interleave.
//!
//! Furthermore, although the sends must be atomic, we also want to be
//! able to have a large number of requests in-flight at any given time,
//! so the receiving part of the message handler must not require exclusive
//! access to the actor while it is waiting. As a result, abstractions
//! like the `AtomicResponse` type are too simplistic to help.
//!
//! To solve this problem, we use the [`critical_section`](critical_section)
//! function to allow specific parts of our message handler to be  atomic.
//!
//! ```rust
//! use std::collections::VecDeque;
//! use std::pin::Pin;
//!
//! use futures::{Sink, SinkExt, Stream, channel::oneshot};
//! use actix::prelude::*;
//!
//! use actix_interop::{FutureInterop, with_ctx, critical_section};
//!
//! // Define our actor
//! pub struct PipelineAdapter<Req, Res, Err> {
//!     sink: Option<Pin<Box<dyn Sink<Req, Error=Err>>>>,
//!     in_flight_reqs: VecDeque<oneshot::Sender<Result<Res, Err>>>,
//! }
//!
//! // Implement a constructor
//! impl<Req, Res, Err> PipelineAdapter<Req, Res, Err>
//! where
//!     Req: 'static,
//!     Res: 'static,
//!     Err: 'static,
//! {
//!     pub fn new<Si, St>(sink: Si, stream: St) -> Addr<Self>
//!     where
//!         Si: Sink<Req, Error=Err> + 'static,
//!         St:


namespace Sanford.Multimedia.Midi
{
    public class RecordingSession
    {
        private IClock clock;

        private List<TimestampedMessage> buffer = new List<TimestampedMessage>();

        private Track result = new Track();

        public RecordingSession(IClock clock)
        {
            this.clock = clock;
        }

        public void Build()
        {
            result = new Track();

            buffer.Sort(new TimestampComparer());

            foreach(TimestampedMessage tm in buffer)
            {
                result.Insert(tm.ticks, tm.message);
            }
        }

        public void Clear()
        {
            buffer.Clear();
        }

        public Track Result
        {
            get
            {
                return result;
            }
        }

        public void Record(ChannelMessage message)
        {
            if(clock.IsRunning)
            {
                buffer.Add(new TimestampedMessage(clock.Ticks, message));
            }
        }

        public void Record(SysExMessage messag


olorImage2D image)
        {
            var tex = new Texture2D(image.Width, image.Height, TextureFormat.ARGB32, false);

            for (int x = 0; x < image.Width; x++)
            {
                for (int y = 0; y < image.Height; y++)
                {
                    tex.SetPixel(x, y, image[x, y].ToColor());
                }
            }

            tex.Apply();

            return tex;
        }

    }

}


s up mtu %s multicast off", ifce.Name(), "1399")
	err = execCmd([]string{cmdstr1})
	if err != nil {
		base.Fatal("testTun err: ", err)
	}
	// 开启服务器转发
	// err = execCmd([]string{"sysctl -w net.ipv4.ip_forward=1"})
	// if err != nil {
	// 	base.Fatal(err)
	// }
	if base.Cfg.IptablesNat {
		// 添加NAT转发规则
		ipt, err := iptables.New()
		if err != nil {
			base.Fatal(err)
			return
		}

		// 修复 rockyos nat 不生效
		base.CheckModOrLoad("iptable_filter")
		base.CheckModOrLoad("iptable_nat")
		// base.CheckModOrLoad("xt_comment")

		// 添加注释
		natRule := []string{"-s", base.Cfg.Ipv4CIDR, "-o", base.Cfg.Ipv4Master, "-m", "comment",
			"--comment", "AnyLink", "-j", "MASQUERADE"}
		if base.InContainer {
			natRule = []string{"-s", base.Cfg.Ipv4CIDR, "-o", base.Cfg.Ipv4Master, "-j", "MASQUERADE"}
		}
		err = ipt.InsertUnique("nat", "POSTROUTING", 1, natRule...)
		if err != nil {
			base.Error(err)
		}

		// 添加注释
		forwardRule := []string{"-m", "comment", "--comment", "AnyLink", "-j", "ACCEPT"}
		if base.InContainer {
			forwardRule = []string{"-j", "ACCEPT"}
		}
		err = ipt.InsertUnique("filter", "FORWARD", 1, forwardRule...)
		if err != nil {
			base.Error(err)
		}

		base.Info(ipt.List("nat", "POSTROUTING"))
		base.Info(ipt.List("filter", "FORWARD"))
	}
}

// 创建tun网卡
func LinkTun(cSess *sessdata.ConnSession) error {
	cfg := water.Config{
		DeviceType: water.TUN,
	}

	ifce, err := water.New(cfg)
	if err != nil {
		base.Error(err)
		return err
	}
	// log.Printf("Interface Name: %s\n", ifce.Name())
	cSess.SetIfName(ifce.Name())

	// 通过 ip link show  查看 alias 信息
	alias := utils.ParseName(cSess.Group.Name + "." + cSess.Username)
	cmdstr1 := fmt.Sprintf("ip link set dev %s up mtu %d multicast off alias %s", ifce.Name(), cSess.Mtu, alias)
	cmdstr2 := fmt.Sprintf("ip addr add dev %s local %s peer %s/32",
		ifce.Name(), base.Cfg.Ipv4Gateway, cSess.IpAddr)
	err = execCmd([]string{cmdstr1, cmdstr2})
	if err != nil {
		base.Error(err)
		_ = ifce.Close()
		return err
	}

	// cmdstr3 := fmt.Sprintf("sysctl -w net.ipv6.conf.%s.disable_ipv6=1", ifce.Name())
	// execCmd([]string{cmdstr3})
	err = gosysctl.Set(fmt.Sprintf("net.ipv6.conf.%s.disable_ipv6", ifce.Name()), "1")
	if err != nil {
		base.Warn(err)
	}

	go tunRead(ifce, cSess)
	go tunWrite(ifce, cSess)
	return nil
}

func tun


e, filename);

    // re-create custom context
    mjr_makeContext(m, &con, fontscale);

    // clear perturbation state and keyreset
    pert.active = 0;
    pert.select = 0;
    keyreset = -1;

    // center and scale view, update scene
    autoscale(window);
    mjv_updateScene(m, d, &vopt, &pert, &cam, mjCAT_ALL, &scn);

    // set window title to mode name
    if( window && m->names )
        glfwSetWindowTitle(window, m->names);
}

// timer in milliseconds
mjtNum timer(void)
{
    // save start time
    static double starttm = 0;
    if( starttm==0 )
        starttm = glfwGetTime();

    // return time since start
    return (mjtNum)(1000 * (glfwGetTime() - starttm));
}

// clear all times
void cleartimers(mjData* d)
{
    for( int i=0; i<mjNTIMER; i++ )
    {
        d->timer[i].duration = 0;
        d->timer[i].number = 0;
    }
}

//--------------------------------- GLFW callbacks --------------------------------------

// keyboard
void keyboard(GLFWwindow* window, int key, int scancode, int act, int mods)
{
    int n;

    // require model
    if( !m )
        return;

    // do not act on release
    if( act==GLFW_RELEASE )
        return;

    switch( key )
    {
    case GLFW_KEY_F1:                   // help
        showhelp++;
        if( showhelp>2 )
            showhelp = 0;
        break;

    case GLFW_KEY_F2:                   // option
        showoption = !showoption;
        break;

    case GLFW_KEY_F3:                   // info
        showinfo = !showinfo;
        break;

    case GLFW_KEY_F4:                   // depth
        showdepth = !showdepth;
        break;

    case GLFW_KEY_F5:                   // toggle full screen
        showfullscreen = !showfullscreen;
        if( showfullscreen )
            glfwMaximizeWindow(window);
        else
            glfwRestoreWindow(window);
        break;

    case GLFW_KEY_F6:                   // stereo
        scn.stereo = (scn.stereo==mjSTEREO_NONE ? mjSTEREO_QUADBUFFERED : mjSTEREO_NONE);
        break;

    case GLFW_KEY_F7:                   // sensor figure
        showsensor = !showsensor;
        break;

    case GLFW_KEY_F8:                   // profiler
        showprofiler = !showprofiler;
        break;

    case GLFW_KEY_ENTER:                // slow motion
        slowmotion = !slowmotion;
        break;

    case GLFW_KEY_SPACE:                // pause
        paused = !paused;
        break;

    case GLFW_KEY_PAGE_UP:              // previous keyreset
    case GLFW_KEY_PAGE_DOWN:            // next keyreset
        if( key==GLFW_KEY_PAGE_UP )
            keyreset = mjMAX(-1, keyreset-1);
        else
            keyreset = mjMIN(m->nkey-1, keyreset+1);

        // continue with reset

    case GLFW_KEY_BACKSPACE:            // reset
        mj_resetData(m, d);
        if( keyreset>=0 && keyreset<m->nkey )
        {
            d->time = m->key_time[keyreset];
            mju_copy(d->qpos, m->key_qpos+keyreset*m->nq, m->nq);
            mju_copy(d->qvel, m->key


    "test-hpa",
			prevReplicas: 5,
			newReplicas:  5,
			expectedUp:   0,
			expectedDown: 0,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			controller := &FHPAController{
				scaleUpEvents:   make(map[string][]timestampedScaleEvent),
				scaleDownEvents: make(map[string][]timestampedScaleEvent),
			}

			controller.storeScaleEvent(tt.behavior, tt.key, tt.prevReplicas, tt.newReplicas)

			assert.Len(t, controller.scaleUpEvents[tt.key], tt.expectedUp, "Unexpected number of scale up events")
			assert.Len(t, controller.scaleDownEvents[tt.key], tt.expectedDown, "Unexpected number of scale down events")
		})
	}
}

// TestStabilizeRecommendationWithBehaviors verifies recommendation stabilization with behaviors
func TestStabilizeRecommendationWithBehaviors(t *testing.T) {
	now := time.Now()
	upWindow := int32(300)   // 5 minutes
	downWindow := int32(600) // 10 minutes

	tests := []struct {
		name                   string
		args                   NormalizationArg
		initialRecommendations []timestampedRecommendation
		expectedReplicas       int32
		expectedReason         string
		expectedMessage        string
	}{
		{
			name: "Scale up stabilized",
			args: NormalizationArg{
				Key:             "test-hpa-1",
				DesiredReplicas: 10,
				CurrentReplicas: 5,
				ScaleUpBehavior: &autoscalingv2.HPAScalingRules{
					StabilizationWindowSeconds: &upWindow,
				},
				ScaleDownBehavior: &autoscalingv2.HPAScalingRules{
					StabilizationWindowSeconds: &downWindow,
				},
			},
			initialRecommendations: []timestampedRecommendation{
				{recommendation: 8, timestamp: now.Add(-2 * time.Minute)},
				{recommendation: 7, timestamp: now.Add(-4 * time.Minute)},
			},
			expectedReplicas: 7,
			expectedReason:   "ScaleUpStabilized",
			expectedMessage:  "recent recommendations were lower than current one, applying the lowest recent recommendation",
		},
		{
			name: "Scale down stabilized",
			args: NormalizationArg{
				Key:             "test-hpa-2",
				DesiredReplicas: 3,
				CurrentReplicas: 8,
				ScaleUpBehavior: &autoscalingv2.HPAScalingRules{
					StabilizationWindowSeconds: &upWindow,
				},
				ScaleDownBehavior: &autoscalingv2.HPAScalingRules{
					StabilizationWindowSeconds: &downWindow,
				},
			},
			initialRecommendations: []timestampedRecommendation{
				{recommendation: 5, timestamp: now.Add(-5 * time.Minute)},
				{recommendation: 4, timestamp: now.Add(-8 * time.Minute)},
			},
			expectedReplicas: 5,
			expectedReason:   "ScaleDownStabilized",
			expectedMessage:  "recent recommendations were higher than current one, applying the highest recent recommendation",
		},
		{
			name: "No change needed",
			args: NormalizationArg{
				Key:             "test-hpa-3",
				DesiredReplicas: 5,
				CurrentReplicas: 5,
				ScaleUpBehavior: &autoscalingv2.HPAScalingRules{
					StabilizationWindowSeconds: &upWindow,
				},
				ScaleDownBehavior: &autoscalingv2.HPAScalingRules{
					StabilizationWindowSeconds: &downWindow,
				},
			},
			initialRecommendations: []timestampedRecommendation{
				{recommendation: 5, timestamp: now.Add(-1 * time.Minute)},
			},
			expectedReplicas: 5,
			expectedReason:   "ScaleUpStabilized",
			expectedMessage:  "recent recommendations were


utun.localuuid", uuid)
            apply()
        }
    }

    fun getEd25519RemotePublicKey(type: String): Ed25519PublicKeyParameters {
        if (type != PUBLIC_CLASS_A && type != PUBLIC_CLASS_C && type != PUBLIC_CLASS_D)
            throw Exception("trying to get public key for invalid type $type")
        val bytes = getKey(type)
        if(bytes == null) {
            Logger.setError("uninitialized keys")
            throw Exception("Trying to get uninitialized key: $type")
        }
        return Ed25519PublicKeyParameters(bytes)
    }

    fun getEd25519LocalPrivateKey(type: String): Ed25519PrivateKeyParameters {
        if (type != PRIVATE_CLASS_A && type != PRIVATE_CLASS_C && type != PRIVATE_CLASS_D)
            throw Exception("trying to get private key for invalid type $type")
        val bytes = getKey(type)
        if(bytes == null) {
            Logger.setError("uninitialized keys")
            throw Exception("Trying to get uninitialized key: $type")
        }
        val unsealed = KeyStoreHelper.unseal(KeyStoreHelper.SealedData.fromBytes(bytes))
        return Ed25519PrivateKeyParameters(unsealed)
    }

    fun getAddress(type: String): String? {
        if (!addresstypes.contains(type))
            throw Exception("trying to get address for invalid type $type")
        return context.getSharedPreferences("$appID.prefs", Context.MODE_PRIVATE).getString(type, null)
    }

    fun setAddress(type: String, value: String) {
        if (!addresstypes.contains(type))
            throw Exception("trying to set address for invalid type $type")
        with (context.getSharedPreferences("$appID.prefs", Context.MODE_PRIVATE).edit()) {
            putString(type, value)
            apply()
        }
    }

    var keyTransitSecret: ByteArray
        get() = getKey(KEY_TRANSIT_SECRET) ?: "witchinthewatch-'#s[MZu!Xv*UZjbt".encodeToByteArray()
        set(value) = setKey(KEY_TRANSIT_SECRET, value)

    fun resetKeyTransitSecret() {
        with (context.getSharedPreferences("$appID.prefs", Context.MODE_PRIVATE).edit()) {
            remove(KEY_TRANSIT_SECRET)
            apply()
        }
    }

    var encryptedDatabaseSecret: ByteArray?
        get() = getKey(ENCRYPTED_DB_SECRET)
        set(value) = setKey(ENCRYPTED_DB_SECRET, value!!)

    var encryptedRsaPrivate: ByteArray?
        get() = getKey(ENCRYPTED_RSA_KEY)
        set(value) = setKey(ENCRYPTED_RSA_KEY, value!!)

    var encryptedEcdsaPrivate: ByteArray?
        get() = getKey(ENCRYPTED_ECDSA_KEY)
        set(value) = setKey(ENCRYPTED_ECDSA_KEY, value!!)

    var notificationAccessDeniedForever: Boolean
        get() = context.getSharedPreferences("$appID.prefs", Context.MODE_PRIVATE).getString(NOTIFICATION_ACCESS_CONSENT, null) == "true"
        set(value) = with (context.getSharedPreferences("$appID.prefs", Context.MODE_PRIVATE).edit()) {
            putString(NOTIFICATION_ACCESS_CONSENT, if(value) "true" else "false")
            apply()
        }

    private fun getKey(type: String): ByteArray? {
        return context.getSharedPreferences("$appID.prefs", Context.MODE_PRIVATE).getString(type, null)?.fromHex()
    }

    fun setKey(type: String, value: ByteArray) {
        with (context.getSharedPreferences("$appID.prefs", Context.MODE_PRIVATE).edit()) {
            putString(type, value.hex())
            apply()
        }
    }
}package net.rec0de.android.watchwitch.adapter

import android.v


bled;

  HorizontalPodAutoscaling({this.disabled});

  HorizontalPodAutoscaling.fromJson(core.Map json_)
    : this(disabled: json_['disabled'] as core.bool?);

  core.Map<core.String, core.dynamic> toJson() => {
    if (disabled != null) 'disabled': disabled!,
  };
}

/// RFC-2616: cache control support
class HttpCacheControlResponseHeader {
  /// 14.6 response cache age, in seconds since the response is generated
  core.String? age;

  /// 14.9 request and response directives
  core.String? directive;

  /// 14.21 response cache expires, in RFC 1123 date format
  core.String? expires;

  HttpCacheControlResponseHeader({this.age, this.directive, this.expires});

  HttpCacheControlResponseHeader.fromJson(core.Map json_)
    : this(
        age: json_['age'] as core.String?,
        directive: json_['directive'] as core.String?,
        expires: json_['expires'] as core.String?,
      );

  core.Map<core.String, core.dynamic> toJson() => {
    if (age != null) 'age': age!,
    if (directive != null) 'directive': directive!,
    if (expires != null) 'expires': expires!,
  };
}

/// Configuration options for the HTTP (L7) load balancing controller addon,
/// which makes it easy to set up HTTP load balancers for services in a cluster.
class HttpLoadBalancing {
  /// Whether the HTTP Load Balancing controller is enabled in the cluster.
  ///
  /// When enabled, it runs a small pod in the cluster that manages the load
  /// balancers.
  core.bool? disabled;

  HttpLoadBalancing({this.disabled});

  HttpLoadBalancing.fromJson(core.Map json_)
    : this(disabled: json_['disabled'] as core.bool?);

  core.Map<core.String, core.dynamic> toJson() => {
    if (disabled != null) 'disabled': disabled!,
  };
}

/// Hugepages amount in both 2m and 1g size
class HugepagesConfig {
  /// Amount of 1G hugepages
  ///
  /// Optional.
  core.int? hugepageSize1g;

  /// Amount of 2M hugepages
  ///
  /// Optional.
  core.int? hugepageSize2m;

  HugepagesConfig({this.hugepageSize1g, this.hugepageSize2m});

  HugepagesConfig.fromJson(core.Map json_)
    : this(
        hugepageSize1g: json_['hugepageSize1g'] as core.int?,
        hugepageSize2m: json_['hugepageSize2m'] as core.int?,
      );

  core.Map<core.String, core.dynamic> toJson() => {
    if (hugepageSize1g != null) 'hugepageSize1g': hugepageSize1g!,
    if (hugepageSize2m != null) 'hugepageSize2m': hugepageSize2m!,
  };
}

/// ILBSubsettingConfig contains the desired config of L4 Internal LoadBalancer
/// subsetting on this cluster.
class ILBSubsettingConfig {
  /// Enables l4 ILB subsetting for this cluster.
  core.bool? enabled;

  ILBSubsettingConfig({this.enabled});

  ILBSubsettingConfig.fromJson(core.Map json_)
    : this(enabled: json_['enabled'] as core.bool?);

  core.Map<core.String, core.dynamic> toJson() => {
    if (enabled != null) 'enabled': enabled!,
  };
}

/// Configuration for controlling how IPs are allocated in the cluster.
class IPAllocationPolicy {
  /// The additional IP ranges that are added to the cluster.
  ///
  /// These IP ranges can be used by new node pools to allocate node and pod IPs
  /// automatically. Each AdditionalIPRangesConfig corresponds to a single
  /// subnetwork. Once a range is removed it will not show up in
  /// IPAllocationPolicy.
  ///
  /// Output only.
  core.List<AdditionalIPRangesConfig>? additionalIpRangesConfigs;

  /// The additional pod ranges that


d to snap, because GMNS and A/B Street may disagree about where a road
/// segment begins/ends. This could happen from OSM IDs changing over time or from different rules
/// about importing things like service roads.
struct Snapper {
    roads_incoming: HashMap<DirectedRoadID, Pt2D>,
    roads_outgoing: HashMap<DirectedRoadID, Pt2D>,
    movements: BTreeMap<MovementID, Movement>,
}

impl Snapper {
    fn new(map: &Map, i: IntersectionID) -> Result<Snapper> {
        let mut roads_incoming = HashMap::new();
        let mut roads_outgoing = HashMap::new();
        for r in &map.get_i(i).roads {
            let r = map.get_r(*r);

            let incoming_id = r.directed_id_to(i);
            let outgoing_id = r.directed_id_from(i);

            // TODO There are a few methods for finding the "middle" of a directed road; here's yet
            // another.
            let mut incoming_pts = Vec::new();
            let mut outgoing_pts = Vec::new();

            for l in &r.lanes {
                if l.lane_type.is_walkable() {
                    continue;
                }
                if l.dir == incoming_id.dir {
                    incoming_pts.push(l.lane_center_pts.last_pt());
                } else {
                    outgoing_pts.push(l.lane_center_pts.first_pt());
                }
            }

            if !incoming_pts.is_empty() {
                roads_incoming.insert(incoming_id, Pt2D::center(&incoming_pts));
            }
            if !outgoing_pts.is_empty() {
                roads_outgoing.insert(outgoing_id, Pt2D::center(&outgoing_pts));
            }
        }
        if roads_incoming.is_empty() || roads_outgoing.is_empty() {
            bail!("{} has no incoming or outgoing roads", i);
        }

        Ok(Snapper {
            roads_incoming,
            roads_outgoing,
            movements: map
                .get_i(i)
                .movements
                .iter()
                .filter(|(id, _)| !id.crosswalk)
                .map(|(k, v)| (*k, v.clone()))
                .collect(),
        })
    }

    fn get_mvmnt(&self, pair: (Pt2D, Pt2D), code: &str, map: &Map) -> Result<MovementID> {
        // Code is something like "WBT", westbound through.
        let code_turn_type = match code.chars().last() {
            Some('T') => TurnType::Straight,
            Some('L') => TurnType::Left,
            Some('R') => TurnType::Right,
            x => bail!("Weird movement_str {:?}", x),
        };
        let code_direction = &code[0..2];

        let (id, mvmnt) = self
            .movements
            .iter()
            .min_by_key(|(id, mvmnt)| {
                let from_cost = pair.0.dist_to(self.roads_incoming[&id.from]);
                let to_cost = pair.1.dist_to(self.roads_outgoing[&id.to]);
                let direction = cardinal_direction(
                    map.get_l(mvmnt.members[0].src)
                        .lane_center_pts
                        .overall_angle(),
                );

                // Arbitrary parameters, tuned to make weird geometry at University/Mill in Tempe
                // work.
                let type_cost = if mvmnt.turn_type == code_turn_type {
                    1.0
                } else {
                    2.0
                };
                // TODO This one is way more important than the geometry! Maybe JUST use


                                          ref_s)
  return _f_p_r_lcs(union_lcs_sum_across_all_references, m, n)

def rouge(hypotheses, references):
  """Calculates average rouge scores for a list of hypotheses and
  references"""

  # Filter out hyps that are of 0 length
  # hyps_and_refs = zip(hypotheses, references)
  # hyps_and_refs = [_ for _ in hyps_and_refs if len(_[0]) > 0]
  # hypotheses, references = zip(*hyps_and_refs)

  # Calculate ROUGE-1 F1, precision, recall scores
  rouge_1 = [
      rouge_n([hyp], [ref], 1) for hyp, ref in zip(hypotheses, references)
  ]
  rouge_1_f, rouge_1_p, rouge_1_r = map(np.mean, zip(*rouge_1))

  # Calculate ROUGE-2 F1, precision, recall scores
  rouge_2 = [
      rouge_n([hyp], [ref], 2) for hyp, ref in zip(hypotheses, references)
  ]
  rouge_2_f, rouge_2_p, rouge_2_r = map(np.mean, zip(*rouge_2))

  # Calculate ROUGE-L F1, precision, recall scores
  rouge_l = [
      rouge_l_sentence_level([hyp], [ref])
      for hyp, ref in zip(hypotheses, references)
  ]
  rouge_l_f, rouge_l_p, rouge_l_r = map(np.mean, zip(*rouge_l))

  return {
      "rouge_1/f_score": rouge_1_f,
      "rouge_1/r_score": rouge_1_r,
      "rouge_1/p_score": rouge_1_p,
      "rouge_2/f_score": rouge_2_f,
      "rouge_2/r_score": rouge_2_r,
      "rouge_2/p_score": rouge_2_p,
      "rouge_l/f_score": rouge_l_f,
      "rouge_l/r_score": rouge_l_r,
      "rouge_l/p_score": rouge_l_p,
  }


ionZ = new Laya.Quaternion();
    private tempRotationX = new Laya.Quaternion();
    private tempRotationY = new Laya.Quaternion();
    onStart(){
        this.camera = this.owner as Laya.Camera;
        this.isMouseDown = false;
        // this.target = this.owner.t
        Laya.stage.on(Laya.Event.MOUSE_DOWN,this,this.onMouseDown);
        Laya.stage.on(Laya.Event.MOUSE_UP,this,this.onMouseUp);
        Laya.stage.on(Laya.Event.MOUSE_OUT,this,this.onMouseOut);
        Laya.stage.on(Laya.Event.MOUSE_WHEEL,this,this.onMouseWheel);
    }

    private onMouseWheel(e:Laya.Event):void{
        // var postion = this.camera.transform.position;
        if(e.delta > 0){
            var a = new Laya.Vector3(0,0,0);
            var b = new Laya.Vector3(0,0,0);
            // postion += this.camera.transform.T
            this.camera.fieldOfView += 1;
        }else{
            this.camera.fieldOfView -= 1;
        }
    }

    public onMouseDown(e:Laya.Event):void{
        this.camera.transform.rotation.getYawPitchRoll(this.yawPitchRoll);
        this.lastMouseX = Laya.stage.mouseX;
        this.lastMouseY = Laya.stage.mouseY;
        this.isMouseDown = true;

    }

    public onMouseUp(e:Laya.Event):void{
        this.isMouseDown = false;
    }

    public onMouseOut(e:Laya.Event):void{
        this.isMouseDown = false;
    }

    onUpdate(){
        // laya.
        console.log("time - ");
        // state.
      //  this.updateCamera();
    }

    private updateCamera():void{
        if(!isNaN(this.lastMouseX) && !isNaN(this.lastMouseY)){
            Laya.KeyBoardManager.hasKeyDown(Laya.Keyboard.W) && this.camera.transform.rotate(new Laya.Vector3(0,1,0),true,false);
            Laya.KeyBoardManager.hasKeyDown(Laya.Keyboard.S) && this.camera.transform.rotate(new Laya.Vector3(0,1,0),true,false);
            Laya.KeyBoardManager.hasKeyDown(Laya.Keyboard.A) && this.camera.transform.rotate(new Laya.Vector3(1,0,0),true,false);
            Laya.KeyBoardManager.hasKeyDown(Laya.Keyboard.D) && this.camera.transform.rotate(new Laya.Vector3(1,0,0),true,false);
            if(this.isMouseDown){
                var mouseX = Laya.stage.mouseX - this.lastMouseX;
                var mouseY = Laya.stage.mouseY - this.lastMouseY;
                var yprElem: Float32Array = this.yawPitchRoll.elements;
                yprElem[0] -= mouseX * this.rotainSpeed * 0.5;
                yprElem[1] -= mouseX * this.rotainSpeed * 0.5;
                this.updateRotation();
            }
        }
        this.lastMouseX = Laya.stage.mouseX;
        this.lastMouseY = Laya.stage.mouseY;
    }

    private updateRotation():void{
        var yprElem:Float32Array = this.yawPitchRoll.elements;
        if(Math.abs(yprElem[1]) < 1.5){
            Laya.Quaternion.createFromYawPitchRoll(yprElem[0],yprElem[1],yprElem[2],this.tempRotationZ);
            this.camera.transform.localRotation = this.tempRotationZ;
        }
    }

    onEnable(){

    }

    onDestroy(){

    }

    onDisable(){


AsHtml( GameVersion version, string versionPostfix, GameLocale locale, WebsiteLanguage websiteLanguage, TSS.TSSFile stringDic, Dictionary<uint, TSS.TSSEntry> inGameIdDict ) {
			StringBuilder sb = new StringBuilder();
			sb.Append( "
" );
			//sb.Append( RefString + "
" );

			sb.Append( "" );
			sb.Append( "" );
			sb.Append( "	" );

			int colspan = websiteLanguage.WantsBoth() ? 1 : 2;
			if ( websiteLanguage.WantsJp() ) {
				sb.Append( "" );
				sb.Append( "" );
				sb.Append( inGameIdDict[NameStringDicID].StringJpnHtml( version, inGameIdDict ) );
				sb.Append( "" );
				sb.Append( "
" );
				sb.Append( inGameIdDict[DescStringDicID].StringJpnHtml( version, inGameIdDict ) );
				sb.Append( "	" );
			}

			if ( websiteLanguage.WantsEn() ) {
				sb.Append( "" );
				sb.Append( "" );
				sb.Append( inGameIdDict[NameStringDicID].StringEngHtml( version, inGameIdDict ) );
				sb.Append( "" );
				sb.Append( "
" );
				sb.Append( inGameIdDict[DescStringDicID].StringEngHtml( version, inGameIdDict ) );
				sb.Append( "	" );
			}

			sb.Append( "" );
			if ( LearnableByBitmask > 0 ) {
				sb.Append( "" );
				Website.WebsiteGenerator.AppendCharacterBitfieldAsImageString( sb, inGameIdDict, version, LearnableByBitmask, websiteLanguage.MainJp() );
				sb.Append( "" );
			}
			sb.Append( EquipCost + " SP
" );
			sb.Append( LearnCost + " LP
" );
			sb.Append( "Symbol Weight: " + SymbolValue + "
" );

			//sb.Append( "~7: " + Unknown7 + "
" );
			//sb.Append( "~13: " + Unknown13 + "
" );
			//sb.Append( "~14: " + Unknown14 + "
" );
			//sb.Append( "~15: " + Unknown15 + "
" );
			if ( Inactive == 0 ) { sb.Append( "Unusable
" ); }
			sb.Append( "	" );
			sb.Append( "
" );
			return sb.ToString();
		}
	}
}


using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Shop.Infrastructure;
using Shop.Infrastructure.Data;
using Shop.Infrastructure.Web.StandardTable;
using Shop.Module.Catalog.Entities;
using Shop.Module.Core.Entities;
using Shop.Module.Core.Extensions;
using Shop.Module.Shipping.Entities;
using Shop.Module.Shipping.ViewModels;

namespace Shop.Module.Shipping.Controllers
{
    /// <summary>
    /// 运费模板 API 控制器，负责管理运费模板相关的操作。
    /// </summary>
    [Authorize(Roles = "admin")]
    [Route("api/shippings/freight-templates")]
    public class FreightTemplateApiController : ControllerBase
    {
        private readonly IRepository<FreightTemplate> _freightTemplateRepository;
        private readonly IWorkContext _workContext;
        private readonly IRepository<StateOrProvince> _provinceRepository;
        private readonly IRepository<PriceAndDestination> _priceAndDestinationRepository;
        private readonly IRepository<Product> _productRepository;

        public FreightTemplateApiController(
            IRepository<FreightTemplate> freightTemplateRepository,
            IWorkContext workContext,
            IRepository<StateOrProvince> provinceRepository,
            IRepository<PriceAndDestination> priceAndDestinationRepository,
            IRepository<Product> productRepository)
        {
            _freightTemplateRepository = freightTemplateRepository;
            _workContext = workContext;
            _provinceRepository = provinceRepository;
            _priceAndDestinationRepository = priceAndDestinationRepository;
            _productRepository = productRepository;
        }

        /// <summary>
        /// 获取所有运费模板的列表。
        /// </summary>
        /// <returns>运费模板的列表。</returns>
        [HttpGet]
        public async Task<Result> Get()
        {
            var query = _freightTemplateRepository.Query();
            var result = await query.Select(x => new FreightTemplateQueryResult
            {
                Id = x.Id,
                Name = x.Name,
                Note = x.Note,
                CreatedOn = x.CreatedOn,
                UpdatedOn = x.UpdatedOn
            }).ToListAsync();
            return Result.Ok(result);
        }

        /// <summary>
        /// 根据给定的参数分页获取运费模板的列表。
        /// </summary>
        /// <param name="param">分页和查询参数。</param>
        /// <returns>分页的运费模板列表。</returns>
        [HttpPost("grid")]
        public async Task<Result<StandardTableResult<FreightTemplateQueryResult>>> DataList([FromBody] StandardTableParam param)
        {
            var query = _freightTemplateRepository.Query();


12 4c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3zm-9 8c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1H6v-1z" />
                </svg>
                My Videos

                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"
                    style="display: inline-block; vertical-align: middle; margin-right: 8px;">
                    <path
                        d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-2z" />
                </svg>
                Liked

                TOPICS

                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"
                    style="display: inline-block; vertical-align: middle; margin-right: 8px;">
                    <path
                        d="M17.06 11.57c.59-.69.94-1.59.94-2.57 0-1.86-1.27-3.43-3-3.87V3h-2v2h-2V3H9v2H6v2h1c.55 0 1 .45 1 1v8c0 .55-.45 1-1 1H6v2h3v2h2v-2h2v2h2v-2.13c2.39-.54 4-2.65 4-5.07 0-1.37-.53-2.62-1.4-3.55M10 7h4c1.1 0 2 .9 2 2s-.9 2-2 2h-4V7zm5 10h-5v-4h5c1.1 0 2 .9 2 2s-.9 2-2 2z" />
                </svg>
                Bitcoin

                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"
                    style="display: inline-block; vertical-align: middle; margin-right: 8px;">
                    <path d="M7 2v11h3v9l7-12h-4l4-8z" />
                </svg>
                Nostr

                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"
                    style="display: inline-block; vertical-align: middle; margin-right: 8px;">
                    <path
                        d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6z" />
                </svg>
                Technology

                <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"
                    style="display: inline-block; vertical-al


_1_1Array_3_01T_00_01N_00_01true_01_4.html#a0a692495c5f7a7d098e60b9292a07e4f',1,'cutlass::Array< T, N, true >::front() const '],['../classcutlass_1_1Array_3_01T_00_01N_00_01false_01_4.html#aa89dd0781c0a81421589182a5402df8b',1,'cutlass::Array< T, N, false >::front()'],['../classcutlass_1_1Array_3_01T_00_01N_00_01false_01_4.html#ab7ebd33505e48ab3beb6b551e8b762e5',1,'cutlass::Array< T, N, false >::front() const ']]],
  ['functor_5fcaller',['functor_caller',['../structcutlass_1_1reduction_1_1BatchedReduction.html#a7c1d173cbe3abd93bd7bd4c4bf0e0d26',1,'cutlass::reduction::BatchedReduction']]]
];
var searchData=
[
  ['v',['v',['../structcutlass_1_1reference_1_1device_1_1detail_1_1TensorFillLinearFunc_1_1Params.html#a37acaffa4b543356b0853056134f2d3a',1,'cutlass::reference::device::detail::TensorFillLinearFunc::Params::v()'],['../structcutlass_1_1reference_1_1host_1_1detail_1_1TensorFillLinearFunc.html#aa47ca9b4e4187f4eee4f332b6cd855bb',1,'cutlass::reference::host::detail::TensorFillLinearFunc::v()']]],
  ['val',['val',['../structcutlass_1_1platform_1_1alignment__of_1_1pad.html#abc729cc51d5c90b1d7b0df3092d47cd4',1,'cutlass::platform::alignment_of::pad']]],
  ['valid',['valid',['../classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileAccessIterator_3_01Shape___00_01Elemen784a0e9da3f55064c47e5613791f51f7.html#ae95bba63dc3b336a5ebfe6bac4d59723',1,'cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::PitchLinear, AdvanceRank, ThreadMap_, AccessType_ >::valid()'],['../classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileAccessIterator_3_01Shape___00_01Elemen89c687c583745a73cb485041911a4c4e.html#a9135a1ca1ddc279c85df584d23fa7003',1,'cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::ColumnMajor, AdvanceRank, ThreadMap_, AccessType_ >::valid()'],['../classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileAccessIterator_3_01Shape___00_01Elemen9838736ad62fae54213fbaf722a989ab.html#a0d3a78ab6cc435681f257465bd452f79',1,'cutlass::transform::threadblock::PredicatedTileAccessIterator< Shape_, Element_, layout::RowMajor, AdvanceRank, ThreadMap_, AccessType_ >::valid()'],['../classcutlass_1_1transform_1_1threadblock_1_1PredicatedTileAccessIterator_3_01Shape___00_01Elemenab63a1e105bf37f6371516cb9e2c5a7a.html#ad55ebaa9c0e4fa51489ee0bfbe122d46',1,'cutlass::transform::threadblock::PredicatedTileA


"BhMCVVMxFDASBgNVBAoTC0VudHJ1c3QubmV0MUgwRgYDVQQLFD93d3cuZW50"
        + "cnVzdC5uZXQvQ2xpZW50X0NBX0luZm8vQ1BTIGluY29ycC4gYnkgcmVmLiBs"
        + "aW1pdHMgbGlhYi4xJTAjBgNVBAsTHChjKSAxOTk5IEVudHJ1c3QubmV0IExp"
        + "bWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENsaWVudCBDZXJ0aWZpY2F0"
        + "aW9uIEF1dGhvcml0eTAeFw05OTEwMTIxOTI0MzBaFw0xOTEwMTIxOTU0MzBa"
        + "MIHJMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxSDBGBgNV"
        + "BAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0FfSW5mby9DUFMgaW5jb3Jw"
        + "LiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UECxMcKGMpIDE5OTkgRW50"
        + "cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50cnVzdC5uZXQgQ2xpZW50"
        + "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUAA4GL"
        + "ADCBhwKBgQDIOpleMRffrCdvkHvkGf9FozTC28GoT/Bo6oT9n3V5z8GKUZSv"
        + "x1cDR2SerYIbWtp/N3hHuzeYEpbOxhN979IMMFGpOZ5V+Pux5zDeg7K6PvHV"
        + "iTs7hbqqdCz+PzFur5GVbgbUB01LLFZHGARS2g4Qk79jkJvh34zmAqTmT173"
        + "iwIBA6OCAeAwggHcMBEGCWCGSAGG+EIBAQQEAwIABzCCASIGA1UdHwSCARkw"
        + "ggEVMIHkoIHhoIHepIHbMIHYMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50"
        + "cnVzdC5uZXQxSDBGBgNVBAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0Ff"
        + "SW5mby9DUFMgaW5jb3JwLiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UE"
        + "CxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50"
        + "cnVzdC5uZXQgQ2xpZW50IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYD"
        + "VQQDEwRDUkwxMCygKqAohiZodHRwOi8vd3d3LmVudHJ1c3QubmV0L0NSTC9D"
        + "bGllbnQxLmNybDArBgNVHRAEJDAigA8xOTk5MTAxMjE5MjQzMFqBDzIwMTkx"
        + "MDEyMTkyNDMwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUxPucKXuXzUy


on must be called when a player logs off for each NPC they were observing.
     */
    internal fun removeObserver(index: Int) {
        // If the allocation cycle is the same as current cycle count,
        // a "hotswap" has occurred.
        // This means that a npc was deallocated and another allocated the same index
        // in the same cycle.
        // Due to the new one being allocated, the observer count is already reset
        // to zero, and we cannot decrement the observer count further - it would go negative.
        if (details.allocateCycle == NpcInfoProtocol.cycleCount) {
            return
        }
        tracker.remove(index)
    }

    /**
     * Resets the observer count.
     */
    internal fun resetObservers() {
        tracker.reset()
    }

    /**
     * Updates the spawn direction of the NPC.
     *
     * Table of possible direction values:
     * ```
     * | Id |  Direction | Angle |
     * |:--:|:----------:|:-----:|
     * |  0 | North-West |  768  |
     * |  1 |    North   |  1024 |
     * |  2 | North-East |  1280 |
     * |  3 |    West    |  512  |
     * |  4 |    East    |  1536 |
     * |  5 | South-West |  256  |
     * |  6 |    South   |   0   |
     * |  7 | South-East |  1792 |
     * ```
     *
     * @param direction the direction for the NPC to face.
     */
    @Deprecated(
        message = "Deprecated. Use setDirection(direction) for consistency.",
        replaceWith = ReplaceWith("setDirection(direction)"),
    )
    public fun updateDirection(direction: Int) {
        setDirection(direction)
    }

    /**
     * Updates the spawn direction of the NPC.
     *
     * Table of possible direction values:
     * ```
     * | Id |  Direction | Angle |
     * |:--:|:----------:|:-----:|
     * |  0 | North-West |  768  |
     * |  1 |    North   |  1024 |
     * |  2 | North-East |  1280 |
     * |  3 |    West    |  512  |
     * |  4 |    East    |  1536 |
     * |  5 | South-West |  256  |
     * |  6 |    South   |   0   |
     * |  7 | South-East |  1792 |
     * ```
     *
     * @param direction the direction for the NPC to face.
     */
    public fun setDirection(direction: Int) {
        require(direction in 0..7) {
            "Direction must be a value in range of 0..7. " +
                "See the table in documentation. Value: $direction"
        }
        this.details.updateDirection(direction)
    }

    /**
     * Sets the id of the avatar - any new observers of this NPC will receive the new id.
     * This should be used in tandem with the transformation extended info block.
     * @param id the id of the npc to set to - any new observers will see that id instead.
     */
    public fun setId(id: Int) {
        require(id in 0..16383) {
            "Id must be a value in range of 0..16383. Value: $id"
        }
        this.details.id = id
    }

    /**
     * A helper function to teleport the NPC to a new coordinate.
     * This will furthermore mark the movement type as teleport, meaning no matter what other
     * coordinate changes are applied, as teleport has the highest priority, teleportation
     * will be how it is rendered on the client's end.
     * @param level the new height level of the NPC
     * @param x the new absolute x coordinate of the NPC
     * @param z the new absolute z coordinate of the NPC
     * @param jump whether to "jump" the NPC to the new coordinate, or to treat it as a
     * regular walk/run type movement. While this should __almost__ always be


)}'.", warning=True); return True

            if not silent: self._print_log(f"Send cancel req for {order_id} ({symbol})...")
            await self.private_client.cancel_order(order_id=order_id, symbol=symbol)
            if not silent: self._print_log(f"Cancel req for {order_id} sent. Verify...")
            await asyncio.sleep(config.POLL_INTERVAL_SECONDS * 0.75)

            final_s = await self._check_order_status(order_id, symbol)
            if final_s and final_s.get('status') == 'Cancelled':
                if not silent: self._print_log(f"Order {order_id} confirmed CANCELLED.")
                return True
            if not silent: self._print_log(f"Could not confirm cancel {order_id}. Final: {final_s.get('status') if final_s else 'Unknown'}", warning=True)
            return False
        except Exception as e: self._print_log(f"Err cancel order {order_id}: {e}", error=True); return False

    # ========================= START: SỬA HÀM TÍNH PHÍ =========================
    def _calculate_pnl_and_fees(self, trade_details):
        """
        Tính toán PnL và phí, có phân biệt phí Maker và Taker.
        """
        size = float(trade_details.get('size', 0))
        en_s = float(trade_details.get('avg_spot_price', 0))
        en_f = float(trade_details.get('avg_futures_price', 0))
        ex_s = float(trade_details.get('exit_price_spot', 0))
        ex_f = float(trade_details.get('exit_price_futures', 0))

        if ex_s == 0 and en_s != 0: ex_s = en_s
        if ex_f == 0 and en_f != 0: ex_f = en_f

        # Phí vào lệnh: Chân Spot là lệnh Limit (Maker), chân Future là lệnh Market (Taker)
        fee_se = size * en_s * config.FEE_MAKER_SPOT
        fee_fe = size * en_f * config.FEE_TAKER_FUTURES

        # Phí đóng lệnh: Tạm tính là Taker cho cả hai chân để ước tính thận trọng (trường hợp xấu nhất)
        fee_sx = size * ex_s * config.FEE_TAKER_SPOT
        fee_fx = size * ex_f * config.FEE_TAKER_FUTURES

        pnl_s, pnl_f = 0, 0
        if trade_details.get('position_type') == "positive_basis":
            pnl_s = (ex_s - en_s) * size
            pnl_f = (en_f - ex_f) * size
        elif trade_details.get('position_type') == "negative_basis":
            pnl_s = (en_s - ex_s) * size
            pnl_f = (ex_f - en_f) * size

        total_f = sum([fee_se, fee_fe, fee_sx, fee_fx])
        pnl_g = pnl_s + pnl_f

        return {
            "pnl_spot_leg": pnl_s, "pnl_futures_leg": pnl_f,
            "fee_spot_entry": fee_se, "fee_futures_entry": fee_fe,
            "fee_spot_exit": fee_sx, "fee_futures_exit": fee_fx,
            "total_fee": total_f, "pnl_gross": pnl_g, "pnl_net": pnl_g - total_f,
            "exit_price_spot": ex_s, "exit_price_futures": ex_f
        }
    # ========================== END: SỬA HÀM TÍNH PHÍ ==========================

    async def run(self):
        self.bot_running = True
        while self.bot_running:
            try:
                if not self.position_open:
                    await self._clear_pre_existing_positions(called_during_run_loop=True)
                    bal_after_cleanup = await self._get_net_usdc_balance()
                    if bal_after_cleanup < 10:
                        self._print_log(f"Net USDC bal ({bal_after_cleanup:.2f}) too low. Waiting.", warning=True)
                        await asyncio.sleep(30); continue

                self._print_log(f"{'='*20} New Cycle {'='*20}")
                if self.position_open:
                    await self.monitor_position()
                    continue

                results = await asyncio.gather(
                    self._get_market_prices_and_mid(), self._check_liquidity_ok(),
                    self._is_funding_soon(), self._get_net_usdc_balance(), return_exceptions=True)
                prices, liq_ok, fund_soon, usdc_bal = results

                if any(isinstance(r, Exception) for r in results):
                    self._print_log("Err fetch initial data.", error=True, detail=[r for r in results if isinstance(r,Exception)]); await asyncio.sleep(config.RETRY_DELAY_SECONDS_ERROR); continue

                s_last, f_last, s_mid, f_mid = prices
                if not all(prices): self._print_log(f"Price data incomplete.", warning=True); await asyncio.sleep(config.RETRY_DELAY_SECONDS_SHORT); continue
                if s_last == 0: self._print_log("Spot price 0.", warnin


ist of {subject}
				{format}
				""";
		PromptTemplate promptTemplate = PromptTemplate.builder()
			.template(template)
			.variables(Map.of("subject", "numbers from 1 to 9 under they key name 'numbers'", "format", format))
			.build();
		Prompt prompt = new Prompt(promptTemplate.createMessage());
		Generation generation = this.chatModel.call(prompt).getResult();

		Map<String, Object> result = outputConverter.convert(generation.getOutput().getText());
		assertThat(result.get("numbers")).isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));

	}

	@Test
	void beanOutputConverter() {

		BeanOutputConverter<ActorsFilms> outputConverter = new BeanOutputConverter<>(ActorsFilms.class);

		String format = outputConverter.getFormat();
		String template = """
				Generate the filmography for a random actor.
				{format}
				""";
		PromptTemplate promptTemplate = PromptTemplate.builder()
			.template(template)
			.variables(Map.of("format", format))
			.build();
		Prompt prompt = new Prompt(promptTemplate.createMessage());
		Generation generation = this.chatModel.call(prompt).getResult();

		ActorsFilms actorsFilms = outputConverter.convert(generation.getOutput().getText());
		assertThat(actorsFilms.getActor()).isNotEmpty();
	}

	@Test
	void beanOutputConverterRecords() {

		BeanOutputConverter<DeepSeekWithOpenAiChatModelIT.ActorsFilmsRecord> outputConverter = new BeanOutputConverter<>(
				DeepSeekWithOpenAiChatModelIT.ActorsFilmsRecord.class);

		String format = outputConverter.getFormat();
		String template = """
				Generate the filmography of 5 movies for Tom Hanks.
				{format}
				""";
		PromptTemplate promptTemplate = PromptTemplate.builder()
			.template(template)
			.variables(Map.of("format", format))
			.build();
		Prompt prompt = new Prompt(promptTemplate.createMessage());
		Generation generation = this.chatModel.call(prompt).getResult();

		DeepSeekWithOpenAiChatModelIT.ActorsFilmsRecord actorsFilms = outputConverter
			.convert(generation.getOutput().getText());
		logger.info("{}", actorsFilms);
		assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
		assertThat(actorsFilms.movies()).hasSize(5);
	}

	@Test
	void beanStreamOutputConverterRecords() {

		BeanOutputConverter<DeepSeekWithOpenAiChatModelIT.ActorsFilmsRecord> outputConverter = new BeanOutputConverter<>(
				DeepSeekWithOpenAiChatModelIT.ActorsFilmsRecord.class);

		String format = outputConverter.getFormat();
		String template = """
				Generate the filmography of 5 movies for Tom Hanks.
				{format}
				""";
		PromptTemplate promptTemplate = PromptTemplate.builder()
			.template(template)
			.variables(Map.of("format", format))
			.build();
		Prompt prompt = new Prompt(promptTemplate.createMessage());

		String generationTextFromStream = this.chatModel.stream(prompt)
			.collectList()
			.block()
			.stream()
			.map(ChatResponse::getResults)
			.flatMap(List::stream)
			.map(Generation::getOutput)
			.map(AssistantMessage::getText)
			.collect(Collectors.joining());

		DeepSeekWithOpenAiChatModelIT.ActorsFilmsRecord actorsFilms = outputConverter.convert(generationTextFromStream);
		logger.info("{}", actorsFilms);
		assertThat(actorsFilms.actor()).isEqualTo("Tom Hanks");
		assertThat(actorsFilms.movies()).hasSize(5);
	}

	@Test
	@Disabled("The current version of the deepseek-chat model's Function Calling capability is unstable, which may result in looped calls or empty responses.")
	void functionCallTest() {

		UserMessage userMessage = new UserMessage("What's the weather like in San Francisco, Tokyo, and Paris?");

		List<


7}
	pop {r1}
	bx r1
	.align 2, 0
_08063320: .4byte gCamera

	thumb_func_start sub_8063324
sub_8063324: @ 0x08063324
	push {r4, r5, r6, r7, lr}
	mov r7, sl
	mov r6, sb
	mov r5, r8
	push {r5, r6, r7}
	sub sp, #8
	adds r6, r0, #0
	adds r0, #0x6c
	str r0, [sp]
	movs r1, #0
	mov r8, r1
	mov sb, r1
	movs r1, #0x84
	lsls r1, r1, #1
	adds r0, r6, r1
	bl UpdateSpriteAnimation
	cmp r0, #0
	bne _0806334E
	movs r0, #1
	mov sb, r0
_0806334E:
	movs r1, #0x9c
	lsls r1, r1, #1
	adds r0, r6, r1
	bl UpdateSpriteAnimation
	cmp r0, #0
	bne _08063366
	mov r0, sb
	adds r0, #1
	lsls r0, r0, #0x18
	lsrs r0, r0, #0x18
	mov sb, r0
_08063366:
	adds r0, r6, #0
	adds r0, #0x3c
	str r0, [sp, #4]
	movs r1, #0x40
	adds r1, r1, r6
	mov sl, r1
	ldr r7, _080633E8 @ =gCamera
_08063374:
	movs r0, #0x84
	lsls r0, r0, #1
	adds r2, r6, r0
	mov r1, r8
	lsls r4, r1, #3
	ldr r0, [sp, #4]
	adds r5, r0, r4
	ldr r1, [r5]
	asrs r1, r1, #8
	ldrh r0, [r6, #0x14]
	lsls r0, r0, #8
	adds r1, r1, r0
	ldr r0, [r7]
	subs r1, r1, r0
	strh r1, [r2, #0x10]
	add r4, sl
	ldr r1, [r4]
	asrs r1, r1, #8
	ldrh r0, [r6, #0x16]
	lsls r0, r0, #8
	adds r1, r1, r0
	ldr r0, [r7, #4]
	subs r1, r1, r0
	strh r1, [r2, #0x12]
	adds r0, r2, #0
	bl DisplaySprite
	movs r1, #0x9c
	lsls r1, r1, #1
	adds r2, r6, r1
	ldr r1, [r5]
	asrs r1, r1, #8
	ldrh r0, [r6, #0x14]
	lsls r0, r0, #8
	adds r1, r1, r0
	ldr r0, [r7]
	subs r5, r1, r0
	strh r5, [r2, #0x10]
	ldr r1, [r4]
	asrs r1, r1, #8
	ldrh r0, [r6, #0x16]
	lsls r0, r0, #8
	adds r1, r1, r0
	ldr r0, [r7, #4]
	subs r3, r1, r0
	strh r3, [


.has-carousel+.hero-footer,.hero.has-carousel+.hero-head{z-index:10;overflow:hidden}.hero.has-carousel .hero-carousel{position:absolute;top:0;left:0;bottom:0;right:0;height:auto;border:none;margin:auto;padding:0;z-index:0}.hero.has-carousel .hero-carousel .slider{width:100%;max-width:100%;overflow:hidden;height:100%!important;max-height:100%;z-index:0}.hero.has-carousel .hero-carousel .slider .has-background{max-height:100%}.hero.has-carousel .hero-carousel .slider .has-background .is-background{-o-object-fit:cover;object-fit:cover;-o-object-position:center center;object-position:center center;height:100%;width:100%}.hero.has-carousel .hero-body{margin:0 3rem;z-index:10}/*!
 * Bootstrap v4.5.2 (https://getbootstrap.com/)
 * Copyright 2011-2020 The Bootstrap Authors
 * Copyright 2011-2020 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
 */:root{--blue:#007bff;--indigo:#6610f2;--purple:#6f42c1;--pink:#e83e8c;--red:#dc3545;--orange:#fd7e14;--yellow:#ffc107;--green:#28a745;--teal:#20c997;--cyan:#17a2b8;--white:#fff;--gray:#6c757d;--gray-dark:#343a40;--primary:#007bff;--secondary:#6c757d;--success:#28a745;--info:#17a2b8;--warning:#ffc107;--danger:#dc3545;--light:#f8f9fa;--dark:#343a40;--breakpoint-xs:0;--breakpoint-sm:576px;--breakpoint-md:768px;--breakpoint-lg:992px;--breakpoint-xl:1200px;--font-family-sans-serif:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-family-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}article,aside,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff}[tabindex="-1"]:focus:not(:focus-visible){outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol


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

//! Tasks implemented on top of OS threads
//!
//! This module contains the implementation of the 1:1 threading module required
//! by rust tasks. This implements the necessary API traits laid out by std::rt
//! in order to spawn new tasks and deschedule the current task.

use std::any::Any;
use std::cast;
use std::rt::bookkeeping;
use std::rt::env;
use std::rt::local::Local;
use std::rt::rtio;
use std::rt::stack;
use std::rt::task::{Task, BlockedTask, SendMessage};
use std::rt::thread::Thread;
use std::rt;
use std::task::TaskOpts;
use std::unstable::mutex::NativeMutex;

use io;
use task;

/// Creates a new Task which is ready to execute as a 1:1 task.
pub fn new(stack_bounds: (uint, uint)) -> ~Task {
    let mut task = ~Task::new();
    let mut ops = ops();
    ops.stack_bounds = stack_bounds;
    task.put_runtime(ops);
    return task;
}

fn ops() -> ~Ops {
    ~Ops {
        lock: unsafe { NativeMutex::new() },
        awoken: false,
        io: io::IoFactory::new(),
        // these *should* get overwritten
        stack_bounds: (0, 0),
    }
}

/// Spawns a function with the default configuration
pub fn spawn(f: proc():Send) {
    spawn_opts(TaskOpts::new(), f)
}

/// Spawns a new task given the configuration options and a procedure to run
/// inside the task.
pub fn spawn_opts(opts: TaskOpts, f: proc():Send) {
    let TaskOpts {
        notify_chan, name, stack_size,
        stderr, stdout,
    } = opts;

    let mut task = ~Task::new();
    task.name = name;
    task.stderr = stderr;
    task.stdout = stdout;
    match notify_chan {
        Some(chan) => { task.death.on_exit = Some(SendMessage(chan)); }
        None => {}
    }

    let stack = stack_size.unwrap_or(env::min_stack());
    let task = task;
    let ops = ops();

    // Note that this increment must happen *before* the spawn in order to
    // guarantee that if this task exits it will always end up waiting for the
    // spawned task to exit.
    bookkeeping::increment();

    // Spawning a new OS thread guarantees that __morestack will never get
    // triggered, but we must manually set up the actual stack bounds once this
    // function starts executing. This raises the lower limit by a bit because
    // by the time that this function is executing we've already consumed at
    // least a little bit of stack (we don't know the exact byte address at
    // which our stack started).
    Thread::spawn_stack(stack, proc() {
        let something_around_the_top_of_the_stack = 1;
        let addr = &something_around_the_top_of_the_stack as *int;
        let my_stack = addr as uint;
        unsafe {
            stack::record_stack_bounds(my_stack - stack + 1024, my_stack);
        }
        let mut ops = ops;
        ops.stack_bounds = (my_stack - stack + 1024, my_stack);

        let mut f = Some(f);
        let mut task = task;
        task.put_runtime(ops);
        let t = task.run(|| { f.take_unwrap()() });
        drop(t);
        bookkeeping::decrement();
    })
}

// This structure is the glue between channels and the 1:1 scheduling mode. This
// structure is allocated once per task.
struct O


olors.white,
              tagText: '自定义标签自定义标签自定义标签自定义标签自定义标签自定义标签自定义标签自定义标签',
            ),
            Container(
              height: 20,
            ),
            BrnStateTag(
              tagText: '自定义标签自定义标签自定义标标别长特别签自定义标签自定义标签',
            ),
            Text(
              '异常案例：文案特别长',
              style: TextStyle(
                color: Color(0xFF222222),
                fontSize: 28,
              ),
            ),
            BrnStateTag(
              tagText:
                  '标题特别长特别长特别长特别长特别长特别长特别长特别长标题特别长特别长特别长特别长特别长特别长特别长特别长标题特别长特别长特别长特别长特别长特别长特别长特别长',
            ),
          ],
        ),
      ),
    );
  }
}

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';

class BorderTagExample extends StatefulWidget {
  @override
  _BorderTagExampleState createState() => _BorderTagExampleState();
}

class _BorderTagExampleState extends State<BorderTagExample> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BrnAppBar(
        title: "带边框的标签",
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          '规则',
          style: TextStyle(
              color: Color(0xFF222222),
              fontSize: 28,
              fontWeight: FontWeight.bold),
        ),
        BrnBubbleText(maxLines: 4, text: ' 文字大小 11，上下左右间距 3'),
        Text(
          '正常案例',
          style: TextStyle(
            color: Color(0xFF222222),
            fontSize: 28,
          ),
        ),
        BrnTagCustom.buildBorderTag(
          tagText: '已盘点',
        ),
        Text(
          '正常案例1',
          style: TextStyle(
            color: Color(0xFF222222),
            fontSize: 28,
          ),
        ),
        BrnTagCustom.buildBorderTag(
          tagText: '认证通过',
          textColor: Colors.red,
          borderColor: Colors.red,
          borderWidth: 2,
          fontSize: 24,
          textPadding: EdgeInsets.all(6),
        ),
      ],
    );
  }
}

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';

/// 描述: 带按钮的通知example

class BrnNoticeBarWithButtonExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BrnAppBar(
        title: '通知样式01',
      ),
      body: SingleChildScrollView(
          child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
            Text(
              '规则',
              style: TextStyle(
                color: Color(0xFF222222),
                fontSize: 28,
              ),
            ),
            BrnBubbleText(
              maxLines: 3,
              text:
                  '高度56，左边为标签，中间是通知内容，右边是按钮， 其中通知内容必传，标签和按钮文案如果是空，就不显示。所有颜色均支持自定义',
            ),
            Text(
              '默认样式',
              style: TextStyle(
                color: Color(0xFF222222),
                fontSize


from asyncio import sleep

from pyrogram import filters

from config import BANNED_USERS
from YukkiMusic import app
from YukkiMusic.core.mongo import mongodb
from YukkiMusic.utils.permissions import adminsOnly

antiservicedb = mongodb.antiservice

async def is_antiservice_on(chat_id: int) -> bool:
    chat = await antiservicedb.find_one({"chat_id": chat_id})
    if not chat:
        return True
    return False

async def antiservice_on(chat_id: int):
    is_antiservice = await is_antiservice_on(chat_id)
    if is_antiservice:
        return
    return await antiservicedb.delete_one({"chat_id": chat_id})

async def antiservice_off(chat_id: int):
    is_antiservice = await is_antiservice_on(chat_id)
    if not is_antiservice:
        return
    return await antiservicedb.insert_one({"chat_id": chat_id})

@app.on_message(
    filters.command(["antiservice", "cleanmode"]) & ~filters.private & ~BANNED_USERS
)
@adminsOnly("can_change_info")
async def anti_service(_, message):
    if len(message.command) != 2:
        return await message.reply_text("Usᴀɢᴇ: /antiservice [enable | disable]")
    status = message.text.split(None, 1)[1].strip()
    status = status.lower()
    chat_id = message.chat.id
    if status == "enable":
        await antiservice_on(chat_id)
        await message.reply_text(
            "**Eɴᴀʙʟᴇᴅ AɴᴛɪSᴇʀᴠɪᴄᴇ Sʏsᴛᴇᴍ**.\n I ᴡɪʟʟ Dᴇʟᴇᴛᴇ Sᴇʀᴠɪᴄᴇ Mᴇssᴀɢᴇs ғʀᴏᴍ Nᴏᴡ ᴏɴ."
        )
    elif status == "disable":
        await antiservice_off(chat_id)
        await message.reply_text(
            "**Dɪsᴀʙʟᴇᴅ AɴᴛɪSᴇʀᴠɪᴄᴇ Sʏsᴛᴇᴍ.**\n I ᴡᴏɴ'ᴛ Bᴇ Dᴇʟᴇᴛɪɴɢ Sᴇʀᴠɪᴄᴇ Mᴇssᴀɢᴇ ғʀᴏᴍ Nᴏᴡ ᴏɴ."
        )
    else:
        await message.reply_text("Unknown Suffix, Use /antiservice [enable|disable]")

@app.on_message(filters.service, group=11)
async def delete_service(_, message):
    chat_id = message.chat.id
    try:
        if await is_antiservice_on(chat_id):
            return await message.delete()
            sleep(300)
    except Exception:
        pass

__MODULE__ = "AɴᴛɪSᴇʀᴠɪᴄᴇ"
__HELP__ = """
Pʟᴜɢɪɴ ᴛᴏ ᴅᴇʟᴇᴛᴇ sᴇʀᴠɪᴄᴇ ᴍᴇssᴀɢᴇs ɪɴ ᴀ ᴄʜᴀᴛ!
/antiservice [ᴇɴᴀʙʟᴇ|ᴅɪsᴀʙʟᴇ]
"""


   LRUD.LEFT => LRUD.DOWN,
        LRUD.DOWN => LRUD.RIGHT,
        _ => LRUD.UP
    };

    public static LRUD RotateCW(this LRUD d) => d switch {
        LRUD.DOWN => LRUD.LEFT,
        LRUD.LEFT => LRUD.UP,
        LRUD.UP => LRUD.RIGHT,
        _ => LRUD.DOWN
    };

    public static LRUD Flip(this LRUD d) => d switch {
        LRUD.UP => LRUD.DOWN,
        LRUD.LEFT => LRUD.RIGHT,
        LRUD.DOWN => LRUD.UP,
        _ => LRUD.DOWN
    };

    public static float CCWRotation(this LRUD d) => d switch {
        LRUD.UP => 90,
        LRUD.LEFT => 180,
        LRUD.DOWN => 270,
        _ => 0
    };
    public static float CWRotation(this LRUD d) => d switch {
        LRUD.UP => 270,
        LRUD.LEFT => 180,
        LRUD.DOWN => 90,
        _ => 0
    };

    public static bool IsLR(this LRUD d) => d is LRUD.LEFT or LRUD.RIGHT;
    public static bool IsUD(this LRUD d) => d is LRUD.UP or LRUD.DOWN;
}
}


�点。**”**

****
将S级高水平白帽和精英白帽资源

充分调配到企业实战攻防演练中

这是2024年，
斗象科技

对“安全众测”模式延展的又一次全新实践

未来，斗象科技将继续以漏洞盒子服务平台为依托，通过
斗象自营战队、平台白帽全明星红队及混编战队
的灵活配置，帮助客户构建**高水平、高保障、可定向、可持续**的攻防演练**红队新模式**。

![](https://mmbiz.qpic.cn/sz_mmbiz_gif/hrWzJ3hmo1Z3BaadfL3ysmyJyCSf4AoHejgzxObbbAYDKm4FQ5d9qOTNbQfLgHvn2apSN26oZADOedzQtU7wNw/640?wx_fmt=gif&from=appmsg "")

![](https://mmbiz.qpic.cn/mmbiz_gif/qq5rfBadR3icF8RMnJbsqatMibR6OicVrUDaz0fyxNtBDpPlLfibJZILzHQcwaKkb4ia57xAShIJfQ54HjOG1oPXBew/640?wx_fmt=gif&wxfrom=5&wx_lazy=1&tp=webp "")

#  漏洞预警 | XStream栈溢出漏洞
浅安  浅安安全   2024-11-16 00:01

**0x00 漏洞编号**
- CVE-2024-47072

**0x01 危险等级**
- 高危

**0x02 漏洞概述**

XStream是一个用于在Java对象和XML之间相互转换的工具，它能够将Java对象序列化为XML或JSON格式，也可以将XML或JSON格式的数据反序列化为Java对象，从而简化了数据的存储、传输和恢复。

![](https://mmbiz.qpic.cn/sz_mmbiz_png/7stTqD182SWpsmBToJ1PmvpWYLUqE5SKR3Ce50wCJImsymoz7GSVlS2psLAvUzlIiaG7QS43dNib3ccr7RUyicfpQ/640?wx_fmt=png&from=appmsg "")

**0x03 漏洞详情**
###
###

**CVE-2024-47072**

**漏洞类型：**
栈溢出

**影响：**
服务中断

**简述：**
XStream 1.4.21之前版本中，当XStream配置为使用BinaryStreamDriver时，由于在反序列化某些特定输入时处理不当，攻击者可以通过构造特定的二进制数据流作为输入，导致在反序列化时进入无限递归，从而触发栈溢出，使应用程序崩溃并导致服务中断，造成拒绝服务


{
			return false;
		}

		// return true if the item's user has a C_Printing_Queue_Recipient

		final I_AD_User queueUser = Services.get(IUserDAO.class).getByIdInTrx(UserId.ofRepoId(queueItem.getAD_User_ID()), I_AD_User.class);

		return queueUser.getC_Printing_Queue_Recipient_ID() > 0;
	}

	/**
	 * Updates the given {@code item}, see the javadoc of this class for further details.
	 */
	@Override
	public void afterEnqueueAfterSave(final I_C_Printing_Queue queueItem, final I_AD_Archive IGNORED)
	{
		final IQueryBL queryBL = Services.get(IQueryBL.class);
		final List<I_C_Printing_Queue_Recipient> recipients = queryBL.createQueryBuilder(I_C_Printing_Queue_Recipient.class, queueItem)
				.addOnlyActiveRecordsFilter() // we must retrieve ALL; the caller shall decide
				.addEqualsFilter(I_C_Printing_Queue_Recipient.COLUMN_C_Printing_Queue_ID, queueItem.getC_Printing_Queue_ID())
				.create()
				.list();

		if (recipients.isEmpty())
		{
			resetToUserPrintingQueueRecipient(queueItem);
		}
		else
		{
			for (final I_C_Printing_Queue_Recipient queueRecipient : recipients)
			{
				final I_AD_User userToPrint = InterfaceWrapperHelper.loadOutOfTrx(queueRecipient.getAD_User_ToPrint_ID(), I_AD_User.class);
				final int newUserToPrintId = getEffectiveUserToPrint(userToPrint, new HashSet<>()).getAD_User_ID();

				queueRecipient.setAD_User_ToPrint_ID(newUserToPrintId);
				InterfaceWrapperHelper.save(queueRecipient);
			}
		}
	}

	private void resetToUserPrintingQueueRecipient(final I_C_Printing_Queue queueItem)
	{

		final I_AD_User itemUser = Services.get(IUserDAO.class).getByIdInTrx(UserId.ofRepoId(queueItem.getAD_User_ID()), I_AD_User.class);

		final int userToPrintId = getEffectiveUserToPrint(itemUser, new HashSet<>()).getAD_User_ID();

		final IPrintingQueueBL printingQueueBL = Services.get(IPrintingQueueBL.class);
		printingQueueBL.setPrintoutForOtherUsers(queueItem, ImmutableSet.of(userToPrintId));
	}

	private I_AD_User getEffectiveUserToPrint(final I_AD_User user, final Set<Integer> alreadSeenUserIDs)
	{
		if (user.getC_Printing_Queue_Recipient_ID() <= 0)
		{
			return user;
		}
		if (!alreadSeenUserIDs.add(user.getC_Printing_Queue_Recipient_ID()))
		{
			return user;
		}

		return getEffectiveUserToPrint(user.getC_Printing_Queue_Recipient(), alreadSeenUserIDs);
	}

}
package de.metas.printing.model.validator;

/*
 * #%L
 * de.metas.printing.base
 * %%
 * Copyright (C) 2015 metas GmbH
 * %%
 * 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 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Genera


	_ = first
	{
		const prefix string = ",\"metric\":"
		out.RawString(prefix[1:])
		(in.Metric).MarshalEasyJSON(out)
	}
	out.RawByte('}')
}

// MarshalEasyJSON supports easyjson.Marshaler interface
func (v MetricInfo) MarshalEasyJSON(w *jwriter.Writer) {
	easyjson888c126aEncodeGithubComVKCOMStatshouseInternalApi7(w, v)
}

// UnmarshalEasyJSON supports easyjson.Unmarshaler interface
func (v *MetricInfo) UnmarshalEasyJSON(l *jlexer.Lexer) {
	easyjson888c126aDecodeGithubComVKCOMStatshouseInternalApi7(l, v)
}
func easyjson888c126aDecodeGithubComVKCOMStatshouseInternalApi8(in *jlexer.Lexer, out *GetTableResp) {
	isTopLevel := in.IsStart()
	if in.IsNull() {
		if isTopLevel {
			in.Consumed()
		}
		in.Skip()
		return
	}
	in.Delim('{')
	for !in.IsDelim('}') {
		key := in.UnsafeFieldName(false)
		in.WantColon()
		if in.IsNull() {
			in.Skip()
			in.WantComma()
			continue
		}
		switch key {
		case "rows":
			if in.IsNull() {
				in.Skip()
				out.Rows = nil
			} else {
				in.Delim('[')
				if out.Rows == nil {
					if !in.IsDelim(']') {
						out.Rows = make([]queryTableRow, 0, 0)
					} else {
						out.Rows = []queryTableRow{}
					}
				} else {
					out.Rows = (out.Rows)[:0]
				}
				for !in.IsDelim(']') {
					var v29 queryTableRow
					(v29).UnmarshalEasyJSON(in)
					out.Rows = append(out.Rows, v29)
					in.WantComma()
				}
				in.Delim(']')
			}
		case "what":
			if in.IsNull() {
				in.Skip()
				out.What = nil
			} else {
				in.Delim('[')
				if out.What == nil {
					if !in.IsDelim(']') {
						out.What = make([]promql.SelectorWhat, 0, 2)
					} else {
						out.What = []promql.SelectorWhat{}
					}
				} else {
					out.What = (out.What)[:0]
				}
				for !in.IsDelim(']') {
					var v30 promql.SelectorWhat
					(v30).UnmarshalEasyJSON(in)
					out.What = append(out.What, v30)
					in.WantComma()
				}
				in.Delim(']')
			}
		case "from_row":
			out.FromRow = string(in.String())
		case "to_row":
			out.ToRow = string(in.String())
		case "more":
			out.More = bool(in.Bool())
		case "__debug_queries":
			if in.IsNull() {
				in.Skip()
				out.DebugQueries = nil
			} else {
				in.Delim('[')
				if out.DebugQueries == nil {
					if !in.IsDelim(']') {
						out.DebugQueries = make([]string, 0, 4)
					} else {
						out.DebugQueries = []string{}
					}
				} else {
					out.DebugQueries = (out.DebugQueries)[:0]
				}
				for !in.IsDelim(']') {
					var v31 string
					v31 = string(in.String())
					out.DebugQueries = append(out.DebugQueries, v31)
					i


    super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity);
            }
            else if (flag3)
            {
                this.setBlockBounds(0.5F, 0.0F, 0.4375F, 1.0F, 1.0F, 0.5625F);
                super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity);
            }
        }
        else
        {
            this.setBlockBounds(0.0F, 0.0F, 0.4375F, 1.0F, 1.0F, 0.5625F);
            super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity);
        }

        if ((!flag || !flag1) && (flag2 || flag3 || flag || flag1))
        {
            if (flag)
            {
                this.setBlockBounds(0.4375F, 0.0F, 0.0F, 0.5625F, 1.0F, 0.5F);
                super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity);
            }
            else if (flag1)
            {
                this.setBlockBounds(0.4375F, 0.0F, 0.5F, 0.5625F, 1.0F, 1.0F);
                super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity);
            }
        }
        else
        {
            this.setBlockBounds(0.4375F, 0.0F, 0.0F, 0.5625F, 1.0F, 1.0F);
            super.addCollisionBoxesToList(worldIn, pos, state, mask, list, collidingEntity);
        }
    }

    /**
     * Sets the block's bounds for rendering it as an item
     */
    public void setBlockBoundsForItemRender()
    {
        this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
    }

    public void setBlockBoundsBasedOnState(IBlockAccess worldIn, BlockPos pos)
    {
        float f = 0.4375F;
        float f1 = 0.5625F;
        float f2 = 0.4375F;
        float f3 = 0.5625F;
        boolean flag = this.canPaneConnectToBlock(worldIn.getBlockState(pos.north()).getBlock());
        boolean flag1 = this.canPaneConnectToBlock(worldIn.getBlockState(pos.south()).getBlock());
        boolean flag2 = this.canPaneConnectToBlock(worldIn.getBlockState(pos.west()).getBlock());
        boolean flag3 = this.canPaneConnectToBlock(worldIn.getBlockState(pos.east()).getBlock());

        if ((!flag2 || !flag3) && (flag2 || flag3 || flag || flag1))
        {
            if (flag2)
            {
                f = 0.0F;
            }
            else if (flag3)
            {
                f1 = 1.0F;
            }
        }
        else
        {
            f = 0.0F;
            f1 = 1.0F;
        }

        if ((!flag || !flag1) && (flag2 || flag3 || flag || flag1))
        {
            if (flag)
            {
                f2 = 0.0F;
            }
            else if (flag1)
            {
                f3 = 1.0F;
            }
        }
        else
        {
            f2 = 0.0F;
            f3 = 1.0F;
        }

        this.setBlockBounds(f, 0.0F, f2, f1, 1.0F, f3);
    }

    public final boolean canPaneConnectToBlock(Block blockIn)
    {
        return blockIn.isFullBlock() || blockIn == this || blockIn == Blocks.glass || blockIn == Blocks.stained_glass || blockIn == Blocks.stained_glass_pane || blockIn instanceof BlockPane;
    }

    protected boolean canSilkHarvest()
    {
        return true;
    }

    public EnumWorldBlockLayer getBlockLayer()
    {
        return EnumWorldBlockLayer.CUTOUT_MIPPED


ipeManager.deserialize(id, RecipeBuilderUtil.generateMelting(
						MC.id("redstone_block"),
						CABF.id("redstone"),
						FluidConstants.BLOCK,
						null, 0, 250, 135
				))
		);

		 */
	}

	@Override
	public void modifyRecipes(RecipeLoadingEvents.ModifyRecipesCallback.RecipeHandler handler) {
		TechThread.THREADS.forEach(thread -> thread.modifyRecipes(handler));
	}

	@Override
	public void removeRecipes(RecipeLoadingEvents.RemoveRecipesCallback.RecipeHandler handler) {
		TechThread.THREADS.forEach(thread -> thread.removeRecipes(handler));

		OreProcessingTweaks.register(handler);
		MechAndSmithCraft.register(handler);

		handler.remove(TC.id("smeltery", "casting", "metal", "gold", "coin_sand_cast"));
		handler.remove(TC.id("smeltery", "casting", "metal", "gold", "coin_gold_cast"));
		handler.remove(TC.id("smeltery", "casting", "metal", "silver", "coin_sand_cast"));
		handler.remove(TC.id("smeltery", "casting", "metal", "silver", "coin_gold_cast"));

		handler.remove(TC.id("smeltery", "alloys", "molten_enderium"));
		handler.remove(TC.id("smeltery", "alloys", "molten_brass"));
		handler.remove(TC.id("smeltery", "alloys", "molten_invar"));

		handler.removeIf(r ->
				r.getId().getNamespace().equals(TC.modid())
						&& r.getId().getPath().startsWith("compat/create")
		);

		// Remove wrenches except Create's and AE2's
		handler.removeIf(recipe ->
				!CREATE.checkContains(handler, recipe) && !AE2.checkContains(handler, recipe)
						&& Registries.ITEM.getId(recipe.getResult(handler.getRegistryManager()).getItem()).getPath().contains("wrench")
		);
		handler.removeIf(INDREV.predicateOutput(handler, "controller"));

		// Ad Astra!
		Arrays.stream(AD_ASTRA_MATERIALS).forEach(material -> Arrays.stream(AD_ASTRA_DECOR_TYPES).forEach(
				type -> handler.removeIf(AD_ASTRA.predicateOutput(handler, material + "_" + type))
		));
		handler.remove(AD_ASTRA.id("recipes/nasa_workbench"));

		// AE2
		handler.removeIf(AllRecipeTypes.MILLING.getType(), AE2.predicateOutput(handler, "certus_quartz_dust").and(
				AE2.predicateIngredient(handler, "certus_quartz_crystal").negate()
		));

		// Indrev
		handler.removeIf(recipe ->
				INDREV.checkContains(handler, recipe)
						&& Registries.ITEM.getId(recipe.getResult(handler.getRegistryManager()).getItem()).getPath()
						.matches(".*_(pickaxe|axe|shovel|hoe|sword)$")
		);
		handler.removeIf(INDREV.predicateIngredient(handler, "fan"));
		handler.removeIf(recipe ->
				recipe.getResult(handler.getRegistryManager()).getItem() instanceof BlockItem blockItem
						&& blockItem.getBlock() instanceof FluidPipeBlock
		);
		handler.remove(INDREV.id("shaped/coal_generator_mk1"));
		handler.remove(INDREV.id("shaped/solar_generator_mk1"));
		handler.remove(INDREV.id("shaped/solar_generator_mk3"));
	}

	private static Identifier recipeId(String type, String name) {
		return Cabricality.id(type, name);
	}
}
package dm.earth.cabricality.content.trading.item;

import dm.earth.cabricality.


FP16_S2                             \
  "st1    {v16.8h}, [%[ptr_out0]], #16              \n" \
  "st1    {v17.8h}, [%[ptr_out1]], #16              \n" \
  "cmp    %w[cnt], #1                               \n" \
  "blt    1f                                        \n"

#define LEFT_RESULT_FP16_S2_RELU                        \
  "fmax   v16.8h,  v16.8h, %[vzero].8h              \n" \
  "fmax   v17.8h,  v17.8h, %[vzero].8h              \n" \
  "st1    {v16.8h}, [%[ptr_out0]], #16              \n" \
  "st1    {v17.8h}, [%[ptr_out1]], #16              \n" \
  "cmp    %w[cnt], #1                               \n" \
  "blt    1f                                        \n"

#define LEFT_RESULT_FP16_S2_RELU6                       \
  "ldr    q21, [%[bias_val], #0x10]                 \n" \
  "fmax   v16.8h,  v16.8h, %[vzero].8h              \n" \
  "fmax   v17.8h,  v17.8h, %[vzero].8h              \n" \
  "fmin   v16.8h,  v16.8h, v21.8h                   \n" \
  "fmin   v17.8h,  v17.8h, v21.8h                   \n" \
  "st1    {v16.8h}, [%[ptr_out0]], #16              \n" \
  "st1    {v17.8h}, [%[ptr_out1]], #16              \n" \
  "cmp    %w[cnt], #1                               \n" \
  "blt    1f                                        \n"

#define LEFT_RESULT_FP16_S2_LEAKY_RELU                  \
  "ldr    q21, [%[bias_val], #0x10]                 \n" \
  "fcmge  v12.8h,  v16.8h,  %[vzero].8h             \n" \
  "fmul   v13.8h,  v16.8h,  v21.8h                  \n" \
  "bif    v16.16b, v13.16b, v12.16b                 \n" \
  "fcmge  v14.8h,  v17.8h,  %[vzero].8h             \n" \
  "fmul   v15.8h,  v17.8h,  v21.8h                  \n" \
  "bif    v17.16b, v15.16b, v14.16b                 \n" \
  "st1    {v16.8h}, [%[ptr_out0]], #16              \n" \
  "st1    {v17.8h}, [%[ptr_out1]], #16              \n" \
  "cmp    %w[cnt], #1                               \n" \
  "blt    1f                                        \n"

#define MID_COMPUTE_FP16_S2                             \
  "2:                                               \n" \
  "ld1    {v15.8h}, [%[din_ptr0]]                   \n" \
  "ld


d the updated office packge is {pink}off the roooof{end} man! hahaha

aaanywho, youre probably itching for some {red}~real~{end} work huh?? we r tryin to tweak some details on the nav sys of the {brown}"robots"{end} lol, but we are having some tech troubles.The main test room is still 2 unstable for u to handle right now, but we can send u the {green}beta{end} version and see if you can handle. btw this one can only handle {red}4 lines of code{end} soooooo yeahh can u handle this job?? if you could that would be {cyan}legen {gray}~wait for it~{cyan} DARY{end} HAHA love that show ;P

don't forget to carry on {purple};))){end}.

jeNny Leubwoot
chief astronaut at marvellous soft.s {blue}KICKASS{end} dojo
]],
    author = "Janine Leubwitz (leubwitz@rtd.marv.com)",
    puzzle_id = 'jen1'
}


es_ctr32_encrypt_blocks:

	cmp	x2, #8                      // use plain AES for
	blo	.Lctr_enc_short             // small sizes

	stp	x29, x30, [sp, #-80]!
	stp	d8, d9, [sp, #16]
	stp	d10, d11, [sp, #32]
	stp	d12, d13, [sp, #48]
	stp	d14, d15, [sp, #64]

	ldr	w15, [x3, #240]             // get # of rounds
	mov	x14, sp

        // allocate the key schedule on the stack
	add	x17, sp, #96
	sub	x17, x17, x15, lsl #7       // 128 bytes per inner round key, less 96 bytes

        // populate the key schedule
	mov	x9, x3                      // pass key
	mov	x10, x15                    // pass # of rounds
	mov	sp, x17                     // sp is sp
	bl	_bsaes_key_convert
	eor	v7.16b, v7.16b, v15.16b     // fix up last round key
	str	q7, [x17]                   // save last round key

	ldr	q0, [x4]                    // load counter
	add	x13, x11, #.LREVM0SR-.LM0_bigendian
	ldr	q4, [sp]                    // load round0 key

	movi	v8.4s, #1                   // compose 1<<96
	movi	v9.16b, #0
	rev32	v15.16b, v0.16b
	rev32	v0.16b, v0.16b
	ext	v11.16b, v9.16b, v8.16b, #4
	rev32	v4.16b, v4.16b
	add	v12.4s, v11.4s, v11.4s      // compose 2<<96
	str	q4, [sp]                    // save adjusted round0 key
	add	v13.4s, v11.4s, v12.4s      // compose 3<<96
	add	v14.4s, v12.4s, v12.4s      // compose 4<<96
	b	.Lctr_enc_loop

.align	4
.Lctr_enc_loop:
        // Intermix prologue from _bsaes_encrypt8 to use the opportunity
        // to flip byte order in 32-bit counter

	add	v1.4s, v15.4s, v11.4s       // +1
	add	x9, sp, #0x10               // pass next round key
	add	v2.4s, v15.4s, v12.4s       // +2
	ldr	q9, [x13]                   // .LREVM0SR
	ldr	q8, [sp]                    // load round0 key
	add	v3.4s, v15.4s, v13.4s       // +3
	mov	x10, x15                    // pass rounds
	sub	x11, x13, #.LREVM0SR-.LSR   // pass constants
	add	v6.4s, v2.4s, v14.4s
	add	v4.4s, v15.4s, v14.4s       // +4
	add	v7.4s, v3.4s, v14.4s
	add	v15.4s, v4.4s, v14.4s       // next counter
	add	v5.4s, v1.4s, v14.4s

	bl	_bsaes_encrypt8


dodA== IEhUQw== dXNh dG1w IHJ1ZGU= IExlZ2VuZGFyeQ== IGFyaXNlcw== QmFk IENsYWlt cGVn IHJlYWxpdGllcw== VGhpbms= IMKw IHJvZGU= IHN0cml2ZQ== IGFuZWNk IHNob3J0cw== IGh5cG90aGVz IGNvb3JkaW5hdGVk IEdhbmRoaQ== IEZQUw== UkVE IHN1c2NlcHRpYmxl IHNocmluaw== IENoYXJ0 SGVscA== IGlvbg== ZGVlcA== cmliZXM= IEthaQ== IEN1c3RvbWVy U3VtbWFyeQ== IGNvdWdo d2lmZQ== IGxlbmQ= IHBvc2l0aW9uaW5n IGxvdHRlcnk= IENhbnlvbg== IGZhZGU= IGJyb256ZQ== IEtlbm55 IGJvYXN0cw== IEVuaGFuY2Vk cmVjb3Jk IGVtZXJnZW5jZQ== IGFraW4= IEJlcnQ= aXRvdXM= 4paR IHN0aXA= IGV4Y2hhbmdlZA== b21vcmU= YWxzaA== IHJlc2Vydm9pcg== IHN0YW5kcG9pbnQ= V00= IGluaXRpYXRl IGRlY2F5 IGJyZXdlcnk= IHRlcnJpYmx5 IG1vcnRhbA== bGV2YXJk IHJldmlz Tkk= ZWxv IGNvbmZlc3M= IE1TTkJD IHN1Ym1pc3Npb25z Q29udHJvbGxlcg== IDIwMg== IFJ1dGg= fSk7 IEF6dXJl IC4i MjA2 IE1hcmtldGluZw== IGxhdW5k aWVuY2llcw== IHJlbm93bmVk IFRyb3U= IE5HTw== YmxlbXM= IHRlcnJpZmllZA== IHdhcm5z IHBlcnQ= IHVuc3VyZQ== NDgw YWxleg== dWx0eg== IE91dHNpZGU= IHN0eWw= IFVuZGVyZ3JvdW5k IHBhbmM= IGRpY3Rpb25hcnk= IGZvZQ== cmltaW5hbA== IE5vcndlZ2lhbg== IGphaWxlZA== IG1hdGVybmFs w6ll IEx1Y3k= Y29w Q2hv IHVuc2lnbmVk IFplbGRh IEluc2lkZXI= IENvbnRpbnVlZA== IDEzMw== IE5hcnV0bw== IE1ham9yaXR5 MTY5 IFdv 44KT IHBhc3Rvcg== IGluZm9ybWFs 0L0= YW50aHJvcA== am9pbg== 44GX aXRhdGlvbmFs TlA= IFdyaXRpbmc= Zm4= IEJldmVy MTk1 IHllbGxpbmc= IGRyYXN0aWNhbGx5 IGVqZWN0 IG5ldXQ= IHRocml2ZQ== IEZyZXF1 b3V4 IHBvc3Nlc3Nlcw== IFNlbmF0b3Jz IERFUw== IFNoYWtlc3BlYXJl IEZyYW5jbw== IExC dWNoaQ== IGluY2Fybg== IGZvdW5kZXJz RnVuY3Rpb24= IGJyaWdodG5lc3M= IEJU IHdoYWxl IFRoZWF0ZXI


,false);
			}
		}
	}
}// @use "sass:math";
@import  '../tools/functions.scss';
// 间距基础倍数
$uni-space-root: 2 !default;
// 边框半径默认值
$uni-radius-root:5px !default;
$uni-radius: () !default;
// 边框半径断点
$uni-radius: map-deep-merge(
  (
    0: 0,
		// TODO 当前版本暂时不支持 sm 属性
    // 'sm': math.div($uni-radius-root, 2),
    null: $uni-radius-root,
    'lg': $uni-radius-root * 2,
    'xl': $uni-radius-root * 6,
    'pill': 9999px,
    'circle': 50%
  ),
  $uni-radius
);
// 字体家族
$body-font-family: 'Roboto', sans-serif !default;
// 文本
$heading-font-family: $body-font-family !default;
$uni-headings: () !default;
$letterSpacing: -0.01562em;
$uni-headings: map-deep-merge(
  (
    'h1': (
      size: 32px,
			weight: 300,
			line-height: 50px,
			// letter-spacing:-0.01562em
    ),
    'h2': (
      size: 28px,
      weight: 300,
      line-height: 40px,
      // letter-spacing: -0.00833em
    ),
    'h3': (
      size: 24px,
      weight: 400,
      line-height: 32px,
      // letter-spacing: normal
    ),
    'h4': (
      size: 20px,
      weight: 400,
      line-height: 30px,
      // letter-spacing: 0.00735em
    ),
    'h5': (
      size: 16px,
      weight: 400,
      line-height: 24px,
      // letter-spacing: normal
    ),
    'h6': (
      size: 14px,
      weight: 500,
      line-height: 18px,
      // letter-spacing: 0.0125em
    ),
    'subtitle': (
      size: 12px,
      weight: 400,
      line-height: 20px,
      // letter-spacing: 0.00937em
    ),
    'body': (
      font-size: 14px,
			font-weight: 400,
			line-height: 22px,
			// letter-spacing: 0.03125em
    ),
    'caption': (
      'size': 12px,
      'weight': 400,
      'line-height': 20px,
      // 'letter-spacing': 0.03333em,
      // 'text-transform': false
    )
  ),
  $uni-headings
);

// 主色
$uni-primary: #2979ff !default;
$uni-primary-disable:lighten($uni-primary,20%) !default;
$uni-primary-light: lighten($uni-primary,25%) !default;

// 辅助色
// 除了主色外的场景色，需要在不同的场景中使用（例如危险色表示危险的操作）。
$uni-success: #18bc37 !default;
$uni-success-disable:lighten($uni-success,20%) !default;
$uni-success-light: lighten($uni-success,25%) !default;

$uni-warning: #f3a73f !default;
$uni-warning-disable:lighten($uni-warning,20%) !default;
$uni-warning-light: lighten($uni-warning,25%) !default;

$uni-error: #e43d33 !default;
$uni-error-disable:lighten($uni-error,20%) !default;
$uni-error-light: lighten($uni-error,25%) !default;

$uni-info: #8f9


 equalTo(awsService))
        assertThat(arn.region, equalTo(region))
        assertThat(arn.account, equalTo(account))
        assertThat(arn.resourceId(KMSKeyId::of), equalTo(resourceId))
    }

    @Test
    fun `can get parts back from ARN - resource path`() {
        val arn = ARN.of(awsService, region, account, resourcePath, partition)

        assertThat(arn.toString(), equalTo("arn:partition:kms:ldn-north-1:001234567890:key/foobar"))
        assertThat(arn.partition, equalTo(partition))
        assertThat(arn.awsService, equalTo(awsService))
        assertThat(arn.region, equalTo(region))
        assertThat(arn.account, equalTo(account))
        assertThat(arn.resourceType, equalTo(resourceType))
        assertThat(arn.resourceId(KMSKeyId::of), equalTo(resourceId))
    }

    @Test
    fun `can get parts back from ARN - resource path with longer path`() {
        val arn = ARN.parse("arn:partition:kms:ldn-north-1:001234567890:key/name/${UUID(0, 0)}")

        assertThat(arn.toString(), equalTo("arn:partition:kms:ldn-north-1:001234567890:key/name/${UUID(0, 0)}"))
        assertThat(arn.partition, equalTo(partition))
        assertThat(arn.awsService, equalTo(awsService))
        assertThat(arn.region, equalTo(region))
        assertThat(arn.account, equalTo(account))
        assertThat(arn.resourceType, equalTo(resourceType))
        assertThat(arn.resourceId(KMSKeyId::of).value, equalTo("name/00000000-0000-0000-0000-000000000000"))
    }
}
package org.http4k.connect.amazon.cloudwatch

import com.squareup.moshi.JsonAdapter
import org.http4k.connect.amazon.cloudwatch.model.AlarmName
import org.http4k.connect.amazon.cloudwatch.model.ExtendedStatistic
import org.http4k.connect.amazon.cloudwatch.model.PercentileExtendedStatistic
import org.http4k.connect.amazon.cloudwatch.model.MetricName
import org.http4k.connect.amazon.cloudwatch.model.Namespace
import org.http4k.connect.amazon.cloudwatch.model.NextToken
import org.http4k.format.AwsMoshiBuilder
import org.http4k.format.ConfigurableMoshi
import org.http4k.format.value
import se.ansman.kotshi.KotshiJsonAdapterFactory

object CloudWatchMoshi : ConfigurableMoshi(
    AwsMoshiBuilder(CloudWatchJsonAdapterFactory)
        .value(AlarmName)
        .value(ExtendedStatistic)
        .value(MetricName)
        .value(PercentileExtendedStatistic)
        .value(Namespace)
        .value(NextToken)
        .done()
)

@KotshiJsonAdapterFactory
object CloudWatchJsonAdapterFactory : JsonAdapter.Factory by KotshiCloudWatchJsonAdapterFactory
package org.http4k.connect.amazon.cloudwatch.action

import org.http4k.connect.Http4kConnectAction
import org.http4k.connect.amazon.cloudwatch.CloudWatchAction
import org.http4k.connect.amazon.cloudwatch.model.AlarmName
import org.http4k.connect.amazon.cloudwatch.model.ComparisonOperator
import org.http4k.connect.amazon.cloudwatch.model.Dimension
import org.http4k.connect.amazon.cloudwatch.model.EvaluateLowSampleCountPercentile
import org.http4k.connect.amazon.cloudwatch.model.ExtendedStatistic
import org.http4k.connect.amazon.cloudwatch.model.MetricDataQuery
import org.http4k.connect.amazon.cloudwatch.model.MetricName
impor


eSize & 0xff);

				if ((seek_Status = encoder.Private.Seek_Callback(this, encoder.Protected.StreamInfo_Offset + min_FrameSize_Offset, encoder.Private.Client_Data)) != Flac__StreamEncoderSeekStatus.Ok)
				{
					if (seek_Status == Flac__StreamEncoderSeekStatus.Error)
						encoder.Protected.State = Flac__StreamEncoderState.Client_Error;

					return;
				}

				if (encoder.Private.Write_Callback(this, b, 6, 0, 0, encoder.Private.Client_Data) != Flac__StreamEncoderWriteStatus.Ok)
				{
					encoder.Protected.State = Flac__StreamEncoderState.Client_Error;
					return;
				}
			}

			// Write seektable
			if ((encoder.Private.Seek_Table != null) && (encoder.Private.Seek_Table.Num_Points > 0) && (encoder.Protected.Seekable_Offset > 0))
			{
				// Convert unused seekpoints to placeholders
				for (uint32_t i = 0; i < encoder.Private.Seek_Table.Num_Points; i++)
				{
					if (encoder.Private.Seek_Table.Points[i].Sample_Number > samples)
						encoder.Private.Seek_Table.Points[i].Sample_Number = Constants.Flac__Stream_Metadata_SeekPoint_Placeholder;
				}

				Format.Flac__Format_SeekTable_Sort(encoder.Private.Seek_Table);

				Debug.Assert(Format.Flac__Format_SeekTable_Is_Legal(encoder.Private.Seek_Table));

				if ((seek_Status = encoder.Private.Seek_Callback(this, encoder.Protected.Seekable_Offset + Constants.Flac__Stream_Metadata_Header_Length, encoder.Private.Client_Data)) != Flac__StreamEncoderSeekStatus.Ok)
				{
					if (seek_Status == Flac__StreamEncoderSeekStatus.Error)
						encoder.Protected.State = Flac__StreamEncoderState.Client_Error;

					return;
				}

				for (uint32_t i = 0; i < encoder.Private.Seek_Table.Num_Points; i++)
				{
					Flac__uint64 xx = encoder.Private.Seek_Table.Points[i].Sample_Number;
					b[7] = (Flac__byte)xx; xx >>= 8;
					b[6] = (Flac__byte)xx; xx >>= 8;
					b[5] = (Flac__byte)xx; xx >>= 8;
					b[4] = (Flac__byte)xx; xx >>= 8;
					b[3] = (Flac__byte)xx; xx >>= 8;
					b[2] = (Flac__byte)xx; xx >>= 8;
					b[1] = (Flac__byte)xx; xx >>= 8;
					b[0] = (Flac__byte)xx;

					xx = encoder.Private.Seek_Table.Points[i].Stream_Offset;
					b[15] = (Flac__byte)xx; xx >>= 8;
					b[14] = (Flac__byte)xx; xx >>= 8;
					b[13] = (Flac__byte)xx; xx >>= 8;
					b[12] = (Flac__byte)xx; xx >>= 8;
					b[11] = (Flac__byte)xx; xx >>= 8;
					b[10] = (Flac__byte)xx; xx >>= 8;
					b[9] = (Flac__byte)xx; xx >>= 8;
					b[8] = (Flac__byte)xx;

					uint32_t x = encoder.Private.Seek_Table.Points[i].Frame_Samples;
					b[17] = (Flac__byte)x; x >>= 8;
					b[16] = (Flac__byte)x;

					if (encoder.Private.Write_Callback(this, b, 18, 0, 0, encoder.Private.Client_Data) != Flac__StreamEncoderWriteStatus.Ok)
					{
						encoder.Protected.State = Flac__StreamEncoderState.Client_Error;
						return;
					}
				}
			}
		}

		/********************************************************************/
		/// <summary>
		///
		/// </summary>
		/********************************************************************/
		private Fl


from decimal import Decimal
from typing import Self

import funcy

# ------------------------ decimal ------------------------

type Amount = Decimal | int

class Money(Decimal):
    CURRENCY = "€"

    def __new__(cls, number):
        return super().__new__(cls, Decimal(number).quantize(Decimal("0.01")))

    def __repr__(self):
        return f"{self.__class__.__name__}('{super().__str__()}')"

    def __str__(self):
        return super().__str__() + self.CURRENCY

    def __format__(self, fmt):  # type:ignore
        return super().__format__(fmt) + self.CURRENCY

    def __add__(self, something):
        return self.__class__(super().__add__(something))

    def __sub__(self, something):
        return self.__class__(super().__sub__(something))

    def __neg__(self):
        return self.__class__(super().__neg__())

    def __truediv__(self, something):
        return self.__class__(super().__truediv__(something))

    def __mul__(self, something):
        return self.__class__(super().__mul__(something))

    def divide_with_no_rest(self, by: int) -> list[Self]:
        """Split a into parts as equal as possible, without error, rounded to cent"""
        quantized_result = self / by
        remainder = self - quantized_result * by
        return funcy.lmap(
            self.__class__,
            funcy.concat(
                [quantized_result + remainder],
                funcy.repeat(quantized_result, by - 1),
            ),
        )


    final _ret = _lib._objc_msgSend_899(
        _id, _lib._sel_initWithStream_1, stream?._id ?? ffi.nullptr);
    return NSXMLParser._(_ret, _lib, retain: true, release: true);
  }

  NSObject? get delegate {
    final _ret = _lib._objc_msgSend_2(_id, _lib._sel_delegate1);
    return _ret.address == 0
        ? null
        : NSObject._(_ret, _lib, retain: true, release: true);
  }

  set delegate(NSObject? value) {
    _lib._objc_msgSend_368(
        _id, _lib._sel_setDelegate_1, value?._id ?? ffi.nullptr);
  }

  bool get shouldProcessNamespaces {
    return _lib._objc_msgSend_12(_id, _lib._sel_shouldProcessNamespaces1);
  }

  set shouldProcessNamespaces(bool value) {
    _lib._objc_msgSend_460(_id, _lib._sel_setShouldProcessNamespaces_1, value);
  }

  bool get shouldReportNamespacePrefixes {
    return _lib._objc_msgSend_12(_id, _lib._sel_shouldReportNamespacePrefixes1);
  }

  set shouldReportNamespacePrefixes(bool value) {
    _lib._objc_msgSend_460(
        _id, _lib._sel_setShouldReportNamespacePrefixes_1, value);
  }

  int get externalEntityResolvingPolicy {
    return _lib._objc_msgSend_900(
        _id, _lib._sel_externalEntityResolvingPolicy1);
  }

  set externalEntityResolvingPolicy(int value) {
    _lib._objc_msgSend_901(
        _id, _lib._sel_setExternalEntityResolvingPolicy_1, value);
  }

  NSSet? get allowedExternalEntityURLs {
    final _ret =
        _lib._objc_msgSend_280(_id, _lib._sel_allowedExternalEntityURLs1);
    return _ret.address == 0
        ? null
        : NSSet._(_ret, _lib, retain: true, release: true);
  }

  set allowedExternalEntityURLs(NSSet? value) {
    _lib._objc_msgSend_902(_id, _lib._sel_setAllowedExternalEntityURLs_1,
        value?._id ?? ffi.nullptr);
  }

  bool parse() {
    return _lib._objc_msgSend_12(_id, _lib._sel_parse1);
  }

  void abortParsing() {
    return _lib._objc_msgSend_1(_id, _lib._sel_abortParsing1);
  }

  NSError? get parserError {
    final _ret = _lib._objc_msgSend_283(_id, _lib._sel_parserError1);
    return _ret.address == 0
        ? null
        : NSError._(_ret, _lib, retain: true, release: true);
  }

  bool get shouldResolveExternalEntities {
    return _lib._objc_msgSend_12(_id, _lib._sel_shouldResolveExternalEntities1);
  }

  set shouldResolveExternalEntities(bool value) {
    _lib._objc_msgSend_460(
        _id, _lib._sel_setShouldResolveExternalEntities_1, value);
  }

  NSString? get publicID {
    final _ret = _lib._objc_msgSend_20(_id, _lib._sel_publicID1);
    return _ret.address == 0
        ? null
        : NSString._(_ret, _lib, retain: true, release: true);
  }

  NSString? get systemID {
    final _ret = _lib._objc_msgSend_20(_id, _lib._sel_systemID1);
    return _ret.address == 0
        ? null
        : NSString._(_ret, _lib, retain: true, release: true);
  }

  int get lineNumber {
    return _lib._objc_msgSend_78(_id, _lib._sel_lineNumber1);
  }

  int get column