Limit(quantity.SizeGiB).Build())
	c.Assert(err, IsNil)

	subgrp1, err := grp1.NewSubGroup("cpu-sub", quota.NewResourcesBuilder().WithCPUCount(2).WithCPUPercentage(50).Build())
	c.Assert(err, IsNil)

	_, err = grp1.NewSubGroup("thread-sub", quota.NewResourcesBuilder().WithThreadLimit(32).Build())
	c.Check(err, IsNil)

	_, err = grp1.NewSubGroup("cpus-sub", quota.NewResourcesBuilder().WithCPUSet([]int{0, 1}).Build())
	c.Check(err, IsNil)

	// Now we have the root with a memory limit, and three subgroups with
	// each with one of the remaining limits. The point of this test is to make
	// sure nested cases of limits that don't fit are caught and reported. So in a
	// sub-sub group we create a limit higher than the upper parent
	_, err = subgrp1.NewSubGroup("mem-sub", quota.NewResourcesBuilder().WithMemoryLimit(quantity.SizeGiB*2).Build())
	c.Check(err, ErrorMatches, `sub-group memory limit of 2 GiB is too large to fit inside group \"groot\" remaining quota space 1 GiB`)
}

func (ts *quotaTestSuite) TestNestingOfLimitsWithExceedingSiblings(c *C) {
	grp1, err := quota.NewGroup("groot", quota.NewResourcesBuilder().WithMemoryLimit(quantity.SizeGiB).Build())
	c.Assert(err, IsNil)

	subgrp1, err := grp1.NewSubGroup("cpu-sub", quota.NewResourcesBuilder().WithCPUCount(2).WithCPUPercentage(50).Build())
	c.Assert(err, IsNil)

	_, err = grp1.NewSubGroup("thread-sub", quota.NewResourcesBuilder().WithThreadLimit(32).Build())
	c.Check(err, IsNil)

	subgrp2, err := grp1.NewSubGroup("cpus-sub", quota.NewResourcesBuilder().WithCPUSet([]int{0, 1}).Build())
	c.Check(err, IsNil)

	// The point here is to catch if we, in a nested, scenario, together with our siblings
	// exceed one of the parent's limits.
	subgrp3, err := subgrp1.NewSubGroup("mem-sub1", quota.NewResourcesBuilder().WithMemoryLimit(quantity.SizeGiB).Build())
	c.Assert(err, IsNil)

	_, err = subgrp3.NewSubGroup("mem-sub-sub", quota.NewResourcesBuilder().WithMemoryLimit(quantity.SizeGiB).Build())
	c.Check(err, IsNil)

	// now we have consumed the entire memory quota set by the parent, so this should fail
	_, err = subgrp2.NewSubGroup("mem-sub2", quota.NewResourcesBuilder().WithMemoryLimit(quantity.SizeGiB).Build())
	c.Check(err, ErrorMatches, `sub-group memory limit of 1 GiB is too large to fit inside group \"groot\" remaining quota space 0 B`)
}

func (ts *quotaTestSuite) TestChangingSubgroupLimits(c *C) {
	grp1, err := quota.NewGroup("groot", quota.NewResourcesBuilder().WithMemoryLimit(quantity.SizeGiB).Build())
	c.Assert(err, IsNil)

	subgrp1, err := grp1.NewSubGroup("cpu-sub", quota.NewResourcesBuilder().WithCPUCount(2).WithCPUPercentage(50).Build())
	c.Assert(err, IsNil)

	// Create a nested subgroup with a memory limit of only half, then we try to adjust the value to another
	// larger value. This must succeed.
	memgrp, err := subgrp1.NewSubGroup("mem-sub", quota.NewResourcesBuilder().WithMemoryLimit(quantity.SizeGiB/2).Build())
	c.Assert(err, IsNil)

	// Now we change it to


naco.languages.IResourceEdit = {
                        resource: model.uri,
                        newText: textEdit.text,
                        range: modelRange
                    }

                    result.edits.push(resourceEdit);
                }
            }
        }

        return result;
    })
}

/**
 * Initializes the module.
 * @param monacoEngine
 * @param languageIdentifier
 */
export function init(monacoEngine : typeof monaco, languageIdentifier: string) {
    monacoEngine.languages.registerRenameProvider(languageIdentifier, {
        provideRenameEdits: function(
            model: monaco.editor.IReadOnlyModel, position: monaco.Position,
            newName: string, token: monaco.CancellationToken) {

            return rename(model, position, newName)
        }
    });

}import test from 'tape';
import { Log } from '../src/index';

test('log - should log to info', t => {
	const oldStdout = process.stdout.write;
	const log = new Log();

	let outputMsg = '';

	// @ts-ignore: This works well, and is only for test purposes
	process.stdout.write = msg => outputMsg = msg;

	log.info('flurp');

	process.stdout.write = oldStdout;

	t.equal(
		outputMsg.substring(19),
		'Z [\u001b[1;32minf\u001b[0m] flurp\n',
		'Should detect "flurp" in the output of the inf log',
	);

	t.end();
});

test('log - should log to error', t => {
	const oldStderr = process.stderr.write;
	const log = new Log();

	let outputMsg = '';

	// @ts-ignore: This works well, and is only for test purposes
	process.stderr.write = msg => outputMsg = msg;

	log.error('burp');

	process.stderr.write = oldStderr;

	t.equal(
		outputMsg.substring(19),
		'Z [\u001b[1;31merr\u001b[0m] burp\n',
		'Should detect "burp" in the output of the err log',
	);

	t.end();
});

test('log - should not print debug by default', t => {
	const oldStdout = process.stdout.write;
	const log = new Log();

	let outputMsg = 'yay';

	// @ts-ignore: This works well, and is only for test purposes
	process.stdout.write = msg => outputMsg = msg;

	log.debug('nai');

	process.stdout.write = oldStdout;

	t.equal(outputMsg, 'yay', 'Should get "yay" since the outputMsg should not be replaced');

	t.end();
});

test('log - should print debug when given "silly" as level', t => {
	const oldStdout = process.stdout.write;
	const log = new Log('silly');

	let outputMsg = 'woof';

	// @ts-ignore: This works well, and is only for test purposes
	process.stdout.write = msg => outputMsg = msg;

	log.debug('wapp');

	process.stdout.write = oldStdout;

	t.equal(outputMsg.substring(19), 'Z [\u001b[1;35mdeb\u001b[0m] wapp\n', 'Should obtain "wapp" from the deb log');

	t.end();
});

test('log - Use environment variable as default log level', t => {
	const oldEnv = process.env.NODE_LOG_LVL;
	const oldStdout = process.stdout.write;
	let outputMsg = 'fail';

	process.env.NODE_LOG_LVL = 'debug';

	const log = new Log();

	// @ts-ignore: This works well, and is only for test purposes
	process.stdout.write = msg => outputMsg = msg;

	log.debug('tepp');

	process.stdout.write = oldStdout;

	process.env.NODE_LOG_LVL = oldEnv;

	t.equal(outputMsg.substring(19), 'Z [\u001b[1;35mdeb\u001b[0m] tepp\n', 'Should get "tepp" from the deb log');

	t.end();
});

test('log - Print nothing, even on error, when no valid lvl is set', t => {
	const oldStderr = process


 io } = require('socket.io-client');
const axios = require('axios');

// 配置
const SERVER_URL = 'http://192.168.18.5:5051';
const INTERVAL = 's30';

let currentMint = null;
let socket = null;

console.log('🚀 启动自动 mint 监听...');
console.log(`📍 服务器地址: ${SERVER_URL}`);
console.log(`⏰ 监听间隔: ${INTERVAL}`);

// 获取最新的 mint 地址
async function getLatestMint() {
    try {
        console.log('\n📡 正在获取最新的 mint 地址...');

        const response = await axios.get(`${SERVER_URL}/api/mints`, {
            headers: {
                'accept': 'application/json'
            }
        });

        if (response.data.success && response.data.data.mints.length > 0) {
            const latestMint = response.data.data.mints[0];
            console.log(`✅ 获取到最新 mint: ${latestMint}`);
            console.log(`📊 总共找到 ${response.data.data.mints.length} 个 mint`);
            return latestMint;
        } else {
            throw new Error('未找到可用的 mint 地址');
        }
    } catch (error) {
        console.error('❌ 获取 mint 地址失败:', error.message);
        if (error.response) {
            console.error('响应状态:', error.response.status);
            console.error('响应数据:', error.response.data);
        }
        return null;
    }
}

// 连接 WebSocket 并监听行情
function connectAndSubscribe(mint) {
    console.log(`\n🔌 连接 WebSocket 并监听 ${mint} 的行情...`);

    // 创建 Socket.IO 客户端 - 连接到 /kline 命名空间
    socket = io(`${SERVER_URL}/kline`, {
        transports: ['websocket', 'polling'],
        timeout: 20000,
        reconnection: true,
        reconnectionAttempts: 10,
        reconnectionDelay: 2000,
    });

    // 连接事件监听
    socket.on('connect', () => {
        console.log('✅ WebSocket 连接成功');
        console.log(`🔌 Socket ID: ${socket.id}`);

        // 等待连接稳定后订阅
        setTimeout(() => {
            subscribeKline(mint);
        }, 1000);
    });

    socket.on('disconnect', (reason) => {
        console.log(`❌ 连接断开: ${reason}`);
        console.log('🔄 等待重连...');
    });

    socket.on('connect_error', (error) => {
        console.log(`💥 连接错误: ${error.message}`);
    });

    // 接收服务器消息
    socket.on('connection_success', (data) => {
        console.log('🎉 收到连接成功消息:', JSON.stringify(data, null, 2));
    });

    socket.on('subscription_confirmed', (data) => {
        console.log('✅ 订阅确认:', JSON.stringify(data, null, 2));
    });

    socket.on('history_data', (data) => {
        if (data.interval === INTERVAL) {
            console.log(`📈 历史数据:`, {
                symbol: data.symbol,
                interval: data.interval,
                dataPoints: data.data.length,
                hasMore: data.has_more,
                totalCount: data.total_count
            });

            if (data.data.length > 0) {
                console.log('   最新K线:', data.data[0]);
            }
        }
    });

    socket.on('kline_data', (data) =>


 explicit type declarations where easily inferrable", () => {
        const createFailure = (start: number[], end: number[], type: string) => {
            const failureString = Rule.FAILURE_STRING_FACTORY(type);
            return Lint.Test.createFailure(fileName, start, end, failureString);
        };

        const expectedFailures = [
            createFailure([2, 8], [2, 14], "number"),
            createFailure([3, 8], [3, 15], "boolean"),
            createFailure([4, 8], [4, 14], "string"),
            createFailure([7, 18], [7, 24], "number"),
            createFailure([7, 33], [7, 40], "boolean"),
            createFailure([7, 52], [7, 58], "string")
        ];
        const actualFailures = Lint.Test.applyRuleOnFile(fileName, Rule);
        Lint.Test.assertFailuresEqual(actualFailures, expectedFailures);
    });
});
import * as ganache from 'ganache-cli'
import Web3 from 'web3'
import { Contract } from '../../../node_modules/web3/types.d'
import { Token } from '../../../src/constants'
import { deployToken } from '../helpers'

// TODO use the web3 IProvider?
const provider:any = ganache.provider(),
  web3 = new Web3(provider)

let accounts:string[], eip20:Contract

describe('EIP20 Token', () => {
  beforeEach(async () => {
    accounts = await web3.eth.getAccounts()

    eip20 = await deployToken(web3, accounts[0])
    eip20.setProvider(provider)
  })

  describe('Creation', () => {
    it('has a network address', async () => {
      const where = eip20.options.address
      expect(where).toBeTruthy()
    })

    it('gives initial balance to owner', async () => {
      const bal = await eip20.methods.balanceOf(accounts[0]).call()
      expect(parseInt(bal)).toBe(5000000)
    })

    it('sets vanity information correctly', async () => {
      const name = await eip20.methods.name().call(),
        sym = await eip20.methods.symbol().call(),
        decimals = await eip20.methods.decimals().call()

      expect(name).toBe(Token.name)
      expect(sym).toBe(Token.symbol)
      expect(parseInt(decimals)).toBe(Token.decimals)
    })
  })

  describe('Transfers', () => {
    it('transfers to another account', async () => {
      // spy on the event -- TODO when a fix for the web3 error is up...
      // const spy = { onTransfer: function(data) {} },
      // transferSpy = spyOn(spy, 'onTransfer').andCallThrough()
      // eip20.events.Transfer().on('data', spy.onTransfer)

      const result = await eip20.methods.transfer(accounts[1], 5000).send({ from: accounts[0] })
      expect(result.status).toBe(true)
      const senderBal = await eip20.methods.balanceOf(accounts[0]).call()
      expect(parseInt(senderBal)).toBe(4995000)
      const recieverBal = await eip20.methods.balanceOf(accounts[1]).call()
      expect(parseInt(recieverBal)).toBe(5000)
      // expect(transferSpy).toHaveBeenCalled()
    })
  })

  describe('Approvals', () => {
    it('sender approves account[1] for 1000', async () => {
      await eip20.methods.approve(accounts[1], 1000).send({ from: accounts[0] })
      const allowan


kImageWidth, kImageHeight, YCbCr_420);
    ASSERT_TRUE(rawImg2420.setImageColorGamut(mYuv420ColorGamut));
    ASSERT_TRUE(rawImg2420.setImageStride(kImageWidth + 46, kImageWidth / 2 + 34));
    ASSERT_TRUE(rawImg2420.setChromaMode(false));
    ASSERT_TRUE(rawImg2420.allocateMemory());
    ASSERT_TRUE(rawImg2420.loadRawResource(kYCbCr420FileName));
    UhdrCompressedStructWrapper jpgImg2(kImageWidth, kImageHeight);
    ASSERT_TRUE(jpgImg2.allocateMemory());
    ASSERT_EQ(uHdrLib.encodeJPEGR(rawImgP010.getImageHandle(), rawImg2420.getImageHandle(),
                                  ultrahdr_transfer_function::ULTRAHDR_TF_HLG,
                                  jpgImg2.getImageHandle(), kQuality, nullptr),
              JPEGR_NO_ERROR);
    auto jpg1 = jpgImg.getImageHandle();
    auto jpg2 = jpgImg2.getImageHandle();
    ASSERT_EQ(jpg1->length, jpg2->length);
    ASSERT_EQ(0, memcmp(jpg1->data, jpg2->data, jpg1->length));

    uhdr_codec_private_t* obj = uhdr_create_encoder();
    uhdr_raw_image_t uhdrRawImg{};
    uhdrRawImg.fmt = UHDR_IMG_FMT_24bppYCbCrP010;
    uhdrRawImg.cg = map_internal_cg_to_cg(mP010ColorGamut);
    uhdrRawImg.ct = map_internal_ct_to_ct(ultrahdr_transfer_function::ULTRAHDR_TF_HLG);
    uhdrRawImg.range = UHDR_CR_LIMITED_RANGE;
    uhdrRawImg.w = kImageWidth;
    uhdrRawImg.h = kImageHeight;
    uhdrRawImg.planes[UHDR_PLANE_Y] = rawImgP010.getImageHandle()->data;
    uhdrRawImg.stride[UHDR_PLANE_Y] = kImageWidth;
    uhdrRawImg.planes[UHDR_PLANE_UV] =
        ((uint8_t*)(rawImgP010.getImageHandle()->data)) + kImageWidth * kImageHeight * 2;
    uhdrRawImg.stride[UHDR_PLANE_UV] = kImageWidth;
    uhdr_error_info_t status = uhdr_enc_set_raw_image(obj, &uhdrRawImg, UHDR_HDR_IMG);
    ASSERT_EQ(UHDR_CODEC_OK, status.error_code) << status.detail;

    uhdrRawImg.fmt = UHDR_IMG_FMT_12bppYCbCr420;
    uhdrRawImg.cg = map_internal_cg_to_cg(mYuv420ColorGamut);
    uhdrRawImg.ct = map_internal_ct_to_ct(ultrahdr_transfer_function::ULTRAHDR_TF_SRGB);
    uhdrRawImg.range = UHDR_CR_FULL_RANGE;
    uhdrRawImg.w = kImageWidth;
    uhdrRawImg.h = kImageHeight;
    uhdrRawImg.planes[UHDR_PLANE_Y] = rawImg2420.getImageHandle()->data;
    uhdrRawImg.stride[UHDR_PLANE_Y] = rawImg2420.getImageHandle()->luma_stride;
    uhdrRawImg.planes[UHDR_PLANE_U] = rawImg2420.getImageHandle()->chroma_data;
    uhdrRawImg.stride[UHDR_PLANE_U] = rawImg2420.getImageHandle()->chroma_stride;
    uhdrRawImg.planes[UHDR_PLANE_V] = ((uint8_t*)(rawImg2420.getImageHandle()->chroma_data)) +
                                      rawImg2420.getImageHandle()->chroma_stride * kImageHeight / 2;
    uhdrRawImg.stride[UHDR_PLANE_V] = rawImg2420.getImageHandle()->chroma_stride;
    status = uhdr_enc_set_raw_image(obj, &uhdrRawImg, UHDR_SDR_


 := genericapirequest.UserFrom(ctx)
			if user == nil || !ok {
				t.Errorf("no user stored in context: %#v", ctx)
			}
			if req.Header.Get("Authorization") != "" {
				t.Errorf("Authorization header should be removed from request on success: %#v", req)
			}
			close(success)
		}),
		authenticator.RequestFunc(func(req *http.Request) (*authenticator.Response, bool, error) {
			if req.Header.Get("Authorization") == "Something" {
				return &authenticator.Response{User: &user.DefaultInfo{Name: "user"}}, true, nil
			}
			return nil, false, errors.New("Authorization header is missing.")
		}),
		http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
			t.Errorf("unexpected call to failed")
		}),
		nil,
	)

	auth.ServeHTTP(httptest.NewRecorder(), &http.Request{Header: map[string][]string{"Authorization": {"Something"}}})

	<-success
}

func TestAuthenticateRequestFailed(t *testing.T) {
	failed := make(chan struct{})
	auth := WithAuthentication(
		http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
			t.Errorf("unexpected call to handler")
		}),
		authenticator.RequestFunc(func(req *http.Request) (*authenticator.Response, bool, error) {
			return nil, false, nil
		}),
		http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
			close(failed)
		}),
		nil,
	)

	auth.ServeHTTP(httptest.NewRecorder(), &http.Request{})

	<-failed
}

func TestAuthenticateRequestError(t *testing.T) {
	failed := make(chan struct{})
	auth := WithAuthentication(
		http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
			t.Errorf("unexpected call to handler")
		}),
		authenticator.RequestFunc(func(req *http.Request) (*authenticator.Response, bool, error) {
			return nil, false, errors.New("failure")
		}),
		http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
			close(failed)
		}),
		nil,
	)

	auth.ServeHTTP(httptest.NewRecorder(), &http.Request{})

	<-failed
}
/*
Copyright 2015 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package negotiation

import (
	"mime"
	"net/http"
	"strconv"
	"strings"

	"github.com/munnerz/goautoneg"

	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

// MediaTypesForSerializer returns a list of media and stream media types for the server.
func MediaTypesForSerializer(ns runtime.NegotiatedSerializer) (mediaTypes, streamMediaTypes []string) {
	for _, info := range ns.SupportedMediaTypes() {
		mediaTypes = append(mediaTypes, info.MediaType)
		if info.StreamSerializer != nil {
			// stream=watch is the existing mime-type parameter for watch
			streamMediaTypes = append(streamMediaTypes, info.MediaType+";stream=watch")
		}
	}
	return mediaTypes, streamMediaTypes
}

// NegotiateOutputMediaType negotiates the output structured media type and a serializer, or
// returns an error.
func NegotiateOutputMediaType(req *http.Request, ns runtime.NegotiatedSerializer, restrictions EndpointRestrictions) (MediaTypeOptions, runtime.S


//
//  OCHamcrest - HCOrderingComparison.h
//  Copyright 2011 hamcrest.org. See LICENSE.txt
//
//  Created by: Jon Reid
//

#import <OCHamcrestIOS/HCBaseMatcher.h>

@interface HCOrderingComparison : HCBaseMatcher
{
    id expected;
    NSComparisonResult minCompare;
    NSComparisonResult maxCompare;
    NSString *comparisonDescription;
}

+ (id)compare:(id)expectedValue
   minCompare:(NSComparisonResult)min
   maxCompare:(NSComparisonResult)max
   comparisonDescription:(NSString *)comparisonDescription;

- (id)initComparing:(id)expectedValue
         minCompare:(NSComparisonResult)min
         maxCompare:(NSComparisonResult)max
         comparisonDescription:(NSString *)comparisonDescription;

@end

#pragma mark -

/**
    Is value > expected?

    @b Synonym: @ref greaterThan
    @ingroup number_matchers
 */
OBJC_EXPORT id<HCMatcher> HC_greaterThan(id expected);

/**
    greaterThan(expected) -
    Is value > expected?

    Synonym for @ref HC_greaterThan, available if @c HC_SHORTHAND is defined.
    @ingroup number_matchers
 */
#ifdef HC_SHORTHAND
    #define greaterThan HC_greaterThan
#endif

/**
    Is value >= expected?

    @b Synonym: @ref greaterThanOrEqualTo
    @ingroup number_matchers
 */
OBJC_EXPORT id<HCMatcher> HC_greaterThanOrEqualTo(id expected);

/**
    greaterThanOrEqualTo(expected) -
    Is value >= expected?

    Synonym for @ref HC_greaterThan, available if @c HC_SHORTHAND is defined.
    @ingroup number_matchers
 */
#ifdef HC_SHORTHAND
    #define greaterThanOrEqualTo HC_greaterThanOrEqualTo
#endif

/**
    Is value < expected?

    @b Synonym: @ref lessThan
    @ingroup number_matchers
 */
OBJC_EXPORT id<HCMatcher> HC_lessThan(id expected);

/**
    lessThan(expected) -
    Is value < expected?

    Synonym for @ref HC_greaterThan, available if @c HC_SHORTHAND is defined.
    @ingroup number_matchers
 */
#ifdef HC_SHORTHAND
    #define lessThan HC_lessThan
#endif

/**
    Is value <= expected?

    @b Synonym: @ref lessThanOrEqualTo
    @ingroup number_matchers
 */
OBJC_EXPORT id<HCMatcher> HC_lessThanOrEqualTo(id expected);

/**
    lessThanOrEqualTo(expected) -
    Is value <= expected?

    Synonym for @ref HC_lessThanOrEqualTo, available if @c HC_SHORTHAND is defined.
    @ingroup number_matchers
 */
#ifdef HC_SHORTHAND
    #define lessThanOrEqualTo HC_lessThanOrEqualTo
#endif


3QAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAAANklEQVQ4y+2RsQ0AIAzDav7/2VzQwoCY4iWbZSmo1QGoUgNMghvWaIejPQW/CrrNCylIwcOCDYfLNRcNer4SAAAAAElFTkSuQmCC" alt="." style="background-color: inherit" class="hierarchy"/><img src="data: image/png;base64,R0lGODlhEAAQAPZ/APrkusOiYvvfqbiXWaV2G+jGhdq1b8GgYf3v1frw3vTUlsWkZNewbcSjY/DQkad4Hb6dXv3u0f3v1ObEgfPTlerJiP3w1v79+e7OkPrfrfnjuNOtZPrpydaxa+/YrvvdpP779ZxvFPvnwKKBQaFyF/369M2vdaqHRPz58/HNh/vowufFhfroxO3OkPrluv779tK0e6JzGProwvrow9m4eOnIifPTlPDPkP78+Naxaf3v0/zowfXRi+bFhLWUVv379/rnwPvszv3rye3LiPvnv+3MjPDasKiIS/789/3x2f747eXDg+7Mifvu0tu7f+/QkfDTnPXWmPrjsvrjtPbPgrqZW+/QlPz48K2EMv36866OUPvowat8Ivvgq/Pbrvzgq/PguvrgrqN0Gda2evfYm9+7d/rpw9q6e/LSku/Rl/XVl/LSlfrkt+zVqe7Wqv3x1/bNffbOf59wFdS6if3u0vrqyP3owPvepfXQivDQkO/PkKh9K7STVf779P///wD/ACH5BAEKAH8ALAAAAAAQABAAAAemgH+CgxeFF4OIhBdKGwFChYl/hYwbdkoBPnaQkosbG3d3VEpSUlonUoY1Gzo6QkI8SrGxWBOFG4uySgY5ZWR3PFy2hnaWZXC/PHcPwkpJk1ShoHcxhQEXSUmtFy6+0iSFVResrjoTPDzdcoU+F65CduVU6KAhhQa3F8Tx8nchBoYuqoTLZoAKFRIhqGwqJAULFx0GYpBQeChRIR4TJm6KJMhQRUSBAAA7" alt="." style="background-color: white; background-color: inherit" title="Data Type" class="hierarchy"/> contact 	Σ	0..*	ContactDetail	<td style="vertical-align: top; text-align : left; background-


ernel>(
             nodes.exact_node(O_prime_index),
             nodes.exact_node(O_index),
             P1_index == -1 ? nodes.to_exact(get(ppmap,P1))
                            : nodes.exact_node(P1_index),
             P2_index == -1 ? nodes.to_exact(get(ppmap,P2))
                            : nodes.exact_node(P2_index),
             Q_index  == -1 ? nodes.to_exact(get(ppmap,Q))
                            : nodes.exact_node(Q_index )
           );
  }
}

}

}

} // end of namespace CGAL::Corefinement::OOP

#endif //CGAL_INTERNAL_COREFINEMENT_PREDICATES_H


ewid="131071" tagname="标题列表新闻快递" action="" layout="" contype="" stylesysid="" template="" tplstyle="" clone="0" istemp=""-->

10-09
我校召开网站建设推进会

09-27
第二届下一代互联网与高校应用服务架构创新研讨会在江南大学...

09-26
成都大学信息网络中心来访

09-22
我校成功举办“信息网络安全教育”新生转型教育活动

09-12
中心召开“建设与服务标准化”研讨会

新版e江南登录入口

旧版e江南登录入口

有线网络登录入口

无线网络登录入口

正版化软件

校园智能卡自助查询服务登录入口

学生邮箱登录入口(2016级及之前)

<img src="images


      await prepare(tester);
      await tester.ime.insertText(':${search ?? 'a'}');
      await tester.pumpAndSettle(Duration(seconds: 1));
    }

    testWidgets('insert with click', (tester) async {
      await createNewDocumentAndShowEmojiList(tester);

      /// emoji list is showing
      final emojiHandler = find.byType(EmojiHandler);
      expect(emojiHandler, findsOneWidget);
      final emojiButtons =
          find.descendant(of: emojiHandler, matching: find.byType(FlowyButton));
      final firstTextFinder = find.descendant(
        of: emojiButtons.first,
        matching: find.byType(FlowyText),
      );
      final emojiText =
          (firstTextFinder.evaluate().first.widget as FlowyText).text;

      /// click first emoji item
      await tester.tapButton(emojiButtons.first);
      final firstNode =
          tester.editor.getCurrentEditorState().getNodeAtPath([0])!;

      /// except the emoji is in document
      expect(emojiText.contains(firstNode.delta!.toPlainText()), true);
    });

    testWidgets('insert with arrow and enter', (tester) async {
      await createNewDocumentAndShowEmojiList(tester);

      /// emoji list is showing
      final emojiHandler = find.byType(EmojiHandler);
      expect(emojiHandler, findsOneWidget);
      final emojiButtons =
          find.descendant(of: emojiHandler, matching: find.byType(FlowyButton));

      /// tap arrow down and arrow up
      await tester.simulateKeyEvent(LogicalKeyboardKey.arrowUp);
      await tester.simulateKeyEvent(LogicalKeyboardKey.arrowDown);

      final firstTextFinder = find.descendant(
        of: emojiButtons.first,
        matching: find.byType(FlowyText),
      );
      final emojiText =
          (firstTextFinder.evaluate().first.widget as FlowyText).text;

      /// tap enter
      await tester.simulateKeyEvent(LogicalKeyboardKey.enter);
      final firstNode =
          tester.editor.getCurrentEditorState().getNodeAtPath([0])!;

      /// except the emoji is in document
      expect(emojiText.contains(firstNode.delta!.toPlainText()), true);
    });

    testWidgets('insert with searching', (tester) async {
      await createNewDocumentAndShowEmojiList(tester, search: 's');

      /// search for `smiling eyes`, IME is not working, use keyboard input
      final searchText = [
        LogicalKeyboardKey.keyM,
        LogicalKeyboardKey.keyI,
        LogicalKeyboardKey.keyL,
        LogicalKeyboardKey.keyI,
        LogicalKeyboardKey.keyN,
        LogicalKeyboardKey.keyG,
        LogicalKeyboardKey.space,
        LogicalKeyboardKey.keyE,
        LogicalKeyboardKey.keyY,
        LogicalKeyboardKey.keyE,
        LogicalKeyboardKey.keyS,
      ];

      for (final key in searchText) {
        await tester.simulateKeyEvent(key);
      }

      /// tap enter
      await tester.simulateKeyEvent(LogicalKeyboardKey.enter);
      final firstNode =
          tester.editor.getCurrentEditorState().getNodeAtPath([0])!;

      /// except the emoji is in document
      expect(firstNode.delta!.toPlainText().contains('😄'), true);
    });

    testWidgets('start searching with sapce', (tester) async {
      await createNewDocumentAndShowEmojiList(tester, search: ' ');

      /// emoji list is showing
      final emojiHandler = find.byType(EmojiHand


});

  describe('Get isRange value', () => {
    test('Should return current value of isRange attribute, when isRange is true', () => {
      options.isRange = true;
      const model = new Model(options);
      expect(model.getRangeStatus()).toBe(true);
    });

    test('Should return current value of isRange attribute, when isRange is false', () => {
      options.isRange = false;
      const model = new Model(options);
      expect(model.getRangeStatus()).toBe(false);
    });
  });

  describe('Set isRange value', () => {
    test('Should change isRange attribute value to given value from false', () => {
      options.isRange = false;
      let model = new Model(options);
      model.setRangeMode(false);
      expect(model.getRangeStatus()).toBe(false);

      model = new Model(options);
      model.setRangeMode(true);
      expect(model.getRangeStatus()).toBe(true);
    });

    test('Should change isRange attribute value to given value from true', () => {
      options.isRange = true;
      let model = new Model(options);
      model.setRangeMode(true);
      expect(model.getRangeStatus()).toBe(true);

      model = new Model(options);
      model.setRangeMode(false);
      expect(model.getRangeStatus()).toBe(false);
    });
  });

  describe('Get max value', () => {
    test('Should return current max value', () => {
      options.maxValue = 250;
      const model = new Model(options);
      expect(model.getMaxValue()).toBe(250);
    });
  });

  describe('Set max value', () => {
    test('Should set current max value attribute to given value', () => {
      const model = new Model(options);
      model.setMaxValue(200);
      expect(model.getMaxValue()).toBe(200);

      model.setMaxValue(50);
      expect(model.getMaxValue()).toBe(50);
    });

    test('Should throw Error while setting max value to given invalid value', () => {
      options.maxValue = 100;
      options.minValue = 0;
      options.step = 5;
      const model = new Model(options);

      // При данном значении разница между максимум и минимумом будет меньше шага
      expect(() => {
        model.setMaxValue(4);
      }).toThrowError();

      // Данное значение меньше минимального
      expect(() => {
        model.setMaxValue(-10);
      }).toThrowError();
    });
  });

  describe('Get min value', () => {
    test('Should return a current min value', () => {
      options.maxValue = 100;
      options.minValue = 0;
      options.step = 5;
      const model = new Model(options);
      expect(model.getMinValue()).toBe(0);
    });
  });

  describe('Set min value', () => {
    test('Should set current min value attribute to given value', () => {
      const model = new Model(options);
      model.setMinValue(-50);
      expect(model.getMinValue()).toBe(-50);

      model.setMinValue(50);
      expect(model.getMinValue()).toBe(50);
    });

    test('Should throw Error while setting min value to given invalid value', () => {
      options.maxValue = 100;
      options.minValue = 0;
      options.step = 5;
      const model = new Model(options);

      // При данном значении разница между максимум и минимумом будет меньше шага
      expect(() => {
        model.setMinValue(96);
      }).toThrowError();
      // Данное значние больше максимального значения
      expect(() => {
        model.setMinValue(200);
      }).toThrowError();
    });
  });

  describe('Get low value', () => {
    test('Should return


харах боломжтой","uf7WYw":"GPT-г нийтлэх боломжгүй байна","UnyV2o":"Өгөгдлийн багц","uP1+Ri":"Холбоостой дурын хүн","UpgradedToTeamSuccess.completeDescription":"Та одоо багийн ажлын талбар үүсгэлээ. Та гишүүдийг ажлын талбарт нэгдэхийг урих боломжтой. Та үүнийг ажлын талбарын тохиргооны хуудаснаас хүссэн үедээ хийж болно.","UpgradedToTeamSuccess.completeTitle":"Ажлын талбарыг тохируулж дууслаа","UpgradedToTeamSuccess.continue":"Үргэлжлүүлэх","UpgradedToTeamSuccess.continueToChatgpt":"ChatGPT рүү үргэлжлүүлнэ үү","UpgradedToTeamSuccess.description":"Танай баг үүслээ. Та хамтран ажиллаж эхлэхийн тулд гишүүдийг ажлын талбарт нэгдэхийг урьж болно.","UpgradedToTeamSuccess.inviteTitle":"{workspaceName}-д гишүүд урих","UpgradedToTeamSuccess.setupSubtitle":"Ажлын талбарын нэр","UpgradedToTeamSuccess.setupTitle":"Багийн ажлын талбар тохируулах","UpgradedToTeamSuccess.skipAddMembers":"Алгасах","UpgradedToTeamSuccess.trial":"Төлбөр амжилттай","UpgradeInviteModal.inviteValidUntilFooter":"Таны урилга {date} хүртэл хүчинтэй","UpgradeInviteModal.title":"Таныг Plus-д урьсан байна","UpgradeInviteModal.upgradeButton":"Сайжруулах","uqD7Y8":"Хандах","useFilePickerState.maxUploadsAtATime":"{fileName}-г байршуулах боломжгүй байна. Нэг удаад дээд тал нь {maxUploads} байршуулалт","useFilePickerState.retrievalSkippedFile":"\\"{fileName}\\"-с текст гаргах боломжгүй байна","userContexModal.tools.browserTooltip":"Хариултуудыг олохын тулд интернэтээр хайна уу","userContexModal.tools.codeInterpreterTooltip":"Код тайлагч ашиглан кодыг гүйцэтгэх","userContexModal.tools.dalleTooltip":"DALL-E ашиглан зураг үүсгэх","UserContextFirstTimeModal.body1":"Чатынхаа тодорхой мэдээлэл, зааварчилгааг өгөн ChatGPT-тэй харилцах харилцаагаа тохируулаарай.","UserContextFirstTimeModal.body2":"Таныг тусгай заавраа засах бүрд таны үүсгэсэн бүх шинэ чатад хүчин төгөлдөр болно. Одоо байгаа чатуудыг шинэчлэхгүй.","UserContextFirstTimeModal.legal1":"Та татгалзаа


DateTime.now())) {
                val userInfo = getUserInfo(properties)
                accessToken = userInfo.body?.get("AccessToken").toString()
                lastUpdate = LocalDateTime.now()
                log.info("Logged in to Emby as {} {}", properties.username, accessToken)
            }

            headerMap.map { e ->
                template.header(e.key, e.value)
                template.query(e.key, e.value)
            }
            template.query("reqformat", "json")
            template.header(AUTHORIZATION, janitorrClientString)
            template.header("X-Emby-Token", accessToken)
            template.header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
        }

        private fun getUserInfo(properties: EmbyProperties): ResponseEntity<Map<*, *>> {
            val login = RestTemplate()
            val headers = HttpHeaders()
            headerMap.map {
                e -> headers.set(e.key, e.value)
            }
            headers.set(AUTHORIZATION, janitorrClientString)
            headers.set(CONTENT_TYPE, APPLICATION_FORM_URLENCODED_VALUE)
            headers.set(ACCEPT, MediaType.ALL_VALUE)

            val content = LinkedMultiValueMap<String, String>()
            content.add("Username", properties.username)
            content.add("Pw", properties.password)
            return login.postForEntity("${properties.url}/emby/Users/AuthenticateByName", HttpEntity(content, headers), Map::class.java)
        }

    }
}package com.github.schaka.naviseerr.music_library.library

import com.github.schaka.naviseerr.download_client.slskd.SoulseekRestService
import com.github.schaka.naviseerr.download_client.slskd.MatchService
import com.github.schaka.naviseerr.music_library.lidarr.ImportManager
import com.github.schaka.naviseerr.music_library.lidarr.LidarrRestService
import com.github.schaka.naviseerr.music_library.lidarr.dto.WantedRecord
import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.stereotype.Component

@Component
class DownloadManager(
    private val lidarrRestService: LidarrRestService,
    private val soulseekRestService: SoulseekRestService,
    private val matchService: MatchService,
    private val importManager: ImportManager,
) {

    private val log = KotlinLogging.logger { }

    suspend fun downloadRelease(missing: WantedRecord) {
        val searchText = "${missing.artist.artistName} - ${missing.title}"
        val result = soulseekRestService.search(searchText)
        val expectedTracks = lidarrRestService.getTracks(missing.id)

        val matches = matchService.matchResultToTrackList(result, expectedTracks, missing.title, missing.artist.artistName)
            .sortedByDescending { it.score }

        if (matches.isNotEmpty()) {
            val match = matches.first()
            log.info { "Found album ${missing.title} - downloading from ${match.result.username}" }
            val downloadFiles = soulseekRestService.download(match)
            importManager.import(missing.artistId, missing.id, missing.releases.first().id, match)

        } else {
            log.info { "Couldn't find any results for ${missing.artist} - ${missing.title}" }
        }

    }

}/*
 * Copyright 2022-2024 New Vector Ltd.
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
 * Please see LICENSE files in the repository root for full details.
 */

import java.net.URI

fun getLocalProperty(key: String, file: String = "local.properties"): Any? {
    val properties = java.util.Properties()
    val localPr


,
            SystemClock.uptimeMillis(),
            KeyEvent.ACTION_DOWN,
            KeyEvent.KEYCODE_BACK,
            0
        )
        val up = KeyEvent(
            SystemClock.uptimeMillis(),
            SystemClock.uptimeMillis(),
            KeyEvent.ACTION_UP,
            KeyEvent.KEYCODE_BACK,
            0
        )

        try {
            InputManager.setDisplayId(down, displayId)
            KeyEvent::class.java.getMethod("setSource", Int::class.javaPrimitiveType)
                .invoke(down, InputDevice.SOURCE_KEYBOARD)
            inputManager!!.injectInputEvent(down, 0)

            InputManager.setDisplayId(up, displayId)
            KeyEvent::class.java.getMethod("setSource", Int::class.javaPrimitiveType)
                .invoke(up, InputDevice.SOURCE_KEYBOARD)
            inputManager!!.injectInputEvent(up, 0)
        } catch (e: Exception) {

        }
    }
}package com.sunshine.freeform.activity.choose_free_form_apps

import android.app.Application
import android.content.pm.LauncherActivityInfo
import android.content.pm.ResolveInfo
import android.os.UserManager
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import com.sunshine.freeform.room.DatabaseRepository
import com.sunshine.freeform.room.FreeFormAppsEntity
import com.sunshine.freeform.room.NotificationAppsEntity
import com.sunshine.freeform.systemapi.UserHandle

/**
 * @author sunshine
 * @date 2021/1/31
 */
class ChooseAppsViewModel(application: Application) : AndroidViewModel(application){

    private val repository = DatabaseRepository(application)

    var type = 1

    fun getAllApps(): LiveData<List<FreeFormAppsEntity>?> {
        return repository.getAllFreeForm()
    }

    fun getAllNotificationApps(): LiveData<List<NotificationAppsEntity>?> {
        return repository.getAllNotification()
    }

    fun insertApps(packageName: String, userId: Int) {
        when (type) {
            2 -> repository.insertNotification(packageName, userId)
            else -> repository.insertFreeForm(packageName, userId)
        }
    }

    fun deleteApps(packageName: String, userId: Int) {
        when (type) {
            2 -> repository.deleteNotification(packageName, userId)
            else -> {
                repository.deleteFreeForm(packageName, userId)
            }
        }
    }

    fun deleteAll() {
        when (type) {
            2 -> repository.deleteAllNotification()
            1 -> {
                repository.deleteAllFreeForm()
            }
        }
    }

    //添加列表中所有软件
    fun insertAllApps(allAppsList: ArrayList<LauncherActivityInfo>, userManager: UserManager) {
        deleteAll()
        allAppsList.forEach {
            when (type) {
                2 -> repository.insertNotification(it.applicationInfo.packageName, UserHandle.getUserId(it.user, it.applicationInfo.uid))
                else -> repository.insertFreeForm(it.applicationInfo.packageName, UserHandle.getUserId(it.user, it.applicationInfo.uid))
            }
        }
    }

}package com.sunshine.freeform.activity.mi_window_setting

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Bundle
import android.os.PowerManager
import android.provider.Settings
import android.provider.Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS
import android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
import android.view.LayoutInflater
import android.widget.Toast
import androidx.appcompat.widget.AppCompatEditText

import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceManager
import


-node-id].li>.bq,
.protyle-wysiwyg .protyle-wysiwyg__embed [data-node-id].li>.bq {
    left: 0.1em;
    top: -1px;
}

/* 缩进调整 */
.b3-typography blockquote>p,
.b3-typography blockquote .code-block,
.b3-typography blockquote ul,
/* .b3-typography blockquote li, */
.b3-typography blockquote blockquote {
    margin-left: 1em;
}

/*  ------------------------------图片 ------------------------------ */
.protyle-wysiwyg img,
.b3-typography img {
    border-radius: 5px;
}

.protyle-wysiwyg img:hover,
.p [contenteditable='true']:focus>.img:first-child img {
    box-shadow: 1px 1px 5px 5px rgba(6, 6, 6, 10%);
}

/* 图片大小调整手柄 */
.protyle-wysiwyg [data-node-id] .img .protyle-action__drag {
    height: 50%;
    top: 25%;
    background: var(--b3-theme-surface);
}

/* 去除图片后的多余空行 CSS片段 */
:is(.b3-typography, .protyle-wysiwyg) .img:not([style]) {
    display: inline-block;
}

/*  ------------------------------列表 ------------------------------ */
/* 调整列表间距 */
.protyle .li {
    padding: 0;
    margin: 0px 0px 0px 0px;
}

.b3-typography ul li.protyle-task::before {
    margin: 2px 2px 0px -2px;
}

/* 列表悬浮 */
.protyle-wysiwyg [data-node-id].li>.protyle-action:hover:after {
    /* 大圆背景 */
    background-color: #b4cef09c !important;
    opacity: 0.68;
}

.protyle-wysiwyg [data-node-id].li>.protyle-action:hover {
    /* 小圆点 */
    color: #476796bb;
}

/* 列表折叠 */
.protyle-wysiwyg .li[fold='1']>.protyle-action:after {
    /* 大圆背景 */
    background-color: #667ea97d !important;
    opacity: 0.68;
}

.protyle-wysiwyg [data-subtype='t'].li[fold='1']>.protyle-action:after {
    /* 大圆背景 */
    background-color: #667ea97d !important;
    border-radius: 0.2em;
    opacity: 0.68;
}

.protyle-wysiwyg [data-subtype='u'].li[fold='1']>.protyle-action {
    /* 小圆点 */
    color: #476796;
}

/*  ------------------------------复选框（待办事项） ------------------------------ */
.b3-typography .protyle-task input {
    opacity: 0;
}

/* 待办事项的鼠标光标为点击 */
.protyle-wysiwyg [data-node-id].li>.protyle-action--task {
    cursor: pointer;
}

.protyle-wysiwyg [data-node-id].li>.protyle-action--task svg {
    opacity: 0;
}

.protyle-wysiwyg [data-node-id].li>.protyle-action--task:hover:after {
    background-color: transparent !importa


	name:      "empty result",
			directory: "empty-result",
			expectedOut: `{"@level":"info","@message":"Terraform ` + tfVer + `","@module":"terraform.ui","@timestamp":"2025-09-12T16:52:57.596469+02:00","terraform":"1.14.0-dev","type":"version","ui":"1.2"}
{"@level":"info","@message":"list.test_instance.example: Starting query...","@module":"terraform.ui","@timestamp":"2025-09-12T16:52:57.600609+02:00","list_start":{"address":"list.test_instance.example","resource_type":"test_instance","input_config":{"ami":"ami-12345","foo":null}},"type":"list_start"}
{"@level":"info","@message":"list.test_instance.example: Result found","@module":"terraform.ui","@timestamp":"2025-09-12T16:52:57.600729+02:00","list_resource_found":{"address":"list.test_instance.example","display_name":"Test Instance 1","identity":{"id":"test-instance-1"},"identity_version":1,"resource_type":"test_instance","resource_object":{"ami":"ami-12345","id":"test-instance-1"}},"type":"list_resource_found"}
{"@level":"info","@message":"list.test_instance.example: Result found","@module":"terraform.ui","@timestamp":"2025-09-12T16:52:57.600759+02:00","list_resource_found":{"address":"list.test_instance.example","display_name":"Test Instance 2","identity":{"id":"test-instance-2"},"identity_version":1,"resource_type":"test_instance","resource_object":{"ami":"ami-67890","id":"test-instance-2"}},"type":"list_resource_found"}
{"@level":"info","@message":"list.test_instance.example: List complete","@module":"terraform.ui","@timestamp":"2025-09-12T16:52:57.600770+02:00","list_complete":{"address":"list.test_instance.example","resource_type":"test_instance","total":2},"type":"list_complete"}
{"@level":"info","@message":"list.test_instance.example2: Starting query...","@module":"terraform.ui","@timestamp":"2025-09-12T16:52:57.600609+02:00","list_start":{"address":"list.test_instance.example2","resource_type":"test_instance","input_config":{"ami":"ami-nonexistent","foo":"test-instance-1"}},"type":"list_start"}
{"@level":"info","@message":"list.test_instance.example2: List complete","@module":"terraform.ui","@timestamp":"2025-09-12T16:52:57.600770+02:00","list_complete":{"address":"list.test_instance.example2","resource_type":"test_instance","total":0},"type":"list_complete"}
`,
		},
	}

	for _, ts := range tests {
		t.Run(ts.name, func(t *testing.T) {
			td := t.TempDir()
			testCopyDir(t, testFixturePath(path.Join("query", ts.directory)), td)
			t.Chdir(td)
			providerSource, close := newMockProviderSource(t, map[string][]string{
				"hashicorp/test": {"1.0.0"},
			})
			defer close()

			p := queryFixtureProvider()
			view, done := testView(t)
			meta := Meta{
				testingOverrides:          metaOverridesForProvider(p),
				View:                      view,
				AllowExperimentalFeatures: true,
				ProviderSource:            providerSource,
			}

			init := &InitCommand{Meta: meta}
			code := init.Run(nil)
			output := done(t)
			if code != 0 {
				t.Fatalf("expected status code %d but got %d: %s", 0, code, output.All())
			}

			view, done = testView(t)
			meta.View = view


::std::sync::Arc<RwLock<::std::collections::HashMap<i64, oneshot::Sender<Vec<u8>>>>>,
                pub(crate) stream_dispatch: ::std::sync::Arc<RwLock<::std::collections::HashMap<u128, ::std::collections::HashMap<i64, mpsc::Sender<Vec<u8>>>>>>,
            }

            impl WsInstance {
                pub(crate) async fn wait_context(&self) {
                    while let None = self.write.read().await.as_ref() {}
                }

                fn new() -> Self {
                    let context = Self::default();

                    let context_lock = context.write.clone();

                    ::tokio::spawn(async move {
                        let url = Url::parse(#url_lit).unwrap();
                        let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");
                        let (write, read) = ws_stream.split();
                        context_lock.write().await.replace((0, write));
                        read.for_each(|message| async {
                            match message {
                                Ok(msg) => match msg {
                                    Message::Binary(data) => {
                                        parse_response_bytes(&mut data.as_slice()).await.expect("Could not read response data");
                                    }
                                    Message::Ping(_) => {}
                                    Message::Pong(_) => {}
                                    Message::Close(_) => {}
                                    _ => panic!("Invalid message type"),
                                },
                                Err(_err) => {}
                            }
                        })
                        .await;
                    });
                    context
                }
            }

            #ws_package
        });

        Ok(())
    }

    fn new() -> Self {
        Self { module: vec![] }
    }
}

pub struct WSInterface {
    module: Vec<TokenStream>,
}

impl ToTokens for WSInterface {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.append_all(&self.module);
    }
}

impl fmt::Display for WSInterface {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut result_code = String::new();

        self.module.iter().for_each(|value| {
            result_code += &value.to_string();
        });

        write!(f, "{}", result_code.rust_fmt())
    }
}

impl WSInterface {
    pub fn generate(package: &ids::package::Package, analyzer: &Analyzer) -> Result<Self, WSClientError> {
        let mut context = Self::new();

        let new_prefix_body = quote! {
            crate::ws::WS_INSTANCE.wait_context().await;
            let mut write_ref = crate::ws::WS_INSTANCE.write.write().await;
            let (_call_id, write) = write_ref.as_mut().expect("Invalid locked value");
            *_call_id += 1;
            let call_id = *_call_id;
        };

        let new_body = quote! {
            write.send(::tungstenite::Message::binary(input.into_boxed_slice())).await.unwrap();
            let response = response_event.await.unwrap();
        };

        let write_prefix_type = quote! { ::tokio::sync::oneshot::Receiver<Vec<u8>> };

        let write_prefix_body = quote! {
            let (sender, response_event) = ::tokio::sync::oneshot::channel();
            let dispatch = crate::ws::WS_INSTANCE.dispatch.clone();


= s;
              break;
            }
            case 56: {
              int rawValue = input.readEnum();

              logType_ = rawValue;
              break;
            }
            case 64: {
              int rawValue = input.readEnum();

              logLevel_ = rawValue;
              break;
            }
            default: {
              if (!parseUnknownField(
                  input, unknownFields, extensionRegistry, tag)) {
                done = true;
              }
              break;
            }
          }
        }
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.setUnfinishedMessage(this);
      } catch (java.io.IOException e) {
        throw new com.google.protobuf.InvalidProtocolBufferException(
            e).setUnfinishedMessage(this);
      } finally {
        this.unknownFields = unknownFields.build();
        makeExtensionsImmutable();
      }
    }
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return emu.grasscutter.net.proto.ServerLogNotifyOuterClass.internal_static_ServerLogNotify_descriptor;
    }

    @java.lang.Override
    protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return emu.grasscutter.net.proto.ServerLogNotifyOuterClass.internal_static_ServerLogNotify_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              emu.grasscutter.net.proto.ServerLogNotifyOuterClass.ServerLogNotify.class, emu.grasscutter.net.proto.ServerLogNotifyOuterClass.ServerLogNotify.Builder.class);
    }

    public static final int LOG_TYPE_FIELD_NUMBER = 7;
    private int logType_;
    /**
     * .ServerLogType log_type = 7;
     * @return The enum numeric value on the wire for logType.
     */
    @java.lang.Override public int getLogTypeValue() {
      return logType_;
    }
    /**
     * .ServerLogType log_type = 7;
     * @return The logType.
     */
    @java.lang.Override public emu.grasscutter.net.proto.ServerLogTypeOuterClass.ServerLogType getLogType() {
      @SuppressWarnings("deprecation")
      emu.grasscutter.net.proto.ServerLogTypeOuterClass.ServerLogType result = emu.grasscutter.net.proto.ServerLogTypeOuterClass.ServerLogType.valueOf(logType_);
      return result == null ? emu.grasscutter.net.proto.ServerLogTypeOuterClass.ServerLogType.UNRECOGNIZED : result;
    }

    public static final int LOG_LEVEL_FIELD_NUMBER = 8;
    private int logLevel_;
    /**
     * .ServerLogLevel log_level = 8;
     * @return The enum numeric value on the wire for logLevel.
     */
    @java.lang.Override public int getLogLevelValue() {
      return logLevel_;
    }
    /**
     * .ServerLogLevel log_level = 8;
     * @return The logLevel.
     */
    @java.lang.Override public emu.grasscutter.net.proto.ServerLogLevelOuterClass.ServerLogLevel getLogLevel() {
      @SuppressWarnings("deprecation")
      emu.grasscutter.net.proto.ServerLogLevelOuterClass.ServerLogLevel result = emu.grasscutter.net.proto.ServerLogLevelOuterClass.ServerLogLevel.valueOf(logLevel_);
      return result == null ? emu.grasscutter.net.proto.ServerLogLevelOuterClass.ServerLogLevel.UNRECOGNIZED : result;
    }

    public static final int SERVER_LOG_FIELD_NUMBER = 3;
    private volatile java.lang.Object serverLog_;
    /**
     * string server_log = 3;
     * @return The serverLog.
     */
    @java.lang.Override
    public java


 (address)
	{
		case 0x3e00:
			*soundlatch = data;
			M6502SetIRQLine(M6502_INPUT_LINE_NMI, CPU_IRQSTATUS_AUTO);
			M6502Run(500);
		return;

		case 0x3c00:
			m6809_bankswitch(data);
		return;

		case 0x3c02:
			memcpy (DrvSprBuf, DrvSprRAM, 0x800);
		return;
	}

	if ((address & 0xffe0) == 0x3800) {
		DrvPf0Ctrl[address & 0x1f] = data;
		return;
	}

	if ((address & 0xffe0) == 0x3a00) {
		DrvPf1Ctrl[address & 0x1f] = data;
		return;
	}
}

static UINT8 cobra_main_read(UINT16 address)
{
	switch (address)
	{
		case 0x3800:
			return DrvInputs[0];

		case 0x3801:
			return DrvInputs[1];

		case 0x3802:
			return DrvDips[0];

		case 0x3803:
			return DrvDips[1];

		case 0x3a00:
			return (DrvInputs[2] & 0x7f) | vblank;
	}

	return 0;
}

static INT32 CobraDoReset()
{
	DrvReset = 0;

	memset (AllRam, 0, RamEnd - AllRam);

	M6809Open(0);
	M6809Reset();
	M6809Close();

	M6502Open(0);
	M6502Reset();
	M6502Close();

	BurnYM2203Reset();
	BurnYM3812Reset();

	i8751_return = 0;
	i8751_value = 0;

	return 0;
}

static INT32 CobraGfxDecode()
{
	// 0, 0x40, 0x80, 0xc0 for offs

	INT32 Plane0[2] = { 0x4000*8,0x0000*8 };
	INT32 Plane1[4] = { 0x60000*8,0x40000*8,0x20000*8,0x00000*8 };
	INT32 XOffs0[8] = { 0, 1, 2, 3, 4, 5, 6, 7 };
	INT32 XOffs1[16]= { 16*8, 1+(16*8), 2+(16*8), 3+(16*8), 4+(16*8), 5+(16*8), 6+(16*8), 7+(16*8),0,1,2,3,4,5,6,7 };
	INT32 YOffs0[16] = { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 ,8*8,9*8,10*8,11*8,12*8,13*8,14*8,15*8 };

	UINT8 *tmp = (UINT8*)BurnMalloc(0x80000);
	if (tmp == NULL) {
		return 1;
	}

	memcpy (tmp, DrvGfxROM0, 0x08000);

	GfxDecode(0x0400, 2,  8,  8, Plane0, XOffs0, YOffs0, 0x040, tmp, DrvGfxROM0);

	memcpy (tmp, DrvGfxROM1, 0x80000);

	GfxDecode(0x1000, 4, 16, 16, Plane1, XOffs1, YOffs0, 0x100, tmp, DrvGfxROM1);

	memcpy (tmp, DrvGfxROM2, 0x80000);

	GfxDecode(0x1000, 4, 16, 16, Plane1, XOffs1, YOffs0, 0x100, tmp, DrvGfxROM2);

	memcpy (tmp, DrvGfxROM3, 0x80000);

	GfxDecode(0x1000, 4, 16,


meObject(targetGameObject.Value);
            if (currentGameObject != prevGameObject) {
                audioSource = currentGameObject.GetComponent<AudioSource>();
                prevGameObject = currentGameObject;
            }
        }

        public override TaskStatus OnUpdate()
        {
            if (audioSource == null) {
                Debug.LogWarning("AudioSource is null");
                return TaskStatus.Failure;
            }

            audioSource.volume = volume.Value;

            return TaskStatus.Success;
        }

        public override void OnReset()
        {
            targetGameObject = null;
            volume = 1;
        }
    }
}


}
        return this.regPS & X86.PS.ZF;
    }

    /**
     * getSF()
     *
     * @this {CPUX86}
     * @return {number} 0 or X86.PS.SF
     */
    getSF()
    {
        if (this.resultType & X86.RESULT.SF) {
            this.regPS &= ~X86.PS.SF;
            if (this.resultLogic & (this.resultType & X86.RESULT.TYPE)) {
                this.regPS |= X86.PS.SF;
            }
            this.resultType &= ~X86.RESULT.SF;
        }
        return this.regPS & X86.PS.SF;
    }

    /**
     * getOF()
     *
     * Overflow was originally calculated as:
     *
     *      (resultParitySign ^ resultAuxOverflow ^ (resultParitySign >> 1)) & (resultSize >> 1)
     *
     * but as you can see, that calculation depends on the carry out of the 8/16/32-bit result in
     * resultParitySign, which we don't have access to for 32-bit results.  So we fall-back to the
     * following:
     *
     *      ((resultDst ^ resultArith) & (resultSrc ^ resultArith)) & resultType
     *
     * which you can verify from the following table of sign bits, where x1 is resultDst ^ resultArith,
     * and x2 is resultSrc ^ resultArith:
     *
     *      D   S   A   x1  x2  OF
     *      -   -   -   --  --  --
     *      0   0   0   0   0   0
     *      0   0   1   1   1   1 (adding two positive values yielded a negative value)
     *      0   1   0   0   1   0
     *      0   1   1   1   0   0
     *      1   0   0   1   0   0
     *      1   0   1   0   1   0
     *      1   1   0   1   1   1 (adding two negative values yielded a positive value)
     *      1   1   1   0   0   0
     *
     * NOTE: The above table assumes that the resultDst (D) and resultSrc (S) operands were ADDED to
     * produce resultArith (A); if they were SUBTRACTED instead (D - S), then D and A must be swapped
     * after the subtraction, so that the above truth table still applies; see setArithResult().
     *
     * @this {CPUX86}
     * @return {number} 0 or X86.PS.OF
     */
    getOF()
    {
        if (this.resultType & X86.RESULT.OF) {
            this.regPS &= ~X86.PS.OF;
            if (((this.resultDst ^ this.resultArith) & (this.resultSrc ^ this.resultArith)) & (this.resultType & X86.RESULT.TYPE)) {
                this.regPS |= X86.PS.OF;
            }
            this.resultType &= ~X86.RESULT.OF;
        }
        return this.regPS & X86.PS.OF;
    }

    /**
     * getTF()
     *
     * @this {CPUX86}
     * @return {number} 0 or X86.PS.TF
     */
    getTF()
    {
        return (this.regPS & X86.PS.TF);
    }

    /**
     * getIF()
     *
     * @this {CPUX86}
     * @return {number} 0 or X86.PS.IF
     */
    getIF()
    {
        return (this.regPS & X86.PS.IF);
    }

    /**
     * getDF()
     *
     * @this {CPUX86}
     * @return {number} 0 or X86.PS.DF
     */
    getDF()
    {
        return (this.regPS & X86.PS.DF);
    }

    /**
     * clearCF()
     *
     * @this {CPUX86}


length
    let i = 1
    while (i < len)
        if (!curvedEdges ||
            (len <= 3 && (i == len - 1 || dist(p[i], p[i + 1]) < ranksep))) {
            cmds.push(new svg.LineTo('L', p[i].x, p[i].y))
            i++
        }
        else if (i < len - 1) {
            cmds.push(new svg.ContCubicCurveTo('S', p[i].x, p[i].y,
                p[i + 1].x, p[i + 1].y))
            i += 2
        }
        else {
            cmds.push(new svg.ContQuadCurveTo('T', p[i].x, p[i].y))
            i++
        }
    let res = svg.path(parent, cmds).addClass("edge")
    if (arrow)
        addArrow(arrow, svgroot, res);
    return res.moveToBack()
}

function defineDigraph(digraph: Digraph, svgroot: svg.GraphElem<SVGSVGElement>,
    viewport: svg.GraphElem<SVGGElement>, dg: dagre.graphlib.Graph) {
    digraph.nodes.forEach(node => {
        drawNode(node, viewport, digraph.nodeMargin)
        let bbox = node.elem.bbox
        dg.setNode(node.name, {
            label: node.label,
            width: bbox.width,
            height: bbox.height
        })
    })
    digraph.edges.forEach(edge => {
        if (edge.label) {
            drawEdgeLabel(edge, viewport)
            let { width, height } = edge.elem.bbox
            dg.setEdge(edge.source.name, edge.destination.name, {
                label: edge.label,
                labelpos: digraph.edgeLabelPos || 'r',
                width, height
            })
        }
        else
            dg.setEdge(edge.source.name, edge.destination.name)
    })
}

function layoutDigraph(digraph: Digraph, svgroot: svg.GraphElem<SVGSVGElement>,
    viewport: svg.GraphElem<SVGGElement>, dg: dagre.graphlib.Graph) {
    digraph.nodes.forEach(node => {
        let dn = dg.node(node.name)
        let e = node.elem
        e.transform = e.transform.translate(dn.x, dn.y)
    })
    digraph.edges.forEach(edge => {
        let de = dg.edge(edge.source.name, edge.destination.name)
        drawEdge(de, svgroot, viewport, edge.arrow, digraph.curvedEdges,
            digraph.ranksep || defaultRanksep)
        let e = edge.elem
        if (e)
            e.transform = e.transform.translate(de.x, de.y)
    })
}

function createDigraph(digraph: Digraph, parent: HTMLElement) {
    let svgroot = svg.create('svg', parent).addClass("digraph")
        .styles({ cursor: "zoom-in" })
    svg.defs(svgroot)
    let graph = new dagre.graphlib.Graph()
    graph.setGraph({
        rankdir: digraph.direction || 'TB',
        nodesep: digraph.nodesep || defaultNodesep,
        ranksep: digraph.ranksep || defaultRanksep
    })
    graph.setDefaultEdgeLabel((v: string, w: string) => { return {} })
    let viewport = anim.animatedView(svgroot).styles({ cursor: "zoom-in" })
    defineDigraph(digraph, svgroot, viewport, graph)
    dagre.layout(graph)
    layoutDigraph(digraph, svgroot, viewport, graph)
    svg.setBounds(svgroot, digraph.margin || 10)
    return svgroot.clicked(e => zoomInOut(svgroot, viewport, e))
}

let zoomed = false
c


/* ========================================
 *  Infinity2 - Infinity2.h
 *  Created 8/12/11 by SPIAdmin
 *  Copyright (c) 2011 __MyCompanyName__, Airwindows uses the MIT license
 * ======================================== */

#ifndef __Infinity2_Infinity2_H
#define __Infinity2_Infinity2_H

#ifndef __audioeffect__
#include "../airwin_consolidated_base.h"
#endif

#include <set>
#include <string>
#include <math.h>

namespace airwinconsolidated::Infinity2 {
enum {
	kParamA = 0,
	kParamB = 1,
	kParamC = 2,
	kParamD = 3,
	kParamE = 4,
	kParamF = 5,
  kNumParameters = 6
}; //

const int kNumPrograms = 0;
const int kNumInputs = 2;
const int kNumOutputs = 2;
const unsigned long kUniqueId = 'infj';    //Change this to what the AU identity is!

class Infinity2 :
    public AudioEffectX
{
public:
    Infinity2(audioMasterCallback audioMaster);
    ~Infinity2();
    virtual bool getEffectName(char* name);                       // The plug-in name
    virtual VstPlugCategory getPlugCategory();                    // The general category for the plug-in
    virtual bool getProductString(char* text);                    // This is a unique plug-in string provided by Steinberg
    virtual bool getVendorString(char* text);                     // Vendor info
    virtual VstInt32 getVendorVersion();                          // Version number
    virtual void processReplacing (float** inputs, float** outputs, VstInt32 sampleFrames);
    virtual void processDoubleReplacing (double** inputs, double** outputs, VstInt32 sampleFrames);
    virtual void getProgramName(char *name);                      // read the name from the host
    virtual void setProgramName(char *name);                      // changes the name of the preset displayed in the host
    virtual float getParameter(VstInt32 index);                   // get the parameter value at the specified index
    virtual void setParameter(VstInt32 index, float value);       // set the parameter at index to value
    virtual void getParameterLabel(VstInt32 index, char *text);  // label for the parameter (eg dB)
    virtual void getParameterName(VstInt32 index, char *text);    // name of the parameter
    virtual void getParameterDisplay(VstInt32 index, char *text); // text description of the current value
    // Added by the perl as inverses
    virtual bool parameterTextToValue(VstInt32 index, const char *text, float &value);
    virtual bool canConvertParameterTextToValue(VstInt32 index);
    virtual VstInt32 canDo(char *text);
private:
    char _programName[kVstMaxProgNameLen + 1];
    std::set< std::string > _canDo;

	double biquadA[11];
	double biquadB[11];
	double biquadC[11];

	double aAL[8111];
	double aBL[7511];
	double aCL[7311];
	double aDL[6911];
	double aEL[6311];
	double aFL[6111];
	double aGL[5511];
	double aHL[4911];
	double aIL[4511];
	double aJL[4311];
	double aKL[3911];
	double aLL[3311];
	double aML[3111];

	double aAR[8111];
	double aBR[7511];
	double aCR[7311];
	double aDR[6911];
	double aER[6311];
	double aFR[6111];
	double aGR[5511];
	double aHR[4911];
	double aIR[4511];
	double aJR[4311];
	double aKR[3911];
	double aLR[3311];
	double aMR[3111];

	int countA, delayA;
	int countB, delayB;
	int countC, delayC;
	int countD, delayD;
	int countE, delayE;
	int countF, delayF;
	int countG, delayG;
	int countH, delayH;
	int countI, delayI;
	int countJ, delayJ;
	int countK, delayK;
	int countL, delayL;
	int countM, delayM;

	double feedbackAL;
	double feedbackBL;
	double feedbackCL;
	double feedbackDL;
	double feedbackEL;
	double feedbackFL;
	double feedbackGL;
	double feedbackHL;

	double feedbackAR;
	double feedbackBR;
	double feedbackCR;
	double feedbackDR;
	double feedbackER;
	double feedbackFR;
	double feedbackGR;
	double feedbackHR;

	uint32_t fpdL;
	uint32_t fpdR;
	//default stuff

    float A;
    float B;
    float C;
    float D;
    float E;
    float F;
};

#endif
} // end namespace


 {'rsp_data': 3}),
      Vector({}, {'rsp_data': 6}),
      Vector({}, {'rsp_data': 9}),
    ];

    final sv = mod.generateSynth();

    expect(sv, contains('''
module Provider (
input logic clk,
input logic reset,
input logic wd0_ready_req,
input logic wd1_ready_req,
input logic [31:0] rd_data_rsp,
input logic rd_valid_rsp,
output logic [31:0] wd0_data_req,
output logic wd0_valid_req,
output logic [31:0] wd1_data_req,
output logic wd1_valid_req,
output logic rd_ready_rsp
);
'''));

    expect(sv, contains('''
module Consumer (
input logic clk,
input logic reset,
input logic [31:0] wd0_data_req,
input logic wd0_valid_req,
input logic [31:0] wd1_data_req,
input logic wd1_valid_req,
input logic rd_ready_rsp,
output logic wd0_ready_req,
output logic wd1_ready_req,
output logic [31:0] rd_data_rsp,
output logic rd_valid_rsp
);
'''));

    await SimCompare.checkFunctionalVector(mod, vectors);
    SimCompare.checkIverilogVector(mod, vectors);
  });
}
// Copyright (C) 2023-2025 Intel Corporation
// SPDX-License-Identifier: BSD-3-Clause
//
// logic_structure_test.dart
// Tests for LogicStructure
//
// 2023 May 5
// Author: Max Korbel <max.korbel@intel.com>

import 'dart:async';

import 'package:rohd/rohd.dart';
import 'package:rohd/src/utilities/simcompare.dart';
import 'package:test/test.dart';

/// This is the struct used in the logic structures documentation.
class ReadyValidStruct extends LogicStructure {
  final Logic ready;
  final Logic valid;

  factory ReadyValidStruct({String name = 'readyValid'}) => ReadyValidStruct._(
        Logic(name: 'ready'),
        Logic(name: 'valid'),
        name: name,
      );

  ReadyValidStruct._(this.ready, this.valid, {required String name})
      : super([ready, valid], name: name);

  @override
  ReadyValidStruct clone({String? name}) =>
      ReadyValidStruct(name: name ?? this.name);
}

class MyStruct extends LogicStructure {
  final Logic ready;
  final Logic valid;

  factory MyStruct({String name = 'myStruct'}) => MyStruct._(
        Logic(name: 'ready'),
        Logic(name: 'valid'),
        name: name,
      );

  MyStruct._(this.ready, this.valid, {required super.name})
      : super([ready, valid]);

  @override
  MyStruct clone({String? name}) => MyStruct(name: name ?? this.name);
}

class MyFancyStruct extends LogicStructure {
  final LogicArray arr;
  final Logic bus;
  final LogicStructure subStruct;

  factory MyFancyStruct({int busWidth = 12, String name = 'myFancyStruct'}) =>
      MyFancyStruct._(
        LogicArray([3, 3], 8, name: 'arr'),
        Logic(name: 'bus', width: busWidth),
        MyStruct(),
        name: name,
      );

  MyFancyStruct._(this.arr, this.bus, this.subStruct,
      {super.name = 'myFancyStruct'})
      : super([arr, bus, subStruct]);

  @override
  MyFancyStruct clone({String? name}) =>
      MyFancyStruct(busWidth: bus.width, name: name ?? this.name);
}

class StructPortModule extends Module {
  StructPortModule(MyStruct struct) {
    final ready = addInput('ready', struct.ready);
    final valid = addOutput('valid');
    struct.valid <= valid;

    valid <= ready;
  }
}

class ModStructPassthrough extends Module {
  MyStruc


/// <summary>
/// An attribute to disable model validation for a particular type.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class NonValidatingParameterBindingAttribute : ModelBinderAttribute, IPropertyValidationFilter
{
    /// <inheritdoc />
    public bool ShouldValidateEntry(ValidationEntry entry, ValidationEntry parentEntry)
    {
        return false;
    }

    /// <inheritdoc/>
    public override BindingSource BindingSource
    {
        get
        {
            return BindingSource.Body;
        }
    }
}


ringPortInfo.portType = typeof(int);
            leftStringPortInfo.direction = EditorPortDirection.Input;
            leftStringPortInfo.orientation = EditorOrientation.Horizontal;
            leftStringPortInfo.color = Color.blue;
            leftStringPortInfo.canMultiConnect = true;
            leftStringPortInfo.priority = 100;

            portInfos.Add(leftStringPortInfo);

            EditorPortInfo rightIntPortInfo = new EditorPortInfo();
            rightIntPortInfo.id = "rightInt1PortInfo";
            rightIntPortInfo.displayName = "右端口1(int)";
            rightIntPortInfo.portType = typeof(int);
            rightIntPortInfo.direction = EditorPortDirection.Output;
            rightIntPortInfo.orientation = EditorOrientation.Horizontal;
            rightIntPortInfo.color = Color.cyan;
            rightIntPortInfo.canMultiConnect = true;

            portInfos.Add(rightIntPortInfo);

            EditorPortInfo rightStringPortInfo = new EditorPortInfo();
            rightStringPortInfo.id = "rightInt2PortInfo";
            rightStringPortInfo.displayName = "右端口2(int)";
            rightStringPortInfo.portType = typeof(int);
            rightStringPortInfo.direction = EditorPortDirection.Output;
            rightStringPortInfo.orientation = EditorOrientation.Horizontal;
            rightStringPortInfo.color = Color.gray;
            rightStringPortInfo.canMultiConnect = true;
            rightStringPortInfo.priority = 100;

            portInfos.Add(rightStringPortInfo);

            return portInfos;
        }
    }
}


21.pm) | `8fe7ca27a17adc337cd892b1d959b4e487b8f0ef09e32214f44fb1b07e461c532e9ec3` |
| [`1430`](/src/modules/module_01430.c) | `sha256(utf16le($pass).$salt)` | <sup>  [a0p](/OpenCL/m01430_a0-pure.cl), [a0o](/OpenCL/m01430_a0-optimized.cl), [a1p](/OpenCL/m01430_a1-pure.cl), [a1o](/OpenCL/m01430_a1-optimized.cl), [a3p](/OpenCL/m01430_a3-pure.cl), [a3o](/OpenCL/m01430_a3-optimized.cl) </sup> | [:white_check_mark:](/tools/test_modules/m01430.pm) | `b2d0db162e30dfef1bfd606689a3acbc213c47ef3fd11968394191886075249d:32002` |
| [`1440`](/src/modules/module_01440.c) | `sha256($salt.utf16le($pass))` | <sup>  [a0p](/OpenCL/m01440_a0-pure.cl), [a0o](/OpenCL/m01440_a0-optimized.cl), [a1p](/OpenCL/m01440_a1-pure.cl), [a1o](/OpenCL/m01440_a1-optimized.cl), [a3p](/OpenCL/m01440_a3-pure.cl), [a3o](/OpenCL/m01440_a3-optimized.cl) </sup> | [:white_check_mark:](/tools/test_modules/m01440.pm) | `84ebe1bc3d59919a8c4f9337d66bd163661586c828b24b8067a27a6dc4228c64:05662` |
| [`1441`](/src/modules/module_01441.c) | `Episerver 6.x >= .NET 4` | <sup>  [a0p](/OpenCL/m01440_a0-pure.cl), [a0o](/OpenCL/m01440_a0-optimized.cl), [a1p](/OpenCL/m01440_a1-pure.cl), [a1o](/OpenCL/m01440_a1-optimized.cl), [a3p](/OpenCL/m01440_a3-pure.cl), [a3o](/OpenCL/m01440_a3-optimized.cl) </sup> | [:white_check_mark:](/tools/test_modules/m01441.pm) | `$episerver$*1*NDg1NTIz*8BFCg/YJBAuZs/wjbH3OWKe69BLr5Lao26ybpnD48Zk` |
| [`1450`](/src/modules/module_01450.c) | `HMAC-SHA256 (key = $pass)` | <sup>  [a0p](/OpenCL/m01450_a0-pure.cl), [a0o](/OpenCL/m01450_a0-optimized.cl), [a1p](/OpenCL/m01450_a1-pure.cl), [a1o](/OpenCL/m01450_a1-optimized.cl), [a3p](/OpenCL/m01450_a3-pure.cl), [a3o](/OpenCL/m01450_a3-optimized.cl) </sup> | [:white_check_mark:](/tools/test_modules/m01450.pm) | `b435ffbacea34


6JMyIP2txs0MPQjS5qNtJ0E00Bc3ba7ya2qvZvl6kCEqb9JYCyXglwWFFuYsnfRHwUgsZb9B71w6iw== sig=2OUWoOnrcUHb6IKYJWC+/gKiMojX2JQ4n1RamPgYKDgbb2zdSxDE6vu2n9DBcvi6Rd9Ys//OSw5lYWAFnqSXBg== e=found last=11 s=22 in addShifted_NP",
                "pub=MCowBQYDK2VwAyEAjZ9fo188feZ3Ek39EpFAX6OC1rE7PRUBZIm2Eyj5qCM= priv=MC4CAQAwBQYDK2VwBCIEIPwXJLdsjJEJ3Q6q84asxlWJKFZylGNaeUpjndCVgEXf msg=eUpjndCVgEXf6n9kNyIydJRiGK16gGo0+8QJ8MzV3vKLzBBsbrBQTL7KIzrKXtoIlH4oro/dDaa97VU+iycDVA== sig=gURlNzID2Em5zuQpxi21CP4huCT97DJfKVJNtJKiYRidUJr0M5Xg2ffM0ySoeaHaw7yna+Bp0uyFIn3jg3idBg== e=found last=11 s=23 in addShifted_NP",
                "pub=MCowBQYDK2VwAyEAOff3r56/XDlzQpcmQXsAaGPUJXoTaMxWT4JB3QR6ApQ= priv=MC4CAQAwBQYDK2VwBCIEIAT1wftFaY+xSWt5vRqkwKReGc69fDuyaB4+EHlDEED7 msg=irBUnXl7Wt+f+6eAK8skK8L8jZne5GTTo2KTuPofbTdWhzy/aDVHCwT1wftFaY+xSWt5vRqkwKReGc69fDuyaA== sig=S7+EnEEp21tm3fGPMJ1j5RFX/lCLU5OEiCqfZWzb3TrJQqlPdoIsOQ9DX2xC+QuYbM0rcXmGb8/cjenqLs2bBA== e=found last=11 s=24 in addShifted_NP",
                "pub=MCowBQYDK2VwAyEAS8n5JxAl5aXpOc6IumYPgzaq+EGhl5gCjv5/SYteKxw= priv=MC4CAQAwBQYDK2VwBCIEIGacq7r9Dvz0HrcROukmNgn70AtSBbcFgMuNhTmKnBJY msg=TsW39+nqc7muxR8fEoh5da7fERd48uVnbCwLB00TagB5w/c7z17VwlPT02acq7r9Dvz0HrcROukmNgn70AtSBQ== sig=o5Bg/3GLULzpO0rEJVFA0pCBDvYt9qv19jDxq5kSG90nKpe2TZaXBbgsu73rXb4nxZGPYJb4cCKafprI1fC+Cg== e=found last=11 s=25 in addShifted_NP",
                "pub=MCowBQYDK2VwAyEA8AacbY1mAXw6ibYvCdT0i7rKvzyX8f7UXcUjXjcdYIw= priv=MC4CAQAwBQYDK2VwBCIEIHEQL9at1ZdynBSsKcUXHmvfuPD25T7Axsd74VFV4fqW msg=Xg/2qyCC/85dy0DK9JqfHHEQL9at


harfbuzz0b',
      'libhyphen.so.0': 'libhyphen0',
      'libjpeg.so.8': 'libjpeg-turbo8',
      'liblcms2.so.2': 'liblcms2-2',
      'libmanette-0.2.so.0': 'libmanette-0.2-0',
      'libnotify.so.4': 'libnotify4',
      'libnspr4.so': 'libnspr4',
      'libnss3.so': 'libnss3',
      'libnssutil3.so': 'libnss3',
      'libOpenGL.so.0': 'libopengl0',
      'libopenjp2.so.7': 'libopenjp2-7',
      'libopus.so.0': 'libopus0',
      'libpango-1.0.so.0': 'libpango-1.0-0',
      'libpangocairo-1.0.so.0': 'libpangocairo-1.0-0',
      'libpng16.so.16': 'libpng16-16',
      'libproxy.so.1': 'libproxy1v5',
      'libsecret-1.so.0': 'libsecret-1-0',
      'libsmime3.so': 'libnss3',
      'libwayland-client.so.0': 'libwayland-client0',
      'libwayland-egl.so.1': 'libwayland-egl1',
      'libwayland-server.so.0': 'libwayland-server0',
      'libwebpdemux.so.2': 'libwebpdemux2',
      'libwoff2dec.so.1.0.2': 'libwoff1',
      'libX11-xcb.so.1': 'libx11-xcb1',
      'libX11.so.6': 'libx11-6',
      'libxcb-shm.so.0': 'libxcb-shm0',
      'libxcb.so.1': 'libxcb1',
      'libXcomposite.so.1': 'libxcomposite1',
      'libXcursor.so.1': 'libxcursor1',
      'libXdamage.so.1': 'libxdamage1',
      'libXext.so.6': 'libxext6',
      'libXfixes.so.3': 'libxfixes3',
      'libXi.so.6': 'libxi6',
      'libxkbcommon.so.0': 'libxkbcommon0',
      'libxml2.so.2': 'libxml2',
      'libXrandr.so.2': 'libxrandr2',
      'libXrender.so.1': 'libxrender1',
      'libxslt.so.1': 'libxslt1.1',
      'libXtst.so.6': 'libxtst6',
      'libicui18n.so.60': 'libicu70',
      'libicuuc.so.66': 'libicu70',
      'libicui18n.so.66': 'libicu70',
      'libwebp.so.6': 'libwebp6',
      'libenchant-2.so.2': 'libenchant-2-2',
      'libx264.so': 'libx264-163',
      'libvpx.so.7': 'libvpx7',
      'libatomic.so.1': 'libatomic1',
      'libevent-2.1.so.7': 'libevent-2.1-7'
    }
  },
  'ubuntu24.04-x64': {
    tools: ['xvfb', 'fonts-noto-color-emoji', 'fonts-unifont', 'libfontconfig1', 'libfreetype6', 'xfonts-cyrillic', 'x


// SPDX-License-Identifier: GPL-2.0+
/*
 *  DM tag test
 *
 *  Copyright (c) 2021 Linaro Limited
 *  Author: AKASHI Takahiro
 */

#include <dm/tag.h>
#include <dm/test.h> /* DM_TEST() */
#include <test/test.h> /* struct unit_test_state */
#include <test/ut.h> /* assertions */

/*
 * Test dm_tag_ptr() API
 */
static int dm_test_tag_ptr(struct unit_test_state *uts)
{
	ulong val;
	void *ptr = NULL;

	ut_assertok(dev_tag_set_ptr(uts->root, DM_TAG_EFI, &val));

	ut_assertok(dev_tag_get_ptr(uts->root, DM_TAG_EFI, &ptr));

	ut_asserteq_ptr(&val, ptr);

	ut_assertok(dev_tag_del(uts->root, DM_TAG_EFI));

	return 0;
}
DM_TEST(dm_test_tag_ptr, 0);

/*
 * Test dm_tag_val() API
 */
static int dm_test_tag_val(struct unit_test_state *uts)
{
	ulong val1 = 0x12345678, val2 = 0;

	ut_assertok(dev_tag_set_val(uts->root, DM_TAG_EFI, val1));

	ut_assertok(dev_tag_get_val(uts->root, DM_TAG_EFI, &val2));

	ut_asserteq_64(val1, val2);

	ut_assertok(dev_tag_del(uts->root, DM_TAG_EFI));

	return 0;
}
DM_TEST(dm_test_tag_val, 0);

/*
 * Test against an invalid tag
 */
static int dm_test_tag_inval(struct unit_test_state *uts)
{
	ulong val;

	ut_asserteq(-EINVAL, dev_tag_set_ptr(uts->root, DM_TAG_COUNT, &val));

	return 0;
}
DM_TEST(dm_test_tag_inval, 0);

/*
 * Test dm_tag_del_all() AP:
 */
static int dm_test_tag_del_all(struct unit_test_state *uts)
{
	ulong val;

	ut_assertok(dev_tag_set_ptr(uts->root, DM_TAG_EFI, &val));

	ut_assertok(dev_tag_del_all(uts->root));

	return 0;
}
DM_TEST(dm_test_tag_del_all, 0);


from brainrender import Scene
from brainrender.actor import Actor

def test_scene_creation():
    scene = Scene(root=False)
    scene.root
    noinset = Scene(inset=False, title="TEST")
    noinset.root

def test_scene_render_simple():
    scene = Scene()
    scene.render(interactive=False)

def test_scene_specials():
    scene = Scene()
    print(scene)
    str(scene)
    scene.content

def test_brain_regions():
    scene = Scene()
    th = scene.add_brain_region("TH")
    assert scene.actors[-1] == th
    assert isinstance(th, Actor)

    regs = scene.add_brain_region("MOs", "CA1")
    assert isinstance(regs, list)
    assert len(regs) == 2

    nan = scene.add_brain_region("MOs", "CA1")
    assert nan is None
    noone = scene.add_brain_region("what is this")
    assert noone is None

    scene.add_brain_region("TH", hemisphere="left")
    scene.add_brain_region("CA1", hemisphere="right")
    scene.add_brain_region("STN", hemisphere="right")

def test_labels():
    scene = Scene()
    th = scene.add_brain_region("TH")
    scene.add_label(th, "TH")

def test_scene_render():
    scene = Scene()
    scene.add_brain_region("TH")

    scene.render(interactive=False, zoom=1.4)

    scene.render(
        interactive=False,
        camera=dict(
            pos=(
                10705.845660949382,
                7435.678067378925,
                -36936.3695486442,
            ),
            viewup=(
                -0.0050579179155257475,
                -0.9965615097647067,
                -0.08270172139591858,
            ),
            clipping_range=(30461.81976236306, 58824.38622122339),
        ),
    )

def test_scene_slice():
    s = Scene()
    s.add_brain_region("TH")

    s.slice("frontal")

    ret = s.slice(
        "frontal",
    )
    assert ret is None

    s.slice("sagittal", close_actors=True)

    s = Scene()
    th = s.add_brain_region("TH")

    plane = s.atlas.get_plane(pos=[1999, 1312, 3421], norm=[1, -1, 2])
    s.slice(plane, actors=th)
    ret = s.slice(
        plane,
        actors=[th, s.root],
    )
    del s

def test_actor_removal():
    s = Scene()
    th = s.add_brain_region("TH")
    assert len(s.actors) == 2

    s.remove(th)
    assert len(s.actors) == 1

    s.remove("no actor")
    assert len(s.actors) == 1

def test_get_actors():
    s = Scene()
    th = s.add_brain_region("TH")

    found1 = s.get_actors(name="TH")
    assert len(found1) == 1
    assert th in found1

    found2 = s.get_actors(br_class="brain region")
    assert len(found2) == 2
    assert th in found2
    assert s.root in found2


_gpu": "auto",
}
```

プログラムを実行すると、DeepSpeed は [`Trainer`] から受け取った設定をログに記録します。
コンソールに渡されるため、最終的にどのような設定が渡されたのかを正確に確認できます。

<a id='deepspeed-config-passing'></a>

### Passing Configuration

このドキュメントで説明したように、通常、DeepSpeed 設定は json ファイルへのパスとして渡されますが、
トレーニングの設定にコマンド ライン インターフェイスを使用せず、代わりにインスタンスを作成します。
[`Trainer`] via [`TrainingArguments`] その後、`deepspeed` 引数については次のことができます
ネストされた `dict` を渡します。これにより、その場で構成を作成でき、それを書き込む必要がありません。
[`TrainingArguments`] に渡す前にファイル システムを変更します。

要約すると、次のことができます。

```python
TrainingArguments(..., deepspeed="/path/to/ds_config.json")
```

または：

```python
ds_config_dict = dict(scheduler=scheduler_params, optimizer=optimizer_params)
TrainingArguments(..., deepspeed=ds_config_dict)
```

### Shared Configuration

<Tip warning={true}>

このセクションは必読です

</Tip>

[`Trainer`] と DeepSpeed の両方が正しく機能するには、いくつかの設定値が必要です。
したがって、検出が困難なエラーにつながる可能性のある定義の競合を防ぐために、それらを構成することにしました。
[`Trainer`] コマンドライン引数経由。

さらに、一部の構成値はモデルの構成に基づいて自動的に導出されます。
複数の値を手動で調整することを忘れないでください。[`Trainer`] に大部分を任せるのが最善です
の設定を行います。

したがって、このガイドの残りの部分では、特別な設定値 `auto` が表示されます。これを設定すると、
正しい値または最も効率的な値に自動的に置き換えられます。これを無視することを自由に選択してください
推奨事項を参照し、値を明示的に設定します。この場合、次の点に十分注意してください。
[`Trainer`] 引数と DeepSpeed 設定は一致します。たとえば、同じものを使用していますか
学習率、バッチサイズ、または勾配累積設定?これらが一致しない場合、トレーニングは非常に失敗する可能性があります
方法を検出するのが難しい。あなたは警告を受けました。

DeepSpeed のみに固有の値や、それに合わせて手動で設定する必要がある値が他にも複数あります。
あなたの要望。

独自のプログラムで、DeepSpeed 構成をマスターとして変更したい場合は、次のアプローチを使用することもできます。
それに基づいて [`TrainingArguments`] を設定します。手順は次のとおりです。

1. マスター構成として使用する DeepSpeed 構成を作成またはロード


 (h maxHeap) Len() int           { return len(h) }
func (h maxHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h maxHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *maxHeap) Push(x interface{}) {
	*h = append(*h, x.(float64))
}
func (h *maxHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

type minHeap []float64

func (h minHeap) Len() int           { return len(h) }
func (h minHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h minHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *minHeap) Push(x interface{}) {
	*h = append(*h, x.(float64))
}
func (h *minHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

// addToHeaps adds a value to the appropriate heap,and keeps their sizes close.
// This is a direct translation of the addToHeaps function described in the
// paper.
func addToHeaps(min *minHeap, max *maxHeap, x float64) {
	// NB: There's an ambiguity in the paper here related to if-then/else
	// evaluation. This structure seems to yield the desired results.
	if min.Len() == 0 || x < (*min)[0] {
		heap.Push(max, x)
	} else {
		heap.Push(min, x)
	}
	if min.Len() > max.Len()+1 {
		heap.Push(max, heap.Pop(min))
	} else if max.Len() > min.Len()+1 {
		heap.Push(min, heap.Pop(max))
	}
}

// getMedian finds the median of the min and max heaps.
// This is a direct translation of the getMedian function described in the
// paper.
func getMedian(min minHeap, max maxHeap) float64 {
	if min.Len() > max.Len() {
		return min[0]
	}
	if max.Len() > min.Len() {
		return max[0]
	}
	return (max[0] + min[0]) / 2
}

// edmx implements the EDM-X algorithm.
// This algorithm runs in place, modifying the data.
func edmx(input []float64, delta int) int {
	input = normalize(input)
	var lmax, rmax maxHeap
	var lmin, rmin minHeap
	heap.Init(&lmax)
	heap.Init(&rmax)
	heap.Init(&lmin)
	heap.Init(&rmin)
	bestStat := math.Inf(-1)
	bestLoc := -1

	for i := 0; i < delta-1; i++ {
		addToHeaps(&lmin, &lmax, input[i])
	}
	for i := delta; i < len(input)-delta+1; i++ {
		addToHeaps(&lmin, &lmax, input[i-1])
		ml := getMedian(lmin, lmax)
		rmax, rmin = rmax[:0], rmin[:0]
		for j := i; j < i+delta-1; j++ {
			addToHeaps(&rmin, &rmax, input[j])
		}
		for j := i + delta; j < len(input)+1; j++ {
			addToHeaps(&rmin, &rmax, input[j-1])
			mr := getMedian(rmin, rmax)
			stat := float64(i*(j-i)) / float64(j) * (ml - mr) * (ml - mr)
			if stat > bestStat {
				bestStat = stat
				bestLoc = i
			}
		}
	}

	return bestLoc
}

// EDMX runs the EDM-X algor


, r2
	bl      Function_2019184
	mov     r1, #0x3
	mov     r0, r5
	mov     r2, r1
	mov     r3, #0x0
	bl      Function_2019184
	b       branch_223cb12
@ 0x223ca90

.thumb
branch_223ca90: @ 223ca90 :thumb
	mov     r0, r5
	mov     r1, #0x1
	mov     r3, #0x0
	bl      Function_20183c4
	mov     r0, r5
	mov     r1, #0x1
	bl      Function_2019ebc
	mov     r2, #0x0
	mov     r0, r5
	mov     r1, #0x1
	mov     r3, r2
	bl      Function_2019184
	mov     r0, r5
	mov     r1, #0x1
	mov     r2, #0x3
	mov     r3, #0x0
	bl      Function_2019184
	mov     r1, #0x2
	mov     r0, r5
	add     r2, sp, #0x70
	mov     r3, r1
	bl      Function_20183c4
	mov     r0, r5
	mov     r1, #0x2
	bl      Function_2019ebc
	mov     r2, #0x0
	mov     r0, r5
	mov     r1, #0x2
	mov     r3, r2
	bl      Function_2019184
	mov     r0, r5
	mov     r1, #0x2
	mov     r2, #0x3
	mov     r3, #0x0
	bl      Function_2019184
	mov     r0, r5
	mov     r1, #0x3
	add     r2, sp, #0x8c
	mov     r3, #0x2
	bl      Function_20183c4
	mov     r0, r5
	mov     r1, #0x3
	bl      Function_2019ebc
	mov     r2, #0x0
	mov     r0, r5
	mov     r1, #0x3
	mov     r3, r2
	bl      Function_2019184
	mov     r1, #0x3
	mov     r0, r5
	mov     r2, r1
	mov     r3, #0x0
	bl      Function_2019184
.thumb
branch_223cb12: @ 223cb12 :thumb
	ldr     r1, [pc, #0x64] @ 0x223cb78, (=0x4000008)
	mov     r0, #0x3
	ldrh    r2, [r1, #0x0]
	bic     r2, r0
	mov     r0, #0x1
	strh    r2, [r1, #0x0]
	mov     r1, r0
	bl      Function_201ff0c
	ldr     r4, [pc, #0x54] @ 0x223cb7c, (=0x2241320)
	add     r3, sp, #0x0
	ldmia   r4!, {r0,r1}
	mov     r2, r3
	stmia   r3!, {r0,r1}
	ldmia   r4!, {r0,r1}
	stmia   r3!, {r0,r1}
	ldmia   r4!, {r0,r1}
	stmia   r3!, {r0,r1}
	ldr     r0, [r4, #0x0]
	mov     r1, #0x4
	str     r0, [r3, #0x0]
	mov     r0, r5
	mov     r3, #0x0
	bl      Function_20183c4
	mov     r0, r5


transition-timing-function:ease;width:128px}.tab_blog .blog_icon.dashboard .blog_icon_active,.tab_post_type .post_type_icon.dashboard .post_type_icon_active{opacity:0}.tab_blog.selected .blog_icon.dashboard .blog_icon_active,.tab_post_type.selected .post_type_icon.dashboard .post_type_icon_active{opacity:1}.tab_blog.loading .blog_icon{opacity:0}.tab_blog.loading .blog_icon,.tab_blog.selected .blog_icon,.tab_post_type.loading .post_type_icon,.tab_post_type.selected .post_type_icon{margin-top:-10px;margin-bottom:10px}.tab_blog.selected .blog_icon .blog_icon_overlay,.tab_post_type.selected .post_type_icon .post_type_icon_overlay{opacity:0}.tab_blog.loading .spinner{left:50%;position:absolute!important;top:50%}.tab_switcher_safari .tab_blog .blog_icon,.tab_switcher_safari .tab_blog .blog_icon.dashboard .blog_icon_active,.tab_switcher_safari .tab_blog .blog_icon.dashboard .blog_icon_resting,.tab_switcher_safari .tab_post_type .post_type_icon,.tab_switcher_safari .tab_post_type .post_type_icon.dashboard .post_type_icon_active,.tab_switcher_safari .tab_post_type .post_type_icon.dashboard .post_type_icon_resting{-webkit-transition-duration:0.25s!important;-webkit-transition-property:opacity!important}#language_switcher{position:relative}#language_switcher .language_icon{cursor:pointer;display:inline-block;line-height:18px;height:18px;margin:0;padding:0;vertical-align:-5px;width:18px}#language_switcher .language_icon::before{background-image:url(/images/dashboard_controls/dashboard_controls_sprite.png);background-position:0 -1900px;background-repeat:no-repeat;content:'';display:block;height:15px;left:50%;margin:-8px 0 0 -8px;opacity:.35;position:absolute;top:50%;width:15px}#language_switcher .language_icon:hover::before,#language_switcher.show .language_icon::before{opacity:.85}#language_switcher.americas .language_icon::before{background-position:0 -1900px}#language_switcher.europe_africa .language_icon::before{background-position:0 -1950px}#language_switcher.asia_pacific .language_icon::before{background-position:0 -2000px}#language_switcher .language_icon{-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=35)"}#language_switcher .language_icon:hover,#language_switcher.show .language_icon{-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=85)"}#language_switcher .popover{display:none}#language_switcher.show .popover{display:block}#language_switcher .popover_menu_item{padding:0}#language_switcher .popover_menu_item a{color:#444;display:block;padding:7px 15px 7px 32px;position:relative;text-align:left}#language_switcher .popover_menu_item.current a::after{background:url(/images/ajax_post_forms/ajax_post_forms_sprite.png) -3px -3px no-repeat;content:'';display:block;height:14px;left:10px;margin:-7px 0 0 0;position:absolute;top:50%;width:14px}#language_switcher .popover_menu_item


SpaceSsData>> seasonSeriesList({
    required int? mid,
    required int pn,
  }) async {
    var res = await Request().get(
      Api.seasonSeries,
      queryParameters: {
        'mid': mid,
        'page_num': pn,
        'page_size': 10,
      },
    );
    if (res.data['code'] == 0) {
      return Success(
        SpaceSsData.fromJson(res.data['data']?['items_lists'] ?? {}),
      );
    } else {
      return Error(res.data['message']);
    }
  }

  static Future<LoadingState<SpaceArchiveData>> spaceArchive({
    required ContributeType type,
    required int? mid,
    String? aid,
    String? order,
    String? sort,
    int? pn,
    int? next,
    int? seasonId,
    int? seriesId,
    bool? includeCursor,
  }) async {
    final params = {
      'aid': ?aid,
      'build': 8430300,
      'version': '8.43.0',
      'c_locale': 'zh_CN',
      'channel': 'master',
      'mobi_app': 'android',
      'platform': 'android',
      's_locale': 'zh_CN',
      'ps': 20,
      'pn': ?pn,
      'next': ?next,
      'season_id': ?seasonId,
      'series_id': ?seriesId,
      'qn': type == ContributeType.video ? 80 : 32,
      'order': ?order,
      'sort': ?sort,
      'include_cursor': ?includeCursor,
      'statistics': Constants.statisticsApp,
      'vmid': mid,
    };
    var res = await Request().get(
      switch (type) {
        ContributeType.video => Api.spaceArchive,
        ContributeType.charging => Api.spaceChargingArchive,
        ContributeType.season => Api.spaceSeason,
        ContributeType.series => Api.spaceSeries,
        ContributeType.bangumi => Api.spaceBangumi,
        ContributeType.comic => Api.spaceComic,
      },
      queryParameters: params,
      options: Options(
        headers: {
          'bili-http-engine': 'cronet',
          'user-agent': Constants.userAgentApp,
        },
      ),
    );
    if (res.data['code'] == 0) {
      return Success(SpaceArchiveData.fromJson(res.data['data']));
    } else {
      return Error(res.data['message']);
    }
  }

  static Future<LoadingState<SpaceAudioData>> spaceAudio({
    required int page,
    required mid,
  }) async {
    var res = await Request().get(
      Api.spaceAudio,
      queryParameters: {
        'pn': page,
        'ps': 20,
        'order': 1,
        'uid': mid,
        'web_location': 333.1387,
      },
    );
    if (res.data['code'] == 0) {
      return Success(SpaceAudioData.fromJson(res.data['data']));
    } else {
      return Error(res.data['message']);
    }
  }

  static Future<LoadingState<SpaceCheeseData>> spaceCheese({
    required int page,
    required mid,
  }) async {
    var res = await Request().get(
      Api.spaceCheese,
      queryParameters: {
        'pn': page,
        'ps': 30,
        'mid': mid,
        'web_location': 333.1387,
      },
    );
    if (res.data['code'] == 0) {
      return Success(SpaceCheeseData.fromJson(res.data['data']));
    } else {
      return Error(res.data['message']);
    }
  }

  static Future<LoadingState> spaceStory({
    required mid,


This will start a client on your local laptop, proxying connections on port 8479 to `mongodb-service:27017` as seen from the proxy.

```
soxy proxy -U ws://soxy-server.com:8080 -L :8479 -R mongodb-service:27017
```

If you have `soxy` behind an HTTPS ingress or reverse proxy, you need to use

```
soxy proxy -U wss://soxy-server.com:8080 -L :8479 -R mongodb-service:27017
```
> Notice the extra `s` in `wss`

You can now connect to the remote service from your workstation as follows

```
mongo --host 127.0.0.1 --port 8479
```

## DEMO

### docker-compose
The included [docker-compose.yml](docker-compose.yml) sets up a demo environment with

* Frontend and backend networks to mimic real world topologies
* Backend Redis DB service
* Backend `soxy` service
* Frontend nginx service
* Frontend `soxy` client exposes `backend-redis:6379`

Data path is redis-cli -> local TCP socket(soxy) -> websocket connection through nginx -> soxy server -> redis container.

```
✔ ~/go/src/github.com/xandout/soxy [master|✔]
02:10 # docker-compose up -d
Creating network "soxy_back" with the default driver
Creating network "soxy_front" with the default driver
Creating soxy_backend-redis_1 ... done
Creating soxy_backend-soxy-server_1 ... done
Creating soxy_frontend-nginx_1      ... done
Creating soxy_frontend-soxy-client_1 ... done
✔ ~/go/src/github.com/xandout/soxy [master|✔]
02:14 # docker run --rm -it redis redis-cli -h 192.168.0.250 INFO CPU
# CPU
used_cpu_sys:0.025931
used_cpu_user:0.153783
used_cpu_sys_children:0.001324
used_cpu_user_children:0.001367
```

### Just a quick local demo proxying redis
```
✔ ~/go/src/github.com/xandout/soxy [master|✔]
01:24 # docker run --rm -d -p 6379:6379 redis
7cefb999a6a23e03883a41776b74304506249ae0368b81cd8308865f826fe404
✔ ~/go/src/github.com/xandout/soxy [master|✔]
01:22 # docker run --rm -d -p 8080:8080 xandout/soxy serve -p :8080
6690096b456e64baf3223df80f590ea2e0962c8c3f07bcdebcb9b0f25dadb3e6
✔ ~/go/src/github.com/xandout/soxy [master|✔]
01:22 # docker run --rm -d -p 8081:8081 xandout/soxy proxy -U ws://192.168.0.250:8080 -L :8081 -R 192.168.0.250:6379
423ccbbfa4b6d961f4fb1b740e93bf38bfda9a96d03c56e3f8188b87d4a88d5b
✔ ~/go/src/github.


shift, a_shift]] += scr_val;
                    } else if a_shift == b_shift {
                        rhs2[[i, j, a_shift, b_shift]] += scr_ijab[[i, j, a, b]];
                    }
                }
            }
        }
    }
```

这一步是朴实无华的 for 循环赋值。好像没有更好的办法了。

不过这里有一个性能上需要留意的地方。

- RSTSR 的指标索引 (通过方括号 operator `[]`) 是安全的，它会充分检查维度边界，确认索引的正确性。但这种维度检查实际上会严重影响程序效率。如果我们能确保指标不可能越界，可以对张量作 unsafe 的 `index_uncheck` 或 `index_mut_uncheck` 索引以避免冗余的维度检查。
- 高维度张量索引的代价总是比低维度张量要大。因此，如果在嵌套循环的某个阶段可以将问题转化为低维度张量，就可以取出子张量的视窗，在内层循环中索引低维度的子张量。
- 动态维度张量索引的代价总是比固定维度张量要大。如果张量索引这一步是性能瓶颈，那么最好通过 `into_dim` 把张量转到确定的维度上。

综合这三点，更新后的赋值代码会是

```rust
// in batched (a, b) parallel iter
    // increment rhs2 from scr_ijab with symmetry
    for i in 0..nocc {
        for j in 0..nocc {
            let rhs2_ij = rhs2.i((i, j)).into_dim::<Ix2>();
            let rhs2_ji = rhs2.i((j, i)).into_dim::<Ix2>();
            let mut rhs2_ij = unsafe { rhs2_ij.force_mut() };
            let mut rhs2_ji = unsafe { rhs2_ji.force_mut() };
            let scr_ij = scr_ijab.i((i, j)).into_dim::<Ix2>();

            for a in 0..nbatch_a {
                let a_shift = a + a_start;
                for b in 0..nbatch_b {
                    let b_shift = b + b_start;
                    unsafe {
                        if a_shift > b_shift {
                            let scr_val = scr_ij.index_uncheck([a, b]);
                            *rhs2_ij.index_mut_uncheck([a_shift, b_shift]) += scr_val;
                            *rhs2_ji.index_mut_uncheck([b_shift, a_shift]) += scr_val;
                        } else if a_shift == b_shift {
                            *rhs2_ij.index_mut_uncheck([a_shift, b_shift]) += scr_ij.index_uncheck([a, b]);
                        }


llback function where the callback function takes three parameters.
        /// The first is the cURL resource, the second is a file-descriptor resource,
        /// and the third is length. Return the string containing the data.
        /// This function gets called by libcurl at a frequent interval during data
        /// transfer.
        /// </summary>
        // This probably doesnt work in PHP: Returning a
        // non-zero value from this delegate will cause libcurl to abort the
        // transfer and return <c>CURLE_ABORTED_BY_CALLBACK"</c>.
        [ImplementsConstant("CURLOPT_PROGRESSFUNCTION")]
        CURLOPT_PROGRESSFUNCTION = 20056,

        /// <summary>
        /// Set HTTP proxy to use. The parameter should be a <c>string</c> holding
        /// the host name or dotted IP address. To specify port number in this
        /// string, append <c>:[port]</c> to the end of the host name. The proxy
        /// string may be prefixed with <c>[protocol]://</c> since any such prefix
        /// will be ignored. The proxy's port number may optionally be specified
        /// with the separate option <c>CURLOPT_PROXYPORT</c>.
        /// <para>
        /// NOTE: when you tell the library to use an HTTP proxy, libcurl will
        /// transparently convert operations to HTTP even if you specify an FTP
        /// URL etc. This may have an impact on what other features of the library
        /// you can use, such as <c>CURLOPT_QUOTE</c> and similar FTP specifics
        /// that don't work unless you tunnel through the HTTP proxy. Such tunneling
        /// is activated with <c>CURLOPT_HTTPPROXYTUNNEL</c>.
        /// </para>
        /// </summary>
        [ImplementsConstant("CURLOPT_PROXY")]
        CURLOPT_PROXY = 10004,
        /// <summary>
        /// Pass a bitmask of <see cref="CURLhttpAuth"/> as the paramter, to tell
        /// libcurl what authentication method(s) you want it to use for your proxy
        /// authentication. If more than one bit is set, libcurl will first query the
        /// site to see what authentication methods it supports and then pick the best
        /// one you allow it to use. Note that for some methods, this will induce an
        /// extra network round-trip. Set the actual name and password with the
        /// <c>CURLOPT_PROXYUSERPWD</c> option. The bitmask can be constructed by
        /// or'ing together the <see cref="CURLhttpAuth"/> bits. As of this writing,
        /// only <see cref="CURLhttpAuth.CURLAUTH_BASIC"/> and
        /// <see cref="CURLhttpAuth.CURLAUTH_NTLM"/> work. (Added in 7.10.7)
        /// </summary>
        [ImplementsConstant("CURLOPT_PROXYAUTH")]
        CURLOPT_PROXYAUTH = 111,
        /// <summary>
        /// Pass an <c>int</c> with this option to set the proxy port to connect
        /// to unless it is specified in the proxy string <c>CURLOPT_PROXY</c>.
        /// </summary>
        [ImplementsConstant("CURLOPT_PROXYPORT")]
        CURLOPT_PROXYPORT = 59,
        /// <summary>
        /// Pass a <see cref="CURLproxyType"/> to set type of the proxy.
        /// </summary>
        [ImplementsConstant("CURLOPT_PROXYTYPE")]
        CURLOPT_PROXYTYPE = 101,
        /// <summary>
        /// Pass a <c>string</c> as parameter, which should be
        /// <c>[user name]:[password]</c> to use for the connection to the
        /// HTTP proxy. Use <c>CURLOPT_PROXYAUTH</c> to decide authentication method.
        /// </summary>
        [ImplementsConstant("CURLOPT_PROXYUSERPWD")]
        CURLOPT_PROXYUSERPWD = 10006,

        /// <summary