read stopped by Exception.");
        } finally {
            Utils.logi(TAG, () -> "Stopping decoder.");
            mQueue.stop();

            mDecoderCallback.onDestroy();
            if (mDecoder != null) {
                try {
                    mDecoder.stop();
                    mDecoder.release();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                }
                mDecoder = null;
            }
        }
        Utils.logi(TAG, () -> "DecoderThread stopped.");
    }

    private void decodeLoop() throws IOException {
        mAvailableInputs.clear();
        mNalQueue.clear();

        Looper.prepare();
        mHandler = new Handler(this);

        MediaFormat format = MediaFormat.createVideoFormat(mFormat, DummyWidth, DummyHeight);
        format.setString("KEY_MIME", mFormat);

        if (mCodec == CODEC_H264) {
            format.setByteBuffer("csd-0", ByteBuffer.wrap(DummySPS, 0, DummySPS.length));
            format.setByteBuffer("csd-1", ByteBuffer.wrap(DummyPPS, 0, DummyPPS.length));
        } else {
            format.setByteBuffer("csd-0", ByteBuffer.wrap(DummyCSD_H265, 0, DummyCSD_H265.length));
        }
        mDecoder = MediaCodec.createDecoderByType(mFormat);

        mQueue.setCodec(mDecoder);

        mDecoder.setVideoScalingMode(MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT);
        mDecoder.setCallback(new Callback());
        mDecoder.configure(format, mSurface, null, 0);
        mDecoder.start();

        Utils.logi(TAG, () -> "Codec created. Type=" + mFormat + " Name=" + mDecoder.getCodecInfo().getName());

        mDecoderCallback.onPrepared();

        mWaitNextIDR = true;

        Looper.loop();
    }

    // Output IDR frame in external media dir for debugging. (/sdcard/Android/media/...)
    private void debugIDRFrame(NAL buf, NAL spsBuffer, NAL ppsBuffer) {
        if (spsBuffer == null || ppsBuffer == null) {
            return;
        }
        if (mDebugIDRFrame) {
            try {
                String path = mContext.getExternalMediaDirs()[0].getAbsolutePath() + "/" + buf.frameIndex + ".h264";
                FileOutputStream stream = new FileOutputStream(path);
                stream.write(spsBuffer.buf, 0, spsBuffer.length);
                stream.write(ppsBuffer.buf, 0, ppsBuffer.length);
                stream.write(buf.buf, 0, buf.length);
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean pushInputBuffer(NAL nal, long presentationTimeUs, int flags) {
        if (presentationTimeUs != 0) {
            mQueue.pushInputBuffer(presentationTimeUs, nal.frameIndex);
        }

        while (nal.length > 0) {
            Integer bufferIndex = mAvailableInputs.poll();
            if (bufferIndex == null) {
                // Insufficient buffer
                return false;
            }
            ByteBuffer buffer = mDecoder.getInputBuffer(bufferIndex);

            int copyLength = Math.min(nal.length, buffer.remaining());
            buffer.put(nal.buf, 0, copyLength);


using Serilog.Core;
using Serilog.Events;
using MultiWeixin.ViewModel;
using System.Windows.Media;

namespace MultiWeixin.Assist;

public class LogSink(MainViewModel mainViewModel) : ILogEventSink
{
    // private readonly MainViewModel _mainViewModel = mainViewModel ?? throw new ArgumentNullException(nameof(mainViewModel));

    // Emit 方法用于接收日志事件
    public void Emit(LogEvent logEvent)
    {
        // 提取日志等级和信息
        var level = logEvent.Level;
        var message = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [ {GetLocalizedLevel(level)} ] {logEvent.RenderMessage()}";
        (var logForeground, var logBackground) = GetColors(level);

        // 更新 MainViewModel 中的日志
        mainViewModel.AddLog(message, level, logForeground, logBackground);
    }

    public static (Brush fg, Brush bg) GetColors(LogEventLevel level)
    {
        return level switch
        {
            LogEventLevel.Verbose => ((Brush fg, Brush bg))(new SolidColorBrush(Colors.DarkGray), new SolidColorBrush(Colors.Transparent)),
            LogEventLevel.Debug => ((Brush fg, Brush bg))(new SolidColorBrush(Colors.Blue), new SolidColorBrush(Colors.T


upb_MessageDef* m) {
  /* string type_url = 1;
   * bytes value = 2; */
  const upb_FieldDef* value_f = upb_MessageDef_FindFieldByNumber(m, 2);
  upb_Message* any_msg;
  const upb_MessageDef* any_m = NULL;
  const char* pre_type_data = NULL;
  const char* pre_type_end = NULL;
  upb_MessageValue encoded;

  jsondec_objstart(d);

  /* Scan looking for "@type", which is not necessarily first. */
  while (!any_m && jsondec_objnext(d)) {
    const char* start = d->ptr;
    upb_StringView name = jsondec_string(d);
    jsondec_entrysep(d);
    if (jsondec_streql(name, "@type")) {
      any_m = jsondec_typeurl(d, msg, m);
      if (pre_type_data) {
        pre_type_end = start;
        while (*pre_type_end != ',') pre_type_end--;
      }
    } else {
      if (!pre_type_data) pre_type_data = start;
      jsondec_skipval(d);
    }
  }

  if (!any_m) {
    jsondec_err(d, "Any object didn't contain a '@type' field");
  }

  any_msg = upb_Message_New(any_m, d->arena);

  if (pre_type_data) {
    size_t len = pre_type_end - pre_type_data + 1;
    char* tmp = upb_Arena_Malloc(d->arena, len);
    const char* saved_ptr = d->ptr;
    const char* saved_end = d->end;
    memcpy(tmp, pre_type_data, len - 1);
    tmp[len - 1] = '}';
    d->ptr = tmp;
    d->end = tmp + len;
    d->is_first = true;
    while (jsondec_objnext(d)) {
      jsondec_anyfield(d, any_msg, any_m);
    }
    d->ptr = saved_ptr;
    d->end = saved_end;
  }

  while (jsondec_objnext(d)) {
    jsondec_anyfield(d, any_msg, any_m);
  }

  jsondec_objend(d);

  upb_EncodeStatus status =
      upb_Encode(any_msg, upb_MessageDef_MiniTable(any_m), 0, d->arena,
                 (char**)&encoded.str_val.data, &encoded.str_val.size);
  // TODO(b/235839510): We should fail gracefully here on a bad return status.
  UPB_ASSERT(status == kUpb_EncodeStatus_Ok);
  upb_Message_Set(msg, value_f, encoded, d->arena);
}

static void jsondec_wrapper(jsondec* d, upb_Message* msg,
                            const upb_MessageDef* m) {
  const upb_FieldDef* value_f = upb_MessageDef_FindFieldByNumber(m, 1);
  upb_MessageValue val = jsondec_value(d, value_f);
  upb_Message_Set(msg, value_f, val, d->arena);
}

static void jsondec_wellknown(jsondec* d, upb_Message* msg,
                              const upb_MessageDef* m) {
  switch (upb_MessageDef_WellKnownType(m)) {
    case kUpb_WellKnown_Any:
      jsondec_any(d, msg, m);
      break;
    case kUpb_WellKnown_FieldMask:
      jsondec_fieldmask(d, msg, m);
      break;
    case kUpb_WellKnown_Duration:
      jsondec_duration(d, msg, m);
      break;
    case kUpb_WellKnown_Timestamp:
      jsondec_timestamp(d, msg, m);
      break;
    case kUpb_WellKnown_Value:
      jsondec_wellknownvalue(d, msg, m);
      break;
    case kUpb_WellKnown_ListValue:
      jsondec_listvalue(d, msg, m);
      break;
    case kUpb_WellKnown_Struct:
      jsondec_struct(d, msg, m);
      break;
    case kUpb_WellKnown_DoubleValue:
    case kUpb_WellKnown_FloatValue:
    case kUpb_WellKnown_Int64Value:
    case kUpb_WellKnown_UInt64Value:
    case kUpb_WellKnown_Int32Value:
    case kUpb_WellKnown_UInt32Value:
    case kUpb_WellKnown_StringValue:
    case kUpb_WellKnown_BytesValue:
    case kUpb_WellKnown_BoolValue:
      jsondec_wrapper(d, msg, m);
      break;
    default:
      UPB_UNREACHABLE();
  }
}

bool upb_JsonDecode(const char* buf, size_t size, upb_Message* msg,
                    const upb_MessageDef* m, const upb_DefPool* symtab,
                    int options, upb_Arena* arena, upb_Status* status) {
  jsondec d;

  if (size == 0) return true;

  d.ptr = buf;
  d.end = buf + size;
  d.arena = arena;
  d.symtab = symtab;
  d.status = status;
  d.options = options;
  d.depth = 64;
  d.line = 1;
  d.line_begin = d.ptr;
  d.debug_field = NULL;
  d.is_first = false;

  if (UPB_SETJMP(d.err)) return false;

  jsondec_tomsg(&d, msg, m);
  return true;
}


static final version = '1.1.8';

  static final githubRelease =
      'https://raw.githubusercontent.com/HenryQuan/AnimeOne/api/app.json';
  static final latestRelease =
      'https://github.com/HenryQuan/AnimeOne/releases/latest';

  static final eminaOne = 'https://github.com/splitline/emina-one';
  static final animeGo = 'https://github.com/HenryQuan/AnimeGo';

  /// if update has been checked
  bool hasUpdate = false;

  /// A flag to check if cookie is necessary
  static String? requestCookieLink = '';

  // Relating to local data
  late SharedPreferences prefs;
  static final lastUpdate = 'AnimeOne:LastUpdate';
  static final animeList = 'AnimeOne:AnimeList';
  static final animeScedule = 'AnimeOne:AnimeScedule';
  static final scheduleIntroVideo = 'AnimeOne:SceduleIntroVideo';
  static final oneCookie = 'AnimeOne:OneCookie';
  static final oneUserAgent = 'AnimeOne:OneUserAgent';
  static final ageRestriction = 'AnimeOne:AgeRestriction';

  // Relating to seasonal anime
  static final _season = new AnimeSeason(DateTime.now());
  String getSeasonName() => _season.toString();
  String getScheduleLink() => _season.getLink();
  String getSeasonLink() => _season.getAnimeLink();
  List<String> getQuickFilters() => _season.getQuickFilters();

  // Relating to anime list (it won't be changed)
  List<AnimeInfo> _animeList = [];
  List<AnimeInfo> getAnimeList() => this._animeList;
  // Relating to anime scedule (it doesn't change as well)
  AnimeVideo? _introductory;
  AnimeVideo? getIntroVideo() => this._introductory;
  List<AnimeSchedule> _animeScheduleList = [];
  List<AnimeSchedule> getScheduleList() => this._animeScheduleList;
  // Relating to recent anime
  late AnimeRecentParser _recentParser;
  List<AnimeRecent> _recentList = [];
  List<AnimeRecent> getRecentList() => this._recentList;
  // Saved cookie for animeon
  String? _cookie;
  String? _userAgent;

  /// Use videopassword as the default cookie
  String getCookie() => _cookie ?? 'videopassword=0';
  void updateCookie(String cookie) {
    _cookie = cookie;
    // Add video password if not included
    if (!cookie.contains('videopassword')) {
      _cookie = _cookie! + '; videopassword=0';
    }

    prefs.setString(oneCookie, _cookie!);
  }

  String getUserAgent() => _userAgent ?? '';
  void updateUserAgent(String agent) {
    _userAgent = agent;
    prefs.setString(oneUserAgent, agent);
  }

  // Age restriction
  bool _showAgeAlert = false;
  bool showShowAgeAlert() => _showAgeAlert;
  void updateAgeAlert() {
    _showAgeAlert = false;
    prefs.setString(ageRestriction, jsonEncode(false));
  }

  // Relating to Github update
  GithubUpdate? _update;
  GithubUpdate? getGithubUpdate() => this._update;

  // Singleton pattern
  GlobalData._init();
  static final GlobalData _instance = new GlobalData._init();

  // Use dart's factory constructor to implement this patternx
  factory GlobalData() {
    return _instance;
  }

  /// Get data from anime1.me if necessary
  Future init() async {
    bool shouldUpdate = false;

    prefs = await SharedPreferences.getInstance();
    // Check if data are stored properly
    // prefs.getKeys().forEach((k) {
    //   debugPrint('$k ${prefs.get(k)}');
    // });

    // Whether an age alert shoud be shown
    String? ageAlert = prefs.get(ageRestriction) as String?;
    if (ageAlert == null) {
      this._showAgeAlert = true;
    }

    // Get saved coo


c((sz), $)
#define calloc(sz, cnt)     rl::rl_calloc((sz), (cnt), $)
#define realloc(p, sz)      rl::rl_realloc((p), (sz), $)
#define free(p)             rl::rl_free((p), $)

#ifdef assert
#undef assert
#endif
#define assert              RL_ASSERT

#ifdef errno
#undef errno
#endif
#define errno               (rl::get_errno())

#endif
/*  Relacy Race Detector
 *  Copyright (c) 2008-2013, Dmitry S. Vyukov
 *  All rights reserved.
 *  This software is provided AS-IS with no warranty, either express or implied.
 *  This software is distributed under a license and may not be copied,
 *  modified or distributed except as expressly authorized under the
 *  terms of the license contained in the file LICENSE in this distribution.
 */

#ifndef RL_CLI_VAR_HPP
#define RL_CLI_VAR_HPP
#ifdef _MSC_VER
#   pragma once
#endif

#include "base.hpp"
#include "atomic.hpp"

namespace rl
{

template<typename T> class nvar;

template<typename T>
class nvar_proxy
{
public:
    typedef typename atomic_add_type<T>::type add_type;
    template<typename Y> friend class nvar;

    operator T () const
    {
        return load();
    }

    T operator = (T value)
    {
        store(value);
        return value;
    }

    T operator = (nvar_proxy const& r)
    {
        T const value = r.load();
        store(value);
        return *this;
    }

    T operator ++ (int)
    {
        T tmp = load();
        store(tmp + 1);
        return tmp;
    }

    T operator -- (int)
    {
        T tmp = load();
        store(tmp - 1);
        return tmp;
    }

    T operator ++ ()
    {
        T tmp = load();
        store(tmp + 1);
        return tmp + 1;
    }

    T operator -- ()
    {
        T tmp = load();
        store(tmp - 1);
        return tmp - 1;
    }

    T operator += (add_type value)
    {
        T tmp = load();
        store(tmp + value);
        return tmp + value;
    }

    T operator -= (add_type value)
    {
        T tmp = load();
        store(tmp - value);
        return tmp - value;
    }

private:
    nvar<T>& var_;
    debug_info info_;

    nvar_proxy(nvar<T>& var, debug_info_param info)
        : var_(var)
        , info_(info)
    {
    }

    T load() const
    {
        return var_.load(mo_relaxed, info_);
    }

    void store(T value)
    {
        var_.store(value, mo_relaxed, info_);
    }
};

template<typename T>
class nvar : public generic_atomic<T, true>
{
public:
    typedef nvar_proxy<T> proxy_t;
    friend class nvar_proxy<T>;

    nvar()
    {
    }

    explicit nvar(T value)
    {
        this->store(value, mo_relaxed, $);
    }

    nvar(nvar const& r)
    {
        T const value = r.load(mo_relaxed, $);
        this->store(value, mo_relaxed, $);
    }

    nvar(proxy_t const& r)
    {
        T const value = r.load();
        this->store(value, mo


 + 2 * l - 1);
  }
}

void find_repetitions(string s, int shift = 0) {
  int n = s.size();
  if (n == 1) return;

  int nu = n / 2;
  int nv = n - nu;
  string u = s.substr(0, nu);
  string v = s.substr(nu);
  string ru(u.rbegin(), u.rend());
  string rv(v.rbegin(), v.rend());

  find_repetitions(u, shift);
  find_repetitions(v, shift + nu);

  vector<int> z1 = z_function(ru);
  vector<int> z2 = z_function(v + '#' + u);
  vector<int> z3 = z_function(ru + '#' + rv);
  vector<int> z4 = z_function(v);

  for (int cntr = 0; cntr < n; cntr++) {
    int l, k1, k2;
    if (cntr < nu) {
      l = nu - cntr;
      k1 = get_z(z1, nu - cntr);
      k2 = get_z(z2, nv + 1 + cntr);
    } else {
      l = cntr - nu + 1;
      k1 = get_z(z3, nu + 1 + nv - 1 - (cntr - nu));
      k2 = get_z(z4, (cntr - nu) + 1);
    }
    if (k1 + k2 >= l) convert_to_repetitions(shift, cntr < nu, cntr, l, k1, k2);
  }
}
```

**本页面主要译自博文 [Поиск всех тандемных повторов в строке. Алгоритм Мейна-Лоренца](http://e-maxx.ru/algo/string_tandems) 与其英文翻译版 [Finding repetitions](https://cp-algorithms.com/string/main_lorentz.html)。其中俄文版版权协议为 Public Domain + Leave a Link；英文版版权协议为 CC-BY-SA 4.0。**
前置知识：[线性规划基础](./linear-programming.md)

## 引入

算法竞赛中，经常使用单纯形法解决线性规划问题。但是，由于算法竞赛中遇到的线性规划问题大多有着更特殊的结构，常常可以转化为网络流问题，因此，单纯形法并不常用，效率也不如专门为网络流问题设计的算法。

## 基本概念

假设要求解如下一个有 $n$ 个决策变量和 $m+n$ 个约束的 [标准形式](./linear-programming.md#标准形式) 线性规划问题：

$$
\begin{aligned}
\min_{x}\; & z = c^Tx \\
\text{subject to }& Ax = b, \\
& x \ge 0.
\end{aligned}
$$

不妨假设这 $m$ 个等式约束确定的线性方程组有解，且 $A$ 满秩，则 $\operatorname{rank}A = m \le n$。

### 一个例子

在严格叙述单纯形法的步骤之前，本节首先考察一个具体的例子，以


// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_COCOA_PROTOCOLS_MAC_H_
#define BASE_COCOA_PROTOCOLS_MAC_H_

#import <Cocoa/Cocoa.h>

// GTM also maintinas a list of empty protocols, but only the ones the library
// requires. Augment that below.
#import "third_party/GTM/GTMDefines.h"

// New Mac OS X SDKs introduce new protocols used for delegates.  These
// protocol defintions aren't not present in earlier releases of the Mac OS X
// SDK.  In order to support building against the new SDK, which requires
// delegates to conform to these protocols, and earlier SDKs, which do not
// define these protocols at all, this file will provide empty protocol
// definitions when used with earlier SDK versions.

#define DEFINE_EMPTY_PROTOCOL(p) \
@protocol p \
@end

#if !defined(MAC_OS_X_VERSION_10_7) || \
    MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7

DEFINE_EMPTY_PROTOCOL(NSDraggingDestination)
DEFINE_EMPTY_PROTOCOL(ICCameraDeviceDownloadDelegate)

#endif  // MAC_OS_X_VERSION_10_7

#if !defined(MAC_OS_X_VERSION_10_8) || \
    MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8

DEFINE_EMPTY_PROTOCOL(NSUserNotificationCenterDelegate)

#endif  // MAC_OS_X_VERSION_10_8

#undef DEFINE_EMPTY_PROTOCOL

#endif  // BASE_COCOA_PROTOCOLS_MAC_H_


 1. Maximum items: 100.
	Labels []string `json:"labels"`
}

// JITRunnerConfig represents encoded JIT configuration that can be used to bootstrap a self-hosted runner.
type JITRunnerConfig struct {
	Runner           *Runner `json:"runner,omitempty"`
	EncodedJITConfig *string `json:"encoded_jit_config,omitempty"`
}

// GenerateOrgJITConfig generate a just-in-time configuration for an organization.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#create-configuration-for-a-just-in-time-runner-for-an-organization
//
//meta:operation POST /orgs/{org}/actions/runners/generate-jitconfig
func (s *ActionsService) GenerateOrgJITConfig(ctx context.Context, org string, request *GenerateJITConfigRequest) (*JITRunnerConfig, *Response, error) {
	u := fmt.Sprintf("orgs/%v/actions/runners/generate-jitconfig", org)
	req, err := s.client.NewRequest("POST", u, request)
	if err != nil {
		return nil, nil, err
	}

	jitConfig := new(JITRunnerConfig)
	resp, err := s.client.Do(ctx, req, jitConfig)
	if err != nil {
		return nil, resp, err
	}

	return jitConfig, resp, nil
}

// GenerateRepoJITConfig generates a just-in-time configuration for a repository.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#create-configuration-for-a-just-in-time-runner-for-a-repository
//
//meta:operation POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig
func (s *ActionsService) GenerateRepoJITConfig(ctx context.Context, owner, repo string, request *GenerateJITConfigRequest) (*JITRunnerConfig, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/actions/runners/generate-jitconfig", owner, repo)
	req, err := s.client.NewRequest("POST", u, request)
	if err != nil {
		return nil, nil, err
	}

	jitConfig := new(JITRunnerConfig)
	resp, err := s.client.Do(ctx, req, jitConfig)
	if err != nil {
		return nil, resp, err
	}

	return jitConfig, resp, nil
}

// RegistrationToken represents a token that can be used to add a self-hosted runner to a repository.
type RegistrationToken struct {
	Token     *string    `json:"token,omitempty"`
	ExpiresAt *Timestamp `json:"expires_at,omitempty"`
}

// CreateRegistrationToken creates a token that can be used to add a self-hosted runner.
//
// GitHub API docs: https://docs.github.com/rest/actions/self-hosted-runners#create-a-registration-token-for-a-repository
//
//meta:operation POST /repos/{owner}/{repo}/actions/runners/registration-token
func (s *ActionsService) CreateRegistrationToken(ctx context.Context, owner, repo string) (*RegistrationToken, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/actions/runners/registration-token", owner, repo)

	req, err := s.client.NewRequest("POST", u, nil)
	if err != nil {
		return nil, nil, err
	}

	registrationToken := new(RegistrationToken)
	resp, err := s.client.Do(ctx, req, registrationToken)
	if err != nil {
		return nil, resp, err
	}

	return registrationToken, resp, nil
}

// Runner represents a self-hosted runner registered with a repository.
type Runner struct {
	ID     *int64          `json:"id,omitempty"`
	Name   *string         `json:"name,omitempty"`
	OS     *string         `json:"os,


li>
  ///

  /// status-message - The reason for the status.
  ///

  ///

  /// update-date - The time when the modification request was last
  /// updated.
  ///

  ///

  ///
  /// Parameter [nextToken] :
  /// The token to retrieve the next page of results.
  ///
  /// Parameter [reservedInstancesModificationIds] :
  /// IDs for the submitted modification request.
  Future<DescribeReservedInstancesModificationsResult>
      describeReservedInstancesModifications({
    List<Filter>? filters,
    String? nextToken,
    List<String>? reservedInstancesModificationIds,
  }) async {
// TODO: implement ec2
    throw UnimplementedError();
  }

  /// Describes Reserved Instance offerings that are available for purchase.
  /// With Reserved Instances, you purchase the right to launch instances for a
  /// period of time. During that time period, you do not receive insufficient
  /// capacity errors, and you pay a lower usage rate than the rate charged for
  /// On-Demand instances for the actual time used.
  ///
  /// If you have listed your own Reserved Instances for sale in the Reserved
  /// Instance Marketplace, they will be excluded from these results. This is to
  /// ensure that you do not purchase your own Reserved Instances.
  ///
  /// For more information, see Sell
  /// in the Reserved Instance Marketplace in the Amazon EC2 User
  /// Guide.
  /// <note>
  /// The order of the elements in the response, including those within nested
  /// structures, might vary. Applications should not assume the elements appear
  /// in a particular order.
  /// </note>
  ///
  /// Parameter [availabilityZone] :
  /// The Availability Zone in which the Reserved Instance can be used.
  ///
  /// Parameter [dryRun] :
  /// Checks whether you have the required permissions for the action, without
  /// actually making the request, and provides an error response. If you have
  /// the required permissions, the error response is
  /// DryRunOperation. Otherwise, it is
  /// UnauthorizedOperation.
  ///
  /// Parameter [filters] :
  /// One or more filters.
  ///
  ///

  ///

  /// availability-zone - The Availability Zone where the Reserved
  /// Instance can be used.
  ///

  ///

  /// duration - The duration of the Reserved Instance (for
  /// example, one year or three years), in seconds (31536000 |
  /// 94608000).
  ///

  ///

  /// fixed-price - The purchase price of the Reserved Instance
  /// (for example, 9800.0).
  ///

  ///

  /// instance-type - The instance type that is covered by the
  /// reservation.
  ///

  ///

  /// marketplace - Set to true to show only Reserved
  /// Instance Marketplace offerings. When this filter is not used, which is the
  /// default behavior, all offerings from both Amazon Web Services and the
  /// Reserved Instance Marketplace are listed.
  ///

  ///

  /// product-description - The Reserved Instance product platform
  /// description (Linux/UNIX | Linux with SQL Server
  /// Standard | Linux with SQL Server Web | Linux
  /// with SQL Server Enterprise | SUSE Linux | Red
  /// Hat Enterprise Linux</cod


edge250Sbnetworking250Sbdescription => 'لنأخذ الوقت الكافي للتعرف على كيفية تفاعل مستخدمي مونيرو مع بعضهم البعض على الشبكة ، وما يعنيه هذا بالنسبة لخصوصيتهم.';

  @override
  String get knowledge250Sbnetworking250Sbtitle => 'ما يحتاج كل مستخدم مونيرو إلى معرفته عندما يتعلق الأمر بالشبكات';

  @override
  String get knowledge250Sbnodes250Sb0250Sbtext => '<p> واحدة من أكبر المزايا التي تتمتع بها مونيرو مقارنة بالعملات المشفرة الأخرى هي خصوصية السلسلة ، ولكن هل تساءلت يومًا كيف يتم الحفاظ على خصوصية مونيرو عند استخدام عقدة بعيدة؟ ماذا لو كنت تستخدم خادم \"light wallet\" مثل MyMonero؟ </p>\n<p> في هذا المنشور ، سنتعمق في بعض التفاصيل حول كيفية توفير مونيرو لخصوصية استثنائية على السلسلة حتى عند استخدام عقدة بعيدة ، بالإضافة إلى ما يجب الانتباه إليه عند استخدام العقد البعيدة. </p>';

  @override
  String get knowledge250Sbnodes250Sb1250Sbtext => '<p> بالنسبة لأولئك الأقل دراية بكيفية عمل Monero ، يمكن لأي شخص تشغيل العقد (أو الخوادم) في شبكة Monero والسماح لمالك العقدة - أو غيرهم ممن يختارون مشاركتها معهم! - لمزامنة نسخة من blockchain وتقديم تلك النسخة للآخرين على الشبكة. تتحقق هذه العقد أيضًا من جميع المعاملات التي تحدث على الشبكة ، بالإضافة إلى جميع الكتل التي يتم نشرها وتضمن أنها تتبع جميعًا القواعد التي تم تحديدها بالإجماع. </p>\n<p> الوظيفة الأخرى التي تخدمها العقد في Monero هي كطريقة لتوفير جميع البيانات التي تحتاجها محفظة Monero المفضلة لديك للتحقق بشكل صحيح من المعاملات التي تخصك وإجراء معاملات جديدة. يتم توفير هذه البيانات بواسطة العقد بطريقتين: </p>\n<ul>\n<li> تطلب المحفظة البيانات من كل كتلة على blockchain ، ويتم مسح


ertEquals(expectedNotes, rs.getInt(1), "笔记数量应该匹配")
            }

            // 检查牌组数量
            conn.createStatement().use { stmt ->
                val rs = stmt.executeQuery("SELECT decks FROM col WHERE id = 1")
                rs.next()
                val decksJson = rs.getString(1)
                val decks = Json.parseToJsonElement(decksJson).jsonObject
                assertEquals(expectedDecks, decks.size, "牌组数量应该匹配")
            }

            // 检查模型数量
            conn.createStatement().use { stmt ->
                val rs = stmt.executeQuery("SELECT models FROM col WHERE id = 1")
                rs.next()
                val modelsJson = rs.getString(1)
                val models = Json.parseToJsonElement(modelsJson).jsonObject
                assertEquals(expectedModels, models.size, "模型数量应该匹配")
            }
        }
    }

    private fun verifyAdvancedModelFields(apkgFile: File, dbName: String = "collection.anki2") {
        withDatabase(apkgFile, dbName) { conn ->
            conn.createStatement().use { stmt ->
                val rs = stmt.executeQuery("SELECT models FROM col WHERE id = 1")
                rs.next()
                val modelsJson = rs.getString(1)
                val models = Json.parseToJsonElement(modelsJson).jsonObject

                models.values.forEach { modelElement ->
                    val model = modelElement.jsonObject
                    val fields = model["flds"]?.jsonArray
                    assertNotNull(fields, "模型应该有字段定义")
                    assertTrue(fields!!.size >= 4, "高级模型应该至少有4个字段")
                }
            }
        }
    }

    private fun verifyNoteTags(apkgFile: File, expectedTag: String, dbName: String = "collection.anki2") {
        withDatabase(apkgFile, dbName) { conn ->
            conn.createStatement().use { stmt ->
                val rs = stmt.executeQuery("SELECT tags FROM notes")
                while (rs.next()) {
                    val tags = rs.getString(1)
                    assertTrue(tags.contains(expectedTag), "笔记应该包含期望的标签")
                }
            }
        }
    }

    private fun verifyMediaFiles(apkgFile: File, expectedMedia: Map<String, ByteArray>, format: ApkgFormat = ApkgFormat.LEGACY) {
        ZipFile(apkgFile).use { zipFile ->
            val mediaEntry = zipFile.getEntry("media")
            assertNotNull(mediaEntry, "media 文件应该存在")

            if (format.schemaVersion >= 18) {
                // LATEST: media 映射为 Protobuf(MediaEntries) 且经过 Zstd 压缩；编号媒体文件内容也经过 Zstd 压缩
                val mediaRaw = zipFile.getInputStream(mediaEntry).use { it.readBytes() }
                val mediaDecoded = ZstdNative().decompress(mediaRaw)
                val entries = decodeMediaEntries(mediaDecoded)
                // 验证每个媒体文件
                expectedMedia.forEach { (filename, expectedData) ->
                    val idx = entries.indexOfFirst { it.name == filename }
                    assertTrue(idx >= 0, "媒体映射应该包含 $filename")
                    val mediaFileEntry = zipFile.getEntry


enderer, arguments);
};

/**
 * Sets/gets the spacing, in pixels, between lines of text. This
 * setting will be used in all subsequent calls to the text() function.
 *
 * @method textLeading
 * @param {Number} leading the size in pixels for spacing between lines
 * @return {Object|Number}
 * @example
 *

 *
 * // Text to display. The "\n" is a "new line" character
 * lines = "L1\nL2\nL3";
 * textSize(12);
 *
 * textLeading(10);  // Set leading to 10
 * text(lines, 10, 25);
 *
 * textLeading(20);  // Set leading to 20
 * text(lines, 40, 25);
 *
 * textLeading(30);  // Set leading to 30
 * text(lines, 70, 25);
 *
 *

 */
p5.prototype.textLeading = function(theLeading) {
  return this._renderer.textLeading.apply(this._renderer, arguments);
};

/**
 * Sets/gets the current font size. This size will be used in all subsequent
 * calls to the text() function. Font size is measured in pixels.
 *
 * @method textSize
 * @param {Number} theSize the size of the letters in units of pixels
 * @return {Object|Number}
 * @example
 *

 *
 * textSize(12);
 * text("Font Size 12", 10, 30);
 * textSize(14);
 * text("Font Size 14", 10, 60);
 * textSize(16);
 * text("Font Size 16", 10, 90);
 *
 *

 */
p5.prototype.textSize = function(theSize) {
  return this._renderer.textSize.apply(this._renderer, arguments);
};

/**
 * Sets/gets the style of the text for system fonts to NORMAL, ITALIC, or BOLD.
 * Note: this may be is overridden by CSS styling. For non-system fonts
 * (opentype, truetype, etc.) please load styled fonts instead.
 *
 * @method textStyle
 * @param {Number/Constant} theStyle styling for text, either NORMAL,
 *                            ITALIC, or BOLD
 * @return {Object|String}
 * @example
 *

 *
 * strokeWeight(0);
 * textSize(12);
 * textStyle(NORMAL);
 * text("Font Style Normal", 10, 30);
 * textStyle(ITALIC);
 * text("Font Style Italic", 10, 60);
 * textStyle(BOLD);
 * text("Font Style Bold", 10, 90);
 *
 *

 */
p5.prototype.textStyle = function(theStyle) {
  return this._renderer.textStyle.apply(this._renderer, arguments);
};

/**
 * Calculates and returns the width of any character or text string.
 *
 * @method textWidth
 * @param {String} theText the String of characters to measure
 * @return {Number}
 * @example
 *

 *
 * textSize(28);
 *
 * var aChar = 'P';
 * var cWidth = textWidth(aChar);
 * text(aChar, 0, 40);
 * line(cWidth, 0, cWidth, 50);
 *
 * var aString = "p5.js";
 * var sWidth = textWidth(aString);
 * text(aString, 0, 85);
 * line(sWidth, 50, sWidth, 100);
 *
 *

 */
p5.prototype.textWidth = function(theText) {
  return this._renderer.textWidth.apply(this._renderer, arguments);
};

/**
 * Returns the ascent of the current font at its current size. The ascent
 * represents the distance, in pixels, of the tallest character above
 * the baseline.
 *
 * @return {Number}
 * @example
 *

 *
 * var base = height * 0.75;
 * var scalar = 0.8


i5.Future<List<_i2.Public>> authorities({_i1.BlockHash? at}) async {
    final hashedKey = _authorities.hashedKey();
    final bytes = await __api.getStorage(
      hashedKey,
      at: at,
    );
    if (bytes != null) {
      return _authorities.decodeValue(bytes);
    }
    return []; /* Default */
  }

  /// The current slot of this block.
  ///
  /// This will be set in `on_initialize`.
  _i5.Future<_i4.Slot> currentSlot({_i1.BlockHash? at}) async {
    final hashedKey = _currentSlot.hashedKey();
    final bytes = await __api.getStorage(
      hashedKey,
      at: at,
    );
    if (bytes != null) {
      return _currentSlot.decodeValue(bytes);
    }
    return BigInt.zero; /* Default */
  }

  /// Returns the storage key for `authorities`.
  _i6.Uint8List authoritiesKey() {
    final hashedKey = _authorities.hashedKey();
    return hashedKey;
  }

  /// Returns the storage key for `currentSlot`.
  _i6.Uint8List currentSlotKey() {
    final hashedKey = _currentSlot.hashedKey();
    return hashedKey;
  }
}

class Constants {
  Constants();

  /// The slot duration Aura should run with, expressed in milliseconds.
  /// The effective value of this type should not change while the chain is running.
  ///
  /// For backwards compatibility either use [`MinimumPeriodTimesTwo`] or a const.
  final BigInt slotDuration = BigInt.from(6000);
}
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:typed_data' as _i4;

import 'package:polkadart/scale_codec.dart' as _i1;
import 'package:quiver/collection.dart' as _i5;

import '../sp_core/crypto/account_id32.dart' as _i2;
import 'review_opinion.dart' as _i3;

class ReviewRecord {
  const ReviewRecord({
    required this.who,
    required this.meta,
    required this.option,
  });

  factory ReviewRecord.decode(_i1.Input input) {
    return codec.decode(input);
  }

  /// AccountId
  final _i2.AccountId32 who;

  /// Vec<u8>
  final List<int> meta;

  /// ReviewOpinion
  final _i3.ReviewOpinion option;

  static const $ReviewRecordCodec codec = $ReviewRecordCodec();

  _i4.Uint8List encode() {
    return codec.encode(this);
  }

  Map<String, dynamic> toJson() => {
        'who': who.toList(),
        'meta': meta,
        'option': option.toJson(),
      };

  @override
  bool operator ==(Object other) =>
      identical(
        this,
        other,
      ) ||
      other is ReviewRecord &&
          _i5.listsEqual(
            other.who,
            who,
          ) &&
          _i5.listsEqual(
            other.meta,
            meta,
          ) &&
          other.option == option;

  @override
  int get hashCode => Object.hash(
        who,
        meta,
        option,
      );
}

class $ReviewRecordCodec with _i1.Codec<ReviewRecord> {
  const $ReviewRecordCodec();

  @override
  void encodeTo(
    ReviewRecord obj,
    _i1.Output output,
  ) {
    const _i1.U8ArrayCodec(32).encodeTo(
      obj.who,
      output,
    );
    _i1.U8SequenceCodec.c


    }};
}

fn verify_max<T: Counter, B: Borrow<Histogram<T>>>(hist: B) -> bool {
    let hist = hist.borrow();
    if let Some(mx) = hist
        .iter_recorded()
        .map(|v| v.value_iterated_to())
        .map(|v| hist.highest_equivalent(v))
        .last()
    {
        hist.max() == mx
    } else {
        hist.max() == 0
    }
}

const TRACKABLE_MAX: u64 = 3600 * 1000 * 1000;
// Store up to 2 * 10^3 in single-unit precision. Can be 5 at most.
const SIGFIG: u8 = 3;
const TEST_VALUE_LEVEL: u64 = 4;

#[test]
fn construction_arg_ranges() {
    assert!(Histogram::<u64>::new_with_max(1, SIGFIG).is_err());
    assert!(Histogram::<u64>::new_with_max(TRACKABLE_MAX, 6).is_err());
}

#[test]
fn empty_histogram() {
    let h = Histogram::<u64>::new(SIGFIG).unwrap();
    assert_eq!(h.min(), 0);
    assert_eq!(h.max(), 0);
    assert_near!(h.mean(), 0.0, 0.0000000000001);
    assert_near!(h.stdev(), 0.0, 0.0000000000001);
    assert_near!(h.quantile_below(0), 1.0, 0.0000000000001);
    assert!(verify_max(h));
}

#[test]
fn construction_arg_gets() {
    let h = Histogram::<u64>::new_with_max(TRACKABLE_MAX, SIGFIG).unwrap();
    assert_eq!(h.low(), 1);
    assert_eq!(h.high(), TRACKABLE_MAX);
    assert_eq!(h.sigfig(), SIGFIG);

    let h = Histogram::<u64>::new_with_bounds(1000, TRACKABLE_MAX, SIGFIG).unwrap();
    assert_eq!(h.low(), 1000);
}

#[test]
fn record() {
    let mut h = Histogram::<u64>::new_with_max(TRACKABLE_MAX, SIGFIG).unwrap();
    h += TEST_VALUE_LEVEL;
    assert_eq!(h.count_at(TEST_VALUE_LEVEL), 1);
    assert_eq!(h.len(), 1);
    assert!(verify_max(h));
}

#[test]
fn record_past_trackable_max() {
    let mut h = Histogram::<u64>::new_with_max(TRACKABLE_MAX, SIGFIG).unwrap();
    assert!(h.record(3 * TRACKABLE_MAX).is_err());
}

#[test]
fn saturating_record() {
    let mut h = Histogram::<u64>::new_with_bounds(512, TRACKABLE_MAX, SIGFIG).unwrap();

    h.saturating_record(1); // clamped below
    h.saturating_record(1000 * 1000); // not clamped
    h.saturating_record(3 * TRACKABLE_MAX); // clamped above

    // https://github.com/HdrHistogram/HdrHistogram_rust/pull/74#discussion_r158192909
    assert_eq!(h.count_at(511), 1);
    assert_eq!(h.count_at(1000 * 1000), 1);
    assert_eq!(h.count_at(h.high()), 1);
    assert_eq!(h.len(), 3);
    assert!(verify_max(h));
}

#[test]
fn record_in_interval() {
    let mut h = Histogram::<u64>::new_with_max(TRACKABLE_MAX, SIGFIG).unwrap();
    h.record_correct(TEST_VALUE_LEVEL, TEST_VALUE_LEVEL / 4)
        .unwrap();
    let mut r = Histogram::<u64>::new_with_max(TRACKABLE_MAX, SIGFIG).unwrap();
    r += TEST_VALUE_LEVEL;

    // The data will include corrected samples:
    assert_eq!(h


b3bcf0;
  --h2-color: #989ed6;
  --h3-color: #8987c9;
  --h4-color: #9482c5;
  --h5-color: #9482c5;
  --h6-color: #9482c5;
}

body.encore-theme-dark-mercury.theme-dark {
  --grey-50-rgb: 255, 255, 255;
  --grey-100-rgb: 244, 244, 247;
  --grey-200-rgb: 199, 199, 204;
  --grey-300-rgb: 174, 175, 183;
  --grey-350-rgb: 129, 130, 144;
  --grey-400-rgb: 116, 116, 127;
  --grey-500-rgb: 73, 73, 80;
  --grey-600-rgb: 42, 42, 46;
  --grey-700-rgb: 33, 33, 36;
  --grey-800-rgb: 29, 29, 32;
  --grey-850-rgb: 23, 23, 26;
  --grey-875-rgb: 18, 18, 21;
  --grey-900-rgb: 12, 12, 15;
  --accent-h: 21;
  --accent-s: 92%;
  --accent-l: 69%;
}
body.encore-theme-dark-mercury.theme-dark.encore-colors-colorful {
  --highlight-hue: 50;
  --italic-color: #d2e6d2;
  --bold-color: #e0eec5;
  --h1-color: #61aafd;
  --h2-color: #5ce4ab;
  --h3-color: #50f3d8;
  --h4-color: #9adfff;
  --h5-color: #9482c5;
  --h6-color: #9482c5;
}

body.encore-theme-dark-iron.theme-dark {
  --grey-50-rgb: 255, 255, 255;
  --grey-100-rgb: 245, 240, 240;
  --grey-200-rgb: 231, 223, 219;
  --grey-300-rgb: 212, 204, 198;
  --grey-350-rgb: 147, 137, 136;
  --grey-400-rgb: 115, 105, 105;
  --grey-500-rgb: 97, 89, 87;
  --grey-600-rgb: 87, 79, 76;
  --grey-700-rgb: 57, 51, 50;
  --grey-800-rgb: 41, 36, 36;
  --grey-850-rgb: 36, 31, 31;
  --grey-875-rgb: 33, 29, 28;
  --grey-900-rgb: 28, 25, 23;
  --accent-h: 165;
  --accent-s: 74%;
  --accent-l: 52%;
  --color-red: #df2a51;
  --color-green: #2adfb2;
  --color-orange: #ff9b7c;
  --color-yellow: #abe667;
  --color-cyan: #2abbdf;
  --color-blue: #5c87ff;
}
body.encore-theme-dark-iron.theme-dark.encore-colors-colorful {
  --highlight-hue: 30;
  --italic-color: #82c0e9;
  --bold-color: #d86679;
  --h1-color: #ffc444;
  --h2-color: #faa250;
  --h3-color: #f88765;
  --h4-color: #f88773;
  --h5-color: #f88773;
  --h6-color: #f88773;
}

body.encore-theme-dark-carbon.theme-dark {
  --grey-50-rgb: 225, 227, 233;
  --grey-100-rgb: 222, 227, 241;
  --grey-200-rgb: 173, 181, 200;
  --grey-300-rgb: 162, 165,


2']]
y = df['Y']

# Создание модели
model = LinearRegression()
model.fit(X, y)

# Предсказание
y_pred = model.predict(X)

# Вывод коэффициентов
print('Коэффициенты:', model.coef_)
print('Свободный член:', model.intercept_)
```

В этом примере мы создаем модель множественной линейной регрессии, используя две независимые переменные \( X1 \) и \( X2 \) для предсказания зависимой переменной \( Y \).

# Применение линейной регрессии

## Примеры использования

Линейная регрессия широко используется в различных областях для анализа и предсказания данных. Вот несколько примеров:

1. **Экономика**: Прогнозирование цен на жилье на основе различных факторов, таких как площадь, количество комнат и местоположение.

2. **Медицина**: Оценка влияния различных факторов на здоровье пациента, например, связь между уровнем холестерина и риском сердечно-сосудистых заболеваний.

3. **Маркетинг**: Анализ влияния рекламных расходов на объем продаж, что позволяет компаниям оптимизировать свои бюджеты.

4. **Спорт**: Прогнозирование результатов матчей на основе статистики игроков и команд.

5. **Наука**: Моделирование зависимости между переменными в экспериментах, например, влияние температуры на скорость химической реакции.

## Преимущества и недостатки

### Преимущества

- **Простота**: Линейная регрессия легко понимается и интерпретируется, что делает её доступной для широкого круга пользователей.

- **Быстрота**: Модели линейной регрессии быстро обучаются и требуют относительно небольших вычислительных ресурсов.

- **Прогнозирование**: Позволяет делать предсказания на основе существующих данных, что полезно в различных областях.

- **Многофункциональность**: Может быть использована для решения как простых, так и сложных задач, включая множественную линейную регрессию.

### Недостатки

- **Линейность**: Предполагает линейную зависимость между переменными, что может не соответствовать реальным данным.

- **Чувствительность к выбросам**: Наличи


(fullName = NAME, displayState = DisplayState.Content(PRODUCTS))
        }

        sut.loadProducts()

        assertEquals(
            listOf(
                PLPScreenState(fullName = NAME),
                PLPScreenState(fullName = NAME, displayState = DisplayState.Content(PRODUCTS))
            ),
            stateObserver.getValues()
        )
    }

    @Test
    fun `EXPECT not favourite WHEN wishlist is empty`() = runTest {
        stateDelegate.updateState {
            PLPScreenState(fullName = NAME, displayState = DisplayState.Content(PRODUCTS))
        }

        val result = sut.isFavourite("2")

        assertFalse(result)
    }

    @Test
    fun `EXPECT favourite WHEN wishlist has id`() = runTest {
        stateDelegate.updateState {
            PLPScreenState(
                fullName = NAME,
                wishlistIds = listOf("2", "3"),
                displayState = DisplayState.Content(PRODUCTS)
            )
        }

        val result = sut.isFavourite("2")

        assertTrue(result)
    }

    @Test
    fun `EXPECT not favourite WHEN wishlist doesn't have id`() = runTest {
        stateDelegate.updateState {
            PLPScreenState(
                fullName = NAME,
                wishlistIds = listOf("2", "3"),
                displayState = DisplayState.Content(PRODUCTS)
            )
        }

        val result = sut.isFavourite("1")

        assertFalse(result)
    }

    @Test
    fun `EXPECT item added to wishlist`() {
        sut.addProductToWishlist(PRODUCT)

        assertEquals(listOf(WISHLIST_ITEM), addToWishlist.invocations)
    }

    @Test
    fun `EXPECT item removed from wishlist`() {
        sut.removeProductFromWishlist("1")

        assertEquals(listOf("1"), removeFromWishlist.invocations)
    }

    @Test
    fun `EXPECT item added to cart`() {
        sut.addProductToCart(PRODUCT)

        assertEquals(listOf(CART_ITEM), addCartItem.invocations)
    }

    private class TestGetProducts : GetProducts {
        lateinit var productsResult: suspend () -> Answer<List<Product>, Unit>
        override suspend fun invoke() = productsResult()
    }

    private class TestObserveUserWishlistIds : ObserveUserWishlistIds {
        val wishlistUpdates = MutableStateFlow(emptyList<String>())
        override fun invoke(): Flow<List<String>> = wishlistUpdates
    }

    private class TestAddToWishlist : AddToWishlist {
        val invocations = mutableListOf<WishlistItem>()
        override fun invoke(wishlistItem: WishlistItem) {
            invocations.add(wishlistItem)
        }
    }

    private class TestRemoveFromWishlist : RemoveFromWishlist {
        val invocations = mutableListOf<String>()
        override fun invoke(wishlistItemId: String) {
            invocations.add(wishlistItemId)
        }
    }

    private class TestAddCartItem : AddCartItem {
        val invocations = mutableListOf<CartItem>()
        override fun invoke(cartItem: CartItem) {
            invocations.add(cartItem)
        }
    }

    private companion object {
        const val NAME = "Amazing Android Dev"
        val USER = User(id = "", fullName = NAME)
        val PRODUCT = Product(
            "1",
            "Wireless Headphones",
            Money(99.99, "$"),
            "https://m.media-amazon.com/images/I/61fU3njgzZL._AC_SL1500_.jpg"
        )
        val PRODUCTS = listOf(PRODUCT)
        val WISHLIST_ITEM = WishlistItem(
            "1",
            "Wireless Headphones",
            Money(99.99, "$"),
            "https://m.media-amazon.com/images/I/61fU3njgzZL._AC_SL1500_.


发展至关重要。 6. **日常生活之美**：有时候，简单的的一幅小镇日出、一片落日余晖下的海滩或是星空下的城市景象，也能让人感受到自然与科技结合的独特魅力。 这些画面不仅展现了地球的多样性和美丽，也提醒我们保护环境的重要性。每次探索卫星地图都像是开启了一扇通往地球每一个角落的大门，每一次点击都可能带来新的发现和惊喜。  |  我先放个图： 这张图片是2018年7月16号的，地点在非洲的肯尼亚，可以看到一个巨大的“水坑”，实际上那是一块冰山。 这张照片拍摄的是冰山融化的瞬间，冰山表面的温度已经达到了0度以上，所以冰山上的雪开始融化，最终形成了一片巨大的“水坑”。 但是，这个“水坑”其实并不是真正的水坑，它只是一是一片冰山。 冰山的融化是因为全球气候变暖引起的，冰山融化之后，海平面就会升高，对人类的生存造成威胁。 所以，为了保护地球，我们应该尽可能地减少二氧化碳排放，减缓全球气候变暖。  |

## 6. 模型上传

您可以使用modelscope modelhub来将已经训练好的模型上传到ModelScope平台。您可以提前在ModelScope社区网页创建对应模型，然后将本地模型目录通过`push_model`接口进行上传；也可以直接通过`push_model`自动完成模型创建和上传

```python
from modelscope.hub.api import HubApi

YOUR_ACCESS_TOKEN = '请从ModelScope个人中心->访问令牌获取'

api = HubApi()
api.login(YOUR_ACCESS_TOKEN)
api.push_model(
    model_id="AlexEz/zhihu_bot_lora", # 用户名/模型仓库名称
    model_dir="output/qwen2-7b-instruct/v1-20240819-150005/checkpoint-371" # 本地模型目录，要求目录中必须包含configuration.json
)
```---
title: "OSINTBuddy: Transformative


lineno"> 1023     Policy,

 1024     PartitionsK

 1025     >;

 1026

 1027   static int const kPaddingM = detail::simt_transpose_padding(kWarpSize, Shape::kK, sizeof_bits<ElementA>::value);

 1028   static int const kPaddingN = detail::simt_transpose_padding(kWarpSize, Shape::kK, sizeof_bits<ElementB>::value);

 1029

 1031   using MmaPolicy = <a class="code" href="structcutlass_1_1gemm_1_1threadblock_1_1DefaultMmaCore_3_01Shape___00_01WarpShape___00_01GemmShaaf312aafe9da92ea9d417bcc12a8e7dc.html#ad8f801b18df3


using System;
using System.Collections.Generic;
using System.Text;

namespace AGS.Types
{
	public interface IGame
	{
		string DirectoryPath { get; }
		IList<GUI> GUIs { get; }
		IList<InventoryItem> InventoryItems { get; }
		IList<Character> Characters { get; }
		IList<Dialog> Dialogs { get; }
		IList<MouseCursor> Cursors { get; }
		IList<Font> Fonts { get; }
		IList<Translation> Translations { get; }
		IList<IRoom> Rooms { get; }
		/// <summary>
		/// Accesses the root view folder, which contains all views
		/// at the top level as well as sub folders.
		/// RequiredAGSVersion: 3.0.1.33
		/// </summary>
		IViewFolder Views { get; }
        /// <summary>
        /// Accesses the root sprite folder, which contains all
        /// sprites


ShouldTrack = shouldTrack;
  activeSub = computed;
  shouldTrack = true;
  try {
    prepareDeps(computed);
    const value = computed.fn(computed._value);
    if (dep.version === 0 || hasChanged(value, computed._value)) {
      computed._value = value;
      dep.version++;
    }
  } catch (err) {
    dep.version++;
    throw err;
  } finally {
    activeSub = prevSub;
    shouldTrack = prevShouldTrack;
    cleanupDeps(computed);
    computed.flags &= ~2;
  }
}
function removeSub(link, soft = false) {
  const { dep, prevSub, nextSub } = link;
  if (prevSub) {
    prevSub.nextSub = nextSub;
    link.prevSub = void 0;
  }
  if (nextSub) {
    nextSub.prevSub = prevSub;
    link.nextSub = void 0;
  }
  if (dep.subsHead === link) {
    dep.subsHead = nextSub;
  }
  if (dep.subs === link) {
    dep.subs = prevSub;
    if (!prevSub && dep.computed) {
      dep.computed.flags &= ~4;
      for (let l = dep.computed.deps; l; l = l.nextDep) {
        removeSub(l, true);
      }
    }
  }
  if (!soft && !--dep.sc && dep.map) {
    dep.map.delete(dep.key);
  }
}
function removeDep(link) {
  const { prevDep, nextDep } = link;
  if (prevDep) {
    prevDep.nextDep = nextDep;
    link.prevDep = void 0;
  }
  if (nextDep) {
    nextDep.prevDep = prevDep;
    link.nextDep = void 0;
  }
}
function effect(fn, options) {
  if (fn.effect instanceof ReactiveEffect) {
    fn = fn.effect.fn;
  }
  const e = new ReactiveEffect(fn);
  if (options) {
    extend(e, options);
  }
  try {
    e.run();
  } catch (err) {
    e.stop();
    throw err;
  }
  const runner = e.run.bind(e);
  runner.effect = e;
  return runner;
}
function stop(runner) {
  runner.effect.stop();
}
let shouldTrack = true;
const trackStack = [];
function pauseTracking() {
  trackStack.push(shouldTrack);
  shouldTrack = false;
}
function resetTracking() {
  const last = trackStack.pop();
  shouldTrack = last === void 0 ? true : last;
}
function cleanupEffect(e) {
  const { cleanup } = e;
  e.cleanup = void 0;
  if (cleanup) {
    const prevSub = activeSub;
    activeSub = void 0;
    try {
      cleanup();
    } finally {
      activeSub = prevSub;
    }
  }
}

let globalVersion = 0;
class Link {
  constructor(sub, dep) {
    this.sub = sub;
    this.dep = dep;
    this.version = dep.version;
    this.nextDep = this.prevDep = this.nextSub = this.prevSub = this.prevActiveLink = void 0;
  }
}
class Dep {
  constructor(computed) {
    this.computed = computed;
    this.version = 0;
    /**
     * Link between this dep and the current active effect
     */
    this.activeLink = void 0;
    /**
     * Doubly linked list representing the subscribing effects (tail)
     */
    this.subs = void 0;
    /**
     * For object property deps cleanup
     */
    this.map = void 0;
    this.key = void 0;
    /**
     * Subscriber counter
     */
    this.sc = 0;
    {
      this.subsHead = void 0;
    }
  }
  track(debugInf


  value_tyBM v_4Q4WBLjAPTV_5WVLmhAvCJY; // v_arg
        value_tyBM v_5wKdFyGNJ5j_50nIjxm7LLY; // v_scanres
        objectval_tyBM* o_68pH0LfBXQ1_9SRMhSZJlQV; // o_varout
        objectval_tyBM* o_6RpSqxAOt2p_35laNqeU6KH; // o_routprep
        objectval_tyBM* o_89nz0KaXXZh_8eSgMmqnK37; // o_from
        value_tyBM v_96vo6uBKhke_6E1vyN3kIKD; // v_expctx
        /// 3 local numbers:
        intptr_t n_2W7Ckt2WxEM_4NVYgEWE73B; // ii
        intptr_t n_6Y20GNUgnSZ_4LkbrcRMU8f; // i_depth
        intptr_t n_833x2jYqhZh_8vDIuJhwz1k; // leni
        /// 0 scalar values:
    } _;
    memset (&_, 0, sizeof(struct frame_1kz7viwMzTp_6PgLhdZzMEy_BMst));
    _.stkfram_head.htyp = typayl_StackFrame_BM;
    _.stkfram_head.hgc = 0;
    _.stkfram_head.rlen = 12;
    _.stkfram_descr = constob_1lhXvXtIyPu_3nhuy4kN3wd_BM[18] /*|_1kz7viwMzTp_6PgLhdZzMEy*/;
    ASSERT_BM (!stkf
               || stkf->stkfram_pA.htyp == typayl_StackFrame_BM
               || stkf->stkfram_pA.htyp == typayl_SpecialFrame_BM);
    _.stkfram_prev = stkf;
    // locking 1:
    objectval_tyBM* locked_1mO4b6i93tJ_8qQI7qdBqdy = NULL; // for o_varout
    // fetch 4 arguments:
    _.o_34Qtvf1thwK_9rziG6sk6Vl = objectcast_BM (arg0); // o_stmt
    _.o_6RpSqxAOt2p_35laNqeU6KH = objectcast_BM (arg1); // o_routprep
    _.v_4nJKFtMqlkA_1teQSqofNux = arg2; // v_depth
    _.o_89nz0KaXXZh_8eSgMmqnK37 = objectcast_BM (arg3); // o_from
    // fetched 4 arguments.
    // no closed values in _1kz7viwMzTp_6PgLhdZzMEy.
    const closure_tyBM* callclos_1kz7viwMzTp_6PgLhdZzMEy __attribute__((unused)) =
        (stkf&&stkf->stkfram_pA.htyp == typayl_StackFrame_BM)
        ? (closurecast_BM(stkf->stkfram_callfun)) : NULL;
    const unsigned nbclosed_1kz7viwMzTp_6PgLhdZzMEy  __attribute__((unused)) = 0;
    // routine _1kz7viwMzTp_6PgLhdZzMEy body:

startblock__2z5wZyWhJId_3qRwMQOiLBm:
    __attribute__((unused));
    {
        /* +block _2z5wZyWhJId_3qRwMQOiLBm */
        /*i_depth:*/_.n_6Y20GNUgnSZ_4LkbrcRMU8f = //assign _74XT4f1vWl9_7pfkRaZCCjn
            /* val_to_int */ getint_BM( /*v_depth:*/_.v_4nJKFtMqlkA_1teQSqofNux) ;

        /*o_varout:*/_.o_68pH0LfBXQ1_9SRMhSZJlQV = //assign _5nVWpRtEEts_2uWUDb4OAKl
            /*val_to_object:*/objectcast_BM(/*objgetattr:*/objgetattr_BM(( /*o_stmt:*/_.o_34Qtvf1thwK_9rziG6sk6Vl),( (constob_1lhXvXtIyPu_3nhuy4kN3wd_BM[11] /*!out*/))));

//+ #2/9 of block _2z5wZyWhJId_3qRwMQOiLBm ::

        /*leni:*/_.n_833x2jYqhZh_8vDIuJhwz1k = //assign _1a4rnGQ9X5p_4tJnSawMpZZ
            /*objnbcomps:*/ objnbcomps_BM ( /*o_stmt:*/_.o_34Qtvf1thwK_9rziG6sk6Vl);

        {
            // run _1mcZijyVnzr_1xEWETupmkp
            /*debug miniscan_stmt°basiclo_outstmt start o_stmt o_routprep depth o_from o_varout leni*/
            DBGPRINTF_BM("miniscan_stmt°basiclo_outstmt start €%.9s o_stmt=%s o_routprep=%s depth#%ld o_from=%s o_varout=%s leni#%ld",
                         "_1mcZijyVnzr_1xEWETupmkp",
                         objectdbg_BM( /*o_stmt:*/_.o_34Qtvf1thwK_9rziG6sk6Vl),
                         objectdbg1_BM( /*o_routprep:*/_.o_6RpSqxAOt2p_35laNqeU6KH),
                         (long int)( /*i_depth:*/_.n_6Y20GNUgnSZ_4LkbrcRMU8f),
                         objectdbg2_BM( /*o_from:*/_.o_89nz0KaXXZh_8eSgMmqnK37),
                         objectdbg3_BM( /*o_varout:*/_.o_68pH0LfBXQ1_9SRMhSZJlQV),
                         (long int)( /*leni:*/_.n_833x2jYqhZh_8vDIuJhwz1k));;
        } // end run _1mcZijyVnzr_1xEWETupmkp

//+ #4/9 of block _2z5wZyWhJId_3qRwMQOiLBm ::

        if /*cond _5VxN0iVhyqn_26Sl2TGladQ*/
        /*when _9AQ254qOzzB_9MWUVdb8wEe:*/
        (/*is_null:*/(( /*o_varout:*/_.o_68pH0LfBXQ1_9SRMhSZJlQV)==NULL))   //body when _9AQ254qOzzB_9MWUVdb8wEe
            {
//failure _1m5rw0BZl8f_4M9cndtjRl8
                PLACEDFAILURE_BM(__LINE__,
                                 /*failreason:*/ (((value_tyBM) makenode6_BM
                                                   (/*make_node conn:*/( (constob_1lhXvXtIyPu_3nhuy4kN3wd_BM[61] /*!failure_miss*/)),
                                                           /*make_node 6 sons:*/
                                                           ( (constob_1lhXvXtIyPu_3nhuy4kN3wd_BM[18] /*!_1kz7viwMzTp_6PgLhdZzMEy*/)),

                                                           ( (constob_1lhXvXtIyPu_3nhuy4kN3wd_BM[11] /*!out*/)),

                                                           ( /*o_stmt:*/_.o_34Qtvf1thwK_9rziG6sk6Vl),

// make_node arg #4


// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Roslyn.LanguageServer.Protocol;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.TestGenerators;
using Roslyn.Utilities;
using Xunit;
using Xunit.Abstractions;

namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.RelatedDocuments;

public sealed class RelatedDocumentsTests(ITestOutputHelper testOutputHelper)
    : AbstractLanguageServerProtocolTests(testOutputHelper)
{
    private static async Task<VSInternalRelatedDocumentReport[]> RunGetRelatedDocumentsAsync(
        TestLspServer testLspServer,
        DocumentUri uri,
        bool useProgress = false)
    {
        BufferedProgress<VSInternalRelatedDocumentReport[]>? progress = useProgress ? BufferedProgress.Create<VSInternalRelatedDocumentReport[]>(null) : null;
        var spans = await testLspServer.ExecuteRequestAsync<VSInternalRelatedDocumentParams, VSInternalRelatedDocumentReport[]>(
            VSInternalMethods.CopilotRelatedDocumentsName,
            new VSInternalRelatedDocumentParams
            {
                TextDocument = new TextDocumentIdentifier { DocumentUri = uri },
                PartialResultToken = progress,
            },
            CancellationToken.None).ConfigureAwait(false);

        if (useProgress)
        {
            Assert.Null(spans);
            spans = progress!.Value.GetFlattenedValues();
        }

        AssertEx.NotNull(spans);
        return spans;
    }

    [Theory, CombinatorialData]
    public async Task ReferenceNoDocuments(bool mutatingLspWorkspace, bool useProgress)
    {
        var markup1 = """
            class X
            {
            }
            """;

        var markup2 = """
            class Y
            {
            }
            """;

        await using var testLspServer = await CreateTestLspServerAsync([markup1, markup2], mutatingLspWorkspace);

        var project = testLspServer.TestWorkspace.CurrentSolution.Projects.Single();
        var results = await RunGetRelatedDocumentsAsync(
            testLspServer,
            project.Documents.First().GetURI(),
            useProgress: useProgress);

        Assert.Empty(results);
    }

    [Theory, CombinatorialData]
    public async Task ReferenceSingleOtherDocument(bool mutatingLspWorkspace, bool useProgress)
    {
        var markup1 = """
            class X
            {
                Y y;
            }
            """;

        var markup2 = """
            class Y
            {
            }
            """;

        await using var testLspServer = await CreateTestLspServerAsync([markup1, markup2], mutatingLspWorkspace);

        var project = testLspServer.TestWorkspace.CurrentSolution.Projects.Single();
        var results = await RunGetRelatedDocumentsAsync(
            testLspServer,
            project.Documents.First().GetURI(),
            useProgress: useProgress);

        Assert.Equal(1, results.Length);
        Assert.Equal(project.Documents.Last().FilePath, results[0].FilePaths!.Single());


4900] = "Chair",
  [174901] = "Chair",
  [174902] = "Chair",
  [174903] = "Chair",
  [174904] = "Chair",
  [174905] = "Chair",
  [174906] = "Chair",
  [174907] = "Chair",
  [174908] = "Chair",
  [174909] = "Chair",
  [174910] = "Chair",
  [174911] = "Chair",
  [174932] = "Chair",
  [174933] = "Chair",
  [174934] = "Chair",
  [174935] = "Chair",
  [174936] = "Chair",
  [174937] = "Chair",
  [174938] = "Chair",
  [174939] = "Chair",
  [174940] = "Chair",
  [174941] = "Chair",
  [174942] = "Chair",
  [174943] = "Chair",
  [174944] = "Chair",
  [174945] = "Chair",
  [174946] = "Chair",
  [174954] = "Wooden Chair",
  [174955] = "Wooden Chair",
  [174956] = "Wooden Chair",
  [174957] = "Wooden Chair",
  [174958] = "Wooden Chair",
  [174959] = "Wooden Chair",
  [174960] = "Wooden Chair",
  [174961] = "Wooden Chair",
  [174962] = "Wooden Chair",
  [174963] = "Wooden Chair",
  [174964] = "Wooden Chair",
  [174965] = "Wooden Chair",
  [174966] = "Wooden Chair",
  [174967] = "Wooden Chair",
  [174968] = "Wooden Chair",
  [174994] = "Wooden Chair",
  [174995] = "Wooden Chair",
  [174996] = "Wooden Chair",
  [174997] = "Wooden Chair",
  [174998] = "Wooden Chair",
  [175075] = "Brazier",
  [175076] = "Brazier",
  [175078] = "Anvil",
  [175080] = "Zeppelin - Grom\'Gol-Orgrimar",
  [175084] = "The Sparklematic 5200",
  [175085] = "The Sparklematic 5200",
  [175087] = "The Sparklematic 5200",
  [175104] = "Campfire",
  [175124] = "Rookery Egg",
  [175144] = "Forge",
  [175145] = "Anvil",
  [175146] = "Cooking Brazier",
  [175148] = "Doodad_UndeadCampFire25",
  [175149] = "Doodad_GeneralMedChair02",
  [175150] = "Doodad_GeneralMedChair03",
  [175151] = "Doodad_GeneralMedChair04",
  [175153] = "Emberseer Out",
  [175165] = "Silver Dawning\'s Lockbox",
  [175166] = "Mist Veil\'s Lockbox",
  [175167] = "Viewing Room Door",
  [175179] = "Campfire",
  [175180] = "Campfire",
  [175181] = "Campfire",
  [175185] = "Doodad_Drake_Rider_portcullis",
  [175186] = "Doodad_Portcullis_TOBOSSROOMS",
  [175187] = "Doodad_DarkIronDwarfRune_A01",
  [175194] = "Room 7 Rune",
  [175195] = "Room 3 Rune",
  [175196] = "Room 6 Rune",
  [175197] = "Room 1 Rune"


8uColorSobelShow_y);
	/*if(showSteps){
	cvNamedWindow("  pImage8uColorSobelShow_y",CV_WINDOW_AUTOSIZE);
	cvShowImage("  pImage8uColorSobelShow_y",pImage8uColorSobelShow_y);
	}*/

	IplImage * imgsum =cvCreateImage(cvGetSize(dst),IPL_DEPTH_32F,3);
	cvZero(imgsum);
	cvAcc(pImage8uColorSobelShow_y,imgsum);
	cvAcc(pImage8uColorSobelShow_x,imgsum);
	/*if(showSteps){
	cvNamedWindow("imgsum",1);
	cvShowImage("imgsum",imgsum);
	}*/

	IplImage * imgavg = cvCreateImage(cvGetSize(dst),IPL_DEPTH_8U,3);
	cvConvertScale(imgsum,imgavg,1.0/2.0);
	if(showSteps){
		cvNamedWindow("imgavg",1);
		cvShowImage("imgavg",imgavg);
	}

	//==================threshold=========================
	IplImage * imgBin = cvCreateImage(cvGetSize(imgavg),IPL_DEPTH_8U,1);
	cvCvtColor(imgavg,imgBin,CV_BGR2GRAY);
	cvThreshold(imgBin,imgBin,0,255,CV_THRESH_OTSU+CV_THRESH_BINARY);
	/*	int blockSize = 19;
	int constValue = 9;
	cvAdaptiveThreshold(imgPostSegEqual, imgPostSegEqualBinary, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, blockSize, constValue);*/
	if(showSteps){
		cvNamedWindow("imgBin",1);
		cvShowImage("imgBin",imgBin);
	}

	//================== imgBin  imgavg are used of input for the stroke width algorithm

	//YͶӰ ȷַ
	IplImage* painty=cvCreateImage( cvGetSize(imgBin),IPL_DEPTH_8U, 1 );
	cvZero(painty);
	int* h=new int[imgBin->height];
	memset(h,0,imgBin->height*4);

	int x,y;
	CvScalar s,t;
	for(y=0;y<imgBin->height;y++)
	{
		for(x=0;x<imgBin->width;x++)
		{
			s=cvGet2D(imgBin,y,x);
			if(s.val[0]==0)
				h[y]++;
		}
	}

	//yͶӰֵС50ĸֵΪ0
	for(y=0;y<imgBin->height;y++)   {
		if((imgBin->width-h[y]) <= 80)
			h[y] = imgBin->width;
		//	printf("%d ",imgBin->width-h[y]);
	}

	//Y խ߶ΣŵĺܳϸֱĨ
	for(x=0;x<painty->height;x++)  {
		for(y=x;y<painty->height;y++)  {
			if( (h[x] == h[y])&&(h[y] == painty->width)&&(y-x <= 6) ){
				for(int i=x;i<=y;i++){
					h[i] = painty->width;
				}
			}
			if( (h[x] != painty->width)&&(h[y] == painty->width)&&(abs(y-x) <= 6)&&((x == 0)||(y == 0)) ){
				for(int i=x;i<=y;i++){
					h[i] = painty->width;
				}
			}

		}
	}

	for(x=0;x<painty->height;x++)


"""The OurGroceries coordinator."""
from __future__ import annotations

import asyncio
from datetime import timedelta
import logging

from ourgroceries import OurGroceries

from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .const import DOMAIN

SCAN_INTERVAL = 60

_LOGGER = logging.getLogger(__name__)

class OurGroceriesDataUpdateCoordinator(DataUpdateCoordinator[dict[str, dict]]):
    """Class to manage fetching OurGroceries data."""

    def __init__(self, hass: HomeAssistant, og: OurGroceries) -> None:
        """Initialize global OurGroceries data updater."""
        self.og = og
        self.lists: list[dict] = []
        self._cache: dict[str, dict] = {}
        interval = timedelta(seconds=SCAN_INTERVAL)
        super().__init__(
            hass,
            _LOGGER,
            name=DOMAIN,
            update_interval=interval,
        )

    async def _update_list(self, list_id: str, version_id: str) -> None:
        old_version = self._cache.get(list_id, {}).get("list", {}).get("versionId", "")
        if old_version == version_id:
            return
        self._cache[list_id] = await self.og.get_list_items(list_id=list_id)

    async def _async_update_data(self) -> dict[str, dict]:
        """Fetch data from OurGroceries."""
        self.lists = (await self.og.get_my_lists())["shoppingLists"]
        await asyncio.gather(
            *[self._update_list(sl["id"], sl["versionId"]) for sl in self.lists]
        )
        return self._cache


"),
            IoError => write!(f, "I/O error while reading the config file"),
            BadFilePath(ref p, _) => write!(f, "{:?} is not a valid config path", p),
            BadEnv(ref e) => write!(f, "{:?} is not a valid `ROCKET_ENV` value", e),
            BadEntry(ref e, _) => write!(f, "{:?} is not a valid `[environment]` entry", e),
            BadType(ref n, e, a, _) => {
                write!(f, "type mismatch for '{}'. expected {}, found {}", n, e, a)
            }
            ParseError(..) => write!(f, "the config file contains invalid TOML"),
        }
    }
}
pub mod community;
pub mod dots;
pub mod home;
pub mod info;
pub mod partners;
pub mod road_map;
pub mod use_cases;

pub use self::community::Community;
pub use self::dots::get_dots_icons;
pub use self::home::Home;
pub use self::info::Info;
pub use self::partners::Partners;
pub use self::road_map::RoadMap;
pub use self::use_cases::UseCases;
<reponame>DGriffin91/Bevy-BakedGI-Demo<gh_stars>1-10
use std::num::NonZeroU8;

use bevy::{
    ecs::system::{lifetimeless::SRes, SystemParamItem},
    pbr::MaterialPipeline,
    prelude::*,
    reflect::TypeUuid,
    render::{
        render_asset::{PrepareAssetError, RenderAsset, RenderAssets},
        render_resource::{
            std140::{AsStd140, Std140},
            AddressMode, BindGroup, BindGroupDescriptor, BindGroupEntry, BindGroupLayout,
            BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingResource, BindingType, Buffer,
            BufferBindingType, BufferInitDescriptor, BufferSize, BufferUsages, FilterMode, Sampler,
            SamplerBindingType, SamplerDescriptor, ShaderStages, TextureSampleType,
            TextureViewDimension,
        },
        renderer::RenderDevice,
    },
};

// This is the struct that will be passed to your shader
#[derive(Debug, Clone, TypeUuid)]
#[uuid = "4ee9c361-1124-4113-890e-197d82b00321"]
pub struct EmissiveMaterial {
    pub emissive: Color,
    pub emissive_texture: Option<Handle<Image>>,
}

#[derive(Clone)]
pub struct GpuEmissiveMaterial {
    _buffer: Buffer,
    bind_group: BindGroup,
}

fn get_custom_sampler(render_device: &mut Res<RenderDevice>) -> Sampler {
    let mut sampler_descriptor = SamplerDescriptor::default();

    sampler_descriptor.address_mode_u = AddressMode::Repeat;
    sampler_descriptor.address_mode_v = AddressMode::Repeat;
    sampler_descriptor.mipmap_filter = FilterMode::Linear;
    sampler_descriptor.mag_filter = FilterMode::Linear;
    sampler_descriptor.min_filter = FilterMode::Linear;
    sampler_descriptor.anisotropy_clamp = NonZeroU8::new(16);

    render_device.create_sampler(&sampler_descriptor)
}

// The implementation of [`Material`] needs this impl to work properly.
impl RenderAsset for EmissiveMaterial {
    type ExtractedAsset = EmissiveMaterial;
    type PreparedAsset = GpuEmissiveMaterial;
    type Param = (
        SRes<RenderDevice>,
        SRes<MaterialPipeline<Self>>,
        SRes<RenderAssets<Image>>,
    );
    fn extract_asset(&self) -> Self::ExtractedAsset {
        self.clone()
    }

    fn prepare_asset(
        material: Self::ExtractedAsset,
        (render_device, material_pipeline, gpu_images): &mut SystemParamItem<Self::Param>,
    ) -> Result<Self::PreparedAsset, PrepareAssetError<Self::ExtractedAsset>> {
        let emissive = Vec4::from_slice(&material.emissive.as_linear_rgba_f32());
        let buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
            contents: emissive.as_std140().as_bytes(),
            label: None,
            usage:


gVersion(
    @get:Schema(title = "项目id", required = false)
    val projectId: String,
    @get:Schema(title = "流水线id", required = false)
    val pipelineId: String,

    // 流水线基础配置
    @get:Schema(title = "流水线名称", required = false)
    var pipelineName: String? = "",
    @get:Schema(title = "版本", required = false)
    var version: Int,
    @get:Schema(title = "描述", required = false)
    val desc: String?,
    @get:Schema(title = "标签列表", required = false)
    var labels: List<String>?,
    @field:BkField(patternStyle = BkStyleEnum.BUILD_NUM_RULE_STYLE, required = false)
    @get:Schema(title = "构建号生成规则", required = false)
    val buildNumRule: String?, // 构建号生成规则

    // 通知订阅相关配置
    @get:Schema(title = "订阅成功通知组", required = false)
    var successSubscriptionList: List<Subscription>?,
    @get:Schema(title = "订阅失败通知组", required = false)
    var failSubscriptionList: List<Subscription>?,

    // 运行控制、流水线禁用相关配置
    @get:Schema(title = "Lock 类型", required = false)
    val runLockType: PipelineRunLockType?,
    @get:Schema(title = "最大排队时长", required = false)
    val waitQueueTimeMinute: Int?,
    @get:Schema(title = "最大排队数量", required = false)
    val maxQueueSize: Int?,
    @field:BkField(patternStyle = BkStyleEnum.PIPELINE_CONCURRENCY_GROUP_STYLE, required = false)
    @get:Schema(title = "并发时,设定的group", required = false)
    var concurrencyGroup: String?,
    @get:Schema(title = "并发时,是否相同group取消正在执行的流水线", required = false)
    var concurrencyCancelInProgress: Boolean?,
    @get:Schema(title = "并发构建数量限制", required = false)
    var maxConRunningQueueSize: Int? = null, // MULTIPLE类型时，并发构建数量限制
    @get:Schema(title = "是否配置流水线变量值超长时终止执行", required = false)
    val failIfVariableInvalid: Boolean? = false,
    @get:Schema(title = "YAML流水线特殊配置", required = false)
    var pipelineAsCodeSettings: PipelineAsCodeSettings? = null
) {
    companion object {

        // 该方法列出所有需要作为修改比对版本的参数，如果有修改则增加版本
        fun convertFromSetting(setting: PipelineSetting) = PipelineSettingVersion(
            projectId = setting.projectId,
            pipelineId = setting.pipelineId,
            version = setting.version,
            pipelineName = setting.pipelineName,
            desc = setting.desc,
            runLockType = setting.runLockType,
            successSubscriptionList = setting.successSubscriptionList,
            failSubscriptionList = setting.failSubscriptionList,
            labels = setting.labels,
            waitQueueTimeMinute = setting.waitQueueTimeMinute,
            maxQueueSize = setting.maxQueueSize,
            buildNumRule = setting.buildNumRule,
            concurrencyCancelInProgress = setting.concurrencyCancelInProgress,
            concurrencyGroup = setting.concurrencyGroup,
            maxConRunningQueueSize = setting.maxConRunningQueueSize,
            pipelineAsCodeSettings = setting.pipelineAsCodeSettings
        )
    }
}
/*
 * Tencent is pleased to support the open source community by making BK-CI 蓝鲸持续集成平台 available.
 *
 * Copyright (C) 2019 Tencent.  All rights reserved.
 *
 * BK-CI 蓝鲸持续集成平台 is licensed under the MIT license.
 *
 * A copy of the MIT License is included in this file.
 *
 *
 * Terms of the MIT License:
 * ---------------------------------------------------
 * Permission is hereby granted, free of charge,


ndler.BatchDeleteSubjectDepartments)
	}

	// subject-groups
	{
		// 带分页 https://github.com/TencentBlueKing/bk-iam-saas/issues/1155
		r.GET("/subject-groups", handler.ListSubjectGroups)

		// subject-groups/detail?type=user&id=tome&groups=1,2,3,4,5
		r.GET("/subjects-groups/detail", handler.QuerySubjectGroupsDetail)

		// add subject-groups?type=user&id=tome&groups=1,2,3,4,5
		r.GET("/subjects-groups/belong", handler.CheckSubjectGroupsBelong)

		// subject-groups?type=user&id=tome&groups=1,2,3,4,5
		r.GET("/subjects-groups/quota", handler.CheckSubjectGroupsQuota)
	}

	// group-subject
	r.GET("/group-subject/before_expired_at", handler.ListGroupSubjectBeforeExpiredAt)

	// Resource: role-subjects
	{
		// 批量添加role subjects
		r.POST("/role-subjects", handler.BatchAddRoleSubject)
		// 批量删除role subject
		r.DELETE("/role-subjects", handler.BatchDeleteRoleSubject)
	}

	// others
	{
		// 模型变更事件
		r.GET("/model-change-event", handler.ListModelChangeEvent)
		r.PUT("/model-change-event/:event_pk", handler.UpdateModelChangeEvent)
		r.DELETE("/model-change-event", handler.BatchDeleteModelChangeEvent)

		// 清理未引用的expression
		r.DELETE("/unreferenced-expressions", handler.DeleteUnreferencedExpressions)
	}

	fg := r.Group("/freeze/subjects")
	{
		// 查询冻结用户列表
		fg.GET("", handler.ListFreezedSubjects)
		// 批量冻结
		fg.POST("", handler.BatchFreezeSubjects)
		// 批量解冻
		fg.DELETE("", handler.BatchUnfreezeSubjects)
	}
}

// RegisterV2 ...
func RegisterV2(r *gin.RouterGroup) {
	s := r.Group("/systems/:system_id")
	s.Use(common.SystemExists())
	{
		// policies 变更
		s.POST("/policies", handler.AlterPoliciesV2)

		// 查询rbac有资源实例权限的用户组
		s.POST("/rbac/resource-groups", handler.QueryRbacGroupByResource)
	}
}
/*
 * TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available.
 * Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://opensource.org/licenses/MIT
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

package handler

import (
	"errors"
	"fmt"

	"iam/pkg/api/common"

	"iam/pkg/service"
	svctypes "iam/pkg/service/types"
)

// 需要db操作的校验, 统一叫 checkXXXX
type AllResourceTypes struct {
	AllBaseInfo
	ResourceTypes []svctypes.ResourceType
}

// NewAllResourceTypes ...
func NewAllResourceTypes(resourceTypes []svctyp


node--nested-indent--base)*8)}.pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item{--pf-c-tree-view__node--PaddingLeft:calc(var(--pf-c-tree-view__node--indent--base) + var(--pf-c-tree-view__node--nested-indent--base)*9)}.pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item.pf-m-expandable{--pf-c-tree-view__node--PaddingLeft:calc(var(--pf-c-tree-view__node--indent--base) + var(--pf-c-tree-view__item--m-expandable__node--nested-indent--base)*9)}.pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item{--pf-c-tree-view__node--PaddingLeft:calc(var(--pf-c-tree-view__node--indent--base) + var(--pf-c-tree-view__node--nested-indent--base)*10)}.pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item .pf-c-tree-view__list-item.pf-m-expandable{--pf-c-tree-view__node--PaddingLeft:calc(var(--pf-c-tree-view__node--indent--base) + var(--pf-c-tree-view__item--m-expandable__node--nested-indent--base)*10)}.pf-c-wizard{--pf-c-wizard--Height:100%;--pf-c-modal-box--c-wizard--FlexBasis:47.625rem;--pf-c-wizard__header--BackgroundColor:var(--pf-global--BackgroundColor--dark-100);--pf-c-wizard__header--ZIndex:var(--pf-global--ZIndex--md);--pf-c-wizard__header--PaddingTop:var(--pf-global--spacer--lg);--pf-c-wizard__header--PaddingRight:var(--pf-global--spacer--md);--pf-c-wizard__header--PaddingBottom:var(--pf-global--spacer--lg);--pf-c-wizard__header--PaddingLeft:var(--pf-global--spacer--md);--pf-c-wizard__header--lg--PaddingRight:var(--pf-global--spacer--md);--pf-c-wizard__header--lg--PaddingLeft:var(--pf-global--spacer--md);--pf-c-wizard__header--xl--PaddingRight:var(--pf-global--spacer-


)
}

// Retry retries a function until it succeeds or the number of retries is reached.
func (s *Suite) Retry(fn func() error, retries int, interval time.Duration) (err error) {
	for i := 0; i < retries; i++ {
		err = fn()
		if err == nil {
			return nil
		}
		time.Sleep(interval)
	}
	return
}
package commands

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"

	"github.com/spf13/cobra"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/celestiaorg/talis/internal/types"
	"github.com/celestiaorg/talis/pkg/api/v1/handlers"
	"github.com/celestiaorg/talis/test"
)

func setupInfraCommand() *cobra.Command {
	// Create a new root command for testing
	cmd := &cobra.Command{
		Use:   "talis",
		Short: "Talis CLI tool",
	}

	// Add the infra command and its subcommands
	infraCmd := &cobra.Command{
		Use:   "infra",
		Short: "Manage infrastructure",
	}
	cmd.AddCommand(infraCmd)

	// Add create command
	createCmd := createInfraCmd
	createCmd.ResetFlags()
	createCmd.Flags().StringP("file", "f", "", "JSON file containing infrastructure configuration")
	_ = createCmd.MarkFlagRequired("file")
	infraCmd.AddCommand(createCmd)

	// Add delete command
	deleteCmd := deleteInfraCmd
	deleteCmd.ResetFlags()
	deleteCmd.Flags().StringP("file", "f", "", "JSON file containing infrastructure configuration")
	_ = deleteCmd.MarkFlagRequired("file")
	infraCmd.AddCommand(deleteCmd)

	return cmd
}

func TestCreateInfraCmd(t *testing.T) {
	tests := []struct {
		name           string
		args           []string
		inputFile      string
		inputContent   string
		expectedOutput string
		expectedError  string
	}{
		{
			name:      "successful create",
			args:      []string{"infra", "create", "--file", "infra.json"},
			inputFile: "infra.json",
			inputContent: fmt.Sprintf(`[
  {
    "project_name": "test-project",
    "number_of_instances": 1,
    "provider": "do",
    "region": "nyc1",
    "size": "s-1vcpu-1gb",
    "image": "ubuntu-20-04-x64",
    "ssh_key_name": "test-key-1",
    "tags": ["test", "dev"],
    "volumes": [
      {
        "name": "test-volume",
        "size_gb": 10,
        "mount_point": "/mnt/data"
      }
    ],
    "owner_id": %d
  }
]`, 1),
			expectedOutput: "Successfully created instances. A delete file has been generated:",
		},
		{
			name:          "missing file flag",
			args:          []string{"infra", "create"},
			expectedError: "required flag(s) \"file\" not set",
		},
		{
			name:          "file not found",
			args:          []string{"infra", "create", "--file", "nonexistent.json"},
			expectedError: "error validating file path",
		},
		{
			name:      "invalid JSON",
			args:      []string{"infra", "create", "--file", "invalid.json"},
			inputFile: "invalid.json",
			inputContent: `{
  "invalid": json
}`,
			expectedError: "error parsing JSON file",
		},
		{
			name:          "empty instances array",
			args:          []string{"infra", "create", "--file", "empty.json"},
			inputFile:     "empty.json",
			inputContent


 (newName.isEmpty || newName == item.name) {
          close();
          return;
        }
        if (directory.value.entries.any((e) => e.name == newName)) {
          setState(() {
            errorText = translate("Already exists");
          });
          return;
        }
        if (!PathUtil.validName(newName, options.value.isWindows)) {
          setState(() {
            if (item.isDirectory) {
              errorText = translate("Invalid folder name");
            } else {
              errorText = translate("Invalid file name");
            }
          });
          return;
        }
        await bind.sessionRenameFile(
            sessionId: sessionId,
            actId: JobController.jobID.next(),
            path: item.path,
            newName: newName,
            isRemote: !isLocal);
        close();
      }

      return CustomAlertDialog(
        content: Column(
          children: [
            DialogTextField(
              title: '${translate('Rename')} ${item.name}',
              controller: textEditingController,
              errorText: errorText,
            ),
          ],
        ),
        actions: [
          dialogButton(
            "Cancel",
            icon: Icon(Icons.close_rounded),
            onPressed: close,
            isOutline: true,
          ),
          dialogButton(
            "OK",
            icon: Icon(Icons.done_rounded),
            onPressed: submit,
          ),
        ],
        onSubmit: submit,
        onCancel: close,
      );
    });
  }
}

const _kOneWayFileTransferError = 'one-way-file-transfer-tip';

class JobController {
  static final JobID jobID = JobID();
  final jobTable = List<JobProgress>.empty(growable: true).obs;
  final jobResultListener = JobResultListener<Map<String, dynamic>>();
  final GetSessionID getSessionID;
  final GetDialogManager getDialogManager;
  SessionID get sessionId => getSessionID();
  OverlayDialogManager? get alogManager => getDialogManager();
  int _lastTimeShowMsgbox = DateTime.now().millisecondsSinceEpoch;

  JobController(this.getSessionID, this.getDialogManager);

  int getJob(int id) {
    return jobTable.indexWhere((element) => element.id == id);
  }

  // return jobID
  int addTransferJob(Entry from, bool isRemoteToLocal) {
    final jobID = JobController.jobID.next();
    jobTable.add(JobProgress()
      ..type = JobType.transfer
      ..fileName = path.basename(from.path)
      ..jobName = from.path
      ..totalSize = from.size
      ..state = JobState.inProgress
      ..id = jobID
      ..isRemoteToLocal = isRemoteToLocal);
    return jobID;
  }

  int addDeleteFileJob(Entry file, bool isRemote) {
    final jobID = JobController.jobID.next();
    jobTable.add(JobProgress()
      ..type = JobType.deleteFile
      ..fileName = path.basename(file.path)
      ..jobName = file.path
      ..totalSize = file.size
      ..state = JobState.none
      ..id = jobID
      ..isRemoteToLocal = isRemote);
    return jobID;
  }

  int addDeleteDirJob(Entry file, bool isRemote, int fileCount) {
    final jobID = JobController.jobID.next();
    jobTable.add(JobProgress()
      ..type = JobType.deleteDir
      ..fileName = path.basename(file.path)
      ..jobName = file.path
      ..fileCount = fileCount
      ..totalSize =


 _wrap_FeatureDefn_SetStyleIgnored, METH_VARARGS, (char *)"\n"
		"FeatureDefn_SetStyleIgnored(FeatureDefn self, int bIgnored)\n"
		"\n"
		"void\n"
		"OGR_FD_SetStyleIgnored(OGRFeatureDefnH hDefn, int bIgnore)\n"
		"\n"
		"Set whether the style can be omitted when fetching features.\n"
		"\n"
		"This function is the same as the C++ method\n"
		"OGRFeatureDefn::SetStyleIgnored().\n"
		"\n"
		"Parameters:\n"
		"-----------\n"
		"\n"
		"hDefn:  handle to the feature definition on witch OGRFeature are based\n"
		"on.\n"
		"\n"
		"bIgnore:  ignore state \n"
		""},
	 { (char *)"FeatureDefn_IsSame", _wrap_FeatureDefn_IsSame, METH_VARARGS, (char *)"\n"
		"FeatureDefn_IsSame(FeatureDefn self, FeatureDefn other_defn) -> int\n"
		"\n"
		"int OGR_FD_IsSame(OGRFeatureDefnH\n"
		"hFDefn, OGRFeatureDefnH hOtherFDefn)\n"
		"\n"
		"Test if the feature definition is identical to the other one.\n"
		"\n"
		"Parameters:\n"
		"-----------\n"
		"\n"
		"hFDefn:  handle to the feature definition on witch OGRFeature are\n"
		"based on.\n"
		"\n"
		"hOtherFDefn:  handle to the other feature definition to compare to.\n"
		"\n"
		"TRUE if the feature definition is identical to the other one.\n"
		"\n"
		"OGR 1.11 \n"
		""},
	 { (char *)"FeatureDefn_swigregister", FeatureDefn_swigregister, METH_VARARGS, NULL},
	 { (char *)"delete_FieldDefn", _wrap_delete_FieldDefn, METH_VARARGS, (char *)"delete_FieldDefn(FieldDefn self)"},
	 { (char *)"new_FieldDefn", (PyCFunction) _wrap_new_FieldDefn, METH_VARARGS | METH_KEYWORDS, (char *)"new_FieldDefn(char const * name_null_ok, OGRFieldType field_type) -> FieldDefn"},
	 { (char *)"FieldDefn_GetName", _wrap_FieldDefn_GetName, METH_VARARGS, (char *)"FieldDefn_GetName(FieldDefn self) -> char const *"},
	 { (char *)"FieldDefn_GetNameRef", _wrap_FieldDefn_GetNameRef, METH_VARARGS, (char *)"\n"
		"FieldDefn_GetNameRef(FieldDefn self) -> char const *\n"
		"\n"
		"const char*\n"
		"OGR_Fld_GetNameRef(OGRFieldDefnH hDefn)\n"
		"\n"
		"Fetch name of this field.\n"
		"\n"
		"This function is the same as the CPP method\n"
		"OGRFieldDefn::GetNameRef().\n"
		"\n"
		"Parameters:\n"
		"-----------\n"
		"\n"
		"hDefn:  handle to the field definition.\n"
		"\n"
		"the name of the field definition. \n"
		""},
	 { (char *)"FieldDefn_SetName", _wrap_FieldDefn_SetName, METH_VARARGS, (char *)"\n"
		"FieldDefn_SetName(FieldDefn self, char const * name)\n"
		"\n"
		"void OGR_Fld_SetName(OGRFieldDefnH\n"
		"hDefn, const char *pszName)\n"
		"\n"
		"Reset the name of this field.\n"
		"\n


  error?: E
): asserts x is NonNullable<T> {
  if (x === undefined || x === null) {
    throw error ?? new Error("assertDefined");
  }
}

export class NotFoundError extends Error {}
export const hexToRgba = (hex: string, alpha: number): string => {
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);

  if (alpha) {
    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
  } else {
    return `rgb(${r}, ${g}, ${b})`;
  }
};

export const rgbaToHex = (rgba: string): string => {
  const r = parseInt(rgba.slice(5, 7), 10);
  const g = parseInt(rgba.slice(9, 11), 10);
  const b = parseInt(rgba.slice(13, 15), 10);
  const a = parseInt(rgba.slice(17, 19), 10);

  return `#${r.toString(16)}${g.toString(16)}${b.toString(16)}${a.toString(
    16
  )}`;
};
import { arrayEquals } from '@/src/utils';
import { Image } from 'itk-wasm';
import { runWasm } from './itkWasmUtils';

const compareProps = ['size', 'direction', 'origin', 'spacing'] as const;

export function compareImageSpaces(imageA: Image, imageB: Image) {
  const equalKeys = compareProps.map((key) =>
    arrayEquals(imageA[key], imageB[key])
  );
  return equalKeys.every((b) => b);
}

export async function resample(fixed: Image, moving: Image) {
  if (compareImageSpaces(fixed, moving)) return moving; // same space, just return

  const { size, spacing, origin, direction } = fixed;
  const args = [
    '--size',
    size.join(','),
    '--spacing',
    spacing.join(','),
    '--origin',
    origin.join(','),
    '--direction',
    direction.join(','),
  ];

  return runWasm('resample', args, [moving]);
}
export default class Canvas {
    public canvas: HTMLCanvasElement;
    public context: CanvasRenderingContext2D;

    constructor() {
        this.canvas = document.getElementById('uwudp4-canvas') as HTMLCanvasElement;
        this.context = this.canvas.getContext('2d') as CanvasRenderingContext2D;
    }

    public create(height: number, width: number) {
        this.height = height;
        this.width  = width;

        this.context.fillStyle = 'black';
        this.context.fillRect(0, 0, width, height);
        this.context.save();
    }

    public clear() {
        const restore = this.context.fillStyle;
        this.context.fillStyle = 'black';
        this.context.clearRect(0, 0, this.width, this.height);
        this.context.fillRect(0, 0, this.width, this.height);
        this.context.fillStyle = restore;
    }

    get width(): number { return this.canvas.width; }
    set width(w: number) { this.canvas.width = w; }
    get height(): number { return this.canvas.width; }
    set height(h: number) { this.canvas.height = h; }
}/**
 * RunItem - interface for a run item.
 */
export interface RunItem {
  runId: number;
  workId: number;
  routeNumber: number;
  runNumber: number;
  daysOn: string;
  releasePoint: string;
  timeOn: string;
  timeOff: string;
  endPoint: string;
  platformTime: string;
  reportTime: string;
  travelTime: string;
  pays: string;
  spreadTime: string;
  specialDetails: string;
  isShowUp: boolean;
}

/**
 * WorkItem - interface for work item.
 */
export inter


'',	'',	'',	'',	'',	'',	'',	'',	'',	'2024/11/20 12:00:00',	'2025/04/30 11:00:00',	'1',	'1',	'0',	'0',	'2',	'',	'',	'',	'获得纳格陵【帘后秘语】的时装'},
{'50058',	'50058',	'13',	'4',	'3',	'',	'',	'焰火飞行',	'',	'',	'',	'10260_Skin124_mall',	'',	'',	'5',	'1',	'[[31026003,1,2]]',	'',	'[[10002,980]]',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'2024/12/23 12:00:00',	'2025/04/30 11:00:00',	'1',	'1',	'0',	'0',	'2',	'',	'',	'',	'获得纳格陵【帘后秘语】的时装'},
{'50059',	'50059',	'12',	'4',	'3',	'',	'',	'逃脱魔术',	'',	'',	'',	'20080_Skin124_mall',	'',	'',	'5',	'1',	'[[32008004,1,2]]',	'',	'[[10002,1080]]',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'2024/12/23 12:00:00',	'2025/04/30 11:00:00',	'1',	'1',	'0',	'0',	'2',	'',	'',	'',	'获得纳格陵【帘后秘语】的时装'},
{'50060',	'50060',	'11',	'4',	'3',	'',	'',	'不夜女王',	'',	'',	'',	'20230_Skin124_mall',	'',	'',	'5',	'1',	'[[32023004,1,2]]',	'',	'[[10002,1080]]',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'2025/01/01 12:00:00',	'2025/04/30 11:00:00',	'1',	'1',	'0',	'0',	'2',	'',	'',	'',	'获得纳格陵【帘后秘语】的时装'},
{'50061',	'50061',	'1',	'4',	'3',	'',	'',	'诱惑束缚',	'',	'',	'',	'30430_Skin124_mall',	'30431_Skin124_mall',	'',	'5',	'1',	'[[33043003,1,2],[33043102,1,2]]',	'',	'[[-1,198]]',	'[[10002,2480]]',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'',	'2024/12/23 12:00:00',	'2025/04/30 11:00:00',	'1',	'1',	'0',	'0',	'2',	'',	'',	'',	'获得纳格陵【帘后秘语】的时装'},
{'50


 cadete ancora [in errore], dopo che avete ricevuto le prove, sappiate allora che Allah è eccelso, saggio."
  },
  {
    "surah_number": 2,
    "verse_number": 210,
    "content":
        "Forse aspettano che Allah venga, avvolto di ombre di nuvole e con gli angeli? Ma tutto è ormai deciso ed è ad Allah che ritorna ogni cosa."
  },
  {
    "surah_number": 2,
    "verse_number": 211,
    "content":
        "Chiedi ai figli di Israele quanti segni evidenti abbiamo inviato loro. Ebbene, chi altera il favore di Allah, dopo che esso gli è giunto, allora veramente Allah è violento nel castigo."
  },
  {
    "surah_number": 2,
    "verse_number": 212,
    "content":
        "Ai miscredenti abbiamo reso piacevole la vita terrena ed essi scherniscono i credenti. Ma coloro che saranno stati timorati saranno superiori a loro nel Giorno della Resurrezione. Allah dà a chi vuole, senza contare."
  },
  {
    "surah_number": 2,
    "verse_number": 213,
    "content":
        "Gli uomini formavano un'unica comunità. Allah poi inviò loro i profeti, in qualità di nunzi e ammonitori; fece scendere su di loro la Scrittura con la verità, affinché si ponesse come criterio tra le genti a proposito di ciò su cui divergevano. E disputarono, ribelli gli uni contro gli altri, proprio coloro che lo avevano. Eppure erano giunte loro le prove! Allah, con la Sua volontà, guidò coloro che cedettero a quella parte di Verità sulla quale gli altri litigavano. Allah guida chi vuole sulla retta Via."
  },
  {
    "surah_number": 2,
    "verse_number": 214,
    "content":
        "Credete forse che entrerete nel Paradiso, senza provare quello che provarono coloro che furono prima di voi? Furono toccati da disgrazie e calamità e furono talmente scossi, che il Messaggero e coloro che erano con lui gridarono: “Quando verrà il soccorso di Allah?”. Non è forse vicino il soccorso di Allah?"
  },
  {
    "surah_number": 2,
    "verse_number": 215,
    "content":
        "Ti chiederanno: “Cosa dobbiamo dare in elemosina?”. Di': “I beni che erogate siano destinati ai genitori, ai parenti, agli orfani, ai poveri e ai viandanti diseredati. E Allah conosce tutto il bene che fate”."
  },
  {
    "surah_number": 2,
    "verse_number": 216,
    "content":
        "Vi è stato ordinato di combattere, anche se non lo gradite. Ebbene, è possibile che abbiate avversione per qualcosa che invece è un bene per voi, e può darsi che amiate una cosa, che invece vi è nociva. Allah sa e voi non sapete."
  },
  {
    "surah_number": 2,
    "verse_number": 217,
    "content":
        "Ti chiedono del combattimento nel mese sacro. Di': “Combattere in questo tempo è un grande peccato, ma più grave è frapporre ostacoli sul sentiero di Allah e distogliere da Lui e dalla Santa Moschea. Ma, di fronte ad Allah, peggio ancora è scacciarne gli abitanti. L'oppressione è peggiore dell'omicidio. Ebbe


180) | ("R", 180) => {
                facing_x = -facing_x;
                facing_y = -facing_y;
            }
            ("L", 270) | ("R", 90) => {
                swap(&mut facing_x, &mut facing_y);
                facing_y = -facing_y;
            }
            _ => panic!(),
        }
    }

    println!("{}", x.abs() + y.abs());
}
<gh_stars>0
use mvt::{decode, Tile, FeatureWithJson};

use glob::glob;
use std::fs::File;
use std::io::prelude::*;
use std::path::{PathBuf, Path};

use serde::{Serialize, Deserialize};

use git2::Repository;

#[derive(Debug, Serialize, Deserialize)]
struct Validity {
    v1: bool,
    v2: bool,
    #[serde(default)]
    error: String
}

#[derive(Debug, Serialize, Deserialize)]
struct Info {
    description: String,
    specification_reference: String,
    validity: Validity,
    proto: String
}

#[test]
fn decode_fixtures() {
    if !Path::new("fixtures").exists() {
        let url = "https://github.com/mapbox/mvt-fixtures";
        match Repository::clone(url, "fixtures") {
            Err(e) => panic!("failed to clone: {}", e),
            _ => ()
        };
    }

    let tiles = glob("./fixtures/fixtures/**/tile.mvt").unwrap();

    for tile in tiles {
        let path = tile.unwrap();
        println!("{:?}", path);

        // Test cases which we cannot process due to different reasons
        if path == PathBuf::from("fixtures/fixtures/014/tile.mvt") ||
           path == PathBuf::from("fixtures/fixtures/023/tile.mvt") ||
           path == PathBuf::from("fixtures/fixtures/024/tile.mvt") ||
           path == PathBuf::from("fixtures/fixtures/030/tile.mvt") ||
           path == PathBuf::from("fixtures/fixtures/061/tile.mvt") {
            continue;
        }

        // Parse test info
        let json_info_path = path.parent().unwrap().join("info.json");
        let mut f_info = File::open(&json_info_path).unwrap();
        let mut info_str = String::new();
        f_info.read_to_string(&mut info_str).unwrap();
        let i: Info = serde_json::from_str(&info_str).unwrap();

        // Parse protobuf
        let mut f_tile = File::open(&path).unwrap();
        let mut buffer = Vec::new();
        f_tile.read_to_end(&mut buffer).unwrap();
        let tile = decode::<FeatureWithJson>(&buffer);
        let tile = match tile {
            Ok(t) => t,
            Err(error) => {
                assert!(!i.validity.v1 || !i.validity.v2, error);
                continue;
            },
        };
        println!("{:#?}", tile);
        // Parse json reference
        let json_tile_path = path.parent().unwrap().join("tile.json");
        let mut f_json = File::open(&json_tile_path).unwrap();
        let mut json = String::new();
        f_json.read_to_string(&mut json).unwrap();
        let reference = serde_json::from_str::<Tile<FeatureWithJson>>(&json);
        match reference {
            Ok(r) => {
                assert_eq!(r, tile);
            },
            Err(error) => {
                println!("{}", error);
                assert!(!i.validity.v1 || !i.validity.v2, error);
            },
        };
    }
}<reponame>ngi-nix/reowolf

use std::collections::VecDeque;

use super::value


lhost:8080';

    constructor(private $httpClient: HttpClient) {
        this._credentials = JSON.parse(sessionStorage.getItem(credentialsKey) || localStorage.getItem(credentialsKey));
    }

    /**
     * Authenticates the user.
     * @param {LoginContext} context The login parameters.
     * @return {Observable<Credentials>} The user credentials.
     */
    login(context: LoginContext): Observable<Credentials> {
        return this.$httpClient.post<Credentials>(this.baseURL + '/user/login', JSON.stringify(context))
            .map((data: Credentials) => {
                console.log(data);
                this.setCredentials(data, context.remember);
                return data;
            }, (err: HttpErrorResponse) => {
                console.error(err.message);
            });

    }

    loginFacebook(authToken: string): Observable<Credentials> {
        return this.$httpClient.post<Credentials>(this.baseURL + '/oauth/facebook/login', authToken)
            .map((data: Credentials) => {
                this.setCredentials(data, true);
                return data;
            }, (err: HttpErrorResponse) => {
                console.error(err.message);
            });
    }

    /**
     * Logs out the user and clear credentials.
     * @return {Observable<boolean>} True if the user was logged out successfully.
     */
    logout(): Observable<boolean> {
        // Customize credentials invalidation here
        this.setCredentials();
        return Observable.of(true);
    }

    /**
     * Checks is the user is authenticated.
     * @return {boolean} True if the user is authenticated.
     */
    isAuthenticated(): boolean {
        return !!this.credentials;
    }

    /**
     * Gets the user credentials.
     * @return {Credentials} The user credentials or null if the user is not authenticated.
     */
    get credentials(): Credentials {
        return this._credentials;
    }

    /**
     * Sets the user credentials.
     * The credentials may be persisted across sessions by setting the `remember` parameter to true.
     * Otherwise, the credentials are only persisted for the current session.
     * @param {Credentials=} credentials The user credentials.
     * @param {boolean=} remember True to remember credentials across sessions.
     */
    private setCredentials(credentials?: Credentials, remember?: boolean) {
        this._credentials = credentials || null;

        if (credentials) {
            const storage = remember ? localStorage : sessionStorage;
            storage.setItem(credentialsKey, JSON.stringify(credentials));
        } else {
            sessionStorage.removeItem(credentialsKey);
            localStorage.removeItem(credentialsKey);
        }
    }

}
import { EC2 } from "aws-sdk";

type SnapshotProgress = {
  state: string;
  progress: string;
  volumeSize: number;
};

export const checkSnapshotProgress = async (SnapshotId: string): Promise<SnapshotProgress> => {
  const ec2 = new EC2();
  const params = {
    SnapshotIds: [SnapshotId],
  };
  const snapshotAttribute = await ec2.describeSnapshots(params).promise();
  const snapshot = snapshotAttribute?.Snapshots?.[0];

  if (!snapshot || !snapshot.State || !snapshot.Progress || !snapshot.VolumeSize) {
    throw new Error(`Snapshot ${SnapshotId} is missing or has missing required attributes.`);
  }

  return {
    state: snapshot.State,
    progress: snapshot.Progress,
    volumeSize: snapshot.VolumeSize,
  };
};
import { ClaimFormFactory } from './claim-form.factory';
import { TicketFactoryT } from './ticket.factory.abstract';