eric plugin header, most easily done by
  * using the vmdplugin_HEAD macro.
  */
typedef struct {
  vmdplugin_HEAD
} vmdplugin_t;

/**
 * Use this macro to initialize the abiversion member of each plugin
 */
#define vmdplugin_ABIVERSION  17

/*@{*/
/** Use this macro to indicate a plugin's thread-safety at registration time */
#define VMDPLUGIN_THREADUNSAFE 0
#define VMDPLUGIN_THREADSAFE   1
/*@}*/

/*@{*/
/** Error return code for use in the plugin registration and init functions */
#define VMDPLUGIN_SUCCESS      0
#define VMDPLUGIN_ERROR       -1
/*@}*/

/**
 * Function pointer typedef for register callback functions
 */
typedef int (*vmdplugin_register_cb)(void *, vmdplugin_t *);

/**
 * Allow the library to register plugins with the application.
 * The callback should be called using the passed-in void pointer, which
 * should not be interpreted in any way by the library.  Each vmdplugin_t
 * pointer passed to the application should point to statically-allocated
 * or heap-allocated memory and should never be later modified by the plugin.
 * Applications must be permitted to retain only a copy of the the plugin
 * pointer, without making any deep copy of the items in the struct.
 */
VMDPLUGIN_EXTERN int VMDPLUGIN_register(void *, vmdplugin_register_cb);

/**
 * Allow the library to register Tcl extensions.
 * This API is optional; if found by dlopen, it will be called after first
 * calling init and register.
 */
VMDPLUGIN_EXTERN int VMDPLUGIN_register_tcl(void *, void *tcl_interp,
    vmdplugin_register_cb);

/**
 * The Fini method is called when the application will no longer use
 * any plugins in the library.
 */
VMDPLUGIN_EXTERN int VMDPLUGIN_fini(void);

#endif   /* VMD_PLUGIN_H */


/*------------------------------------------------------------------------
------------ forward input data downstream (re-buffer if Xowner)  --------
------------ primarily used to pass compressed data to a photomap --------
------------------------------------------------------------------------*/
static void forward_strip(flo,pet,fwd)
     floDefPtr	 flo;
     peTexPtr    pet;
     stripPtr    fwd;
{
  if(!pet->peDef->flags.putData) {
    /* non-client data -- just pass it along
     */
    fwd->flink = NULL;
    put_strip(flo,pet,fwd);		  /* give to downstream receptors */
    if(!fwd->flink)
      free_strip(flo,fwd);		  /* hmm, nobody wanted it	  */
  } else {
    /* since this is client data we must copy it before passing it along
     */
    stripLstPtr lst = &pet->outFlo->output[fwd->format->band];
    stripPtr    tmp =  ListEmpty(lst) ? NULL : lst->flink;
    int      maxlen =  flo->floTex->stripSize, datlen;
    int	    overlap =  tmp ? tmp->end - fwd->start + 1 : 0;
    int       start =  fwd->start  + overlap;
    int        size =  fwd->length - overlap;
    CARD8     *data = &fwd->data[overlap];
    Bool      final = FALSE;

    while(!final) {
      if(ListEmpty(lst))
	if(tmp = make_strip(flo, fwd->format, start, 0, maxlen, TRUE)) {
	  InsertMember(tmp,lst->flink);
	} else {
	  free_strip(flo,fwd);
	  AllocError(flo,pet->peDef, return);
	}
      if(size) {
	datlen = min(size, tmp->bufSiz - tmp->length);
	memcpy((char*)&tmp->data[tmp->length], (char*)data, (int)datlen);
	tmp->length += datlen;
	tmp->end    += datlen;
	data        += datlen;
	size        -= datlen;
      }
      if(!size && fwd->final || tmp->length == tmp->bufSiz) {
	RemoveMember(tmp,lst->flink);
	start        = tmp->start + tmp->length;
	tmp->final   = final = fwd->final && !size;
	tmp->canonic = fwd->canonic;
	tmp->flink   = NULL;
	put_strip(flo,pet,tmp);		  /* give to downstream receptors */
	if(!tmp->flink)
	  free_strip(flo,tmp);
      }
      if(!size)   break;
    }
    free_strip(flo,fwd);
  }
}                               /* end forward_strip */

/*------------------------------------------------------------------------
----------------------------- Get rid of a strip -------------------------
------------------------------------------------------------------------*/
static stripPtr	free_strip(flo, strip)
     floDefPtr  flo;
     stripPtr strip;
{
  lstPtr cache;

  if(strip && !--strip->refCnt) {
    /* since this was the last reference we're going to nuke this strip,
     * if this was a clone, free the parent and forget where the data was
     */
    if(strip->parent) {
      free_strip(flo, strip->parent);
      strip->data = NULL;
    } else if(strip->data) {
      /* if the data buffer belongs to coreX or is uncachable, nuke it */
      if(strip->Xowner)
	strip->data = NULL;
      else if(!flo || !strip->cache) {
	strip->data = (CARD8 *) XieFree(strip->data);
	BYTES -= strip->bufSiz; /*DEBUG*/
      }
    }
    if(flo) {
      /* strips with standard data buffers are cached at the front
       * strips without data buffers go at the back
       */
      strip->refCnt = 1;
      strip->parent = NULL;
      cache = (strip->data
	       ? (lstPtr)&flo->floTex->stripHead
	       : (lstPtr) flo->floTex->stripHead.blink);
      InsertMember(strip,cache);
    } else {
      XieFree(strip);
      --STRIPS; /*DEBUG*/
    }
  }
  return(NULL);
}                               /* end free_strip */

/* end module strip.c */


cast.com/category/podcast/">   The Bitcoin Podcast</option>
<option value="https://thebitcoinpodcast.com/category/hashitout/">   Hashing It Out</option>
<option value="https://thebitcoinpodcast.com/category/podcast/archived-podcasts/">Archive</option>
<option value="https://thebitcoinpodcast.com/category/announcements/">   Announcements</option>
<option value="https://thebitcoinpodcast.com/category/blocked-by-design/">   Blocked by Design</option>
<option value="https://thebitcoinpodcast.com/category/the-bull-pen-podcast/">   The Bull Pen Podcast</option>
<option value="https://thebitcoinpodcast.com/category/dose-of-ether/">   Dose of Ether</option>
<option value="https://thebitcoinpodcast.com/category/onramp/">   OnRamp</option>
<option value="https://thebitcoinpodcast.com/category/nftqt/">   NFTQT</option>
<option value="https://thebitcoinpodcast.com/contact/">Contact</option></select>

						<form action="https://thebitcoinpodcast.com/" method="get">
    <fieldset>
        <input type="text" name="s" id="search" value="Search">
    </fieldset>
</form>

  cognitive psychology

						Share

Tweet

										<div class="post post-6241 type-post status-publish format-standard has-post-thumbnail hentry category-blocked-by-design tag-bitcoin tag-blockchain tag-blocked-by-design tag-causal-loops tag-china tag-cognitive-psychology tag-columbia tag-consensys tag-content-strategy tag-content-testing tag-crypto-design tag-crypto-users tag-curse-of-knowledge-effect tag-customer-insights tag-decentralized-design tag-decentralized-organizations tag-design-


bers li{display:block;float:left;text-align:center}#wp_page_numbers li a{background-color:#fbfbfb;text-decoration:none;padding:3px 8px 3px 8px;display:block;float:left;margin:0 5px 5px 0;text-align:center;border:1px solid #fbfbfb;color:#acacac;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px}#wp_page_numbers li{color:#acacac}#wp_page_numbers li a:hover{border:1px solid #dedede}#wp_page_numbers .active_page a{opacity:.7;color:grey;text-shadow:0 1px 0 rgba(255,255,255,.15);border:1px solid rgba(0,0,0,.2);-moz-background-clip:padding;-webkit-background-clip:padding-box;background-clip:padding-box;background-color:#f2f2f2;background-image:url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEwMCAxMDAiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjxsaW5lYXJHcmFkaWVudCBpZD0iaGF0MCIgZ3JhZGllbnRVbml0cz0ib2JqZWN0Qm91bmRpbmdCb3giIHgxPSI1MCUiIHkxPSIxMTclIiB4Mj0iNTAlIiB5Mj0iLTE3JSI+CjxzdG9wIG9mZnNldD0iMCUiIHN0b3AtY29sb3I9IiMwMDAiIHN0b3Atb3BhY2l0eT0iMC4wNSIvPgo8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNmZmYiIHN0b3Atb3BhY2l0eT0iMC4wNSIvPgogICA8L2xpbmVhckdyYWRpZW50PgoKPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMCIgaGVpZ2h0PSIxMDAiIGZpbGw9InVybCgjaGF0MCkiIC8+Cjwvc3ZnPg==);background-image:-moz-linear-gradient(bottom,rgba(0,0,0,.05) -17%,rgba(255,255,255,.05) 117%);background-image:-o-linear-gradient(bottom,rgba(0,0,0,.05) -17%,rgba(255,255,255,.05) 117%);background-image:-webkit-linear-gradient(bottom,rgba(0,0,0,.05) -17%,rgba(255,255,255,.05) 117%);background-image:linear-gradient(bottom,rgba(0,0,0,.05) -17%,rgba(255,255,255,.05) 117%)}#wp_page_numbers li span{text-decoration:none;padding:3px 8px 3px 8px;display:block;float:left;margin:0 5px 5px 0;text-align:center;-moz-border-radius:3px;-webkit-border-radius:3px;border-radius:3px opacity:.7;color:grey;text-shadow:0 1px 0 rgba(255,255,255,.15);border:1px solid rgba(0,0,0,.2);-moz-background-clip:padding;-webkit-background-clip:padding-box;background-clip:padding-box;background-color:#f2f2f2;background-image:url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEwMCAxMDAiIHByZXNlcnZlQXN


u_1[:]= u

The program <tt>diffu1D_u0.py</tt>
contains a function solver_FE for solving the 1D diffusion equation
with \( u=0 \) on the boundary. The functions plug and gaussian
runs the case with \( I(x) \) as a discontinuous plug or a smooth
Gaussian function, respectively. Experiments with these two functions
reveal some important observations:

 The Forward Euler scheme leads to growing solutions if \( F>\half \).

 \( I(x) \) as a discontinuous plug leads to a saw tooth-like noise
   for \( F=\half \), see movie, which is absent for \( F\leq\frac{1}{4} \), see
   movie.

 The smooth Gaussian initial function leads to a smooth solution,
   see movie
   for \( F=\half \).

Backward Euler scheme

We now apply a backward difference in time in (272),
but the same central difference in space:

$$
\begin{equation}
[D_t^- u = D_xD_x u]^n_i,
\tag{276}
\end{equation}
$$

which written out reads

$$
\begin{equation}
\frac{u^{n}_i-u^{n-1}_i}{\Delta t} = \dfc\frac{u^{n}_{i+1} - 2u^n_i + u^n_{i-1}}{\Delta x^2} \tp
\tag{277}
\end{equation}
$$

Now we assume \( u^{n-1}_i \) is computed, but all quantities at the "new"
time level \( n \) are unknown. This time it is not possible to solve
with respect to \( u_i^{n} \) because this value couples to its neighbors
in space, \( u^n_{i-1} \) and \( u^n_{i+1} \), which are also unknown.
Let us examine this fact for the case when \( N_x=3 \). Equation (277) written for \( i=1,\ldots,Nx-1= 1,2 \) becomes

$$
\begin{align}
\frac{u^{n}_1-u^{n-1}_1}{\Delta t} &= \dfc\frac{u^{n}_{2} - 2u^n_1 + u^n_{0}}{\Delta x^2}
\tag{278}\\
\frac{u^{n}_2-u^{n-1}_2}{\Delta t} &= \dfc\frac{u^{n}_{3} - 2u^n_2 + u^n_{1}}{\Delta x^2}
\tag{279}
\end{align}
$$

The boundary values \( u^n_0 \) and \( u^n_3 \) are known as zero. Collecting the
unknown new values \( u^n_1 \) and \( u^n_2 \) on the left-hand side gives

$$
\begin{align}
\left(1+  2F\right) u^{n}_1 - F u^{n}_{2}    &= u^{n-1}_1,
\tag{280}\\
- F u^{n}_{1} + \left(1+  2


 data2;
  Node2I2A car;
  Node2I2A cdr;

  static double measuredObjectSize = 0.0;
  static int objectSize = 0;
  static Object fakeLock = new Object();

  // This should require no more than 28 Megs even with 3 word headers
  //
  public static void computeObjectSize() {
    int estimateSize = 1000000;
    while (true) {
      System.gc();
      long start = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
      Node2I2A head = new Node2I2A();
      Node2I2A cur = head;
      for (int i = 0; i < estimateSize; i++) {
        cur.cdr = new Node2I2A();
        cur = cur.cdr;
      }
      synchronized (fakeLock) {
        // This seemingly useless lock operation prevents the optimizing
        // compiler from doing redundant load elimination of the internal fields
        // used to compute freeMemory in the watson semispace collector.
        // Fairly amusing...at the HIR level there is of course nothing in the above loop
        // that would cause the compiler to think that the fields of VM_ContiguousHeap get changed.
        // Arguably the fields in question should be marked volatile, but injecting this
        // fake lock operation here causes us to obey the java memory model and not do the
        // redundant load elimination.
      }
      long end = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
      long used = end - start;
      if (used > 0) {
        measuredObjectSize = used / ((double) estimateSize);
        objectSize = (int) (measuredObjectSize + 0.5); // round to byte
        objectSize = (objectSize + 2) / 4 * 4; // round to word
        if (objectSize > 16)
          break;
      }
      estimateSize = (int) (0.75 * estimateSize);
      System.out.println("GC occured since used memory decreased after allocation or implausible object size obtained.  Retrying with " + estimateSize + " objects.");
    }
  }

  public static Node2I2A createTree(int nodes) {
    if (nodes == 0) return null;
    int children = nodes - 1;
    int left = children / 2;
    int right = children - left;
    Node2I2A self = new Node2I2A();
    self.car = createTree(left);
    self.cdr = createTree(right);
    return self;
  }
}
/*
 *  This file is part of the Jikes RVM project (http://jikesrvm.org).
 *
 *  This file is licensed to You under the Eclipse Public License (EPL);
 *  You may not use this file except in compliance with the License. You
 *  may obtain a copy of the License at
 *
 *      http://www.opensource.org/licenses/eclipse-1.0.php
 *
 *  See the COPYRIGHT.txt file distributed with this work for information
 *  regarding copyright ownership.
 */
package test.org.jikesrvm.basic.core.intrinsics;

import org.jikesrvm.VM;
import org.jikesrvm.runtime.SysCall;

public class TestSysCalls {

  public static void main(String[] args) {
    testArgumentPassingForSysCalls();
  }

  public static void testArgumentPassingForSysCalls() {
    VM.sysWriteln("Test argument passing: longs and doubles");

    SysCall.sysCall.sysArgumentPassingSeveralLongsAndSeveralDoubles(Long.MIN_VALUE, Long.MAX_VALUE, -1L, 1L, 0xFFFF0000FFFF0000L, 0x0000FFFF0000FFFFL, 0, -1L, Double.MIN_VALUE, Double.MAX_VALUE, -1D, 0.1D, 1.2345678910E300D, Double.NaN, Double.MAX_VALUE, -1


0 * (max(buffer.shape[1], buffer.shape[2]) - self.short_side_size) / 2
                spatial_start = int(spatial_step)
            else:
                spatial_step = 1.0 * (max(buffer.shape[1], buffer.shape[2]) - self.short_side_size) \
                                    / (self.test_num_crop - 1)
                spatial_start = int(split_nb * spatial_step)
            if buffer.shape[1] >= buffer.shape[2]:
                buffer = buffer[:, spatial_start:spatial_start + self.short_side_size, :, :]
            else:
                buffer = buffer[:, :, spatial_start:spatial_start + self.short_side_size, :]

            buffer = self.data_transform(buffer)
            return buffer, self.test_label_array[index], sample.split("/")[-1].split(".")[0], \
                   chunk_nb, split_nb
        else:
            raise NameError('mode {} unkown'.format(self.mode))

    def _aug_frame(
        self,
        buffer,
        args,
    ):

        aug_transform = create_random_augment(
            input_size=(self.crop_size, self.crop_size),
            auto_augment=args.aa,
            interpolation=args.train_interpolation,
        )

        buffer = [
            transforms.ToPILImage()(frame) for frame in buffer
        ]

        buffer = aug_transform(buffer)

        buffer = [transforms.ToTensor()(img) for img in buffer]
        buffer = torch.stack(buffer) # T C H W
        buffer = buffer.permute(0, 2, 3, 1) # T H W C

        # T H W C
        buffer = tensor_normalize(
            buffer, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
        )
        # T H W C -> C T H W.
        buffer = buffer.permute(3, 0, 1, 2)
        # Perform data augmentation.
        scl, asp = (
            [0.08, 1.0],
            [0.75, 1.3333],
        )

        buffer = spatial_sampling(
            buffer,
            spatial_idx=-1,
            min_scale=256,
            max_scale=320,
            crop_size=self.crop_size,
            random_horizontal_flip=False if args.data_set == 'SSV2' else True ,
            inverse_uniform_sampling=False,
            aspect_ratio=asp,
            scale=scl,
            motion_shift=False
        )

        if self.rand_erase:
            erase_transform = RandomErasing(
                args.reprob,
                mode=args.remode,
                max_count=args.recount,
                num_splits=args.recount,
                device="cpu",
            )
            buffer = buffer.permute(1, 0, 2, 3)
            buffer = erase_transform(buffer)
            buffer = buffer.permute(1, 0, 2, 3)

        return buffer

    def _get_seq_frames(self, video_size, start, end, num_frames, clip_idx=-1):
        # 确保 start 和 end 在视频大小范围内
        start = max(0, min(start, video_size - 1))
        end = max(start, min(end, video_size - 1))

        # 计算裁剪后视频的实际大小
        clipped_video_size = end - start + 1
        seg_size = max(0., float(clipped_video_size - 1) / num_frames)
        seq = []

        if clip_idx == -1:
            for i in range(num_frames):
                start_frame = int(np.round(seg_size * i)) + start
                end_frame = int(np.round(seg_size * (i + 1))) + start
                idx = min(random.randint(start_frame, end_frame), end)
                seq.append(idx)
        else:
            num_segment = 1
            if self.mode == 'test':
                num_segment = self.test_num_segment
            duration = seg_size / (num_segment + 1)
            for i in range(num_frames):
                start_frame = int(np.round(seg_size * i)) + start
                frame_index = start_frame + int(duration * (clip_idx + 1))
                idx = min(frame_index, end)
                seq.append(idx)
        return seq

    def loadvideo_decord(self, sample, start, end, chunk_nb=0):
        """Load video content using Decord"""
        fname = sample
        fname = os.path.join(self.prefix, fname)

        try:
            if self.keep_aspect_ratio:
                if "s3://" in fname:
                    video_bytes = self.client.get(fname)
                    vr = VideoReader(io.BytesIO(video_bytes),
                                     num_threads=1,
                                     ctx=cpu(0))
                else:
                    vr = VideoReader(fname, num_threads=1, ctx=cpu(0))
            else:
                if "s3://" in fname:
                    video_bytes = self.client.get(fname)
                    vr = VideoReader(io.BytesIO(vid


/* This is the memory initialization functions, the function
 * implemented below initializes each memory controller
 * found and specified by the input grlib_mctrl_handler structure.
 *
 * After the memory controllers have been initialized the stack
 * can be used.
 *
 * (C) Copyright 2010, 2015
 * Daniel Hellstrom, Cobham Gaisler, daniel@gaisler.com.
 *
 * SPDX-License-Identifier:	GPL-2.0+
 */

#include <ambapp.h>
#include "memcfg.h"
#include <config.h>

	.seg	"text"
	.globl	_nomem_memory_ctrl_init
	.globl	_nomem_mctrl_init, _nomem_ahbmctrl_init
	.extern	_nomem_find_apb
	.extern	_nomem_find_ahb

/* FUNCTION
 *   _nomem_memory_controller_init(struct grlib_mctrl_handler *mem_handlers)
 *
 * Initialize AMBA devices, _nomem_amba_init() has prepared i0-i5
 * with the AHB buses on the system.
 *
 * For each entry in mem_handlers find the VENDOR:DEVICE and handle it
 * by calling the handler function pointer.
 *
 * Constraints:
 *  i6, i7, o6, l7, l6, g3, g4, g5, g6, g7 is used by caller
 *  o7 is return address
 *  l5 reserved for this function for future use.
 *
 * Arguments
 *  - o0 Pointer to memory handler array
 *
 * Results
 *  - o0 Number of memory controllers found
 *
 * Clobbered
 *  - o0 (Current AHB slave conf address)
 *  - l0 (mem handler entry address)
 *  - l1 (Return value, number of memory controllers found)
 *  - o7 (function pointer)
 *  - l0, l1, l2, l3, l4, g1, g2 (used by _nomem_ambapp_find_buses)
 *  - o0, o1, o2, o3, o4, o5 (Used as arguments)
 *
 *  - g1 ( level 1 return address)
 *  - g2 ( level 2 return address)
 */

_nomem_memory_ctrl_init:
	/* At this point all AHB buses has been found and the I/O Areas of
	 * all AHB buses is stored in the i0-i5 registers. Max 6 buses. Next,
	 * memory controllers are found by searching all buses for matching
	 * VENDOR:DEVICE. The VENDOR:DEVICE to search for are taken from the
	 * mem_handlers array. For each match the function pointer stored in
	 * the mem_handler entry is called to handle the hardware setup.
	 */
	mov	%o7, %g1	/* Save return address */
	mov	%o0, %l0
	mov	%g0, %l1	/* The return value */

.L_do_one_mem_handler:
	ld	[%l0 + MH_FUNC], %o7
	cmp	%o7, %g0
	be	.L_all_mctrl_handled
	 nop

	/*** Scan for memory controller ***/

	/* Set up argments, o5 not used by _nomem_find_apb */
	ldub	[%l0 + MH_TYPE], %o5
	clr	%o4
	clr	%o3
	ldub	[%


inary
     * analysis tools. It is not used when compiling all the testcases as one
     * application, which is how source code analysis tools are tested.
     */
    public static void main(String[] args) throws ClassNotFoundException,
           InstantiationException, IllegalAccessException
    {
        mainFromParent(args);
    }
}
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE259_Hard_Coded_Password__kerberosKey_54b.java
Label Definition File: CWE259_Hard_Coded_Password.label.xml
Template File: sources-sink-54b.tmpl.java
*/
/*
 * @description
 * CWE: 259 Hard Coded Password
 * BadSource: hardcodedPassword Set data to a hardcoded string
 * GoodSource: Read data from the console using readLine()
 * Sinks: kerberosKey
 *    BadSink : data used as password in KerberosKey()
 * Flow Variant: 54 Data flow: data passed as an argument from one method through three others to a fifth; all five functions are in different classes in the same package
 *
 * */

package testcases.CWE259_Hard_Coded_Password;

import testcasesupport.*;

import java.util.logging.Level;
import java.io.*;

public class CWE259_Hard_Coded_Password__kerberosKey_54b
{
    public void badSink(String data ) throws Throwable
    {
        (new CWE259_Hard_Coded_Password__kerberosKey_54c()).badSink(data );
    }

    /* goodG2B() - use goodsource and badsink */
    public void goodG2BSink(String data ) throws Throwable
    {
        (new CWE259_Hard_Coded_Password__kerberosKey_54c()).goodG2BSink(data );
    }
}
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE259_Hard_Coded_Password__kerberosKey_81_goodG2B.java
Label Definition File: CWE259_Hard_Coded_Password.label.xml
Template File: sources-sink-81_goodG2B.tmpl.java
*/
/*
 * @description
 * CWE: 259 Hard Coded Password
 * BadSource: hardcodedPassword Set data to a hardcoded string
 * GoodSource: Read data from the console using readLine()
 * Sinks: kerberosKey
 *    BadSink : data used as password in KerberosKey()
 * Flow Variant: 81 Data flow: data passed in a parameter to an abstract method
 *
 * */

package testcases.CWE259_Hard_Coded_Password;

import testcasesupport.*;

import java.util.logging.Level;
import java.io.*;

import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.kerberos.KerberosKey;

public class CWE259_Hard_Coded_Password__kerberosKey_81_goodG2B extends CWE259_Hard_Coded_Password__kerberosKey_81_base
{
    public void action(String data ) throws Throwable
    {

        if (data != null)
        {
            KerberosPrincipal principal = new KerberosPrincipal("test");
            /* POTENTIAL FLAW: data used as password in KerberosKey() */
            KerberosKey key = new KerberosKey(principal, data.toCharArray(), null);
            IO.writeLine(key.toString());
        }

    }
}
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE259_Hard_Coded_Password__driverManager_53a.java
Label Definition File: CWE259_Hard_Coded_Password.label.xml
Template File: sources-sink-53a.tmpl.java
*/
/*
 * @description
 * CWE: 259 Hard Coded Password
 * BadSource: hardcodedPassword Set data to a hardcoded string
 * GoodSource: Read data from the console using readLine()
 * Sinks: driverManager
 *    BadSink : data used as password in database connection
 * Flow Variant: 53 Data flow: data passed as an argument from one method through two others to a fourth; all four functions are in different classes in the same package
 *
 * */

package testcases.CWE259_Hard_Coded_Password;

import testcasesupport.*;

import java.util.logging.Level;


kDebugMode) {
        //print('[StoryFlowchart] 保存失败: $e');
      }
    }
  }

  /// 添加或更新节点
  Future<void> addOrUpdateNode(StoryFlowNode node) async {
    _nodes[node.id] = node;

    // 如果是章节节点且没有父节点，添加到根节点列表
    if (node.type == StoryNodeType.chapter && node.parentNodeId == null) {
      if (!_rootNodeIds.contains(node.id)) {
        _rootNodeIds.add(node.id);
      }
    }

    // 更新父节点的子节点列表
    if (node.parentNodeId != null) {
      final parentNode = _nodes[node.parentNodeId];
      if (parentNode != null) {
        final updatedChildren = List<String>.from(parentNode.childNodeIds);
        if (!updatedChildren.contains(node.id)) {
          updatedChildren.add(node.id);
          _nodes[node.parentNodeId!] = parentNode.copyWith(
            childNodeIds: updatedChildren,
          );
        }
      }
    }

    await save();
    notifyListeners();
  }

  /// 解锁节点（玩家到达该节点时调用）
  Future<void> unlockNode(String nodeId, {String? autoSaveId}) async {
    final node = _nodes[nodeId];
    if (node != null && !node.isUnlocked) {
      _nodes[nodeId] = node.copyWith(
        isUnlocked: true,
        firstReachedTime: DateTime.now(),
        autoSaveId: autoSaveId ?? node.autoSaveId,
      );

      _currentNodeId = nodeId;
      await save();
      notifyListeners();

      if (kDebugMode) {
        //print('[StoryFlowchart] 解锁节点: ${node.displayName} ($nodeId)');
      }
    }
  }

  /// 创建自动存档并关联到节点
  Future<String?> createAutoSaveForNode(
    String nodeId,
    SaveSlot saveSlot,
  ) async {
    try {
      final node = _nodes[nodeId];
      if (node == null) return null;

      // 使用节点ID作为文件名（语言无关）
      final autoSaveId = '${autoSavePrefix}$nodeId';

      // 直接保存为文件（参考 SaveLoadManager 的实现）
      final saveLoadManager = SaveLoadManager();
      final directory = await saveLoadManager.getSavesDirectory();
      final file = File('$directory/$autoSaveId.sakisav');

      final binaryData = saveSlot.toBinary();
      await file.writeAsBytes(binaryData);

      // 更新节点关联
      _nodes[nodeId] = node.copyWith(autoSaveId: autoSaveId);
      await save();

      if (kDebugMode) {
        //print('[StoryFlowchart] 为节点 $nodeId (${node.displayName}) 创建自动存档文件: $autoSaveId.sakisav');
      }

      return autoSaveId;
    } catch (e) {
      if (kDebugMode) {
        //print('[StoryFlowchart] 创建自动存档失败: $e');
      }
      return null;
    }
  }

  /// 获取节点的子节点列表
  List<StoryFlowNode> getChildNodes(String nodeId) {
    final node = _nodes[nodeId];
    if (node == null) return [];

    return node.childNodeIds
        .map((id) => _nodes[id])
        .whereType<StoryFlowNode>()
        .toList();
  }

  /// 获取节点的父节点
  StoryFlowNode? getParentNode(String nodeId) {
    final node = _nodes[nodeId];
    if (node?.pare


class EPUBError(Exception):
    """Base exception class for EPUB processing"""
    pass

class ChapterError(EPUBError):
    """Exception for chapter processing"""
    pass

class MetadataError(EPUBError):
    """Exception for metadata processing"""
    pass

class TOCError(EPUBError):
    """Exception for table of contents generation"""
    pass

class ContentGenerationError(EPUBError):
    """Exception for content generation"""
    pass

class FileHandlerError(EPUBError):
    """Exception for file handling"""
    pass

class TextProcessingError(EPUBError):
    """Exception for text processing"""
    pass


fdAvatar_BackgroundColor);
    --fdAvatarBorderRadius: var(--sapElement_BorderCornerRadius);
    --fdAvatarBoxShadow: none;
    --fdAvatarHoverBorderColor: var(--sapAvatar_6_TextColor);
    --fdAvatarHoverBackgroundColor: var(--fdAvatar_Accent_Color_Hover_6);
    --fdAvatarHoverBorder: 0.0625rem solid var(--fdAvatarHoverBorderColor);
    --fdAvatarZoomIconFontSize: 0.75rem;
    --fdAvatarZoomIconDimensions: 1.125rem;
    --fdAvatar_BackgroundColor: var(--sapAccentColor6);
    --fdAvatar_Border_Color: transparent;
    --fdAvatar_Text_Shadow: var(--sapContent_ContrastTextShadow);
    --fdAvatar_Color: var(--sapContent_ContrastTextColor);
    --fdAvatar_Tile_BackgroundColor: var(--sapTile_IconColor);
    --fdAvatar_Tile_BorderColor: transparent;
    --fdAvatar_Tile_TextColor: var(--sapContent_ContrastTextColor);
    --fdAvatar_Tile_BackgroundColor_Hover: var(--sapTile_IconColor);
    --fdAvatar_Placeholder_BorderColor: transparent;
    --fdAvatar_Placeholder_BackgroundColor_Hover: var(--sapContent_ImagePlaceholderBackground);
    --fdAvatar_Transparent_BorderColor: transparent;
    --fdAvatar_Transparent_BackgroundColor: transparent;
    --fdAvatar_Transparent_BackgroundColor_Hover: transparent;
    --fdAvatar_Overflow_BorderColor: var(--sapButton_BorderColor);
    --fdAvatar_Overflow_BackgroundColor: var(--sapButton_Background);
    --fdAvatar_Overflow_TextColor: var(--sapButton_TextColor);
    --fdAvatar_Overflow_Border_Width: 0.0625rem;
    --fdAvatar_Thumbnail_BorderColor: transparent;
    --fdAvatar_Focus_Outline_Offset: -0.1875rem;
    --fdAvatar_Focus_Outline_Radius: 0;
    --fdAvatar_Focus_Outline_Radius_Circle: 0;
    --fdAvatar_Accent_Color_1: var(--sapAccentColor1);
    --fdAvatar_Accent_Color_2: var(--sapAccentColor2);
    --fdAvatar_Accent_Color_3: var(--sapAccentColor3);
    --fdAvatar_Accent_Color_4: var(--sapAccentColor4);
    --fdAvatar_Accent_Color_5: var(--sapAccentColor5);
    --fdAvatar_Accent_Color_6: var(--sapAccentColor6);
    --fdAvatar_Accent_Color_7: var(--sapAccentColor7);
    --fdAvatar_Accent_Color_8: var(--sapAccentColor8);
    --fdAvatar_Accent_Color_9: var(--sapAccentColor9);
    --fdAvatar_Accent_Color_10: var(--sapAccentColor10);
    --fdAvatar_Accent_Color_1_Text: var(--sapContent_ContrastTextColor);
    --fdAvatar_Accent_Color_2_Text: var(--sapContent_ContrastTextColor);
    --fdAvatar_Accent_Color_3_Text: var(--sapContent_ContrastTextColor);
    --fdAvatar_Accent_Color_4_Text: var(--sapContent_ContrastTextColor);
    --fdAvatar_Accent_Color_5_Text: var(--sapContent_ContrastTextColor);
    --fdAvatar_Accent_Color_6_Text: var(--sapContent_Con


    left: @h-spacing-md;
  }

  &-placement-bottomRight &-arrow {
    right: @h-spacing-md;
  }
}
.am-notice-bar {
  background-color: #fefcec;
  height: 36px;
  overflow: hidden;
  font-size: 14px;
  line-height: 36px;
  color: #f76a24;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
}
.am-notice-bar-content {
  -webkit-box-flex: 1;
  -webkit-flex: 1;
      -ms-flex: 1;
          flex: 1;
  width: 100%;
  margin: auto 15px;
  width: auto;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.am-notice-bar-icon {
  margin-left: 15px;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -webkit-align-items: center;
      -ms-flex-align: center;
          align-items: center;
}
.am-notice-bar-icon .am-notice-bar-trips {
  background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg%20width%3D%2238%22%20height%3D%2233%22%20viewBox%3D%220%200%2038%2033%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Ctitle%3Etrips%3C%2Ftitle%3E%3Cg%20fill-rule%3D%22evenodd%22%3E%3Cpath%20d%3D%22M17.838%2028.8c-.564-.468-1.192-.983-1.836-1.496-4.244-3.385-5.294-3.67-6.006-3.67-.014%200-.027.005-.04.005-.015%200-.028-.005-.042-.005H3.562c-.734%200-.903-.203-.903-.928V10.085c0-.49.058-.8.66-.8h5.782c.693%200%201.758-.28%206.4-3.628.828-.597%201.637-1.197%202.336-1.723V28.8zM19.682.19c-.463-.22-1.014-.158-1.417.157-.02.016-1.983%201.552-4.152%203.125C10.34%206.21%209.243%206.664%209.02%206.737H3.676c-.027%200-.053.003-.08.004H1.183c-.608%200-1.1.486-1.1%201.085V25.14c0%20.598.492%201.084%201.1%201.084h8.71c.22.08%201.257.55%204.605%203.24%201.947%201.562%203.694%203.088%203.712%203.103.25.22.568.333.89.333.186%200%20.373-.038.55-.116.48-.213.79-.684.79-1.204V1.38c0-.506-.294-.968-.758-1.19z%22%20mask%3D%22url(%23mask-2)%22%2F%3E%3Cpath%20d%3D%22M31.42%2016.475c0-3.363-1.854-6.297-4.606-7.876-.125-.066-.42-.192-.625-.192-.612%200-1.108.488-1.108%201.09%200%20.404.22.764.55.952%202.128%201.19%203.565%203.442%203.565%206.025%200%202.627-1.486%204.913-3.677%206.087-.318.19-.53.54-.53.934%200%20.602.496%201.09%201.107%201.09.26.002.568-.15.568-.15%202.835-1.556%204.754-4.538%204.754-7.96%22%20mask%3D%22url


参数中了预留了一个 128 字节的最小存储，因为这些字节不可用存储特定的程序。因此，`solanarent 5` 实际的余额是 133 字节（即 128 + 5）。

# SPL 代币是什么
SPL 代币是在 Solana 区块链生态系统中运行的数字资产。管理 SPL 代币的代码由 Solana Labs 部署，它是 Solana 程序库的一部分。举个例子，与以太坊形成鲜明对比的是，以太坊上的每个代币都必须有自己的合约，而 Solana 上的代币则重复使用现有的合约。

涉及 SPL 代币的交易费用可以使用该平台的原生代币 SOL 支付。

## SPL代币的特点
SPL代币与其他区块链生态系统中的代币标准不同，例如以太坊的ERC标准、波场（TRON）的TRC-20和币安智能链的BEP-20。 SPL 代币的主要特征包括：

- NFT 和可替代代币的适用性：SPL 代币涵盖同一标准下的可替代（可互换）和不可替代（唯一）代币。 （而以太坊对每种代币类型都有单独的标准。）

- 可组合性：代币代码可以重复使用，从而用最小的更改即可创建新的 SPL 代币。这种可组合性意味着开发人员可以通过仅更改某些参数来快速地生成新代币。

- 效率：SPL 代币直接受益于 Solana 区块链的高性能。该网络的高处理速度提高了 SPL 代币的交易效率，使这些代币比其他区块链上的操作更快、更具成本效益。

# 什么是 Token-2022?
Solana 的 [Token-2022 计划](https://spl.solana.com/token-2022)（也称为Token Extensions）是一种新的实现方式。它在一定程度上向下兼容原来的 SPL 代币。然而，它是一个不同的程序，具有单独的源代码并部署在不同的地址。

Token Extensions扩大了 SPL 代币的铸造和使用范围，使用户能够在更广泛的应用中使用 SPL 代币，例如机密交易、创新合规机制、引入代币转让费用等。Token Extensions同时兼容可替代和不可替代代币。

尽管该计划于 2022 年推出，但 Beta 测试在最近才完成，这为智能合约开发提供了机会。然而，在撰写本文时，程序仍然在更新并有进一步的更改，并暂定计划在 2024 年晚些时候冻结更新。

Token-2022


`, {@link ClearStatus.playStyle playStyle} and {@link ClearStatus.level level}.
 * @description
 * - No need Authentication. Authenticated users can get their own data even if they are private.
 * - `GET api/v1/users/:id/clear?style=:style&lv=:lv`
 *   - `id`: `UserSchema.id`
 *   - `style`(optional): {@link ClearStatus.playStyle}
 *   - `lv`(optional): {@link ClearStatus.level}
 * @param event HTTP Event
 * @returns
 * - Returns `404 Not Found` if no user that matches `id` or user is private.
 * - Returns `200 OK` with JSON body if found.
 * @example
 * ```json
 * [
 *   { "playStyle": 1, "level": 1, "clearLamp": -1, "count": 10 },
 *   { "playStyle": 1, "level": 1, "clearLamp": 6, "count": 10 },
 *   { "playStyle": 1, "level": 1, "clearLamp": 7, "count": 20 }
 * ]
 * ```
 */
export default defineEventHandler(async event => {
  const user = await tryFetchUser(event)
  if (!user) return sendNullWithError(event, 404)

  const query = getQuery(event)
  const style = getQueryInteger(query, 'style')
  const lv = getQueryInteger(query, 'lv')

  const conditions: Condition<'UserDetails'>[] = []
  if (playStyleMap.has(style)) {
    conditions.push({ condition: 'c.playStyle = @', value: style })
  }
  if (lv >= 1 && lv <= 20) {
    conditions.push({ condition: 'c.level = @', value: lv })
  }

  /** User Clear Statuses */
  const clears = (await fetchList(
    'UserDetails',
    ['playStyle', 'level', 'clearLamp', 'count'],
    [
      { condition: 'c.userId = @', value: user.id },
      { condition: 'c.type = "clear"' },
      ...conditions,
    ],
    { playStyle: 'ASC' }
  )) as ClearStatus[]
  /** Chart total counts */
  const total = (await fetchList(
    'UserDetails',
    ['playStyle', 'level', 'count'],
    [{ condition: 'c.userId = "0"' }, ...conditions],
    { playStyle: 'ASC' }
  )) as Omit<ClearStatus, 'clearLamp'>[]

  return total
    .flatMap(d => {
      const filtered = clears.filter(
        r => r.playStyle === d.playStyle && r.level === d.level
      )
      const playedCount = filtered.reduce((p, c) => p + c.count, 0)
      return [
        ...filtered,
        { ...d, clearLamp: -1 as const, count: d.count - playedCount },
      ]
    })
    .sort((l, r) =>
      l.playStyle !== r.playStyle
        ? l.playStyle - r.playStyle
        : l.level !== r.level
        ? l.level - r.level
        : l.clearLamp - r.clearLamp
    ) // ORDER BY playStyle, level, clearLamp ASC
})
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class MountService {
  constructor(private http: HttpClient) {}

  /**
   * 通过hostId 获取未挂载的VMFS
   * @param hostObjectId
   * @param dataStoreType
   */
  getDataStoreByHostId(hostObjectId:string, dataStoreType:string) {
    return this.http.get('accessvmware/getdatastoresbyhostobjectid?hostObjectId=' +


 message.
 * If no valid PublicKey can be retrieved an error will be returned.
 */
export async function messagePublicKey (message: SignedMessage): Promise<Uint8Array> {
  if (message.type !== 'signed') {
    throw new Error('Message type must be "signed" to have a public key')
  }

  // should be available in the from property of the message (peer id)
  if (message.from == null) {
    throw new Error('Could not get the public key from the originator id')
  }

  if (message.key != null) {
    const keyPeerId = await peerIdFromKeys(message.key)

    if (keyPeerId.publicKey != null) {
      return keyPeerId.publicKey
    }
  }

  if (message.from.publicKey != null) {
    return message.from.publicKey
  }

  // We couldn't validate pubkey is from the originator, error
  throw new Error('Could not get the public key from the originator id')
}
import { CharactersJSONSchema } from "../types";
import { Character } from "./character";
import { BitArray, bit } from "../utils/bit-array";

export class CharactersJSON {
    static import(path: string, success: (content: Character[]) => any) {
        fetch(path)
        .then((response) => {
            return response.text();
        })
        .then((response) => {
            success(CharactersJSON.parse(response))
        })
        .catch((error) => {
            throw `Couldn't fetch file: ${path}`;
        });
    }

    static export() {
        // TODO: Implement
    }

    static parse(json: string): Character[] {
        const data = JSON.parse(json) as CharactersJSONSchema;

        if (data == null) {
            throw 'Invalid character json file';
        }

        if (data.characters == null) {
            throw 'Invalid character json file: Can\'t find property characters';
        }

        return data.characters.map(x => {
            if (x.pattern == null) {
                throw 'Invalid character json file: Can\'t find property patterns for a character';
            }
            if (x.output == null) {
                throw 'Invalid character json file: Can\'t find property output for a character';
            }
            if (x.width == null) {
                throw 'Invalid character json file: Can\'t find property width for a character';
            }
            return new Character(x.pattern, new BitArray(x.output.map(x => x as bit)), x.width)
        });
    }

    static stringify(characters: Character[]): string {
        if (characters == null || characters.length == 0) {
            return JSON.stringify("");
        }

        return JSON.stringify({
            characters: characters.map(x => {
                return {
                    patterns: x.pattern,
                    output: x.output.atIndexRange(0, x.output.size),
                    width: x.width
                };
            })
        });
    }
}import { fromObject, Observable } from "@nativescript/core/data/observable";

(Observable as any).prototype.addListener = function (eventNames, callback, thisArg) {
  this.on(eventNames, callback, thisArg);
};

(Observable as any).prototype.removeListener = function (eventNames, callback, thisArg) {
  this.off(eventNames, callback, thisArg);
};

(Observable as any).prototype.emit = function (eventNames, thisArg) {
  this.notify({
    eventName: eventNames,
    object: null,
  })
};

export class Node {
  emitter;
  style;
  className;
  nodeName;
  constructor(nodeName) {
    this.emitt


-btn" data-bs-toggle="tooltip"
                        data-bs-placement="top"
                        title="Se aconseja desactivar el plato, en vez de borrarlo, permanentemente">Eliminar</button>

                    </form>

                {% endfor %}
                {% else %}

¡No hay bebidas en tu menu!

                {% endif %}

{% endif %}
{% endblock %}<!DOCTYPE html>

        <input type="text" id="nameInput" placeholder="Enter your name">
        <button onclick="submitName()">Join Chat</button>

        <input type="text" id="input" placeholder="Type a message...">
        <button onclick="sendMessage()">Send</button>

{% extends 'base.html' %}

{% block content %}

Apply for {{ course.name }}

    <form method="post" class="mx-auto w-50 border p-4 rounded shadow">
        {% csrf_token %}

            {


endall': pd.Series(x).corr(pd.Series(y), method='kendall')
    }

def get_metric_data(df, metric, corr_type):

    # Select the row for the given correlation type (assumed to be lowercase)
    row = df.loc[corr_type.lower()]
    # Filter columns that match the metric name followed by "@"
    metric_cols = [col for col in row.index if col.startswith(metric + "@")]

    def get_cutoff(col):
        try:
            return float(col.split("@")[1])
        except Exception:
            return np.inf

    # Sort by numeric cutoff value
    sorted_pairs = sorted(((get_cutoff(col), col) for col in metric_cols), key=lambda x: x[0])
    cutoffs = [pair[0] for pair in sorted_pairs]
    values = [row[pair[1]] for pair in sorted_pairs]

    return cutoffs, values

def get_avg_metric_across_cutoffs(df, metric, corr_type):

    _, values = get_metric_data(df, metric, corr_type)
    return np.mean(values)


ce());
  }
  length():number {
    return this._ts.length;
  }
  // 文字列に変換する
  tos():string {
    var ts = this._ts;
    var ret = "";
    var firstflag = true;
    for( var it = 0 ; it < ts.length; ++it ) {
      if ( ts[it].isZero() )
        continue;
      if ( firstflag )
        firstflag = false;
      else
        ret += "+";
      ret += ts[it].tos();
    }
    if ( firstflag ) {
      ret += "Φ";
    }
    return ret;
  }
  // 内部配列を返す
  toa():ATuple3[] {
    return this._ts;
  }
  //
  isZero(): boolean {
    var it;
    var ts = this._ts;
    for( it=0; it<ts.length; ++it ) {
      if ( !ts[it].isZero() )
        return false;
    }
    return true;
  }
  // Tuples3を追加する
  pushts(tsm:Tuples3) {
    var tsa2 = tsm.toa();
    for(var it=0; it<tsa2.length; ++it) {
      this.pusht( tsa2[it] );
    }
  }
  // ATuple3を追加する
  pusht(tm:ATuple3) {
    var tsa1 = this.toa();
    tsa1.push( tm );
  }
  // ATuple3とのorを計算する
  ort(tm:ATuple3):Tuples3 {
    var ret = this.clone();
    ret.pusht(tm);
    return ret;
  }
  // Tuples3とのorを計算する
  orts(tsm:Tuples3):Tuples3 {
    var ts1 = this.clone();
    ts1.pushts(tsm);
    return ts1;
  }
  // ATuple3とのandを計算する
  andt( tm:ATuple3): Tuples3 {
    var ret = new Tuples3([]);
    var ts1 = this.toa();
    for( var it=0; it<ts1.length; ++it)  {
      ret.pusht( ts1[it].andt( tm ) );
    }
    return ret;
  }
  // Tuples3とのandを計算する
  andts( tsm:Tuples3):Tuples3 {
    var ret = new Tuples3([]);
    var tsa2 = tsm.toa();
    for( var it=0; it<tsa2.length; ++it)  {
      ret.pushts( this.andt( tsa2[it] ) );
    }
    return ret;
  }
  // ATuple3を引く
  minust(tm:ATuple3):Tuples3 {
    var ts1 = this.clone();
    var tsa1 = ts1.toa();
    var ret = ts1.andts(new Tuples3(tm.neg()));
    return ret;
  }
  // Tuples3を引く
  minusts(tsm:Tuples3):Tuples3 {
    var ts1 = this.clone()
    var tsa2 = tsm.toa();
    for( var it=0; it<tsa2.length; ++it) {
      ts1 = ts1.minust( tsa2[it] );
    }
    return ts1;
  }
  //
  reduceZero():Tuples3 {
    var tsa1 = this.toa();
    if (tsa1.length <= 1 )
      return;
    var new_tsa = [];
    for(var it=0; it<tsa1.length; ++it) {
      var t1 = tsa1[it];
      if ( t1.isZero() )
        continue;
      new_tsa.push( t1 );
    }
    if (new


 {
            false => RX_BBA_DIAGSEL1R::_0,
            true => RX_BBA_DIAGSEL1R::_1,
        }
    }
    #[doc = "Checks if the value of the field is `_0`"]
    #[inline]
    pub fn is_0(&self) -> bool {
        *self == RX_BBA_DIAGSEL1R::_0
    }
    #[doc = "Checks if the value of the field is `_1`"]
    #[inline]
    pub fn is_1(&self) -> bool {
        *self == RX_BBA_DIAGSEL1R::_1
    }
}
#[doc = "Possible values of the field `RX_BBA_DIAGSEL2`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RX_BBA_DIAGSEL2R {
    #[doc = "Diag disable"]
    _0,
    #[doc = "Diag enable"]
    _1,
}
impl RX_BBA_DIAGSEL2R {
    #[doc = r" Returns `true` if the bit is clear (0)"]
    #[inline]
    pub fn bit_is_clear(&self) -> bool {
        !self.bit()
    }
    #[doc = r" Returns `true` if the bit is set (1)"]
    #[inline]
    pub fn bit_is_set(&self) -> bool {
        self.bit()
    }
    #[doc = r" Value of the field as raw bits"]
    #[inline]
    pub fn bit(&self) -> bool {
        match *self {
            RX_BBA_DIAGSEL2R::_0 => false,
            RX_BBA_DIAGSEL2R::_1 => true,
        }
    }
    #[allow(missing_docs)]
    #[doc(hidden)]
    #[inline]
    pub fn _from(value: bool) -> RX_BBA_DIAGSEL2R {
        match value {
            false => RX_BBA_DIAGSEL2R::_0,
            true => RX_BBA_DIAGSEL2R::_1,
        }
    }
    #[doc = "Checks if the value of the field is `_0`"]
    #[inline]
    pub fn is_0(&self) -> bool {
        *self == RX_BBA_DIAGSEL2R::_0
    }
    #[doc = "Checks if the value of the field is `_1`"]
    #[inline]
    pub fn is_1(&self) -> bool {
        *self == RX_BBA_DIAGSEL2R::_1
    }
}
#[doc = "Possible values of the field `RX_BBA_DIAGSEL3`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RX_BBA_DIAGSEL3R {
    #[doc = "Diag disable"]
    _0,
    #[doc = "Diag enable"]
    _1,
}
impl RX_BBA_DIAGSEL3R {
    #[doc = r" Returns `true` if the bit is clear (0)"]
    #[inline]
    pub fn bit_is_clear(&self) -> bool {
        !self.bit()
    }
    #[doc = r" Returns `true` if the bit is set (1)"]
    #[inline]
    pub fn bit_is_set(&self) -> bool {
        self.bit()
    }
    #[doc = r" Value of the field as raw bits"]
    #[inline]
    pub fn bit(&self) -> bool {
        match *self {
            RX_BBA_DIAGSEL3R::_0 => false,
            RX_BBA_DIAGSEL3R::_1 => true,
        }
    }
    #[allow(missing_docs)]
    #[doc(hidden)]
    #[inline]
    pub fn _from(value: bool) -> RX


addAdmin(address)",
		"11117fc8": "adminList(uint256)",
		"4f97638f": "clearRequest()",
		"3b2d2aca": "confirmRequest(uint256,uint8,bytes32,bytes32,bytes32)",
		"7a5db068": "contractValidator()",
		"27e1f7df": "deleteAdmin(address)",
		"0fd440ec": "getRequestIds(uint256,uint256,uint8)",
		"0b816045": "getRequestInfo(uint256)",
		"ed979dd6": "getRequestState(uint256)",
		"75a87643": "getReviewers()",
		"1865c57d": "getState()",
		"24d7806c": "isAdmin(address)",
		"e7abb98d": "lastClearedId()",
		"5badbe4c": "requestCount()",
		"b7563930": "requirement()",
		"164990f8": "revokeConfirmation(uint256,uint8,bytes32,bytes32,bytes32)",
		"863f5c0a": "submitAddAdmin(address)",
		"7818097c": "submitApproveStakingWithdrawal(address,uint256)",
		"06b35d31": "submitCancelApprovedStakingWithdrawal(uint256)",
		"87cd9feb": "submitClearRequest()",
		"791b5123": "submitDeleteAdmin(address)",
		"2f890b1d": "submitToggleRedelegation()",
		"e748357b": "submitUpdateRequirement(uint256)",
		"069135af": "submitUpdateRewardAddress(address)",
		"0df5975c": "submitUpdateStakingTracker(address)",
		"b756e6ff": "submitUpdateVoterAddress(address)",
		"4b8bc6f8": "submitWithdrawLockupStaking(address,uint256)",
		"c47afb3a": "updateRequirement(uint256)",
	},
}

// ICnStakingV3MultiSigABI is the input ABI used to generate the binding from.
// Deprecated: Use ICnStakingV3MultiSigMetaData.ABI instead.
var ICnStakingV3MultiSigABI = ICnStakingV3MultiSigMetaData.ABI

// ICnStakingV3MultiSigBinRuntime is the compiled bytecode used for adding genesis block without deploying code.
const ICnStakingV3MultiSigBinRuntime = ``

// ICnStakingV3MultiSigFuncSigs maps the 4-byte function signature to its string representation.
// Deprecated: Use ICnStakingV3MultiSigMetaData.Sigs instead.
var ICnStakingV3MultiSigFuncSigs = ICnStakingV3MultiSigMetaData.Sigs

// ICnStakingV3MultiSig is an auto generated Go binding around a Kaia contract.
type ICnStakingV3MultiSig struct {
	ICnStakingV3MultiSigCaller     // Read-only binding to the contract
	ICnStakingV3MultiSigTransactor // Write-only binding to the contract
	ICnStakingV3MultiSigFilterer   // Log filterer for contract events
}

// ICnStakingV3MultiSigCaller is an auto generated read-only Go binding around a Kaia contract.
type ICnStakingV3MultiSigCaller struct {
	contract *bind.BoundContract // Generic contract wrapper for the low level calls
}

// ICnStakingV3MultiSigTransactor is an auto generated write-only Go binding around a Kaia contract.
type ICnStakingV3MultiSigTransactor struct {
	contract *bind.BoundContract // Generic contract wrapper for the low level calls
}

// ICnStakingV3MultiSigFilterer is an auto generated log filtering Go binding around a Kaia contract events.
type ICnStakingV3MultiSigFilterer struct {
	contract *bind.BoundContract // Generic contract wrapper for the low level calls
}

// ICnStakingV3MultiSigSession is an auto generated Go binding around a Kaia contract,
// with pre-set call and transact options.
type ICnStakingV3MultiSigSession struct {
	Contract     *ICnStakingV3MultiSig // Generic contract binding to set the session for
	CallOpts     bind.CallOpts         // Call options to use throu


= {"비밀결사대 마술사",nil},
[2320] = {"나가즈",nil},
[2321] = {"새끼 숲타조",nil},
[2322] = {"숲타조",nil},
[2323] = {"거대한 숲타조",nil},
[2324] = {"검은나무일족 풍수사",nil},
[2325] = {"언데드 전문 응급치료사","전문 응급치료사"},
[2326] = {"탐네르 폴","전문 응급치료사"},
[2327] = {"샤이나 풀러","전문 응급치료사"},
[2329] = {"미셸 벨르","전문 응급치료사"},
[2330] = {"칼리 채디스",nil},
[2331] = {"페이지 채디스",nil},
[2332] = {"발드레드 모레이",nil},
[2333] = {"심복 발릭",nil},
[2334] = {"이벤트 생성기 001",nil},
[2335] = {"집정관 번사이드",nil},
[2336] = {"암흑이교도 광신자",nil},
[2337] = {"암흑이교도 소환사",nil},
[2338] = {"황혼의망치단 신도",nil},
[2339] = {"황혼의망치단 암살단원",nil},
[2344] = {"던 가록 산악경비대",nil},
[2345] = {"던 가록 소총병",nil},
[2346] = {"던 가록 사제",nil},
[2347] = {"야생 그리핀",nil},
[2348] = {"덩치 큰 이끼거미",nil},
[2349] = {"거대한 이끼거미",nil},
[2350] = {"숲이끼거미",nil},
[2351] = {"회색곰",nil},
[2352] = {"여관주인 앤더슨","여관주인"},
[2354] = {"흉포한 회색곰",nil},
[2356] = {"덩치 큰 회색곰",nil},
[2357] = {"메리데스 칼슨","마구간지기"},
[2358] = {"달라란 소환사",nil},
[2359] = {"노예 바위 정령",nil},
[2360] = {"힐스브래드 농노",nil},
[236


	animState = animator.animationState("objectState")

				if mcontroller.xVelocity() > 0 and atRest() then
					if state > 3 then
						status.clearPersistentEffects("egg")
						effect.expire()
						do return end
					end

					animator.setAnimationState("objectState", "right" .. state )

					state = state + 1
				elseif mcontroller.xVelocity() < 0 and atRest() then
					if state > 3 then
						status.clearPersistentEffects("egg")
						effect.expire()
						do return end
					end

					animator.setAnimationState("objectState", "left" .. state )

					state = state + 1
				end
				mcontroller.setXVelocity( 0 )
			end
		else
			timer = timer + dt
			if timer > 10 then
				status.clearPersistentEffects("para")
			end
		end
		mcontroller.setPosition( base )
	else
		groundLock = 0
	end
end

function uninit()
	effect.expire()
end

function atRest()
	if animState == "ready" or animState == "idle1" or animState == "idle2" or animState == "idle3" then
		do return true end
	end
	do return false end
end


#ifndef __GENERIC_IO_H
#define __GENERIC_IO_H

#include <linux/linkage.h>
#include <asm/byteorder.h>

/*
 * These are the "generic" interfaces for doing new-style
 * memory-mapped or PIO accesses. Architectures may do
 * their own arch-optimized versions, these just act as
 * wrappers around the old-style IO register access functions:
 * read[bwl]/write[bwl]/in[bwl]/out[bwl]
 *
 * Don't include this directly, include it from <asm/io.h>.
 */

/*
 * Read/write from/to an (offsettable) iomem cookie. It might be a PIO
 * access or a MMIO access, these functions don't care. The info is
 * encoded in the hardware mapping set up by the mapping functions
 * (or the cookie itself, depending on implementation and hw).
 *
 * The generic routines just encode the PIO/MMIO as part of the
 * cookie, and coldly assume that the MMIO IO mappings are not
 * in the low address range. Architectures for which this is not
 * true can't use this generic implementation.
 */
extern unsigned int fastcall ioread8(void __iomem *);
extern unsigned int fastcall ioread16(void __iomem *);
extern unsigned int fastcall ioread16be(void __iomem *);
extern unsigned int fastcall ioread32(void __iomem *);
extern unsigned int fastcall ioread32be(void __iomem *);

extern void fastcall iowrite8(u8, void __iomem *);
extern void fastcall iowrite16(u16, void __iomem *);
extern void fastcall iowrite16be(u16, void __iomem *);
extern void fastcall iowrite32(u32, void __iomem *);
extern void fastcall iowrite32be(u32, void __iomem *);

/*
 * "string" versions of the above. Note that they
 * use native byte ordering for the accesses (on
 * the assumption that IO and memory agree on a
 * byte order, and CPU byteorder is irrelevant).
 *
 * They do _not_ update the port address. If you
 * want MMIO that copies stuff laid out in MMIO
 * memory across multiple ports, use "memcpy_toio()"
 * and friends.
 */
extern void fastcall ioread8_rep(void __iomem *port, void *buf, unsigned long count);
extern void fastcall ioread16_rep(void __iomem *port, void *buf, unsigned long count);
extern void fastcall ioread32_rep(void __iomem *port, void *buf, unsigned long count);

extern void fastcall iowrite8_rep(void __iomem *port, const void *buf, unsigned long count);
extern void fastcall iowrite16_rep(void __iomem *port, const void *buf, unsigned long count);
extern void fastcall iowrite32_rep(void __iomem *port, const void *buf, unsigned long count);

/* Create a virtual mapping cookie for an IO port range */
extern void __iomem *ioport_map(unsigned long port, unsigned int nr);
extern void ioport_unmap(void __iomem *);

/* Create a virtual mapping cookie for a PCI BAR (memory or IO) */
struct pci_dev;
extern void __iomem *pci_iomap(struct pci_dev *dev, int bar, unsigned long max);
extern void pci_iounmap(struct pci_dev *dev, void __iomem *);

#endif


+this.items.map((e=>D(e))).join(", ")+")";return this.in$repr=!1,e}}}),P.methodcaller=M("operator.methodcaller",{constructor:function methodcaller(e,t,a){this.$name=e,this.args=t,this.kwargs=a||[],this.in$repr=!1},slots:{tp$getattr:G,tp$new(e,t){g("methodcaller",e,1);const a=e[0];if(!u(a))throw new s("method name must be a string");return new P.methodcaller(a,e.slice(1),t)},tp$call(e,t){f("methodcaller",e,t);const a=e[0];return E(q(a,this.$name,!0),(e=>C(e,this.args,this.kwargs)))},tp$doc:"methodcaller(name, ...) --\\x3e methodcaller object\\n\\nReturn a callable object that calls the given method on its operand.\\nAfter f = methodcaller(\'name\'), the call f(r) returns r.name().\\nAfter g = methodcaller(\'name\', \'date\', foo=1), the call g(r) returns\\nr.name(\'date\', foo=1).",$r(){if(this.in$repr)return new t(this.tp$name+"(...)");this.in$repr=!0;let e=[D(this.$name)];e.push(...this.args.map((e=>D(e))));for(let t=0;t<this.kwargs.length;t+=2)e.push(this.kwargs[t]+"="+D(this.kwargs[t+1]));return e=this.tp$name+"("+e.join(", ")+")",this.in$repr=!1,e}}});const U={1:{$flags:{OneArg:!0},$textsig:"($module, a, /)"},2:{$flags:{MinArgs:2,MaxArgs:2},$textsig:"($module, a, b, /)"},3:{$flags:{MinArgs:3,MaxArgs:3},$textsig:"($module, a, b, c, /)"}};function makeModuleMethod(e,t){return{$meth:e,$doc:t,...U[e.length]}}function sameAs(e){return"Same as "+e+"."}return R("operator",P,{lt:makeModuleMethod(((e,t)=>n(B(e,t,"Lt"))),sameAs("a < b")),le:makeModuleMethod(((e,t)=>n(B(e,t,"LtE"))),sameAs("a <= b")),eq:makeModuleMethod(((e,t)=>n(B(e,t,"Eq"))),sameAs("a == b")),ne:makeModuleMethod(((e,t)=>n(B(e,t,"NotEq"))),sameAs("a != b")),ge:makeModuleMethod(((e,t)=>n(B(e,t,"GtE"))),sameAs("a >= b")),gt:makeModuleMethod(((e,t)=>n(B(e,t,"Gt"))),sameAs("a > b")),not_:makeModuleMethod((e=>p(e,"Not")),sameAs("not a")),truth:makeModuleMethod((e=>n(e)),"Return True if a is true, False otherwise."),is_:makeModuleMethod(((e,t)=>n(B(e,t,"Is"))),sameAs("a is b")),is_not:makeModuleMethod(((e,t)=>n(B(e,t,"IsNot"))),sameAs("a is not b")),abs:makeModuleMethod((e=>l(e)),sameAs("abs(a)")),add:makeModuleMethod(((e,t)=>A(e,t,"Add")),sameAs("a + b")),and_:makeModuleMethod(((e,t)=>A(e,t,"BitAnd")),sameAs("a & b")),floordiv:makeModuleMethod(((e,t)=>A(e,t,"FloorDiv")),sameAs("a // b")),index:makeModuleMethod((e=>new o(N(e))),sameAs("a.__index__()")),inv:makeModuleMethod((e=>p(e,


using System.Collections.Generic;
using System.Threading.Tasks;
using EventHub.Web.Components.Toolbar.CreateButton;
using EventHub.Web.Components.Toolbar.LoginLink;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared.Toolbars;
using Volo.Abp.Users;

namespace EventHub.Web.Menus
{
    public class EventHubToolbarContributor : IToolbarContributor
    {
        public virtual Task ConfigureToolbarAsync(IToolbarConfigurationContext context)
        {
            if (context.Toolbar.Name != StandardToolbars.Main)


    let font = from_bytes(include_bytes!("../../dsk/ini/fonts/zap-light-8x16.psf")).unwrap();
    assert_eq!(font.height, 16);
    assert_eq!(font.size, 256);
    assert_eq!(font.data.len(), 256 * 16);
}
<filename>common/cros_asyncv2/src/enter.rs
// Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::cell::Cell;

use thiserror::Error as ThisError;

thread_local! (static EXECUTOR_ACTIVE: Cell<bool> = Cell::new(false));

#[derive(ThisError, Debug)]
#[error("Nested execution is not supported")]
struct NestedExecutionNotSupported;

#[derive(Debug)]
pub struct ExecutionGuard;

impl Drop for ExecutionGuard {
    fn drop(&mut self) {
        EXECUTOR_ACTIVE.with(|active| {
            assert!(active.get());
            active.set(false);
        })
    }
}

pub fn enter() -> anyhow::Result<ExecutionGuard> {
    EXECUTOR_ACTIVE.with(|active| {
        if active.get() {
            Err(NestedExecutionNotSupported.into())
        } else {
            active.set(true);

            Ok(ExecutionGuard)
        }
    })
}

#[cfg(test)]
mod test {
    use crate::Executor;

    use super::NestedExecutionNotSupported;

    #[test]
    fn nested_execution() {
        Executor::new()
            .run_until(async {
                let e = Executor::new()
                    .run_until(async {})
                    .expect_err("nested execution successful");
                e.downcast::<NestedExecutionNotSupported>()
                    .expect("unexpected error type");
            })
            .unwrap();

        let ex = Executor::new();
        ex.run_until(async {
            let e = ex
                .run_until(async {})
                .expect_err("nested execution successful");
            e.downcast::<NestedExecutionNotSupported>()
                .expect("unexpected error type");
        })
        .unwrap();
    }
}
<filename>crates/sml-frontend/src/ast.rs
use sml_util::interner::Symbol;
use sml_util::span::{Span, Spanned};
use sml_util::Const;

#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct Datatype {
    pub tycon: Symbol,
    pub tyvars: Vec<Symbol>,
    pub constructors: Vec<Variant>,
    pub span: Span,
}

#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct Typebind {
    pub tycon: Symbol,
    pub tyvars: Vec<Symbol>,
    pub ty: Type,
}

#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub enum Fixity {
    Infix,
    Infixr,
    Nonfix,
}

#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct Primitive {
    pub sym: Symbol,
    pub ty: Type,
}

#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub enum DeclKind {
    /// If `N` > 1, then we have potentially mutually recursive datatype
    /// definitions
    Datatype(Vec<Datatype>),
    /// If `N` > 1, then we have mutually rec. type defs
    Type(Vec<Typebind>),
    /// Allow for mutually recursive function defs:
    /// fun 'tyvars fnbindings1
    ///             ...
    ///      and    fnbindingsN
    Function(Vec<Symbol>, Vec<Fun>),
    V


  saved += 1
                if max_profiles is not None and saved >= max_profiles:
                    logging.info(f"\n[INFO] Reached max of {max_profiles} new profiles. Stopping.\n")
                    break

        logging.info(f"\n[SUCCESS] HTML extraction complete. {saved} new profiles saved.")
        logging.info(f"[INFO] Processed {self.processed_count} profiles in total.")
        logging.info(f"[INFO] All HTML files saved in: {self.cache_dir}")
        logging.info(f"[INFO] DB path: {self.db_path}")
        logging.info(f"[INFO] Cache folder: {self.cache_dir}\n")


     []byte
	}{
		{"single byte prefix", 1, 126, []byte{0b01111110}},
		{"two byte prefix", 2, 131, []byte{0b10000001, 0b10000011}},
		{"three byte prefix", 3, 65039, []byte{0b10000010, 0b11111110, 0b00001111}},
	}

	// test encoding
	for _, tt := range tests {
		t.Run(tt.desc+"_EncodeLength", func(t *testing.T) {
			got, err := BerTLV.EncodeLength(0, tt.length)
			require.NoError(t, err)
			require.Equal(t, tt.data, got)
		})
	}

	// test decoding
	for _, tt := range tests {
		t.Run(tt.desc+"_DecodeLength", func(t *testing.T) {
			got, read, err := BerTLV.DecodeLength(0, tt.data)
			require.NoError(t, err)
			require.Equal(t, tt.length, got)
			require.Equal(t, tt.numBytes, read)
		})
	}

	t.Run("when maxLen is set EncodeLength returns error if length is larger than maxLen", func(t *testing.T) {
		_, err := BerTLV.EncodeLength(2, 3)
		require.EqualError(t, err, "field length: 3 is larger than maximum: 2")
	})

	t.Run("when maxLen is set DecodeLength returns error if length is larger than maxLen", func(t *testing.T) {
		_, _, err := BerTLV.DecodeLength(2, []byte{0b10000010, 0b11111110, 0b00001111})
		require.EqualError(t, err, "field length: 65039 is larger than maximum: 2")
	})
}

func TestBerTLVPrefixer_DecodeReturnsErrOnIncorrectInput(t *testing.T) {
	t.Run("if initial byte larger than number of subsequent bytes", func(t *testing.T) {
		// First byte indicates that there should be 3 additional bytes to follow
		// However, there are only 2.
		_, _, err := BerTLV.DecodeLength(0, []byte{0b10000011, 0b11111110, 0b00001111})
		require.EqualError(t, err, "failed to read long form TLV length: unexpected EOF")
	})

	t.Run("if input is empty", func(t *testing.T) {
		_, _, err := BerTLV.DecodeLength(0, []byte{})
		require.EqualError(t, err, "failed to decode TLV length: EOF")
	})
}
package prefix

import (
	"testing"

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

func TestFixedHex(t *testing.T) {
	pref := hexFixedPrefixer{}

	dataLen, read, err := pref.DecodeLength(16, []byte("whatever"))

	require.NoError(t, err)
	require.Equal(t, 16, dataLen)
	require.Equal(t, 0, read)
}

func Test_hexVarPrefixer_EncodeLength(t *testing.T) {
	type fields struct {
		Digits int
	}
	type args struct {
		maxLen  int
		dataLen int
	}
	tests := []struct {
		name    string
		fields  fields
		args    args
		want    []byte
		wantErr bool
	}{
		{
			name: "success",
			fields: fields{
				Digits: 3,
			},
			args: args{
				maxLen:  32,
				dataLen: 24,
			},
			want:    []byte("000018"),
			wantErr: false,
		},
		{
			na


using StringToExpression.LanguageDefinitions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace StringToExpression.Test.Languages.Arithmetic
{
    public class Parameter
    {
        public int FavouriteNumber { get; set; }

        public Limit Limits { get; set; }
    }

    public class Limit
    {
        public double Min { get; set; }
        public double Max { get; set; }
    }

    public class ArithmeticLangaugeTests
    {
        [Theory]
        [InlineData("1 + 1", 2)]
        [InlineData("2 + 2 * 5", 12)]
        [InlineData("2 + -2 * 5", -8)]
        [InlineData("(2 + 2) * 5", 20)]
        [InlineData("4 - 2 * 5", -6)]
        [InlineData("(4 - 2) * 5", 10)]
        [InlineData("2.5 * 4", 10)]
        [InlineData("2.5 * 3", 7.5)]
        [InlineData("9 / 10", 0.9)]
        [InlineData("10 / 9", 1.111)]
        [InlineData("10 / 5 * 2", 4)]
        [InlineData("10 % 3", 1)]
        [InlineData("Pi", 3.14159)]
        [InlineData("sin(Pi)", 0)]
        [InlineData("Sin(Pi * 1 / 2)", 1)]
        [InlineData("SIN(Pi * 1 / 4)", 0.707)]
        [InlineData("cos(Pi)", -1)]
        [InlineData


");
    let err = statement::<SimpleGrammar, Complete>(input).unwrap_err();
    assert_matches!(err, NomErr::Error(spanned) if *spanned.span().fragment() == "|");
}

#[test]
fn tuples_when_switched_off() {
    #[derive(Debug, Clone)]
    struct SimpleGrammar;

    impl Parse<'_> for SimpleGrammar {
        type Base = FieldGrammarBase;

        const FEATURES: Features = Features::all().without(Features::TUPLES);
    }

    let input = InputSpan::new("tup = (1 + 2, 3 + 5)");
    let err = statement::<SimpleGrammar, Complete>(input).unwrap_err();
    assert_matches!(err, NomErr::Failure(spanned) if spanned.span().location_offset() == 6);

    let input = InputSpan::new("(x, y) = (1 + 2, 3 + 5)");
    let err = statement::<SimpleGrammar, Complete>(input).unwrap_err();
    assert_matches!(err, NomErr::Failure(spanned) if spanned.span().location_offset() == 0);

    let input = InputSpan::new("{ x, y } = #{ x: 1, y: 2 }");
    let stmt = statement::<SimpleGrammar, Complete>(input).unwrap().1;
    assert_matches!(
        stmt.extra,
        Statement::Assignment { lhs, .. } if matches!(lhs.extra, Lvalue::Object(_))
    );
}

#[test]
fn blocks_when_switched_off() {
    #[derive(Debug, Clone)]
    struct SimpleGrammar;

    impl Parse<'_> for SimpleGrammar {
        type Base = FieldGrammarBase;

        const FEATURES: Features = Features::all().without(Features::BLOCKS);
    }

    let input = InputSpan::new("x = { y = 10; y * 2 }");
    let err = statement::<SimpleGrammar, Complete>(input).unwrap_err();
    assert_matches!(err, NomErr::Error(spanned) if spanned.span().location_offset() == 4);

    let input = InputSpan::new("foo({ y = 10; y * 2 }, z)");
    let err = statement::<SimpleGrammar, Complete>(input).unwrap_err();
    assert_matches!(err, NomErr::Failure(spanned) if spanned.span().location_offset() == 4);
}

#[test]
fn methods_when_switched_off() {
    #[derive(Debug, Clone)]
    struct SimpleGrammar;

    impl Parse<'_> for SimpleGrammar {
        type Base = FieldGrammarBase;

        const FEATURES: Features = Features::all().without(Features::METHODS);
    }

    let input = InputSpan::new("foo.bar(1)");
    let (rest, _) = statement::<SimpleGrammar, Complete>(input).unwrap();
    assert_eq!(*rest.fragment(), ".bar(1)");

    let input = InputSpan::new("(1, 2).bar(1)");
    let (rest, _) = statement::<SimpleGrammar, Complete>(input).unwrap();
    assert_eq!(*rest.fragment(), ".bar(1)");
}

#[test]
fn order_comparisons_when_switched_off() {
    #[derive(Debug, Clone)]
    struct SimpleGrammar;

    impl Parse<'_> for SimpleGrammar {
        type Base = FieldGrammarBase;

        const FEATURES: Features = Features::all().without(Features::ORDER_COMPARISONS);
    }

    for &op in &[BinaryOp::Gt, BinaryOp::Lt, BinaryOp::Ge, BinaryOp::Le] {
        assert_binary_op_is_not_parsed::<SimpleGrammar>(op);
    }
}

fn assert_binary_op_is_not_parsed<T>(op: BinaryOp)
where
    T: for<'a> Parse<'a>,
{


0 0 512 512'><path d='M405.84 136.9a151.25 151.25 0 00-47.6-81.9 153 153 0 00-241.81 51.86C60.5 110.16 16 156.65 16 213.33 16 272.15 63.91 320 122.8 320h72.31L176 416h48v80l112-144h-43.51l8-32h103.84a91.56 91.56 0 001.51-183.1z'/><path d='M74.53 407.177l38.32-76.622 28.62 14.313-38.32 76.623zM98.52 471.189l30.318-60.622 28.62 14.313-30.317 60.622zM354.541 407.189l38.32-76.623 28.62 14.314-38.32 76.622zM378.542 471.2l30.317-60.622 28.62 14.314-30.317 60.621z'/></svg>"
export const ticket = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512' class='ionicon'><path d='M490.18 181.4l-44.13-44.13a20 20 0 00-27-1 30.81 30.81 0 01-41.68-1.6 30.81 30.81 0 01-1.6-41.67 20 20 0 00-1-27L330.6 21.82a19.91 19.91 0 00-28.13 0l-70.35 70.34a39.87 39.87 0 00-9.57 15.5 7.71 7.71 0 01-4.83 4.83 39.78 39.78 0 00-15.5 9.58l-180.4 180.4a19.91 19.91 0 000 28.13L66 374.73a20 20 0 0027 1 30.69 30.69 0 0143.28 43.28 20 20 0 001 27l44.13 44.13a19.91 19.91 0 0028.13 0l180.4-180.4a39.82 39.82 0 009.58-15.49 7.69 7.69 0 014.84-4.84 39.84 39.84 0 0015.49-9.57l70.34-70.35a19.91 19.91 0 00-.01-28.09zm-228.37-29.65a16 16 0 01-22.63 0l-11.51-11.51a16 16 0 0122.63-22.62l11.51 11.5a16 16 0 010 22.63zm44 44a16 16 0 01-22.62 0l-11-11a16 16 0 1122.63-22.63l11 11a16 16 0 01.01 22.66zm44 44a16 16 0 01-22.63 0l-11-11a16 16 0 0122.63-22.62l11 11a16 16 0 01.05 22.67zm44.43 44.54a16 16 0 01-22.63 0l-11.44-11.5a16 16 0 1122.68-22.57l11.45 11.49a16 16 0 01-.01 22.63z'/></svg>"
export const ticketOutline = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512' class='ionicon'><path stroke-miterlimit='10' d='M366.05 146a46.7 46.7 0 01-2.42-63.42 3.87 3.87 0 00-.22-5.26l-44.13-44.18a3.89 3.89 0 00-5.5 0l-70.34 70.34a23.62 23.62 0 00-5.71 9.24h0a23.66 23.66 0 01-14.95 15h0a23.7 23.7 0 00-9.25 5.71L33.14 313.78a3.89 3.89 0 000 5.5l44.13 44.13a3.87 3.87 0 005.26.22 46.69 46.69 0 0165.84 65.84 3.87 3.87 0 00.22 5.26l44.13 44.13a3.89 3.89 0 005.5 0l180.4-180.39a23.7 23.7 0 005.71-9.


info("Detected categories from reference data: {}", Arrays.toString(categories));
		}
		this.categories = categories;
		return this;
	}

	/**
	 * Enable choice evaluation tab. This only produces valid data if choice reference data was set in the population.
	 *
	 * @see TripAnalysis#ATTR_REF_MODES
	 */
	public TripDashboard withChoiceEvaluation(boolean enable) {
		this.choiceEvaluation = enable;
		return this;
	}

	/**
	 * Set argument that will be passed to the analysis script. See {@link TripAnalysis}.
	 */
	public TripDashboard setAnalysisArgs(String... args) {
		this.args = args;
		return this;
	}

	@Override
	public void configure(Header header, Layout layout) {

		header.title = "Trips";
		header.description = "General information about modal share and trip distributions.";

		String[] args = new String[this.groupedRefCsv == null ? this.args.length : this.args.length + 2];
		System.arraycopy(this.args, 0, args, 0, this.args.length);

		// Add ref data to the argument if set
		if (groupedRefCsv != null) {
			args[this.args.length] = "--input-ref-data";
			args[this.args.length + 1] = groupedRefCsv;
		}

		// A tab will only be present if one of the other tabs is used as well
		String tab = (groupedRefCsv != null || choiceEvaluation) ? header.title : null;

		Layout.Row first = layout.row("first", tab);
		first.el(Plotly.class, (viz, data) -> {
			viz.title = "Modal split";

			viz.layout = tech.tablesaw.plotly.components.Layout.builder()
				.barMode(tech.tablesaw.plotly.components.Layout.BarMode.STACK)
				.build();

			Plotly.DataSet ds = viz.addDataset(data.compute(TripAnalysis.class, "mode_share.csv", args))
				.constant("source", "Simulated")
				.aggregate(List.of("main_mode"), "share", Plotly.AggrFunc.SUM);

			if (modeShareRefCsv != null) {
				viz.addDataset(data.resource(modeShareRefCsv))
					.constant("source", "Reference")
					.aggregate(List.of("main_mode"), "share", Plotly.AggrFunc.SUM);

				viz.mergeDatasets = true;
			}

			viz.addTrace(BarTrace.builder(Plotly.OBJ_INPUT, Plotly.INPUT).orientation(BarTrace.Orientation.HORIZONTAL).build(),
				ds.mapping()
					.name("main_mode")
					.y("source")
					.x("share")
			);
		});

		first.el(Plotly.class, (viz, data) -> {

			viz.title = "Trip distance distribution";
			viz.colorRamp = ColorScheme.Viridis;

			viz.addTrace(BarTrace.builder(Plotly.OBJ_INPUT, Plotly.INPUT).name("Simulated").build(),
				viz.addDataset(data.compute(TripAnalysis.class, "mode_share.csv", args))
					.aggregate(List.of("dist_group"), "share", Plotly.AggrFunc.SUM)
					.mapping()
					.x("dist_group")
					.y("share")
			);

			if (modeShareRefCsv != null) {
				viz.addTrace(BarTrace.builder(Plotly.OBJ_INPUT, Plotly.INPUT).name("Reference").build(),
					viz.addDataset(data.resource(modeShareRefCsv))
						.aggregate(List.of("dist_group"), "share", Plotly.AggrFunc.SUM)
						.mapping()
						.x("dist_group")
						.y("share")
				);
			}
		});

		layout.row("second"


n,r){if(1===e.length)return p(e[0],t,n,r);let o;const i=s.toHash(e);if(i.array&&i.object){const e=a._`typeof ${t} != "object"`;o=i.null?e:a._`!${t} || ${e}`,delete i.null,delete i.array,delete i.object}else o=a.nil;i.number&&delete i.integer;for(const e in i)o=a.and(o,p(e,t,n,r));return o}t.checkDataType=p,t.checkDataTypes=d;const f={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>"string"==typeof e?a._`{type: ${e}}`:a._`{type: ${t}}`};function h(e){const t=function(e){const{gen:t,data:n,schema:r}=e,o=s.schemaRefOrVal(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:e}}(e);i.reportError(t,f)}t.reportTypeError=h},2537:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.assignDefaults=void 0;const r=n(4475),o=n(6124);function i(e,t,n){const{gen:i,compositeRule:a,data:s,opts:l}=e;if(void 0===n)return;const c=r._`${s}${r.getProperty(t)}`;if(a)return void o.checkStrictMode(e,`default is ignored for: ${c}`);let u=r._`${c} === undefined`;"empty"===l.useDefaults&&(u=r._`${u} || ${c} === null || ${c} === ""`),i.if(u,r._`${c} = ${r.stringify(n)}`)}t.assignDefaults=function(e,t){const{properties:n,items:r}=e.schema;if("object"===t&&n)for(const t in n)i(e,t,n[t].default);else"array"===t&&Array.isArray(r)&&r.forEach(((t,n)=>i(e,n,t.default)))}},1321:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getData=t.KeywordCxt=t.validateFunctionCode=void 0;const r=n(7627),o=n(7927),i=n(4566),a=n(7927),s=n(2537),l=n(6488),c=n(4688),u=n(4475),p=n(5018),d=n(9826),f=n(6124),h=n(1885);function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:o},i){o.code.es5?e.func(t,u._`${p.default.data}, ${p.default.valCxt}`,r.$async,(()=>{e.code(u._`"use strict"; ${g(n,o)}`),function(e,t){e.if(p.default.valCxt,(()=>{e.var(p.default.instancePath,u._`${p.default.valCxt}.${p.default.instancePath}`),e.var(p.default.parentData,u._`${p.default.valCxt}.${p.default.parentData}`),e.var(p.default.parentDataProperty,u._`${p.default.valCxt}.${p.default.parentDataProperty}`),e.var(p.default.rootData,u._`${p.default.valCxt}.${p.default.rootData}`),t.dynamicRef&&e.var(p.default.dynamicAnchors,u._`${p.default.valCxt}.${p.


;Commercial Space –
NASA"](https://www.nasa.gov/humans-in-space/commercial-space/). Retrieved September 5,
2024.[^](https://en.wikipedia.org#cite_ref-418)["U.S. energy facts explained – consumption and production – U.S. Energy
Information Administration (EIA)"](https://www.eia.gov/energyexplained/us-energy-facts/).eia.gov. Retrieved November 21,
2023.[^](https://en.wikipedia.org#cite_ref-visu_419-0)["Energy Flow Charts: Charting the Complex Relationships among
Energy, Water, and Carbon"](https://flowcharts.llnl.gov/). Lawrence Livermore National Laboratory. March 2022. Retrieved
May 16, 2023.[^](https://en.wikipedia.org#cite_ref-420)["What is the United States' share of world energy
consumption?"](https://www.eia.gov/tools/faqs/faq.php?id=87&t=1).. November 5, 2021.[U.S. Energy Information
Administration](https://en.wikipedia.org/wiki/Energy_Information_Administration)US Environmental Protection Agency, OAR
(February 8, 2017).[^](https://en.wikipedia.org#cite_ref-421)["Inventory of U.S. Greenhouse Gas Emissions and
Sinks"](https://www.epa.gov/ghgemissions/inventory-us-greenhouse-gas-emissions-and-sinks).US EPA. Retrieved December 3,
2020.[^](https://en.wikipedia.org#cite_ref-422)["Nuclear Power in the USA - World Nuclear Association"](https://world-
nuclear.org/information-library/country-profiles/countries-t-z/usa-nuclear-power).world-nuclear.org. Retrieved March 1,
2025.Rouse, Sabina (November 5, 2019).[^](https://en.wikipedia.org#cite_ref-423)["Where are the world's 449 nuclear
reactors?"](https://www.weforum.org/stories/2019/11/countries-that-have-the-most-nuclear-power-alternative-energy-
electricity-climate-change/).World Economic
Forum.[Archived](https://web.archive.org/web/20250214075151/https://www.weforum.org/stories/2019/11/countries-that-have-
the-most-nuclear-power-alternative-energy-electricity-climate-change/)from the original on February 14, 2025. Retrieved
March 1, 2025.[^](https://en.wikipedia.org#cite_ref-424)["U.S. Sets Targets to Triple Nuclear Energy Capacity by
2050"](https://www.energy.gov/ne/articles/us-sets-targets-triple-nuclear-energy-capacity-2050).Energy.gov. November 12,
2024. Retrieved March 1, 2025.[^](https://en.wikipedia.org#cite_ref-425)["Roadways – The World
Factbook"](https://www.cia.gov/the-world-factbook/field/roadways/country-
comparison).Cia.gov.[Archived](https://web.archive.org/web/20210712201909/https://www.cia.gov/the-world-
factbook/field/roadways/country-comparison)from the original on July 12, 2021. Retrieved July 15,
2021.[^](https://en.wikipedia.org#cite_ref-426)["Public Road and Street Mileage in the United States by Type of
Surface"](https://web.archive.org/web/20150102141414/https://www.rita.dot.gov/bts/sites/rita.dot.gov.bts/files/publications/national_transportation_statistics/html/table_01_04.html).United
States Department


Item(item: Item, predicate: Predicate<ItemStack>? = null) =
    filterByStack {
        it.item == item && (predicate == null || predicate.test(it))
    }

fun <T : Slot> Iterable<T>.filterByID(itemID: Int, predicate: Predicate<ItemStack>? = null) =
    filterByStack {
        it.item.id == itemID && (predicate == null || predicate.test(it))
    }

fun <T : Slot> Iterable<T>.filterByStack(predicate: Predicate<ItemStack>? = null) =
    filter {
        predicate == null || predicate.test(it.stack)
    }import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform
import org.jetbrains.kotlin.gradle.dsl.JvmTarget

val currentPlatform: Platform = when {
    DefaultNativePlatform.getCurrentOperatingSystem().isMacOsX && DefaultNativePlatform.getCurrentArchitecture().isAmd64 -> Platform.MACOS_X64
    DefaultNativePlatform.getCurrentOperatingSystem().isMacOsX && DefaultNativePlatform.getCurrentArchitecture().isArm64 -> Platform.MACOS_ARM64
    DefaultNativePlatform.getCurrentOperatingSystem().isLinux && DefaultNativePlatform.getCurrentArchitecture().isAmd64 -> Platform.LINUX_X64
    DefaultNativePlatform.getCurrentOperatingSystem().isLinux && DefaultNativePlatform.getCurrentArchitecture().isArm64 -> Platform.LINUX_ARM64
    DefaultNativePlatform.getCurrentOperatingSystem().isWindows && DefaultNativePlatform.getCurrentArchitecture().isAmd64 -> Platform.MINGW_X64
    else -> throw GradleException("Host OS is not supported in Kotlin/Native.")
}

plugins {
    kotlin("multiplatform")
}

repositories {
    mavenCentral()
    gradlePluginPortal()
}

kotlin {
    jvm {
        compilerOptions {
            jvmTarget.set(JvmTarget.JVM_17)
        }
        withJava()
        testRuns["test"].executionTask.configure {
            useJUnitPlatform()
        }
    }

    val nativeTarget = when (currentPlatform) {
        Platform.MACOS_X64 -> macosX64()
        Platform.MACOS_ARM64 -> macosArm64()
        Platform.LINUX_X64 -> linuxX64()
        Platform.LINUX_ARM64 -> linuxArm64()
        Platform.MINGW_X64 -> mingwX64()
    }

    nativeTarget.apply {
        binaries {
            executable {
                entryPoint = "com.kgit2.kommand.main"
            }
        }
    }

    applyDefaultHierarchyTemplate()

    sourceSets {
        commonMain {
            dependencies {
                implementation(rootProject)
                implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.0-RC2")
                implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.5.0")
            }
        }
    }
}

enum class Platform(
    val archName: String
) {
    MACOS_X64("x86_64-apple-darwin"),
    MACOS_ARM64("aarch64-apple-darwin"),
    LINUX_X64("x86_64-unknown-linux-gnu"),
    LINUX_ARM64("aarch64-unknown-linux-gnu"),
    MINGW_X64("x86_64-pc-windows-gnu"),
    ;
}
plugins {
    kotlin("multiplatform") version "1.5.0-RC"
    id("org.jetbrains.dokka") version "1.4.0-rc"
    id("maven-publish")
    id("com.diffplug.spotless") version "5.8.2"
}

repositories {
    mavenCentral()
    jcenter()
}

kotlin {
    jvm() // Needed to satisfy multiplatform plugin
}

group = rootProject.extra["projectGroup"]!!
version = rootProject.extra["projectVersion"]!!

tasks.dokk


:
	.asciz	"x"                     // string offset=160
	.section	.debug_str_offsets,"",@progbits
	.word	.Linfo_string0
	.word	.Linfo_string1
	.word	.Linfo_string2
	.word	.Linfo_string3
	.word	.Linfo_string4
	.word	.Linfo_string5
	.word	.Linfo_string6
	.word	.Linfo_string7
	.word	.Linfo_string8
	.section	.debug_loclists,"",@progbits
	.word	.Ldebug_loclist_table_end0-.Ldebug_loclist_table_start0 // Length
.Ldebug_loclist_table_start0:
	.hword	5                       // Version
	.byte	8                       // Address size
	.byte	0                       // Segment selector size
	.word	1                       // Offset entry count
.Lloclists_table_base0:
	.word	.Ldebug_loc0-.Lloclists_table_base0
.Ldebug_loc0:
	.byte	4                       // DW_LLE_offset_pair
	.uleb128 .Ltmp0-.Lfunc_begin0   //   starting offset
	.uleb128 .Ltmp1-.Lfunc_begin0   //   ending offset
	.byte	3                       // Loc expr size
	.byte	17                      // DW_OP_consts
	.byte	1                       // 1
	.byte	159                     // DW_OP_stack_value
	.byte	4                       // DW_LLE_offset_pair
	.uleb128 .Ltmp1-.Lfunc_begin0   //   starting offset
	.uleb128 .Lfunc_end0-.Lfunc_begin0 //   ending offset
	.byte	2                       // Loc expr size
	.byte	141                     // DW_OP_breg29
	.byte	124                     // -4
	.byte	0                       // DW_LLE_end_of_list
.Ldebug_loclist_table_end0:
	.section	.debug_abbrev,"",@progbits
	.byte	1                       // Abbreviation Code
	.byte	17                      // DW_TAG_compile_unit
	.byte	1                       // DW_CHILDREN_yes
	.byte	37                      // DW_AT_producer
	.byte	37                      // DW_FORM_strx1
	.byte	19                      // DW_AT_language
	.byte	5                       // DW_FORM_data2
	.byte	3                       // DW_AT_name
	.byte	37                      // DW_FORM_strx1
	.byte	114                     // DW_AT_str_offsets_base
	.byte	23                      // DW_FORM_sec_offset
	.byte	16                      // DW_AT_stmt_list
	.byte	23                      // DW_FORM_sec_offset
	.byte	27                      // DW_AT_comp_dir
	.byte	37                      // DW_FORM_strx1
	.byte	17                      // DW_AT_low_pc
	.byte	27                      // DW_FORM_addrx
	.byte	18                      // DW_AT_high_pc
	.byte	6                       // DW_FORM_data4
	.byte	115                     // DW_AT_addr_base
	.byte	23                      // DW_FORM_sec_offset
	.ascii	"\214\001"              // DW_AT_loclists_base
	.byte	23                      // DW_FORM_sec_offset


 */
const _ChannelEnd = t.readonly(
  t.type({
    address: Address,
    deposit: UInt(32), // total deposit/contract balance
    withdraw: UInt(32),
    locks: t.readonlyArray(Lock),
    balanceProof: Signed(BalanceProof),
    pendingWithdraws: t.readonlyArray(
      t.union([Signed(WithdrawRequest), Signed(WithdrawConfirmation), Signed(WithdrawExpired)]),
    ),
    nextNonce: UInt(8), // usually balanceProof.nonce+1, but withdraw messages also increment it
  }),
  'ChannelEnd',
);
export interface ChannelEnd extends t.TypeOf<typeof _ChannelEnd> {}
export interface ChannelEndC extends t.Type<ChannelEnd, t.OutputOf<typeof _ChannelEnd>> {}
export const ChannelEnd: ChannelEndC = _ChannelEnd;

export const Channel = t.intersection([
  // readonly needs to be applied to the individual types to allow tagged union narrowing
  t.readonly(
    t.type({
      _id: ChannelUniqueKey,
      id: t.number,
      token: Address,
      tokenNetwork: Address,
      settleTimeout: t.number,
      isFirstParticipant: t.boolean,
      openBlock: t.number,
      own: ChannelEnd,
      partner: ChannelEnd,
    }),
    'Channel',
  ),
  t.union([
    /* union of types with literals intersection allows narrowing other props presence. e.g.:
     * if (channel.state === ChannelState.open) {
     *   id = channel.id; // <- id can't be undefined
     *   closeBlock = channel.closeBlock; // error: closeBlock only exist on states closed|settling
     * }
     */
    t.readonly(
      t.type({
        state: t.union([t.literal(ChannelState.open), t.literal(ChannelState.closing)]),
      }),
      'state[open|closing]',
    ),
    t.intersection([
      t.readonly(
        t.type({
          closeBlock: t.number,
          closeParticipant: Address,
        }),
        'ChannelClosed',
      ),
      t.union([
        t.readonly(
          t.type({
            state: t.union([
              t.literal(ChannelState.closed),
              t.literal(ChannelState.settleable),
              t.literal(ChannelState.settling),
            ]),
          }),
          'state[closed|settleable|settling]',
        ),
        t.readonly(
          t.type({ state: t.literal(ChannelState.settled), settleBlock: t.number }),
          'state[settled]',
        ),
      ]),
    ]),
  ]),
]);
export type Channel = t.TypeOf<typeof Channel>;

export interface ChannelBalances {
  ownDeposit: UInt<32>; // on-chain totalDeposit
  ownWithdraw: UInt<32>; // on-chain totalWithdraw
  ownTransferred: UInt<32>; // off-chain unlocked
  ownLocked: UInt<32>; // sum of locks not unlocked on- nor off-chain
  ownBalance: Int<32>; // received minus paid, unlocked either on- or off-chain
  ownCapacity: UInt<32>; // how much still available to be sent on channel
  ownOnchainUnlocked: UInt<32>; // total of locks registered on-chain and not unlocked off-chain
  ownUnlocked: UInt<32>; // off & on-chain unlocked amount *sent* from this end
  ownTotalWithdrawable: UInt<32>; // total which can be sent in a setTotalWithdraw call
  ownWithdrawable: UInt<32>; // maximum amount available currently to be withdrawn
  partnerDeposit: UInt<32>;
  partnerWithdraw: UInt<32>;
  partnerTransferred: UInt<32>;
  partnerLocked: UInt<32>;
  partnerBalance: Int<32>;
  partnerCapacity: UInt<32>;
  partnerOnchainUnlocked: UInt<32>;
  partnerUnlocked: UInt


,.page-item.previous.disabled .page-link:before{background-image:url('data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%23b9b9c3\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\' class=\'feather feather-chevron-left\'%3E%3Cpolyline points=\'15 18 9 12 15 6\'%3E%3C/polyline%3E%3C/svg%3E')}.page-item.next .page-link:after{background-image:url('data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%236e6b7b\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\' class=\'feather feather-chevron-right\'%3E%3Cpolyline points=\'9 18 15 12 9 6\'%3E%3C/polyline%3E%3C/svg%3E')}.page-item.next .page-link:hover:after{background-image:url('data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%237367f0\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\' class=\'feather feather-chevron-right\'%3E%3Cpolyline points=\'9 18 15 12 9 6\'%3E%3C/polyline%3E%3C/svg%3E')!important}.page-item.next.disabled .page-link:after{background-image:url('data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%23b9b9c3\' stroke-width=\'2\' stroke-linecap=\'round\' stroke-linejoin=\'round\' class=\'feather feather-chevron-right\'%3E%3Cpolyline points=\'9 18 15 12 9 6\'%3E%3C/polyline%3E%3C/svg%3E')}.page-item.disabled .page-link{color:#B9B9C3}.page-item .page-link{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-align:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;margin:0;font-size:1rem;min-width:2.286rem}.page-item .page-link:focus{box-shadow:none}.page-item .page-link:hover{color:#7367F0}.page-item.active{background-color:#F3F2F7;border-radius:0}.page-item.active .page-link{z-index:3;border-radius:5rem;background-color:#7367F0;color:#FFF!important;font-weight:600}.page-item:first-child:not(.prev-item).active{border-top-right-radius:1.428rem;border-bottom-right-radius:1.428rem}.page-item:first-child:not(.prev-item).active .page-link{border-radius:5rem}.page-item:first-child:not(.prev-item) .page-link{border-top-right-radius:1.428rem;border-bottom-right-radius:1.428rem}.page-item:last-child:not(.next-item).active{border-top-left-radius:1.428rem;border-bottom-left-radius:1.428rem}.page-item:last-child:not(.next-item).active .page-link{border-radius:5rem}.page-item:last-child:not(.next-item) .page-link{border-t


ognitionConfig.create)
    ..aOM<RecognitionAudio>(2, _omitFieldNames ? '' : 'audio',
        subBuilder: RecognitionAudio.create)
    ..aOM<TranscriptOutputConfig>(4, _omitFieldNames ? '' : 'outputConfig',
        subBuilder: TranscriptOutputConfig.create)
    ..hasRequiredFields = false;

  @$core.Deprecated('Using this can add significant overhead to your binary. '
      'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
      'Will be removed in next major version')
  LongRunningRecognizeRequest clone() =>
      LongRunningRecognizeRequest()..mergeFromMessage(this);
  @$core.Deprecated('Using this can add significant overhead to your binary. '
      'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
      'Will be removed in next major version')
  LongRunningRecognizeRequest copyWith(
          void Function(LongRunningRecognizeRequest) updates) =>
      super.copyWith(
              (message) => updates(message as LongRunningRecognizeRequest))
          as LongRunningRecognizeRequest;

  $pb.BuilderInfo get info_ => _i;

  @$core.pragma('dart2js:noInline')
  static LongRunningRecognizeRequest create() =>
      LongRunningRecognizeRequest._();
  LongRunningRecognizeRequest createEmptyInstance() => create();
  static $pb.PbList<LongRunningRecognizeRequest> createRepeated() =>
      $pb.PbList<LongRunningRecognizeRequest>();
  @$core.pragma('dart2js:noInline')
  static LongRunningRecognizeRequest getDefault() => _defaultInstance ??=
      $pb.GeneratedMessage.$_defaultFor<LongRunningRecognizeRequest>(create);
  static LongRunningRecognizeRequest? _defaultInstance;

  /// Required. Provides information to the recognizer that specifies how to
  /// process the request.
  @$pb.TagNumber(1)
  RecognitionConfig get config => $_getN(0);
  @$pb.TagNumber(1)
  set config(RecognitionConfig v) {
    setField(1, v);
  }

  @$pb.TagNumber(1)
  $core.bool hasConfig() => $_has(0);
  @$pb.TagNumber(1)
  void clearConfig() => clearField(1);
  @$pb.TagNumber(1)
  RecognitionConfig ensureConfig() => $_ensure(0);

  /// Required. The audio data to be recognized.
  @$pb.TagNumber(2)
  RecognitionAudio get audio => $_getN(1);
  @$pb.TagNumber(2)
  set audio(RecognitionAudio v) {
    setField(2, v);
  }

  @$pb.TagNumber(2)
  $core.bool hasAudio() => $_has(1);
  @$pb.TagNumber(2)
  void clearAudio() => clearField(2);
  @$pb.TagNumber(2)
  RecognitionAudio ensureAudio() => $_ensure(1);

  /// Optional. Specifies an optional destination for the recognition results.
  @$pb.TagNumber(4)
  TranscriptOutputConfig get outputConfig => $_getN(2);
  @$pb.TagNumber(4)
  set outputConfig(TranscriptOutputConfig v) {
    setField(4, v);
  }

  @$pb.TagNumber(4)
  $core.bool hasOutputConfig() => $_has(2);
  @$pb.TagNumber(4)
  void clearOutputConfig() => clearField(4);
  @$pb.TagNumber(4)
  TranscriptOutputConfig ensureOutputConfig() => $_ensure(2);
}

enum TranscriptOutputConfig_OutputType { gcsUri, notSet }

/// Specifies an optional destination for the recognition results.
class TranscriptOutputConfig extends $pb.GeneratedMessage {
  factory TranscriptOutputConfig({
    $core.String? gcsUri,
  }) {
    final $result = create();
    if (gcsUri != null) {
      $result.gcsUri = gcsUri;
    }
    return $result;
  }
  TranscriptOutputConfig._() : super();
  factory TranscriptOutputConfig.fromBuffer($core.List<$core.int> i,
          [$pb.Exten


e4ede0-8716-4691-a3fa-493c56c5be2d"
        val submitPath = "/submit/org-mozilla-samples-gleancore/deletion-request/1/$pingId"
        val content = "$submitPath\n{}"
        val pingFile = File(pendingDeletionRequestDir, pingId)
        assertTrue(pingFile.createNewFile())
        pingFile.writeText(content)

        val server = getMockWebServer()
        val context = getContext()

        resetGlean(
            context,
            Glean.configuration.copy(
                serverEndpoint = "http://" + server.hostName + ":" + server.port,
            ),
            clearStores = true,
            uploadEnabled = false,
        )
        triggerWorkManager(context)

        val request = server.takeRequest(2L, TimeUnit.SECONDS)!!
        val docType = request.path!!.split("/")[3]
        assertEquals("deletion-request", docType)
    }

    @Test
    fun `deletion-request pings are only sent when toggled from on to off`() {
        val server = getMockWebServer()
        val context = getContext()

        resetGlean(
            context,
            Glean.configuration.copy(
                serverEndpoint = "http://" + server.hostName + ":" + server.port,
            ),
            clearStores = true,
            uploadEnabled = true,
        )

        // Get directory for pending deletion-request pings
        val pendingDeletionRequestDir = File(Glean.getDataDir(), DELETION_PING_DIR)

        // Disabling upload generates a deletion ping
        Glean.setCollectionEnabled(false)
        triggerWorkManager(context)

        val request = server.takeRequest(2L, TimeUnit.SECONDS)!!
        val docType = request.path!!.split("/")[3]
        assertEquals("deletion-request", docType)

        // File is deleted afterwards.
        assertEquals(0, pendingDeletionRequestDir.listFiles()?.size)

        // Re-setting upload to `false` should not generate an additional ping
        // and no worker should be scheduled.
        Glean.setCollectionEnabled(false)

        assertFalse(getWorkerStatus(context, PingUploadWorker.PING_WORKER_TAG).isEnqueued)
        // No new file should have been written
        assertEquals(0, pendingDeletionRequestDir.listFiles()?.size)
    }

    @Test
    fun `non-deletion-pings are not uploaded when upload disabled`() {
        // Create directory for pending pings
        val pendingDeletionRequestDir = File(Glean.getDataDir(), DELETION_PING_DIR)
        pendingDeletionRequestDir.mkdirs()
        val pendingPingDir = File(Glean.getDataDir(), PENDING_PING_DIR)
        pendingPingDir.mkdirs()

        // Write a deletion-request ping file
        var pingId = "775b6590-7f21-11ea-92e3-479998edf98c"
        var submitPath = "/submit/org-mozilla-samples-gleancore/deletion-request/1/$pingId"
        var content = "$submitPath\n{}"
        var pingFile = File(pendingDeletionRequestDir, pingId)
        assertTrue(pingFile.createNewFile())
        pingFile.writeText(content)

        // Write a baseline ping file
        pingId = "899b0ab8-7f20-11ea-ac03-ff76f2a19f1c"
        submitPath = "/submit/org-mozilla-samples-gleancore/baseline/1/$pingId"
        content = "$submitPath\n{}"
        pingFile = File(pendingPingDir, pingId)
        assertTrue(pingFile.createNewFile())
        pingFile.writeText(content)

        val server = getMockWebServer()
        val context = getContext()

        resetGlean(
            context,
            Glean.configuration.copy(
                serverEndpoint = "http://" + server.host


4_m_r(Amode::imm_reg(128, r9), w_rdi),
        "498BB980000000",
        "movq    128(%r9), %rdi",
    ));
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(128, r10), w_rdi),
        "498BBA80000000",
        "movq    128(%r10), %rdi",
    ));
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(128, r11), w_rdi),
        "498BBB80000000",
        "movq    128(%r11), %rdi",
    ));
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(128, r12), w_rdi),
        "498BBC2480000000",
        "movq    128(%r12), %rdi",
    ));
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(128, r13), w_rdi),
        "498BBD80000000",
        "movq    128(%r13), %rdi",
    ));
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(128, r14), w_rdi),
        "498BBE80000000",
        "movq    128(%r14), %rdi",
    ));
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(128, r15), w_rdi),
        "498BBF80000000",
        "movq    128(%r15), %rdi",
    ));

    // ========================================================
    // Addr_IR, offset smallest negative simm32
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(-129i32 as u32, rax), w_rdi),
        "488BB87FFFFFFF",
        "movq    -129(%rax), %rdi",
    ));
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(-129i32 as u32, rbx), w_rdi),
        "488BBB7FFFFFFF",
        "movq    -129(%rbx), %rdi",
    ));
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(-129i32 as u32, rcx), w_rdi),
        "488BB97FFFFFFF",
        "movq    -129(%rcx), %rdi",
    ));
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(-129i32 as u32, rdx), w_rdi),
        "488BBA7FFFFFFF",
        "movq    -129(%rdx), %rdi",
    ));
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(-129i32 as u32, rbp), w_rdi),
        "488BBD7FFFFFFF",
        "movq    -129(%rbp), %rdi",
    ));
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(-129i32 as u32, rsp), w_rdi),
        "488BBC247FFFFFFF",
        "movq    -129(%rsp), %rdi",
    ));
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(-129i32 as u32, rsi), w_rdi),
        "488BBE7FFFFFFF",
        "movq    -129(%rsi), %rdi",
    ));
    insns.push((
        Inst::mov64_m_r(Amode::imm_reg(-129i32 as u32, rdi), w_rdi),
        "488BBF7FFFFFFF",
        "movq    -129(%rdi), %rdi",
    ));
    insns.push((
        Inst