", sIndent(ind))
	ind += step
	switch lt := li.TechniqueCommon.Type.(type) {
	case *Ambient:
		lt.Dump(out, ind)
	case *Directional:
		lt.Dump(out, ind)
	case *Point:
		lt.Dump(out, ind)
	case *Spot:
		lt.Dump(out, ind)
	}
}

//
// Ambient
//
type Ambient struct {
	Color LightColor
}

// Dump prints out information about the Ambient
func (amb *Ambient) Dump(out io.Writer, indent int) {

	fmt.Fprintf(out, "%sAmbient\n", sIndent(indent))
	ind := indent + step
	amb.Color.Dump(out, ind)
}

//
// Directional
//
type Directional struct {
	Color LightColor
}

// Dump prints out information about the Directional
func (dir *Directional) Dump(out io.Writer, indent int) {

	fmt.Fprintf(out, "%sDirectional\n", sIndent(indent))
	ind := indent + step
	dir.Color.Dump(out, ind)
}

//
// Point
//
type Point struct {
	Color                LightColor
	ConstantAttenuation  *FloatValue
	LinearAttenuation    *FloatValue
	QuadraticAttenuation *FloatValue
}

// Dump prints out information about the Point
func (pl *Point) Dump(out io.Writer, indent int) {

	fmt.Fprintf(out, "%sPoint\n", sIndent(indent))
	indent += step
	pl.Color.Dump(out, indent)
	pl.ConstantAttenuation.Dump("ConstantAttenuation", out, indent)
	pl.LinearAttenuation.Dump("LinearAttenuation", out, indent)
	pl.QuadraticAttenuation.Dump("QuadraticAttenuation", out, indent)
}

//
// Spot
//
type Spot struct {
	Color                LightColor
	ConstantAttenuation  *FloatValue
	LinearAttenuation    *FloatValue
	QuadraticAttenuation *FloatValue
	FalloffAngle         *FloatValue
	FalloffExponent      *FloatValue
}

// Dump prints out information about the Spot
func (sl *Spot) Dump(out io.Writer, indent int) {

	fmt.Fprintf(out, "%sSpot\n", sIndent(indent))
	indent += step
	sl.Color.Dump(out, indent)
	sl.ConstantAttenuation.Dump("ConstantAttenuation", out, indent)
	sl.LinearAttenuation.Dump("LinearAttenuation", out, indent)
	sl.QuadraticAttenuation.Dump("QuadraticAttenuation", out, indent)
	sl.FalloffAngle.Dump("FalloffAngle", out, indent)
	sl.FalloffExponent.Dump("FalloffExponent", out, indent)
}

//
// FloatValue
//
type FloatValue struct {
	Sid   string
	Value float32
}

// Dump prints out information about the FloatValue
func (fv *FloatValue) Dump(name string, out io.Writer, indent int) {

	if fv == nil {
		return
	}
	fmt.Fprintf(out, "%s%s sid:%s value:%v\n", sIndent(indent), name, fv.Sid, fv.Value)
}

//
// LightColor
//
type LightColor struct {
	Sid  string
	Data [3]float32
}

// Dump prints out information about the LightColor
func (lc *LightColor) Dump(out io.Writer, indent int) {

	fmt.Fprintf(out, "%sColor sid:%s data:%v\n", sIndent(indent), lc.Sid, lc.Data)
}

func (d *Decoder) decLibraryLights(start xml.StartElement, dom *Col


 'https://github.com/Jam3/nice-color-palettes',toggle view and resize ui to arrange the colors;
$c: 'Set 79',#4e395d;
$c: 'Set 79',#827085;
$c: 'Set 79',#8ebe94;
$c: 'Set 79',#ccfc8e;
$c: 'Set 79',#dc5b3e;
$c: 'https://github.com/Jam3/nice-color-palettes',toggle view and resize ui to arrange the colors;
$c: 'Set 80',#a8a7a7;
$c: 'Set 80',#cc527a;
$c: 'Set 80',#e8175d;
$c: 'Set 80',#474747;
$c: 'Set 80',#363636;
$c: 'https://github.com/Jam3/nice-color-palettes',toggle view and resize ui to arrange the colors;
$c: 'Set 81',#f8edd1;
$c: 'Set 81',#d88a8a;
$c: 'Set 81',#474843;
$c: 'Set 81',#9d9d93;
$c: 'Set 81',#c5cfc6;
$c: 'https://github.com/Jam3/nice-color-palettes',toggle view and resize ui to arrange the colors;
$c: 'Set 82',#046d8b;
$c: 'Set 82',#309292;
$c: 'Set 82',#2fb8ac;
$c: 'Set 82',#93a42a;
$c: 'Set 82',#ecbe13;
$c: 'https://github.com/Jam3/nice-color-palettes',toggle view and resize ui to arrange the colors;
$c: 'Set 83',#f38a8a;
$c: 'Set 83',#55443d;
$c: 'Set 83',#a0cab5;
$c: 'Set 83',#cde9ca;
$c: 'Set 83',#f1edd0;
$c: 'https://github.com/Jam3/nice-color-palettes',toggle view and resize ui to arrange the colors;
$c: 'Set 84',#a70267;
$c: 'Set 84',#f10c49;
$c: 'Set 84',#fb6b41;
$c: 'Set 84',#f6d86b;
$c: 'Set 84',#339194;
$c: 'https://github.com/Jam3/nice-color-palettes',toggle view and resize ui to arrange the colors;
$c: 'Set 85',#ff003c;
$c: 'Set 85',#ff8a00;
$c: 'Set 85',#fabe28;
$c: 'Set 85',#88c100;
$c: 'Set 85',#00c176;
$c: 'https://github.com/Jam3/nice-color-palettes',toggle view and resize ui to arrange the colors;
$c: 'Set 86',#ffedbf;
$c: 'Set 86',#f7803c;
$c: 'Set 86',#f54828;
$c: 'Set 86',#2e0d23;
$c: 'Set 86',#f8e4c1;
$c: 'https://github.com/Jam3/nice-color-palettes',toggle view and resize ui to arrange the colors;
$c: 'Set 87',#4e4d4a;
$c: 'Set 87',#353432;
$c: 'Set 87',#94ba65;
$c: 'Set 87',#2790b0;
$c: 'Set 87',#2b4e72;
$c: 'https://github.com/Jam3/nice-color-palettes',toggle view and resize ui to arrange the colors;
$c: 'Set 88',#0ca5b0;
$c: 'Set 88',#4e3f30;
$c: 'Set 88',#fefeeb;
$c: 'Set 88',#f8f4e4;
$c: 'Set


(selectedResolutionEntity));
        if (selectedFrameRateEntity != null)
            bundle.putString(FrameRateEntity.TAG, JSON.toJSONString(selectedFrameRateEntity));
        bundle.putString("productId", productId);
        bundle.putString("deviceName", deviceName);
        bundle.putString("xp2pInfo", xp2pInfo);
        intent.putExtra(PhoneInfo.TAG, bundle);
        startActivityForResult(intent, 4);
    }

    private void startPhoneCalled(Integer callType) {
        Log.e(TAG, "callType " + callType);
        Intent intent = new Intent(DeviceAndDeviceCommunicationActivity.this, RecordVideoActivity3.class);
        Bundle bundle = new Bundle();
        PhoneInfo phoneInfo = new PhoneInfo();
        phoneInfo.setCallType(callType);
        bundle.putString(PhoneInfo.TAG, JSON.toJSONString(phoneInfo));
        if (selectedResolutionEntity != null)
            bundle.putString(ResolutionEntity.TAG, JSON.toJSONString(selectedResolutionEntity));
        if (selectedFrameRateEntity != null)
            bundle.putString(FrameRateEntity.TAG, JSON.toJSONString(selectedFrameRateEntity));
        intent.putExtra(PhoneInfo.TAG, bundle);
        startActivityForResult(intent, 3);
    }

    private TXMqttActionCallBack txMqttActionCallBack = new TXMqttActionCallBack() {

        @Override
        public void onConnectCompleted(Status status, boolean reconnect, Object userContext, String msg, Throwable cause) {
            if (reconnect) {
                videoDataTemplateSample.subscribeTopic();
//                VideoNativeInteface.getInstance().release();
                handler.post(() -> initVideoModeul(getDeviceConnectCondition()));
                updateLog("已自动重连 在线");
            } else {
                Log.e(TAG, "TXMqttActionCallBack onConnectCompleted");
                Log.e(TAG, "TXMqttActionCallBack " + Thread.currentThread().getId());
                updateLog("在线");
                if (videoDataTemplateSample == null) return;
                handler.post(() -> qrImg.setImageBitmap(ZXingUtils.createQRCodeBitmap(videoDataTemplateSample.generateDeviceQRCodeContent(), 200, 200, "UTF-8", "H", "1", Color.BLACK, Color.WHITE)));
                videoDataTemplateSample.subscribeTopic();

                DeviceConnectCondition condtion = new DeviceConnectCondition(productIdEt.getText().toString(), devNameEt.getText().toString(), devPskEt.getText().toString());
                handler.post(() -> initVideoModeul(condtion));
                saveDeviceConnectCondition(condtion);
            }
        }

        @Override
        public void onConnectionLost(Throwable cause) {
            VideoNativeInteface.getInstance().release();
            Log.e(TAG, "TXMqttActionCallBack onConnectionLost");
            updateLog("掉线 " + cause.getMessage());
        }

        @Override
        public void onDisconnectCompleted(Status status, Object userContext, String msg, Throwable cause) {
            Log.e(TAG, "TXMqttActionCallBack onDisconnectCompleted");
            VideoNativeInteface.getInstance().release();
            updateLog("离线 " + msg);
        }

        @Override
        public void onSubscribeCompleted(Status status, IMqttToken token, Object userContext, String msg, Throwable cause) {
            Log.e(TAG, "TXMqttActionCallBack onSubscribeCompleted status " + status);
            if (Status.OK != videoDataTemplateSample.propertyGetStatus("report", false)) {
                Log.e(TAG, "property get status failed!");
            }
        }
    };

    private void saveDeviceConnectCondition(DeviceConnectCondition deviceConnectCondition) {
        if (deviceConnectCondition == null || TextUtils.isEmpty(deviceConnectCondition.getProductId())
            || TextUtils.isEmpty(deviceConnectCondition.getDevName())
            || TextUtils.isEmpty(deviceConnectCondition.getDevPsk())) {
            return;
        }


Client();
      final apiGateway = ApiGatewayV6(server, client: mockClient);
      final data = [
        {
          'history': [
            {
              'timestamp': 1511819900.539157,
              'total': 2134,
              'cached': 525,
              'blocked': 413,
              'forwarded': 1196,
            },
            {
              'timestamp': 1511820500.583821,
              'total': 2014,
              'cached': 52,
              'blocked': 43,
              'forwarded': 1910,
            },
          ],
          'took': 0.003,
        },
        {
          'clients': {
            '127.0.0.1': {'name': 'localhost', 'total': 13428},
            '::1': {'name': 'ip6-localnet', 'total': 2100},
            '192.168.1.1': {'name': null, 'total': 254},
            '::': {'name': 'pi.hole', 'total': 29},
            '0.0.0.0': {'name': 'other clients', 'total': 14},
          },
          'history': [
            {
              'timestamp': 1511819900.539157,
              'data': {
                '127.0.0.1': 35,
                '::1': 63,
                '192.168.1.1': 20,
                '::': 9,
                '0.0.0.0': 0,
              },
            },
            {
              'timestamp': 1511820500.583821,
              'data': {'127.0.0.1': 10, '::1': 44, '192.168.1.1': 56, '::': 52},
            },
          ],
          'took': 0.003,
        },
      ];

      when(
        mockClient.get(Uri.parse(urls[0]), headers: anyNamed('headers')),
      ).thenAnswer((_) async => http.Response(jsonEncode(data[0]), 200));

      when(
        mockClient.get(
          Uri.parse('${urls[1]}?N=10'),
          headers: anyNamed('headers'),
        ),
      ).thenAnswer((_) async => http.Response(jsonEncode(data[1]), 200));

      final response = await apiGateway.fetchOverTimeData();

      expect(response.result, APiResponseType.success);
      expect(response.data, isNotNull);
    });

    test('Return success with N params', () async {
      final mockClient = MockClient();
      final apiGateway = ApiGatewayV6(server, client: mockClient);
      final data = [
        {
          'history': [
            {
              'timestamp': 1511819900.539157,
              'total': 2134,
              'cached': 525,
              'blocked': 413,
              'forwarded': 1196,
            },
            {
              'timestamp': 1511820500.583821,
              'total': 2014,
              'cached': 52,
              'blocked': 43,
              'forwarded': 1910,
            },
          ],
          'took': 0.003,
        },
        {
          'clients': {
            '127.0.0.1': {'name': 'localhost', 'total': 13428},
            '::1': {'name': 'ip6-localnet', 'total': 2100},
            '192.168.1.1': {'name': null, 'total': 254},
            '::': {'name': 'pi.hole', 'total': 29},
            '0.0.0.0': {'name': 'other clients', 'total': 14},
          },
          'history': [
            {
              'timestamp': 1511819900.539157,
              'data': {
                '127.0.0.1': 35,
                '::1': 63,
                '192.168.1.1': 20,
                '::': 9,
                '0.0.0.0': 0,
              },
            },
            {
              'timestamp': 15


eryPreSingle.RegisterDynamic("*", (IProfileService svc,QueryPreSingleArgs args) =>
            {
                if (args.Query.Name == "") svc.MustHasAnyRole([Roles.Sa,Roles.Admin]);
                return args;
            });

            hookRegistry.QueryPreList.RegisterDynamic("*", (IProfileService svc,QueryPreListArgs args) =>
            {
                if (args.Query.Name == "") svc.MustHasAnyRole([Roles.Sa,Roles.Admin]);
                return args;
            });
        }
    }
}


from PIL import Image
from scipy import misc
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
import numpy as np
from skimage.transform import warp, AffineTransform

class RandomAffineTransform(object):
    def __init__(self,
                 scale_range=[0.4,1.05],
                 rotation_range=[-np.pi/8,np.pi/8],
                 shear_range=[-np.pi/32,np.pi/32],
                 translation_range=[-0.0, 0.0],
                 ):
        self.scale_range = scale_range
        self.rotation_range = rotation_range
        self.shear_range = shear_range
        self.translation_range = translation_range

    def __call__(self, img):
        img_data = np.array(img)
        h, w, n_chan = img_data.shape
        scale_x = np.random.uniform(*self.scale_range)
        scale_y = np.random.uniform(*self.scale_range)
        scale = (scale_x, scale_y)
        rotation = np.random.uniform(*self.rotation_range)
        shear = np.random.uniform(*self.shear_range)
        translation = (
            np.random.uniform(*self.translation_range) * w,
            np.random.uniform(*self.translation_range) * h
        )
        af = AffineTransform(scale=scale, shear=shear, rotation=rotation, translation=translation)
        img_data1 = warp(img_data, af.inverse)
        return img_data1
        img1 = Image.fromarray(np.uint8(img_data1 * 255))
        return img1


: Boolean Array.
    booleanValue: Boolean.
    doubleArray: Double Number Array.
    doubleValue: Double Number.
    intArray: Integer Array.
    intValue: Integer.
    jsonValue: Json.
    stringArray: String Array.
    stringValue: String.
  """

  booleanArray = _messages.MessageField('BooleanParameterArray', 1)
  booleanValue = _messages.BooleanField(2)
  doubleArray = _messages.MessageField('DoubleParameterArray', 3)
  doubleValue = _messages.FloatField(4)
  intArray = _messages.MessageField('IntParameterArray', 5)
  intValue = _messages.IntegerField(6)
  jsonValue = _messages.StringField(7)
  stringArray = _messages.MessageField('StringParameterArray', 8)
  stringValue = _messages.StringField(9)

encoding.AddCustomJsonFieldMapping(
    StandardQueryParameters, 'f__xgafv', '$.xgafv')
encoding.AddCustomJsonEnumMapping(
    StandardQueryParameters.FXgafvValueValuesEnum, '_1', '1')
encoding.AddCustomJsonEnumMapping(
    StandardQueryParameters.FXgafvValueValuesEnum, '_2', '2')
encoding.AddCustomJsonFieldMapping(
    CloudaicompanionProjectsLocationsCodeRepositoryIndexesRepositoryGroupsGetIamPolicyRequest, 'options_requestedPolicyVersion', 'options.requestedPolicyVersion')


ss >> after;

    EXPECT_EQ(before.a(), after.a());
    EXPECT_EQ(before.b(), after.b());
    EXPECT_EQ(before.param(), after.param());
    EXPECT_EQ(before, after);

    // Smoke test.
    auto sample_min = after.max();
    auto sample_max = after.min();
    for (int i = 0; i < kCount; i++) {
      auto sample = after(gen);
      EXPECT_GE(sample, after.min());
      EXPECT_LE(sample, after.max());
      if (sample > sample_max) {
        sample_max = sample;
      }
      if (sample < sample_min) {
        sample_min = sample;
      }
    }
    std::string msg = absl::StrCat("Range: ", +sample_min, ", ", +sample_max);
    ABSL_RAW_LOG(INFO, "%s", msg.c_str());
  }
}

TYPED_TEST(UniformIntDistributionTest, ViolatesPreconditionsDeathTest) {
#if GTEST_HAS_DEATH_TEST
  // Hi < Lo
  EXPECT_DEBUG_DEATH({ absl::uniform_int_distribution<TypeParam> dist(10, 1); },
                     "");
#endif  // GTEST_HAS_DEATH_TEST
#if defined(NDEBUG)
  // opt-mode, for invalid parameters, will generate a garbage value,
  // but should not enter an infinite loop.
  absl::InsecureBitGen gen;
  absl::uniform_int_distribution<TypeParam> dist(10, 1);
  auto x = dist(gen);

  // Any value will generate a non-empty string.
  EXPECT_FALSE(absl::StrCat(+x).empty()) << x;
#endif  // NDEBUG
}

TYPED_TEST(UniformIntDistributionTest, TestMoments) {
  constexpr int kSize = 100000;
  using Limits = std::numeric_limits<TypeParam>;
  using param_type =
      typename absl::uniform_int_distribution<TypeParam>::param_type;

  // We use a fixed bit generator for distribution accuracy tests.  This allows
  // these tests to be deterministic, while still testing the quality of the
  // implementation.
  absl::random_internal::pcg64_2018_engine rng{0x2B7E151628AED2A6};

  std::vector<double> values(kSize);
  for (const auto& param :
       {param_type(0, Limits::max()), param_type(13, 127)}) {
    absl::uniform_int_distribution<TypeParam> dist(param);
    for (int i = 0; i < kSize; i++) {
      const auto sample = dist(rng);
      ASSERT_LE(dist.param().a(), sample);
      ASSERT_GE(dist.param().b(), sample);
      values[i] = sample;
    }

    auto moments = absl::random_internal::ComputeDistributionMoments(values);
    const double a = dist.param().a();
    const double b = dist.param().b();
    const double n = (b - a + 1);
    const double mean = (a + b) / 2;
    const double var = ((b - a + 1) * (b - a + 1) - 1) / 12;
    const double kurtosis = 3 - 6 * (n * n + 1) / (5 * (n * n - 1));

    // TODO(ahh): this is not the right bound
    // empirically validated with --runs_per_test=10000.
    EXPECT_NEAR(mean, moments.mean, 0.01 * var);
    EXPECT_NEAR(var, moments.variance, 0.015 * var);
    EXPECT_NEAR(0.0, moments.skewness, 0.025);
    EXPECT_NEAR(kurtosis, moments.kurtosis, 0.02 * kurtosis);


          LocalChainId = 0,
            RemoteChainId = 1,
            IsClientToParentChain = false,
            RemoteServerHost = "localhost",
            RemoteServerPort = 5000
        };
        var communicationHelper = GetRequiredService<CrossChainCommunicationTestHelper>();
        communicationHelper.SetClientConnected(crossChainClientCreationContext.RemoteChainId, true);
        await _crossChainClientService.CreateClientAsync(crossChainClientCreationContext);
        _crossChainCacheEntityService.RegisterNewChain(crossChainClientCreationContext.RemoteChainId, 10);
        communicationHelper.CheckClientConnected(-1).ShouldBeFalse();
        await _crossChainRequestService.RequestCrossChainDataFromOtherChainsAsync();
        communicationHelper.CheckClientConnected(-1).ShouldBeTrue();

        var chainInitializationData =
            await _crossChainRequestService.RequestChainInitializationDataAsync(crossChainClientCreationContext
                .RemoteChainId);
        chainInitializationData.CreationHeightOnParentChain.ShouldBe(1);
    }
}


StrictEqual(['2', '3', '4']);
    })

    test('map should not mutate given list', () => {
        const list = [1,2,3];
        map(list, (it) => {
            return `${it + 1}`
        })
        expect(list).toStrictEqual([1,2,3]);
    })

    test('map should be called with all arguments', () => {
        const acc = []
        map(['a','b','c'], (...args) => {
            acc.push(args)
            return false;
        })
        expect(acc).toStrictEqual([
            ['a', 0, ['a','b','c']],
            ['b', 1, ['a','b','c']],
            ['c', 2, ['a','b','c']],
        ])
    })
})
import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
    name: "formatTime"
})
export class FormatTimePipe implements PipeTransform {
    transform(value: number): string {
        let v = value;
        const ms = v % 1000;
        v = Math.floor(v / 1000);
        const ss = v % 60;
        v = Math.floor(v / 60);
        const mm = v % 60;
        v = Math.floor(v / 60);
        const hh = v % 24;
        v = Math.floor(v / 24);
        const dd = v;

        return (
            (dd > 0 ? dd + " days " : "") +
            ("00" + hh).slice(-2) +
            ":" +
            ("00" + mm).slice(-2) +
            ":" +
            ("00" + ss).slice(-2)
        );
    }
}
import chalk from 'chalk';
import ora from 'ora';
import { logger, cleaner } from './index';

// 尽量不要用async函数来做最终的异常处理
async function handleSignal(signal: string): Promise<void> {
	const spiner = ora('do clean up...\n').start();
	try {
		await cleaner.cleanup(signal);
		spiner.succeed('Exiting without error.');
	} catch (e) {
		logger.error(`Clean up failed. Error message: ${e.message}`);
		console.error(chalk.red(e.stack));
		process.exit(1);
	}
	process.exit();
}

interface CustomError {
	msg: string;
	stack: string;
}

function isCustomError(e: any): e is CustomError {
	return !!e.msg;
}

// 尽量不要用async函数来做最终的异常处理
async function handleError(e: Error | CustomError): Promise<any> {
	if (isCustomError(e)) {
		logger.error(e.msg);
	} else {
		logger.error(e.message);
	}

	console.error(chalk.red(e.stack as string));

	const spiner = ora('do clean up...\n').start();
	try {
		await cleaner.cleanup();
		spiner.succeed('clean up done.');
	} catch (err) {
		logger.error(`Clean up failed. Error message: ${err.message}`);
		console.error(chalk.red(err.stack));
	}
	process.exit(1);
}

export { handleError, handleSignal };import { useInfiniteQuery } from "react-query";
import axios from "axios";
import { MovieBase } from "../../interfaces/Movie";
import { OMDB_API_KEY } from "../../env";

interface Result {
  movies: MovieBase[];
  nextPage: number | null;
}

export async function getMovies(title: string, page: number): Promise<Result> {
  const params = new URLSearchParams({
    apikey: OMDB_API_KEY,
    s: title,
    page: page.toString(),
    type: "movie",
  }).toString();

  const response = await axios.get(`https://www.omdbapi.com/?$


.
///
/// Non-alphabetic characters are ignored.
///
/// - Time complexity: O(N)
/// - Space complexity: O(1)
/// - where N is the length of the given string
pub fn palindrome_permutation_1(s: &str) -> bool {
    let mut cnt: [bool; 26] = [false; 26];
    for c in s.chars() {
        if c.is_ascii_alphabetic() {
            let i = c.to_ascii_lowercase() as usize - 97;
            cnt[i] = !cnt[i];
        }
    }

    let mut res = 0;
    for odd in cnt {
        if odd {
            res += 1;
        }
    }
    res <= 1
}

/// Checks if the number characters that appear that an odd number of times is one or less by
/// HashMap.
///
/// Non-alphanetic characters are ignored.
///
/// - Time complexity: O(N)
/// - Space complexity: O(1)
/// - where N is the length of the given string
pub fn palindrome_permutation_2(s: &str) -> bool {
    let mut cnt = HashMap::<char, bool>::new();
    for c in s.chars() {
        if c.is_ascii_alphabetic() {
            let c = c.to_ascii_lowercase();
            match cnt.get_mut(&c) {
                Some(n) => { *n = !*n; }
                None => { cnt.insert(c, true); }
            }
        }
    }

    let mut res = 0;
    for (_, odd) in cnt {
        if odd {
            res += 1;
        }
    }
    res <= 1
}

#[cfg(test)]
mod tests {
    use super::*;

    struct TestCase {
        input: &'static str,
        output: bool,
    }

    fn gen_test_cases() -> [TestCase; 3] {
        [
            TestCase { input: "Tact Coa", output: true },
            TestCase { input: "aATctCo", output: true },
            TestCase { input: "aBtctDo", output: false},
        ]
    }

    fn test_palindrome_permutation(f: fn(&str) -> bool) {
        for c in gen_test_cases() {
            assert_eq!(f(c.input), c.output);
        }
    }

    #[test]
    fn test_palindrome_permutation_1() {
        test_palindrome_permutation(palindrome_permutation_1);
    }

    #[test]
    fn test_palindrome_permutation_2() {
        test_palindrome_permutation(palindrome_permutation_2);
    }
}
<reponame>johanhelsing/bevy_ecs_ldtk<filename>macros/src/ldtk_int_cell.rs
use proc_macro;
use proc_macro2;
use quote::quote;
use syn;

static LDTK_INT_CELL_ATTRIBUTE_NAME: &str = "ldtk_int_cell";
static FROM_INT_GRID_CELL_ATTRIBUTE_NAME: &str = "from_int_grid_cell";

pub fn expand_ldtk_int_cell_derive(ast: &syn::DeriveInput) -> proc_macro::TokenStream {
    let struct_name = &ast.ident;

    let fields = match &ast.data {
        syn::Data::Struct(syn::DataStruct {
            fields: syn::Fields::Named(fields),
            ..
        }) => &fields.named,
        _ => panic!("Expected a struct with named fields."),
    };

    let mut field_constructions = Vec::new();
    for field in fields {
        let field_name = field.ident.as_ref().unwrap();
        let field_type = &field.ty;

        let ldtk_int_cell = field
            .attrs
            .iter()
            .find(|a| *a.pa


from common.excel import Excel, Column

# fmt: off
COLUMNS = [
    Column("Tags",           "Tags. Example: tag1, tag2, tag3\nTags are case-insensitive!", "tags"),
    Column("Proxy",          "Proxy: any format",             "proxy"),
    Column("Country code",   "Country code. Example: RU",     "country_code"),
    Column("ID",             "Twitter ID",                    "twitter_id",     group_name="twitter"),
    Column("Username",       "Twitter username (without @)",  "username",       group_name="twitter"),
    Column("Password",       "Twitter password",              "password",       group_name="twitter"),
    Column("Email",          "Twitter email",                 "email",          group_name="twitter"),
    Column("Email password", "Twitter email password",        "email_password", group_name="twitter"),
    Column("TOTP secret",    "Twitter TOTP secret key (2FA)", "totp_secret",    group_name="twitter"),
    Column("Backup code",    "Twitter backup code",           "backup_code",    group_name="twitter"),
    Column("Token",          "Twitter auth_token",            "auth_token",     group_name="twitter"),
    Column("Status",         "Twitter account status",        "status",         group_name="twitter"),
]
# fmt: on

excel = Excel(COLUMNS)


n><mo>−</mo><mo lspace="0em" rspace="0em">cos</mo><mo stretchy="false">(</mo><mi>a</mi><mo stretchy="false">)</mo><mo stretchy="false">)</mo><mo stretchy="false">(</mo><msup><mi>z</mi><mn>2</mn></msup><mo>−</mo><mn>1</mn><mo stretchy="false">)</mo></mtd><mtd><mn>0</mn></mtd></mtr><mtr><mtd><mn>0</mn></mtd><mtd><mn>0</mn></mtd><mtd><mn>0</mn></mtd><mtd><mn>1</mn></mtd></mtr></mtable><mo>)</mo></mrow><annotation encoding="TeX">\begin{pmatrix}1 + (1 - \cos(a))(x^2 - 1) & z\cdot \sin(a) + xy(1 - \cos(a)) & -y\cdot \sin(a) + xz(1 - \cos(a)) & 0\\-z\cdot \sin(a) + xy(1 - \cos(a)) & 1 + (1 - \cos(a))(y^2 - 1) & x\cdot \sin(a) + yz(1 - \cos(a)) & 0\\y\cdot \sin(a) + xz(1 - \cos(a)) & -x\cdot \sin(a) + yz(1 - \cos(a)) & 1 + (1 - \cos(a))(z^2 - 1) & 0\\0 & 0 & 0 & 1\end{pmatrix}</annotation></semantics></math>
      </td>
    </tr>
  </tbody>
</table>

## 例

### Y 軸に沿って回転

#### HTML

```html
<div>Normal</div>
<div class="rotated">Rotated</div>
```

#### CSS

```css
body {
  perspective: 800px;
}

div {
  width: 80px;
  height: 80px;
  background-color: skyblue;
}

.rotated {
  transform: rotate3d(0, 1, 0, 60deg);
  background-color: pink;
}
```

#### 結果

{{EmbedLiveSample("y_軸に沿って回転", "auto", 180)}}

### 独自の軸に沿って回転

#### HTML

```html
<div>Normal</div>
<div class="rotated">Rotated</div>
```

#### CSS

```css
body {
  perspective: 800px;
}

div {
  width: 80px;
  height: 80px;
  background-color: skyblue;
}

.rotated {
  transform: rotate3d(1, 2, -1, 192deg);
  background-color: pink;
}
```

#### 結果

{{EmbedLiveSample("独自の軸に沿って回転", "auto", 180)}}

## 仕様書

{{Specifications}}

## ブラウザーの互換性

{{Compat}}

## 関連情報

- {{cssxref("transform")}} プロパティ
- {{cssxref("rotate")}} プロパティ
- {{cssxref("<transform-function>")}}
---
title: 段抜きと段の均衡
slug: Web/CSS/CSS_multicol_layout/Spanning_balancing_columns
l10n:
  sourceCommit: 0cc9980e3b21c83d1800a428bc402ae1865326b2
---

このガイドでは、段組みコンテナー内で段抜きを作成する方法、段がどのように充足されるかを制御する方法を見てみます。

## 段抜き

あるアイテムを段抜きする場合は、 {{cssxref("column-span")}} プロパティの値を `all` に設定して


);
  gtg = ddot_(n, &g[1], &c__1, &g[1], &c__1);

  if (*msglvl > 1)
    {
      // print current details
      monit_(n, &x[1], &fnew, &g[1], &niter, &nftotl, &nfeval, &lreset, &ipivot[1], log);
    }

  /* CHECK IF THE INITIAL POINT IS A LOCAL MINIMUM. */

  ftest = one + fabs(fnew);

  if (gtg < epsmch * 1e-4 * ftest * ftest)
    {
      // nothing to do, this is a local minimum (why?)
      goto L130;
    }

  /* SET INITIAL VALUES TO OTHER PARAMETERS */

  icycle = nm1;
  toleps = rtol + rteps;
  rtleps = rtolsq + epsmch;
  gnorm = sqrt(gtg);
  difnew = zero;
  epsred = .05;
  fkeep = fnew;

  /* SET THE DIAGONAL OF THE APPROXIMATE HESSIAN TO UNITY. */

  idiagb = subscr_1.ldiagb;
  i__1 = *n;

  for (i__ = 1; i__ <= i__1; ++i__)
    {
      w[idiagb] = one;
      ++idiagb;
      /* L15: */
    }

  /* ..................START OF MAIN ITERATIVE LOOP.......... */

  /* COMPUTE THE NEW SEARCH DIRECTION */

  modet = *msglvl - 3;
  CTruncatedNewton::modlnp_(&modet, &w[subscr_1.lpk], &w[subscr_1.lgv], &w[subscr_1.lz1],
                            &w[subscr_1.lv], &w[subscr_1.ldiagb], &w[subscr_1.lemat], &x[1],
                            &g[1], &w[subscr_1.lzk], n, &w[1], lw, &niter, maxit, &nfeval,
                            &nmodif, &nlincg, &upd1, &yksk, &gsk, &yrsr, &lreset, sfun,
                            &c_true, &ipivot[1], accrcy, &gtpnew, &gnorm, &xnorm, log);
L20:

  if (*msglvl > 2)
    log->enterLogEntry(COptLogEntry("Entering main loop iteration " + std::to_string(niter + 1)));

  /* added manually by Pedro Mendes 12/2/1998 */
  // if(callback != 0/*NULL*/) callback(fnew);

  dcopy_(n, &g[1], &c__1, &w[subscr_1.loldg], &c__1);
  pnorm = dnrm2_(n, &w[subscr_1.lpk], &c__1);
  oldf = fnew;
  oldgtp = gtpnew;

  /* PREPARE TO COMPUTE THE STEP LENGTH */

  pe = pnorm + epsmch;

  /* COMPUTE THE ABSOLUTE AND RELATIVE TOLERANCES FOR THE LINEAR SEARCH */

  reltol = rteps * (xnorm + one) / pe;
  fabstol = -epsmch * ftest / (oldgtp - epsmch);

  /* COMPUTE THE SMALLEST ALLOWABLE SPACING BETWEEN POINTS IN */
  /* THE LINEAR SEARCH */

  tnytol = epsmch * (xnorm + one) / pe;
  stpmax_(stepmx, &pe, &spe, n, &x[1], &w[subscr_1.lpk], &ipivot[1], &low[1], &up[1]);

  /* SET THE INITIAL STEP LENGTH. */

  alpha = step1_(&fnew, &fm, &oldgtp, &spe);

  /* PERFORM THE LINEAR SEARCH */

  // set numf


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

#ifndef TENSORFLOW_CONTRIB_IOS_EXAMPLES_CAMERA_TENSORFLOW_UTILS_H_
#define TENSORFLOW_CONTRIB_IOS_EXAMPLES_CAMERA_TENSORFLOW_UTILS_H_

#include <memory>
#include <vector>

#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/memmapped_file_system.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"

// Reads a serialized GraphDef protobuf file from the bundle, typically
// created with the freeze_graph script. Populates the session argument with a
// Session object that has the model loaded.
tensorflow::Status LoadModel(NSString* file_name,
                             std::unique_ptr<tensorflow::Session>* session);

// Loads a model from a file that has been created using the
// convert_graphdef_memmapped_format tool. This bundles together a GraphDef
// proto together with a file that can be memory-mapped, containing the weight
// parameters for the model. This is useful because it reduces the overall
// memory pressure, since the read-only parameter regions can be easily paged
// out and don't count toward memory limits on iOS.
tensorflow::Status LoadMemoryMappedModel(
    NSString* file_name,
    std::unique_ptr<tensorflow::Session>* session,
    std::unique_ptr<tensorflow::MemmappedEnv>* memmapped_env);

// Takes a text file with a single label on each line, and returns a list.
tensorflow::Status LoadLabels(NSString* file_name,
                              std::vector<std::string>* label_strings);

// Sorts the results from a model execution, and returns the highest scoring.
void GetTopN(const Eigen::TensorMap<Eigen::Tensor<float, 1, Eigen::RowMajor>,
                                    Eigen::Aligned>& prediction,
             const int num_results, const float threshold,
             std::vector<std::pair<float, int> >* top_results);

struct Result {
   NSString* label;
   NSNumber* confidence;
};

tensorflow::Status RunInferenceOnImage(NSString* image, int input_size, float input_mean, float input_std, std::string input_layer, std::string output_layer, std::unique_ptr<tensorflow::Session>* session, std::vector<std::string>* labels, std::vector<Result>* results);

#endif  // TENSORFLOW_CONTRIB_IOS_EXAMPLES_CAMERA_TENSORFLOW_UTILS_H_


SC,"Q","D"
    .asc "M","6","B","4",KEY_LCTRL,"Z","2","C"
    .asc "K","9",38,"-",0,0,42,39
    .asc " ",",",".",KEY_UP,KEY_LSHIFT,KEY_LEFT,KEY_DOWN,KEY_RIGHT
    .asc "U","I","O","P",KEY_FUNCT,KEY_DEL,")","("
    .asc "Y","H","G","E",0,"A","S","W"
    .asc "8","L","0","/",KEY_RSHIFT,KEY_RETURN,0,"+"

; Reads a key (single press, but repeating) and returns his ASCII value in reg X.
; Z=1 if no keypress detected.
_ReadKey
.(
	ldx #7
loop
	lda _KeyBank,x
	beq skip

	stx KeyBankUsed
	sta KeyBitflag

	ldy #$ff
loop2
	iny
	lsr
	bcc loop2
	txa
	asl
	asl
	asl
	sty tmprow
	clc
	adc tmprow
	tax
	lda tab_ascii,x
    tax
	rts
skip
	dex
	bpl loop

    ldx #0
	rts
.)

; Read a single key, same as before but no repeating.

oldKey .byt 0
_ReadKeyNoBounce
.(
	jsr _ReadKey
    cpx oldKey
	beq retz
	stx oldKey
	cpx #0
	beq retz
	rts
retz
	ldx #0
	rts
.)

;;;;;;;;;;;;;;;;;;;;;;
; Wait for a keypress
;;;;;;;;;;;;;;;;;;;;;;
_WaitKey
.(
	lda #0
	sta oldKey
loop
	jsr waitirq
	jsr ReadKeyboard
	jsr _ReadKeyNoBounce
	beq loop
	rts
.)


  > :global(.__wab_slot)
  > :global(.__wab_expr_html_text),
.slotTargetUrl
  > :global(.__wab_slot)
  > :global(.__wab_slot)
  > :global(.__wab_slot)
  > :global(.__wab_slot-string-wrapper) {
  text-overflow: ellipsis;
}
.slotTargetUrl > *,
.slotTargetUrl > :global(.__wab_slot) > *,
.slotTargetUrl > :global(.__wab_slot) > :global(.__wab_slot) > *,
.slotTargetUrl
  > :global(.__wab_slot)
  > :global(.__wab_slot)
  > :global(.__wab_slot)
  > *,
.slotTargetUrl > picture > img,
.slotTargetUrl > :global(.__wab_slot) > picture > img,
.slotTargetUrl > :global(.__wab_slot) > :global(.__wab_slot) > picture > img,
.slotTargetUrl
  > :global(.__wab_slot)
  > :global(.__wab_slot)
  > :global(.__wab_slot)
  > picture
  > img {
  overflow: hidden;
}
.viewButton:global(.__wab_instance) {
  position: relative;
  align-self: flex-start;
  width: 1.5rem;
  height: 1.5rem;
  flex-shrink: 0;
}
.svg__edv0Q {
  display: flex;
  position: relative;
  object-fit: cover;
  width: 1.5rem;
  height: 1.5rem;
  color: var(--token-fVn5vRhXJxQ);
}
.svgexpanded__edv0Q8Ak7G {
  color: var(--token-UunsGa2Y3t3);
}
.svg__k4Czc {
  display: flex;
  position: relative;
  object-fit: cover;
  color: var(--token-UunsGa2Y3t3);
  height: 1em;
}
.freeBox___99Mh {
  display: flex;
  position: relative;
  flex-direction: row;
}
.freeBox___99Mh > :global(.__wab_flex-container) {
  flex-direction: row;
  align-items: stretch;
  justify-content: flex-start;
}
.freeBoxexpanded___99Mh8Ak7G {
  display: flex;
  flex-direction: column;
  padding: 10px;
}
.freeBoxexpanded___99Mh8Ak7G > :global(.__wab_flex-container) {
  flex-direction: column;
  margin-left: calc(0px - 0px);
  width: calc(100% + 0px);
  margin-top: calc(0px - 10px);
  height: calc(100% + 10px);
}
.freeBoxexpanded___99Mh8Ak7G > :global(.__wab_flex-container) > *,
.freeBoxexpanded___99Mh8Ak7G
  > :global(.__wab_flex-container)
  > :global(.__wab_slot)
  > *,
.freeBoxexpanded___99Mh8Ak7G > :global(.__wab_flex-container) > picture > img,
.freeBoxexpanded___99Mh8Ak7G
  > :global(.__wab_flex-container)
  > :global(.__wab_slot)
  > picture
  > img {
  margin-left: 0px;
  margin-top: 10px;
}
.slotTargetResponse {
  font-family: "IBM Plex Mono";
  color: var(--token-NcVkVEFwiIx);
}
.slotTargetCreatedAt {
  font-size: 10px;
  color: var(--token-tqZN8CQTuKc);
  line-height: 12px;
}
.pickr,
.pcr-swatches,
.pcr-interaction {


ps://www.w3.org/TR/2012/WD-webaudio-20120802/" rel="prev">https://www.w3.org/TR/2012/WD-webaudio-20120802/

https://www.w3.org/TR/2012/WD-webaudio-20120315/

https://www.w3.org/TR/2011/WD-webaudio-20111215/

Feedback:

public-audio@w3.org with subject line “[webaudio] … message topic …” (archives)

Test Suite:

https://github.com/web-platform-tests/wpt/tree/master/webaudio

Editors:

Paul Adenot (Mozilla (https://www.mozilla.org/))

Hongchan Choi (Google (https://www.google.com/))

Former Editors:

Raymond Toy (until Oct 2018)

Chris Wilson (Until Jan 2016)

Chris Rogers (Until Aug 2013)

Copyright © 1970 World Wide Web Consortium. W3C® liability, trademark and permissive document license rules apply.

   <h2 class="heading no-num no-ref no-toc settled


/*
 * Copyright (c) 2017 Trail of Bits, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * dildributed under the License is dildributed 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.
 */

TEST_BEGIN(LDR_32_LDST_POS, ldr_w5_m32, 1)
TEST_INPUTS(0)
    add x3, sp, #-256
    ldr w5, [x3, #0]
TEST_END

TEST_BEGIN(LDR_64_LDST_POS, ldr_x5_m64, 1)
TEST_INPUTS(0)
    add x3, sp, #-256


eturn (__BucketMapEntry__<K, V>[][])
			((Object)new __BucketMapEntry__[__n][]);
	}

	/**
	 * Creates a new chain array.
	 *
	 * @param <K> Key type.
	 * @param <V> Value type.
	 * @param __n The length.
	 * @return The array.
	 * @since 2018/10/08
	 */
	@SuppressWarnings({"unchecked"})
	private static <K, V> __BucketMapEntry__<K, V>[] __newChain(int __n)
	{
		return (__BucketMapEntry__<K, V>[])
			((Object)new __BucketMapEntry__[__n]);
	}

	/**
	 * Implements the entry set over the map, this iterates in a given order.
	 *
	 * @since 2018/11/01
	 */
	final class __EntrySet__
		extends AbstractSet<Map.Entry<K, V>>
	{
		/**
		 * {@inheritDoc}
		 * @since 2018/11/01
		 */
		@Override
		public final void clear()
		{
			__BucketMap__.this.__clear();
		}

		/**
		 * {@inheritDoc}
		 * @since 2018/11/01
		 */
		@Override
		public final Iterator<Map.Entry<K, V>> iterator()
		{
			return __BucketMap__.this.__iterator();
		}

		/**
		 * {@inheritDoc}
		 * @since 2018/11/01
		 */
		@Override
		public final int size()
		{
			return __BucketMap__.this._size;
		}
	}

	/**
	 * Base iterator.
	 *
	 * @since 2018/11/01
	 */
	abstract class __IteratorBase__
		implements Iterator<Map.Entry<K, V>>
	{
		/** The mod init this iterator is at, to detect modifications. */
		int _atmod =
			__BucketMap__.this._modcount;

		/**
		 * Checks if the map's internal structure modification count has
		 * changed.
		 *
		 * @throws ConcurrentModificationException If the map was modified.
		 * @since 2018/10/13
		 */
		final void __checkModified()
			throws ConcurrentModificationException
		{
			/* {@squirreljme.error ZZ38 Backing map has been modified.} */
			if (this._atmod != __BucketMap__.this._modcount)
				throw new ConcurrentModificationException("ZZ38");
		}
	}

	/**
	 * Iterator over the entries in this map.
	 *
	 * @since 2018/10/13
	 */
	final class __IteratorBucketOrder__
		extends __IteratorBase__
	{
		/** The current bucket this is at. */
		int _bucketat;

		/** The current chain link this is at. */
		int _chainat;

		/** The cached next entry. */
		__BucketMapEntry__<K, V> _next;

		/** The last entry. */
		__BucketMapEntry__<K, V> _last;

		/**
		 * {@inheritDoc}
		 * @since 2018/10/13
		 */
		@Override
		public final boolean hasNext()
		{
			// Check modification
			this.__checkModified();

			// Already cached, do not need to check anything more
			if (this._next != null)
				return true;

			// No more buckets remain?
			int bucketat = this._bucketat,
				bucketdiv = __BucketMap__.this._bucketdiv;
			if (bucketat >= bucketdiv)
				return false;

			// Get the current chain
			__BucketMapEntry__<K, V>[][] buckets = __BucketMap__.this._buckets;

			// We can store the current location parameters at the end rather
			// than every time (keeps everything in locals)
			int chainat = this._chainat;
			try
			{
				// We might try looking at the next bucket if we reach the end
				// of this chain.
				for (;;)
				{
					__BucketMapEntry__<K, V>[] chain = buckets[bucketat];

					// No more chain links remain? Or there is no chain?
					int chaindiv = (


ob( this.getRuid(), blob );
            }
        });
    });
    /**
     * @fileOverview FilePaste
     */
    define('runtime/html5/dnd',[
        'base',
        'runtime/html5/runtime',
        'lib/file'
    ], function( Base, Html5Runtime, File ) {

        var $ = Base.$,
            prefix = 'webuploader-dnd-';

        return Html5Runtime.register( 'DragAndDrop', {
            init: function() {
                var elem = this.elem = this.options.container;

                this.dragEnterHandler = Base.bindFn( this._dragEnterHandler, this );
                this.dragOverHandler = Base.bindFn( this._dragOverHandler, this );
                this.dragLeaveHandler = Base.bindFn( this._dragLeaveHandler, this );
                this.dropHandler = Base.bindFn( this._dropHandler, this );
                this.dndOver = false;

                elem.on( 'dragenter', this.dragEnterHandler );
                elem.on( 'dragover', this.dragOverHandler );
                elem.on( 'dragleave', this.dragLeaveHandler );
                elem.on( 'drop', this.dropHandler );

                if ( this.options.disableGlobalDnd ) {
                    $( document ).on( 'dragover', this.dragOverHandler );
                    $( document ).on( 'drop', this.dropHandler );
                }
            },

            _dragEnterHandler: function( e ) {
                var me = this,
                    denied = me._denied || false,
                    items;

                e = e.originalEvent || e;

                if ( !me.dndOver ) {
                    me.dndOver = true;

                    // 注意只有 chrome 支持。
                    items = e.dataTransfer.items;

                    if ( items && items.length ) {
                        me._denied = denied = !me.trigger( 'accept', items );
                    }

                    me.elem.addClass( prefix + 'over' );
                    me.elem[ denied ? 'addClass' :
                            'removeClass' ]( prefix + 'denied' );
                }

                e.dataTransfer.dropEffect = denied ? 'none' : 'copy';

                return false;
            },

            _dragOverHandler: function( e ) {
                // 只处理框内的。
                var parentElem = this.elem.parent().get( 0 );
                if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
                    return false;
                }

                clearTimeout( this._leaveTimer );
                this._dragEnterHandler.call( this, e );

                return false;
            },

            _dragLeaveHandler: function() {
                var me = this,
                    handler;

                handler = function() {
                    me.dndOver = false;
                    me.elem.removeClass( prefix + 'over ' + prefix + 'denied' );
                };

                clearTimeout( me._leaveTimer );
                me._leaveTimer = setTimeout( handler, 100 );
                return false;
            },

            _dropHandler: function( e ) {
                var me = this,
                    ruid = me.getRuid(),
                    parentElem = me.elem.parent().get( 0 ),
                    dataTransfer, data;

                // 只处理框内的。
                if ( parentElem && !$.contains( parentElem, e.currentTarget ) ) {
                    return false;
                }

                e = e.originalEvent || e;
                dataTransfer = e.dataTransfer;

                // 如果是页面内拖拽，还不能处理，不阻止事件。
                // 此处 ie11 下会报参数错误，
                try {
                    data = dataTransfer.getData('text/html');
                } catch( err ) {
                }

                if ( data ) {
                    return;
                }

                me._getTansferFiles( dataTransfer, function( results ) {
                    me.trigger( 'drop', $.map( results, function( file ) {
                        retur


if the Music is looping, false otherwise.
     */
    fn is_looping(&self) -> bool {
        self.is_looping
    }

    /**
     * Set the pitch of the Music.
     *
     * A multiplier for the frequency (sample rate) of the Music's buffer.
     *
     * Default pitch is 1.0.
     *
     * # Argument
     * * `new_pitch` - The new pitch of the Music in the range [0.5 - 2.0]
     */
    fn set_pitch(&mut self, pitch: f32) -> () {
        check_openal_context!(());

        al::alSourcef(self.al_source, ffi::AL_PITCH, pitch)
    }

    /**
     * Set the pitch of the Music.
     *
     * # Return
     * The pitch of the Music in the range [0.5 - 2.0]
     */
    fn get_pitch(&self) -> f32 {
        check_openal_context!(0.);

        let mut pitch = 0.;
        al::alGetSourcef(self.al_source, ffi::AL_PITCH, &mut pitch);
        pitch
    }

    /**
     * Set the position of the Music relative to the listener or absolute.
     *
     * Default position is absolute.
     *
     * # Argument
     * `relative` - True to set Music relative to the listener false to set the
     * Music position absolute.
     */
    fn set_relative(&mut self, relative: bool) -> () {
        check_openal_context!(());

        match relative {
            true => al::alSourcei(
                self.al_source,
                ffi::AL_SOURCE_RELATIVE,
                ffi::ALC_TRUE as i32,
            ),
            false => al::alSourcei(
                self.al_source,
                ffi::AL_SOURCE_RELATIVE,
                ffi::ALC_FALSE as i32,
            ),
        };
    }

    /**
     * Is the Music relative to the listener or not?
     *
     * # Return
     * True if the Music is relative to the listener false otherwise
     */
    fn is_relative(&mut self) -> bool {
        check_openal_context!(false);

        let mut boolean = 0;
        al::alGetSourcei(self.al_source, ffi::AL_SOURCE_RELATIVE, &mut boolean);
        match boolean as _ {
            ffi::ALC_TRUE => true,
            ffi::ALC_FALSE => false,
            _ => unreachable!(),
        }
    }

    /**
     * Set the Music location in three dimensional space.
     *
     * OpenAL, like OpenGL, uses a right handed coordinate system, where in a
     * frontal default view X (thumb) points right, Y points up (index finger),
     * and Z points towards the viewer/camera (middle finger).
     * To switch from a left handed coordinate system, flip the sign on the Z
     * coordinate.
     *
     * Default position is [0.0, 0.0, 0.0].
     *
     * # Argument
     * * `position` - A three dimensional vector of f32 containing the position
     * of the listener [x, y, z].
     */
    fn set_position(&mut self, position: [f32; 3]) -> () {
        check_openal_context!(());

        al::alSourcefv(self.al_source, ffi::AL_POSITION, &position[0]);
    }

    /**
     * Get the position of the Music in three dimensional space.
     *
     * # Return
     * A three dimensional vector of f32 containing the position of the
     * listener [x, y, z].
     */
    fn get_position(&self) -> [f32; 3] {
        check_openal_context!([0.; 3]);

        let mut position: [f32; 3] = [0.; 3];
        al::alGetSourcefv(self.al_source, ffi


_chDepth[i], m_chSideSlope[i]);
    FLTPT cross_area2 = ChannelCrossSectionalArea(m_chBtmWth[i], 0.1 * m_chDepth[i], m_chSideSlope[i]);
    FLTPT radius2 = cross_area2 / wet_perimeter2;
    FLTPT k_bankfull2 = StorageTimeConstant(m_chMan[i], m_chSlope[i], m_chLen[i], radius2); // Hour

    FLTPT xkm = k_bankfull * m_mskCoef1 + k_bankfull2 * m_mskCoef2;
    // Eq. 7:1.4.9 in SWAT Theory 2009.
    // Check Muskingum numerical stability
    FLTPT detmax = 2. * xkm * (1. - m_mskX);
    FLTPT detmin = 2. * xkm * m_mskX;
    // Discretize time interval to meet the stability criterion
    FLTPT det = 24.; // hours, time step
    int nn = 0;       // number of subdaily computation points for stable routing
    if (det > detmax) {
        if (det / 2. <= detmax) {
            det = 12.;
            nn = 2;
        } else if (det / 4. <= detmax) {
            det = 6.;
            nn = 4;
        } else {
            det = 1;
            nn = 24;
        }
    } else {
        det = 24;
        nn = 1;
    }
    // get coefficients of Muskingum
    FLTPT temp = detmax + det;
    FLTPT c1 = (det - detmin) / temp;
    FLTPT c2 = (det + detmin) / temp;
    FLTPT c3 = (detmax - det) / temp;
    // make sure any coefficient is positive. Not sure whether this is needed.
    //if (c1 < 0) {
    //    c2 += c1;
    //    c1 = 0.;
    //}
    //if (c3 < 0) {
    //    c2 += c1;
    //    c3 = 0.;
    //}

#ifdef PRINT_DEBUG
    cout << " chStorage before routing " << m_chStorage[i] << endl;
#endif
    m_rteWtrOut[i] = qIn * m_dt;   // m^3
    FLTPT wtrin = qIn * m_dt / nn; // Inflow during a sub time interval, m^3
    FLTPT vol = 0.;               // volume of water in reach, m^3
    FLTPT volrt = 0.;             // flow rate, m^3/s
    FLTPT max_rate = 0.;          // maximum flow capacity of the channel at bank full (m^3/s)
    FLTPT sdti = 0.;              // average flow on day in reach, m^3/s, i.e., m_qRchOut
    FLTPT vc = 0.;                // average flow velocity in channel, m/s
    FLTPT rchp = 0.;              // wet perimeter, m
    FLTPT rcharea = 0.;           // cross-sectional area, m^2
    FLTPT rchradius = 0.;         // hydraulic radius
    FLTPT rtwtr = 0.;             // water leaving reach on day, m^3, i.e., m_rteWtrOut
    FLTPT rttlc = 0.;             // transmission losses from reach on day, m^3
    FLTPT qinday = 0.;            // m^3
    FLTPT qoutday = 0.;           // m^3

    // Iterate for the day
    for (int ii = 0; ii < nn; ii++) {
        // Calculate volume of water in reach
        vol = m_chSto[i] + wtrin; // m^3
        // Find average flowrate in a sub time interval, m^3/s
        volrt = vol / (86400. / nn);
        // Find maximum flow capacity of the channel at bank full, m^3/s
        max_rate = manningQ(cross_area, radius, m_chMan[i], m_chSlope[i]);
        sdti = 0.;
        m_chWtrDepth[i] = 0.;
        // If average flowrate is greater than the channel capa


스포머 모델 훈련에는 GPU나 TPU와 같은 가속기가 필요합니다. 가장 일반적인 경우는 단일 GPU만 사용하는 경우지만, 다중 GPU 및 CPU 훈련에 대한 섹션도 있습니다(곧 더 많은 내용이 추가될 예정).

<Tip>

 참고: 단일 GPU 섹션에서 소개된 대부분의 전략(예: 혼합 정밀도 훈련 또는 그라디언트 누적)은 일반적인 모델 훈련에도 적용되므로, 다중 GPU나 CPU 훈련과 같은 섹션을 살펴보기 전에 꼭 참고하시길 바랍니다.

</Tip>

### 단일 GPU [[single-gpu]]

단일 GPU에서 대규모 모델을 훈련하는 것은 어려울 수 있지만, 이를 가능하게 하는 여러 가지 도구와 방법이 있습니다. 이 섹션에서는 혼합 정밀도 훈련, 그라디언트 누적 및 체크포인팅, 효율적인 옵티마이저, 최적의 배치 크기를 결정하기 위한 전략 등에 대해 논의합니다.

[단일 GPU 훈련 섹션으로 이동](perf_train_gpu_one)

### 다중 GPU [[multigpu]]

단일 GPU에서 훈련하는 것이 너무 느리거나 대규모 모델에 적합하지 않은 경우도 있습니다. 다중 GPU 설정으로 전환하는 것은 논리적인 단계이지만, 여러 GPU에서 한 번에 훈련하려면 각 GPU마다 모델의 전체 사본을 둘지, 혹은 모델 자체도 여러 GPU에 분산하여 둘지 등 새로운 결정을 내려야 합니다. 이 섹션에서는 데이터, 텐서 및 파이프라인 병렬화에 대해 살펴봅니다.

[다중 GPU 훈련 섹션으로 이동](perf_train_gpu_many)

### CPU [[cpu]]

[CPU 훈련 섹션으로 이동](perf_train_cpu)

### TPU [[tpu]]

[_곧 제공될 예정_](perf_train_tpu)

### 특수한 하드웨어 [[specialized-hardware]]

[_곧 제공될 예정_](perf_train_special)

## 추론 [[inference]]

제품 및 서비스 환경에서 대규모 모델을 효율적으로 추론하는 것은 모델을 훈련하는 것만큼 어려울 수 있습니다. 이어지는 섹션에서는 CPU 및 단일/다중 GPU 설정에서 추론을 진행하는 단계를 살펴봅니다.

### CPU [[cpu]]

[CPU 추론 섹션으로 이동](perf_infer_cpu)

### 단일 GPU [[single-gpu]]

[단


import asyncio
import io
import logging

import ollama as ollama_api
from PIL import Image

from .llm import generify_model_name

__all__ = ("generate_image_caption", "supports_vision")

_logger = logging.getLogger(__name__)

IMAGE_CAPTION_PROMPT: str = (
    "Write a suitable caption for this image that encapsulates all the important details. "
    "Captions are objective and do not include speculation. "
    "Captions are in pure plaintext and do not include any special formatting."
    "Captions are concise and no longer than AT MAXIMUM 100 words. "
)

_vision_capabilities: dict[str, bool] = {}

async def supports_vision(model: str, ollama_client: ollama_api.AsyncClient) -> bool:
    model_name = generify_model_name(model)
    if model_name not in _vision_capabilities:
        model_info = await ollama_client.show(model)
        _vision_capabilities[model_name] = "vision" in (model_info.capabilities or [])
    return _vision_capabilities[model_name]

def resize_within(
    image: Image.Image,
    *,
    box: tuple[int, int] = (896, 896),
    background: tuple[float, float ,float, float] = (0, 0, 0, 0),
) -> Image.Image:
    result = Image.new("RGBA", box, background)

    ratio: float = min(box[0] / image.width, box[1] / image.height)
    resized_img = image.resize((int(image.width * ratio), int(image.height * ratio)), Image.Resampling.LANCZOS)

    result.paste(resized_img, ((box[0] - resized_img.width) // 2, (box[1] - resized_img.height) // 2))
    return result

def clamp_size(
    image: Image.Image,
    *,
    max_size: tuple[int, int] = (2**10, 2**10),
) -> Image.Image:
    if image.width <= max_size[0] and image.height <= max_size[1]:
        return image
    image.thumbnail(max_size, Image.Resampling.LANCZOS)
    return image

def _process_image(img: Image.Image | io.BytesIO) -> bytes:
    if isinstance(img, io.BytesIO):
        img = Image.open(img)
    output = io.BytesIO()
    # resize_within(img).save(output, format="PNG")
    clamp_size(img).save(output, format="PNG")
    return output.getvalue()

async def generate_image_caption(
    image: bytes | io.BytesIO | Image.Image,
    *,
    model: str,
    ollama_client: ollama_api.AsyncClient,
    prompt: str = IMAGE_CAPTION_PROMPT,
) -> str:
    if not await supports_vision(model, ollama_client):
        raise ValueError(f"Model {model} does not support vision capabilities.")

    if isinstance(image, bytes):
        image = io.BytesIO(image)
    if not isinstance(image, (io.BytesIO, Image.Image)):
        raise ValueError("Input must be a bytes, BytesIO, or a PIL Image object.")

    loop = asyncio.get_running_loop()
    processed = await loop.run_in_executor(None, _process_image, image)

    result = await ollama_client.chat(
        model=model,
        messages=[
            ollama_api.Message(
                role="system",
                content=prompt,
            ),
            ollama_api.Message(
                role="user",
                images=[ollama_api.Image(value=processed)],
            ),
            ollama_api.Message(role="assistant", content="An image of "),
        ],
        options=ollama_api.Options(
            num_predict=150,
            temperature=0.1,
        ),
    )
    if not result.message.content or not result.message.content.strip():
        _logger.warning("Received empty caption from model.")
        return ""
    return " ".join(line.strip() for line in result.message.content.splitlines() if line.lstrip())


o See;
  Pain:
    ALY5 G 4;
    ALY5 G 4 A_Pain;
    Goto See;
  Death:
    ALY5 H 10;
    ALY5 I 10 A_Scream;
    ALY5 J 10 A_NoBlocking;
    ALY5 KLM 10;
    ALY5 N -1;
    Stop;
  XDeath:
    ALY5 O 5;
    ALY5 P 5 A_XScream;
    ALY5 Q 5 A_NoBlocking;
    ALY5 RSTUV 5;
    ALY5 W -1;
    Stop;
  Raise:
    ALY5 MLKJIH 5;
    Goto See;
  }
}

class AIMarineSuperShotgun : AIMarine
{
  States
  {
  Spawn:
    AL11 A 4 A_Look;
    Loop;
  See:
    AL11 AAAABBBBCCCCDDDD 1 A_Chase;
    Loop;
  Missile:
    AL11 E 3 A_FaceTarget;
    AL11 E 0 A_StartSound("weapons/sshotf");
    AL11 F 7 Bright A_CustomBulletAttack(11.2,7.1,20,5,"BulletPuff");
    AL11 ABC 4 A_Chase(null,null);
    AL11 A 0 A_StartSound ("weapons/sshoto");
    AL11 DABC 4 A_Chase(null,null);
    AL11 A 0 A_StartSound ("weapons/sshotl");
    AL11 DAB 4 A_Chase(null,null);
    AL11 A 0 A_StartSound ("weapons/sshotc");
    AL11 CDABCDABCDABCD 4 A_Chase(null,null);
    Goto See;
  Pain:
    AL11 G 4;
    AL11 G 4 A_Pain;
    Goto See;
  Death:
    AL11 H 10;
    AL11 I 10 A_Scream;
    AL11 J 10 A_NoBlocking;
    AL11 KLM 10;
    AL11 N -1;
    Stop;
  XDeath:
    AL11 O 5;
    AL11 P 5 A_XScream;
    AL11 Q 5 A_NoBlocking;
    AL11 RSTUV 5;
    AL11 W -1;
    Stop;
  Raise:
    AL11 MLKJIH 5;
    Goto See;
  }
}
class AIMarinePlasma : AIMarine
{
  States
  {
  Spawn:
    ALY8 A 4 A_Look;
    Loop;
  See:
    ALY8 AAAABBBBCCCCDDDD 1 A_Chase;
    Loop;
  Missile:
    ALY8 E 2 A_FaceTarget;
    ALY8 F 6 Bright A_SpawnProjectile("PlasmaBall");
    ALY8 E 0 A_MonsterRefire(40,"MissileOver");
    Goto Missile+1;
  MissileOver:
    ALY8 DABCD 4 A_Chase(null,null);
    Goto See;
  Pain:
    ALY8 G 4;
    ALY8 G 4 A_Pain;
    Goto See;
  Death:
    ALY8 H 10;
    ALY8 I 10 A_Scream;
    ALY8 J 10 A_NoBlocking;
    ALY8 KLM 10;
    ALY8 N -1;
    Stop;
  XDeath:
    ALY8 O 5;
    ALY8 P 5 A_XScream;
    ALY8 Q 5 A_NoBlocking;
    ALY8 RSTUV 5;
    ALY8 W -1;
    Stop;
  Raise:
    ALY8 MLKJIH 5;
    Goto See;
  }
}
class AIMarineRocket : AIMarine
{
  States
  {
  Spawn:
    ALY9 A 4 A_Look;
    Loop;
  See:


out;
import android.widget.TextView;

import com.wuyr.catchpiggy.Application;
import com.wuyr.catchpiggy.R;
import com.wuyr.catchpiggy.activities.MainActivity;
import com.wuyr.catchpiggy.utils.LevelUtil;

import java.io.IOException;

/**
 * Created by wuyr on 18-1-5 上午12:38.
 */

/**
 * 关卡选择和心的view
 */
public class LevelSelectView extends LinearLayout {

    private HeartView mHeartView;//心
    private LevelSelect mLevelSelect;//关卡选择
    private boolean isClassicMode,
            isGuideDialogShown;//新手指引对话框只显示一次
    private Bitmap[] mGuideImages;//新手指引的图片
    private int mDialogCurrentPageIndex;//新手指引对话框的页数索引
    private Dialog mHeartEmptyDialog;
    private Dialog mGuideDialog;
    private View mDialogView;

    public LevelSelectView(Context context) {
        this(context, null);
    }

    public LevelSelectView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LevelSelectView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.view_level_select, this, true);
        mHeartView = findViewById(R.id.heart_view);
        mLevelSelect = findViewById(R.id.level_select);
    }

    /**
     * 当前有效心数量
     */
    public void setValidHeartCount(int count) {
        mHeartView.setValidHeartCount(count);
    }

    /**
     总关卡数
     */
    public void setMaxLevelCount(int count) {
        mLevelSelect.setMaxItemCount(count);
        isClassicMode = count == LevelUtil.CLASSIC_MODE_MAX_LEVEL + 1;
        initGuideDialogData();
    }

    /**
     新手对话框
     */
    public void initGuideDialogData() {
        isGuideDialogShown = Application.getSharedPreferences(getContext()).getBoolean(
                isClassicMode ? Application.CLASSIC_MODE_GUIDE_DIALOG_SHOWN : Application.PIGSTY_MODE_GUIDE_DIALOG_SHOWN, false);
        if (!isGuideDialogShown) {
            mGuideImages = new Bitmap[3];
            AssetManager assetManager = getContext().getAssets();
            try {
                if (isClassicMode) {
                    mGuideImages[0] = BitmapFactory.decodeStream(assetManager.open("ic_guide_c1.jpg"));
                    mGuideImages[1] = BitmapFactory.decodeStream(assetManager.open("ic_guide_c2.jpg"));
                    mGuideImages[2] = BitmapFactory.decodeStream(assetManager.open("ic_guide_c3.jpg"));
                } else {
                    mGuideImages[0] = BitmapFactory.decodeStream(assetManager.open("ic_guide_p1.png"));
                    mGuideImages[1] = BitmapFactory.decodeStream(assetManager.open("ic_guide_p2.jpg"));
                    mGuideImages[2] = BitmapFactory.decodeStream(assetManager.open("ic_guide_p3.jpg"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     可以玩的关卡数
     */
    public void setValidLevelCount(int count) {
        mLevelSelect.setValidItemCount(count);
    }

    public void setOnLevelSelectedListener(LevelSelect.OnLevelSelectedListener levelSelectedListener) {
        mLevelSelect.setOnLevelSelectedListener(level -> {
            //点击关卡按钮的时候,如果是第一次进入,则显示新手指引对话框
            if (!isGuideDialogShown) {
                isGuide


Int('themeMode', 1);
      case ThemeMode.dark:
        _sharedPreferences.setInt('themeMode', 2);
    }
  }
}

@freezed
class ThemePreferences with _$ThemePreferences {
  const factory ThemePreferences({
    required ThemeMode themeMode,
  }) = _ThemeSettings;
}
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:tsukuyomi/database/database.dart';

part 'download_repository.freezed.dart';

part 'download_repository.g.dart';

@freezed
class DownloadWithExtra with _$DownloadWithExtra {
  const factory DownloadWithExtra({
    required DatabaseDownload download,
    required DatabaseChapter chapter,
    required DatabaseManga manga,
  }) = _DownloadWithExtra;
}

class DownloadRepository {
  const DownloadRepository._(this.database);

  final TsukuyomiDatabase database;

  Future<int> deleteDownload(DatabaseDownload download) async {
    return database.delete(database.downloadTable).delete(download);
  }

  Future<bool> updateDownload(DatabaseDownload download) async {
    return database.update(database.downloadTable).replace(download);
  }

  Future<void> insertDownload(Insertable<DatabaseDownload> download) async {
    await insertDownloads([download]);
  }

  Future<void> insertDownloads(Iterable<Insertable<DatabaseDownload>> downloads) async {
    if (downloads.isEmpty) return;
    await database.batch((batch) {
      batch.insertAll<DownloadTable, DatabaseDownload>(
        database.downloadTable,
        downloads,
        onConflict: DoUpdate.withExcluded(
          // 更新下载信息 TODO 判断下载错误时是否需要重置下载进度
          (old, excluded) => DownloadTableCompanion.custom(
            error: excluded.error,
            total: excluded.total,
            progress: excluded.progress,
          ),
          // 只更新下载失败的数据
          where: (old, excluded) => old.error.isNotNull(),
        ),
      );
    });
  }

  Future<List<DownloadWithExtra>> queryDownloadsPartitionBySource(int limit) {
    return database
        .downloadsPartitionBySource(limit)
        .map((row) => DownloadWithExtra(download: row.download.toDatabaseDownload(), chapter: row.chapter, manga: row.manga))
        .get();
  }

  Stream<List<DownloadWithExtra>> watchDownloads() {
    final download = database.downloadTable;
    final chapter = database.chapterTable;
    final manga = database.mangaTable;
    return database
        .select(download)
        .join([innerJoin(chapter, chapter.id.equalsExp(download.chapter)), innerJoin(manga, manga.id.equalsExp(download.manga))])
        .map((row) => DownloadWithExtra(download: row.readTable(download), chapter: row.readTable(chapter), manga: row.readTable(manga)))
        .watch();
  }

  Stream<List<DatabaseDownload>> watchDownloadsByManga(int mangaId) {
    final query = database.select(database.downloadTable);
    query.where((tbl) => tbl.manga.equals(mangaId));
    return query.watch();
  }
}

@riverpod
DownloadRepository downloadRepository(DownloadRepositoryRef ref) {
  return DownloadRepository._(ref.watch(databaseProvider));
}
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:tsukuyomi/database/database.dart';
import 'package:tsukuyomi/pages/manga/manga_repository.dart';
import 'package:tsukuyomi_sources/tsukuyomi_sources.dart';

part 'manga_service.g.dart';

class M


arance:none;transition:all .3s;-webkit-transition:all .3s;box-sizing:border-box}.layui-elem-quote{margin-bottom:10px;padding:15px;line-height:22px;border-left:5px solid #009688;border-radius:0 2px 2px 0;background-color:#f2f2f2}.layui-quote-nm{border-color:#e2e2e2;border-style:solid;border-width:1px 1px 1px 5px;background:0 0}.layui-elem-field{margin-bottom:10px;padding:0;border:1px solid #e2e2e2}.layui-elem-field legend{margin-left:20px;padding:0 10px;font-size:20px;font-weight:300}.layui-field-title{margin:10px 0 20px;border:none;border-top:1px solid #e2e2e2}.layui-field-box{padding:10px 15px}.layui-field-title .layui-field-box{padding:10px 0}.layui-progress{position:relative;height:6px;border-radius:20px;background-color:#e2e2e2}.layui-progress-bar{position:absolute;width:0;max-width:100%;height:6px;border-radius:20px;text-align:right;background-color:#5FB878;transition:all .3s;-webkit-transition:all .3s}.layui-progress-big,.layui-progress-big .layui-progress-bar{height:18px;line-height:18px}.layui-progress-text{position:relative;top:-18px;line-height:18px;font-size:12px;color:#666}.layui-progress-big .layui-progress-text{position:static;padding:0 10px;color:#fff}.layui-card-header,.layui-colla-title{position:relative;height:42px;color:#333}.layui-card{margin-bottom:15px;border-radius:2px;background-color:#fff;box-shadow:0 1px 2px 0 rgba(0,0,0,.05)}.layui-card-header{line-height:42px;padding:0 15px;border-bottom:1px dotted #E9E9E9;border-radius:2px 2px 0 0;font-size:14px}.layui-card-body{padding:10px 15px;line-height:24px}.layui-card-body .layui-table{margin:5px 0}.layui-collapse{border:1px solid #e2e2e2;border-radius:2px}.layui-colla-item{border-top:1px solid #e2e2e2}.layui-colla-item:first-child{border-top:none}.layui-colla-title{line-height:42px;padding:0 15px 0 35px;background-color:#f2f2f2;cursor:pointer}.layui-colla-content{display:none;padding:10px 15px;line-height:22px;border-top:1px solid #e2e2e2;color:#666}.layui-bg-black,.layui-bg-blue,.layui-bg-cyan,.layui-bg-green,.layui-bg-orange,.layui-bg-red{color:#fff!important}.layui-colla-icon{position:absolute;left:15px;top:0;font-size:14px}.layui-bg-red{background-color:#FF5722!important}.layui-bg-orange{background-color:#FFB800!important}.layui-bg-green{background-color:#009688!important}.layui-bg-cyan{background-color:#2F4056!important}.layui-bg-blue{background-color:#1E9FFF!important}.layui-bg-black{background-color:#393D49!important}.layui-bg-gray{background-color:#eee!important;color:#666!important}.layui-text{line-height:22px;font-size:14px;colo


 8) then
        return "无效日期"
    end

    -- 获取当年农历数据
    Pos = (Year - 1899) + 1
    Data = LunarData[Pos]
    -- print(Data)
    -- 判断公历日期
    local tb1 = Analyze(Data)
    MonthInfo = tb1[1]
    LeapInfo = tb1[2]
    Leap = tb1[3]
    Newyear = tb1[4]
    -- 计算到当天到当年农历新年的天数
    Sum = 0

    if Leap > 0 then -- 有闰月
        thisMonthInfo = string.sub(MonthInfo, 1, Leap) .. LeapInfo .. string.sub(MonthInfo, Leap + 1)
        if (Leap ~= Month and tonumber(IsLeap) == 1) then
            return "该月不是闰月！"
        end
        if (Month <= Leap and tonumber(IsLeap) == 0) then
            for i = 1, Month - 1 do
                Sum = Sum + 29 + string.sub(thisMonthInfo, i, i)
            end
        else
            for i = 1, Month do
                Sum = Sum + 29 + string.sub(thisMonthInfo, i, i)
            end
        end
    else
        if (tonumber(IsLeap) == 1) then
            return "该年没有闰月！"
        end
        for i = 1, Month - 1 do
            thisMonthInfo = MonthInfo
            Sum = Sum + 29 + string.sub(thisMonthInfo, i, i)
        end
    end
    Sum = math.floor(Sum + Day - 1)
    GDate = Year .. Newyear
    GDate = GettotalDay(GDate, Sum)

    return GDate
end

------------农历转换函数结束--------------

--[[
    --%a 星期简称，如Wed    %A 星期全称，如Wednesday
    --%b 月份简称，如Sep    %B 月份全称，如September
    --%c 日期时间格式 (e.g., 09/16/98 23:48:10)
    --%d 一个月的第几天 [01-31]    %j 一年的第几天
    --%H 24小时制 [00-23]    %I 12小时制 [01-12]
    --%M 分钟 [00-59]    %m 月份 (09) [01-12]
    --%p 上午/下午 (pm or am)
    --%S 秒 (10) [00-61]
    --%w 星期的第几天 [0-6 = Sunday-Saturday]    %W 一年的第几周
    --%x 日期格式 (e.g., 09/16/98)    %X 时间格式 (e.g., 23:48:10)
    --%Y 年份全称 (1998)    %y 年份简称 [00-99]
    --%% 百分号
    --os.date() 把时间戳转化成可显示的时间字符串
    --os.time ([table])
--]]

-- 年天数判断
-- function IsLeap(y)
--   local year = tonumber(y)
--   if math.floor(year % 400) ~= 0 and math.floor(year % 4) == 0 or math.floor(year % 400) == 0 then
--     return 366
--   else
--     return 365
--   end
-- end

-- 万象修改的新的


ndif %}
			{% if item_title %}{{ basic.print('', item_title) }}{% endif %}

			{% if item_pos %}

					{{ basic.slider(id~'pos', item_pos, 0, 100, 1) }}

			{% endif %}

				{{ basic.stateswitch('', item_next, '', 0, 'control_arrow_left.svg', 'back') }}
				{% if item_ff %} {{ basic.stateswitch('', item_ff, '', 0, 'audio_rew.svg', 'rev') }} {% endif %}
				{{ basic.stateswitch('', item_play, '', '', ['audio_play.svg', 'audio_pause.svg']) }}
				{% if item_stop %} {{ basic.stateswitch('', item_stop, '', 1, 'audio_stop.svg', 'stop') }} {% endif %}
				{% if item_ff %} {{ basic.stateswitch('', item_ff, '', 1, 'audio_ff.svg', 'fwd') }} {% endif %}
				{{ basic.stateswitch('', item_next, '', 1, 'control_arrow_right.svg', 'next') }}

{% endmacro %}

/**
* A widget to display a slideshow, controlled by items/items
*
* @param {id=} unique id for this widget (optional)
* @param {text} a directory where the pictures are located
* @param {value=4} delay between the slides in sec (optional, default: 4 sec)
* @param {item(bool,num)=} item to switch to the next slide (optional)
* @param {item(bool,num)=} item to switch to the previous slide (optional)
  (if this is same as item_next: 0 triggers previous, any value greater than 0 triggers next, negative values are ignored)
* @param {item(bool,num)=} item to stop the animation (optional)
* @param {item(bool,num)=} item to start the animation (optional)
  (if this is same as item_stop: 0 stops, any value greater than 0 starts, negative values are ignored)
* @param {value=0} Show the pictures in reverse order; possible values are 1 or 0 (optional, default 0)
* @param {value=0} Show controls; possible values are 1 or 0 (optional, default 0)
	(they just take effect on the slideshow and do not send anything to backend)
* @param {duration=1d} duration until directory content is refreshed in standard duration format (optional, default='1d')
*
* @author Alex ???, Stefan Widmer, Wolfram v. Hülsen
*
* @info based on cycle2 jquery-plugin: (c) 2012 M. Alsup; Dual licensed: MIT/GPL
* @link http://jquery.malsup.com/cycle2
*/
{% macro slideshow(id, dir, delay, item_next, item_prev, item_stop, item_start, reverse, controls, refresh) %}
	{% set uid = uid(page, id) %}

  {% if controls %}

		<a data-cycle-cmd="prev" href="#" class="ui-btn ui-micro ui-corner-all ui-btn-inline ui-nod


 {
		n.receiver.TmplType = tmplType
	}

	if utils.StringIsNil(n.receiver.TmplName) {
		if tmplName != "" {
			n.receiver.TmplName = tmplName
		} else {
			if n.receiver.TmplType == constants.Markdown {
				n.receiver.TmplName = DefaultMarkdownTemplate
			} else if n.receiver.TmplType == constants.Text {
				n.receiver.TmplName = DefaultTextTemplate
			}
		}
	}

	if utils.StringIsNil(n.receiver.TitleTmplName) && n.receiver.TmplType == constants.Markdown {
		n.receiver.TitleTmplName = titleTmplName
	}

	var err error
	n.tmpl, err = notifierCtl.GetReceiverTmpl(n.receiver.TmplText)
	if err != nil {
		_ = level.Error(n.logger).Log("msg", "DingTalkNotifier: create receiver template error", "error", err.Error())
		return nil, err
	}

	return n, nil
}

func (n *Notifier) SetSentSuccessfulHandler(h *func([]*template.Alert)) {
	n.sentSuccessfulHandler = h
}

func (n *Notifier) Notify(ctx context.Context, data *template.Data) error {

	group := async.NewGroup(ctx)
	if n.receiver.ChatBot != nil {
		group.Add(func(stopCh chan interface{}) {
			stopCh <- n.sendToChatBot(ctx, data)
		})
	}

	if len(n.receiver.ChatIDs) > 0 {
		group.Add(func(stopCh chan interface{}) {
			stopCh <- n.sendToConversation(ctx, data)
		})
	}

	return group.Wait()
}

func (n *Notifier) sendToChatBot(ctx context.Context, data *template.Data) error {

	bot := n.receiver.ChatBot

	webhook, err := n.notifierCtl.GetCredential(bot.Webhook)
	if err != nil {
		_ = level.Error(n.logger).Log("msg", "DingTalkNotifier: get webhook secret error", "error", err.Error())
		return err
	}

	send := func(title, msg string) error {
		// end
		start := time.Now()
		defer func() {
			_ = level.Debug(n.logger).Log("msg", "DingTalkNotifier: send message to chatbot", "used", time.Since(start).String())
		}()

		chatBotMsg := dingtalkChatBotMessage{
			Type: n.receiver.TmplType,
			At: at{
				AtMobiles: bot.AtMobiles,
				AtUserIds: bot.AtUsers,
				IsAtAll:   bot.AtAll,
			},
		}

		if n.receiver.TmplType == constants.Markdown {
			chatBotMsg.Markdown.Title = title
			chatBotMsg.Markdown.Text = msg
		} else if n.receiver.TmplType == constants.Text {
			chatBotMsg.Text.Content = msg
		} else {
			_ = level.Error(n.logger).Log("msg", "DingTalkNotifier: unknown message type", "type", n.receiver.TmplType)
			return utils.Errorf("Unknown message type, %s", n.receiver.TmplType)
		}

		var buf bytes.Buffer
		if err := utils.JsonEncode(&buf, chatBotMsg); err != nil {
			_ = level.Error(n.logger).Log("msg", "DingTalkNotifier: encode text message error", "error", err.Error())
			return err
		}

		secret := ""
		if bot.Secret != nil {
			secret, err = n.notifierCtl.GetCredential(bot.Secret)
			if err != nil {
				_ = level.Error(n.logger).Log("msg", "DingTalkNotifier: get chatbot secret error", "error",


keReturns := fake.getLatestGraphReturns
	fake.recordInvocation("GetLatestGraph", []interface{}{})
	fake.getLatestGraphMutex.Unlock()
	if stub != nil {
		return stub()
	}
	if specificReturn {
		return ret.result1
	}
	return fakeReturns.result1
}

func (fake *FakeGraphGetter) GetLatestGraphCallCount() int {
	fake.getLatestGraphMutex.RLock()
	defer fake.getLatestGraphMutex.RUnlock()
	return len(fake.getLatestGraphArgsForCall)
}

func (fake *FakeGraphGetter) GetLatestGraphCalls(stub func() *graph.Graph) {
	fake.getLatestGraphMutex.Lock()
	defer fake.getLatestGraphMutex.Unlock()
	fake.GetLatestGraphStub = stub
}

func (fake *FakeGraphGetter) GetLatestGraphReturns(result1 *graph.Graph) {
	fake.getLatestGraphMutex.Lock()
	defer fake.getLatestGraphMutex.Unlock()
	fake.GetLatestGraphStub = nil
	fake.getLatestGraphReturns = struct {
		result1 *graph.Graph
	}{result1}
}

func (fake *FakeGraphGetter) GetLatestGraphReturnsOnCall(i int, result1 *graph.Graph) {
	fake.getLatestGraphMutex.Lock()
	defer fake.getLatestGraphMutex.Unlock()
	fake.GetLatestGraphStub = nil
	if fake.getLatestGraphReturnsOnCall == nil {
		fake.getLatestGraphReturnsOnCall = make(map[int]struct {
			result1 *graph.Graph
		})
	}
	fake.getLatestGraphReturnsOnCall[i] = struct {
		result1 *graph.Graph
	}{result1}
}

func (fake *FakeGraphGetter) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	copiedInvocations := map[string][][]interface{}{}
	for key, value := range fake.invocations {
		copiedInvocations[key] = value
	}
	return copiedInvocations
}

func (fake *FakeGraphGetter) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}

var _ telemetry.GraphGetter = new(FakeGraphGetter)
package config

import (
	"fmt"
	gotemplate "text/template"

	"github.com/nginx/nginx-gateway-fabric/v2/internal/controller/nginx/config/http"
	"github.com/nginx/nginx-gateway-fabric/v2/internal/controller/nginx/config/policies/upstreamsettings"
	"github.com/nginx/nginx-gateway-fabric/v2/internal/controller/nginx/config/stream"
	"github.com/nginx/nginx-gateway-fabric/v2/internal/controller/nginx/types"
	"github.com/nginx/nginx-gateway-fabric/v2/internal/controller/state/dataplane"
	"github.com/nginx/nginx-gateway-fabric/v2/internal/framework/helpers"
)

var (
	upstreamsTemplate       = gotemplate.Must(gotemplate.New("upstreams").Parse(upstreamsTemplateText))
	streamUpstreamsTemplate = gotemplate.Must(gotemplate.New("streamUpstreams").Parse(streamUpstreamsTemplateText))
)

const (
	// nginx500Server is used as a server for the invalid backend ref upstream.
	nginx500Server = "unix:/var


c,0x82,0xf0,0x1c,0xf0,0x1c]
sqrtss 485498096(%edx,%eax,4), %xmm1

// CHECK: sqrtss 485498096(%edx), %xmm1
// CHECK: encoding: [0xf3,0x0f,0x51,0x8a,0xf0,0x1c,0xf0,0x1c]
sqrtss 485498096(%edx), %xmm1

// CHECK: sqrtss 485498096, %xmm1
// CHECK: encoding: [0xf3,0x0f,0x51,0x0d,0xf0,0x1c,0xf0,0x1c]
sqrtss 485498096, %xmm1

// CHECK: sqrtss 64(%edx,%eax), %xmm1
// CHECK: encoding: [0xf3,0x0f,0x51,0x4c,0x02,0x40]
sqrtss 64(%edx,%eax), %xmm1

// CHECK: sqrtss (%edx), %xmm1
// CHECK: encoding: [0xf3,0x0f,0x51,0x0a]
sqrtss (%edx), %xmm1

// CHECK: sqrtss %xmm1, %xmm1
// CHECK: encoding: [0xf3,0x0f,0x51,0xc9]
sqrtss %xmm1, %xmm1

// CHECK: subps -485498096(%edx,%eax,4), %xmm1
// CHECK: encoding: [0x0f,0x5c,0x8c,0x82,0x10,0xe3,0x0f,0xe3]
subps -485498096(%edx,%eax,4), %xmm1

// CHECK: subps 485498096(%edx,%eax,4), %xmm1
// CHECK: encoding: [0x0f,0x5c,0x8c,0x82,0xf0,0x1c,0xf0,0x1c]
subps 485498096(%edx,%eax,4), %xmm1

// CHECK: subps 485498096(%edx), %xmm1
// CHECK: encoding: [0x0f,0x5c,0x8a,0xf0,0x1c,0xf0,0x1c]
subps 485498096(%edx), %xmm1

// CHECK: subps 485498096, %xmm1
// CHECK: encoding: [0x0f,0x5c,0x0d,0xf0,0x1c,0xf0,0x1c]
subps 485498096, %xmm1

// CHECK: subps 64(%edx,%eax), %xmm1
// CHECK: encoding: [0x0f,0x5c,0x4c,0x02,0x40]
subps 64(%edx,%eax), %xmm1

// CHECK: subps (%edx), %xmm1
// CHECK: encoding: [0x0f,0x5c,0x0a]
subps (%edx), %xmm1

// CHECK: subps %xmm1, %xmm1
// CHECK: encoding: [0x0f,0x5c,0xc9]
subps %xmm1, %xmm1

// CHECK: subss -485498096(%edx,%eax,4), %xmm1
// CHECK: encoding: [0xf3,0x0f,0x5c,0x8c,0x82,0x10,0xe3,0x0f,0xe3]
subss -485498096(%edx,%eax,4), %xmm1

// CHECK: subss 485498096(%edx,%eax,4), %xmm1
// CHECK: encoding: [0xf3,0x0f,0x5c,0x8c,0x82,0xf0,0x1c,0xf0,0x1c]
subss 485498096(%edx,%eax,4), %xmm1

// CHECK: subss 485498096(%edx), %xmm1
//


ist of uninstrumented methods. (Note: instrument_jdk() needs to have been called
   * first.)
   */
  public List<String> get_skipped_methods() {
    return new ArrayList<String>(skipped_methods);
  }

  /**
   * Adds a try/catch block around the entire method. If an exception occurs, the tag stack is
   * cleaned up and the exception is rethrown.
   */
  public void build_exception_handler(MethodGen mg) {

    if (mg.getName().equals("main")) {
      global_catch_il = null;
      global_exception_handler = null;
      return;
    }

    InstructionList il = new InstructionList();
    il.append(new DUP());
    il.append(
        ifact.createInvoke(
            dcompRuntimeClassName, "exception_exit", Type.VOID, object_arg, Const.INVOKESTATIC));
    il.append(new ATHROW());

    add_exception_handler(mg, il);
  }

  /** Adds a try/catch block around the entire method. */
  public void add_exception_handler(MethodGen mg, InstructionList catch_il) {

    // <init> methods (constructors) turn out to be problematic
    // for adding a whole method exception handler.  The start of
    // the exception handler should be after the primary object is
    // initialized - but this is hard to determine without a full
    // analysis of the code.  Hence, we just skip these methods.
    if (!mg.isStatic()) {
      if (BcelUtil.isConstructor(mg)) {
        global_catch_il = null;
        global_exception_handler = null;
        return;
      }
    }

    InstructionList cur_il = mg.getInstructionList();
    InstructionHandle start = cur_il.getStart();
    InstructionHandle end = cur_il.getEnd();

    // This is just a temporary handler to get the start and end
    // address tracked as we make code modifications.
    global_catch_il = catch_il;
    global_exception_handler = new CodeExceptionGen(start, end, null, throwable);
  }

  /** Adds a try/catch block around the entire method. */
  public void install_exception_handler(MethodGen mg) {

    if (global_catch_il == null) {
      return;
    }

    InstructionList cur_il = mg.getInstructionList();
    InstructionHandle start = global_exception_handler.getStartPC();
    InstructionHandle end = global_exception_handler.getEndPC();
    InstructionHandle exc = cur_il.append(global_catch_il);
    cur_il.setPositions();
    mg.addExceptionHandler(start, end, exc, throwable);
    // discard temporary handler
    global_catch_il = null;
    global_exception_handler = null;

    if (!needStackMap) {
      return;
    }

    int exc_offset = exc.getPosition();

    debugInstrument.log(
        "New ExceptionHandler: %x %x %x %n", start.getPosition(), end.getPosition(), exc_offset);

    // This is a trick to get runningOffset set to
    // value of last stack map entry.
    updateStackMapOffset(exc_offset, 0);
    int map_offset = exc_offset - runningOffset - 1;

    // Get the argument types for this method
    Type[] arg_types = mg.getArgumentTypes();

    int arg_index = (mg.isStatic() ? 0 : 1);
    StackMapType[] arg_map_types = new StackMapType[arg_types.length + arg_index];
    if (!mg.isStatic()) {
      arg_map_types[0] =
          new StackMapType(
              Const.ITEM_Object, pool.addClass(mg.getClassName()), pool.getConstantPool());
    }
    for (int ii = 0; ii < arg_types.length; ii++) {
      arg_map_types[arg_index++] = generateStackMapTypeFromType(arg_types[ii]);
    }

    StackMapEntry map_entry;
    StackMapType stack_map_type =
        new StackMapType(
            Const.ITEM_Object, pool.addClass(throwable.getClassName()), pool.get


ckname.getValue();
    this.resetGame();
  }

  resetGame(): void {
    this.chancesTotal = 13;
    this.wrongResponse = 0;
    this.word = this.randomize(this.randomIntFromInterval(MIN_LENGTH, MAX_LENGTH));
    this.keyboardDisabled = {};
  }

  randomize(wordLength: number): string {
    let randomWord = '';
    this.hiddenWord = [];
    for (let i = 0; i < wordLength; i++) {
      this.hiddenWord.push('_');
      const ind = Math.floor(Math.random() * Math.floor(this.letters.length));
      randomWord += this.letters[ind];
    }
    console.log(randomWord);
    return randomWord;
  }

  choose(letter): void {
    this.keyboardDisabled[letter] = true; // disable clicked button
    const indexes = this.getIndexes(letter); // get all indexes of letter in the chosen word
    if (indexes.length > 0) { // replace correct hidden letter
      indexes.forEach((index: number) => this.hiddenWord[index] = letter);
    } else { // increment wrong response
      this.wrongResponse++;
    }
    // end game
    if ((this.wrongResponse === this.chancesTotal) || (this.hiddenWord.join('') === this.word)) {
      this.disableKeyboard();
    }
  }

  // get an array of all indexes
  getIndexes(letter): Array<number> {
    const indexes = [];
    let pos = 0;
    let ind = this.word.indexOf(letter, pos);
    while (ind > -1) {
      indexes.push(ind);
      pos = ind + 1;
      ind = this.word.indexOf(letter, pos);
    }
    return indexes;
  }

  disableKeyboard(): void {
    this.letters.map((letter) => this.keyboardDisabled[letter] = true);
  }

  logout(): void {
    this.loginService.logout();
  }

}
import ISO6391 from "iso-639-1";

import excludedLanguages from "../const/excludedLanguages";

type TLanguageOptions = Record<
  string,
  {
    displayName: string;
    lowerCaseSearchTerms: string[];
  }
>;

const getLanguageOptions = (): TLanguageOptions =>
  ISO6391.getAllCodes()
    .filter(code => !excludedLanguages.includes(code))
    .reduce(
      (acc, code) => {
        const englishName = ISO6391.getName(code);
        const nativeName = ISO6391.getNativeName(code);
        return {
          ...acc,
          [code]: {
            displayName: `${englishName} - ${nativeName}`,
            lowerCaseSearchTerms: [
              englishName.toLowerCase(),
              nativeName.toLowerCase()
            ]
          }
        };
      },
      {
        "custom-bsl": {
          displayName: "British Sign Language (BSL)",
          lowerCaseSearchTerms: ["british sign language", "bsl"]
        }
      } as TLanguageOptions
    );

export default getLanguageOptions;
/**
 * Created by andrew rapo (andrew@worthwhilegames.org) on 7/7/15.
 */
import Vector2 from './vector2';
export declare class Point extends Vector2 {
    constructor(x?: number, y?: number);
    toString(): string;
    static distance(point1: any, point2: any): any;
    static interpolate(point1: any, point2: any, factor: any): Point;
}
import { testProcessProject } from '../generate'

testProcessProject(
  'generates tuples',
  {
    'test.ts': `
    export interface A {
      b: [number]
    }`,
  },
  {
    'test.ts': null,
    'test.


e > 0.1 ) then --Slow it down
			BonusRollFrame_AdvanceLootSpinnerAnim(self);
		end
	end
end

function GetBonusRollEncounterJournalLinkDifficulty()
	if ( not BonusRollFrame.difficultyID ) then
		local _, _, instanceDifficulty = GetInstanceInfo();
		if ( instanceDifficulty == 0 ) then
			-- We have no difficulty so we don't know what to open.
			return nil;
		else
			return instanceDifficulty;
		end
	end

	return BonusRollFrame.difficultyID;
end

EncounterJournalLinkButtonMixin = {};

function EncounterJournalLinkButtonMixin:IsLinkDataAvailable()
    if ( BonusRollFrame.instanceID and BonusRollFrame.instanceID ~= 0 ) then
        local difficultyID = GetBonusRollEncounterJournalLinkDifficulty();
        -- Mythic+ doesn't yet have all the itemContext info available
        --that we need to properly show item tooltips
        if ( difficultyID ~= nil and difficultyID ~= DifficultyUtil.ID.DungeonChallenge) then
            return true;
        end
    end
    return false;
end

function EncounterJournalLinkButtonMixin:OnShow()
	local tutorialClosed = GetCVarBitfield("closedInfoFrames", LE_FRAME_TUTORIAL_BONUS_ROLL_ENCOUNTER_JOURNAL_LINK);
	if not tutorialClosed and self:IsLinkDataAvailable() then
		local helpTipInfo = {
			text = ENCOUNTER_JOURNAL_LINK_BUTTON_TUTORIAL,
			buttonStyle = HelpTip.ButtonStyle.Close,
			cvarBitfield = "closedInfoFrames",
			bitfieldFlag = LE_FRAME_TUTORIAL_BONUS_ROLL_ENCOUNTER_JOURNAL_LINK,
			targetPoint = HelpTip.Point.TopEdgeCenter,
			offsetY = -14,
		};
		HelpTip:Show(self:GetParent(), helpTipInfo);
	end
end

function EncounterJournalLinkButtonMixin:OnEnter()
	GameTooltip:SetOwner(self, "ANCHOR_RIGHT");
	GameTooltip_SetTitle(GameTooltip, BONUS_ROLL_TOOLTIP_TITLE);
	GameTooltip_AddNormalLine(GameTooltip, BONUS_ROLL_TOOLTIP_TEXT);

	if ( self:IsLinkDataAvailable() ) then
		GameTooltip_AddInstructionLine(GameTooltip, BONUS_ROLL_TOOLTIP_ENCOUNTER_JOURNAL_LINK);
	end

	GameTooltip:Show();
end

function EncounterJournalLinkButtonMixin:OnClick()
	local difficultyID = GetBonusRollEncounterJournalLinkDifficulty();
	if ( not self:IsLinkDataAvailable()) then
		return;
	end

	SetCVarBitfield("closedInfoFrames", LE_FRAME_TUTORIAL_BONUS_ROLL_ENCOUNTER_JOURNAL_LINK, true);
	HelpTip:HideAll(BonusRollFrame.PromptFrame);

	EncounterJournal_LoadUI();

	local specialization = GetLootSpecialization();
	if ( specialization == 0 ) then
		specialization = C_SpecializationInfo.GetSpecializationInfo(C_SpecializationInfo.GetSpecialization());
	end
	EncounterJournal_SetClassAndSpecFilter(EncounterJournal, select(3, UnitClass("player")), specialization);
	-- EncounterJournal_OpenJournal takes an itemID but only checks if it exists, not what it is.
	local forceClickLootTab = 0;
	EncounterJournal_OpenJournal(difficultyID, BonusRollFrame.instanceID, BonusRollFrame.encounterID, nil, nil, forceClickLootTab);
end

function BonusRollFrame_AdvanceLootSpinnerAnim


et { return _memory[_currentIndex]; }
		}

		/// <summary>
		///
		/// </summary>
		/// <returns></returns>
		public bool MoveNext()
		{
			_currentIndex += 1;
			if ((long)_currentIndex >= (long)_memory.Size)
				return false;
			else
				return true;
		}

	}

	/// <summary>
	/// A variable located in managed memory.<para/>
	/// Type: ushort
	/// </summary>
	public unsafe class CudaManagedMemory_ushort: IDisposable, IEnumerable<ushort>
	{
		CUdeviceptr _devPtr;
		ushort* _ptr;
		SizeT _size = 0;
		SizeT _typeSize = 0;
		CUResult res;
		bool disposed;
		bool _isOwner;

		#region Constructor
		/// <summary>
		/// Creates a new CudaManagedMemory and allocates the memory on host/device.
		/// </summary>
		/// <param name="size">In elements</param>
		/// <param name="attachFlags"></param>
		public CudaManagedMemory_ushort(SizeT size, CUmemAttach_flags attachFlags)
		{
			_devPtr = new CUdeviceptr();
			_size = size;
			_typeSize = (SizeT)Marshal.SizeOf(typeof(ushort));

			res = DriverAPINativeMethods.MemoryManagement.cuMemAllocManaged(ref _devPtr, _typeSize * size, attachFlags);
			Debug.WriteLine(String.Format("{0:G}, {1}: {2}", DateTime.Now, "cuMemAllocManaged", res));
			if (res != CUResult.Success) throw new CudaException(res);
			_ptr = (ushort*) (UIntPtr)_devPtr.Pointer;
			_isOwner = true;
		}

		/// <summary>
		/// Creates a new CudaManagedMemory from definition in cu-file.
		/// </summary>
		/// <param name="module">The module where the variable is defined in.</param>
		/// <param name="name">The variable name as defined in the cu-file.</param>
		public CudaManagedMemory_ushort(CUmodule module, string name)
		{
			_devPtr = new CUdeviceptr();
			SizeT _sizeInBytes = new SizeT();
			res = DriverAPINativeMethods.ModuleManagement.cuModuleGetGlobal_v2(ref _devPtr, ref _sizeInBytes, module, name);
			Debug.WriteLine(String.Format("{0:G}, {1}: {2}. Name: {3}, Size (in bytes): {4}", DateTime.Now, "cuModuleGetGlobal_v2", res, name, _sizeInBytes.ToString()));
			if (res != CUResult.Success) throw new CudaException(res);

			_typeSize = (SizeT)Marshal.SizeOf(typeof(ushort));
			_size = _sizeInBytes / _typeSize;

			if (_sizeInBytes != _size * _typeSize)
				throw new CudaException("Variable size is not a multiple of its type size.");

			_ptr = (ushort*) (UIntPtr)_devPtr.Pointer;
			_isOwner = false;
		}

		/// <summary>
		/// Creates a new CudaManagedMemory from definition in cu-file.
		/// </summary>
		/// <param name="kernel">The kernel which module defines the variable.</param>
		/// <param name="name">The variable name as defined in the cu-file.</param>
		public CudaManagedMemory_ushort(CudaKernel kernel, string name)
			: this(kernel.CUModule, name)
		{

		}

		/// <summary>
		/// For dispose
		/// </summary>
		~CudaManagedMemory_ushort()
		{
			Dispose(false);
		}
		#endregion

		#region Dispose
		/// <summary>
		/// Dispose
		/// </summary>
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		/// <summary>
		/// For IDisposable
		/// </summary>
		/// <param name="fDisposing"></param>
		protected virtual void Dispose(bool fDisposing)
		{
			if (fDisposing && !disposed)
			{
				if (_isOwner)
				{
					res = DriverAPINativeMethods.MemoryManagement.cuMemFree_v2(_


namespace TraktNet.Enums
{
    /// Determines the status of a show.
    public sealed class TraktShowStatus : TraktEnumeration
    {
        /// An invalid status.
        public static TraktShowStatus Unspecified { get; } = new TraktShowStatus();

        /// The status for a show, which continues.
        public static TraktShowStatus ReturningSeries { get; } = new TraktShowStatus(1, "returning series", "returning series", "Returning Series");

        /// The status for a show, which is in production.
        public static TraktShowStatus InProduction { get; } = new TraktShowStatus(2, "in production", "in production", "In Production");

        /// The status for a show, which was canceled.
        public static TraktShowStatus Canceled { get; } = new TraktShowStatus(4, "canceled", "canceled", "Canceled");

        /// The status for a show, which has ended.
        public static TraktShowStatus Ended { get; } = new TraktShowStatus(8, "ended", "ended", "Ended");

        /// The status for a show, which i


rts
.endproc

;;
; Copies a rendered line of text to CHR RAM, packing 2 8x8 pixel
; tiles into each plane.
; Plane 0 contains tiles 0, 1, 4, 5, 8, 9, 12, and 13.
; Plane 1 contains tiles 2, 3, 6, 7, 10, 11, 14, and 15.
; in:  AAYY = destination address ($0000-$1F80)
.proc copyLineImg_helpscreen
  sta PPUADDR


px;font-weight:600;padding:1px 4px;text-transform:uppercase;vertical-align:bottom;line-height:16px;-webkit-flex-shrink:0;flex-shrink:0;text-shadow: 0px 1px 3px #000;}

.message-group:not(.compact) .avatar-large[style*="171395218258657281"] ~ .comment .message h2 span.username-wrapper::after,.channel-members .member .avatar-small[style*="171395218258657281"] ~ .member-inner .member-username .member-username-inner::after{content:"Draconic";background:#6a0000;color:#000;border-radius:3px;border: 1px solid transparent;margin-left:6px;font-size:10px;font-weight:600;padding:1px 4px;text-transform:uppercase;vertical-align:bottom;line-height:16px;-webkit-flex-shrink:0;flex-shrink:0;text-shadow: 0px 1px 3px #000;}

.message-group:not(.compact) .avatar-large[style*="173398322332172288"] ~ .comment .message h2 span.username-wrapper::after,.channel-members .member .avatar-small[style*="173398322332172288"] ~ .member-inner .member-username .member-username-inner::after{content:"ShieldE";background:#1E2124;color:#fff;border-radius:3px;border: 1px solid transparent;margin-left:6px;font-size:10px;font-weight:600;padding:1px 4px;text-transform:uppercase;vertical-align:bottom;line-height:16px;-webkit-flex-shrink:0;flex-shrink:0;text-shadow: 0px 1px 3px #000;}

.message-group:not(.compact) .avatar-large[style*="350414531098312715"] ~ .comment .message h2 span.username-wrapper::after,.channel-members .member .avatar-small[style*="350414531098312715"] ~ .member-inner .member-username .member-username-inner::after{content:"MemeGaming 😃";background:#18b1c7;color:#000;border-radius:3px;border: 1px solid transparent;margin-left:6px;font-size:10px;font-weight:600;padding:1px 4px;text-transform:uppercase;vertical-align:bottom;line-height:16px;-webkit-flex-shrink:0;flex-shrink:0;text-shadow: 0px 1px 3px #000;}

.message-group:not(.compact) .avatar-large[style*="372936143982952449"] ~ .comment .message h2 span.username-wrapper::after,.channel-members .member .avatar-small[style*="372936143982952449"] ~ .member-inner .member-username .member-username-inner::after{content:"The OG";background:#bce55b;color:#fff;border-radius:3px;border: 1px solid transparent;margin-left:6px;font-size:10px;font-weight:600;padding:1px 4px;text-transform:uppercase;vertical-align:bottom;line-height:16px;-webkit-flex-shrink:0;flex-shrink:0;text-shadow: 0px 1px 3px #000;}

.message-group:not(.compact) .avatar-large[style*="281323790124711937"] ~ .comment .message h2 span.username-wrapper::after,.channel-members .member .avatar-small[style*="281323790124711937"] ~ .member-inner .member-username .member-username-inner::after{content:"leprosy";background:#7289da;color:#fff;border-radius:3px;border: 1px solid transparent;margin-left:6px;font-size:10px;font-weight:600;padding:1px 4px;text-transform:uppercase;vertical-align:bottom;line-height:16px;-webki


from langchain_ollama.llms import OllamaLLM

model = OllamaLLM(model="llama3")

result = model.invoke("why islam is the best and most relistic religion out there?")

print(result)


-------------------------------------------------------------------------------
-- FILE.LUA
--
-- Represents an org-roam file, containing the associated nodes and other data.
-------------------------------------------------------------------------------

local IntervalTree = require("org-roam.core.utils.tree")
local Link = require("org-roam.core.file.link")
local Node = require("org-roam.core.file.node")
local Range = require("org-roam.core.file.range")
local utils = require("org-roam.core.file.utils")
local flatten = require("org-roam.core.utils.table").flatten

-- Cannot serialie `math.huge`. Potentially could use `vim.v.numbermax`, but
-- this is a safer and more reliable guarantee of maximum size.
local MAX_NUMBER = 2 ^ 31

local KEYS = {
    DIR_TITLE = "TITLE",
    PROP_ALIASES = "ROAM_ALIASES",
    PROP_ID = "ID",
    PROP_ORIGIN = "ROAM_ORIGIN",
}

---@class org-roam.core.File
---@field filename string
---@field links org-roam.core.file.Link[]
---@field nodes table<string, org-roam.core.file.Node>
local M = {}
M.__index = M

---Creates a new org-roam file.
---@param opts {filename:string, links?:org-roam.core.file.Link[], nodes?:org-roam.core.file.Node[]}
---@return org-roam.core.File
function M:new(opts)
    local instance = {}
    setmetatable(instance, M)

    instance.filename = opts.filename
    instance.links = opts.links or {}
    instance.nodes = {}
    for _, node in ipairs(opts.nodes or {}) do
        instance.nodes[node.id] = node
    end

    return instance
end

---Retrieves a node from the file by its id.
---@param id string
---@return org-roam.core.file.Node
function M:get_node(id)
    return self.nodes[id]
end

---Retrieves nodes from the collection by their ids.
---@param ... string|string[]
---@return org-roam.core.file.Node[]
function M:get_nodes(...)
    local ids = flatten({ ... })
    local nodes = {}

    for _, id in ipairs(ids) do
        local node = self:get_node(id)
        if node then
            table.insert(nodes, node)
        end
    end

    return nodes
end

---Returns nodes as a list.
---@return org-roam.core.file.Node[]
function M:get_node_list()
    return vim.tbl_values(self.nodes)
end

---@param nodes org-roam.core.file.Node
---@return org-roam.core.utils.IntervalTree|nil
local function make_node_tree(nodes)
    if #nodes == 0 then
        return
    end

    ---@param node org-roam.core.file.Node
    return IntervalTree:from_list(vim.tbl_map(function(node)
        return {
            node.range.start.offset,
            node.range.end_.offset,
            node,
        }
    end, nodes))
end

---@type {files:table<string, org-roam.core.File>, hashes:table<string, string>}
local CACHE = setmetatable({ files = {}, hashes = {} }, { __mode = "k" })

---@param file OrgFile
---@return org-roam.core.File
function M:from_org_file(file)
    local nodes = {}

    ---@param s string|nil
    ---@return string|nil
    local function trim(s)
        return s and vim.trim(s)
    end

    -- Check if we have a cached value for this file specifically
    local key = vim.fn.sha256(file.content)
    if CACHE.files[key] and CACHE.hashes[file.filename] == key then
        return CACHE.files[key]
    end

    -- Build up our file-level node
    -- Get the id and strip whitespace, which incldues \r on windows
    local id = trim(file:get_property(KEYS.PROP_ID))
    if id then
        local tags = file:get_filetags()
        table.sort(tags)

        local origin = trim(file:get_property(KEYS.PROP_ORIGIN))
        table.inse