public Builder setItemList(
          int index, emu.grasscutter.net.proto.EquipParamOuterClass.EquipParam.Builder builderForValue) {
        if (itemListBuilder_ == null) {
          ensureItemListIsMutable();
          itemList_.set(index, builderForValue.build());
          onChanged();
        } else {
          itemListBuilder_.setMessage(index, builderForValue.build());
        }
        return this;
      }

/**
       * repeated .EquipParam itemList = 9;
       */


public Builder setExpeditionStateValue(int value) {

        expeditionState_ = value;
        onChanged();
        return this;
      }

/**
       * <code>.AvatarExpeditionState expeditionState = 16;</code>
       * @param value The enum numeric value on the wire for expeditionState to set.
       * @return This builder for chaining.
       */


public Builder setForwardTypeValue(int value) {

        forwardType_ = value;
        onChanged();
        return this;
      }

/**
       * <code>.ForwardType forwardType = 5;</code>
       * @param value The enum numeric value on the wire for forwardType to set.
       * @return This builder for chaining.
       */


private com.google.protobuf.SingleFieldBuilderV3<
          emu.grasscutter.net.proto.VectorOuterClass.Vector, emu.grasscutter.net.proto.VectorOuterClass.Vector.Builder, emu.grasscutter.net.proto.VectorOuterClass.VectorOrBuilder>
          getSkillAnchorPositionFieldBuilder() {
        if (skillAnchorPositionBuilder_ == null) {
          skillAnchorPositionBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
              emu.grasscutter.net.proto.VectorOuterClass.Vector, emu.grasscutter.net.proto.VectorOuterClass.Vector.Builder, emu.grasscutter.net.proto.VectorOuterClass.VectorOrBuilder>(
                  getSkillAnchorPosition(),
                  getParentForChildren(),
                  isClean());
          skillAnchorPosition_ = null;
        }
        return skillAnchorPositionBuilder_;
      }

/**
       * <code>.Vector skillAnchorPosition = 1;</code>
       */


public java.util.List<emu.grasscutter.net.proto.SceneReliquaryInfoOuterClass.SceneReliquaryInfo.Builder>
           getReliquaryListBuilderList() {
        return getReliquaryListFieldBuilder().getBuilderList();
      }

/**
       * repeated .SceneReliquaryInfo reliquaryList = 9;
       */


public Builder clearCurVehicleInfo() {
        if (curVehicleInfoBuilder_ == null) {
          curVehicleInfo_ = null;
          onChanged();
        } else {
          curVehicleInfo_ = null;
          curVehicleInfoBuilder_ = null;
        }

        return this;
      }

/**
       * <code>.CurVehicleInfo curVehicleInfo = 20;</code>
       */


public Builder setMark(emu.grasscutter.net.proto.MapMarkPointOuterClass.MapMarkPoint value) {
        if (markBuilder_ == null) {
          if (value == null) {
            throw new NullPointerException();
          }
          mark_ = value;
          onChanged();
        } else {
          markBuilder_.setMessage(value);
        }

        return this;
      }

/**
       * <code>.MapMarkPoint mark = 10;</code>
       */


public Builder addLhjhgbpjpkl(
          int index, emu.grasscutter.net.proto.IrodoriChessMonsterInfoOuterClass.IrodoriChessMonsterInfo value) {
        if (lhjhgbpjpklBuilder_ == null) {
          if (value == null) {
            throw new NullPointerException();
          }
          ensureLhjhgbpjpklIsMutable();
          lhjhgbpjpkl_.add(index, value);
          onChanged();
        } else {
          lhjhgbpjpklBuilder_.addMessage(index, value);
        }
        return this;
      }

/**
       * repeated .IrodoriChessMonsterInfo lhjhgbpjpkl = 8;
       */


public boolean hasNeedPlayerLevel() {
        return needPlayerLevelBuilder_ != null || needPlayerLevel_ != null;
      }

/**
       * <code>.ChapterStateNotify.NeedPlayerLevel needPlayerLevel = 2;</code>
       * @return Whether the needPlayerLevel field is set.
       */


public Builder clearMailId() {

        mailId_ = 0;
        onChanged();
        return this;
      }

/**
       * uint32 mailId = 1;
       * @return This builder for chaining.
       */


@java.lang.Override
    public int getUnlockTaskListCount() {
      return unlockTaskList_.size();
    }

/**
     * repeated .BartenderTaskInfo unlockTaskList = 15;
     */


public Builder clearAsterMid() {
        if (asterMidBuilder_ == null) {
          asterMid_ = null;
          onChanged();
        } else {
          asterMid_ = null;
          asterMidBuilder_ = null;
        }

        return this;
      }

/**
       * <code>.AsterMidDetailInfo asterMid = 4;</code>
       */


public java.util.List<emu.grasscutter.net.proto.CustomCommonNodeInfoOuterClass.CustomCommonNodeInfo.Builder>
           getNodeListBuilderList() {
        return getNodeListFieldBuilder().getBuilderList();
      }

/**
       * repeated .CustomCommonNodeInfo nodeList = 1;
       */


public Builder setUnk3300NMDNLHLAKAMBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  checkByteStringIsUtf8(value);

        unk3300NMDNLHLAKAM_ = value;
        onChanged();
        return this;
      }

/**
       * string Unk3300_NMDNLHLAKAM = 11;
       * @param value The bytes for unk3300NMDNLHLAKAM to set.
       * @return This builder for chaining.
       */


public Builder addUsedItemList(
          int index, emu.grasscutter.net.proto.ItemParamOuterClass.ItemParam.Builder builderForValue) {
        if (usedItemListBuilder_ == null) {
          ensureUsedItemListIsMutable();
          usedItemList_.add(index, builderForValue.build());
          onChanged();
        } else {
          usedItemListBuilder_.addMessage(index, builderForValue.build());
        }
        return this;
      }

/**
       * repeated .ItemParam used_item_list = 14;
       */


public Builder addItemList(
          int index, emu.grasscutter.net.proto.ItemParamOuterClass.ItemParam.Builder builderForValue) {
        if (itemListBuilder_ == null) {
          ensureItemListIsMutable();
          itemList_.add(index, builderForValue.build());
          onChanged();
        } else {
          itemListBuilder_.addMessage(index, builderForValue.build());
        }
        return this;
      }

/**
       * repeated .ItemParam itemList = 9;
       */


public Builder clearItemParam() {
        if (itemParamBuilder_ == null) {
          itemParam_ = null;
          onChanged();
        } else {
          itemParam_ = null;
          itemParamBuilder_ = null;
        }

        return this;
      }

/**
       * <code>.ItemParam itemParam = 5;</code>
       */


public Builder clearUnk3300FAIAIJGCBJG() {
        unk3300FAIAIJGCBJG_ = java.util.Collections.emptyList();
        bitField0_ = (bitField0_ & ~0x00000001);
        onChanged();
        return this;
      }

/**
       * repeated .ClientInputType Unk3300_FAIAIJGCBJG = 2;
       * @return This builder for chaining.
       */


public static void makeAccessible(Field field) {
        if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
                || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
            field.setAccessible(true);
        }
    }

/**
     * 改变private/protected的成员变量为public，尽量不调用实际改动的语句，避免JDK的SecurityManager抱怨。
     */


public List<SysMenuEntity> getChildPerms(List<SysMenuEntity> list, int parentId) {
        List<SysMenuEntity> returnList = new ArrayList<SysMenuEntity>();
        for (Iterator<SysMenuEntity> iterator = list.iterator(); iterator.hasNext(); ) {
            SysMenuEntity t = (SysMenuEntity) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

/**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */


public static char readConfirmSelection() {
        System.out.print("确认是否预订(Y/N): ");
        char c;
        for (; ; ) {//无限循环
            //在这里，将接受到字符，转成了大写字母
            //y => Y n=>N
            String str = readKeyBoard(1, false).toUpperCase();
            c = str.charAt(0);
            if (c == 'Y' || c == 'N') {
                break;
            } else {
                System.out.print("选择错误，请重新输入：");
            }
        }
        return c;
    }

/**
     * 功能：读取键盘输入的确认选项，Y或N
     * 将小的功能，封装到一个方法中.
     * @return Y或N
     */


public static <T,R> BsonField min(final SFunction<T,?> fieldName, final SFunction<R,?> expression) {
        return min(fieldName.getFieldNameLine(),expression.getFieldNameLineOption());
    }

/**
     * 获取 $group 操作的字段名称，该字段名称表示应用于组内所有成员时给定表达式的最小值.
     *
     * @param fieldName {@link BsonField} 名称
     * @param expression 表达式
     * @return {@link BsonField}
     * @since mongodb.driver.manual reference/operator/aggregation/min/ $min
     */


public static LinearFillOutputField linear(final String field) {
        return new FillField(notNull("field", field),
                new Document("method", "linear"));
    }

/**
     * 返回一个使用 {@link WindowOutputFields#linearFill(String, Object) Linear} 方法的 {@link FillOutputField}.
     *

     * {@linkplain FillOptions#sortBy(Bson) Sorting} 是必需的。

     *
     * @param field 要填写的字段.
     * @return 请求的 {@link FillOutputField}.
     * @since mongodb.driver.manual core/document/#dot-notation Dot notation
     */


public static <T> Bson text(final SFunction<T,Object> fieldName) {
        notNull("fieldName", fieldName);
        return new BsonDocument(fieldName.getFieldNameLine(), new BsonString("text"));
    }

/**
     * 为给定字段上的文本索引创建索引键。
     *
     * @param fieldName 要在其上创建文本索引的字段
     * @return 索引详述
     */


public QueryCondition likeRaw(Object value, BooleanSupplier isEffective) {
        return likeRaw(value, isEffective.getAsBoolean());
    }


public static DistinctQueryColumn distinct(QueryColumn... columns) {
        return new DistinctQueryColumn(columns);
    }

/**
     * 对指定列进行去重。
     */


public static QueryWrapper selectCountOne() {
        return select(count(new RawQueryColumn("1")).as("temp_count_one"));
    }

/**
     * SELECT COUNT(1) as temp_count_one FROM table
     */


public <T> QueryWrapper ge(LambdaGetter<T> column, Object value) {
        and(QueryMethods.column(column).ge(value));
        return this;
    }

/**
     * 大于等于 {@code >=}
     *
     * @param column 列名, lambda 展示
     * @param value  值
     */


public Builder setRenderGL20(Boolean renderGL20) {
            this.renderGL20 = renderGL20;
            return this;
        }

/**
         * 是否支持OpenGL2.0
         * @param renderGL20 null 表示都可以， true表示要支持，false表示不支持
         */


public static String nbtToBase64(NbtMap nbtMap) {
        try (ByteArrayOutputStream stream = new ByteArrayOutputStream(); NBTOutputStream writer = org.cloudburstmc.nbt.NbtUtils.createWriter(stream)) {
            writer.writeTag(nbtMap);
            return Base64.getEncoder().encodeToString(stream.toByteArray());
        } catch (Exception e) {
            // Handle exceptions accordingly
            log.error("Failed to convert NBT to Base64", e);
        }
        return null;
    }

/**
     * Convert NBT to Base64.
     *
     * @param nbtMap the NBT map.
     *
     * @return the Base64 string.
     */


public static Map<String, Object> fromMap(String json) {
        return GSON.fromJson(json, new TypeToken<HashMap<String, Object>>() {
        }.getType());
    }

/**
     * Parse a JSON string to a map.
     *
     * @param json the JSON string.
     *
     * @return the map.
     */


static int countArgumentPlaceholders3(final char[] messagePattern, final int length, final int[] indices) {
        int result = 0;
        boolean isEscaped = false;
        for (int i = 0; i < length - 1; i++) {
            final char curChar = messagePattern[i];
            if (curChar == ESCAPE_CHAR) {
                isEscaped = !isEscaped;
            } else if (curChar == DELIM_START) {
                if (!isEscaped && messagePattern[i + 1] == DELIM_STOP) {
                    indices[result] = i;
                    result++;
                    i++;
                }
                isEscaped = false;
            } else {
                isEscaped = false;
            }
        }
        return result;
    }

/**
     * Counts the number of unescaped placeholders in the given messagePattern.
     *
     * @param messagePattern the message pattern to be analyzed.
     *
     * @return the number of unescaped placeholders.
     */


private void initFailover() {
        //第一层的fail指针指向root
        Queue<ACTrieNode> queue = new LinkedList<>();
        Map<Character, ACTrieNode> children = root.getChildren();
        for (ACTrieNode node : children.values()) {
            node.setFailover(root);
            queue.offer(node);
        }
        //构建剩余层数节点的fail指针,利用层次遍历
        while (!queue.isEmpty()) {
            ACTrieNode parentNode = queue.poll();
            for (Map.Entry<Character, ACTrieNode> entry : parentNode.getChildren().entrySet()) {
                ACTrieNode childNode = entry.getValue();
                ACTrieNode failover = parentNode.getFailover();
                // 在树中找到以childNode为结尾的字符串的最长前缀匹配，failover指向了这个最长前缀匹配的父节点
                while (failover != null && (!failover.hasChild(entry.getKey()))) {
                    failover = failover.getFailover();
                }
                //回溯到了root节点
                if (failover == null) {
                    childNode.setFailover(root);
                } else {
                    // 更新当前节点的回退指针
                    childNode.setFailover(failover.childOf(entry.getKey()));
                }
                queue.offer(childNode);
            }
        }
    }

/**
     * 初始化节点中的回退指针
     */


void injectProperties(BeanDefinition def, Class<?> clazz, Object bean) throws ReflectiveOperationException {
        // 在当前类查找Field和Method并注入:
        for (Field f : clazz.getDeclaredFields()) {
            tryInjectProperties(def, clazz, bean, f);
        }
        for (Method m : clazz.getDeclaredMethods()) {
            tryInjectProperties(def, clazz, bean, m);
        }
        // 在父类查找Field和Method并注入:
        Class<?> superClazz = clazz.getSuperclass();
        if (superClazz != null) {
            injectProperties(def, superClazz, bean);
        }
    }


public static boolean install(Context context, File apkFile) throws IOException {
        return isSupportSilentInstall() ? install(context, apkFile.getCanonicalPath()) : installNormal(context, apkFile.getCanonicalPath());
    }

/**
     * 自适应apk安装（如果设备有root权限就自动静默安装）
     *
     * @param context
     * @param apkFile apk文件
     * @return
     */


public abstract void checkVerifyCode(String identity, String verifyCode);

/**
     * 校验验证码是否通过
     *
     * @param identity   用户账号，可能为空。一般邮箱情况下会为空，手机情况下不为空
     * @param verifyCode 邮箱策略时为邮箱验证码；手机策略时为手机短信验证码
     */


public static void PrintBanner(String version) {
        System.out.println(BANNER +version);
    }


public String getBCP47LanguageTag() {
    if (isSetLocale()) {
      return getLocale().toLanguageTag();
    } else {
      return null;
    }
  }

/**
   * Returns the IETF BCP 47 Language Tag of the locale. E.g. zh-CN
   */


public static void replaceCreatedAtAndCreatedAtCSF(ThriftDocument document, int value) {
    removeField(document, EarlybirdFieldConstant.CREATED_AT_FIELD);
    removeField(document, EarlybirdFieldConstant.CREATED_AT_CSF_FIELD);

    addIntField(document, EarlybirdFieldConstant.CREATED_AT_FIELD, value);
    addIntField(document, EarlybirdFieldConstant.CREATED_AT_CSF_FIELD, value);
  }

/**
   * First remove the old timestamp if they exist.
   * Then add the created at and created at csf fields to the given thrift document.
   */


protected static LightweightLinearModel createForSchemaBased(
      String modelName,
      double bias,
      Map<Integer, Double> binaryFeaturesById,
      Map<Integer, Double> continuousFeaturesById,
      Map<Integer, DiscretizedFeature> discretizedFeaturesById) {
    return new LightweightLinearModel(modelName, bias, true,
        null, null, null,
        binaryFeaturesById, continuousFeaturesById, discretizedFeaturesById);
  }

/**
   * Create model for schema-based features
   */


public abstract int add(long termID, int scoreIncrement, int penaltyIncrement, int tweepCred);

/** Called to notify the accumulator that the given termID has occurred in a document
   *  Returns the current count of the given termID.
   */


public int getPackedValueIndex() {
    return packedValueIndex;
  }

/**
   * A simple getter of {@link #packedValueIndex}.
   */


public int searchCeil(
      K key,
      int skipListHead,
      SkipListComparator<K> comparator,
      @Nullable SkipListSearchFinger searchFinger) {
    assert comparator != null;

    // Perform regular search.
    final int foundPointer = search(key, skipListHead, comparator, searchFinger);

    // Return foundPointer if it is not the list head and the pointed value has key equal to the
    // given key; otherwise, return next pointer.
    if (foundPointer != skipListHead
        && comparator.compareKeyWithValue(key, getValue(foundPointer), INVALID_POSITION) == 0) {
      return foundPointer;
    } else {
      return getNextPointer(foundPointer);
    }
  }

/**
   * Ceil search on given {@param key}.
   *
   * @param key target key will be searched.
   * @param skipListHead index of the header tower of the skip list will be searched.
   * @param comparator comparator used for comparison when traversing through the skip list.
   * @param searchFinger {@link SkipListSearchFinger} to accelerate search speed.
   * @return index of the smallest value with key greater or equal to the given key.
   */


public List<String> getSegmentMetadata() {
    List<String> segmentMetadata = new ArrayList<>();
    for (SegmentInfo segment : getSegmentInfos(Filter.All, Order.OLD_TO_NEW)) {
      segmentMetadata.add(segment.getSegmentMetadata());
    }
    return segmentMetadata;
  }

/**
   * Gets metadata for segments for debugging purposes.
   */


@VisibleForTesting
  public static AntiGamingFilter newMock(boolean alwaysValue) {
    return new AntiGamingFilter(alwaysValue) {
      @Override
      public void startSegment(EarlybirdIndexSegmentAtomicReader reader) {
      }
    };
  }

/**
   * Creates an AntiGamingFilter that either accepts or rejects tweets from all users.
   * This method should only be called in tests.
   *
   * @param alwaysValue Determines if tweets should always be accepted or rejected.
   * @return An AntiGamingFilter that either accepts or rejects tweets from all users.
   */


private Map<String, RawFieldCounter> getFieldStats() {
    Iterable<SegmentInfo> segmentInfos = segmentManager.getSegmentInfos(
        SegmentManager.Filter.Enabled, SegmentManager.Order.NEW_TO_OLD);
    Map<String, RawFieldCounter> rawCounts = new HashMap<>();

    ImmutableSchemaInterface schemaSnapshot =
        segmentManager.getEarlybirdIndexConfig().getSchema().getSchemaSnapshot();
    Set<String> missingFieldsCandidates = schemaSnapshot
        .getFieldInfos()
        .stream()
        .filter(fieldInfo -> fieldInfo.getFieldType().indexOptions() != IndexOptions.NONE)
        .map(Schema.FieldInfo::getName)
        .collect(Collectors.toSet());
    int segmentCount = 0;
    for (SegmentInfo segmentInfo : segmentInfos) {
      segmentCount++;
      try {
        EarlybirdSingleSegmentSearcher searcher = segmentManager.getSearcher(
            segmentInfo.getTimeSliceID(), schemaSnapshot);
        if (searcher != null) {
          EarlybirdIndexSegmentAtomicReader reader = searcher.getTwitterIndexReader();
          for (Schema.FieldInfo fieldInfo : schemaSnapshot.getFieldInfos()) {
            if (fieldInfo.getFieldType().indexOptions() == IndexOptions.NONE) {
              continue;
            }

            String fieldName = fieldInfo.getName();
            RawFieldCounter count = rawCounts.get(fieldName);
            if (count == null) {
              count = new RawFieldCounter();
              rawCounts.put(fieldName, count);
            }
            Terms terms = reader.terms(fieldName);
            if (terms != null) {
              missingFieldsCandidates.remove(fieldName);
              count.numTerms.add(terms.size());
              long sumTotalTermFreq = terms.getSumTotalTermFreq();
              if (sumTotalTermFreq != -1) {
                count.numTokens.add(sumTotalTermFreq);
              }
            }
          }
        }
      } catch (Exception e) {
        LOG.error("Exception getting average term count per field: " + segmentInfo, e);
      }
    }

    // Update missing fields stats.
    missingFieldsCandidates.forEach(
        field -> getOrCreateLongGauge(missingFields, field, missingFieldStatNameFunc).set(1));
    missingFields.keySet().stream()
        .filter(
            field -> !missingFieldsCandidates.contains(field))
        .forEach(
            field -> getOrCreateLongGauge(missingFields, field, missingFieldStatNameFunc).set(0));

    long totalTermCount = 0;
    long totalTokenCount = 0;
    if (segmentCount == 0) {
      LOG.error("No segments are found to calculate per-field term counts.");
    } else {
      LOG.debug("TermCountMonitor.getPerFieldTermCount.segmentCount = {}", segmentCount);
      LOG.debug("  field: term count (average per segment)");
      for (Map.Entry<String, RawFieldCounter> entry : rawCounts.entrySet()) {
        String field = entry.getKey();
        final long averageTermCount = entry.getValue().numTerms.longValue() / segmentCount;
        final long averageTokenCount = entry.getValue().numTokens.longValue() / segmentCount;
        totalTermCount += entry.getValue().numTerms.longValue();
        totalTokenCount += entry.getValue().numTokens.longValue();

        LOG.debug("  '{} term': {}", field, averageTermCount);
        LOG.debug("  '{} token': {}", field, averageTokenCount);

        entry.getValue().numTerms.setValue(averageTermCount);
        entry.getValue().numTokens.setValue(averageTokenCount);
      }
    }
    LOG.info("Total term count: {}", totalTermCount);
    LOG.info("Total token count: {}", totalTokenCount);
    this.termCountOnAllFields.set(totalTermCount);
    this.tokenCountOnAllFields.set(totalTokenCount);

    return rawCounts;
  }

/**
   * Loops through all segments, and for each field gets the average term/token count.
   * Based on that, returns a map from each field to its term/token count (average per segment).
   */


public static @NonNull PlannerBenchmarkFactory createFromFreemarkerXmlResource(@NonNull String templateResource) {
        PlannerBenchmarkConfig benchmarkConfig = PlannerBenchmarkConfig.createFromFreemarkerXmlResource(templateResource);
        return new DefaultPlannerBenchmarkFactory(benchmarkConfig);
    }

/**
     * Reads a Freemarker template from the classpath that generates an XML benchmark configuration
     * and uses that {@link PlannerBenchmarkConfig} to build a {@link PlannerBenchmarkFactory}.
     * The generated XML root element must be {@code <plannerBenchmark>}.
     *
     * @param templateResource a classpath resource as defined by {@link ClassLoader#getResource(String)}
     * @see #createFromFreemarkerXmlResource(String)
     */


public void registerProblemSizeStatistics(ProblemSizeStatistics problemSizeStatistics) {
        if (entityCount == null) {
            entityCount = problemSizeStatistics.entityCount();
        } else if (entityCount.longValue() != problemSizeStatistics.entityCount()) {
            LOGGER.warn("The problemBenchmarkResult ({}) has different entityCount values ([{},{}]).\n"
                    + "This is normally impossible for 1 inputSolutionFile.",
                    getName(), entityCount, problemSizeStatistics.entityCount());
            // The entityCount is not unknown (null), but known to be ambiguous
            entityCount = -1L;
        }
        if (variableCount == null) {
            variableCount = problemSizeStatistics.variableCount();
        } else if (variableCount.longValue() != problemSizeStatistics.variableCount()) {
            LOGGER.warn("The problemBenchmarkResult ({}) has different variableCount values ([{},{}]).\n"
                    + "This is normally impossible for 1 inputSolutionFile.",
                    getName(), variableCount, problemSizeStatistics.variableCount());
            // The variableCount is not unknown (null), but known to be ambiguous
            variableCount = -1L;
        }
        if (maximumValueCount == null) {
            maximumValueCount = problemSizeStatistics.approximateValueCount();
        } else if (maximumValueCount.longValue() != problemSizeStatistics.approximateValueCount()) {
            LOGGER.warn("The problemBenchmarkResult ({}) has different approximateValueCount values ([{},{}]).\n"
                    + "This is normally impossible for 1 inputSolutionFile.",
                    getName(), maximumValueCount, problemSizeStatistics.approximateValueCount());
            // The approximateValueCount is not unknown (null), but known to be ambiguous
            maximumValueCount = -1L;
        }
        if (problemScale == null) {
            problemScale = problemSizeStatistics.approximateProblemScaleLogAsFixedPointLong();
        } else if (problemScale.longValue() != problemSizeStatistics.approximateProblemScaleLogAsFixedPointLong()) {
            LOGGER.warn("The problemBenchmarkResult ({}) has different problemScale values ([{},{}]).\n"
                    + "This is normally impossible for 1 inputSolutionFile.",
                    getName(), problemScale, problemSizeStatistics.approximateProblemScaleLogAsFixedPointLong());
            // The problemScale is not unknown (null), but known to be ambiguous
            problemScale = -1L;
        }
    }

/**
     * HACK to avoid loading the problem just to extract its problemScale.
     * Called multiple times, for every {@link SingleBenchmarkResult} of this {@link ProblemBenchmarkResult}.
     *
     * @param problemSizeStatistics never null
     */


public static <A, B, Key, Value> @NonNull BiConstraintCollector<A, B, ?, Map<Key, Set<Value>>> toMap(
            @NonNull BiFunction<? super A, ? super B, ? extends Key> keyMapper,
            @NonNull BiFunction<? super A, ? super B, ? extends Value> valueMapper) {
        return toMap(keyMapper, valueMapper, (IntFunction<Set<Value>>) LinkedHashSet::new);
    }

/**
     * As defined by {@link #toMap(Function, Function)}.
     */


@Override
    public JobsResponse searchJobs(JobsRequest request) throws Exception {
        Map<String, Object> termQuery = request.getTermQuery();
        Map<String, SortOrder> sort = request.getSortOrder();
        Map<String, Object[]> rangeConditions = request.getRangeConditions();

        SearchSourceBuilder builder = openSearchService.genSearchBuilder(termQuery, rangeConditions, sort, null);
        Long count = openSearchService.count(builder, jobsIndex + "-*");
        builder.from(request.getFrom()).size(request.getSize());

        List<JobAnalysis> items = openSearchService.find(JobAnalysis.class, builder, jobsIndex + "-*");
        List<JobInfo> jobInfos = items.stream().map(data -> JobInfo.from(data, redisService.get(String.format("%s:%s:%s", data.getProjectName(), data.getFlowName(), data.getTaskName())))).collect(Collectors.toList());

        JobsResponse response = new JobsResponse();
        response.setJobInfos(jobInfos);
        response.setCount(count);
        return response;
    }


@PostMapping("/register")
    public Result register(@RequestBody UserParam user){
        String pwd = new String(Base64.decodeBase64(user.getPassword()), StandardCharsets.UTF_8);
        String md5 = Md5Utils.hash(pwd).toUpperCase();
        user.setPassword(md5);
        BaseUser baseUser = new BaseUser();
        BeanUtils.copyProperties(user, baseUser);
        iBaseUserService.addUser(baseUser);
        return Result.success();
    }

/**
     * 用户注册
     * @param user
     * @return
     */


@PostMapping("/unlockAvailablePieces")
    public BaseResponse unlockAvailablePieces(@RequestBody LockChargingVo lockChargingVo){
        return interfaceChargingService.unlockAvailablePieces(lockChargingVo);
    }

/**
     * 解锁库存
     * @param lockChargingVo
     * @return
     */


public static <T, R> void defaultOrder(List<PageRequest.OrderBy> orders, QueryWrapper<T> queryWrapper, SFunction<T, R> defaultColumnName) {
        if (CollUtil.isEmpty(orders)) {
            defaultOrderProcess(queryWrapper, defaultColumnName);
            return;
        }
        orders.forEach(orderBy -> {
            //默认时间倒序
            if (StringUtils.EMPTY.equals(orderBy.getColumnName())) {
                defaultOrderProcess(queryWrapper, defaultColumnName);
            } else {
                if (orderBy.isDesc()) {
                    queryWrapper.orderByDesc(orderBy.getColumnName());
                } else {
                    queryWrapper.orderByAsc(orderBy.getColumnName());
                }
            }
        });
    }

/**
     * 默认排序,可以指定默认排序字段
     *
     * @param orders            排序条件
     * @param queryWrapper      查询条件
     * @param defaultColumnName 指定默认排序字段列
     * @param <T>               T
     */


public static String str(Object obj, Charset charset) {
        if (null == obj) {
            return null;
        }

        if (obj instanceof String) {
            return (String) obj;
        } else if (obj instanceof byte[]) {
            return str((byte[]) obj, charset);
        } else if (obj instanceof Byte[]) {
            byte[] bytes = ArrayUtils.toPrimitive((Byte[]) obj);
            return str(bytes, charset);
        } else if (obj instanceof ByteBuffer) {
            return str((ByteBuffer) obj, charset);
        }
        return obj.toString();
    }

/**
     * 将对象转为字符串<br>
     * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
     *
     * @param obj     对象
     * @param charset 字符集
     * @return 字符串
     */


public KronotopInstanceStatus getStatus() {
        return status;
    }

/**
     * Retrieves the status of the Kronotop instance.
     *
     * @return the status of the Kronotop instance.
     */


@Override
    public void writeInteger(long value) {
        ctx.writeAndFlush(new IntegerRedisMessage(value));
    }

/**
     * Writes a long integer value as a Redis response message to the client.
     *
     * @param value the long integer value to be written
     * @throws NullPointerException if the value is null
     */


public Long watchKey(ChannelId channelId, String key) {
        AtomicLong version = new AtomicLong();
        watchedKeys.compute(key, (k, watchedKey) -> {
            if (watchedKey == null) {
                watchedKey = new WatchedKey();
            }
            version.set(watchedKey.getVersion());
            watchedKey.getChannels().add(channelId);
            return watchedKey;
        });
        return version.get();
    }

/**
     * Watches a key for changes and associates a given channelId with it.
     *
     * @param channelId The channelId to associate with the key
     * @param key       The key to watch
     * @return The version of the watched key
     */


public MigrateArgs<K> copy() {
        this.copy = true;
        return this;
    }

/**
     * Do not remove the key from the local instance by setting {@code COPY}.
     *
     * @return {@code this} {@link MigrateArgs}.
     */


public static char readMenuSelection() {
        char c;
        for (; ; ) {
            String str = readKeyBoard(1, false);//包含一个字符的字符串
            c = str.charAt(0);//将字符串转换成字符char类型
            if (c != '1' && c != '2' &&
                c != '3' && c != '4' && c != '5') {
                System.out.print("选择错误，请重新输入：");
            } else break;
        }
        return c;
    }

/**
     * 功能：读取键盘输入的一个菜单选项，值：1——5的范围
     * @return 1——5
     */


private String getDeleteChangeDescription(AuditableEntity p, String entityClass, StringBuilder change) {
        debug("[getDeleteChangeDescription] entityClass: {}", entityClass);
        change.append("Deleted ").append(entityClass).append(" ").append(p.toAuditString());
        return change.toString();
    }

/**
     * Creates change log for object deleted.
     */


public void setName(String name) {
        this.name = name;
    }


public String getTitle() {
        return title;
    }


public static String toBigCamelCase(String str) {
        return toCamelCase(str, true);
    }

/**
     * 将下划线方式命名的字符串转换为大驼峰式。如果转换前的下划线大写方式命名的字符串为空，则返回空字符串。<br>
     * 例如：hello_world=》HelloWorld
     *
     * @param str 转换前的下划线大写方式命名的字符串
     * @return 转换后的驼峰式命名的字符串
     */


public final boolean isPragmaLine() {
		if (!firstToken.isPragma())
			return false;
		// starting from the second Token, check for pragmas and line breaks
		Token token = firstToken.getNext();
		while (token != null && token.isPragma() && token.lineBreaks == 0) {
			token = token.getNext();
		}
		return (token == null || token.isComment());
	}

/**
	 * returns true if the Command only consists of one line with one or several pragmas (and potentially a line-end comment)
	 */


public PeriodicTask.Builder setService(Class<? extends GcmTaskService> gcmTaskService) {
            this.gcmTaskService = gcmTaskService.getName();
            return this;
        }

/**
         *
Set whichever {@link com.google.android.gms.gcm.GcmTaskService} you implement to execute the logic for this task.

         *
         * @param gcmTaskService Endpoint against which you're scheduling this task.
         */


@RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
    public boolean isScanning() {
        throw new UnsupportedOperationException();
    }

/**
     * Check whether the Wi-Fi subsystem has started a scan and is waiting for scan results.
     *
     * @return true if a scan initiated via
     * {@link WifiScanner#startScan(ScanSettings, ScanListener)} or
     * {@link WifiManager#startScan()} is in progress.
     * false if there is currently no scanning initiated by {@link WifiScanner} or
     * {@link WifiManager}, but it's still possible the wifi radio is scanning for
     * another reason.
     * @hide
     */


public boolean isVisible() {
        return visible;
    }

/**
     * Gets the visibility setting for this {@link TileOverlayOptions} object.
     *
     * @return {@code true} if the tile overlay is to be visible; {@code false} if it is not.
     */


const initializePlayers = () => {
      new window.YT.Player('player1', {
        events: {
          onStateChange: (event: any) => {
            if (event.data === window.YT.PlayerState.PLAYING) {
              const player2Frame = document.getElementById(
                'player2'
              ) as HTMLIFrameElement;
              player2Frame?.contentWindow?.postMessage(
                '{"event":"command","func":"pauseVideo","args":""}',
                '*'
              );
            }
          },
        },
      });

      new window.YT.Player('player2', {
        events: {
          onStateChange: (event: any) => {
            if (event.data === window.YT.PlayerState.PLAYING) {
              const player1Frame = document.getElementById(
                'player1'
              ) as HTMLIFrameElement;
              player1Frame?.contentWindow?.postMessage(
                '{"event":"command","func":"pauseVideo","args":""}',
                '*'
              );
            }
          },
        },
      });
    };


function createAssertionError(
  options: ExtendedAssertionErrorConstructorOptions,
): AssertionError {
  const error = new AssertionError(options);
  if (options.generatedMessage) {
    error.generatedMessage = true;
  }
  return error;
}

// TODO(uki00a): This function is a workaround for setting the `generatedMessage` property flexibly.


parallel() {
		return new RelateQueryWriter({
			...this.#state,
			parallel: true
		});
	}

/**
	 * Run the query in parallel
	 *
	 * @returns The query writer
	 */


function flatten(obj: any, path: any = []) {
    // Iterate over the object's keys

    if (Array.isArray(obj)) {
      flat[`${path.join('.')}`] = obj;
    } else {
      for (const key of Object.keys(obj)) {
        // If the value is an object, recurse
        if (key === 'ids' && path.length > 0) {
          flat[`${path.join('.')}`] = obj[key];
        } else if (key === 'props') {
          flat[`${path.join('.')}.${key}`] = obj[key];
        } else if (typeof obj[key] === 'object') {
          flatten(obj[key], [...path, key]);
        } else {
          flat[`${path.join('.')}`] = obj[key];
        }
      }
    }
  }

// Recursive function to flatten the object


public calculateDamage() {
		return Math.max(
			this.damage * this.damageMultiplier - this.damageReduction,
			0,
		)
	}

/** Calculates the damage for this attack */


function parseUntil(text: string, until: Array<string>): [string, string] {
	// We take characters until we get to something that is probably a parser
	let out = ''
	let i = 0

	let isEscaped = text[0] == '\\'
	let nextChar: string | undefined = text[0]

	while (true) {
		if (!isEscaped) {
			out += nextChar
		}
		i++

		if (i >= text.length) {
			break
		}
		nextChar = text.at(i)
		if (nextChar == undefined) {
			break
		}

		if (!isEscaped && until.includes(nextChar)) {
			break
		}

		isEscaped = nextChar === '\\'
	}

	if (text[text.length - 1] == '\\') {
		out += '\\'
	}

	return [out, text.slice(i)]
}

/* Parse the raw text that is part of a text mode or emoji node, handling escape sequences. */


getNodeLocation(node: t.Type) {
    return this.observer.getNodeLocation(node);
  }

/**
   * Get the nearest parent Node and its relative path of a given AST node in the State.
   */


public async initOpeParam(context: vscode.ExtensionContext): Promise<RefreshPrjConfig> {
        const os = process.platform;
        const extensionPath = hdlPath.toSlash(context.extensionPath);
        const workspacePath = this.getWorkspacePath();
        const propertyJsonPath = hdlPath.join(workspacePath, '.vscode', 'property.json');
        const propertySchemaPath = hdlPath.join(extensionPath, 'project', 'property-schema.json');
        const propertyInitPath = hdlPath.join(extensionPath, 'project', 'property-init.json');

        opeParam.setBasicInfo(os,
                              extensionPath,
                              workspacePath,
                              propertyJsonPath,
                              propertySchemaPath,
                              propertyInitPath);

        opeParam.prjInfo.initContextPath(extensionPath, workspacePath);
        const refreshPrjConfig: RefreshPrjConfig = {mkdir: true};
        if (fs.existsSync(propertyJsonPath)) {
            const rawPrjInfo = hdlFile.readJSON(propertyJsonPath) as RawPrjInfo;
            opeParam.mergePrjInfo(rawPrjInfo);
        } else {
            refreshPrjConfig.mkdir = false;
        }

        // 创建用户目录
        hdlDir.mkdir(opeParam.dideHome);
        // 同步部分文件
        const cachePPySchema = hdlPath.join(opeParam.dideHome, 'property-schema.json');
        const propertySchema = opeParam.propertySchemaPath;
        if (fs.existsSync(cachePPySchema) && checkJson(cachePPySchema)) {
            hdlFile.copyFile(cachePPySchema, propertySchema);
        }

        return refreshPrjConfig;
    }

/**
     * init opeParam
     * @param context
     */


async updateLinter(path: string) {
    }

// 下一个版本丢弃，完全由后端承担这部分功能


private async verifyKnownTicket(
    client: PoolClient,
    serializedPCD: SerializedPCD
  ): Promise<VerifyTicketResult> {
    if (!serializedPCD.type) {
      throw new Error("input was not a serialized PCD");
    }

    if (
      serializedPCD.type !== EdDSATicketPCDPackage.name &&
      serializedPCD.type !== ZKEdDSAEventTicketPCDPackage.name
    ) {
      throw new Error(
        `serialized PCD was wrong type, '${serializedPCD.type}' instead of '${EdDSATicketPCDPackage.name}' or '${ZKEdDSAEventTicketPCDPackage.name}'`
      );
    }

    let eventId: string;
    let productId: string;
    let publicKey: EdDSAPublicKey;

    if (serializedPCD.type === EdDSATicketPCDPackage.name) {
      const pcd = await EdDSATicketPCDPackage.deserialize(serializedPCD.pcd);

      if (!EdDSATicketPCDPackage.verify(pcd)) {
        return {
          success: true,
          value: { verified: false, message: "Could not verify PCD." }
        };
      }

      eventId = pcd.claim.ticket.eventId;
      productId = pcd.claim.ticket.productId;
      publicKey = pcd.proof.eddsaPCD.claim.publicKey;
    } else {
      const pcd = await ZKEdDSAEventTicketPCDPackage.deserialize(
        serializedPCD.pcd
      );

      if (!ZKEdDSAEventTicketPCDPackage.verify(pcd)) {
        return {
          success: true,
          value: { verified: false, message: "Could not verify PCD." }
        };
      }

      if (
        !(pcd.claim.partialTicket.eventId && pcd.claim.partialTicket.productId)
      ) {
        return {
          success: true,
          value: {
            verified: false,
            message: "PCD does not reveal the correct fields."
          }
        };
      }

      // Watermarks can be up to four hours old
      if (Date.now() - parseInt(pcd.claim.watermark) > ONE_HOUR_MS * 4) {
        return {
          success: true,
          value: {
            verified: false,
            message: "PCD watermark has expired."
          }
        };
      }

      eventId = pcd.claim.partialTicket.eventId;
      productId = pcd.claim.partialTicket.productId;
      publicKey = pcd.claim.signer;
    }

    const knownTicketType = await fetchKnownTicketByEventAndProductId(
      client,
      eventId,
      productId
    );

    // If we found a known ticket type, compare public keys
    if (
      knownTicketType &&
      isEqualEdDSAPublicKey(JSON.parse(knownTicketType.public_key), publicKey)
    ) {
      // We can say that the submitted ticket can be verified as belonging
      // to a known group
      return {
        success: true,
        value: {
          verified: true,
          publicKeyName: knownTicketType.known_public_key_name,
          group: knownTicketType.ticket_group,
          eventName: knownTicketType.event_name
        }
      };
    } else {
      return {
        success: true,
        value: {
          verified: false,
          message: "Not a recognized ticket"
        }
      };
    }
  }

/**
   * Verifies a ticket based on:
   * 1) verification of the PCD (that it is correctly formed, with a proof
   *    matching the claim)
   * 2) whether the ticket matches the ticket types known to us, e.g. Zuzalu
   *    or Zuconnect tickets
   *
   */


public async handlePollFeed(
    pipelineId: string,
    req: PollFeedRequest
  ): Promise<PollFeedResponseValue> {
    return traced(SERVICE_NAME, "handlePollFeed", async (span) => {
      logger(LOG_TAG, `handlePollFeed`, pipelineId, str(req));
      span?.setAttribute("feed_id", req.feedId);
      const pipelineSlot =
        await this.pipelineSubservice.ensurePipelineSlotExists(pipelineId);
      tracePipeline(pipelineSlot.definition);
      const pipeline =
        await this.pipelineSubservice.ensurePipelineStarted(pipelineId);
      const feed = ensureFeedIssuanceCapability(pipeline, req.feedId);
      const feedResponse = await feed.issue(req);
      traceFlattenedObject(span, {
        result: {
          actionCount: feedResponse.actions.length,
          pcdCount: getPcdsFromActions(feedResponse.actions).length
        }
      });
      return feedResponse;
    });
  }

/**
   * Handles incoming requests that hit a Pipeline-specific feed for PCDs
   * for every single pipeline that has this capability that this server manages.
   */


public static findCircuit(
    familyName: string,
    circuitName: string,
    circuitFamily: ProtoPODGPCCircuitDesc[] = ProtoPODGPC.CIRCUIT_FAMILY
  ): ProtoPODGPCCircuitDesc | undefined {
    if (familyName && familyName !== PROTO_POD_GPC_FAMILY_NAME) {
      return undefined;
    }
    for (const circuitDesc of circuitFamily) {
      if (circuitName && circuitDesc.name === circuitName) {
        return circuitDesc;
      }
    }
    return undefined;
  }

/**
   * Finds the description of a circuit in this family by name.
   *
   * @param familyName the circuit family name
   * @param circuitName the name of the circuit
   * @param [circuitFamily=ProtoPODGPC.CIRCUIT_FAMILY] the circuit family to
   *   search
   * @returns the circuit description, or undefined if the name is
   *   unrecognized.
   */


function replacer(key: unknown, value: unknown): unknown {
  if (key === "message" && value instanceof Array) {
    return value.map((num: bigint) => num.toString(16));
  } else {
    return value;
  }
}

/**
 * The replacer is used by `JSON.stringify` and, in this package, it is used within the
 * PCD's `serialize` function. It is called for each property on the JSON object and
 * converts the value of the property from a list of big integers to a list of hexadecimal
 * strings when the property's key name equals "message".
 * @param key The object property key.
 * @param value The object property value.
 * @returns The original value of the property or the converted one.
 */


_tableNameFromId<TableName extends TableNamesInDataModel<DataModel>>(
    id: GenericId<TableName>,
  ): TableName | null {
    for (const tableName of Object.keys(this.triggers.registered)) {
      if (
        this.innerDb.normalizeId(
          tableName as TableNamesInDataModel<DataModel>,
          id,
        )
      ) {
        return tableName as TableName;
      }
    }
    return null;
  }


private get firstFourDocs() {
    return this.args.docs.slice(0, 4);
  }

/**
   * (Up to) the first four docs. The default documents shown.
   */


protected get allApprovers() {
    return this.approverGroups.concat(this.approvers);
  }

/**
   * A computed property that returns all approvers and approverGroups.
   * Passed to the EditableField component to render the list of approvers and groups.
   * Recomputes when the approvers or approverGroups arrays change.
   */


protected get titleTooltipText(): string {
    return `Documents and links that are relevant to this work.`;
  }

/**
   * The text passed to the TooltipIcon beside the title.
   */


protected get jiraIsEnabled() {
    return !!this.configSvc.config.jira_url;
  }

/**
   * Whether Jira is configured for the project.
   * Determines whether to show the Jira-related UI.
   */


protected get projectID() {
    if ("objectID" in this.args.project) {
      return this.args.project.objectID;
    } else {
      return this.args.project.id;
    }
  }

/**
   * The project ID used as our LinkTo model.
   * If the project is an Algolia result, it has an `objectID`.
   * If the project is retrieved from the back-end, it has an `id`.
   */


async function loaderAdvancedConfig() {
  const testCrawlApp = createCrawl({
    log: false,
    baseUrl: 'http://localhost:8888'
  })

  const res = await testCrawlApp.crawlData({
    targets: ['/data', '/data'],
    proxy: { urls: ['http://localhost:7890'] },
    timeout: 10000,
    intervalTime: { max: 1000 },
    maxRetry: 0
  })

  return res.reduce((prev, item) => prev && item.isSuccess, true)
}


_singleRealTransform2(outOff, off, step) {
    const out = this._out;
    const data = this._data;

    const evenR = data[off];
    const oddR = data[off + step];

    const leftR = evenR + oddR;
    const rightR = evenR - oddR;

    out[outOff] = leftR;
    out[outOff + 1] = 0;
    out[outOff + 2] = rightR;
    out[outOff + 3] = 0;
  }


public async listener(t: number) {
        let isExecCommand = false;
        this.intervalID = window.setInterval(async () => {
            if (!Zotero.ZoteroCitation) {
                return this.clear();
            }
            if (!Zotero.Integration.currentSession || isExecCommand) {
                return;
            }
            const sessions = Zotero.Integration.sessions;
            const _sessions = this.sessions;
            for (const sessionID in sessions) {
                const session = sessions[sessionID];
                let _session: SessionData;
                if (!(session.agent as string).includes("Word")) {
                    continue;
                }
                // 初始化对象的session
                if (sessionID in _sessions) {
                    _session = _sessions[sessionID];
                } else {
                    _sessions[sessionID] = _session = { search: undefined, idData: {}, pending: true } as SessionData;
                    await this.initSearch(sessionID);
                    _session.pending = false;
                }
                // 其它线程search正在创建，则退出本次执行
                if (_session.pending == true && !_session.search) {
                    return;
                }
                const citationsByItemID = session.citationsByItemID;
                // 分析排序
                const sortedItemIDs = this.getSortedItemIDs(session.citationsByIndex);
                this.updateCitations(sessionID, citationsByItemID, sortedItemIDs, session.styleClass);
            }
        }, t);
        window.addEventListener("close", (event) => {
            event.preventDefault();
            try {
                this.clear();
            } catch {
                /* empty */
            }
            window.setTimeout(() => {
                window.close();
            });
        });
        const execCommand = Zotero.Integration.execCommand;
        const _sessions = this.sessions;
        // @ts-ignore ignore
        Zotero.Integration.execCommand = async function (agent, command, docId) {
            // eslint-disable-next-line prefer-rest-params
            console.log(...arguments);
            isExecCommand = true;
            // eslint-disable-next-line prefer-rest-params
            await execCommand(...arguments);
            isExecCommand = false;
            if (docId.endsWith("__doc__")) {
                return;
            }
            const id = window.setInterval(async () => {
                const sessionID = Zotero.Integration?.currentSession?.sessionID;
                if (!sessionID) {
                    console.log("sessionID is null, waiting...");
                    return;
                }
                window.clearInterval(id);
                console.log("clear interval");
                let _session;
                while (!((_session ??= _sessions[sessionID]) && _session.search)) {
                    await Zotero.Promise.delay(10);
                }
                console.log(_sessions);
                // 判断是否为插件修改过的名称，如果是则更新
                // 若为用户更改则不进行更新
                if ([sessionID, _session.lastName].indexOf(_session.search.name) != -1) {
                    let targetName = docId
                    try {
                        targetName = PathUtils.split(docId).slice(-1)[0];
                    } catch { }
                    console.log(`${_session.search.name}->${targetName}`);
                    // 修复Mac储存
                    if (targetName && targetName.trim().length > 0) {
                        _session.search.name = _session.lastName = targetName;
                        await _session.search.saveTx({ skipSelect: true });
                    }
                }
            }, 0);
        };
    }


const _classicalRegister = (
  startX: number,
  gateY: number,
  endX: number,
  wireY: number,
): SVGElement => {
  const wirePadding = 1;
  // Draw vertical lines
  const vLine1: SVGElement = line(
    startX + wirePadding,
    gateY,
    startX + wirePadding,
    wireY - wirePadding,
    "register-classical",
  );
  const vLine2: SVGElement = line(
    startX - wirePadding,
    gateY,
    startX - wirePadding,
    wireY + wirePadding,
    "register-classical",
  );

  // Draw horizontal lines
  const hLine1: SVGElement = line(
    startX + wirePadding,
    wireY - wirePadding,
    endX,
    wireY - wirePadding,
    "register-classical",
  );
  const hLine2: SVGElement = line(
    startX - wirePadding,
    wireY + wirePadding,
    endX,
    wireY + wirePadding,
    "register-classical",
  );

  return group([vLine1, vLine2, hLine1, hLine2]);
};

/**
 * Generates the SVG representation of a classical register.
 *
 * @param startX Start x coord.
 * @param gateY  y coord of measurement gate.
 * @param endX   End x coord.
 * @param wireY  y coord of wire.
 *
 * @returns SVG representation of the given classical register.
 */


maybeWidened<T extends Token>(t: T): T | PackageObjectToken {
        if (options.widening && t instanceof ObjectToken && this.widened.has(t))
            return this.a.canonicalizeToken(new PackageObjectToken(t.getPackageInfo(), t.kind));
        else
            return t;
    }

/**
     * If the provided token is an object token that has been widened, the corresponding package object token is returned.
     * Otherwise the provided token is returned as is.
     */


getSecretKey(): string {
    return encodeRoochSercetKey(
      this.keypair.secretKey.slice(0, PRIVATE_KEY_SIZE),
      this.getKeyScheme(),
    )
  }

/**
   * The Bech32 secret key string for this Ed25519 keypair
   */


flag(): number {
    return SIGNATURE_SCHEME_TO_FLAG['Secp256k1']
  }

/**
   * Return the Rooch address associated with this Secp256k1 public key
   */


function deserializeValue(value: any, options: EJSONOptions = {}) {
  if (typeof value === 'number') {
    // TODO(NODE-4377): EJSON js number handling diverges from BSON
    const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
    const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;

    if (options.relaxed || options.legacy) {
      return value;
    }

    if (Number.isInteger(value) && !Object.is(value, -0)) {
      // interpret as being of the smallest BSON integer type that can represent the number exactly
      if (in32BitRange) {
        return new Int32(value);
      }
      if (in64BitRange) {
        if (options.useBigInt64) {
          // eslint-disable-next-line no-restricted-globals -- This is allowed here as useBigInt64=true
          return BigInt(value);
        }
        return Long.fromNumber(value);
      }
    }

    // If the number is a non-integer or out of integer range, should interpret as BSON Double.
    return new Double(value);
  }

  // from here on out we're looking for bson types, so bail if its not an object
  if (value == null || typeof value !== 'object') return value;

  // upgrade deprecated undefined to null
  if (value.$undefined) return null;

  const keys = Object.keys(value).filter(
    k => k.startsWith('$') && value[k] != null
  ) as (keyof typeof keysToCodecs)[];
  for (let i = 0; i < keys.length; i++) {
    const c = keysToCodecs[keys[i]];
    if (c) return c.fromExtendedJSON(value, options);
  }

  if (value.$date != null) {
    const d = value.$date;
    const date = new Date();

    if (options.legacy) {
      if (typeof d === 'number') date.setTime(d);
      else if (typeof d === 'string') date.setTime(Date.parse(d));
      else if (typeof d === 'bigint') date.setTime(Number(d));
      else throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
    } else {
      if (typeof d === 'string') date.setTime(Date.parse(d));
      else if (Long.isLong(d)) date.setTime(d.toNumber());
      else if (typeof d === 'number' && options.relaxed) date.setTime(d);
      else if (typeof d === 'bigint') date.setTime(Number(d));
      else throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
    }
    return date;
  }

  if (value.$code != null) {
    const copy = Object.assign({}, value);
    if (value.$scope) {
      copy.$scope = deserializeValue(value.$scope);
    }

    return Code.fromExtendedJSON(value);
  }

  if (isDBRefLike(value) || value.$dbPointer) {
    const v = value.$ref ? value : value.$dbPointer;

    // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped)
    // because of the order JSON.parse goes through the document
    if (v instanceof DBRef) return v;

    const dollarKeys = Object.keys(v).filter(k => k.startsWith('$'));
    let valid = true;
    dollarKeys.forEach(k => {
      if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false;
    });

    // only make DBRef if $ keys are all valid
    if (valid) return DBRef.fromExtendedJSON(v);
  }

  return value;
}


advanceOperationTime(operationTime: Timestamp): void {
    if (this.operationTime == null) {
      this.operationTime = operationTime;
      return;
    }

    if (operationTime.greaterThan(this.operationTime)) {
      this.operationTime = operationTime;
    }
  }

/**
   * Advances the operationTime for a ClientSession.
   *
   * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to
   */


last(): T | null {
    // If the list is empty, value will be the head's null
    return this.head.prev.value;
  }

/** Returns the last item in the list, does not remove */


function isFieldOnly(node: any): boolean {
    return node && node.type === "column_ref";
  }

// Helper function to check if a node is a field-only reference (column_ref without literal)


function onDrop(event:any ,offSet:any = {x:0,y:0}) {
    if (
      pipelineObj.hasInputNode &&
      pipelineObj.draggedNode.io_type == "input"
    ) {
      $q.notify({
        message: "Only 1 source node is allowed",
        color: "negative",
        position: "bottom",
        timeout: 2000,
    });
      return;
    }

    const position = screenToFlowCoordinate({
      x: event.clientX + offSet.x,
      y: event.clientY + offSet.y,
    });

    const nodeId = getUUID();

    const newNode = {
      id: nodeId,
      type: pipelineObj.draggedNode.io_type || "default",
      io_type: pipelineObj.draggedNode.io_type || "default",
      position,
      data: { label: nodeId, node_type: pipelineObj.draggedNode.subtype },
    };

    /**
     * Align node position after drop, so it's centered to the mouse
     *
     * We can hook into events even in a callback, and we can remove the event listener after it's been called.
     */
    const { off } = onNodesInitialized(() => {
      updateNode(nodeId, (node) => ({
        position: {
          x: node.position.x - node.dimensions.width / 2,
          y: node.position.y - node.dimensions.height / 2,
        },
      }));

      off();
    });

    pipelineObj.currentSelectedNodeData = newNode;
    pipelineObj.dialog.name = newNode.data.node_type;
    pipelineObj.dialog.show = true;
    pipelineObj.isEditNode = false;

  }

/**
   * Handles the drop event.
   *
   * @param {DragEvent} event
   */


function parseConstraints(constraints?: EdgeConstraint[]): EdgeConstraint[] {
    if (!constraints) {
        return [];
    }

    return constraints.map((c) => {
        const constraintType = c.type;
        const { source, target } = c;

        return {
            ...c,
            source,
            target,
            type: constraintType,
        };
    });
}

/**
 * Parse initially defined constraints.
 * Reverses backward directed edges.
 *
 * @param constraints constraints to parse
 */


const NavigateTo: ActionHandler<NavigateToImpl> = (ctx, actionImpl): void => {
    const isValidUrl = isValidHttpUrl(actionImpl.url);

    if (!isValidUrl) {
        throw new Error(`Invalid URL: ${actionImpl.url}`);
    }

    if (actionImpl.new_tab) {
        window.open(actionImpl.url, actionImpl.new_tab ? '_blank' : undefined);
    } else {
        ctx.history.push(actionImpl.url);
    }
};

/**
 * Front-end handler for NavigateTo action.
 * Navigates to a specified URL.
 */


const UpdateVariable: ActionHandler<UpdateVariableImpl> = async (ctx, actionImpl) => {
    let varAtom;
    let eventName: 'PLAIN_VARIABLE_LOADED' | 'URL_VARIABLE_LOADED';

    // Make sure the variable is registered
    switch (actionImpl.variable.__typename) {
        case 'Variable':
            varAtom = getOrRegisterPlainVariable(actionImpl.variable, ctx.wsClient, ctx.taskCtx, ctx.extras);
            eventName = 'PLAIN_VARIABLE_LOADED';
            break;
        case 'UrlVariable':
            varAtom = getOrRegisterUrlVariable(actionImpl.variable);
            eventName = 'URL_VARIABLE_LOADED';
            break;
        case 'DataVariable':
            throw new Error('DataVariable is not supported in UpdateVariable action');
    }

    let newValue;

    if (actionImpl.value === INPUT) {
        newValue = ctx.input;
    } else if (actionImpl.value === TOGGLE) {
        // normally we'd use the updater form here, but we need to know what value we're
        // toggling to emit the correct event, and the updater must be pure
        const value = await ctx.snapshot.getLoadable(varAtom).toPromise();
        newValue = !value;
    } else {
        newValue = actionImpl.value;
    }

    ctx.set(varAtom, newValue);
    ctx.eventBus.publish(eventName, { variable: actionImpl.variable as any, value: newValue });
};

/**
 * Front-end handler for UpdateVariable action.
 */


function cleanSessionCache(sessionToken: string): void {
    for (const storage of [sessionStorage, localStorage]) {
        const keys = Object.keys(storage);

        keys.forEach((key) => {
            // Remove keys related to a different Dara session
            if (key.startsWith('dara-session') && !key.startsWith(`dara-session-${sessionToken}`)) {
                storage.removeItem(key);
            }
        });
    }
}

/**
 * Clean up session storage cache.
 * Purges sessionStorage persisted values which are related to a different session than the current one.
 *
 * @param sessionToken current session token
 */


function Modal(props: ModalProps): JSX.Element {
    const [mounted, setMounted] = useState(false);
    const [renderModal, setRenderModal] = useState(false);

    // Internal state is updated using the useEffect to delay it to the next tick. This allows for the components css
    // animations to work correctly
    useEffect(() => {
        setRenderModal(props.render);
    }, [props.render]);

    useEffect(() => {
        if (renderModal) {
            const keyHandler = (e: KeyboardEvent): void => {
                if (e.key === Key.ESCAPE && props.onAttemptClose) {
                    props.onAttemptClose();
                }
            };
            document.addEventListener('keydown', keyHandler);
            return () => {
                document.removeEventListener('keydown', keyHandler);
            };
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [renderModal, props.onAttemptClose]);

    if (!props.render && !mounted) {
        return null;
    }

    const onTransitionEnd = (): void => {
        setMounted(props.render);
        if (!props.render && props.onClosed) {
            props.onClosed();
        }
    };

    const stopPropagation = (e: React.MouseEvent<HTMLDivElement>): void => {
        e.stopPropagation();
    };

    return ReactDOM.createPortal(
        <Background id={props.id} onClick={props.onAttemptClose} onTransitionEnd={onTransitionEnd} render={renderModal}>
            <ModalWrapper
                className={`cl-modal-content ${props.className ?? ''}`}
                onClick={stopPropagation}
                render={renderModal}
                style={props.style}
            >
                {props.children}
            </ModalWrapper>
        </Background>,
        document.body
    );
}

/**
 * A simple modal component, accepts children and a render property. It handles attaching the modal to the body of the
 * document and transitioning it in and out of view as required
 *
 * @param {ModalProps} props - the component props
 */


const EllipsisH = (props: IconProps): JSX.Element => {
    return <StyledFAIcon icon={faEllipsisH} {...props} />;
};

/**
 * EllipsisH icon from FontAwesome
 *
 * @param {IconProps} props - the component props
 */


const Dizzy = (props: IconProps): JSX.Element => {
    return <StyledFAIcon icon={faDizzy} {...props} />;
};

/**
 * Dizzy icon from FontAwesome
 *
 * @param {IconProps} props - the component props
 */


const HouseMedicalCircleExclamation = (props: IconProps): JSX.Element => {
    return <StyledFAIcon icon={faHouseMedicalCircleExclamation} {...props} />;
};

/**
 * HouseMedicalCircleExclamation icon from FontAwesome
 *
 * @param {IconProps} props - the component props
 */


const RoadSpikes = (props: IconProps): JSX.Element => {
    return <StyledFAIcon icon={faRoadSpikes} {...props} />;
};

/**
 * RoadSpikes icon from FontAwesome
 *
 * @param {IconProps} props - the component props
 */


const PersonCircleMinus = (props: IconProps): JSX.Element => {
    return <StyledFAIcon icon={faPersonCircleMinus} {...props} />;
};

/**
 * PersonCircleMinus icon from FontAwesome
 *
 * @param {IconProps} props - the component props
 */


const PlaneLock = (props: IconProps): JSX.Element => {
    return <StyledFAIcon icon={faPlaneLock} {...props} />;
};

/**
 * PlaneLock icon from FontAwesome
 *
 * @param {IconProps} props - the component props
 */


const List = (props: IconProps): JSX.Element => {
    return <StyledFAIcon icon={faList} {...props} />;
};

/**
 * List icon from FontAwesome
 *
 * @param {IconProps} props - the component props
 */


const UserSecret = (props: IconProps): JSX.Element => {
    return <StyledFAIcon icon={faUserSecret} {...props} />;
};

/**
 * UserSecret icon from FontAwesome
 *
 * @param {IconProps} props - the component props
 */


update() {
    this.getOrInitRenderWatcher().update()
  }


removeAttribute(name: string) {
    if (this._$nodeAttributes) {
      delete this._$nodeAttributes[name]
    }
    const be = this._$backendElement
    if (be) {
      if (ENV.DEV) performanceMeasureStart('backend.removeAttribute')
      be.removeAttribute(name)
      if (ENV.DEV) performanceMeasureEnd()
    }
    if (this._$mutationObserverTarget) {
      MutationObserverTarget.callAttrObservers(this, {
        type: 'properties',
        target: this,
        nameType: 'attribute',
        attributeName: name,
      })
    }
  }


const shortenNumber = (number: number): string | number => {
    if (number > 0 && number < 1) return number.toString().replace("0.", ".");
    return number;
  };

// Removes leading zero before floating point if necessary


public clear(): this
    {
        this._geometry.clear();
        this._lineStyle.reset();
        this._fillStyle.reset();

        this._boundsID++;
        this._matrix = null;
        this._holeMode = false;
        this.currentPath = null;

        return this;
    }

/**
     * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
     * @returns - This Graphics object. Good for chaining method calls
     */


ceil(resolution = 1, eps = 0.001): this
    {
        const x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution;
        const y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution;

        this.x = Math.floor((this.x + eps) * resolution) / resolution;
        this.y = Math.floor((this.y + eps) * resolution) / resolution;

        this.width = x2 - this.x;
        this.height = y2 - this.y;

        return this;
    }

/**
     * Enlarges rectangle that way its corners lie on grid
     * @param resolution - resolution
     * @param eps - precision
     * @returns Returns itself.
     */


function hierarchyConv(state) {
  const parent = {
    name: "root",
    children: [],
  };

  function addNodeToTree(key, value, parent) {
    if (Array.isArray(value) && value.length > 0) {
      const node = { name: key, children: [] };
      parent.children.push(node);
      value.forEach((item, index) => {
        addNodeToTree(`[${index}]`, item, node);
      });
    } else if (typeof value === "object" && Object.keys(value).length > 0) {
      const node = { name: key, children: [] };
      parent.children.push(node);
      Object.entries(value).forEach(([key, val]) => {
        addNodeToTree(key, val, node);
      });
    } else {
      if (typeof value === "object") {
        const node = { name: key, attributes: { value: "empty" } };
        parent.children.push(node);
      } else {
        const node = { name: key, attributes: { value } };
        parent.children.push(node);
      }
    }
  }

  addNodeToTree("state", state, parent);
  return parent.children[0];
}

/*
hierarchyConv takes in the state to display in the visualization tree,
and converts it to a format readable by D3.

const example = {
  name: 'State',
  children: [
    {
      name: 'member1',
      attributes: {
        value: 'org1',
      },
    },
    {
      name: 'member2',
      children: [
        name: 'member3',
        attributes: {
          value: 'org2'
        }
      ]
    }
  ]
}
 */


function parseQueryString(query) {
  const params = {};
  query.split('&').forEach(function (part) {
    // 使用正则表达式匹配键和值，直到遇到第一个等号为止
    const regex = /^(.*?)=(.*)/;
    const match = part.match(regex);
    if (match) {
      const key = decodeURIComponent(match[1]);
      const value = decodeURIComponent(match[2]);
      params[key] = value;
    }
  });
  return params;
}


get clientGroupID(): Promise<string> {
    return this.#impl.clientGroupID;
  }

/**
   * The client group ID for this instance of Replicache. Instances of
   * Replicache will have the same client group ID if and only if they have
   * the same name, mutators, indexes, schema version, format version, and
   * browser profile.
   */


const filterOutput = (
  dataFromCSV: any,
  output: string | string[] | string[][]
) => {
  if (output === '*') {
    return nanifyEmptyValues(dataFromCSV);
  }

  if (Array.isArray(output)) {
    /** Check if it's a multidimensional array. */
    if (Array.isArray(output[0])) {
      const result: any = {};

      output.forEach(outputField => {
        /** Check if there is no renaming request, then export as is */
        const outputTitle = outputField[1] || outputField[0];
        result[outputTitle] = fieldAccessor(outputField[0], dataFromCSV);
      });

      return result;
    }

    const outputTitle = output[1] || output[0];

    return {
      [outputTitle as string]: fieldAccessor(output[0], dataFromCSV),
    };
  }

  return {
    [output]: fieldAccessor(output, dataFromCSV),
  };
};

/**
 * 1. If output is anything, then removes query data from csv record to escape duplicates.
 * 2. Otherwise checks if it's a miltidimensional array, then grabs multiple fields ().
 * 3. If not, then returns single field.
 * 4. In case if it's string, then
 */


const computeNode = async (node: Node, params: ComputeParams): Promise<any> => {
  const pipeline = node.pipeline || (params.pipeline as PhasedPipeline);
  const config = node.config || params.config;
  const defaults = node.defaults || params.defaults;
  const noFlags = !params.observe && !params.regroup && !params.compute;

  debugLogger.setExecutingPluginName();
  warnIfConfigProvided(node);

  if (node.children) {
    return traverse(node.children, {
      ...params,
      pipeline,
      defaults,
      config,
    });
  }

  let outputStorage = structuredClone(node.inputs) as PluginParams[];
  outputStorage = mergeDefaults(outputStorage, defaults);
  const pipelineCopy = structuredClone(pipeline) || {};

  /** Checks if pipeline is not an array or empty object. */
  if (
    Array.isArray(pipelineCopy) ||
    (typeof pipelineCopy === 'object' &&
      pipelineCopy !== null &&
      Object.keys(pipelineCopy).length === 0)
  ) {
    logger.warn(EMPTY_PIPELINE);
  }

  /**
   * If iteration is on observe pipeline, then executes observe plugins and sets the inputs value.
   */
  if ((noFlags || params.observe) && pipelineCopy.observe) {
    while (pipelineCopy.observe.length !== 0) {
      const pluginName = pipelineCopy.observe.shift() as string;
      console.debug(OBSERVING(pluginName));
      debugLogger.setExecutingPluginName(pluginName);

      const plugin = params.pluginStorage.get(pluginName);
      const nodeConfig = config && config[pluginName];

      outputStorage = await plugin.execute(outputStorage, nodeConfig);
      node.inputs = outputStorage;

      if (params.context.explainer) {
        addExplainData({
          pluginName,
          metadata: plugin.metadata,
        });
      }
    }
  }

  /**
   * If regroup is requested, execute regroup strategy, delete child's inputs, outputs and empty regroup array.
   */
  if ((noFlags || params.regroup) && pipelineCopy.regroup) {
    const originalOutputs = params.append ? node.outputs || [] : [];

    if (!isRegrouped(pipelineCopy.regroup, outputStorage, childNames)) {
      node.children = Regroup(
        outputStorage,
        originalOutputs,
        pipelineCopy.regroup
      );

      delete node.inputs;
      delete node.outputs;

      debugLogger.setExecutingPluginName();
      console.debug(REGROUPING);

      return traverse(node.children, {
        ...params,
        pipeline: {
          ...pipelineCopy,
          regroup: undefined,
        },
        defaults,
        config,
      });
    } else {
      console.debug(SKIPPING_REGROUP);
    }
  }

  console.debug('\n');

  /**
   * If iteration is on compute plugin, then executes compute plugins and sets the outputs value.
   */
  if ((noFlags || params.compute) && pipelineCopy.compute) {
    const originalOutputs = params.append ? node.outputs || [] : [];

    while (pipelineCopy.compute.length !== 0) {
      const pluginName = pipelineCopy.compute.shift() as string;
      const plugin = params.pluginStorage.get(pluginName);
      const nodeConfig = config && config[pluginName];

      console.debug(COMPUTING_PIPELINE_FOR_NODE(pluginName));
      debugLogger.setExecutingPluginName(pluginName);

      outputStorage = await plugin.execute(outputStorage, nodeConfig);

      debugLogger.setExecutingPluginName();

      node.outputs = outputStorage;

      if (params.context.explainer) {
        addExplainData({
          pluginName,
          metadata: plugin.metadata,
        });
      }
    }

    if (params.append) {
      node.outputs = originalOutputs.concat(node.outputs || []);
    }
  }

  console.debug('\n');
};

/**
 * 1. If the node has it's own pipeline, defaults or config then use that,
 *    otherwise use whatever has been passed down from further up the tree.
 * 2. If it's a grouping node, then first of all computes all it's children.
 *    This is doing a depth first traversal.
 * 3. Otherwise merges the defaults into the inputs.
 * 4. Iterates over pipeline phases (observe, regroup, compute).
 * 5. Observe plugins are used to insert input values
 *    (isolated execution can be achived by passing `--observe` flag to CLI command).
 * 6. Regroup plugin is used to group existing inputs by criteria
 *    (isolated execution can be achived by passing `--regroup` flag to CLI command).
 *    Since it creates new children for node, existing inputs and outputs are dropped and recursive traversal is called
 *    for newbord child component.
 * 7. Compute plugins are used to do desired computations and appending the result to outputs
 *    (isolated execution can be achived by passing `--compute` flag to CLI command).
 */


public claim(): BitPosition {
		const { recycled } = this;

		// Claim the next bit.
		const claimed = (recycled.length > 0) ? recycled.pop() : (this.next++);

		// Update the field.
		this.asField = BitField.or(this.asField, BitField.fromPosition(claimed as BitPosition));
		return claimed as BitPosition;
	}

/**
	 * Claims a bit from the registry.
	 */


async function getFileStats(filePath: string): Promise<FileInfo> {
  const stats = await fs.stat(filePath);
  return {
    size: stats.size,
    created: stats.birthtime,
    modified: stats.mtime,
    accessed: stats.atime,
    isDirectory: stats.isDirectory(),
    isFile: stats.isFile(),
    permissions: stats.mode.toString(8).slice(-3),
  };
}


cliqueEpochTransitionSigners(): EthjsAddress[] {
		this._requireClique('cliqueEpochTransitionSigners')
		if (!this.cliqueIsEpochTransition()) {
			const msg = this._errorMsg('Signers are only included in epoch transition blocks (clique)')
			throw new Error(msg)
		}

		const start = CLIQUE_EXTRA_VANITY
		const end = this.extraData.length - CLIQUE_EXTRA_SEAL
		const signerBytes = this.extraData.subarray(start, end)

		const signerList: Uint8Array[] = []
		const signerLength = 20
		for (let start = 0; start <= signerBytes.length - signerLength; start += signerLength) {
			signerList.push(signerBytes.subarray(start, start + signerLength))
		}
		return signerList.map((buf) => new EthjsAddress(buf))
	}

/**
	 * Returns a list of signers
	 * (only clique PoA, throws otherwise)
	 *
	 * This function throws if not called on an epoch
	 * transition block and should therefore be used
	 * in conjunction with {@link BlockHeader.cliqueIsEpochTransition}
	 */


async emulateMessageToAccountEvent(requestParameters: EmulateMessageToAccountEventRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<AccountEvent> {
        const response = await this.emulateMessageToAccountEventRaw(requestParameters, initOverrides);
        return await response.value();
    }

/**
     * Emulate sending message to blockchain
     */


async emulateMessageToTrace(requestParameters: EmulateMessageToTraceRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<Trace> {
        const response = await this.emulateMessageToTraceRaw(requestParameters, initOverrides);
        return await response.value();
    }


async getAccountNominatorsPoolsRaw(requestParameters: GetAccountNominatorsPoolsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<AccountStaking>> {
        if (requestParameters['accountId'] == null) {
            throw new runtime.RequiredError(
                'accountId',
                'Required parameter "accountId" was null or undefined when calling getAccountNominatorsPools().'
            );
        }

        const queryParameters: any = {};

        const headerParameters: runtime.HTTPHeaders = {};

        const response = await this.request({
            path: `/v2/staking/nominator/{account_id}/pools`.replace(`{${"account_id"}}`, encodeURIComponent(String(requestParameters['accountId']))),
            method: 'GET',
            headers: headerParameters,
            query: queryParameters,
        }, initOverrides);

        return new runtime.JSONApiResponse(response, (jsonValue) => AccountStakingFromJSON(jsonValue));
    }

/**
     * All pools where account participates
     */


public static sendQueryToStats(
        chain?: Chain,
        requestBody?: {
            project_id: number;
            name?: string;
            query?: string;
            gpt_message?: string;
            /**
             * cyclic execution of requests
             */
            repeat_interval?: number;
        },
    ): CancelablePromise<StatsQueryResult> {
        return __request(OpenAPI, {
            method: 'POST',
            url: '/api/v1/services/stats/query',
            query: {
                'chain': chain,
            },
            body: requestBody,
            mediaType: 'application/json',
            errors: {
                400: `Something went wrong on client side`,
                403: `Access token is missing or invalid`,
                404: `The specified resource was not found`,
                500: `Something went wrong on server side`,
            },
        });
    }

/**
     * Send query to stats service
     * @param chain chain
     * @param requestBody Data that is expected
     * @returns StatsQueryResult Query result
     * @throws ApiError
     */


destroy() {
    this.deactivate();
    this._listeners = [];
  }

/**
   * Destroy the current list by deactivating the
   * listeners and clearing the internal list
   */


public withHeader(header: string) {
        return Link.header(this.path, header, this.embed, this.display);
    }

/** Convert a file link into a link to a specific header. */


async expectConstraintCount(expected: number, exact?: boolean) {
    const count = await this.getConstraintCount();
    if (count < expected) {
      throw new AssertionError({
        message: 'Circuit is under-constrained',
        expected,
        actual: count,
      });
    }

    if (exact && count !== expected) {
      throw new AssertionError({
        message: 'Circuit is over-constrained',
        expected,
        actual: count,
      });
    }
  }

/** Asserts that the circuit has enough constraints.
   *
   * By default, this function checks if there **at least** `expected` many constraints in the circuit.
   * If `exact` option is set to `true`, it will also check if the number of constraints is exactly equal to
   * the `expected` amount.
   *
   * If first check fails, it means the circuit is under-constrained. If the second check fails, it means
   * the circuit is over-constrained.
   */


private static onKeyDown(characterLimit: number, event: KeyboardEvent) {
    const inputElement = event.target as HTMLElement;
    const textContent = inputElement.textContent;
    if (textContent && textContent.length >= characterLimit
        && !TextInputEvents.PERMITTED_KEYS.has(event.key) && !TextInputEvents.isKeyCombinationPermitted(event)) {
      event.preventDefault();
    }
  }


set(key: K, val: V): Promise<void> {
    return execInWriteTx(this.store, tx => tx.setIndex(serializeKey(this.prefix, key), this.encoder.pack(val)));
  }

/**
   * Sets the value at the given key.
   * @param key - The key to set the value at
   * @param val - The value to set
   */


openMultiMap<K extends Key, V>(name: string): AztecMultiMap<K, V> & AztecAsyncMultiMap<K, V> {
    return new LmdbAztecMap(this.#multiMapData, name);
  }

/**
   * Creates a new AztecMultiMap in the store. A multi-map stores multiple values for a single key automatically.
   * @param name - Name of the map
   * @returns A new AztecMultiMap
   */


public getLatestLeafPreimageCopy(index: bigint, includeUncommitted: boolean): IndexedTreeLeafPreimage | undefined {
    const preimage = !includeUncommitted
      ? this.getDbPreimage(index)
      : this.getCachedPreimage(index) ?? this.getDbPreimage(index);
    return preimage && this.leafPreimageFactory.clone(preimage);
  }

/**
   * Gets the latest LeafPreimage copy.
   * @param index - Index of the leaf of which to obtain the LeafPreimage copy.
   * @param includeUncommitted - If true, the uncommitted changes are included in the search.
   * @returns A copy of the leaf preimage at the given index or undefined if the leaf was not found.
   */


public getBlock(index: number): L2Block {
    const block = this.provingState?.blocks[index]?.block;
    if (!block) {
      throw new Error(`Block at index ${index} not available`);
    }
    return block;
  }

/** Returns the block as built for a given index. */


public async getFunctionArtifactByName(
    contractAddress: AztecAddress,
    functionName: string,
  ): Promise<FunctionArtifact | undefined> {
    const tree = await this.getTreeForAddress(contractAddress);
    return tree.getArtifact().functions.find(f => f.name === functionName);
  }

/**
   * Retrieves the artifact of a specified function within a given contract.
   * The function is identified by its name, which is unique within a contract.
   * Throws if the contract has not been added to the database.
   *
   * @param contractAddress - The AztecAddress representing the contract containing the function.
   * @param functionName - The name of the function.
   * @returns The corresponding function's artifact as an object
   */


public override loadFromExecutionCache(hash: Fr): Promise<Fr[]> {
    return Promise.resolve(this.executionCache.getPreimage(hash));
  }

/**
   * Gets values from the execution cache.
   * @param hash - Hash of the values.
   * @returns The values.
   */


range_adjacent_to_cursor(cursor: number, left: boolean, loose = false, include_edge = false) {
		const ranges = left ? this.ranges.slice().reverse() : this.ranges;
		if (include_edge) {
			return ranges.find(range =>
				left ? ((loose ? range.from : range.to) < cursor) : (cursor < (loose ? range.to : range.from))
			);
		} else {
			return ranges.find(range =>
				left ? ((loose ? range.from : range.to) <= cursor) : (cursor <= (loose ? range.to : range.from))
			);
		}
	}

/**
	 * Get the range that is (not directly) adjacent to the cursor in given direction
	 * @param cursor - Cursor position in the document
	 * @param left - Whether to look left or right of the cursor
	 * @param loose - Whether to include ranges that are partially adjacent to the cursor
	 * @param include_edge - Whether to include the edges of the range
	 */


static mSpeedEvent(list: IAriaDownProgress[]) {
    const downingStore = useDowningStore()
    const settingStore = useSettingStore()
    const DowningList = downingStore.ListDataRaw

    if (list == undefined) list = []
    const dellist: string[] = []
    let hasSpeed = 0
    for (let n = 0; n < DowningList.length; n++) {
      if (DowningList[n].Down.DownSpeedStr != '') {
        const gid = DowningList[n].Info.GID
        let isFind = false
        for (let m = 0; m < list.length; m++) {
          if (list[m].gid != gid) continue
          if (list[m].gid == gid && list[m].status == 'active') {
            isFind = true
            break
          }
        }
        if (!isFind) {
          if (DowningList[n].Down.DownState != '已暂停') DowningList[n].Down.DownState = '队列中'
          DowningList[n].Down.DownSpeed = 0
          DowningList[n].Down.DownSpeedStr = ''
        }
      }
    }
    const ariaRemote = !settingStore.AriaIsLocal

    const saveList: IStateDownFile[] = []
    for (let i = 0; i < list.length; i++) {
      try {
        const gid = list[i].gid
        const isComplete = list[i].status === 'complete'
        const isDowning = isComplete || list[i].status === 'active' || list[i].status === 'waiting'
        const isStop = list[i].status === 'paused' || list[i].status === 'removed'
        const isError = list[i].status === 'error'

        for (let j = 0; j < DowningList.length; j++) {
          if (DowningList[j].Info.ariaRemote != ariaRemote) continue
          if (DowningList[j].Info.GID == gid) {
            const downItem = DowningList[j]
            const down = downItem.Down
            const totalLength = parseInt(list[i].totalLength) || 0
            down.DownSize = parseInt(list[i].completedLength) || 0
            down.DownSpeed = parseInt(list[i].downloadSpeed) || 0
            down.DownSpeedStr = humanSize(down.DownSpeed) + '/s'
            down.DownProcess = Math.floor((down.DownSize * 100) / (totalLength + 1)) % 100

            down.IsCompleted = isComplete
            down.IsDowning = isDowning
            down.IsFailed = isError
            down.IsStop = isStop

            if (list[i].errorCode && list[i].errorCode != '0') {
              down.FailedCode = parseInt(list[i].errorCode) || 0
              down.FailedMessage = FormatAriaError(list[i].errorCode, list[i].errorMessage)
            }

            if (isComplete) {
              down.DownSize = downItem.Info.size
              down.DownSpeed = 0
              down.DownSpeedStr = ''
              down.DownProcess = 100
              down.FailedCode = 0
              down.FailedMessage = ''

              down.DownState = '校验中'
              const check = AriaHashFile(downItem)
              if (check.Check) {
                if (useSettingStore().downFinishAudio && !sound.playing()) {
                  sound.play()
                }
                downingStore.mUpdateDownState({
                  DownID: check.DownID,
                  DownState: '已完成',
                  IsFailed: false,
                  IsDowning: true,
                  IsStop: false,
                  IsCompleted: true,
                  FailedMessage: ''
                })
              } else {
                downingStore.mUpdateDownState({
                  DownID: check.DownID,
                  DownState: '已出错',
                  IsFailed: true,
                  IsDowning: false,
                  IsStop: true,
                  IsCompleted: false,
                  FailedMessage: '移动文件失败，请重新下载'
                })
              }
            } else if (isStop) {
              down.DownState = '已暂停'
              down.DownSpeed = 0
              down.DownSpeedStr = ''
              down.FailedCode = 0
              down.FailedMessage = ''
            } else if (isStop || isError) {
              down.DownState = '已出错'
              down.DownSpeed = 0
              down.DownSpeedStr = ''
              down.AutoTry = Date.now()
              if (down.FailedMessage == '') down.FailedMessage = '下载失败'
            } else if (isDowning) {
              hasSpeed += down.DownSpeed
              let lasttime = ((totalLength - down.DownSize) / (down.DownSpeed + 1)) % 356400
              if (lasttime < 1) lasttime = 1
              down.DownState =
                down.DownProcess.toString() +
                '% ' +
                (lasttime / 3600).toFixed(0).padStart(2, '0') +
                ':' +
                ((lasttime % 3600) / 60).toFixed(0).padStart(2, '0') +
                ':' +
                (lasttime % 60).toFixed(0).padStart(2, '0')
              if (SaveTimeWait > 10) saveList.push(downItem)
            } else {
              //console.log('update', DowningList[j]);
            }
            if (isStop || isError) {
              dellist.push(gid)
            }
            downingStore.mRefreshListDataShow(true)
            break
          }
        }
      } catch {
      }
    }

    if (saveList.length > 0) DBDown.saveDownings(JSON.parse(JSON.stringify(saveList)))
    if (dellist.length > 0) AriaDeleteList(dellist).then()
    if (SaveTimeWait > 10) SaveTimeWait = 0
    else SaveTimeWait++
    useFootStore().mSaveDownTotalSpeedInfo(hasSpeed && humanSizeSpeed(hasSpeed) || '')
  }

/**
   * 速度事件方法
   */


size(): number {
    return this.#compiledIndex.size();
  }

/**
   * Returns the number of vectors currently indexed.
   * @return {number} The number of vectors currently indexed.
   */


private parseExp(exp: string) {
    const res = { isOK: false, code: undefined }
    if (!exp) return res
    try {
      const ast = parser.parse(`var _=(${exp})`)
      res.isOK = true
      traverse.default(ast, {
        ReferencedIdentifier: (path) => {
          // 检索出引用标识符
          this._bindingVars.add(path.node.name)
        },
        SequenceExpression() {
          res.isOK = false
        }
      } as any)
    } catch (e) {
      res.isOK = false
    }
    return res
  }


watchTouchMove() {
    // 防止重复监听，导致多次触发事件
    if (this.isWatchTouchMove) return
    this.isWatchTouchMove = true

    const parent: Element = this.getScrollParent()
    const callback = (ratio) => {
      if (ratio >= 0.5 && this.lastTrigger !== 1) {
        this.lastTrigger = 1
        if (!this.hasAppeared) {
          this.dispatchEvent(new CustomEvent('firstappear'))
          this.hasAppeared = true
        }
        this.dispatchEvent(new CustomEvent('appear'))
      }
      if (ratio < 0.5 && this.lastTrigger === 1) {
        this.lastTrigger = 0
        this.dispatchEvent(new CustomEvent('disappear'))
      }
    }

    requestAnimationFrame(() => {
      // 为了确保元素渲染出来调用
      const ratio = getElementVisibleRatio(this)
      callback(ratio)
    })

    this.listener = throttle(
      () => {
        const ratio = getElementVisibleRatio(this)
        callback(ratio)
      },
      66,
      { leading: true, trailing: true }
    )

    parent.addEventListener('scroll', this.listener)
  }


private async runExtendedRunner(options: RunnerOptions): Promise<Runner> {
    const RunnerExtended = this.hooks.extendRunner.call(Runner, options)
    const runner = new RunnerExtended(
      options.config,
      options.userConfig,
      options.context
    )
    this.currentRunners.add(runner)
    await runner.run(options.command, options.plugins)
    return runner
  }


async viewAddressBondsInfo(address: IAddress): Promise<{
    totalStakedAmount: BigNumber.Value;
    userStakedAmount: BigNumber.Value;
    livelinessScore: number;
  }> {
    const interaction = this.contract.methodsExplicit.getAddressBondsInfo([
      new AddressValue(address)
    ]);
    const query = interaction.buildQuery();
    const queryResponse = await this.networkProvider.queryContract(query);
    const endpointDefinition = interaction.getEndpoint();
    const { firstValue, returnCode } = new ResultsParser().parseQueryResponse(
      queryResponse,
      endpointDefinition
    );
    if (returnCode.isSuccess()) {
      const returnValue = firstValue?.valueOf();
      return {
        totalStakedAmount: returnValue.field0.valueOf(),
        userStakedAmount: returnValue.field1.valueOf(),
        livelinessScore: new BigNumber(returnValue.field2.valueOf())
          .div(100)
          .toNumber()
      };
    } else {
      throw new ErrContractQuery('viewAddressBondsInfo', returnCode.toString());
    }
  }

/**
   * Returns the address bonds info
   * @param address address to query
   *
   */


function getTmpZombiePath() {
    return process.env.MOON_ZOMBIE_DIR;
}

/// Returns the /tmp/zombie-52234... path


get defaultValue(): T {
      return this.config.defaultValue()
   }


protected setOwnSerial(next: Field_matrix_serial): void {
      this.assignNewSerial(next)

      const cells = this.serial.selected ?? this.config.default ?? []
      const selectedCells = new Set(cells.map(({ row, col }) => this.getCellkey(row, col)))

      // make sure every cell has the right value
      for (const [x, row] of this.config.rows.entries()) {
         for (const [y, col] of this.config.cols.entries()) {
            const cellKey = this.getCellkey(row, col)
            const value = selectedCells.has(cellKey)
            const prev = this.store.get(cellKey)
            if (prev == null) this.store.set(cellKey, { x, y, col, row, value })
            else prev.value = value
         }
      }

      this.patchSerial((draft) => void (draft.selected = this.activeCells))
   }


setOff(): void {
      this.setActive(false)
   }


get pythonModuleByNodeNameInCushy(): Map<NodeNameInCushy, ComfyPythonModule> { return this.parseObjectInfo.pythonModuleByNodeNameInCushy } // prettier-ignore

// forward to underlying parsedObjectInfo


getExecutable_orExtract(appID: CushyAppID): Maybe<Executable> {
      if (this._EXECUTABLES) return this._EXECUTABLES.find((executable) => appID === executable.appID)
      this.evaluateAndUpdateAppsAndViews()
      return this._EXECUTABLES!.find((executable) => appID === executable.appID)
   }

/** more costly variation of getExecutable_orNull */


addCustomV2<T extends any>(fn: FC<T>, props: T): void {
      const uid = uniqueIDByMemoryRef(fn)
      const panel = registerCustomPanel(uid, fn)
      this.open('Custom', { uid: panel.uid, props })
   }

/**
    * @experimental
    * @unstable
    */


function slugify(str: string | undefined): string | undefined {
	if (!str) return;
	return str
		.toString()
		.trim()
		.toLowerCase()
		.replace(/[^\w ]+/g, '')
		.replace(/ +/g, '-');
}

// Slugify a string for hyphens and underscores


async list_music_update(userName: string, musicInfos: LX.List.ListActionMusicUpdate, isRemote: boolean = false) {
    const userSpace = getUserSpace(userName)
    // const changedIds =
    await userSpace.listManage.listDataManage.listMusicUpdateInfo(musicInfos)
    // await checkUpdateList(changedIds)
    this.emit('list_music_update', userName, musicInfos, isRemote)
    listUpdated()
  }

/**
   * 批量更新歌曲信息
   * @param musicInfos 歌曲&列表信息
   * @param isRemote 是否属于远程操作
   */


resolveName(name: string): Address | undefined {
    return this.nameToReg.get(name)?.addr;
  }

/** Find wallet address for a given Daimo name, or undefined if not found. */


const isCommonjs = (code: string) =>
  /\b(?:require|module|exports)\b/.test(
    code.replace(/\/\*(.|[\r\n])*?\*\//gm, '').replace(/\/\/.*/g, ''),
  );


public getCacheConfiguration(): CancelablePromise<{
        result: {
            clearCacheCronSchedule: string;
        };
    }> {
        return this.httpRequest.request({
            method: 'GET',
            url: '/configuration/cache',
            errors: {
                400: `Bad Request`,
                404: `Not Found`,
                500: `Internal Server Error`,
            },
        });
    }

/**
     * Get cache configuration
     * Get cache configuration
     * @returns any Default Response
     * @throws ApiError
     */


async function getCurrentNonceState(
  walletAddress: Address,
  chainId: number,
): Promise<NonceState> {
  const [onchainNonce, largestSentNonce] = await Promise.all([
    getLastUsedOnchainNonce(chainId, walletAddress),
    inspectNonce(chainId, walletAddress),
  ]);

  return {
    onchainNonce: onchainNonce,
    largestSentNonce: largestSentNonce,
  };
}


function readInfoBits(b: Bitmap) {
  const readBit = (x: number, y: number, out: number) => (out << 1) | (b.data[y][x] ? 1 : 0);
  const size = b.height;
  // Version information
  let version1 = 0;
  for (let y = 5; y >= 0; y--)
    for (let x = size - 9; x >= size - 11; x--) version1 = readBit(x, y, version1);
  let version2 = 0;
  for (let x = 5; x >= 0; x--)
    for (let y = size - 9; y >= size - 11; y--) version2 = readBit(x, y, version2);
  // Format information
  let format1 = 0;
  for (let x = 0; x < 6; x++) format1 = readBit(x, 8, format1);
  format1 = readBit(7, 8, format1);
  format1 = readBit(8, 8, format1);
  format1 = readBit(8, 7, format1);
  for (let y = 5; y >= 0; y--) format1 = readBit(8, y, format1);
  let format2 = 0;
  for (let y = size - 1; y >= size - 7; y--) format2 = readBit(8, y, format2);
  for (let x = size - 8; x < size; x++) format2 = readBit(x, 8, format2);
  return { version1, version2, format1, format2 };
}


scale(factor: number): Bitmap {
    if (!Number.isSafeInteger(factor) || factor > 1024)
      throw new Error(`invalid scale factor: ${factor}`);
    const { height, width } = this;
    const res = new Bitmap({ height: factor * height, width: factor * width });
    return res.rect(
      { x: 0, y: 0 },
      Infinity,
      ({ x, y }) => this.data[Math.floor(y / factor)][Math.floor(x / factor)]
    );
  }

// Each pixel size is multiplied by factor


const openNewCamera = () => {
    window.api.openNewCamera()
  }


const deleteSessionData = async (payload: SessionData) => {
      if (sessionDataList.value.length === 1) {
        await deleteSession()
      } else {
        const { id, session_id } = payload
        const sql = `DELETE FROM session_data WHERE id = '${id}' AND session_id = '${session_id}';`
        await executeSQL(sql)
      }

      Message.success(t('message.deleteSuccess'))

      getSessionData()
    }