if (AvailLoader.debugLoadedStatements)
					{
						println(
							module.toString()
								+ ":" + function.code()
								.codeStartingLineNumber
								+ " Running precompiled -- " + function)
					}
					availBuilder.runtime.runOutermostFunction(
						fiber, function, emptyList(), true)
				}
				availBuilder.shouldStopBuild ->
					module.removeFrom(availLoader) {
						postLoad(moduleName, 0L)
						completionAction()
					}
				else ->
				{
					// All the functions in the body have run.  Now run any
					// post-load functions that were accumulated.
					availLoader.phase = Phase.EXECUTING_FOR_LOAD
					val functions = module.takePostLoadFunctions()
					availLoader.runFunctions(
						functions = functions.iterator(),
						purpose = "Post-load function (for fast-loader)",
						afterFailingOne = { failedFunction, e, _ ->
							// An error has happened in the fiber running a
							// post-load function.  Report the problem and abort
							// the load.
							val line =
								failedFunction.code().codeStartingLineNumber
							fail(RuntimeException(
								"Post-load function at $module:$line failed.",
								e))
							// Specifically DO NOT run more functions.
						},
						afterRunningAll = {
							module.serializedObjects(
								deserializer.serializedObjects())
							availBuilder.runtime.addModule(module)
							val loadedModule = LoadedModule(
								moduleName,
								sourceDigest,
								module,
								version,
								compilation)
							availBuilder.putLoadedModule(
								moduleName, loadedModule)
							postLoad(moduleName, 0L)
							completionAction()
						})
				}
			}
		}
	}

	/**
	 * Compile the [module][ModuleDescriptor] with the specified [moduleName]
	 * into the current [AvailRuntime], and then store its compilation into the
	 * [repository][Repository].
	 *
	 * Note that the predecessors of this module must have already been loaded.
	 *
	 * @param moduleName
	 *   The [resolved name][ResolvedModuleName] of the module that should
	 *   be loaded.
	 * @param compilationKey
	 *   The circumstances of compilation of this module.  Currently this is
	 *   just the compilation times (`long`s) of the module's currently loaded
	 *   predecessors, listed in the same order as the module's
	 *   [imports][ModuleHeader.importedModules].
	 * @param completionAction
	 *   What to do after loading the module successfully or unsuccessfully.
	 */
	private fun compileModule(
		moduleName: ResolvedModuleName,
		compilationKey: ModuleCompilationKey,
		completionAction: ()->Unit)
	{
		val repository = moduleName.repository
		val archive = repository.getArchive(moduleName.rootRelativeName)
		archive.digestForFile(
			moduleName,
			false,
			{ digest ->
				val versionKey = ModuleVersionKey(moduleName, digest)
				var lastPosition = 0L
				val ranOnce = AtomicBoolean(false)
				AvailCompiler.create(
					moduleName,
					availBuilder.runtime,
					availBuilder.textInterface,
					availBuilder.pollForAbort,
					reporter = {
							moduleName2, moduleSize, position, line, phrase ->
						assert(moduleName == moduleName2)
						// Don't reach the full module size yet.  A separate
						// update at 100% will be sent after post-loading
						// actions are complete.
						localTracker(
							moduleName,
							moduleSize,
							min(position, moduleSize - 1),
							line,
							phrase)
						globalTracker(
							bytesCompiled.addAndGet(position - lastPosition),
							globalCodeSize)
						lastPosition = position
					},
					afterFail = {
						postLoad(moduleName, lastPosition)
						completionAction()
					},
					problemHandler,
					succeed = { compiler: AvailCompiler ->
						compiler.parseModule(
							onSuccess = {
								val old = ranOnce.getAndSet(true)
								assert(!old) {
									"Completed module compilation twice!"
								}
								completedCompilation(
									compile


)
        val splineF = (x - splineI).clamp(0f, 1f)
        return splinePieces[splineI].evaluate(splineF, result)
    }

    private fun checkSplinePieces() {
        if (splinePieces.size != ctrlPoints.size - 1) {
            update()
        }
    }

    fun update() {
        splinePieces.clear()
        for (i in 1 until ctrlPoints.size) {
            val ctrl0 = ctrlPoints[i-1]
            val ctrl1 = ctrlPoints[i]
            splinePieces += BSplineVec3f(3).apply {
                ctrlPoints += ctrl0
                ctrlPoints += MutableVec3f(ctrl0).add(ctrl0.direction)
                ctrlPoints += MutableVec3f(ctrl1).subtract(ctrl1.direction)
                ctrlPoints += ctrl1
                addInterpolationEndpoints()
            }
        }
    }

    class CtrlPoint(x: Float, y: Float, z: Float) : MutableVec3f(x, y, z) {
        val direction = MutableVec3f(1f, 0f, 0f)

        constructor() : this(0f, 0f, 0f)
        constructor(pt: Vec3f) : this(pt.x, pt.y, pt.z)
        constructor(pt: Vec3f, direction: Vec3f) : this(pt.x, pt.y, pt.z) {
            this.direction.set(direction)
        }
    }
}

package de.fabmax.kool.math

import de.fabmax.kool.util.Float32Buffer
import de.fabmax.kool.util.MixedBuffer
import kotlin.math.*

fun QuatF.toQuatD() = QuatD(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
fun QuatF.toMutableQuatD(result: MutableQuatD = MutableQuatD()) = result.set(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
fun QuatF.toVec4f(): Vec4f = Vec4f(x, y, z, w)
fun QuatF.toMutableVec4f(result: MutableVec4f = MutableVec4f()): MutableVec4f = result.set(x, y, z, w)
fun MutableQuatF.set(that: QuatD) = set(that.x.toFloat(), that.y.toFloat(), that.z.toFloat(), that.w.toFloat())
fun Vec4f.toQuatF() = QuatF(x, y, z, w)

fun QuatD.toQuatF() = QuatF(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
fun QuatD.toMutableQuatF(result: MutableQuatF = MutableQuatF()) = result.set(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
fun QuatD.toVec4d(): Vec4d = Vec4d(x, y, z, w)
fun QuatD.toMutableVec4d(result: MutableVec4d = MutableVec4d()): MutableVec4d = result.set(x, y, z, w)
fun MutableQuatD.set(that: QuatF) = set(that.x.toDouble(), that.y.toDouble(), that.z.toDouble(), that.w.toDouble())
fun Vec4d.toQuatD() = QuatD(x, y, z, w)

private const val TAYLOR_EPS_F = 1e-3f
private const val TAYLOR_EPS_D = 1e-5f

// <template> Changes made within the template section will also affect the other type variants of this class

fun QuatF.toEulers(eulersDeg: MutableVec3f = MutableVec3f(), order: EulerOrder = EulerOrder.ZYX): MutableVec3f {
    Mat3f.rotation(this).getEulerAngles(eulersDeg, order)
    return eulersDeg
}

fun MutableQuatF.rotateByEulers(eulersDeg: Vec3f, order: EulerOrder = EulerOrder.ZYX): MutableQuatF {
    mul(Mat3f.rotation(eulersDeg.x.deg, eulersDeg.y.deg, eulersDeg.z.deg


import time

import torch

from pix2latent.optimizer.base_optimizer import _BaseOptimizer
from pix2latent.utils.misc import progress_print
from pix2latent.utils.image import to_image, to_grid, binarize

class GradientOptimizer(_BaseOptimizer):
    """
    Basic gradient optimizer. Compatible with any gradient-based optimizer.
    This optimizer uses the optimizer defined in variable_manager
    """

    def __init__(self, *args, **kwargs):
        _BaseOptimizer.__init__(self, *args, **kwargs)
        return

    def optimize(self, num_samples, grad_steps, pbar=None):
        """
        Args
            num_samples (int): number of samples to optimize over
            grad_steps (int): number of gradient descent updates.
            pbar: progress bar such as tqdm or st.progress [Default: None]

        """
        self.losses, self.outs = [], []

        variables = self.var_manager.initialize(num_samples=num_samples)

        t_st = time.time()

        for i in range(grad_steps):
            self.step(variables, optimize=True, transform=(i == 0))

            if pbar is not None:
                pbar.progress(i / grad_steps)

            if self.log:
                if ((i + 1) % self.log_iter == 0) or (i + 1 == grad_steps):
                    self.log_result(variables, i + 1)

            if (i + 1) % self.show_iter == 0:
                t_avg = (time.time() - t_st) / self.show_iter
                progress_print('optimize', i + 1, grad_steps, 'c', t_avg)
                t_st = time.time()

        if self.log:
            return variables, self.outs, self.losses

        transform_out = to_grid(torch.stack(list(self.out.cpu().detach())))

        return variables, [transform_out], [[grad_steps, {'loss':self.loss}]]


 to be a good citizen)
            if (!isValid(value)) {
                value = new Date(val);
            }

            // If that didn't work, don't change the underlying value. Instead, display an error.
            if (!value || !isValid(value)) {

                // TODO: i18n
                this.error = ["Invalid Date. Try formatting like " + format(new Date(), this.dateFormat)]
                value = null
            }
        }

        // Only emit an event if the input isn't invalid.
        // If we don't emit an input event, it gives the user a chance to correct their text.
        if (!this.error.length) this.$emit('input', value)
    }

    timeChanged(val: string) {
        var value = this.value || new Date()

        var parts = /(\d\d):(\d\d)/.exec(val);
        if (!parts) throw `Time set by vuetify timepicker not in expected format: ${val}`

        value = setHours(value, parseInt(parts[1]))
        value = setMinutes(value, parseInt(parts[2]))
        this.$emit('input', value)
    }

    dateChanged(val: string) {
        var value = this.value || new Date()

        var parts = /(\d\d\d\d)-(\d\d)-(\d\d)/.exec(val);
        if (!parts) throw `Date set by vuetify datepicker not in expected format: ${val}`

        value = setYear(value, parseInt(parts[1]))
        value = setMonth(value, parseInt(parts[2]) - 1)
        value = setDate(value, parseInt(parts[3]))
        this.$emit('input', value)
    }

    menu = false
    selectedTab: "date" | "time" | null = null; // = "date"

    get datePart() { return this.value && format(this.value, "yyyy-MM-dd") || null }
    get timePart() { return this.value && format(this.value, "HH:mm") || null }
}

//union type
function getLength(obj: Array<any>|string): number {
  return obj.length;
}

console.log(getLength([1, 2, 3]));
console.log(getLength("hogehoge"))

//union type for user defined interface
interface Bird {
  fly(): void;
  layEggs(): void;
}

interface Fish {
  swim(): void;
  layEggs(): void;
}

class MyFish implements Fish {
  swim(): void {};
  layEggs(): void {};
}

function getSmallPet(): Fish | Bird {
  return new MyFish();
}

let pet = getSmallPet();
pet.layEggs(); //ok!!!

/*  cause errors in compile time
if(pet.swim){
  pet.swim();
}
*/

if((<Fish>pet).swim){
  (<Fish>pet).swim();
}
else {
  (<Bird>pet).fly();
}

// type guards

function isFish(pet: Fish | Bird): pet is Fish {
  return (<Fish>pet).swim !== undefined;
}

if(isFish(pet)) {
  pet.swim();
}

// instanceof

if(pet instanceof MyFish){
  pet.swim();
}

// nullable types
let s = "foo";
//s = null;
let sn: string | null = "bar";
sn = null;import { CVariableInitializerTree } from './CVariableInitializerTree';
import {
  CNamedTypedEntry,
  CNamedTypedEntryDescriptor,
} from './CNamedTypedEntry';
import { CVariableInitializerPrintVisitor } from '../../ast/initializer-builder/CVariableInitializerPrintVisitor';
import { CType } from '../../types';

export type CVariableDescriptor = CNamedTypedEntryDescriptor & {
  global?: boolean;
  fnArg?: boolean;
  initializer?: CVariableInitializerTree;
};

/**
 * Pair name and type with additional global flag
 */
export class CVariable extends CNamedTypedEntry<CVariableDescriptor> {
  stati


 [0, -1, 0],
    size: [1.5, 0.001, 1.5],
    cameraAngle: [-HALF_PI, HALF_PI]
  },
  // BACK
  {
    position: [0, 1, 0],
    size: [1.5, 0.001, 1.5],
    cameraAngle: [HALF_PI, HALF_PI]
  },
  // RIGHT
  {
    position: [1, 0, 0],
    size: [0.001, 1.5, 1.5],
    cameraAngle: [0, HALF_PI]
  },
  // LEFT
  {
    position: [-1, 0, 0],
    size: [0.001, 1.5, 1.5],
    cameraAngle: [-Math.PI, HALF_PI]
  },
  // TOP-FRONT
  {
    position: [0, -0.876, 0.876],
    size: [1.5, 0.25, 0.25],
    cameraAngle: [-HALF_PI, QUARTER_PI]
  },
  // TOP-LEFT
  {
    position: [-0.876, 0, 0.876],
    size: [0.25, 1.5, 0.25],
    cameraAngle: [-Math.PI, QUARTER_PI]
  },
  // TOP-BACK
  {
    position: [0, 0.876, 0.876],
    size: [1.5, 0.25, 0.25],
    cameraAngle: [HALF_PI, QUARTER_PI]
  },
  // TOP-RIGHT
  {
    position: [0.876, 0, 0.876],
    size: [0.25, 1.5, 0.25],
    cameraAngle: [0, QUARTER_PI]
  },
  // BOTTOM-FRONT
  {
    position: [0, -0.876, -0.876],
    size: [1.5, 0.25, 0.25],
    cameraAngle: [-HALF_PI, 3 * QUARTER_PI]
  },
  // BOTTOM-LEFT
  {
    position: [-0.876, 0, -0.876],
    size: [0.25, 1.5, 0.25],
    cameraAngle: [-Math.PI, 3 * QUARTER_PI]
  },
  // BOTTOM-BACK
  {
    position: [0, 0.876, -0.876],
    size: [1.5, 0.25, 0.25],
    cameraAngle: [HALF_PI, 3 * QUARTER_PI]
  },
  // BOTTOM-RIGHT
  {
    position: [0.876, 0, -0.876],
    size: [0.25, 1.5, 0.25],
    cameraAngle: [0, 3 * QUARTER_PI]
  },
  // FRONT-LEFT
  {
    position: [-0.876, -0.876, 0],
    size: [0.25, 0.25, 1.5],
    cameraAngle: [-3 * QUARTER_PI, HALF_PI]
  },
  // FRONT-RIGHT
  {
    position: [0.876, -0.876, 0],
    size: [0.25, 0.25, 1.5],
    cameraAngle: [-QUARTER_PI, HALF_PI]
  },
  // BACK-LEFT
  {
    position: [-0.876, 0.876, 0],
    size: [0.25, 0.25, 1.5],
    cameraAngle: [3 * QUARTER_PI, HALF_PI]
  },
  // BACK-RIGHT
  {
    position: [0.876, 0.876, 0],
    size: [0.25, 0.25, 1.5],
    cameraAngle: [QUARTER_PI, HALF_PI]
  },
  // TOP-FRONT-LEFT
  {
    position: [-0.876, -0.876, 0.876],
    size: [0.25, 0.25, 0.25],
    cameraAngle: [-3 * QUARTER_PI, QUARTER_PI]
  },
  // TOP-FRONT-RIGHT
  {
    position: [0.876, -0.876, 0.876],
    size: [0.25, 0.25, 0.25],
    cameraAngle: [-QUARTER_PI, QUARTER_PI]
  },
  // TOP-BACK-LEFT
  {
    position: [-0.876, 0.876, 0.876],
    size: [0.25, 0.2


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

#pragma once

#include <QtWidgets/QDialog>
#include <QtWidgets/QLineEdit>

namespace qReal {
namespace gui {

class RenameDialog : public QDialog
{
public:
	static QString selectNewName(const QString &currentName, QWidget *parent = nullptr);

private slots:
	virtual void accept();
	virtual void reject();

private:
	explicit RenameDialog(const QString &initialText = "", QWidget *parent = nullptr);
	virtual ~RenameDialog();

	QString name() const;

	const QString mInitialName;
	QLineEdit *mTextBox;
};

}
}


INT_PAR__year));
    print_char('.' as i32);
    print_int(INTPAR(INT_PAR__month));
    print_char('.' as i32);
    print_int(INTPAR(INT_PAR__day));
    print_char(')' as i32);
    if interaction as i32 == BATCH_MODE {
        selector = Selector::LOG_ONLY
    } else {
        selector = Selector::TERM_AND_LOG
    }
    if pool_ptr + 1 > pool_size {
        overflow(
            b"pool size\x00" as *const u8 as *const i8,
            pool_size - init_pool_ptr,
        );
    }
    format_ident = make_string();
    pack_job_name(b".fmt\x00" as *const u8 as *const i8);
    let fmt_out = ttstub_output_open(name_of_file, 0i32);
    if fmt_out.is_none() {
        _tt_abort(
            b"cannot open format output file \"%s\"\x00" as *const u8 as *const i8,
            name_of_file,
        );
    }
    let mut fmt_out_owner = fmt_out.unwrap();
    let fmt_out = &mut fmt_out_owner;
    print_nl_cstr(b"Beginning to dump on file \x00" as *const u8 as *const i8);
    print(make_name_string());
    str_ptr -= 1;
    pool_ptr = *str_start.offset((str_ptr - 65536i32) as isize);
    print_nl_cstr(b"\x00" as *const u8 as *const i8);
    print(format_ident);
    /* Header */
    let mut x_val: i32 = 0x54544e43i32; /* TODO: can we move this farther up in this function? */
    do_dump(
        &mut x_val as *mut i32 as *mut i8,
        ::std::mem::size_of::<i32>() as u64,
        1i32 as size_t,
        fmt_out,
    );
    let mut x_val_0: i32 = FORMAT_SERIAL;
    do_dump(
        &mut x_val_0 as *mut i32 as *mut i8,
        ::std::mem::size_of::<i32>() as u64,
        1i32 as size_t,
        fmt_out,
    );
    let mut x_val_1: i32 = hash_high;
    do_dump(
        &mut x_val_1 as *mut i32 as *mut i8,
        ::std::mem::size_of::<i32>() as u64,
        1i32 as size_t,
        fmt_out,
    );
    while pseudo_files != TEX_NULL {
        pseudo_close();
    }
    let mut x_val_2: i32 = MEM_TOP;
    do_dump(
        &mut x_val_2 as *mut i32 as *mut i8,
        ::std::mem::size_of::<i32>() as u64,
        1i32 as size_t,
        fmt_out,
    );
    let mut x_val_3: i32 = EQTB_SIZE;
    do_dump(
        &mut x_val_3 as *mut i32 as *mut i8,
        ::std::mem::size_of::<i32>() as u64,
        1i32 as size_t,
        fmt_out,
    );
    let mut x_val_4: i32 = HASH_PRIME;
    do_dump(
        &mut x_val_4 as *mut i32 as *mut i8,
        ::std::mem::size_of::<i32>() as u64,
        1i32 as size_t,
        fmt_out,
    );
    let mut x_val_5: i32 = HYPH_PRIME;
    do_dump(


, nod(OAS, nr, n.Right))

	nfrm := nod(OSPTR, nr, nil)
	nto := nod(OSPTR, nl, nil)

	nlen := temp(types.Types[TINT])

	// n = len(to)
	l = append(l, nod(OAS, nlen, nod(OLEN, nl, nil)))

	// if n > len(frm) { n = len(frm) }
	nif := nod(OIF, nil, nil)

	nif.Left = nod(OGT, nlen, nod(OLEN, nr, nil))
	nif.Nbody.Append(nod(OAS, nlen, nod(OLEN, nr, nil)))
	l = append(l, nif)

	// if to.ptr != frm.ptr { memmove( ... ) }
	ne := nod(OIF, nod(ONE, nto, nfrm), nil)
	ne.SetLikely(true)
	l = append(l, ne)

	fn := syslook("memmove")
	fn = substArgTypes(fn, nl.Type.Elem(), nl.Type.Elem())
	nwid := temp(types.Types[TUINTPTR])
	setwid := nod(OAS, nwid, conv(nlen, types.Types[TUINTPTR]))
	ne.Nbody.Append(setwid)
	nwid = nod(OMUL, nwid, nodintconst(nl.Type.Elem().Width))
	call := mkcall1(fn, nil, init, nto, nfrm, nwid)
	ne.Nbody.Append(call)

	typecheckslice(l, ctxStmt)
	walkstmtlist(l)
	init.Append(l...)
	return nlen
}

func eqfor(t *types.Type) (n *Node, needsize bool) {
	// Should only arrive here with large memory or
	// a struct/array containing a non-memory field/element.
	// Small memory is handled inline, and single non-memory
	// is handled by walkcompare.
	switch a, _ := algtype1(t); a {
	case AMEM:
		n := syslook("memequal")
		n = substArgTypes(n, t, t)
		return n, true
	case ASPECIAL:
		sym := typesymprefix(".eq", t)
		n := newname(sym)
		n.SetClass(PFUNC)
		n.Sym.SetFunc(true)
		n.Type = functype(nil, []*Node{
			anonfield(types.NewPtr(t)),
			anonfield(types.NewPtr(t)),
		}, []*Node{
			anonfield(types.Types[TBOOL]),
		})
		return n, false
	}
	Fatalf("eqfor %v", t)
	return nil, false
}

// The result of walkcompare MUST be assigned back to n, e.g.
// 	n.Left = walkcompare(n.Left, init)
func walkcompare(n *Node, init *Nodes) *Node {
	if n.Left.Type.IsInterface() && n.Right.Type.IsInterface() && n.Left.Op != OLITERAL && n.Right.Op != OLITERAL {
		return walkcompareInterface(n, init)
	}

	if n.Left.Type.IsString() && n.Right.Type.IsString() {
		return walkcompareString(n, init)
	}

	n.Left = walkexpr(n.Left, init)
	n.Right = walkexpr(n.Right, init)

	// Given mixed interface/concrete comparison,
	// rewrite into types-equal && data-equal.
	// This is efficient, avoids allocations, and avoids runtime calls.
	if n.Left.Type.IsInterface() != n.Right.Type.IsInterface() {
		// Preserve side-effects in case of short-circuiting; see #32187.
		l := cheapexpr(n.Left, init)
		r := cheapexpr(n.Right, init)
		// Swap so that l is the interface value and r is the concrete value.
		if n.Right.Type.IsInterface() {
			l, r = r, l
		}

		// Handl


 llvm-mc -triple=aarch64 -filetype=obj -mattr=+sve < %s \
// RUN:   | llvm-objdump -d --mattr=-sve - | FileCheck %s --check-prefix=CHECK-UNKNOWN

brkpa  p0.b,  p15/z, p1.b,  p2.b
// CHECK-INST: brkpa	p0.b, p15/z, p1.b, p2.b
// CHECK-ENCODING: [0x20,0xfc,0x02,0x25]
// CHECK-ERROR: instruction requires: sve or sme
// CHECK-UNKNOWN: 2502fc20 <unknown>

brkpa  p15.b, p15/z, p15.b, p15.b
// CHECK-INST: brkpa	p15.b, p15/z, p15.b, p15.b
// CHECK-ENCODING: [0xef,0xfd,0x0f,0x25]
// CHECK-ERROR: instruction requires: sve or sme
// CHECK-UNKNOWN: 250ffdef <unknown>


extension("wotwrh");
    }

    let mut header_block = String::new();
    let mut context = HeaderContext {
        dependencies: dependencies.into_iter().collect::<HashSet<_>>(),
        ..HeaderContext::default()
    };

    let mut param_values = HashMap::new();

    for header_arg in &settings.header_args {
        let mut parts = header_arg.splitn(2, '=');
        let identifier = parts.next().unwrap();
        let value = parts.next().unwrap_or("true");

        if let Some(prior) = param_values.insert(identifier.to_string(), value.to_string()) {
            log::warn!("Overwriting {} with {} for header argument {}", prior, value, identifier);
        }
    }

    for header in headers {
        log::trace!("Parsing inline header");

        let header = headers::parser::parse_header(&PathBuf::from("inline header"), header, world, &mut context, &param_values, rng).map_err(|err| format!("{} in inline header", err))?;

        header_block += &header;
    }

    let mut parsed = HashSet::new();
    loop {
        let unparsed = context.dependencies.difference(&parsed).cloned().collect::<Vec<_>>();
        if unparsed.is_empty() { break; }

        parsed = context.dependencies.clone();

        for mut path in unparsed {
            path.set_extension("wotwrh");

            log::trace!("Parsing header {}", path.display());
            let header = util::read_file(&path, "headers")?;
            let header = headers::parser::parse_header(&path, &header, world, &mut context, &param_values, rng).map_err(|err| format!("{} in header {}", err, path.display()))?;

            header_block += &header;
        }
    }

    for header in context.dependencies {
        let name = header.file_stem().unwrap().to_string_lossy().to_string();

        if let Some(incompability) = context.excludes.get(&name) {
            return Err(format!("{} and {} are incompatible", header.display(), incompability));
        }
    }

    Ok((header_block, context.flags, context.names))
}

fn generate_placements<'a, R>(graph: &'a Graph, worlds: Vec<World<'a>>, settings: &Settings, spawn_pickup_node: &'a Node, custom_names: &HashMap<String, String>, rng: &mut R) -> Result<(Vec<Vec<Placement<'a>>>, Vec<&'a Node>), String>
where R: Rng
{
    let mut index = 0;
    loop {
        let spawn_locs = (0..settings.worlds)
            .map(|_| pick_spawn(graph, &settings, rng))
            .collect::<Result<Vec<_>, String>>()?;
        let identifiers = spawn_locs.iter().map(|spawn_loc| spawn_loc.identifier()).collect::<Vec<_>>();
        log::trace!("Spawning on {}", identifiers.join(", "));

        match generator::generate_placements(worlds.clone(), &spawn_locs, spawn_pickup_node, custom_names, settings, rng) {
            Ok(seed) => {
                if index > 0 {
                    log::info!("Generated seed after {} tries{}", index + 1, if index < RETRIES / 2 { "" } else { " (phew)" });
                }
                return Ok((seed, spawn_locs));
            },
            Err(err) => log::error!("{}\nRetrying...", err),
        }

        index += 1;
        if index == RETRIES {
            return Err(format!("All {} attempts to generate a seed failed :(", RETRIES));
        }
    };
}

#[inline]
fn format_placements(world_placements: Vec<Placement>, custom_names: &HashMap<String, String>, spoilers: bool) -> String {


alf("failed to export public key: %v", err)
	}

	// Verify with vendor library

	verifiedPayload, err := jws.Verify([]byte(result.(string)), jws.WithKey(alg, rawPublicKey))
	if err != nil || string(verifiedPayload) != examplePayload {
		t.Fatal("Failed to verify message")
	}
}

// TestTopDownJWTEncodeSignEC needs to perform all tests inline because we do not know the
// expected values before hand
func TestTopDownJWTEncodeSignES512(t *testing.T) {
	t.Parallel()

	const examplePayload = `{"iss":"joe",` + "\r\n" + ` "exp":1300819380,` + "\r\n" + ` "http://example.com/is_root":true}`
	const es512Hdr = `{"alg":"ES512"}`
	const ecKey = `{
"kty":"EC",
"crv":"P-521",
"x":"AekpBQ8ST8a8VcfVOTNl353vSrDCLLJXmPk06wTjxrrjcBpXp5EOnYG_NjFZ6OvLFV1jSfS9tsz4qUxcWceqwQGk",
"y":"ADSmRA43Z1DSNx_RvcLI87cdL07l6jQyyBXMoxVg_l2Th-x3S1WDhjDly79ajL4Kkd0AZMaZmh9ubmf63e3kyMj2",
"d":"AY5pb7A0UFiB3RELSD64fTLOSV_jazdF7fLYyuTw8lOfRhWg6Y6rUrPAxerEzgdRhajnu0ferB0d53vM9mE15j2C"
}`

	params := struct {
		note   string
		input1 string
		input2 string
		input3 string
	}{
		"https://tools.ietf.org/html/rfc7515#appendix-A.4",
		"`" + es512Hdr + "`",
		"`" + examplePayload + "`",
		"`" + ecKey + "`",
	}
	type test struct {
		note  string
		rules []string
	}
	var tests []test

	tests = append(tests, test{
		params.note,
		[]string{fmt.Sprintf(`p = x { io.jwt.encode_sign_raw(%s, %s, %s, x) }`, params.input1, params.input2, params.input3)},
	})

	tc := tests[0]

	compiler, err := compileRules(nil, tc.rules, nil)
	if err != nil {
		t.Errorf("%v: Compiler error: %v", tc.note, err)
		return
	}
	store := inmem.New()
	path := []string{"generated", "p"}
	var inputTerm *ast.Term

	ctx := t.Context()
	txn := storage.NewTransactionOrDie(ctx, store)

	defer store.Abort(ctx, txn)

	var lhs *ast.Term
	if len(path) == 0 {
		lhs = ast.NewTerm(ast.DefaultRootRef)
	} else {
		lhs = ast.MustParseTerm("data." + strings.Join(path, "."))
	}

	rhs := ast.VarTerm(ast.WildcardPrefix + "result")
	body := ast.NewBody(ast.Equality.Expr(lhs, rhs))

	query := NewQuery(body).
		WithCompiler(compiler).
		WithStore(store).
		WithTransaction(txn).
		WithInput(inputTerm)

	var tracer BufferTracer

	if os.Getenv("OPA_TRACE_TEST") != "" {
		query = query.WithTracer(&tracer)
	}

	qrs, err := query.Run(ctx)

	if tracer != nil {
		PrettyTrace(os.Stdout, tracer)
	}

	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	if len(qrs) == 0 {
		t.Fatal("Undefined result")
	}

	res


y\\g\\T\\j\\Z\\s\\t";4 4b="aw";if(46!=4b){ax=av}5{c=""}4 4e=-1;if(6.A(4e)>=0){au=ar}5{4 lR=d}if("-as".14("\\s\\W\\o\\O")==-1){4 at="af"}5{N="\\l\\e\\l\\O\\Z"}4 4f=0;if(6.10(4f)==0){ad=-a2}5{4 a3=9}4 4a=1;if(6.A(4a)===0){4 a1=d}if("-a0"!="9X"){9Y=-9Z}5{a4="\\g\\o\\y\\S\\T\\g\\Z"}4 kP=-1;if(6.J(kP)!=0){4 a5=d}5{4 ab=\'\\W\\g\\e\\g\\g\\j\\y\'}4 X=-1;if(6.A(X)==0){4 ac=9}5{aa=d}4 4t=-1;if(6.A(4t)===0){ae=\'a9\'}4 K=0;if(6.A(K)!=0){a6=\'a7\'}5{4 a8=-9l}if("9k".R("8z")==0){8A=9}4 4n="";if(4n==="-8y"){4 8x=""}if("8u".z<=7(-8v)){4 D=9}5{4 8w=8B}4 3L=1;if(6.A(3L)>0){4 8C=-8I}5{8J=7(8H,8)}4 3S=0;if(6.10(3S)!=0){8G=8D}5{8E="8F"}B 8t(3Z){E 6.13(3Z)}if("8s"=="8g"){8h=9}4 3X=1;if(6.A(3X)===0){8i="8f"}if("\\v\\g\\W\\g\\W\\e"=="8e"){c9=8b}5{4 n=9}4 4x=0;if(6.A(4x)>=0){4 8c="8d"}5{4 8j=8k}if("\\t\\e\\O\\o\\S\\t\\g".14("")!=-1){4 fT="\\11\\j\\W\\e\\S"}5{8q="8r"}4 4E="\\U\\v\\W\\W\\s\\j\\e\\S";4 4G="8p";if(4E==4G){4 8o=d}5{8l=9}4 4I=1;if(6.A(4I)>=0){8m=d}4 1b=12("8n","8K");if(8L==-99){4 9a="\\O\\t\\W\\U\\y\\e"}if("\\s\\e\\O\\s\\t\\j".z!=98){4 97=-94}4 mj=-1;if(6.A(mj)==0){95=9}4 1L="96";4 1N="9b";if(1L==1N){4 9c=\'\\v\\y\\s\\t\\v\\l\\T\'}5{9i=\'\'}4 2j=0;if(6.10(2j)===0){9j=\'9h\'}5{4 9g=-9d}4 1b=1b.2e(",");if("9e".R("9f")==-1){4 93="92"}5{8R="8S"}B 8Q(20){E 6.1h(20)}4 1Z=1;if(6.13(1Z)>=0){8P=8M}5{4 8N=\'\'}B 8O(2a){E 6.1h(2a)}4 27=-1;if(6.J(27)>0){4 8T=7(-8U)}5{4 90=\'\\U\\W\\j\\11\\


operation was successful.</returns>
    bool NavigateExternal(Uri absolutePageUri, object dataContext);

    /// <summary>
    /// Sets <see cref="System.Windows.FrameworkElement.DataContext"/> of the page.
    /// <para>If the page is not in the Cache, and is defined based on <see cref="INavigationItem.PageType"/>, its object will be created and then its DataContext will be defined.</para>
    /// </summary>
    /// <param name="pageId">Id of the page from <see cref="Items"/> or <see cref="Footer"/>.</param>
    /// <param name="dataContext">Context of the data for data binding.</param>
    /// <returns><see langword="true"/> if the operation was successful.</returns>
    bool SetContext(int pageId, object dataContext);

    /// <summary>
    /// Sets <see cref="System.Windows.FrameworkElement.DataContext"/> of the page.
    /// <para>If the page is not in the Cache, and is defined based on <see cref="INavigationItem.PageType"/>, its object will be created and then its DataContext will be defined.</para>
    /// </summary>
    /// <param name="pageTag">Tag of the page from <see cref="Items"/> or <see cref="Footer"/>.</param>
    /// <param name="dataContext">Context of the data for data binding.</param>
    /// <returns><see langword="true"/> if the operation was successful.</returns>
    bool SetContext(string pageTag, object dataContext);

    /// <summary>
    /// Tires to set the DataContext for the currently displayed page.
    /// </summary>
    /// <param name="dataContext">Data context to be set.</param>
    void SetCurrentContext(object dataContext);
}


.position();
        final int len = LFH_FILENAME_OFFSET + nameLen + extra.length;
        final byte[] buf = new byte[len];

        System.arraycopy(LFH_SIG,  0, buf, LFH_SIG_OFFSET, ZipConstants.WORD);

        //store method in local variable to prevent multiple method calls
        final int zipMethod = ze.getMethod();
        final boolean dataDescriptor = usesDataDescriptor(zipMethod, phased);

        ZipShort.putShort(versionNeededToExtract(zipMethod, hasZip64Extra(ze), dataDescriptor), buf, LFH_VERSION_NEEDED_OFFSET);

        final GeneralPurposeBit generalPurposeBit = getGeneralPurposeBits(!encodable && fallbackToUTF8, dataDescriptor);
        generalPurposeBit.encode(buf, LFH_GPB_OFFSET);

        // compression method
        ZipShort.putShort(zipMethod, buf, LFH_METHOD_OFFSET);

        ZipUtil.toDosTime(calendarInstance, ze.getTime(), buf, LFH_TIME_OFFSET);

        // CRC
        if (phased || !(zipMethod == DEFLATED || channel != null)){
            putLong(ze.getCrc(), buf, LFH_CRC_OFFSET);
        } else {
            System.arraycopy(LZERO, 0, buf, LFH_CRC_OFFSET, ZipConstants.WORD);
        }

        // compressed length
        // uncompressed length
        if (hasZip64Extra(entry.entry)){
            // point to ZIP64 extended information extra field for
            // sizes, may get rewritten once sizes are known if
            // stream is seekable
            ZipLong.ZIP64_MAGIC.putLong(buf, LFH_COMPRESSED_SIZE_OFFSET);
            ZipLong.ZIP64_MAGIC.putLong(buf, LFH_ORIGINAL_SIZE_OFFSET);
        } else if (phased) {
            putLong(ze.getCompressedSize(), buf, LFH_COMPRESSED_SIZE_OFFSET);
            putLong(ze.getSize(), buf, LFH_ORIGINAL_SIZE_OFFSET);
        } else if (zipMethod == DEFLATED || channel != null) {
            System.arraycopy(LZERO, 0, buf, LFH_COMPRESSED_SIZE_OFFSET, ZipConstants.WORD);
            System.arraycopy(LZERO, 0, buf, LFH_ORIGINAL_SIZE_OFFSET, ZipConstants.WORD);
        } else { // Stored
            putLong(ze.getSize(), buf, LFH_COMPRESSED_SIZE_OFFSET);
            putLong(ze.getSize(), buf, LFH_ORIGINAL_SIZE_OFFSET);
        }
        // file name length
        ZipShort.putShort(nameLen, buf, LFH_FILENAME_LENGTH_OFFSET);

        // extra field length
        ZipShort.putShort(extra.length, buf, LFH_EXTRA_LENGTH_OFFSET);

        // file name
        System.arraycopy( name.array(), name.arrayOffset(), buf, LFH_FILENAME_OFFSET, nameLen);

        // extra fields
        System.arraycopy(extra, 0, buf, LFH_FILENAME_OFFSET + nameLen, extra.length);

        return buf;
    }

    /**
     * Writes next block of compressed data to the output stream.
     * @throws IOException on error
     */
    protected final void deflate() throws IOException {
        streamCompressor.deflate();
    }

    /**
     * Closes the underlying stream/file without finishing the
     * archive, the result will likely be a corrupt archive.
     *
     *
This method only exists to support tests that generate
     * corrupt archives so they can clean up any temporary files.

     */
    void destroy() throws IOException {
        try {
            if (channel != null) {
                channel.close();
            }
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

    /**
     * {@inheritDoc}
     * @throws Zip64RequiredException if the archive's size exceeds 4
     * GByte or there are more than 65535 entries inside the archive
     * and {@link #setUseZip64} is {@link Zip64Mode#Never}.
     */
    @Override
    public void finish() throws IOException {
        if (finished) {
            throw new IOException("This archive has already been finished");
        }

        if (entry != null) {
            throw new IOException("This archive contains unc


1, [r1, r7]
	bl      Function_201e190
	ldr     r1, [sp, #0x20]
	sub     r0, r1, r0
	cmp     r6, r0
	ble     branch_21eeeec
	mov     r6, r0
	str     r4, [sp, #0xc]
branch_21eeeec: @ 21eeeec :thumb
	add     r0, r4, #0x1
	lsl     r0, r0, #16
	lsr     r4, r0, #16
	cmp     r4, r5
	blt     branch_21eeec4
branch_21eeef6: @ 21eeef6 :thumb
	ldr     r0, [sp, #0xc]
	mov     r1, #0xc
	mul     r1, r0
	add     r0, sp, #0x50
	ldr     r1, [r0, r1]
	ldr     r0, [sp, #0xe0]
	add     sp, #0xc8
	str     r1, [r0, #0x0]
	mov     r0, #0x1
	pop     {r3-r7,pc}

branch_21eef0a: @ 21eef0a :thumb
	bne     branch_21eef18
	ldr     r1, [sp, #0x50]
	ldr     r0, [sp, #0xe0]
	add     sp, #0xc8
	str     r1, [r0, #0x0]
	mov     r0, #0x1
	pop     {r3-r7,pc}

branch_21eef18: @ 21eef18 :thumb
	cmp     r5, #0x0
	beq     branch_21eef28
	ldr     r1, [sp, #0x50]
	ldr     r0, [sp, #0xe0]
	add     sp, #0xc8
	str     r1, [r0, #0x0]
	mov     r0, #0x1
	pop     {r3-r7,pc}

branch_21eef28: @ 21eef28 :thumb
	mov     r0, #0x0
	add     sp, #0xc8
	pop     {r3-r7,pc}
@ 0x21eef2e

.align 2
.word 0x0 @ 0x21eef30

.thumb
Function_21eef34: @ 21eef34 :thumb
	push    {r3-r5,lr}
	add     sp, #-0x8
	mov     r5, r0
	mov     r0, #0x0
	mov     r2, #0x18
	mov     r4, r1
	blx     MIi_CpuClear32
	mov     r0, r5
	mov     r1, #0x4
	add     r2, sp, #0x0
	bl      Call_FS_ReadFile
	mov     r0, r5
	mov     r1, #0x2
	mov     r2, r4
	bl      Call_FS_ReadFile
	mov     r0, r5
	mov     r1, #0x2
	add     r2, r4, #0x4
	bl      Call_FS_ReadFile
	mov     r2, r4
	mov     r0, r5
	mov     r1, #0x2
	add     r2, #0x8
	bl      Call_FS_ReadFile
	mov     r2, r4
	mov     r0, r5
	mov     r1, #0x2
	add     r2, #0xc
	bl      Call_FS_ReadFile
	mov     r2, r4
	mov     r0, r5
	mov     r1, #0x2
	add     r2, #0x10
	bl


ined', undefined)).toBeTruthy();
      expect(HandyVal.validate('undefined', 123)).toBeFalsy();
    });
  });
});
import * as THREE from "three";
import {Fisheye, Radian} from "./Fisheye";

export interface CameraConfig { region: FishEyeRegion, direction: DirectionOfView, zoom: number }

export type Pixel     = number;

/**
 * 画像上の魚眼円の位置と大きさ
 */
export interface FishEyeRegion {
  centerX: Pixel;
  centerY: Pixel;
  radius: Pixel;
}

/**
 * 注視点の向き、単位
 */
export interface DirectionOfView {
  pitch: Radian;
  yaw: Radian;
}

/**
 * 魚眼cnvを透視投影に変換する
 * ソースとなる cnv を動的に変えることができる、再利用可能な gl renderer
 * @example
 * ```js
 * // ライフサイクル
 * const a = new FisheyeCanvas2PerspectiveRenderer();
 * a.changeSource(video);         // 魚眼ソース指定
 * a.updateFisheyeRegion(region); // 魚眼ソースからクリッピングする領域を指定
 * a.setCanvasSize(size);         // 出力 canvas サイズを指定
 * a.setCameraPose(pose);         // カメラの向きを指定
 * a.render();                    // 描画
 * document.body.append(a.canvas); // 結果表示
 * ```
 */
export class Fisheye2Perspective extends Fisheye<THREE.PerspectiveCamera> {

  /**
   * ソース魚眼をクリッピングしたテクスチャ
   */
  readonly texctx1: CanvasRenderingContext2D;
  readonly texctx2: CanvasRenderingContext2D;

  /**
   * 描画モード
   * true - テクスチャ&ポリゴン削減モード
   * false - naive モード
   */
  readonly sep_mode: boolean;

  // 当たり判定
  readonly collisionSphere: THREE.Mesh;

  /** load 前 === src 変更前に書き換えてね */
  public mesh_num: number;
  private meshes: THREE.Mesh[];
  private texis: THREE.Texture[];
  private readonly local: THREE.Object3D;

  readonly CAMERA_PITCH_MAX: number;
  readonly CAMERA_PITCH_MIN: number;

  // for debug
  readonly debug: boolean;

  private prevEuler: {pitch: Radian, yaw: Radian};

  constructor(o?: {textureSizeExponent?: number, mesh?: number, sep_mode?: boolean, debug?: boolean}){
    super(new THREE.PerspectiveCamera( 30, 4 / 3, 1, 10000 ), o);

    if(o != null && o.sep_mode === true){
      this.sep_mode = true;
    }else{
      this.sep_mode = false;
    }
    if(o != null && o.mesh != null){
      this.mesh_num = o.mesh;
    }else{
      this.mesh_num = 32;
    }

    this.local = new THREE.Object3D();
    this.meshes = [];
    this.texis = [];

    this.local.position.z = 0;
    this.camera.position.z = 0.01;

    // ドラッグ用当たり判定メッシュ
    // SphereGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength)
    const sphereGeom =  new THREE.SphereGeometry( 100, 32, 16 );
    const blueMaterial = new THREE.MeshBasicMaterial( { color: 0x0000ff, side: THREE.BackSide, transparent: true, opacity: 0 } );
    this.collisionSphere = new THREE.Mesh( sphereGeom, blueMaterial );

    this.scene.add(this.local);
    this.scene.add(this.collisionSphere);

    if(this.sep_mode){
      this.texctx1 = <CanvasRenderingContext2D>document.createElement("canvas").getContext("2d");
      this.texctx2 = <CanvasRenderingContext2D>document.createElement("canvas").getContext("2d");
    }

    this.CAMERA_PITCH_MAX = Math.PI*1/


);">Citizen Lab声称该app应用程序正受困于不一致以及不充分的身份验证。该应用程序接受请求,甚至不需要验证发送验证的人是否拥有该帐户。这意味着,如果攻击者有用户的电话号码,他们可以检索信息,修改帐户,并禁用设备,这是需要人们提高警惕的。

MOIBA的基础设施,监视着这些app,同时也被不加密的数据传输所困扰。

“他们的服务器无法满足共同的安全标准,“,Citizen Lab 写到,“部署是基于过时的,不安全的协议,这很容易受到攻击,可能导致被拦截以及moiba的服务器假冒验证。”

Citizen Lab警告说:在所有这些漏洞的最初,应用程序背后的软件是如此的不可救药的落后,在一些情况下,两年的旧的软件,使得它更容易出现错误以及漏洞。

Citizen Lab提醒道——当结合所有的问题时,这些所有的漏洞已经是显而易见的了。

研究人员写道:“已经确定的漏洞组合可能会导致大规模的帐户处于危险境地或者服务中断。一个拥有资源来运行高容量的查询来对抗智能监控(Smart Sheriff)的攻击者,可能会暗中识别智能监控的所有用户,然后使用我们确定的系统漏洞来破坏所有用户的设备或服务本身。“

Smart Sheriff拥有将近500,000的用户,和其他几个应用程序一样,被要求履行韩国四月份通过的一个政策,要求韩国电信运营商对相关的手机监控有害的内容进行阻止和封锁。事实上,一个监管机构——韩国通信委员会(kcc)在今年五月份帮助该APP进行开发和推广,这促使主权国家围绕人权法对儿童隐私问题以及移动设备隐私问题的讨论。

总部在多伦多大学


 0x10($a0)
/* B49484 800D22E4 C48E0014 */  lwc1  $f14, 0x14($a0)
/* B49488 800D22E8 0C03F494 */  jal   func_800FD250
/* B4948C 800D22EC 46006307 */   neg.s $f12, $f12
/* B49490 800D22F0 3C018014 */  lui   $at, %hi(D_80146658)
/* B49494 800D22F4 C4326658 */  lwc1  $f18, %lo(D_80146658)($at)
/* B49498 800D22F8 46120102 */  mul.s $f4, $f0, $f18
/* B4949C 800D22FC 4600218D */  trunc.w.s $f6, $f4
/* B494A0 800D2300 44193000 */  mfc1  $t9, $f6
/* B494A4 800D2304 10000038 */  b     .L800D23E8
/* B494A8 800D2308 A6190004 */   sh    $t9, 4($s0)
/* B494AC 800D230C C48C0004 */  lwc1  $f12, 4($a0)
.L800D2310:
/* B494B0 800D2310 C48E0000 */  lwc1  $f14, ($a0)
/* B494B4 800D2314 0C03F494 */  jal   func_800FD250
/* B494B8 800D2318 AFA40028 */   sw    $a0, 0x28($sp)
/* B494BC 800D231C 3C018014 */  lui   $at, %hi(D_8014665C)
/* B494C0 800D2320 C428665C */  lwc1  $f8, %lo(D_8014665C)($at)
/* B494C4 800D2324 8FA40028 */  lw    $a0, 0x28($sp)
/* B494C8 800D2328 46080282 */  mul.s $f10, $f0, $f8
/* B494CC 800D232C 4600548D */  trunc.w.s $f18, $f10
/* B494D0 800D2330 44099000 */  mfc1  $t1, $f18
/* B494D4 800D2334 00000000 */  nop
/* B494D8 800D2338 A6090004 */  sh    $t1, 4($s0)
/* B494DC 800D233C 8FAA0030 */  lw    $t2, 0x30($sp)
/* B494E0 800D2340 5540000C */  bnezl $t2, .L800D2374
/* B494E4 800D2344 C4940010 */   lwc1  $f20, 0x10($a0)
/* B494E8 800D2348 C48C0018 */  lwc1  $f12, 0x18($a0)
/* B494EC 800D234C 0C03F494 */  jal   func_800FD250
/* B494F0 800D2350 C48E0028 */   lwc1  $f14, 0x28($a0)
/* B494F4 800D2354 3C018014 */  lui   $at, %hi(D_80146660)
/* B494F8 800D2358 C4246660 */  lwc1  $f4, %lo(D_80146660)($at)
/* B494FC 800D235C 46040182 */  mul.s $f6, $f0, $f4
/* B49500 800D2360 4600320D */  trunc.w.s $f8, $f6
/* B49504 800D2364 440C4000 */  mfc1  $t4, $f8
/* B49508 800D2368 1000001F */  b     .L800D23E8
/* B4950C 800D236C A60C0000 */   sh    $t4, ($s0)
/* B49510 800D2370 C4940010 */  lwc1  $f


内 存的 目的 ，Java 语言 没有 提供 释放已分 配内 存的 显示 操作 方法 。Java 程序 员不 用担 心内 存管 理， 因为 垃圾 收集 器会自动 进行 管理 。要 请求 垃圾 收集 ，可 以调 用下 面的 方法 之一 ：System.gc() 或Runtime.getRuntime().gc() ，但 JVM 可以 屏蔽 掉显 示的 垃圾 回收 调用 。

垃圾回收可以有效的防止内存泄露，有效的使用可以使用的内存。垃圾回收器通常是作为一个单独的低优先级的线程运行，不可预知的情况下对内存堆中已经死亡的或者长时间没有使用的对象进行清除和回收，程序员不能实时的调用垃圾回收器对某个对象或所有对象进行垃圾回收。在 Java 诞生初期，垃圾回收是 Java最大的亮点之一，因为服务器端的编程需要有效的防止内存泄露问题，然而时过境迁，如今 Java 的垃圾回收机制已经成为被诟病的东。移动智能终端用户通常觉得 iOS 的系统比 Android 系统有更好的用户体验，其中一个深层次的原因就在于 Android 系统中垃圾回收的不可预知性。

### 20、堆（Heap-线程共享） -运行时数据区

是被线程共享的一块内存区域， 创建的对象和数组都保存在 Java 堆内存中，也是垃圾收集器进行垃圾收集的最重要的内存区域。 由于现代 VM 采用分代收集算法, 因此 Java 堆从 GC 的角度还可以细分为: 新生代(Eden 区、 From Survivor 区和 To Survivor 区)和老年代。

### 21、方法区/永久代（线程共享）

即我们常说的永久代(Permanent Generation), 用于存储被 JVM 加载的类信息、 常量、 静态变量、 即时编译器编译后的代码等数据. HotSpot VM把GC分代收集扩展至方法区, 即使用Java堆的永久代来实现方法区, 这样 HotSpot 的垃圾收集器就可以像管理 Java 堆一样管理这部分内存,而不必为方法区开发专门的内存管理器(永久带的内存回收的主要目标是针对常量池的回收和类型的卸载, 因此收益一般很小)  。

运行时常量池（Runtime Constant Pool）是方法区的一部分。 Class 文件中除了有类的版本、字段、方法、接口等描述等信息外，还有一项信息是常量池  （Constant Pool Table），用于存放编译


from threading import Thread
import time

import numpy as np

from fury import actor, window
from fury.utils import rotate, update_actor, vertices_from_actor

def test_multithreading():
    xyz = 10 * (np.random.random((100, 3)) - 0.5)
    colors = np.random.random((100, 4))
    radii = np.random.random(100) + 0.5

    scene = window.Scene()
    sphere_actor = actor.sphere(
        centers=xyz, colors=colors, radii=radii, use_primitive=False
    )
    scene.add(sphere_actor)

    # Preparing the show manager as usual
    showm = window.ShowManager(
        scene=scene, size=(900, 768), reset_camera=False, order_transparent=True
    )

    # showm.initialize()

    vsa = vertices_from_actor(sphere_actor)

    def callback1():
        for i in range(100):
            if showm.lock_current():
                rotate(sphere_actor, rotation=(0.01 * i, 1, 0, 0))
                vsa[:] = 1.01 * vsa[:]
                update_actor(sphere_actor)
                showm.release_current()
                time.sleep(0.01)
            else:
                break

        showm.exit()
        # if not showm.is_done():
        #    arr = window.snapshot(
        #        scene,
        #        render_window=showm.window,
        #        fname="test.png",
        #    )
        #    showm.exit()
        #    npt.assert_equal(np.sum(arr) > 1, True)

    thread_a = Thread(target=callback1)
    thread_a.start()

    showm.start(multithreaded=True)
    thread_a.join()


w($crate::dom::DynamicNode::from(e)))
            }
        }

        impl TryFrom<$crate::event::DynamicEventTarget> for $tpe {
            type Error = $crate::InvalidCast<$crate::event::DynamicEventTarget, $tpe>;

            fn try_from(value: $crate::event::DynamicEventTarget) -> Result<Self, Self::Error> {
                use wasm_bindgen::JsCast;

                let value: web_sys::EventTarget = value.into();

                value.dyn_into::<$tpe>().map_err(|e| {
                    $crate::InvalidCast::new($crate::event::DynamicEventTarget::from(e))
                })
            }
        }
    };
}

pub(crate) use impl_try_from_element_with_tag_check;
<filename>src/main.rs
#[macro_use]
extern crate clap;

extern crate ipnet;
extern crate netscan;

mod process;
mod option;
mod define;
mod db;
mod model;
mod parser;
mod handler;
mod interface;
mod validator;
mod network;
mod probe;
mod result;
mod printer;

use std::env;
use chrono::{Local, DateTime};
use clap::{App, AppSettings, Arg, ArgGroup};
use crossterm::style::Colorize;

#[cfg(target_os = "windows")]
fn get_os_type() -> String{"windows".to_owned()}

#[cfg(target_os = "linux")]
fn get_os_type() -> String{"linux".to_owned()}

#[cfg(target_os = "macos")]
fn get_os_type() -> String{"macos".to_owned()}

#[tokio::main]
async fn main() {
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        show_app_desc();
        std::process::exit(0);
    }
    let app = get_app_settings();
    let matches = app.get_matches();
    let mut require_admin = if get_os_type() == "windows"{false}else{true};
    //Scan
    show_banner_with_starttime();
    if matches.is_present("async") && get_os_type() == "windows" {
        println!();
        println!("Asynchronous scanning is not supported on Windows");
        println!("Please remove the -a(--async) flag and try again.");
        std::process::exit(0);
    }
    if matches.is_present("port"){
        if let Some(p) = matches.value_of("portscantype") {
            if p == "CONNECT" {
                require_admin = false;
            }
        }
        if require_admin && !process::privileged() {
            println!("{} This feature requires administrator privileges. ","Error:".red());
            std::process::exit(0);
        }
        let opt = parser::parse_port_args(matches);
        handler::handle_port_scan(opt).await;
    }else if matches.is_present("network") || matches.is_present("host") {
        if require_admin && !process::privileged() {
            println!("{} This feature requires administrator privileges. ","Error:".red());
            std::process::exit(0);
        }
        let opt = parser::parse_host_args(matches);
        handler::handle_host_scan(opt).await;
    }else{
        println!();
        println!("Error: Scan mode not specified.");
        std::process::exit(0);
    }
}

fn get_app_settings<'a, 'b>() -> App<'a, 'b> {
    let app = App::new(crate_name!())
        .version(crate_version!())
        .author(define::CRATE_AUTHOR_GITHUB)
        .about(crate_description!())
        .arg(Arg::with_name("port")
            .help("Scan ports of the specified host. \nUse default port list if port range


)).then((i:number) => {return i-1});
//     let b = page.getElementArrayLength(page.getQuestionElementArray(page.getOtherQuestionComponent())).then((i:number) => {return i+1});
//     page.getCollapseButton(page.getMyQuestionComponent()).click();
//     let q = page.getQuestionElement(page.getQuestionElementArray(page.getFaqComponent()), 0);
//     let id= page.getQuestionId(q); //id to compare at end
//       page.getAssignButton(q).click();
//       //have to do modal stuff
//
//     page.navigateToLab1();
//     expect(page.getElementArrayLength(page.getQuestionElementArray(page.getMyQuestionComponent()))).toBe(a);
//     expect(page.getElementArrayLength(page.getQuestionElementArray(page.getOtherQuestionComponent()))).toBe(b);
//     expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getMyQuestionComponent()))).not.toContain(id);
//     expect(page.getQuestionIdArray(page.getQuestionElementArray(page.getOtherQuestionComponent()))).toContain(id);
//     //also compare to assigned to field
//   });

});
import { Rose } from '../../../../src';
import { salesByArea } from '../../../data/sales';
import { createDiv } from '../../../utils/dom';

describe('rose: pattern', () => {
  const rose = new Rose(createDiv(), {
    width: 400,
    height: 300,
    data: salesByArea,
    xField: 'area',
    yField: 'sales',
    meta: {
      sales: {
        nice: true,
        formatter: (v) => `${Math.floor(v / 10000)}万`,
      },
    },
  });

  rose.render();

  it('pattern: obj', () => {
    rose.update({
      pattern: {
        type: 'line',
      },
    });

    const geometry = rose.chart.geometries[0];
    const elements = geometry.elements;
    expect(elements[0].shape.attr('fill') instanceof CanvasPattern).toEqual(true);
    expect(elements[1].shape.attr('fill') instanceof CanvasPattern).toEqual(true);
    expect(elements[2].shape.attr('fill') instanceof CanvasPattern).toEqual(true);

    rose.update({
      pattern: null,
    });

    expect(rose.chart.geometries[0].elements[0].shape.attr('fill') instanceof CanvasPattern).toEqual(false);
    expect(rose.chart.geometries[0].elements[1].shape.attr('fill') instanceof CanvasPattern).toEqual(false);
    expect(rose.chart.geometries[0].elements[2].shape.attr('fill') instanceof CanvasPattern).toEqual(false);
  });

  it('pattern: callback', () => {
    rose.update({
      pattern: ({ area }) => {
        if (area === '中南') {
          return { type: 'dot' };
        }
      },
    });

    expect(rose.chart.geometries[0].elements[0].shape.attr('fill') instanceof CanvasPattern).toEqual(false);
    expect(rose.chart.geometries[0].elements[1].shape.attr('fill') instanceof CanvasPattern).toEqual(true);
    expect(rose.chart.geometries[0].elements[2].shape.attr('fill') instanceof CanvasPattern).toEqual(false);
  });

  afterAll(() => {
    rose.destroy();
  });
});
import { DateSchema, NumberSchema } from 'yup';
import { toYup } from 'src/toYup';
import { DateTypeSchema } from 'src/types';;

const schemaNullable: DateTypeSchema = {
    type: 'date',
    min: [''] as any, //purposely wrong for code coverage
    max: [''] as any, //purposely wrong for code coverage
    strict: true,
    nullable: true,
};

const schemaNotNullable: Dat


r.append("assert ");

    tracer.addMapping(bytecode);

    if (parameters.get(0) == null) {
      buffer.append("false");
    }
    else {
      buffer.append(parameters.get(0).toJava(indent, tracer));
    }

    if (parameters.size() > 1) {
      buffer.append(" : ");
      buffer.append(parameters.get(1).toJava(indent, tracer));
    }

    return buffer;
  }
}
/*
 * Copyright 2000-2015 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jetbrains.java.decompiler.modules.decompiler.exps;

import org.jetbrains.java.decompiler.code.CodeConstants;
import org.jetbrains.java.decompiler.main.ClassesProcessor.ClassNode;
import org.jetbrains.java.decompiler.main.DecompilerContext;
import org.jetbrains.java.decompiler.main.TextBuffer;
import org.jetbrains.java.decompiler.main.collectors.BytecodeMappingTracer;
import org.jetbrains.java.decompiler.main.rels.MethodWrapper;
import org.jetbrains.java.decompiler.modules.decompiler.ExprProcessor;
import org.jetbrains.java.decompiler.modules.decompiler.vars.CheckTypesResult;
import org.jetbrains.java.decompiler.struct.attr.StructExceptionsAttribute;
import org.jetbrains.java.decompiler.struct.gen.VarType;
import org.jetbrains.java.decompiler.struct.match.MatchEngine;
import org.jetbrains.java.decompiler.struct.match.MatchNode;
import org.jetbrains.java.decompiler.struct.match.IMatchable.MatchProperties;
import org.jetbrains.java.decompiler.util.InterpreterUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class ExitExprent extends Exprent {

  public static final int EXIT_RETURN = 0;
  public static final int EXIT_THROW = 1;

  private final int exitType;
  private Exprent value;
  private final VarType retType;

  public ExitExprent(int exitType, Exprent value, VarType retType, Set<Integer> bytecodeOffsets) {
    super(EXPRENT_EXIT);
    this.exitType = exitType;
    this.value = value;
    this.retType = retType;

    addBytecodeOffsets(bytecodeOffsets);
  }

  @Override
  public Exprent copy() {
    return new ExitExprent(exitType, value == null ? null : value.copy(), retType, bytecode);
  }

  @Override
  public CheckTypesResult checkExprTypeBounds() {
    CheckTypesResult result = new CheckTypesResult();

    if (exitType == EXIT_RETURN && retType.type != CodeConstants.TYPE_VOID) {
      result.addMinTypeExprent(value, VarType.getMinTypeInFamily(retType.typeFamily));
      result.addMaxTypeExprent(value, retType);
    }

    return result;
  }

  @Override
  public List<Exprent> getAllExprents() {
    List<Exprent> lst = new ArrayList<Exprent>();
    if (value != null) {
      lst.add(value);
    }
    return lst;
  }

  @Override
  public TextBuffer toJava(int indent, BytecodeMappingTracer tracer) {
    tracer.addMapping(bytecode);

    if (exitType == EXIT_RETURN) {
      TextBuffer buffer = new TextBuffer();

      if (retType.type != CodeConstants.TYPE_VOID) {


from machine import Pin, ADC
from utime import ticks_ms

from ...urtps import Node

class Battery(Node):
    """
    Represents a battery module that measures the battery percentage.

    Args:
        battery_pin (int): The pin number connected to the battery voltage.
        delta_time (int): The time interval (in milliseconds) between battery percentage measurements.
        name (str, optional): The name of the battery module. Defaults to 'battery'.
        R1 (float, optional): The value of resistor R1 in the voltage divider circuit. Defaults to 100.0.
        R2 (float, optional): The value of resistor R2 in the voltage divider circuit. Defaults to 47.0.
    """

    def __init__(self, battery_pin, delta_time, name='battery', R1=100.0, R2=47.0) -> None:
        super().__init__(name, 'publishing')
        self.battery_adc = ADC(Pin(battery_pin))
        self.battery_percentage = 0
        self.ratio = (R1 + R2) / R2
        self.delta_time = delta_time
        self.last_time = ticks_ms()

    async def tick(self):
        """
        Measures the battery percentage at regular intervals.

        Returns:
            float: The current battery percentage.
        """
        self.set_message(None)
        time = ticks_ms()
        if time - self.last_time < self.delta_time:
            return
        self.last_time = time
        self.battery_percentage = self.battery_adc.read_u16() / 65535 * 3.3 * self.ratio
        self.set_message(self.battery_percentage)


s f32
        ))
    }
}

impl ElectrumLikeSync for Client {
    fn els_batch_script_get_history<'s, I: IntoIterator<Item = &'s Script>>(
        &self,
        scripts: I,
    ) -> Result<Vec<Vec<ELSGetHistoryRes>>, Error> {
        self.batch_script_get_history(scripts)
            .map(|v| {
                v.into_iter()
                    .map(|v| {
                        v.into_iter()
                            .map(
                                |electrum_client::GetHistoryRes {
                                     height, tx_hash, ..
                                 }| ELSGetHistoryRes {
                                    height,
                                    tx_hash,
                                },
                            )
                            .collect()
                    })
                    .collect()
            })
            .map_err(Error::Electrum)
    }

    fn els_batch_script_list_unspent<'s, I: IntoIterator<Item = &'s Script>>(
        &self,
        scripts: I,
    ) -> Result<Vec<Vec<ELSListUnspentRes>>, Error> {
        self.batch_script_list_unspent(scripts)
            .map(|v| {
                v.into_iter()
                    .map(|v| {
                        v.into_iter()
                            .map(
                                |electrum_client::ListUnspentRes {
                                     height,
                                     tx_hash,
                                     tx_pos,
                                     ..
                                 }| ELSListUnspentRes {
                                    height,
                                    tx_hash,
                                    tx_pos,
                                },
                            )
                            .collect()
                    })
                    .collect()
            })
            .map_err(Error::Electrum)
    }

    fn els_transaction_get(&self, txid: &Txid) -> Result<Transaction, Error> {
        self.transaction_get(txid).map_err(Error::Electrum)
    }
}

/// Configuration for an [`ElectrumBlockchain`]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct ElectrumBlockchainConfig {
    pub url: String,
    pub socks5: Option<String>,
}

impl ConfigurableBlockchain for ElectrumBlockchain {
    type Config = ElectrumBlockchainConfig;

    fn from_config(config: &Self::Config) -> Result<Self, Error> {
        Ok(ElectrumBlockchain(Client::new(
            config.url.as_str(),
            config.socks5.as_deref(),
        )?))
    }
}
// Copyright 2020-2021 The Datafuse Authors.
//
// SPDX-License-Identifier: Apache-2.0.

#[cfg(test)]
mod stream_datablock_test;

#[cfg(test)]
mod stream_progress_test;

mod stream;
mod stream_abort;
mod stream_datablock;
mod stream_limit_by;
mod stream_parquet;
mod stream_progress;
mod stream_skip;
mod stream_sort;
mod stream_take;

pub use stream::SendableDataBlockStream;
pub use stream_abort::AbortStream;
pub use stream_datablock::DataBlockStream;
pub use stream_limit_by::LimitByStream;
pub use stream_parquet::ParquetStream;
pub use stream_progress::ProgressStream;
pub use stream_skip::SkipStream;
pub use stream_sort::SortStream;
pub use stream_take::TakeStream;
<filename>src/field/intersection.rs<gh_stars>1-10
//! A field defined by the intersection of a pair of fields.

use cgmath::{Point3, Vector3};

use field;

#[allow(missing_docs)]
pub struct T ([Box<field::T>; 2]);

unsafe impl Send for T {}

#[allow(missing_docs)]


hence at most 64 hexadecimal digits
        ch = toupper(*cp++);    // process a hexadecimal digit
        if(ch >= '0' && ch <= '9')
            by = (by << 4) + ch - '0';
        else if(ch >= 'A' && ch <= 'F')
            by = (by << 4) + ch - 'A' + 10;
        else                    // error if not hexadecimal
        {
            printf("key must be in hexadecimal notation\n");
            err = -2; goto exit;
        }

        // store a key byte for each pair of hexadecimal digits
        if(i++ & 1)
            key[i / 2 - 1] = by & 0xff;
    }

    if(*cp)
    {
        printf("The key value is too long\n");
        err = -3; goto exit;
    }
    else if(i < 32 || (i & 15))
    {
        printf("The key length must be 32, 48 or 64 hexadecimal digits\n");
        err = -4; goto exit;
    }

    key_len = i / 2;

    if(!(fin = fopen(argv[1], "rb")))   // try to open the input file
    {
        printf("The input file: %s could not be opened\n", argv[1]);
        err = -5; goto exit;
    }

    if(!(fout = fopen(argv[2], "wb")))  // try to open the output file
    {
        printf("The output file: %s could not be opened\n", argv[2]);
        err = -6; goto exit;
    }

    if(toupper(*argv[3]) == 'E') // encryption in Cipher Block Chaining mode
    {   aes_encrypt_ctx ctx[1];

        aes_encrypt_key((unsigned char*)key, key_len, ctx);

        err = encfile(fin, fout, ctx);
    }
    else                         // decryption in Cipher Block Chaining mode
    {   aes_decrypt_ctx ctx[1];

        aes_decrypt_key((unsigned char*)key, key_len, ctx);

        err = decfile(fin, fout, ctx);
    }
exit:
    if(err == READ_ERROR)
        printf("Error reading from input file: %s\n", argv[1]);

    if(err == WRITE_ERROR)
        printf("Error writing to output file: %s\n", argv[2]);

    if(fout)
        fclose(fout);

    if(fin)
        fclose(fin);

    return err;
}


Event("CONTENT_TRACKING_UPDATE")
    end
    self:SetScript("OnEvent", OnEvent)

    self.header = CreateFrame("Button", nil, self, "GwQuestTrackerHeader")
    self.header.icon:SetTexCoord(0, 0.5, 0, 0.25)
    self.header.title:GwSetFontTemplate(DAMAGE_TEXT_FONT, GW.TextSizeType.HEADER)
    self.header.title:SetShadowOffset(1, -1)
    self.header.title:SetText(TRACKER_HEADER_ACHIEVEMENTS)

    self.collapsed = false
    self.header:SetScript("OnMouseDown", function() self:CollapseHeader() end) -- this way, otherwiese we have a wrong self at the function
    self.header.title:SetTextColor(
        TRACKER_TYPE_COLOR.ACHIEVEMENT.r,
        TRACKER_TYPE_COLOR.ACHIEVEMENT.g,
        TRACKER_TYPE_COLOR.ACHIEVEMENT.b
    )

    self.timedCriteria = {}
    self.blockMixInTemplate = GwAchievementTrackerBlockMixin

    self:UpdateLayout()
end


name("destination")
          .short("d")
          .long("destination")
          .value_name("DESTINATION")
          .help("Path to the directory of tarball and index files to use for tarball construction, and ultimate tarball write")
          .takes_value(true)
          .required(true)
        )
        .arg(Arg::with_name("file")
          .short("f")
          .long("file")
          .value_name("FILE")
          .help("File name to create in the destination directory")
          .takes_value(true)
          .required(true)
        )
      )
    )
    .get_matches();

  let result = if let Some(matches) = matches.subcommand_matches("index") {
    index(matches)
      .map_err(MainError::IndexError)
  } else if let Some(matches) = matches.subcommand_matches("transport") {
    transport(matches)
      .map_err(MainError::TransportError)
  } else {
    Err(MainError::UnknownCommand)
  };

  match result {
    Err(e) => panic!("{:#?}", e),
    _ => {}
  }
}

#[derive(Debug)]
enum IndexError {
  CreateIndex(io::Error),
  UnknownCommand,
}

fn index(matches: &clap::ArgMatches) -> Result<(), IndexError> {
  if let Some(matches) = matches.subcommand_matches("create") {
    create_index(matches)
      .map_err(IndexError::CreateIndex)
  } else {
    Err(IndexError::UnknownCommand)
  }
}

fn create_index(matches: &clap::ArgMatches) -> io::Result<()> {
  let tar_path = matches.value_of("file").expect("file arg required");
  let index_path = matches.value_of("output").expect("output arg required");

  let mut index_file = File::create(index_path)?;
  index_file.write_all(&index::create(tar_path)?)?;

  Ok(())
}

#[derive(Debug)]
enum TransportError {
  UploadIndex(upload::UploadIndexError),
  ReceiveIndex(receive::ReceiveIndexError),
  UnknownCommand,
}

fn transport(matches: &clap::ArgMatches) -> Result<(), TransportError> {
  if let Some(matches) = matches.subcommand_matches("upload-index") {
    let tar_path = matches.value_of("file").expect("file arg required");
    let index_path = matches.value_of("index").expect("index arg required");

    upload::upload_index(tar_path, index_path)
      .map_err(TransportError::UploadIndex)
  } else if let Some(matches) = matches.subcommand_matches("receive-index") {
    let destination_path = matches.value_of("destination").expect("destination arg required");
    let destination_file = matches.value_of("file").expect("file arg required");

    receive::receive_index(destination_path.as_ref(), destination_file)
      .map_err(TransportError::ReceiveIndex)
  } else {
    Err(TransportError::UnknownCommand)
  }
}
use std::path::Path;
use std::time::Duration;

static SCREEN_WIDTH: u32 = 640;
static SCREEN_HEIGHT: u32 = 480;

pub fn main() -> Result<(), String> {
    let args: Vec<_> = std::env::args().collect();

    Ok(())
}
<filename>src/rendering/mod.rs
//! Rendering in fumarole is handled by drawing 'Shapes' to the window.

mod rect;
mod anchor;
mod line;
mod ellipse;
mod image;
mod text;
mod traits;
mod frame;
mod mask;

pub use rect::*;
pub use anchor::*;
pub use line::*;
pub use ellipse::*;
pub use self::image::*;
pub use text::*;
pub use frame::*;
pub use mask::*;

use crate::


                              (iter, SONG_ID_COLUMN as i32)).unwrap();
            if changed_songs.contains(&id) {
                changed_songs.remove(&id);
                if let Some(song_ref) = logical::get_song_by_song_id(id) {
                    self.emplace_metadata(playlist_model, iter,
                                          playlist.get_columns(),
                                          &manual_songs,
                                          &song_ref.read().unwrap());
                }
                else {
                    did_ok = false;
                    return true
                }
            }
            changed_songs.is_empty()
        });
        match did_ok {
            true => {
                self.update_selected_songs();
                Ok(())
            },
            false => Err(anyhow!("A song got deleted out from under us?")),
        }
    }
    fn emplace_metadata(&self, playlist_model: &ListStore, iter: &TreeIter,
                        columns: &[playlist::Column],
                        manual_songs: &HashSet<SongID>,
                        song: &LogicalSong) {
        let metadata = song.get_metadata();
        playlist_model.set_value(&iter, SONG_IS_MANUAL_COLUMN,
                                 &manual_songs.contains(&song.get_id())
                                 .to_value());
        let mut column_index: u32 = SONG_FIRST_META_COLUMN;
        for column in columns {
            let s = if column.tag == "duration" {
                pretty_duration(song.get_duration()).to_value()
            }
            else {
                metadata.get(&column.tag).map(String::as_str)
                    .and_then(|x| if x.len() == 0 { None } else { Some(x)})
                    .to_value()
            };
            playlist_model.set_value(&iter, column_index, &s);
            column_index += 1;
        }
    }
    fn get_expanded_playlists(&mut self) -> Vec<PlaylistID> {
        let mut ret = Vec::new();
        self.playlists_view.map_expanded_rows(|_, wo| {
            self.playlists_model.get_iter(wo)
                .map(|x| self.playlists_model.get_value(&x, PLAYLIST_ID_COLUMN
                                                        as i32))
                .and_then(value_to_playlist_id)
                .map(|x| ret.push(x));
        });
        ret
    }
    fn expand_playlists(&mut self, mut playlist_ids: Vec<PlaylistID>) {
        self.playlists_model.foreach(|playlists_model, wo, iter| {
            let id = match value_to_playlist_id(playlists_model.get_value
                                                (&iter, PLAYLIST_ID_COLUMN
                                                 as i32)) {
                Some(x) => x,
                None => return playlist_ids.len() == 0,
            };
            for i in 0 .. playlist_ids.len() {
                if playlist_ids[i] == id {
                    playlist_ids.remove(i);
                    self.playlists_view.expand_row(wo, false);
                    break
                }
            }
            playlist_ids.len() == 0
        });
    }
    fn dragged_playlists_in_playlist_list(&mut self,
                                          data: &SelectionData,
                                          wo: TreePath,
                                          pos: TreeViewDropPosition,
                                          _time: u32) -> (bool, bool) {
        assert_eq!(data.get_format(), 8);
        assert_eq!(data


	vmovdqu64	zmm30, zmm29	 # AVX512F
	vmovdqu64.s	zmm30{k7}, zmm29	 # AVX512F
	vmovdqu64	zmm30{k7}, zmm29	 # AVX512F
	vmovdqu64.s	zmm30{k7}{z}, zmm29	 # AVX512F
	vmovdqu64	zmm30{k7}{z}, zmm29	 # AVX512F
	vmovq.s	rax, xmm30	 # AVX512F
	vmovq	rax, xmm30	 # AVX512F
	vmovq.s	r8, xmm30	 # AVX512F
	vmovq	r8, xmm30	 # AVX512F
	vmovq.s	xmm30, xmm29	 # AVX512F
	vmovq	xmm30, xmm29	 # AVX512F
	vmovsd.s	xmm30{k7}, xmm29, xmm28	 # AVX512F
	vmovsd	xmm30{k7}, xmm29, xmm28	 # AVX512F
	vmovsd.s	xmm30{k7}{z}, xmm29, xmm28	 # AVX512F
	vmovsd	xmm30{k7}{z}, xmm29, xmm28	 # AVX512F
	vmovss.s	xmm30{k7}, xmm29, xmm28	 # AVX512F
	vmovss	xmm30{k7}, xmm29, xmm28	 # AVX512F
	vmovss.s	xmm30{k7}{z}, xmm29, xmm28	 # AVX512F
	vmovss	xmm30{k7}{z}, xmm29, xmm28	 # AVX512F
	vmovupd.s	zmm30, zmm29	 # AVX512F
	vmovupd	zmm30, zmm29	 # AVX512F
	vmovupd.s	zmm30{k7}, zmm29	 # AVX512F
	vmovupd	zmm30{k7}, zmm29	 # AVX512F
	vmovupd.s	zmm30{k7}{z}, zmm29	 # AVX512F
	vmovupd	zmm30{k7}{z}, zmm29	 # AVX512F
	vmovups.s	zmm30, zmm29	 # AVX512F
	vmovups	zmm30, zmm29	 # AVX512F
	vmovups.s	zmm30{k7}, zmm29	 # AVX512F
	vmovups	zmm30{k7}, zmm29	 # AVX512F
	vmovups.s	zmm30{k7}{z}, zmm29	 # AVX512F
	vmovups	zmm30{k7}{z}, zmm29	 # AVX512F


        for (var i = 1; i < stroke.length - 1; i++) {
          final p0 = stroke[i];
          final p1 = stroke[i + 1];
          final midPoint = Offset(
            (p0.dx + p1.dx) / 2,
            (p0.dy + p1.dy) / 2,
          );
          path.quadraticBezierTo(p0.dx, p0.dy, midPoint.dx, midPoint.dy);
        }
      }

      canvas.drawPath(path, paint);
    }
  }

  @override
  bool shouldRepaint(CharacterPainter oldDelegate) {
    return true;
  }
}
// Flutter imports:
import 'package:flutter/material.dart';

// Package imports:
import 'package:streaming_shared_preferences/streaming_shared_preferences.dart';

// Project imports:
import 'package:words625/di/injection.dart';
import 'package:words625/domain/auth/firebase_user.dart';
import 'package:words625/service/locator.dart';

class AccountAppBar extends StatelessWidget implements PreferredSizeWidget {
  const AccountAppBar({Key? key}) : super(key: key);

  @override
  Size get preferredSize => const Size.fromHeight(75);

  @override
  Widget build(BuildContext context) {
    return const AccountWidget();
  }
}

class AccountWidget extends StatelessWidget {
  const AccountWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(left: 12, top: 16, right: 12),
      child: PreferenceBuilder<SerializableFirebaseUser?>(
        preference: getIt<AppPrefs>().authUser,
        builder: (BuildContext context, SerializableFirebaseUser? user) {
          // Default values if user is null
          final displayName = user?.displayName ?? 'Guest';
          final email = user?.email ?? 'No email';
          final profileImage =
              user?.photoUrl ?? 'https://example.com/default_avatar.png';

          return Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      displayName,
                      style: const TextStyle(
                        fontSize: 25,
                        fontWeight: FontWeight.bold,
                        color: Color(0xFF4B4B4B),
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      email,
                      style: const TextStyle(
                        fontSize: 15,
                        color: Color(0xFFAFAFAF),
                      ),
                    ),
                  ),
                ],
              ),
              CircleAvatar(
                radius: 26,
                backgroundImage: NetworkImage(profileImage),
                onBackgroundImageError: (_, __) => const Icon(
                    Icons.account_circle,
                    size: 60,
                    color: Colors.grey),
              ),
            ],
          );
        },
      ),
    );
  }
}
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:http/io_client.dart' as http;
import 'package:material_symbols_icons/symbols.dart';
import 'package:nextcloud/nextcloud.dart';
import 'package:nextcloud/notes.dart';
import 'package:scrawler/src/helpers/avatar_color.dart';
import 'package:scrawler/src/screens/settings_page.dart';
i


        self.outputs[id as usize] = Some(device);
    }
}

#[cfg(test)]
mod tests {
    use super::super::cpu::Cpu;
    use intel8080cpu::{Intel8080Cpu, State, ROM_MEMORY_LIMIT};

    #[test]
    fn it_should_execute_instruction_when_running() {
        let mut cpu = Intel8080Cpu::new([0; ROM_MEMORY_LIMIT]);
        cpu.state = State::Running;
        cpu.pc = 0;
        cpu.memory[0] = 0x00;
        cpu.execute().unwrap();
        assert_eq!(cpu.pc, 0x01);
    }

    #[test]
    fn it_shouldnt_execute_instruction_when_stopped() {
        let mut cpu = Intel8080Cpu::new([0; ROM_MEMORY_LIMIT]);
        cpu.state = State::Stopped;
        cpu.pc = 0;
        cpu.memory[0] = 0x00;
        cpu.execute().unwrap();
        assert_eq!(cpu.pc, 0x00);
    }
}
<gh_stars>1-10
use super::address::PhysAddr;
use super::address::PhysPageNum;
use crate::config::ekernel;
use crate::config::MEMORY_END;
use crate::sync::UniProcSafeCell;
use alloc::vec::Vec;
use lazy_static::lazy_static;

trait FrameAllocator {
    fn new() -> Self;
    fn alloc(&mut self) -> Option<PhysPageNum>;
    fn dealloc(&mut self, ppn: PhysPageNum);
}

/// # physical frame allocator
/// alloc physical frame from ram
///
/// ## alloc
/// @return `Option<PhysPageNum>`
///
/// We use a simple stack to alloc frame.
/// - if user return frame, push it into a vector
/// - if there is no frame that return, from user, `cur++`
/// - if there is some frames released, use it from vector
///
/// ## dealloc
/// release PhysPageNum
///
pub struct StackFrameAllocator {
    cur: usize,
    end: usize,
    recycled: Vec<usize>,
}

impl StackFrameAllocator {
    pub fn init(&mut self, l: PhysPageNum, r: PhysPageNum) {
        self.cur = l.0;
        self.end = r.0;
    }
    pub fn empty(&self) -> bool {
        self.cur == self.end
    }

    fn is_valid(&self, ppn: PhysPageNum) -> bool {
        let ppn = ppn.0;
        ppn < self.cur && !self.recycled.iter().any(|v| *v == ppn)
    }
}

impl FrameAllocator for StackFrameAllocator {
    fn new() -> Self {
        Self {
            cur: 0,
            end: 0,
            recycled: Vec::new(),
        }
    }

    fn alloc(&mut self) -> Option<PhysPageNum> {
        if let Some(ppn) = self.recycled.pop() {
            Some(ppn.into())
        } else if self.empty() {
            None
        } else {
            self.cur += 1;
            Some((self.cur - 1).into())
        }
    }

    fn dealloc(&mut self, ppn: PhysPageNum) {
        if self.is_valid(ppn) {
            let ppn = ppn.0;
            self.recycled.push(ppn);
        } else {
            panic!("Frame ppn={:#x} hasn't been allocated", ppn.0);
        }
    }
}

type FrameAllocatorImpl = StackFrameAllocator;

lazy_static! {
    pub static ref FRAME_ALLOCATOR: UniProcSafeCell<FrameAllocatorImpl> =
        UniProcSafeCell::new(FrameAllocatorImpl::new());
}

// pub interface
pub fn init() {
    FRAME_ALLOCATOR.borrow_mut().init(
        PhysAddr::from(ekernel as usize).ceil(),
        PhysAddr::from(MEMORY_END).floor(),
    )
}

pub fn frame_alloc() -> Option<FrameTracker> {
    FRAME_ALLOCATOR.borrow_mut().alloc().map(FrameTracker::new)
}

// do not use outside
pub fn frame_dealloc(ppn: PhysPage


sourceNoteId: {type: String},
  parentNoteId: {type: String, default: 'top'},
  index: {type: Number, default: 0},
};

const NoteSchema = new mongoose.Schema<Note['Model']>(noteSchema);

export default mongoose.model<INoteDocument>('Note', NoteSchema);
import SSManager = require("./SSManager");

class ShockingMoleLoadingScene extends g.LoadingScene {
    private loadingMole: SSManager; // シーンに表示されるモグラ
    private loading: SSManager;     // シーンに表示されるNOWLOADING

    constructor(param: g.LoadingSceneParameterObject) {
        super({ game: param.game, assetIds: [].concat(["mogura"], "pj_mole1", ["an_1_in", "an_1_out", "an_1_damage", "an_1_dead", "an_1_wait_1", "an_1_wait_2", "an_1_wait_3", "an_1_wait"], ["bn_mole1"], ["sk_1_mogura"], ["pj_nowloading"], ["an_loading"], ["bn_nowloading"], ["sk_mogura"]) });
        this.loaded.handle(this, this._onLoaded);
        this._load();
        this.update.handle(this, this.Update);
    }

    // ロード
    _onLoaded(): boolean {
        const bg = new g.FilledRect({ scene: this, width: g.game.width, height: g.game.height, cssColor: "black" });
        this.append(bg);

        this.loadingMole = new SSManager(["mogura"], "pj_mole1", ["an_1_in", "an_1_out", "an_1_damage", "an_1_dead", "an_1_wait_1", "an_1_wait_2", "an_1_wait_3", "an_1_wait"], ["bn_mole1"], ["sk_1_mogura"], ["mogura"], "mole1", 145, 185);
        this.loadingMole.Load(this, "wait_3", g.game.width / 2, (g.game.height / 2) + 50);

        this.loading = new SSManager(["mogura"], "pj_nowloading", ["an_loading"], ["bn_nowloading"], ["sk_mogura"], ["mogura"], "nowloading", 640, 360);
        this.loading.Load(this, "loading", g.game.width / 2, (g.game.height / 2));
        return true;
    }

    // 更新
    Update(): void {
        this.loadingMole.Update();
        this.loading.Update();
    }
};

export = ShockingMoleLoadingScene;
import { processHeaders, flattenHeaders, parseHeaders } from '../../src/helper/headers'

describe('helpers:headers', () => {
  describe('parseHeaders', () => {
    test('处理响应 headers 转化', () => {
      const res = parseHeaders(
        'Cache-Control: public, max-age=0\r\n' +
          'Connection: keep-alive\r\n' +
          'Content-Length: 311\r\n' +
          'Content-Type: text/html; charset=UTF-8\r\n' +
          'key\r\n' +
          ':aa\r\n' +
          'hecun: 1 \r\n' +
          'hecun1:\r\n' +
          'Date: Sun, 01 Dec 2019 02:43:29 GMT'
      )
      expect(res['cache-control']).toBe('public, max-age=0')
      expect(res['connection']).toBe('keep-alive')
      expect(res['date']).toEqual('Sun, 01 Dec 2019 02:43:29 GMT')
      expect(res['key']).toBeUndefined()
      expect(res['hecun']).toEqual('1')
      expect(res['hecun1']).toBeUndefined()
      expect(parseHeaders('')).toEqual({})
    })
  })

  describe('processHeaders', () => {
    test('处理请求 headers 配置', () => {
      expect(processHeaders({}, {})['Content-Type']).toEqual('application/json;charset=utf-8')

      expect(processHeaders(un


local map = ...
-- Dungeon 10 B1

local water_delay = 500 -- delay between each water step

local function set_water_drained()

  map:set_entities_enabled("water_tile", false)

  -- enable the custom obstacles near stairs (stairs can be used)
  map:set_entities_enabled("water_off_obstacle", true)

  -- disable the jumper placed over stairs (there is no water to jump into)
  map:set_entities_enabled("water_on_jumper", false)
end

local drain_water_step_1, drain_water_step_2, drain_water_step_3, drain_water_step_4

function drain_water_step_1()

  sol.audio.play_sound("water_drain_begin")
  sol.audio.play_sound("water_drain")
  water_tile_full:set_enabled(false)
  water_tile_less_1:set_enabled(true)
  sol.timer.start(water_delay, drain_water_step_2)
end

function drain_water_step_2()

  water_tile_less_1:set_enabled(false)
  water_tile_less_2:set_enabled(true)
  sol.timer.start(water_delay, drain_water_step_3)
end

function drain_water_step_3()

  water_tile_less_2:set_enabled(false)
  water_tile_less_3:set_enabled(true)
  sol.timer.start(water_delay, drain_water_step_4)
end

function drain_water_step_4()

  water_tile_less_3:set_enabled(false)
  map:get_game():set_value("b297", true)
  sol.audio.play_sound("secret")
  set_water_drained()
end

function map:on_started(destination)

  if map:get_ga


                      i,
                            len(iterable),
                            eta=eta_string,
                            meters=str(self),
                            time=str(iter_time),
                            data=str(data_time),
                            memory=torch.cuda.max_memory_allocated() / MB,
                        )
                    )
                else:
                    print(
                        log_msg.format(
                            i,
                            len(iterable),
                            eta=eta_string,
                            meters=str(self),
                            time=str(iter_time),
                            data=str(data_time),
                        )
                    )
            i += 1
            end = time.time()
        total_time = time.time() - start_time
        total_time_str = str(datetime.timedelta(seconds=int(total_time)))
        print(
            "{} Total time: {} ({:.4f} s / it)".format(
                header, total_time_str, total_time / len(iterable)
            )
        )

class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

def setup_logger():
    logging.basicConfig(
        level=logging.INFO if dist_utils.is_main_process() else logging.WARN,
        format="%(asctime)s [%(levelname)s] %(message)s",
        handlers=[logging.StreamHandler()],
    )


efs": [{ "id": "ref-for-descdef-font-face-src\u2467" }], "title": "7.3. \nFeature precedence examples" }, { "refs": [{ "id": "ref-for-descdef-font-face-src\u2468" }], "title": "11.1. Font tech" }], "url": "#descdef-font-face-src" },
                "descdef-font-face-unicode-range": { "dfnID": "descdef-font-face-unicode-range", "dfnText": "unicode-range", "external": false, "refSections": [{ "refs": [{ "id": "ref-for-descdef-font-face-unicode-range" }, { "id": "ref-for-descdef-font-face-unicode-range\u2460" }, { "id": "ref-for-descdef-font-face-unicode-range\u2461" }, { "id": "ref-for-descdef-font-face-unicode-range\u2462" }], "title": "4.5. \nCharacter range: the unicode-range descriptor" }, { "refs": [{ "id": "ref-for-descdef-font-face-unicode-range\u2463" }, { "id": "ref-for-descdef-font-face-unicode-range\u2464" }, { "id": "ref-for-descdef-font-face-unicode-range\u2465" }, { "id": "ref-for-descdef-font-face-unicode-range\u2466" }], "title": "5.2. Matching font styles" }, { "refs": [{ "id": "ref-for-descdef-font-face-unicode-range\u2467" }], "title": "9.2. \nUser-defined font color palettes: The @font-palette-values rule" }], "url": "#descdef-font-face-unicode-range" },
                "descdef-font-feature-values-font-display": { "dfnID": "descdef-font-feature-values-font-display", "dfnText": "font-display", "external": false, "refSections": [{ "refs": [{ "id": "ref-for-descdef-font-feature-values-font-display" }, { "id": "ref-for-descdef-font-feature-values-font-display\u2460" }, { "id": "ref-for-descdef-font-feature-values-font-display\u2461" }], "title": "4.9.1. \nControlling Font Display Per Font-Family via @font-feature-values" }, { "refs": [{ "id": "ref-for-descdef-font-feature-values-font-display\u2462" }], "title": "6.9.1. Basic syntax" }], "url": "#descdef-font-feature-values-font-display" },
                "descdef-font-palette-values-base-palette": { "dfnID": "descdef-font-palette-values-base-palette", "dfnText": "base-palette", "external": false, "refSections": [{ "refs": [{ "id": "ref-for-descdef-font-palette-values-base-palette" }], "title": "9.2. \nUser-defined font color palettes: The @font-palette-values rule" }, { "refs": [{ "id": "ref-for-descdef-font-palette-values-base-palette\u2460" }], "title": "9.2.2. \nSpecifying the base palette: the base-palette descriptor" }], "url": "#descdef-font-palette-values-base-palette" },
                "descdef-font-palette-values-font-family": { "dfnID": "descdef-font-palette-values-font-family", "dfnText": "font-family", "external": false, "refSections": [{ "refs": [{ "id": "ref-for-descdef-font-palette-values-font-family" }], "title": "9.2. \nUser-defined font color pal


units_of_Tc(2).to_ul_rtoa(1), 492513);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(3).to_ul_rtoa(1), 492514);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(4).to_ul_rtoa(1), 492514);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(5).to_ul_rtoa(1), 492515);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(6).to_ul_rtoa(1), 492515);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(985023).to_ul_rtoa(1), 985024);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(985024).to_ul_rtoa(1), 985024);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(985025).to_ul_rtoa(1), 985025);

  // Use TS38.133 Table 13.1.1-3 entries as test points.
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(-985025).to_ul_rtoa(2), 0);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(-985024).to_ul_rtoa(2), 1);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(-985021).to_ul_rtoa(2), 1);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(-985020).to_ul_rtoa(2), 2);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(-985017).to_ul_rtoa(2), 2);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(-8).to_ul_rtoa(2), 246255);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(-5).to_ul_rtoa(2), 246255);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(-4).to_ul_rtoa(2), 246256);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(-1).to_ul_rtoa(2), 246256);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(0).to_ul_rtoa(2), 246256);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(1).to_ul_rtoa(2), 246257);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(4).to_ul_rtoa(2), 246257);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(5).to_ul_rtoa(2), 246258);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(8).to_ul_rtoa(2), 246258);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(9).to_ul_rtoa(2), 246259);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(12).to_ul_rtoa(2), 246259);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(985021).to_ul_rtoa(2), 492512);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(985024).to_ul_rtoa(2), 492512);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(985025).to_ul_rtoa(2), 492513);

  // Use TS38.133 Table 13.1.1-4 entries as test points.
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(-985025).to_ul_rtoa(3), 0);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(-985024).to_ul_rtoa(3), 1);
  ASSERT_EQ(phy_time_unit::from_units_of_Tc(-985017).to_ul_rtoa


		node[0].subWorlds = [];
	}
	for (const world of node[0].subWorlds) {
		if (world.name === current) {
			findSpot(level, newPath, [world]);
			return;
		}
	}
	const world: IWorld = {
		name: current,
	};
	node[0].subWorlds.push(world);
	findSpot(level, newPath, [world]);
}

export default organizeWorlds;
import Listener from "./Listener"
import Match from "../Models/Match"
import { Client, VoiceChannel } from "discord.js"
import bot from "../bot"
import _ from "lodash"

export default class DeleteMatchVoiceChannels extends Listener {
    async handle({ match }: { match: Match }) {
        const client = <Client>bot.getClient()
        const guild = await client.guilds.find(
            guild => guild.id === match.guildId,
        )

        if (!guild) {
            console.log("Unable to find guild to create voice channels")
            return
        }

        const voiceChannels = guild.channels.filter(
            channel => channel.type === "voice",
        )
        const matchChannels = voiceChannels
            .filter(channel => _.includes(channel.name, `Match #${match.id}`))
            .array()

        matchChannels.forEach((matchChannel: VoiceChannel) => {
            const members = matchChannel.members.array()
            console.log("members", members)

            if (members.length) {
                console.log("Prevented not empty voice channel from removing")
                return
            }

            matchChannel.delete()
        })
    }
}
/*
============================================
; Title:  kimberlin-assignment-4.2
; Author: Professor Krasso
; Date:   January 25 2021
; Modified By: Rhiannon Kimberlin
; Description: di-Composer-app
;===========================================
*/

//Generated by Angular CLI
import { Injectable } from '@angular/core';
//Importing iComposer from composer.interfacec
import { IComposer } from './composer.interface';

@Injectable({
  providedIn: 'root'
})
export class ComposerService {
    composers:Array<IComposer>;

    //Defined Composers to retrieve
    constructor() {
        this.composers = [
        {
            composerId: 100, fullName: "Ludwig van Beethoven", genre: "Classical"
        },
        {
            composerId: 101, fullName: "Fryderyck Chopin", genre: "Classical"
        },
        {
            composerId: 102, fullName: "Johannes Brahm", genre: "Classical"
        },
        {
            composerId: 103, fullName: "Johann Bach", genre: "Classical"
        },
        {
            composerId: 104, fullName: "Wolfgang Mozart", genre: "Classical"
        },
    ]};

getComposers(){
    return this.composers;
};

//Returns composer matching with ID if ID matches a composer
getComposer(composerId: number){
    for(let composer of this.composers) {
        if (composer.composerId === composerId){
            return composer;
        }
    }
}
};import { TNavMenuItem } from '@financial-times/dotcom-types-navigation'

const isSelected = (url: string, currentPath: string): boolean => {
  return url === currentPath
}

const isMenuItem = (item: any): boolean => {
  return item.hasOwnProperty('label') && item.hasOwnProperty('url')
}

const decorateURL = (url: string, currentPath: string): string => {
  if (url && url.includes('${currentPath}')) {
    // Don't replace the URL placeholder with a barrier or error URL so that
    // a user logging in is not redirected to a barrier


 as I don't feel ok with people being able to remove these
    //node.fields.removeIf { fieldNode: FieldNode -> removeIfDevMixin(fieldNode.visibleAnnotations) }

    return ClassWriter(0).also { node.accept(it) }.toByteArray()
}

fun removeIfDevMixin(nodeName: String, visibleAnnotations: List<AnnotationNode>?): Boolean {
    // Don't remove methods if it's not a GHA build/Release build
    if (!removeDevMixinAnyway && buildNumber == null && !nodeName.lowercase(Locale.ROOT).matches(Regex(".*\\/mixin\\/.*Mixin")))
        return false

    if (visibleAnnotations != null) {
        for (annotationNode in visibleAnnotations) {
            if (annotationNode.desc == "Lcom/railwayteam/railways/annotation/mixin/DevEnvMixin;")
                return true
        }
    }

    return false
}

fun <T> getValueFromAnnotation(annotation: AnnotationNode?, key: String): T? {
    var getNextValue = false

    if (annotation?.values == null) {
        return null
    }

    // Keys and value are stored in successive pairs, search for the key and if found return the following entry
    for (value in annotation.values) {
        if (getNextValue) {
            @Suppress("UNCHECKED_CAST")
            return value as T
        }
        if (value == key) {
            getNextValue = true
        }
    }

    return null
}

tasks.create("railwaysPublish") {
    when (val platform = System.getenv("PLATFORM")) {
        "both" -> {
            dependsOn(tasks.build, ":fabric:publish", ":forge:publish", ":common:publish", ":fabric:publishMods", ":forge:publishMods")
        }
        "fabric", "forge" -> {
            dependsOn("${platform}:build", "${platform}:publish", "${platform}:publishMods")
        }
    }
}

fun Project.setupRepositories() {
    repositories {
        mavenCentral()
        maven("https://maven.shedaniel.me/") // Cloth Config, REI
        maven("https://maven.blamejared.com/") // JEI, Hex Casting
        exclusiveMaven("https://maven.parchmentmc.org", "org.parchmentmc.data") // Parchment mappings
        exclusiveMaven("https://maven.quiltmc.org/repository/release", "org.quiltmc") // Quilt Mappings
        maven("https://jm.gserv.me/repository/maven-public/") // JourneyMap API
        exclusiveMaven("https://api.modrinth.com/maven", "maven.modrinth") // LazyDFU, JourneyMap
        exclusiveMaven("https://cursemaven.com", "curse.maven")
        maven("https://maven.theillusivec4.top/") // Curios
        maven("https://maven.tterrag.com/") { // Flywheel, Registrate, Create
            content {
                includeGroup("com.simibubi.create")
                includeGroup("com.tterrag.registrate")
                includeGroup("com.jozufozu.flywheel")
            }
        }
        maven("https://maven.maxhenkel.de/repository/public") // Simple Voice Chat
        maven("https://maven.jamieswhiteshirt.com/libs-release") // Reach Entity Attributes
        exclusiveMaven("https://thedarkcolour.github.io/KotlinForForge/", "thedarkcolour") // KFF (Hex Casting dependency)
        maven("https://maven.terraformersmc.com/releases/") // Mod Menu, EMI
        maven("https://mvn.devos.one/snapshots/") // Create Fabric, Porting Lib, Forge Tags, Milk Lib, Registrate Fabric
        maven("https://mvn.devos.one/releases/") // Porting Lib
        maven("https://maven.cafeteria.dev/releases") // Fake Player API
        maven("https://raw.githubusercontent.com/Fuzss


hr_talkingboard_auth',
        categories: const [],
        searchKeys: const [
          'bundeswehr_talkingboard_auth',
          'bundeswehr_talkingboard',
        ]),
    GCWTool(
        tool: const BundeswehrTalkingBoardObfuscation(),
        id: 'bundeswehr_talkingboard_code',
        categories: const [],
        searchKeys: const [
          'bundeswehr_talkingboard',
          'bundeswehr_talkingboard_code',
        ]),

    //Braille Selection ****************************************************************
    GCWTool(tool: const Braille(), id: 'braille', searchKeys: const [
      'braille',
      'symbol_fakoo'
    ], licenses: const []),
    GCWTool(
        tool: const BrailleDotNumbers(),
        id: 'brailledotnumbers',
        searchKeys: const [
          'braille',
          'symbol_fakoo'
        ],
        licenses: [
          ToolLicenseOnlineArticle(
              context: context,
              author: 'Alexander Fakoó',
              title: '9-Punkt-Decoder',
              sourceUrl:
                'https://web.archive.org/web/20240415000000*/https://fakoo.de/fakoo/9-punkt-decoder.html',
              licenseType: ToolLicenseType.CCBYNCND40,
              licenseUrl:
                'https://web.archive.org/web/20240415000000*/https://creativecommons.org/licenses/by-nc-nd/4.0/deed.de')
    ]),

    //CCITT Selection **********************************************************************************************
    GCWTool(
        tool: const CCITT1(),
        id: 'ccitt_1',
        searchKeys: const ['ccitt', 'ccitt_1', 'symbol_baudot']),
    GCWTool(tool: const CCITT2(), id: 'ccitt_2', searchKeys: const [
      'ccitt',
      'ccitt_2',
      'teletypewriter',
      'symbol_murraybaudot',
    ]),
    GCWTool(tool: const CCITT3(), id: 'ccitt_3', searchKeys: const [
      'ccitt',
      'ccitt_3',
      'teletypewriter',
    ]),
    GCWTool(tool: const CCITT4(), id: 'ccitt_4', searchKeys: const [
      'ccitt',
      'ccitt_4',
      'teletypewriter',
    ]),
    GCWTool(tool: const CCITT5(), id: 'ccitt_5', searchKeys: const [
      'ccitt',
      'ccitt_5',
      'teletypewriter',
    ]),
    GCWTool(tool: const CCIR476(), id: 'ccitt_ccir476', searchKeys: const [
      'ccitt',
      'ccitt_ccir_476',
      'teletypewriter',
    ]),

    //CheckDigitsSelection  ********************************************************************************************
    GCWTool(
        tool: const CheckDigitsCreditCardSelection(),
        id: 'checkdigits_creditcard_selection',
        searchKeys: const ['checkdigits']),
    GCWTool(
        tool: const CheckDigitsDETaxIDSelection(),
        id: 'checkdigits_de_taxid_selection',
        searchKeys: const ['checkdigits', 'checkdigits_de_taxid']),
    GCWTool(
      tool: const CheckDigitsEANSelection(),
      id: 'checkdigits_ean_selection',
      searchKeys: const ['checkdigits', 'checkdigits_ean'],
    ),
    GCWTool(
        tool: const CheckDigitsIBANSelection(),
        id: 'checkdigits_iban_selection',
        searchKeys: const ['checkdigits', 'checkdigits_iban']),
    GCWTool(
        tool: const CheckDigitsIMEISelection(),


Tiles = [
	[0, -1],
	[-1, -1],
	[-1, 0],
	[-1, 1],
	[0, 1],
	[1, 1],
	[1, 0],
	[1, -1],
];
const roomCorners = [
	[[1, 1], [1, 2], [2, 1]],
	[[48, 1], [48, 2], [47, 1]],
	[[1, 48], [1, 47], [2, 48]],
	[[48, 48], [48, 47], [47, 48]],
];

/**
 * Generates an array representation of room terrain.
 *
 * @param {string} roomName
 *   Name of the room for which to use terrain data.
 * @param {object} bounds
 *   Bounds of the room.
 *
 * @todo Check if bounds parameter makes any sense.
 */
function generateRoomTerrainArray(roomName, bounds = {x1: 0, y1: 0, x2: 49, y2: 49}) {
	// Create two dimensional array of room tiles.
	const roomArray = Array.from({length: 50}).fill(0).map(() => Array.from({length: 50}).fill(UNWALKABLE)) as number[][];

	const terrain = Game.map.getRoomTerrain(roomName);
	for (let x = bounds.x1; x <= bounds.x2; x++) {
		for (let y = bounds.y1; y <= bounds.y2; y++) {
			if (terrain.get(x, y) !== TERRAIN_MASK_WALL) {
				roomArray[x][y] = NORMAL;

				if (x === 0 || y === 0 || x === 49 || y === 49) {
					// Mark exit tiles.
					roomArray[x][y] = EXIT;
				}
			}
		}
	}

	// Mark tiles near exits as sinks - walls / ramparts may not be built there.
	for (let y = 1; y < 49; y++) {
		if (
			roomArray[0][y - 1] === EXIT ||
			roomArray[0][y] === EXIT ||
			roomArray[0][y + 1] === EXIT
		) {
			roomArray[1][y] = TO_EXIT;
		}
		if (
			roomArray[49][y - 1] === EXIT ||
			roomArray[49][y] === EXIT ||
			roomArray[49][y + 1] === EXIT
		) {
			roomArray[48][y] = TO_EXIT;
		}
	}

	for (let x = 1; x < 49; x++) {
		if (
			roomArray[x - 1][0] === EXIT ||
			roomArray[x][0] === EXIT ||
			roomArray[x + 1][0] === EXIT
		) {
			roomArray[x][1] = TO_EXIT;
		}
		if (
			roomArray[x - 1][49] === EXIT ||
			roomArray[x][49] === EXIT ||
			roomArray[x + 1][49] === EXIT
		) {
			roomArray[x][48] = TO_EXIT;
		}
	}

	addProtectedExitsToRoomArray(roomArray, bounds);
	modifyProblematicProtectedExits(roomArray);

	// Mark border tiles as not usable.
	for (let y = 1; y < 49; y++) {
		roomArray[0][y] = UNWALKABLE;
		roomArray[49][y] = UNWALKABLE;
	}

	for (let x = 1; x < 49; x++) {
		roomArray[x][0] = UNWALKABLE;
		roomArray[x][49] = UNWALKABLE;
	}

	return roomArray;
}

let protectedExitTiles: Record<string, boolean>;

/**
 * Marks protected exits.
 */
function addProtectedExitsToRoomArray(roomArray: number[][], bounds: MinCutRect) {
	protectedExitTiles = {};

	if (bounds.protectTopExits) {
		for (let x = 1; x < 49; x++) {
			protectExitTile(roomArray, x, 1);
		}
	}

	if (bounds.protectBottomExits) {
		for (let x = 1; x < 49; x++) {
			protectExitTile(roomArray, x, 48);
		}
	}

	if (bounds.protectLeftExits) {
		for (let y = 1; y < 49; y++) {
			protectExitTile(roomArray, 1, y);
		}
	}

	if (bounds.protectRightExits) {
		for (let y = 1; y < 49; y++) {
			protectExitTile(roomArray, 48, y);
		}
	}
}

function protectExitTile(roomArray, x: number, y: number) {
	if (roomArray[x][y] !== TO_EXIT) return;