er1)
    for name, param in model.network.named_parameters():
        if "layer1" in name:
            assert param.requires_grad
        else:
            assert not param.requires_grad

    # should also work when the weights were previously frozen
    model.freeze_layers_except()
    model.freeze_layers_except(model.network.layer1)
    for name, param in model.network.named_parameters():
        if "layer1" in name:
            assert param.requires_grad
        else:
            assert not param.requires_grad

def test_freeze_feature_extractor_all_arch():
    """freeze_feature_extractor() should result in only the classifier layer having requires_grad=True

    all other params will have requires_grad=False. Classifier layer is determined by .classifier property
    """
    for arch_name in cnn_architectures.ARCH_DICT.keys():
        try:
            arch = cnn_architectures.ARCH_DICT[arch_name](
                num_classes=2, num_channels=1, weights=None
            )
            model = cnn.CNN(
                architecture=arch, classes=[0, 1], sample_duration=5.0, channels=1
            )
            model.freeze_feature_extractor()

            clf_params = list([id(x) for x in model.classifier.parameters()])
            for p in model.network.parameters():
                if id(p) in clf_params:
                    assert p.requires_grad
                else:
                    assert not p.requires_grad
        except Exception as e:
            raise Exception(f"{arch_name} failed") from e

def test_change_classes_all_arch():
    """change_classes should change the classes attribute and the output layer of the network"""
    for arch_name in cnn_architectures.ARCH_DICT.keys():
        try:
            model = cnn.CNN(
                architecture=arch_name, classes=[0, 1], sample_duration=5.0, channels=1
            )
            if arch_name == "squeezenet1_0":
                # has conv2d not linear layer
                with pytest.raises(AssertionError):
                    model.change_classes([0, 1, 2])
            else:
                model.change_classes([0, 1, 2])
                assert model.classes == [0, 1, 2]
                assert model.classifier.out_features == 3
        except Exception as e:
            raise Exception(f"{arch_name} failed") from e


e,  99,  93, 0 ),
  V( 101, 0x5231, 105, 102, 0 ),
  V( 102, 0x4c0f, 106, 103, 0 ),
  V( 103, 0x4639, 107, 104, 0 ),
  V( 104, 0x415e, 103,  99, 0 ),
  V( 105, 0x5627, 105, 106, 1 ),
  V( 106, 0x50e7, 108, 107, 0 ),
  V( 107, 0x4b85, 109, 103, 0 ),
  V( 108, 0x5597, 110, 109, 0 ),
  V( 109, 0x504f, 111, 107, 0 ),
  V( 110, 0x5a10, 110, 111, 1 ),
  V( 111, 0x5522, 112, 109, 0 ),
  V( 112, 0x59eb, 112, 111, 1 ),
/*
 * This last entry is used for fixed probability estimate of 0.5
 * as suggested in Section 10.3 Table 5 of ITU-T Rec. T.851.
 */
  V( 113, 0x5a1d, 113, 113, 0 )
};


            "Authorization": `Bearer ${localStorage.getItem("token")}`
        }
    }
    return axios.get(`http://localhost:8000/api/users/${ localStorage.getItem("user_name")}/monthboard`, config).then((res) => {
        console.log(res)
        if (res.status == 200) {
            var notes: string = res.data;
            return notes
        }
        return null as any;
    }).catch((e)=>{
        console.log("problem with get notes")
    })

}

export const postNote = async (note:NotePost) : Promise<Number> => {
    let config: AxiosRequestConfig = {
        method: "post",
        url: `http://localhost:8000/api/users/${ localStorage.getItem("user_name")}/monthboard/update`,
        headers: {
            "Content-Type": "application/json",
            "X-Requested-With": "XMLHttpRequest",
            "Authorization": `Bearer ${localStorage.getItem("token")}`
        }
    }
    return axios.post(`http://localhost:8000/api/users/${ localStorage.getItem("user_name")}/monthboard/update`, note, config).then((res) => {
       console.log(res)
        console.log(res)
        if (res.status == 200) {
            return 1
        }
        return 0;
    }).catch((e)=>{
        console.log("problem with get notes")
        return 0;
    })

}import { expect } from 'chai';
import IDCardChecker from '../src/IDCardChecker';

describe('验证中国居民身份证', () => {
  it('正确的身份证', () => {
    const result = IDCardChecker.validate('11010519491231002X');
    expect(result).to.equal(true);
  });

  it('地区码不符', () => {
    const result = IDCardChecker.validate('160105194912310029');
    expect(result).to.equal(false);
  });

  it('日期码不符', () => {
    const result = IDCardChecker.validate('110105194902310026');
    expect(result).to.equal(false);
  });

  it('校验码不符', () => {
    const result = IDCardChecker.validate('110105194912310021');
    expect(result).to.equal(false);
  });

  it('获取省份', () => {
    const result = IDCardChecker.getProvince('11010519491231002X');
    expect(result).to.equal('北京市');
  });

  it('获取省份（身份证号错误）', () => {
    const result = IDCardChecker.getProvince('160105194912310029');
    expect(result).to.equal(null);
  });

  it('获取出生日期', () => {
    // @ts-ignore
    const result = IDCardChecker.getBirthDate('11010519491231002X').getTime();
    expect(result).to.equal(new Date('1949-12-31').getTime());
  });

  it('获取出生日期（身份证号错误）', () => {
    const result = IDCardChecker.getBirthDate('110105194902310026');
    expect(result).to.equal(null);
  });

  it('获取性别（女）', () => {
    const result = IDCardChecker.getGender('11010519491231002X');
    expect(result).to.equal('女');
  });

  it('获取性别（男）', () => {
    const result = IDCardChecker.getGender('350724199111282910');
    expect(result).to.equal('男');
  });

  it('获取性别（身份证号错误）', () => {
    const result = IDCardChecker.getGender('110105194912310021');
    expect(result).to.equal(null);
  });
});
import m,


ating it alone won't have any effect on the actual property, it has to be reassigned again
   * afterward.
   */
  @CoreTypeLocalCopy
  public final inline var gravity: Vector3
    @JvmName("gravityProperty")
    get() = getGravity()
    @JvmName("gravityProperty")
    set(`value`) {
      setGravity(value)
    }

  /**
   * Minimum value of the initial velocity.
   */
  public final inline var initialVelocityMin: Float
    @JvmName("initialVelocityMinProperty")
    get() = getParamMin(CPUParticles3D.Parameter.INITIAL_LINEAR_VELOCITY)
    @JvmName("initialVelocityMinProperty")
    set(`value`) {
      setParamMin(CPUParticles3D.Parameter.INITIAL_LINEAR_VELOCITY, value)
    }

  /**
   * Maximum value of the initial velocity.
   */
  public final inline var initialVelocityMax: Float
    @JvmName("initialVelocityMaxProperty")
    get() = getParamMax(CPUParticles3D.Parameter.INITIAL_LINEAR_VELOCITY)
    @JvmName("initialVelocityMaxProperty")
    set(`value`) {
      setParamMax(CPUParticles3D.Parameter.INITIAL_LINEAR_VELOCITY, value)
    }

  /**
   * Minimum initial angular velocity (rotation speed) applied to each particle in *degrees* per
   * second.
   */
  public final inline var angularVelocityMin: Float
    @JvmName("angularVelocityMinProperty")
    get() = getParamMin(CPUParticles3D.Parameter.ANGULAR_VELOCITY)
    @JvmName("angularVelocityMinProperty")
    set(`value`) {
      setParamMin(CPUParticles3D.Parameter.ANGULAR_VELOCITY, value)
    }

  /**
   * Maximum initial angular velocity (rotation speed) applied to each particle in *degrees* per
   * second.
   */
  public final inline var angularVelocityMax: Float
    @JvmName("angularVelocityMaxProperty")
    get() = getParamMax(CPUParticles3D.Parameter.ANGULAR_VELOCITY)
    @JvmName("angularVelocityMaxProperty")
    set(`value`) {
      setParamMax(CPUParticles3D.Parameter.ANGULAR_VELOCITY, value)
    }

  /**
   * Each particle's angular velocity (rotation speed) will vary along this [Curve] over its
   * lifetime. Should be a unit [Curve].
   */
  public final inline var angularVelocityCurve: Curve?
    @JvmName("angularVelocityCurveProperty")
    get() = getParamCurve(CPUParticles3D.Parameter.ANGULAR_VELOCITY)
    @JvmName("angularVelocityCurveProperty")
    set(`value`) {
      setParamCurve(CPUParticles3D.Parameter.ANGULAR_VELOCITY, value)
    }

  /**
   * Minimum orbit velocity.
   */
  public final inline var orbitVelocityMin: Float
    @JvmName("orbitVelocityMinProperty")
    get() = getParamMin(CPUParticles3D.Parameter.ORBIT_VELOCITY)
    @JvmName("orbitVelocityMinProperty")
    set(`value`) {
      setParamMin(CPUParticles3D.Parameter.ORBIT_VELOCITY, value)
    }

  /**
   * Maximum orbit velocity.
   */
  public final inline var orbitVelocityMax: Float
    @JvmName("orbitVelocityMaxProperty")
    get() = getParamMax(CPUParticles3D.Parameter.ORBIT_VELOCITY)
    @JvmName("orbitVelocityMaxProperty")
    set(`value`) {
      setParamMax(CPUParticles3D.Parameter.ORBIT_VELOCITY, value)
    }

  /**
   * Each particle's orbital velocity will vary along this [Curve]. Should be a un


				.clientConnector(httpConnector)
				.build();

		String destinationUri = "https://www.springsource.org/spring-integration";
		WebFluxRequestExecutingMessageHandler reactiveHandler =
				new WebFluxRequestExecutingMessageHandler(destinationUri, webClient);

		QueueChannel replyChannel = new QueueChannel();
		reactiveHandler.setOutputChannel(replyChannel);
		reactiveHandler.setBodyExtractor(new ClientHttpResponseBodyExtractor());

		reactiveHandler.handleMessage(MessageBuilder.withPayload("hello, world").build());

		Message<?> receive = replyChannel.receive(10_000);

		assertThat(receive).isNotNull();

		assertThat(receive.getPayload()).isInstanceOf(ClientHttpResponse.class);

		ClientHttpResponse response = (ClientHttpResponse) receive.getPayload();

		assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
		assertThat(response.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN);

		StepVerifier.create(response.getBody().map(dataBuffer -> dataBuffer.toString(StandardCharsets.UTF_8)))
				.expectNext("foo", "bar", "baz")
				.verifyComplete();
	}

	@Test
	void testClientHttpResponseErrorAsReply() {
		ClientHttpConnector httpConnector = new HttpHandlerConnector((request, response) -> {
			response.setStatusCode(HttpStatus.NOT_FOUND);
			response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

			DataBufferFactory bufferFactory = response.bufferFactory();

			Flux<DataBuffer> data =
					Flux.just(
									"{",
									"  \"error\": \"Not Found\",",
									"  \"message\": \"404 NOT_FOUND\",",
									"  \"path\": \"/spring-integration\",",
									"  \"status\": 404,",
									"  \"timestamp\": \"1970-01-01T00:00:00.000+00:00\",",
									"  \"trace\": \"some really\nlong\ntrace\",",
									"}")
							.map(String::getBytes)
							.map(bufferFactory::wrap);

			return response.writeWith(data)
					.then(Mono.defer(response::setComplete));
		});

		WebClient webClient = WebClient.builder()
				.clientConnector(httpConnector)
				.build();

		String destinationUri = "https://www.springsource.org/spring-integration";
		WebFluxRequestExecutingMessageHandler reactiveHandler =
				new WebFluxRequestExecutingMessageHandler(destinationUri, webClient);

		QueueChannel replyChannel = new QueueChannel();
		QueueChannel errorChannel = new QueueChannel();
		reactiveHandler.setOutputChannel(replyChannel);
		reactiveHandler.setBodyExtractor(new ClientHttpResponseBodyExtractor());

		final Message<?> message =
				MessageBuilder.withPayload("hello, world")
						.setErrorChannel(errorChannel)
						.build();
		reactiveHandler.handleMessage(message);

		Message<?> errorMessage = errorChannel.receive(10_000);

		assertThat(errorMessage).isNotNull();
		assertThat(errorMessage).isInstanceOf(ErrorMessage.class);
		final Throwable throwable = (Throwable) errorMessage.getPayload();
		assertThat(throwable).isInstanceOf(MessageHandlingException.class);
		assertThat(throwable.getCause()).isInstanceOf(WebClientResponseException.NotFound.class);
		assertThat(throwable).hasStackTraceContaining("404 Not Found");
	}

	@Test
	void testMaxInMemorySizeExceeded() {
		ClientHttpConnector httpConnector = new HttpHandlerConnector((request, response) -> {
			response.setStatusCode(HttpStatus.OK);

			DataBufferFactory bufferFactory = response.bufferFactory();

			Mono<DataBuffer> data = Mono.just(bufferFactory.wrap("test".getBytes()));

			return response.writeWith(data)
					.then(Mono.defer(response::setComplete));
		});

		WebClient webClient = WebClient.builder()
				.clientConnector(httpConnector)
				.exchangeStrategies(ExchangeStrategies.builder()
						.codecs(clientCodecConfigurer -> clientCo


 https://github.com/phetsims/scenery/issues/637.
const GUTTER_SIZE = 1;

// Amount of blank space along the bottom and right of each image that is left transparent, to avoid graphical
// artifacts due to texture filtering blending the adjacent image in.
// See https://github.com/phetsims/scenery/issues/637.
const PADDING = 1;

export default class SpriteSheet {

  private useMipmaps: boolean;
  private gl: WebGLRenderingContext | null;
  public texture: WebGLTexture | null;

  // The top-level bounding box for texture content. All sprites will have coordinate bounding
  // boxes that are included in these bounds.
  private bounds: Bounds2;

  private width: number;
  private height: number;

  private canvas: HTMLCanvasElement;
  private context: CanvasRenderingContext2D;

  // Handles how our available area is partitioned into sprites.
  private binPacker: BinPacker;

  // Whether this spritesheet needs updates.
  private dirty: boolean;

  private usedSprites: Sprite[];

  // works as a LRU cache for removing items when we need to allocate new space
  private unusedSprites: Sprite[];

  /**
   * @param useMipmaps - Whether built-in WebGL mipmapping should be used. Higher quality, but may be slower
   *                     to add images (since mipmaps need to be updated).
   */
  public constructor( useMipmaps: boolean ) {
    this.useMipmaps = useMipmaps;

    // Will be passed in with initializeContext
    this.gl = null;

    // Will be set later, once we have a context
    this.texture = null;

    // TODO: potentially support larger texture sizes based on reported capabilities (could cause fewer draw calls?)
    this.bounds = new Bounds2( 0, 0, MAX_DIMENSION.width, MAX_DIMENSION.height );
    assert && assert( this.bounds.minX === 0 && this.bounds.minY === 0, 'Assumed constraint later on for transforms' );

    this.width = this.bounds.width;
    this.height = this.bounds.height;

    this.canvas = document.createElement( 'canvas' );
    this.canvas.width = this.width;
    this.canvas.height = this.height;
    this.context = this.canvas.getContext( '2d' )!;

    this.binPacker = new BinPacker( this.bounds );
    this.dirty = true;

    this.usedSprites = [];
    this.unusedSprites = [];
  }

  /**
   * Initialize (or reinitialize) ourself with a new GL context. Should be called at least once before updateTexture()
   *
   * NOTE: Should be safe to call with a different context (will recreate a different texture) should this be needed
   *       for things like context loss.
   */
  public initializeContext( gl: WebGLRenderingContext ): void {
    this.gl = gl;

    this.createTexture();
  }

  /**
   * Allocates and creates a GL texture, configures it, and initializes it with our current Canvas.
   */
  private createTexture(): void {
    const gl = this.gl!;
    assert && assert( gl );

    this.texture = gl.createTexture();
    gl.bindTexture( gl.TEXTURE_2D, this.texture );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.useMipmaps ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTUR


  pointer-events: none

    @include vendor('transition', 0.3s ease)
    @include vendor('transition-delay', $hintHideDelay)

  &:hover:before, &:hover:after
    visibility: visible
    opacity: 1

  &:hover:before, &:hover:after
    // $hintShowDelay will apply as soon as element is hovered.
    @include vendor('transition-delay', $hintShowDelay)

  /**
   * tooltip arrow
   */
  &:before
    content: ''
    position: absolute
    background: transparent
    border: $hintArrowBorderWidth solid transparent
    // move z-index 1 up than :after so that it shows over box-shadow
    z-index: $hintZIndex + 1

.hint--html
  .hint__content
    position: absolute

    // HACK: Trigger hardware accelerated rendering, otherwise transform was not
    // working on a hidden element
    @include vendor('transform', translate3d(0, 0, 0))

    // HACK: visibility is set to hidden because IE & Opera don't support
    // pointer-events on HTML content yet because of which hovering a hidden tooltip
    // shows the tooltip.
    visibility: hidden
    opacity: 0
    z-index: $hintZIndex
    // shouldn't receive pointer events, otherwise even hovering tooltip will make it appear
    //pointer-events: none

    @include vendor('transition', 0.3s ease)
    @include vendor('transition-delay', $hintHideDelay)

  &:hover .hint__content,
  &:focus .hint__content
    visibility: visible
    opacity: 1

  &:hover .hint__content
    // $hintShowDelay will apply as soon as element is hovered.
    @include vendor('transition-delay', $hintShowDelay)

  &.hint--notrans
    &:before, &:after
      @include vendor('transition', none)
    .hint__content
      @include vendor('transition', none)

@mixin ice-set-margin($property, $transitionDirection, $xDirection:0)
  $translateX: -50%
  @if $xDirection == -1
    $translateX: -100%
  @elseif $xDirection == 1
    $translateX: 0

  $value: unquote("#{$property}(#{$hintTransitionDistance * $transitionDirection})")
  @if $translateX != 0
    @include vendor('transform', translateX($translateX) $value)
  @else
    @include vendor('transform', $value)

@mixin ice-vertical-positioned-tooltip($propertyY, $transitionDirection, $xDirection:0)
  .hint__content
    #{$propertyY}: 100%
    left: 50%

  $translateX: -50%
  @if $xDirection == -1
  	$translateX: -100%
  @elseif $xDirection == 1
  	$translateX: 0

  &:before, .hint__content
    @include vendor('transform', translateX($translateX))

  &:before
    @if $xDirection != 0
      margin-left: -$xDirection * $hintArrowOffsetX
  .hint__content
    @if $xDirection != 0
      margin-left: -2 * $xDirection * $hintArrowOffsetX

  .hint__content
    &:after //to prevent mouse out
      content: ' '
      position: absolute
      @if $transitionDirection == -1
        top: 100%
      @else
        top: -$custom-hint-hover-helper-size
      left: 0
      height: $custom-hint-hover-helper-size
      width: 100%
      opacity: 0
      background-color: red

  &:hover .hint__content, &:focus .hint__content
    @include ice-set-margin('translateY', $transitionDirection, $xDirection)

@mixin ice-horizontal-positioned-tooltip($propertyX, $transitionDirection)
  &:before
    // get the arrow out
    margin-#{$propertyX}: -2 * $hintArrowBorderWidth
    // bring back to center
    margin-bottom: -1 * $hintAr


", 2)))
                .withPage(new TextPage(getLangPath("drygmy_charm", 3)).withTitle("ars_nouveau.summoning"))
                .withPage(new TextPage(getLangPath("drygmy_charm", 4)).withTitle("ars_nouveau.happiness"))
                .withPage(new TextPage(getLangPath("drygmy_charm", 5)).withTitle("ars_nouveau.production"))
                .withPage(new RelationsPage().withEntry(MACHINES, "mob_jar")), getPath(AUTOMATION, "drygmy_charm"));

        addPage(new PatchouliBuilder(EQUIPMENT, ItemsRegistry.DULL_TRINKET)
                .withPage(new CraftingPage(ItemsRegistry.DULL_TRINKET).withRecipe2(ItemsRegistry.MUNDANE_BELT))
                .withPage(new CraftingPage(ItemsRegistry.RING_OF_POTENTIAL)), getPath(EQUIPMENT, "dull_items"));

        addPage(new PatchouliBuilder(RESOURCES, BlockRegistry.MAGE_BLOOM_CROP)
                .withTextPage("ars_nouveau.page.magebloom_crop")
                .withPage(new ApparatusPage(BlockRegistry.MAGE_BLOOM_CROP))
                .withPage(new CraftingPage(ItemsRegistry.MAGE_FIBER).withRecipe2(BlockRegistry.MAGEBLOOM_BLOCK)), getPath(RESOURCES, "magebloom_crop"));

        addPage(new PatchouliBuilder(EQUIPMENT, ItemsRegistry.POTION_FLASK)
                .withLocalizedText()
                .withPage(new ApparatusPage(ItemsRegistry.POTION_FLASK))
                .withLocalizedText()
                .withPage(new ApparatusPage(ItemsRegistry.POTION_FLASK_EXTEND_TIME))
                .withLocalizedText()
                .withPage(new ApparatusPage(ItemsRegistry.POTION_FLASK_AMPLIFY)), getPath(EQUIPMENT, "potion_flask"));

        addPage(new PatchouliBuilder(EQUIPMENT, "reactive_enchantment")
                .withIcon(Items.ENCHANTED_BOOK)
                .withLocalizedText()
                .withPage(new EnchantingPage("ars_nouveau:" + EnchantmentRegistry.REACTIVE_ENCHANTMENT.location().getPath()))
                .withLocalizedText()
                .withPage(new EnchantingPage("ars_nouveau:" + EnchantmentRegistry.REACTIVE_ENCHANTMENT.location().getPath() + "_" + 2))
                .withPage(new EnchantingPage("ars_nouveau:" + EnchantmentRegistry.REACTIVE_ENCHANTMENT.location().getPath() + "_" + 3))
                .withPage(new EnchantingPage("ars_nouveau:" + EnchantmentRegistry.REACTIVE_ENCHANTMENT.location().getPath() + "_" + 4))
                .withLocalizedText()
                .withPage(new ApparatusTextPage("ars_nouveau:spell_write")), getPath(EQUIPMENT, "reactive_enchantment"));

        addBasicItem(ItemsRegistry.RING_OF_GREATER_DISCOUNT, EQUIPMENT, new ApparatusPage(ItemsRegistry.RING_OF_GREATER_DISCOUNT));
        addBasicItem(ItemsRegistry.RING_OF_LESSER_DISCOUNT, EQUIPMENT, new ApparatusPage(ItemsRegistry.RING_OF_LESSER_DISCOUNT));

        var turrets = addPage(new PatchouliBuilder(AUTOMATION, BlockRegistry.BASIC_SPELL_TURRET)
                .withLocalizedText()
                .withPage(new CraftingPage(BlockRegistry.BASIC_SPELL_TURRET).withRecipe2(BlockRegistry.ROTATING_TURRET))
                .withLocalizedText()
                .withPage(new ApparatusPage(BlockRegistry.ENCHANTED_SPELL_TURRET))
                .withLocalizedText()
                .wi


 * value to mS2 conversion (threshold \* 18 = milli-g / 1000 = g / 1.0197162 = mS2).
   * Default [22].
   */
  accelerationWarningThreshold?: number;
  /**
   * Gets or sets the accelerometer threshold warning factor value for this vehicle.
   * Default [0].
   */
  accelerometerThresholdWarningFactor?: number;
  /**
   * Gets or sets the braking warning accelerometer threshold (y axis) value for the
   * vehicle. A negative value that when exceeded will trigger device beeping. Threshold
   * value to mS2 conversion (threshold \* 18 = milli-g / 1000 = g / 1.0197162 = mS2).
   * Default [-34].
   */
  brakingWarningThreshold?: number;
  /**
   * Gets or sets the cornering warning threshold (x axis) value for the vehicle. A positive
   * value that when exceeded will trigger device beeping (the additive inverse is automatically
   * applied: 26/-26). Threshold value to mS2 conversion (threshold \* 18 = milli-g /
   * 1000 = g / 1.0197162 = mS2). Default [26].
   */
  corneringWarningThreshold?: number;
  /**
   * Gets or sets toggle to enable beeping when any of the acceleration thresholds are
   * exceeded by device accelerometer readings. Default [false].
   */
  enableBeepOnDangerousDriving?: boolean;
  /**
   * Gets or sets toggle to enable beeping when the vehicle's RPM exceeds the 'RpmValue'.
   * Default [false].
   */
  enableBeepOnRpm?: boolean;
  /**
   * Gets or sets the offset to be applied engine hours data reported by the engine computer.
   * Default [0].
   */
  engineHourOffset?: number;
  /**
   * Gets or sets toggle to enable active tracking on the device. enables Active Tracking
   * which triggers the device to transmit data more frequently. This allows for continuously
   * up-to-date vehicle positions animated on the live map. It also enables live server-side
   * driver alerts. Default [false].
   */
  isActiveTrackingEnabled?: boolean;
  /**
   * Gets or sets value which toggles beeping if an unbuckled seat belt is detected.
   * This will only work if the device is able to obtain seat belt information from the
   * vehicle. Default [false].
   */
  isDriverSeatbeltWarningOn?: boolean;
  /** Gets or sets value which toggles device IOX USB connection. Default [true]. */
  isIoxConnectionEnabled?: boolean;
  /**
   * Gets or sets value which toggles monitoring both passenger and driver unbuckled
   * seat belt, otherwise only the driver is monitored. Default [false].
   */
  isPassengerSeatbeltWarningOn?: boolean;
  /**
   * Gets or sets value which toggles device beeping when the vehicle is reversing. Default
   * [false].
   */
  isReverseDetectOn?: boolean;
  /**
   * Gets or sets a {@link ISingle} used to correct the odometer value received from
   * the engine. Default [1].
   */
  odometerFactor?: number;
  /**
   * Gets or sets the offset to be applied odometer reported by the engine computer.
   * Default [0].
   */
  odometerOffset?: number;
  /** Gets or sets the RPM value that when exceeded triggers device beeping. Default [3500]. */
  rpmValue?: number;
  /**
   * Gets or sets the value in km/h that below will not trigger 'Seat belt Warning'.
   * Default [10].
   */
  seatbeltWarningSpeed?: number;
}
import { mkdirSync, writeFileSync } from 'fs';
import { join } from 'path';
import { exec } from './exec-sync';
import { ensureThat, jsonPackage, PackageDotJson } from


//
// Copyright 2016 Google Inc.
//
// 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.
//

#import <EarlGrey/GREYIdlingResource.h>

/**
 *  An idling resource to track NSTimer firing events so that the framework can synchronize
 *  with them.
 */
@interface GREYNSTimerIdlingResource : NSObject<GREYIdlingResource>

/**
 *  @remark init is not an available initializer. Use the other initializers.
 */
- (instancetype)init NS_UNAVAILABLE;

/**
 *  Creates an idling resource that tracks the specified @c timer, causing actions to wait until
 *  the timer is fired or invalidated. If @c removeOnIdle is @c YES, the idling resource will
 *  automatically remove itself from the list of registered idling resources when it becomes idle.
 *
 *  @param timer        The timer that will be tracked by the idling resource.
 *  @param name         A descriptive name for the idling resource.
 *  @param removeOnIdle Defines whether the resource should unregister itself when it becomes idle.
 *
 *  @return A new and initialized GREYNSTimerIdlingResource instance.
 */
+ (instancetype)trackTimer:(NSTimer *)timer name:(NSString *)name removeOnIdle:(BOOL)removeOnIdle;

@end


from selenium import webdriver
from bs4 import BeautifulSoup
import requests
from selenium.webdriver.common.by import By
import time

# Your Chrome Path
chrome_path = "YOUR_CHROME_DRIVER_PATH"

# Your Google Form Link
FORM = "YOUR_GOOGLE_FORM"
# Three empty list to save Scraped data
ADDRESS = []
PRICE = []
LINK = []

# Header to add with requests.get
HEADERS = {
    "User-Agent": "YOUR_USER_AGENT",
    "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
}

class HouseData:
    def __init__(self):
        self.driver = webdriver.Chrome(executable_path=chrome_path)
        # Making a request to the website
        self.web = requests.get(
            "https://www.zillow.com/homes/for_rent/1-_beds/?searchQueryState=%7B%22pagination%22%3A%7B%7D%2C%22usersSearchTerm%22%3Anull%2C%22mapBounds%22%3A%7B%22west%22%3A-122.56276167822266%2C%22east%22%3A-122.30389632177734%2C%22south%22%3A37.69261345230467%2C%22north%22%3A37.857877098316834%7D%2C%22isMapVisible%22%3Atrue%2C%22filterState%22%3A%7B%22fr%22%3A%7B%22value%22%3Atrue%7D%2C%22fsba%22%3A%7B%22value%22%3Afalse%7D%2C%22fsbo%22%3A%7B%22value%22%3Afalse%7D%2C%22nc%22%3A%7B%22value%22%3Afalse%7D%2C%22cmsn%22%3A%7B%22value%22%3Afalse%7D%2C%22auc%22%3A%7B%22value%22%3Afalse%7D%2C%22fore%22%3A%7B%22value%22%3Afalse%7D%2C%22pmf%22%3A%7B%22value%22%3Afalse%7D%2C%22pf%22%3A%7B%22value%22%3Afalse%7D%2C%22mp%22%3A%7B%22max%22%3A3000%7D%2C%22price%22%3A%7B%22max%22%3A872627%7D%2C%22beds%22%3A%7B%22min%22%3A1%7D%7D%2C%22isListVisible%22%3Atrue%2C%22mapZoom%22%3A12%7D",
            headers=HEADERS,
        )
        self.my_html = self.web.content

        self.soup = BeautifulSoup(self.my_html, "html.parser")

    # This function help in selection the specific elemen(address,link)t from the web page
    def my_css(self, css_class):
        return (
            css_class is not None
            and "StyledPropertyCardDataArea-c11n-8-89-0__sc-yipmu-0 gZUDVm property-card-link"
            in css_class
        )

    # This function help in selection the specific elemen(price)t from the web page
    def my_price(self, css_class):
        return (
            css_class is not None
            and "PropertyCardWrapper__StyledPriceLine-srp__sc-16e8gqd-1 iMKTKr"
            in css_class
        )

    # This Function find data we need and add them to the lists
    def scrape(self):
        # print(self.soup.prettify())
        address = self.soup.find_all(class_=self.my_css)
        price = self.soup.find_all(class_=self.my_price)
        for i in address:
            ADDRESS.append(i.text)
            LINK.append(f'https://www.zillow.com{i.get("href")}')

        for j in price:
            PRICE.append(j.text)

    # This function use selenium and fill form with the data we scrape
    def form(self):
        for i in range(len(ADDRESS)):
            self.driver.get(FORM)
            time.sleep(1)
            ad = self.driver.find_element(
                By.XPATH,
                "/html/body/div/div[2]/form/div[2]/div/div[2]/div[1]/div/div/div[2]/div/div[1]/div/div[1]/input",
            )
            ad.send_keys(ADDRESS[i])

            pr = self.driver.find_element(
                By.XPATH,
                "/html/body/div/div[2]/form/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/input",
            )
            pr.send_keys(PRICE[i])

            li = self.driver.find_element(
                By.XPATH,
                "/html/body/div/div[2]/form/div[2]/div/div[2]/div[3]/div/div/div[2]/div/div[1]/div/div[1]/input",
            )
            li.send_keys(LINK[i])

            submit = self.driver.find_element(
                By.XPATH,
                "/html/body/div/div[2]/form/div[2]/div/div[3]/div[1]/div[1]/div",
            )
            submit.click()

# Making object of our class and calling its function
bot = HouseData()
bot.scrape()
bot.form()


fd(int fd, uint32_t events) {
    epoll_event event{};
    event.events = events;
    event.data.fd = fd;

    if (epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event) == -1) {
        throw std::runtime_error("Failed to modify fd in epoll: " + std::string(strerror(errno)));
    }

    std::lock_guard<std::mutex> lock(handlers_mutex_);
    auto handler_it = handlers_.find(fd);
    if (handler_it != handlers_.end()) {
        handler_it->second->events = event.events;
    }
}

void EventLoop::remove_fd(int fd) {
    if (epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, nullptr) == -1) {
        // 可能fd已经关闭，这里不抛异常
    }

    std::lock_guard<std::mutex> lock(handlers_mutex_);
    handlers_.erase(fd);
}

void EventLoop::post_task(std::function<void()> task) {
    pending_tasks_.enqueue(std::move(task));
    // 唤醒epoll_wait
    if (wakeup_fd_ != -1) {
        eventfd_t inc = 1;
        (void)eventfd_write(wakeup_fd_, inc);
    }
}

void EventLoop::schedule_timer(std::chrono::milliseconds delay, std::function<void()> callback) {
    auto when = std::chrono::steady_clock::now() + delay;

    std::lock_guard<std::mutex> lock(timer_mutex_);
    timer_queue_.push({when, std::move(callback)});

    // 唤醒epoll_wait，让它重新计算超时时间
    if (wakeup_fd_ != -1) {
        eventfd_t inc = 1;
        (void)eventfd_write(wakeup_fd_, inc);
    }
}

void EventLoop::process_pending_tasks() {
    std::function<void()> task;
    int processed = 0;
    const int max_process = 100; // 避免长时间阻塞

    while (processed < max_process && pending_tasks_.dequeue(task)) {
        try {
            task();
        } catch (const std::exception& e) {
            // 记录异常但不中断事件循环
            // TODO: 使用日志系统记录
        }
        ++processed;
    }
}

void EventLoop::process_timers() {
    auto now = std::chrono::steady_clock::now();

    std::lock_guard<std::mutex> lock(timer_mutex_);
    while (!timer_queue_.empty() && timer_queue_.top().when <= now) {
        auto timer = timer_queue_.top();
        timer_queue_.pop();

        try {
            timer.callback();
        } catch (const std::exception& e) {
            // 记录异常但不中断事件循环
        }
    }
}

int EventLoop::get_next_timeout() {
    std::lock_guard<std::mutex> lock(timer_mutex_);

    if (timer_queue_.empty()) {
    return 10; // 更低的默认超时提升响应性
    }

    auto now = std::chrono::steady_clock::now();
    auto next_timeout = timer_queue_.top().when;

    if (next_timeout <= now) {
        return 0; // 立即超时
    }

    auto timeout_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
        next_timeout - now).count();

    return std::min(static_cast<int>(timeout_ms), 10);
}

// ============================================================================
// Socket 实现
// ============================================================================

Socket::Socket(EventLoop* loop) : loop_(loop) {
    fd_ = socket(AF_INET, SOCK_STREAM, 0);


/*
 * This file is part of the openHiTLS project.
 *
 * openHiTLS is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include "hitls_build.h"
#ifdef HITLS_CRYPTO_AES

/* AES_ENC_1_BLK */
.macro    AES_ENC_1_BLK    key round rdk blk
.align 16
.Laesenc_loop:
    leaq 16(\key), \key
    movdqu (\key), \rdk
    aesenc  \rdk, \blk
    decl \round
    jnz .Laesenc_loop
    leaq 16(\key), \key
    movdqu (\key), \rdk
    aesenclast \rdk, \blk
.endm

/* AES_ENC_2_BLKS */
.macro    AES_ENC_2_BLKS    key round rdk blk0 blk1
.align 16
.Laesenc_2_blks_loop:
    leaq 16(\key), \key
    movdqu (\key), \rdk
    aesenc  \rdk, \blk0
    aesenc  \rdk, \blk1
    decl \round
    jnz .Laesenc_2_blks_loop
    leaq 16(\key), \key
    movdqu (\key), \rdk
    aesenclast \rdk, \blk0
    aesenclast \rdk, \blk1
.endm

/* AES_ENC_3_BLKS */
.macro    AES_ENC_3_BLKS    key round rdk blk0 blk1 blk2
.align 16
.Laesenc_3_blks_loop:
    leaq 16(\key), \key
    movdqu (\key), \rdk
    aesenc  \rdk, \blk0
    aesenc  \rdk, \blk1
    aesenc  \rdk, \blk2
    decl \round
    jnz .Laesenc_3_blks_loop
    leaq 16(\key), \key
    movdqu (\key), \rdk
    aesenclast \rdk, \blk0
    aesenclast \rdk, \blk1
    aesenclast \rdk, \blk2
.endm

/* AES_ENC_4_BLKS */
.macro    AES_ENC_4_BLKS    key round rdk blk0 blk1 blk2 blk3
.align 16
.Laesenc_4_blks_loop:
    leaq 16(\key), \key
    movdqu (\key), \rdk
    aesenc  \rdk, \blk0
    aesenc  \rdk, \blk1
    aesenc  \rdk, \blk2
    aesenc  \rdk, \blk3
    decl \round
    jnz .Laesenc_4_blks_loop
    leaq 16(\key), \key
    movdqu (\key), \rdk
    aesenclast \rdk, \blk0
    aesenclast \rdk, \blk1
    aesenclast \rdk, \blk2
    aesenclast \rdk, \blk3
.endm

/* AES_ENC_5_BLKS */
.macro    AES_ENC_5_BLKS    key round rdk blk0 blk1 blk2 blk3


# Code generated by Lark OpenAPI.

import lark_oapi as lark
from lark_oapi.api.corehr.v1 import *

def main():
    # 创建client
    client = lark.Client.builder() \
        .app_id(lark.APP_ID) \
        .app_secret(lark.APP_SECRET) \
        .log_level(lark.LogLevel.DEBUG) \
        .build()

    # 构造请求对象
    request: GetCurrencyRequest = GetCurrencyRequest.builder() \
        .currency_id("67489937334909845") \
        .build()

    # 发起请求
    response: GetCurrencyResponse = client.corehr.v1.currency.get(request)

    # 处理失败返回
    if not response.success():
        lark.logger.error(
            f"client.corehr.v1.currency.get failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}")
        return

    # 处理业务结果
    lark.logger.info(lark.JSON.marshal(response.data, indent=4))

# 异步方式
async def amain():
    # 创建client
    client = lark.Client.builder() \
        .app_id(lark.APP_ID) \
        .app_secret(lark.APP_SECRET) \
        .log_level(lark.LogLevel.DEBUG) \
        .build()

    # 构造请求对象
    request: GetCurrencyRequest = GetCurrencyRequest.builder() \
        .currency_id("67489937334909845") \
        .build()

    # 发起请求
    response: GetCurrencyResponse = await client.corehr.v1.currency.aget(request)

    # 处理失败返回
    if not response.success():
        lark.logger.error(
            f"client.corehr.v1.currency.aget failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}")
        return

    # 处理业务结果
    lark.logger.info(lark.JSON.marshal(response.data, indent=4))

if __name__ == "__main__":
    # asyncio.run(amain()) 异步方式
    main()


还可以借助诸如 Better WordPress Minify 之类的插件来简化请求，将多个 CSS/JS 文件简化为一个 CSS/JS 文件，也能提升网站的加载速度。

其次，对于主题使用到的函数，可以考虑使用获取缓存数据的函数来替换直接从数据库查询数据的函数。比如`get_the_terms` 和 `wp_get_object_terms`。

> It should be noted that the results from `wp_get_object_terms` are not cached which will result in a db call everytime this function is called. For performance, functions like `get_the_terms()` (which the results of has been cached), should be used.

> `https://codex.wordpress.org/Function_Reference/wp_get_object_terms.`

通过使用缓存数据可以有效减少数据库查询，提升数据的查询结果。

如果一定要从数据库中直接查询，则要注意对查询结果进行缓存，可以使用 [WordPress Object Cache 函数](https://codex.wordpress.org/Class_Reference/WP_Object_Cache)来进行处理。

此外，也要精简主题的结构，去除一些无用的标签，减少 HTML 的代码，也可以有效的提升网站加载速度。

#### 优化图片

这里的图片优化不同于前面的图片优化，前面的优化更多是用户层面的，而这里的图片优化值得是 CSS 雪碧图（Sprites），通过使用 CSS 雪碧图，可以减少 CSS 调用的图片的数量，加速页面的展示。

##### 加入 LazyLoad

为博客加入 LazyLoad 可以让页面不在一开始就加载图片，从而让图片的加载分步进行，能够更好的利用服务器的带宽，将压力分流到整个页面的浏览过程中。除此之外，还可以给你的服务器减少一些请求的压力和流量的使用，如果图片没有被浏览到，则不加载相关的图片。

**使用 ROCKET LAZYLOAD**

到 [https://wordpress.org/plugins/rocket-lazy-load/](https://wordpress.org/plugins/rocket-lazy-load/) 下载插件，在后台启用该插件后，可以设置图片、iFrame 和 YouTube 视频的 LazyLoad。

![](https://postimg.aliavv.com/2018/nz5ch.png)

#### 优化数据库

WordPress 有修订版本的功能，可以使用插件来删除旧文章的修订版本，来优化数据库，达到更好的查询效果。

##### 安装 WP-Optimize

可以到 [https://wordpress.org/plugins


246118 80225A08 00000000 */  nop
/* 24611C 80225A0C 4502002D */  bc1fl .L80225AC4_ovl19
/* 246120 80225A10 8D0C0000 */   lw    $t4, ($t0)
/* 246124 80225A14 1000002A */  b     .L80225AC0_ovl19
/* 246128 80225A18 ACF90044 */   sw    $t9, 0x44($a3)
glabel L80225A1C_ovl19
/* 24612C 80225A1C 8CE90030 */  lw    $t1, 0x30($a3)
/* 246130 80225A20 51200028 */  beql  $t1, $zero, .L80225AC4_ovl19
/* 246134 80225A24 8D0C0000 */   lw    $t4, ($t0)
/* 246138 80225A28 8D0A0000 */  lw    $t2, ($t0)
/* 24613C 80225A2C 3C0D800F */ lui $t5, %hi(D_800E8920)
/* 246140 80225A30 240E0002 */  li    $t6, 2
/* 246144 80225A34 8D4B0000 */  lw    $t3, ($t2)
/* 246148 80225A38 000B6080 */  sll   $t4, $t3, 2
/* 24614C 80225A3C 01AC6821 */  addu  $t5, $t5, $t4
/* 246150 80225A40 8DAD8920 */ lw $t5, %lo(D_800E8920)($t5)
/* 246154 80225A44 11A00003 */  beqz  $t5, .L80225A54_ovl19
/* 246158 80225A48 00000000 */   nop
/* 24615C 80225A4C 1000001C */  b     .L80225AC0_ovl19
/* 246160 80225A50 ACE00044 */   sw    $zero, 0x44($a3)
.L80225A54_ovl19:
/* 246164 80225A54 1000001A */  b     .L80225AC0_ovl19
/* 246168 80225A58 ACEE0044 */   sw    $t6, 0x44($a3)
glabel L80225A5C_ovl19
/* 24616C 80225A5C 8CEF0030 */  lw    $t7, 0x30($a3)
/* 246170 80225A60 11E000E1 */  beqz  $t7, .L80225DE8_ovl19
/* 246174 80225A64 3C18800C */   lui   $t8, %hi(D_800BE500) # $t8, 0x800c
/* 246178 80225A68 8F18E500 */  lw    $t8, %lo(D_800BE500)($t8)
/* 24617C 80225A6C 3C19800C */  lui   $t9, %hi(D_800BE504) # $t9, 0x800c
/* 246180 80225A70 8F39E504 */  lw    $t9, %lo(D_800BE504)($t9)
/* 246184 80225A74 3C01800C */  lui   $at, %hi(D_800BE52C) # $at, 0x800c
/* 246188 80225A78 3C09800C */  lui   $t1, %hi(D_800BE508) # $t1, 0x800c
/* 24618C 80225A7C 8D29E508 */  lw    $t1, %lo(D_800BE508)($t1)
/* 246190 80225A80 AC38E52C */  sw    $t8, %lo(D_800BE52C)($at)
/* 246194 80225A84 3C01800C */  lui   $at, %hi(D_800BE530) # $at, 0x800c
/* 24619


Stream
import java.nio.*
import kotlin.math.abs

/**
 * Created by elect on 07/10/16.
 */

class Vec2ub(@JvmField var ofs: Int, var array: UbyteArray) : Vec2t<Ubyte>, ToBuffer {

    inline var x: Ubyte
        get() = array[ofs]
        set(value) = array.set(ofs, value)
    inline var y: Ubyte
        get() = array[ofs + 1]
        set(value) = array.set(ofs + 1, value)

    inline var vX: Byte
        get() = array[ofs].toByte()
        set(value) = array.set(ofs, value.toUbyte())
    inline var vY: Byte
        get() = array[ofs + 1].toByte()
        set(value) = array.set(ofs + 1, value.toUbyte())

    // -- Implicit basic constructors --

    constructor() : this(0)
    constructor(v: Vec2ub) : this(v.x, v.y)

    // -- Explicit basic constructors --

    @JvmOverloads
    constructor(x: Byte, y: Byte = x) : this(x.ub, y.ub)

    @JvmOverloads
    constructor(x: Ubyte, y: Ubyte = x) : this(0, UbyteArray(byteArrayOf(x.v, y.v)))

    // -- Conversion constructors --

    constructor(v: Number) : this(v.ub)
    constructor(x: Number, y: Number) : this(x.ub, y.ub)

    constructor(x: Number, v: Vec1t<out Number>) : this(x, v._x)

    @JvmOverloads
    constructor(v: Vec1t<out Number>, y: Number = v._x) : this(v._x, y)

    constructor(x: Vec1t<out Number>, y: Vec1t<out Number>) : this(x._x, y._x)

    constructor(v: Vec2t<out Number>) : this(v._x, v._y)
    constructor(v: Vec3t<out Number>) : this(v._x, v._y)
    constructor(v: Vec4t<out Number>) : this(v._x, v._y)

    @JvmOverloads
    constructor(x: Boolean, y: Boolean = x) : this(x.ub, y.ub)

    constructor(x: Boolean, v: Vec1bool) : this(x.ub, v.x.ub)

    @JvmOverloads
    constructor(v: Vec1bool, y: Boolean = v.x) : this(v.x.ub, y.ub)

    constructor(x: Vec1bool, y: Vec1bool) : this(x.x.ub, y.x.ub)

    constructor(v: Vec2bool) : this(v.x.ub, v.y.ub)
    constructor(v: Vec3bool) : this(v.x.ub, v.y.ub)
    constructor(v: Vec4bool) : this(v.x.ub, v.y.ub)

    constructor(bytes: ByteArray, index: Int = 0) : this(bytes[index], bytes[index + 1])
    constructor(chars: CharArray, index: Int = 0) : this(chars[index].ub, chars[index + 1].ub)
    constructor(shorts: ShortArray, index: Int = 0) : this(shorts[index], shorts[index + 1])
    constructor(ints: IntArray, index: Int = 0) : this(ints[index], ints[index + 1])
    constructor(longs: LongArray, index: Int = 0) : this(longs[index], longs[index + 1])
    constructor(floats: FloatArray, index: Int = 0) : this(floats[index], floats[index + 1])
    constructor(doubles: DoubleArray, index: Int = 0) : this(doubles[index], doubles[index + 1])
    constructor(booleans: BooleanArray, index: Int = 0) : this(booleans[index].ub, booleans[index + 1].ub)

    constructor(numbers: Array<out Number>, index: Int = 0) : this(numbers[index], numbers[index + 1])
    constructor(chars: Array<Cha


using System;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OAuthApp.Tenant;
using OAuthApp.Services;
using Swashbuckle.AspNetCore.Annotations;
using OAuthApp.Filters;

namespace OAuthApp.Apis
{
    [SwaggerTag("租户文件")]
    public class TenantBlobsController : BaseController
    {
        private readonly TenantDbContext _context;
        private readonly UploadService _uploader;
        private readonly TenantContext _tenant;

        public TenantBlobsController(
            TenantDbContext context,
            UploadService uploader,
            IHttpContextAccessor contextAccessor)
        {
            _context = context;
            _uploader = uploader;
            _tenant = contextAccessor.HttpContext.GetTenantContext();
        }

        [HttpGet]
        [SwaggerOperation(OperationId = "TenantBlobs")]
        [EncryptResultFilter]
        public IActionResult List(string channelCode,string channelAppId,string tag)
        {
            var q = _context.TenantBlobs.Where(x => x.TenantID == _tenant.Id);

            if(!string.IsNullOrWhiteSpace(channelCode))
            {
                q = q.Where(x => x.ChannelCode.Equals(channelCode));
            }

            if (!string.IsNullOrWhiteSpace(channelAppId))
            {
                q = q.Where(x => x.ChannelAppID.Equals(channelAppId));
            }

            if (!string.IsNullOrWhiteSpace(tag))
            {
                q = q.Where(x => x.Tag.Contains(tag));
            }

            var result = q.ToList();

            return OK(result);
        }

        [HttpGet("{id}")]
        [SwaggerOperation(OperationId = "TenantBlob")]
        [EncryptResultFilter]
        public IActionResult Get(long id)
        {
            var result =  _context.TenantBlobs.Find(id);

            if (result == null)
            {
                return NotFound();
            }

            return OK(result);
        }

        [HttpPut("{id}")]
        [SwaggerOperation(OperationId


 16)) -> intp(3, 0, 36)
	.word 0xfa358000  ! 3140: STH_R	sth	%r29, [%r22 + %r0]
	.word 0xf0342136  ! 3141: STH_I	sth	%r24, [%r16 + 0x0136]
	.word 0xf23de156  ! 3144: STD_I	std	%r25, [%r23 + 0x0156]
	.word 0x9194e1f8  ! 3146: WRPR_PIL_I	wrpr	%r19, 0x01f8, %pil
	.word 0xb37c6401  ! 3149: MOVR_I	movre	%r17, 0x1, %r25
	.word 0xbb50c000  ! 3150: RDPR_TT	rdpr	%tt, %r29
	.word 0xf6244000  ! 3154: STW_R	stw	%r27, [%r17 + %r0]
	.word 0xf024e0e8  ! 3157: STW_I	stw	%r24, [%r19 + 0x00e8]
	.word 0x9194e057  ! 3160: WRPR_PIL_I	wrpr	%r19, 0x0057, %pil
	.word 0x8d952057  ! 3164: WRPR_PSTATE_I	wrpr	%r20, 0x0057, %pstate
	.word 0xb23d6183  ! 3165: XNOR_I	xnor 	%r21, 0x0183, %r25
	.word 0xfe3ce02b  ! 3166: STD_I	std	%r31, [%r19 + 0x002b]
	.word 0xfe3de12e  ! 3167: STD_I	std	%r31, [%r23 + 0x012e]
	.word 0xfb3c614f  ! 3168: STDF_I	std	%f29, [0x014f, %r17]
	.word 0xf835e087  ! 3169: STH_I	sth	%r28, [%r23 + 0x0087]
	.word 0xfa2d8000  ! 3170: STB_R	stb	%r29, [%r22 + %r0]
	.word 0xfc34a19d  ! 3176: STH_I	sth	%r30, [%r18 + 0x019d]
	.word 0x9195a0c7  ! 3177: WRPR_PIL_I	wrpr	%r22, 0x00c7, %pil
	setx	data_start_0, %g1, %r22
	ta	T_CHANGE_HPRIV
	mov	0x38, %g1
	stxa	%r18, [%g1] 0x58
	ta	T_CHANGE_NONHPRIV
	.word 0xb751c000  ! 3180: RDPR_TL	rdpr	%tl, %r27
	.word 0xfc75e12a  ! 3187: STX_I	stx	%r30, [%r23 + 0x012a]
	mov	2, %r14
	.word 0xa193a000  ! 3193: WRPR_GL_I	wrpr	%r14, 0x0000, %-
	.word 0xf13da174  ! 3199: STDF_I	std	%f24, [0x0174, %r22]
	setx	data_start_1, %g1, %r22
	ta	T_CHANGE_HPRIV
	mov	0x38, %g1
	stxa	%r16, [%g1] 0x58
	ta	T_CHANGE_NONHPRIV
	.word 0x899560f2  ! 3204: WRPR_TICK_I	wrpr	%r21, 0x00f2, %tick
	.word 0x9194e047  ! 3205: WRPR_PIL_I	wrpr	%r19


 the data model this renderer will use to construct the DOM structure.
 * {@see goog.ui.media.Vimeo.newControl} for a example of constructing a control
 * with this renderer.
 *
 * This design is patterned after http://go/closure_control_subclassing
 *
 * It uses {@link goog.ui.media.FlashObject} to embed the flash object.
 *
 * @constructor
 * @extends {goog.ui.media.MediaRenderer}
 * @final
 */
goog.ui.media.Vimeo = function() {
  goog.ui.media.MediaRenderer.call(this);
};
goog.inherits(goog.ui.media.Vimeo, goog.ui.media.MediaRenderer);
goog.addSingletonGetter(goog.ui.media.Vimeo);

/**
 * Default CSS class to be applied to the root element of components rendered
 * by this renderer.
 *
 * @type {string}
 */
goog.ui.media.Vimeo.CSS_CLASS = goog.getCssName('goog-ui-media-vimeo');

/**
 * A static convenient method to construct a goog.ui.media.Media control out of
 * a Vimeo URL. It extracts the videoId information on the URL, sets it
 * as the data model goog.ui.media.Vimeo renderer uses, sets the states
 * supported by the renderer, and returns a Control that binds everything
 * together. This is what you should be using for constructing Vimeo videos,
 * except if you need more fine control over the configuration.
 *
 * @param {goog.ui.media.VimeoModel} dataModel A vimeo video URL.
 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper, used for
 *     document interaction.
 * @return {goog.ui.media.Media} A Control binded to the Vimeo renderer.
 */
goog.ui.media.Vimeo.newControl = function(dataModel, opt_domHelper) {
  var control = new goog.ui.media.Media(
      dataModel, goog.ui.media.Vimeo.getInstance(), opt_domHelper);
  // vimeo videos don't have any thumbnail for now, so we show the
  // "selected" version of the UI at the start, which is the
  // flash player.
  control.setSelected(true);
  return control;
};

/**
 * Creates the initial DOM structure of the vimeo video, which is basically a
 * the flash object pointing to a vimeo video player.
 *
 * @param {goog.ui.Control} c The media control.
 * @return {Element} The DOM structure that represents this control.
 * @override
 */
goog.ui.media.Vimeo.prototype.createDom = function(c) {
  var control = /** @type {goog.ui.media.Media} */ (c);
  var div = goog.ui.media.Vimeo.superClass_.createDom.call(this, control);

  var dataModel =
      /** @type {goog.ui.media.VimeoModel} */ (control.getDataModel());

  var flash = new goog.ui.media.FlashObject(
      dataModel.getPlayer().getUrl() || '',
      control.getDomHelper());
  flash.render(div);

  return div;
};

/**
 * Returns the CSS class to be applied to the root element of components
 * rendered using this renderer.
 * @return {string} Renderer-specific CSS class.
 * @override
 */
goog.ui.media.Vimeo.prototype.getCssClass = function() {
  return goog.ui.media.Vimeo.CSS_CLASS;
};

/**
 * The {@code goog.ui.media.Vimeo} media data model. It stores a required
 * {@code videoId} field, sets the vimeo URL, and allows a few optional
 * parameters.
 *
 * @param {string} videoId The vimeo video id.
 * @param


ftLastAccessTime.dwLowDateTime;
			find->atime_hi.dw = fd.ftLastAccessTime.dwHighDateTime;
			find->mtime_lo.dw = fd.ftLastWriteTime.dwLowDateTime;
			find->mtime_hi.dw = fd.ftLastWriteTime.dwHighDateTime;
		} else {
			FileTimeToDosDateTime(&fd.ftCreationTime, &find->ctime_lo.w.h, &find->ctime_lo.w.l);
			FileTimeToDosDateTime(&fd.ftLastAccessTime, &find->atime_lo.w.h, &find->atime_lo.w.l);
			FileTimeToDosDateTime(&fd.ftLastWriteTime, &find->mtime_lo.w.h, &find->mtime_lo.w.l);
		}
		find->size_hi = fd.nFileSizeHigh;
		find->size_lo = fd.nFileSizeLow;
		strcpy(find->full_name, fd.cFileName);
		strcpy(find->short_name, fd.cAlternateFileName);
		CPU_AX = dtainfo - dtalist + 1;
	} else if(dtainfo->allowable_mask & 8) {
		// volume label
		find->attrib = 8;
		find->size_hi = find->size_lo = 0;
		strcpy(find->full_name, process->volume_label);
		strcpy(find->short_name, msdos_short_volume_label(process->volume_label));
		dtainfo->allowable_mask &= ~8;
		CPU_AX = dtainfo - dtalist + 1;
	} else {
		CPU_AX = msdos_error_code(GetLastError());
		CPU_SET_C_FLAG(1);
	}
}

inline void msdos_int_21h_714fh()
{
	process_t *process = msdos_process_info_get(current_psp);
	find_lfn_t *find = (find_lfn_t *)(mem + CPU_ES_BASE + CPU_DI);
	WIN32_FIND_DATAA fd;

	if(CPU_BX - 1u >= MAX_DTAINFO) {
		CPU_AX = 6;
		CPU_SET_C_FLAG(1);
		return;
	}
	dtainfo_t *dtainfo = &dtalist[CPU_BX - 1];
	if(dtainfo->find_handle != INVALID_HANDLE_VALUE) {
		if(MyFindNextFileA(dtainfo->find_handle, &fd)) {
			while(!msdos_find_file_check_attribute(fd.dwFileAttributes, dtainfo->allowable_mask, dtainfo->required_mask)) {
				if(!MyFindNextFileA(dtainfo->find_handle, &fd)) {
					FindClose(dtainfo->find_handle);
					dtainfo->find_handle = INVALID_HANDLE_VALUE;
					break;
				}
			}
		} else {
			FindClose(dtainfo->find_handle);
			dtainfo->find_handle = INVALID_HANDLE_VALUE;
		}
	}
	if(dtainfo->find_handle != INVALID_HANDLE_VALUE) {
		find->attrib = fd.dwFileAttributes;
		msdos_find_file_conv_local_time(&fd);
		if(CPU_SI == 0) {
			find->ctime_lo.dw = fd.ftCreationTime.dwLowDateTime;
			find->ctime_hi.dw = fd.ftCreationTime.dwHighDateTime;
			find->atime_lo.dw = fd.ftLastAccessTime.dwLowDateTime;
			find->atime_hi.dw = fd.ftLastAccessTime.dwHighDateTime;
			find->mtime_lo.dw = fd.ftLastWriteTime.dwLowDateTime;
			find->mtime_hi.dw = fd.ftLastWriteTime.dwHighDateTime;
		} else {
			FileT


], %r4
	.word 0x1e800001  ! 675: BVC	bvc  	<label_0x1>
	.word 0xfb220009  ! 678: STF_R	st	%f29, [%r9, %r8]
	.word 0xf65a0009  ! 678: LDX_R	ldx	[%r8 + %r9], %r27
	.word 0xccca1009  ! 678: LDSBA_R	ldsba	[%r8, %r9] 0x80, %r6
	.word 0xc8320009  ! 681: STH_R	sth	%r4, [%r8 + %r9]
	.word 0xc84a0009  ! 681: LDSB_R	ldsb	[%r8 + %r9], %r4
	.word 0x12800002  ! 681: BNE	bne  	<label_0x2>
	.word 0xef3a0009  ! 684: STDF_R	std	%f23, [%r9, %r8]
	.word 0xc81a0009  ! 684: LDD_R	ldd	[%r8 + %r9], %r4
	.word 0x8c4a2d50  ! 684: MULX_I	mulx 	%r8, 0x0d50, %r6
	.word 0xeb3a0009  ! 687: STDF_R	std	%f21, [%r9, %r8]
	.word 0xea0a0009  ! 687: LDUB_R	ldub	[%r8 + %r9], %r21
	.word 0xe8d21009  ! 687: LDSHA_R	ldsha	[%r8, %r9] 0x80, %r20
	.word 0xeb3a0009  ! 690: STDF_R	std	%f21, [%r9, %r8]
	.word 0xce020009  ! 690: LDUW_R	lduw	[%r8 + %r9], %r7
	.word 0xc4c229c0  ! 690: LDSWA_I	ldswa	[%r8, + 0x09c0] %asi, %r2
	.word 0xcf220009  ! 693: STF_R	st	%f7, [%r9, %r8]
	.word 0xce5a0009  ! 693: LDX_R	ldx	[%r8 + %r9], %r7
	.word 0x83a208a9  ! 693: FSUBs	fsubs	%f8, %f9, %f1
	.word 0xcb3a0009  ! 696: STDF_R	std	%f5, [%r9, %r8]
	.word 0xcb020009  ! 696: LDF_R	ld	[%r8, %r9], %f5
	.word 0xc36a24ec  ! 696: PREFETCH_I	prefetch	[%r8 + 0x04ec], #one_read
	.word 0xca220009  ! 699: STW_R	stw	%r5, [%r8 + %r9]
	.word 0xce020009  ! 699: LDUW_R	lduw	[%r8 + %r9], %r7
	.word 0xa24a2034  ! 699: MULX_I	mulx 	%r8, 0x0034, %r17
	.word 0xca720009  ! 702: STX_R	stx	%r5, [%r8 + %r9]
	.word 0xca0a0009  ! 702: LDUB_R	ldub	[%r8 + %r9], %r5
	.word 0xc4122580  ! 702: LDUH_I	lduh	[%r8 + 0x0580], %r2
	.word 0xfe2a0009  ! 705: S


list__item")
    .withText(text)
    .filterVisible();
}
export var completeButton = Selector(".sd-navigation__complete-btn");

export const explicitErrorHandler = ClientFunction(() => {
  window.addEventListener("error", e => {
    if (e.message === "ResizeObserver loop completed with undelivered notifications." ||
      e.message === "ResizeObserver loop limit exceeded") {
      e.stopImmediatePropagation();
    }
  });
});
export function filterIsInViewport(node) {
  const rect = node.getBoundingClientRect();

  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}
export async function setTimeZoneUnsafe(t, timezone) {
  //Please note that the workaround uses internal API, which can be changed in the future, so you should use it carefully.
  //https://stackoverflow.com/questions/75837713/timezone-tests-in-testcafe
  const browserConnection = t["testRun"].browserConnection;
  const providerPlugin = browserConnection.provider.plugin;
  const browserClient = providerPlugin._getBrowserProtocolClient(providerPlugin.openedBrowsers[browserConnection.id]);
  const cdpClient = await browserClient.getActiveClient();
  await cdpClient.Emulation.setTimezoneOverride({ timezoneId: timezone });
}
export function getTimeZone() {
  return ClientFunction(() => Intl.DateTimeFormat().resolvedOptions().timeZone)();
}// import { frameworks, url, initSurvey, getSurveyResult } from "../helper";
// import { Selector, ClientFunction, fixture, test } from "testcafe";
// const title = "ShowPreview";

// const json = {
//   pages: [
//     { elements: [{ type: "text", name: "q1" }] },
//     {
//       elements: [
//         { type: "text", name: "q2", defaultValue: "2" },
//         { type: "text", name: "q3" },
//       ],
//     },
//     { elements: [{ type: "text", name: "q4", defaultValue: "4" }] },
//     { elements: [{ type: "text", name: "q5" }] },
//   ],
// };

// const showAnsweredQuestions = ClientFunction(() => {
//   window["survey"].showPreviewBeforeComplete = "showAnsweredQuestions";
// });
// const showAllQuestions = ClientFunction(() => {
//   window["survey"].showPreviewBeforeComplete = "showAllQuestions";
// });
// const goLastPage = ClientFunction(() => {
//   window["survey"].currentPageNo = window["survey"].visiblePageCount - 1;
// });

// frameworks.forEach((framework) => {
//   fixture`${framework} ${title}`.page`${url}${framework}`.beforeEach(
//     async (t) => {
//       await initSurvey(framework, json);
//     }
//   );

//   test("showPreview = showAllQuestions", async (t) => {
//     await showAllQuestions();
//     await goLastPage();
//     await t.click("input[value=Preview]");
//     await t.expect(Selector("input[title=Edit]").count).eql(4);
//     await t.click(Selector("input[title=Edit]").nth(1));
//     await t.typeText(Selector("input[type=text]").nth(1), "val3");
//     await t
//       .click("input[value=Next]")
//       .click("input[value=Next]")
//       .click("input[value=Preview]")
//       .click("input[value=Complete]");
//     const surveyResult = await getSurveyResult();
//     await t.expect(surveyResult).eql({
//       q2: "2",
//


Uniform2fv(location, buffer);
    }

    public static void glUniform2(int location, IntBuffer buffer) {
        glUniform2iv(location, buffer);
    }

    public static void glUniform3(int location, FloatBuffer buffer) {
        glUniform3fv(location, buffer);
    }

    public static void glUniform3(int location, IntBuffer buffer) {
        glUniform3iv(location, buffer);
    }

    public static void glUniform4(int location, FloatBuffer buffer) {
        glUniform4fv(location, buffer);
    }

    public static void glUniform4(int location, IntBuffer buffer) {
        glUniform4iv(location, buffer);
    }

    public static void glUniformMatrix2(int location, boolean transpose, FloatBuffer buffer) {
        glUniformMatrix2fv(location, transpose, buffer);
    }

    public static void glUniformMatrix3(int location, boolean transpose, FloatBuffer buffer) {
        glUniformMatrix3fv(location, transpose, buffer);
    }

    public static void glUniformMatrix4(int location, boolean transpose, FloatBuffer buffer) {
        glUniformMatrix4fv(location, transpose, buffer);
    }

    // FIXME
/*
    public static void glVertexAttribPointer(int index, int size, boolean normalized, int stride, DoubleBuffer buffer) {
        glVertexAttribPointer(index, size, GL11.GL_DOUBLE, normalized, stride, buffer);
    }
*/
    public static void glVertexAttribPointer(int index, int size, boolean normalized, int stride, FloatBuffer buffer) {
        glVertexAttribPointer(index, size, GL11.GL_FLOAT, normalized, stride, buffer);
    }
// -- End LWJGL2 part --

    // --- [ glCreateProgram ] ---

    /**
     * Creates a program object.
     *
     * @see Reference Page
     */
    @NativeType("GLuint")
    public static int glCreateProgram() {
        return GL20C.glCreateProgram();
    }

    // --- [ glDeleteProgram ] ---

    /**
     * Deletes a program object.
     *
     * @param program the program object to be deleted
     *
     * @see Reference Page
     */
    public static void glDeleteProgram(@NativeType("GLuint") int program) {
        GL20C.glDeleteProgram(program);
    }

    // --- [ glIsProgram ] ---

    /**
     * Returns {@link GL11#GL_TRUE TRUE} if {@code program} is the name of a program object. If {@code program} is zero, or a non-zero value that is not the name of a program
     * object, IsProgram returns {@link GL11#GL_FALSE FALSE}. No error is generated if program is not a valid program object name.
     *
     * @param program the program object name to query
     *
     * @see Reference Page
     */
    @NativeType("GLboolean")
    public static boolean glIsProgram(@NativeType("GLuint") int program) {
        return GL20C.glIsProgram(program);
    }

    // --- [ glCreateShader ] ---

    /**
     * Creates a shader object.
     *
     * @param type the type of shader to be created. One of:

{@link GL20C#GL_VERTEX_SHADER VERTEX_SHADER}	{@link GL20C#GL_FRAGMENT_SHADER FRAGMENT_SHADER}	{@link GL32#GL_GEOMETRY_SHADER GEOMETRY_SHADER}	{@link GL40#GL_TESS_CONTROL_SHADER TESS_CONTROL_SHADER}

{@link GL40#GL_TESS_EVALUATION_SHADER TESS_EVALUATION_SHADER}

     *
     * @see Reference Page
     */
    @NativeType("GLuint")
    public static int glCreateShader(@N


e.
 *
 * @param[in] self_p Initialized driver object.
 * @param[in] buf_p Buffer to write.
 * @param[in] size Number of bits to write.
 *
 * @return zero(0) or negative error code.
 */
int jtag_soft_data_write(struct jtag_soft_driver_t *self_p,
                         const void *buf_p,
                         size_t number_of_bits);

/**
 * Make given transition in the JTAG TAP controller state machine.
 *
 * @param[in] self_p Initialized driver object.
 * @param[in] transition Transition to take in the state machine
 *                       (one(1) or zero(0)).
 *
 * @return zero(0) or negative error code.
 */
int jtag_soft_make_transition(struct jtag_soft_driver_t *self_p,
                              int transition);

#endif


		cmd->ucmd.buttons |= BT_FORWARD;
	if (buttonMap.ButtonDown(Button_Right))			cmd->ucmd.buttons |= BT_RIGHT;
	if (buttonMap.ButtonDown(Button_Left))			cmd->ucmd.buttons |= BT_LEFT;
	if (buttonMap.ButtonDown(Button_MoveDown))		cmd->ucmd.buttons |= BT_MOVEDOWN;
	if (buttonMap.ButtonDown(Button_MoveUp))		cmd->ucmd.buttons |= BT_MOVEUP;
	if (buttonMap.ButtonDown(Button_ShowScores))	cmd->ucmd.buttons |= BT_SHOWSCORES;
	if (speed) cmd->ucmd.buttons |= BT_RUN;

	// Handle joysticks/game controllers.
	float joyaxes[NUM_JOYAXIS];

	I_GetAxes(joyaxes);

	// Remap some axes depending on button state.
	if (buttonMap.ButtonDown(Button_Strafe) || (buttonMap.ButtonDown(Button_Mlook) && lookstrafe))
	{
		joyaxes[JOYAXIS_Side] = joyaxes[JOYAXIS_Yaw];
		joyaxes[JOYAXIS_Yaw] = 0;
	}
	if (buttonMap.ButtonDown(Button_Mlook))
	{
		joyaxes[JOYAXIS_Pitch] = joyaxes[JOYAXIS_Forward];
		joyaxes[JOYAXIS_Forward] = 0;
	}

	if (joyaxes[JOYAXIS_Pitch] != 0)
	{
		G_AddViewPitch(joyint(joyaxes[JOYAXIS_Pitch] * 2048));
	}
	if (joyaxes[JOYAXIS_Yaw] != 0)
	{
		G_AddViewAngle(joyint(-1280 * joyaxes[JOYAXIS_Yaw]));
	}

	side -= joyint(sidemove[speed] * joyaxes[JOYAXIS_Side]);
	forward += joyint(joyaxes[JOYAXIS_Forward] * forwardmove[speed]);
	fly += joyint(joyaxes[JOYAXIS_Up] * 2048);

	// Handle mice.
	if (!buttonMap.ButtonDown(Button_Mlook) && !freelook)
	{
		forward += xs_CRoundToInt(mousey * m_forward);
	}

	cmd->ucmd.pitch = LocalViewPitch >> 16;

	if (SendLand)
	{
		SendLand = false;
		fly = -32768;
	}

	if (strafe || lookstrafe)
		side += xs_CRoundToInt(mousex * m_side);

	mousex = mousey = 0;

	// Build command.
	if (forward > MAXPLMOVE)
		forward = MAXPLMOVE;
	else if (forward < -MAXPLMOVE)
		forward = -MAXPLMOVE;
	if (side > MAXPLMOVE)
		side = MAXPLMOVE;
	else if (side < -MAXPLMOVE)
		side = -MAXPLMOVE;

	cmd->ucmd.forwardmove += forward;
	cmd->ucmd.sidemove += side;
	cmd->ucmd.yaw = LocalViewAngle >> 16;
	cmd->ucmd.upmove = fly;
	LocalViewAngle = 0;
	LocalViewPitch = 0;

	// special buttons
	if (sendturn180)
	{
		sendturn180 = false;
		cmd->ucmd.buttons |= BT_TURN180;
	}
	if (sendpause)
	{
		sendpause = false;
		Net_WriteByte (DEM_PAUSE);
	}
	if (sendsave)
	{
		sendsave = false;
		Net_WriteByte (DEM_SAVEGAME);
		Net_WriteString (savegamefile);
		Net_WriteString (savedescription);
		savegamefile = "";
	}
	if (SendItemUse == (const AActor *)1)
	{
		Net_WriteByte (DEM_INVUSEALL);
		SendItemUse = NULL;
	}
	else if (SendItemUse != NULL)
	{
		Net_WriteByte (DEM_INVUSE);


/*
*********************************************************************************************************
*                                              uC/TCP-IP
*                                      The Embedded TCP/IP Suite
*
*                    Copyright 2004-2021 Silicon Laboratories Inc. www.silabs.com
*
*                                 SPDX-License-Identifier: APACHE-2.0
*
*               This software is subject to an open source license and is distributed by
*                Silicon Laboratories Inc. pursuant to the terms of the Apache License,
*                    Version 2.0 available at www.apache.org/licenses/LICENSE-2.0.
*
*********************************************************************************************************
*/

/*
*********************************************************************************************************
*
*                                   NETWORK PHYSICAL LAYER DRIVER
*
*                                        GENERIC ETHERNET PHY
*
* Filename : net_phy_upd6061x.h
* Version  : V3.06.01
*********************************************************************************************************
* Note(s)  : (1) Assumes uC/TCP-IP V2.02 (or more recent version) is included in the project build.
*
*            (2) The (R)MII interface port is assumed to be part of the host EMAC.  Therefore, (R)MII
*                reads/writes MUST be performed through the network device API interface via calls to
*                function pointers 'Phy_RegRd()' & 'Phy_RegWr()'.
*
*            (3) Interrupt support is Phy specific, therefore the generic Phy driver does NOT support
*                interrupts.  However, interrupt support is easily added to the generic Phy driver &
*                thus the ISR handler has been prototyped and & populated within the function pointer
*                structure for example purposes.
*
*            (4) Does NOT support 1000Mbps Phy.
*********************************************************************************************************
*/

#include  <IF/net_if.h>
#include  <IF/net_if_ether.h>

/*
*********************************************************************************************************
*                                               MODULE
*
* Note(s) : (1) This network physical layer header file is protected from multiple pre-processor inclusion
*               through use of the network physical layer module present pre-processor macro definition.
*********************************************************************************************************
*/

#ifndef  NET_PHY_UPD6061X_MODULE_PRESENT                                 /* See Note #1.                                         */
#define  NET_PHY_UPD6061X_MODULE_PRESENT
#ifdef   NET_IF_ETHER_MODULE_EN

/**********************************************************************************************************************
 *                                          GLOBAL VARIABLES
 *********************************************************************************************************************/

extern  const  NET_PHY_API_ETHER  NetPhy_API_UPD6061X;

#endif  /* NET_IF_ETHER_MODULE_EN          */
#endif  /* NET_PHY_UPD6061X_MODULE_PRESENT */


oduleType < moduleTypes; ++curModuleType )
	{

		// how many modules are here for this type
		Module **m;
		UnsignedShort moduleCount = 0;
		for( m = m_modules[ curModuleType ]; m && *m; ++m )
			moduleCount++;
		xfer->xferUnsignedShort( &moduleCount );

		// xfer each module data
		if( xfer->getXferMode() == XFER_SAVE )
		{

			// save each module
			for( m = m_modules[ curModuleType ]; m && *m; ++m )
			{

				// write module identifier
				moduleIdentifier = TheNameKeyGenerator->keyToName( (*m)->getModuleTagNameKey() );
				DEBUG_ASSERTCRASH( moduleIdentifier != AsciiString::TheEmptyString,
													 ("Drawable::xferDrawableModules - module name key does not translate to a string!\n") );
				xfer->xferAsciiString( &moduleIdentifier );

				// begin data block
				xfer->beginBlock();

				// xfer data
				xfer->xferSnapshot( *m );

				// end data block
				xfer->endBlock();

			}  // end for, m

		}  // end if, save
		else
		{
			// read each module
			for( UnsignedShort j = 0; j < moduleCount; ++j )
			{

				// read module identifier
				xfer->xferAsciiString( &moduleIdentifier );
				NameKeyType moduleIdentifierKey = TheNameKeyGenerator->nameToKey(moduleIdentifier);

				// find module in the drawable module list
				Module* module = NULL;
				for( Module **m = m_modules[curModuleType]; m && *m; ++m )
				{
					if (moduleIdentifierKey == (*m)->getModuleTagNameKey())
					{

						module = *m;
						break;  // exit for m

					}  // end if

				}  // end for, m

				// new block of data
				Int dataSize = xfer->beginBlock();

				//
				// if we didn't find the module, it's quite possible that we have removed
				// it from the object definition in a future patch, if that is so, we need to
				// skip the module data in the file
				//
				if( module == NULL )
				{

					// for testing purposes, this module better be found
					DEBUG_CRASH(( "Drawable::xferDrawableModules - Module '%s' was indicated in file, but not found on Drawable %s %d\n",
												moduleIdentifier.str(), getTemplate()->getName().str(),getID() ));

					// skip this data in the file
					xfer->skip( dataSize );

				}  // end if
				else
				{

					// xfer the data into this module
					xfer->xferSnapshot( module );

				}  // end else

				// end of data block
				xfer->endBlock();

			}  // end for j

		}  // end else, load

	}  // end for curModuleType

}  // end xferDrawableModules

// ------------------------------------------------------------------------------------------------
/** Xfer method
	* Version Info;
	* 1: Initial version
	* 2: Moved condition state xfer before module xfer so we can restore anim frame
	*    during the module xfer (CBD)
	* 4: Added m_ambientSoundEnabled flag
	* 5: save full mtx, not pos+orient.
  * 6: Added m_ambientSoundEnabledFromScript flag
  * 7: Save the customize ambient sound info
	*/
// ------------------------------------------------------------------------------------------------
void Drawable::xfer( Xfer *xfer )
{

	// version
	const XferVersion currentVersion = 7;
	XferVersion version = currentVersion;
	xfer->xferVersion( &version, currentVersion );

	//Wow, because the constructor creates the ambient sound, the xfer can
	//change the ID the sound points to, therefore, we must remove it now
	//and restore it in loadPostProcess().
	if( xfer->getXferMode() == XFER_LOAD && m_ambientSound )
	{
		TheAudio->killAudioEventImmediately( m_ambientSound->m_event.getPlayingHandle() );
		m_ambientSound->deleteInstance();
		m_ambientSound = NULL;
	}

	// drawable id
	DrawableID id = getID();
	xfer->xferDrawableID( &id );
	setID( id );

	// condition state, note that when we're loading we need to force a replace of these flags
	if( version >= 2 )
	{

		m_conditionState.xfer( xfer );
		if( xfer->getXferMode() == XFER_LOAD	)
			replaceModelConditionFlags( m_conditionState,


```Bash
❯❯ du -cms .[^.]*/ */ | sort -rn | head
```

- On Linux, print out a list of the process IDs that are in the zombie state

```Bash
❯❯ ps aux | awk \'{if ($8=="Z") { print $2 }}\'
```

- Mount a CDROM disc from its ISO image file

```Bash
❯❯ dd if=/dev/cdrom of=image.iso ; mkdir CDroot ; mount -o loop image.iso CDroot ; cd CDroot
```

- 20 years ago IBM supercomputer Deep Blue defeats Garry Kasparov in chess for the first time

```Bash
❯❯ fliptable(){ echo "\xef\xbc\x88\xe2\x95\xaf\xc2\xb0\xe2\x96\xa1\xc2\xb0\xef\xbc\x89\xe2\x95\xaf \xe2\x94\xbb\xe2\x94\x81\xe2\x94\xbb"; }
```

- Write out 20 png format frames from a video starting at 3 minutes, 46 seconds

```Bash
❯❯ mplayer -vo png -ss 3:46 -frames 20 stairs.mp4
```

- Move photos with EXIF data to directories by year created/taken. Be verbose

```Bash
❯❯ exiftool -v '-Directory<DateTimeOriginal' -d %Y .
```

- Get list of top URLs from all logs combined

```Bash
❯❯ zcat access_log*.gz |cat - access_log |awk '{print $7}' |sed 's/\\?.*//' |sort|uniq -c|sort -nr
```

- xkcd https://t.co/qIAPXwY2Xj

```Bash
❯❯ These are your father's parentheses. Elegant decorations, for a birthday cake.
```

- A site that helps you build the find options you want to use and now several other common commands

```Bash
❯❯ https://t.co/OahUUpr12o
```

- Annoyed by wrapped lines in df output. Try -P to unwrap the lines and piping to column will align the columns

```Bash
❯❯ df -P | column -t
```

- Print disk space used on all ext3 or 4 FS in GiB

```Bash
❯❯ df -Pl -t ext3 -t ext4 | tail -n+2 | awk '{ sum+=$3 } END { print sum/2**20 }'
```

- $PS1

```Bash
❯❯ PS1=
```

- Compress files with xz in PWD according to size, starting with smallest

```Bash
❯❯ ls -Sr1 | while IFS=$\'\\n\' read -r file; do xz "$file"; done
```

- For Mar 22nd, print the req fields for hosts from two letter gTLD

```Bash
❯❯ fgrep 22/Mar/2015 access_log |awk \'$1~/\\.[a-z][a-z]$/{print $6 " " $7}\'
```

- "}; print $0 " " b;}

```Bash
❯❯ awk \'{print $4}\' apache_log|sort -n|cut -c1-15|uniq -c|awk \'{b="";for(i=0;i<$1/10;i++){b=b
```

- Imagine being able to run tail -f /dev/world (You can get the t command for twitter here: https://t.co/wa8QhYYAdE)

```Bash
❯❯ t matrix
```

- Do an instant replay on your Roku

```Bash
❯❯ curl -d "" http://YourRokuIP:8060/keypress/InstantReplay
```

- CLIMagic video: Epic demo of how I watched Superbowl 46 over a netcat stream

```Ba


; background: rgb(255, 255, 255);\">

<img data-v-ccdb1440=\"\" data-src=\"//cdn.cnbj1.fds.api.mi-img.com/mi-mall/59ce8a29a6


aitUninterruptibly()
        Launcher.instance.consoleSender.sendProperty("manager.service.start", wrapper.getName(), service.getName())
        this.serviceQueue.remove(service)
    }

    private fun getWrapperForService(service: ICloudService): IWrapperInfo? {
        if (service.getWrapperName() == null) {
            val wrapper = CloudAPI.instance.getWrapperManager().getWrapperByUnusedMemory(service.getMaxMemory())
            if (wrapper == null)
                this.warningMessageHandler.handleNotEnoughMemoryForService(service.getName())
            return wrapper
        } else {
            val requiredWrapper = CloudAPI.instance.getWrapperManager().getWrapperByName(service.getWrapperName()!!)
                ?: return null
            val hasEnoughMemory = requiredWrapper.hasEnoughMemory(service.getMaxMemory())
            if (!hasEnoughMemory) {
                this.warningMessageHandler.handleNotEnoughMemoryForService(service.getName())
            }
            if (hasEnoughMemory && requiredWrapper.isAuthenticated()
                && requiredWrapper.hasTemplatesReceived()
                && requiredWrapper.getCurrentlyStartingServices() != requiredWrapper.getMaxSimultaneouslyStartingServices()
            ) {
                return requiredWrapper
            }
            return null
        }
    }

    fun stopThread() {
        this.threadRunning = false
    }

}/*
 * MIT License
 *
 * Copyright (C) 2020-2022 The SimpleCloud authors
 *
 * 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.
 */

package eu.thesimplecloud.base.manager.update.converter

import eu.thesimplecloud.api.directorypaths.DirectoryPaths
import eu.thesimplecloud.jsonlib.JsonLib
import eu.thesimplecloud.launcher.startup.Launcher
import java.io.File

/**
 * Created by IntelliJ IDEA.
 * Date: 18.06.2020
 * Time: 12:38
 * @author Frederick Baier
 */
class VersionConversionManager {

    private val converters = listOf(
        Converter_2_0_To_2_1(),
        Converter_2_2_To_2_3(),
        Converter_2_3_To_2_4(),
        Converter_2_4_To_2_5(),
        Converter_2_6_To_2_7(),
        Converter_2_7_To_2_8()
    )

    private val lastStartedVersionFile = File(DirectoryPaths.paths.storagePath + "versions/lastStartedVersion.json")

    fun convertIfNecessary() {
        getConvertersToExecute().forEach { converter ->
            executeConverter(converter)
        }
        writeLastStartedVersion()
    }

    private fun executeConverter(converter: IVersionConverter) {
        Launcher.instance.logger.info("Running converter to version 2.${converter.getTargetMinorVersion()}...")
        try {
            converter.convert()
        } catch (e: Exception) {
            throw ConversionException(converter.getTargetMinorVersion(), e)
        }
        Launcher.instance.logger.info("Converted")
    }

    private fun getConvertersToExecute(): ArrayList<IVersionConverter> {
        val lastStartedVersion = getLastStartedVersion()


r := stmt.ColumnInt64(9)
			app.MustBe(ok)
			app.MustBeNil(err)
			articleId, ok, err := stmt.ColumnInt(10)
			app.MustBe(ok)
			app.MustBeNil(err)
			text, ok, err := stmt.ColumnText(11)
			app.MustBe(ok)
			app.MustBeNil(err)
			comment := app.NewComment(id, app.UnbindTime(created), articleId, text)
			_, found := commentIndexer[comment.Id]
			if !found {
				commentIndexer[comment.Id] = len(comments)
				comments = append(comments, comment)
			}
		}
		more, err = stmt.Step()
		app.MustBeNil(err)
	}
	err = stmt.Close()
	app.MustBeNil(err)
	return users, articles, comments
}

func (d *dbImpl) Close() {
	err := d.conn.Close()
	app.MustBeNil(err)
}
// Package main provides the HTTP server for the Go package analyzer.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"runtime/debug"
	"strings"
	"syscall"
	"time"

	"github.com/cvsouth/go-package-analyzer/internal/analyzer"
	"github.com/cvsouth/go-package-analyzer/internal/scanner"
	"github.com/cvsouth/go-package-analyzer/internal/visualizer"
)

// Server timeout constants.
const (
	serverReadTimeout       = 60 * time.Second  // HTTP server read timeout
	serverWriteTimeout      = 60 * time.Second  // HTTP server write timeout
	serverIdleTimeout       = 120 * time.Second // HTTP server idle timeout
	serverReadHeaderTimeout = 10 * time.Second  // HTTP server read header timeout
	serverMaxHeaderBytes    = 1 << 20           // HTTP server max header bytes (1 MB)
	serverShutdownTimeout   = 30 * time.Second  // Server graceful shutdown timeout
)

// APIResponse represents the response structure for the API.
type APIResponse struct {
	Success bool   `json:"success"`
	DOT     string `json:"dot,omitempty"`
	Error   string `json:"error,omitempty"`
}

// MultiEntryAPIResponse represents the response structure for multi-entry analysis.
type MultiEntryAPIResponse struct {
	Success     bool                  `json:"success"`
	EntryPoints []analyzer.EntryPoint `json:"entryPoints,omitempty"`
	Error       string                `json:"error,omitempty"`
	RepoRoot    string                `json:"repoRoot,omitempty"`
	ModuleName  string                `json:"moduleName,omitempty"`
}

func main() {
	port := os.Getenv("PORT")
	if port == "" {
		port = "6333"
	}

	server := &http.Server{
		Addr:              ":" + port,
		ReadTimeout:       serverReadTimeout,
		WriteTimeout:      serverWriteTimeout,
		IdleTimeout:       serverIdleTimeout,
		ReadHeaderTimeout: serverReadHeaderTimeout,
		MaxHeaderBytes:    serverMaxHeaderBytes,
	}

	mux := http.NewServeMux()

	mux.Handle("/", http.FileServer(http.Dir("./web/")))

	mux.HandleFunc("/api/analyze", handleAnalyze)
	mux.HandleFunc("/api/


color:#f6f6f6;background:rgba(0,0,0,0.1)}.skin-purple .main-header .navbar .sidebar-toggle{color:#fff}.skin-purple .main-header .navbar .sidebar-toggle:hover{background-color:#555299}@media (max-width:767px){.skin-purple .main-header .navbar .dropdown-menu li.divider{background-color:rgba(255,255,255,0.1)}.skin-purple .main-header .navbar .dropdown-menu li a{color:#fff}.skin-purple .main-header .navbar .dropdown-menu li a:hover{background:#555299}}.skin-purple .main-header .logo{background-color:#555299;color:#fff;border-bottom:0 solid transparent}.skin-purple .main-header .logo:hover{background-color:#545096}.skin-purple .main-header li.user-header{background-color:#605ca8}.skin-purple .content-header{background:transparent}.skin-purple .wrapper,.skin-purple .main-sidebar,.skin-purple .left-side{background-color:#222d32}.skin-purple .user-panel>.info,.skin-purple .user-panel>.info>a{color:#fff}.skin-purple .sidebar-menu>li.header{color:#4b646f;background:#1a2226}.skin-purple .sidebar-menu>li>a{border-left:3px solid transparent}.skin-purple .sidebar-menu>li:hover>a,.skin-purple .sidebar-menu>li.active>a{color:#fff;background:#1e282c;border-left-color:#605ca8}.skin-purple .sidebar-menu>li>.treeview-menu{margin:0 1px;background:#2c3b41}.skin-purple .sidebar a{color:#b8c7ce}.skin-purple .sidebar a:hover{text-decoration:none}.skin-purple .treeview-menu>li>a{color:#8aa4af}.skin-purple .treeview-menu>li.active>a,.skin-purple .treeview-menu>li>a:hover{color:#fff}.skin-purple .sidebar-form{border-radius:3px;border:1px solid #374850;margin:10px 10px}.skin-purple .sidebar-form input[type="text"],.skin-purple .sidebar-form .btn{box-shadow:none;background-color:#374850;border:1px solid transparent;height:35px;-webkit-transition:all .3s ease-in-out;-o-transition:all .3s ease-in-out;transition:all .3s ease-in-out}.skin-purple .sidebar-form input[type="text"]{color:#666;border-top-left-radius:2px;border-top-right-radius:0;border-bottom-right-radius:0;border-bottom-left-radius:2px}.skin-purple .sidebar-form input[type="text"]:focus,.skin-purple .sidebar-form input[type="text"]:focus+.input-group-btn .btn{background-color:#fff;color:#666}.skin-purple .sidebar-form input[type="text"]:focus+.input-group-btn .btn{border-left-color:#fff}.skin-purple .sidebar-form .btn{color:#999;border-top-left-radius:0;border-top-right-radius:2px;border-bottom-right-radius:2px;border-bottom-left-radius:0}/**
 * Any CSS included here will be global. The classic template
 * bundles Infima by default. Infima is a CSS framework designed to
 * work well for content-centric websites.
 */

/* You can override the default Infima variables here. */
:root {
  --ifm-color-primary: #2e8555;
  --ifm-color-primary-dark: #29784c;
  --ifm-co


�

* 通过dubbo完成扣减优惠券

```java
private void changeCoponStatus(TradeOrder order) {
    //判断用户是否使用优惠券
    if (!StringUtils.isEmpty(order.getCouponId())) {
        //封装优惠券对象
        TradeCoupon coupon = couponService.findOne(order.getCouponId());
        coupon.setIsUsed(ShopCode.SHOP_COUPON_ISUSED.getCode());
        coupon.setUsedTime(new Date());
        coupon.setOrderId(order.getOrderId());
        Result result = couponService.changeCouponStatus(coupon);
        //判断执行结果
        if (result.getSuccess().equals(ShopCode.SHOP_FAIL.getSuccess())) {
            //优惠券使用失败
            CastException.cast(ShopCode.SHOP_COUPON_USE_FAIL);
        }
        log.info("订单:["+order.getOrderId()+"]使用扣减优惠券["+coupon.getCouponPrice()+"元]成功");
    }

}
```

* 优惠券服务CouponService更改优惠券状态

```java
@Override
public Result changeCouponStatus(TradeCoupon coupon) {
    try {
        //判断请求参数是否合法
        if (coupon == null || StringUtils.isEmpty(coupon.getCouponId())) {
            CastException.cast(ShopCode.SHOP_REQUEST_PARAMETER_VALID);
        }
		//更新优惠券状态为已使用
        couponMapper.updateByPrimaryKey(coupon);
        return new Result(ShopCode.SHOP_SUCCESS.getSuccess(), ShopCode.SHOP_SUCCESS.getMessage());
    } catch (Exception e) {
        return new Result(ShopCode.SHOP_FAIL.getSuccess(), ShopCode.SHOP_FAIL.getMessage());
    }
}
```

###7）扣减用户余额

* 通过用户服务完成扣减余额

```java
private void reduceMoneyPaid(TradeOrder order) {
    //判断订单中使用的余额是否合法
    if (order.getMoneyPaid() != null && order.getMoneyPaid().compareTo(BigDecimal.ZERO) == 1) {
        TradeUserMoneyLog userMoneyLog = new TradeUserMoneyLog();
        userMoneyLog.setOrderId(order.getOrderId());
        userMoneyLog.setUserId(order.getUserId());
        userMoneyLog.setUseMoney(order.getMoneyPaid());
        userMoneyLog.setMoneyLogType(ShopCode.SHOP_USER_MONEY_PAID.getCode());
        //扣减余额
        Result result = userService.changeUserMoney(userMoneyLog);
        if (result.getSuccess().equals(ShopCode.SHOP_FAIL.getSuccess())) {
            CastException.cast(ShopCode.SHOP_USER_MONEY_REDUCE_FAIL);
        }
        log.info("订单:["+order.getOrderId()+"扣减余额["+order.getMoneyPaid()+"元]成功]");
    }
}
```

* 用户服务UserService,更新余额

![](doc/img/更改用户余额.png)

```java
@Override
public Result changeUserMoney(TradeUserMoneyLog userMoneyLog) {
    //判断请求参数是否合法
    if (userMoneyLog == null
            || userMoneyLog.getUserId() == null
            || userMoneyLog.getUseMoney() == null
            || userMoneyLog.getOrderId() == null
            || userMoneyLog.getUseMoney().compareTo(BigDecimal.ZERO)


ound_trigger_phrase_recognition_event) */
};

/*
 * Confidence level for each user in struct sound_trigger_phrase_recognition_extra
 */
struct sound_trigger_confidence_level {
    unsigned int user_id;   /* user ID */
    unsigned int level;     /* confidence level in percent (0 - 100).
                               - min level for recognition configuration
                               - detected level for recognition event */
};

/*
 * Specialized recognition event for key phrase detection
 */
struct sound_trigger_phrase_recognition_extra {
    unsigned int id;                /* keyphrase ID */
    unsigned int recognition_modes; /* recognition modes used for this keyphrase */
    unsigned int confidence_level;  /* confidence level for mode RECOGNITION_MODE_VOICE_TRIGGER */
    unsigned int num_levels;        /* number of user confidence levels */
    struct sound_trigger_confidence_level levels[SOUND_TRIGGER_MAX_USERS];
};

struct sound_trigger_phrase_recognition_event {
    struct sound_trigger_recognition_event common;
    unsigned int                           num_phrases;
    struct sound_trigger_phrase_recognition_extra phrase_extras[SOUND_TRIGGER_MAX_PHRASES];
};

/*
 * configuration for sound trigger capture session passed to start_recognition()
 */
struct sound_trigger_recognition_config {
    audio_io_handle_t    capture_handle;    /* IO handle that will be used for capture.
                                            N/A if capture_requested is false */
    audio_devices_t      capture_device;    /* input device requested for detection capture */
    bool                 capture_requested; /* capture and buffer audio for this recognition
                                            instance */
    unsigned int         num_phrases;   /* number of key phrases recognition extras */
    struct sound_trigger_phrase_recognition_extra phrases[SOUND_TRIGGER_MAX_PHRASES];
                                           /* configuration for each key phrase */
    unsigned int        data_size;         /* size of opaque capture configuration data */
    unsigned int        data_offset;       /* offset of opaque data start from start of this struct
                                           (e.g sizeof struct sound_trigger_recognition_config) */
};

/*
 * Event sent via load sound model callback
 */
struct sound_trigger_model_event {
    int                  status;      /* sound model status e.g. SOUND_MODEL_STATUS_UPDATED */
    sound_model_handle_t model;       /* loaded sound model that triggered the event */
    unsigned int         data_size;   /* size of event data if any. Size of updated sound model if
                                       status is SOUND_MODEL_STATUS_UPDATED */
    unsigned int         data_offset; /* offset of data start from start of this struct
                                       (e.g sizeof struct sound_trigger_model_event) */
};

#endif  // ANDROID_SOUND_TRIGGER_H


           JoseHeader.fromJson({'kid': 'key1', 'alg': 'A128KW'}), 'sign')
              .first;

          expect(key?.keyType, 'oct');
          expect(key?.algorithm, 'A128KW');

          key = await store
              .findJsonWebKeys(
                  JoseHeader.fromJson({'kid': 'key1', 'alg': 'A128KW'}), 'sign')
              .first;
        }, loader: DefaultJsonWebKeySetLoader(httpClient: client));
      });
    });

    test("Example Use of 'x5c' (X.509 Certificate Chain) Parameter", () {
      var json = {
        'kty': 'RSA',
        'use': 'sig',
        'kid': '1b94c',
        'n': 'vrjOfz9Ccdgx5nQudyhdoR17V-IubWMeOZCwX_jj0hgAsz2J_pqYW08'
            'PLbK_PdiVGKPrqzmDIsLI7sA25VEnHU1uCLNwBuUiCO11_-7dYbsr4iJmG0Q'
            'u2j8DsVyT1azpJC_NG84Ty5KKthuCaPod7iI7w0LK9orSMhBEwwZDCxTWq4a'
            'YWAchc8t-emd9qOvWtVMDC2BXksRngh6X5bUYLy6AyHKvj-nUy1wgzjYQDwH'
            'MTplCoLtU-o-8SNnZ1tmRoGE9uJkBLdh5gFENabWnU5m1ZqZPdwS-qo-meMv'
            'VfJb6jJVWRpl2SUtCnYG2C32qvbWbjZ_jBPD5eunqsIo1vQ',
        'e': 'AQAB',
        'x5c': [
          'MIIDQjCCAiqgAwIBAgIGATz/FuLiMA0GCSqGSIb3DQEBBQUAMGIxCzAJB'
              'gNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYD'
              'VQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1'
              'wYmVsbDAeFw0xMzAyMjEyMzI5MTVaFw0xODA4MTQyMjI5MTVaMGIxCzAJBg'
              'NVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDV'
              'QQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1w'
              'YmVsbDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL64zn8/QnH'
              'YMeZ0LncoXaEde1fiLm1jHjmQsF/449IYALM9if6amFtPDy2yvz3YlRij66'
              's5gyLCyO7ANuVRJx1NbgizcAblIgjtdf/u3WG7K+IiZhtELto/A7Fck9Ws6'
              'SQvzRvOE8uSirYbgmj6He4iO8NCyvaK0jIQRMMGQwsU1quGmFgHIXPLfnpn'
              'fajr1rVTAwtgV5LEZ4Iel+W1GC8ugMhyr4/p1MtcIM42EA8BzE6ZQqC7VPq'
              'PvEjZ2dbZkaBhPbiZAS3YeYBRDWm1p1OZtWamT3cEvqqPpnjL1XyW+oyVVk'
              'aZdklLQp2Btgt9qr21m42f4wTw+Xrp6rCKNb0CAwEAATANBgkqhkiG9w0BA'
              'QUFAAOCAQEAh8zGlfSlcI0o3rYDPBB07aXNswb4ECNIKG0CETTUxmXl9KUL'
              '+9gGlqCz5iWLOgWsnrcKcY0vXPG9J1r9AqBNTqNgHq2G03X09266X5CpOe1'
              'zFo+Owb1zxtp3PehFdfQJ610CDLEa


ith(): RetrofitUtils {
        val client = unsafeOkHttpClient
        retrofit = Retrofit.Builder()
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(Constant.BASE_URL)
                .build()
        return this
    }

    internal class LogInterceptor : Interceptor {

        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val request = chain.request()
            val startTime = System.currentTimeMillis()
            val response = chain.proceed(chain.request())
            val endTime = System.currentTimeMillis()
            val duration = endTime - startTime
            val mediaType = response.body()!!.contentType()
            val content = response.body()!!.string()
            Log.d(TAG, "\n")
            Log.d(TAG, "\n")
            Log.d(TAG, "----------Start----------------")
            Log.d(TAG, "| " + request.toString())
            val headers = request.headers()
            Log.d(TAG, "| RequestHeaders:{" + headers.toString() + "}")
            val method = request.method()
            if ("POST" == method) {
                val sb = StringBuilder()
                if (request.body() is FormBody) {
                    val body = request.body() as FormBody?
                    for (i in 0 until body!!.size()) {
                        val str = URLDecoder.decode(body.encodedValue(i), "utf-8")
                        if (isNumeric(str)) {
                            sb.append("\"" + body.encodedName(i) + "\"" + ":" + str + ",")
                        } else {
                            sb.append("\"" + body.encodedName(i) + "\"" + ":" + "\"" + str + "\"" + ",")
                        }
                    }
                    sb.delete(sb.length - 1, sb.length)
                    Log.d(TAG, "| RequestParams:{" + sb.toString() + "}")
                }
            }
            Log.d(TAG, "| Response:" + content)
            Log.d(TAG, "----------End:" + duration + "毫秒----------")
            Log.d(TAG, "\n")
            Log.d(TAG, "\n")
            return response.newBuilder()
                    .body(okhttp3.ResponseBody.create(mediaType, content))
                    .build()
        }

        companion object {
            var TAG = "LogInterceptor"
        }
    }

    fun build(): Service = retrofit!!.create(Service::class.java)

    companion object {
        private var retrofit: Retrofit? = null

        fun isNumeric(cs: CharSequence): Boolean {
            if (TextUtils.isEmpty(cs)) {
                return false
            }
            val sz = cs.length
            return (0 until sz).any { Character.isDigit(cs[it]) }
        }
    }
}
package com.moment.eyepetizer.home

import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.util.Log
import com.moment.eyepetizer.R
import com.moment.eyepetizer.base.BaseFragment
import com.moment.eyepetizer.net.entity.Result
import com.moment.eyepetizer.utils.UriUtils
import com.scwang.smartrefresh.layout.footer.ClassicsFooter
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import kotlinx.android.synthetic.main.ranklist_fragment.*
import com.bumptech.glide.Glide
import com.moment.eyepetizer.home.adapter.MyMultiTypeAdapter
import com.moment.eyepetizer.home.mvp.RankListDetailContract
import com.moment.eyepetizer.home.mvp.RankListDetailPresenter
import com.scwang.smartrefresh.layout.api.RefreshHeader
import kotlinx.android.synthetic.*

/**
 * Created by moment on 2018/2/2.
 */

class RankListFragment(path


.fromIcarus(
      {required CardanoIcarusBip32 bip32,
      ADANetwork network = ADANetwork.mainnet}) {
    final credential =
        AdaAddressUtils.publicKeyToCredential(bip32.publicKey.compressed);
    final encode = AdaShelleyEnterpriseAddrEncoder().encodeCredential(
        AdaAddressUtils.toAdaStakeCredential(credential), {'net_tag': network});
    return ADAEnterpriseAddress._(
        paymentCredential: credential, address: encode, network: network);
  }
  factory ADAEnterpriseAddress.fromCip1852(
      {required Cip1852 cip1852, ADANetwork network = ADANetwork.mainnet}) {
    final credential =
        AdaAddressUtils.publicKeyToCredential(cip1852.publicKey.compressed);
    final encode = AdaShelleyEnterpriseAddrEncoder().encodeCredential(
        AdaAddressUtils.toAdaStakeCredential(credential), {'net_tag': network});
    return ADAEnterpriseAddress._(
        paymentCredential: credential, address: encode, network: network);
  }
}
export 'certificates/stake_delegation.dart';
export 'certificates/stake_deregistration.dart';
export 'certificates/stake_registration.dart';
export 'certificates/genesis_key_delegation.dart';
export 'certificates/move_instantaneous_rewards_cert.dart';
export 'certificates/pool_registration.dart';
export 'certificates/pool_retirement.dart';
export 'certificates/committee_cold_resign.dart';
export 'certificates/committee_hot_auth.dart';
export 'certificates/drep_deregistration.dart';
export 'certificates/drep_registration.dart';
export 'certificates/drep_update.dart';
export 'certificates/vote_delegation.dart';
export 'certificates/vote_registration_and_delegation.dart';
export 'certificates/stake_vote_registration_and_delegation.dart';
export 'certificates/stake_registration_conway.dart';
export 'certificates/stake_and_vote_delegation.dart';
export 'certificates/stake_deregistration_conway.dart';
export 'certificates/stake_registration_and_delegation.dart';
export 'certificates/certificate.dart';
export 'certificates/certificates.dart';
export 'certificates/types.dart';
export 'certificates/move_instantaneous_reward/mir.dart';
export 'certificates/pool/pool.dart';
import 'package:blockchain_utils/cbor/cbor.dart';
import 'package:on_chain/ada/src/serialization/cbor_serialization.dart';
import 'package:on_chain/ada/src/models/fixed_bytes/models/models.dart';

class OperationalCert with ADASerialization {
  final KESVKey hotVkey;
  final int sequenceNumber;
  final int kesPeriod;
  final Ed25519Signature sigma;
  factory OperationalCert.fromJson(Map<String, dynamic> json) {
    return OperationalCert(
      hotVkey: KESVKey.fromHex(json['hot_vkey']),
      sequenceNumber: json['sequence_number'],
      kesPeriod: json['kes_period'],
      sigma: Ed25519Signature.fromHex(json['sigma']),
    );
  }

  const OperationalCert(
      {required this.hotVkey,
      required this.sequenceNumber,
      required this.kesPeriod,
      required this.sigma});
  factory OperationalCert.deserialize(CborListValue cbor) {
    return OperationalCert(
        hotVkey: KESVKey.deserialize(cbor.elementAt<CborBytesValue>(0)),
        sequenceNumber: cbor.elementAt<CborIntValue>(1).value,
        kesPeriod: cbor.elementAt<C