if (!hasRemoteMatch(config.domains, config.remotePatterns, parsedSrc)) {\n                    throw new Error(\"Invalid src prop (\" + src + ') on `next/image`, hostname \"' + parsedSrc.hostname + '\" is not configured under images in your `next.config.js`\\n' + \"See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host\");\n                }\n            }\n        }\n    }\n    return config.path + \"?url=\" + encodeURIComponent(src) + \"&w=\" + width + \"&q=\" + (quality || 75) + ( false ? 0 : \"\");\n}\n// We use this to determine if the import is the default loader\n// or a custom loader defined by the user in next.config.js\ndefaultLoader.__next_img_default = true;\nconst _default = defaultLoader; //# sourceMappingURL=image-loader.js.map\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiKHNzcikvLi9ub2RlX21vZHVsZXMvbmV4dC9kaXN0L3NoYXJlZC9saWIvaW1hZ2UtbG9hZGVyLmpzIiwibWFwcGluZ3MiOiI7Ozs7MkNBeUZBOzs7ZUFBQUE7OztBQXZGQSxTQUFTQyxjQUFjQyxLQUtNO0lBTE4sTUFDckJDLE1BQU0sRUFDTkMsR0FBRyxFQUNIQyxLQUFLLEVBQ0xDLE9BQU8sRUFDb0IsR0FMTko7SUFNckIsSUFBSUssSUFBeUIsRUFBYztRQUN6QyxNQUFNQyxnQkFBZ0IsRUFBRTtRQUV4Qix5REFBeUQ7UUFDekQsSUFBSSxDQUFDSixLQUFLSSxjQUFjQyxJQUFJLENBQUM7UUFDN0IsSUFBSSxDQUFDSixPQUFPRyxjQUFjQyxJQUFJLENBQUM7UUFFL0IsSUFBSUQsY0FBY0UsTUFBTSxHQUFHLEdBQUc7WUFDNUIsTUFBTSxJQUFJQyxNQUNSLHNDQUFvQ0gsY0FBY0ksSUFBSSxDQUNwRCxRQUNBLGdHQUErRkMsS0FBS0MsU0FBUyxDQUM3RztnQkFBRVY7Z0JBQUtDO2dCQUFPQztZQUFRO1FBRzVCO1FBRUEsSUFBSUYsSUFBSVcsVUFBVSxDQUFDLE9BQU87WUFDeEIsTUFBTSxJQUFJSixNQUNSLDBCQUF3QlAsTUFBSTtRQUVoQztRQUVBLElBQUlBLElBQUlXLFVBQVUsQ0FBQyxRQUFRWixPQUFPYSxhQUFhLEVBQUU7WUFDL0MsSUFDRVQsSUFFNkIsRUFDN0I7Z0JBQ0EsdUVBQXVFO2dCQUN2RSxNQUFNLEVBQUVZLGFBQWEsRUFBRSxHQUFHQyxtQkFBQUEsQ0FBUTtnQkFDbEMsSUFBSSxDQUFDRCxjQUFjaEIsT0FBT2EsYUFBYSxFQUFFWixNQUFNO29CQUM3QyxNQUFNLElBQUlPLE1BQ1IsdUJBQXFCUCxNQUFJLGtHQUN0QjtnQkFFUDtZQUNGO1FBQ0Y7UUFFQSxJQUFJLENBQUNBLElBQUlXLFVBQVUsQ0FBQyxRQUFTWixDQUFBQSxPQUFPa0IsT0FBTyxJQUFJbEIsT0FBT21CLGNBQWMsR0FBRztZQUNyRSxJQUFJQztZQUNKLElBQUk7Z0JBQ0ZBLFlBQVksSUFBSUMsSUFBSXBCO1lBQ3RCLEVBQUUsT0FBT3FCLEtBQUs7Z0JBQ1pDLFFBQVFDLEtBQUssQ0FBQ0Y7Z0JBQ2QsTUFBTSxJQUFJZCxNQUNSLDBCQUF3QlAsTUFBSTtZQUVoQztZQUVBLElBQ0VHLElBRTZCLEVBQzdCO2dCQUNBLHVFQUF1RTtnQkFDdkUsTUFBTSxFQUFFcUIsY0FBYyxFQUFFLEdBQUdSLG1CQUFBQSxDQUFRO2dCQUNuQyxJQUFJLENBQUNRLGVBQWV6QixPQUFPa0IsT0FBTyxFQUFFbEIsT0FBT21CLGNBQWMsRUFBRUMsWUFBWTtvQkFDckUsTUFBTSxJQUFJWixNQUNSLHVCQUFxQlAsTUFBSSxrQ0FBaUNtQ


, int size){
            for (int index = size - 1; index >= 0; --index)
                dstptr[index] = srcptr[index];
        }

        public static byte* AllocAndZero(int bytes){
            var ptr = (byte*) (Marshal.AllocHGlobal(bytes).ToPointer());
            Zero(ptr, bytes);
            return ptr;
        }

        public static void NullPointer(){
            throw new NullReferenceException("Method invoked on null pointer.");
        }

        public static void ArrayOutOfRange(){
            throw new ArgumentOutOfRangeException("Array index out of range");
        }
    }
}


-31.862 5.559-44.14 16.88-12.326 11.308-18.422 25.029-18.422 41.218 0 16.339 6.074 30.26 18.422 41.783 12.326 11.581 27.114 17.299 44.14 17.299h416.466c-39.733 6.324-75.81 19.515-108.119 39.845-32.524 20.381-59.397 46.122-80.607 77.347h-227.626c-17.171 0-31.862 5.682-44.14 17.021-12.326 11.306-18.422 24.946-18.422 41.218 0 16.218 6.074 30.164 18.422 41.696 12.326 11.581 27.114 17.299 44.14 17.299l182.749 0.002zM448.177 779.497z"  ></path></symbol><symbol id="icow-shanchu5" viewBox="0 0 1024 1024"><path d="M920.17126 829.921793 603.27175 513.023306 920.17126 196.123796 829.921793 105.875353 513.023306 422.773839 196.123796 105.875353 105.875353 196.123796 422.773839 513.023306 105.875353 829.921793 196.123796 920.17126 513.023306 603.27175 829.921793 920.17126Z"  ></path></symbol><symbol id="icow-sysset" viewBox="0 0 1024 1024"><path d="M826.961 699.97c32.739-56.275 92.663-85.831 149.2-79.14 8.272-35.178 12.654-71.854 12.654-109.555 0-33.259-3.41-65.719-9.89-97.058-57.249 7.573-118.263-22.258-151.225-79.445-33.492-58.108-28.027-127.12 8.786-172.869-50.563-46.981-111.34-83.117-178.63-104.714-20.875 55.378-78.288 95.159-145.855 95.159-67.568 0-124.982-39.781-145.855-95.159-66.658 21.394-126.922 57.058-177.199 103.397 36.633 45.898 41.821 114.935 8.093 172.911-33.196 57.059-94.34 86.644-151.564 78.831-6.737 31.923-10.29 65.020-10.29 98.948 0 37.031 4.222 73.076 12.21 107.68 56.572-6.476 116.389 23.324 148.906 79.74 31.952 55.438 28.453 120.804-3.903 166.422 50.604 45.737 111.062 80.775 177.813 101.536 23.611-50.305 78.205-85.536 141.789-85.536 63.585 0 118.178 35.231 141.789 85.536 66.128-20.567 126.078-55.149 176.393-100.26-32.163-45.747-35.395-111.121-3.221-166.422zM512 718.602c-114.503 0-207.327-92.823-207.327-207.327s92.823-207.327 207.327-207.327c114.503 0 207.327 92.823 207.327 207.327s-92.823 207.327-207.327 207.327z"  ></path></symbol><symbol id="icow-iconmingchengpaixu65" viewBox="0 0 1024 1024"><path d="M660.768 289.824c4.16-7.136 4.16-19.136 0-26.3


 := range knowledgeIDs {
							assert.Equal(t, "100100", knowledgeIDs[idx].(string))
						}
					case entity.NodeTypeDatabaseCustomSQL, entity.NodeTypeDatabaseQuery, entity.NodeTypeDatabaseInsert, entity.NodeTypeDatabaseDelete, entity.NodeTypeDatabaseUpdate:
						for _, d := range node.Data.Inputs.DatabaseInfoList {
							assert.Equal(t, "100100", d.DatabaseInfoID)
						}

					}

				}
			}

			validateSubWorkflowIDs(canvas.Nodes)
			return nil

		}

		defer mockey.Mock(appworkflow.PublishWorkflowResource).To(mockPublishWorkflowResource).Build().UnPatch()

		defer mockey.Mock((*appknowledge.KnowledgeApplicationService).CopyKnowledge).Return(&modelknowledge.CopyKnowledgeResponse{
			TargetKnowledgeID: 100100,
		}, nil).Build().UnPatch()

		mockCopyDatabase := func(ctx context.Context, req *appmemory.CopyDatabaseRequest) (*appmemory.CopyDatabaseResponse, error) {
			es := make(map[int64]*entity4.Database)
			for _, id := range req.DatabaseIDs {
				es[id] = &entity4.Database{ID: 100100}
			}
			return &appmemory.CopyDatabaseResponse{
				Databases: es,
			}, nil
		}

		defer mockey.Mock((*appmemory.DatabaseApplicationService).CopyDatabase).To(mockCopyDatabase).Build().UnPatch()

		defer mockey.Mock((*appplugin.PluginApplicationService).CopyPlugin).Return(&dto.CopyPluginResponse{
			Plugin: &entity5.PluginInfo{
				PluginInfo: &pluginmodel.PluginInfo{
					ID:      time.Now().Unix(),
					Version: ptr.Of("v0.0.1"),
				},
			},
		}, nil).Build().UnPatch()

		appIDInt64 := int64(7516515408422109184)

		r.load("copy_to_app/child2_1.json", withID(7516518409656336384), withProjectID(appIDInt64))
		r.load("copy_to_app/main2.json", withID(7516516198096306176), withProjectID(appIDInt64))

		_, ret, err := appworkflow.SVC.CopyWorkflowFromAppToLibrary(t.Context(), 7516516198096306176, 123, appIDInt64)
		assert.NoError(t, err)
		assert.Equal(t, 0, len(ret))
	})
}

func TestMoveWorkflowAppToLibrary(t *testing.T) {
	mockey.PatchConvey("test move workflow", t, func() {
		r := newWfTestRunner(t)
		r.publishPatcher.UnPatch()
		defer r.closeFn()
		vars := map[string]*vo.TypeInfo{
			"app_v1": {
				Type: vo.DataTypeString,
			},
			"app_list_v1": {
				Type: vo.DataTypeArray,
				ElemTypeInfo: &vo.TypeInfo{
					Type: vo.DataTypeString,
				},
			},
			"app_list_v2": {
				Type: vo.DataTypeString,
			},
		}

		r.varGetter.EXPECT().GetAppVariablesMeta(gomock.Any(), gomock.Any(), gomock.Any()).Return(vars, nil).AnyTimes()
		t.Run("move workflow", func(t *testing.T) {

			var mockPublishWorkflowResource func(ctx context.Context, workflowID int64, mode *int32, op search.OpType, r *search.ResourceDocument) error

			named2Idx := []string{"c1", "c2", "cc1", "main"}
			callCount := 0
			initialWf2ID := map[string]int64{}
			old2newID := map[int64]int64{}
			mockPublishWorkflowResource = func(ctx context.Context, workflowID int64, mode *int32,


te);
    if (s.isEmpty) {
      return;
    }

    try {
      final m = jsonDecode(s);
      if (m != null) {
        _pin = RxBool(m['pin'] ?? false);
      }
    } catch (e) {
      debugPrint('Failed to decode toolbar state ${e.toString()}');
    }
  }

  bool get pin => _pin.value;

  switchShow(SessionID sessionId) async {
    bind.sessionToggleOption(
        sessionId: sessionId, value: kOptionCollapseToolbar);
    show.value = !show.value;
  }

  initShow(SessionID sessionId) async {
    if (!isShowInited) {
      show.value = !(await bind.sessionGetToggleOption(
              sessionId: sessionId, arg: kOptionCollapseToolbar) ??
          false);
      isShowInited = true;
    }
  }

  switchPin() async {
    _pin.value = !_pin.value;
    // Save everytime changed, as this func will not be called frequently
    await _savePin();
  }

  setPin(bool v) async {
    if (_pin.value != v) {
      _pin.value = v;
      // Save everytime changed, as this func will not be called frequently
      await _savePin();
    }
  }

  _savePin() async {
    bind.setLocalFlutterOption(
        k: kOptionRemoteMenubarState, v: jsonEncode({'pin': _pin.value}));
  }
}

class _ToolbarTheme {
  static const Color blueColor = MyTheme.button;
  static const Color hoverBlueColor = MyTheme.accent;
  static Color inactiveColor = Colors.grey[800]!;
  static Color hoverInactiveColor = Colors.grey[850]!;

  static const Color redColor = Colors.redAccent;
  static const Color hoverRedColor = Colors.red;
  // kMinInteractiveDimension
  static const double height = 20.0;
  static const double dividerHeight = 12.0;

  static const double buttonSize = 32;
  static const double buttonHMargin = 2;
  static const double buttonVMargin = 6;
  static const double iconRadius = 8;
  static const double elevation = 3;

  static double dividerSpaceToAction = isWindows ? 8 : 14;

  static double menuBorderRadius = isWindows ? 5.0 : 7.0;
  static EdgeInsets menuPadding = isWindows
      ? EdgeInsets.fromLTRB(4, 12, 4, 12)
      : EdgeInsets.fromLTRB(6, 14, 6, 14);
  static const double menuButtonBorderRadius = 3.0;

  static Color borderColor(BuildContext context) =>
      MyTheme.color(context).border3 ?? MyTheme.border;

  static Color? dividerColor(BuildContext context) =>
      MyTheme.color(context).divider;

  static MenuStyle defaultMenuStyle(BuildContext context) => MenuStyle(
        side: MaterialStateProperty.all(BorderSide(
          width: 1,
          color: borderColor(context),
        )),
        shape: MaterialStatePropertyAll(RoundedRectangleBorder(
            borderRadius:
                BorderRadius.circular(_ToolbarTheme.menuBorderRadius))),
        padding: MaterialStateProperty.all(_ToolbarTheme.menuPadding),
      );
  static final defaultMenuButtonStyle = ButtonStyle(
    backgroundColor: MaterialStatePropertyAll(Colors.transparent),
    padding: MaterialStatePropertyAll(EdgeInsets.zero),
    overlayColor: MaterialStatePropertyAll(Colors.transparent),
  );

  static Widget borderWrapper(
      BuildContext context, Widget child, BorderRadius borderRadius) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(
          color: borderColor(context),
          width: 1,
        ),


h.useCallback(Qe=>{G.debug(`Set grid density to ${Qe}`),C.current.setState(Ie=>{const Fe=kn(Ie),_e={value:Qe,factor:a2[Qe]};return Ot(Fe,_e)?Ie:(0,m.Z)({},Ie,{density:_e})}),C.current.forceUpdate()},[G,C]);h.useEffect(()=>{C.current.setDensity(_.density)},[C,_.density]),an(C,{setDensity:le},"public")};function yl(C,_="csv",G=document.title||"untitled"){const le=`${G}.${_}`;if("download"in HTMLAnchorElement.prototype){const me=URL.createObjectURL(C),Qe=document.createElement("a");Qe.href=me,Qe.download=le,Qe.click(),setTimeout(()=>{URL.revokeObjectURL(me)});return}throw new Error("MUI: exportAs not supported")}const o2=({apiRef:C,options:_})=>{const G=Kt(C);return _.fields?_.fields.reduce((me,Qe)=>{const Ie=G.find(Fe=>Fe.field===Qe);return Ie&&me.push(Ie),me},[]):(_.allColumns?G:En(C)).filter(me=>!me.disableExport)},bl=({apiRef:C})=>{var _,G;const le=$e(C),me=oa(C),Qe=C.current.getSelectedRows(),Ie=le.filter(je=>me[je].type!=="footer"),Fe=$a(C),_e=(Fe==null||(_=Fe.top)==null?void 0:_.map(je=>je.id))||[],Ye=(Fe==null||(G=Fe.bottom)==null?void 0:G.map(je=>je.id))||[];return Ie.unshift(..._e),Ie.push(...Ye),Qe.size>0?Ie.filter(je=>Qe.has(je)):Ie};var Ps=t(33797);const vl=["hideMenu","options"],El=["hideMenu","options"],X0=null;function xl(C){const _=Ga(),{hideMenu:G,options:le}=C,me=(0,u.Z)(C,vl);return(0,st.jsx)(Ps.Z,(0,m.Z)({onClick:()=>{_.current.exportDataAsCsv(le),G==null||G()}},me,{children:_.current.getLocaleText("toolbarExportCSV")}))}function Cl(C){const _=Ga(),{hideMenu:G,options:le}=C,me=(0,u.Z)(C,El);return(0,st.jsx)(Ps.Z,(0,m.Z)({onClick:()=>{_.current.exportDataAsPrint(le),G==null||G()}},me,{children:_.current.getLocaleText("toolbarExportPrint")}))}const J0=null,Ll=(C,_)=>{const G=yo(C,"useGridCsvExport"),le=_.unstable_ignoreValueFormatterDuringExport,me=(typeof le=="object"?le==null?void 0:le.csvExport:le)||!1,Qe=h.useCallback((Ye={})=>{var je,it,ft;G.debug("Get data as CSV");const xt=o2({apiRef:C,options:Ye}),vt=((je=Ye.getRowsToExport)!=null?je:bl)({apiRef:C});return Rt({columns:xt,rowIds:vt,delimiterCharacter:Ye.delimiter||",",includeHeaders:(it=Ye.includeHeaders)!=null?it:!0,includeColumnGroupsHeaders:(ft=Ye.includeColumnGroupsHeaders)!=null?ft:!0,ignoreValueFormatter:me,apiRef:C})},[G,C,me]),Ie=h.useCallback(Ye=>{G.debug("Export data as CSV");const je=Qe(Ye),it=new Blob([Ye!=null&&Ye.utf8WithBom?new Uint8Array([239,18


using Android.App;
using Android.Content;
using Android.OS;
using Application = Android.App.Application;

namespace MauiPerfDebugOverlay.Platforms
{
    public static class BatteryService
    {
        private static readonly BatteryManager _batteryManager;
        private static readonly IntentFilter _batteryFilter;

        static BatteryService()
        {
            _batteryManager = Application.Context.GetSystemService(Context.BatteryService) as BatteryManager;
            _batteryFilter = new IntentFilter(Intent.ActionBatteryChanged);


t.firstWhereOrNull((e) => e.value == groupValue.value);
    if (e != null) {
      valueText.value = e.label;
    }
  }

  init();

  void showDialog() async {
    gFFI.dialogManager.show((setState, close, context) {
      final onChanged = asyncSetter == null
          ? null
          : (String? value) async {
              if (value == null) return;
              await asyncSetter(value);
              init();
              if (value != notCloseValue) {
                close();
              }
            };

      return CustomAlertDialog(
          content: Obx(
        () => Column(children: [
          ...list
              .map((e) => getRadio(Text(translate(e.label)), e.value,
                  groupValue.value, onChanged))
              .toList(),
          Offstage(
            offstage:
                !(tail != null && showTail != null && showTail.value == true),
            child: tail,
          ),
        ]),
      ));
    }, backDismiss: true, clickMaskDismiss: true);
  }

  return SettingsTile(
    title: Text(translate(title)),
    onPressed: asyncSetter == null ? null : (context) => showDialog(),
    value: Padding(
      padding: EdgeInsets.symmetric(vertical: 8),
      child: Obx(() => Text(translate(valueText.value))),
    ),
  );
}
import 'dart:async';
import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hbb/common/shared_state.dart';
import 'package:flutter_hbb/common/widgets/setting_widgets.dart';
import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/models/peer_model.dart';
import 'package:flutter_hbb/models/peer_tab_model.dart';
import 'package:flutter_hbb/models/state_model.dart';
import 'package:get/get.dart';
import 'package:qr_flutter/qr_flutter.dart';

import '../../common.dart';
import '../../models/model.dart';
import '../../models/platform_model.dart';
import 'address_book.dart';

void clientClose(SessionID sessionId, OverlayDialogManager dialogManager) {
  msgBox(sessionId, 'info', 'Close', 'Are you sure to close the connection?',
      '', dialogManager);
}

abstract class ValidationRule {
  String get name;
  bool validate(String value);
}

class LengthRangeValidationRule extends ValidationRule {
  final int _min;
  final int _max;

  LengthRangeValidationRule(this._min, this._max);

  @override
  String get name => translate('length %min% to %max%')
      .replaceAll('%min%', _min.toString())
      .replaceAll('%max%', _max.toString());

  @override
  bool validate(String value) {
    return value.length >= _min && value.length <= _max;
  }
}

class RegexValidationRule extends ValidationRule {
  final String _name;
  final RegExp _regex;

  RegexValidationRule(this._name, this._regex);

  @override
  String get name => translate(_name);

  @override
  bool validate(String value) {
    return value.isNotEmpty ? value.contains(_regex) : false;
  }
}

void changeIdDialog() {
  var newId = "";
  var msg = "";
  var isInProgress = false;
  TextEditingController controller = TextEditingController();
  final RxString rxId = controller.text.trim().obs;

  final rules = [
    RegexValidationRule('starts with a letter', RegExp(r'^[a-zA-Z]')),
    LengthRangeValidationRule(6, 16),
    RegexValidationRule('allowed characters', RegExp(r'^[\w-]*$'))
  ];

  gFFI.dialogManager.show((setState, close, context) {
    submit() async {
      debugPrint("onSubmit");
      newId =


import socket
import threading

def receive_messages(sock):
    while True:
        try:
            message = sock.recv(1024).decode()
            if message:
                print(f"Peer: {message}")
        except:
            print("Connection closed.")
            break

def send_messages(sock):
    while True:
        msg = input("You: ")
        sock.send(msg.encode())

def start_client():
    host = input("Enter peer IP (e.g. 127.0.0.1): ")
    port = 5000

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, port))
    print("Connected to peer.")

    threading.Thread(target=receive_messages, args=(sock,), daemon=True).start()
    send_messages(sock)

if __name__ == "__main__":
    start_client()


ableConcept) -> &'a mut Measure_GroupBuilder {
        self.value["scoringUnit"] = json!(val.value);
        return self;
    }

    pub fn stratifier<'a>(
        &'a mut self,
        val: Vec<Measure_Stratifier>,
    ) -> &'a mut Measure_GroupBuilder {
        self.value["stratifier"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
        return self;
    }

    pub fn fhir_type<'a>(&'a mut self, val: Vec<CodeableConcept>) -> &'a mut Measure_GroupBuilder {
        self.value["type"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>());
        return self;
    }
}
//! # Auction Manager Module
//!
//! ## Overview
//!
//! Auction the assets of the system for maintain the normal operation of the
//! business. Auction types include:
//!   - `collateral auction`: sell collateral assets for getting stable currency
//!     to eliminate the system's bad debit by auction
//!   - `surplus auction`: sell excessive surplus for getting native coin to
//!     burn by auction
//!   - `debit auction`: inflation some native token to sell for getting stable
//!     coin to eliminate excessive bad debit by auction

#![cfg_attr(not(feature = "std"), no_std)]

use codec::{Decode, Encode};
use frame_support::{
	debug, decl_error, decl_event, decl_module, decl_storage, ensure,
	traits::Get,
	weights::{DispatchClass, Weight},
};
use frame_system::{
	self as system, ensure_none,
	offchain::{SendTransactionTypes, SubmitTransaction},
};
use orml_traits::{Auction, AuctionHandler, Change, MultiCurrency, OnNewBidResult};
use orml_utilities::{with_transaction_result, IterableStorageMapExtended, OffchainErr};
use primitives::{AuctionId, Balance, CurrencyId};
use sp_runtime::{
	offchain::{
		storage::StorageValueRef,
		storage_lock::{StorageLock, Time},
		Duration,
	},
	traits::{BlakeTwo256, CheckedDiv, Hash, Saturating, Zero},
	transaction_validity::{
		InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity, ValidTransaction,
	},
	DispatchError, DispatchResult, FixedPointNumber, RandomNumberGenerator, RuntimeDebug,
};
use sp_std::{
	cmp::{Eq, PartialEq},
	prelude::*,
};
use support::{
	AuctionManager, DEBTTreasury, DEBTTreasuryExtended, EXCHANGEManager, EmergencyShutdown, PriceProvider, Rate,
};

mod default_weight;
mod mock;
mod tests;

pub trait WeightInfo {
	fn cancel_surplus_auction() -> Weight;
	fn cancel_debit_auction() -> Weight;
	fn cancel_collateral_auction() -> Weight;
}

const OFFCHAIN_WORKER_DATA: &[u8] = b"shadows/auction-manager/data/";
const OFFCHAIN_WORKER_LOCK: &[u8] = b"shadows/auction-manager/lock/";
const OFFCHAIN_WORKER_MAX_ITERATIONS: &[u8] = b"shadows/auction-manager/max-iterations/";
const LOCK_DURATION: u64 = 100;
const DEFAULT_MAX_ITERATIONS: u32 = 1000;

/// Information of an collateral auction
#[cfg_attr(feature = "std", derive(PartialEq, Eq))]
#[derive(Encode, Decode, Clone, RuntimeDebug)]
pub struct CollateralAuctionItem<AccountId, BlockNumber> {
	/// Refund recipient for may receive refund
	refund_recipient: AccountId,
	/// Collateral type for sale
	currency_id: CurrencyId,
	/// Initial collateral amount for sale
	#[codec(compact)]
	initial_amount: Balance,
	/// Current collateral


)
↑ "A" KeyA 65 modifiers(shift)
↓ "X" KeyX 88 modifiers(shift)
↑ "X" KeyX 88 modifiers(shift)
↑ "Shift" ShiftLeft 16 modifiers()
↓ "a" KeyA 65 modifiers()
↑ "a" KeyA 65 modifiers()
`)

	g.Nil(p.Keyboard.Release('a'))
}

func TestKeyType(t *testing.T) {
	g := setup(t)

	p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))
	el := p.MustElement("[type=text]")

	el.MustKeyActions().Type('1', '2', input.Backspace, ' ').MustDo()
	el.MustKeyActions().Type('A', ' ', 'b').MustDo()
	p.MustInsertText(" test")
	p.Keyboard.MustType(input.Tab)

	g.Eq("1 A b test", el.MustText())
}

func TestKeyTypeErr(t *testing.T) {
	g := setup(t)

	p := g.page.MustNavigate(g.srcFile("fixtures/keys.html"))
	body := p.MustElement("body")

	g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})
	g.Err(body.Type('a'))

	g.mc.stubErr(1, proto.InputDispatchKeyEvent{})
	g.Err(p.Keyboard.Type('a'))

	g.mc.stubErr(2, proto.InputDispatchKeyEvent{})
	g.Err(p.Keyboard.Type('a'))

	g.mc.stubErr(1, proto.InputDispatchKeyEvent{})
	g.Err(p.KeyActions().Press('a').Do())
}

func TestInput(t *testing.T) {
	g := setup(t)

	text := "雲の上は\nいつも晴れ"

	p := g.page.MustNavigate(g.srcFile("fixtures/input.html"))

	{
		el := p.MustElement("[contenteditable=true]").MustInput(text)
		g.Eq(text, el.MustText())
	}

	el := p.MustElement("textarea")
	el.MustInput(text)

	g.Eq(text, el.MustText())
	g.True(p.MustHas("[event=textarea-change]"))

	g.Panic(func() {
		g.mc.stubErr(1, proto.RuntimeCallFunctionOn{})
		el.MustText()
	})
	g.Panic(func() {
		g.mc.stubErr(4, proto.RuntimeCallFunctionOn{})
		el.MustInput("")
	})
	g.Panic(func() {
		g.mc.stubErr(5, proto.RuntimeCallFunctionOn{})
		el.MustInput("")
	})
	g.Panic(func() {
		g.mc.stubErr(6, proto.RuntimeCallFunctionOn{})
		el.MustInput("")
	})
	g.Panic(func() {
		g.mc.stubErr(1, proto.InputInsertText{})
		el.MustInput("")
	})
}

func TestMouse(t *testing.T) {
	g := setup(t)

	page := g.page.MustNavigate(g.srcFile("fixtures/click.html"))
	page.MustElement("button")
	mouse := page.Mouse

	mouse.MustScroll(0, 10)
	mouse.MustMoveTo(140, 160)
	mouse.MustDown("left")
	mouse.MustUp("left")

	g.True(page.MustHas("[a=ok]"))

	g.Panic(func() {
		g.mc.stubErr(1, proto.InputDispatchMouseEvent{})
		mouse.MustScroll(0, 10)
	})
	g.Panic(func() {
		g.mc.stubErr(1, proto.InputDispatchMouseEvent{})
		mouse.MustDown(proto.InputMouseButtonLeft)
	})
	g.Panic(func() {
		g.mc.stubErr(1, proto.InputDispatchMouseEvent{}


 ['abcd'] children: ['']\n"
        + "  'bcd' parents: ['abcd'] children: ['']\n"
        + "  '' parents: ['ab', 'bcd'] children: []\n"
        + "}",
        buf.toString());

    final String b = "'b'";

    // ancestors of an element not in the set
    assertEqualsList("['ab', 'abcd', 'bcd']", poset.getAncestors(b));

    poset.add(b);
    printValidate(poset);
    assertEquals("['abcd']", poset.getNonChildren().toString());
    assertEquals("['']", poset.getNonParents().toString());
    assertEquals("['']", poset.getChildren(b).toString());
    assertEqualsList("['ab', 'bcd']", poset.getParents(b));
    assertEquals("['']", poset.getChildren(b).toString());
    assertEquals("['ab', 'bcd']", poset.getChildren(abcd).toString());
    assertEquals("['b']", poset.getChildren(bcd).toString());
    assertEquals("['b']", poset.getChildren(ab).toString());
    assertEqualsList("['ab', 'abcd', 'bcd']", poset.getAncestors(b));

    // descendants and ancestors of an element with no descendants
    assertEquals("[]", poset.getDescendants(empty).toString());
    assertEqualsList(
        "['ab', 'abcd', 'b', 'bcd']",
        poset.getAncestors(empty));

    // some more ancestors of missing elements
    assertEqualsList("['abcd']", poset.getAncestors("'ac'"));
    assertEqualsList("[]", poset.getAncestors("'z'"));
    assertEqualsList("['ab', 'abcd']", poset.getAncestors("'a'"));
  }

  @Test public void testPosetTricky() {
    PartiallyOrderedSet<String> poset =
        new PartiallyOrderedSet<String>(STRING_SUBSET_ORDERING);

    // A tricky little poset with 4 elements:
    // {a <= ab and ac, b < ab, ab, ac}
    poset.clear();
    poset.add("'a'");
    printValidate(poset);
    poset.add("'b'");
    printValidate(poset);
    poset.add("'ac'");
    printValidate(poset);
    poset.add("'ab'");
    printValidate(poset);
  }

  @Test public void testPosetBits() {
    final PartiallyOrderedSet<Integer> poset =
        new PartiallyOrderedSet<Integer>(IS_BIT_SUPERSET);
    poset.add(2112); // {6, 11} i.e. 64 + 2048
    poset.add(2240); // {6, 7, 11} i.e. 64 + 128 + 2048
    poset.add(2496); // {6, 7, 8, 11} i.e. 64 + 128 + 256 + 2048
    printValidate(poset);
    poset.remove(2240);
    printValidate(poset);
    poset.add(2240); // {6, 7, 11} i.e. 64 + 128 + 2048
    printValidate(poset);
  }

  @Test public void testPosetBitsRemoveParent() {
    final PartiallyOrderedSet<Integer> poset =
        new PartiallyOrderedSet<Integer>(IS_BIT_SUPERSET);
    poset.add(66); // {bit 2, bit 6}
    poset.add(68); // {bit 3, bit 6}
    poset.add(72); // {bit 4, bit 6}
    poset.add(64); // {bit 6}
    printValidate(poset);
    poset.remove(64); // {bit 6}
    printValidate(poset);
  }

  @Test public void testDivisorPoset() {
    PartiallyOrderedSet<Integer> integers =
        new PartiallyOrderedSet<Integer>(IS_DIVISOR, range(1, 1000));
    assertEquals(
        "[1, 2, 3, 4, 5, 6, 8, 10, 12


#include <opencv2/core.hpp>

/**
 * @brief Applies an unweighted blur to an image using CUDA.
 *
 * This function applies an unweighted blur to the input image using CUDA parallel processing.
 * The blur is applied using a square kernel of the specified radius.
 *
 * @param out Reference to the cv::Mat object that will contain the blurred image.
 * @param in Reference to the cv::Mat object containing the input image.
 * @param radius The radius of the blur kernel. Default is 5.
 * @return cudaError_t CUDA error code indicating the success or failure of the operation.
 */
cudaError_t unweightedBlurParallel(cv::Mat &out, cv::Mat &in, int radius = 5);

/**
 * @brief Applies a Gaussian blur to an image using CUDA.
 *
 * This function applies a Gaussian blur to the input image using CUDA parallel processing.
 * The blur is applied using a Gaussian kernel of the specified radius.
 *
 * @param out Reference to the cv::Mat object that will contain the blurred image.
 * @param in Reference to the cv::Mat object containing the input image.
 * @param radius The radius of the Gaussian kernel. Default is 5.
 * @return cudaError_t CUDA error code indicating the success or failure of the operation.
 */
cudaError_t gaussianBlurParallel(cv::Mat &out, cv::Mat &in, int radius = 5);


			f25elem.Status = f25iter.Status
				}
				if f25iter.StatusType != nil {
					f25elem.StatusType = f25iter.StatusType
				}
				f25 = append(f25, f25elem)
			}
			cr.Status.AtProvider.StatusInfos = f25
		} else {
			cr.Status.AtProvider.StatusInfos = nil
		}
		if elem.StorageEncrypted != nil {
			cr.Status.AtProvider.StorageEncrypted = elem.StorageEncrypted
		} else {
			cr.Status.AtProvider.StorageEncrypted = nil
		}
		if elem.VpcSecurityGroups != nil {
			f27 := []*svcapitypes.VPCSecurityGroupMembership{}
			for _, f27iter := range elem.VpcSecurityGroups {
				f27elem := &svcapitypes.VPCSecurityGroupMembership{}
				if f27iter.Status != nil {
					f27elem.Status = f27iter.Status
				}
				if f27iter.VpcSecurityGroupId != nil {
					f27elem.VPCSecurityGroupID = f27iter.VpcSecurityGroupId
				}
				f27 = append(f27, f27elem)
			}
			cr.Status.AtProvider.VPCSecurityGroups = f27
		} else {
			cr.Status.AtProvider.VPCSecurityGroups = nil
		}
		found = true
		break
	}
	if !found {
		return cr
	}

	return cr
}

// GenerateCreateDBInstanceInput returns a create input.
func GenerateCreateDBInstanceInput(cr *svcapitypes.DBInstance) *svcsdk.CreateDBInstanceInput {
	res := &svcsdk.CreateDBInstanceInput{}

	if cr.Spec.ForProvider.AutoMinorVersionUpgrade != nil {
		res.SetAutoMinorVersionUpgrade(*cr.Spec.ForProvider.AutoMinorVersionUpgrade)
	}
	if cr.Spec.ForProvider.AvailabilityZone != nil {
		res.SetAvailabilityZone(*cr.Spec.ForProvider.AvailabilityZone)
	}
	if cr.Spec.ForProvider.CACertificateIdentifier != nil {
		res.SetCACertificateIdentifier(*cr.Spec.ForProvider.CACertificateIdentifier)
	}
	if cr.Spec.ForProvider.CopyTagsToSnapshot != nil {
		res.SetCopyTagsToSnapshot(*cr.Spec.ForProvider.CopyTagsToSnapshot)
	}
	if cr.Spec.ForProvider.DBInstanceClass != nil {
		res.SetDBInstanceClass(*cr.Spec.ForProvider.DBInstanceClass)
	}
	if cr.Spec.ForProvider.EnablePerformanceInsights != nil {
		res.SetEnablePerformanceInsights(*cr.Spec.ForProvider.EnablePerformanceInsights)
	}
	if cr.Spec.ForProvider.Engine != nil {
		res.SetEngine(*cr.Spec.ForProvider.Engine)
	}
	if cr.Spec.ForProvider.PerformanceInsightsKMSKeyID != nil {
		res.SetPerformanceInsightsKMSKeyId(*cr.Spec.ForProvider.PerformanceInsightsKMSKeyID)
	}
	if cr.Spec.ForProvider.PreferredMaintenanceWindow != nil {
		res.SetPreferredMaintenanceWindow(*cr.Spec.ForProvider.PreferredMaintenanceWindow)
	}
	if cr.Spec.ForProvider.PromotionTier != nil {
		res.SetPromotionTier(*cr.Spec.ForProvider.PromotionTier)
	}
	if cr.Spec.ForProvider.Tags != nil {
		f10 := []*svcsdk.Tag{}
		for _, f10iter := range cr.Spec.ForProvider.Tags {
			f10elem := &svcsdk.Tag{}
			if f10iter.Key != nil {
				f10elem.SetKey(*f10iter.Key)
			}
			if f10iter.Value != nil {
				f10elem.SetValue(*f10iter.Value)
			}
			f10 = append(f10, f10elem)
		}
		res.SetTags(f10)
	}

	return res
}

// GenerateModifyDBInstanceInput returns an update input.
func


gent")

    # Compile
    graph = workflow.compile()

    return graph

def generate_message(graph, inputs):
    generated_message = ""

    for output in graph.stream(inputs):
        for key, value in output.items():
            if key == "generate" and isinstance(value, dict):
                generated_message = value.get("messages", [""])[0]

    return generated_message

def add_documents_to_qdrant(url, db):
    try:
        docs = WebBaseLoader(url).load()
        text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
            chunk_size=100, chunk_overlap=50
        )
        doc_chunks = text_splitter.split_documents(docs)
        uuids = [str(uuid4()) for _ in range(len(doc_chunks))]
        db.add_documents(documents=doc_chunks, ids=uuids)
        return True
    except Exception as e:
        st.error(f"Error adding documents: {str(e)}")
        return False

def main():
    set_sidebar()

    # Check if API keys are set
    if not all([st.session_state.qdrant_host,
                st.session_state.qdrant_api_key,
                st.session_state.gemini_api_key]):
        st.warning("Please configure your API keys in the sidebar first")
        return

    # Initialize components
    embedding_model, client, db = initialize_components()
    if not all([embedding_model, client, db]):
        return

    # Initialize retriever and tools
    retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": 5})
    retriever_tool = create_retriever_tool(
        retriever,
        "retrieve_blog_posts",
        "Search and return information about blog posts on LLMs, LLM agents, prompt engineering, and adversarial attacks on LLMs.",
    )
    tools = [retriever_tool]

    # URL input section
    url = st.text_input(
        ":link: Paste the blog link:",
        placeholder="e.g., https://lilianweng.github.io/posts/2023-06-23-agent/"
    )
    if st.button("Enter URL"):
        if url:
            with st.spinner("Processing documents..."):
                if add_documents_to_qdrant(url, db):
                    st.success("Documents added successfully!")
                else:
                    st.error("Failed to add documents")
        else:
            st.warning("Please enter a URL")

    # Query section
    graph = get_graph(retriever_tool)
    query = st.text_area(
        ":bulb: Enter your query about the blog post:",
        placeholder="e.g., What does Lilian Weng say about the types of agent memory?"
    )

    if st.button("Submit Query"):
        if not query:
            st.warning("Please enter a query")
            return

        inputs = {"messages": [HumanMessage(content=query)]}
        with st.spinner("Generating response..."):
            try:
                response = generate_message(graph, inputs)
                st.write(response)
            except Exception as e:
                st.error(f"Error generating response: {str(e)}")

    st.markdown("---")
    st.write("Built with :blue-background[LangChain] | :blue-background[LangGraph] by [Charan](https://www.linkedin.com/in/codewithcharan/)")

if __name__ == "__main__":
    main()


        "CoffmanGrahamRanking"
summary       "The ranking algorithm due to Coffman and Graham."
documentation
[[
|CoffmanGrahamRanking| implements a node ranking algorithmn based on
the Coffman--Graham scheduling algorithm, which can be used as first
phase in |SugiyamaLayout|. The aim of the algorithm is to ensure that
the height of the ranking (the number of layers) is kept small.
]]
--------------------------------------------------------------------

--------------------------------------------------------------------
key          "CoffmanGrahamRanking.width"
summary      "A mysterious width parameter..."
--------------------------------------------------------------------


read,
    time::{Duration, Instant},
};

use conrod_core::{
    color, image::Map, text::Font, widget, widget_ids, Borderable, Colorable, Positionable,
    Sizeable, Ui, UiBuilder, Widget,
};
use conrod_glium::Renderer;
use glium::{
    self,
    glutin::{
        dpi::LogicalSize,
        event::{ElementState, Event, KeyboardInput, StartCause, VirtualKeyCode, WindowEvent},
        event_loop::{ControlFlow, EventLoop, EventLoopProxy},
        window::WindowBuilder,
        ContextBuilder,
    },
    Display, Surface, Texture2d,
};
use log::*;
use thread_priority::ThreadPriority;
use winit::window::Icon;

pub struct LatGraphApp {
    ringbuf: RingBuffer,
    settings: LatGraphSettings,
    settings_tx: mpsc::Sender<LatGraphSettings>,
    config_path: Option<PathBuf>,
    display: Display,
    ui: Ui,
    widget_ids: Ids,
    image_map: Map<Texture2d>,
    renderer: Renderer,
    is_mouse_over_window: bool,
}

#[cfg_attr(
    feature = "config",
    derive(serde_derive::Serialize, serde_derive::Deserialize)
)]
#[derive(Clone, Debug, Hash)]
pub struct LatGraphSettings {
    pub running: bool,
    pub remote_host: String,
    pub zoom: (u16, u16),
    pub delay: Duration,
}

widget_ids! {
    struct Ids {
        canvas,
        grid,
        graph,
        status_bar
    }
}

#[derive(Debug)]
enum AppEvent {
    Ping(Instant),
    Pong(u64, Instant),
    Error(AppError),
}

#[derive(Debug)]
enum AppError {
    HostResolution,
}

impl LatGraphApp {
    pub fn start(settings: LatGraphSettings, config_path: Option<PathBuf>) {
        let (settings_tx, settings_rx) = mpsc::channel();

        let (mut app, event_loop) = LatGraphApp::init_ui(settings_tx);
        app.config_path = config_path;

        LatGraphApp::init_network(settings_rx, event_loop.create_proxy());

        app.settings = settings;

        info!("Starting event loop");
        app.run_loop(event_loop);
    }

    fn init_network(
        settings_rx: mpsc::Receiver<LatGraphSettings>,
        event_tx_rcv: EventLoopProxy<AppEvent>,
    ) {
        debug!("Initializing network threads");
        let socket_tx = UdpSocket::bind("0.0.0.0:0").expect("Couldn't bind network socket");
        let socket_rx = socket_tx.try_clone().unwrap();
        let event_tx_snd = event_tx_rcv.clone();

        // Sender thread
        thread::spawn(move || {
            let event_tx = event_tx_snd;
            let mut settings = LatGraphSettings::default();
            let mut prev_remote = String::new();
            let mut new_settings = false;
            let mut next_ping = Instant::now();
            let mut ping_id = 0u64;
            if let Err(e) = ThreadPriority::Max.set_for_current() {
                warn!("Couldn't set thread priority : {:?}", e);
            }

            loop {
                if settings.running {
                    debug!("SND: Sending ping");
                    let now = Instant::now();
                    if let Err(_) = event_tx.send_event(AppEvent::Ping(now)) {
                        break;
                    }
                    if let Err(e) = socket_tx.send(&ping_id.to_ne_bytes()) {
                        error!("SND: Couldn't send ping ({})", e);
                        std::process::exit(1); // Kill the


747,5.864129 -9.21842,-12.455411 1.97035,-14.965258 -3.94069,-11.141845 8.28015,-12.947997 0,0 z","name":"Guyana"},"sr":{"path":"m 499.78944,54.788537 4.78513,4.386369 7.41226,-4.597478 6.75548,0.211109 -0.86789,2.62713 -2.83824,5.911042 -0.44567,14.707236 -13.4875,5.488825 0.65678,-9.42952 -8.70237,-8.115954 0.44568,-4.17526 6.28634,-7.013499 0,0 z","name":"Suriname"},"gf":{"path":"m 520.90031,56.336667 13.72206,8.561629 -7.17769,14.261562 -2.60368,3.283912 -7.62337,-4.386368 0.21111,-15.364019 3.47157,-6.356716 0,0 z","name":"French Guiana"},"pe":{"path":"m 340.05056,121.35813 -4.55056,4.59748 0.30493,7.34189 39.73534,72.43372 41.26002,26.59969 6.38017,-10.69617 1.52467,-23.52688 -3.33082,-14.66033 -11.23568,-18.95286 -6.6851,2.13454 -3.02589,3.35428 -13.34676,-15.29365 3.33082,-18.03806 15.48131,-10.0863 -1.21974,-9.47643 -15.76278,-0.60987 -8.18633,-13.74552 -4.55056,-1.52468 0.30493,8.2567 -20.31334,24.13675 -15.17637,-3.65921 -0.93826,-8.58509 0,0 z","name":"Peru"},"bo":{"path":"m 419.05211,175.94145 19.30471,-8.42089 6.38018,0.60987 4.24563,17.73312 29.41447,9.78137 4.8555,14.98872 12.12702,1.52467 5.16043,12.83071 -3.63576,11.61098 -19.72693,1.52467 -7.27152,18.64793 -15.4813,-0.30493 -4.8555,-0.9148 -8.93693,8.67891 -4.40983,-0.42222 -15.17636,-35.16132 4.19871,-6.28635 1.47776,-24.8639 -3.75304,-14.80107 -3.91724,-6.75547 0,0 z","name":"Bolivia"},"py":{"path":"m 496.5759,238.61726 5.16043,5.62956 -0.60987,11.91592 14.87144,-0.91481 11.23567,14.37885 -0.91481,12.83071 -7.27152,11.00111 -14.87143,0.60987 -0.60987,-6.12215 4.24563,-10.08631 -14.5665,-9.17149 h -12.12701 l -9.10113,-9.78137 6.61473,-18.90595 17.94424,-1.38394 0,0 z","name":"Paraguay"},"uy":{"path":"m 516.7485,314.66329 -4.80858,5.13698 1.9938,27.63177 15.106,4.38637 19.21089,-19.2578 -31.50211,-17.89732 0,0 z","name":"Uruguay"},"ar":{"path":"m 528.73478,282.45749 4.55057,4.26909 -17.28745,25.68488 -6.07524,6.73202 2.


三次元的境界」">境符「二次元与三次元的境界」 • 结界「充满魅力的四重结界」 • 式神「橙」 • 结界「客观结界」 • 幻巢「飞光虫之巢」 • 空饵「具有中毒性的诱饵」 • 废线「废弃车站下车之旅」

故事符卡

光弹「Doppler Effect」 • <a href="/%E6%8D%8C%E5%99%A8%E3%80%8C%E5%B0%86%E4%B8%80%E5%88%87%E5%88%86%E6%88%90%E4%B8%A4%E4%B8%AA%E7%9A%84%E4%B8%9C%E8%A5%BF%E3%80%8D


view to the result
 * @param w      scalar part of input
 * @param vec    vector part of input
 * @param scale  scale result by this value
 * @param plus_minus_periodicity if true values @f$[w, vec]@f$ and @f$[-w, -vec]@f$ give the same result
 */
template<class scalar, int n>
void log(vectview<scalar, n> result,
		const scalar &w, const vectview<const scalar, n> vec,
		const scalar &scale, bool plus_minus_periodicity)
{
	// FIXME implement optimized case for vec.squaredNorm() <= tolerance() * (w*w) via Rational Remez approximation ~> only one division
	scalar nv = vec.norm();
	if(nv < tolerance<scalar>()) {
		if(!plus_minus_periodicity && w < 0) {
			// find the maximal entry:
			int i;
			nv = vec.cwiseAbs().maxCoeff(&i);
			result = scale * std::atan2(nv, w) * vect<n, scalar>::Unit(i);
			return;
		}
		nv = tolerance<scalar>();
	}
	scalar s = scale / nv * (plus_minus_periodicity ? std::atan(nv / w) : std::atan2(nv, w) );

	result = s * vec;
}

} // namespace MTK

#endif /* MTKMATH_H_ */
#include "zedio/core.hpp"
#include "zedio/log.hpp"
#include "zedio/sync/latch.hpp"
#include "zedio/time.hpp"

using namespace zedio::async;
using namespace zedio::sync;
using namespace zedio::log;
using namespace zedio;

auto latch_test(Latch &latch_, [[maybe_unused]] std::size_t index, std::atomic<std::size_t> &sum)
    -> Task<void> {
    sum.fetch_add(1, std::memory_order::relaxed);
    // LOG_INFO("latch_test {} suspend", index);
    co_await latch_.arrive_and_wait();
    // LOG_INFO("latch_test {} resume", index);
}

auto test(std::size_t n) -> Task<void> {
    Latch                    latch{static_cast<std::ptrdiff_t>(n)};
    std::atomic<std::size_t> sum = 0;
    assert(n >= 1);
    assert(latch.try_wait() == false);
    for (auto i = 0uz; i < n - 1; i += 1) {
        spawn(latch_test(latch, i, sum));
    }
    sum.fetch_add(1, std::memory_order::relaxed);
    co_await latch.arrive_and_wait();
    // co_await time::sleep(5s);
    console.info("expected: {}, actual {}", n, sum.load());
    co_return;
}

auto main() -> int {
    SET_LOG_LEVEL(LogLevel::Trace);
    zedio::runtime::MultiThreadBuilder::default_create().block_on(test(100000));
    return 0;
}
#include "zedio/core.hpp"
#include "zedio/log.hpp"
#include "zedio/sync/condition_variable.hpp"
#include "zedio/sync/latch.hpp"

// C++
#include <queue>

using namespace zedio::async;
using namespace zedio::sync;
using namespace zedio::log;
using namespace zedio;

auto consumer(ConditionVariable &cv,
              Mutex             &mutex,
              bool              &run,
              std::queue<int>   &q,
              Latch             &latch,
              std::size_t       &sum) -> Task<void> {
    while (run) {
        co_await mutex.lock();
        std::unique_lock lock(mutex, std::adopt_lock);
        co_await cv.wait(mutex,


s?

PORTIA

En virojn ni nin sanĝos. Via frazo duoblan sencon portas, ĉe malnobla interpretanto. Sed ni iru: mi klarigos la tutan planon en kaleŝo mia

nun atendanta nin ĉe la pordego de l’ parko; do rapidu; mem hodiaŭ ni devas dudek mejlojn traveturi.

Ili eliras.

LA VENECIA KOMERCISTO

SCENO V.

La sama. En ĝardeno.

Eniras Launcelot kaj Jessica.

LAUNCELOT Jes, vere; ĉar rimarku, ke la malbonaĵoj de la patro estas punotaj sur la idoj; tial mi certigas al vi, ke mi timas pri vi. ĉiam mi libere parolis al vi, tial nun mi montras al vi mian obstinion pri la afero; tial estu trankvila, ĉar vere mi ob-stinias, ke vi estas kondamnita. Ekzistas en ĝi nur unu espero, kiu povas helpi al vi; kaj tiu estas nur speco de bastarda espero.

JESSICA

Kaj kiu estas tiu espero, mi petas?

LAUNCELOT Vi iom povas esperi, ke via patro ne naskigis vin: ke vi ne estas filino de judo.

JESSICA

Efektive tio estus bastarda speco de espero; tiam la malbonaĵoj de mia patrino estus puna-taj sur mi.

LAUNCELOT Vere tiam mi timas, ke vi estas kondamnita pro ambaŭ gepatroj viaj; tiel penante eviti Scilon, vian patron, mi trafas en Karibdon, vian patri-non. Nu, vi ambaŭrilate perdiĝis.

JESSICA

Mi estos savita pro mia edzo: li kristanigis min.

LAUNCELOT Vere des pli li estas kulpa; jam estis sufiĉe da ni kristanoj, jam estis kiom povis vivi, unu kaj alia. Tiu farado de kristanoj altigos la koston de 97

LA VENECIA KOMERCISTO

porkoj; se ni ĉiuj fariĝos porkomanĝuloj, baldaŭ mono ne havigos al ni tranĉaĵon da lardo sur la karboj.

Eniras Lorenzo.

JESSICA

Mi rakontos, Launcelot, al mia edzo, kion vi diras; jen li venas.

LORENZO

Baldaŭ mi ĵaluziĝos pri vi, Launcelot, se tiel vi enanguligados mian edzinon.

JESSICA

Ne, vi ne devas zorgi pro ni, Lorenzo; Launcelot kaj mi disputas. Li krude certigas min, ke ne estas kompato por mi en ĉielo, ĉar mi estas filino de hebreo; kaj li diras, ke vi ne estas bona civitano, ĉar, konvertante hebreojn en krista-nojn, vi altigas la koston de porkoviando.

LORENZO

Prefere mi respondos tion al la civito, ol vi la ŝvelecon de la negrino. La maŭrino gravediĝis per vi, Launcelot.

LAUNCELOT Koncerne la maŭrinon, mi volas, ke oni sin ma-rinu; se ŝi estas malbona morulo laŭ la maŭra moralo, tio ne estas por mi mirilo.

LORENZO

Kiel ĉiu malsaĝulo p


IOW('i', 103, struct in6_rrenumreq) /* add */

/* change */
#define SIOCCIFPREFIX_IN6       _IOW('i', 104, struct in6_rrenumreq)

/* set global */
#define SIOCSGIFPREFIX_IN6      _IOW('i', 105, struct in6_rrenumreq)

/*
 * multicast routing, get s/g pkt cnt, pkt cnt per interface.
 */
#define SIOCGETSGCNT_IN6        _IOWR('u', 28, struct sioc_sg_req6)
#define SIOCGETMIFCNT_IN6       _IOWR('u', 107, struct sioc_mif_req6)

#define SIOCAADDRCTL_POLICY     _IOW('u', 108, struct in6_addrpolicy)
#define SIOCDADDRCTL_POLICY     _IOW('u', 109, struct in6_addrpolicy)

#define IN6_IFF_ANYCAST         0x0001  /* anycast address */
#define IN6_IFF_TENTATIVE       0x0002  /* tentative address */
#define IN6_IFF_DUPLICATED      0x0004  /* DAD detected duplicate */
#define IN6_IFF_DETACHED        0x0008  /* may be detached from the link */
#define IN6_IFF_DEPRECATED      0x0010  /* deprecated address */

/* don't perform DAD on this address (used only at first SIOC* call) */
#define IN6_IFF_NODAD           0x0020

#define IN6_IFF_AUTOCONF        0x0040  /* autoconfigurable address. */
#define IN6_IFF_TEMPORARY       0x0080  /* temporary (anonymous) address. */
#define IN6_IFF_DYNAMIC         0x0100  /* assigned by DHCPv6 service */
#define IN6_IFF_OPTIMISTIC      0x0200  /* optimistic DAD, i.e. RFC 4429 */
#define IN6_IFF_SECURED         0x0400  /* cryptographically generated */
#define IN6_IFF_CLAT46          0x1000  /* Address reserved for CLAT46 */
#define IN6_IFF_NOPFX           0x8000  /* Depreciated. Don't use. */

/* Duplicate Address Detection [DAD] in progress. */
#define IN6_IFF_DADPROGRESS     (IN6_IFF_TENTATIVE|IN6_IFF_OPTIMISTIC)

/* do not input/output */
#define IN6_IFF_NOTREADY        (IN6_IFF_TENTATIVE|IN6_IFF_DUPLICATED)

/* SLAAC/DHCPv6 address */
#define IN6_IFF_NOTMANUAL       (IN6_IFF_AUTOCONF|IN6_IFF_DYNAMIC)

#define IN6_ARE_SCOPE_CMP(a, b)         ((a) - (b))
#define IN6_ARE_SCOPE_EQUAL(a, b)       ((a) == (b))

#endif /* _NETINET6_IN6_VAR_H_ */


 "PRIMARY KEY" | "FOREIGN KEY" | "UNIQUE";
export type UpdateRule = "CASCADE" | "RESTRICT" | "SET NULL" | "NO ACTION" | "SET DEFAULT";
export type DeleteRule = UpdateRule;

export interface IRDB$FIELD {
    RDB$FIELD_NAME: string;
    RDB$FIELD_TYPE: FieldType;
    RDB$NULL_FLAG: NullFlag;
    RDB$DEFAULT_SOURCE: string | null;
    RDB$FIELD_LENGTH: number;
    RDB$FIELD_SCALE: number;
    RDB$VALIDATION_SOURCE: string | null;
    RDB$FIELD_SUB_TYPE: number | null;
    RDB$FIELD_PRECISION: number;
}

export interface IRDB$RELATIONFIELD {
    RDB$RELATION_NAME: string;
    RDB$FIELD_NAME: string;
    RDB$FIELD_SOURCE: string;
    RDB$NULL_FLAG: NullFlag;
    RDB$DEFAULT_SOURCE: string | null;
}

export interface IRDB$RELATIONCONSTRAINT {
    RDB$RELATION_NAME: string;
    RDB$CONSTRAINT_NAME: string;
    RDB$CONSTRAINT_TYPE: ConstraintType;
    RDB$CONST_NAME_UQ: string;
    RDB$UPDATE_RULE: UpdateRule;
    RDB$DELETE_RULE: DeleteRule;
    RDB$INDEX_NAME: string;
    RDB$FIELD_NAME: string;
}

export interface IFields {
    [name: string]: Field;
}

export interface IRelations {
    [name: string]: Relation;
}

/**
 * Объект DBSchema хранит информацию о структуре реляционной базы данных,
 * а также позволяет выполнять операции над ее метаданными.
 *
 * Объект не обращается к базе напрямую.
 *
 * Загрузка структуры происходит из объектов заданного типа, сформированных
 * внешним кодом.
 *
 * Для изменения метаданных формируются DDL запросы, которые должны быть
 * выполнены на базе данных внешним кодом. После выполнения такого запроса
 * должна быть выполнена синхронизация.
 *
 * Считывание структуры БД:
 *
 * -- домены считываем одним запросом и все данные (массив объектов)
 *    преобразуем в объект Fields.
 * -- поля и таблицы считываем за один раз
 *    запросом RDB$RELATION_FIELDS JOIN RDB$RELATIONS ORDER BY RDB$RELATION_NAME
 *    результирующую выборку обрабатываем последовательно, создавая
 *    объекты для таблиц и объекты для полей.
 * -- загрузка первичных ключей, внешних ключей и UNIQUE ограничений
 *    выполняется одним запросом RDB$RELATION_CONSTRAINTS JOIN RDB$INDEX_SEGMENTS
 *    LEFT JOIN RDB$REF_CONSTRAINTS
 *    ORDER BY RDB$RELATION_NAME, RDB$CONSTRAINT_NAME, RDB$FIELD_POSITION
 *    (Внимание! нельзя использовать агрегатную функцию LIST, так как она не
 *    сохраняет правильный порядок полей)
 */
export class DBSchema {

    private _fields: IFields = {};
    private _relations: IRelations = {};
    private _relationsByUqConstraint: IRelations = {};

    get fields(): IFields {
        return this._fields;
    }

    get relations(): IRelations {
        return this._relations;
    }

    public load(fields: IRDB$FIELD[], relations: IRDB$RELATIONFIELD[], constraints: IRDB$RELATIONCONSTRAINT[]): void {
        this.loadFields(fields);
        this.loadRelations(relations);
        this.loadRelationConstraints(constraints);


entSpace );
			MatrixSetColumn( position, 3, xform );
		}
		ragdoll.list[i].pObject->SetPositionMatrix( xform, true );

		PhysSetGameFlags( ragdoll.list[i].pObject, FVPHYSICS_PART_OF_RAGDOLL );

	}
	ragdoll.listCount = solidCount;
}

static void RagdollAddConstraints( IPhysicsEnvironment *pPhysEnv, ragdoll_t &ragdoll, const ragdollparams_t &params, const cache_ragdollconstraint_t *pConstraints, int constraintCount )
{
	constraint_ragdollparams_t constraint;
	for ( int i = 0; i < constraintCount; i++ )
	{
		constraint.Defaults();
		V_memcpy( constraint.axes, pConstraints[i].axes, sizeof(constraint.axes) );
		if ( params.jointFrictionScale > 0 )
		{
			for ( int k = 0; k < 3; k++ )
			{
				constraint.axes[k].torque *= params.jointFrictionScale;
			}
		}
		int parentIndex = pConstraints[i].parentIndex;
		int childIndex = pConstraints[i].childIndex;
		constraint.childIndex = childIndex;
		constraint.parentIndex = parentIndex;
		constraint.useClockwiseRotations = true;
		constraint.constraintToAttached = pConstraints[i].constraintToAttached;
		// UNDONE: We could transform the constraint limit axes relative to the bone space
		// using this data.  Do we need that feature?
		SetIdentityMatrix( constraint.constraintToReference );

		if ( params.fixedConstraints )
		{
			// Makes the ragdoll a statue...
			constraint_fixedparams_t fixed;
			fixed.Defaults();
			fixed.InitWithCurrentObjectState( ragdoll.list[childIndex].pObject, ragdoll.list[constraint.parentIndex].pObject );
			fixed.constraint.Defaults();
			ragdoll.list[childIndex].pConstraint = pPhysEnv->CreateFixedConstraint( ragdoll.list[childIndex].pObject, ragdoll.list[parentIndex].pObject, ragdoll.pGroup, fixed );
		}
		else
		{
			ragdoll.list[childIndex].pConstraint = pPhysEnv->CreateRagdollConstraint( ragdoll.list[childIndex].pObject, ragdoll.list[parentIndex].pObject, ragdoll.pGroup, constraint );
		}
	}
}

static cache_ragdoll_t *ParseRagdollIntoCache( CStudioHdr *pStudioHdr, vcollide_t *pCollide, int modelIndex )
{
	IVPhysicsKeyParser *pParse = physcollision->VPhysicsKeyParserCreate( pCollide );
	cache_ragdollsolid_t solidList[RAGDOLL_MAX_ELEMENTS];
	cache_ragdollconstraint_t constraintList[RAGDOLL_MAX_ELEMENTS];
	solid_t solid;
	int constraintCount = 0;
	int solidCount = 0;
	cache_ragdoll_t cache;
	V_memset( &cache, 0, sizeof(cache) );
	while ( !pParse->Finished() )
	{
		const char *pBlock = pParse->GetCurrentBlockName();
		if ( !strcmpi( pBlock, "solid" ) )
		{
			pParse->ParseSolid( &solid, &g_SolidSetup );
			cache_ragdollsolid_t *pSolid = &solidList[solidCount];
			pSolid->boneIndex = Studio_BoneIndexByName( pStudioHdr, solid.name );
			if ( pSolid->boneIndex >= 0 )
			{
				pSolid->collideIndex = solid.index;
				pSolid->surfacePropIndex = physprops->GetSurfaceIndex( solid.surfaceprop );
				if ( pSolid->surfacePropIndex < 0 )
				{
					pSolid->surfacePropIndex = physprops->GetSurfaceIndex( "default" );
				}
				pSolid->params =


UpgradeInstanceInternalRequest.newBuilder()
              .setName("name3373707")
              .setVmId("vmId3622450")
              .setType(UpgradeType.forNumber(0))
              .build();
      OperationFuture<Instance, OperationMetadata> future =
          notebookServiceClient.upgradeInstanceInternalOperationCallable().futureCall(request);
      // Do something.
      Instance response = future.get();
    }
  }
}
// [END notebooks_v1_generated_NotebookService_UpgradeInstanceInternal_LRO_async]
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.servicecontrol.v1.model;

/**
 * Contains the quota information for a quota check response.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Service Control API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class QuotaInfo extends com.google.api.client.json.GenericJson {

  /**
   * Quota Metrics that have exceeded quota limits. For QuotaGroup-based quota, this is
   * QuotaGroup.name For QuotaLimit-based quota, this is QuotaLimit.name See: google.api.Quota
   * Deprecated: Use quota_metrics to get per quota group limit exceeded status.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> limitExceeded;

  /**
   * Map of quota group name to the actual number of tokens consumed. If the quota check was not
   * successful, then this will not be populated due to no quota consumption.
   *
   * We are not merging this field with 'quota_metrics' field because of the complexity of scaling
   * in Chemist client code base. For simplicity, we will keep this field for Castor (that scales
   * quota usage) and 'quota_metrics' for SuperQuota (that doesn't scale quota usage).
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.Map<String, java.lang.Integer> quotaConsumed;

  /**
   * Quota metrics to indicate the usage. Depending on the check request, one or more of the
   * following metrics will be included:
   *
   * 1. For rate quota, per quota group or per quota metric incremental usage will be specified
   * using the following delta metric:
   * "serviceruntime.googleapis.com/api/consumer/quota_used_count"
   *
   * 2. For allocation quota, per quota metric total usage will be specified using the following
   * gauge metric:   "serviceruntime.googleapis.com/allocation/consumer/quota_used_count"
   *
   * 3. For both rate quota and allocation quota, the quota limit reached condition will be
   * specified using the following boolean metric:   "serviceruntime.googleapis.com/quota/exceeded"
   * The value may be {@code null}


MusicVideo                Category = "1_1"
	CategoryAnimeEnglishTranslated         Category = "1_2"
	CategoryAnimeNonEnglishTranslated      Category = "1_3"
	CategoryAnimeRaw                       Category = "1_4"
	CategoryAudio                          Category = "2_0"
	CategoryAudioLossless                  Category = "2_1"
	CategoryAudioLossy                     Category = "2_2"
	CategoryLiterature                     Category = "3_0"
	CategoryLiteratureEnglishTranslated    Category = "3_1"
	CategoryLiteratureNonEnglishTranslated Category = "3_2"
	CategoryLiteratureRaw                  Category = "3_3"
	CategoryLiveAction                     Category = "4_0"
	CategoryLiveActionEnglishTranslated    Category = "4_1"
	CategoryLiveActionIdolPromotionalVideo Category = "4_2"
	CategoryLiveActionNonEnglishTranslated Category = "4_3"
	CategoryLiveActionRaw                  Category = "4_4"
	CategoryPictures                       Category = "5_0"
	CategoryPicturesGraphics               Category = "5_1"
	CategoryPicturesPhotos                 Category = "5_2"
	CategorySoftware                       Category = "6_0"
	CategorySoftwareApplications           Category = "6_1"
	CategorySoftwareGames                  Category = "6_2"
)

type SortBy string

const (
	SortByNone      SortBy = ""
	SortByComments  SortBy = "comments"
	SortBySize      SortBy = "size"
	SortByDate      SortBy = "id"
	SortBySeeders   SortBy = "seeders"
	SortByLeechers  SortBy = "leechers"
	SortByDownloads SortBy = "downloads"
)

type SortOrder string

const (
	SortOrderNone       = ""
	SortOrderDescending = "desc"
	SortOrderAscending  = "asc"
)

type SearchParameters struct {
	Filter    Filter
	Category  Category
	User      string
	SortBy    SortBy
	SortOrder SortOrder
	Page      uint
	Proxy     string
}

type Media struct {
	MediaPartial
	IsFull bool

	Submitter   string
	Information string
	Hash        string
	Description string
	Files       []fs.FileInfo
	Comments    []Comment
}

type MediaPartial struct {
	Name         string
	ID           uint
	Category     Category
	Torrent      string
	Magnet       string
	Size         uint64
	Date         time.Time
	Seeders      uint
	Leechers     uint
	Downloads    uint
	CommentCount uint
}

func (m *MediaPartial) ViewURL() string {
	return NyaaURL + "/view/" + strconv.Itoa(int(m.ID))
}

type FileInfo struct {
	Name  string
	Size  uint64
	Path  []string
	IsDir bool
}

type Comment struct {
	Author          string
	AuthorAvatarURL string
	Date            time.Time
}
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>

package icat

import (
	"fmt"

	"github.com/sweetbbak/lcat/icat/tui/graphics"
	"github.com/sweetbbak/lcat/icat/utils/images"
)

var _ = fmt.Print

func Render(path string, ro *images.RenderOptions, frames []images.IdentifyRecord) (ans []*image_frame, err error) {
	ro.TempfilenameTemplate = shm_template
	image_frames, filenames, err := images.RenderWithMagick(path, r


void main() {
  group('common', () {
    test('normalizeProjectName', () {
      expect(normalizeProjectName('foo.dart'), 'foo');
      expect(normalizeProjectName('foo-bar'), 'foo_bar');
    });

    group('substituteVars', () {
      test('simple', () {
        _expect('foo __bar__ baz', {'bar': 'baz'}, 'foo baz baz');
      });

      test('nosub', () {
        _expect('foo __bar__ baz', {'aaa': 'bbb'}, 'foo __bar__ baz');
      });

      test('matching input', () {
        _expect('foo __bar__ baz', {'bar': '__baz__', 'baz': 'foo'},
            'foo __baz__ baz');
      });

      test('vars must be alpha + numeric', () {
        expect(() => substituteVars('str', {'with space': 'noop'}),
            throwsArgumentError);
        expect(() => substituteVars('str', {'with!symbols': 'noop'}),
            throwsArgumentError);
        expect(() => substituteVars('str', {'with1numbers': 'noop'}),
            throwsArgumentError);
        expect(() => substituteVars('str', {'with_under': 'noop'}),
            throwsArgumentError);
      });
    });
  });
}

void _expect(String original, Map<String, String> vars, String result) {
  expect(substituteVars(original, vars), result);
}
import 'dart:async';
import 'dart:html' as html;
import 'package:stagexl/stagexl.dart';
import 'dart:math';

Future<void> main() async {
  var options = StageOptions()
    ..backgroundColor = Color.White
    ..renderEngine = RenderEngine.WebGL;

  var canvas = html.querySelector('#stage');
  var stage = Stage(canvas, width: 1280, height: 800, options: options);

  var renderLoop = RenderLoop();
  renderLoop.addStage(stage);

  var resourceManager = ResourceManager();
  resourceManager.addBitmapData('dart', 'images/dart@1x.png');

  await resourceManager.load();

  var logoData = resourceManager.getBitmapData('dart');
  var logo = Sprite();
  logo.addChild(Bitmap(logoData));

  logo.pivotX = logoData.width / 2;
  logo.pivotY = logoData.height / 2;

  // Place it at top center.
  logo.x = 1280 / 2;
  logo.y = 0;

  stage.addChild(logo);

  // And let it fall.
  var tween = stage.juggler.addTween(logo, 3, Transition.easeOutBounce);
  tween.animate.y.to(800 / 2);

  // Add some interaction on mouse click.
  Tween rotation;
  logo.onMouseClick.listen(


ndariesDownTree,
    moveRangeBoundariesUpTree,
} from './range/Boundaries';

import type { Squire } from './Editor';

// ---

const indexOf = Array.prototype.indexOf;

// The (non-standard but supported enough) innerText property is based on the
// render tree in Firefox and possibly other browsers, so we must insert the
// DOM node into the document to ensure the text part is correct.
const setClipboardData = (
    event: ClipboardEvent,
    contents: Node,
    root: HTMLElement,
    toCleanHTML: null | ((html: string) => string),
    toPlainText: null | ((html: string) => string),
    plainTextOnly: boolean,
): void => {
    const clipboardData = event.clipboardData!;
    const body = document.body;
    const node = createElement('DIV') as HTMLDivElement;
    let html: string | undefined;
    let text: string | undefined;

    if (
        contents.childNodes.length === 1 &&
        contents.childNodes[0] instanceof Text
    ) {
        // Replace nbsp with regular space;
        // eslint-disable-next-line no-irregular-whitespace
        text = contents.childNodes[0].data.replace(/ /g, ' ');
        plainTextOnly = true;
    } else {
        node.appendChild(contents);
        html = node.innerHTML;
        if (toCleanHTML) {
            html = toCleanHTML(html);
        }
    }

    if (text !== undefined) {
        // Do nothing; we were copying plain text to start
    } else if (toPlainText && html !== undefined) {
        text = toPlainText(html);
    } else {
        // Firefox will add an extra new line for BRs at the end of block when
        // calculating innerText, even though they don't actually affect
        // display, so we need to remove them first.
        cleanupBRs(node, root, true);
        node.setAttribute(
            'style',
            'position:fixed;overflow:hidden;bottom:100%;right:100%;',
        );
        body.appendChild(node);
        text = node.innerText || node.textContent!;
        // Replace nbsp with regular space
        // eslint-disable-next-line no-irregular-whitespace
        text = text.replace(/ /g, ' ');
        body.removeChild(node);
    }
    // Firefox (and others?) returns unix line endings (\n) even on Windows.
    // If on Windows, normalise to \r\n, since Notepad and some other crappy
    // apps do not understand just \n.
    if (isWin) {
        text = text.replace(/\r?\n/g, '\r\n');
    }

    if (!plainTextOnly && html && text !== html) {
        clipboardData.setData('text/html', html);
    }
    clipboardData.setData('text/plain', text);
    event.preventDefault();
};

const extractRangeToClipboard = (
    event: ClipboardEvent,
    range: Range,
    root: HTMLElement,
    removeRangeFromDocument: boolean,
    toCleanHTML: null | ((html: string) => string),
    toPlainText: null | ((html: string) => string),
    plainTextOnly: boolean,
): boolean => {
    // Edge only seems to support setting plain text as of 2016-03-11.
    if (!isLegacyEdge && event.clipboardData) {
        // Clipboard content should include all parents within block, or all
        // parents up to root if selection across blocks
        const startBlock = getStartBlockOfRange(range, root);
        const endBlock = getEndBlockOfRange(range, root);
        let copyRoot


package observer

import (
	"context"
	"fmt"
	"sync"
	"time"

	"github.com/hyperledger-twgc/tape/pkg/infra"
	"github.com/hyperledger-twgc/tape/pkg/infra/basic"
	"github.com/hyperledger-twgc/tape/pkg/infra/bitmap"

	"github.com/hyperledger/fabric-protos-go-apiv2/peer"
	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"
)

// BlockCollector keeps track of committed blocks on multiple peers.
// This is used when a block is considered confirmed only when committed
// on a certain number of peers within network.
type BlockCollector struct {
	sync.Mutex
	thresholdP, totalP, totalTx int
	registry                    map[uint64]*bitmap.BitMap
	ctx                         context.Context
	blockCh                     chan *AddressedBlock
	finishCh                    chan struct{}
	logger                      *log.Logger
	once                        *sync.Once
	printResult                 bool // controls whether to print block commit message. Tests set this to false to avoid polluting stdout.
	finishflag                  bool
}

// AddressedBlock describe the source of block
type AddressedBlock struct {
	*peer.FilteredBlock
	Address int // source peer's number
	Now     time.Duration
}

// NewBlockCollector creates a BlockCollector
func NewBlockCollector(threshold int, totalP int,
	ctx context.Context,
	blockCh chan *AddressedBlock,
	finishCh chan struct{},
	totalTx int,
	printResult bool,
	logger *log.Logger,
	once *sync.Once, finishflag bool) (*BlockCollector, error) {
	registry := make(map[uint64]*bitmap.BitMap)
	if threshold <= 0 || totalP <= 0 {
		return nil, errors.New("threshold and total must be greater than zero")
	}
	if threshold > totalP {
		return nil, errors.Errorf("threshold [%d] must be less than or equal to total [%d]", threshold, totalP)
	}
	return &BlockCollector{
		thresholdP:  threshold,
		totalP:      totalP,
		totalTx:     totalTx,
		registry:    registry,
		ctx:         ctx,
		blockCh:     blockCh,
		finishCh:    finishCh,
		printResult: printResult,
		logger:      logger,
		once:        once,
		finishflag:  finishflag,
	}, nil
}

func (bc *BlockCollector) Start() {
	for {
		select {
		case block := <-bc.blockCh:
			bc.commit(block)
		case <-bc.ctx.Done():
			return
		}
	}
}

// TODO This function contains too many functions and needs further optimization
// commit commits a block to collector.
// If the number of peers on which this block has been committed has satisfied thresholdP,
// adds the number to the totalTx.
func (bc *BlockCollector) commit(block *AddressedBlock) {
	breakbynumber := true
	if bc.totalTx <= 0 {
		breakbynumber = false
	}
	bitMap, ok := bc.registry[block.Number]
	if !ok {
		// The block with Number is received for the first time
		b, err := bitmap.NewBitMap(bc.totalP)
		if err != nil {
			panic("Can not make new bitmap for BlockCollector" + err.Error())
		}
		bc.registry[block.Number] = &b
		bitMap = &b
	}
	// When the block from Address has been received before, return directly.
	if bitMap.Has(block.Address) {
		return
	}

	bitMap.Set(block.Address)
	cnt := bitMap.Count()

	// newly committed block just hits threshold
	if cnt == bc.thresholdP {
		if bc.printResult {
			// todo: logging
			// receive tx over threshold
			fmt.Pri


Chunk>,
}

impl exports::example::data_processor::processor::ProcessorState for ProcessorState {
    fn new(format: DataFormat) -> Self {
        ProcessorState {
            format,
            buffer_size: 4096, // 默认缓冲区大小
            chunks: Vec::new(),
        }
    }

    fn set_buffer_size(&mut self, size: u32) {
        self.buffer_size = size;
    }

    fn add_chunk(&mut self, chunk: DataChunk) -> ProcessResult {
        // 验证格式匹配
        if chunk.format != self.format {
            return Err(format!("格式不匹配: 期望 {:?}, 得到 {:?}", self.format, chunk.format));
        }

        // 验证大小
        if chunk.content.len() > self.buffer_size as usize {
            return Err(format!("块大小 ({}) 超过缓冲区大小 ({})", chunk.content.len(), self.buffer_size));
        }

        // 处理并存储块
        let processed_chunk = self.process_chunk(chunk)?;
        self.chunks.push(processed_chunk.clone());

        Ok(processed_chunk)
    }

    fn finalize(&mut self) -> Vec<DataChunk> {
        let result = self.chunks.clone();
        self.chunks.clear();
        result
    }
}

impl ProcessorState {
    // 辅助方法
    fn process_chunk(&self, chunk: DataChunk) -> ProcessResult {
        // 处理单个数据块的实现
        // ...

        Ok(chunk)
    }
}

// 辅助函数
fn validate_data(data: &[u8], format: DataFormat) -> bool {
    // 根据格式验证数据
    match format {
        DataFormat::Json => validate_json(data),
        DataFormat::Xml => validate_xml(data),
        DataFormat::Binary => true, // 二进制数据总是有效的
        DataFormat::Custom => validate_custom_format(data),
    }
}

fn optimize_data(data: Vec<u8>, format: DataFormat) -> Vec<u8> {
    // 根据格式优化数据
    // ...

    data
}

fn compress_data(data: Vec<u8>) -> Vec<u8> {
    // 压缩数据
    // ...

    data
}

fn encrypt_data(data: Vec<u8>) -> Vec<u8> {
    // 加密数据
    // ...

    data
}

fn get_current_timestamp() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
}

// 格式验证辅助函数
fn validate_json(data: &[u8]) -> bool {
    if let Ok(s) = std::str::from_utf8(data) {
        serde_json::from_str::<serde_json::Value>(s).is_ok()
    } else {
        false
    }
}

fn validate_xml(data: &[u8]) -> bool {
    // 验证XML格式
    // ...

    true
}

fn validate_custom_format(data: &[u8]) -> bool {
    // 验证自定义格式
    // ...

    true
}
```

### 7.3 组件间通信

WebAssembly组件如何相互通信：

**通信模式**：

1. **直接调用**：跨组件函数调用
2. **资源传递**：通过资源句柄共享状态
3. **数据传递**：通过类型化的接口传输数据

**多组件系统示例**：

```wit
// 系统定义
package


 ({type: 'SET_CARDS', cards} as const)
export const setCurrentPackIdAC = (packID: string) => ({type: 'SET_CURRENT_PACK_ID', packID} as const)
export const setCurrentCardPageAC = (currentPage: number) => ({type: SET_CURRENT_CARD_PAGE, currentPage} as const)
export const setCurrentPackUserIdAC = (currentPackUserID: string) => ({type: 'SET_CURRENT_PACK_USER_ID', currentPackUserID} as const)

//Thunk creators
export const getCardsTC = (cardsPack_id: string,currentPage?:number) => {
    return (dispatch: Dispatch<any>) => {
        dispatch(setStatusAppAC('loading'))
        CardsAPI.getCards(cardsPack_id,"",currentPage)
            .then((res) => {
                dispatch(setCardsAC(res.data.cards))
                dispatch(setCardPacksTotalCountAC(res.data.cardsTotalCount))
                dispatch(setStatusAppAC('succeeded'))
            })

    }
}
export const deleteCard = (cardID: string, packID: string) => {
    return (dispatch: Dispatch<any>) => {
        CardsAPI.deleteCard(cardID)
            .then((res) => {
                dispatch(getCardsTC(packID))
            })
    }
}
export const createCard = (card: PostCardParamsType, packID: string) => {
    return (dispatch: Dispatch<any>) => {
        CardsAPI.postCard(card)
            .then((res) => {
                dispatch(getCardsTC(packID))
            })
    }
}

//types
type ActionsTypes =
    | ReturnType<typeof setCardsAC>
    | ReturnType<typeof setCurrentPackIdAC>
    | SetCardPacksTotalCountActionType
    | SetStatusApp
    | ReturnType<typeof setCurrentCardPageAC>
    | ReturnType<typeof setCurrentPackUserIdAC>
    |SetPageSize

type ThunksDispatch = ThunkAction<Promise<void>, AppRootStateType, unknown, ActionsTypes>

import { Reservation } from '@core/reservations';

/**
 * Full description of the state object.
 * **Be sure to have a *core* service** (ie. injected in the `AppComponent`)
 * **where you initialize the value** (ie. in the service's constructor)
 * (otherwise when listening to this property, the observable could hang on forever).
 */
export interface State {
  reservations: Reservation[];
  reservationsCount: number;
  isAuthenticated: boolean;
}
import { AbstractFactory } from "../abstract/abstractFactory";
import { ProductA } from "../interface/productA";
import { ProductA1 } from "../products/productsA/productA1";
import { ProductB } from "../interface/productB";
import { ProductB1 } from "../products/productsB/productB1";

export class ConcreteFactory1 implements AbstractFactory {
    public createProductA(): ProductA {
        return new ProductA1();
    }

    public createProductB(): ProductB {
        return new ProductB1();
    }
}/**
 * 公共模块
 */
class Common{

    /**     * 窗口大小更改事件列表     */
    private windowResizeHandlers:Function[]=[];

    /**     * 添加窗口更改监听     */
    public addResizeHandler(fun:Function):void{
        this.windowResizeHandlers.push(fun);
    }

    /**     * 移除监听     */
    public removeResizeHandler(fun:Function):void{
        for (let i = 0; i < this.windowResizeHandlers.length; i++) {
            let fun_:Function=this.windowResizeHandlers[i];
            if(fun_==fun){
                this.windowResizeHandlers.splice(i,1);
                i--;
                continue;
            }
        }
    }


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

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Graphics;
using Android.Util;

namespace HoloGraphLibrary
{
	public class PieGraph : View
	{
		private List<PieSlice> slices = new List<PieSlice>();
		private Paint paint = new Paint();
		private Path path = new Path();

		private int indexSelected = -1;
		private int thickness = 50;
		private OnSliceClickedListener listener;

		public PieGraph(Context context):base(context) {
		}
		public PieGraph(Context context, IAttributeSet attrs):base(context,attrs) {
		}
		protected override void OnDraw(Canvas canvas)  {
			canvas.DrawColor(Color.Transparent);
			paint.Reset();
			paint.AntiAlias = true;
			float midX, midY, radius, innerRadius;
			path.Reset();

			float currentAngle = 270;
			float currentSweep;
			float totalValue = 0;
			float padding = 2;

			midX = Width / 2;
			midY = Height/2;
			if (midX < midY){
				radius = midX;
			} else {
				radius = midY;
			}
			radius -= padding;
			innerRadius = radius - thickness;

			foreach (PieSlice slice in slices) {
				totalValue += slice.getValue();
			}

			int count = 0;
			foreach (PieSlice slice in slices) {
				Path p = new Path();
				paint.Color = slice.getColor ();
				currentSweep = (slice.getValue()/totalValue)*(360);
				p.ArcTo(new RectF(midX-radius, midY-radius, midX+radius, midY+radius), currentAngle+padding, currentSweep - padding);
				p.ArcTo(new RectF(midX-innerRadius, midY-innerRadius, midX+innerRadius, midY+innerRadius), (currentAngle+padding) + (currentSweep - padding), -(currentSweep-padding));
				p.Close ();

				slice.setPath(p);
				slice.setRegion(new Region((int)(midX-radius), (int)(midY-radius), (int)(midX+radius), (int)(midY+radius)));
				canvas.DrawPath(p, paint);

				if (indexSelected == count && listener != null){
					path.Reset();
					paint.Color = slice.getColor ();
					paint.Color = Color.ParseColor ("#33B5E5");
					paint.Alpha=100;

					if (slices.Count > 1) {
						path.ArcTo(new RectF(midX-radius-(padding*2)


.Equals(this.SelectedFilter)) && (ShowSnapshots || imageHistoryItem.Type == CaptureSequence.ImageTypes.LIGHT)) {
                        imageHistoryItem.Index = index++;
                        ObservableImageHistoryView.Add(imageHistoryItem);
                    }
                }
            }
        }

        public void AppendAutoFocusPoint(AutoFocusReport report) {
            if (report != null) {
                ImageHistoryPoint last;
                lock (lockObj) {
                    last = ImageHistory.LastOrDefault();
                }

                if (last == null) {
                    last = new ImageHistoryPoint(0, "NONE");
                }
                last.PopulateAFPoint(report);
                AutoFocusPoints.Add(last);
                if ((this.SelectedFilter.Equals(AllFilters) || last.Filter.Equals(this.SelectedFilter)) && (ShowSnapshots || last.Type == CaptureSequence.ImageTypes.LIGHT)) {
                    AutoFocusPointsView.Add(last);
                }
            }
        }

        public void PlotClear() {
            ObservableImageHistory.Clear();
            AutoFocusPoints.Clear();
            ObservableImageHistoryView.Clear();
            AutoFocusPointsView.Clear();
            ImageHistory.Clear();
            index = 0;
            _exposureId = 0;
            Logger.Info("Image history has been cleared");
        }

        public void PlotSave() {
            if (this.ObservableImageHistory.Count != 0) {
                FileDialog sfd = new SaveFileDialog();
                sfd.FileName = NINA.Core.Utility.CoreUtil.ApplicationStartDate.ToString("yyyy-MM-dd") + "_history.csv";
                sfd.InitialDirectory = Path.GetDirectoryName(ActiveProfile.SequenceSettings.DefaultSequenceFolder);
                if (sfd.ShowDialog() == true) {
                    if (!sfd.FileName.ToLower().EndsWith(".csv")) sfd.FileName += ".csv";
                    using (var writer = new StreamWriter(sfd.FileName))
                    using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) {
                        csv.Context.RegisterClassMap<ImageHistoryPointMap>();
                        csv.WriteRecords(ObservableImageHistory);
                    }
                }
                Logger.Info($"Image history has been saved to {sfd.FileName}");
            }
        }

        public ICommand PlotClearCommand { get; private set; }
        public ICommand PlotSaveCommand { get; private set; }
    }
}


// Copyright (C) 2009,2010,2011,2012 GlavSoft LLC.
// All rights reserved.
//
//-------------------------------------------------------------------------
// This file is part of the TightVNC software.  Please visit our Web site:
//
//                       http://www.tightvnc.com/
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//-------------------------------------------------------------------------
//

#ifndef _MULTI_THREAD_TCP_SERVER_H_
#define _MULTI_THREAD_TCP_SERVER_H_

#include "thread/Thread.h"
#include "util/Exception.h"
#include "network/socket/SocketIPv4.h"

/**
 * Abstract multithreaded TCP server class.
 * Bind on specified host and port and listening for connections,
 * but don't know what to do with incoming connections.
 * @usage create subclass of TcpServer and call start (or use autoStart flag)
 * in TcpServer constructor.
 */
class TcpServer : private Thread
{
public:
  /**
   * Creates new TcpServer that listens for incoming connection after creation.
   * @param bindHost host to bind.
   * @param bindPort port to bind.
   * @param bool autoStart if true, then server starts listening for incoming connections
   * in it's own thread, if false, then you must call protected start() method later from subclass.
   * @param lockAddr determinates if need to lock adress to other processes cannot reuse it.
   * @throws Exception if fail to create tcp server.
   */
  TcpServer(const TCHAR *bindHost,
            unsigned short bindPort,
            bool autoStart = false,
            bool lockAddr = false) throw(Exception);
  /**
   * Closes listening socket, terminates tcp server thread and
   * deletes tcp server object.
   */
  virtual ~TcpServer();

  /**
   * Returns bind host.
   */
  const TCHAR *getBindHost() const;

  /**
   * Returns bind port.
   */
  unsigned short getBindPort() const;

protected:
  /**
   * Starts tcp server thread (listen for incoming connections).
   */
  virtual void start();

  /**
   * Called from tcp server thread when server accepts connection to process it.
   * @param socket incoming connection socket.
   */
  virtual void onAcceptConnection(SocketIPv4 *socket) = 0;

  /**
   * Inherited from Thread class.
   * Listening for incoming tcp connections.
   */
  virtual void execute();

private:
  /**
   * Listening socket.
   */
  SocketIPv4 m_listenSocket;
  /**
   * Host to bind.
   */
  StringStorage m_bindHost;
  /**
   * Port to bind.
   */
  unsigned short m_bindPort;
};

#endif


.AND P5, PT, PT, PT, PT;
--:-:-:-:0      BFE.U32 super_y, tid, param_superYI;
--:-:1:-:2      LDS blkC, [addr_blk_C];
--:-:-:-:1      ISETP.LT.AND P6, PT, gys, param_GYS, PT;
<SCHEDULE_BLOCK>
01:-:-:-:1      SHL gx, gxs, param_shiftXI;
--:-:-:-:1      SHL gy, gys, param_shiftYI;
--:-:-:-:1      IADD gx, gx, super_x;
--:-:-:-:1      IADD gy, gy, super_y;
--:-:-:-:1      XMAD.U16.U16      offset, gx,   param_N,   n;
--:-:-:-:1      XMAD.U16.U16.LO2C offset, gy,   param_XN,  offset;
--:-:-:-:1      XMAD.U16.U16.LO2C offset, blkC, param_YXN, offset;
</SCHEDULE_BLOCK>
--:-:-:Y:5  @P6 BRA.U IMAGE_LOOP;

// Set n to loop remaining times
--:-:-:-:1      LOP.AND.NZ P5, init, pred_bits,  3;
--:-:-:-:1      MOV nloop, param_loopN;
--:-:-:-:1      MOV N,     param_N;
--:-:-:Y:a      LOP.AND   pred_bits, pred_bits, ~3;
--:-:-:-:0      VMAD.U16.U16 n, -init, nloop, N;
--:-:-:Y:5  @P5 BRA.U IMAGE_LOOP;
--:-:-:Y:5      BRA.U END_LOOP;
    } : q{
// Advance x offset/preds
<SCHEDULE_BLOCK>
--:-:-:-:1      IADD gxs, gxs, param_strideX;
--:-:-:-:1      IADD offset, offset, param_loopX;
--:-:-:-:1      ISETP.LT.AND P5, PT, gxs, param_GXS, P6;
--:-:-:-:1      SHL x, gxs, param_shiftX;
01:-:-:-:1      BFE.U32 super_x, tid, param_superX;
--:-:-:-:1      BFE.U32 n, tid, param_superN;
--:-:-:-:1      ISCADD x, super_x,  x, 1;
--:-:-:-:1      IADD x, x, -param_pad_x;
--:-:-:-:1      IADD x1, x, 1;
--:-:-:-:1      IADD x2, x, 2;
--:-:-:-:1      IADD x3, x, 3;
--:-:-:-:1      ISETP.LT.AND P0, PT, x,  param_X, P6;
--:-:-:-:1      ISETP.LT.AND P1, PT, x1, param_X, P6;
--:-:-:-:1      ISETP.LT.AND P2, PT, x2, param_X, P6;
--:-:-:-:1      ISETP.LT.AND P3, PT, x3, param_X, P6;
--:-:-:-:1      ISETP.GE.AND P0, PT, x,  RZ, P0;
--:-:-:-:1      ISETP.GE.AND P1, PT, x1, RZ, P1;
--:-:-:-:1      ISETP.GE.AND P2, PT, x2, RZ, P2;
--:-:-:-:1      ISETP.GE.AND P3, PT, x3, RZ, P3;
--:-:-:-:1      P2R mask_x, PR, RZ, 0x0f;
// Extract y + init + buffer bits
--:-:-:-:1      BFE.U32 mask_y, pred_bits, 0x710;
--:-:-:-:1


/*
 * Copyright (c) 2008, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Willow Garage, Inc. nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/** \author Wim Meeussen */

#ifndef TF2_ROS__BUFFER_H_
#define TF2_ROS__BUFFER_H_

#define BUFFER_HEADER_DEPRECATION This header is obsolete, \
  please include "tf2_ros/buffer.hpp" instead
#ifdef _MSC_VER
  #pragma message(BUFFER_HEADER_DEPRECATION)
#else
  #warning BUFFER_HEADER_DEPRECATION
#endif

#include <tf2_ros/buffer.hpp>

#endif  // TF2_ROS__BUFFER_H_


click())
        onView(withId(R.id.pocketpaint_image_name_save_text))
            .perform(replaceText("12345test12345"))
        onView(withText(R.string.save_button_text)).perform(click())
        onView(isRoot()).perform(waitFor(300))
        assertNotNull(activity.model.savedPictureUri)
        addUriToDeletionFileList(activity.model.savedPictureUri)
        onTopBarView().performOpenMoreOptions()
        onView(withText(R.string.menu_save_image)).perform(click())
        onView(withText(R.string.save_button_text)).perform(click())
        onView(withText(R.string.overwrite_button_text)).check(matches(isDisplayed()))
    }

    @Test
    fun testCheckImageNumberIncrementAfterSaveWithStandardName() {
        FileIO.filename = "image"
        val imageNumber = launchActivityRule.activity.presenter.imageNumber
        onTopBarView().performOpenMoreOptions()
        onView(withText(R.string.menu_save_image)).perform(click())
        onView(withText(R.string.save_button_text)).perform(click())
        onView(isRoot()).perform(waitFor(200))
        assertNotNull(activity.model.savedPictureUri)
        addUriToDeletionFileList(activity.model.savedPictureUri)
        onDrawingSurfaceView().perform(touchAt(MIDDLE))
        onTopBarView().performOpenMoreOptions()
        onView(withText(R.string.menu_save_image)).perform(click())
        val newImageNumber = launchActivityRule.activity.presenter.imageNumber
        assertEquals((imageNumber + 1).toLong(), newImageNumber.toLong())
    }

    @Test
    fun testCheckImageNumberSameAfterSaveWithNonStandardName() {
        onDrawingSurfaceView().perform(touchAt(MIDDLE))
        onTopBarView().performOpenMoreOptions()
        onView(withText(R.string.menu_save_image)).perform(click())
        val imageNumber = launchActivityRule.activity.presenter.imageNumber
        onView(withId(R.id.pocketpaint_image_name_save_text))
            .perform(replaceText("test9876"))
        onView(withText(R.string.save_button_text)).perform(click())
        assertNotNull(activity.model.savedPictureUri)
        addUriToDeletionFileList(activity.model.savedPictureUri)
        val newImageNumber = launchActivityRule.activity.presenter.imageNumber
        assertEquals(imageNumber.toLong(), newImageNumber.toLong())
    }

    @Test
    fun testCheckSaveFileWithDifferentFormats() {
        onDrawingSurfaceView().perform(touchAt(MIDDLE))
        onTopBarView().performOpenMoreOptions()
        onView(withText(R.string.menu_save_image)).perform(click())
        onView(withId(R.id.pocketpaint_save_info_title)).check(matches(isDisplayed()))
        onView(withId(R.id.pocketpaint_image_name_save_text)).check(matches(isDisplayed()))
        onView(withId(R.id.pocketpaint_save_dialog_spinner)).check(matches(isDisplayed()))
        onView(withId(R.id.pocketpaint_save_dialog_spinner)).perform(click())
        onData(allOf(`is`(instanceOf<Any>(String::class.java)), `is`("png")))
            .inRoot(RootMatchers.isPlatformPopup()).perform(click())
        onView(withId(R.id.pocketpaint_image_name_save_text))
            .perform(replaceText(defaultFileName))
        onView(withText(R.string.save_button_text)).perform(click())
        assertNotNull(activity.model.savedPictureUri)
        addUriToDeletionFileList(activity.model.savedPictureUri)
        val oldFile = File(activ


 { 1, 1, 1, 1, 2, 2, 3, 3, 3 };
            var longestSubsequence = LongestSubsequenceOfEquals.FindLongestSubsequence(collection).ToList();
            var expectedLongestSubsequence = new List<int>() { 1, 1, 1, 1 };

            CollectionAssert.AreEqual(expectedLongestSubsequence, longestSubsequence);
        }

        [TestMethod]
        public void ShouldReturnOnlyOneSubsequenceAtTheEnd()
        {
            var collection = new List<int>() { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 };
            var longestSubsequence = LongestSubsequenceOfEquals.FindLongestSubsequence(collection).ToList();
            var expectedLongestSubsequence = new List<int>() { 4, 4, 4, 4 };

            CollectionAssert.AreEqual(expectedLongestSubsequence, longestSubsequence);
        }

        [TestMethod]
        public void ShouldReturnOnlyOneSubsequenceAtTheMiddle()
        {
            var collection = new List<int>() { 1, 2, 2, 3, 3, 3, 3, 4, 4, 4 };
            var longestSubsequence = LongestSubsequenceOfEquals.FindLongestSubsequence(collection).ToList();
            var expectedLongestSubsequence = new List<int>() { 3, 3, 3, 3 };

            CollectionAssert.AreEqual(expectedLongestSubsequence, longestSubsequence);
        }

        [TestMethod]
        public void ShouldReturnOnlyOneSubsequenceAtTheMiddleOnStrings()
        {
            var collection = new List<string>() { "a", "b", "b", "b", "c", "c" };
            var longestSubsequence = LongestSubsequenceOfEquals.FindLongestSubsequence(collection).ToList();
            var expectedLongestSubsequence = new List<string>() { "b", "b", "b" };

            CollectionAssert.AreEqual(expectedLongestSubsequence, longestSubsequence);
        }
    }
}


get('popOverTarget');
  }

  getPopOverAnchor(): HTMLElement {
    return this.get('popOverAnchor');
  }

  getPopOverValue(): string {
    return this.get('popOverValue');
  }

  setPopOverValue(value: string): this {
    return this.set('popOverValue', value) as this;
  }

  getPopOverAction(): Function {
    return this.get('popOverAction');
  }

  setPopOver(target: PopOverTarget, anchor: HTMLElement, value: string, action: (value: string) => void): this {
    return this.set('popOverTarget', target).set('popOverAnchor', anchor)
      .set('popOverValue', value).set('popOverAction', action) as this;
  }
}
//<----------------GETTERS & SETTERS------------------------->

class User {
	id: number;
	private _username: string;
	private _email: string;

	constructor(id: number, username: string, email: string) {
		this.id = id;
		this._username = username;
		this._email = email;
	}

	get username() {
		return this._username;
	}

	set username(newUsername) {
		if (newUsername.length > 10) {
			throw new Error('The Name is too long');
		}

		this._username = newUsername;
	}

	get email() {
		return this._email;
	}

	set email(newEmail) {
		if (!newEmail.includes('@')) {
			throw new Error('Has To be An Email');
		}

		this._email = newEmail;
	}
}

const myUser = new User(1, 'Nilson', 'nilson@gmail.com');

console.log(myUser);

myUser.email = 'nilsonkr@hotmail.com';
myUser.username = 'NilsonKr';

console.log(myUser);

// myUser.email = 'sdsASDAS'; //Set Error
// myUser.username = 'Nilson Diaz Perez'; //Set Error
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { Platform } from 'ionic-angular';

@Injectable()
export class HistorialProvider {

  historial:string[]=[];

  constructor(
    public http: HttpClient,
    private storage: Storage,
    private plarform: Platform) {

    console.log('Hello HistorialProvider Provider');
  }

  leerHistorial(){

    let promesa = new Promise( (resolve, reject) => {

      if (this.plarform.is("cordova")){
        //estamos en el dispositivo
        this.storage.ready().then( ()=> {
          this.storage.get("historial").then( (historial) => {
            this.historial = historial;
            resolve();
          });
        });
      }else{
        //estamos en la PC
        if (localStorage.getItem("historial")){
          this.historial = JSON.parse(localStorage.getItem("historial"));
          resolve();
        }
      }
    });

    return promesa;
  }

  agregar(busqueda:string){
    this.historial.push(busqueda);
    this.guardarHistorial();
  }

  guardarHistorial(){
    if (this.plarform.is("cordova")){
      //estamos en el dispositivo
      this.storage.ready().then( ()=> {
        this.storage.set("historial", this.historial);
      });
    }else{
      //estamos en la PC
      localStorage.setItem("historial", JSON.stringify(this.historial));
    }
  }
}
import fetch from 'node-fetch';
import {RedditApiItemInterface, RedditApiResponseInterface} from './reddit-api-response.interface';
import {FetchOptionsInterface} from './fetch-options.interface';

export class


"
  },
  {
    "name": "avoid_void_async",
    "description": "Avoid `async` functions that return `void`.",
    "categories": [
      "style"
    ],
    "state": "stable",
    "incompatible": [],
    "sets": [],
    "fixStatus": "hasFix",
    "details": "**DO** mark `async` functions as returning `Future<void>`.\n\nWhen declaring an `async` method or function which does not return a value,\ndeclare that it returns `Future<void>` and not just `void`.\n\n**BAD:**\n```dart\nvoid f() async {}\nvoid f2() async => null;\n```\n\n**GOOD:**\n```dart\nFuture<void> f() async {}\nFuture<void> f2() async => null;\n```\n\n**EXCEPTION:**\n\nAn exception is made for top-level `main` functions, where the `Future`\nannotation *can* (and generally should) be dropped in favor of `void`.\n\n**GOOD:**\n```dart\nFuture<void> f() async {}\n\nvoid main() async {\n  await f();\n}\n```",
    "sinceDartSdk": "2.1"
  },
  {
    "name": "avoid_web_libraries_in_flutter",
    "description": "Avoid using web-only libraries outside Flutter web plugin packages.",
    "categories": [
      "errorProne",
      "flutter",
      "web"
    ],
    "state": "stable",
    "incompatible": [],
    "sets": [
      "flutter"
    ],
    "fixStatus": "noFix",
    "details": "**AVOID** using web libraries, `dart:html`, `dart:js` and\n`dart:js_util` in Flutter packages that are not web plugins. These libraries are\nnot supported outside of a web context; functionality that depends on them will\nfail at runtime in Flutter mobile, and their use is generally discouraged in\nFlutter web.\n\nWeb library access *is* allowed in:\n\n* plugin packages that declare `web` as a supported context\n\notherwise, imports of `dart:html`, `dart:js` and  `dart:js_util` are disallowed.",
    "sinceDartSdk": "2.6"
  },
  {
    "name": "await_only_futures",
    "description": "Await only futures.",
    "categories": [
      "style"
    ],
    "state": "stable",
    "incompatible": [],
    "sets": [
      "core",
      "recommended",
      "flutter"
    ],
    "fixStatus": "hasFix",
    "details": "**AVOID** using await on anything which is not a future.\n\nAwait is allowed on the types: `Future<X>`, `FutureOr<X>`, `Future<X>?`,\n`FutureOr<X>?` and `dynamic`.\n\nFurther, using `await null` is specifically allowed as a way to introduce a\nmicrotask delay.\n\n**BAD:**\n```dart\nmain() async {\n  print(await 23);\n}\n```\n\n**GOOD:**\n```dart\nmain() async {\n  await null; // If a delay is really intended.\n  print(23);\n}\n```",
    "sinceDartSdk": "2.0"
  },
  {
    "name": "camel_case_extensions",
    "description": "Name extensions using UpperCamelCase.",
    "categories": [
      "effectiveDart",
      "style"
    ],
    "state": "stable",
    "incompatible": [],
    "sets": [
      "core",
      "recommended",
      "flutter"
    ],
    "fixStatus": "noFix",
    "details": "From [Effective Dart](https://dart.dev/effective-dart/style#do-name-extensions-using-uppercamelc