 Tuple" + numFields + "[tuples.size()]);");
		w.println("\t}");

		// foot
		w.println("}");
	}

	private static String HEADER =
		"/***********************************************************************************************************************\n" +
		" *\n" +
		" * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu)\n" +
		" *\n" +
		" * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with\n" +
		" * the License. You may obtain a copy of the License at\n" +
		" *\n" +
		" *     http://www.apache.org/licenses/LICENSE-2.0\n" +
		" *\n" +
		" * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on\n" +
		" * an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\n" +
		" * specific language governing permissions and limitations under the License.\n" +
		" *\n" +
		" **********************************************************************************************************************/\n" +
		"\n" +
		"// --------------------------------------------------------------\n" +
		"//  THIS IS A GENERATED SOURCE FILE. DO NOT EDIT!\n" +
		"//  GENERATED FROM " + TupleGenerator.class.getName() + ".\n" +
		"// --------------------------------------------------------------\n\n\n";
}
/***********************************************************************************************************************
 *
 * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu)
 *
 * 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 eu.stratosphere.api.java.io;

import java.util.ArrayList;
import java.util.Arrays;

import org.apache.commons.lang3.Validate;

import eu.stratosphere.api.java.ExecutionEnvironment;
import eu.stratosphere.api.java.operators.DataSource;
//CHECKSTYLE.OFF: AvoidStarImport - Needed for TupleGenerator
import eu.stratosphere.api.java.tuple.*;
//CHECKSTYLE.ON: AvoidStarImport
import eu.stratosphere.api.java.typeutils.TupleTypeInfo;
import eu.stratosphere.api.java.typeutils.TypeExtractor;
import eu.stratosphere.core.fs.Path;

/**
 * A builder class to instantiate a CSV parsing data source. The CSV reader configures the field types,
 * the delimiters (row and field),  the fields that should be included or skipped, and other flags
 * such as whether to skip the initial line as the header.
 */
public class CsvReader {

	private final Path path;

	private final ExecutionEnvironment executionContext;

	protected boolean[] includedMask;

	protected String lineDelimiter = CsvInputFormat.DEFAULT_LINE_DELIMITER;

	protected char fieldDelimiter = CsvInputFormat.DEFAULT_FIELD_DELIMITER;

	protected


}

	var resource T
	var schema any
	if dc.FetchWithArgs != nil {
		resource, schema, err = dc.FetchWithArgs(s, cmd, args)
	} else {
		resource, schema, err = dc.Fetch(s, cmd, args[0])
	}
	if err != nil {
		return err
	}

	// resource is an interface that always has a type, so the interface is never nil
	// (i.e. == nil) is always false.
	if reflect.ValueOf(resource).IsNil() {
		return fmt.Errorf("%s not found: %s", dc.ResourceNameSingular, strings.Join(args, " "))
	}

	switch {
	case outputFlags.IsSet("json"):
		return util.DescribeJSON(schemaOut, schema)
	case outputFlags.IsSet("yaml"):
		return util.DescribeYAML(schemaOut, schema)
	case outputFlags.IsSet("format"):
		return util.DescribeFormat(schemaOut, resource, outputFlags["format"][0])
	default:
		return dc.PrintText(s, cmd, resource)
	}
}
package keeper_test

import (
	"math"
	"time"

	storetypes "cosmossdk.io/store/types"
	"github.com/cosmos/cosmos-sdk/baseapp"
	"github.com/hetu-project/hetu/v1/app"
	"github.com/hetu-project/hetu/v1/testutil"
	"github.com/hetu-project/hetu/v1/x/epochs/types"
	evm "github.com/hetu-project/hetu/v1/x/evm/types"
)

// Test helpers
func (suite *KeeperTestSuite) DoSetupTest() {
	checkTx := false

	// init app
	suite.app = app.Setup(checkTx, nil)

	// setup context
	header := testutil.NewHeader(
		1, time.Now().UTC(), "hetu_560001-1", suite.consAddress, nil, nil,
	)
	suite.ctx = suite.app.BaseApp.NewContextLegacy(checkTx, header)
	suite.ctx = suite.ctx.WithBlockGasMeter(storetypes.NewGasMeter(math.MaxUint64))

	// setup query helpers
	queryHelper := baseapp.NewQueryServerTestHelper(suite.ctx, suite.app.InterfaceRegistry())
	types.RegisterQueryServer(queryHelper, suite.app.EpochsKeeper)
	suite.queryClient = types.NewQueryClient(queryHelper)

	// Set epoch start time and height for all epoch identifiers
	identifiers := []string{types.WeekEpochID, types.DayEpochID}
	for _, identifier := range identifiers {
		epoch, found := suite.app.EpochsKeeper.GetEpochInfo(suite.ctx, identifier)
		suite.Require().True(found)
		epoch.StartTime = suite.ctx.BlockTime()
		epoch.CurrentEpochStartHeight = suite.ctx.BlockHeight()
		suite.app.EpochsKeeper.SetEpochInfo(suite.ctx, epoch)
	}
}

func (suite *KeeperTestSuite) Commit() {
	suite.CommitAfter(time.Nanosecond)
}

func (suite *KeeperTestSuite) CommitAfter(t time.Duration) {
	var err error
	suite.ctx, err = testutil.Commit(suite.ctx, suite.app, t, nil)
	suite.Require().NoError(err)

	queryHelper := baseapp.NewQueryServerTestHelper(suite.ctx, suite.app.InterfaceRegistry())
	evm.RegisterQueryServer(queryHelper, suite.app.EvmKeeper)
	suite.queryClientEvm = evm.NewQueryClient(queryHelper)
}
package base_test

import (
	"cmp"
	"fmt"
	"slices"
	"testing"


simplified, compare);
    }

    #[test]
    fn multilinestring() {
        let mline = MultiLineString::new(vec![LineString::from(vec![
            (0.0, 0.0),
            (5.0, 4.0),
            (11.0, 5.5),
            (17.3, 3.2),
            (27.8, 0.1),
        ])]);

        let mline2 = mline.simplify(&1.0);

        assert_eq!(
            mline2,
            MultiLineString::new(vec![LineString::from(vec![
                (0.0, 0.0),
                (5.0, 4.0),
                (11.0, 5.5),
                (27.8, 0.1),
            ])])
        );
    }

    #[test]
    fn polygon() {
        let poly = polygon![
            (x: 0., y: 0.),
            (x: 0., y: 10.),
            (x: 5., y: 11.),
            (x: 10., y: 10.),
            (x: 10., y: 0.),
            (x: 0., y: 0.),
        ];

        let poly2 = poly.simplify(&2.);

        assert_eq!(
            poly2,
            polygon![
                (x: 0., y: 0.),
                (x: 0., y: 10.),
                (x: 10., y: 10.),
                (x: 10., y: 0.),
                (x: 0., y: 0.),
            ],
        );
    }

    #[test]
    fn multipolygon() {
        let mpoly = MultiPolygon::new(vec![polygon![
            (x: 0., y: 0.),
            (x: 0., y: 10.),
            (x: 5., y: 11.),
            (x: 10., y: 10.),
            (x: 10., y: 0.),
            (x: 0., y: 0.),
        ]]);

        let mpoly2 = mpoly.simplify(&2.);

        assert_eq!(
            mpoly2,
            MultiPolygon::new(vec![polygon![
                (x: 0., y: 0.),
                (x: 0., y: 10.),
                (x: 10., y: 10.),
                (x: 10., y: 0.),
                (x: 0., y: 0.)
            ]]),
        );
    }

    #[test]
    fn simplify_negative_epsilon() {
        let ls = line_string![
            (x: 0., y: 0.),
            (x: 0., y: 10.),
            (x: 5., y: 11.),
            (x: 10., y: 10.),
            (x: 10., y: 0.),
        ];
        let simplified = ls.simplify(&-1.0);
        assert_eq!(ls, simplified);
    }

    #[test]
    fn simplify_idx_negative_epsilon() {
        let ls = line_string![
            (x: 0., y: 0.),
            (x: 0., y: 10.),
            (x: 5., y: 11.),
            (x: 10., y: 10.),
            (x: 10., y: 0.),
        ];
        let indices = ls.simplify_idx(&-1.0);
        assert_eq!(vec![0usize, 1, 2, 3, 4], indices);
    }
}
use crate::log;
use crate::sinks::*;

use APU_SAMPLING_FREQUENCY;
use CPU_FREQUENCY;

const APU_SAMPLING_RATE: f64 = APU_SAMPLING_FREQUENCY / CPU_FREQUENCY;
const APU_FRAME_COUNTER_RATE: f64 = 240.0 / CPU_FREQUENCY;

#[derive(Debug, Eq, PartialEq)]
pub enum ApuChannel {
    Pulse1,
    Pulse2,
    Triangle,
    Noise,
}

#[derive(Debug)]
enum FrameCounterMode {
    FourSteps,


# Generated by Django 5.1.6 on 2025-04-10 17:24

import django.db.models.deletion
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('student', '0002_subject_studentprofile_subjects'),
    ]

    operations = [
        migrations.CreateModel(
            name='Attendance',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('date', models.DateField()),
                ('present', models.BooleanField(default=False)),
                ('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='student.studentprofile')),
                ('subject', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='student.subject')),
            ],
            options={
                'unique_together': {('student', 'subject', 'date')},
            },
        ),
    ]


      .setDisabledMessage(getString(string.shortcut_disabled_message))
      .setIntent(
        Intent(this, CustomMainActivity::class.java).apply {
          action = ACTION_NEW_TAB
        }
      )
      .build()
    ShortcutManagerCompat.addDynamicShortcuts(this, listOf(newTabShortcut))
  }

  override fun openSearch(searchString: String, isOpenedFromTabView: Boolean, isVoice: Boolean) {
    navigate(
      CustomDestination.Search.createRoute(
        searchString = searchString,
        isOpenedFromTabView = isOpenedFromTabView,
        isVoice = isVoice
      ),
      NavOptions.Builder().setPopUpTo(searchFragmentRoute, inclusive = true).build()
    )
  }

  override fun openPage(
    pageUrl: String,
    zimReaderSource: ZimReaderSource?,
    shouldOpenInNewTab: Boolean
  ) {
    var zimFileUri = ""
    if (zimReaderSource != null) {
      zimFileUri = zimReaderSource.toDatabase()
    }
    val navOptions = NavOptions.Builder()
      .setLaunchSingleTop(true)
      .setPopUpTo(readerFragmentRoute, inclusive = true)
      .build()
    // Navigate to reader screen.
    navigate(CustomDestination.Reader.route, navOptions)
    // Set arguments on current destination(reader).
    setNavigationResultOnCurrent(zimFileUri, ZIM_FILE_URI_KEY)
    setNavigationResultOnCurrent(pageUrl, PAGE_URL_KEY)
    setNavigationResultOnCurrent(shouldOpenInNewTab, SHOULD_OPEN_IN_NEW_TAB)
  }

  override fun hideBottomAppBar() {
    // Do nothing since custom apps does not have the bottomAppBar.
  }

  override fun showBottomAppBar() {
    // Do nothing since custom apps does not have the bottomAppBar.
  }

  // Outdated shortcut id(new_tab)
  // Remove if the application has the outdated shortcut.
  private fun removeOutdatedIdShortcuts() {
    ShortcutManagerCompat.getDynamicShortcuts(this).forEach {
      if (it.id == "new_tab") {
        ShortcutManagerCompat.removeDynamicShortcuts(this, arrayListOf(it.id))
      }
    }
  }
}
/*
 * Kiwix Android
 * Copyright (c) 2022 Kiwix <android.kiwix.org>
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

package org.kiwix.kiwixmobile.search

import android.view.KeyEvent
import androidx.compose.ui.test.assert
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.ComposeContentTestRule
import androidx.compose.ui.test.onAllNodesWithTag
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTextClearance
import androidx.compose.ui.test.performTextInput
import androidx.test.espresso.web.sugar.Web.onWebView
import androi


持库（v4库）的 Fragment
    // 接入后可以使用  AndroidInjection.inject(activity) 和  AndroidSupportInjection.inject(f)
    AndroidSupportInjectionModule::class,
    AppModule::class,
    ActivityBindModule::class
])
interface AppComponent {
    /**
     * 通过 @Component.Builder 增加builder方法，提供Application 注入方法。
     */
    @Component.Builder
    interface Builder {
        //@BindsInstance注解的作用，只能在 Component.Builder 中使用
        //创建 Component 的时候绑定依赖实例
        @BindsInstance
        fun application(application: Application): Builder

        fun build(): AppComponent
    }

    fun inject(gsyGithubApplication: GSYGithubApplication)
}

@Module(includes = [ViewModelModule::class])
class AppModule {
    @Singleton
    @Provides
    fun providerRetrofit(): Retrofit {
        return RetrofitFactory.instance.retrofit
    }

    @Singleton
    @Provides
    fun providerRealmFactory(): RealmFactory {
        return RealmFactory.instance
    }
}

package com.shuyu.github.kotlin.model

import android.os.Parcel
import android.os.Parcelable

/**
 * Created by guoshuyu
 * Date: 2018-11-28
 */
class AIDLResultModel() : Parcelable {

    var name: String? = null

    var time: Long = 0

    constructor(parcel: Parcel) : this() {
        name = parcel.readString()
        time = parcel.readLong()
    }

    override fun writeToParcel(dest: Parcel, flags: Int) {
        dest.writeString(name)
        dest.writeLong(time)
    }

    override fun describeContents(): Int = 0

    companion object CREATOR : Parcelable.Creator<AIDLResultModel> {
        override fun createFromParcel(source: Parcel): AIDLResultModel {
            val result = AIDLResultModel()
            result.name = source.readString()
            result.time = source.readLong()
            return result
        }

        override fun newArray(size: Int): Array<AIDLResultModel?> {
            return arrayOfNulls(size)
        }
    }

    override fun toString(): String = "name : $name time : $time "

}package com.shuyu.github.kotlin.repository

import android.app.Application
import android.content.Context
import com.shuyu.github.kotlin.common.config.AppConfig
import com.shuyu.github.kotlin.common.net.*
import com.shuyu.github.kotlin.common.utils.Debuger
import com.shuyu.github.kotlin.common.utils.GSYPreference
import com.shuyu.github.kotlin.model.AppGlobalModel
import com.shuyu.github.kotlin.model.bean.Event
import com.shuyu.github.kotlin.model.bean.Notification
import com.shuyu.github.kotlin.model.bean.User
import com.shuyu.github.kotlin.model.bean.UserInfoRequestModel
import com.shuyu.github.kotlin.model.conversion.EventConversion
import com.shuyu.github.kotlin.model.conversion.UserConversion
import com.shuyu.github.kotlin.model.ui.UserUIModel
import com.shuyu.github.kotlin.repository.dao.UserDao
import com.shuyu.github.kotlin.service.NotificationService
import com.shuyu.github.kotlin.service.RepoService
import com.shuyu.github.kotlin.service.UserService
import io.reactivex.Observable
import io.reactivex.functions.BiFunction
import io.reactivex.functions.Function
import okhttp3.ResponseBody
import retrofit2.Response
import retrofit2.Retrofit
import javax.inject.Inject

/**
 * 用户相关数据获取
 */
class UserRepository @Inject constructor(private val retrofit: Retrofit, private val appGlobalModel: AppGlobalModel,
                                         private val applic


//===== Copyright  1996-2006, Valve Corporation, All rights reserved. ======//
//
// Base class for windows that draw vgui in Maya
//
//===========================================================================//

#ifndef VSVGUIWINDOW_H
#define VSVGUIWINDOW_H

#ifdef _WIN32
#pragma once
#endif

#include "imayavgui.h"

//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
class IMayaVGui;

//-----------------------------------------------------------------------------
// The singleton is defined here twice just so we don't have to include valvemaya.h also
//-----------------------------------------------------------------------------
extern IMayaVGui *g_pMayaVGui;

//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
namespace vgui
{
	class EditablePanel;
}

//-----------------------------------------------------------------------------
// Creates, destroys a maya vgui window
//-----------------------------------------------------------------------------
void CreateMayaVGuiWindow( HWND in_hParent, vgui::EditablePanel *pRootPanel, const char *pPanelName );
void DestroyMayaVGuiWindow( const char *pPanelName );

//-----------------------------------------------------------------------------
// Factory used to install vgui windows easily
//-----------------------------------------------------------------------------
class CVsVguiWindowFactoryBase : public IMayaVguiWindowFactory
{
public:
	CVsVguiWindowFactoryBase( const char *pWindowTypeName );

	// Registers/deregisters all vgui windows
	static void RegisterAllVguiWindows( );
	static void UnregisterAllVguiWindows( );

protected:
	const char *m_pWindowTypeName;

private:
	CVsVguiWindowFactoryBase *m_pNext;
	static CVsVguiWindowFactoryBase *s_pFirstCommandFactory;
};

template< class T >
class CVsVguiWindowFactory : public CVsVguiWindowFactoryBase
{
	typedef CVsVguiWindowFactoryBase BaseClass;

public:
	CVsVguiWindowFactory( const char *pWindowTypeName ) : BaseClass( pWindowTypeName )
	{
	}

	virtual void CreateVguiWindow(HWND in_hParent,  const char *pPanelName )
	{
		T *pVguiPanel = new T;
		CreateMayaVGuiWindow( in_hParent, pVguiPanel, pPanelName );
	}

	virtual void DestroyVguiWindow( const char *pPanelName )
	{
		DestroyMayaVGuiWindow( pPanelName );
	}

private:
};

#define INSTALL_MAYA_VGUI_WINDOW( _className, _windowTypeName )	\
	static CVsVguiWindowFactory< _className > s_VsVguiWindowFactory##_className##( _windowTypeName )

#endif // VSVGUIWINDOW_H


dict': {
            'id': '151549',
            'ext': 'mp4',
            'title': 'Gyvūnų pasaulis',
            'description': '',
            'view_count': int,
            'duration': 1264,
            'upload_date': '20220108',
            'thumbnail': r're:^https?://.*\.jpg$',
            'episode_number': 16,
            'series': 'Gyvūnų pasaulis',
            'episode': 'Episode 16'
        },
        'params': {'skip_download': True}
    }]

    def _real_extract(self, url):
        id = self._match_id(url)
        video_json = self._download_json(f'https://lnk.lt/api/video/video-config/{id}', id)['videoInfo']
        formats, subtitles = [], {}
        if video_json.get('videoUrl'):
            fmts, subs = self._extract_m3u8_formats_and_subtitles(video_json['videoUrl'], id)
            formats.extend(fmts)
            subtitles = self._merge_subtitles(subtitles, subs)
        if video_json.get('videoFairplayUrl') and not video_json.get('drm'):
            fmts, subs = self._extract_m3u8_formats_and_subtitles(video_json['videoFairplayUrl'], id)
            formats.extend(fmts)
            subtitles = self._merge_subtitles(subtitles, subs)

        return {
            'id': id,
            'title': video_json.get('title'),
            'description': video_json.get('description'),
            'view_count': video_json.get('viewsCount'),
            'duration': video_json.get('duration'),
            'upload_date': unified_strdate(video_json.get('airDate')),
            'thumbnail': format_field(video_json, 'posterImage', 'https://lnk.lt/all-images/%s'),
            'episode_number': int_or_none(video_json.get('episodeNumber')),
            'series': video_json.get('programTitle'),
            'formats': formats,
            'subtitles': subtitles,
        }


o
    local key = coords["latitude"] .. "," .. coords["longitude"]
    if not t[key] then
      t[key] = {}
    end
    table.insert(t[key], ip)
  end

  return t
end

-- Order in which field names will be shown in XML
local field_order = {
  "latitude",
  "longitude",
  "city",
  "region",
  "country"
}

--- Location object
--
-- The object supports setting the following fields using functions like
-- set_fieldname:
-- * latitude
-- * longitude
-- * city
-- * region
-- * country
--
-- The location object is suitable for returning from a script, and will
-- produce appropriate string and structured XML output.
Location = {
  new = function(self,o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    return o
  end,

  -- Ensure fields are put in the XML in proper order
  __pairs = function(self)
    local function iterator ()
      for i, key in ipairs(field_order) do
        coroutine.yield(key, self[key])
      end
    end
    return coroutine.wrap(iterator)
  end,

  __tostring = function(self)
    local out = {
      ("coordinates: %s, %s"):format(self.latitude, self.longitude)
    }
    -- if any of these are nil, it doesn't increase #place
    local place = {self.city}
    place[#place+1] = self.region
    place[#place+1] = self.country
    if #place > 0 then
      out[#out+1] = ("location: %s"):format(table.concat(place, ", "))
    end

    return table.concat(out, "\n")
  end,
}

-- Generate setter functions
for _, field in ipairs(field_order) do
  Location["set_" .. field] = function(self, value)
    self[field] = value
  end
end

return _ENV;


testData.errorCorrectionLevel);

    QZXing decoder(QZXing::DecoderFormat_QR_CODE);
    QString decodedData = decoder.decodeImage(generatedImage);
    bool wasDecoded = decoder.getLastDecodeOperationSucceded();

    testData.successful = (testData.data == decodedData);

    printLockMutex.lock();
    std::cout << "M[" << testData.mode.getName() << "], E[" << testData.errorCorrectionLevel << "], L[" << testData.data.size() << "]: " <<
                 "decoded=" << wasDecoded <<
                 ", match=" << testData.successful << std::endl;
    printLockMutex.unlock();
}

}
}

#include "BitVectorTests.h"

namespace zxing{
namespace qrcode{
namespace tests{

BitVectorTests::BitVectorTests()
{

}

void BitVectorTests::execute()
{
    testAppendBit();
    testAppendBits();
    testNumBytes();
}

unsigned long zxing::qrcode::tests::BitVectorTests::getUnsignedInt(BitArray &v, int index)
{
    long result = 0L;
    for (int i = 0, offset = index << 3; i < 32; i++) {
        if (v.get(offset + i)) {
            result |= 1L << (31 - i);
        }
    }
    return result;
}

void BitVectorTests::testAppendBit()
{
    BitArray v;
    assertEquals(0, v.getSizeInBytes());
    // 1
    v.appendBit(true);
    assertEquals(1, v.getSize());
    assertEquals(0x80000000ul, getUnsignedInt(v, 0));
    // 10
    v.appendBit(false);
    assertEquals(2, v.getSize());
    assertEquals(0x80000000ul, getUnsignedInt(v, 0));
    // 101
    v.appendBit(true);
    assertEquals(3, v.getSize());
    assertEquals(0xa0000000ul, getUnsignedInt(v, 0));
    // 1010
    v.appendBit(false);
    assertEquals(4, v.getSize());
    assertEquals(0xa0000000ul, getUnsignedInt(v, 0));
    // 10101
    v.appendBit(true);
    assertEquals(5, v.getSize());
    assertEquals(0xa8000000ul, getUnsignedInt(v, 0));
    // 101010
    v.appendBit(false);
    assertEquals(6, v.getSize());
    assertEquals(0xa8000000ul, getUnsignedInt(v, 0));
    // 1010101
    v.appendBit(true);
    assertEquals(7, v.getSize());
    assertEquals(0xaa000000ul, getUnsignedInt(v, 0));
    // 10101010
    v.appendBit(false);
    assertEquals(8, v.getSize());
    assertEquals(0xaa000000ul, getUnsignedInt(v, 0));
    // 10101010 1
    v.appendBit(true);
    assertEquals(9, v.getSize());
    assertEquals(0xaa800000ul, getUnsignedInt(v, 0));
    // 10101010 10
    v.appendBit(false);
    assertEquals(10, v.getSize());
    assertEquals(0xaa800000ul, getUnsignedInt(v, 0));
}

void BitVectorTests::testAppendBits()
{
    BitArray v;
    v.appendBits(0x1, 1);
    assertEquals(1, v.getSize());
    assertEquals(0x80000000ul, getUnsignedInt(v, 0));
    v = BitArray();
    v.appendBits(0xff, 8);
    assertEquals(8, v.getSize());
    assertEquals(0xff000000ul, getUnsign


    );
  }

  @override
  AutoDisposeFutureProviderElement<Map<String, double>> createElement() {
    return _CoingeckoPriceProviderElement(this);
  }

  @override
  bool operator ==(Object other) {
    return other is CoingeckoPriceProvider &&
        other.coingeckoAssetPairs == coingeckoAssetPairs;
  }

  @override
  int get hashCode {
    var hash = _SystemHash.combine(0, runtimeType.hashCode);
    hash = _SystemHash.combine(hash, coingeckoAssetPairs.hashCode);

    return _SystemHash.finish(hash);
  }
}

@Deprecated('Will be removed in 3.0. Use Ref instead')
// ignore: unused_element
mixin CoingeckoPriceRef on AutoDisposeFutureProviderRef<Map<String, double>> {
  /// The parameter `coingeckoAssetPairs` of this provider.
  CoingeckoAssetPairs get coingeckoAssetPairs;
}

class _CoingeckoPriceProviderElement
    extends AutoDisposeFutureProviderElement<Map<String, double>>
    with CoingeckoPriceRef {
  _CoingeckoPriceProviderElement(super.provider);

  @override
  CoingeckoAssetPairs get coingeckoAssetPairs =>
      (origin as CoingeckoPriceProvider).coingeckoAssetPairs;
}

String _$coinGeckoPriceCacheHash() =>
    r'3e78897745b52bcec93384f449ac3b91a83949ae';

/// See also [CoinGeckoPriceCache].
@ProviderFor(CoinGeckoPriceCache)
final coinGeckoPriceCacheProvider =
    AsyncNotifierProvider<CoinGeckoPriceCache, CachedPrices>.internal(
      CoinGeckoPriceCache.new,
      name: r'coinGeckoPriceCacheProvider',
      debugGetCreateSourceHash:
          const bool.fromEnvironment('dart.vm.product')
              ? null
              : _$coinGeckoPriceCacheHash,
      dependencies: null,
      allTransitiveDependencies: null,
    );

typedef _$CoinGeckoPriceCache = AsyncNotifier<CachedPrices>;
// ignore_for_file: type=lint
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package
// GENERATED CODE - DO NOT MODIFY BY HAND
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'intl/messages_all.dart';

// **************************************************************************
// Generator: Flutter Intl IDE plugin
// Made by Localizely
// **************************************************************************

// ignore_for_file: non_constant_identifier_names, lines_longer_than_80_chars
// ignore_for_file: join_return_with_assignment, prefer_final_in_for_each
// ignore_for_file: avoid_redundant_argument_values, avoid_escaping_inner_quotes

class S {
  S();

  static S? _current;

  static S get current {
    assert(_current != null,
        'No instance of S was loaded. Try to initialize the S delegate before accessing S.current.');
    return _current!;
  }

  static const AppLocalizationDelegate delegate = AppLocalizationDelegate();

  static Future<S> load(Locale locale) {
    final name = (locale.countryCode?.isEmpty ?? false)
        ? locale.languageCode
        : locale.toString();
    final localeName = Intl.canonicalizedLocale(name);
    return initializeMessages(localeName).then((_) {
      Intl.defaultLocale = localeName;
      final instance = S();
      S._current = instance;

      return instance;
    });
  }

  static S of(BuildContext context) {
    final instance = S.maybeOf(context);
    assert(instance != null,
        'No instance of S present in the widget tree. Did you add S.delegate in localizationsDelegates?');
    return instance!;
  }

  static S? maybeOf


session.SPRING_SECURITY_LAST_EXCEPTION}">

                        <input class="form-check-input" name="remember-me" type="checkbox" value="true"> Remember me

                <button type="submit" class="btn btn-primary">Submit</button>
            </form>

短信登陆

            <form th:action="@{/authentication/mobile}" method="post">

                    mobile
                    <input type="text" class="form-control" id="mobile" name="mobile" value="12345678910" placeholder="Enter mobile">

                    smsCode:
                    <input type="text" class="form-control" id="smsCode" name="smsCode" placeholder="Enter smsCode">
                    发送手机验证码

                <button type="submit" class="btn btn-primary">Submit</button>
            </form>

            QQ登录


据ServiceName,hash找到我这个客户端应该被集群中哪个Nacos服务端去处理
                final String targetServer = distroMapper.mapSrv(groupedServiceName);

                List<String> headerList = new ArrayList<>(16);
                Enumeration<String> headers = req.getHeaderNames();
                while (headers.hasMoreElements()) {
                    String headerName = headers.nextElement();
                    headerList.add(headerName);
                    headerList.add(req.getHeader(headerName));
                }
                //计算出targetServer,直接请求去targetServer
                RestResult<String> result = HttpClient
                        .request("http://" + targetServer + req.getRequestURI(), headerList, paramsValue, body,
                                PROXY_CONNECT_TIMEOUT, PROXY_READ_TIMEOUT, Charsets.UTF_8.name(), req.getMethod());
                String data = result.ok() ? result.getData() : result.getMessage();
}

    }
```

###  DistroFilter#mapSrv

  根据服务名称 Hash, 再对我们服务器数量求模, 计算出我当前的服务应该属于哪一台 Nacos 去处理. 这个 Servers.size 是动态的, Nacos 服务端集群之间会有心跳去保活.

![img](http://cdn.jayh.club/uPic/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBARHIu5Yqz,size_20,color_FFFFFF,t_70,g_se,x_16-20220412102839217XEX2Xe.png)

##  5.2 ClientBeatCheckTask#run

  我们再看回上面的对客户端的心跳保活任务, 这个 DistroMapper#responsible, 会计算服务名出当前定时任务需不需要执行, 假如 order 服务是我这台 nacos 服务执行的, 就执行心跳保活任务, 并且如果状态改变, 同步给其他服务, 如果不是我这台服务执行, 则 return;

![img](http://cdn.jayh.club/uPic/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBARHIu5Yqz,size_20,color_FFFFFF,t_70,g_se,x_16-20220412102839553LFGlIa.png)

DistroMapper#responsible

![img](http://cdn.jayh.club/uPic/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBARHIu5Yqz,size_20,color_FFFFFF,t_70,g_se,x_16-20220412102839636VPKMRB.png)

# 6. Nacos 服务端之间的心跳任务

  . 上面我们说到如果是更改 serviceMap 的请求, 会根据服务名称路由到对应的服务节点去处理. 他根据服务名称 hash 再模服务器数量, 既然这里有服务器数量这


.filter(|(_, prevote)| {
                        prevote.height == self.height
                            && prevote.round == self.current.round
                            && prevote.id == Some(id)
                    })
                    .map(|(weight, _)| weight)
                    .sum::<u64>();
                total_weight > self.two_f()
            })
    }
}
<reponame>matthiaseiholzer/mathru_mirror
pub mod linear;
use serde_derive::{Deserialize, Serialize};

/// Overrides the corresponding CarPhysicsByCarType data
/// unless acceleration = 0
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CarPhysicsByTrack {
    pub acceleration: u8,
    pub top_speed: u8,
    pub grip: u8,
    pub collision_impact: u8,
    pub turning: u8,
    pub sliding_friction: u8,
}

/// Contains the base physics data for a car type but some fields
/// can be overwritten by the relevant CarPhysicsByTrack values
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CarPhysicsByCarType {
    pub grip: u16,
    pub collision_impact: u16,
    pub braking: u16, /// Not fully understood
    pub top_speed: u16,
    pub reverse_related: u16, /// Not fully understood
    pub turning: u16,
    pub sliding_friction: u16,
    pub acceleration: u16,
    pub _unknown_1: u16,
    pub _unknown_2: u16
}

impl From<CarPhysicsByCarType> for CarPhysicsByTrack {
    fn from(car_type_physics: CarPhysicsByCarType) -> Self {
        Self {
            acceleration: car_type_physics.acceleration as u8,
            top_speed: (car_type_physics.top_speed / 100) as u8,
            grip: (car_type_physics.grip / 10) as u8,
            collision_impact: (car_type_physics.collision_impact / 4) as u8,
            turning: car_type_physics.turning as u8,
            sliding_friction: car_type_physics.sliding_friction as u8
        }
    }
}

impl CarPhysicsByTrack {
    pub fn get_byte_array(&self) -> [u8; 6] {
        [
            self.acceleration,
            self.top_speed,
            self.grip,
            self.collision_impact,
            self.turning,
            self.sliding_friction
        ]
    }

    pub fn new_from_byte_array(bytes: &[u8]) -> Self {
        Self {
            acceleration: bytes[0],
            top_speed: bytes[1],
            grip: bytes[2],
            collision_impact: bytes[3],
            turning: bytes[4],
            sliding_friction: bytes[5]
        }
    }
}
#![allow(dead_code,unused_variables)]
extern crate gamecore;
use gamecore::{State,Game,Bot};
use bots::{DummyBot,SimpleBot};
use std::io;
use std::io::BufRead;
use std::io::Write;

mod bots;

// fn main() {
//     let mut results = [0u64;3];
//     for _ in 0..1000000 {
//         let mut game = Game::new();
//         let bot1: SimpleBot = Bot::new(State::X);
//         let bot2: DummyBot = Bot::new(State::O);
//         while game.is_game_ended() == None {
//             while !game.make_m


# -*- coding: utf-8 -*-
"""
@author: Hiromasa Kaneko
"""

import pandas as pd
from sklearn.neighbors import NearestNeighbors  # k-NN

k_in_knn = 5  # k-NN における k
rate_of_training_samples_inside_ad = 0.96  # AD 内となるトレーニングデータの割合。AD　のしきい値を決めるときに使用

dataset = pd.read_csv('resin.csv', index_col=0, header=0)
x_prediction = pd.read_csv('resin_prediction.csv', index_col=0, header=0)

# データ分割
y = dataset.iloc[:, 0]  # 目的変数
x = dataset.iloc[:, 1:]  # 説明変数

# 標準偏差が 0 の特徴量の削除
deleting_variables = x.columns[x.std() == 0]
x = x.drop(deleting_variables, axis=1)
x_prediction = x_prediction.drop(deleting_variables, axis=1)

# オートスケーリング
autoscaled_x = (x - x.mean()) / x.std()
autoscaled_x_prediction = (x_prediction - x.mean()) / x.std()

# k-NN による AD
ad_model = NearestNeighbors(n_neighbors=k_in_knn, metric='euclidean')  # AD モデルの宣言
ad_model.fit(autoscaled_x)  # k-NN による AD では、トレーニングデータの x を model_ad に格納することに対応

# サンプルごとの k 最近傍サンプルとの距離に加えて、k 最近傍サンプルのインデックス番号も一緒に出力されるため、出力用の変数を 2 つに
# トレーニングデータでは k 最近傍サンプルの中に自分も含まれ、自分との距離の 0 を除いた距離を考える必要があるため、k_in_knn + 1 個と設定
knn_distance_train, knn_index_train = ad_model.kneighbors(autoscaled_x, n_neighbors=k_in_knn + 1)
knn_distance_train = pd.DataFrame(knn_distance_train, index=autoscaled_x.index)  # DataFrame型に変換
mean_of_knn_distance_train = pd.DataFrame(knn_distance_train.iloc[:, 1:].mean(axis=1),
                                          columns=['mean_of_knn_distance'])  # 自分以外の k_in_knn 個の距離の平均
mean_of_knn_distance_train.to_csv('mean_of_knn_distance_train.csv')  # csv ファイルに保存。同じ名前のファイルがあるときは上書きされるため注意

# トレーニングデータのサンプルの rate_of_training_samples_inside_ad * 100 % が含まれるようにしきい値を設定
sorted_mean_of_knn_distance_train = mean_of_knn_distance_train.iloc[:, 0].sort_values(ascending=True)  # 距離の平均の小さい順に並び替え
ad_threshold = sorted_mean_of_knn_distance_train.iloc[
    round(autoscaled_x.shape[0] * rate_of_training_samples_inside_ad) - 1]

# トレーニングデータに対して、AD の中か外かを判定
inside_ad_flag_train = mean_of_knn_distance_train <= ad_threshold   # AD 内のサンプルのみ TRUE
inside_ad_flag_train.columns=['inside_ad_flag']
inside_ad_flag_train.to_csv('inside_ad_flag_train_knn.csv')  # csv ファイルに保存。同じ名前のファイルがあるときは上書きされるため注意

# 予測用データに対する k-NN 距離の計算
knn_distance_prediction, knn_index_prediction = ad_model.kneighbors(autoscaled_x_prediction)
knn_distance_prediction = pd.DataFrame(knn_distance_prediction, index=x_prediction.index)  # DataFrame型に変換
mean_of_knn_distance_prediction = pd.DataFrame(knn_distance_prediction.mean(axis=1),
                                         columns=['mean_of_knn_distance'])  # k_in_knn 個の距離の平均
mean_of_knn_distance_prediction.to_csv('mean_of_knn_distance_prediction.csv')  # csv ファイルに保存。同じ名前のファイルがあるときは上書きされるため注意

# 予測用データに対して、AD の中か外かを判定
inside_ad_flag_prediction = mean_of_knn_distance_prediction <= ad_threshold  # AD 内のサンプルのみ TRUE
inside_ad_flag_prediction.columns=['inside_ad_flag']
inside_ad_flag_prediction.to_csv('inside_ad_flag_prediction_knn.csv')  # csv ファイルに保存。同じ名前のファイルがあるときは上書きされるため注意


yloadIndex {
    /// Get indexed fields
    fn indexed_fields(&self) -> Vec<PayloadKeyType>;

    /// Mark field as one which should be indexed
    fn set_indexed(&mut self, field: &PayloadKeyType) -> OperationResult<()>;

    /// Remove index
    fn drop_index(&mut self, field: &PayloadKeyType) -> OperationResult<()>;

    /// Estimate amount of points (min, max) which satisfies filtering condition.
    fn estimate_cardinality(&self, query: &Filter) -> CardinalityEstimation;

    /// Return list of all point ids, which satisfy filtering criteria
    fn query_points<'a>(&'a self, query: &'a Filter) -> Box<dyn Iterator<Item=PointOffsetType> + 'a>;

    /// Iterate conditions for payload blocks with minimum size of `threshold`
    /// Required for building HNSW index
    fn payload_blocks(&self, threshold: usize) -> Box<dyn Iterator<Item=PayloadBlockCondition> + '_>;
}
<filename>unittest/src/fake/syscalls/raw_syscalls_impl.rs
use libtock_platform::{syscall_class, yield_id, RawSyscalls, Register};
use std::convert::TryInto;

unsafe impl RawSyscalls for crate::fake::Syscalls {
    unsafe fn yield1([r0]: [Register; 1]) {
        crate::fake::syscalls::assert_valid(r0);
        match r0.try_into().expect("too-large Yield ID passed") {
            yield_id::NO_WAIT => panic!("yield-no-wait called without an argument"),
            yield_id::WAIT => super::yield_impl::yield_wait(),
            id => panic!("unknown yield ID {}", id),
        }
    }

    unsafe fn yield2([r0, r1]: [Register; 2]) {
        crate::fake::syscalls::assert_valid((r0, r1));
        match r0.try_into().expect("too-large Yield ID passed") {
            yield_id::NO_WAIT => unsafe { super::yield_impl::yield_no_wait(r1.into()) },
            yield_id::WAIT => {
                // Technically it is acceptable to call yield_wait with an
                // argument, but it shouldn't be done because it's wasteful so
                // we fail the test case regardless.
                panic!("yield-wait called with an argument");
            }
            id => panic!("unknown yield ID {}", id),
        }
    }

    unsafe fn syscall1<const CLASS: usize>([Register(_r0)]: [Register; 1]) -> [Register; 2] {
        match CLASS {
            syscall_class::MEMOP => unimplemented!("TODO: Add Memop"),
            _ => panic!("Unknown syscall1 call. Class: {}", CLASS),
        }
    }

    unsafe fn syscall2<const CLASS: usize>(
        [Register(_r0), Register(_r1)]: [Register; 2],
    ) -> [Register; 2] {
        match CLASS {
            syscall_class::MEMOP => unimplemented!("TODO: Add Memop"),
            syscall_class::EXIT => unimplemented!("TODO: Add Exit"),
            _ => panic!("Unknown syscall2 call. Class: {}", CLASS),
        }
    }

    unsafe fn syscall4<const CLASS: usize>([r0, r1, r2, r3]: [Register; 4]) -> [Register; 4] {
        crate::fake::syscalls::assert_valid((r0, r1, r2, r3));
        match CLASS {
            syscall_class::SUBSCRIBE => unimplemented!("TODO: Add Subscribe"),
            syscall_class::COMMAND => super::command_impl::command(r0, r1, r2, r3),
            syscall_class::RW_ALLOW => unimplemented!("TODO: Add Allow"),
            syscall_class::RO_ALLOW => unimplemented!("TODO: Add Allow"),
            _ => panic!("Unknown syscall4 call. Class


 attribute,
  }) {
    if (data is! String || data != '\n') {
      return null;
    }

    final itr = DeltaIterator(document.toDelta());
    final prev = itr.skip(index), cur = itr.next();
    final blockStyle = Style.fromJson(cur.attributes).getBlockExceptHeader();
    // We are not in a block, ignore.
    if (cur.isPlain || blockStyle == null) {
      return null;
    }
    // We are not on an empty line, ignore.
    if (!_isEmptyLine(prev, cur)) {
      return null;
    }

    // We are on an empty line. Now we need to determine if we are on the
    // last line of a block.
    // First check if `cur` length is greater than 1, this would indicate
    // that it contains multiple newline characters which share the same style.
    // This would mean we are not on the last line yet.
    // `cur.value as String` is safe since we already called isEmptyLine and
    // know it contains a newline
    if ((cur.value as String).length > 1) {
      // We are not on the last line of this block, ignore.
      return null;
    }

    // Keep looking for the next newline character to see if it shares the same
    // block style as `cur`.
    final nextNewLine = _getNextNewLine(itr);
    if (nextNewLine.operation != null &&
        nextNewLine.operation!.attributes != null &&
        Style.fromJson(nextNewLine.operation!.attributes)
                .getBlockExceptHeader() ==
            blockStyle) {
      // We are not at the end of this block, ignore.
      return null;
    }

    // Here we now know that the line after `cur` is not in the same block
    // therefore we can exit this block.
    final attributes = cur.attributes ?? <String, dynamic>{};
    final k =
        attributes.keys.firstWhere(Attribute.blockKeysExceptHeader.contains);
    attributes[k] = null;
    // retain(1) should be '\n', set it with no attribute
    return Delta()
      ..retain(index + (len ?? 0))
      ..retain(1, attributes);
  }
}

/// Resets format for a newly inserted line when insert occurred at the end
/// of a line (right before a newline).
///
/// This handles scenarios when a new line is added when at the end of a
/// heading line. The newly added line should be a regular paragraph.
@immutable
class ResetLineFormatOnNewLineRule extends InsertRule {
  const ResetLineFormatOnNewLineRule();

  @override
  Delta? applyRule(
    Document document,
    int index, {
    int? len,
    Object? data,
    Attribute? attribute,
  }) {
    if (data is! String || data != '\n') {
      return null;
    }

    final itr = DeltaIterator(document.toDelta())..skip(index);
    final cur = itr.next();
    if (cur.data is! String || !(cur.data as String).startsWith('\n')) {
      return null;
    }

    Map<String, dynamic>? resetStyle;
    if (cur.attributes != null &&
        cur.attributes!.containsKey(Attribute.header.key)) {
      resetStyle = Attribute.header.toJson();
    }
    return Delta()
      ..retain(index + (len ?? 0))
      ..insert('\n', cur.attributes)
      ..retain(1, resetStyle)
      ..trim();
  }
}

/// Handles all format operations which manipulate embeds.
/// This rule wraps line breaks around video, not image.
@immutable
class InsertEmbedsRule extends InsertRule {
  const InsertEmbedsRule();

  @override
  Delta? applyRule(
    Document document,
    int index, {
    int? len,
    Object? dat


ctx.Done():
				return
			case v1, ok := <-c1:
				if ok {
					r <- v1
				} else {
					c1 = nil
				}
			case v2, ok := <-c2:
				if ok {
					r <- v2
				} else {
					c2 = nil
				}
			}
		}
	}(ctx, c1, c2, r)
	return r
}

// Filter calls f on each value read from c. If f returns true the value
// is sent on the returned channel. This will leave a goroutine running
// until c is closed or the context is canceled, at which point the
// returned channel is closed.
func Filter[Elem any](ctx context.Context, c <-chan Elem, f func(Elem) bool) <-chan Elem {
	r := make(chan Elem)
	go func(ctx context.Context, c <-chan Elem, f func(Elem) bool, r chan<- Elem) {
		defer close(r)
		for {
			select {
			case <-ctx.Done():
				return
			case v, ok := <-c:
				if !ok {
					return
				}
				if f(v) {
					r <- v
				}
			}
		}
	}(ctx, c, f, r)
	return r
}

// Sink returns a channel that discards all values sent to it.
// This will leave a goroutine running until the context is canceled
// or the returned channel is closed.
func Sink[Elem any](ctx context.Context) chan<- Elem {
	r := make(chan Elem)
	go func(ctx context.Context, r <-chan Elem) {
		for {
			select {
			case <-ctx.Done():
				return
			case _, ok := <-r:
				if !ok {
					return
				}
			}
		}
	}(ctx, r)
	return r
}

// An Exclusive is a value that may only be used by a single goroutine
// at a time. This is implemented using channels rather than a mutex.
type Exclusive[Val any] struct {
	c chan Val
}

// MakeExclusive makes an initialized exclusive value.
func MakeExclusive[Val any](initial Val) *Exclusive[Val] {
	r := &Exclusive[Val]{
		c: make(chan Val, 1),
	}
	r.c <- initial
	return r
}

// Acquire acquires the exclusive value for private use.
// It must be released using the Release method.
func (e *Exclusive[Val]) Acquire() Val {
	return <-e.c
}

// TryAcquire attempts to acquire the value. The ok result reports whether
// the value was acquired. If the value is acquired, it must be released
// using the Release method.
func (e *Exclusive[Val]) TryAcquire() (v Val, ok bool) {
	select {
	case r := <-e.c:
		return r, true
	default:
		return v, false
	}
}

// Release updates and releases the value.
// This method panics if the value has not been acquired.
func (e *Exclusive[Val]) Release(v Val) {
	select {
	case e.c <- v:
	default:
		panic("Exclusive Release without Acquire")
	}
}

// Ranger returns a Sender and a Receiver. The Receiver provides a
// Next method to retrieve values. The Sender provides a Send method
// to send values and a Close method to stop sending values. The Next
// method indicates when the Sender has been closed, and the Send
// method indicates when the Receiver has been freed.
//
// This is a convenie


.Override
  public boolean equals(final java.lang.Object obj) {
    if (obj == this) {
      return true;
    }
    if (!(obj
        instanceof com.google.identity.accesscontextmanager.v1.CommitServicePerimetersResponse)) {
      return super.equals(obj);
    }
    com.google.identity.accesscontextmanager.v1.CommitServicePerimetersResponse other =
        (com.google.identity.accesscontextmanager.v1.CommitServicePerimetersResponse) obj;

    if (!getServicePerimetersList().equals(other.getServicePerimetersList())) return false;
    if (!getUnknownFields().equals(other.getUnknownFields())) return false;
    return true;
  }

  @java.lang.Override
  public int hashCode() {
    if (memoizedHashCode != 0) {
      return memoizedHashCode;
    }
    int hash = 41;
    hash = (19 * hash) + getDescriptor().hashCode();
    if (getServicePerimetersCount() > 0) {
      hash = (37 * hash) + SERVICE_PERIMETERS_FIELD_NUMBER;
      hash = (53 * hash) + getServicePerimetersList().hashCode();
    }
    hash = (29 * hash) + getUnknownFields().hashCode();
    memoizedHashCode = hash;
    return hash;
  }

  public static com.google.identity.accesscontextmanager.v1.CommitServicePerimetersResponse
      parseFrom(java.nio.ByteBuffer data)
          throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.identity.accesscontextmanager.v1.CommitServicePerimetersResponse
      parseFrom(
          java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.identity.accesscontextmanager.v1.CommitServicePerimetersResponse
      parseFrom(com.google.protobuf.ByteString data)
          throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.identity.accesscontextmanager.v1.CommitServicePerimetersResponse
      parseFrom(
          com.google.protobuf.ByteString data,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.identity.accesscontextmanager.v1.CommitServicePerimetersResponse
      parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.identity.accesscontextmanager.v1.CommitServicePerimetersResponse
      parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.identity.accesscontextmanager.v1.CommitServicePerimetersResponse
      parseFrom(java.io.InputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
  }

  public static com.google.identity.accesscontextmanager.v1.CommitServicePerimetersResponse
      parseFrom(
          java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
        PARSER, input, extension


int*, unsigned char const*, unsigned int, bool)"}, {"value": 543, "name": "Put2(unsigned char const*, unsigned long, int, bool)"}, {"children": [{"value": 532, "name": "Decoder(int const*, int, CryptoPP::BufferedTransformation*)"}], "name": "BaseN_"}, {"value": 426, "name": "~BaseN_Decoder()"}, {"value": 431, "name": "non-virtual thunk to ~BaseN_Decoder()"}], "name": "BaseN_Decoder::"}, {"children": [{"value": 672, "name": "IsolatedInitialize(CryptoPP::NameValuePairs const&)"}, {"value": 739, "name": "Put2(unsigned char const*, unsigned long, int, bool)"}, {"value": 426, "name": "~BaseN_Encoder()"}, {"value": 431, "name": "non-virtual thunk to ~BaseN_Encoder()"}], "name": "BaseN_Encoder::"}, {"value": 75, "name": "DEREncodeNull(CryptoPP::BufferedTransformation&)"}, {"children": [{"children": [{"value": 364, "name": "BadElement()"}], "name": "DL_"}, {"value": 53, "name": "~DL_BadElement()"}], "name": "DL_BadElement::"}, {"children": [{"value": 5, "name": "~DL_PrivateKey()"}, {"value": 293, "name": "MakePublicKey(CryptoPP::DL_PublicKey<CryptoPP::Integer>&) const"}], "name": "DL_PrivateKey<CryptoPP::Integer>::"}, {"children": [{"value": 5, "name": "~DL_PrivateKey()"}, {"value": 183, "name": "MakePublicKey(CryptoPP::DL_PublicKey<CryptoPP::ECPPoint>&) const"}], "name": "DL_PrivateKey<CryptoPP::ECPPoint>::"}, {"children": [{"value": 5, "name": "~DL_PrivateKey()"}, {"value": 380, "name": "MakePublicKey(CryptoPP::DL_PublicKey<CryptoPP::EC2NPoint>&) const"}], "name": "DL_PrivateKey<CryptoPP::EC2NPoint>::"}, {"value": 42, "name": "GetPrimeTable(unsigned int&)"}, {"children": [{"value": 5, "name": "~TF_SignerBase()"}, {"value": 880, "name": "SignAndRestart(CryptoPP::RandomNumberGenerator&, CryptoPP::PK_MessageAccumulator&, unsigned char*, bool) const"}, {"value": 1177, "name": "InputRecoverableMessage(CryptoPP::PK_MessageAccumulator&, unsigned char const*, unsigned long) const"}, {"value": 20, "name": "non-virtual thunk to ~TF_SignerBase()"}], "name": "TF_SignerBase::"}, {"value": 122, "name": "TrialDivision(CryptoPP::Integer const&, unsigned int)"}, {"children": [{"value": 13, "name": "BERDecodeAlgorithmParameters(CryptoPP::BufferedTransformation&)"}, {"value": 946, "name": "BERDecode(CryptoPP::BufferedTransformation&)"}, {"value": 6, "name": "~X509PublicKey()"}, {"value": 80, "name": "DEREncodeAlgorithmParameters(CryptoPP::BufferedTransformation&) const"}, {"value": 931, "name": "DEREncode(CryptoPP::BufferedTransformation&) const"}, {"value": 10, "name": "non-virtual thunk to ~X509PublicKey()"}], "name": "X509PublicKey::"}, {"children": [{"children": [{"value": 122, "name": "c(CryptoPP::Integer const&, CryptoPP::Integer const&, CryptoPP::Integer const&)"}], "name": "exp_b_mod_"}, {"children": [{"value": 201, "name": "c(CryptoPP::Integer const&, CryptoPP::Integer const&, CryptoPP::Integer const&)"}], "name": "times_b_mod_"}], "name": "a_"}, {"value": 66, "name": "BERDecodeError()"}, {"value": 1495, "name": "BERDecodeGF2NP(CryptoPP::BufferedTransformation&)"}, {"children": [{"value": 147, "name": "ProcessData(unsigned char*, unsigned char const*, unsigned long)"}, {"value": 107, "name": "ResizeBuffers()"}, {"value": 275, "n


	/*
	 * Get the list of orphaned Single Instance IDs which we can delete.
	 */
	er = GetOrphanedSingleInstances(lstAttachments, &lstDeleteAttach);
	if (er != erSuccess)
		return er;
	if (!lstDeleteAttach.empty()) {
		er = DeleteAttachmentInstances(lstDeleteAttach, false);
		if (er != erSuccess)
			return er;
	}
	return erSuccess;
}

/**
 * Delete one single instance property of an object.
 *
 * @param[in] ulObjId HierarchyID of object to delete single instance property from
 * @param[in] ulPropId Property of object to remove
 * @param[in] bReplace Flag used for transitions in ECFileStorage
 *
 * @return Kopano error code
 */
ECRESULT ECAttachmentStorage::DeleteAttachment(ULONG ulObjId, ULONG ulPropId)
{
	ext_siid ulInstanceId;
	bool bOrphan = false;

	/*
	 * Convert object id into attachment id
	 */
	auto er = GetSingleInstanceId(ulObjId, ulPropId, &ulInstanceId);
	if (er != erSuccess) {
		if (er == KCERR_NOT_FOUND)
			er = erSuccess;	// Nothing to delete
		return er;
	}

	/*
	 * Remove object from `singleinstances` table, this will decrease the
	 * reference count for the attachment.
	 */
	std::string strQuery =
		"DELETE FROM `singleinstances` "
		"WHERE `hierarchyid` = " + stringify(ulObjId) + " "
		"AND `tag` = " + stringify(ulPropId);

	er = m_lpDatabase->DoDelete(strQuery);
	if (er != erSuccess) {
		return ec_perror("ECAttachmentStorage::DeleteAttachment(): DoDelete failed", er);
	}
	/*
	 * Check if the attachment can be permanently deleted.
	 */
	if (IsOrphanedSingleInstance(ulInstanceId, &bOrphan) != erSuccess || !bOrphan) {
		return erSuccess;
	}

	return DeleteAttachmentInstance(ulInstanceId, true);
}

/**
 * Get the size of a large property of a specific object
 *
 * @param[in] ulObjId HierarchyID of object
 * @param[in] ulPropId PropertyID of object
 * @param[out] lpulSize size of property
 *
 * @return Kopano error code
 */
ECRESULT ECAttachmentStorage::GetSize(ULONG ulObjId, ULONG ulPropId, size_t *lpulSize)
{
	ext_siid ulInstanceId;
	/*
	 * Convert object id into attachment id
	 */
	auto er = GetSingleInstanceId(ulObjId, ulPropId, &ulInstanceId);
	if (er == KCERR_NOT_FOUND) {
		*lpulSize = 0;
		return erSuccess;
	} else if (er != erSuccess) {
		return er;
	}
	return GetSizeInstance(ulInstanceId, lpulSize);
}

// Attachment storage is in database
ECDatabaseAttachment::ECDatabaseAttachment(ECDatabase *lpDatabase) :
	ECAttachmentStorage(lpDatabase, 0)
{
}

/**
 * Load instance data using soap and return as blob.
 *
 * @param[in] soap soap to use memory allocations for
 * @param[in] ulInstanceId InstanceID to load
 * @param[out] lpiSize size in lppData
 * @param[out] lppData data of instance
 *
 * @return Kopano error code
 */
ECRESULT ECDatabaseAttachment::LoadAttachmentInstance(struct soap *soap,
    const ext_siid &ulInstanceId, size_t *lpiSize, unsigned char **lppData)
{
	size_t iReadSize = 0;
	DB_RESULT lpDBResult;

	// we first need to know the complete size of the attachment (some old databas


, "another:tag", "nocolon"})
		defer mockConfig.SetWithoutSource("tags", []string{})
		staticTags := GetStaticTagsSlice(context.Background(), mockConfig)
		assert.ElementsMatch(t, []string{
			"nocolon",
			"some:tag",
			"another:tag",
			"eks_fargate_node:eksnode",
			"kube_distribution:eks",
		}, staticTags)
	})

	t.Run("tags and extra_tags", func(t *testing.T) {
		mockConfig.SetWithoutSource("tags", []string{"some:tag", "nocolon"})
		mockConfig.SetWithoutSource("extra_tags", []string{"extra:tag", "missingcolon"})
		defer mockConfig.SetWithoutSource("tags", []string{})
		defer mockConfig.SetWithoutSource("extra_tags", []string{})
		staticTags := GetStaticTagsSlice(context.Background(), mockConfig)
		assert.ElementsMatch(t, []string{
			"nocolon",
			"missingcolon",
			"some:tag",
			"extra:tag",
			"eks_fargate_node:eksnode",
			"kube_distribution:eks",
		}, staticTags)
	})
}

func TestClusterAgentGlobalTags(t *testing.T) {
	env.SetFeatures(t, env.Kubernetes)
	clustername.ResetClusterName()
	mockConfig := configmock.New(t)

	// Agent tags config
	mockConfig.SetWithoutSource("tags", []string{"some:tag", "nocolon"})
	mockConfig.SetWithoutSource("extra_tags", []string{"extra:tag", "missingcolon"})
	mockConfig.SetWithoutSource("cluster_checks.extra_tags", []string{"cluster:tag", "nocolon"})
	mockConfig.SetWithoutSource("orchestrator_explorer.extra_tags", []string{"orch:tag", "missingcolon"})

	recordFlavor := flavor.GetFlavor()
	defer func() {
		flavor.SetFlavor(recordFlavor)
	}()

	t.Run("Agent extraGlobalTags", func(t *testing.T) {
		flavor.SetFlavor(flavor.DefaultAgent)
		globalTags := GetClusterAgentStaticTags(t.Context(), mockConfig)
		assert.Equal(t, map[string][]string(nil), globalTags)
	})

	t.Run("ClusterAgent extraGlobalTags", func(t *testing.T) {
		flavor.SetFlavor(flavor.ClusterAgent)
		globalTags := GetClusterAgentStaticTags(t.Context(), mockConfig)
		assert.Equal(t, map[string][]string{
			"some":    {"tag"},
			"extra":   {"tag"},
			"cluster": {"tag"},
			"orch":    {"tag"},
		}, globalTags)
	})
}
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2025-present Datadog, Inc.

//go:build windows

// Package winutil contains Windows OS utilities
package winutil

import (
	"unsafe"

	"golang.org/x/sys/windows"
)

var (
	crypt32                               = windows.NewLazySystemDLL("crypt32.dll")
	procCertEnumCRLsInStore               = crypt32.NewProc("CertEnumCRLsInStore")
	procCertFreeCRLContext                = crypt32.NewProc("CertFreeCRLContext")
	procCertGetCRLContextProperty         = crypt32.NewProc("CertGetCRLContextProperty")
	procCertGetCertificateContextProperty = crypt32.NewProc("CertGetCertificateContextProperty")
	procCertNameToStr                     = crypt32.NewProc("CertNameToStrW")
)

// CRLContext contains both the encoded and decoded representations of a certificate revocation list (CRL).
//
// https://learn.microsoft.com/en-us/windows/win32


tances)

	instancesMap := instances.(*expvar.Map)

	keyCount := 0
	instancesMap.Do(func(kv expvar.KeyValue) {
		require.Equal(t, stats[kv.Key].String(), kv.Value.String())

		keyCount++
	})

	require.Equal(t, len(stats), keyCount)
}

// Tests

func TestWorkersInitialState(t *testing.T) {
	setUp()
	assertExpectedInitialState(t)
}

func TestWorkersStatsReset(t *testing.T) {
	setUp()

	expectedWorkers := 20

	require.Equal(t, 0, GetWorkerCount())
	require.Equal(t, 0, getWorkersCountExpvar(t))

	// Test addition of new stats
	for idx := 0; idx < expectedWorkers; idx++ {
		stats := &WorkerStats{}
		SetWorkerStats(fmt.Sprintf("stats %d", idx), stats)

		require.Equal(t, idx+1, GetWorkerCount())
		require.Equal(t, idx+1, getWorkersCountExpvar(t))
	}

	Reset()

	assertExpectedInitialState(t)
}

func TestWorkersInstances(t *testing.T) {
	setUp()

	stats1Update1 := &WorkerStats{Utilization: 1.01}
	stats1Update2 := &WorkerStats{Utilization: 1.02}
	stats1Update3 := &WorkerStats{Utilization: 1.03}

	stats2Update1 := &WorkerStats{Utilization: 2.01}

	SetWorkerStats("stats1", stats1Update1)
	SetWorkerStats("stats1", stats1Update2)
	SetWorkerStats("stats2", stats2Update1)
	SetWorkerStats("stats1", stats1Update3)

	// Sanity check to ensure that the output is exactly what we expect
	require.Equal(
		t,
		"{\"stats1\": {\"Utilization\": 1.03}, \"stats2\": {\"Utilization\": 2.01}}",
		getWorkerInstancesStats(t),
	)

	// Ensure that the instances are exactly the ones we passed in
	assertWorkerInstanceStats(
		t,
		map[string]*WorkerStats{
			"stats1": stats1Update3,
			"stats2": stats2Update1,
		},
	)
}

func TestWorkersInstancesAsync(t *testing.T) {
	setUp()

	var wg sync.WaitGroup
	var expectedStatsLock sync.Mutex

	maxTestWorkers := 500

	start := make(chan struct{})
	expectedStats := make(map[string]*WorkerStats)

	require.Equal(t, 0, GetWorkerCount())
	require.Equal(t, 0, getWorkersCountExpvar(t))

	canary1Stats := &WorkerStats{Utilization: -100}
	SetWorkerStats("canary1", canary1Stats)
	expectedStats["canary1"] = canary1Stats

	for idx := 0; idx < maxTestWorkers; idx++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()

			stats := &WorkerStats{Utilization: -1.0}
			updatedStats := &WorkerStats{Utilization: float64(id)}

			<-start

			name := fmt.Sprintf("stats %d", id)

			SetWorkerStats(name, stats)
			SetWorkerStats(name, updatedStats)

			// Keep every even stat and delete every odd worker stat
			if id%2 == 0 {
				expectedStatsLock.Lock()
				expectedStats[name] = updatedStats
				expectedStatsLock.Unlock()
			} else {
				DeleteWorkerStats(name)
			}
		}(idx)
	}

	close(start)

	wg.Wait()

	require.Equal(t, maxTestWorkers/2+1, GetWorkerCount())
	assertWorkerInstanceStats(t, expectedStats)
}

func TestWorkersCount(t *testing.T) {
	setUp()

	expectedWorkers := 20

	require.Equal(t, 0, GetWorkerCount())
	require.Equal(t, 0, getWorkersCountExpvar(t))

	// Test


      if (usedOrderIndexes.contains(order)) {
        // One index used multiple times.
        penalty.dna += 0.1;
      }
      usedOrderIndexes.add(order);
    }

    for (final evaluator in _customEvaluators) {
      evaluator(baked, penalty);
    }

    return penalty;
  }

  static Duration _getDistanceFromLunchHour(DateTime time) {
    final lunchTimeMin =
        new DateTime.utc(time.year, time.month, time.day, _lunchHourMin);
    final lunchTimeMax =
        new DateTime.utc(time.year, time.month, time.day, _lunchHourMax);
    if (time.isAfter(lunchTimeMin) && time.isBefore(lunchTimeMax) ||
        time == lunchTimeMin ||
        time == lunchTimeMax) {
      // Inside range.
      return const Duration();
    }
    if (time.isBefore(lunchTimeMin)) {
      return lunchTimeMin.difference(time);
    }
    if (time.isAfter(lunchTimeMax)) {
      return lunchTimeMax.difference(time);
    }
    throw new StateError("time has undefined relationship to lunchTimeMin"
        " and lunchTimeMax");
  }
}

class ScheduleEvaluatorPenalty extends FitnessResult {
  /// Penalty for breaking expectations, like lunch at 12pm.
  double cultural = 0.0;

  /// Penalty for breaking constraints, like "end first day at 6pm".
  double constraints = 0.0;

  double hunger = 0.0;

  double repetitiveness = 0.0;

  /// Mostly bonus (negative values) for things like session of the same
  /// theme appearing after each other.
  double harmony = 0.0;

  /// Penalty for straining audience focus, like "not starting with exciting
  /// session after lunch".
  double awareness = 0.0;

  /// Penalty for ambivalence or other problems in the chromosome.
  double dna = 0.0;

  /// Used for debugging only.
  // ignore: unused_field
  double _cachedEvaluate;

  @override
  bool dominates(ScheduleEvaluatorPenalty other) {
    return cultural < other.cultural &&
        constraints < other.constraints &&
        hunger < other.hunger &&
        repetitiveness < other.repetitiveness &&
        harmony < other.harmony &&
        awareness < other.awareness &&
        dna < other.dna;
  }

  double evaluate() {
    double result = 0.0;
    result += cultural;
    result += constraints;
    result += hunger;
    result += repetitiveness;
    result += harmony;
    result += awareness;
    result += dna;
    _cachedEvaluate = result;
    return result;
  }
}

/// A function that takes a [schedule] and modifies the [penalty].
///
/// These are used for specific rules pertaining to only one conference but
/// not generally applicable, such as that a particular conference's first day
/// must end as close to 6pm as possible.
typedef void CustomEvaluator(
    BakedSchedule schedule, ScheduleEvaluatorPenalty penalty);
/// Lists 5000 top English words.
///
/// The list is sorted in order of frequency of use, descending.
const List<String> all = [
  'the',
  'be',
  'and',
  'of',
  'a',
  'in',
  'to',
  'have',
  'it',
  'I',
  'that',
  'for',
  'you',
  'he',
  'with',
  'on',
  'do',
  'say',
  'this',
  'they',
  'at',
  'but',
  'we',
  'his',
  'from',
  'not',
  'by',
  'she',
  'or',
  'as',
  'what',
  'go',
  'their',
  'can',
  'who',
  'get',
  'if',
  'would',
  'her',
  'all',
  'my',
  'make',
  'about',


/*
 *
 *    Copyright (c) 2024 Project CHIP Authors
 *    Copyright 2024 NXP
 *    All rights reserved.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

#pragma once

#include <stdint.h>

namespace chip::NXP::App {

/**
 * @brief This class describes a manager for extra application BLE-related
 * functionality (e.g multiple BLE connections).
 *
 */
class BLEApplicationManager
{
public:
    void Init();
    void EnableMultipleConnectionsHandler();
    void FactoryReset();

private:
    static void EnableMultipleConnections(intptr_t arg);

    friend BLEApplicationManager & BleAppMgr();
    static BLEApplicationManager sInstance;
};

inline BLEApplicationManager & BleAppMgr()
{
    return BLEApplicationManager::sInstance;
}

} // namespace chip::NXP::App


constants.CENTER) {
      return { x: a, y: b, w: c, h: d };
    }
  }

};

},{"./constants":36}],36:[function(_dereq_,module,exports){
/**
 * @module Constants
 * @submodule Constants
 * @for p5
 */

var PI = Math.PI;

module.exports = {

  // GRAPHICS RENDERER
  P2D: 'p2d',
  WEBGL: 'webgl',

  // ENVIRONMENT
  ARROW: 'default',
  CROSS: 'crosshair',
  HAND: 'pointer',
  MOVE: 'move',
  TEXT: 'text',
  WAIT: 'wait',

  // TRIGONOMETRY

  /**
   * HALF_PI is a mathematical constant with the value
   * 1.57079632679489661923. It is half the ratio of the
   * circumference of a circle to its diameter. It is useful in
   * combination with the trigonometric functions sin() and cos().
   *
   * @property HALF_PI
   *
   * @example
   *

   * arc(50, 50, 80, 80, 0, HALF_PI);
   *

   *
   * @alt
   * 80x80 white quarter-circle with curve toward bottom right of canvas.
   *
   */
  HALF_PI: PI / 2,
  /**
   * PI is a mathematical constant with the value
   * 3.14159265358979323846. It is the ratio of the circumference
   * of a circle to its diameter. It is useful in combination with
   * the trigonometric functions sin() and cos().
   *
   * @property PI
   *
   * @example
   *

   * arc(50, 50, 80, 80, 0, PI);
   *

   *
   * @alt
   * white half-circle with curve toward bottom of canvas.
   *
   */
  PI: PI,
  /**
   * QUARTER_PI is a mathematical constant with the value 0.7853982.
   * It is one quarter the ratio of the circumference of a circle to
   * its diameter. It is useful in combination with the trigonometric
   * functions sin() and cos().
   *
   * @property QUARTER_PI
   *
   * @example
   *

   * arc(50, 50, 80, 80, 0, QUARTER_PI);
   *

   *
   * @alt
   * white eighth-circle rotated about 40 degrees with curve bottom right canvas.
   *
   */
  QUARTER_PI: PI / 4,
  /**
   * TAU is an alias for TWO_PI, a mathematical constant with the
   * value 6.28318530717958647693. It is twice the ratio of the
   * circumference of a circle to its diameter. It is useful in
   * combination with the trigonometric functions sin() and cos().
   *
   * @property TAU
   *
   * @example
   *

   * arc(50, 50, 80, 80, 0, TAU);
   *

   *
   * @alt
   * 80x80 white ellipse shape in center of canvas.
   *
   */
  TAU: PI * 2,
  /**
   * TWO_PI is a mathematical constant with the value
   * 6.28318530717958647693. It is twice the ratio of the
   * circumference of a circle to its diameter. It is useful in
   * combination with the trigonometric functions sin() and cos().
   *
   * @property TWO_PI
   *
   * @example
   *

   * arc(50, 50, 80, 80, 0, TWO_PI);
   *

   *
   * @alt
   * 80x80 white


.ACTION_MOVE) {
//            //			if(downX-ev.getRawX()>40||ev.getRawX()-downX>40){
//            //				getParent().requestDisallowInterceptTouchEvent(false);
//            //				return false;
//            //			}else {
//            //				getParent().requestDisallowInterceptTouchEvent(true);
//            //			}
//            if (!needConsumeTouch) {
//                // 在最顶端且向上拉了，则这个touch事件交给父类去处理
//                parent.requestDisallowInterceptTouchEvent(false)
//                return false
//            } else if (allowDragTop) {
//                // needConsumeTouch尚未被定性，此处给其定性
//                // 允许拖动到底部的下一页，而且又向上拖动了，就将touch事件交给父view
//                if (ev.rawY - downY > 2) {
//                    // flag设置，由父类去消费
//                    needConsumeTouch = false
//                    parent.requestDisallowInterceptTouchEvent(false)
//                    return false
//                }
//            }
//        }
//
//        // 通知父view是否要处理touch事件
//        parent.requestDisallowInterceptTouchEvent(needConsumeTouch)
//        return super.dispatchTouchEvent(ev)
//    }

    override fun onTouchEvent(ev: MotionEvent?): Boolean {
        velocityTracker.addMovement(ev)

        val action = ev?.action ?: return false

//        Log.d(TAG, "onTouchEvent: action:$action")

        when (action and MotionEvent.ACTION_MASK) {
            MotionEvent.ACTION_DOWN -> {
//                Log.d(TAG, "onTouchEvent: ACTION_DOWN")
                //只有一个元素也没办法滚动
                if (getChildCount() <= 1) {
                    return false
                }

                mIsBeingDragged = !scroller.isFinished
                if (mIsBeingDragged) {
                    this.parent?.requestDisallowInterceptTouchEvent(true)
                }

                if (!scroller.isFinished) {
                    scroller.abortAnimation()
                }

                mLastMotionX = ev.x.toInt()
            }
            MotionEvent.ACTION_MOVE -> {
//                Log.d(TAG, "onTouchEvent: ACTION_MOVE")
                val x = ev.x.toInt()
                var deltaX = mLastMotionX - x
                if (!mIsBeingDragged && Math.abs(deltaX) > mTouchSlop) {
                    val parent = parent
                    parent?.requestDisallowInterceptTouchEvent(true)
                    mIsBeingDragged = true
                    if (deltaX > 0) {
                        deltaX -= mTouchSlop
                    } else {
                        deltaX += mTouchSlop
                    }
                }
                if (mIsBeingDragged) {
                    // Scroll to follow the motion event
                    mLastMotionX = x

                    val oldX = mScrollX
                    val oldY = 0
                    val range = getScrollRange()
                    val canOverscroll = overScrollMode == View.OVER_SCROLL_ALWAYS || overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0

                    // Calling overScrollBy will call onOverScrolled, which
                    // calls onScrollChanged if applicable.
                    if (overScrollBy(deltaX, 0, mScrollX, 0, range, 0, mOverscrollDistance, 0, true)) {
                        // Break our velocity if we hit a scroll barrier.
                        velocityTracker.clear()
                    }

                    if (canOverscroll) {
                        val pulledToX = oldX + deltaX
                        if (pulledToX < 0) {


onst ParsedExpr& val) {
  this->filter_expr = val;
__isset.filter_expr = true;
}
std::ostream& operator<<(std::ostream& out, const MatchSparseExpr& obj)
{
  obj.printTo(out);
  return out;
}

uint32_t MatchSparseExpr::read(::apache::thrift::protocol::TProtocol* iprot) {

  ::apache::thrift::protocol::TInputRecursionTracker tracker(*iprot);
  uint32_t xfer = 0;
  std::string fname;
  ::apache::thrift::protocol::TType ftype;
  int16_t fid;

  xfer += iprot->readStructBegin(fname);

  using ::apache::thrift::protocol::TProtocolException;

  while (true)
  {
    xfer += iprot->readFieldBegin(fname, ftype, fid);
    if (ftype == ::apache::thrift::protocol::T_STOP) {
      break;
    }
    switch (fid)
    {
      case 1:
        if (ftype == ::apache::thrift::protocol::T_STRUCT) {
          xfer += this->column_expr.read(iprot);
          this->__isset.column_expr = true;
        } else {
          xfer += iprot->skip(ftype);
        }
        break;
      case 2:
        if (ftype == ::apache::thrift::protocol::T_STRUCT) {
          xfer += this->query_sparse_expr.read(iprot);
          this->__isset.query_sparse_expr = true;
        } else {
          xfer += iprot->skip(ftype);
        }
        break;
      case 3:
        if (ftype == ::apache::thrift::protocol::T_STRING) {
          xfer += iprot->readString(this->metric_type);
          this->__isset.metric_type = true;
        } else {
          xfer += iprot->skip(ftype);
        }
        break;
      case 4:
        if (ftype == ::apache::thrift::protocol::T_I64) {
          xfer += iprot->readI64(this->topn);
          this->__isset.topn = true;
        } else {
          xfer += iprot->skip(ftype);
        }
        break;
      case 5:
        if (ftype == ::apache::thrift::protocol::T_LIST) {
          {
            this->opt_params.clear();
            uint32_t _size213;
            ::apache::thrift::protocol::TType _etype216;
            xfer += iprot->readListBegin(_etype216, _size213);
            this->opt_params.resize(_size213);
            uint32_t _i217;
            for (_i217 = 0; _i217 < _size213; ++_i217)
            {
              xfer += this->opt_params[_i217].read(iprot);
            }
            xfer += iprot->readListEnd();
          }
          this->__isset.opt_params = true;
        } else {
          xfer += iprot->skip(ftype);
        }
        break;
      case 6:
        if (ftype == ::apache::thrift::protocol::T_STRUCT) {
          xfer += this->filter_expr.read(iprot);
          this->__isset.filter_expr = true;
        } else {
          xfer += iprot->skip(ftype);
        }
        break;
      default:
        xfer += iprot->skip(ftype);
        break;
    }
    xfer += iprot->readFieldEnd();
  }

  xfer += iprot->readStructEnd();

  return xfer;
}

uint32_t MatchSparseExpr::write(::apache::thrift::protocol::TProtocol* oprot) const {
  uint32_t xfer = 0;


    p.setColor(m_color);
    painter.setPen(p);

    if (m_style == Percent)
    {
        painter.drawArc(r, Deg90, -1 * static_cast<int>(m_value) * FullCircle / 100);
    }
    else
    {
        painter.drawArc(r, m_angle, -1 * FullCircle / 5);
    }

    const bool hover = property("hover").toBool();

    if (hover && m_buttonStyle != NoButton)
    {
        switch (m_buttonStyle)
        {
            case Cross:
            {
                paintCrossButton(painter, r);
                break;
            }

            case Stop:
            {
                paintStopButton(painter, r);
                break;
            }

            default:
            {
                break;
            }
        }
    }
    else if (m_style == Percent)
    {
        // Draw text
        p.setWidth(px(1));
        p.setColor(palette().foreground().color());
        painter.setPen(p);
        painter.setFont(font());
        painter.drawText(r, Qt::AlignCenter, m_text);
    }
}

void RoundProgressIndicator::paintCrossButton(QPainter& painter, QRect& r)
{
    // Draw cancel button (red cross)

    const auto margin = (1. - m_buttonSize) * 0.5;
    const auto dh = m_indicatorWidth + static_cast<int>(r.width() * margin);
    const auto dv = m_indicatorWidth + static_cast<int>(r.height() * margin);
    r.adjust(dh, dv, -dh, -dv);

    auto p = painter.pen();
    p.setWidth(m_crossWidth);
    p.setColor(m_buttonColor);
    p.setCapStyle(Qt::SquareCap);

    painter.setPen(p);
    painter.setBrush(Qt::NoBrush);
    painter.drawLine(r.topLeft(), r.bottomRight());
    painter.drawLine(r.bottomLeft(), r.topRight());
}

void RoundProgressIndicator::paintStopButton(QPainter& painter, QRect& r)
{
    // Draw cancel button (red cross)

    const auto margin = (1. - m_buttonSize) * 0.5;
    const auto dh = m_indicatorWidth + static_cast<int>(r.width() * margin);
    const auto dv = m_indicatorWidth + static_cast<int>(r.height() * margin);
    r.adjust(dh, dv, -dh, -dv);

    painter.setPen(Qt::NoPen);
    painter.setBrush(m_buttonColor);
    painter.drawRect(r);
}

void RoundProgressIndicator::enterEvent(QEvent* event) {
    Parent::enterEvent(event);
    profiler_gui::updateProperty(this, "hover", true);
}

void RoundProgressIndicator::leaveEvent(QEvent* event) {
    Parent::leaveEvent(event);
    profiler_gui::updateProperty(this, "hover", false);
}

void RoundProgressIndicator::mousePressEvent(QMouseEvent* event)
{
    Parent::mousePressEvent(event);
    m_pressed = true;
    profiler_gui::updateProperty(this, "pressed", true);
}

void RoundProgressIndicator::mouseReleaseEvent(QMouseEvent* event)
{
    Parent::mouseReleaseEvent(event);

    const bool hover = property("hover").toBool();
    const bool pressed = m_pressed;

    m_pressed = false;
    profiler_gui::updateProperty(this, "pressed", false);

    if (pressed && hover && m_buttonStyle != NoButton)
    {
        emit buttonClicked(m_buttonRole);
    }
}

void RoundProgressIndicator::mouseMoveEvent(QMouseEvent* event)
{
    if (m_pressed)
    {
        const bool hover = property("hover").toBool();
        if (rect().contains(event->pos()))
        {
            if (!hover)
            {


�值对 |

## Events

| 名字 | 参数  | 描述 |
|-----|-----|-----|
| on-change | (value) | 值变化时触发 |

## Demos

``` vux height=500 components=Group,Selector
<template>
<div>
  <group :title="'no placeholder, the current value is : ' + defaultValue">
    <selector title="省份" :options="list" :value.sync="defaultValue"></selector>
  </group>

  <group title="with placeholder">
    <selector placeholder="请选择省份" title="省份" :options="list" @on-change="onChange"></selector>
  </group>

  <group title="without title">
    <selector placeholder="请选择省份" :options="list"></selector>
  </group>

  <group title="set value=广西">
    <selector :value.sync="value1" title="省份" :options="plainList" @on-change="onChange"></selector>
  </group>

  <group title="readonly, displays just like a cell">
    <selector value="gd" readonly title="省份" :options="list"></selector>
  </group>

  <group title="use plain options">
    <selector value="C" title="Selector" :options="list1" @on-change="onChange"></selector>
  </group>

  <group title='multi selector'>
    <selector placeholder="请选择省份" title="省份" :options="list"></selector>
    <selector :value.sync="value2" title="省份" :options="list"></selector>
  </group>
</div>
</template>

<script>
export default {
  data () {
    return {
      defaultValue: '',
      plainList: ['广东', '广西'],
      list: [{key: 'gd', value: '广东'}, {key: 'gx', value: '广西'}],
      value1: '广西',
      value2: 'gd',
      list1: ['A', 'B', 'C']
    }
  },
  methods: {
    onChange (val) {
      console.log(val)
    }
  }
}
</script>
```# 秒数倒计时

## 使用场景

> 用于发送短信等耗费操作时，不要依赖前端验证，`必须一定要`同时在后端进行ratelimit验证。

+ 短信验证重发的场景中。一般为60s, 120s

## API

| 参数         | 说明                  | 类型        | 默认值 |
| ----------- | ---------------------- | ---------- | ------- |
| time| 可选，计时秒数  | Number  | 60 |
| start| 可选，默认自动倒计时，设为false时可以手动开始计时 | Boolean | true |

## Demo

``` vux height=65 components=Group,Cell,Countdown
<template>
<group>
  <cell title="15s" :value="value">
    <countdown slot="value" :time="15" @on-finish="finish" v-show="show"></countdown>
  </cell>
</group>
</template>

<script>
export default {
  methods: {
    finish: function (index) {
      this.show = false
      this.value = 'completed'
      console.log('current index', index)
    }
  },
  data


s(hours: number): void;
    addDays(days: number): void;
    subtractDays(days: number): void;
    get milliseconds(): number;
    get seconds(): number;
    get minutes(): number;
    get hours(): number;
    get days(): number;
    get totalMilliseconds(): number;
    get totalSeconds(): number;
    get totalMinutes(): number;
    get totalHours(): number;
    get totalDays(): number;
    equals(compare: TimeSpan): boolean;
    lesser(compare: TimeSpan): boolean;
    lesserEqual(compare: TimeSpan): boolean;
    greater(compare: TimeSpan): boolean;
    greaterEqual(compare: TimeSpan): boolean;
}
// -----------------------------------------------------------------------
// <copyright file="AlertRule.ts" company="Microsoft Corporation">
//        Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

/**
 * This model represents an alert rule
 */
export default interface AlertRule {

    /**
     * The alert rule name.
     */
    name: string;

    /**
     * The alert rule description.
     */
    description?: string;

    /**
     * The signal id.
     */
    signalId: string;

    /**
     * The resource to be analyzed by the signal.
     */
    resourceId: string;

    /**
     * The cadence in minutes interval.
     */
    cadenceInMinutes: number;

    /**
     * The email recipients for the signal result.
     */
    emailRecipients?: string[];
}import isInteger from "./is-integer";

/**
 * Checks that input is even number.
 * @param {number} input
 * @return {boolean}
 * @exemple
 *
 * isEven(2) //=> true
 * isEven(Infinity) //=> false
 * isEven(1) //=> false
 * isEven(2.2) //=> false
 */
const isEven = (input: number): boolean => {
  return isInteger(input) && (input % 2 === 1 ? false : true);
};

export default isEven;
namespace L01_FirstFudge {
    import f = FudgeCore;

    window.addEventListener("load", hndLoad);
    export let viewport: f.Viewport;

    function hndLoad(_event: Event): void {
        const canvas: HTMLCanvasElement = document.querySelector("canvas");
        f.Debug.log(canvas);

        //Nodes werden deklariert.
        let node: f.Node = new f.Node("Quad");
        let node2: f.Node = new f.Node("Cube");
        let node3: f.Node = new f.Node("Pyramid");
        let node4: f.Node = new f.Node("Torus");

        //Mesh für das Quad wird deklariert und transformiert.
        let mesh: f.MeshQuad = new f.MeshQuad();
        let cmpMesh: f.ComponentMesh = new f.ComponentMesh(mesh);
        cmpMesh.pivot.translateY(-0.5);
        node.addComponent(cmpMesh);

        //Mesh für den Cube wird deklariert und transformiert.
        let mesh2: f.MeshCube = new f.MeshCube();
        let cmpMesh2: f.ComponentMesh = new f.ComponentMesh(mesh2);
        cmpMesh2.pivot.translateX(-1.1);
        cmpMesh2.pivot.translateY(-0.2);
        cmpMesh2.pivot.rotateX(45);
        node2.addComponent(cmpMesh2);
        node.addChild(node2);

        //Mesh für die Pyramide wird deklariert und transformiert.
        let mesh3: f.MeshPyramid = new f.MeshPyramid();
        let cmpMesh3: f.ComponentMesh = new f.ComponentMesh(mesh3);
        cmpMesh3.pivot.rotateY(45);
        cmpMesh3.pivot.rotateX(30);
        node3.addComponent(cmpMesh3);
        node.addChild(node3);

        //Mesh für den Torus wird dekl


on update_height(svg, height)
  return svg:gsub("height='.-pt'", "height='"..height .."pt'")
end

-- we need to fix the svg height
return function(svg)
  local max_height = 0
  local height = get_height(svg)
  for path in svg:gmatch("path d='([^']+)'") do
    -- find highest height in all paths in the svg file
    max_height = get_max_height(path, max_height)
  end
  -- update the height only if the max_height is larger than height set in the SVG file
  log:debug("max height and height", max_height, height)
  if max_height > height then
    svg = update_height(svg, max_height)
  end
  return svg
end


check:active + &,
  &:active,
  &.active,
  &.show {
    color: var(--#{$prefix}btn-active-color);
    box-shadow: var(--#{$prefix}btn-box-shadow);

    &:focus {
      color: var(--#{$prefix}btn-focus-color);
      box-shadow: var(--#{$prefix}btn-box-shadow);
    }
  }

  &:disabled,
  &.disabled,
  fieldset:disabled & {
    box-shadow: var(--#{$prefix}btn-box-shadow);
  }
}

[data-mdb-theme='dark'] .btn-secondary {
  --#{$prefix}btn-bg: #{tint-color($primary, 60%)};
  --#{$prefix}btn-hover-bg: #{tint-color($primary, 50%)};
  --#{$prefix}btn-focus-bg: #{tint-color($primary, 50%)};
  --#{$prefix}btn-active-bg: #{tint-color($primary, 50%)};
}

[data-mdb-theme='dark'] .btn-link {
  --#{$prefix}btn-color: #{$secondary};
  --#{$prefix}btn-hover-color: #{tint-color($secondary, 30%)};
  --#{$prefix}btn-hover-bg: #{shade-color($secondary, 60%)};
  --#{$prefix}btn-focus-color: #{tint-color($secondary, 30%)};
  --#{$prefix}btn-active-color: #{tint-color($secondary, 30%)};
}

[data-mdb-theme='dark'] .btn-tertiary {
  --#{$prefix}btn-color: #{$secondary};
  --#{$prefix}btn-hover-color: #{tint-color($secondary, 30%)};
  --#{$prefix}btn-focus-color: #{tint-color($secondary, 30%)};
  --#{$prefix}btn-active-color: #{tint-color($secondary, 30%)};
}

//
// Button Sizes
//

.btn-lg {
  @include button-size(
    $btn-padding-top-lg,
    $btn-padding-bottom-lg,
    $btn-padding-x-lg,
    $btn-font-size-lg,
    $btn-line-height-lg
  );
}

.btn-sm {
  @include button-size(
    $btn-padding-top-sm,
    $btn-padding-bottom-sm,
    $btn-padding-x-sm,
    $btn-font-size-sm,
    $btn-line-height-sm
  );
}

//
// Rounded option
//

.btn-rounded {
  --#{$prefix}btn-border-radius: #{$btn-rounded-border-radius};

  border-radius: var(--#{$prefix}btn-border-radius);
}

//
// Floating option
//

.btn-floating,
[class*='btn-outline-'].btn-floating {
  --#{$prefix}btn-border-radius: #{$btn-floating-border-radius};

  border-radius: var(--#{$prefix}btn-border-radius);
  padding: 0;
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.btn-floating {
  --#{$prefix}btn-width: #{$btn-floating-width};
  --#{$prefix}btn-height: #{$btn-floating-height};
  --#{$prefix}btn-icon-width: #{$btn-floating-icon-width};
  --#{$prefix}btn-icon-line-height: #{$btn-floating-icon-line-height};
  --#{$prefix}btn-width-lg: #{$btn-floating-width-lg};
  --#{$prefix}btn-height-lg: #{$btn-floating-height-lg};
  --#{$prefix}btn-icon-width-lg: #{$btn-floating-icon-width-lg};
  --#{$prefix}btn-icon-line-height-lg: #{$btn-floating-icon-line-height


大概只能装个打火机、钥匙、电子烟。其实，起初是为了装怀表而刻意设计的。百年来却成了经典样式，沿用至今。

### 起飞

多么不起眼的小虫子啊，却能做许多了不起的事情，比如飞翔。美国生物学家 Adrian Smith
拍摄了一些飞蛾和甲虫的起飞慢动作镜头，治愈、惊艳又令人敬畏。看了三遍！

### 茶的读音

地图不能完全反映真实世界，却是理解世界和历史的有效工具。一个有意思的现象：「茶」字在外语中有两种主流读法：cha 和
tea。前者是茶通过陆路贸易得以传播的体现，后者则是海路贸易（闽南话中，「茶......

### 身高

平时看到周遭的初中生总诧异，怎么都长这么高？找到一组有趣的数据：从 1810 年到 1980 年，人类的平均身高一直在增加。中国人大概长高了 0.5
厘米，日本人是 1.3 厘米。

......

### 自行车

有些东西看似构造简单，却到近代才出现，令人匪夷所思。自行车就是一例。

为什么等到 18 世纪才有呢？马车已经存在上千年，怎么人们都没有想过自行车？为什么自行车......

### 高桥流简报法

不喜欢制作花哨的 PPT？可以了解一下 20
多年前由日本人高桥征义发明的高桥流简报法：每张幻灯片都无图或图表，只用最少的文字和超大的字号来浓缩展示观点，相当有视觉冲击力。

### 黒鹭

有白鹭，自然也有黑鹭。二者同属（白鹭属）不同种，前者常见，后者嘛，不记得在动物园是否见过，反正，生活中不曾见，毕竟没有分布在国内。它有两个特殊之处：

1\. 黑（身）黄（......

awesome-xiaobot

返回 [首页](../README.md)
# 培训经理工作手册_小报童_Awesome_XiaoBOT

## 培训经理工作手册介绍
> 积累知识很重要，但沉淀真实场景下的解决方案更重要\n聚焦你遇到的真实挑战\n这本小册子是我对过往10年实践的总结和思考\n希望当我们遇到新难题的时候\n拿出来看看可以找到破局的灵感\n\n目标：BEST
Handbook For TM\n做最贴心的培训经理基本功手册\n\n本专栏内容属于买断制，一次付费永久查看。\n


�检查** - 检查系统环境和依赖
2. **数据库配置** - 配置 SurrealDB 连接
3. **管理员账户** - 创建系统管理员账户
4. **站点配置** - 配置站点基本信息
5. **完成安装** - 保存配置并初始化系统

#### Cargo Run vs Cargo Build 的区别

**开发时使用 Cargo Run:**
```bash
cargo run                        # 编译+运行开发版本
cargo run --features installer   # 编译+运行安装版本
```
- 每次检查代码变化并重新编译
- 适合开发和测试
- 程序运行在前台，Ctrl+C 停止

**生产部署使用 Cargo Build:**
```bash
cargo build --release            # 只编译，生成优化的可执行文件
./target/release/rainbow-docs     # 运行编译好的程序
```
- 生成独立的二进制文件，可部署到其他机器
- 性能更好，适合生产环境

### 方式二：手动配置（高级用户）

#### 1. 克隆项目
```bash
git clone https://github.com/yourusername/rainbow-docs.git
cd rainbow-docs
```

#### 2. 配置环境变量
```bash
cp .env.example .env
# 编辑 .env 文件配置数据库和认证信息
```

#### 3. 初始化数据库
```bash
# 连接到 SurrealDB
surreal sql --conn http://localhost:8000 --user root --pass root --ns docs --db main

# 导入数据库架构
surreal import --conn http://localhost:8000 --user root --pass root --ns docs --db main schemas/docs_schema.sql
```

#### 4. 构建和运行
```bash
# 构建生产版本（不包含安装向导）
cargo build --release
cargo run

# 或直接运行
./target/release/rainbow-docs
```

#### 5. 验证安装
```bash
curl http://localhost:3000/health
```

### 🔄 安装状态检查机制

系统通过以下机制判断是否需要显示安装向导：

1. **首次启动**: 没有 `.rainbow_docs_installed` 文件 → 显示安装向导
2. **安装完成**: 创建 `.rainbow_docs_installed` 文件 → 正常运行模式
3. **重新安装**: 删除 `.rainbow_docs_installed` 文件 → 重新显示安装向导

```bash
# 重新进入安装模式（用于测试）
rm -f .rainbow_docs_installed
cargo run --features installer
```

### 🛠 构建脚本使用

项目提供了便捷的构建脚本：

```bash
# 构建安装版本（包含安装向导）
./build.sh installer

# 构建生产版本（不包含安装向导）
./build.sh production

# 构建开发版本
./build.sh dev

# 查看帮助
./build.sh
```

### 📋 前后端配


 test := range cases {
			txn := client.NewTxn()
			reply, err := txn.Query(ctx, test.query)
			require.NoError(t, err)
			testutil.CompareJSON(t, test.wantResult, string(reply.GetJson()))
		}
	}

	suite(
		"name: string @index(term) .",
		`[
			{ "name": "Michael" },
			{ "name": "Amit" },
			{ "name": "Luke" },
			{ "name": "Darth" },
			{ "name": "Sarah" },
			{ "name": "Ricky" },
			{ "name": "Hugo" }
		]`,
		[]testCase{
			{`
				{
					q(func: eq(name, "Hugo")) {
						name
					}
				}`, `
				{
				"q": [
				  {
					"name": "Hugo"
				  }
				]
			  }`,
			},
		},
	)
}

func TestClusterSetupWithMultiGroup(t *testing.T) {
	c := &x.TLSHelperConfig{
		CertRequired:     true,
		Cert:             "../tls/alpha1/client.alpha1.crt",
		Key:              "../tls/alpha1/client.alpha1.key",
		ServerName:       "alpha1",
		RootCACert:       "../tls/alpha1/ca.crt",
		UseSystemCACerts: true,
	}
	tlsConf, err := x.GenerateClientTLSConfig(c)
	require.NoError(t, err)
	dgConn, err := grpc.Dial(testutil.SockAddr, grpc.WithTransportCredentials(credentials.NewTLS(tlsConf)))
	require.NoError(t, err)
	client := dgo.NewDgraphClient(api.NewDgraphClient(dgConn))
	runTests(t, client)
}
// Copyright 2022 Outcaste LLC. Licensed under the Apache License v2.0.
package main

import "time"

type RateMonitor struct {
	start       time.Time
	lastSent    uint64
	lastCapture time.Time
	rates       []float64
	idx         int
}

func NewRateMonitor(numSamples int) *RateMonitor {
	return &RateMonitor{
		start: time.Now(),
		rates: make([]float64, numSamples),
	}
}

const minRate = 0.0001

// Capture captures the current number of sent bytes. This number should be monotonically
// increasing.
func (rm *RateMonitor) Capture(sent uint64) {
	diff := sent - rm.lastSent
	dur := time.Since(rm.lastCapture)
	rm.lastCapture, rm.lastSent = time.Now(), sent

	rate := float64(diff) / dur.Seconds()
	if rate < minRate {
		rate = minRate
	}
	rm.rates[rm.idx] = rate
	rm.idx = (rm.idx + 1) % len(rm.rates)
}

// Rate returns the average rate of transmission smoothed out by the number of samples.
func (rm *RateMonitor) Rate() uint64 {
	var total float64
	var den float64
	for _, r := range rm.rates {
		if r < minRate {
			// Ignore this. We always set minRate, so this is a zero.
			// Typically at the start of the rate monitor, we'd have zeros.
			continue
		}
		total += r
		den += 1.0
	}
	if den < minRate {
		return 0
	}
	return uint64(total / den)
}
// Copyright 2022 Outcaste LLC. Licensed under the Apache License v2.0.

package main

import "time"

type RateMonitor struct {
	start       time.Time
	lastSent    uint64
	lastCapture time.Time
	rates       []float64
	idx         int
}

func NewRateMonitor(numSamples int) *RateMonitor {
	return &RateMonitor{
		start: time.Now(),
		rates: make([]float64, numSamples),
	}
}

const minRate = 0.0001

// Capture captures the current number of sent bytes. This number sh


eBottom = 0
        private set

    @JvmStatic
    var lineSpacingExtra = 0f
        private set

    @JvmStatic
    var paragraphSpacing = 0
        private set

    @JvmStatic
    var titleTopSpacing = 0
        private set

    @JvmStatic
    var titleBottomSpacing = 0
        private set

    @JvmStatic
    var indentCharWidth = 0f
        private set

    @JvmStatic
    var titlePaintTextHeight = 0f
        private set

    @JvmStatic
    var contentPaintTextHeight = 0f
        private set

    @JvmStatic
    var titlePaintFontMetrics = FontMetrics()

    @JvmStatic
    var contentPaintFontMetrics = FontMetrics()

    @JvmStatic
    var typeface: Typeface? = Typeface.DEFAULT
        private set

    @JvmStatic
    var titlePaint: TextPaint = TextPaint()

    @JvmStatic
    var contentPaint: TextPaint = TextPaint()

    @JvmStatic
    var reviewPaint: TextPaint = TextPaint()

    @JvmStatic
    var doublePage = false
        private set

    @JvmStatic
    var visibleRect = RectF()

    private val handler by lazy {
        buildMainHandler()
    }

    private var upViewSizeRunnable: Runnable? = null

    init {
        upStyle()
    }

    /**
     * 获取拆分完的章节数据
     */
    suspend fun getTextChapter(
        book: Book,
        bookChapter: BookChapter,
        displayTitle: String,
        bookContent: BookContent,
        chapterSize: Int,
    ): TextChapter {
        val contents = bookContent.textList
        val textPages = arrayListOf<TextPage>()
        val stringBuilder = StringBuilder()
        var absStartX = paddingLeft
        var durY = 0f
        textPages.add(TextPage())
        if (ReadBookConfig.titleMode != 2 || bookChapter.isVolume) {
            //标题非隐藏
            displayTitle.splitNotBlank("\n").forEach { text ->
                setTypeText(
                    book, absStartX, durY,
                    if (AppConfig.enableReview) text + reviewChar else text,
                    textPages,
                    stringBuilder,
                    titlePaint,
                    titlePaintTextHeight,
                    titlePaintFontMetrics,
                    isTitle = true,
                    emptyContent = contents.isEmpty(),
                    isVolumeTitle = bookChapter.isVolume
                ).let {
                    absStartX = it.first
                    durY = it.second
                }
            }
            textPages.last().lines.last().isParagraphEnd = true
            stringBuilder.append("\n")
            durY += titleBottomSpacing
        }
        contents.forEach { content ->
            if (book.getImageStyle().equals(Book.imgStyleText, true)) {
                //图片样式为文字嵌入类型
                var text = content.replace(srcReplaceChar, "▣")
                val srcList = LinkedList<String>()
                val sb = StringBuffer()
                val matcher = AppPattern.imgPattern.matcher(text)
                while (matcher.find()) {
                    matcher.group(1)?.let { src ->
                        srcList.add(src)
                        matcher.appendReplacement(sb, srcReplaceChar)
                    }
                }
                matcher.appendTail(sb)
                text = sb.toString()
                setTypeText(
                    book,
                    absStartX,
                    durY,
                    text,
                    textPages,
                    stringBuilder,
                    contentPaint,
                    contentPaintTextHeight,
                    content


using System;

namespace LibreMetaverse.RLV
{
    /// <summary>
    /// Represents a request to attach an item to the avatar
    /// </summary>
    public class AttachmentRequest
    {
        public Guid ItemId { get; }
        public RlvAttachmentPoint AttachmentPoint { get; }
        public bool ReplaceExistingAttachments { get; }

        public AttachmentRequest(Guid itemId, RlvAttachmentPoint attachmentPoint, bool replaceExistingAttachments)
        {
            ItemId = itemId;
            AttachmentPoint = attachmentPoint;
            R