8,generador9,generador10,generador11,generador12,generador13,generador14,generador15,generador16,generador17,generador18,generador19];

//Variables de control para utilizar en el controlador de generadores de tipo 1
let numeroGeneradoresTipoUno = generadoresTipoUno.length;
let totalPotencia = 0;
let contadorGeneradoresUno = 0;
//Función que permite monitorear la potencia total dependiendo del estado de los generadores tipo 1
function controlGeneradoresTipoUno() {
    while (numeroGeneradoresTipoUno > 0)
    {
        if (generadoresTipoUno[contadorGeneradoresUno].mEstado === "apagado")
        {
            console.log(`Generador #${generadoresTipoUno[contadorGeneradoresUno].mNumero} esta ${generadoresTipoUno[contadorGeneradoresUno].mEstado}.`);
            contadorGeneradoresUno++;
            numeroGeneradoresTipoUno--;
        }
        else {
            totalPotencia = totalPotencia + generadoresTipoUno[contadorGeneradoresUno].mPotencia;
            console.log(`Generador #${generadoresTipoUno[contadorGeneradoresUno].mNumero} esta ${generadoresTipoUno[contadorGeneradoresUno].mEstado}, añadiendo ${generadoresTipoUno[contadorGeneradoresUno].mPotencia} MW para un total de ${totalPotencia} MW.`);
            contadorGeneradoresUno++;
            numeroGeneradoresTipoUno--;
        }
    }
}
//Función que permite monitorear la potencia total dependiendo del estado de los generadores tipo 2
function controlGeneradoresTipoDos(){
    for (let contadorGeneradoresDos in generadoresTipoDos)
    {
        if (generadoresTipoDos[contadorGeneradoresDos].mEstado === "apagado")
        {
            console.log(`Generador #${generadoresTipoDos[contadorGeneradoresDos].mNumero} esta ${generadoresTipoDos[contadorGeneradoresDos].mEstado}.`);
        }
        else {
            totalPotencia = totalPotencia + generadoresTipoDos[contadorGeneradoresUno].mPotencia;
            console.log(`Generador #${generadoresTipoDos[contadorGeneradoresDos].mNumero} esta ${generadoresTipoDos[contadorGeneradoresDos].mEstado}, añadiendo ${generadoresTipoDos[contadorGeneradoresDos].mPotencia} MW para un total de ${totalPotencia} MW.`);
        }
    }
}
//función encargada de controlar el estado de todos los generadores
function controlGeneradores()
{
    controlGeneradoresTipoUno();
    controlGeneradoresTipoDos();
}
//Función encargada de encender los generadores que tengan un numero par
function prenderGeneradoresPares()
{
    for (let contador in generadoresTipoUno)
    {
        if (!(generadoresTipoUno[contador].mNumero%2))
            generadoresTipoUno[contador].mEstado = "prendido";
    }
    for (let contador2 in generadoresTipoDos)
    {
        if (!(generadoresTipoDos[contador2].mNumero%2))
            generadoresTipoDos[contador2].mEstado = "prendido";
    }
}
//Función encargada de encender los generadores que tengan un numero impar
function prenderGeneradoresImpares()
{
    for (let contador in generadoresTipoUno)
    {
        if (generadoresTipoUno[contador].mNumero%2)
            generadoresTipoUno[contador].mEstado = "prendido";
    }


5">#3F51B5</xy-button>

button

normal

    <xy-button type="primary" id="btn">primary</xy-button>
    <xy-button type="dashed">dashed</xy-button>
    <xy-button type="flat">flat</xy-button>
    <xy-button>default</xy-button>
    <xy-button type="primary" loading>loading</xy-button>

with icon

    <xy-button type="primary" icon="heart" shape="circle"></xy-button>
    <xy-button type="dashed" icon="heart" shape="circle"></xy-button>
    <xy-button type="flat" icon="heart" shape="circle"></xy-button>
    <xy-button icon="heart" shape="circle"></xy-button>
    <xy-button type="primary" icon="heart">like</xy-button>
    <xy-button type="dashed" icon="search">search</xy-button>
    <xy-button type="flat" icon="left">back</xy-button>
    <xy-button icon="link">link</xy-button>

block

    <xy-button type="primary" block>primary</xy-button>
    <xy-button type="dashed" block>dashed</xy-button>
    <xy-button type="flat" block>flat</xy-button>
    <xy-button block>default</xy-button>

disabled

    <xy-button disabled type="primary" onclick="XyMessage.info('This a info message')">primary</xy-button>
    <xy-button disabled type="dashed">dashed</xy-button>
    <xy-button disabled type="flat">flat</xy-button>
    <xy-button disabled >default</xy-button>

slider

    <xy-slider onchange="console.log(event)"></xy-slider>
    <xy-slider defaultvalue="100" min="0" max="300" step="5"></xy-slider>
    <xy-slider defaultvalue="30" min="-100" max="100" step="1"></xy-slider>
    <xy-slider defaultvalue="100" min="10" max="200" step="2" showtips></xy-slider>
    <xy-slider defaultvalue="150" min="10" max="200" step="2" disabled></xy-slider>
    <xy-slider style="height:200px" vertical showtips defaultvalue="150" min="10" max="200" step="2"></xy-slider>

loading

    <xy-loading></xy-loading>
    <xy-loading size="40" color="green"></xy-loading>
    <xy-loading size="60" color="olivedrab"></xy-loading>
    <xy-loading size="80" color="orange"></xy-loading>

switch

    <xy-switch onchange="console.log(event)" checked></xy-switch>
    <xy-switch></xy-switch>
    <xy-switch disabled checked></xy-switch>

checkbox

    <xy-checkbox name="lang" onchange="console.log(event)" checked>Html</xy-checkbox>
    <xy-checkbox name="lang">Css</xy-checkbox>
    <xy-checkbox name="lang" checked>Javascript</xy-checkbox>
    <xy-checkbox name="lang">Python</xy-checkbox>
    <xy-checkbox name="lang">Php</xy-checkbox>
    <xy-checkbox name="lang">Dart</xy-checkbox>
    <xy-checkbox name="lang">Swift</xy-checkbox>
    <xy-checkbox name="lang" disabled>Other</xy-checkbox>

radio

javascript

    <xy-radio onchange="console.log(event)" name="library" checked>React</xy-radio>
    <xy-radio name="library">Vue</xy-radio>
    <xy-


ng a general purpose register or temporary
// * `.undef`: delete the variable if this is assigned to it (like Option::None)
// * `<a signed decimal integer>`: read this integer constant (limited to i64 precision)
//
//
// Before evaluating a STACK WIN expression:
//
// * The variables `$ebp` and `$esp` should be initialized from the callee's
//   values for those registers (error out if those are unknown). `$ebx` should
//   similarly be initialized if it's available, since some things use it, but
//   it's optional.
//
// * The following constant variables should be set accordingly:
//   * `.cbParams = parameter_size`
//   * `.cbCalleeParams = grand_callee_parameter_size` (only for breakpad-generated exprs?)
//   * `.cbSavedRegs = saved_register_size`
//   * `.cbLocals = local_size`
//   * `.raSearch = $esp + frame_size`
//   * `.raSearchStart = .raSearch` (synonym that sometimes shows up?)
//
// Note that .raSearch(Start) roughly corresponds to STACK CFI's `.cfa`, in that
// it generally points to where the return address is. However breakpad seems to
// believe there are many circumstances where this value can be slightly wrong
// (due to the frame pointer having mysterious extra alignment?). As such,
// breakpad has several messy heuristics to "refine" `.raSearchStart`, such as
// scanning the stack. This implementation does not (yet?) implement those
// heuristics. As of this writing I have not encountered an instance of this
// problem in the wild (but I haven't done much testing!).
//
//
// After evaluating a STACK WIN expression:
//
// The caller's registers are stored in `$eip`, `$esp`, `$ebp`, `$ebx`, `$esi`,
// and `$edi`. If those variables are undefined, then their values in the caller
// are unknown. Do not implicitly forward registers that weren't explicitly set.
//
// (Should it be an error if the stack isn't empty at the end? It's
// arguably malformed input but also it doesn't matter since the output is
// in the variables? *shrug*)
//
//
//
// ## Example STACK WIN framedata evaluation
//
// Here is an example of framedata for a function with the standard prologue.
// Given the input:
//
// ```
// $T0 $ebp = $eip $T0 4 + ^ = $ebp $T0 ^ = $esp $T0 8 + =
// ```
//
// and initial state:
//
// ```
// ebp: 16, esp: 1600
// ```
//
// Then evaluation proceeds as follows:
//
// ```
//   Token  |    Stack     |                       Vars
// ---------+--------------+----------------------------------------------------
//          |              | $ebp: 16,      $esp: 1600,
//   $T0    | $T0          | $ebp: 16,      $esp: 1600,
//   $ebp   | $T0 $ebp     | $ebp: 16,      $esp: 1600,
//   =      |              | $ebp: 16,      $esp: 1600,   $T0: 16,
//   $eip   | $eip         | $ebp: 16,      $esp: 1600,   $T0: 16,
//   $T0    | $eip $T0     | $ebp: 16,      $esp: 1600,   $T0: 16,
//   4      | $eip $T0 4   | $ebp: 16,      $esp: 1600,   $T0: 16,
//   +      | $eip 20      | $ebp: 16,      $esp: 1600,   $T0: 16,
//   ^      | $eip (*20)   | $ebp: 16,      $esp: 1600,   $T0: 16,
//   =      |              | $ebp: 16,      $esp: 1600,   $T0: 16,   $eip: (*20)
//   $ebp   | $ebp         | $ebp: 16,      $esp: 1600,   $T0: 16,   $eip: (*20)
//   $T0    | $ebp $T0     | $ebp: 16,      $esp: 1600,   $T0: 16,   $eip: (*20)
//   ^      | $ebp (*16)   | $ebp: 16,      $esp: 1600,   $T0: 16,


.OthersCanAddTasks == true ? TodoList.Flags.others_can_append : 0)
				| (list.OthersCanMarkTasksAsDone == true ? TodoList.Flags.others_can_complete : 0),
			title = new TextWithEntities { text = text, entities = entities },
			li


       cypherPassword,
            userData.role,
            user_id,
            userData.logradouro,
            userData.numero,
            userData.complemento,
            userData.bairro,
            userData.cidade,
            userData.estado
        )

        const token = generateToken({
            id,
            role: userData.role
        })

        res
        .status(200)
        .send({
            message: "User successfuly created",
            token
        })

   } catch (error) {
       res
       .status(400)
       .send({
           message: error.message
       })
   }
}import { ethers, BigNumber } from 'ethers';
import { secondsInTenYears } from './constants'
import { Decimal } from 'decimal.js';

Decimal.set({ precision: 64 });

/* constants exposed for export */
export const ZERO_DEC: Decimal = new Decimal(0);
export const ONE_DEC: Decimal = new Decimal(1);
export const TWO_DEC: Decimal = new Decimal(2);
export const SECONDS_PER_YEAR: number = (365 * 24 * 60 * 60);

/* locally used constants */
const ZERO = ZERO_DEC;
const ONE = ONE_DEC;
const TWO = TWO_DEC;
const k = new Decimal(1 / secondsInTenYears.toNumber()); // inv of seconds in 4 years
const g1 = new Decimal(950 / 1000);
const g2 = new Decimal(1000 / 950);
const precisionFee = new Decimal(1000000000000);

/** *************************
 Support functions
 *************************** */

/**
 * @param { BigNumber | string } multiplicant
 * @param { BigNumber | string } multiplier
 * @param { string } precisionDifference  // Difference between multiplicant and multiplier precision (eg. wei vs ray '1e-27' )
 * @returns { string } in decimal precision of the multiplicant
 */
export const mulDecimal = (
  multiplicant: BigNumber | string,
  multiplier: BigNumber | string,
  precisionDifference: string = '1', // DEFAULT = 1 (same precision)
): string => {
  const multiplicant_ = new Decimal(multiplicant.toString());
  const multiplier_ = new Decimal(multiplier.toString());
  const _preDif = new Decimal(precisionDifference.toString());
  const _normalisedMul = multiplier_.mul(_preDif);
  return multiplicant_.mul(_normalisedMul).toFixed();
};

/**
 * @param  { BigNumber | string } numerator
 * @param { BigNumber | string } divisor
 * @param { BigNumber | string } precisionDifference // Difference between multiplicant and mulitplier precision (eg. wei vs ray '1e-27' )
 * @returns { string } in decimal precision of the numerator
 */
export const divDecimal = (
  numerator: BigNumber | string,
  divisor: BigNumber | string,
  precisionDifference: string = '1', // DEFAULT = 1 (same precision)
): string => {
  const numerator_ = new Decimal(numerator.toString());
  const divisor_ = new Decimal(divisor.toString());
  const _preDif = new Decimal(precisionDifference.toString());
  const _normalisedDiv = divisor_.mul(_preDif);


5984e93b81cbf5a1272b824570-8000.html">Home / Learning ActionScript 3.0 / Object-oriented programming in ActionScript

          Introduction to object-oriented programming


  # how_to_render_lines args
  # =======================================================================

  # == HOW TO RENDER A SPRITE =============================================
  # Remove the "#" at the beginning of the line below
  # how_to_render_sprites args
  # =======================================================================

  # ==== HOW TO MOVE A SPRITE BASED OFF OF USER INPUT =====================
  # Remove the "#" at the beginning of the line below
  # how_to_move_a_sprite args
  # =======================================================================

  # ==== HOW TO ANIMATE A SPRITE (SEPERATE PNGS) ==========================
  # Remove the "#" at the beginning of the line below
  # how_to_animate_a_sprite args
  # =======================================================================

  # ==== HOW TO ANIMATE A SPRITE (SPRITE SHEET) ===========================
  # Remove the "#" at the beginning of the line below
  # how_to_animate_a_sprite_sheet args
  # =======================================================================

  # ==== HOW TO DETERMINE COLLISION =============================================
  # Remove the "#" at the beginning of the line below
  # how_to_determine_collision args
  # =======================================================================

  # ==== HOW TO CREATE BUTTONS ==================================================
  # Remove the "#" at the beginning of the line below
  # how_to_create_buttons args
  # =======================================================================

  # ==== The line below renders a debug grid, mouse information, and current tick
  render_debug args
end

def hello_world args
  args.lowrez.solids  << { x: 0, y: 64, w: 10, h: 10, r: 255 }

  args.lowrez.labels  << {
    x: 32,
    y: 63,
    text: "lowrezjam 2020",
    size_enum: LOWREZ_FONT_SM,
    alignment_enum: 1,
    r: 0,
    g: 0,
    b: 0,
    a: 255,
    font: LOWREZ_FONT_PATH
  }

  args.lowrez.sprites << {
    x: 32 - 10,
    y: 32 - 10,
    w: 20,
    h: 20,
    path: 'sprites/lowrez-ship-blue.png',
    a: args.state.tick_count % 255,
    angle: args.state.tick_count % 360
  }
end

# =======================================================================
# ==== HOW TO RENDER A LABEL ============================================
# =======================================================================
def how_to_render_a_label args
  # NOTE: Text is aligned from the TOP LEFT corner

  # Render an EXTRA LARGE/XL label (remove the "#" in front of each line below)
  args.lowrez.labels << { x: 0, y: 57, text: "Hello World",
                         size_enum: LOWREZ_FONT_XL,
                         r: 0, g: 0, b: 0, a: 255,
                         font: LOWREZ_FONT_PATH }

  # Render a LARGE/LG label (remove the "#" in front of each line below)
  args.lowrez.labels << { x: 0, y: 36, text: "Hello World",
                          size_enum: LOWREZ_FONT_LG,
                          r: 0, g: 0, b: 0, a: 255,
                          font: LOWREZ_FONT_PATH }

  # Render a MEDIUM/MD label (remove the "#" in front of each line below)
  args.lowrez.labels << { x: 0, y: 20, text: "Hello World",
                          size_enum: LOWREZ_FONT_MD,
                          r: 0, g: 0, b: 0, a: 255,
                          font: LOWREZ_FONT_PATH }

  # Render a SMALL/SM label (remove the "#" in front of each line below)
  args.lowrez.labels << { x: 0, y: 9, text: "Hello World",


id InitAttributes()
		{
			_embed_attr = "";
			_cstate_attr = "none";
		}

		protected override void InitElements()
		{
		}

		protected override void InitCollections()
		{
		}

		public override void Write(TextWriter s, string tagName)
		{
			WriteEmptyTag(s, tagName, "a");
		}

		public override void WriteOpenTag(TextWriter s, string tagName, Dictionary<string, string> namespaces)
		{
			WriteOpenTag(s, tagName, "a", namespaces);
		}

		public override void WriteCloseTag(TextWriter s, string tagName)
		{
			s.Write("</a:");
			s.Write(tagName);
			s.Write(">");
		}

		public override void WriteAttributes(TextWriter s)
		{
			if (_embed_attr != "")
			{
				s.Write(" r:embed=\"");
				OoxmlComplexType.WriteData(s, _embed_attr);
				s.Write("\"");
			}
			if (_cstate_attr != "none")
			{
				s.Write(" cstate=\"");
				OoxmlComplexType.WriteData(s, _cstate_attr);
				s.Write("\"");
			}
		}

		public override void WriteElements(TextWriter s)
		{
		}
	}
}


 Deliver is not satisfied
		//
		By("fetching the latest block from the peer as a forbidden org2 Admin identity")
		sess, err = network.PeerAdminSession(org2Peer0, fetchNewest)
		Expect(err).NotTo(HaveOccurred())
		Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit())
		Expect(sess.Err).To(gbytes.Say("can't read the block: &{FORBIDDEN}"))

		//
		// when the ACL policy for lscc/GetInstantiatedChaincodes is satisfied
		//
		By("setting the lscc/GetInstantiatedChaincodes ACL policy to Org1/Admins")
		policyName = resources.Lscc_GetInstantiatedChaincodes
		policy = "/Channel/Application/Org1/Admins"
		SetACLPolicy(network, "testchannel", policyName, policy, "orderer")

		By("listing the instantiated chaincodes as a permitted Org1 Admin identity")
		sess, err = network.PeerAdminSession(org1Peer0, commands.ChaincodeListInstantiatedLegacy{
			ChannelID: "testchannel",
		})
		Expect(err).NotTo(HaveOccurred())
		Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit(0))
		Expect(sess).To(gbytes.Say("Name: mycc, Version: 0.0, Path: .*, Escc: escc, Vscc: vscc"))

		//
		// when the ACL policy for lscc/GetInstantiatedChaincodes is not satisfied
		//
		By("listing the instantiated chaincodes as a forbidden org2 Admin identity")
		sess, err = network.PeerAdminSession(org2Peer0, commands.ChaincodeListInstantiatedLegacy{
			ChannelID: "testchannel",
		})
		Expect(err).NotTo(HaveOccurred())
		Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit())
		Expect(sess).NotTo(gbytes.Say("Name: mycc, Version: 0.0, Path: .*, Escc: escc, Vscc: vscc"))
		Expect(sess.Err).To(gbytes.Say(`access denied for \[getchaincodes\]\[testchannel\](.*)signature set did not satisfy policy`))

		//
		// when a system chaincode ACL policy is set and a query is performed
		//

		// getting a transaction id from a block in the ledger
		sess, err = network.PeerAdminSession(org1Peer0, fetchNewest)
		Expect(err).NotTo(HaveOccurred())
		Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit(0))
		Expect(sess.Err).To(gbytes.Say("Received block: "))
		txID := GetTxIDFromBlockFile(outputBlock)

		ItEnforcesPolicy := func(scc, operation string, args ...string) {
			policyName := fmt.Sprintf("%s/%s", scc, operation)
			policy := "/Channel/Application/Org1/Admins"
			By("setting " + policyName + " to Org1 Admins")
			SetACLPolicy(network, "testchannel", policyName, policy, "orderer")

			args = append([]string{operation}, args...)
			chaincodeQuery := commands.ChaincodeQuery{
				ChannelID: "testchannel",
				Name:      scc,
				Ctor:      ToCLIChaincodeArgs(args...),
			}

			By("evaluating " + policyName + " for a permitted subject")
			sess, err := network.PeerAdminSession(org1Peer0, chaincodeQuery)
			Expect(err).NotTo(HaveOccurred())
			Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit(0))

			By("evaluating " + policyName + " for a forbidden subject")
			sess, err = network.PeerAdminSession(org2Peer0, chaincodeQuery)
			Expect(err).NotTo(HaveOccurred())
			Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit())
			Expect(sess.Err).To(gbytes.Say(fmt.Sprintf(`access denied for \[%s\]\[%s\](.*)signature set did not satisfy policy`, operation, "te


_8019E79C
lbl_8019E738:
/* 8019E738 0019A398  57 3C 13 BA */	rlwinm r28, r25, 2, 0xe, 0x1d
/* 8019E73C 0019A39C  7E C3 B3 78 */	mr r3, r22
/* 8019E740 0019A3A0  7C 9B E0 2E */	lwzx r4, r27, r28
/* 8019E744 0019A3A4  4B FE 17 29 */	bl func_8017FE6C
/* 8019E748 0019A3A8  7C 9B E0 2E */	lwzx r4, r27, r28
/* 8019E74C 0019A3AC  7C 7C 1B 78 */	mr r28, r3
/* 8019E750 0019A3B0  7E C3 B3 78 */	mr r3, r22
/* 8019E754 0019A3B4  4B FE 17 21 */	bl func_8017FE74
/* 8019E758 0019A3B8  7C 7D 1B 78 */	mr r29, r3
/* 8019E75C 0019A3BC  7E C3 B3 78 */	mr r3, r22
/* 8019E760 0019A3C0  7F 04 C3 78 */	mr r4, r24
/* 8019E764 0019A3C4  4B FE 22 E9 */	bl func_80180A4C
/* 8019E768 0019A3C8  7C 7E 1B 78 */	mr r30, r3
/* 8019E76C 0019A3CC  7E C3 B3 78 */	mr r3, r22
/* 8019E770 0019A3D0  7F 04 C3 78 */	mr r4, r24
/* 8019E774 0019A3D4  4B FE 23 01 */	bl func_80180A74
/* 8019E778 0019A3D8  7C 60 1B 78 */	mr r0, r3
/* 8019E77C 0019A3DC  7E E3 BB 78 */	mr r3, r23
/* 8019E780 0019A3E0  57 84 04 3E */	clrlwi r4, r28, 0x10
/* 8019E784 0019A3E4  57 A5 06 3E */	clrlwi r5, r29, 0x18
/* 8019E788 0019A3E8  57 C6 04 3E */	clrlwi r6, r30, 0x10
/* 8019E78C 0019A3EC  54 07 06 3E */	clrlwi r7, r0, 0x18
/* 8019E790 0019A3F0  48 02 3D 25 */	bl func_801C24B4
/* 8019E794 0019A3F4  7F 5A 1A 14 */	add r26, r26, r3
/* 8019E798 0019A3F8  3B 39 00 01 */	addi r25, r25, 1
lbl_8019E79C:
/* 8019E79C 0019A3FC  57 20 04 3E */	clrlwi r0, r25, 0x10
/* 8019E7A0 0019A400  7C 00 F8 40 */	cmplw r0, r31
/* 8019E7A4 0019A404  41 80 FF 94 */	blt lbl_8019E738
/* 8019E7A8 0019A408  39 61 00 90 */	addi r11, r1, 0x90
/* 8019E7AC 0019A40C  7F 43 D3 78 */	mr r3, r26
/* 8019E7B0 0019A410  48 02 89 B1 */	bl _restgpr_22
/* 8019E7B4 0019A414  80 01 00 94 */	lwz r0, 0x94(r1)
/* 8019E7B8 0019A418  7C 08 03 A6 */	mtlr r0
/* 8019E7BC 0019A41C  38 21 00 90


[2];

					bCanDrag = ((to.tv.oEvEdt !== null) && (to.tv.oDVEdtgEv.sEventId === sEventId)) ? true : false;

					if(to.tv.bChkDroppable)
					{
						$oElemDragged = $(to.elem).find("#" + sElemId + ".ui-draggable-dragging");

						iNumOfEventElements = to._getNumberOfDaysOfEventForWeek(bIsAllDay, dDragStartDate, dDragEndDate, false, true);
						sDroppableId = $oElemDragged.attr("data-droppableid");
						bEventEntered = to._findWhetherEventEnteredNonDroppableZone(dDragStartDate, dDragEndDate, bIsAllDay, iNumOfEventElements, sDroppableId);

						$oElemDragged.removeClass("cCursorNotAllowed");
						$oElemDragged.find(".cEventLink").removeClass("cCursorNotAllowed");
					}

					if(bEventEntered)
					{
						setTimeout(function()
						{
							to._performOperationsAfterDraggingStopsInDetailView(sEventId, null, null, true);

							to.tv.dDrgSDt = null;
							to.tv.dDrgEDt = null;

							if(!bCanDrag)
								return false;
						}, 300);
					}
					else
					{
						if(bCanDrag)
						{
							to._performOperationsAfterDraggingStopsInDetailView(sEventId, dDragStartDate, dDragEndDate, true);

							to.tv.bDVDrgEv = false;
							to.tv.dDrgSDt = null;
							to.tv.dDrgEDt = null;
						}
						else
						{
							if(!$.CalenStyle.extra.bTouchDevice)
								to._makeEventNonEditableInDetailView();
							to.tv.dDrgSDt = null;
							to.tv.dDrgEDt = null;
							return false;
						}
					}
				},

				revert: function(event, ui)
				{
					if(bEventEntered)
						return true;
					return false;
				}

			});
		}
		else if($.cf.compareStrings(sClass, ".cdvEventAllDay"))
		{
			iEventHeight = $(to.elem).find(".cdvEventAllDay").height();
			iEventWidth = $(to.elem).find(".cdvTableColumns").width();
			if(iEventWidth > 140)
				iEventWidth = 140;

			iColumn1Width = $(to.elem).find(".cdvDetailTableColumnTime").width();
			iCalendarLeft = $(to.elem).position().left;
			iCalendarMarginLeft = $(to.elem).css("margin-left");
			iCalendarMarginLeft = parseInt(iCalendarMarginLeft.replace("px", ""));
			iLeft = iCalendarLeft + iCalendarMarginLeft + $(to.elem).find(".cdvContRow2Main").position().left;
			iX1 = iLeft + iColumn1Width;
			iX2 = iX1 + $(to.elem).find(".cdvContRow2Main").width() - (iEventWidth + iScrollbarWidth + iColumn1Width);

			iCalendarTop = $(to.elem).position().top;
			iCalendarMarginTop = $(to.elem).css("margin-top");
			iCalendarMarginTop = parseInt(iCalendarMarginTop.replace("px", ""));
			iY1 = iCalendarTop + iCalendarMarginTop + $(to.elem).find(".cdvContRow2Main").position().top;
			if(to.tv.bDisFBar && $.cf.compareStrings(to.setting.filterBarPosition, "Top"))
				iY1 += to.setting.filterBarHeight;
			iY2 = iY1 + $(to.elem).find(".cdvContRow2Main").height() - (iEventHeight);

			bCanDrag = false;
			$(to.elem).find("."+sDraggableClass).draggable(


) is used in AnkiDroid and should be documented.
 *  This property should always be set
 *
 * TODO: Anki Desktop (2024) defines the following properties which this class should document for
 *  completeness
 * * bfont: '' - the font used in Browse
 * * bsize: 0 - the font size used in Browse
 * * id: 1556256845231882422
 *
 * ## Links
 * * [Anki Manual](https://docs.ankiweb.net/templates/intro.html)
 */
data class CardTemplate(
    override val jsonObject: JSONObject,
) : JSONObjectHolder {
    /**
     * The user-facing name of the template
     *
     * By default, Anki uses `Card 1`
     */
    var name by jsonString("name")

    /** The 0-based ordinal of the template */
    val ord by jsonInt("ord")

    /**
     * Format string for the question when reviewing
     *
     * Example:
     *
     * ```
     * {{Front}}
     * ```
     */
    var qfmt by jsonString("qfmt")

    /**
     * Format string for the answer when reviewing
     *
     * Example
     * ```
     * {{FrontSide}}
     *
     * <hr id=answer>
     *
     * {{Back}}
     * ```
     */
    var afmt by jsonString("afmt")

    /**
     * Format string for the question of the card **when displayed in Browse**
     */
    var bqfmt by jsonString("bqfmt")

    /**
     * Format string for the answer of the card **when displayed in Browse**
     */
    var bafmt by jsonString("bafmt")

    /** @see ord */
    @RustCleanup("Check JSONObject.NULL")
    fun setOrd(value: Int?) = jsonObject.put("ord", if (value == null) JSONObject.NULL else value)

    fun deepClone() = CardTemplate(jsonObject.deepClone())

    override fun toString() = jsonObject.toString()
}
/****************************************************************************************
 * Copyright (c) 2020 Arthur Milchior <arthur@milchior.fr>                             *
 *                                                                                *
 * This program is free software; you can redistribute it and/or modify it under        *
 * the terms of the GNU General Public License as published by the Free Software        *
 * Foundation; either version 3 of the License, or (at your option) any later           *
 * version.                                                                             *
 *                                                                                *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY      *
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A      *
 * PARTICULAR PURPOSE. See the GNU General Public License for more details.             *
 *                                                                                *
 * You should have received a copy of the GNU General Public License along with         *
 * this program.  If not, see <http://www.gnu.org/licenses/>.                           *
 ****************************************************************************************/

package com.ichi2.anki.libanki

import androidx.annotation.CheckResult
import androidx.annotation.VisibleForTesting
import anki.notetypes.StockNotetype.OriginalStockKind.ORIGINAL_STOCK_KIND_IMAGE_OCCLUSION_VALUE
import anki.notetypes.StockNotetype.OriginalStockKind.ORIGINAL_STOCK_KIND_UNKNOWN_VALUE
import com.ichi2.anki.common.json.JSONObjectHolder
import com.ichi2.anki.common.json.NamedObject
import com.ichi2.anki.common.json.jsonArray
import com.ichi2.anki.common.json.jsonBoolean
import com.ichi2.anki.common.json.jsonInt
import com.ichi2.anki.common.json.jsonLong
import com.ichi2.anki.common.json.jsonString
import com.ichi2.anki.c


urn `${player} cannot pay ${-adjustValue} Fate point${-adjustValue > 1 ? 's' : ''}.`;
		else
		{
			if(character.FatePoints == undefined)
				character.FatePoints = 0;
			character.FatePoints += adjustValue;
			return `${adjustValue > -1 ? 'Gaining' : 'Spending'} ${adjustValue < 0 ? adjustValue * -1 : adjustValue} Fate point${ adjustValue * adjustValue > 1 ? 's' : ''}, ${player} now has ${character.FatePoints} Fate points.`;
		}
	}
}import { DownloadError, DownloadTask } from '../../services/downloader';

export const DOWNLOAD_CHAPTERS = 'DOWNLOAD_CHAPTERS';
export const PAUSE_DOWNLOADER = 'PAUSE_DOWNLOADER';
export const START_DOWNLOADER = 'START_DOWNLOADER';
export const CLEAR_DOWNLOADER_QUEUE = 'CLEAR_DOWNLOADER_QUEUE';
export const INTERNAL_COPY_CLIENT_STATE = 'INTERNAL_COPY_CLIENT_STATE';

export interface DownloaderState {
  running: boolean;
  queue: DownloadTask[];
  currentTask: DownloadTask | null;
  downloadErrors: DownloadError[];
}

interface DownloadChaptersAction {
  type: typeof DOWNLOAD_CHAPTERS;
  payload: {
    tasks: DownloadTask[];
  };
}

interface PauseDownloaderAction {
  type: typeof PAUSE_DOWNLOADER;
}

interface StartDownloaderAction {
  type: typeof START_DOWNLOADER;
}

interface ClearDownloaderQueueAction {
  type: typeof CLEAR_DOWNLOADER_QUEUE;
}

interface InternalCopyClientStateAction {
  type: typeof INTERNAL_COPY_CLIENT_STATE;
}

export type DownloaderAction =
  | DownloadChaptersAction
  | PauseDownloaderAction
  | StartDownloaderAction
  | ClearDownloaderQueueAction
  | InternalCopyClientStateAction;
import { Injectable } from '@angular/core';
import { Question} from '../models/question';

@Injectable()
export class DataService {
questions: Question[];

  constructor() {
    //   this.questions = [{
    //     text: "What is your name",
    //     answer: "My name is Edwin",
    //     hide: true
    //   },
    //   {
    //     text: "What is your fav color",
    //     answer: "My fav color is blue",
    //     hide: true
    //   },
    //   {
    //     text: "What is your fav language",
    //     answer: "My fav language is JavaScript",
    //     hide: true
    //   }
    // ]
    };

    getQuestions(){
      if(localStorage.getItem('questions') === null){
        this.questions = [];
      } else {
        this.questions = (JSON.parse(localStorage.getItem('questions'))); //parse is to convert localStorage(string) to JSON for JS
      }
        return this.questions;
    };

    addQuestion(question){
      this.questions.unshift(question);

      //local variable
      var questions;

      if(localStorage.getItem('questions') === null){
        questions = []; //start a new array
        questions.unshift(question); //add new question in new array
        localStorage.setItem('questions', JSON.stringify(questions)); //store questions array into LocalStorage
      } else {
        questions = (JSON.parse(localStorage.getItem('questions'))); //parse out to temp variable
        questions.unshift(question); //add new question to array converted from LocalStorage
        localStorage.setItem('questions', JSON.stringify(questions)); //store questions array into LocalStorage again
      }

    };

    removeQuestion(question){
      for(let i = 0; i < this.questions.length; i++){
        if(this.questions[i] == question){
          this.questions.splice(i,


  3. 请将光标移动到本节中下面标记有 ---> 的第一行。

  4. 接着将光标移动到第一个错误处。

  5. 然后输入 c$ 使得该行剩下的部分更正得同第二行一样。最后按 <ESC> 键。

---> The end of this line needs some help to make it like the second.---> The end of this line needs to be corrected using the  c$  command.

第三讲小结

1. 要重新置入已经删除的文本内容，请输入小写字母 p。该操作可以将已删除     的文本内容置于光标之后。如果最后一次删除的是一个整行，那么该行将置     于当前光标所在行的下一行。

  2. 要替换光标所在位置的字符，请输入小写的 r 和要替换掉原位置字符的新字     符即可。

  3. 更改类命令允许您改变指定的对象，从当前光标所在位置直到对象的末尾。     比如输入 cw 可以替换当前光标到单词的末尾的内容；输入 c$ 可以替换当     前光标到行末的内容。

  4. 更改类命令的格式是∶

  [number]   c object        或者  c   [number]   object

下面我们继续学习下一讲。

 第四讲

第一节∶定位及文件状态

** 输入 CTRL-g 显示当前编辑文件中当前光标所在行位置以及文件状态信息。输入 SHIFT-G 则直接跳转到文件中的某一指定行。**

  提示∶切记要先通读本节内容，之后才可以执行以下步骤!!!

  1. 按下 CTRL 键不放开然后按 g 键。然后就会看到页面最底部出现一个状态信     息行，显示的内容是当前编辑的文件名和文件的总行数。请记住步骤3的行号。

  2. 按下 SHIFT-G 键可以使得当前光标直接跳转到文件最后一行。

  3. 输入您曾停留的行号，然后按下 SHIFT-G。这样就可以返回到您第一次按下     CTRL-g 时所在的行好了。注意∶输入行号时，行号是不会在屏幕上显示出来     的。


                SASSERT(obj.m_id == id);
                obj.m_term = orig_term?to_app(orig_term):nullptr;
                obj.m_terms.reset();
                obj.m_terms.append(terms);
                obj.m_weights.reset();
                obj.m_weights.append(weights);
                obj.m_adjust_value.set_offset(offset);
                obj.m_adjust_value.set_negate(neg);
                m_maxsmts.find(id)->set_adjust_value(obj.m_adjust_value);
                TRACE("opt", tout << "maxsat: " << id << " offset:" << offset << "\n";
                      tout << terms << "\n";);
            }
            else if (is_maximize(fml, tr, orig_term, index)) {
                purify(tr);
                m_objectives[index].m_term = tr;
            }
            else if (is_minimize(fml, tr, orig_term, index)) {
                purify(tr);
                m_objectives[index].m_term = tr;
                m_objectives[index].m_adjust_value.set_negate(true);
            }
            else {
                m_hard_constraints.push_back(fml);
            }
        }
        // fix types of objectives:
        for (objective & obj : m_objectives) {
            expr* t = obj.m_term;
            switch(obj.m_type) {
            case O_MINIMIZE:
            case O_MAXIMIZE:
                if (!m_arith.is_int(t) && !m_arith.is_real(t)) {
                    obj.m_term = m_arith.mk_numeral(rational(0), true);
                }
                break;
            default:
                break;
            }
        }
    }

    void context::model_updated(model* md) {
        model_ref mdl = md;
        set_model(mdl);
#if 0
        opt_params optp(m_params);
        symbol prefix = optp.solution_prefix();
        if (prefix == symbol::null || prefix == symbol("")) return;
        model_ref mdl = md->copy();
        fix_model(mdl);
        std::ostringstream buffer;
        buffer << prefix << (m_model_counter++) << ".smt2";
        std::ofstream out(buffer.str());
        if (out) {
            out << *mdl;
            out.close();
        }
#endif
    }

    bool context::verify_model(unsigned index, model* md, rational const& _v) {
        rational r;
        app_ref term = m_objectives[index].m_term;
        if (!term) {
            return true;
        }
        rational v = m_objectives[index].m_adjust_value(_v);
        expr_ref val(m);
        model_ref mdl = md->copy();
        fix_model(mdl);
        val = (*mdl)(term);
        unsigned bvsz;
        if (!m_arith.is_numeral(val, r) && !m_bv.is_numeral(val, r, bvsz)) {
            TRACE("opt", tout << "model does not evaluate objective to a value but instead " << val << "\n";
                  tout << *mdl << "\n";
                  );
            return false;
        }
        if (r != v) {
            TRACE("opt", tout << "Out of bounds: " << term << " " << val << " != " << v << "\n";);
            return false;
        }
        else {
            TRACE("opt", tout << "validated: " << term << " = " << val << "\n";);
        }
        return true;
    }

    void context::pu


o the LO nibbles
            ushr    v1.8b, v0.8b, #4        // and V1 to the HO nibbles
            bic     v0.4h, #0xf0
            bic     v0.4h, #0xf0, lsl #8

            zip1    v0.8b, v0.8b, v1.8b     // Interleave the HO and LO nibbles

            orr     v0.4h, #0x30            // Convert binary to ascii,
            orr     v0.4h, #0x30, lsl #8    // note only 0-9 will be correct

            movi    v1.8b, #'9'             // Determine which bytes
            cmgt    v1.8b, v0.8b, v1.8b     // should be A-F

            bic     v1.4h, #invert0ToA      // Update bytes that should be A-F
            bic     v1.4h, #invert0ToA, lsl #8
            add     v0.8b, v0.8b, v1.8b

            ext     v0.8b, v0.8b, v0.8b, #4 // Reverse the bytes
            rev32   v0.8b, v0.8b

            str     d0, [x0]                // Output the string
            strb    wzr, [x0, #8]

            ldp     q0, q1, [sp], #32       // Restore registers
            ret

// 16-bit half word
u16ToHexStr:
            stp     x1, lr, [sp, #-16]!     // Preserve registers
            bl      u32ToHexStr             // Start with 64-bit string
            ldr     w1,  [x0, #12]          // Move the substring we want
            str     w1,  [x0]
            strb    wzr, [x0, #4]
            ldp     x1, lr, [sp], #16       // Restore registers
            ret

// 8-bit byte
u8ToHexStr:
            stp     x1, lr, [sp, #-16]!     // Preserve registers
            bl      u32ToHexStr             // Start with 64-bit string
            ldrh    w1,  [x0, #14]          // Move the substring we want
            strh    w1,  [x0]
            strb    wzr, [x0, #2]
            ldp     x1, lr, [sp], #16       // Restore registers
            ret

// 4-bit nibble
u4ToHexStr:
            stp     x1, lr, [sp, #-16]!     // Preserve registers
            bl      u32ToHexStr             // Start with 64-bit string
            ldrb    w1,  [x0, #15]          // Move the substring we want
            strb    w1,  [x0]
            strb    wzr, [x0, #1]
            ldp     x1, lr, [sp], #16       // Restore registers
            ret


     /// This value should always index a non-empty string.
        /// </remarks>
        public uint Name
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets an index into the #Blob heap containing the signature of the field. This includes the field type.
        /// </summary>
        /// <remarks>
        /// This value should always index a valid field signature.
        /// </remarks>
        public uint Signature
        {
            get;
        }

        /// <inheritdoc />
        public void Write(BinaryStreamWriter writer, TableLayout layout)
        {
            writer.WriteUInt16((ushort) Attributes);
            writer.WriteIndex(Name, (IndexSize) layout.Columns[1].Size);
            writer.WriteIndex(Signature, (IndexSize) layout.Columns[2].Size);
        }

        /// <inheritdoc />
        public bool Equals(FieldDefinitionRow other)
        {
            return Attributes == other.Attributes && Name == other.Name && Signature == other.Signature;
        }

        /// <inheritdoc />
        public override bool Equals(object? obj)
        {
            return obj is FieldDefinitionRow other && Equals(other);
        }

        /// <inheritdoc />
        public override int GetHashCode()
        {
            unchecked
            {
                int hashCode = (int) Attributes;
                hashCode = (hashCode * 397) ^ (int) Name;
                hashCode = (hashCode * 397) ^ (int) Signature;
                return hashCode;
            }
        }

        /// <inheritdoc />
        public override string ToString()
        {
            return $"({(ushort) Attributes:X4}, {Name:X8}, {Signature:X8})";
        }

        /// <inheritdoc />
        public IEnumerator<uint> GetEnumerator()
        {
            return new MetadataRowColumnEnumerator(this);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        /// <summary>
        /// Determines whether two rows are considered equal.
        /// </summary>
        public static bool operator ==(FieldDefinitionRow left, FieldDefinitionRow right) => left.Equals(right);

        /// <summary>
        /// Determines whether two rows are not considered equal.
        /// </summary>
        public static bool operator !=(FieldDefinitionRow left, FieldDefinitionRow right) => !(left == right);
    }
}


import os
import sys

from langchain_anthropic import ChatAnthropic
from langchain_openai import ChatOpenAI
from langchain_google_genai import ChatGoogleGenerativeAI

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import argparse
import asyncio

from mlx_use import Agent
from pydantic import SecretStr
from mlx_use.controller.service import Controller

def set_llm(llm_provider:str = None):
	if not llm_provider:
		raise ValueError("No llm provider was set")

	if llm_provider == "OAI":
		api_key = os.getenv('OPENAI_API_KEY')
		return ChatOpenAI(model='gpt-4o', api_key=SecretStr(api_key))

	if llm_provider == "google":
		api_key = os.getenv('GEMINI_API_KEY')
		return ChatGoogleGenerativeAI(model='gemini-2.0-flash-exp',  api_key=SecretStr(api_key))

llm = set_llm('google')
llm = set_llm('OAI')

controller = Controller()

task = 'Can you check online what hour is Shabbat in israel this week? call done when you finish.'

agent = Agent(
	task=task,
	llm=llm,
	controller=controller,
	use_vision=False,
	max_actions_per_step=5,
	max_failures=5
)

async def main():
	await agent.run(max_steps=25)

asyncio.run(main())


7FFF */  andi  $t7, $s0, 0x7fff
/* 00D53C 8000C93C 448F3000 */  mtc1  $t7, $f6
/* 00D540 8000C940 C6640074 */  lwc1  $f4, 0x74($s3)
/* 00D544 8000C944 05E10005 */  bgez  $t7, .L8000C95C_ovl0
/* 00D548 8000C948 46803220 */   cvt.s.w $f8, $f6
/* 00D54C 8000C94C 3C014F80 */  li    $at, 0x4F800000 # 4294967296.000000
/* 00D550 8000C950 44818000 */  mtc1  $at, $f16
/* 00D554 8000C954 00000000 */  nop
/* 00D558 8000C958 46104200 */  add.s $f8, $f8, $f16
.L8000C95C_ovl0:
/* 00D55C 8000C95C 46082280 */  add.s $f10, $f4, $f8
/* 00D560 8000C960 24780004 */  addiu $t8, $v1, 4
/* 00D564 8000C964 AE780070 */  sw    $t8, 0x70($s3)
/* 00D568 8000C968 E66A0074 */  swc1  $f10, 0x74($s3)
/* 00D56C 8000C96C 10000117 */  b     .L8000CDCC_ovl0
/* 00D570 8000C970 C6600074 */   lwc1  $f0, 0x74($s3)
.L8000C974_ovl0:
/* 00D574 8000C974 32197FFF */  andi  $t9, $s0, 0x7fff
/* 00D578 8000C978 44999000 */  mtc1  $t9, $f18
/* 00D57C 8000C97C 001091C0 */  sll   $s2, $s0, 7
/* 00D580 8000C980 07210005 */  bgez  $t9, .L8000C998_ovl0
/* 00D584 8000C984 46809520 */   cvt.s.w $f20, $f18
/* 00D588 8000C988 3C014F80 */  li    $at, 0x4F800000 # 4294967296.000000
/* 00D58C 8000C98C 44813000 */  mtc1  $at, $f6
/* 00D590 8000C990 00000000 */  nop
/* 00D594 8000C994 4606A500 */  add.s $f20, $f20, $f6
.L8000C998_ovl0:
/* 00D598 8000C998 24680004 */  addiu $t0, $v1, 4
/* 00D59C 8000C99C AE680070 */  sw    $t0, 0x70($s3)
/* 00D5A0 8000C9A0 00129582 */  srl   $s2, $s2, 0x16
/* 00D5A4 8000C9A4 00008825 */  move  $s1, $zero
.L8000C9A8_ovl0:
/* 00D5A8 8000C9A8 12400026 */  beqz  $s2, .L8000CA44_ovl0
/* 00D5AC 8000C9AC 32490001 */   andi  $t1, $s2, 1
/* 00D5B0 8000C9B0 11200021 */  beqz  $t1, .L8000CA38_ovl0
/* 00D5B4 8000C9B4 00115080 */   sll   $t2, $s1, 2
/* 00D5B8 8000C9B8 02AA8021 */  addu  $s0, $s5, $t2
/* 00D5BC 8000C9BC 8E030000 */  lw    $v1, ($s


v[v_sst_b_os], v[v_gld_b+8:v_gld_b+8+3] offset:2048
    ds_write_b128 v[v_sst_b_os], v[v_gld_b+12:v_gld_b+12+3] offset:3072

    s_waitcnt vmcnt(0)
    ds_write_b128 v[v_sst_a_os], v[v_gld_a+0:v_gld_a+0+3]
    ds_write_b128 v[v_sst_a_os], v[v_gld_a+4:v_gld_a+4+3] offset:1024

    .v_clear_acc_c a_c, 128
    ; make sure acc WAR harzard, at least 1 nop for src_c
    s_sub_i32 s[s_kitr], s[s_knum], 32
    s_cmp_gt_i32 s[s_kitr], 0
    s_cbranch_scc0 L_igemm_fwd_gtcx_nhwc_fp16_bx0_ex1_bt128x256x32_wt32x32x8_ws1x2_wr2x2_ta1x8x2x1_1x4x1x64_tb1x8x4x1_1x4x1x64_vs1_gkgs_mfma_end

    s_add_u32 s[s_in_offset],  s[s_move_slice_k_stride_c], s[s_in_offset]
    v_add_u32 v[v_wei_os], s[s_move_slice_k_stride_c], v[v_wei_os]
    s_cmp_le_u32 s[s_gemm_k_num_c], s[s_in_offset]
    s_cselect_b32 s[s_flag_need_acc_yx], 1, 0

    s_cmp_eq_u32 1, s[s_flag_need_acc_yx]
    s_cbranch_scc0 igemm_fwd_gtcx_nhwc_fp16_bx0_ex1_bt128x256x32_wt32x32x8_ws1x2_wr2x2_ta1x8x2x1_1x4x1x64_tb1x8x4x1_1x4x1x64_vs1_gkgs_acc_yx_end_0  ; no need do accumulate yx
igemm_fwd_gtcx_nhwc_fp16_bx0_ex1_bt128x256x32_wt32x32x8_ws1x2_wr2x2_ta1x8x2x1_1x4x1x64_tb1x8x4x1_1x4x1x64_vs1_gkgs_acc_yx_0:
    v_add_u32 v[v_wei_os], v[v_wei_os], s[s_gemm_k_diff_c]
    s_mov_b32 s[s_in_offset], 0
    s_add_u32 s[s_move_slice_k_ix], 1, s[s_move_slice_k_ix]
    s_cmp_le_u32 s[s_x], s[s_move_slice_k_ix]
    s_cselect_b32 s[s_tmp], s[s_dilation_w_x], s[s_dilation_w]
    v_add_u32 v[v_in_iwi_list], s[s_tmp], v[v_in_iwi_list]
    v_add_u32 v[v_in_iwi_list+1], s[s_tmp], v[v_in_iwi_list+1]
    s_cselect_b32 s[s_tmp], s[s_in_diff_hi]


linecap:square;stroke-linejoin:miter;stroke-width:0.8;"/>
   </g>
   <g id="text_148">
    <!-- I have command -->
    <g transform="translate(654.54671 476.779301)scale(0.12 -0.12)">
     <use xlink:href="#DejaVuSans-73"/>
     <use x="29.492188" xlink:href="#DejaVuSans-32"/>
     <use x="61.279297" xlink:href="#DejaVuSans-104"/>
     <use x="124.658203" xlink:href="#DejaVuSans-97"/>
     <use x="185.9375" xlink:href="#DejaVuSans-118"/>
     <use x="245.117188" xlink:href="#DejaVuSans-101"/>
     <use x="306.640625" xlink:href="#DejaVuSans-32"/>
     <use x="338.427734" xlink:href="#DejaVuSans-99"/>
     <use x="393.408203" xlink:href="#DejaVuSans-111"/>
     <use x="454.589844" xlink:href="#DejaVuSans-109"/>
     <use x="552.001953" xlink:href="#DejaVuSans-109"/>
     <use x="649.414062" xlink:href="#DejaVuSans-97"/>
     <use x="710.693359" xlink:href="#DejaVuSans-110"/>
     <use x="774.072266" xlink:href="#DejaVuSans-100"/>
    </g>
   </g>
   <g id="legend_9">
    <g id="patch_55">
     <path d="M 696.285938 520.135551
L 812.682813 520.135551
Q 814.682813 520.135551 814.682813 518.135551
L 814.682813 489.779301
Q 814.682813 487.779301 812.682813 487.779301
L 696.285938 487.779301
Q 694.285938 487.779301 694.285938 489.779301
L 694.285938 518.135551
Q 694.285938 520.135551 696.285938 520.135551
z
" style="fill:#ffffff;opacity:0.5;stroke:#cccccc;stroke-linejoin:miter;"/>
    </g>
    <g id="line2d_208">
     <path d="M 698.285938 495.877739
L 718.285938 495.877739
" style="fill:none;stroke:#1f77b4;stroke-linecap:square;stroke-width:1.5;"/>
    </g>
    <g id="line2d_209"/>
    <g id="text_149">
     <!-- ch0 -->
     <g transform="translate(726.285938 499.377739)scale(0.1 -0.1)">
      <use xlink:href="#DejaVuSans-99"/>
      <use x="54.980469" xlink:href="#DejaVuSans-104"/>
      <use x="118.359375" xlink:href="#DejaVuSans-48"/>
     </g>
    </g>
    <g id="line2d_210">
     <path d="M 698.285938 510.555864
L 718.285938 510.555864
" style="fill:none;stroke:#ff7f0e;stroke-linecap:square;stroke-width:1.5;"/>
    </g>
    <g id="line2d_211"/>
    <g id="text_150">
     <!-- ch3 -->
     <g transform="translate(726.285938 51


			log.Warningf("fail to unmarshal job %s runtime info %s: %v", optJob.JobMeta.Name, optJob.Metrics.JobRuntime, err)
		}
	}

	if lastOptWorkerMemory > 0 && lastOptWorkerMemory+minMemoryIncrease > maxMemory {
		maxMemory = lastOptWorkerMemory + minMemoryIncrease
	}
	resOptPlan := &common.AlgorithmOptimizePlan{
		JobRes: &common.JobResource{
			TaskGroupResources: map[string]*common.TaskGroupResource{
				common.WorkerTaskGroupName: {
					Resource: &common.PodResource{
						Memory: maxMemory,
					},
				},
			},
		},
	}

	return resOptPlan, nil
}

func getWorkerMemoryFromOptimizeResult(result *pb.JobOptimization) float64 {
	if result == nil || result.Plan == nil || result.Plan.Resource == nil {
		return 0.0
	}
	maxMemory := 0.0
	res := result.Plan.Resource
	if res.PodResources != nil {
		for name, podRes := range res.PodResources {
			if strings.Contains(name, "worker-") {
				memory := float64(podRes.Memory)
				if maxMemory < memory {
					maxMemory = memory
				}
			}
		}
	}

	if res.TaskGroupResources != nil {
		taskGroupRes, found := res.TaskGroupResources[common.WorkerTaskGroupName]
		if found && taskGroupRes.Resource != nil {
			memory := float64(taskGroupRes.Resource.Memory)
			if maxMemory < memory {
				maxMemory = memory
			}
		}
	}
	return maxMemory
}
// Copyright 2022 The DLRover Authors. All rights reserved.
// 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 optalgorithm

import (
	"encoding/json"
	"github.com/intelligent-machine-learning/easydl/brain/pkg/common"
	"github.com/intelligent-machine-learning/easydl/brain/pkg/config"
	dsimpl "github.com/intelligent-machine-learning/easydl/brain/pkg/datastore/implementation"
	"github.com/intelligent-machine-learning/easydl/brain/pkg/datastore/recorder/mysql"
	optconfig "github.com/intelligent-machine-learning/easydl/brain/pkg/optimizer/config"
	optimplcomm "github.com/intelligent-machine-learning/easydl/brain/pkg/optimizer/implementation/common"

	"github.com/stretchr/testify/assert"
	"testing"
)

func TestOptimizeJobWorkerCreateResource(t *testing.T) {
	dataStore := &dsimpl.BaseDataStore{
		Client: mysql.NewFakeClient(),
	}

	maxMem := 14.0 * 1024 * 1024 * 1024
	maxCPU := 14.0
	rt1 := []*common.JobRuntimeInfo{
		{
			WorkerCPU: map[uint64]float64{
				0: 11,
				1: 12,
			},
			WorkerMemory: map[uint64]float64{
				0: maxMem,
				1: 2 * 1024 * 1024 * 1024,
			},
		},
	}

	rt2 := []*common.JobRuntimeInfo{
		{
			WorkerCPU: map[uint64]float64{
				0: maxCPU,
				1: 11,
			},
			WorkerMemory: map[uint64]float


).
  ///  1: Mono.
  ///  2: Stereo.
  @JsonKey(name: 'channels')
  final int? channels;

  /// The number of samples per channel in the audio frame.
  @JsonKey(name: 'samplesPerSec')
  final int? samplesPerSec;

  /// The data buffer of the audio frame. When the audio frame uses a stereo channel, the data buffer is interleaved. The size of the data buffer is as follows: buffer = samples × channels × bytesPerSample.
  @JsonKey(name: 'buffer', ignore: true)
  final Uint8List? buffer;

  /// The timestamp (ms) of the external audio frame. You can use this timestamp to restore the order of the captured audio frame, and synchronize audio and video frames in video scenarios, including scenarios where external video sources are used.
  @JsonKey(name: 'renderTimeMs')
  final int? renderTimeMs;

  /// Reserved for future use.
  @JsonKey(name: 'avsync_type')
  final int? avsyncType;

  /// @nodoc
  @JsonKey(name: 'presentationMs')
  final int? presentationMs;

  /// @nodoc
  @JsonKey(name: 'audioTrackNumber')
  final int? audioTrackNumber;

  /// @nodoc
  @JsonKey(name: 'rtpTimestamp')
  final int? rtpTimestamp;

  /// @nodoc
  factory AudioFrame.fromJson(Map<String, dynamic> json) =>
      _$AudioFrameFromJson(json);

  @override
  Map<String, dynamic> toJson() => _$AudioFrameToJson(this);
}

/// @nodoc
@JsonEnum(alwaysCreate: true)
enum AudioFramePosition {
  /// @nodoc
  @JsonValue(0x0000)
  audioFramePositionNone,

  /// @nodoc
  @JsonValue(0x0001)
  audioFramePositionPlayback,

  /// @nodoc
  @JsonValue(0x0002)
  audioFramePositionRecord,

  /// @nodoc
  @JsonValue(0x0004)
  audioFramePositionMixed,

  /// @nodoc
  @JsonValue(0x0008)
  audioFramePositionBeforeMixing,

  /// @nodoc
  @JsonValue(0x0010)
  audioFramePositionEarMonitoring,
}

/// @nodoc
extension AudioFramePositionExt on AudioFramePosition {
  /// @nodoc
  static AudioFramePosition fromValue(int value) {
    return $enumDecode(_$AudioFramePositionEnumMap, value);
  }

  /// @nodoc
  int value() {
    return _$AudioFramePositionEnumMap[this]!;
  }
}

/// Audio data format.
///
/// The SDK calculates the sampling interval through the samplesPerCall, sampleRate, and channel parameters in AudioParams, and triggers the onRecordAudioFrame, onPlaybackAudioFrame, onMixedAudioFrame, and onEarMonitoringAudioFrame callbacks according to the sampling interval. Sample interval (sec) = samplePerCall /(sampleRate × channel).
///  Ensure that the sample interval ≥ 0.01 (s).
@JsonSerializable(explicitToJson: true, includeIfNull: false)
class AudioParams implements AgoraSerializable {
  /// @nodoc
  const AudioParams(
      {this.sampleRate, this.channels, this.mode, this.samplesPerCall});

  /// The audio sample rate (Hz), which can be set as one of the following values:
  ///  8000.
  ///  (Default) 16000.
  ///  32000.
  ///  44100
  ///  48000
  @JsonKey(name: 'sample_rate')
  final int? sampleRate;

  /// The number of audio channels, which can be set as either of the following values:
  ///  1: (Default) Mono.
  ///  2: Stereo.
  @JsonKey(name: 'channels')
  final int? channels;

  /// The use mode of the audio data. See RawAudioFrameOpModeType.
  @JsonKey(name: 'mode')
  final RawAudioFrameOpModeType? mode;

  /// The number of samples, such as 1024 for the media push.
  @JsonKey(name: 'samples_per_call')
  final int? samplesPerCall;

  /// @nodoc
  factory AudioParams.fromJson(Map<String, dynamic> json) =>
      _$AudioParamsFromJson(json);


Set 偏移量，默认为0。
     * @param Offset 偏移量，默认为0。
     */
    public void setOffset(Long Offset) {
        this.Offset = Offset;
    }

    /**
     * Get 返回数量，默认为20，最大值为100。
     * @return Limit 返回数量，默认为20，最大值为100。
     */
    public Long getLimit() {
        return this.Limit;
    }

    /**
     * Set 返回数量，默认为20，最大值为100。
     * @param Limit 返回数量，默认为20，最大值为100。
     */
    public void setLimit(Long Limit) {
        this.Limit = Limit;
    }

    /**
     * Get 配置ID列表，不传入时查询全量，低优先级。该参数可以通过调用 [DescribePublicConfigs](https://cloud.tencent.com/document/product/649/38335) 的返回值中的 ConfigId 字段来获取或通过登录[控制台](https://console.cloud.tencent.com/tse/tsf-consul?subTab=public)配置详情-配置版本页查看；也可以调用[CreatePublicConfig](https://cloud.tencent.com/document/product/649/38347)创建新的配置。
     * @return ConfigIdList 配置ID列表，不传入时查询全量，低优先级。该参数可以通过调用 [DescribePublicConfigs](https://cloud.tencent.com/document/product/649/38335) 的返回值中的 ConfigId 字段来获取或通过登录[控制台](https://console.cloud.tencent.com/tse/tsf-consul?subTab=public)配置详情-配置版本页查看；也可以调用[CreatePublicConfig](https://cloud.tencent.com/document/product/649/38347)创建新的配置。
     */
    public String [] getConfigIdList() {
        return this.ConfigIdList;
    }

    /**
     * Set 配置ID列表，不传入时查询全量，低优先级。该参数可以通过调用 [DescribePublicConfigs](https://cloud.tencent.com/document/product/649/38335) 的返回值中的 ConfigId 字段来获取或通过登录[控制台](https://console.cloud.tencent.com/tse/tsf-consul?subTab=public)配置详情-配置版本页查看；也可以调用[CreatePublicConfig](https://cloud.tencent.com/document/product/649/38347)创建新的配置。
     * @param ConfigIdList 配置ID列表，不传入时查询全量，低优先级。该参数可以通过调用 [DescribePublicConfigs](https://cloud.tencent.com/document/product/649/38335) 的返回值中的 ConfigId 字段来获取或通过登录[控制台](https://console.cloud.tencent.com/tse/tsf-consul?subTab=public)配置详情-配置版本页查看；也可以调用[CreatePublicConfig](https://cloud.tencent.com/document/product/649/38347)创建新的配置。
     */
    public void setConfigIdList(String [] ConfigIdList) {
        this.ConfigIdList = ConfigIdList;
    }

    /**
     * Get 配置项名称，精确查询，不传入时查询全量。


id);
		if (i == end(sources)) {
			sources.push_back(info);
		} else if (*i == info) {
			return;
		} else {
			*i = info;
		}
		sort(list);
	};
	if (result.peer->isSelf()
		|| (result.peer->isChannel() && result.peer->asChannel()->amIn())
		|| (result.peer->isUser()
			&& (result.peer->asUser()->isBot()
				|| result.peer->asUser()->isContact()))
		|| result.peer->isServiceUser()) {
		const auto hidden = result.peer->hasStoriesHidden();
		using List = StorySourcesList;
		add(hidden ? List::Hidden : List::NotHidden);
		applyDeletedFromSources(
			peerId,
			hidden ? List::NotHidden : List::Hidden);
	} else {
		applyDeletedFromSources(peerId, StorySourcesList::NotHidden);
		applyDeletedFromSources(peerId, StorySourcesList::Hidden);
	}
	_sourceChanged.fire_copy(peerId);
	updatePeerStoriesState(result.peer);
}

Story *Stories::parseAndApply(
		not_null<PeerData*> peer,
		const MTPDstoryItem &data,
		TimeId now) {
	const auto media = ParseMedia(_owner, data.vmedia());
	if (!media) {
		return nullptr;
	}
	const auto expires = data.vexpire_date().v;
	const auto expired = (expires <= now);
	if (expired && !data.is_pinned() && !hasArchive(peer)) {
		return nullptr;
	}
	const auto id = data.vid().v;
	const auto fullId = FullStoryId{ peer->id, id };
	auto &stories = _stories[peer->id];
	const auto i = stories.find(id);
	if (i != end(stories)) {
		const auto result = i->second.get();
		const auto mediaChanged = (result->media() != *media);
		result->applyChanges(*media, data, now);
		const auto j = _pollingSettings.find(result);
		if (j != end(_pollingSettings)) {
			maybeSchedulePolling(result, j->second, now);
		}
		if (mediaChanged) {
			_preloaded.remove(fullId);
			if (_preloading && _preloading->id() == fullId) {
				_preloading = nullptr;
				rebuildPreloadSources(StorySourcesList::NotHidden);
				rebuildPreloadSources(StorySourcesList::Hidden);
				continuePreloading();
			}
			_owner->refreshStoryItemViews(fullId);
		}
		return result;
	}
	const auto wasDeleted = _deleted.remove(fullId);
	const auto result = stories.emplace(id, std::make_unique<Story>(
		id,
		peer,
		StoryMedia{ *media },
		data,
		now
	)).first->second.get();

	if (const auto archive = lookupArchive(peer)) {
		const auto added = archive->ids.list.emplace(id).second;
		if (added) {
			if (archive->total >= 0 && id > archive->lastId) {
				++archive->total;
			}
			_archiveChanged.fire_copy(peer->id);
		}
	}

	if (expired) {
		_expiring.remove(expires, fullId);
		applyExpired(fullId);
	} else {
		registerExpiring(expires, fullId);
	}

	if (wasDeleted) {
		_owner->refreshStoryItemViews(fullId);
	}

	return result;
}

StoryIdDates Stories::parseAndApply(
		not_null<PeerData*> peer,
		const MTPstoryItem &story,
		TimeId now) {
	return story.match([&](const MTPDstoryItem &data) {
		if (const auto story = parseAndApply(peer, data, now)) {
			return story->idD


= 3
		},
		flare = {
			chargeSz = 1,
			default = 72,
			increment = 3
		}
	},
	radar_can_see_ground = false,
	range = 12300,
	singleInFlight = false,
	stores_number = 2,
	swapped_names = true,
	tand


 appears in a function signature)
///
/// Implementing this all manually is of course possible, but it's tedious; why bother? This macro exists for
/// the purpose of doing it automatically:
///
/// ```ignore
/// delegated_subsystem!(ExampleJob(ExampleRunArgs) <- ExampleToJob as ExampleSubsystem);
/// ```
#[macro_export]
macro_rules! delegated_subsystem {
	($job:ident($run_args:ty, $metrics:ty) <- $to_job:ty as $subsystem:ident) => {
		delegated_subsystem!($job($run_args, $metrics) <- $to_job as $subsystem; stringify!($subsystem));
	};

	($job:ident($run_args:ty, $metrics:ty) <- $to_job:ty as $subsystem:ident; $subsystem_name:expr) => {
		#[doc = "Manager type for the "]
		#[doc = $subsystem_name]
		type Manager<Spawner, Context> = $crate::JobManager<Spawner, Context, $job>;

		#[doc = "An implementation of the "]
		#[doc = $subsystem_name]
		pub struct $subsystem<Spawner, Context> {
			manager: Manager<Spawner, Context>,
		}

		impl<Spawner, Context> $subsystem<Spawner, Context>
		where
			Spawner: Clone + $crate::reexports::SpawnNamed + Send + Unpin,
			Context: $crate::reexports::SubsystemContext,
			<Context as $crate::reexports::SubsystemContext>::Message: Into<$to_job>,
		{
			#[doc = "Creates a new "]
			#[doc = $subsystem_name]
			pub fn new(spawner: Spawner, run_args: $run_args, metrics: $metrics) -> Self {
				$subsystem {
					manager: $crate::JobManager::new(spawner, run_args, metrics)
				}
			}

			/// Run this subsystem
			pub async fn run(ctx: Context, run_args: $run_args, metrics: $metrics, spawner: Spawner) {
				<Manager<Spawner, Context>>::run(ctx, run_args, metrics, spawner, None).await
			}
		}

		impl<Spawner, Context> $crate::reexports::Subsystem<Context> for $subsystem<Spawner, Context>
		where
			Spawner: $crate::reexports::SpawnNamed + Send + Clone + Unpin + 'static,
			Context: $crate::reexports::SubsystemContext,
			<Context as $crate::reexports::SubsystemContext>::Message: Into<$to_job>,
		{
			type Metrics = $metrics;

			fn start(self, ctx: Context) -> $crate::reexports::SpawnedSubsystem {
				self.manager.start(ctx)
			}
		}
	};
}

/// A future that wraps another future with a `Delay` allowing for time-limited futures.
#[pin_project]
pub struct Timeout<F: Future> {
	#[pin]
	future: F,
	#[pin]
	delay: Delay,
}

/// Extends `Future` to allow time-limited futures.
pub trait TimeoutExt: Future {
	fn timeout(self, duration: Duration) -> Timeout<Self>
	where
		Self: Sized,
	{
		Timeout {
			future: self,
			delay: Delay::new(duration),
		}
	}
}

impl<F: Future> TimeoutExt for F {}

impl<F: Future> Future for Timeout<F> {
	type Output = Option<F::Output>;

	fn poll(self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Self::Output> {
		let this = self.project();

		if this.delay.poll(ctx).is_ready() {
			return Poll::Ready(None);
		}

		if let Poll::Ready(output) = this.future.poll(ctx) {
			return Poll::Ready(Some(output));
		}

		Poll::Pending
	}
}

#[cfg(test)]
mod tests {
	use super::{Er


2.181 3.755 9.771 9.771 0 00-.398 2.118 8.885 8.885 0 00-.012 1.07c.014.352.049.706.12 1.06.149-.325.282-.644.417-.953.136-.315.269-.62.409-.921.277-.602.565-1.175.878-1.726a15.084 15.084 0 012.161-2.96m1.773 29.133-.14.155c.522 1.501 1.28 2.742 2.122 3.888.827 1.164 1.77 2.195 2.784 3.15 1.019.949 2.104 1.825 3.307 2.568 1.189.762 2.46 1.43 3.964 1.84l.14-.154c-1.97-1.975-4.015-3.865-6.018-5.802-2.055-1.88-4.069-3.803-6.159-5.645m-4.16 2.969-.14.154c.694 1.664 1.624 3.065 2.637 4.374.999 1.323 2.114 2.519 3.299 3.635 1.191 1.109 2.448 2.147 3.823 3.052 1.361.922 2.803 1.753 4.479 2.324l.14-.154c-2.313-2.298-4.701-4.513-7.049-6.77-2.399-2.202-4.756-4.451-7.189-6.615m47.857 4.225c1.014-.955 1.957-1.986 2.784-3.15.842-1.146 1.6-2.387 2.121-3.888l-.14-.155c-2.089 1.842-4.104 3.765-6.158 5.646-2.004 1.937-4.049 3.827-6.019 5.802l.141.154c1.504-.41 2.774-1.078 3.963-1.84 1.204-.744 2.289-1.62 3.308-2.569m1.737 2.39c-2.348 2.257-4.734 4.472-7.048 6.77l.138.154c1.677-.571 3.119-1.402 4.479-2.324 1.374-.904 2.631-1.942 3.824-3.052 1.185-1.116 2.3-2.312 3.298-3.635 1.013-1.309 1.943-2.71 2.637-4.374l-.14-.154c-2.432 2.164-4.789 4.413-7.188 6.615"/></svg>';
  static const String bed =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="64" height="64" preserveAspectRatio="xMidYMid meet" viewBox="0 0 64 64"><path fill="currentColor" d="M60.026 39.445v-5.854l-5.82-1.464-.397-.744c-.469-.875-.856-1.433-1.154-1.657-.33-.255-.889-.394-1.42-.468-.401-.745-.676-.864-.835-.934a1.345 1.345 0 00-.536-.106c-.438 0-.967.208-1.408.43-.679-.729-1.063-.734-1.267-.736h-.224c-2.12 0-4.896.154-7.912.42l-.798-1.016c-.023-.03-2.393-3.065-3.031-5.41l-.116-.425v-8.232s-2.338.345-3.488-2.554h-1.031s-.27.111-.725.168c-.922-.105-2.119-.521-3.388-1


l, OriginalSemanticModel);

            EnumDeclaration.Identifier = syntaxNode.Identifier.ToString();

            if (EnumSymbol != null)
            {
                EnumDeclaration.Reference.Namespace = GetNamespace(EnumSymbol);
                EnumDeclaration.Reference.Assembly = GetAssembly(EnumSymbol);
                EnumDeclaration.Reference.Version = GetAssemblyVersion(EnumSymbol);
                EnumDeclaration.Reference.AssemblySymbol = EnumSymbol.ContainingAssembly;
                EnumDeclaration.FullIdentifier = EnumSymbol.OriginalDefinition.ToString();
            }
        }
    }
}


// Decompiled with JetBrains decompiler
// Type: Terraria.GameContent.WellFedHelper
// Assembly: Terraria, Version=1.4.0.5, Culture=neutral, PublicKeyToken=null
// MVID: 67F9E73E-0A81-4937-A22C-5515CD405A83
// Assembly location: C:\Program Files (x86)\Steam\steamapps\common\Terraria\Terraria.exe

namespace Terraria.GameContent
{
  public struct WellFedHelper
  {
    private const int MAXIMUM_TIME_LEFT_PER_COUNTER = 72000;
    private int _timeLeftRank1;
    private int _timeLeftRank2;
    private int _timeLeftRank3;

    public int TimeLeft
    {
      get
      {
        return this._timeLeftRank1 + this._timeLeftRank2 + this._timeLeftRank3;
      }
    }

    public int Rank
    {
      get
      {
        if (this._timeLeftRank3 > 0)
          return 3;
        if (this._timeLeftRank2 > 0)
          return 2;
        return this._timeLeftRank1 > 0 ? 1 : 0;
      }
    }

    public void Eat(int foodRank, int foodBuffTime)
    {
      int timeLeftToAdd = foodBuffTime;
      if (foodRank >= 3)
        this.AddTimeTo(ref this._timeLeftRank3, ref timeLeftToAdd, 72000);


.text
  .globl target
  .type target, @function

#! file-offset 0
#! rip-offset  0
#! capacity    5 bytes

# Text                                 #  Line  RIP   Bytes  Opcode
.target:                               #        0     0      OPC=<label>
  vpbroadcastq %xmm3, %xmm14           #  1     0     5      OPC=vpbroadcastq_xmm_xmm
  callq .move_128_64_xmm2_xmm12_xmm13  #  2     0x5   5      OPC=callq_label
  vunpckhps %xmm3, %xmm14, %xmm12      #  3     0xa   4      OPC=vunpckhps_xmm_xmm_xmm
  v


e.Date(2022, time.March, 17, 14, 5, 33, 0, time.UTC)))
	s.False(cc.matches(time.Date(2022, time.March, 17, 14, 15, 0, 0, time.UTC)))
	s.True(cc.matches(time.Date(2022, time.March, 18, 3, 9, 0, 0, pacific)))
	s.False(cc.matches(time.Date(2022, time.March, 18, 3, 9, 0, 0, time.UTC)))

	cc = s.mustCompileCalendarSpec(&schedulepb.CalendarSpec{
		Second:     "55",
		Minute:     "55",
		Hour:       "5",
		DayOfWeek:  "wed-thurs",
		DayOfMonth: "2/2",
	}, pacific)
	s.False(cc.matches(time.Date(2022, time.March, 9, 5, 55, 55, 0, pacific)))
	s.True(cc.matches(time.Date(2022, time.March, 10, 5, 55, 55, 0, pacific)))
	s.False(cc.matches(time.Date(2022, time.March, 14, 5, 55, 55, 0, pacific)))
	s.True(cc.matches(time.Date(2022, time.March, 16, 5, 55, 55, 0, pacific)))
	s.False(cc.matches(time.Date(2022, time.February, 9, 5, 55, 55, 0, pacific)))
	s.True(cc.matches(time.Date(2022, time.February, 10, 5, 55, 55, 0, pacific)))
	s.False(cc.matches(time.Date(2022, time.February, 10, 1, 55, 55, 0, pacific)))
	// match another zone
	s.True(cc.matches(time.Date(2022, time.March, 10, 13, 55, 55, 0, time.UTC)))
	// offset changes between march 10 and 16
	s.False(cc.matches(time.Date(2022, time.March, 16, 13, 55, 55, 0, time.UTC)))
	// correct offset
	s.True(cc.matches(time.Date(2022, time.March, 16, 12, 55, 55, 0, time.UTC)))

	// different sunday representations
	for _, dow := range []string{"0", "7", "sun", "*", "0-3", "5-7", "5-7/2", "6-7", "2-7/5", "0-7/7", "0/7"} {
		cc = s.mustCompileCalendarSpec(&schedulepb.CalendarSpec{
			DayOfWeek: dow,
		}, time.UTC)
		s.True(cc.matches(time.Date(2022, time.March, 6, 0, 0, 0, 0, time.UTC)), dow) // sunday
	}
	for _, dow := range []string{"*", "5-7", "6-7", "2/4", "2-7/4"} {
		cc = s.mustCompileCalendarSpec(&schedulepb.CalendarSpec{
			DayOfWeek: dow,
		}, time.UTC)
		s.True(cc.matches(time.Date(2022, time.March, 5, 0, 0, 0, 0, time.UTC)), dow) // saturday
	}
	for _, dow := range []string{"0", "7", "sun", "5-7", "5-7/2", "6-7", "2-7/5", "0-7/7", "0/7"} {
		cc = s.mustCompileCalendarSpec(&schedulepb.CalendarSpec{
			DayOfWeek: dow,
		}, time.UTC)
		s.False(cc.matches(time.Date(2022, time.March, 7, 0, 0, 0, 0, time.UTC)), dow) // monday
	}
}

func (s *calendarSuite) TestParseCronString() {
	scs, iv, tz, err := parseCronString("5,9 */2 * * *")
	s.NoError(err)
	s.Equal(&schedulepb.StructuredCalendarSpec{
		Second:     []*schedulepb.Range{{Start: 0}},
		Minute:     []*schedulepb.Range{{Start: 5}, {Start: 9}},
		Hour:       []*schedulepb.Range{{Start: 0, End: 23,


ame)
		} else {
			require.NoError(t, err, tc.name)
		}
	}
}

func TestIsLondon(t *testing.T) {
	testCases := []struct {
		name   string
		height int64
		result bool
	}{
		{
			"Before london block",
			5,
			false,
		},
		{
			"After london block",
			12_965_001,
			true,
		},
		{
			"london block",
			12_965_000,
			true,
		},
	}

	for _, tc := range testCases {
		ethConfig := params.MainnetChainConfig
		require.Equal(t, IsLondon(ethConfig, tc.height), tc.result)
	}
}
package cli

import (
	"io"

	"github.com/spf13/cobra"

	"github.com/hetznercloud/cli/internal/cmd/all"
	"github.com/hetznercloud/cli/internal/cmd/certificate"
	"github.com/hetznercloud/cli/internal/cmd/completion"
	configCmd "github.com/hetznercloud/cli/internal/cmd/config"
	"github.com/hetznercloud/cli/internal/cmd/context"
	"github.com/hetznercloud/cli/internal/cmd/datacenter"
	"github.com/hetznercloud/cli/internal/cmd/firewall"
	"github.com/hetznercloud/cli/internal/cmd/floatingip"
	"github.com/hetznercloud/cli/internal/cmd/image"
	"github.com/hetznercloud/cli/internal/cmd/iso"
	"github.com/hetznercloud/cli/internal/cmd/loadbalancer"
	"github.com/hetznercloud/cli/internal/cmd/loadbalancertype"
	"github.com/hetznercloud/cli/internal/cmd/location"
	"github.com/hetznercloud/cli/internal/cmd/network"
	"github.com/hetznercloud/cli/internal/cmd/placementgroup"
	"github.com/hetznercloud/cli/internal/cmd/primaryip"
	"github.com/hetznercloud/cli/internal/cmd/server"
	"github.com/hetznercloud/cli/internal/cmd/servertype"
	"github.com/hetznercloud/cli/internal/cmd/sshkey"
	"github.com/hetznercloud/cli/internal/cmd/util"
	"github.com/hetznercloud/cli/internal/cmd/version"
	"github.com/hetznercloud/cli/internal/cmd/volume"
	"github.com/hetznercloud/cli/internal/cmd/zone"
	"github.com/hetznercloud/cli/internal/state"
	"github.com/hetznercloud/cli/internal/state/config"
)

func NewRootCommand(s state.State) *cobra.Command {
	cmd := &cobra.Command{
		Use:                   "hcloud",
		Short:                 "Hetzner Cloud CLI",
		Long:                  "A command-line interface for Hetzner Cloud",
		TraverseChildren:      true,
		SilenceUsage:          true,
		SilenceErrors:         true,
		DisableFlagsInUseLine: true,
	}

	util.AddGroup(cmd, "resource", "Resources",
		all.NewCommand(s),
		floatingip.NewCommand(s),
		image.NewCommand(s),
		server.NewCommand(s),
		sshkey.NewCommand(s),
		servertype.NewCommand(s),
		datacenter.NewCommand(s),
		location.NewCommand(s),
		iso.NewCommand(s),
		volume.NewCommand(s),
		network.NewCommand(s),
		loadbalancer.NewCommand(s),
		loadbal


;
  final Function(FlutterWidgetBean, Offset)? onWidgetDragUpdate;
  final Function(FlutterWidgetBean, Offset)? onWidgetDragEnd;
  final List<FlutterWidgetBean> allWidgets;

  const FrameContainer({
    super.key,
    required this.widgetBean,
    this.scale = 1.0,
    this.touchController,
    this.selectionService,
    this.onWidgetSelected,
    this.onWidgetDragStart,
    this.onWidgetDragUpdate,
    this.onWidgetDragEnd,
    required this.allWidgets,
  });

  @override
  State<FrameContainer> createState() => _FrameContainerState();
}

class _FrameContainerState extends State<FrameContainer> {
  final GlobalKey _widgetKey = GlobalKey();
  bool _isPressed = false;
  late LayoutPropertyService _layoutPropertyService;

  @override
  void initState() {
    super.initState();
    _layoutPropertyService = LayoutPropertyService();
    _setupTouchController();
  }

  /// SKETCHWARE PRO STYLE: Setup touch controller callbacks
  void _setupTouchController() {
    widget.touchController?.setCallbacks(
      onWidgetSelected: widget.onWidgetSelected,
      onWidgetDragStart: widget.onWidgetDragStart,
      onWidgetDragUpdate: widget.onWidgetDragUpdate,
      onWidgetDragEnd: widget.onWidgetDragEnd,
      onWidgetLongPress: (widget) {
        print('🎯 FRAME CONTAINER LONG PRESS: ${widget.id}');
        // Handle long press feedback
      },
      onDragStateChanged: (isDragging) {
        print(
            '🎯 FRAME CONTAINER DRAG STATE: ${widget.widgetBean.id} - $isDragging');
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final isSelected =
        widget.selectionService?.isWidgetSelected(widget.widgetBean) ?? false;

    // SKETCHWARE PRO STYLE: Get exact position and size like ItemCardView
    final position = widget.widgetBean.position;
    final layout = widget.widgetBean.layout;

    // SKETCHWARE PRO STYLE: Convert dp to pixels like wB.a(context, value)
    final density = MediaQuery.of(context).devicePixelRatio;

    // SKETCHWARE PRO STYLE: Handle width/height like ViewPane.updateLayout()
    double? width = position.width * widget.scale;
    double? height = position.height * widget.scale;

    // SKETCHWARE PRO STYLE: Handle MATCH_PARENT and positive values
    if (layout.width == -1) {
      // MATCH_PARENT - Mobile frame handles width via Positioned(right: 0)
      width = null; // ✅ Let parent constraints determine width
    } else if (layout.width > 0) {
      width = layout.width * density * widget.scale;
    }

    if (layout.height == -1) {
      // MATCH_PARENT - Let Container handle full height
      height = null; // ✅ Let parent constraints determine height
    } else if (layout.height > 0) {
      height = layout.height * density * widget.scale;
    }

    return GestureDetector(
      // FLUTTER FIX: Ensure tap events are captured
      behavior: HitTestBehavior.opaque,
      onTap: () {
        // SKETCHWARE PRO STYLE: Handle widget selection on tap
        print('🎯 FRAME CONTAINER TAP: ${widget.widgetBean.id}');
        if (widget.selectionService != null) {
          widget.selectionService!.selectWidget(widget.widgetBean);
          print(
              '🎯 SELECTION SERVICE: Widget ${widget.widgetBean.id} selected');
        }
        _notifyWidgetSelected();
      },
      onTapDown: (details) {
        setState(() => _isPressed = true);
        _handleTouchStart(details.globalPosition);
      },
      onTapUp: (details) {
        setState(() => _isPressed = false);
        _handleTouchEnd(details.globalPosition);
      },
      onTapCancel: () {
        setState(() => _isPressed = false);
        _handleTouchCancel();
      },
      onPanStart: (details) {
        _handleTouchStart(details.globalPosition);
      }


es less than '0' become >= 208. */
            c = *p - '0';

            if (njs_slow_path(c > 9)) {
                if (literal && *p == '_' && (p - _) > 1) {
                    _ = p;
                    continue;
                }

                break;
            }

            if (pos < last) {
                *pos++ = *p;
                exponent--;

            } else {
                /* Ignore insignificant digits in the fractional part. */
            }
        }
    }

    if (pos == data) {
        return NAN;
    }

    e = p + 1;

    if (e < end && (*p == 'e' || *p == 'E')) {
        minus = 0;

        if (e + 1 < end) {
            if (*e == '-') {
                e++;
                minus = 1;

            } else if (*e == '+') {
                e++;
            }
        }

        /* Values less than '0' become >= 208. */
        c = *e - '0';

        if (njs_fast_path(c <= 9)) {
            exp = c;

            for (p = e + 1; p < end; p++) {
                /* Values less than '0' become >= 208. */
                c = *p - '0';

                if (njs_slow_path(c > 9)) {
                    if (literal && *p == '_' && (p - _) > 1) {
                        _ = p;
                        continue;
                    }

                    break;
                }

                if (exp < (INT_MAX - 9) / 10) {
                    exp = exp * 10 + c;
                }
            }

            exponent += minus ? -exp : exp;

        } else if (literal && *e == '_') {
            p = e;
        }
    }

done:

    *start = p;

    exponent += insignf;

    return njs_strtod_internal(data, pos - data, exponent);
}


;
; Jaguar Example Source Code
; Jaguar Workshop Series #12
; Copyright (c)1994 Atari Corp.
; ALL RIGHTS RESERVED
;
; Program: jr.cof      - Bitmap Rotation Example
;  Module: jr_list.s   - Object List Refresh and Initialization
;
; Revision History:
;  7/26/94 - SDS: Copied from MOU.COF sources
;

		.include        "jaguar.inc"
		.include        "jr.inc"

		.globl          InitLister
		.globl          UpdateList

		.extern         a_vde
		.extern         a_vdb
		.extern         a_hdb
		.extern         a_hde
		.extern         height
		.extern		width

		.text

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; InitLister: Initialize Object List Processor List
;
;    Returns: Pre-word-swapped address of current object list in d0.l
;
;  Registers: d1.l/d0.l - Phrase being built
;             d2.l      - Address of STOP object in destination buffer
;             d3.l      - Calculation register
;             d4.l      - Width of image in phrases
;             d5.l      - Height of image in scanlines
;             a0.l      - Roving object list pointer

InitLister:
		movem.l d1-d5/a0,-(sp)          ; Save registers

		lea     main_obj_list,a0
		move.l  a0,d2                   ; Copy

		add.l   #(LISTSIZE-1)*8,d2      ; Address of STOP object

; Write first BRANCH object (branch if YPOS > a_vde )

		clr.l   d1
		move.l  #(BRANCHOBJ|O_BRLT),d0 ; $4000 = YPOS > VC

		jsr     format_link             ; Stuff in our LINK address

		move.w  a_vde,d3                ; for YPOS
		lsl.w   #3,d3                   ; Make it bits 13-3
		or.w    d3,d0

		move.l  d1,(a0)+
		move.l  d0,(a0)+                ; First OBJ is done.

; Write second branch object (branch if YPOS < a_vdb)
; Note: LINK address is the same so preserve it

		andi.l  #$FF000007,d0           ; Mask off CC and YPOS
		ori.l   #O_BRGT,d0              ; $8000 = YPOS < VC
		move.w  a_vdb,d3                ; for YPOS
		lsl.w   #3,d3                   ; Make it bits 13-3
		or.w    d3,d0

		move.l  d1,(a0)+                ; Second OBJ is done
		move.l  d0,(a0)+

; Write a standard BITMAP object
		clr.l   d1
		clr.l   d0                      ; Type = BITOBJ

		jsr     format_link

		move.l  #BMP_HEIGHT,d5          ; Height of image
		move.w  d5,bmp_height           ; Store for later update

		lsl.l   #8,d5                   ; HEIGHT
		lsl.l   #6,d5
		or.l    d5,d0

		move.w  height,d3               ; Center bitmap vertically
		sub.w   #BMP_HEIGHT,d3
		add.w   a_vdb,d3
		andi.w  #$FFFE,d3


.define .cmu
.sect .text
.sect .rom
.sect .data
.sect .bss
.sect .text

! parameters:
!   hl   :  size (#bytes)
!   stack:  second operand
!	    first operand
!   stack:  result (out)

.cmu:
	! The two operands are compared byte by byte,
	! starting at the highest byte, until
	! they differ.
	pop ix		! return address
	pop hl		! #bytes
	ld b,h		! bc := hl
	ld c,l
	add hl,sp
	dec hl		! pointer to highest byte
			! of second operand
	ld d,h		! de := hl
	ld e,l
	add hl,bc	! pointer to highest byte
			! of first operand
	ld sp,hl	! points to where the
			! result will be stored
	ex de,hl
	! now, de points to highest byte of 1st operand
	!      sp   ,,		,,		,,
	!      hl   ,,		,,	    2nd	,,
	! bc contains #bytes

0:
	! loop, compare the two operands
	! byte by


 400));
    _expectTopLeft(6, const Offset(400, 400));
    _expectTopLeft(7, const Offset(600, 400));
  });

  testWidgets('AlignedGridView.extent control test',
      (WidgetTester tester) async {
    // Screen size is 800x600 in the test environment.
    final itemCount = 12;

    await tester.pumpWidget(
      Directionality(
        textDirection: TextDirection.ltr,
        child: AlignedGridView.extent(
          cacheExtent: 0,
          dragStartBehavior: DragStartBehavior.down,
          maxCrossAxisExtent: 200,
          itemBuilder: (context, index) {
            return Tile(
              index: index,
              height: ((index % 5) + 1) * 100,
            );
          },
          itemCount: itemCount,
        ),
      ),
    );

    void _expectSize(int index, Size size) {
      expect(tester.getSize(find.text('$index')), equals(size));
    }

    void _expectTopLeft(int index, Offset topLeft) {
      expect(tester.getTopLeft(find.text('$index')), equals(topLeft));
    }

    _expectSize(0, const Size(200, 400));
    _expectSize(1, const Size(200, 400));
    _expectSize(2, const Size(200, 400));
    _expectSize(3, const Size(200, 400));
    _expectSize(4, const Size(200, 500));
    _expectSize(5, const Size(200, 500));
    _expectSize(6, const Size(200, 500));
    _expectSize(7, const Size(200, 500));

    _expectTopLeft(0, const Offset(0, 0));
    _expectTopLeft(1, const Offset(200, 0));
    _expectTopLeft(2, const Offset(400, 0));
    _expectTopLeft(3, const Offset(600, 0));
    _expectTopLeft(4, const Offset(0, 400));
    _expectTopLeft(5, const Offset(200, 400));
    _expectTopLeft(6, const Offset(400, 400));
    _expectTopLeft(7, const Offset(600, 400));

    // Change orientation to portrait.
    await binding.setSurfaceSize(const Size(600, 800));
    await tester.pump();

    _expectSize(0, const Size(200, 300));
    _expectSize(1, const Size(200, 300));
    _expectSize(2, const Size(200, 300));
    _expectSize(3, const Size(200, 500));
    _expectSize(4, const Size(200, 500));
    _expectSize(5, const Size(200, 500));

    _expectTopLeft(0, const Offset(0, 0));
    _expectTopLeft(1, const Offset(200, 0));
    _expectTopLeft(2, const Offset(400, 0));
    _expectTopLeft(3, const Offset(0, 300));
    _expectTopLeft(4, const Offset(200, 300));
    _expectTopLeft(5, const Offset(400, 300));

    expect(find.text('6'), findsNothing);
    expect(find.text('7'), findsNothing);
  });
}
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/src/rendering/staggered_grid.dart';
import 'package:flutter_staggered_grid_view/src/widgets/staggered_grid.dart';

/// Represents the size of a [StaggeredGrid]'s tile.
class StaggeredGridTile extends ParentDataWidget<StaggeredGridParentData> {
  const StaggeredGridTile._({
    Key? key,
    required this.crossAxisCellCount,
    required this.mainAxisCellCount,
    required this.mainAxisExtent,
    required Widget child,
  })  : assert(crossAxisCellCount > 0),
        assert(mainAxisCellCount == null || mainAxisCellCount > 0),
        assert(mainAxisExtent == null || mainAxisExtent > 0),
        super(key: key, child: child);

  /// Creates a [StaggeredGrid]'s tile that takes a fixed number of cells along
  ///


'''
    Module: personas
    Author: Ivan
    Versión: 1.0
'''

from datetime import date
class Persona:

    def __init__(self, Nombre: str, Apellidos: str, DNI: str,FechaNacimiento: date) -> None:
        self.nombre = Nombre
        self.apellidos = Apellidos
        self.dni = DNI
        self.fecha_nacimiento = FechaNacimiento

    @property
    def nombre(self) -> str:
        return self._nombre

    @nombre.setter
    def nombre(self, Nombre: str) -> None:
        if not isinstance(Nombre,str):
            raise TypeError(f'Tipo de dato diferente a Str, {type(Nombre)}')
        if len(Nombre) > 50:
            raise ValueError(f'El tamaño del campo es demasiado elevado: {len(Nombre)}')
        self._nombre = Nombre

    @property
    def apellidos(self) -> str:
        return self._apellidos

    @apellidos.setter
    def apellidos(self, Apellidos: str) -> None:
        if not isinstance(Apellidos,str):
            raise TypeError(f'Tipo de dato diferente a Str, {type(Apellidos)}')
        if len(Apellidos) > 50:
            raise ValueError(f'El tamaño del campo es demasiado elevado: {len(Apellidos)}')
        self._apellidos = Apellidos

    @property
    def dni(self) -> str:
        return self._dni

    @dni.setter
    def dni(self, DNI: str) -> None:
        DIG_CONTROL = 'TRWAGMYFPDXBNJZSQVHLCKE'
        if not isinstance(DNI,str):
            raise TypeError(f'Tipo de dato diferente a Str, {type(DNI)}')
        if len(DNI) != 9:
            raise ValueError('Formato erroneo, Formato: 00000000X')
        dig_control = DNI[8]
        num_dni = DNI[:8]
        if not num_dni.isdigit():
            raise ValueError(f'Formato erroneo, Formato: 00000000X, DIN: {DNI}')
        if dig_control not in DIG_CONTROL:
            raise ValueError(f'Formato erroneo, Formato: 00000000X, DIN: {DNI}')
        self._dni = DNI

    @property
    def fecha_nacimiento(self) -> date:
        '''Python DocString'''
        return self._fecha_nacimiento

    @fecha_nacimiento.setter
    def fecha_nacimiento(self, Fecha: date):
        '''Python DocString'''
        if not isinstance(Fecha,date):
            raise TypeError(f'Tipo de dato diferente a timedate.date, {type(Fecha)}')
        if Fecha > date.today():
            raise ValueError(f'La Fecha no puede ser superion a la fecha actual: {Fecha}')
        self._fecha_nacimiento = Fecha

    def edad(self) -> int:
        '''Python DocString'''
        return (date.today() - self.fecha_nacimiento).days // 365

    def esMayorEdad(self)  -> bool:
        return self.edad() >= 18

    def esJoven(self) -> bool:
        return self.edad() >= 12 and self.edad() <= 18


.
    selector: 'my-heroes',

    // Com "Directives" informamos para o Component quais elementos HTML ele deve considerar
    // Sem este, ele ve <my-hero-detail> e considera uma tag comum.
    directives: [HeroDetailComponent],

    // Template do Componente.
    templateUrl: 'app/templates/heroes.component.html',

    // Styles do Componente.
    styleUrls: ['app/styles/heroes.component.css']
})
// OnInit é uma interface que contem método NgOnInit, parte do Lifecycle do Angular
// Este método será invocado no momento que o componente terminar de inicializar.
export class HeroesComponent implements OnInit {
    // Titulo do App.
    title = 'Tour of Heroes';

    // Listagem de Herois.
    heroes: Hero[];

    // Heroi selecionado.
    selectedHero: Hero;

    // Variavel para controle da interface.
    addingHero: boolean;

    // Variavel para manter valor de error.
    error: any;

    // Utilizamos o Constructor para Injetar objetos no Componente.
    // Desta forma, HeroService é injetado no AppComponent e é criado uma referência privada para este como "heroService".
    constructor(private router: Router, private heroService: HeroService) {

        // Invocar listagem de herois.
        // PORÉM ISTO É ERRADO!
        // this.getHeroes();
        // Deve se evitar lógicas complexas dentro de métodos de construção
        // Principalmente métodos relacionados a carregamento de informações.
    }

    // Método para selecionar heroi.
    onSelect(hero: Hero) {
        this.selectedHero = hero;
        this.addingHero = false;
    }

    // Método para recuperar lista de herois do Serviço.
    getHeroes() {
        // Não ira funcionar devido a alteração para utilização de Promise
        // this.heroes = this.heroService.getHeroes();

        // A Promise possui 2 métodos: Then e Catch. Then ocorre em sucesso. Catch, em erros.
        // "heroes" antes de "=>" é o parametro passado pelo Then.
        this.heroService.getHeroes()
            .then(heroes => this.heroes = heroes)
            .catch(error => this.error = error); // TODO: Display error message;
    }

    // Método invocado no momento que o componente termina de inicializar.
    ngOnInit() {
        this.getHeroes();
    }

    // Método invocado ao desejar detalhes de um heroi.
    gotoDetail() {
        // Criar array definindo um RouteLink, com Nome e Parameter Id
        let link = ['/form', this.selectedHero.id];

        // Invocar navegação.
        this.router.navigate(link);
    }

    // Método para gerenciar criação de um novo heroi.
    addHero() {
        this.addingHero = true;
        this.selectedHero = null;
    }

    // Método para fechar parte da interface para salvar heroi.
    // Quando ocorre evento "close" do HeroDetail é enviado um heroi, que foi salvo.
    // Este heroi então é passado para este método.
    close(savedHero: Hero) {
        this.addingHero = false;
        if (savedHero) {
            this.getHeroes();
        }
    }

    // Método para deletar heroi.
    delete(hero: Hero, event: any) {
        // Parar evento?
        event.stopPropagation();

        // Invocar serviço para deletar heroi.
        this.heroService
            .delete(hero)
            .then(response => {
                // Filtrar lista por sometne herois que não são o heroi deletado.
                this.heroes = this.hero


se } from "next";
import fs from "fs/promises";
import path from "path";
import { POSTS_DIR } from "../../src/posts";
import type { Post } from "../../src/types";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  switch (req.method.toLowerCase()) {
    case "post": {
      try {
        const body = JSON.parse(req.body) as Post;

        await fs.writeFile(
          path.join(POSTS_DIR, body.fileName),
          body.rawContent,
          {
            encoding: "utf-8",
          }
        );

        return res.status(200).json({ status: "updated" });
      } catch (err) {
        res.status(500).json({ status: "error", error: err.toString() });
      }
    }
    case "get": {
      // const postTitle =
    }
    default:
      // Method not allowed
      res.status(405);
  }
}
export function formatDate(date?: Date) {
  let publishedDate = null

  if (date) {
    const dateObj = new Date(date)
    const month = dateObj.getUTCMonth() + 1 //months from 1-12
    const day = dateObj.getUTCDate()
    const year = dateObj.getUTCFullYear()

    publishedDate = day + '/' + month + '/' + year
  }

  return publishedDate
}
import { BoundingBox, Line, Vector } from '../../src/common';
import { v00, v01, v11, v10, v33 } from './fixtures/Vectors';
import { ae, ed, da, af } from './fixtures/Lines';
import { limits } from '../../src/interfaces';

describe('common / BoundingBox', () => {
  it('should find its four corners', () => {
    const box: BoundingBox = new BoundingBox([v00, v01, v11, v10]);

    expect(box.topLeft).toEqual(v01);
    expect(box.topRight).toEqual(v11);
    expect(box.bottomLeft).toEqual(v00);
    expect(box.bottomRight).toEqual(v10);
  });

  it('should find its four bounding lines', () => {
    const box: BoundingBox = new BoundingBox([v00, v01, v11, v10]);
    const correct: Line[] = [ae, ed, da, af];

    expect(box.lines).toMatchObject(correct);
  });

  it('should find its limits', () => {
    const box: BoundingBox = new BoundingBox([v00, v01, v11, v10]);
    const correct: limits = {
      left: new Vector({ x: 0, y: 0.5 }),
      right: new Vector({ x: 1, y: 0.5 }),
      top: new Vector({ x: 0.5, y: 1 }),
      bottom: new Vector({ x: 0.5, y: 0 }),
    };

    expect(box.midpoints).toEqual(correct);
    expect(box.limits).toEqual(correct);
  });

  it('should know its area', () => {
    const box: BoundingBox = new BoundingBox([v00, v01, v33, v10]);

    expect(box.area).toBe(9);
  });
});
import { range, last, clamp } from 'lodash'
import heredoc from 'heredocument'

import Canvas from 'types/Canvas'
import Colour from 'types/Colour'
import Serializer from './Serializer'

const MAXIMUM_LINE_LENGTH = 70

export default class PpmSerializer implements Serializer {
  canvas: Canvas
  colourSpace: number

  constructor (colourSpace: number = 255) {
    this.colourSpace = colourSpace
  }

  render (canvas: Canvas): string {
    this.canvas = canvas
    return `${this.header()}\n${this.body()}\n`
  }

  private header (): string {
    return heredoc`
      P3
      ${this.canvas.width.toString()} ${this.canvas.height.toString()}
      ${this.colour


 {
  text-decoration: none;
}

.github-theme h1:hover .anchor .octicon-link,
.github-theme h2:hover .anchor .octicon-link,
.github-theme h3:hover .anchor .octicon-link,
.github-theme h4:hover .anchor .octicon-link,
.github-theme h5:hover .anchor .octicon-link,
.github-theme h6:hover .anchor .octicon-link {
  visibility: visible;
}

.github-theme h1:hover .anchor .octicon-link:before,
.github-theme h2:hover .anchor .octicon-link:before,
.github-theme h3:hover .anchor .octicon-link:before,
.github-theme h4:hover .anchor .octicon-link:before,
.github-theme h5:hover .anchor .octicon-link:before,
.github-theme h6:hover .anchor .octicon-link:before {
  width: 16px;
  height: 16px;
  content: ' ';
  display: inline-block;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' version='1.1' width='16' height='16' aria-hidden='true'%3E%3Cpath fill-rule='evenodd' d='M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z'%3E%3C/path%3E%3C/svg%3E");
}
.github-theme {
  -ms-text-size-adjust: 100%;
  -webkit-text-size-adjust: 100%;
  line-height: 1.5;
  color: #24292e;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial,
    sans-serif, Apple Color Emoji, Segoe UI Emoji;
  font-size: 16px;
  line-height: 1.5;
  word-wrap: break-word;
}

.github-theme details {
  display: block;
}

.github-theme summary {
  display: list-item;
}

.github-theme a {
  background-color: initial;
}

.github-theme a:active,
.github-theme a:hover {
  outline-width: 0;
}

.github-theme strong {
  font-weight: inherit;
  font-weight: bolder;
}

.github-theme h1 {
  font-size: 2em;
  margin: 0.67em 0;
}

.github-theme img {
  border-style: none;
}

.github-theme code,
.github-theme kbd,
.github-theme pre {
  font-family: monospace, monospace;
  font-size: 1em;
}

.github-theme hr {
  box-sizing: initial;
  height: 0;
  overflow: visible;
}

.github-theme input {
  font: inherit;
  margin: 0;
}

.github-theme input {
  overflow: visible;
}

.github-theme [type='checkbox'] {
  box-sizing: border-box;
  padding: 0


info("订单" + of.getOrder_id() + "购物减少可用预存款");
				log.setPd_type("可用预存款");
				this.predepositLogService.save(log);

				for (GoodsCart gc : of.getGcs()) {
					Goods goods = gc.getGoods();
					if ((goods.getGroup() != null) && (goods.getGroup_buy() == 2)) {
						for (GroupGoods gg : goods.getGroup_goods_list()) {
							if (gg.getGroup().getId().equals(goods.getGroup().getId())) {
								gg.setGg_count(gg.getGg_count() - gc.getCount());
								gg.setGg_def_count(gg.getGg_def_count() + gc.getCount());
								this.groupGoodsService.update(gg);
							}
						}
					}
					List gsps = new ArrayList();
					for (GoodsSpecProperty gsp : gc.getGsps()) {
						gsps.add(gsp.getId().toString());
					}
					String[] gsp_list = new String[gsps.size()];
					gsps.toArray(gsp_list);
					goods.setGoods_salenum(goods.getGoods_salenum() + gc.getCount());
					Map temp;
					if (goods.getInventory_type().equals("all")) {
						goods.setGoods_inventory(goods.getGoods_inventory() - gc.getCount());
					} else {
						List list = (List) Json.fromJson(ArrayList.class, goods.getGoods_inventory_detail());
						for (Iterator localIterator4 = list.iterator(); localIterator4.hasNext();) {
							temp = (Map) localIterator4.next();
							String[] temp_ids = CommUtil.null2String(temp.get("id")).split("_");
							Arrays.sort(temp_ids);
							Arrays.sort(gsp_list);
							if (Arrays.equals(temp_ids, gsp_list)) {
								temp.put("count",
										Integer.valueOf(CommUtil.null2Int(temp.get("count")) - gc.getCount()));
							}
						}
						goods.setGoods_inventory_detail(Json.toJson(list, JsonFormat.compact()));
					}
					for (GroupGoods gg : goods.getGroup_goods_list()) {
						if ((!gg.getGroup().getId().equals(goods.getGroup().getId())) || (gg.getGg_count() != 0))
							continue;
						goods.setGroup_buy(3);
					}

					this.goodsService.update(goods);
				}

			}

			OrderFormLog ofl = new OrderFormLog();
			ofl.setAddTime(new Date());
			ofl.setLog_info("预付款支付");
			ofl.setLog_user(SecurityUserHolder.getCurrentUser());
			ofl.setOf(of);
			this.orderFormLogService.save(ofl);
			mv.addObject("op_title", "预付款支付成功！");
			mv.addObject("url", CommUtil.getURL(request) + "/buyer/order.htm");
		} else {
			mv = new JModelAndView("error.html", this.configService.getSysConfig(),
					this.userConfigService.getUserConfig(), 1, request, response);
			mv.addObject("op_title", "可用余额不足，支付失败！");
			mv.addObject("url", CommUtil.getURL(request) + "/buyer/order.htm");
		}
		return mv;
	}

	@SecurityMapping(display = false, rsequence = 0, title = "订单支付结果", value = "/order_finish.htm*", rtype = "buyer", rname = "购物流程3", rcode = "goods_cart", rgroup = "在线购物")
	@RequestMapping({ "/order_finish.htm" })
	public ModelAndView order_finish(HttpServletRequest request, HttpSer


      }
      else {
        regWr(rMODE, MODE_FS_HOST); // start full-speed host
        vbusState = FSHOST;
      }
      break;
    case bmSE1: // illegal state
      vbusState = SE1;
      break;
    case bmSE0: // disconnected state
      regWr(rMODE, bmDPPULLDN | bmDMPULLDN | bmHOST | bmSEPIRQ);
      vbusState = SE0;
      break;
  }
}

// MAX3421 state change task and interrupt handler
uint8_t MAX3421e::Task() {
  return READ(USB_INTR_PIN) ? 0 : IntHandler();
}

uint8_t MAX3421e::IntHandler() {
  uint8_t HIRQ = regRd(rHIRQ), // determine interrupt source
          HIRQ_sendback = 0x00;
  if (HIRQ & bmCONDETIRQ) {
    busprobe();
    HIRQ_sendback |= bmCONDETIRQ;
  }
  // End HIRQ interrupts handling, clear serviced IRQs
  regWr(rHIRQ, HIRQ_sendback);
  return HIRQ_sendback;
}

#endif // USB_FLASH_DRIVE_SUPPORT
/**
 * Marlin 3D Printer Firmware
 * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
 *
 * Based on Sprinter and grbl.
 * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

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

#if ENABLED(MAGNETIC_PARKING_EXTRUDER)

#include "../gcode.h"
#include "../../module/tool_change.h"
#include "../../module/motion.h"

mpe_settings_t mpe_settings;

inline void mpe_settings_report() {
  SERIAL_ECHO_MSG("Magnetic Parking Extruder");
  SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR("L: Left parking  :", mpe_settings.parking_xpos[0]);
  SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR("R: Right parking :", mpe_settings.parking_xpos[1]);
  SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR("I: Grab Offset   :", mpe_settings.grab_distance);
  SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR("J: Normal speed  :", long(MMS_TO_MMM(mpe_settings.slow_feedrate)));
  SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR("H: High speed    :", long(MMS_TO_MMM(mpe_settings.fast_feedrate)));
  SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR("D: Distance trav.:", mpe_settings.travel_distance);
  SERIAL_ECHO_START(); SERIAL_ECHOLNPAIR("C: Compenstion   :", mpe_settings.compensation_factor);
}

void mpe_settings_init() {
  constexpr float pex[2] = PARKING_EXTRUDER_PARKING_X;
  mpe_settings.parking_xpos