>

در اینجا یک مثال بد از کد با اتصال محکم آورده شده است:

public class Database
{
    private SqlServerConnection _databaseConnection;
    public Database(SqlServerConnection databaseConnection)

    {
        _databaseConnection = databaseConnection;
    }
}

همانطور که از مثال می‌بینید، کلاس پایگاه داده ما به استفاده از SQL Server وابسته است و برای پذیرش هر نوع پایگاه داده دیگری نیاز به تغییر هاردکد (hardcoded) خواهد داشت. ما در فصل‌های بعدی، بازسازی کد را با مثال‌های کد واقعی پوشش خواهیم داد.

انسجام پایین (Low Cohesion)

انسجام پایین (Low cohesion) شامل کدهای نامرتبطی است که وظایف مختلفی را انجام می‌دهند و همگی با هم گروه‌بندی شده‌اند. یک مثال می‌تواند یک کلاس ابزار (utility class) باشد که شامل تعدادی متد ابزاری مختلف برای مدیریت تاریخ‌ها، متن، اعداد، انجام ورودی و خروجی فایل، اعتبارسنجی داده (data validation) و رمزگذاری و رمزگشایی (encryption and decryption) است.

اشیاء سرگردان (Hanging Around) در حافظه

هنگامی که اشیاء در حافظه سرگردان می‌مانند، می‌توانند منجر به نشت حافظه (memory leaks) شوند.

متغیرهای استاتیک (Static variables) می‌توانند به چندین روش منجر به نشت حافظه شوند. اگر از DependencyObject یا INotifyPropertyChanged استفاده نمی‌کنید، در واقع در حال مشترک شدن در رویدادها (subscribing to events) هستید. Common Language Runtime (CLR) با استفاده از رویداد ValueChanged از طریق رویداد PropertyDescriptors AddValueChanged، یک ارجاع قوی (strong reference) ایجاد می‌کند که منجر به ذخیره PropertyDescriptor می‌شود که به شیء‌ای که به آن متصل است، ارجاع می‌دهد.

<p


\n\t\t\nTask category\nt2c\n\n\nDomains\nNews, Written\n\n\nReference\nhttps://github.com/AnushaMotamarri/Telugu-Newspaper-Article-Dataset\n\n\n\t\n\n\n\t\n\t\t\n\t\tHow to evaluate on this task\n\t\n\nYou can evaluate an embedding model on this dataset using the following code:\nimport mteb\n\ntask = mteb.get_task(\"TeluguAndhraJyotiNewsClassification\")… See the full description on the dataset page: https://huggingface.co/datasets/mteb/TeluguAndhraJyotiNewsClassification.","first_N":5,"first_N_keywords":["text-classification","topic-classification","derived","monolingual","mlexplorer008/telugu_news_classification"],"keywords_longer_than_N":true},
	{"name":"TenKGnadClusteringP2P.v2","keyword":"mteb","license":"Creative Commons Attribution Share Alike 4.0 International","license_url":"https://choosealicense.com/licenses/cc-by-sa-4.0/","language":"en","dataset_url":"https://huggingface.co/datasets/mteb/TenKGnadClusteringP2P.v2","creator_name":"Massive Text Embedding Benchmark","creator_url":"https://huggingface.co/mteb","description":"\n  TenKGnadClusteringP2P.v2\n  An MTEB dataset\n  Massive Text Embedding Benchmark\n\n\nClustering of news article titles+subheadings+texts. Clustering of 10 splits on the news article category.\n\n\t\n\t\t\n\n\n\n\n\t\t\nTask category\nt2c\n\n\nDomains\nNews, Non-fiction, Written\n\nReference\nhttps://tblock.github.io/10kGNAD/\n\n\n\t\n\n\n\t\n\t\t\n\t\tHow to evaluate on this task\n\t\n\nYou can evaluate an embedding model on this dataset using the following code:\nimport mteb\n\ntask = mteb.get_task(\"TenKGnadClusteringP2P.v2\")\nevaluator… See the full description on the dataset page: https://huggingface.co/datasets/mteb/TenKGnadClusteringP2P.v2.","first_N":5,"first_N_keywords":["text-classification","derived","monolingual","slvnwhrl/tenkgnad-clustering-p2p","German"],"keywords_longer_than_N":true},
	{"name":"TenKGnadClusteringS2S.v2","keyword":"mteb","license":"Creative Commons Attribution Share Alike 4.0 International","license_url":"https://choosealicense.com/licenses/cc-by-sa-4.0/","language":"en","dataset_url":"https://huggingface.co/datasets/mteb/TenKGnadClusteringS2S.v2","creator_name":"Massive Text Embedding Benchmark","creator_url":"https://huggingface.co/mteb","description":"\n  TenKGnadClusteringS2S.v2\n  An MTEB dataset\n  Massive Text Embedding Benchmark\n\n\nClustering of news article titles. Clustering of 10 splits on the news article category.\n\n\t\n\t\t\n\n\n\n\n\t\t\nTask category\nt2c\n\n\nDomains\nNews, Non-fiction, Written\n\n\nReferencehttps://tblock.github.io/10kGNAD/\n\n\n\t\n\n\n\t\n\t\t\n\t\tHow to evaluate on this task\n\t\n\nYou can evaluate an embedding model on this dataset using the following code:\nimport mteb\n\ntask = mteb.get_task(\"TenKGnadClusteringS2S.v2\")\nevaluator =… See the full description on the datase


oad' attribute.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	int IFC_STRUCTURAL_LINEAR_ACTION_VARYING__DESTABILIZING_LOAD = IFC_STRUCTURAL_LINEAR_ACTION__DESTABILIZING_LOAD;

	/**
	 * The feature id for the 'Caused By' reference.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	int IFC_STRUCTURAL_LINEAR_ACTION_VARYING__CAUSED_BY = IFC_STRUCTURAL_LINEAR_ACTION__CAUSED_BY;

	/**
	 * The feature id for the 'Projected Or True' attribute.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	int IFC_STRUCTURAL_LINEAR_ACTION_VARYING__PROJECTED_OR_TRUE = IFC_STRUCTURAL_LINEAR_ACTION__PROJECTED_OR_TRUE;

	/**
	 * The feature id for the 'Varying Applied Load Location' reference.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	int IFC_STRUCTURAL_LINEAR_ACTION_VARYING__VARYING_APPLIED_LOAD_LOCATION = IFC_STRUCTURAL_LINEAR_ACTION_FEATURE_COUNT
			+ 0;

	/**
	 * The feature id for the 'Subsequent Applied Loads' reference list.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	int IFC_STRUCTURAL_LINEAR_ACTION_VARYING__SUBSEQUENT_APPLIED_LOADS = IFC_STRUCTURAL_LINEAR_ACTION_FEATURE_COUNT + 1;

	/**
	 * The number of structural features of the 'Ifc Structural Linear Action Varying' class.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	int IFC_STRUCTURAL_LINEAR_ACTION_VARYING_FEATURE_COUNT = IFC_STRUCTURAL_LINEAR_ACTION_FEATURE_COUNT + 2;

	/**
	 * The meta object id for the '{@link org.bimserver.models.ifc2x3tc1.impl.IfcStructuralLoadImpl Ifc Structural Load}' class.
	 *
	 *
	 * @see org.bimserver.models.ifc2x3tc1.impl.IfcStructuralLoadImpl
	 * @see org.bimserver.models.ifc2x3tc1.impl.Ifc2x3tc1PackageImpl#getIfcStructuralLoad()
	 * @generated
	 */
	int IFC_STRUCTURAL_LOAD = 544;

	/**
	 * The feature id for the 'Name' attribute.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	int IFC_STRUCTURAL_LOAD__NAME = 0;

	/**
	 * The number of structural features of the 'Ifc Structural Load' class.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	int IFC_STRUCTURAL_LOAD_FEATURE_COUNT = 1;

	/**
	 * The meta object id for the '{@link org.bimserver.models.ifc2x3tc1.impl.IfcStructuralLoadGroupImpl Ifc Structural Load Group}' class.
	 *
	 *
	 * @see org.bimserver.models.ifc2x3tc1.impl.IfcStructuralLoadGroupImpl
	 * @see org.bimserver.models.ifc2x3tc1.impl.If


 value for whereHour must not be null.',
      );
    }

    final paramName = _nextParamName();
    bindings[paramName] = value;

    return "HOUR($column) $operator :$paramName";
  }

  String _createInCondition(
    String column,
    dynamic values,
    bool not,
  ) {
    String clause = not ? "NOT IN" : "IN";

    if (values is List) {
      if (values.isEmpty) {
        throw InvalidArgumentException(
          "The list of values for IN must not be empty.",
        );
      }

      List<String> paramNames = [];
      for (var i = 0; i < values.length; i++) {
        final paramName = _nextParamName();
        bindings[paramName] = values[i];
        paramNames.add(":$paramName");
      }

      return "$column $clause (${paramNames.join(", ")})";
    } else if (values is QueryBuilder) {
      final subQuery = values.toSql();
      bindings.addAll((values as dynamic).getBindings());
      return "$column $clause ($subQuery)";
    } else {
      throw InvalidArgumentException(
        "The value for 'values' must be of type List or QueryBuilder.",
      );
    }
  }

  String _createJsonContainsCondition(
    String column,
    dynamic value,
    bool not,
  ) {
    final paramName = _nextParamName();
    bindings[paramName] = value;

    String condition = "JSON_CONTAINS($column, :$paramName)";
    if (not) {
      condition = "NOT $condition";
    }
    return condition;
  }

  String _createJsonLengthCondition(
    String column,
    String operator,
    dynamic value,
  ) {
    final paramName = _nextParamName();
    bindings[paramName] = value;

    return "JSON_LENGTH($column) $operator :$paramName";
  }

  String _createLikeCondition(String column, dynamic value,
      {bool not = false, bool caseSensitive = false}) {
    final paramName = _nextParamName();
    bindings[paramName] = value;

    String operator = not ? "NOT LIKE" : "LIKE";
    if (!caseSensitive) {
      return "LOWER($column) $operator LOWER(:$paramName)";
    }
    return "$column $operator :$paramName";
  }

  String _createNullCondition(String column, bool not) {
    return "$column IS ${not ? 'NOT ' : ''}NULL";
  }

  String _createRowValuesCondition(
    List<String> columns,
    String operator,
    List<dynamic> values,
  ) {
    if (columns.length != values.length) {
      throw InvalidArgumentException(
        "The number of columns and values must be equal.",
      );
    }

    List<String> paramNames = [];
    for (var i = 0; i < values.length; i++) {
      final paramName = _nextParamName();
      bindings[paramName] = values[i];
      paramNames.add(":$paramName");
    }

    String cols = "(${columns.join(", ")})";
    String vals = "(${paramNames.join(", ")})";

    return "$cols $operator $vals";
  }

  String _processRawSQL(String sql, List<dynamic> rawBindings) {
    String processed = sql;
    for (var binding in rawBindings) {
      final paramName = _nextParamName();
      bindings[paramName] = binding;
      processed = processed.replaceFirst('?', ':$paramName');
    }

    return processed;
  }
}
import 'package:vania/src/database/db.dart';
import 'package:vania/src/http/request/request_file.dart';

class Rules {
  /// Check field is requ


nodiscard]] EvaluationType evaluate() const;

    /**
     * @brief Gets a const reference to the underlying vector of terms.
     * @return A const reference to `m_terms`.
     */
    [[nodiscard]] const TermsVectorType& terms() const;

    /**
     * @brief Returns a const iterator to the beginning of the terms vector.
     * @return A const iterator.
     */
    [[nodiscard]] typename TermsVectorType::const_iterator begin() const;

    /**
     * @brief Returns a const iterator to the end of the terms vector.
     * @return A const iterator.
     */
    [[nodiscard]] typename TermsVectorType::const_iterator end() const;

    LinearCombination<VarT> linear_combine(const Rat& coeff_this,
                                             const Rat& coeff_other,
                                             const LinearCombination<VarT>& other);

    auto operator<=>(const LinearCombination& other) const = default;
  };

  /**
   * @brief Multiplies a linear combination by a coefficient (coeff * lc).
   * @param multiplier The coefficient.
   * @param lc The linear combination.
   * @return A new linear combination representing the product.
   */
  template <typename VarT>
  LinearCombination<VarT> operator*(const Rat& multiplier,
                                      const LinearCombination<VarT>& lc);

  /**
   * @brief Inserts a string representation of the linear combination into an output stream.
   * @param os The output stream.
   * @param lc The linear combination to print.
   * @return A reference to the output stream.
   */
  template <typename VarT>
  std::ostream& operator<<(std::ostream& os, const LinearCombination<VarT>& lc);

} // namespace Yuclid

#define YUCLID_INSTANTIATE_LINEAR_COMBINATION(r, prefix, VarT)          \
  prefix template class Yuclid::LinearCombination<VarT>;                \
  prefix template Yuclid::LinearCombination<VarT>                       \
  Yuclid::operator*(const Yuclid::Rat& multiplier,                      \
                    const Yuclid::LinearCombination<VarT>& lc);         \
  prefix template std::ostream&                                         \
  Yuclid::operator<<(std::ostream& os,                                  \
                     const Yuclid::LinearCombination<VarT>& lc);

BOOST_PP_SEQ_FOR_EACH(YUCLID_INSTANTIATE_LINEAR_COMBINATION, extern,
                      YUCLID_LINEAR_COMBINATION_TYPES)
/**
   Copyright 2025 Concordance Inc. dba Harmonic

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
#include "eqn_index.hpp"
#include "linear_system.hpp"
#include "type/variable_types.hpp"
#include <boost/preprocessor/seq/for_each.hpp>
#include <ostream>

namespace Yuclid {

  // implementation of EqnIndex::equation()
  template <typename VarT>
  const Equation<VarT>& EqnIndex<VarT>::equation() const {
    return m_system->at(*this);
  }

  template <typename VarT>
  std::ostream& operator<<(std::ostream& os, const EqnIndex<VarT>& idx) {
    os << "Eq[" << idx.get() << "]: " << idx.equation();
    return os;
  }

}

BOOST_PP_SEQ_FOR_EAC


; 2
OldPeriod:	equ	30	; 2
OrgPeriodARP	equ	32	; 2
Oldd0		equ	34	; 2
Oldd1		equ	36	; 2
Oldd2		equ	38	; 2
Oldd3		equ	40	; 2
Oldd4		equ	42	; 2
Oldd5		equ	44	; 2
Oldd6		equ	46	; 2
loopsdataschanA	equ	48	; 4
loopsdataschanB	equ	52	; 4

EqNewSamA	equ	56	; 1
EqNewSamB	equ	57	; 1

VolEnvTime	equ	58	; 2
VolEnvOff	equ	60	; 1
VolEnvMode	equ	61	; 1

PortUpOldValA	equ	62	; 1
PortUpOldValB	equ	63	; 1
PortDownOldValA	equ	64	; 1
PortDownOldValB	equ	65	; 1
VibratoDatasA	equ	66	; 4
VibratoDatasB	equ	70	; 4
GlissandoDatasA	equ	74	; 6
GlissandoDatasB	equ	80	; 6

NoteDelayPeriodA	equ	86	; 2
NoteDelayInstrNumA	equ	88	; 2
NoteDelayPeriodB	equ	90	; 2
NoteDelayInstrNumB	equ	92	; 2

PanPos		equ	94	; 4		; it is a calculated panning

OnOffChanA	equ	98	; 1
OnOffChanB	equ	99	; 1

PanEnvTime	equ	100	; 2
PanEnvOff	equ	102	; 1
PanEnvMode	equ	103	; 1

GeneralPan	equ	104	; 2		; it is a default pan
						; changeable by 8xx e8x and
						; general pan parameter in pan env
						; range (0-256)

OldMainVol:	equ	106	; 2
OldPanPos:	equ	108	; 4

SlidePanOldA	equ	112	; 1
SlidePanOldB	equ	113	; 1

LastFreq	equ	114	; 4
;----------------------------------------------

ahibase:	dc.l	0
ahi_ctrl:	dc.l	0

ahi_ctrltags:
        dc.l	AHIC_Play,1
        dc.l	TAG_DONE
ahi_tags
        dc.l	AHIA_MixFreq
ahi_freq
        dc.l	32600
        dc.l	AHIA_Channels
ahi_chan:
        dc.l	8
        dc.l	AHIA_Sounds,1
        dc.l	AHIA_AudioID
ahi_audioid
        dc.l	$00020002	; 2 pan, 4 stereo, 6 mono   8 8bit pan
        dc.l	AHIA_SoundFunc,SoundFunc
        dc.l	AHIA_PlayerFunc,PlayerFunc
        dc.l	AHIA_PlayerFreq,50<<16
        dc.l	AHIA_MinPlayerFreq,(8*2/5)<<16
        dc.l	AHIA_MaxPlayerFreq,(600*2/5)<<16
        dc.l	TAG_DONE

ahi_sound0:
        dc.l	AHIST_M8S
ahi_sta	dc.l	0	        ; start
ahi_len	dc.l	-1                ; len

AHI_VOLBOOST:
        dc.l	Ahiet_MasterVolume
AHIBoost
        dc.


  if (ot.children) {
    for (const child of ot.children) {

      const resChild = searchByArticleNumber(child, articleNumber)

      if (resChild) return resChild
    }
  }

  return null
}

// To optimize order creation, we hava a cache for the children of order templates
const cache = {}
async function createChildrenFromCache(db: Prisma, orderTemplateId: string) {

  if (!cache[orderTemplateId]) {
    cache[orderTemplateId] = await createChildren(db, orderTemplateId)
  }

  return cache[orderTemplateId]
}

async function createChildren(db: Prisma, orderTemplateId: string) {

  const ot = await db.query.orderTemplate(
    { where: { id: orderTemplateId } },
    "{ children { id defaultOrderAmount properties { name price currency } product { id } } }",
  )

  if (ot.children) {

    const orderItems = [] as OrderItemCreateInput[]

    for (const child of ot.children) {

      orderItems.push({
        name: child.product ? null : child.properties.name,
        amount: child.defaultOrderAmount,
        price: child.product ? null : child.properties.price,
        currency: child.product ? null : child.properties.currency,
        product: child.product ? { connect: { id: child.product.id } } : {},
        orderTemplate: { connect: { id: orderTemplateId } },
        items: await createChildren(db, child.id),
      })
    }
    return { create: orderItems } as OrderItemCreateManyInput
  }

  return {} as OrderItemCreateManyInput
}
import { Message } from "discord.js";
import { Command, CommandMessage, CommandoClient } from "discord.js-commando";
import { delay } from "../utils";

const emojis: string[] = ["🇷", "🇪", "🇵", "🇴", "🇸", "🇹"];

// tslint:disable-next-line:class-name
export class repostCommand extends Command {
    constructor(client: CommandoClient) {
        super(client, {
            args: [
                {
                    default: "",
                    key: "messageId",
                    prompt: "Which message should be tagged",
                    type: "string",
                },
            ],
            description: "Tags messages as repost",
            examples: ["!repost", "!repost <messageId>"],
            group: "custom",
            memberName: "repost",
            name: "repost",
        });
    }

    public async run(recievedMessage: CommandMessage, args: { messageId: string }): Promise<Message | Message[]> {
        // !repost <id> >>> tag message with id = <id>
        if (args.messageId) {
            await recievedMessage.channel.fetchMessage(args.messageId)
                .then(async (message) => { await tagMessage(message); })
                .catch(() => {
                    recievedMessage.channel
                        .send("The message was not found. use a valid messageId for an existing message")
                        .then(async (sentMessage: Message) => {
                            // Delete the error message after 5 seconds
                            await delay(5000);
                            sentMessage.deletable && await sentMessage.delete();
                        })
                        .catch();
                });
            // !repost >>> tag message before command
        } else {
            recievedMessage.channel.fetchMessages({ before: recievedMessage.id, limit: 1 })
                .then(async (messages) =>
                    await tagMessage(messages.first()),
                );
        }
		await recievedMessage.deletable && recievedMessage.delete();
        return;
    }
}

async function tagMessage(message: Message): Promise<void> {
    for (const emoji of


/************************************************************************
 **
 **  @file   dialogcutarc.h
 **  @author Roman Telezhynskyi <dismine(at)gmail.com>
 **  @date   7 1, 2014
 **
 **  @brief
 **  @copyright
 **  This source code is part of the Valentina project, a pattern making
 **  program, whose allow create and modeling patterns of clothing.
 **  Copyright (C) 2013-2015 Valentina project
 **  <https://gitlab.com/smart-pattern/valentina> All Rights Reserved.
 **
 **  Valentina is free software: you can redistribute it and/or modify
 **  it under the terms of the GNU General Public License as published by
 **  the Free Software Foundation, either version 3 of the License, or
 **  (at your option) any later version.
 **
 **  Valentina is distributed in the hope that it will be useful,
 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 **  GNU General Public License for more details.
 **
 **  You should have received a copy of the GNU General Public License
 **  along with Valentina.  If not, see <http://www.gnu.org/licenses/>.
 **
 *************************************************************************/

#ifndef DIALOGCUTARC_H
#define DIALOGCUTARC_H

#include <qcompilerdetection.h>
#include <QMetaObject>
#include <QObject>
#include <QString>
#include <QtGlobal>

#include "../vmisc/def.h"
#include "dialogtool.h"

namespace Ui
{
    class DialogCutArc;
}

/**
 * @brief The DialogCutArc class dialog for ToolCutArc.
 */
class DialogCutArc : public DialogTool
{
    Q_OBJECT
public:

    DialogCutArc(const VContainer *data, quint32 toolId, QWidget *parent = nullptr);
    virtual ~DialogCutArc() override;

    QString           GetPointName() const;
    void              SetPointName(const QString &value);

    QString           GetFormula() const;
    void              SetFormula(const QString &value);

    quint32           getArcId() const;
    void              setArcId(quint32 value);
public slots:
    virtual void      ChosenObject(quint32 id, const SceneObject &type) override;
    /**
     * @brief DeployFormulaTextEdit grow or shrink formula input
     */
    void              DeployFormulaTextEdit();

    void              FXLength();
    void              EvalFormula();
protected:
    virtual void      ShowVisualization() override;
    /**
     * @brief SaveData Put dialog data in local variables
     */
    virtual void      SaveData() override;
    virtual void      closeEvent(QCloseEvent *event) override;
    virtual bool      IsValid() const final;
private slots:
    void ArcChanged();
private:
    Q_DISABLE_COPY(DialogCutArc)
    /** @brief ui keeps information about user interface */
    Ui::DialogCutArc  *ui;

    /** @brief formula string with formula */
    QString formula;
    QString pointName;

    /** @brief formulaBaseHeight base height defined by dialogui */
    int               formulaBaseHeight;

    QTimer *timerFormula;

    bool flagFormula;
    bool flagName;
};

//---------------------------------------------------------------------------------------------------------------------
inline bool DialogCutArc::IsValid() const
{
    return flagFormula && flagName;
}

#endif // DIALOGCUTARC_H


涉及RCE（远程代码执行）或权限绕过，风险较高。更新内容提供了各个漏洞的详细描述、影响版本、利用条件、POC可用性以及投毒风险的评估。针对SQLPad的CVE-2022-0944漏洞，提供了多个POC，说明该漏洞的危害性和易利用性。此外，还包括了Chrome沙箱逃逸漏洞和Next.js中间件漏洞的分析。

#### 🔍 关键发现

| 序号 | 发现内容 |
|------|----------|
| 1 | 该仓库提供了多个CVE漏洞的分析报告，包括详细描述、影响版本、利用方式和POC |
| 2 | 针对SQLPad的CVE-2022-0944漏洞，提供了多个POC，说明其RCE风险 |
| 3 | 涉及的漏洞类型包括RCE、沙箱逃逸、权限绕过和文件读取，危害性高 |
| 4 | 漏洞分析涉及TeamViewer、Next.js、Chrome、Vite等多个组件，影响范围广 |

#### 🛠 技术细节

> CVE-2024-7479: TeamViewer 驱动签名验证漏洞，导致权限提升。POC可用，利用方式为本地权限提升，安装恶意驱动。

> CVE-2025-29927: Next.js 中间件授权绕过漏洞。POC可用，绕过中间件的授权检查，允许未授权访问。

> CVE-2022-0944: SQLPad 模板注入漏洞，导致RCE。多个POC，利用方式为构造恶意请求，执行任意代码。

> CVE-2025-2783: Chrome Mojo 沙箱逃逸漏洞。POC可用性不确定，存在投毒风险。

> CVE-2025-50000: CoPilot 用户ID混淆，导致信息泄露。POC可用，影响会话安全。

> CVE-2025-30208: Vite 文件读取漏洞。POC可用，通过构造恶意URL读取服务器文件。

#### 🎯 受影响组件

```
• TeamViewer Remote Client/Host
• Next.js
• SQLPad
• Google Chrome
• CoPilot
• Vite
```

#### ⚡ 价值评估

<details>
<summary>展开查看详细评估</summary>

该仓库更新内容涉及多个高危漏洞的分析，特别是SQLPad RCE漏洞和Chrome沙箱逃逸漏洞，提供了POC和详细的利用说明，对于安全研究和漏洞分析具有重要价值。
</details>

---

### poc_everyday - CVE/POC 收集与每日更新

#### 📌 仓库信息

| 属性 | 详情 |
|------|------|
| 仓库名称 | [poc_everyday](https://github.com/126789t/poc_ev


 cp0);
				}
				VECTORS.release(point);
			}
		} finally {
			VECTORS.release(vert0, vert1, vert2, v10, v20, triangleNormal);
		}
	}

	/**
	 * Report hit.
	 *
	 * @param hitNormalLocal the hit normal local
	 * @param hitFraction the hit fraction
	 * @param partId the part id
	 * @param triangleIndex the triangle index
	 * @return the float
	 */
	public abstract float reportHit(Vector3f hitNormalLocal, float hitFraction, int partId, int triangleIndex);

}
/*
 * Java port of Bullet (c) 2008 Martin Dvorak <jezek2@advel.cz>
 *
 * Bullet Continuous Collision Detection and Physics Library
 * Copyright (c) 2003-2008 Erwin Coumans  http://www.bulletphysics.com/
 *
 * This software is provided 'as-is', without any express or implied warranty.
 * In no event will the authors be held liable for any damages arising from
 * the use of this software.
 *
 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:
 *
 * 1. The origin of this software must not be misrepresented; you must not
 *    claim that you wrote the original software. If you use this software
 *    in a product, an acknowledgment in the product documentation would be
 *    appreciated but is not required.
 * 2. Altered source versions must be plainly marked as such, and must not be
 *    misrepresented as being the original software.
 * 3. This notice may not be removed or altered from any source distribution.
 */

/**
 * Narrow-phase collision.
 */
package com.bulletphysics.collision.narrowphase;

/*******************************************************************************************************
 *
 * SimplexSolverInterface.java, in simtools.gaml.extensions.physics, is part of the source code of the
 * GAMA modeling and simulation platform (v.1.9.3).
 *
 * (c) 2007-2023 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU)
 *
 * Visit https://github.com/gama-platform/gama for license information and contacts.
 *
 ********************************************************************************************************/

package com.bulletphysics.collision.narrowphase;

import javax.vecmath.Vector3f;

/**
 * SimplexSolverInterface can incrementally calculate distance between origin and
 * up to 4 vertices. Used by GJK or Linear Casting. Can be implemented by the
 * Johnson-algorithm or alternative approaches based on voronoi regions or barycentric
 * coordinates.
 *
 * @author jezek2
 */
public abstract class SimplexSolverInterface {

	/**
	 * Reset.
	 */
	public abstract void reset();

	/**
	 * Adds the vertex.
	 *
	 * @param w the w
	 * @param p the p
	 * @param q the q
	 */
	public abstract void addVertex(Vector3f w, Vector3f p, Vector3f q);

	/**
	 * Closest.
	 *
	 * @param v the v
	 * @return true, if successful
	 */
	public abstract boolean closest(Vector3f v);

	/**
	 * Max vertex.
	 *
	 * @return the float
	 */
	public abstract float maxVertex();

	/**
	 * Full simplex.
	 *
	 * @return true, if successful
	 */
	public abstract boolean fullSimplex();

	/**
	 * Gets the simplex.
	 *
	 * @param pBuf the buf
	 * @param qBuf the q buf
	 * @param yBuf the y buf
	 * @return the simplex
	 */
	public abstract int getSimplex(Vector3f[] pBuf, Vector3f[] q


k( "lead_neutral_creep_1", true )
		self:SetupStage2()
	elseif self.nCheckpoint == 3 then
		printf( "CHECKPOINT 3" )
		local bForceStart = true
		self:CheckpointSkipCompleteTask( "move_to_location_2", true, bForceStart )
		self:CheckpointSkipCompleteTask( "attack_neutral_creep_2", true )
		self:CheckpointSkipCompleteTask( "lead_neutral_creep_2", true )
		self:SetupStage3()
	end
end

--------------------------------------------------------------------

function CDotaNPXScenario_CreepPulling:OnHeroFinishSpawn( hHero, hPlayer )
	CDotaNPXScenario.OnHeroFinishSpawn( self, hHero, hPlayer )
	self.hHero = hHero
	self.hHero:SetAbilityPoints( 0 )

	if self.nCheckpoint == 0 then
		self:ShowWizardTip( "scenario_creep_pulling_wizard_tip_intro1", 5.0 )
		--self:BlockPlayer( true )
		self:ScheduleFunctionAtGameTime( GameRules:GetDOTATime( false, false ) + 5, function()
			self:ShowWizardTip( "scenario_creep_pulling_wizard_tip_intro2", 5.0 )
		end )
		self:ScheduleFunctionAtGameTime( GameRules:GetDOTATime( false, false ) + 10, function()
			self:SetupDemoGood()
		end )
	end
end

--------------------------------------------------------------------

function CDotaNPXScenario_CreepPulling:SetupDemoGood()
	--print("Setting up first Demo")
	self:SpawnDemoCreepWaves( 1 )
	--self:HintWorldText( self.hDemoHintLoc1:GetAbsOrigin(), "good", 89, -1 )
	self:ShowWizardTip( "scenario_creep_pulling_wizard_tip_intro_radiant", 10.0 )
	local hGoodLoc = Entities:FindByName( nil, "radiant_melee_spawner_good" )
	local vDemo1Pos = hGoodLoc:GetAbsOrigin()
	SendToConsole( "dota_camera_lerp_position " .. vDemo1Pos.x .. " " .. vDemo1Pos.y .. " " .. 1 )
	self:ScheduleFunctionAtGameTime( GameRules:GetDOTATime( false, false ) + 10, function()
		self:Fade( 1 )
		self:RemoveDemoCreepWaves()
		--self:EndHintWorldText( self.hDemoHintLoc1:GetAbsOrigin() )
		self:SetupDemoBad()
	end )
end

--------------------------------------------------------------------

function CDotaNPXScenario_CreepPulling:SetupDemoBad()
	--print("Setting up second Demo")
	self:Fade( 0 )
	self:SpawnDemoCreepWaves( 2 )
	--self:HintWorldText( self.hDemoHintLoc2:GetAbsOrigin(), "bad", 89, -1 )
	self:ShowWizardTip( "scenario_creep_pulling_wizard_tip_intro_dire", 10.0 )
	local hBadLoc = Entities:FindByName( nil, "radiant_melee_spawner_bad" )
	local vDemo2Pos = hBadLoc:GetAbsOrigin()
	SendToConsole( "dota_camera_lerp_position " .. vDemo2Pos.x .. " " .. vDemo2Pos.y .. " " .. 1 )
	self:ScheduleFunctionAtGameTime( GameRules:GetDOTATime( false, false ) + 10, function()
		local vPlayerStartLoc = self.hHeroSpawn:GetAbsOrigin()
		self:GetPlayerHero():Stop()
		FindClearSpaceForUnit( self:GetPlayerHero(), vPlayerStartLoc, true )
		SendToConsole( "dota_camera_lerp_position " .. vPlayerStartLoc.x .. " " .. vPlayerStartLoc.y .. " " .. 1 )
		self:RemoveDemoCreepWaves()
		--self:EndHintWorldText( self.hDemoHintLoc2:GetAbsOrigin()


.Compose(&localkm.T{T: memkm.T{Signer: &nonprod.Signer{Rand: testsign.RootRand()}}},
			memca.Create()),
	}
}

func localkmMemcaBootstrapped() *cmd.AppComponents {
	app := localkmMemca()
	app.Global = cmd.Compose(
		&localkm.T{T: memkm.T{Signer: &nonprod.Signer{Rand: testsign.RootRand()}}},
		memca.TestOnlyCertificateAuthority())
	return app
}

func TestEndorseRootCmd(t *testing.T) {
	outdir := t.TempDir()
	outdir2 := t.TempDir()
	simpleCmd(t, RootCmd, func(fwPath, certdir string) []string {
		keyDir := t.TempDir()
		if err := devkeys.DumpTo(&devkeys.Options{
			KeyDir:   keyDir,
			CertRoot: certdir,
			CertDir:  "signer_certs",
			Bucket:   "certs-dev",
		}); err != nil {
			t.Fatal(err)
		}
		return []string{"endorse", "--add_snp", "--uefi", fwPath, "--verbose",
			"--key_dir", keyDir,
			"--root_path", "root.crt",
			"--bucket_root", certdir,
			"--out_root", outdir,
			"--snapshot_dir", outdir2,
		}
	}, &wantEndorsement{
		endorsementPath: path.Join(outdir2, "fw.fd.signed"),
		clspec:          123,
	})
}

func TestEndorseLocalKeysMemca(t *testing.T) {
	outdir := t.TempDir()
	simple(t, memAppBootstrapped(), func(fwPath, certdir string) []string {
		keyDir := t.TempDir()
		if err := devkeys.DumpTo(&devkeys.Options{
			KeyDir:   keyDir,
			CertRoot: certdir,
			CertDir:  "certs",
			Bucket:   "testbucket",
		}); err != nil {
			t.Fatal(err)
		}
		return []string{"endorse", "--add_snp", "--uefi", fwPath, "--verbose", "--out_root", outdir}
	}, "")
}

// When the release branch already exists from a previous release candidate, there are some
// scenarios with existing files that need coverage.
func TestEndorseLocalKeysMemcaWithExistingBranch(t *testing.T) {
	legacyWant := &wantEndorsement{endorsementPath: "2023-09-26-T20-00-viperlite-npi-2-RC00.binarypb"}
	tcs := []struct {
		name         string
		initialFiles []*endorse.File
		extraArgs    []string
		wantErr      string
		wants        []wants
	}{
		{
			name:  "empty",
			wants: []wants{legacyWant},
		},
		{
			name: "manifest exists but irrelevant",
			initialFiles: []*endorse.File{
				{
					Path: "manifest.textproto",
					Contents: []byte(`
					# proto-file: github.com/google/gce-tcb-verifier/proto/releases.proto
					# proto-message: VMEndorsementMap
					# !!! THIS FILE WAS AUTOMATICALLY GENERATED !!!
					# !!! DO NOT MODIFY BY HAND !!!
					entries {
						digest: "nothindoin"
						path: "irrelevant.binarypb"
						create_time: {
							seconds: 5
							nanos: 100
						}
					}
`),
				},
			},
			wants: []wants{legacyWant},
		},
		{
			name:      "manifest exists with different path for digest",
			extraArgs: []string{"--timestamp=2023-11-10T16:13:00Z"},
			initialFiles: []*endorse.File{
				{
					Path: "


System Generated Value
	///
	/// OpcodeToken0:
	///
	/// [10:00] D3D10_SB_OPCODE_DCL_OUTPUT_SGV
	/// [23:11] Ignored, 0
	/// [30:24] Instruction length in DWORDs including the opcode token.
	/// [31]    0 normally. 1 if extended operand definition, meaning next DWORD
	///         contains extended operand description.  This dcl is currently not
	///         extended.
	///
	/// OpcodeToken0 is followed by 2 operands:
	/// (1) an operand, starting with OperandToken0, defining which
	///     o# register (D3D10_SB_OPERAND_TYPE_OUTPUT) is being declared,
	///     including writemask.
	/// (2) a System Generated Name token (NameToken)
	/// </summary>
	public class OutputRegisterDeclarationToken : DeclarationToken
	{
		/// <summary>
		/// Only applicable for SGV and SIV declarations.
		/// </summary>
		public SystemValueName SystemValueName { get; internal set; }

		public static OutputRegisterDeclarationToken Parse(BytecodeReader reader)
		{
			uint token0 = reader.ReadUInt32();
			var opcodeType = token0.DecodeValue<OpcodeType>(0, 10);

			var result = new OutputRegisterDeclarationToken
			{
				Operand = Operand.Parse(reader, opcodeType)
			};

			switch (opcodeType)
			{
				case OpcodeType.DclOutputSgv:
				case OpcodeType.DclOutputSiv:
					result.SystemValueName = NameToken.Parse(reader);
					break;
			}

			return result;
		}

		public override string ToString()
		{
			string result = string.Format("{0} {1}", TypeDescription, Operand);

			if (Header.OpcodeType == OpcodeType.DclOutputSgv || Header.OpcodeType == OpcodeType.DclOutputSiv)
				result += ", " + SystemValueName.GetDescription();

			return result;
		}
	}
}


equest that impact the content of this's body.
     */
    fun Response.varyHeaders(): Headers {
      // Use the request headers sent over the network, since that's what the response varies on.
      // Otherwise OkHttp-supplied headers like "Accept-Encoding: gzip" may be lost.
      val requestHeaders = networkResponse!!.request.headers
      val responseHeaders = headers
      return varyHeaders(requestHeaders, responseHeaders)
    }

    /**
     * Returns the subset of the headers in [requestHeaders] that impact the content of the
     * response's body.
     */
    private fun varyHeaders(
      requestHeaders: Headers,
      responseHeaders: Headers,
    ): Headers {
      val varyFields = responseHeaders.varyFields()
      if (varyFields.isEmpty()) return Headers.EMPTY

      val result = Headers.Builder()
      for (i in 0 until requestHeaders.size) {
        val fieldName = requestHeaders.name(i)
        if (fieldName in varyFields) {
          result.add(fieldName, requestHeaders.value(i))
        }
      }
      return result.build()
    }
  }
}
/*
 * Copyright (C) 2014 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package okhttp3.internal.ws

import okio.Buffer
import okio.ByteString.Companion.encodeUtf8

object WebSocketProtocol {
  /** Magic value which must be appended to the key in a response header. */
  internal const val ACCEPT_MAGIC = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

  /*
  Each frame starts with two bytes of data.

   0 1 2 3 4 5 6 7    0 1 2 3 4 5 6 7
  +-+-+-+-+-------+  +-+-------------+
  |F|R|R|R| OP    |  |M| LENGTH      |
  |I|S|S|S| CODE  |  |A|             |
  |N|V|V|V|       |  |S|             |
  | |1|2|3|       |  |K|             |
  +-+-+-+-+-------+  +-+-------------+
   */

  /** Byte 0 flag for whether this is the final fragment in a message. */
  internal const val B0_FLAG_FIN = 128

  /** Byte 0 reserved flag 1. Must be 0 unless negotiated otherwise. */
  internal const val B0_FLAG_RSV1 = 64

  /** Byte 0 reserved flag 2. Must be 0 unless negotiated otherwise. */
  internal const val B0_FLAG_RSV2 = 32

  /** Byte 0 reserved flag 3. Must be 0 unless negotiated otherwise. */
  internal const val B0_FLAG_RSV3 = 16

  /** Byte 0 mask for the frame opcode. */
  internal const val B0_MASK_OPCODE = 15

  /** Flag in the opcode which indicates a control frame. */
  internal const val OPCODE_FLAG_CONTROL = 8

  /**
   * Byte 1 flag for whether the payload data is masked.
   *
   * If this flag is set, the next four
   * bytes represent the mask key. These bytes appear after any additional bytes specified by [B1_MASK_LENGTH].
   */
  internal const val B1_FLAG_MASK = 128

  /**
   * Byte 1 mask for the payload length.
   *
   * If this value is [PAYLOAD_SHORT], the next two
   * bytes represent the length. If this value is [PAYLOAD_LONG], the next eight bytes
   * represent the length.
   */
  internal const val B1_MASK_LENGTH = 127

  internal const val OPCODE_CONTINUATION = 0x0
  internal const val OPCODE_TEXT = 0x1


fact(num);
    let s = Selector::new(num as usize);

    let max_v: Mutex<u64> = Mutex::new(0);
    let best = (0..cmb).into_par_iter().
        map(|i| s.select(i)).fold(|| 0,|max,(v,ap)| {
            let sum = min_brk(0, v, ap).unwrap();
            if sum >= max {
                {
                    let mut mv = max_v.lock().unwrap();
                    if sum >= *mv {
                        println!("{} {} (atomic: {:?})", sum, v, ap);
                        *mv = sum;
                    }
                    *mv // Return mutex protected max value
                }
            } else {
                max
            }}).
        reduce(|| 0, |p: u64, n: u64|  p.max(n) );

    println!("best: {:?}", best);
}
<filename>src/solution/y2021/d22.rs
use crate::error::*;

use std::ops::Range;

use nom::
{
	character::complete::*,
	number::complete::*,
	bytes::complete::*,
	combinator::*,
	sequence::*,
	branch::*,
	multi::*,
	IResult,
	Parser,
};

#[derive(Debug,Eq,PartialEq)]
enum Part
{
	Part1,
	Part2,
}

/// # Examples
///
/// ```
/// # use adventofcode::solution::{ y2021::d22::Solution, Solution as S };
/// # env_logger::init();
/// let input = "on x=10..12,y=10..12,z=10..12\n\
///     on x=11..13,y=11..13,z=11..13\n\
///     off x=9..11,y=9..11,z=9..11\n\
///     on x=10..10,y=10..10,z=10..10\n";
/// assert_eq!(Solution::part1(input.to_string()).solve().unwrap(), "39");
/// let input = "on x=-20..26,y=-36..17,z=-47..7\n\
///     on x=-20..33,y=-21..23,z=-26..28\n\
///     on x=-22..28,y=-29..23,z=-38..16\n\
///     on x=-46..7,y=-6..46,z=-50..-1\n\
///     on x=-49..1,y=-3..46,z=-24..28\n\
///     on x=2..47,y=-22..22,z=-23..27\n\
///     on x=-27..23,y=-28..26,z=-21..29\n\
///     on x=-39..5,y=-6..47,z=-3..44\n\
///     on x=-30..21,y=-8..43,z=-13..34\n\
///     on x=-22..26,y=-27..20,z=-29..19\n\
///     off x=-48..-32,y=26..41,z=-47..-37\n\
///     on x=-12..35,y=6..50,z=-50..-2\n\
///     off x=-48..-32,y=-32..-16,z=-15..-5\n\
///     on x=-18..26,y=-33..15,z=-7..46\n\
///     off x=-40..-22,y=-38..-28,z=23..41\n\
///     on x=-16..35,y=-41..10,z=-47..6\n\
///     off x=-32..-23,y=11..30,z=-14..3\n\
///     on x=-49..-5,y=-3..45,z=-29..18\n\
///     off x=18..30,y=-20..-8,z=-3..13\n\
///     on x=-41..9,y=-7..43,z=-33..15\n\
///     on x=-54112..-39298,y=-85059..-49293,z=-27449..7877\n\
///     on x=967..23432,y=45373..81175,z=27513..53682\n";
/// let input = "on x=-5..47,y=-31..22,z=-19..33\n\
///     on x=-44..5,y=-27..21,z=-14..35\n\
///     on x=-49..-1,y=-11..42,z=-10..38\n\
///     on x=-20


58e742ada458e8a98e5ad44.jpeg?

odnHeight=180&odnWidth=180&odnBg=FFFFFF","largeImage":"https:

//i5.walmartimages.com/asr/95c06e89-7222-4057-94c5-

776d8b88d847_1.7eff452cf58e742ada458e8a98e5ad44.jpeg?

odnHeight=450&odnWidth=450&odnBg=FFFFFF","productTrackingUrl"

:"http://linksynergy.walmart.com/fs-bin/click?id=|LSNID|

&offerid=223073.7200&type=14&catid=8&subid=0&hid=7200&tmpid=1

082&RD_PARM1=https%253A%252F%252Fwww.walmart.com%252Fip

%252FApple-iPod-touch-5th-Generation-Space-Gray-and-Silver

%252F25174174%253Faffp1%253DkZWWK28HYe3THWF5eR0beb_mHYxjnc-

b3TOUal__uQ0%2526affilsrc

%253Dapi","standardShipRate":0.0,"marketplace":false,"modelNu

mber":"iPod

Touch","productUrl":"http://c.affil.walmart.com/t/api02?

l=https%3A%2F%2Fwww.walmart.com%2Fip%2FApple-iPod-touch-5th-

Generation-Space-Gray-and-Silver

%2F25174174%3Faffp1%3DkZWWK28HYe3THWF5eR0beb_mHYxjnc-

b3TOUal__uQ0%26affilsrc%3Dapi%26veh%3Daff%26wmlspartner

%3Dreadonlyapi","customerRating":"3.824","numReviews":238,"cu

stomerRatingImage":"http://i2.walmartimages.com/i/CustRating/

3_8.gif","categoryNode":"3944_96469_1231508","bundle":false,"

stock":"Available","addToCartUrl":"http://c.affil.walmart.com

/t/api02?l=http%3A%2F%2Faffil.walmart.com%2Fcart%2FaddToCart

%3Fitems

%3D25174174%7C1%26affp1%3DkZWWK28HYe3THWF5eR0beb_mHYxjnc-

b3TOUal__uQ0%26affilsrc%3Dapi%26veh%3Daff%26wmlspartner

%3Dreadonlyapi","affiliateAddToCartUrl":"http://linksynergy.w

almart.com/fs-bin/click?id=|LSNID|

&offerid=223073.7200&type=14&catid=8&subid=0&hid=7200&tmpid=1

082&RD_PARM1=http%253A%252F%252Faffil.walmart.com%252Fcart

%252FaddToCart%253Fitems

%253D25174174%257C1%2526affp1%253DkZWWK28HYe3THWF5eR0beb_mHYx

jnc-b3TOUal__uQ0%2526affilsrc%253Dapi","giftOptions":

{"allowGiftWrap":false,"allowGiftMessage":false,"allowGiftRec

eipt":false},"imageEntities":

[{"thumbnailImage":"https://i5.walmartimages.com/asr/5190b388

-1327-4a5a-a4bf-

dafabe4147da_1.f02dcfd5fda302bd5a664fa40bf34af1.jpeg?

odnHeight=100&odnWidth=100&odnBg=FFFFFF","mediumImage":"https

://i5.walmartimages.com/as


"ro"
			]
		}
	],
	"linux": {
		"resources": {
			"devices": [
				{
					"allow": false,
					"access": "rwm"
				}
			]
		},
		"namespaces": [
			{
				"type": "pid"
			},
			{
				"type": "network"
			},
			{
				"type": "ipc"
			},
			{
				"type": "uts"
			},
			{
				"type": "mount"
			}
		],
		"maskedPaths": [
			"/proc/acpi",
			"/proc/asound",
			"/proc/kcore",
			"/proc/keys",
			"/proc/latency_stats",
			"/proc/timer_list",
			"/proc/timer_stats",
			"/proc/sched_debug",
			"/sys/firmware",
			"/proc/scsi"
		],
		"readonlyPaths": [
			"/proc/bus",
			"/proc/fs",
			"/proc/irq",
			"/proc/sys",
			"/proc/sysrq-trigger"
		]
	}
}"#;

pub fn run(_opts: Spec, logger: &Logger) -> Result<()> {
    // TODO: liboci-cli does not support --bundle option for spec command.
    // After liboci-cli supports the option, we will　change the following code.
    // let config_path = get_config_path(&opts.bundle);
    let config_path = Path::new(".").join(CONFIG_FILE_NAME);
    let config_data = DEFAULT_SPEC;

    let mut file = File::create(config_path)?;
    file.write_all(config_data.as_bytes())?;

    info!(&logger, "spec command finished successfully");

    Ok(())
}

#[derive(Debug)]
pub struct Keypad {
    pub keys: [bool; 16],
}

impl Keypad {
    pub fn new() -> Self {
        Self {
            keys: [false; 16]
        }

    }

    pub fn set(&mut self, index: u8, down: bool) {
        self.keys[index as usize] = down;
    }

    pub fn is_key_down(&self, index: u8) -> bool {
        self.keys[index as usize]
    }

    pub fn get_pressed_key(&self) -> Option<u8> {
        for i in 0..self.keys.len() {
            if self.is_key_down(i as u8) {
                return Some(i as u8);
            }
        }
        None
    }
}
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use leggevm::{compile, vm, LogLevel, Timing};

pub fn compare(c: &mut Criterion) {
    c.bench_function("reference", |b| {
        b.iter(|| {
            fn add(i: isize) -> isize {
                let mut val = 0;
                if i >= 0 {
                    val = black_box(i + val + add(i - 1));
                }
                return val;
            }
            let n = 10000;
            let res = add(n);
            assert_eq!(res * 2, n * (n + 1))
        });
    });

    let mut timing = Timing::default();
    let runtime = vm::Runtime::default();
    let (bytecode, _) = compile(
        &mut timing,
        &runtime,
        LogLevel::LogNone,
        "
            import assert;
            add :: fn(i: int) -> int {
              val := 0;
              if (i >= 0) {
                val = i + val + add(i-1);
              }
              return val;
            }
            n :: 10000;
            res :: add(n);

            assert(res*2, n*(n+1));
        "
        .into(),
    )
    .unwrap();

    c.bench_function("interpreter", |b| {
        b.iter(|| {
            let mut interp = vm::Interpreter::new(&runtime, LogLevel::LogNone, &|_| {});
            interp.run(&bytecode);
        });
    });
}

criterion_group!(b


h, pos));

        let nf = prf_nf(&nk, &mp);

        let nftest: [u8; 32] = [
            0x4a, 0xb5, 0x57, 0x93, 0x33, 0x81, 0xd9, 0xb0, 0xa2, 0x6a, 0x10, 0xc9, 0x66, 0xdb,
            0x62, 0x4a, 0x18, 0xc5, 0xf4, 0xa5, 0xe5, 0x0c, 0x93, 0x8f, 0x2f, 0x24, 0x11, 0x19,
            0x88, 0x5e, 0x39, 0xb1,
        ];
        assert_eq!(nf, nftest);
    }

    #[test]
    fn test_mixed_pedersen() {
        let v = 312354353;
        let h = mixed_pedersen(ExtendedPoint::identity(), v);
        let a = extended_to_bytes(&h);
        assert_eq!(
            a,
            [
                229, 21, 27, 49, 9, 57, 15, 12, 130, 17, 72, 150, 250, 83, 173, 10, 32, 188, 132,
                68, 124, 203, 153, 66, 197, 109, 156, 189, 116, 231, 80, 75
            ]
        );
    }

    #[test]
    fn test_note_commitment_null() {
        let rcm: [u8; 32] = [
            0x6e, 0xbb, 0xed, 0x74, 0x36, 0x19, 0xa2, 0x56, 0xf9, 0xad, 0x2e, 0x85, 0x88, 0x0c,
            0xfa, 0xa9, 0x09, 0x8a, 0x5f, 0xdb, 0x16, 0x29, 0x99, 0x0d, 0x9a, 0x7d, 0x3b, 0xb9,
            0x3f, 0xc9, 0x00, 0x03,
        ];
        let g_d = [0u8; 32];
        let pk_d = [0u8; 32];
        let value: u64 = 0;

        let cmnul = [
            0x0d, 0x7d, 0xfe, 0x59, 0x28, 0xee, 0x5d, 0x23, 0xbc, 0x93, 0x85, 0x9b, 0xb9, 0x93,
            0x5a, 0x23, 0xe7, 0xa9, 0x9d, 0xda, 0xf9, 0xd0, 0x97, 0x3d, 0x1d, 0xd1, 0x9e, 0xff,
            0xed, 0x3f, 0x29, 0x13,
        ];

        let t = note_commitment(value, &g_d, &pk_d, &rcm);
        let b = AffinePoint::from(&t).get_u().to_bytes();
        assert_eq!(b, cmnul);
    }

    #[test]
    fn test_note_commitment() {
        let rcm: [u8; 32] = [
            0x6e, 0xbb, 0xed, 0x74, 0x36, 0x19, 0xa2, 0x56, 0xf9, 0xad, 0x2e, 0x85, 0x88, 0x0c,
            0xfa, 0xa9, 0x09, 0x8a, 0x5f, 0xdb, 0x16, 0x29, 0x99, 0x0d, 0x9a, 0x7d, 0x3b, 0xb9,
            0x3f, 0xc9, 0x00, 0x03,
        ];


1]
          vpunpckhwd (%rcx), %zmm26, %zmm30

// CHECK: vpunpckhwd 291(%rax,%r14,8), %zmm26, %zmm30
// CHECK:  encoding: [0x62,0x21,0x2d,0x40,0x69,0xb4,0xf0,0x23,0x01,0x00,0x00]
          vpunpckhwd 291(%rax,%r14,8), %zmm26, %zmm30

// CHECK: vpunpckhwd 8128(%rdx), %zmm26, %zmm30
// CHECK:  encoding: [0x62,0x61,0x2d,0x40,0x69,0x72,0x7f]
          vpunpckhwd 8128(%rdx), %zmm26, %zmm30

// CHECK: vpunpckhwd 8192(%rdx), %zmm26, %zmm30
// CHECK:  encoding: [0x62,0x61,0x2d,0x40,0x69,0xb2,0x00,0x20,0x00,0x00]
          vpunpckhwd 8192(%rdx), %zmm26, %zmm30

// CHECK: vpunpckhwd -8192(%rdx), %zmm26, %zmm30
// CHECK:  encoding: [0x62,0x61,0x2d,0x40,0x69,0x72,0x80]
          vpunpckhwd -8192(%rdx), %zmm26, %zmm30

// CHECK: vpunpckhwd -8256(%rdx), %zmm26, %zmm30
// CHECK:  encoding: [0x62,0x61,0x2d,0x40,0x69,0xb2,0xc0,0xdf,0xff,0xff]
          vpunpckhwd -8256(%rdx), %zmm26, %zmm30

// CHECK: vpextrb $171, %xmm17, %eax
// CHECK:  encoding: [0x62,0xe3,0x7d,0x08,0x14,0xc8,0xab]
          vpextrb $171, %xmm17, %eax

// CHECK: vpextrb $123, %xmm17, %eax
// CHECK:  encoding: [0x62,0xe3,0x7d,0x08,0x14,0xc8,0x7b]
          vpextrb $123, %xmm17, %eax

// CHECK: vpextrb $123, %xmm17, %r8d
// CHECK:  encoding: [0x62,0xc3,0x7d,0x08,0x14,0xc8,0x7b]
          vpextrb $123, %xmm17,%r8d

// CHECK: vpextrb $123, %xmm17, (%rcx)
// CHECK:  encoding: [0x62,0xe3,0x7d,0x08,0x14,0x09,0x7b]
          vpextrb $123, %xmm17, (%rcx)

// CHECK: vpextrb $123, %xmm17, 291(%rax,%r14,8)
// CHECK:  encoding: [0x62,0xa3,0x7d,0x08,0x14,0x8c,0xf0,0x23,0x01,0x00,0x00,0x7b]
          vpextrb $123, %xmm17, 291(%rax,%r14,8)

// CHECK: vpextrb $123, %xmm17, 127(%rdx)
// CHECK:  encoding: [0x62,0xe3,0x7d,0x08,0x14,0x4a,0x7f,0x7b]
          vpextrb $123, %xmm17, 127(%rdx)

// CHECK: vpext


	cmp x0, x1
	b.ne .L_loop

	ADR_REL x0, __bss_start
	ADR_REL x1, __bss_end_executive

.L_bss_init_loop:
	cmp x0, x1
	b.eq .L_prepare_rust
	stp xzr, xzr, [x0], 0x10
	b .L_bss_init_loop

.L_prepare_rust:
  ADR_REL x0, __boot_core_stack_end_executive
	mov sp, x0
	b _start_rust

.L_loop:
	wfe
	b .L_loop

.size _start, . - _start
.type _start, function
.global _start

adr_dtb: .quad


Cell::new();
    let mut vl = NcCell::new();
    if unsafe {
        crate::nccells_rounded_box(
            plane,
            stylemask as u32,
            channels,
            &mut ul,
            &mut ur,
            &mut ll,
            &mut lr,
            &mut hl,
            &mut vl,
        )
    } != NCRESULT_OK
    {
        return NCRESULT_ERR;
    }
    let ret = ncplane_box_sized(
        plane,
        &ul,
        &ur,
        &ll,
        &lr,
        &hl,
        &vl,
        dimy as NcDim,
        dimx as NcDim,
        boxmask,
    );
    unsafe {
        nccell_release(plane, &mut ul);
        nccell_release(plane, &mut ur);
        nccell_release(plane, &mut ll);
        nccell_release(plane, &mut lr);
        nccell_release(plane, &mut hl);
        nccell_release(plane, &mut vl);
    }
    ret
}

// box -------------------------------------------------------------------------

/// Draws a box with its upper-left corner at the current cursor position,
/// having dimensions `y_len` * `x_len`.
///
/// The minimum box size is 2x2, and it cannot be drawn off-screen.
///
/// See [ncplane_box()](crate::ncplane_box) for more information.
///
/// *Method: NcPlane.[box_sized()][NcPlane#method.box_sized].*
#[inline]
pub fn ncplane_box_sized(
    plane: &mut NcPlane,
    ul: &NcCell,
    ur: &NcCell,
    ll: &NcCell,
    lr: &NcCell,
    hline: &NcCell,
    vline: &NcCell,
    y_len: NcDim,
    x_len: NcDim,
    boxmask: NcBoxMask,
) -> NcIntResult {
    let (mut y, mut x) = (0, 0);
    unsafe {
        crate::ncplane_cursor_yx(plane, &mut y, &mut x);
        crate::ncplane_box(
            plane,
            ul,
            ur,
            ll,
            lr,
            hline,
            vline,
            y + y_len as i32 - 1,
            x + x_len as i32 - 1,
            boxmask,
        )
    }
}

///
///
/// *Method: NcPlane.[double_box()][NcPlane#method.double_box].*
#[inline]
pub fn ncplane_double_box(
    plane: &mut NcPlane,
    stylemask: NcStyle,
    channels: NcChannels,
    y_stop: NcDim,
    x_stop: NcDim,
    boxmask: NcBoxMask,
) -> NcIntResult {
    #[allow(unused_assignments)]
    let mut ret = NCRESULT_OK;

    let mut ul = NcCell::new();
    let mut ur = NcCell::new();
    let mut ll = NcCell::new();
    let mut lr = NcCell::new();
    let mut hl = NcCell::new();
    let mut vl = NcCell::new();

    unsafe {
        ret = crate::nccells_double_box(
            plane,
            stylemask as u32,
            channels,
            &mut ul,
            &mut ur,
            &mut ll,
            &mut lr,
            &mut hl,
            &mut vl,
        );
        if ret == NCRESULT_OK {
            ret = crate::ncplane_box(
                plane,
                &ul,
                &ur,
                &ll,
                &lr,


	assert.Equal(t, credential.ClientSecret, "FAKE-SECRET")
	})

	t.Run("should return error when credentials not supported even if legacy configuration present", func(t *testing.T) {
		var data = map[string]interface{}{
			"azureCredentials": map[string]interface{}{
				"authType":   "invalid",
				"azureCloud": "AzureChinaCloud",
				"tenantId":   "TENANT-ID",
				"clientId":   "CLIENT-TD",
			},
			"azureCloud":    "azuremonitor",
			"tenantId":      "LEGACY-TENANT-ID",
			"clientId":      "LEGACY-CLIENT-ID",
			"onBehalfOf":    true,
			"oauthPassThru": true,
		}
		var secureData = map[string]string{
			"azureClientSecret": "FAKE-SECRET",
			"clientSecret":      "FAKE-LEGACY-SECRET",
		}

		_, err := FromDatasourceData(data, secureData)
		assert.Error(t, err)
	})
}

func TestNormalizeAzureCloud(t *testing.T) {
	t.Run("should return normalized cloud name", func(t *testing.T) {
		tests := []struct {
			description     string
			legacyCloud     string
			normalizedCloud string
		}{
			{
				legacyCloud:     azureMonitorPublic,
				normalizedCloud: azsettings.AzurePublic,
			},
			{
				legacyCloud:     azureMonitorChina,
				normalizedCloud: azsettings.AzureChina,
			},
			{
				legacyCloud:     azureMonitorUSGovernment,
				normalizedCloud: azsettings.AzureUSGovernment,
			},
			{
				legacyCloud:     "",
				normalizedCloud: azsettings.AzurePublic,
			},
		}

		for _, tt := range tests {
			t.Run(tt.description, func(t *testing.T) {
				actualCloud, err := resolveLegacyCloudName(tt.legacyCloud)
				require.NoError(t, err)

				assert.Equal(t, tt.normalizedCloud, actualCloud)
			})
		}
	})

	t.Run("should fail when cloud is unknown", func(t *testing.T) {
		legacyCloud := "unknown"

		_, err := resolveLegacyCloudName(legacyCloud)
		assert.Error(t, err)
	})
}
package config

import (
	"flag"
	"testing"
)

func TestStringSliceFlag_Set(t *testing.T) {
	tests := map[string]struct {
		values []string
		exp    int
	}{
		"empty": {
			values: []string{},
			exp:    0,
		},
		"single": {
			values: []string{"-test", "test1"},
			exp:    1,
		},
		"multiple": {
			values: []string{"-test", "test1", "-test", "test2"},
			exp:    2,
		},
	}

	for name, test := range tests {
		t.Run(name, func(t *testing.T) {
			var ssf StringSliceFlag
			fs := flag.NewFlagSet("test", flag.ContinueOnError)
			fs.Var(&ssf, "test", "test")
			if err := fs.Parse(test.values); err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if exp, got := test.exp, len(ssf); exp != got {
				t.Fatalf("expected %d, got %d", exp, got)
			}
		})
	}
}

func TestStringSliceFlag_String(t *testing.T) {
	tests := map[string]struct {
		values []string
		exp    string
	}{
		"empty": {
			values: []string{},
			exp:    "",
		}, "single": {
			values: []string{"test1"},
			exp:    "test1",
		}, "multiple": {


28621.75000000",
            //         "A": "2.52500800"
            //     }
            //
            if (event === undefined && ('a' in message) && ('b' in message)) {
                this.handleBidsAsks(client, message);
            }
        }
        else {
            method.call(this, client, message);
        }
    }
}
CKEDITOR.plugins.setLang("wsc","gl",{btnIgnore:"Ignorar",btnIgnoreAll:"Ignorar Todas",btnReplace:"Substituir",btnReplaceAll:"Substituir Todas",btnUndo:"Desfacer",changeTo:"Cambiar a",errorLoading:"Error loading application service host: %s.",ieSpellDownload:"O corrector ortográfico non está instalado. ¿Quere descargalo agora?",manyChanges:"Corrección ortográfica rematada: %1 verbas substituidas",noChanges:"Corrección ortográfica rematada: Non se substituiu nengunha verba",noMispell:"Corrección ortográfica rematada: Non se atoparon erros",
noSuggestions:"- Sen candidatos -",notAvailable:"Sorry, but service is unavailable now.",notInDic:"Non está no diccionario",oneChange:"Corrección ortográfica rematada: Unha verba substituida",progress:"Corrección ortográfica en progreso...",title:"Spell Checker",toolbar:"Corrección Ortográfica"});CKEDITOR.plugins.setLang("wsc","da",{btnIgnore:"Ignorér",btnIgnoreAll:"Ignorér alle",btnReplace:"Erstat",btnReplaceAll:"Erstat alle",btnUndo:"Tilbage",changeTo:"Forslag",errorLoading:"Fejl ved indlæsning af host: %s.",ieSpellDownload:"Stavekontrol ikke installeret. Vil du installere den nu?",manyChanges:"Stavekontrol færdig: %1 ord ændret",noChanges:"Stavekontrol færdig: Ingen ord ændret",noMispell:"Stavekontrol færdig: Ingen fejl fundet",noSuggestions:"(ingen forslag)",notAvailable:"Stavekontrol er desværre ikke tilgængelig.",
notInDic:"Ikke i ordbogen",oneChange:"Stavekontrol færdig: Et ord ændret",progress:"Stavekontrollen arbejder...",title:"Stavekontrol",toolbar:"Stavekontrol"});CKEDITOR.plugins.setLang("wsc","et",{btnIgnore:"Ignoreeri",btnIgnoreAll:"Ignoreeri kõiki",btnReplace:"Asenda",btnReplaceAll:"Asenda kõik",btnUndo:"Võta tagasi",changeTo:"Muuda",errorLoading:"Viga rakenduse teenushosti laadimisel: %s.",ieSpellDownload:"Õigekirja kontrollija ei ole paigaldatud. Soovid sa selle alla laadida?",manyChanges:"Õigekirja kontroll sooritatud: %1 sõna muudetud",noChanges:"Õigekirja kontroll sooritatud: ühtegi sõna ei muudetud",noMispell:"Õigekirja kontroll sooritatud: õigekirjuvigu ei leitud",
noSuggestions:"- Soovitused puuduvad -",notAvailable:"Kahjuks ei ole teenus praegu saadaval.",notInDic:"Puudub sõnastikust",oneChange:"Õigekirja kontroll sooritatud: üks sõna muudeti",progress:"Toimub õigekirja kontroll...",title:"Õigekirjakontroll",toolbar:"Õigekirjakontroll"});// ----------------------------------------------------------------------------

// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
// EDIT THE CORRESPONDENT .ts FILE INSTEAD

import { bytes as assertBytes } from './_as


body, "Hello, World!");
}

async fn handler(ConnectInfo(info): ConnectInfo<UdsConnectInfo>) -> &'static str {
    println!("new connection from `{:?}`", info);

    "Hello, World!"
}

struct ServerAccept {
    uds: UnixListener,
}

impl Accept for ServerAccept {
    type Conn = UnixStream;
    type Error = BoxError;

    fn poll_accept(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
        let (stream, _addr) = ready!(self.uds.poll_accept(cx))?;
        Poll::Ready(Some(Ok(stream)))
    }
}

struct ClientConnection {
    stream: UnixStream,
}

impl AsyncWrite for ClientConnection {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, io::Error>> {
        Pin::new(&mut self.stream).poll_write(cx, buf)
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
        Pin::new(&mut self.stream).poll_flush(cx)
    }

    fn poll_shutdown(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<(), io::Error>> {
        Pin::new(&mut self.stream).poll_shutdown(cx)
    }
}

impl AsyncRead for ClientConnection {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        Pin::new(&mut self.stream).poll_read(cx, buf)
    }
}

impl Connection for ClientConnection {
    fn connected(&self) -> Connected {
        Connected::new()
    }
}

#[derive(Clone, Debug)]
struct UdsConnectInfo {
    peer_addr: Arc<tokio::net::unix::SocketAddr>,
    peer_cred: UCred,
}

impl connect_info::Connected<&UnixStream> for UdsConnectInfo {
    type ConnectInfo = Self;

    fn connect_info(target: &UnixStream) -> Self::ConnectInfo {
        let peer_addr = target.peer_addr().unwrap();
        let peer_cred = target.peer_cred().unwrap();

        Self {
            peer_addr: Arc::new(peer_addr),
            peer_cred,
        }
    }
}
<reponame>Proful/youtube-snippets
#![allow(warnings)] // NOT RECOMMENDED

fn main() {
    let age: u8 = "34".parse().unwrap();
    let age = "24".parse::<i32>().unwrap();

    let x = 5;

    let y = {
        let z = 3;
        x + z // try after adding ;
    };

    dbg!(y);

    let age = 30;

    if age >= 21 {
        println!("You can buy a drink!");
    } else {
        println!("You can't buy a drink!");
    }

    let is_of_age = {
        if age >= 21 {
            true
        } else {
            false
        }
    };
    dbg!(is_of_age);

    let mut count = 0;

    loop {
        count += 1;

        if count == 5 {
            continue;
        }

        //dbg!(count);

        if count == 10 {
            break;
        }
    }
    dbg!(count);

    let mut count = 0;

    let result = loop {
        count += 1;

        if count == 10 {
            break count * 5;
        }
    };
    dbg!(result);

    'outer: loop {
        println!("outer loop");


st rootNode = new TestSyncedFrameNode(rootSyncedFrame);

      rootNode.outerGaps = 20;

      expect(rootNode.isFrameDirty()).toBeTruthy();
    });

    it('should not mark dirty if value is the same', async () => {
      const rootFrameRect = <Frame>{ x: 0, y: 0, width: 100, height: 100 };
      const rootSyncedFrame = new SyncedFrame(rootFrameRect);
      const rootNode = new TestSyncedFrameNode(rootSyncedFrame);

      rootNode.outerGaps = 20;
      rootNode.clean();
      rootNode.outerGaps = 20;

      expect(rootNode.isFrameDirty()).toBeFalsy();
    });

    it('should set a padded frame to node\'s SyncedFrame', async () => {
      const rootFrameRect = <Frame>{ x: 0, y: 0, width: 100, height: 100 };
      const rootSyncedFrame = new SyncedFrame(rootFrameRect);
      const rootNode = new TestSyncedFrameNode(rootSyncedFrame);

      rootNode.outerGaps = 20;
      await rootNode.clean();

      const expectedRect = <Frame>{ x: 20, y: 20, width: 60, height: 60 };
      expect(rootSyncedFrame.get()).toEqual(expectedRect);
    });

    it('should not alter the node\'s frame', async () => {
      const rootFrameRect = <Frame>{ x: 0, y: 0, width: 100, height: 100 };
      const rootSyncedFrame = new SyncedFrame(rootFrameRect);
      const rootNode = new TestSyncedFrameNode(rootSyncedFrame);

      rootNode.outerGaps = 20;
      await rootNode.clean();

      expect(rootNode.getFrame()).toEqual(rootFrameRect);
    });

    it('should preserve outerGaps after frame change', async () => {
      const rootFrameRect = <Frame>{ x: 0, y: 0, width: 100, height: 100 };
      const rootSyncedFrame = new SyncedFrame(rootFrameRect);
      const rootNode = new TestSyncedFrameNode(rootSyncedFrame);

      rootNode.outerGaps = 20;
      await rootNode.clean();

      const nextFrameRect = <Frame>{ x: 50, y: 50, width: 150, height: 150 };
      await rootNode.setFrame(nextFrameRect);

      const expectedRect = <Frame>{ x: 70, y: 70, width: 110, height: 110 };
      expect(rootSyncedFrame.get()).toEqual(expectedRect);
    });
  });
});
export function isFunction(value: any): value is (...args: any[]) => any {
  return typeof value === "function";
}
export function arrRemove<T>(arr: T[] | undefined | null, item: T) {
  if (arr) {
    const index = arr.indexOf(item);
    0 <= index && arr.splice(index, 1);
  }
}
export class Persona {
    nombre: String;
    apellido: String;
    cedula: String;
    direccion: String;
    creado: Date;
    constructor(nombre, apellido, cedula, direccion){
        this.nombre = nombre;
        this.apellido = apellido;
        this.cedula = cedula;
        this.direccion = direccion;
        this.creado = new Date(Date.now());
    }
}/// <reference path="../../../../../typings/tsd.d.ts" />

import {Component, View, NgFor, NgZone} from 'angular2/angular2';
import {ChampionService} from 'app/services/ChampionService';

@Component({
    selector: 'champions',
    viewInjector: [ChampionService]
})
@View({
    templateUrl: 'app/components/champions/champions.html',
    directives: [NgFor]
})

export class Champions {
    champions: Array<Object>;
    championSvc: ChampionService;
    zone: NgZone;

    constructor(championSvc: ChampionService, zone: NgZone) {
        this.champ


mpose.runtime.Composable
import androidx.compose.ui.platform.LocalContext

private val DarkColorScheme = darkColorScheme(
    primary = Purple80,
    secondary = PurpleGrey80,
    tertiary = Pink80
)

private val LightColorScheme = lightColorScheme(
    primary = Purple40,
    secondary = PurpleGrey40,
    tertiary = Pink40

    /* Other default colors to override
    background = Color(0xFFFFFBFE),
    surface = Color(0xFFFFFBFE),
    onPrimary = Color.White,
    onSecondary = Color.White,
    onTertiary = Color.White,
    onBackground = Color(0xFF1C1B1F),
    onSurface = Color(0xFF1C1B1F),
    */
)

@Composable
fun HabitGameNativeTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    // Dynamic color is available on Android 12+
    dynamicColor: Boolean = true,
    content: @Composable () -> Unit
) {
    val colorScheme = when {
        dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
            val context = LocalContext.current
            if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
        }

        darkTheme -> DarkColorScheme
        else -> LightColorScheme
    }

    MaterialTheme(
        colorScheme = colorScheme,
        typography = Typography,
        content = content
    )
}/*
 *  Copyright (c) 2024 Ben Wicks <benjaminlwicks@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.ichi2.anki.api

/*
 * [value] should be kept in sync with the [com.ichi2.anki.Ease] enum.
 *
 * param value The so called value of the button. For the sake of consistency with upstream and our API
 * the buttons are numbered from 1 to 4.
 */
public enum class Ease(
    public val value: Int,
) {
    EASE_1(1),
    EASE_2(2),
    EASE_3(3),
    EASE_4(4),
}
plugins {
    id("com.android.application")
}

android {
    namespace = "com.example.skyjoproject"
    compileSdk = 34

    defaultConfig {
        applicationId = "com.example.skyjoproject"
        minSdk = 26
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation("androidx.appcompat:appcompat:1.6.1")
    implementation("com.google.android.material:material:1.10.0")
    implementation("androidx.constraintlayout:constraintlayout:2.1.4")
    testImplementation("junit:junit:4.13.2")
    androidTestImplementation("androidx.test.ext:junit:1.1.5")
    androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
}package com.test.fore


x01AA($s0)           ## 000001AA
/* 004E4 80B89254 18400002 */  blez    $v0, .L80B89260
/* 004E8 80B89258 244EFFFF */  addiu   $t6, $v0, 0xFFFF           ## $t6 = FFFFFFFF
/* 004EC 80B8925C A60E01AA */  sh      $t6, 0x01AA($s0)           ## 000001AA
.L80B89260:
/* 004F0 80B89260 8FBF0024 */  lw      $ra, 0x0024($sp)
.L80B89264:
/* 004F4 80B89264 8FB00020 */  lw      $s0, 0x0020($sp)
/* 004F8 80B89268 27BD0048 */  addiu   $sp, $sp, 0x0048           ## $sp = 00000000
/* 004FC 80B8926C 03E00008 */  jr      $ra
/* 00500 80B89270 00000000 */  nop


更加流畅：“尽管他们不太热衷于参与，但是我相信他们会喜欢这个活动。”                                                                             |
| 对比                   | 比较并解释云存储和物理存储的优缺点。                                                                                |
| 建议                    | 假设你知道某人正在寻找新工作，请给他们三个建议以帮助他们成功地申请求职。                                                                           |
| 解释                    | 什么是深度学习？它有什么应用？                                                                                |
| 翻译                    | 把这个句子翻译成法语：“明天我要去看望我的祖母。”                                                                                |
| 表格数据提取      | 从以下表格中提取2019年第四季度公司B的盈利：（表格需要自行生成）                                                                                |
| 咨询                    | 如果我想开始一个餐厅生意，你能告诉我该从哪里开始吗？                                                                                |
| 推理                    | 给定以下信息，贵公司2022年的年终奖金会是多少？
员工年薪：10万
公司每年发放的总年终奖池：100万（分配给所有员工）
员工评级：A级（年终奖金为年薪的2倍）|
| 分类任务 | 如何识别垃圾邮件？ |
| 生成任务 | 写一篇科技新闻报道。 |
| 编辑任务 | 将这篇文章中的语法错误修正一下。 |
| 推理任务 | 如果明天下雪，我需要穿什么衣服出门？ |
| 摘要任务 | 对这篇长篇小说进行摘要，不超过150字。|
| 翻译任务 | 将这篇新闻翻译成英文。 |
| 对话任务 | 你认为明年会涨房价吗？ |
| 判断任务 | 你认为在未


 // leftmost element is considered smallest
        assert!(c3 < c4);

        assert_eq!(c1, choice!(0 <- "a"));
        assert_eq!(c2, choice!(0 <- "b"));
        assert_eq!(c3, choice!(1 <- 'a'));
        assert_eq!(c4, choice!(1 <- 'b'));

        // Elements with unmatched positions are never equal, even if the values are equal.
        let c1: choice![char, char] = choice!(0 <- 'a');
        let c2: choice![char, char] = choice!(1 <- 'a');
        assert_ne!(c1, c2);
    }

    #[test]
    fn can_debug() {
        let c1: choice![&'static str, char] = choice!(0 <- "a");
        let c2: choice![&'static str, char] = choice!(1 <- 'b');
        assert_eq!(format!("{:?}", c1), "\"a\"");
        assert_eq!(format!("{:?}", c2), "'b'");
    }

    #[test]
    fn can_display() {
        let c1: choice![&'static str, char] = choice!(0 <- "a");
        let c2: choice![&'static str, char] = choice!(1 <- 'b');
        assert_eq!(format!("{}", c1), "a");
        assert_eq!(format!("{}", c2), "b");
    }

    #[test]
    fn can_destructure() {
        let c1: choice![&'static str, char] = choice!(0 <- "a");
        if let choice!(0 -> v) = c1 {
            assert_eq!(v, "a");
        } else {
            panic!("Expected match.");
        }
        if let choice!(1 -> _v) = c1 {
            panic!("Unexpected match.");
        }

        let c2: choice![&'static str, char] = choice!(1 <- 'b');
        match c2 {
            choice!(0 -> _v) => {
                panic!("Unexpected match.");
            }
            choice!(1 -> v) => {
                assert_eq!(v, 'b');
            }
            choice!(2 -> !) => {
                unreachable!();
            }
        }
    }

    #[test]
    fn smoke_test() {
        let choices: Vec<choice![u8, char, &'static str, String]> = vec![
            choice!(0 <- 1),
            choice!(1 <- '2'),
            choice!(2 <- "3"),
            choice!(3 <- "4".to_string()),
        ];
        assert_eq!(
            format!("{:?}", choices),
            r#"[1, '2', "3", "4"]"#);
        assert_eq!(choices, vec![
            Choice::new(1),
            Choice::new('2').or(),
            Choice::new("3").or().or(),
            Choice::new("4".to_string()).or().or().or(),
        ]);
        assert_ne!(choices, vec![
            choice!(0 <- 1),
            choice!(1 <- '2'),
            choice!(2 <- "three"),
            choice!(3 <- "4".to_string()),
        ]);

        #[derive(Debug, Eq, PartialEq)] struct A;
        #[derive(Debug, Eq, PartialEq)] struct B;
        #[derive(Debug, Eq, PartialEq)] struct C;
        #[derive(Debug, Eq, PartialEq)] struct D;
        #[derive(Debug, Eq, PartialEq)] struct E;
        #[derive(Debug, Eq, PartialEq)] struct F;
        #[derive(Debug, Eq, PartialEq)] struct G;
        #[derive(Debug, Eq, PartialEq)] struct H;
        #[derive(Debug, Eq, PartialEq)] struct I;
        #[derive(Debug, Eq, PartialEq)] struct J;
        #[derive(Debug, Eq, PartialEq)] struct K;
        #[derive(Debug, Eq, PartialEq)] struct L;
        let v: Vec<choice![A, B, C, D, E, F, G, H, I, J, K, L]> = vec![
            choice!(0 <- A),
            choice!(1 <- B),
            choice!(2 <- C),
            choice!(3 <- D),
            choice!(4 <- E),
            choice!(5 <- F),
            choice!


e = "short_url" ;
        DataSource datasource = DatabaseUtil.getDatasource(LeafSegmentTest.username, password, url, driver.getName());

        // 创建 provider 发号器
        LeafSegmentProvider provider = new LeafSegmentProvider(bizType, datasource);

        // 生产号段
        Long nextId = provider.getNextId(provider.tinyIdConfig().getBizType());

        System.out.println(nextId);

    }

    // 循环获取 id 号
    @Test
    public void getNextIdListTest(){

        // 环境准备
        String bizType = "short_url" ;
        DataSource datasource = DatabaseUtil.getDatasource(LeafSegmentTest.username, password, url, driver.getName());

        // 创建 provider 发号器
        LeafSegmentProvider provider = new LeafSegmentProvider(bizType, datasource);

        // 生产号段
        for (int i = 0; i < 20000; i++) {
            Long nextId = provider.getNextId(null);
            System.out.println(nextId);
        }

    }

    // 测试批量获取 id 号
    @Test
    public void getNextIdBatchTest(){

        // 环境准备
        String bizType = "short_url" ;
        DataSource datasource = DatabaseUtil.getDatasource(LeafSegmentTest.username, password, url, driver.getName());

        // 创建 provider 发号器
        LeafSegmentProvider provider = new LeafSegmentProvider(bizType, datasource);

        List<Long> ids = provider.getNextIdByBatch(32100);

        // 保存环境
        provider.saveContext();

        System.out.println(ids);

    }

    /**
     * @methodName :providerTest
     * @author : HK意境
     * @date : 2022/5/31 19:53
     * @description : 百万 id 号获取
     * @Todo :
     * @params :
         * @param : null
     * @return : null
     * @throws:
     * @Bug :
     * @Modified :
     * @Version : 1.0.0
     */
    @Test
    public void providerTest(){

        // 环境准备
        String bizType = "short_url" ;
        DataSource datasource = DatabaseUtil.getDatasource(LeafSegmentTest.username, password, url, driver.getName());

        // 创建 provider 发号器
        LeafSegmentProvider provider = new LeafSegmentProvider(bizType, datasource);

        ArrayList<String> list = new ArrayList<>();
        long s = System.currentTimeMillis();

        for (int i = 0; i < 1000; i++) {
            list.add(provider.provideShortUrl(null));
        }
        long e = System.currentTimeMillis();
        System.out.println(list);

        log.info("开始时间:{}",s);
        log.info("结束时间:{}",e );
        log.info("时长:{}",(double)(e-s)/1000);
    }

}
package com.hkh.ai.chain.llm.capabilities.generation;

import cn.hutool.http.HttpUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hkh.ai.domain.AccessToken;
import com.hkh.ai.service.AccessTokenService;
import jakarta.xml.bind.DatatypeConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation


If the Euler process converged sufficiently according to \`TARGET_CONSECUTIVE_CONVERGED\`:\\n        if consecutive_converged_count >= TARGET_CONSECUTIVE_CONVERGED:\\n            # Error is estimated by the last difference or the requested tolerances.\\n            euler_error_component = max(last_diff_euler, \\n                                 EULER_REL_TOL * abs(final_answer), \\n                                 EULER_ABS_TOL, MIN_ERROR_FLOOR) \\n        else:\\n            # If Euler did not meet the strict convergence criteria, provide a more\\n            # conservative (larger) error estimate based on the tail of the original series\\n            # combined with relaxed tolerances.\\n            conservative_raw_tail_error = np.sum(np.abs(segment_integrals[max(0, N_segments - min(15, N_segments)):]))\\n            \\n            euler_error_component = max(conservative_raw_tail_error,\\n                                        abs(final_answer) * EULER_REL_TOL * 5, # 5x less strict relative tolerance.\\n                                        EULER_ABS_TOL * 5, # 5x less strict absolute tolerance.\\n                                        MIN_ERROR_FLOOR)\\n    else: \\n        # If Euler transformation couldn't produce enough diagonal values for robust error estimation,\\n        # fall back to a conservative estimate based on the raw segment sums.\\n        # This is the most conservative fallback for the Euler part of the error.\\n        euler_error_component = np.sum(np.abs(segment_integrals[max(0, N_segments - min(15, N_segments)):]))\\n        euler_error_component = max(euler_error_component, \\n                               abs(initial_sum_segments) * EULER_REL_TOL * 10, \\n                               EULER_ABS_TOL * 10, MIN_ERROR_FLOOR)\\n\\n    # Combine the two main error sources (quad integration errors and Euler series truncation error) in quadrature.\\n    final_error_estimate = math.sqrt(euler_error_component**2 + total_quad_error_sq)\\n    final_error_estimate = max(final_error_estimate, MIN_ERROR_FLOOR) # Ensure a minimum error floor.\\n\\n    # Final checks for NaN/Inf results before returning the final answer.\\n    if np.isnan(final_answer) or np.isinf(final_answer):\\n        return np.nan, np.inf\\n\\n    # Ensure error_estimate is not NaN or Inf.\\n    if np.isnan(final_error_estimate) or np.isinf(final_error_estimate):\\n        return final_answer, np.inf # If error itself becomes problematic, return inf error.\\n\\n    return final_answer, final_error_estimate",
  "new_index": 989,
  "new_code": "# TODO: Implement the \`quadrature()\` function to numerically evaluate integrals.\\n\\nimport math\\nfrom typing import Any, Callable, Tuple\\nimport numpy as np\\nimport scipy.integrate\\nimport scipy.optimize\\n\\n# Define constants outside the function for clarity and potential reusability\\n# These are tuned for performance and robustness on oscillatory integrals.\\nDEFAULT_QUAD_LIMIT = 2000000\\nDEFAULT_QUAD_EPSABS = 1e-13\\nDEFAULT_QUAD_EPSREL = 1e-13\\n\\n# Euler acceleration parameters\\nMIN_SEGMENTS_FOR_EULER = 30 # Minimum terms to consider Euler acceleration.\\nTARGET_CONSECUTIVE_CONVERGED = 15 # Number of consecutive stable Euler estimates for confident convergence.\\nEULER_ABS_TOL = 1e-10 # Absolute tolerance for Euler convergence.\\nEULER_REL_TOL = 1e-8 # Relative tolerance for Euler convergence.\\nSEGMENT_INTEGRATION_TOL = 1e-8 # Tolerance for individual segment integrations.\\n\\n# Heuristic thresholds for stopping segment collection early (Euler suitability checks).\\n# Adjusted to be relative to MIN_SEGMENTS_FOR_EULER


0);
 *   };
 * }
 *
 * // Initialize the sketch.
 * new p5(sketch);
 *
 *

 */
export default p5;
/**
 * @module Rendering
 * @submodule Rendering
 * @for p5
 */

import p5 from './main';
import * as constants from './constants';

/**
 * A class to describe a drawing surface that's separate from the main canvas.
 *
 * Each `p5.Graphics` object provides a dedicated drawing surface called a
 * *graphics buffer*. Graphics buffers are helpful when drawing should happen
 * offscreen. For example, separate scenes can be drawn offscreen and
 * displayed only when needed.
 *
 * `p5.Graphics` objects have nearly all the drawing features of the main
 * canvas. For example, calling the method `myGraphics.circle(50, 50, 20)`
 * draws to the graphics buffer. The resulting image can be displayed on the
 * main canvas by passing the `p5.Graphics` object to the
 * image() function, as in `image(myGraphics, 0, 0)`.
 *
 * Note: createGraphics() is the recommended
 * way to create an instance of this class.
 *
 * @class p5.Graphics
 * @constructor
 * @extends p5.Element
 * @param {Number} width width of the graphics buffer in pixels.
 * @param {Number} height height of the graphics buffer in pixels.
 * @param {Constant} renderer renderer to use, either P2D or WEBGL.
 * @param {p5} [pInst] sketch instance.
 * @param {HTMLCanvasElement} [canvas] existing `<canvas>` element to use.
 *
 * @example
 *

 *
 * let pg;
 *
 * function setup() {
 *   createCanvas(100, 100);
 *
 *   // Create a p5.Graphics object.
 *   pg = createGraphics(50, 50);
 *
 *   // Draw to the p5.Graphics object.
 *   pg.background(100);
 *   pg.circle(25, 25, 20);
 *
 *   describe('A dark gray square with a white circle at its center drawn on a gray background.');
 * }
 *
 * function draw() {
 *   background(200);
 *
 *   // Display the p5.Graphics object.
 *   image(pg, 25, 25);
 * }
 *
 *

 *
 *

 *
 * // Click the canvas to display the graphics buffer.
 *
 * let pg;
 *
 * function setup() {
 *   createCanvas(100, 100);
 *
 *   // Create a p5.Graphics object.
 *   pg = createGraphics(50, 50);
 *
 *   describe('A square appears on a gray background when the user presses the mouse. The square cycles between white and black.');
 * }
 *
 * function draw() {
 *   background(200);
 *
 *   // Calculate the background color.
 *   let bg = frameCount % 255;
 *
 *   // Draw to the p5.Graphics object.
 *   pg.background(bg);
 *
 *   // Display the p5.Graphics object while
 *   // the user presses the mouse.
 *   if (mouseIsPressed === true) {
 *     image(pg, 25, 25);
 *   }
 * }
 *
 *

 */
p5.Graphics = class extends p5.Element {
  constructor(w, h, renderer, pInst, canvas) {
    let canvasTemp;
    if (canvas) {
      canvasTemp = canvas;
    } else {
      canvasTemp = document.createElement('canvas');
    }

    super(canvasTemp, pInst);
    this.canvas = canvasTemp;

    const r = renderer || constants.P2D;

    const node = pInst._userNode || document.body;
    if (!canvas) {
      node.appendChild(this.canvas);
    }


"
	"os"
	"path/filepath"
	"strconv"

	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/klog"

	cloudprovider "k8s.io/cloud-provider"
)

// OutSideCluster allows the controller to be started using a local kubeConfig for testing
var OutSideCluster bool

const (
	// ProviderName is the name of the cloud provider
	ProviderName = "kubevip"

	// KubeVipClientConfig is the default name of the load balancer config Map
	KubeVipClientConfig = "kubevip"

	// KubeVipClientConfigNamespace is the default namespace of the load balancer config Map
	KubeVipClientConfigNamespace = "kube-system"

	// KubeVipServicesKey is the key in the ConfigMap that has the services configuration
	KubeVipServicesKey = "kubevip-services"

	// CustomLoadbalancerClassEnvKey environment key for custom loadbalancerclass name.
	// A LoadbalancerClass could be set in service.spec.loadbalancerclass.
	// If the service has this value, then service controller will reconcile the service.
	CustomLoadbalancerClassEnvKey = "KUBEVIP_CUSTOM_LOADBALANCERCLASS_NAME"

	// DefaultLoadbalancerClass is the default loadbalancerClass name if no custom loadbalancerClass name is
	// supplied by CustomLoadbalancerClassEnvKey
	DefaultLoadbalancerClass = "kube-vip.io/kube-vip-class"

	// EnableLoadbalancerClassEnvKey environment key for enabling loadbalancerclass.
	// This should be enabled if CustomLoadbalancerClassNameEnvKey is not empty
	EnableLoadbalancerClassEnvKey = "KUBEVIP_ENABLE_LOADBALANCERCLASS"
)

func init() {
	cloudprovider.RegisterCloudProvider(ProviderName, newKubeVipCloudProvider)
}

// KubeVipCloudProvider - contains all of the interfaces for the cloud provider
type KubeVipCloudProvider struct {
	lb            cloudprovider.LoadBalancer
	kubeClient    kubernetes.Interface
	namespace     string
	configMapName string
	enableLBClass bool
	lbClass       string
}

var _ cloudprovider.Interface = &KubeVipCloudProvider{}

func newKubeVipCloudProvider(io.Reader) (cloudprovider.Interface, error) {
	ns := os.Getenv("KUBEVIP_NAMESPACE")
	cm := os.Getenv("KUBEVIP_CONFIG_MAP")
	lbc := os.Getenv(EnableLoadbalancerClassEnvKey)
	cbc := os.Getenv(CustomLoadbalancerClassEnvKey)

	if cm == "" {
		cm = KubeVipClientConfig
	}

	if ns == "" {
		ns = KubeVipClientConfigNamespace
	}

	var (
		enableLBClass bool
		lbClass       string
		err           error
	)

	if len(lbc) > 0 {
		klog.Infof("Checking if loadbalancerClass is enabled: %s", lbc)
		enableLBClass, err = strconv.ParseBool(lbc)
		if err != nil {
			return nil, fmt.Errorf("error parsing value of %s: %s", EnableLoadbalancerClassEnvKey, err.Error())
		}
	}
	klog.Infof("starting with enable loadbalancerClass flag set to: %t", enableLBClass)

	lbClass = DefaultLoadbalancerClass
	if cbc != "" {
		lbClass = cbc
	}
	klog.Infof("loadbalancerClass value set to: %s", lbClass)

	klog.Infof("Watching configMap for pool config with name: '%s', namespace: '%s'", cm, ns)

	var cl *kubernetes.Clientset
	if !OutSideCluster {
		// This will attempt t


addLine("([name] == thresher || [name] == crypticaxe || [name] == greatpoleaxe || [name] == giantthresher) && [flag] == ethereal && [quality] == normal # [sockets] == 0 # [maxquantity] == 1");
    }
    NTIP.addLine("([name] == thresher || [name] == crypticaxe || [name] == greatpoleaxe || [name] == giantthresher) && [flag] == ethereal && [quality] >= normal && [quality] <= superior # [sockets] == 5 # [maxquantity] == 1");
  } else {
    NTIP.addLine("([name] == thresher || [name] == crypticaxe || [name] == greatpoleaxe || [name] == giantthresher) && [flag] == ethereal && [quality] == superior # [enhanceddamage] >= 10 && [sockets] == 5 # [maxquantity] == 1");
  }
  // Cube to Cham
  const needCham = function () {
    return !me.getItem(sdk.items.runes.Cham);
  };
  if (!me.getItem(sdk.items.runes.Cham)) {
    Config.Recipes.push([Recipe.Rune, "Ist Rune", { condition: needCham }]);
    Config.Recipes.push([Recipe.Rune, "Gul Rune", { condition: needCham }]);
    Config.Recipes.push([Recipe.Rune, "Vex Rune", { condition: needCham }]);
    Config.Recipes.push([Recipe.Rune, "Ohm Rune", { condition: needCham }]);
    Config.Recipes.push([Recipe.Rune, "Lo Rune", { condition: needCham }]);
    if ((me.barbarian && me.haveAll([{ name: sdk.locale.items.Grief }, { name: sdk.locale.items.Fortitude }]))
      || (["Witchyzon", "Wfzon"].includes(SetUp.finalBuild) && me.checkItem({ name: sdk.locale.items.ChainsofHonor }).have)
      || (SetUp.currentBuild === "Faithbowzon")) {
      Config.Recipes.push([Recipe.Rune, "Sur Rune", { condition: needCham }]);
    }
    Config.Recipes.push([Recipe.Rune, "Ber Rune", { condition: needCham }]);
    Config.Recipes.push([Recipe.Rune, "Jah Rune", { condition: needCham }]);
    Config.Recipes.push([Recipe.Rune, "Cham Rune", { condition: needCham }]);
  }

  // Cube to Lo
  const needLo = function () {
    return !me.getItem(sdk.items.runes.Lo);
  };
  if (needLo()) {
    if (me.barbarian
      || (SetUp.currentBuild === "Faithbowzon" && me.checkItem({ name: sdk.locale.items.CalltoArms }).have)
      || (["Witchyzon", "Wfzon"].includes(SetUp.finalBuild)
      && me.haveAll([{ name: sdk.locale.items.ChainsofHonor }, { name: sdk.locale.items.CalltoArms }]))) {
      Config.Recipes.push([Recipe.Rune, "Ist Rune", { condition: needLo }]);
      Config.Recipes.push([Recipe.Rune, "Gul Rune", { condition: needLo }]);
      Config.Recipes.push([Recipe.Rune, "Vex Rune", { condition: needLo }]);
      Config.Recipes.push([Recipe.Rune, "Ohm Rune", { condition: needLo }]);
      Config.Recipes.push([Recipe.Rune, "Lo Rune", { condition: needLo }]);
    }
  }

  // Cube to


*/
        /*
         * within polar circle we swap AC/DC if AC is on wrong side
         */
        acmc = sl.swe_difdeg2n(hsp.ac, hsp.mc);
        if (acmc < 0) {
          hsp.ac = sl.swe_degnorm(hsp.ac + 180);
        }
        /* A0. Start point - ecliptic coords of ascendant */
        x[0] = hsp.ac; /* Asc longitude   */
        x[1] = 0.0;     /* Asc declination */
        x[2] = 1.0;     /* Radius to test validity of subsequent transformations. */
        sl.swe_cotrans(x, x, -ekl);      /* A1. Transform into equatorial coords */
        x[0] = x[0] - (th-90);        /* A2. Rotate                           */
        sl.swe_cotrans(x, x, -(90-fi));  /* A3. Transform into horizontal coords */
        krHorizonLon = x[0];          /* ...save asc lon on horizon to get back later with house cusp */
        x[0] = x[0] - x[0];           /* A4. Rotate                           */
        sl.swe_cotrans(x, x, -90);       /* A5. Transform into this house system great circle (asc-zenith) */
        /* As it is house circle now, simple add 30 deg increments... */
        for(i = 0; i < 6; i++) {
          /* B0. Set 'n-th' house cusp.
           *     Note that IC/MC are also calculated here to check
           *     if really this is the asc-zenith great circle. */
          x[0] = 30.0*i;
          x[1] = 0.0;
          sl.swe_cotrans(x, x, 90);                 /* B1. Transform back into horizontal coords */
          x[0] = x[0] + krHorizonLon;            /* B2. Rotate back.                          */
          sl.swe_cotrans(x, x, 90-fi);              /* B3. Transform back into equatorial coords */
          x[0] = sl.swe_degnorm(x[0] + (th-90));    /* B4. Rotate back -> RA of house cusp as result. */
          /* B5. Where's this house cusp on ecliptic? */
          /* ... so last but not least - get ecliptic longitude of house cusp: */
          hsp.cusp[i+1] = atand(tand(x[0])/cosd(ekl));
          if (x[0] > 90 && x[0] <= 270)
            hsp.cusp[i+1] = sl.swe_degnorm(hsp.cusp[i+1] + 180);
          hsp.cusp[i+1] = sl.swe_degnorm(hsp.cusp[i+1]);
          hsp.cusp[i+7] = sl.swe_degnorm(hsp.cusp[i+1]+180);
        }
        break;
      case 'Y':     /* APC houses */
        for (i = 1; i <= 12; i++) {
          hsp.cusp[i] = apc_sector(i, fi * SwissData.DEGTORAD, ekl * SwissData.DEGTORAD, th * SwissData.DEGTORAD);
        }
        hsp.ac = hsp.cusp[1];
        hsp.mc = hsp.cusp[10];
        /* within polar circle, when mc sinks below horizon and
         * ascendant changes to western hemisphere, all cusps
         * must be added 180 degrees.
         * houses will be in clockwise direction */
        if (SMath.abs(fi) >= 90 - ekl) {  /* within polar circle */
          acmc = sl.swe_difdeg2n(hsp.ac, hsp.mc);


;
  tql::on_buf_changed = &on_buf_changed;
  tql::unload_on_drv_shutdown = &unload_on_drv_shutdown;
  texmgr_internal::always_release_threshold_tex_size_kb = b.getInt("alwaysReleaseThresholdTexSizeKB", -1);
  if (!b.getBool("alwaysRelease", false))
    texmgr_internal::should_release_tex = &should_release_tex;
  else if (texmgr_internal::always_release_threshold_tex_size_kb > 0)
    texmgr_internal::should_release_tex = &always_release_tex_above_threshold_size;
  texmgr_internal::stop_bkg_tex_loading = &do_stop_bkg_tex_loading;
  mem_quota_reserve_kb = READ_PROP(Int, "quotaReserveMB", mem_quota_reserve_kb >> 10) << 10;
  sys_mem_usage_thres_mb = READ_PROP(Int, "sysMemUsageThresholdMB", sys_mem_usage_thres_mb);
  sys_mem_add_free_mb = READ_PROP(Int, "sysMemAddFreeMB", sys_mem_add_free_mb);
  texmgr_internal::enable_cur_ql_mismatch_assert = b.getBool("enableCurQLMismatchAssert", true);
#if _TARGET_PC_WIN
  MEMORYSTATUSEX msx;
  msx.dwLength = sizeof(msx);
  if (GlobalMemoryStatusEx(&msx))
  {
    debug("avail virt=%dM phys=%dM", msx.ullAvailVirtual >> 20, msx.ullAvailPhys >> 20);
    int64_t max_phys_mb = msx.ullAvailPhys >> 20;
    int64_t max_virt_mb = msx.ullAvailVirtual >> 20;
    if (max_phys_mb > 144)
      max_phys_mb -= 144;
    if (max_virt_mb > 304)
      max_virt_mb -= 304;
    if (sys_mem_usage_thres_mb > max_virt_mb)
      sys_mem_usage_thres_mb = (int)max_virt_mb;
    if (sys_mem_usage_thres_mb > max_phys_mb)
      sys_mem_usage_thres_mb = (int)max_phys_mb;
    debug("maxVirt=%dM maxPhys=%dM -> max=%dM", max_virt_mb, max_phys_mb, sys_mem_usage_thres_mb);
    int allow_up_sysmem_to_physmem_avail_percent = READ_PROP(Int, "useSysMemUptoPhysMemPercent", 60);
    int allowed_max_mem = int(min(max_phys_mb, max_virt_mb) * allow_up_sysmem_to_physmem_avail_percent / 100);
    if (sys_mem_usage_thres_mb && sys_mem_usage_thres_mb < allowed_max_mem)
    {
      sys_mem_usage_thres_mb = allowed_max_mem;
      debug("using sysMemThres=%dM due to useSysMemUptoPhysMemPercent=%d%% and phys=%dM", sys_mem_usage_thres_mb,
        allow_up_sysmem_to_physmem_avail_percent, min<int>(max_phys_mb, max_virt_mb));
    }
  }
#endif

  tql::streaming_enabled = true;
  debug("texture streaming enabled: reload_jobmgr=%d, mem_quota_reserve_kb=%dM (sysMemThres=%dM +%dM)", reload_jobmgr_id,
    mem_quota_reserve_kb >> 10, sys_mem_usage_thres_mb, sys_mem_add_free_mb);

  if (sys_mem_usage_thres_mb)
    dgs_on_out_of_memory = texql_try_unload_tex_on_oom;

  if (const char *tq = b.get


e used to
// conveniently allocate a shared_ptr to an object whose destructor will be run
// without the GIL.  Pass it as the second argument to shared_ptr, e.g.,
//
//    shared_ptr<T>(new T(), destroy_without_gil<T>)
//
// Attaching the GIL release logic to the holder pointer rather than the
// actual destructor of T is helpful when T is Python-agnostic and
// shouldn't refer to the PYthon API.
//
// Note there are limitations to the correctness of code that makes use of this.
// In particular, if a shared_ptr is constructed from C++ code without this
// destructor and then passed to pybind11, pybind11 will happily take ownership
// of the shared_ptr (and be willing to destruct it from a context where it is
// holding the GIL).  unique_ptr with a type branded deleter is less prone to
// this problem, because a stock deleter unique_ptr is not convertible with it.
// I plan to mitigate this problem by adding DEBUG-only asserts to the true C++
// destructors that the GIL is not held (using a virtual call to get to the
// Python interpreter); alternately, we could use a virtual call to simply
// ensure we release the GIL in the C++ destructor, however, this is a layering
// violation (why does code that is ostensibly Python agnostic calling into the
// GIL).
//
// Adapted from
// https://github.com/pybind/pybind11/issues/1446#issuecomment-406341510
template <typename T>
inline void destroy_without_gil(T* ptr) {
  // Because the ownership of a shared_ptr is diffuse, it's not possible to
  // necessarily predict whether or not the last reference to an object will
  // be destructed from Python or C++.  This means that in the destructor here,
  // we don't necessarily know if we actually have the GIL or not; in fact,
  // we don't even know if the Python interpreter still exists!  Thus, we have
  // to test for it before releasing the GIL.
  //
  // PyGILState_Check is hopefully self explanatory.  But Py_IsInitialized or
  // _PyIsFinalizing?  Both get set at the same time during the Python
  // destruction process:
  // https://github.com/python/cpython/blob/d92513390a1a0da781bb08c284136f4d7abea36d/Python/pylifecycle.c#L1716-L1717
  // so the operant question is whether or not you want to release the GIL after
  // finalization has completed (and there is just no Python interpreter).
  // Clearly there is no need to release GIL in that state, so we want
  // Py_IsInitialized.
  if (Py_IsInitialized() && PyGILState_Check()) {
    pybind11::gil_scoped_release nogil;
    delete ptr;
  } else {
    delete ptr;
  }
}

} // namespace torch::impl


elta).isEqualTo(delta)
  }

  @Test
  @TestParameters(
    "{initialEpsilon: 2.0, delta: 0.5, factor: 0.5, calculatedWeight: 1.0, calculatedDelta: 0.25}",
    "{initialEpsilon: 2.0, delta: 0.5, factor: 1, calculatedWeight: 2.0, calculatedDelta: 0.5}",
  )
  fun times_validInput_hasCorrectCalculation(
    initialEpsilon: Double,
    delta: Double,
    factor: Double,
    calculatedWeight: Double,
    calculatedDelta: Double,
  ) {
    assertThat(AbsoluteBudgetPerOpSpec(initialEpsilon, delta).times(factor))
      .isEqualTo(AbsoluteBudgetPerOpSpec(calculatedWeight, calculatedDelta))
  }

  @Test
  fun times_invalidCalculatedWeight_throws() {
    assertFailsWith<IllegalArgumentException> { AbsoluteBudgetPerOpSpec(1.0, 0.5).times(-1.0) }
  }
}
/*
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.privacy.differentialprivacy.pipelinedp4j.core.budget

import org.junit.runner.RunWith
import org.junit.runners.Suite

/** Provides a list of JUnit test classes to Bazel. When creating a new test class, add it here. */
@RunWith(Suite::class)
@Suite.SuiteClasses(
  AbsoluteBudgetPerOpSpecTest::class,
  NaiveBudgetAccountantTest::class,
  RelativeBudgetPerOpSpecTest::class,
  TotalBudgetTest::class,
)
class BudgetTests {}
/*
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.privacy.differentialprivacy.pipelinedp4j.api

import java.io.Serializable

@ConsistentCopyVisibility
data class ColumnNames internal constructor(internal val names: List<String>) : Serializable {
  constructor(vararg names: String) : this(names.toList())
}

/**
 * Type of List implementation where column values of the same row will be stored.
 *
 * It is important for list comparisons (e.g. in "group by" operations) to have the same
 * implementations of the list. It is not enough that these lists have the same elements in the same
 * order (i.e. l1.equals(l2)). This is because keys (which are lists in our case) in join/group by
 * operations are compared just as a sequence of bytes and different list implementations have
 * different serialized representation even if they are equal.
 */
internal typealias ColumnValuesListImplementation<T> = ArrayList<T>
/*
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at