r v) {
        return new BNField2(bn, re.multiply(v), im.multiply(v));
    }

    /**
     * (x + yi)(u + vi) = (xu - yv) + ((x + y)(u + v) - xu - yv)i
     */
    public BNField2 multiply(BNField2 v) {
        if (!bn.equals(v.bn)) {
            throw new IllegalArgumentException(differentFields);
        }
        final BigInteger re2 = re.multiply(v.re); // mod p
        final BigInteger im2 = im.multiply(v.im); // mod p
        final BigInteger mix = re.add(im).multiply(v.re.add(v.im)); // mod p;
        return new BNField2(bn, re2.subtract(im2), mix.subtract(re2).subtract(im2));
    }

    /**
     * (x + yi)i = (-y + ix)
     */
    public BNField2 multiplyI() {
        return new BNField2(bn, bn.p.subtract(im), re, 0);
    }

    /**
     * (x + yi)(1 + i) = (x - y) + (x + y)i
     */
    public BNField2 multiplyV() {
        BigInteger r = re.subtract(im);
        if (r.signum() < 0) {
            r = r.add(bn.p);
        }
        BigInteger i = re.add(im);
        if (i.compareTo(bn.p) >= 0) {
            i = i.subtract(bn.p);
        }
        return new BNField2(bn, r, i, 0);
    }

    public BNField2 negate() {
        /*
         * -(x + yi)
         */
        return new BNField2(bn, bn.p.subtract(re), bn.p.subtract(im), 0);
    }

    public BigInteger norm() {
        /*
         * (x + yi)^{p + 1} = (x - yi)(x + yi) = x^2 + y^2
         */
        return re.multiply(re).add(im.multiply(im)).mod(bn.p);
    }

    /**
     * Compute a square root of this.
     *
     * @return a square root of this if one exists, or null otherwise.
     */
    public BNField2 sqrt() {
        if (isZero()) {
            return this;
        }
        BNField2 r = exp(bn.sqrtExponent2); // r = v^{(p^2 + 7)/16}
        BNField2 r2 = r.square();
        if (r2.subtract(this).isZero()) {
            return r;
        }
        if (r2.add(this).isZero()) {
            return r.multiplyI();
        }
        r2 = r2.multiplyI();
        final BNField2 sqrtI = new BNField2(bn, bn.invSqrtMinus2, bn.p.subtract(bn.invSqrtMinus2), 0); // sqrt(i) = (1 -
        // i)/sqrt(-2)
        r = r.multiply(sqrtI);
        if (r2.subtract(this).isZero()) {
            return r;
        }
        if (r2.add(this).isZero()) {
            return r.multiplyI();
        }
        return null;
    }

    /*
     * public BNField2 exp0(BigInteger k) { BNField2 u = this; for (int i = k.bitLength()-2; i >= 0; i--) { u =
     * u.square(); if (k.testBit(i)) { u = u.multiply(this); } } return u; } //
     */

    /**
     * (x + yi)^2 = (x + y)(x - y) + 2xyi
     */
    public BNField2 square() {
        return new BNField2(bn, re.add(im).multiply(re.subtract(im)), re.multiply(


 set.
   * @override
   * @throws [[InvalidOperationException]] this pin is not configured for PWM.
   */
  public async setPwm(value: number) {
    if (this.mode !== PinMode.PWM) {
      throw new InvalidOperationException('Cannot set PWM value on a pin not configured for PWM.');
    }

    if (value < 0) {
      value = 0;
    }

    if (value > 1023) {
      value = 1023;
    }

    if (this.pinPwm !== value) {
      this.pinPwm = value;
      let cmd: string = '';
      const cmds: Promise<string[]>[] = [];
      if (!this.isPwmPin) {
        // We may have to change mode first.
        cmd = `gpio mode ${GpioPins[this.innerPin]} pwm`;
        cmds.push(ExecUtils.executeCommand(cmd));
        this.isPwmPin = true;
      }

      cmd = `gpio pwm ${GpioPins[this.innerPin]} ${this.pinPwm.toString()}`;
      cmds.push(ExecUtils.executeCommand(cmd));
      await Promise.all(cmds);
    }
  }

  /**
   * Provisions the I/O pin. See http://wiringpi.com/reference/raspberry-pi-specifics/
   * @throws [[ObjectDisposedException]] if this instance has been disposed.
   * @override
   */
  public async provision() {
    if (this.isDisposed) {
      throw new ObjectDisposedException('GpioStandard');
    }

    await this.exportPin(this.innerPin, this.mode);
    return this.privWrite(this.innerPin, this.getInitialPinValue());
  }

  /**
   * Write a value to the pin.
   * @param ps The pin state value to write to the pin.
   * @throws [[ObjectDisposedException]] if this instance has been disposed.
   * @emits [[PinStateChangeEvent]] if the pin is changing state.
   * @override
   */
  public async write(ps: PinState) {
    await super.write(ps);
    await this.privWrite(this.innerPin, ps);
    if (this.lastPinState !== ps) {
      const psce = new PinStateChangeEvent(this.lastPinState, ps, this.innerPin);
      this.onPinStateChange(psce);
      this.lastPinState = ps;
    }
  }

  /**
   * Pulse the pin output for the specified number of milliseconds.
   * @param millis The number of milliseconds to wait between states.
   * @throws [[ObjectDisposedException]] if this instance has been disposed.
   * @throws [[InvalidOperationException]] the this pin is not configured as
   * an input.
   * @emits [[PinStateChangeEvent]] as the pin changes state.
   * @override
   */
  public async pulse(millis: number = 500) {
    if (this.mode === PinMode.IN) {
      throw new InvalidOperationException('You cannot pulse a pin set as in input.');
    }

    await this.write(PinState.HIGH);
    await CoreUtils.delay(millis);
    await this.write(PinState.LOW);
  }

  /**
   * Gets the value (state) of the pin.
   * @returns The pin state.
   * @throws [[ObjectDisposedException]] if this instance has been disposed.
   * @emits [[PinStateChangeEvent]] if the pin has changed state since the
   * last read.
   * @override
   */
  public async read() {
    const val = await this.privRead(this.innerPin);
    if (this.lastPinState !== val) {
      this.onPinStateChange(new PinStateChangeEvent(this.lastPinState, val, this.innerPin));
      this.lastPinState = val;
    }

    return


import enum

import torch

class BiasMetrics(enum.Enum):
    """ """

    TPR_GAP = "TPR_GAP"
    FPR_GAP = "FPR_GAP"
    TNR_GAP = "TNR_GAP"
    FNR_GAP = "FNR_GAP"
    EO_GAP = "EO_GAP"
    DP_GAP = "DP_GAP"

def stabilize(x, epsilon=1e-4):
    """

    Args:
      x:
      epsilon:  (Default value = 1e-4)

    Returns:

    """
    return torch.max(x, torch.tensor(epsilon, dtype=x.dtype, device=x.device))

def calculate_bias_metric_torch(
    metric: BiasMetrics | str,
    y_pred: torch.Tensor,
    y_true: torch.Tensor,
    protected_attribute: torch.Tensor,
) -> torch.Tensor:
    """

    Args:
      metric: BiasMetrics | str:
      y_pred: torch.Tensor:
      y_true: torch.Tensor:
      protected_attribute: torch.Tensor:

    Returns:

    """
    if isinstance(metric, BiasMetrics):
        metric = metric.value

    # Make sure proper data types are used
    prot_attr = protected_attribute.bool()
    y_true = y_true.int()
    y_pred = y_pred.int()

    # Calculate confusion matrix for group A (prot_attr == 1)
    tp_a = ((y_pred[prot_attr] == 1) & (y_true[prot_attr] == 1)).sum().float()
    fp_a = ((y_pred[prot_attr] == 1) & (y_true[prot_attr] == 0)).sum().float()
    tn_a = ((y_pred[prot_attr] == 0) & (y_true[prot_attr] == 0)).sum().float()
    fn_a = ((y_pred[prot_attr] == 0) & (y_true[prot_attr] == 1)).sum().float()

    # Calculate rates for group A
    tpr_a = tp_a / stabilize(tp_a + fn_a)
    fpr_a = fp_a / stabilize(fp_a + tn_a)
    tnr_a = tn_a / stabilize(tn_a + fp_a)
    fnr_a = fn_a / stabilize(fn_a + tp_a)

    # Calculate confusion matrix for group B (prot_attr == 0)
    tp_b = ((y_pred[~prot_attr] == 1) & (y_true[~prot_attr] == 1)).sum().float()
    fp_b = ((y_pred[~prot_attr] == 1) & (y_true[~prot_attr] == 0)).sum().float()
    tn_b = ((y_pred[~prot_attr] == 0) & (y_true[~prot_attr] == 0)).sum().float()
    fn_b = ((y_pred[~prot_attr] == 0) & (y_true[~prot_attr] == 1)).sum().float()

    tpr_b = tp_b / stabilize(tp_b + fn_b)
    fpr_b = fp_b / stabilize(fp_b + tn_b)
    tnr_b = tn_b / stabilize(tn_b + fp_b)
    fnr_b = fn_b / stabilize(fn_b + tp_b)

    ppr_a = (y_pred[prot_attr] == 1).sum().float() / stabilize(
        prot_attr.int().sum()
    ).float()
    ppr_b = (y_pred[~prot_attr] == 1).sum().float() / stabilize(
        (~prot_attr).int().sum()
    ).float()

    if metric == BiasMetrics.TPR_GAP.value:
        bias = torch.abs(tpr_a - tpr_b)
    elif metric == BiasMetrics.FPR_GAP.value:
        bias = torch.abs(fpr_a - fpr_b)
    elif metric == BiasMetrics.TNR_GAP.value:
        bias = torch.abs(tnr_a - tnr_b)
    elif metric == BiasMetrics.FNR_GAP.value:
        bias = torch.abs(fnr_a - fnr_b)
    elif metric == BiasMetrics.EO_GAP.value:
        bias = torch.max(torch.abs(tpr_a - tpr_b), torch.abs(fpr_a - fpr_b))
    elif metric == BiasMetrics.DP_GAP.value:
        bias = torch.abs(ppr_a - ppr_b)
    else:
        raise ValueError(f"Unknown bias metric: {metric}")

    return bias


afa,#ececec);background:-webkit-gradient(linear,left top,right bottom,from(#fafafa),to(#ececec))}
#breadcrumbs .breadcrumb-button .breadcrumb-arrow span{background-color:#fafafa;background:-moz-linear-gradient(135deg,#ececec,#fafafa);background:-ms-linear-gradient(135deg,#ececec,#fafafa);background:-o-linear-gradient(135deg,#ececec,#fafafa);background:-webkit-gradient(linear,right bottom,left top,from(#ececec),to(#fafafa))}
#breadcrumbs .breadcrumb-button:first-child{-webkit-border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;-ms-border-radius:3px 0 0 3px;-o-border-radius:3px 0 0 3px;border-radius:3px 0 0 3px}
#breadcrumbs .breadcrumb-button:first-child .breadcrumb-label{border-top-left-radius:3px;border-bottom-left-radius:3px}
#breadcrumbs .breadcrumb-button:last-child{-webkit-border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;-ms-border-radius:0 3px 3px 0;-o-border-radius:0 3px 3px 0;border-radius:0 3px 3px 0}
#breadcrumbs .breadcrumb-button:first-child .breadcrumb-label{padding-left:15px}
#breadcrumbs .breadcrumb-button:last-child .breadcrumb-label{padding-right:15px}
#breadcrumbs .breadcrumb-button:last-child .breadcrumb-arrow{display:none}
#breadcrumbs .breadcrumb-button .breadcrumb-label{padding:8px;-moz-user-select:none;-webkit-user-select:none;display:inline-block;padding-left:25px}
#breadcrumbs .breadcrumb-button .breadcrumb-arrow{width:17px;height:34px;display:inline-block;vertical-align:top;overflow:hidden;margin-left:-5px}
#breadcrumbs .breadcrumb-button .breadcrumb-arrow span{border-radius:4px;width:26px;height:30px;display:inline-block;-webkit-transform:rotate(45deg);-moz-transform:rotate(45deg);-ms-transform:rotate(45deg);-o-transform:rotate(45deg);transform:rotate(45deg);margin-left:-16px;margin-top:3px}
.breadcrumb-line{color:#666;height:28px;-webkit-box-shadow:0 1px 0 white,0 1px 0 white inset;-moz-box-shadow:0 1px 0 white,0 1px 0 white inset;box-shadow:0 1px 0 white,0 1px 0 white inset;background:#e3e3e3;background-image:url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4gPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJncmFkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjUwJSIgeTE9IjAlIiB4Mj0iNTAlIiB5Mj0iMTAwJSI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2Y0ZjRmNCIvPjxzdG9wIG9mZnNldD0iMTAwJSIgc3RvcC1jb2xvcj0iI2UzZTNlMyIvP


et to "production"');
    }
  }

  /**
   * Check dependencies
   */
  async checkDependencies() {
    console.log('📦 Checking dependencies...');

    try {
      const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));

      // Check for security vulnerabilities
      try {
        execSync('npm audit --audit-level=high', { stdio: 'pipe' });
        this.checks.push('✅ No high-severity security vulnerabilities found');
      } catch (error) {
        this.errors.push('High-severity security vulnerabilities found. Run "npm audit fix"');
      }

      // Check for outdated dependencies
      try {
        const outdated = execSync('npm outdated --json', { stdio: 'pipe' }).toString();
        const outdatedPackages = JSON.parse(outdated || '{}');

        if (Object.keys(outdatedPackages).length > 0) {
          this.warnings.push(`${Object.keys(outdatedPackages).length} outdated dependencies found`);
        } else {
          this.checks.push('✅ All dependencies are up to date');
        }
      } catch (error) {
        // npm outdated returns exit code 1 when outdated packages exist
        this.warnings.push('Some dependencies may be outdated');
      }

      // Check for production dependencies
      const prodDeps = Object.keys(packageJson.dependencies || {});
      if (prodDeps.length === 0) {
        this.warnings.push('No production dependencies found');
      } else {
        this.checks.push(`✅ ${prodDeps.length} production dependencies`);
      }

    } catch (error) {
      this.errors.push('Failed to check dependencies: ' + error.message);
    }
  }

  /**
   * Check build configuration
   */
  async checkBuildConfiguration() {
    console.log('🔧 Checking build configuration...');

    // Check Next.js configuration
    if (fs.existsSync('next.config.js')) {
      this.checks.push('✅ next.config.js exists');

      try {
        const nextConfig = require(path.resolve('next.config.js'));

        // Check for production optimizations
        if (nextConfig.compress !== false) {
          this.checks.push('✅ Compression enabled');
        }

        if (nextConfig.poweredByHeader === false) {
          this.checks.push('✅ X-Powered-By header disabled');
        } else {
          this.warnings.push('Consider disabling X-Powered-By header for security');
        }

      } catch (error) {
        this.warnings.push('Could not validate next.config.js');
      }
    } else {
      this.warnings.push('next.config.js not found');
    }

    // Check TypeScript configuration
    if (fs.existsSync('tsconfig.json')) {
      this.checks.push('✅ tsconfig.json exists');

      try {
        const tsConfig = JSON.parse(fs.readFileSync('tsconfig.json', 'utf8'));

        if (tsConfig.compilerOptions?.strict) {
          this.checks.push('✅ TypeScript strict mode enabled');
        } else {
          this.warnings.push('Consider enabling TypeScript strict mode');
        }

      } catch (error) {
        this.warnings.push('Could not validate tsconfig.json');
      }
    } else {
      this.errors.push('tsconfig.json not found');
    }
  }

  /**
   * Check security configuration
   */
  async checkSecurityConfiguration() {
    console.log('🔒 Checking security configuration...


pink.rating .icon.partial.active{background:linear-gradient(to right,#ff8edf 0 var(--full),rgba(0,0,0,.15) var(--full) 100%);-webkit-text-stroke:#e03997 .78px}.ui.brown.rating .active.icon{color:#d67c1c;text-shadow:0 -1px 0 #a5673f,-1px 0 0 #a5673f,0 1px 0 #a5673f,1px 0 0 #a5673f}.ui.brown.rating .icon.selected,.ui.brown.rating .icon.selected.active,.ui.brown.rating .icon.selected.partial.active{background:inherit;color:#b0620f;text-shadow:0 -1px 0 #975b33,-1px 0 0 #975b33,0 1px 0 #975b33,1px 0 0 #975b33;-webkit-text-stroke:unset;background-clip:unset}.ui.brown.rating .icon.partial.active{background:linear-gradient(to right,#d67c1c 0 var(--full),rgba(0,0,0,.15) var(--full) 100%);-webkit-text-stroke:#a5673f .78px}.ui.grey.rating .active.icon{color:#dcddde;text-shadow:0 -1px 0 #767676,-1px 0 0 #767676,0 1px 0 #767676,1px 0 0 #767676}.ui.grey.rating .icon.selected,.ui.grey.rating .icon.selected.active,.ui.grey.rating .icon.selected.partial.active{background:inherit;color:#c2c4c5;text-shadow:0 -1px 0 #838383,-1px 0 0 #838383,0 1px 0 #838383,1px 0 0 #838383;-webkit-text-stroke:unset;background-clip:unset}.ui.grey.rating .icon.partial.active{background:linear-gradient(to right,#dcddde 0 var(--full),rgba(0,0,0,.15) var(--full) 100%);-webkit-text-stroke:#767676 .78px}.ui.black.rating .active.icon{color:#545454;text-shadow:0 -1px 0 #1b1c1d,-1px 0 0 #1b1c1d,0 1px 0 #1b1c1d,1px 0 0 #1b1c1d}.ui.black.rating .icon.selected,.ui.black.rating .icon.selected.active,.ui.black.rating .icon.selected.partial.active{background:inherit;color:#000;text-shadow:0 -1px 0 #27292a,-1px 0 0 #27292a,0 1px 0 #27292a,1px 0 0 #27292a;-webkit-text-stroke:unset;background-clip:unset}.ui.black.rating .icon.partial.active{background:linear-gradient(to right,#545454 0 var(--full),rgba(0,0,0,.15) var(--full) 100%);-webkit-text-stroke:#1b1c1d .78px}.ui.disabled.rating .icon{cursor:default;pointer-events:none}.ui.rating.selected .active.icon{opacity:1}.ui.rating .icon.selected,.ui.rating.selected .icon.selected{opacity:1}.ui.rating{font-size:1rem}.ui.mini.rating{font-size:.78571429rem}.ui.tiny.rating{font-size:.85714286rem}.ui.small.rating{font-size:.92857143rem}.ui.large.rating{font-size:1.14285714rem}.ui.big.rating{font-size:1.28571429rem}.ui.huge.rating{font-size:1.42857143rem}.ui.massive.rating{font-size:2rem}/*!
 * # Fomantic-UI 2.9.4 - Sticky
 * https://github.com/fomantic/Fomantic-UI/
 *
 *
 * Released under the MIT license
 * https://opensource.org/licenses/MIT
 *
 */

/*******************************
            Sticky
*******************************/

.ui.sticky {
  position: static;
  transition: none;
  z-index: 800;
}

/


RecordNodeStatusChange用于记录节点状态的变化。

SwapNodeControllerTaint用于交换节点控制器的Taint。

AddOrUpdateLabelsOnNode用于添加或更新节点的标签。

CreateAddNodeHandler用于创建添加节点的处理器。

CreateUpdateNodeHandler用于创建更新节点的处理器。

CreateDeleteNodeHandler用于创建删除节点的处理器。

GetNodeCondition用于获取节点的条件信息。

在整个node控制器中，这些函数都是重要的功能组成部分，它们协同工作，实现对节点的控制和管理。有些函数是用于记录节点状态的变化，有些函数是用于更新和删除节点的Pod，而有些函数则是用于添加和更新节点的标签。这些函数的使用都可以帮助运维人员更加方便地对节点进行管理和维护。

# File: pkg/volume/vsphere_volume/attacher.go

在Kubernetes项目中，pkg/volume/vsphere_volume/attacher.go文件的作用是实现vSphere卷附加功能。vSphere是VMware公司的虚拟化平台，通过该文件实现与vSphere数据存储相关的卷的挂载和卸载操作。

对于变量_,attachdetachMutex，下划线表示空白标识符，用于占位表示占据一个变量位置但不使用，而attachdetachMutex是一个互斥锁，用于确保并发时只有一个卷可以被附加或分离。

vsphereVMDKAttacher结构体是一个实现了Attacher接口的类型，用于实现vSphere卷的附加操作。它包括一些字段和方法，用于处理卷的附加和卸载。

vsphereVMDKDetacher结构体是一个实现了Detacher接口的类型，用于实现vSphere卷的分离操作。它也包括一些字段和方法，用于处理卷的分离和卸载。

NewAttacher函数用于创建一个新的vsphereVMDKAttacher实例。

NewDeviceMounter函数用于创建一个新的DeviceMounter实例，用于将设备挂载到指定路径。

Attach函数用于将vSphere卷附加到指定节点的指定路径上。

VolumesAreAttached函数用于判断给定的卷是否已经附加到指定的节点上。

BulkVerifyVolumes函数用于批量验证给定的卷是否都已经附加到指定的节点上。

WaitForAttach函数用于等待给定的卷被附加到指定的节点上。

GetDeviceMountPath函数用于获取给定的卷在指定节点上的挂载路径。

GetDeviceMountRefs函数用于获取给定的卷在指定节点上的挂载引用。

MountDevice函数用于将给定的卷挂载到指定的节点上的指定路径。

NewDetacher函数用于创建一个新的vsphereVMDKDetacher实例。

NewDeviceUnmounter函数用于创建一个新的DeviceUnmounter实例，用于卸载设备。

Detach函数用于将指定的卷从指定节点上分离。

UnmountDevice函数用于卸载指定节点上的指定设备。

CanAttach函


200);
 * writer.writeUInt32(12345678);
 * writer.writeString("hello");
 * writer.writeUInt16(45000);
 *
 * // Read the values
 * const binaryString = writer.toString();
 * const reader = new BinaryReader(binaryString);
 * const values: any[] = [];
 *
 * values[0] = reader.readUInt8(); // 5
 * values[1] = reader.readUInt8(); // 32
 * values[2] = reader.readUInt8(); // 78
 * values[3] = reader.readUInt8(); // 200
 * values[4] = reader.readUInt32(); // 12345678
 * values[5] = reader.readString(); // hello
 * values[6] = reader.readUInt16(); // 45000
 * ```
 */
export class BinaryWriter {
  public readonly values: (string | number)[] = [];

  private fmj = ">";

  public toString() {
    return string.pack(this.fmj, ...this.values);
  }

  public writeDouble(value: number) {
    this.fmj += "d";
    this.values.push(value);
  }

  public writeFloat(value: number) {
    this.fmj += "f";
    this.values.push(value);
  }

  public writeInt16(value: number) {
    this.fmj += "h";
    this.values.push(value);
  }

  public writeInt32(value: number) {
    this.fmj += "i4";
    this.values.push(value);
  }

  public writeInt8(value: number) {
    this.fmj += "b";
    this.values.push(value);
  }

  public writeString(value: string) {
    this.fmj += "z";
    this.values.push(value);
  }

  public writeUInt16(value: number) {
    this.fmj += "H";
    this.values.push(value);
  }

  public writeUInt32(value: number) {
    this.fmj += "I4";
    this.values.push(value);
  }

  public writeUInt8(value: number) {
    this.fmj += "B";
    this.values.push(value);
  }
}
import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  OneToMany,
  ManyToOne,
} from 'typeorm';
import { User } from '../../user/entities/user.entity';
import { PlaylistItem } from '../../playlist-item/entities/playlist-item.entity';
import { Identifiable } from '../../common/interfaces/identifiable';

@Entity()
export class Playlist implements Identifiable {
  @PrimaryGeneratedColumn()
  public id: number;
  @Column()
  public name: string;

  // Relations

  @ManyToOne(
    type => User,
    user => user.playlists,
    { onDelete: 'CASCADE', eager: true, nullable: false }, //TODO: delete eager
  )
  public user: User;

  @OneToMany(
    type => PlaylistItem,
    playlistItem => playlistItem.playlist,
    { onDelete: 'CASCADE', nullable: false, eager: true },
  )
  public playlistItems: PlaylistItem[];
}
export class IndexTest {
  public someMethod(prop: string): string {
    if (prop === 'test') {
      // tslint:disable-next-line:no-console
      console.log('test');
    } else {
      // tslint:disable-next-line:no-console
      console.log('prod');
    }
    return prop.toUpperCase();
  }
}
import { MiddlewareAPI, Dispatch, Action } from 'redux';
import { getDarkTheme, setDarkTheme } from '../actions/data';
import { getThemeLocalStorage, setThemeLocalStorage } from '../utils/theme-local-storage';

export const isDarkTheme = (store: MiddlewareAPI) => (next: Dispatch) => (action: Action) => {
  if (action.type =


color: #3C3C3C) {
  background-color: transparent;
  background-color: rgba($r, $g, $b, $opacity);
            filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#{$color}',endColorstr='#{$color}');
            zoom:   1;
}

/// Box Shadow
/// @param {Size} $x [2px] - X
/// @param {Size} $y [2px] - Y
/// @param {Size} $blur [5px] - Blur
/// @param {Color} $color [rgba(0,0,0,.4)] - Color
/// @param {Boolean} $inset - Inset

@mixin box-shadow($x: 2px, $y: 2px, $blur: 5px, $color: rgba(0,0,0,.4), $inset: "") {
  @if ($inset != "") {
    @include css3-prefix('box-shadow', $inset $x $y $blur $color);
  } @else {
    @include css3-prefix('box-shadow', $x $y $blur $color);
  }
}

/// Box Sizing
/// @param {*} $type [border-box] - Type
/// @require {mixin} css3-prefix

@mixin box-sizing($type: border-box) {
  @include css3-prefix('box-sizing', $type);
}

/// Columns
/// @param {Integer} $count [3] - Count
/// @param {Integer} $gap [10] - Gap
/// @require {mixin} css3-prefix

@mixin columns($count: 3, $gap: 10) {
  @include css3-prefix('column-count', $count);
  @include css3-prefix('column-gap', $gap);
}

/// Double Borders
/// @param {Color} $colorOne [#3C3C3C] - Color One
/// @param {Color} $colorTwo [#999999] - Color Two
/// @param {Size} $radius [0] - Radius
/// @require {mixin} css3-prefix
/// @require {mixin} border-radius

@mixin double-borders($colorOne: #3C3C3C, $colorTwo: #999999, $radius: 0) {
  border: 1px solid $colorOne;

  @include css3-prefix('box-shadow', 0 0 0 1px $colorTwo);

  @include border-radius( $radius );
}

/// Flex
/// @param {Integer} $value [1] - Value
/// @require {mixin} css3-prefix

@mixin flex($value: 1) {
  @include css3-prefix('box-flex', $value);
}

/// Flip
/// @param {Double} $scaleX [-1] - ScaleX
/// @require {mixin} css3-prefix

@mixin flip($scaleX: -1) {
  @include css3-prefix('transform', scaleX($scaleX));
  filter:            FlipH;
  -ms-filter:        "FlipH";
}

/// Font Face
/// @param {Font} $fontFamily [myFont] - Font Family
/// @param {String} $eotFileSrc ['myFont.eot'] - Eot File Source
/// @param {String} $woffFileSrc ['myFont.woff'] - Woff File Source
/// @param {String} $ttfFileSrc ['myFont.ttf'] - Ttf File Source
/// @param {String} $svgFileSrc ['myFont.svg'] - Svg File Source

@mixin font-face($fontFamily: myFont, $eotFileSrc: 'myFont.eot', $woffFileSrc: 'myFont.woff', $ttfFileSrc: 'myFont.ttf', $svgFileSrc: 'myFont.svg', $svgFontID: '#myFont') {
  font-family: $fontFamily;
  src: url($eotFileSrc)  format('eot'),
       url($woffFileSrc) format('woff'),
       url($ttfFileSrc)  format('truetype'),
       url($svgFileSrc + $svgFontID) format('svg');
}

/// Opacit


         songId: model!.songId),
                                    if (!DownloadManager()
                                        .hasDownloaded(model.songId))
                                      CommonPopupMenuItemDownload(model: model)
                                  ]);
                                },
                              );
                            },
                          );
                        }
                      },
                      indexCountBuilder: (context, section) {
                        if (section == 0) {
                          return 1;
                        } else {
                          return viewModel?.songs.isEmpty == true
                              ? 0
                              : viewModel!.songs.length;
                        }
                      },
                    );
                  },
                ),
              );
            } else {
              return const LoadingView();
            }
          },
        ));
  }

  @override
  MyLikeStateModel? createViewModel() {
    return MyLikeStateModel();
  }
}
import 'package:dream_music/src/config/global_constant.dart';
import 'package:dream_music/src/pages/song_detail/model/single_song_model.dart';
import 'package:dream_music/src/pages/songlist/model/songlist_detail_model.dart';

/// 每日歌曲推荐
class DailySongsModel {
  List<SonglistDetailModelTracks?>? dailySongs;
  List<RecommendReasonModel?>? recommendReasons;

  DailySongsModel({
    this.dailySongs,
    this.recommendReasons,
  });

  DailySongsModel.fromJson(Map<String, dynamic> json) {
    if (json['dailySongs'] != null && (json['dailySongs'] is List)) {
      final v = json['dailySongs'];
      final arr0 = <SonglistDetailModelTracks>[];
      v.forEach((v) {
        arr0.add(SonglistDetailModelTracks.fromJson(v));
      });
      dailySongs = arr0;
    }
    if (json['recommendReasons'] != null &&
        (json['recommendReasons'] is List)) {
      final v = json['recommendReasons'];
      final arr0 = <RecommendReasonModel>[];
      v.forEach((v) {
        arr0.add(RecommendReasonModel.fromJson(v));
      });
      recommendReasons = arr0;
    }
  }

  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    if (dailySongs != null) {
      final v = dailySongs;
      final arr0 = [];
      for (var v in v!) {
        arr0.add(v!.toJson());
      }
      data['dailySongs'] = arr0;
    }
    if (recommendReasons != null) {
      final v = recommendReasons;
      final arr0 = [];
      for (var v in v!) {
        arr0.add(v!.toJson());
      }
      data['recommendReasons'] = arr0;
    }
    return data;
  }

  /// 获取歌曲详情数组
  List<SingleSongModel> getSongs() {
    if (dailySongs == null) return [];
    final tracks = dailySongs!;
    List<SingleSongModel> ret = [];
    for (int i = 0; i < tracks.length; i++) {
      final track = tracks[i];
      ret.add(
            SingleSongModel(
              track:track,
              privilege: null
            )
        );
    }
    return ret;
  }

  /// 每日推荐歌曲的歌单id
  int get songlistId => kDailySongsSonglistId;
}

class RecommendReasonModel {
  /*
    {
    "songId": 1896178370,
    "reason": "超73%人播放"
    }
  */

  int? songId;
  String? reason;

  RecommendReasonModel({
    this.songId,
    this.reason,
  });
  RecommendReasonModel.fromJson(Map<String, dynamic> json) {
    songId = int.tryParse(json['songId']?.toString() ?? '');
    reason = json['reason']?.toString();
  }
  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['songId'] = songId;
    data['reason'] = reason;
    return data;
  }
}
import 'package:dream_music/src/components/basic/mixin_easy_interface.dart';
import 'package:dream_music/src/components/button/main_button.dart';
import 'package:dream_music/src/components/downloder/download_manager.dart';
import 'package:dream_music/src/components/image/image_view.dart';
import 'package:dream_music/src/config/global_constant.dart';
import 'package:dream_music/src/config/theme_color_constant.dart';
import 'package:dream_music/src/pages/dailysongs/model/daily_songs_state_model.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';


import os
import time
import random

from ledcube.core import rgb_graphics, Face
from ledcube.core.color import Color
from ledcube.core.cube import Cube
from ledcube.core.utils import reverse

fonts_text = (
    # '8pt_15_H.bdf',
    # 'Espy_Sans_Bold_14.bdf',
    # 'Espy_Sans_Bold_16.bdf',
    # 'Modern_12pt_10_H.bdf',
    # 'Modern_12pt_H.bdf',
    'Athens_18.bdf',
    'Classic_18pt_H.bdf',
    'Cory_24.bdf',
    'Courier_15.bdf',
    'Dwinelle_18.bdf',
    'Espy_Sans_16.bdf',
    'Geneva_24.bdf',
    'Helv (2).bdf',
    'MS_Sans_Serif_24.bdf',
    'Modern_12pt_H.bdf',
    'Modern_24pt_C.bdf',
    'New_York_18.bdf',
    'San_Francisco_18.bdf',
    'figlet-banner.bdf',
    'shaston-16.bdf',
    'spleen-32x64.bdf',
    'superpet-ascii.bdf',
    'swiss-36-ega.bdf',
    'swiss-36-vga.bdf'
)

fonts_symbols = (
    'Cairo_18.bdf',
    'Mobile_18.bdf'
)

class DemoFonts(Cube):

    def run(self):
        self.clear()

        fonts_path = f'{os.path.dirname(__file__)}/../../fonts'
        fonts = {}

        # word = 'Bienvenue chez PYXIS'
        # word = 'PYXIS'
        word = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
        i = 0
        k = 0
        while True:
            self.clear()
            self.canvas.Fill(0, 0, 0)
            for face in Face:
                filename = fonts_text[k]
                if filename not in fonts:
                    fonts[filename] = rgb_graphics.Font()
                    fonts[filename].LoadFont(f'{fonts_path}/{filename}')
                c = word[(i+k) % len(word)]
                x = (64 - fonts[filename].CharacterWidth(ord(c))) // 2
                y = (64 - fonts[filename].height) // 2 + fonts[filename].baseline
                self.planes[face.value].text(x, reverse(y), Color.WHITE(), c, fonts[filename])
                k = (k + 1) % len(fonts_text)
            self.refresh()
            i = (i+1) % len(word)
            # time.sleep(0.1)

if __name__ == "__main__":
    s = DemoFonts()
    print("CTRL-C to quit", end="", flush=True)
    try:
        s.setup()
        s.run()
    except KeyboardInterrupt:
        s.clear()


            ffi::SURFACE_TYPE_PDF => SurfaceType::Pdf,
            ffi::SURFACE_TYPE_PS => SurfaceType::Ps,
            ffi::SURFACE_TYPE_XLIB => SurfaceType::Xlib,
            ffi::SURFACE_TYPE_XCB => SurfaceType::Xcb,
            ffi::SURFACE_TYPE_GLITZ => SurfaceType::Glitz,
            ffi::SURFACE_TYPE_QUARTZ => SurfaceType::Quartz,
            ffi::SURFACE_TYPE_WIN32 => SurfaceType::Win32,
            ffi::SURFACE_TYPE_BE_OS => SurfaceType::BeOs,
            ffi::SURFACE_TYPE_DIRECT_FB => SurfaceType::DirectFb,
            ffi::SURFACE_TYPE_SVG => SurfaceType::Svg,
            ffi::SURFACE_TYPE_OS2 => SurfaceType::Os2,
            ffi::SURFACE_TYPE_WIN32_PRINTING => SurfaceType::Win32Printing,
            ffi::SURFACE_TYPE_QUARTZ_IMAGE => SurfaceType::QuartzImage,
            ffi::SURFACE_TYPE_SCRIPT => SurfaceType::Script,
            ffi::SURFACE_TYPE_QT => SurfaceType::Qt,
            ffi::SURFACE_TYPE_RECORDING => SurfaceType::Recording,
            ffi::SURFACE_TYPE_VG => SurfaceType::Vg,
            ffi::SURFACE_TYPE_GL => SurfaceType::Gl,
            ffi::SURFACE_TYPE_DRM => SurfaceType::Drm,
            ffi::SURFACE_TYPE_TEE => SurfaceType::Tee,
            ffi::SURFACE_TYPE_XML => SurfaceType::Xml,
            ffi::SURFACE_TYPE_SKIA => SurfaceType::Skia,
            ffi::SURFACE_TYPE_SUBSURFACE => SurfaceType::Subsurface,
            ffi::SURFACE_TYPE_COGL => SurfaceType::Cogl,
            value => SurfaceType::__Unknown(value),
        }
    }
}

#[cfg(feature = "use_glib")]
gvalue_impl!(SurfaceType, ffi::gobject::cairo_gobject_surface_type_get_type);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SvgUnit {
    User,
    Em,
    Ex,
    Px,
    In,
    Cm,
    Mm,
    Pt,
    Pc,
    Percent,
    #[doc(hidden)]
    __Unknown(i32),
}

#[doc(hidden)]
impl Into<ffi::cairo_svg_unit_t> for SvgUnit {
    fn into(self) -> ffi::cairo_svg_unit_t {
        match self {
            SvgUnit::User => ffi::SVG_UNIT_USER,
            SvgUnit::Em => ffi::SVG_UNIT_EM,
            SvgUnit::Ex => ffi::SVG_UNIT_EX,
            SvgUnit::Px => ffi::SVG_UNIT_PX,
            SvgUnit::In => ffi::SVG_UNIT_IN,
            SvgUnit::Cm => ffi::SVG_UNIT_CM,
            SvgUnit::Mm => ffi::SVG_UNIT_MM,
            SvgUnit::Pt => ffi::SVG_UNIT_PT,
            SvgUnit::Pc => ffi::SVG_UNIT_PC,
            SvgUnit::Percent => ffi::SVG_UNIT_PERCENT,
            SvgUnit::__Unknown(value) => value,
        }
    }
}

#[doc(hidden)]
impl From<ffi::cairo_svg_unit_t> for SvgUnit {
    fn from(value: ffi::cairo_svg_unit_t) -> Self {
        match value {
            ffi::SVG_UNIT_USER => SvgUnit::User,
            ffi::SVG_UNIT_EM => SvgUnit::Em,
            ffi::SVG_UNIT_EX => SvgUnit::Ex,


	return diskInfo, nil
	})
	mockBlobNode.EXPECT().ReleaseChunk(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)

	err := mockVolumeMgr.ReleaseVolumeUnit(ctx, proto.EncodeVuid(vuidPrefix1, 1), 1, false)
	require.NoError(t, err)

	// failed case ,diskid not exist
	mockDiskMgr.EXPECT().GetDiskInfo(gomock.Any(), gomock.Any()).Return(nil, errors.New("err"))
	err = mockVolumeMgr.ReleaseVolumeUnit(ctx, proto.EncodeVuid(vuidPrefix1, 1), 90, false)
	require.Error(t, err)
}

func BenchmarkVolumeMgr_ChunkReport(b *testing.B) {
	mockVolumeMgr, clean := initMockVolumeMgr(b)
	defer clean()

	var args []clustermgr.ChunkInfo
	for i := 0; i < volumeCount; i++ {
		vuid := proto.EncodeVuid(proto.EncodeVuidPrefix(proto.Vid(i), 2), 1)
		chunk := clustermgr.ChunkInfo{
			Vuid:  vuid,
			Total: defaultChunkSize + 1,
			Free:  uint64(1024 * 1024),
			Used:  defaultChunkSize - uint64(1024*i),
		}
		args = append(args, chunk)
	}

	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			err := mockVolumeMgr.applyChunkReport(context.Background(), &clustermgr.ReportChunkArgs{ChunkInfos: args})
			require.NoError(b, err)
		}
	})
}
// Copyright 2024 The CubeFS Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.

package catalog

import (
	"sync"

	"github.com/cubefs/cubefs/blobstore/api/clustermgr"
	"github.com/cubefs/cubefs/blobstore/clustermgr/persistence/catalogdb"
	"github.com/cubefs/cubefs/blobstore/common/proto"
	"github.com/cubefs/cubefs/blobstore/common/sharding"
)

type shardInfoBase struct {
	clustermgr.Shard
}

type shardItem struct {
	shardID    proto.ShardID
	unitEpochs []*shardUnitEpoch
	info       shardInfoBase
	lock       sync.RWMutex
}

func (s *shardItem) withRLocked(f func() error) error {
	s.lock.RLock()
	err := f()
	s.lock.RUnlock()
	return err
}

func (s *shardItem) withLocked(f func() error) error {
	s.lock.Lock()
	err := f()
	s.lock.Unlock()
	return err
}

func (s *shardItem) isValid() bool {
	if s.shardID == proto.InvalidShardID {
		return false
	}
	for _, unit := range s.unitEpochs {
		if !unit.isValid() {
			return false
		}
	}
	return true
}

func


f err != nil {
		t.Fatalf("GenerateFromPassword error: %s", err)
	}

	if CompareHashAndPassword(hp, pass) != nil {
		t.Errorf("%v should hash %s correctly", hp, pass)
	}

	notPass := "notthepass"
	err = CompareHashAndPassword(hp, []byte(notPass))
	if err != ErrMismatchedHashAndPassword {
		t.Errorf("%v and %s should be mismatched", hp, notPass)
	}
}

func TestBcryptingIsCorrect(t *testing.T) {
	pass := []byte("allmine")
	salt := []byte("XajjQvNhvvRt5GSeFk1xFe")
	expectedHash := []byte("$2a$10$XajjQvNhvvRt5GSeFk1xFeyqRrsxkhBkUiQeg0dt.wU1qD4aFDcga")

	hash, err := bcrypt(pass, 10, salt)
	if err != nil {
		t.Fatalf("bcrypt blew up: %v", err)
	}
	if !bytes.HasSuffix(expectedHash, hash) {
		t.Errorf("%v should be the suffix of %v", hash, expectedHash)
	}

	h, err := newFromHash(expectedHash)
	if err != nil {
		t.Errorf("Unable to parse %s: %v", string(expectedHash), err)
	}

	// This is not the safe way to compare these hashes. We do this only for
	// testing clarity. Use bcrypt.CompareHashAndPassword()
	if err == nil && !bytes.Equal(expectedHash, h.Hash()) {
		t.Errorf("Parsed hash %v should equal %v", h.Hash(), expectedHash)
	}
}

func TestVeryShortPasswords(t *testing.T) {
	key := []byte("k")
	salt := []byte("XajjQvNhvvRt5GSeFk1xFe")
	_, err := bcrypt(key, 10, salt)
	if err != nil {
		t.Errorf("One byte key resulted in error: %s", err)
	}
}

func TestTooLongPasswordsWork(t *testing.T) {
	salt := []byte("XajjQvNhvvRt5GSeFk1xFe")
	// One byte over the usual 56 byte limit that blowfish has
	tooLongPass := []byte("012345678901234567890123456789012345678901234567890123456")
	tooLongExpected := []byte("$2a$10$XajjQvNhvvRt5GSeFk1xFe5l47dONXg781AmZtd869sO8zfsHuw7C")
	hash, err := bcrypt(tooLongPass, 10, salt)
	if err != nil {
		t.Fatalf("bcrypt blew up on long password: %v", err)
	}
	if !bytes.HasSuffix(tooLongExpected, hash) {
		t.Errorf("%v should be the suffix of %v", hash, tooLongExpected)
	}
}

type InvalidHashTest struct {
	err  error
	hash []byte
}

var invalidTests = []InvalidHashTest{
	{ErrHashTooShort, []byte("$2a$10$fooo")},
	{ErrHashTooShort, []byte("$2a")},
	{HashVersionTooNewError('3'), []byte("$3a$10$sssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")},
	{InvalidHashPrefixError('%'), []byte("%2a$10$sssssssssssssssssssssshhhhhhhhhhhhhhhhhhhhhhhhhhhhhh


///

{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}

/// tip | Consejo

La sintaxis `{"name", "description"}` crea un `set` con esos dos valores.

Es equivalente a `set(["name", "description"])`.

///

#### Usar `list`s en lugar de `set`s

Si olvidas usar un `set` y usas un `list` o `tuple` en su lugar, FastAPI todavía lo convertirá a un `set` y funcionará correctamente:

{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}

## Resumen

Usa el parámetro `response_model` del *decorador de path operation* para definir modelos de response y especialmente para asegurarte de que los datos privados sean filtrados.

Usa `response_model_exclude_unset` para devolver solo los valores establecidos explícitamente.
# Incluyendo WSGI - Flask, Django, otros

Puedes montar aplicaciones WSGI como viste con [Sub Aplicaciones - Mounts](sub-applications.md){.internal-link target=_blank}, [Detrás de un Proxy](behind-a-proxy.md){.internal-link target=_blank}.

Para eso, puedes usar `WSGIMiddleware` y usarlo para envolver tu aplicación WSGI, por ejemplo, Flask, Django, etc.

## Usando `WSGIMiddleware`

Necesitas importar `WSGIMiddleware`.

Luego envuelve la aplicación WSGI (p. ej., Flask) con el middleware.

Y luego móntala bajo un path.

{* ../../docs_src/wsgi/tutorial001.py hl[2:3,3] *}

## Revisa

Ahora, cada request bajo el path `/v1/` será manejado por la aplicación Flask.

Y el resto será manejado por **FastAPI**.

Si lo ejecutas y vas a http://localhost:8000/v1/ verás el response de Flask:

```txt
Hello, World from Flask!
```

Y si vas a http://localhost:8000/v2 verás el response de FastAPI:

```JSON
{
    "message": "Hello World"
}
```
# Probando Dependencias con Overrides

## Sobrescribir dependencias durante las pruebas

Hay algunos escenarios donde podrías querer sobrescribir una dependencia durante las pruebas.

No quieres que la dependencia original se ejecute (ni ninguna de las sub-dependencias que pueda tener).

En cambio, quieres proporcionar una dependencia diferente que se usará solo durante las pruebas (posiblemente solo algunas pruebas específicas), y que proporcionará un valor que pueda ser usado donde se usó el valor de la dependencia original.

### Casos de uso: servicio externo

Un ejemplo podría ser que tienes un proveedor de autenticación externo al que necesitas llamar.

Le envías un token y te devuelve un usuario autenticado.

Este proveedor podría estar cobrándote por cada request, y llamarlo podría tomar más tiempo adicional que si tuvieras un usuario de prueba fijo para los tests.

Probablemente quieras probar el proveedor externo una vez, pero no necesariamente llamarlo para cada test que se realice.

En este caso, puedes sobrescribir la dependencia que llama a ese proveedor y usar una dependencia personalizada que devuelva un usuario de prueba, solo para tus tests.

### Usa el atributo `app.dependency_overrides`

Para estos casos, tu aplicación **FastAPI**


)]
pub use sc_cli::{Error, Result};
use self::Attribute::*;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Attribute {
    Pinned,
    PinnedBoxed,
    PinnedBoxedSend,
    Unpinned,
    UnpinnedBoxed,
    UnpinnedBoxedSend,
}

impl Attribute {
    pub fn boxed(&self) -> bool {
        match *self {
            PinnedBoxed | PinnedBoxedSend | UnpinnedBoxed | UnpinnedBoxedSend => true,
            Pinned | Unpinned => false,
        }
    }

    pub fn pinned(&self) -> bool {
        match *self {
            Pinned | PinnedBoxed | PinnedBoxedSend => true,
            Unpinned | UnpinnedBoxed | UnpinnedBoxedSend => false,
        }
    }
}
//! Module for dealing with third party identifiers

pub mod bind_callback;
pub mod exchange_invite;
use super::{
    component::Component, component::ComponentText, item::Item, item_section::ItemSection, Bar,
};
use crate::{
    config::Config, display::Display, event::Event, system::DisplayId, system::Rectangle,
    window::Api, window::WindowEvent, AppState, NOG_BAR_NAME,
};
use log::{debug, error, info};
use mlua::Result as RuntimeResult;
use parking_lot::Mutex;
use std::sync::Arc;
use std::time::Duration;

fn draw_component_text(
    api: &Api,
    rect: &Rectangle,
    config: &Config,
    component_text: &ComponentText,
) {
    if component_text.display_text.is_empty() {
        return;
    }

    let fg = Some(component_text.foreground_color)
        .filter(|x| *x > 0)
        .unwrap_or(if config.light_theme {
            0x00333333
        } else {
            0x00ffffff
        });

    let bg = Some(component_text.background_color)
        .filter(|x| *x > 0)
        .unwrap_or(config.bar.color);

    api.set_text_color(fg);
    api.set_background_color(bg);
    api.write_text(
        &component_text.display_text,
        rect.left,
        rect.top,
        true,
        false,
    )
}

fn draw_components(
    api: &Api,
    config: &Config,
    display_id: DisplayId,
    mut offset: i32,
    components: &[Component],
) -> RuntimeResult<()> {
    for component in components {
        let component_texts = component.render(display_id)?;

        for (_i, component_text) in component_texts.iter().enumerate() {
            let width = api
                .calculate_text_rect(&component_text.display_text)
                .width();

            let rect = Rectangle {
                left: offset,
                right: offset + width,
                bottom: config.bar.height,
                top: 0,
            };

            offset = rect.right;

            draw_component_text(api, &rect, config, &component_text);
        }
    }

    Ok(())
}

fn components_to_section(
    api: &Api,
    display_id: DisplayId,
    components: &[Component],
) -> RuntimeResult<ItemSection> {
    let mut section = ItemSection::default();
    let mut component_offset = 0;

    for component in components {
        let mut item = Item::default();
        let mut component_text_offset = 0;
        let mut component_width = 0;

        for component_text in component.render(display_id)? {
            let width = api
                .calculate_text_rect(&component_text.display_text)
                .width();
            let left = component_text_offset;
            let right = component_text_offset + width;

            item.cached_


             "Pass as two space-separated values (e.g., --origin 0.0 0.0).")
    parser.add_argument(
        '--scale_factor', type=float, required=False,
        help="Factor value for the scaling. Default is 1.0."
             " (e.g., --factor 0.01 for 1/100.0).")
    parser.add_argument(
        '--timestep_stride', type=int, required=False,
        help="Timestep stride value. Default is 1.0."
             " (e.g., --timestep_stride 10).")
    args = parser.parse_args()

    n_dims = args.n_dims
    n_material_props = args.n_material_props
    result_dir = args.result_dir
    save_path = args.save_path
    mpm_input_path = args.mpm_input_path
    max_cohesion = args.max_cohesion

    # # Just for debug
    # n_dims = 2
    # n_material_props = 2
    # result_dir = "/work2/08264/baagee/frontera/cbgeopy/examples/sand_layers-2d-random/sim-0/results/sand2d/"
    # mpm_input_path = "/work2/08264/baagee/frontera/cbgeopy/examples/sand_layers-2d-random/sim-0/mpm-resume.json"
    # save_path = "/work2/08264/baagee/frontera/cbgeopy/examples/sand_layers-2d-random/sim-0/trajectory.npz"

    scale = {
        "origin": [0, 0] if args.scale_origin is None else args.scale_origin,
        "factor": [1.0, 1.0] if args.scale_factor is None else args.scale_factor,
        "timestep_stride": int(1) if args.timestep_stride is None else args.timestep_stride
    }

    convert_hd5_to_npz(
        n_dims=n_dims,
        n_material_props=n_material_props,
        max_cohesion=max_cohesion,
        result_dir=result_dir,
        mpm_input_path=mpm_input_path,
        save_path=save_path,
        scale=scale,
        use_material_feature=True)


�과 십자군 휘장을 각각 110개씩 내면 은빛 여명회의 보물 창고에서 꺼내온 물건을 하나 선택할 수 있습니다."}},
[9223] = {"희귀한 전투 장비: 여명회에 우호적", nil, {"여명회 휘장과 십자군 휘장을 각각 20개씩 내면 은빛 여명회의 보물 창고에서 꺼내온 물건을 하나 선택할 수 있습니다."}},
[9224] = {"영웅을 위한 전투 장비: 여명회에 우호적", nil, {"여명회 휘장과 십자군 휘장을 각각 75개씩 내면 은빛 여명회의 보물 창고에서 꺼내온 물건을 하나 선택할 수 있습니다."}},
[9225] = {"영웅을 위한 전투 장비: 여명회에 매우 우호적", nil, {"여명회 휘장과 십자군 휘장을 각각 45개씩 내면 은빛 여명회의 보물 창고에서 꺼내온 물건을 하나 선택할 수 있습니다."}},
[9226] = {"희귀한 전투 장비: 여명회에 매우 우호적", nil, {"여명회 휘장과 십자군 휘장을 각각 7개씩 내면 은빛 여명회의 보물 창고에서 꺼내온 물건을 하나 선택할 수 있습니다."}},
[9227] = {"희귀한 전투 장비: 여명회의 확고한 동맹", nil, {"여명회 휘장과 십자군 휘장을 각각 6개씩 내면 은빛 여명회의 보물 창고에서 꺼내온 물건을 하나 선택할 수 있습니다."}},
[9228] = {"영웅을 위한 전투 장비: 여명회의 확고한 동맹", nil, {"여명회 휘장과 십자군 휘장을 각각 27개씩 내면 은빛 여명회의 보물 창고에서 꺼내온 물건을 하나 선택할 수 있습니다."}},
[9


29, 39.914708],
    'pop': 18991,
    'state': 'NJ'
  },
  {
    '_id': '08722',
    'city': 'BEACHWOOD',
    'loc': [-74.196145, 39.930246],
    'pop': 9324,
    'state': 'NJ'
  },
  {
    '_id': '08723',
    'city': 'OSBORNSVILLE',
    'loc': [-74.12685999999999, 40.040817],
    'pop': 28128,
    'state': 'NJ'
  },
  {
    '_id': '08724',
    'city': 'BRICK',
    'loc': [-74.11523699999999, 40.087432],
    'pop': 34507,
    'state': 'NJ'
  },
  {
    '_id': '08730',
    'city': 'BRIELLE',
    'loc': [-74.06351100000001, 40.107727],
    'pop': 4290,
    'state': 'NJ'
  },
  {
    '_id': '08731',
    'city': 'FORKED RIVER',
    'loc': [-74.197301, 39.844425],
    'pop': 16664,
    'state': 'NJ'
  },
  {
    '_id': '08732',
    'city': 'ISLAND HEIGHTS',
    'loc': [-74.146787, 39.943197],
    'pop': 1470,
    'state': 'NJ'
  },
  {
    '_id': '08733',
    'city': 'LAKEHURST NAEC',
    'loc': [-74.29090100000001, 40.020054],
    'pop': 14205,
    'state': 'NJ'
  },
  {
    '_id': '08734',
    'city': 'LANOKA HARBOR',
    'loc': [-74.166765, 39.861993],
    'pop': 5473,
    'state': 'NJ'
  },
  {
    '_id': '08735',
    'city': 'LAVALLETTE',
    'loc': [-74.070424, 39.977486],
    'pop': 3985,
    'state': 'NJ'
  },
  {
    '_id': '08736',
    'city': 'MANASQUAN',
    'loc': [-74.061055, 40.121693],
    'pop': 10341,
    'state': 'NJ'
  },
  {
    '_id': '08738',
    'city': 'MANTOLOKING',
    'loc': [-74.05618800000001, 40.026125],
    'pop': 1186,
    'state': 'NJ'
  },
  {
    '_id': '08740',
    'city': 'OCEAN GATE',
    'loc': [-74.13512799999999, 39.925975],
    'pop': 2028,
    'state': 'NJ'
  },
  {
    '_id': '08741',
    'city': 'PINE BEACH',
    'loc': [-74.167992, 39.934746],
    'pop': 2354,
    'state': 'NJ'
  },
  {
    '_id': '08742',
    'city': 'BAY HEAD',
    'loc': [-74.065719, 40.080226],
    'pop': 25071,
    'state': 'NJ'
  },
  {
    '_id': '08750',
    'city': 'SEA GIRT',
    'loc': [-74.043604, 40.134522],
    'pop': 3624,
    'state': 'NJ'
  },
  {
    '_id': '08751',
    'city': 'SEASIDE HEIGHTS',
    'loc': [-


/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2014 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#pragma once

#include "../../interactionbase_api.h"

#include "ExpressionTreeBuildInstruction.h"

namespace Interaction {

class OperatorDescriptor;

class INTERACTIONBASE_API AddOperator : public ExpressionTreeBuildInstruction
{
	public:
		AddOperator(OperatorDescriptor* descriptor);
		virtual void perform(ExpressionTreeBuilder& tb);

	private:
		OperatorDescriptor* descriptor_;
};

}


: 4),
                  Text(formatter.format(product.price), style: theme.textTheme.bodySmall),
                ],
              ),
            ),
          ],
        ),
        const Padding(padding: EdgeInsets.all(16), child: Icon(Icons.add_shopping_cart)),
      ],
    ),
  );
}
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

class Email {
  Email({
    required this.id,
    required this.avatar,
    this.sender = '',
    this.time = '',
    this.subject = '',
    this.message = '',
    this.recipients = '',
    this.containsPictures = false,
  });

  final int id;
  final String sender;
  final String time;
  final String subject;
  final String message;
  final String avatar;
  final String recipients;
  final bool containsPictures;
}

class InboxEmail extends Email {
  InboxEmail({
    required super.id,
    required super.sender,
    super.time,
    super.subject,
    super.message,
    required super.avatar,
    super.recipients,
    super.containsPictures,
    this.inboxType = InboxType.normal,
  });

  InboxType inboxType;
}

// The different mailbox pages that the Reply app contains.
enum MailboxPageType { inbox, starred, sent, trash, spam, drafts }

// Different types of mail that can be sent to the inbox.
enum InboxType { normal, spam }
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/widgets.dart';

import 'email_model.dart';

const String _avatarsLocation = 'reply/avatars';

class EmailStore with ChangeNotifier {
  static final List<Email> _inbox = <Email>[
    InboxEmail(
      id: 1,
      sender: 'Google Express',
      time: '15 minutes ago',
      subject: 'Package shipped!',
      message:
          'Cucumber Mask Facial has shipped.\n\n'
          "Keep an eye out for a package to arrive between this Thursday and next Tuesday. If for any reason you don't receive your package before the end of next week, please reach out to us for details on your shipment.\n\n"
          'As always, thank you for shopping with us and we hope you love our specially formulated Cucumber Mask!',
      avatar: '$_avatarsLocation/avatar_express.png',
      recipients: 'Jeff',
    ),
    InboxEmail(
      id: 2,
      sender: 'Ali Connors',
      time: '4 hrs ago',
      subject: 'Brunch this weekend?',
      message:
          "I'll be in your neighborhood doing errands and was hoping to catch you for a coffee this Saturday. If you don't have anything scheduled, it would be great to see you! It feels like its been forever.\n\n"
          'If we do get a chance to get together, remind me to tell you about Kim. She stopped over at the house to say hey to the kids and told me all about her trip to Mexico.\n\n'
          'Talk to you soon,\n\n'
          'Ali',
      avatar: '$_avatarsLocation/avatar_5.jpg',
      recipients: 'Jeff',
    ),
    InboxEmail(
      id: 3,
      sender: 'Allison Trabucco',
      time: '5 hrs ago',
      subject: 'Bonjour from Paris',
      message: 'Here are some great shots from my trip...',
      avatar: '$_avatarsLocation/avatar_3.jpg',
      recipients: 'Jeff',
      containsPictures: true,
    ),
    InboxEmail(
      id: 4,
      sender: 'Trevor Hansen',
      time: '9 hrs ago',
      subject: 'Brazil trip',
      message:
          'Thought we might be able to go over some details about our upcoming vacati


entedError:
                return

    def syncmessagesto_labels(self, dstfolder, statusfolder):
        """Pass 4: Label Synchronization (Gmail only)

        Compare label mismatches in self with those in statusfolder. If
        msg has a valid UID and exists on dstfolder (has not e.g. been
        deleted there), sync the labels change to both dstfolder and
        statusfolder.

        This function checks and protects us from action in dryrun mode.
        """
        # This applies the labels message by message, as this makes more sense for a
        # Maildir target. If applied with an other Gmail IMAP target it would not be
        # the fastest thing in the world though...
        uidlist = []

        # filter the uids (fast)
        try:
            for uid in self.getmessageuidlist():
                # bail out on CTRL-C or SIGTERM
                if offlineimap.accounts.Account.abort_NOW_signal.is_set():
                    break

                # Ignore messages with negative UIDs missed by pass 1 and
                # don't do anything if the message has been deleted remotely
                if uid < 0 or not dstfolder.uidexists(uid):
                    continue

                selflabels = self.getmessagelabels(uid) - self.ignorelabels

                if statusfolder.uidexists(uid):
                    statuslabels = statusfolder.getmessagelabels(uid) - self.ignorelabels
                else:
                    statuslabels = set()

                if selflabels != statuslabels:
                    uidlist.append(uid)

            # now sync labels (slow)
            mtimes = {}
            labels = {}
            for i, uid in enumerate(uidlist):
                # bail out on CTRL-C or SIGTERM
                if offlineimap.accounts.Account.abort_NOW_signal.is_set():
                    break

                selflabels = self.getmessagelabels(uid) - self.ignorelabels

                if statusfolder.uidexists(uid):
                    statuslabels = statusfolder.getmessagelabels(uid) - self.ignorelabels
                else:
                    statuslabels = set()

                if selflabels != statuslabels:
                    self.ui.settinglabels(uid, i + 1, len(uidlist), sorted(selflabels), dstfolder)
                    if self.repository.account.dryrun:
                        continue  # don't actually add in a dryrun
                    dstfolder.savemessagelabels(uid, selflabels, ignorelabels=self.ignorelabels)
                    mtime = dstfolder.getmessagemtime(uid)
                    mtimes[uid] = mtime
                    labels[uid] = selflabels

            # Update statusfolder in a single DB transaction. It is safe, as if something fails,
            # statusfolder will be updated on the next run.
            statusfolder.savemessageslabelsbulk(labels)
            statusfolder.savemessagesmtimebulk(mtimes)

        except NotImplementedError:
            self.ui.warn("Can't sync labels. You need to configure a local repository of type GmailMaildir")


                     str = false;
                    }
                }

                switch (ch)
                {
                    case '{':
                    case '[':
                        output.Append(ch);
                        output.AppendLine();
                        AppendIndent(output, ++depth);
                        break;
                    case '}':
                    case ']':
                        output.AppendLine();
                        AppendIndent(output, --depth);
                        output.Append(ch);
                        break;
                    case ',':
                        output.Append(ch);
                        output.AppendLine();
                        AppendIndent(output, depth);
                        break;
                    case ':':
                        output.Append(" : ");
                        break;
                    default:
                        if (!char.IsWhiteSpace(ch))
                            output.Append(ch);
                        break;
                }

            }

            return output.ToString();
        }
    }
}


cionais [aquí](https://github.com/CollaboraOnline/richdocumentscode#richdocumentscode)\n\n*A descarga é bastante grande polo que é posíbel que experimente un tempo de espera ao usar a interface web*. Pode usar a ferramenta de liña de ordes OCC para instalar o servidor incorporado:\n\n```\nsudo -u wwwrun php -d memory_limit=512M ./occ app:install richdocumentscode\n```\nOnde «wwwrun» é o usuario do seu servidor web. Trátase de «www-data» en Debian, Ubuntu e derivados, «wwwrun» en distribucións baseadas en SUSE, «apache» en Red Hat / Fedora e «http» en Arch linux e derivados.\n\nAs actualizacións pódense facer así:\n```\nsudo -u wwwrun php -d memory_limit=512M ./occ app:update --all\n```\n\nPor suposto, tamén pode aumentar o uso de memoria e os tempos de espera PHP predeterminados, consulte a [documentación de Nextcloud.](https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/big_file_upload_configuration.html?highlight=php%20timeout#configuring-your-web-server)\nAtopará máis consellos para a resolución de problemas [aquí](https://github.com/CollaboraOnline/richdocumentscode?tab=readme-ov-file#troubleshooting).",
    "Your system is ARM64, but you have installed the x86_64 version of the app. Please remove this and" : "O seu sistema é ARM64, pero instalou a versión x86_64 da aplicación. retire isto e",
    "install the correct version from the Nextcloud App Store." : "instale a versión correcta desde a tenda de aplicacións de Nextcloud.",
    "Your system is x86_64, but you have installed the ARM64 version of the app. Please remove this and" : "O seu sistema é x86_64, pero instalou a versión ARM64 da aplicación. Retire isto isto e",
    "You have the Collabora Online app enabled. For further information and configuration, please check:" : "Ten a aplicación Collabora Online activada. Para obter máis información e configuración, consulte:",
    "Administration settings > Nextcloud Office" : "Axustes de administración > Nextcloud Office",
    "The Built-in CODE Server is designed to work with the Nextcloud Office app." : "O servidor CODE integrado está deseñado para funcionar coa aplicación Nextcloud Office.",
    "Install it from the Nextcloud App Store." : "Instalalo desde a tenda de aplicacións de Nextcloud.",
    "An error occurred while trying to check your Collabora Online app installation. You may report this error\n                with the tag: richdocuments-EnabledCheckFailed" : "Produciuse un erro ao tentar comprobar a instalación da aplicación Collabora Online. Pode informar deste erro\n                coa etiqueta: richdocuments-EnabledCheckFailed"
},
"nplurals=2; plural=(n != 1);");
OC.L10N.register(
    "richdocumentscode",
    {
    "Built-in CODE Server" : "O'rnatilgan CODE serveri",
    "Collabora Online - Built-in CODE Server" : "Collabora Online - o'rnatilgan CODE serveri",
    "Built-in Collabora Online Development Edition (CODE) server for local testing and non-production use" : "Mahalliy sinov va ishlab chiqarishdan tashqari foydalanish uchun o'rnatilgan Collabora Online Development Edition (CODE) serveri",
    "**This app has to be installed and used together with the [Nextcloud Office](https://apps.nextcloud.com/apps/richdocuments) integration app.**\n\nCollabora Online is a powerful LibreOffice-based online office suite with collaborative editing, which supports all major documents, spreadsheet and presentation file formats and works together with all modern browsers.\n\n


using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Xml.Linq;
using Autodesk.Revit.DB;
using Common_glTF_Exporter.Core;

namespace Common_glTF_Exporter.Materials
{
    public static class MaterialProperties
    {
        private const string BLEND = "BLEND";
        private const string OPAQUE = "OPAQUE";
        public static void SetProperties(MaterialNode node, float opacity, ref GLTFPBR pbr, ref GLTFMaterial gl_mat)
        {
            pbr.metallicFactor = 0f;
            pbr.roughnessFactor = opacity != 1 ? 0.5f : 1f;
            gl_mat.pbrMetallicRoughness = pbr;

            gl_mat.alphaMode = opacity != 1 ? BLEND : OPAQUE;
            gl_mat.alphaCutoff = null;
        }

        public static void SetMaterialColour(MaterialNode node,
            float opacity, ref GLTFPBR pbr, ref GLTFMaterial gl_mat)
        {
            if (gl_mat.EmbeddedTexturePath == null)
            {
                (float, float, float) baseColours;

                if (gl_mat.BaseColor == null)
                {
                    baseColours = RgbToUnit(node.Color);
                }
                else
                {
                    baseColours = RgbToUnit(gl_mat.BaseColor);
                }

                if (gl_mat.TintColour == null)
                {
                    pbr.baseColorFactor = GetLinearColour(baseColours, opacity);
                }
                else
                {
                    (float, float, float) baseTintColour = RgbToUnit(gl_mat.TintColour);
                    (float, float, float) blendColour = BlendColour(baseColours, baseTintColour);


#include <common.h>
#include <sys_partition.h>
#include <fdt_support.h>
#include <sunxi_board.h>
#include <asm/io.h>
#include <smc.h>

int get_serial_num_from_file(char* serial)
{
	int nodeoffset;
	int ret = 0;
	int partno = -1;
	char *filename = NULL;
	char part_info[16] = {0};  // format is "partno:0"
	char addr_info[32] = {0};  //"00000000"
	char file_info[64] = {0};
	char * bmp_argv[6] = { "fatload", "sunxi_flash", part_info, addr_info, file_info, NULL };

	//check serial_feature config info
	nodeoffset = fdt_path_offset (working_fdt, "/soc/serial_feature");
	if (nodeoffset < 0)
	{
		printf("sunxi_serial: serial_feature is not exist\n");
		return -1;
	}
	ret = fdt_getprop_string(working_fdt,nodeoffset,"sn_filename",&filename);
	if((ret < 0) || (strlen(filename)== 0) )
	{
		printf("sunxi_serial: sn_filename is not exist\n");
		return -1;
	}
	//check private partition info
	partno = sunxi_partition_get_partno_byname("private");
	if(partno < 0)
	{
		return -1;
	}

	//get data from file
	sprintf(part_info,"%d:0", partno);
	sprintf(addr_info,"%lx", (ulong)serial);
	sprintf(file_info,"%s", filename);
	if(do_fat_fsload(0, 0, 5, bmp_argv))
	{
		printf("load file(%s) error \n", bmp_argv[4]);
		return -1;
	}
	return 0;
}

int get_serial_num_from_chipid(char* serial)
{
	u32 sunxi_soc_chipid[4];
	u32 sunxi_serial[3];

	sunxi_soc_chipid[0] = arm_svc_read_sec_reg(SUNXI_SID_BASE + 0x200);
	sunxi_soc_chipid[1] = arm_svc_read_sec_reg(SUNXI_SID_BASE + 0x200 + 0x4);
	sunxi_soc_chipid[2] = arm_svc_read_sec_reg(SUNXI_SID_BASE + 0x200 + 0x8);
	sunxi_soc_chipid[3] = arm_svc_read_sec_reg(SUNXI_SID_BASE + 0x200 + 0xc);

	sunxi_serial[0] = sunxi_soc_chipid[3];
	sunxi_serial[1] = sunxi_soc_chipid[2];
	sunxi_serial[2] = (sunxi_soc_chipid[1] >> 16) & 0xFFFF;

	sprintf(serial , "%04x%08x%08x",sunxi_serial[2], sunxi_serial[1], sunxi_serial[0]);
	return 0;
}

int sunxi_set_serial_num(void)
{
	char serial[128] = {0};
	if(get_serial_num_from_file(serial))
	{
		get_serial_num_from_chipid(serial);
	}
	printf("serial is: %s\n",serial);
	if(setenv("sunxi_serial", serial))
	{
		printf("error:set variable [sunxi_serial] fail\n");
	}
	return 0;
}


ces = GlobalEvent("demon oak voices")
function demonOakVoices.onThink(interval, lastExecution)
	local spectators, spectator = Game.getSpectators(DEMON_OAK_POSITION, false, true, 0, 15, 0, 15)
	local sound = sounds[math.random(#sounds)]
	for i = 1, #spectators do
		spectator = spectators[i]
		if spectator:getPosition():isInRange(questArea[1], questArea[2]) then
			return true
		end
		spectator:say(sound, TALKTYPE_MONSTER_YELL, false, 0, DEMON_OAK_POSITION)
	end
	return true
end

demonOakVoices:interval(15000)
demonOakVoices:register()


//
//  GHTestUtils.h
//  GHUnitIOS
//
//  Created by John Boiles on 10/22/12.
//  Copyright 2012. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person
//  obtaining a copy of this software and associated documentation
//  files (the "Software"), to deal in the Software without
//  restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following
//  conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//  OTHER DEALINGS IN THE SOFTWARE.
//

#import <Foundation/Foundation.h>

#define GHRunWhile(__CONDITION__) GHRunUntilTimeoutWhileBlock(10.0, ^BOOL{ return (__CONDITION__); })

/*!
 Run the main run loop for a period of time. This is useful to give views time to
 render any asynchronously rendered views. However when possible, GHRunUntilTimeoutWhileBlock
 should be used instead since it will provide more determinate output.

 @param interval Interval for the main loop to run
 */
void GHRunForInterval(CFTimeInterval interval);

/*!
 Keep running the main runloop until whileBlock returns NO or timeout is reached.
 This is useful for waiting until certain parts of views render. This method should be
 used instead of putting GHRunForInterval in a while loop.

 @param timeout Maximum time to run the main loop before giving up
 @param whileBlock Block that returns YES if the main runloop should keep running
 */
void GHRunUntilTimeoutWhileBlock(CFTimeInterval timeout, BOOL(^whileBlock)());


otherAuthorzVideosController;
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SectionHeader(icon: Icons.person, title: t.videoDetail.authorOtherVideos), // 使用共享的SectionHeader
          if (otherVideosController == null)
            const SizedBox.shrink()
          else if (otherVideosController.isLoading.value)
            const MediaTileListSkeletonWidget()
          else if (otherVideosController.videos.isEmpty)
            _buildEmptyState(t.videoDetail.authorNoOtherVideos)
          else
            ListView.separated(
              itemCount: otherVideosController.videos.length,
              shrinkWrap: true,
              padding: EdgeInsets.zero,
              physics: const NeverScrollableScrollPhysics(),
              separatorBuilder: (_, ___) => const SizedBox(height: UIConstants.listSpacing),
              itemBuilder: (_, index) => VideoTileListItem(video: otherVideosController.videos[index]),
            ),
        ],
      );
    });
  }

  Widget _buildRelatedVideos(slang.Translations t) {
    return Obx(() {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SectionHeader( // 使用共享的SectionHeader
            icon: Icons.recommend,
            title: t.videoDetail.relatedVideos,
            action: IconButton(
              onPressed: relatedVideoController.fetchRelatedMedias,
              icon: const Icon(Icons.refresh),
              tooltip: t.common.refresh,
            ),
          ),
          if (relatedVideoController.isLoading.value)
            const MediaTileListSkeletonWidget()
          else if (relatedVideoController.videos.isEmpty)
            _buildEmptyState(t.videoDetail.noRelatedVideos)
          else
            ListView.separated(
              itemCount: relatedVideoController.videos.length,
              shrinkWrap: true,
              padding: EdgeInsets.zero,
              physics: const NeverScrollableScrollPhysics(),
              separatorBuilder: (_, ___) => const SizedBox(height: UIConstants.listSpacing),
              itemBuilder: (_, index) => VideoTileListItem(video: relatedVideoController.videos[index]),
            )
        ],
      );
    });
  }

  Widget _buildEmptyState(String message) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(vertical: 32),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.video_library_outlined, size: 48, color: Colors.grey[400]),
          const SizedBox(height: 16),
          Text(message, style: TextStyle(fontSize: 16, color: Colors.grey[600])),
        ],
      ),
    );
  }
}
import 'package:flutter/material.dart';

/// Centralized constants for consistent UI styling across tabs.
class UIConstants {
  // 基础间距
  static const double pagePadding = 12.0;          // 页面内边距
  static const double sectionSpacing = 12.0;       // 区域间间距
  static const double interElementSpacing = 10.0;  // 元素间间距
  static const double listSpacing = 8.0;           // 列表项间距

  // 派生间距
  static const double cardPadding = pagePadding;                   // 卡片内边距
  static const double smallSpacing = 4.0;                          // 小间距
  static const double tinySpacing = 2.0;                           // 微小间距
  static const double iconTextSpacing = 6.0;                       // 图标与文字间距
  static const double buttonInternalPadding = 8.0;                 // 按钮内部间距
  static const double


  'bloc_pattern',
  'bokain_models',
  'built_collection',
  'built_redux',
  'built_redux_thunk',
  'built_value',
  'built_value_generator',
  'built_value_test',
  'built_viewmodel',
  'built_viewmodel_flutter_built_redux',
  'built_viewmodel_flutter_redux',
  'built_viewmodel_generator',
  'carp_context_package',
  'codemetrics',
  'fluttercontactpicker',
  'interactive_webview',
  'meta_types',
  'meta_types_generator',
  'meta_types_json',
  'meta_types_json_generator',
  'meta_types_redux',
  'meta_types_redux_generator',
  'mocktail',
  'mocktail_image_network',
  'polymer_interop',
};

/// The strict version parsing fix will be part of this SDK release.
final _maxSdkVersion = Version(2, 17, 0);
final _defaultSdkVersionRange = VersionRange(
  min: Version(2, 12, 0),
  includeMin: true,
  max: _maxSdkVersion,
  includeMax: false,
);

/// Override pubspec.yaml if needed:
///
/// - If the archive was created before 2022-01-01, we may need to update the
///   version number, version constraint and SDK constraints, as `pub_semver`
///   accepted separator characters other than `.`.
///   https://github.com/dart-lang/pub_semver/pull/63
String overridePubspecYamlIfNeeded({
  required String pubspecYaml,
  required DateTime published,
}) {
  // quick checks to skip overrides
  if (published.year >= 2022) {
    return pubspecYaml;
  }

  try {
    return _fixupBrokenVersionAndConstraints(pubspecYaml);
  } on FormatException catch (e, st) {
    _logger.info('Unable to parse pubspec.', e, st);
  }
  // fallback: don't override
  return pubspecYaml;
}

/// Fixes broken version and version constraints in [pubspecYaml] and returns a new YAML string.
///
/// Prior to [pub_semver#63] version numbers and version constraints were accepted with any
/// character as separator, instead of requiring  `.` (dot). This occurred because the regular expression
/// in `package:pub_semver` didn't escape dots as `\.`, but just contained `.` (dot, meaning any character). (see https://github.com/dart-lang/pub_semver/commit/cee044a3dc8)
///
/// Thus, package versions published prior to 2022-01-01, may contain _version numbers_,
/// _version constraints_ and _SDK constraints_ that don't use `.` (dot) as separator. As removing
/// these _package versions_ would break existing users, this function will rewrite the version numbers
/// and version constraints to have a valid format equivalent to how older versions of `pub_semver`
/// would have interpreted the version number / version constraints.
///
/// [pub_semver#63]: https://github.com/dart-lang/pub_semver/pull/63
String _fixupBrokenVersionAndConstraints(String pubspecYaml) {
  final root = yaml.loadYaml(pubspecYaml);
  if (root is! Map) {
    _logger.warning(
      'Unable to parse YAML for package, in _fixupBrokenVersionAndConstraints!',
    );
    return pubspecYaml; // return original as no changes can be made
  }

  // sanity check on the name again, now with parsed yaml
  final name = root['name'];
  if (name is! String || !_packagesWithBadVersions.contains(name)) {
    return pubspecYaml; // return original


findColorEquals
declare const findImage: typeof images.findImage
declare const findImageInRegion: typeof images.findImageInRegion
/*
 * @Author: bowentang
 * @Date: 2021-08-27 15:25:32
 * @LastEditTime: 2021-08-27 20:37:56
 * @FilePath: /draw/src/ts/EventTarget.ts
 * @Description:
 */
//制作事件驱动源
class EventTarget{
  //事件对象
  handlers: any;
  /**
   * 构造
   */
  constructor(){
    this.handlers={}
  }
  /**
   * 注册事件
   * @param type
   * @param handler
   */
  handler(type:string, handler:Function) {
    //添加事件对象
    if (typeof this.handlers[type] == 'undefined') {
      this.handlers[type] = new Array();
    }
    this.handlers[type] = this.handlers[type].concat(handler);
  }
  /**
   * 移除事件
   * @param type
   * @param handler
   */
  removeHandler(type:string, handler:Function) {
    if (typeof this.handlers == "undefined") { this.handlers = {} }
    if (this.handlers[type] instanceof Array) {
      var handlers = this.handlers[type];
      for (var i = 0, len = handlers.length; i < len; i++) {
        if (handler[i] == handler) {
          handlers.splice(i, 1);
          break;
        }
      }
    }
  }
  /**
   * 触发事件
   * @param type
   */
  trigger(type:string,data1?:any,data2?:any) {
    if (typeof this.handlers == "undefined") { this.handlers = {} }
    if (this.handlers[type] instanceof Array) {
      var handlers = this.handlers[type];
      for (var i = 0, len = handlers.length; i < len; i++) {
        handlers[i].call(this,data1,data2);
      }
    }
  }
}
export default EventTarget;
import Sticker from './Sticker';

/**
 * This object represents a sticker set.
 */
export default interface StickerSet {
    /**
     * Sticker set name
     */
    name: string;

    /**
     * Sticker set title
     */
    title: string;

    /**
     * true, if the sticker set contains masks
     */
    contains_masks: boolean;

    /**
     * List of all set stickers
     */
    stickers: Sticker[];
}
import {fromJS} from "immutable";
import * as constants from "./constants";
import {ModifyAction} from "./actionCreators";

const defaultState = fromJS({
    list:[]
});

const reduce = (state = defaultState, action:ModifyAction)=>{
    switch (action.type) {
        case constants.CHANGE_ALBUM:
            return state.set('list', fromJS(action.data));
        default :
            return state;
    }
}

export default reduce
import { Command, flags } from '@oclif/command'
import {
  Applicant,
  Applicants,
  getConnpassApplicants,
} from '@suin/get-connpass-applicants'
import csv from 'fast-csv'

class GetConnpassApplicants extends Command {
  static description =
    'A simple CLI command that gets the applicants from a given Connpass event URL.'

  static example = [
    'Basic usage:',
    '$ connpass-applicants https://connpass.com/event/144296/',
    '',
    'Output as CSV format:',
    '$ connpass-applicants https://connpass.com/event/144296/ --format=json --pretty',
    '',
    'Print only accepted applicants as CSV (working with q command):',
    `$ connpass-applicants https://connpass.com/event/144296/ --format=csv | q \\
  --skip-header \\
  --delimiter=',' \\
  'SELECT displayName, participationType FROM -


 post );
			Reveal.addEventListener( 'overviewhidden', post );
			Reveal.addEventListener( 'overviewshown', post );
			Reveal.addEventListener( 'paused', post );
			Reveal.addEventListener( 'resumed', post );

			// Post the initial state
			post();

		}

		connect();

	}

	if( !/receiver/i.test( window.location.search ) ) {

		// If the there's a 'notes' query set, open directly
		if( window.location.search.match( /(\?|\&)notes/gi ) !== null ) {
			openNotes();
		}

		// Open the notes when the 's' key is hit
		document.addEventListener( 'keydown', function( event ) {
			// Disregard the event if the target is editable or a
			// modifier is present
			if ( document.querySelector( ':focus' ) !== null || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ) return;

			// Disregard the event if keyboard is disabled
			if ( Reveal.getConfig().keyboard === false ) return;

			if( event.keyCode === 83 ) {
				event.preventDefault();
				openNotes();
			}
		}, false );

		// Show our keyboard shortcut in the reveal.js help overlay
		if( window.Reveal ) Reveal.registerKeyboardShortcut( 'S', 'Speaker notes view' );

	}

	return { open: openNotes };

})();
/*!
  * Bowser - a browser detector
  * https://github.com/ded/bowser
  * MIT License | (c) Dustin Diaz 2014
  */
!function(e,t){typeof module!="undefined"&&module.exports?module.exports.browser=t():typeof define=="function"&&define.amd?define(t):this[e]=t()}("bowser",function(){function t(t){function n(e){var n=t.match(e);return n&&n.length>1&&n[1]||""}function r(e){var n=t.match(e);return n&&n.length>1&&n[2]||""}var i=n(/(ipod|iphone|ipad)/i).toLowerCase(),s=/like android/i.test(t),o=!s&&/android/i.test(t),u=n(/edge\/(\d+(\.\d+)?)/i),a=n(/version\/(\d+(\.\d+)?)/i),f=/tablet/i.test(t),l=!f&&/[^-]mobi/i.test(t),c;/opera|opr/i.test(t)?c={name:"Opera",opera:e,version:a||n(/(?:opera|opr)[\s\/](\d+(\.\d+)?)/i)}:/yabrowser/i.test(t)?c={name:"Yandex Browser",yandexbrowser:e,version:a||n(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i)}:/windows phone/i.test(t)?(c={name:"Windows Phone",windowsphone:e},u?(c.msedge=e,c.version=u):(c.msie=e,c.version=n(/iemobile\/(\d+(\.\d+)?)/i))):/msie|trident/i.test(t)?c={name:"Internet Explorer",msie:e,version:n(/(?:msie |rv:)(\d+(\.\


"cluster.post_voting_config_exclusions")]
	public partial interface IPostVotingConfigExclusionsRequest { }

	public partial class PostVotingConfigExclusionsRequest
	{
		protected sealed override void RequestDefaults(PostVotingConfigExclusionsRequestParameters parameters) =>
			parameters.CustomResponseBuilder = new PostVotingConfigExclusionsResponseBuilder();
	}

	public partial class PostVotingConfigExclusionsDescriptor
	{
		protected sealed override void RequestDefaults(PostVotingConfigExclusionsRequestParameters parameters) =>
			parameters.CustomResponseBuilder = new PostVotingConfigExclusionsResponseBuilder();
	}

	/// <summary>
	/// Response is a single newline character, so skip trying to deserialize to an object
	/// </summary>
	internal class PostVotingConfigExclusionsResponseBuilder : CustomResponseBuilderBase
	{
		public override object DeserializeResponse(IOpenSearchSerializer builtInSerializer, IApiCallDetails response, Stream stream) =>
			new PostVotingConfigExclusionsResponse();

		public override Task<object> DeserializeResponseAsync(IOpenSearchSerializer builtInSerializer, IApiCallDetails response, Stream stream, CancellationToken ctx = default) =>
			Task.FromResult<object>(new PostVotingConfigExclusionsResponse());
	}
}


, *model.AppError)); ok {
		return rf(channel)
	}
	if rf, ok := ret.Get(0).(func(*model.Channel) *model.Channel); ok {
		r0 = rf(channel)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.Channel)
		}
	}

	if rf, ok := ret.Get(1).(func(*model.Channel) *model.AppError); ok {
		r1 = rf(channel)
	} else {
		if ret.Get(1) != nil {
			r1 = ret.Get(1).(*model.AppError)
		}
	}

	return r0, r1
}

// MockAPI_CreateChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateChannel'
type MockAPI_CreateChannel_Call struct {
	*mock.Call
}

// CreateChannel is a helper method to define mock.On call
//   - channel *model.Channel
func (_e *MockAPI_Expecter) CreateChannel(channel interface{}) *MockAPI_CreateChannel_Call {
	return &MockAPI_CreateChannel_Call{Call: _e.mock.On("CreateChannel", channel)}
}

func (_c *MockAPI_CreateChannel_Call) Run(run func(channel *model.Channel)) *MockAPI_CreateChannel_Call {
	_c.Call.Run(func(args mock.Arguments) {
		run(args[0].(*model.Channel))
	})
	return _c
}

func (_c *MockAPI_CreateChannel_Call) Return(_a0 *model.Channel, _a1 *model.AppError) *MockAPI_CreateChannel_Call {
	_c.Call.Return(_a0, _a1)
	return _c
}

func (_c *MockAPI_CreateChannel_Call) RunAndReturn(run func(*model.Channel) (*model.Channel, *model.AppError)) *MockAPI_CreateChannel_Call {
	_c.Call.Return(run)
	return _c
}

// CreateChannelSidebarCategory provides a mock function with given fields: userID, teamID, newCategory
func (_m *MockAPI) CreateChannelSidebarCategory(userID string, teamID string, newCategory *model.SidebarCategoryWithChannels) (*model.SidebarCategoryWithChannels, *model.AppError) {
	ret := _m.Called(userID, teamID, newCategory)

	if len(ret) == 0 {
		panic("no return value specified for CreateChannelSidebarCategory")
	}

	var r0 *model.SidebarCategoryWithChannels
	var r1 *model.AppError
	if rf, ok := ret.Get(0).(func(string, string, *model.SidebarCategoryWithChannels) (*model.SidebarCategoryWithChannels, *model.AppError)); ok {
		return rf(userID, teamID, newCategory)
	}
	if rf, ok := ret.Get(0).(func(string, string, *model.SidebarCategoryWithChannels) *model.SidebarCategoryWithChannels); ok {
		r0 = rf(userID, teamID, newCategory)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.SidebarCategoryWithChannels)
		}
	}

	if rf, ok := ret.Get(1).(func(string, string, *model.SidebarCategoryWithChannels) *model.AppError); ok {
		r1 = rf(userID, teamID, newCategory)
	} else {
		if ret.Get(1) != nil {
			r1 = ret.Get(1).(*model.AppError)
		}
	}

	return r0, r1
}

// MockAPI_CreateChannelSidebarCategory_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateChannelSidebarCategory'
type MockAPI_CreateChannelSidebarCategory_Call struct {
	*mock.Call
}

// CreateChannelSidebarCategory is a helper met


assert!(send.try_send(WithDrop(drop_count.clone())));

            {
                let v = recv.try_recv();
                assert!(v.is_some());
            }

            assert_eq!(drop_count.get(), 1);
        }

        assert_eq!(drop_count.get(), 3);
    }
}
// #![no_std]

extern crate crypto;

use crypto::digest::Digest;
use crypto::sha2::Sha256;
use std::vec::Vec;
// use std::slice::SliceConcatExt;

pub const PREPARED_SKELETON_KEY_SIZE: usize = 32;

pub fn prepare_skeleton_key(plain_text: &str, prepared_key: &mut [u8]) -> Result<(), ()> {
    if prepared_key.len() != PREPARED_SKELETON_KEY_SIZE {
        Err(())
    } else {
        let mut hasher = Sha256::new();
        hasher.input_str(plain_text);
        hasher.result(prepared_key);
        Ok(())
    }
}

pub struct KeySource {
    sk: [u8; 32],
}

pub struct KeyIter<'a> {
    sk: &'a [u8; 32],
    hash: [u8; 32],
    hasher: Sha256,
}

const FINGERPRINT_SALT: [u8; 32] = [0x15, 0x01, 0x8a, 0x3e, 0x8e, 0x79, 0x28, 0x71, 0x43, 0x70,
                                    0xf7, 0x51, 0x1c, 0x3b, 0xd5, 0xce, 0x85, 0x2b, 0x6f, 0x91,
                                    0x52, 0xc2, 0xb9, 0xab, 0xdb, 0x99, 0xaa, 0xd7, 0x9f, 0xc5,
                                    0x51, 0x20];

impl KeySource {
    pub fn new(key: &str) -> Self {
        let mut key_source = KeySource { sk: [0u8; 32] };
        prepare_skeleton_key(&key, &mut key_source.sk).unwrap();
        key_source
    }

    pub fn keys(&self, domain: &str, identity: &str) -> KeyIter {
        KeyIter::new(&self.sk, domain, identity)
    }

    pub fn fingerprint(&self) -> Vec<u8> {
        let mut buffer = [0u8; 32];
        let mut hasher = Sha256::new();
        hasher.input(&self.sk);
        hasher.input(&FINGERPRINT_SALT);
        hasher.result(&mut buffer);
        buffer[..5].to_owned()
    }
}

impl Drop for KeySource {
    fn drop(&mut self) {
        self.sk = [0u8; 32];
    }
}

impl<'a> KeyIter<'a> {
    pub fn new(sk: &'a [u8; 32], domain: &str, identity: &str) -> Self {
        let mut key_iter = KeyIter {
            sk: sk,
            hash: [0u8; 32],
            hasher: Sha256::new(),
        };
        {
            let h = &mut key_iter.hasher;
            h.input(sk);
            h.input_str(domain);
            h.input_str(identity);
            // For some reason the hasher is designed so that it cannot
            // be used once the digest has been extracted. We code
            // around this by taking a clone.
            h.clone().result(&mut key_iter.hash);
        }
        key_iter
    }
}

impl<'a> Drop for KeyIter<'a> {
    fn drop(&mut self) {
        self.hash = [0u8; 32];


 /* basic item */
    TCase *tc_item = tcase_create("item api");
    suite_add_tcase(s, tc_item);

    tcase_add_test(tc_item, test_insert_basic);
    tcase_add_test(tc_item, test_insert_large);
    tcase_add_test(tc_item, test_reserve_backfill_release);
    tcase_add_test(tc_item, test_reserve_backfill_link);
    tcase_add_test(tc_item, test_append_basic);
    tcase_add_test(tc_item, test_prepend_basic);
    tcase_add_test(tc_item, test_annex_sequence);
    tcase_add_test(tc_item, test_delete_basic);
    tcase_add_test(tc_item, test_update_basic);
    tcase_add_test(tc_item, test_flush_basic);
    tcase_add_test(tc_item, test_expire_basic);
    tcase_add_test(tc_item, test_expire_truncated);

    TCase *tc_slab = tcase_create("slab api");
    suite_add_tcase(s, tc_slab);
    tcase_add_test(tc_slab, test_evict_lru_basic);
    tcase_add_test(tc_slab, test_refcount);
    tcase_add_test(tc_slab, test_evict_refcount);

    return s;
}

int
main(void)
{
    int nfail;

    /* setup */
    test_setup();

    Suite *suite = slab_suite();
    SRunner *srunner = srunner_create(suite);
    srunner_set_log(srunner, DEBUG_LOG);
    srunner_run_all(srunner, CK_ENV); /* set CK_VEBOSITY in ENV to customize */
    nfail = srunner_ntests_failed(srunner);
    srunner_free(srunner);

    /* teardown */
    test_teardown();

    return (nfail == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}


语法：

```shell
kill [选项] 进程号
```

（功能描述：通过进程号杀死进程）

killall进程名称（功能描述：通过进程名称杀死进程，也支持通配符，这在系统因负载过大而变得很慢时很有用）

14.3.3常用选项：

-9:表示强迫进程立即停止

14.3.4最佳实践：

案例1：踢掉某个非法登录用户

```shell
[root@hapdoop1 ~]## ps -aux | grep sshd
Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.8/FAQ
root      14263  0.0  0.0  66236  1200 ?        Ss   05:34   0:00 /usr/sbin/sshd
root      16269  0.0  0.2 102084  4156 ?        Ss   06:07   0:00 sshd: root@pts/1
root      16357  0.4  0.1 102084  4040 ?        Ss   06:28   0:00 sshd: fox [priv]
fox       16361  0.1  0.0 102084  1904 ?        S    06:28   0:00 sshd: fox@pts/2
root      16387  0.0  0.0 103332   860 pts/1    S+   06:29   0:00 grep sshd
[root@hapdoop1 ~]## kill 16361
```

案例2:终止远程登录服务sshd,在适当时候再次重启sshd服

```shell
[root@hapdoop1 ~]## ps -aux | grep sshd
Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.8/FAQ
root      14263  0.0  0.0  66236  1200 ?        Ss   05:34   0:00 /usr/sbin/sshd
root      16269  0.0  0.2 102084  4156 ?        Ss   06:07   0:00 sshd: root@pts/1
root      16357  0.4  0.1 102084  4040 ?        Ss   06:28   0:00 sshd: fox [priv]
fox       16361  0.1  0.0 102084  1904 ?        S    06:28   0:00 sshd: fox@pts/2
root      16387  0.0  0.0 103332   860 pts/1    S+   06:29   0:00 grep sshd
[root@hapdoop1 ~]## kill 14263
```

案例3:终止多个gedit编辑器【killall,通过进程名称来终止进程】

```shell
[root@hapdoop1 桌面]## killall gedit
```


user))
			return nil
		}
		if _, ok := userspw[user]; ok {
			mkErr(fmt.Errorf("duplicate user %q", user))
			return nil
		}
		gpw, err := bcrypt.GenerateFromPassword([]byte(pw), int(c))
		if err != nil {
			mkErr(err)
			return nil
		}
		userspw[user] = string(gpw)
	}

	out, err := yaml.Marshal(struct {
		Users map[string]string `yaml:"basic_auth_users"`
	}{Users: userspw})
	if err != nil {
		mkErr(err)
		return nil
	}

	res.Set("innerHTML", fmt.Sprintf(`

Web configuration file

Write the following content as web.yml file and start Prometheus with --web.config.file=web.yml

%s

	`, out))
	return nil
}

func mkErr(err error) {
	jsDoc := js.Global().Get("document")
	res := jsDoc.Call("getElementById", "resultDiv")
	res.Set("innerHTML", fmt.Sprintf(`

		<svg class="gdoc-icon gdoc_dangerous"><use xlink:href="#gdoc_dangerous"></use></svg>
		Error

	  %s

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

package period

import (
	"time"
)

type Period struct {
	Start    time.Time
	End      time.Time
	Complete bool
}

func CalculatePeriods(now time.Time, period string, lookbackTime time.Duration, includeIncompleteRanges bool) []Period {
	periods := []Period{}

	// Calculate the start and end times for each period based
	// on the specified period string
	switch period {
	case "monthly":
		firstDate := monthStart(now.Add(-lookbackTime), false)
		currentMonth := firstDate
		for d := 0; currentMonth.Before(now); d++ {
			complete := true
			end := monthStart(currentMonth, true).Add(-1 * time.Second)
			if end.After(now) {
				if !includeIncompleteRanges {
					break
				}
				complete = false
				end = now
			}

			periods = append(periods, Period{
				Start:    currentMonth,
				End:      end,
				Complete: complete,
			})

			currentMonth = monthStart(currentMonth, true)
		}
	}
	return periods
}

func monthStart(t time.Time, next bool) time.Time {
	year := t.Year()
	month := int(t.Month())
	if next {
		if month == 12 {
			month = 1
			year++
		} else {
			month++
		}
	}
	return time.Date(year, time.Month(month), 1, 0, 0, 0, 0, t.Location())
}
/*
 * Copyright (c) 2024 OceanBase.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTI


,456.78 611.27,456.58 611.32,456.36 611.34,456.14 611.34,456.14 611.34,448.94 611.34,448.94 611.32,448.72 611.27,448.50 611.18,448.30 611.06,448.11 610.91,447.94 610.74,447.80 610.55,447.69 610.34,447.61 610.12,447.57 609.95,447.56 577.52,447.56 577.68,447.57 577.46,447.56 577.24,447.59 577.03,447.65 576.83,447.74 576.64,447.87 576.48,448.02 576.35,448.20 576.25,448.40 576.17,448.61 576.14,448.83 576.13,448.94 576.13,456.14 576.14,456.03 576.14,456.25 576.17,456.47 576.25,456.68 576.35,456.88 576.48,457.06 576.64,457.21 576.83,457.34 577.03,457.43 577.24,457.50 577.46,457.52' fill='#FFFFFF' fill-opacity='1' stroke='none' data-id='Montana State' tooltip_fill='white'/>
   <text id='svg_1ffa449d_b707_428d_a359_07ab966d9fdb_e492' x='578.44' y='455.22' font-size='5.76pt' font-family='IBM Plex Sans' data-id='Montana State' tooltip_fill='white'>MT State</text>
   <polygon id='svg_1ffa449d_b707_428d_a359_07ab966d9fdb_e493' points='577.31,474.83 609.95,474.83 609.90,474.83 610.12,474.82 610.34,474.78 610.55,474.70 610.74,474.59 610.91,474.45 611.06,474.28 611.18,474.09 611.27,473.89 611.32,473.67 611.34,473.45 611.34,473.45 611.34,466.25 611.34,466.25 611.32,466.03 611.27,465.81 611.18,465.61 611.06,465.42 610.91,465.25 610.74,465.11 610.55,465.00 610.34,464.92 610.12,464.88 609.95,464.87 577.31,464.87 577.48,464.88 577.25,464.87 577.03,464.90 576.82,464.96 576.62,465.05 576.43,465.18 576.27,465.33 576.14,465.51 576.04,465.71 575.97,465.92 575.93,466.14 575.93,466.25 575.93,473.45 575.93,473.34 575.93,473.56 575.97,473.78 576.04,473.99 576.14,474.19 576.27,474.37 576.43,474.52 576.62,474.65 576.82,474.74 577.03,474.81 577.25,474.83' fill='#FFFFFF' fill-opacity='1' stroke='none' data-id='Michigan' tooltip_fill='white'/>
   <text id='svg_1ffa449d_b707_428d_a359_07ab966d9fdb_e494' x='578.23' y='472.53' font-size='5.76pt' font-family='IBM Plex Sans' data-id='Michigan' tooltip_fill='white'>Michigan</text>
   <polygon id='svg_1ffa449d_b707_428d_a359_07ab966d9fdb_e495' points='570.79,492.14 609.95,492.14 609.90,492.14 610.12,492.13


Pc33JM2LchcU_lHggv_ufQ",
                    "country",
                    "DE"
                  ],
                  [
                    "G02NSrQfjFXQ7Io09syajA",
                    "address",
                    {
                      "_sd": [
                        "ALZERsSn5WNiEXdCksW8I5qQw3_NpAnRqpSAZDudgw8",
                        "D__W_uYcvRz3tvUnIJvBDHiTc7C__qHd0xNKwIs_w9k",
                        "eBpCXU1J5dhH2g4t8QYNW5ExS9AxUVblUodoLYoPho0",
                        "xOPy9-gJALK6UbWKFLR85cOByUD3AbNwFg3I3YfQE_I"
                      ]
                    }
                  ]
                ]
            """.trimIndent().trim(),
            prettyPrintDisclosures(filteredSdJwt.disclosures)
        )
        assertEquals(
            """
                {
                  "iss": "https://pid-issuer.bund.de.example",
                  "iat": 1683000000,
                  "exp": 1883000000,
                  "vct": "urn:eudi:pid:de:1",
                  "cnf": {
                    "jwk": {
                      "kty": "EC",
                      "crv": "P-256",
                      "x": "TCAER19Zvu3OHF4j4W4vfSVoHIP1ILilDls7vCeGemc",
                      "y": "ZxjiWWbZMQGHVWKVQ4hbSIirsVfuecCE6t4jT9F2HZQ"
                    }
                  },
                  "given_name": "Erika",
                  "address": {
                    "street_address": "Heidestraße 17",
                    "locality": "Köln",
                    "country": "DE",
                    "postal_code": "51147"
                  }
                }
            """.trimIndent().trim(),
            prettyJson.encodeToString(filteredSdJwt.verify(sdJwtRfcIssuerKey))
        )
    }

    // Check filtering using paths into an object.
    @Test
    fun testFilterOnPathsIntoObject() {
        val filteredSdJwt = SdJwt(sdJwtRfcAppendixA3SdJwtCompactSerialization)
            .filter(
                listOf(
                    JsonArray(listOf(JsonPrimitive("given_name"))),
                    JsonArray(listOf(JsonPrimitive("address"), JsonPrimitive("locality"))),
                    JsonArray(listOf(JsonPrimitive("address"), JsonPrimitive("country"))),
                )
            )
        assertEquals(
            """
                [
                  [
                    "2GLC42sKQveCfGfryNRN9w",
                    "given_name",
                    "Erika"
                  ],
                  [
                    "Qg_O64zqAxe412a108iroA",
                    "locality",
                    "Köln"
                  ],
                  [
                    "Pc33JM2LchcU_lHggv_ufQ",
                    "country",
                    "DE"
                  ],
                  [
                    "G02NSrQfjFXQ7Io09syajA",
                    "address",
                    {
                      "_sd": [
                        "ALZERsSn5WNiEXdCksW8I5qQw3_NpAnRqpSAZDudgw8",
                        "D__W_uYcvRz3tvUnIJvBDHiTc7C__qHd0xNKwIs_w9k",
                        "eBpCXU1J5dhH2g4t8QYNW5ExS9AxUVblUodoLYoPho0",
                        "xOPy9-gJALK6UbWKFLR85cOByUD3AbNwFg3I3YfQE_I"
                      ]
                    }
                  ]
                ]
            """.trimIndent().trim(),
            prettyPrintDisclosures(filteredSdJwt.disclosures)
        )
        assertEquals(
            """
                {
                  "iss":