和顺 返回模型广场

源码片段索引

片段来自固定提交的标注行段。接口用法以对应 Skill 页面为准。

196 个片段

Alertmanager

Apache-2.0。 项目仓库 · 许可入口

Alertmanager · func (d *Dispatcher) Run(

dispatch/dispatch.go · 202–215 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func (d *Dispatcher) Run(dispatchStartTime time.Time) {
	if !d.state.CompareAndSwap(DispatcherStateUnknown, DispatcherStateWaitingToStart) {
		return
	}
	d.finished.Add(1)
	defer d.finished.Done()

	d.logger.Debug("preparing to start", "startTime", dispatchStartTime)
	d.startTimer = time.NewTimer(time.Until(dispatchStartTime))
	d.logger.Debug("setting state", "state", "waiting_to_start")
	d.aggrGroupsNum.Store(0)
	d.metrics.aggrGroups.Set(0)

	initalAlerts, it := d.alerts.SlurpAndSubscribe("dispatcher")
  • // Copyright The Prometheus Authors

Alertmanager · func (rs RoutingStage) Exec(

notify/notify.go · 279–292 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func (rs RoutingStage) Exec(ctx context.Context, l *slog.Logger, alerts ...*alert.Alert) (context.Context, []*alert.Alert, error) {
	receiver, ok := ReceiverName(ctx)
	if !ok {
		return ctx, nil, errors.New("receiver missing")
	}

	ctx, span := tracer.StartRoutingStage(ctx, receiver, len(alerts))
	defer span.End()

	s, ok := rs[receiver]
	if !ok {
		return ctx, nil, errors.New("stage for receiver missing")
	}
  • // Copyright The Prometheus Authors

Alertmanager · func (s *Silences) Set(

silence/silence.go · 205–218 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func (s *Silences) Set(ctx context.Context, sil *pb.Silence) error {
	_, span := tracer.Start(ctx, "silences.Set")
	defer span.End()

	now := s.nowUTC()
	if sil.StartsAt == nil || sil.StartsAt.AsTime().IsZero() {
		sil.StartsAt = timestamppb.New(now)
	}

	if err := validateSilence(sil); err != nil {
		return fmt.Errorf("invalid silence: %w", err)
	}

	s.mtx.Lock()
  • // Copyright The Prometheus Authors

Alphalens

Apache-2.0。 项目仓库 · 许可入口

Alphalens · def get_clean_factor_and_forward_returns(

alphalens/utils.py · 666–679 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def get_clean_factor_and_forward_returns(factor,
                                         prices,
                                         groupby=None,
                                         binning_by_group=False,
                                         quantiles=5,
                                         bins=None,
                                         periods=(1, 5, 10),
                                         filter_zscore=20,
                                         groupby_labels=None,
                                         max_loss=0.35,
                                         zero_aware=False,
                                         cumulative_returns=True):
    """
    Formats the factor data, pricing data, and group mappings into a DataFrame
  • # Copyright 2018 Quantopian, Inc.

Alphalens · def factor_information_coefficient(

alphalens/performance.py · 28–41 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def factor_information_coefficient(factor_data,
                                   group_adjust=False,
                                   by_group=False):
    """
    Computes the Spearman Rank Correlation based Information Coefficient (IC)
    between factor values and N period forward returns for each period in
    the factor index.

    Parameters
    ----------
    factor_data : pd.DataFrame - MultiIndex
        A MultiIndex DataFrame indexed by date (level 0) and asset (level 1),
        containing the values for a single alpha factor, forward returns for
        each period, the factor quantile/bin that factor value belongs to, and
  • # Copyright 2017 Quantopian, Inc.

Amadeus Node SDK

MIT(SDK,服务另约)。 项目仓库 · 许可入口

Amadeus Node SDK · post(params

src/amadeus/namespaces/shopping/flight_offers/pricing.js · 41–54 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
  post(params = {}, additionalParams = {}) {
    // Convert additionalParams object to query string
    const queryString = Object.keys(additionalParams).map(key => key + '=' + additionalParams[key]).join('&');

    // Check if queryString is empty before appending it to the URL
    let url = '/v1/shopping/flight-offers/pricing';
    if (queryString !== '') {
      url += '?' + queryString;
    }

    return this.client.post(url, params);
  }
}

Amadeus Node SDK · get() {

src/amadeus/namespaces/booking/flight_order.js · 31–44 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
  get() {
    if (this._orderId)
      return this.client.get('/v1/booking/flight-orders/' + this._orderId);
    else
      throw new Error('MISSING_REQUIRED_PARAMETER');
  }

  /**
   * To cancel a flight order based on its id.
   *
   * @return {Promise.<Response,ResponseError>} a Promise
   *
   * To cancel a flight order with ID 'XXX'
   *

Amadeus Node SDK · get(params

src/amadeus/namespaces/shopping/flight_offers_search.js · 41–54 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
  get(params = {}) {
    return this.client.get('/v2/shopping/flight-offers', params);
  }

  /**
   * To do a customized search with every option available.
   *
   * @param {Object} params
   * @param {Double} params.getFlightOffersBody list of criteria to retrieve a list of flight offers
   * @return {Promise.<Response,ResponseError>} a Promise
   *
   * To do a customized search with given options.
   *
   * ```js

axe-core

MPL-2.0。 项目仓库 · 许可入口

axe-core · export default function run(

lib/core/public/run.js · 20–33 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
export default function run(...args) {
  setupGlobals(args[0]);
  const { context, options, callback = noop } = normalizeRunParams(args);
  const { thenable, resolve, reject } = getPromiseHandlers(callback);
  try {
    assert(axe._audit, 'No audit configured');
    assert(
      !axe._running,
      'Axe is already running. Use `await axe.run()` to wait ' +
        'for the previous run to finish before starting a new run.'
    );
  } catch (e) {
    return handleError(e, callback);
  }

Blender

GPL-3.0(整体,个别文件另核)。 项目仓库 · 许可入口

Blender · void RNA_def_camera(

source/blender/makesrna/intern/rna_camera.cc · 664–677 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
void RNA_def_camera(BlenderRNA *brna)
{
  StructRNA *srna;
  PropertyRNA *prop;
  static const EnumPropertyItem prop_type_items[] = {
      {CAM_PERSP, "PERSP", 0, "Perspective", ""},
      {CAM_ORTHO, "ORTHO", 0, "Orthographic", ""},
      {CAM_PANO, "PANO", 0, "Panoramic", ""},
      {CAM_CUSTOM, "CUSTOM", 0, "Custom", ""},
      {0, nullptr, 0, nullptr, nullptr},
  };
  static const EnumPropertyItem prop_lens_unit_items[] = {
      {0, "MILLIMETERS", 0, "Millimeters", "Specify focal length of the lens in millimeters"},
      {CAM_ANGLETOGGLE,
  • * SPDX-License-Identifier: GPL-2.0-or-later */

Blender · void RNA_def_grease_pencil(

source/blender/makesrna/intern/rna_grease_pencil.cc · 1617–1630 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
void RNA_def_grease_pencil(BlenderRNA *brna)
{
  rna_def_grease_pencil_data(brna);
  rna_def_grease_pencil_tree_node(brna);
  rna_def_grease_pencil_layer(brna);
  rna_def_grease_pencil_layer_mask(brna);
  rna_def_grease_pencil_layer_group(brna);
  rna_def_grease_pencil_frame(brna);
  rna_def_grease_pencil_drawing(brna);
}

}  // namespace blender

#endif
  • * SPDX-License-Identifier: GPL-2.0-or-later */

CKAN

AGPL-3.0。 项目仓库 · 许可入口

CKAN · def package_create(

ckan/logic/action/package.py · 39–52 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def package_create(context: Context, data_dict: DataDict) -> ActionResult.PackageCreate:  # noqa: C901
    """Create a new package.

    You must be authorized to create new packages. If you specify any groups
    for the new package, you must also be authorized to edit these groups.

    Plugins may change the parameters of this function depending on the value
    of the ``type`` parameter, see the
    :py:class:`~ckan.plugins.interfaces.IDatasetForm` plugin interface.

    :param name: the name of the new package, must be between 2 and 100
        characters long and contain only lowercase alphanumeric characters,
        ``-`` and ``_``, e.g. ``'warandpeace'``
    :type name: string

CKAN · def resource_create(

ckan/logic/action/resource.py · 28–41 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def resource_create(
    context: Context, data_dict: DataDict
) -> ActionResult.ResourceCreate:
    """Appends a new resource to a packages list of resources.

    :param package_id: id of package that the resource should be added to.

    :type package_id: string
    :param url: url of resource
    :type url: string
    :param description: (optional)
    :type description: string
    :param format: (optional)
    :type format: string

Cosign

Apache-2.0。 项目仓库 · 许可入口

Cosign · type VerifyCommand struct

cmd/cosign/cli/verify/verify.go · 40–53 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
type VerifyCommand struct {
	options.RegistryOptions
	options.CertVerifyOptions
	options.CommonVerifyOptions
	CheckClaims                  bool
	KeyRef                       string
	CertGithubWorkflowTrigger    string
	CertGithubWorkflowSha        string
	CertGithubWorkflowName       string
	CertGithubWorkflowRepository string
	CertGithubWorkflowRef        string
	CertOidcProvider             string
	IgnoreSCT                    bool
	Sk                           bool
  • // Copyright 2021 The Sigstore Authors.

Cosign · func SignCmd(

cmd/cosign/cli/sign/sign.go · 43–56 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func SignCmd(ctx context.Context, ro *options.RootOptions, ko options.KeyOpts, signOpts options.SignOptions, imgs []string) error {
	if options.NOf(ko.KeyRef, ko.Sk) > 1 {
		return &options.KeyParseError{}
	}

	ctx, cancel := context.WithTimeout(ctx, ro.Timeout)
	defer cancel()

	// Set up an ErrDone consideration to return along "success" paths
	var ErrDone error
	if !signOpts.Recursive {
		ErrDone = mutate.ErrSkipChildren
	}
	regOpts := signOpts.Registry
  • // Copyright 2021 The Sigstore Authors.

CVXPY

Apache-2.0。 项目仓库 · 许可入口

CVXPY · def quad_form(

cvxpy/atoms/quad_form.py · 290–303 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def quad_form(x, P, assume_PSD: bool = False) -> Expression:
    """Alias for :math:`x^T P x`.

    Parameters
    ----------
    x : vector argument.
    P : matrix argument.
    assume_PSD : P is assumed to be PSD without checking.

    Notes
    -----
    When ``P`` is a ``Parameter`` declared PSD or NSD and the solver supports
    quadratic objectives, ``quad_form(x, P)`` can participate in a DPP solve,
    so repeated solves can reuse cached compilation data.
  • Copyright 2013 Steven Diamond, 2017 Robin Verschueren

CVXPY · class Problem

cvxpy/problems/problem.py · 135–148 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Problem(u.Canonical):
    """A convex optimization problem.

    Problems are immutable, save for modification through the specification
    of :class:`~cvxpy.expressions.constants.parameters.Parameter`

    Arguments
    ---------
    objective : Minimize or Maximize
        The problem's objective.
    constraints : iterable
        The constraints on the problem variables.
    """
  • Copyright 2013 Steven Diamond, 2017 Akshay Agrawal

Debezium

Apache-2.0(仓库,连接器依赖另核)。 项目仓库 · 许可入口

Debezium · interface OffsetContext

debezium-connector-common/src/main/java/io/debezium/pipeline/spi/OffsetContext.java · 33–46 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
public interface OffsetContext {

    /**
     * Implementations load a connector-specific offset context based on the offset values stored in Kafka.
     */
    interface Loader<O extends OffsetContext> {

        default Optional<SnapshotType> loadSnapshot(Map<String, ?> offset) {

            Object snapshot = offset.getOrDefault(AbstractSourceInfo.SNAPSHOT_KEY, null);
            // this is to manage transition from a boolean snapshot to SnapshotType
            if (Boolean.TRUE.equals(snapshot) || Boolean.TRUE.toString().equals(snapshot)) {
                return Optional.of(SnapshotType.INITIAL);
            }
  • * Copyright Debezium Authors.

Debezium · class EventRouter

debezium-connect-plugins/src/main/java/io/debezium/transforms/outbox/EventRouter.java · 25–38 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
public class EventRouter<R extends ConnectRecord<R>> implements Transformation<R>, Versioned, ConfigDescriptor {

    EventRouterDelegate<R> eventRouterDelegate = new EventRouterDelegate<>();

    @Override
    public R apply(R r) {
        return eventRouterDelegate.apply(r, rec -> rec);
    }

    @Override
    public ConfigDef config() {
        return eventRouterDelegate.config();
    }
  • * Copyright Debezium Authors.

dlt

Apache-2.0(开源库)。 项目仓库 · 许可入口

dlt · class Incremental(

dlt/extract/incremental/__init__.py · 99–112 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Incremental(
    ItemTransform[TDataItem, IncrementalCustomMetrics], BaseConfiguration, Generic[TCursorValue]
):
    """Adds incremental extraction for a resource by storing a cursor value in persistent state.

    The cursor could for example be a timestamp for when the record was created and you can use this to load only
    new records created since the last run of the pipeline.

    To use this the resource function should have an argument either type annotated with `Incremental` or a default `Incremental` instance.
    For example:

    >>> @dlt.resource(primary_key='id')
    >>> def some_data(created_at=dlt.sources.incremental('created_at', '2023-01-01T00:00:00Z'):
    >>>    yield from request_data(created_after=created_at.last_value)

Docling

MIT 代码,模型许可独立。 项目仓库 · 许可入口

Docling · def convert(

docling/document_converter.py · 696–709 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def convert(
        self,
        source: Union[Path, str, DocumentStream, HttpSource],  # TODO review naming
        headers: Optional[dict[str, str]] = None,
        raises_on_error: bool = True,
        max_num_pages: int = sys.maxsize,
        max_file_size: int = sys.maxsize,
        page_range: PageRange = DEFAULT_PAGE_RANGE,
        progress_callback: Optional[ProgressCallback] = None,
    ) -> ConversionResult:
        """Convert one document fetched from a file path, URL, or DocumentStream.

        A generic ZIP archive can contain multiple documents. Use ``convert_all``
        for such archives. This method raises ``ConversionError`` instead of
  • # SPDX-License-Identifier: MIT

DoWhy

MIT。 项目仓库 · 许可入口

DoWhy · def identify_effect(

dowhy/causal_model.py · 234–247 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def identify_effect(
        self, estimand_type=None, method_name="default", proceed_when_unidentifiable=None, optimize_backdoor=False
    ):
        """Identify the causal effect to be estimated, using properties of the causal graph.

        :param method_name: Method name for identification algorithm. ("id-algorithm" or "default")
        :param proceed_when_unidentifiable: Binary flag indicating whether identification should proceed in the presence of (potential) unobserved confounders.
        :returns: a probability expression (estimand) for the causal effect if identified, else NULL

        """
        if proceed_when_unidentifiable is None:
            proceed_when_unidentifiable = self._proceed_when_unidentifiable
        if estimand_type is None:
            estimand_type = self._estimand_type

DoWhy · def refute_estimate(

dowhy/causal_model.py · 474–487 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def refute_estimate(self, estimand, estimate, method_name=None, show_progress_bar=False, **kwargs):
        """Refute an estimated causal effect.

        method_name must be specified. Examples of refutation methods include:
            * Adding a randomly-generated confounder: "random_common_cause"
            * Adding a confounder that is associated with both treatment and outcome: "add_unobserved_common_cause"
            * Replacing the treatment with a placebo (random) variable): "placebo_treatment_refuter"
            * Removing a random subset of the data: "data_subset_refuter"
            * Bootstrap the data: "bootstrap_refuter"
            * Replace outcome with a dummy (random) variable: "dummy_outcome_refuter"
        For available refuters, see modules under dowhy.causal_refuters.

        :param estimand: target estimand, an instance of the IdentifiedEstimand class
            (typically the output of identify_effect)

DoWhy · def estimate_effect(

dowhy/causal_model.py · 271–284 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def estimate_effect(
        self,
        identified_estimand,
        method_name=None,
        control_value=0,
        treatment_value=1,
        test_significance=None,
        evaluate_effect_strength=False,
        confidence_intervals=False,
        target_units="ate",
        effect_modifiers=None,
        fit_estimator=True,
        method_params=None,
        num_quantiles_to_discretize_cont_cols=None,

DuckDB

MIT(核心)。 项目仓库 · 许可入口

DuckDB · void WindowRowNumberExecutor::GetData(

src/function/window/window_rownumber_function.cpp · 181–194 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
void WindowRowNumberExecutor::GetData(ExecutionContext &context, DataChunk &eval_chunk, DataChunk &bounds,
                                      Vector &result, idx_t row_idx, OperatorSinkInput &sink) {
	auto &grstate = sink.global_state.Cast<WindowRowNumberGlobalState>();
	const auto count = bounds.size();
	auto rdata = FlatVector::Writer<int64_t>(result, count);

	if (grstate.use_framing) {
		auto frame_begin = FlatVector::GetData<const idx_t>(bounds.data[FRAME_BEGIN]);
		auto frame_end = FlatVector::GetData<const idx_t>(bounds.data[FRAME_END]);
		if (grstate.token_tree) {
			for (idx_t i = 0; i < count; ++i, ++row_idx) {
				// Row numbers are unique ranks
				rdata.WriteValue(
				    UnsafeNumericCast<int64_t>(grstate.token_tree->Rank(frame_begin[i], frame_end[i], row_idx)));

DuckDB · void WindowAggregateExecutor::EvaluateInternal(

src/function/window/window_aggregate_function.cpp · 254–265 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
void WindowAggregateExecutor::EvaluateInternal(ExecutionContext &context, DataChunk &eval_chunk, DataChunk &bounds,
                                               Vector &result, idx_t row_idx, OperatorSinkInput &sink) const {
	auto &gastate = sink.global_state.Cast<WindowAggregateExecutorGlobalState>();
	auto &lastate = sink.local_state.Cast<WindowAggregateExecutorLocalState>();
	auto &gsink = gastate.gsink;
	D_ASSERT(aggregator);

	OperatorSinkInput asink {*gsink, *lastate.aggregator_state, sink.interrupt_state};
	aggregator->Evaluate(context, bounds, result, bounds.size(), row_idx, asink);
}

} // namespace duckdb

DuckDB · PhysicalAsOfJoin::

src/execution/operator/join/physical_asof_join.cpp · 18–31 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
PhysicalAsOfJoin::PhysicalAsOfJoin(PhysicalPlan &physical_plan, LogicalComparisonJoin &op, PhysicalOperator &left,
                                   PhysicalOperator &right, vector<column_t> lhs_partition_cols,
                                   vector<column_t> rhs_partition_cols)
    : PhysicalComparisonJoin(physical_plan, op, PhysicalOperatorType::ASOF_JOIN, std::move(op.conditions), op.join_type,
                             op.estimated_cardinality),
      comparison_type(ExpressionType::INVALID) {
	// Convert the conditions partitions and sorts
	for (auto &cond : conditions) {
		D_ASSERT(cond.IsComparison());
		D_ASSERT(cond.GetLHS().GetReturnType() == cond.GetRHS().GetReturnType());
		join_key_types.push_back(cond.GetLHS().GetReturnType());
		const auto join_key_idx = join_key_types.size() - 1;

		auto left_cond = cond.LeftReference()->Copy();

DuckDB · SinkResultType PhysicalHashAggregate::Sink(

src/execution/operator/aggregate/physical_hash_aggregate.cpp · 396–409 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
SinkResultType PhysicalHashAggregate::Sink(ExecutionContext &context, DataChunk &chunk,
                                           OperatorSinkInput &input) const {
	auto &local_state = input.local_state.Cast<HashAggregateLocalSinkState>();
	auto &global_state = input.global_state.Cast<HashAggregateGlobalSinkState>();

	if (distinct_collection_info) {
		SinkDistinct(context, chunk, input);
	}

	if (CanSkipRegularSink()) {
		return SinkResultType::NEED_MORE_INPUT;
	}

	DataChunk &aggregate_input_chunk = local_state.aggregate_input_chunk;

DVC

Apache-2.0。 项目仓库 · 许可入口

DVC · def to_lockfile(

dvc/stage/serialize.py · 195–208 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def to_lockfile(stage: "PipelineStage", **kwargs) -> dict:
    assert stage.name
    return {stage.name: to_single_stage_lockfile(stage, **kwargs)}


def to_single_stage_file(stage: "Stage", **kwargs):
    state = stage.dumpd(**kwargs)

    # When we load a stage we parse yaml with a fast parser, which strips
    # off all the comments and formatting. To retain those on update we do
    # a trick here:
    # - reparse the same yaml text with a slow but smart ruamel yaml parser
    # - apply changes to a returned structure
    # - serialize it

DVC · def checkout(

dvc/repo/checkout.py · 110–123 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def checkout(  # noqa: C901
    self,
    targets=None,
    with_deps=False,
    force=False,
    relink=False,
    recursive=False,
    allow_missing=False,
    **kwargs,
):
    from dvc.repo.index import build_data_index
    from dvc.stage.exceptions import StageFileBadNameError, StageFileDoesNotExistError
    from dvc_data.index.checkout import ADD, DELETE, MODIFY, apply, compare

EdgarTools

MIT。 项目仓库 · 许可入口

EdgarTools · class Entity(

edgar/entity/core.py · 225–238 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Entity(SecFiler):
    """
    Represents any entity that files with the SEC.

    This is the base concrete implementation that can be used directly
    or specialized for specific entity types.
    """

    def __init__(self, cik_or_identifier: Union[str, int]):
        # If it's a ticker, convert to CIK first
        if isinstance(cik_or_identifier, str) and not cik_or_identifier.isdigit():
            cik = find_cik(cik_or_identifier)
            if cik is None:
                raise CompanyNotFoundError(

EdgarTools · def xbrl(

edgar/_filings.py · 1874–1887 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def xbrl(self) -> Optional[XBRL]:
        """
        Get the XBRL document for the filing, parsed and as a FilingXbrl object

        :return: The parsed XBRL, or `None` when the filing carries no XBRL
            attachments — a property of the filing, not a failure to read it,
            and one this keeps answering quietly in 6.0 (docs/upgrade/6.0.md).
        """
        # The `except XBRLFilingWithNoXbrlData` that used to sit here was dead:
        # nothing in the library raised that error, and `from_filing` signals
        # the no-XBRL case by returning None. Removed rather than left as
        # decoration, so this function's None has one visible source.
        try:
            return XBRL.from_filing(self)

EdgarTools · def income_statement(

edgar/financials.py · 249–262 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def income_statement(self, *, view: ViewType = None):
        """
        Get the income statement.

        Args:
            view: StatementView controlling dimensional data display.
                  STANDARD: Face presentation matching SEC Viewer (display default)
                  DETAILED: All dimensional data included (to_dataframe default)
                  SUMMARY: Non-dimensional totals only

        Returns:
            A Statement object for the income statement, or None if not available
        """
        if self.xb is None:

EdgarTools · def cash_flow_statement(

edgar/financials.py · 266–279 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def cash_flow_statement(self, *, view: ViewType = None):
        """
        Get the cash flow statement.

        Args:
            view: StatementView controlling dimensional data display.
                  STANDARD: Face presentation matching SEC Viewer (display default)
                  DETAILED: All dimensional data included (to_dataframe default)
                  SUMMARY: Non-dimensional totals only

        Returns:
            A Statement object for the cash flow statement, or None if not available
        """
        if self.xb is None:

Empyrical

Apache-2.0。 项目仓库 · 许可入口

Empyrical · def alpha_beta(

empyrical/stats.py · 1004–1017 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def alpha_beta(returns,
               factor_returns,
               risk_free=0.0,
               period=DAILY,
               annualization=None,
               out=None):
    """Calculates annualized alpha and beta.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
        - See full explanation in :func:`~empyrical.stats.cum_returns`.
    factor_returns : pd.Series
  • # Copyright 2016 Quantopian, Inc.

Empyrical · def max_drawdown(

empyrical/stats.py · 352–365 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def max_drawdown(returns, out=None):
    """
    Determines the maximum drawdown of a strategy.

    Parameters
    ----------
    returns : pd.Series or np.ndarray
        Daily returns of the strategy, noncumulative.
        - See full explanation in :func:`~empyrical.stats.cum_returns`.
    out : array-like, optional
        Array to use as output buffer.
        If not passed, a new array will be created.

    Returns
  • # Copyright 2016 Quantopian, Inc.

Empyrical · def annual_volatility(

empyrical/stats.py · 487–500 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def annual_volatility(returns,
                      period=DAILY,
                      alpha=2.0,
                      annualization=None,
                      out=None):
    """
    Determines the annual volatility of a strategy.

    Parameters
    ----------
    returns : pd.Series or np.ndarray
        Periodic returns of the strategy, noncumulative.
        - See full explanation in :func:`~empyrical.stats.cum_returns`.
    period : str, optional
  • # Copyright 2016 Quantopian, Inc.

Empyrical · def cum_returns(

empyrical/stats.py · 219–232 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def cum_returns(returns, starting_value=0, out=None):
    """
    Compute cumulative returns from simple returns.

    Parameters
    ----------
    returns : pd.Series, np.ndarray, or pd.DataFrame
        Returns of the strategy as a percentage, noncumulative.
         - Time series with decimal returns.
         - Example::

            2015-07-16   -0.012143
            2015-07-17    0.045350
            2015-07-20    0.030957
  • # Copyright 2016 Quantopian, Inc.

FFmpeg

主要 LGPL-2.1-or-later,选件可切换 GPL。 项目仓库 · 许可入口

FFmpeg · static int show_stream(

fftools/ffprobe.c · 1984–1997 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
static int show_stream(AVTextFormatContext *tfc, AVFormatContext *fmt_ctx, int stream_idx, InputStream *ist, int container)
{
    AVStream *stream = ist->st;
    AVCodecParameters *par;
    AVCodecContext *dec_ctx;
    char val_str[128];
    const char *s;
    AVRational sar, dar;
    AVBPrint pbuf;
    const AVCodecDescriptor *cd;
    const SectionID section_header[] = {
        SECTION_ID_STREAM,
        SECTION_ID_PROGRAM_STREAM,
        SECTION_ID_STREAM_GROUP_STREAM,
  • * Copyright (c) 2007-2010 Stefano Sabatini

FFmpeg · static int show_format(

fftools/ffprobe.c · 2666–2679 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
static int show_format(AVTextFormatContext *tfc, InputFile *ifile)
{
    AVFormatContext *fmt_ctx = ifile->fmt_ctx;
    int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
    int ret = 0;

    avtext_print_section_header(tfc, NULL, SECTION_ID_FORMAT);
    print_str_validate("filename", fmt_ctx->url);
    print_int("nb_streams",       fmt_ctx->nb_streams);
    print_int("nb_programs",      fmt_ctx->nb_programs);
    print_int("nb_stream_groups", fmt_ctx->nb_stream_groups);
    print_str("format_name",      fmt_ctx->iformat->name);
    if (!do_bitexact) {
        if (fmt_ctx->iformat->long_name) print_str    ("format_long_name", fmt_ctx->iformat->long_name);
  • * Copyright (c) 2007-2010 Stefano Sabatini

Financial Services Plugins

Apache-2.0 根仓库。 项目仓库 · 许可入口

Financial Services Plugins · name: dcf-model

plugins/agent-plugins/model-builder/skills/dcf-model/SKILL.md · 2–15 行。 在 GitHub 查看配置与指引 · 许可证与声明

上游配置与指引
name: dcf-model
description: Real DCF (Discounted Cash Flow) model creation for equity valuation. Retrieves financial data from SEC filings and analyst reports, builds comprehensive cash flow projections with proper WACC calculations, performs sensitivity analysis, and outputs professional Excel models with executive summaries. Use when users need to value a company using DCF methodology, request intrinsic value analysis, or ask for detailed financial modeling with growth projections and terminal value calculations.
---

# DCF Model Builder

## Overview

This skill creates institutional-quality DCF models for equity valuation following investment banking standards. Each analysis produces a detailed Excel model (with sensitivity analysis included at the bottom of the DCF sheet).

## Tools

- Default to using all of the information provided by the user and MCP servers available for data sourcing.

Financial Services Plugins · name: investment-proposal

plugins/agent-plugins/meeting-prep-agent/skills/investment-proposal/SKILL.md · 2–15 行。 在 GitHub 查看配置与指引 · 许可证与声明

上游配置与指引
name: investment-proposal
description: Create professional investment proposals for prospective clients. Covers the firm's approach, proposed allocation, expected outcomes, and fee structure. Use when pitching new clients or presenting a new investment strategy. Triggers on "investment proposal", "prospect presentation", "pitch new client", "proposal for [client]", or "new client presentation".
---

# Investment Proposal

## Workflow

### Step 1: Prospect Context

Gather:
- **Prospect name** and household details
- **Current situation**: Existing advisor? Self-directed? What prompted the meeting?
- **Assets**: Estimated AUM, account types, current holdings (if shared)

FINOS CDM

Community Specification License 1.0(CDM 规范及对应资产)。 项目仓库 · 许可入口

FINOS CDM · type EconomicTerms:

rosetta-source/src/main/rosetta/product-template-type.rosetta · 31–44 行。 在 GitHub 查看规范模型 · 许可证与声明

上游配置与指引
type EconomicTerms: <" This class represents the full set of price-forming features associated with a contractual product: the payout component, the notional/quantity, the effective and termination date and the date adjustment provisions when applying uniformily across the payout components. This class also includes the legal provisions which have valuation implications: cancelable provision, extendible provision, early termination provision and extraordinary events specification.">

    effectiveDate AdjustableOrRelativeDate (0..1) <"The first day of the terms of the trade. This day may be subject to adjustment in accordance with a business day convention.">
        [docReference ICMA GMRA namingConvention "Purchase Date"
            provision "As defined in GMRA paragraph 2(mm) The date on which Purchased Securities are sold or are to be sold by Seller to Buyer."]
        [docReference ICMA ERCCBestPractice namingConvention "Purchase Date"
            provision "ERCC Guide: Annex II  Glossary of repo terminology. The term for the value date of a repo."]
    effectiveTime DirectOrRelativeTime (0..1) <"The time and zone of the first day of the terms of the trade. It can also be specified in relation to another time.">
    terminationDate AdjustableOrRelativeDate (0..1) <"The last day of the terms of the trade. This date may be subject to adjustments in accordance with the business day convention. It can also be specified in relation to another scheduled date (e.g. the last payment date).">
        [docReference ICMA GMRA namingConvention "Repurchase Date"
            provision "As defined in GMRA paragraph 2(qq) The date on which Buyer is to sell Equivalent Securities to Seller."]
        [docReference ICMA ERCCBestPractice namingConvention "Repurchase Date"
            provision "ERCC Guide: Annex II  Glossary of repo terminology. The term for the maturity date of a repo."]
    terminationTime DirectOrRelativeTime (0..1) <"The time and zone of the last day of the terms of the trade. It can also be specified in relation to another time.">

FINOS CDM · type BusinessEvent extends

rosetta-source/src/main/rosetta/event-common-type.rosetta · 60–73 行。 在 GitHub 查看规范模型 · 许可证与声明

上游配置与指引
type BusinessEvent extends EventInstruction: <"A business event represents a life cycle event of a trade. The combination of the state changes results in a qualifiable life cycle event. An example of a Business Event is a PartialTermination which is a defined by a quantity change primitive event.">
    [metadata key]
    [rootType]

    eventQualifier string (0..1) <"The CDM event qualifier, which corresponds to the outcome of the isEvent qualification logic which qualifies the lifecycle event as a function of its features (e.g. PartialTermination, ClearingSubmission, Novation, ...).">
    after TradeState (0..*) <"Specifies the after trade state(s) created.">

    condition EventDate:
        eventDate exists

type AgreementEvent extends AgreementEventInstruction: <"An agreement event represents a life cycle event of a legal document. The combination of legal term amendments, contracting party changes or agreement status changes that are represented by an amendment agreement that includes a change to the overall Legal agreement representation through a change in contractual parties or terms.">
    [metadata key]
    [rootType]

FINOS CDM · type TransferInstruction:

rosetta-source/src/main/rosetta/event-common-type.rosetta · 162–175 行。 在 GitHub 查看规范模型 · 许可证与声明

源码片段
type TransferInstruction: <"Defines the payout on which to create a Transfer along with all necessary resets.">
    transferState TransferState (0..*) <"Specifies the terms and state of a transfers.">

type QuantityChangeInstruction: <"Instructions required to create a Quantity Change Primitive Event, which can be either an increase, a decrease or a replacement. An increase adds a new trade lot to the original trade, whereas a decrease subtracts from an existing trade lot's quantity. A replacement updates the quantity of an existing trade lot to the new value.">
    change PriceQuantity (1..*) <"Quantity by which the trade is being increased, decreased or replaced, and the price at which such quantity change is agreed. The quantity change should always be specified as a positive number, with the direction (increase/decrease/replacement) being specified by the direction enumeration. A fee can also be associated to the quantity change by specifying a Price component of type CashPrice, including the corresponding settlement date and direction.">
    direction QuantityChangeDirectionEnum (1..1) <"Direction of the quantity change specified as either an increase, decrease or replacement.">
    lotIdentifier Identifier (0..*) <"Identifier for the new lot (in case of increase) or for the existing lot to be changed(in case of decrease or replacement). This optional attribute is mandatory in case of a decrease or replacement if the initial trade state contains multiple trade lots.">

type IndexTransitionInstruction: <"Defines the information needed to create a Index Transition Business Event.">
    priceQuantity PriceQuantity (1..*) <"Specifies both new floating rate index and spread adjustment for each leg to be updated.  The spread adjustment accounts for the difference between the old floating rate index relative to the new one. This spread amount is added to the existing spread to determine the new spread, which is applied from the specified effective date forward. In the case of the IBOR Fallback Rate Adjustments, the adjustment spread (also known as the Fallback Adjustment) accounts for two distinctions: i) the fact that the replacement Risk-Free Rate is an overnight rate while IBORs have term structures (e.g., 1, 3, 6-month LIBOR); and (ii) the historical spread differential between IBORs and their term equivalent Overnight Risk-Free Rate compounded rates.">
    effectiveDate date (1..1) <"Specifies the effective date of the index transition event. This is first date on which the floating rate calculation will use the new floating rate index and adjusted spread in the floating rate calculation.">
    cashTransfer Transfer (0..1) <"Specifies the cash transfer that can optionally be tied to an index transition event.">

    condition PriceQuantity:

FINOS CDM · type Collateral

rosetta-source/src/main/rosetta/product-collateral-type.rosetta · 17–30 行。 在 GitHub 查看规范模型 · 许可证与声明

源码片段
type Collateral: <"A type for defining the obligations of the counterparty subject to credit support requirements.">
    [metadata key]
    independentAmount IndependentAmount (0..1) <"Independent Amount is an amount that usually less creditworthy counterparties are asked to provide. It can either be a fixed amount or a percentage of the Transaction's value. The Independent Amount can be: (i) transferred before any trading between the parties occurs (as a deposit at a third party's account or with the counterparty) or (ii) callable after trading has occurred (typically because a downgrade has occurred). In situation (i), the Independent Amount is not included in the calculation of Exposure, but in situation (ii), it is included in the calculation of Exposure. Thus, for situation (ii), the Independent Amount may be transferred along with any collateral call. Independent Amount is a defined term in the ISDA Credit Support Annex. ('with respect to a party, the amount specified as such for that party in Paragraph 13; if no amount is specified, zero').">
    portfolioIdentifier Identifier (0..*) <"A list of identifiers pointing to the collateral portfolios which contain the collateral which covers a trade.">
    collateralPortfolio CollateralPortfolio (0..*) <"The collateral portfolios which contain the collateral which covers a trade. (NB: this can be provided by reference to a global key for each CollateralPortfolio object)">
        [metadata reference]
    collateralProvisions CollateralProvisions (0..1) <"specifies the collateral provisions of the product.">

    condition CollateralExists: <"Collateral must represent either a simple independent amount or full collateral portfolio.">
        independentAmount exists or collateralPortfolio exists

    condition CollateralProvisions: <"When a collateral portfolio is provided, collateral provisions must exists that govern this collateral.">
        if collateralPortfolio exists then collateralProvisions exists

Flowable

Apache-2.0(开源引擎)。 项目仓库 · 许可入口

Flowable · public interface TaskService

modules/flowable-engine/src/main/java/org/flowable/engine/TaskService.java · 46–59 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
public interface TaskService {

    /**
     * Creates a new task that is not related to any process instance.
     * 
     * The returned task is transient and must be saved with {@link #saveTask(Task)} 'manually'.
     */
    Task newTask();

    /** create a new task with a user defined task id */
    Task newTask(String taskId);

    /**
     * Create a builder for the task

Flowable · public interface RuntimeService

modules/flowable-engine/src/main/java/org/flowable/engine/RuntimeService.java · 62–75 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
public interface RuntimeService {

    /**
     * Create a {@link ProcessInstanceBuilder}, that allows to set various options for starting a process instance, as an alternative to the various startProcessInstanceByXX methods.
     */
    ProcessInstanceBuilder createProcessInstanceBuilder();

    /**
     * Create a {@link ProcessInstanceUpdateBuilder}, that allows to update various properties of a process instance.
     *
     * @param processInstanceId
     *     id of the process instance to update, cannot be null
     */
    ProcessInstanceUpdateBuilder createProcessInstanceUpdateBuilder(String processInstanceId);

Flowable · public interface Task

modules/flowable-task-service-api/src/main/java/org/flowable/task/api/Task.java · 23–36 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
public interface Task extends TaskInfo {
    
    String CREATED = "created";
    String CLAIMED = "claimed";
    String IN_PROGRESS = "inProgress";
    String SUSPENDED = "suspended";
    String COMPLETED = "completed";
    String TERMINATED = "terminated";

    /**
     * Default value used for priority when a new {@link Task} is created.
     */
    int DEFAULT_PRIORITY = 50;

Formance Ledger

MIT。 项目仓库 · 许可入口

Formance Ledger · func (s *Server) handleCreateTransaction(

internal/adapter/http/handlers_create_transaction.go · 13–26 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func (s *Server) handleCreateTransaction(w http.ResponseWriter, r *http.Request) {
	ledgerName, ok := requireLedgerName(w, r)
	if !ok {
		return
	}

	// Decode request body into protobuf CreateTransactionPayload.
	// The custom UnmarshalJSON in service.pb.json.go drives field naming
	// from the public camelCase contract (scriptReference, accountMetadata,
	// …) — the default protoc-gen-go tags are snake_case and would silently
	// drop multi-word keys (#452).
	req := &servicepb.CreateTransactionPayload{}

	err := json.UnmarshalRead(r.Body, req)

Formance Ledger · func (s *Server) handleRevertTransaction(

internal/adapter/http/handlers_revert_transaction.go · 23–36 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func (s *Server) handleRevertTransaction(w http.ResponseWriter, r *http.Request) {
	ledgerName, ok := requireLedgerName(w, r)
	if !ok {
		return
	}

	transactionID, ok := requireTransactionID(w, r)
	if !ok {
		return
	}

	// Read the whole body through the router's MaxBytesReader before decoding.
	// A stream decoder can stop at the first value and miss trailing data or
	// an oversized suffix. Only a zero-byte body means default revert options.

Formance Ledger · func (s *Server) handleGetAccount(

internal/adapter/http/handlers_get_account.go · 12–25 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func (s *Server) handleGetAccount(w http.ResponseWriter, r *http.Request) {
	ledgerName, ok := requireLedgerName(w, r)
	if !ok {
		return
	}

	address, ok := requirePathParameter(w, r, "address", "account address")
	if !ok {
		return
	}

	// Verify ledger exists
	_, err := s.backend.GetLedgerByName(r.Context(), ledgerName)
	if err != nil {

Fountain.js

MIT。 项目仓库 · 许可入口

Fountain.js · fountain.parse = function

fountain.js · 275–284 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
  fountain.parse = function (script, tokens, callback) {
    return parse(script, tokens, callback);
  };

  if (typeof module !== 'undefined') {
    module.exports = fountain;
  } else {
    this.fountain = fountain;
  }  
}).call(this);
  • // Copyright (c) 2012 Matt Daly
  • title_page: /^((?:title|credit|author[s]?|source|notes|draft date|date|contact|copyright)\:)/gim,

Fountain.js · var tokenize = function

fountain.js · 54–67 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
  var tokenize = function (script) {
    var src    = lexer(script).split(regex.splitter)
      , i      = src.length, line, match, parts, text, meta, x, xlen, dual
      , tokens = [];

    while (i--) {
      line = src[i];
      
      // title page
      if (regex.title_page.test(line)) {
        match = line.replace(regex.title_page, '\n$1').split(regex.splitter).reverse();
        for (x = 0, xlen = match.length; x < xlen; x++) {
          parts = match[x].replace(regex.cleaner, '').split(/\:\n*/);
          tokens.push({ type: parts[0].trim().toLowerCase().replace(' ', '_'), text: parts[1].trim() });
  • // Copyright (c) 2012 Matt Daly
  • title_page: /^((?:title|credit|author[s]?|source|notes|draft date|date|contact|copyright)\:)/gim,

Git LFS

MIT(部分 Go 代码 BSD-3-Clause)。 项目仓库 · 许可入口

Git LFS · func DecodePointer(

lfs/pointer.go · 118–131 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func DecodePointer(reader io.Reader) (*Pointer, error) {
	p, _, err := DecodeFrom(reader)
	return p, err
}

// DecodeFrom decodes an *lfs.Pointer from the given io.Reader, "reader".
// If the pointer encoded in the reader could successfully be read and decoded,
// it will be returned with a nil error.
//
// If the pointer could not be decoded, an io.Reader containing the entire
// blob's data will be returned, along with a parse error.
func DecodeFrom(reader io.Reader) (*Pointer, io.Reader, error) {
	buf := make([]byte, BlobSizeCutoff)
	n, err := reader.Read(buf)

Git LFS · func (f *GitFilter) Clean(

lfs/gitfilter_clean.go · 19–32 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func (f *GitFilter) Clean(reader io.Reader, fileName string, fileSize int64, cb tools.CopyCallback) (*cleanedAsset, error) {
	extensions, err := f.cfg.SortedExtensions()
	if err != nil {
		return nil, err
	}

	var oid string
	var size int64
	var tmp *os.File
	var exts []*PointerExtension
	if len(extensions) > 0 {
		request := &pipeRequest{"clean", reader, fileName, extensions}

		var response pipeResponse

GTFS Realtime Bindings

Apache-2.0(绑定库)。 项目仓库 · 许可入口

GTFS Realtime Bindings · message TripUpdate

gtfs-realtime.proto · 156–169 行。 在 GitHub 查看规范模型 · 许可证与声明

源码片段
message TripUpdate {
  // The Trip that this message applies to. There can be at most one
  // TripUpdate entity for each actual trip instance.
  // If there is none, that means there is no prediction information available.
  // It does *not* mean that the trip is progressing according to schedule.
  required TripDescriptor trip = 1;

  // Additional information on the vehicle that is serving this trip.
  optional VehicleDescriptor vehicle = 3;

  // Timing information for a single predicted event (either arrival or
  // departure).
  // Timing consists of delay and/or estimated time, and uncertainty.
  // - delay should be used when the prediction is given relative to some
  • // Copyright 2015 The GTFS Specifications Authors.

GTFS Realtime Bindings · message Alert

gtfs-realtime.proto · 624–637 行。 在 GitHub 查看规范模型 · 许可证与声明

源码片段
message Alert {
  // Time when the alert should be shown to the user. If missing, the
  // alert will be shown as long as it appears in the feed.
  // If multiple ranges are given, the alert will be shown during all of them.
  // Should not be used - for backwards-compatibility only.
  repeated TimeRange active_period = 1 [deprecated = true];

  // Time when the alert should be shown to the user strictly for informative reasons.
  // If missing, the consuming application can decide when it's appropriate to be shown.
  // If multiple ranges are given, the alert will be shown during all of them.
  repeated TimeRange communication_period = 2;

  // Time when the services are affected by the alert. If communication_period is specified,
  // every time interval in impact_period must be fully contained within at least
  • // Copyright 2015 The GTFS Specifications Authors.

icalendar

BSD-2-Clause(上游)。 项目仓库 · 许可入口

icalendar · class Event(

src/icalendar/cal/event.py · 66–79 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Event(Component):
    """A grouping of component properties that describe an event.

    Description:
        A "VEVENT" calendar component is a grouping of
        component properties, possibly including "VALARM" calendar
        components, that represents a scheduled amount of time on a
        calendar.  For example, it can be an activity; such as a one-hour
        long, department meeting from 8:00 AM to 9:00 AM, tomorrow.
        Generally, an event will take up time on an individual calendar.
        Hence, the event will appear as an opaque interval in a search for
        busy time.  Alternately, the event can have its Time Transparency
        set to "TRANSPARENT" in order to prevent blocking of the event in
        searches for busy time.

icalendar · class Calendar(

src/icalendar/cal/calendar.py · 48–61 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Calendar(Component):
    """
        The "VCALENDAR" object is a collection of calendar information.
        This information can include a variety of components, such as
        "VEVENT", "VTODO", "VJOURNAL", "VFREEBUSY", "VTIMEZONE", or any
        other type of calendar component.

    Example:
        Create a new Calendar:

            >>> from icalendar import Calendar
            >>> calendar = Calendar.new(name="My Calendar")
            >>> print(calendar.calendar_name)
            My Calendar

Ink

MIT。 项目仓库 · 许可入口

Ink · public void ChooseChoiceIndex(

ink-engine-runtime/Story.cs · 1794–1807 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
        public void ChooseChoiceIndex(int choiceIdx)
        {
            var choices = currentChoices;
            Assert (choiceIdx >= 0 && choiceIdx < choices.Count, "choice out of range");

            // Replace callstack with the one from the thread at the choosing point, 
            // so that we can jump into the right place in the flow.
            // This is important in case the flow was forked by a new thread, which
            // can create multiple leading edges for the story, each of
            // which has its own context.
            var choiceToChoose = choices [choiceIdx];
            if(onMakeChoice != null) onMakeChoice(choiceToChoose);
            state.callStack.currentThread = choiceToChoose.threadAtGeneration;

Ink · public string ToJson(

ink-engine-runtime/StoryState.cs · 37–50 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
        public string ToJson() {
            var writer = new SimpleJson.Writer();
            WriteJson(writer);
            return writer.ToString();
        }

        /// <summary>
        /// Exports the current state to json format, in order to save the game.
        /// For this overload you can pass in a custom stream, such as a FileStream.
        /// </summary>
        public void ToJson(Stream stream) {
            var writer = new SimpleJson.Writer(stream);
            WriteJson(writer);
        }

k6

AGPL-3.0。 项目仓库 · 许可入口

k6 · func (ts *Thresholds) Run(

metrics/thresholds.go · 170–183 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func (ts *Thresholds) Run(sink Sink, duration time.Duration) (bool, error) {
	// Initialize the sinks store
	ts.sinked = make(map[string]float64)

	// FIXME: Remove this comment as soon as the metrics.Sink does not expose Format anymore.
	//
	// As of December 2021, this block reproduces the behavior of the
	// metrics.Sink.Format behavior. As we intend to try to get away from it,
	// we instead implement the behavior directly here.
	//
	// For more details, see https://github.com/grafana/k6/issues/2320
	switch sinkImpl := sink.(type) {
	case *CounterSink:
		ts.sinked["count"] = sinkImpl.Value

Keycloak

Apache-2.0。 项目仓库 · 许可入口

Keycloak · public class AuthorizationEndpoint

services/src/main/java/org/keycloak/protocol/oidc/endpoints/AuthorizationEndpoint.java · 82–95 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
public class AuthorizationEndpoint extends AuthorizationEndpointBase {

    private static final Logger logger = Logger.getLogger(AuthorizationEndpoint.class);

    public static final String CODE_AUTH_TYPE = "code";

    /**
     * Prefix used to store additional HTTP GET params from original client request into {@link AuthenticationSessionModel} note to be available later in Authenticators, RequiredActions etc. Prefix is used to
     * prevent collisions with internally used notes.
     *
     * @see AuthenticationSessionModel#getClientNote(String)
     */
    public static final String LOGIN_SESSION_NOTE_ADDITIONAL_REQ_PARAMS_PREFIX = "client_request_param_";
  • * Copyright 2016 Red Hat, Inc. and/or its affiliates

Label Studio

Apache-2.0。 项目仓库 · 许可入口

Label Studio · .model("RichTextRegionModel"

web/libs/editor/src/regions/RichTextRegion.js · 27–40 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
  .model("RichTextRegionModel", {
    type: "richtextregion",
    object: types.late(() => types.reference(RichTextModel)),

    startOffset: types.integer,
    endOffset: types.integer,
    start: types.string,
    end: types.string,
    text: types.maybeNull(types.string),
    isText: types.optional(types.boolean, false),
    globalOffsets: types.maybeNull(GlobalOffsets),
  })
  .volatile(() => ({
    hideable: true,

LangGraph

MIT,限仓库相关代码。 项目仓库 · 许可入口

LangGraph · class StateGraph(

libs/langgraph/langgraph/graph/state.py · 132–145 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class StateGraph(Generic[StateT, ContextT, InputT, OutputT]):
    """A graph whose nodes communicate by reading and writing to a shared state.

    The signature of each node is `State -> Partial<State>`.

    Each state key can optionally be annotated with a reducer function that
    will be used to aggregate the values of that key received from multiple nodes.
    The signature of a reducer function is `(Value, Value) -> Value`.

    !!! warning

        `StateGraph` is a builder class and cannot be used directly for execution.
        You must first call `.compile()` to create an executable graph that supports
        methods like `invoke()`, `stream()`, `astream()`, and `ainvoke()`. See the

LangGraph · def interrupt(

libs/langgraph/langgraph/types.py · 913–926 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def interrupt(
    value: Any, *, response_schema: dict[str, Any] | type | None = None
) -> Any:
    """Interrupt the graph with a resumable exception from within a node.

    The `interrupt` function enables human-in-the-loop workflows by pausing graph
    execution and surfacing a value to the client. This value can communicate context
    or request input required to resume execution.

    In a given node, the first invocation of this function raises a `GraphInterrupt`
    exception, halting execution. The provided `value` is included with the exception
    and sent to the client executing the graph.

    A client resuming the graph must use the [`Command`][langgraph.types.Command]

Matomo

GPL-3.0 平台核心。 项目仓库 · 许可入口

Matomo · public function get(

plugins/Goals/API.php · 892–905 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    public function get($idSite, string $period, string $date, $segment = false, $idGoal = false, $columns = [], bool $showAllGoalSpecificMetrics = false, bool $compare = false)
    {
        Piwik::checkUserHasViewAccess($idSite);

        $table = null;

        $segments = array(
            '' => false,
            '_new_visit' => VisitFrequencyAPI::NEW_VISITOR_SEGMENT,
            '_returning_visit' => VisitFrequencyAPI::RETURNING_VISITOR_SEGMENT,
        );

        foreach ($segments as $appendToMetricName => $predefinedSegment) {
            $startingArchiveDependent = \Piwik\Plugin\Archiver::$ARCHIVE_DEPENDENT;

Matomo · public function getEntryPageUrls(

plugins/Actions/API.php · 244–257 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    public function getEntryPageUrls(
        $idSite,
        string $period,
        string $date,
        $segment = false,
        bool $expanded = false,
        $idSubtable = false,
        bool $flat = false
    ) {
        Piwik::checkUserHasViewAccess($idSite);

        $dataTable = $this->getPageUrls($idSite, $period, $date, $segment, $expanded, $idSubtable, false, $flat);
        $this->filterNonEntryActions($dataTable);
        return $dataTable;

Matomo · public function getCategory(

plugins/Events/API.php · 229–242 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    public function getCategory($idSite, string $period, string $date, $segment = false, bool $expanded = false, $secondaryDimension = false, bool $flat = false)
    {
        return $this->getDataTable(__FUNCTION__, $idSite, $period, $date, $segment, $expanded, false, $secondaryDimension, $flat);
    }

    /**
     * Returns event metrics grouped by event action.
     *
     * @param int|string|int[] $idSite Website ID(s) to query.
     *                                 - Single site ID (e.g. 1)
     *                                 - Multiple site IDs (e.g. [1, 4, 5])
     *                                 - Comma-separated list ("1,4,5") or "all"
     * @param 'day'|'week'|'month'|'year'|'range' $period The period to process, processes data for the period
     *                                                    containing the specified date.

Mautic

GPL-3.0。 项目仓库 · 许可入口

Mautic · public function rebuildListLeads(

app/bundles/LeadBundle/Model/ListModel.php · 383–396 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    public function rebuildListLeads(LeadList $leadList, $limit = 100, $maxLeads = false, ?OutputInterface $output = null): int
    {
        defined('MAUTIC_REBUILDING_LEAD_LISTS') || define('MAUTIC_REBUILDING_LEAD_LISTS', 1);

        $segmentId = $leadList->getId();

        $dtHelper = new DateTimeHelper();

        $batchLimiters = ['dateTime' => $dtHelper->toUtcString()];
        $list          = ['id' => $segmentId, 'filters' => $leadList->getFilters()];

        $this->dispatcher->dispatch(
            new ListPreProcessListEvent($list, false), LeadEvents::LIST_PRE_PROCESS_LIST
        );

Mautic · class Event

app/bundles/CampaignBundle/Entity/Event.php · 45–58 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Event implements ChannelInterface, UuidInterface
{
    use UuidTrait;
    use DateAddedTrait;

    public const TABLE_NAME = 'campaign_events';

    public const ENTITY_NAME = 'campaign_event';

    public const TYPE_DECISION  = 'decision';

    public const TYPE_ACTION    = 'action';

    public const TYPE_CONDITION = 'condition';

Mautic · class LeadEventLog

app/bundles/CampaignBundle/Entity/LeadEventLog.php · 15–28 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class LeadEventLog implements ChannelInterface, OptimisticLockInterface
{
    use OptimisticLockTrait;

    public const TABLE_NAME = 'campaign_lead_event_log';

    /**
     * @var string|null
     */
    private $id;

    /**
     * @var Event
     */

Mermaid

MIT。 项目仓库 · 许可入口

Mermaid · addVertex(

packages/mermaid/src/diagrams/flowchart/flowDb.ts · 188–201 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
  public addVertex(
    id: string,
    textObj: FlowText,
    type: FlowVertexTypeParam,
    style: string[],
    classes: string[],
    dir: string,
    props = {},
    metadata: any
  ) {
    if (!id || id.trim().length === 0) {
      return;
    }
    // Extract the metadata from the shapeData, the syntax for adding metadata for nodes and edges is the same

Mesa

Apache-2.0。 项目仓库 · 许可入口

Mesa · class Model

mesa/model.py · 44–57 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Model[A: Agent, S: Scenario](HasEmitters):
    """Base class for models in the Mesa ABM library.

    This class serves as a foundational structure for creating agent-based models.
    It includes the basic attributes and methods necessary for initializing and
    running a simulation model.

    Type Parameters:
        A: The agent type used in this model
        S: The scenario type used in this model

    Attributes:
        running: A boolean indicating if the model should continue running.
        time: the current simulation time.

MLflow

Apache-2.0(开源仓库)。 项目仓库 · 许可入口

MLflow · def get_model_version(

mlflow/tracking/client.py · 5162–5175 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def get_model_version(self, name: str, version: str) -> ModelVersion:
        """
        Converts the docstring args and returns to google style.

        Args:
            name: Name of the containing registered model.
            version: Version number as an integer of the model version.

        Returns:
            A single :py:class:`mlflow.entities.model_registry.ModelVersion` object.

        .. code-block:: python
            :caption: Example

MLflow · def get_run(

mlflow/tracking/client.py · 452–465 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def get_run(self, run_id: str) -> Run:
        """
        Fetch the run from backend store. The resulting :py:class:`Run <mlflow.entities.Run>`
        contains a collection of run metadata -- :py:class:`RunInfo <mlflow.entities.RunInfo>`,
        as well as a collection of run parameters, tags, and metrics --
        :py:class:`RunData <mlflow.entities.RunData>`. It also contains a collection of run
        inputs (experimental), including information about datasets used by the run --
        :py:class:`RunInputs <mlflow.entities.RunInputs>`. In the case where multiple metrics with
        the same key are logged for the run, the :py:class:`RunData <mlflow.entities.RunData>`
        contains the most recently logged value at the largest step for each metric.

        Args:
            run_id: Unique identifier for the run.

MLflow · def set_registered_model_alias(

mlflow/tracking/client.py · 5602–5615 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def set_registered_model_alias(self, name: str, alias: str, version: str) -> None:
        """
        Set a registered model alias pointing to a model version.

        Args:
            name: Registered model name.
            alias: Name of the alias. Note that aliases of the format ``v<number>``, such as
                ``v9`` and ``v42``, are reserved and cannot be set.
            version: Registered model version number.

        .. code-block:: Python
            :caption: Example

            import mlflow

MLflow · def log_metric(

mlflow/tracking/client.py · 2350–2363 行。 在 GitHub 查看源码 · 许可证与声明

上游配置与指引
    def log_metric(
        self,
        run_id: str,
        key: str,
        value: float,
        timestamp: int | None = None,
        step: int | None = None,
        synchronous: bool | None = None,
        dataset_name: str | None = None,
        dataset_digest: str | None = None,
        model_id: str | None = None,
    ) -> RunOperations | None:
        """
        Log a metric against the run ID.

NautilusTrader

LGPL-3.0(仓库标注)。 项目仓库 · 许可入口

NautilusTrader · pub struct RiskEngine

crates/risk/src/engine/mod.rs · 74–87 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
pub struct RiskEngine {
    clock: Rc<RefCell<dyn Clock>>,
    cache: Rc<RefCell<Cache>>,
    portfolio: Portfolio,
    trading_state: TradingState,
    config: RiskEngineConfig,
    max_notional_per_order: AHashMap<InstrumentId, Decimal>,
    throttler_submit: Throttler<TradingCommand, SubmitCommandFn>,
    throttler_modify: Throttler<ModifyOrder, ModifyOrderFn>,
    reservations: Vec<Reservation>,
    command_count: u64,
    event_count: u64,
}
  • // Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.

NautilusTrader · pub struct OrderBook

crates/model/src/orderbook/book.rs · 59–72 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
pub struct OrderBook {
    /// The instrument ID for the order book.
    pub instrument_id: InstrumentId,
    /// The order book type (MBP types will aggregate orders).
    pub book_type: BookType,
    /// The last event sequence number for the order book.
    pub sequence: u64,
    /// The timestamp of the last event applied to the order book.
    pub ts_last: UnixNanos,
    /// The current count of updates applied to the order book.
    pub update_count: u64,
    pub(crate) bids: BookLadder,
    pub(crate) asks: BookLadder,
}
  • // Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.

NautilusTrader · pub struct Quantity

crates/model/src/types/quantity.rs · 162–175 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
pub struct Quantity {
    pub(crate) raw: QuantityRaw,
    /// The number of decimal places, with a maximum of [`FIXED_PRECISION`].
    pub precision: u8,
}

impl Quantity {
    /// Creates a new [`Quantity`] instance with correctness checking.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `value` is invalid outside the representable range [0, `QUANTITY_MAX`].
    /// - `precision` is invalid outside the representable range [0, `FIXED_PRECISION`].
  • // Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.

NautilusTrader · pub enum OrderEventAny

crates/model/src/events/order/any.rs · 39–52 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
pub enum OrderEventAny {
    Initialized(OrderInitialized),
    Denied(OrderDenied),
    Emulated(OrderEmulated),
    Released(OrderReleased),
    Submitted(OrderSubmitted),
    Accepted(OrderAccepted),
    Rejected(OrderRejected),
    Canceled(OrderCanceled),
    Expired(OrderExpired),
    Triggered(OrderTriggered),
    PendingUpdate(OrderPendingUpdate),
    PendingCancel(OrderPendingCancel),
    ModifyDenied(OrderModifyDenied),
  • // Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.

NautilusTrader · pub struct OrderFilled

crates/model/src/events/order/filled.rs · 49–62 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
pub struct OrderFilled {
    /// The trader ID associated with the event.
    pub trader_id: TraderId,
    /// The strategy ID associated with the event.
    pub strategy_id: StrategyId,
    /// The instrument ID associated with the event.
    pub instrument_id: InstrumentId,
    /// The client order ID associated with the event.
    pub client_order_id: ClientOrderId,
    /// The venue order ID associated with the event.
    pub venue_order_id: VenueOrderId,
    /// The account ID associated with the event.
    pub account_id: AccountId,
    /// The trade match ID (assigned by the venue).
  • // Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.

NautilusTrader · pub struct CancelOrder

crates/common/src/messages/execution/cancel.rs · 36–49 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
pub struct CancelOrder {
    pub trader_id: TraderId,
    pub client_id: Option<ClientId>,
    pub strategy_id: StrategyId,
    pub instrument_id: InstrumentId,
    pub client_order_id: ClientOrderId,
    pub venue_order_id: Option<VenueOrderId>,
    pub command_id: UUID4,
    pub ts_init: UnixNanos,
    pub params: Option<Params>,
    #[builder(default)]
    pub correlation_id: Option<UUID4>,
    #[builder(default)]
    #[serde(default, skip_serializing_if = "Option::is_none")]
  • // Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.

NautilusTrader · pub trait ExecutionAlgorithmNative

crates/trading/src/algorithm/core.rs · 111–124 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
pub trait ExecutionAlgorithmNative: DataActorNative {
    /// Returns the execution algorithm core.
    fn exec_algorithm_core(&self) -> &ExecutionAlgorithmCore;

    /// Returns the mutable execution algorithm core.
    fn exec_algorithm_core_mut(&mut self) -> &mut ExecutionAlgorithmCore;

    /// Returns a clone of the reference-counted portfolio.
    ///
    /// # Panics
    ///
    /// Panics if the execution algorithm has not been registered.
    fn portfolio_rc(&self) -> Rc<RefCell<Portfolio>> {
        self.exec_algorithm_core()
  • // Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.

NetworkX

BSD-3-Clause。 项目仓库 · 许可入口

NetworkX · def add_edge(

networkx/classes/digraph.py · 676–689 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def add_edge(self, u_of_edge, v_of_edge, **attr):
        """Add an edge between u and v.

        The nodes u and v will be automatically added if they are
        not already in the graph.

        Edge attributes can be specified with keywords or by directly
        accessing the edge's attribute dictionary. See examples below.

        Parameters
        ----------
        u_of_edge, v_of_edge : nodes
            Nodes can be, for example, strings or numbers.
            Nodes must be hashable (and not None) Python objects.

NetworkX · def shortest_path(

networkx/algorithms/shortest_paths/generic.py · 43–56 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def shortest_path(G, source=None, target=None, weight=None, method="dijkstra"):
    """Compute shortest paths in the graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node, optional
        Starting node for path. If not specified, compute shortest
        paths for each possible starting node.

    target : node, optional
        Ending node for path. If not specified, compute shortest
        paths to all possible nodes.

NetworkX · def descendants(

networkx/algorithms/dag.py · 36–49 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def descendants(G, source):
    """Returns all nodes reachable from `source` in `G`.

    Parameters
    ----------
    G : NetworkX Graph
    source : node in `G`

    Returns
    -------
    set()
        The descendants of `source` in `G`

    Raises

NetworkX · def simple_cycles(

networkx/algorithms/cycles.py · 106–119 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def simple_cycles(G, length_bound=None):
    """Find simple cycles (elementary circuits) of a graph.

    A "simple cycle", or "elementary circuit", is a closed path where
    no node appears twice.  In a directed graph, two simple cycles are distinct
    if they are not cyclic permutations of each other.  In an undirected graph,
    two simple cycles are distinct if they are not cyclic permutations of each
    other nor of the other's reversal.

    Optionally, the cycles are bounded in length.  In the unbounded case, we use
    a nonrecursive, iterator/generator version of Johnson's algorithm [1]_.  In
    the bounded case, we use a version of the algorithm of Gupta and
    Suzumura [2]_. There may be better algorithms for some cases [3]_ [4]_ [5]_.

NetworkX · def topological_sort(

networkx/algorithms/dag.py · 312–325 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def topological_sort(G):
    """Returns a generator of nodes in topologically sorted order.

    A topological sort is a nonunique permutation of the nodes of a
    directed graph such that an edge from u to v implies that u
    appears before v in the topological sort order. This ordering is
    valid only if the graph has no directed cycles.

    Parameters
    ----------
    G : NetworkX digraph
        A directed acyclic graph (DAG)

    Yields

Open Policy Agent

Apache-2.0。 项目仓库 · 许可入口

Open Policy Agent · func (pq PreparedEvalQuery) Eval(

v1/rego/rego.go · 608–621 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func (pq PreparedEvalQuery) Eval(ctx context.Context, options ...EvalOption) (ResultSet, error) {
	ectx, finish, err := pq.newEvalContext(ctx, options)
	if err != nil {
		return nil, err
	}
	defer finish(ctx)

	ectx.compiledQuery = pq.r.compiledQueries[evalQueryType]

	return pq.r.eval(ctx, ectx)
}

// PreparedPartialQuery holds the prepared Rego state that has been pre-processed
// for partial evaluations.
  • // Copyright 2017 The OPA Authors. All rights reserved.

OpenBB

Apache-2.0(Open Data Platform,上游 README 与合同记录;供应商另约)。 项目仓库 · 许可入口

OpenBB · class Fetcher(

openbb_platform/core/openbb_core/provider/abstract/fetcher.py · 35–48 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Fetcher(Generic[Q, R]):
    """Abstract class for the fetcher."""

    # Tell query executor if credentials are required. Can be overridden by subclasses.
    require_credentials = True

    @staticmethod
    def transform_query(params: dict[str, Any]) -> Q:
        """Transform the params to the provider-specific query."""
        raise NotImplementedError

    @staticmethod
    async def aextract_data(query: Q, credentials: dict[str, str] | None) -> Any:
        """Asynchronously extract the data from the provider."""

OpenFGA

Apache-2.0。 项目仓库 · 许可入口

OpenFGA · func (s *Server) Check(

pkg/server/check.go · 37–50 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func (s *Server) Check(ctx context.Context, req *openfgav1.CheckRequest) (*openfgav1.CheckResponse, error) {
	const methodName = "check"

	startTime := time.Now()

	tk := req.GetTupleKey()
	ctx, span := tracer.Start(ctx, apimethod.Check.String(), trace.WithAttributes(
		attribute.KeyValue{Key: "store_id", Value: attribute.StringValue(req.GetStoreId())},
		attribute.KeyValue{Key: "object", Value: attribute.StringValue(tk.GetObject())},
		attribute.KeyValue{Key: "relation", Value: attribute.StringValue(tk.GetRelation())},
		attribute.KeyValue{Key: "user", Value: attribute.StringValue(tk.GetUser())},
		attribute.KeyValue{Key: "consistency", Value: attribute.StringValue(req.GetConsistency().String())},
	))
	defer span.End()

OpenFGA · func (s *Server) Write(

pkg/server/write.go · 26–39 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func (s *Server) Write(ctx context.Context, req *openfgav1.WriteRequest) (*openfgav1.WriteResponse, error) {
	start := time.Now()

	ctx, span := tracer.Start(ctx, apimethod.Write.String(), trace.WithAttributes(
		attribute.String("store_id", req.GetStoreId()),
	))
	defer span.End()

	if !validator.RequestIsValidatedFromContext(ctx) {
		if err := req.Validate(); err != nil {
			return nil, status.Error(codes.InvalidArgument, err.Error())
		}
	}

OpenLineage

Apache-2.0。 项目仓库 · 许可入口

OpenLineage · class RunEvent

client/python/src/openlineage/client/run.py · 102–115 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class RunEvent(RedactMixin):
    eventType: RunState = attr.ib(validator=attr.validators.in_(list(RunState)))  # noqa:  N815
    eventTime: str = attr.ib()  # noqa:  N815
    run: Run = attr.ib()
    job: Job = attr.ib()
    producer: str = attr.ib()
    inputs: list[Dataset] | None = attr.ib(factory=list)
    outputs: list[Dataset] | None = attr.ib(factory=list)
    schemaURL: str = attr.ib(default=SCHEMA_URL)  # noqa: N815

    _skip_redact: ClassVar[list[str]] = ["eventType", "eventTime", "producer", "schemaURL"]

    @eventTime.validator
    def check(self, attribute: str, value: str) -> None:  # noqa: ARG002
  • # Copyright 2018-2026 contributors to the OpenLineage project
  • # SPDX-License-Identifier: Apache-2.0

OpenProject

GPL-3.0(社区代码)。 项目仓库 · 许可入口

OpenProject · class Journal

app/models/journal.rb · 30–43 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Journal < ApplicationRecord
  self.table_name = "journals"
  self.ignored_columns += ["activity_type"]

  include ::JournalChanges
  include ::JournalFormatter
  include ::Acts::Journalized::FormatHooks
  include Journal::Timestamps
  include Reactable

  # Inline attachments for Journal#notes aka comments
  acts_as_attachable view_permission: :view_work_packages,
                     add_on_new_permission: :add_work_package_comments,
                     add_on_persisted_permission: :edit_own_work_package_comments,
  • #-- copyright
  • # Copyright (C) the OpenProject GmbH
  • # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
  • # Copyright (C) 2006-2013 Jean-Philippe Lang
  • # Copyright (C) 2010-2013 the ChiliProject Team
  • # See COPYRIGHT and LICENSE files for more details.

OpenProject · class WorkPackage

app/models/work_package.rb · 30–43 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class WorkPackage < ApplicationRecord
  include WorkPackage::SemanticIdentifier
  include WorkPackage::Validations
  include WorkPackage::SchedulingRules
  include WorkPackage::StatusTransitions
  include WorkPackage::AskBeforeDestruction
  include WorkPackage::TimeEntriesCleaner
  include WorkPackage::Ancestors
  include WorkPackage::Automatable
  include WorkPackage::Hooks
  include WorkPackage::Origin
  # Must stay above WorkPackage::Journalized: its after_save persists the
  # version rows that the journal snapshot then reads.
  include WorkPackage::Versions
  • #-- copyright
  • # Copyright (C) the OpenProject GmbH
  • # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
  • # Copyright (C) 2006-2013 Jean-Philippe Lang
  • # Copyright (C) 2010-2013 the ChiliProject Team
  • # See COPYRIGHT and LICENSE files for more details.

OpenProject · class Relation

app/models/relation.rb · 30–43 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Relation < ApplicationRecord
  belongs_to :from, class_name: "WorkPackage"
  belongs_to :to, class_name: "WorkPackage"

  TYPE_RELATES      = "relates"
  TYPE_PRECEDES     = "precedes"
  TYPE_FOLLOWS      = "follows"
  TYPE_BLOCKS       = "blocks"
  TYPE_BLOCKED      = "blocked"
  TYPE_DUPLICATES   = "duplicates"
  TYPE_DUPLICATED   = "duplicated"
  TYPE_INCLUDES     = "includes"
  TYPE_PARTOF       = "partof"
  TYPE_REQUIRES     = "requires"
  • #-- copyright
  • # Copyright (C) the OpenProject GmbH
  • # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
  • # Copyright (C) 2006-2013 Jean-Philippe Lang
  • # Copyright (C) 2010-2013 the ChiliProject Team
  • # See COPYRIGHT and LICENSE files for more details.

OpenProject · class WorkPackages::SetAttributesService

app/services/work_packages/set_attributes_service.rb · 30–43 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class WorkPackages::SetAttributesService < BaseServices::SetAttributes
  include Attachments::SetReplacements

  private

  def validate_and_result
    result = super
    # restore identifier for error messages
    work_package.restore_identifier_after_failed_move unless result.success?
    result
  end

  def set_attributes(attributes)
    validate_custom_fields = attributes.delete(:validate_custom_fields)
  • #-- copyright
  • # Copyright (C) the OpenProject GmbH
  • # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
  • # Copyright (C) 2006-2013 Jean-Philippe Lang
  • # Copyright (C) 2010-2013 the ChiliProject Team
  • # See COPYRIGHT and LICENSE files for more details.

OpenRefine

BSD-3-Clause(主项目)。 项目仓库 · 许可入口

OpenRefine · public class BinningClusterer

modules/core/src/main/java/com/google/refine/clustering/binning/BinningClusterer.java · 65–78 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
public class BinningClusterer extends Clusterer {

    public static class BinningClustererConfig extends ClustererConfig {

        @JsonIgnore
        private String _keyerName;
        @JsonIgnore
        private Keyer _keyer;
        @JsonIgnore
        private BinningParameters _parameters = null;

        @JsonIgnore
        public Keyer getKeyer() {
            return _keyer;
  • Copyright 2010, Google Inc.
  • * Redistributions of source code must retain the above copyright
  • copyright notice, this list of conditions and the following disclaimer
  • THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  • A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT

OpenTelemetry Python

Apache-2.0。 项目仓库 · 许可入口

OpenTelemetry Python · def start_span(

opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py · 1219–1232 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def start_span(  # pylint: disable=too-many-locals
        self,
        name: str,
        context: context_api.Context | None = None,
        kind: trace_api.SpanKind = trace_api.SpanKind.INTERNAL,
        attributes: types.Attributes = None,
        links: Sequence[trace_api.Link] | None = (),
        start_time: int | None = None,
        record_exception: bool = True,
        set_status_on_exception: bool = True,
    ) -> trace_api.Span:
        links = links or ()
        parent_span_context = trace_api.get_current_span(context).get_span_context()
  • # Copyright The OpenTelemetry Authors
  • # SPDX-License-Identifier: Apache-2.0

OpenTimelineIO

Apache-2.0,见附加说明。 项目仓库 · 许可入口

OpenTimelineIO · class OTIO_API_TYPE Clip

src/opentimelineio/clip.h · 15–28 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class OTIO_API_TYPE Clip : public Item
{
public:
    /// @brief The default media within a clip.
    static char constexpr default_media_key[] = "DEFAULT_MEDIA";

    /// @brief This struct provides the Clip schema.
    struct Schema
    {
        static auto constexpr name   = "Clip";
        static int constexpr version = 2;
    };

    using Parent = Item;
  • // SPDX-License-Identifier: Apache-2.0
  • // Copyright Contributors to the OpenTimelineIO project

OpenTimelineIO · class OTIO_API_TYPE Marker

src/opentimelineio/marker.h · 17–30 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class OTIO_API_TYPE Marker : public SerializableObjectWithMetadata
{
public:

    /// @brief This struct provides the Marker schema.
    struct Schema
    {
        static auto constexpr name   = "Marker";
        static int constexpr version = 3;
    };

    using Parent = SerializableObjectWithMetadata;

    /// @brief Create a new marker.
  • // SPDX-License-Identifier: Apache-2.0
  • // Copyright Contributors to the OpenTimelineIO project

OpenTimelineIO · class OTIO_API_TYPE Track

src/opentimelineio/track.h · 14–27 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class OTIO_API_TYPE Track : public Composition
{
public:
    /// @brief This struct provides the base set of kinds of tracks.
    struct Kind
    {
        static auto constexpr video = "Video";
        static auto constexpr audio = "Audio";
    };

    /// @brief This enumeration provides the neighbor gap policy.
    enum NeighborGapPolicy
    {
        never              = 0,
  • // SPDX-License-Identifier: Apache-2.0
  • // Copyright Contributors to the OpenTimelineIO project

OpenTimelineIO · class OTIO_API_TYPE Transition

src/opentimelineio/transition.h · 13–26 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class OTIO_API_TYPE Transition : public Composable
{
public:
    /// @brief This struct provides base set of transitions.
    struct Type
    {
        static auto constexpr SMPTE_Dissolve = "SMPTE_Dissolve";
        static auto constexpr Custom         = "Custom_Transition";
    };

    /// @brief This struct provides the Transition schema.
    struct Schema
    {
        static auto constexpr name   = "Transition";
  • // SPDX-License-Identifier: Apache-2.0
  • // Copyright Contributors to the OpenTimelineIO project

OpenTimelineIO · def write_to_file(

src/py-opentimelineio/opentimelineio/adapters/__init__.py · 177–190 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def write_to_file(
    input_otio,
    filepath,
    adapter_name=None,
    **adapter_argument_map
):
    """Write input_otio to filepath using adapter_name.

    If adapter_name is None, infer the adapter_name to use based on the
    filepath.

    .. code-block:: python
       :caption: Example
  • # SPDX-License-Identifier: Apache-2.0
  • # Copyright Contributors to the OpenTimelineIO project

OpenTripPlanner

LGPL-3.0,局部按许可头。 项目仓库 · 许可入口

OpenTripPlanner · public RoutingResponse route()

application/src/main/java/org/opentripplanner/routing/algorithm/RoutingWorker.java · 193–206 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
  public RoutingResponse route() {
    OTPRequestTimeoutException.checkForTimeout();
    this.debugTimingAggregator.finishedPrecalculating();
    var result = RoutingResult.empty();

    try (var temporaryVerticesContainer = new TemporaryVerticesContainer()) {
      this.currentLinkingContext = createLinkingContext(temporaryVerticesContainer);

      if (OTPFeature.ParallelRouting.isOn()) {
        // TODO: This is not using {@link OtpRequestThreadFactory} which means we do not get
        //       log-trace-parameters-propagation and graceful timeout handling here.
        try {
          var r1 = CompletableFuture.supplyAsync(() -> routeDirectStreet());
          var r2 = CompletableFuture.supplyAsync(() -> routeDirectFlex());

OpenTripPlanner · class PollingTripUpdater

application/src/main/java/org/opentripplanner/updater/trip/gtfs/updater/http/PollingTripUpdater.java · 23–36 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
public class PollingTripUpdater extends PollingGraphUpdater<TransitRealTimeUpdateContext> {

  private static final Logger LOG = LoggerFactory.getLogger(PollingTripUpdater.class);

  private final HttpTripUpdateSource updateSource;
  private final GtfsRealTimeTripUpdateAdapter adapter;

  /**
   * Feed id that is used for the trip ids in the TripUpdates
   */
  private final String feedId;

  /**
   * Defines when delays are propagated to next stops.

OpenTripPlanner · class RouteRequest

application/src/main/java/org/opentripplanner/routing/api/request/RouteRequest.java · 41–54 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
public class RouteRequest implements Serializable {

  private static final Logger LOG = LoggerFactory.getLogger(RouteRequest.class);

  private static final int DEFAULT_NUM_ITINERARIES = 50;
  private static final long NOW_THRESHOLD_SEC = durationInSeconds("15h");

  private static final RouteRequest DEFAULT = new RouteRequest();

  private final GenericLocation from;
  private final GenericLocation to;
  private final List<ViaLocation> via;
  private final Instant dateTime;
  private final boolean arriveBy;

OR-Tools

Apache-2.0。 项目仓库 · 许可入口

OR-Tools · def add_cumulative(

ortools/sat/python/cp_model.py · 1476–1489 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def add_cumulative(
        self,
        intervals: Iterable[IntervalVar],
        demands: Iterable[LinearExprT],
        capacity: LinearExprT,
    ) -> Constraint:
        """Adds Cumulative(intervals, demands, capacity).

        This constraint enforces that:

            for all t:
              sum(demands[i]
                if (start(intervals[i]) <= t < end(intervals[i])) and
                (intervals[i] is present)) <= capacity
  • # Copyright 2010-2025 Google LLC

OR-Tools · def solve(

ortools/sat/python/cp_model.py · 1785–1798 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def solve(
        self,
        model: CpModel,
        solution_callback: Optional["CpSolverSolutionCallback"] = None,
    ) -> cmh.CpSolverStatus:
        """Solves a problem and passes each solution to the callback if not null."""
        with self.__lock:
            self.__solve_wrapper = cmh.SolveWrapper()

        self.__solve_wrapper.set_parameters(self.parameters)
        if solution_callback is not None:
            self.__solve_wrapper.add_solution_callback(solution_callback)

        if self.log_callback is not None:
  • # Copyright 2010-2025 Google LLC

OR-Tools · def main(

ortools/routing/samples/vrp_time_windows.py · 112–125 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def main() -> None:
    """Solve the VRP with time windows."""
    # Instantiate the data problem.
    # [START data]
    data = create_data_model()
    # [END data]

    # Create the routing index manager.
    # [START index_manager]
    manager = routing.IndexManager(
        len(data["time_matrix"]), data["num_vehicles"], data["depot"]
    )
    # [END index_manager]
  • # Copyright 2010-2025 Google LLC

Pandera

MIT。 项目仓库 · 许可入口

Pandera · def validate(

pandera/api/pandas/container.py · 127–140 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def validate(
        self,
        check_obj: pd.DataFrame,
        head: int | None = None,
        tail: int | None = None,
        sample: int | None = None,
        random_state: int | None = None,
        lazy: bool = False,
        inplace: bool = False,
    ) -> pd.DataFrame:
        """Validate a DataFrame based on the schema specification.

        :param pd.DataFrame check_obj: the dataframe to be validated.
        :param head: validate the first n rows. Rows overlapping with `tail` or

Pandera · class Check(

pandera/api/checks.py · 18–31 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Check(BaseCheck):
    """Check a data object for certain properties."""

    def __init__(
        self,
        check_fn: Callable,
        groups: Union[str, list[Hashable]] | None = None,
        groupby: Union[str, list[str], Callable] | None = None,
        ignore_na: bool = True,
        element_wise: bool = False,
        native: bool = True,
        name: str | None = None,
        error: str | None = None,
        raise_warning: bool = False,

Pandoc

GPL-2.0-or-later(须按拟用构建核)。 项目仓库 · 许可入口

Pandoc · optToOutputSettings scriptingEngine opts = do

src/Text/Pandoc/App/OutputSettings.hs · 66–79 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
optToOutputSettings scriptingEngine opts = do
  let outputFile = fromMaybe "-" (optOutputFile opts)

  when (optDumpArgs opts) . liftIO $ do
    UTF8.hPutStrLn stdout (T.pack outputFile)
    mapM_ (UTF8.hPutStrLn stdout . T.pack) (fromMaybe [] $ optInputFiles opts)
    exitSuccess

  epubMetadata <- traverse readUtf8File $ optEpubMetadata opts

  let pdfOutput = map toLower (takeExtension outputFile) == ".pdf" ||
                  optTo opts == Just "pdf"
  let defaultOutput = "html"
  defaultOutputFlavor <- parseFlavoredFormat defaultOutput
  • Copyright : Copyright (C) 2006-2024 John MacFarlane

Penpot

MPL-2.0。 项目仓库 · 许可入口

Penpot · defn add-shape

frontend/src/app/main/data/workspace/shapes.cljs · 287–300 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
(defn add-shape
  ([shape]
   (add-shape shape {}))
  ([shape {:keys [no-select? no-update-layout? skip-edition?]}]

   (cts/check-shape shape)

   (ptk/reify ::add-shape
     ptk/UpdateEvent
     (update [_ state]
       (cond-> state
         (and (cfh/text-shape? shape) (nil? (:content shape)))
         (update :workspace-new-text-shapes (fnil conj #{}) (:id shape))))
  • ;; Copyright (c) KALEIDOS SUBSIDIARY SL

Penpot · (defn add-interaction

frontend/src/app/main/data/workspace/interactions.cljs · 146–159 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
(defn add-interaction
  [page-id shape-id interaction]
  (ptk/reify ::add-interaction
    ptk/WatchEvent
    (watch [_ state _]
      (let [page-id  (or page-id (:current-page-id state))]
        (rx/of (dwsh/update-shapes [shape-id]
                                   (fn [shape]
                                     (cls/add-new-interaction shape interaction))
                                   {:page-id page-id})

               (when (:destination interaction)
                 (dwsh/update-shapes [(:destination interaction)]
                                     cls/show-in-viewer
  • ;; Copyright (c) KALEIDOS SUBSIDIARY SL

Platypus

GPL-3.0。 项目仓库 · 许可入口

Platypus · class ParetoDominance

platypus/core.py · 780–793 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class ParetoDominance(Dominance):
    """Pareto dominance with constraints.

    If either solution violates constraints, then the solution with a smaller
    constraint violation is preferred.  If both solutions are feasible, then
    Pareto dominance is used to select the preferred solution.
    """

    def __init__(self):
        super().__init__()

    def compare(self, solution1, solution2):
        problem = solution1.problem
  • # Copyright 2015-2024 David Hadka

Portfolio

Apache-2.0(仓库标注)。 项目仓库 · 许可入口

Portfolio · export async function GET(

app/api/deals/route.ts · 8–21 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
export async function GET(req: NextRequest) {
  const supabase = await createClient()
  const { data: { user } } = await supabase.auth.getUser()
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const admin = createAdminClient()
  const { data: membership } = await admin
    .from('fund_members')
    .select('fund_id')
    .eq('user_id', user.id)
    .maybeSingle()

  if (!membership) return NextResponse.json({ error: 'No fund found' }, { status: 403 })

Portfolio · export async function GET(

app/api/portfolio/investments/route.ts · 18–31 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
export async function GET(req: NextRequest) {
  const supabase = await createClient()
  const { data: { user } } = await supabase.auth.getUser()
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

  const admin = createAdminClient()

  const { data: membership } = await admin
    .from('fund_members')
    .select('fund_id, role')
    .eq('user_id', user.id)
    .maybeSingle()

  if (!membership) return NextResponse.json({ error: 'No fund found' }, { status: 403 })

Pyomo

BSD-3-Clause 上游标注。 项目仓库 · 许可入口

Pyomo · class Constraint(

pyomo/core/base/constraint.py · 563–576 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Constraint(ActiveIndexedComponent):
    """
    This modeling component defines a constraint expression using a
    rule function.

    Constructor arguments:
        expr
            A Pyomo expression for this constraint
        rule
            A function that is used to construct constraint expressions
        name
            A name for this component
        doc
            A text string describing this component
  • # Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC

Pyomo · class Objective(

pyomo/core/base/objective.py · 212–225 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Objective(ActiveIndexedComponent):
    """
    This modeling component defines an objective expression.

    Note that this is a subclass of NumericValue to allow
    objectives to be used as part of expressions.

    Constructor arguments:
        expr
            A Pyomo expression for this objective
        rule
            A function that is used to construct objective expressions
        sense
            Indicate whether minimizing (the default) or maximizing
  • # Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC

PyPortfolioOpt

MIT。 项目仓库 · 许可入口

PyPortfolioOpt · def efficient_risk(

pypfopt/efficient_frontier/efficient_cvar.py · 201–214 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def efficient_risk(self, target_cvar, market_neutral=False):
        """
        Maximise return for a target CVaR.
        The resulting portfolio will have a CVaR less than the target
        (but not guaranteed to be equal).

        Parameters
        ----------
        target_cvar : float
            the desired conditional value at risk of the resulting portfolio.
        market_neutral : bool, optional
            whether the portfolio should be market neutral (weights sum to zero),
            defaults to False. Requires negative lower weight bound.

PyPortfolioOpt · class EfficientCVaR

pypfopt/efficient_frontier/efficient_cvar.py · 15–28 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class EfficientCVaR(EfficientFrontier):
    """
    The EfficientCVaR class allows for optimization along the mean-CVaR frontier, using the
    formulation of Rockafellar and Ursayev (2001).

    Instance variables:

    - Inputs:

        - ``n_assets`` - int
        - ``tickers`` - str list
        - ``bounds`` - float tuple OR (float tuple) list
        - ``returns`` - pd.DataFrame
        - ``expected_returns`` - np.ndarray

pytest

MIT。 项目仓库 · 许可入口

pytest · def parametrize(

src/_pytest/python.py · 1387–1400 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def parametrize(
        self,
        argnames: str | Sequence[str],
        argvalues: Iterable[ParameterSet | Sequence[object] | object],
        *,
        indirect: bool | Sequence[str] = False,
        ids: Iterable[object | None] | Callable[[Any], object | None] | None = None,
        scope: ScopeName | None = None,
        _param_mark: Mark | None = None,
    ) -> None:
        """Add new invocations to the underlying test function using the list
        of argvalues for the given argnames. Parametrization is performed
        during the collection phase. If you need to setup expensive resources
        see about setting ``indirect`` to do it at test setup time instead.

python-jsonschema

MIT。 项目仓库 · 许可入口

python-jsonschema · def iter_errors(self, instance

jsonschema/validators.py · 352–365 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
        def iter_errors(self, instance, _schema=None):
            if _schema is not None:
                warnings.warn(
                    (
                        "Passing a schema to Validator.iter_errors "
                        "is deprecated and will be removed in a future "
                        "release. Call validator.evolve(schema=new_schema)."
                        "iter_errors(...) instead."
                    ),
                    DeprecationWarning,
                    stacklevel=2,
                )
                validators = [
                    (self.VALIDATORS[k], k, v)

PyXIRR

Unlicense,上游仓库标注。 项目仓库 · 许可入口

PyXIRR · fn xnpv<'

src/lib.rs · 96–109 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
fn xnpv<'a>(
    py: Python<'a>,
    rate: Arg<f64, 'a>,
    dates: &Bound<PyAny>,
    amounts: Option<&Bound<PyAny>>,
    silent: Option<bool>,
    day_count: Option<PyDayCount>,
) -> PyResult<Option<Arg<f64, 'a>>> {
    let (dates, amounts) = conversions::extract_payments(dates, amounts)?;
    let day_count = day_count.map(|x| x.try_into()).transpose()?;
    let silent = silent.unwrap_or(false);

    match rate {
        Arg::Scalar(rate) => {

Qlib

MIT。 项目仓库 · 许可入口

Qlib · class LocalExpressionProvider(

qlib/data/data.py · 835–848 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class LocalExpressionProvider(ExpressionProvider):
    """Local expression data provider class

    Provide expression data from local data source.
    """

    def __init__(self, time2idx=True):
        super().__init__()
        self.time2idx = time2idx

    def expression(self, instrument, field, start_time=None, end_time=None, freq="day"):
        expression = self.get_expression_instance(field)
        start_time = time_to_slc_point(start_time)
        end_time = time_to_slc_point(end_time)
  • # Copyright (c) Microsoft Corporation.

Qlib · class Ref(

qlib/data/ops.py · 781–794 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Ref(Rolling):
    """Feature Reference

    Parameters
    ----------
    feature : Expression
        feature instance
    N : int
        N = 0, retrieve the first data; N > 0, retrieve data of N periods ago; N < 0, future data

    Returns
    ----------
    Expression
        a feature instance with target reference
  • # Copyright (c) Microsoft Corporation.

Qlib · class Mean(

qlib/data/ops.py · 827–840 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Mean(Rolling):
    """Rolling Mean (MA)

    Parameters
    ----------
    feature : Expression
        feature instance
    N : int
        rolling window size

    Returns
    ----------
    Expression
        a feature instance with rolling average
  • # Copyright (c) Microsoft Corporation.

Qlib · class EMA(

qlib/data/ops.py · 1349–1362 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class EMA(Rolling):
    """Rolling Exponential Mean (EMA)

    Parameters
    ----------
    feature : Expression
        feature instance
    N : int, float
        rolling window size

    Returns
    ----------
    Expression
        a feature instance with regression r-value square of given window
  • # Copyright (c) Microsoft Corporation.

Qlib · class Std(

qlib/data/ops.py · 867–880 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Std(Rolling):
    """Rolling Std

    Parameters
    ----------
    feature : Expression
        feature instance
    N : int
        rolling window size

    Returns
    ----------
    Expression
        a feature instance with rolling std
  • # Copyright (c) Microsoft Corporation.

Qlib · class Max(

qlib/data/ops.py · 951–964 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Max(Rolling):
    """Rolling Max

    Parameters
    ----------
    feature : Expression
        feature instance
    N : int
        rolling window size

    Returns
    ----------
    Expression
        a feature instance with rolling max
  • # Copyright (c) Microsoft Corporation.

Qlib · class Min(

qlib/data/ops.py · 999–1012 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Min(Rolling):
    """Rolling Min

    Parameters
    ----------
    feature : Expression
        feature instance
    N : int
        rolling window size

    Returns
    ----------
    Expression
        a feature instance with rolling min
  • # Copyright (c) Microsoft Corporation.

Qlib · class Corr(

qlib/data/ops.py · 1467–1480 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Corr(PairRolling):
    """Rolling Correlation

    Parameters
    ----------
    feature_left : Expression
        feature instance
    feature_right : Expression
        feature instance
    N : int
        rolling window size

    Returns
    ----------
  • # Copyright (c) Microsoft Corporation.

Qlib · class Rolling(

qlib/data/ops.py · 713–726 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Rolling(ExpressionOps):
    """Rolling Operator
    The meaning of rolling and expanding is the same in pandas.
    When the window is set to 0, the behaviour of the operator should follow `expanding`
    Otherwise, it follows `rolling`

    Parameters
    ----------
    feature : Expression
        feature instance
    N : int
        rolling window size
    func : str
        rolling method
  • # Copyright (c) Microsoft Corporation.

Qlib · class LocalInstrumentProvider(

qlib/data/data.py · 680–693 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class LocalInstrumentProvider(InstrumentProvider, ProviderBackendMixin):
    """Local instrument data provider class

    Provide instrument data from local data source.
    """

    def __init__(self, backend={}) -> None:
        super().__init__()
        self.backend = backend

    def _load_instruments(self, market, freq):
        return self.backend_obj(market=market, freq=freq).data

    def list_instruments(self, instruments, start_time=None, end_time=None, freq="day", as_list=False):
  • # Copyright (c) Microsoft Corporation.

Qlib · class Rank(

qlib/data/ops.py · 1133–1146 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Rank(Rolling):
    """Rolling Rank (Percentile)

    Parameters
    ----------
    feature : Expression
        feature instance
    N : int
        rolling window size

    Returns
    ----------
    Expression
        a feature instance with rolling rank
  • # Copyright (c) Microsoft Corporation.

Qlib · class CSZScoreNorm

qlib/data/dataset/processor.py · 300–313 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class CSZScoreNorm(Processor):
    """Cross Sectional ZScore Normalization"""

    def __init__(self, fields_group=None, method="zscore"):
        self.fields_group = fields_group
        if method == "zscore":
            self.zscore_func = zscore
        elif method == "robust":
            self.zscore_func = robust_zscore
        else:
            raise NotImplementedError(f"This type of input is not supported")

    def __call__(self, df):
        # try not modify original dataframe
  • # Copyright (c) Microsoft Corporation.

Qlib · class Alpha158(

qlib/contrib/data/handler.py · 98–111 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Alpha158(DataHandlerLP):
    def __init__(
        self,
        instruments="csi500",
        start_time=None,
        end_time=None,
        freq="day",
        infer_processors=[],
        learn_processors=_DEFAULT_LEARN_PROCESSORS,
        fit_start_time=None,
        fit_end_time=None,
        process_type=DataHandlerLP.PTYPE_A,
        filter_pipe=None,
        inst_processors=None,
  • # Copyright (c) Microsoft Corporation.

Qlib · def backtest(

qlib/backtest/__init__.py · 217–230 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def backtest(
    start_time: Union[pd.Timestamp, str],
    end_time: Union[pd.Timestamp, str],
    strategy: Union[str, dict, object, Path],
    executor: Union[str, dict, object, Path],
    benchmark: str = "SH000300",
    account: Union[float, int, dict] = 1e9,
    exchange_kwargs: dict = {},
    pos_type: str = "Position",
) -> Tuple[PORT_METRIC, INDICATOR_METRIC]:
    """initialize the strategy and executor, then backtest function for the interaction of the outermost strategy and
    executor in the nested decision execution

    Parameters
  • # Copyright (c) Microsoft Corporation.

QuantLib

Modified BSD,上游许可正文。 项目仓库 · 许可入口

QuantLib · CashFlows::npv(

ql/cashflows/cashflows.cpp · 420–433 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    Real CashFlows::npv(const Leg& leg,
                        const YieldTermStructure& discountCurve,
                        const std::optional<bool>& includeSettlementDateFlows,
                        Date settlementDate,
                        Date npvDate) {

        if (leg.empty())
            return 0.0;

        if (settlementDate == Date())
            settlementDate = Settings::instance().evaluationDate();

        if (npvDate == Date())
            npvDate = settlementDate;
  • Copyright (C) 2005, 2006 StatPro Italia srl
  • Copyright (C) 2005 Charles Whitmore
  • Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012 Ferdinando Ametrano
  • Copyright (C) 2008 Toyin Akin

QuantLib · class Calendar

ql/time/calendar.hpp · 61–74 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    class Calendar {
      protected:
        //! abstract base class for calendar implementations
        class Impl {
          public:
            virtual ~Impl() = default;
            virtual std::string name() const = 0;
            virtual bool isBusinessDay(const Date&) const = 0;
            virtual bool isWeekend(Weekday) const = 0;
            std::set<Date> addedHolidays, removedHolidays;
        };
        ext::shared_ptr<Impl> impl_;
      public:
        /*! The default constructor returns a calendar with a null
  • Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
  • Copyright (C) 2003, 2004, 2005, 2006, 2007 StatPro Italia srl
  • Copyright (C) 2006 Piter Dias
  • Copyright (C) 2020 Leonardo Arcari
  • Copyright (C) 2020 Kline s.r.l.

QuantLib · class Schedule

ql/time/schedule.hpp · 40–53 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    class Schedule {
      public:
        /*! constructor that takes any list of dates, and optionally
            meta information that can be used by client classes. Note
            that neither the list of dates nor the meta information is
            checked for plausibility in any sense. */
        Schedule(
            const std::vector<Date>&,
            Calendar calendar = NullCalendar(),
            BusinessDayConvention convention = Unadjusted,
            const std::optional<BusinessDayConvention>& terminationDateConvention = std::nullopt,
            const std::optional<Period>& tenor = std::nullopt,
            const std::optional<DateGeneration::Rule>& rule = std::nullopt,
            const std::optional<bool>& endOfMonth = std::nullopt,
  • Copyright (C) 2006, 2007, 2011 Ferdinando Ametrano
  • Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
  • Copyright (C) 2003, 2004, 2005, 2006, 2009 StatPro Italia srl

QuantLib · BondFunctions::yield(

ql/pricingengines/bond/bondfunctions.cpp · 373–386 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    Rate BondFunctions::yield(const Bond& bond,
                              Bond::Price price,
                              const DayCounter& dayCounter,
                              Compounding compounding,
                              Frequency frequency,
                              Date settlement,
                              Real accuracy,
                              Size maxIterations,
                              Rate guess) {
        NewtonSafe solver;
        solver.setMaxEvaluations(maxIterations);
        return yield<NewtonSafe>(solver, bond, price, dayCounter,
                                 compounding, frequency, settlement,
                                 accuracy, guess);
  • Copyright (C) 2009 Nathan Abbott
  • Copyright (C) 2007, 2008, 2009, 2010 Ferdinando Ametrano
  • Copyright (C) 2007 Chiara Fornarola
  • Copyright (C) 2008 Simon Ibbotson
  • Copyright (C) 2004 M-Dimension Consulting Inc.
  • Copyright (C) 2005, 2006, 2007, 2008, 2009 StatPro Italia srl
  • Copyright (C) 2004 Jeff Yu

QuantLib · class FixedRateBond

ql/instruments/bonds/fixedratebond.hpp · 46–59 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    class FixedRateBond : public Bond {
      public:
        //! simple annual compounding coupon rates
        FixedRateBond(Natural settlementDays,
                      Real faceAmount,
                      Schedule schedule,
                      const std::vector<Rate>& coupons,
                      const DayCounter& accrualDayCounter,
                      BusinessDayConvention paymentConvention = Following,
                      Real redemption = 100.0,
                      const Date& issueDate = Date(),
                      const Calendar& paymentCalendar = Calendar(),
                      const Period& exCouponPeriod = Period(),
                      const Calendar& exCouponCalendar = Calendar(),
  • Copyright (C) 2004 Jeff Yu
  • Copyright (C) 2004 M-Dimension Consulting Inc.
  • Copyright (C) 2005 StatPro Italia srl
  • Copyright (C) 2007, 2008, 2010 Ferdinando Ametrano
  • Copyright (C) 2009 Piter Dias

QuantLib · class PiecewiseYieldCurve

ql/termstructures/yield/piecewiseyieldcurve.hpp · 64–77 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    class PiecewiseYieldCurve
        : public Traits::template curve<Interpolator>::type,
          public LazyObject,
          public MultiCurveBootstrapProvider,
          public CurveJacobianNodeProvider {
      private:
        typedef typename Traits::template curve<Interpolator>::type base_curve;
        typedef PiecewiseYieldCurve<Traits,Interpolator,Bootstrap> this_curve;
      public:
        typedef Traits traits_type;
        typedef Interpolator interpolator_type;
        typedef Bootstrap<this_curve> bootstrap_type;

        //! \name Constructors
  • Copyright (C) 2005, 2006, 2007, 2008 StatPro Italia srl
  • Copyright (C) 2007, 2008, 2009 Ferdinando Ametrano
  • Copyright (C) 2007 Chris Kenyon
  • Copyright (C) 2026 Kyrylo Protsenko

QuantLib · AnalyticEuropeanEngine::calculate(

ql/pricingengines/vanilla/analyticeuropeanengine.cpp · 42–55 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    void AnalyticEuropeanEngine::calculate() const {

        // if the discount curve is not specified, we default to the
        // risk free rate curve embedded within the GBM process
        ext::shared_ptr<YieldTermStructure> discountPtr = 
            discountCurve_.empty() ? 
            process_->riskFreeRate().currentLink() :
            discountCurve_.currentLink();

        QL_REQUIRE(arguments_.exercise->type() == Exercise::European,
                   "not an European option");

        ext::shared_ptr<StrikedTypePayoff> payoff =
            ext::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);
  • Copyright (C) 2003 Ferdinando Ametrano
  • Copyright (C) 2007 StatPro Italia srl

QuantLib · BinomialVanillaEngine<T>::calculate(

ql/pricingengines/vanilla/binomialengine.hpp · 76–89 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    void BinomialVanillaEngine<T>::calculate() const {

        DayCounter rfdc  = process_->riskFreeRate()->dayCounter();
        DayCounter divdc = process_->dividendYield()->dayCounter();
        DayCounter voldc = process_->blackVolatility()->dayCounter();
        Calendar volcal = process_->blackVolatility()->calendar();

        Real s0 = process_->stateVariable()->value();
        QL_REQUIRE(s0 > 0.0, "negative or null underlying given");
        Volatility v = process_->blackVolatility()->blackVol(
            arguments_.exercise->lastDate(), s0);
        Date maturityDate = arguments_.exercise->lastDate();
        Rate r = process_->riskFreeRate()->zeroRate(maturityDate,
            rfdc, Continuous, NoFrequency);
  • Copyright (C) 2002, 2003, 2004 Ferdinando Ametrano
  • Copyright (C) 2002, 2003 RiskMap srl
  • Copyright (C) 2003, 2004, 2005, 2007 StatPro Italia srl
  • Copyright (C) 2007 Affine Group Limited

QuantLib · FdBlackScholesVanillaEngine::calculate(

ql/pricingengines/vanilla/fdblackscholesvanillaengine.cpp · 109–122 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    void FdBlackScholesVanillaEngine::calculate() const {

        // 0. Cash dividend model
        const Date exerciseDate = arguments_.exercise->lastDate();
        const Time maturity = process_->time(exerciseDate);
        const Date settlementDate = process_->riskFreeRate()->referenceDate();

        Real spotAdjustment = 0.0;
        DividendSchedule dividendSchedule = DividendSchedule();

        ext::shared_ptr<EscrowedDividendAdjustment> escrowedDivAdj;

        switch (cashDividendModel_) {
          case Spot:
  • Copyright (C) 2008 Andreas Gaida
  • Copyright (C) 2008, 2009 Ralph Schreyer
  • Copyright (C) 2008, 2009 Klaus Spanderen

QuantLib · class MCVanillaEngine

ql/pricingengines/vanilla/mcvanillaengine.hpp · 37–50 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    class MCVanillaEngine : public Inst::engine,
                            public McSimulation<MC,RNG,S> {
      public:
        void calculate() const override {
            McSimulation<MC,RNG,S>::calculate(requiredTolerance_,
                                              requiredSamples_,
                                              maxSamples_);
            this->results_.value = this->mcModel_->sampleAccumulator().mean();
            if constexpr (RNG::allowsErrorEstimate)
                this->results_.errorEstimate =
                    this->mcModel_->sampleAccumulator().errorEstimate();
        }

      protected:
  • Copyright (C) 2003 Ferdinando Ametrano
  • Copyright (C) 2003, 2004, 2005, 2007 StatPro Italia srl

QuantLib · class LongstaffSchwartzPathPricer

ql/methods/montecarlo/longstaffschwartzpathpricer.hpp · 53–66 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    class LongstaffSchwartzPathPricer : public PathPricer<PathType> {
      public:
        typedef typename EarlyExerciseTraits<PathType>::StateType StateType;

        LongstaffSchwartzPathPricer(const TimeGrid& times,
                                    ext::shared_ptr<EarlyExercisePathPricer<PathType> >,
                                    const ext::shared_ptr<YieldTermStructure>& termStructure);

        Real operator()(const PathType& path) const override;
        virtual void calibrate();

        Real exerciseProbability() const;

      protected:
  • Copyright (C) 2006 Klaus Spanderen
  • Copyright (C) 2015 Peter Caspers
  • Copyright (C) 2015 Thema Consulting SA

QuantLib · class BlackCalculator

ql/pricingengines/blackcalculator.hpp · 33–46 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    class BlackCalculator {
      private:
        class Calculator;
      public:
        BlackCalculator(const ext::shared_ptr<StrikedTypePayoff>& payoff,
                        Real forward,
                        Real stdDev,
                        Real discount = 1.0);
        BlackCalculator(Option::Type optionType,
                        Real strike,
                        Real forward,
                        Real stdDev,
                        Real discount = 1.0);
        virtual ~BlackCalculator() = default;
  • Copyright (C) 2003, 2004, 2005, 2006 Ferdinando Ametrano
  • Copyright (C) 2006 StatPro Italia srl

QuantLib · testValues

test-suite/europeanoption.cpp · 288–301 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
BOOST_AUTO_TEST_CASE(testValues) {

    BOOST_TEST_MESSAGE("Testing European option values...");

    /* The data below are from
       "Option pricing formulas", E.G. Haug, McGraw-Hill 1998
    */
    EuropeanOptionData values[] = {
      // pag 2-8
      //        type, strike,   spot,    q,    r,    t,  vol,   value,    tol
      { Option::Call,  65.00,  60.00, 0.00, 0.08, 0.25, 0.30,  2.1334, 1.0e-4},
      { Option::Put,   95.00, 100.00, 0.05, 0.10, 0.50, 0.20,  2.4648, 1.0e-4},
      { Option::Put,   19.00,  19.00, 0.10, 0.10, 0.75, 0.28,  1.7011, 1.0e-4},
      { Option::Call,  19.00,  19.00, 0.10, 0.10, 0.75, 0.28,  1.7011, 1.0e-4},
  • Copyright (C) 2003, 2007 Ferdinando Ametrano
  • Copyright (C) 2003, 2007 StatPro Italia srl
  • Copyright (C) 2009 Klaus Spanderen
  • Copyright (C) 2026 Mahimn Patel

QuickFIX C++

QuickFIX Software License(自有许可证)。 项目仓库 · 许可入口

QuickFIX C++ · void Session::next(const std::string &msg

src/C++/Session.cpp · 1170–1183 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
void Session::next(const std::string &msg, const UtcTimeStamp &now, bool queued) {
  try {
    m_state.onIncoming(msg);
    const DataDictionary &sessionDD = m_dataDictionaryProvider.getSessionDataDictionary(m_sessionID.getBeginString());
    if (m_sessionID.isFIXT()) {
      const DataDictionary &applicationDD
          = m_dataDictionaryProvider.getApplicationDataDictionary(m_senderDefaultApplVerID);
      next(Message(msg, sessionDD, applicationDD, m_validateLengthAndChecksum), now, queued);
    } else {
      next(Message(msg, sessionDD, m_validateLengthAndChecksum), now, queued);
    }
  } catch (InvalidMessage &e) {
    m_state.onEvent(e.what());
  • ** Copyright (c) 2001-2014

River

BSD-3-Clause。 项目仓库 · 许可入口

River · class ADWIN

river/drift/adwin.py · 7–20 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class ADWIN(DriftDetector):
    r"""Adaptive Windowing method for concept drift detection[^1].

    ADWIN (ADaptive WINdowing) is a popular drift detection method with mathematical guarantees.
    ADWIN efficiently keeps a variable-length window of recent items; such that it holds that
    there has no been change in the data distribution. This window is further divided into two
    sub-windows $(W_0, W_1)$ used to determine if a change has happened. ADWIN compares the average of
    $W_0$ and $W_1$ to confirm that they correspond to the same distribution. Concept drift is detected
    if the distribution equality no longer holds. Upon detecting a drift, $W_0$ is replaced by $W_1$ and a
    new $W_1$ is initialized. ADWIN uses a significance value $\delta=\in(0,1)$ to determine
    if the two sub-windows correspond to the same distribution.

    Parameters
    ----------

ruptures

BSD-2-Clause。 项目仓库 · 许可入口

ruptures · def predict(

src/ruptures/detection/pelt.py · 117–130 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def predict(self, pen: float) -> list[int]:
        """Return the optimal breakpoints.

        Must be called after the fit method. The breakpoints are associated with the signal passed
        to [`fit()`][ruptures.detection.pelt.Pelt.fit].

        Args:
            pen (float): penalty value (>0)

        Raises:
            BadSegmentationParameters: in case of impossible segmentation
                configuration

        Returns:

SALib

MIT。 项目仓库 · 许可入口

SALib · def analyze(

src/SALib/analyze/sobol.py · 22–35 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def analyze(
    problem,
    Y,
    calc_second_order=True,
    num_resamples=100,
    conf_level=0.95,
    print_to_console=False,
    parallel=False,
    n_processors=None,
    keep_resamples=False,
    seed=None,
):
    """Perform Sobol Analysis on model outputs.

SALib · def analyze(

src/SALib/analyze/morris.py · 17–30 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def analyze(
    problem: Dict,
    X: np.ndarray,
    Y: np.ndarray,
    num_resamples: int = 100,
    conf_level: float = 0.95,
    scaled: bool = False,
    print_to_console: bool = False,
    num_levels: int = 4,
    seed=None,
    keep_resamples: bool = False,
) -> Dict:
    """Perform Morris Analysis on model outputs.

scikit-learn

BSD-3-Clause。 项目仓库 · 许可入口

scikit-learn · class OneVsRestClassifier

sklearn/multiclass.py · 202–215 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class OneVsRestClassifier(
    MultiOutputMixin,
    ClassifierMixin,
    MetaEstimatorMixin,
    BaseEstimator,
):
    """One-vs-the-rest (OvR) multiclass strategy.

    Also known as one-vs-all, this strategy consists in fitting one classifier
    per class. For each classifier, the class is fitted against all the other
    classes. In addition to its computational efficiency (only `n_classes`
    classifiers are needed), one advantage of this approach is its
    interpretability. Since each class is represented by one and one classifier
    only, it is possible to gain knowledge about the class by inspecting its
  • # SPDX-License-Identifier: BSD-3-Clause

scikit-learn · def calibration_curve(

sklearn/calibration.py · 1329–1342 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def calibration_curve(
    y_true,
    y_prob,
    *,
    pos_label=None,
    n_bins="warn",
    strategy="warn",
):
    """Compute true and predicted probabilities for a calibration curve.

    The method assumes the inputs come from a binary classifier, and
    discretize the [0, 1] interval into bins.

    Calibration curves may also be referred to as reliability diagrams.
  • # SPDX-License-Identifier: BSD-3-Clause

scikit-learn · def confusion_matrix(

sklearn/metrics/_classification.py · 443–456 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def confusion_matrix(
    y_true, y_pred, *, labels=None, sample_weight=None, normalize=None
):
    """Compute confusion matrix to evaluate the accuracy of a classification.

    By definition a confusion matrix :math:`C` is such that :math:`C_{i, j}`
    is equal to the number of observations known to be in group :math:`i` and
    predicted to be in group :math:`j`.

    Thus in binary classification, the count of true negatives is
    :math:`C_{0,0}`, false negatives is :math:`C_{1,0}`, true positives is
    :math:`C_{1,1}` and false positives is :math:`C_{0,1}`.

    Read more in the :ref:`User Guide <confusion_matrix>`.
  • # SPDX-License-Identifier: BSD-3-Clause

scikit-learn · def brier_score_loss(

sklearn/metrics/_classification.py · 3710–3723 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def brier_score_loss(
    y_true,
    y_proba,
    *,
    sample_weight=None,
    pos_label=None,
    labels=None,
    scale_by_half="auto",
):
    r"""Compute the Brier score loss.

    The smaller the Brier score loss, the better, hence the naming with "loss".
    The Brier score measures the mean squared difference between the predicted
    probability and the actual outcome. The Brier score is a strictly proper scoring
  • # SPDX-License-Identifier: BSD-3-Clause

StatsForecast

Apache-2.0。 项目仓库 · 许可入口

StatsForecast · def forecast(

python/statsforecast/core.py · 1744–1757 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def forecast(
        self,
        h: int,
        df: Any,
        X_df: Optional[DataFrame] = None,
        level: Optional[List[int]] = None,
        fitted: bool = False,
        prediction_intervals: Optional[ConformalIntervals] = None,
        id_col: str = "unique_id",
        time_col: str = "ds",
        target_col: str = "y",
    ) -> DataFrame:
        """Generate forecasts with memory-efficient model training.

StatsForecast · def cross_validation(

python/statsforecast/core.py · 1896–1909 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def cross_validation(
        self,
        h: int,
        df: Any,
        n_windows: int = 1,
        step_size: int = 1,
        test_size: Optional[int] = None,
        input_size: Optional[int] = None,
        level: Optional[List[int]] = None,
        fitted: bool = False,
        refit: Union[bool, int] = True,
        prediction_intervals: Optional[ConformalIntervals] = None,
        id_col: str = "unique_id",
        time_col: str = "ds",

statsmodels

BSD-3-Clause。 项目仓库 · 许可入口

statsmodels · cdef class STL

statsmodels/tsa/stl/_stl.pyx · 106–119 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
cdef class STL(object):
    """
    STL(endog, period=None, seasonal=7, trend=None, low_pass=None, seasonal_deg=1, trend_deg=1, low_pass_deg=1, robust=False, seasonal_jump=1, trend_jump=1, low_pass_jump=1)

    Season-Trend decomposition using LOESS.

    Parameters
    ----------
    endog : array_like
        Data to be decomposed. Must be 1-d or an (n, 1) column, such as a
        one-column DataFrame.
    period : int, optional
        Periodicity of the sequence. If None and endog is a pandas Series or
        DataFrame, attempts to determine from endog. If endog is a ndarray,

Strata

Apache-2.0。 项目仓库 · 许可入口

Strata · class DiscountingIborFutureTradePricer

modules/pricer/src/main/java/com/opengamma/strata/pricer/index/DiscountingIborFutureTradePricer.java · 30–43 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
public class DiscountingIborFutureTradePricer {

  /**
   * Default implementation.
   */
  public static final DiscountingIborFutureTradePricer DEFAULT =
      new DiscountingIborFutureTradePricer(DiscountingIborFutureProductPricer.DEFAULT);

  /**
   * Underlying pricer.
   */
  private final DiscountingIborFutureProductPricer productPricer;

  /**
  • * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies

Strata · class DiscountingSwapTradePricer

modules/pricer/src/main/java/com/opengamma/strata/pricer/swap/DiscountingSwapTradePricer.java · 25–38 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
public class DiscountingSwapTradePricer {

  /**
   * Default implementation.
   */
  public static final DiscountingSwapTradePricer DEFAULT = new DiscountingSwapTradePricer(
      DiscountingSwapProductPricer.DEFAULT);

  /**
   * Pricer for {@link ResolvedSwap}.
   */
  private final DiscountingSwapProductPricer productPricer;

  /**
  • * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies

SurveyJS Form Library

MIT(Form Library)。 项目仓库 · 许可入口

SurveyJS Form Library · class SurveyModel

packages/survey-core/src/survey.ts · 241–254 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
export class SurveyModel extends SurveyElementCore
  implements
  ISurvey,
  ISurveyData,
  ISurveyVariables,
  ISurveyDataGetEditingObj,
  ISurveyImpl,
  ISurveyTriggerOwner,
  ISurveyErrorOwner,
  ISurveyTimerText {
  public static readonly TemplateRendererComponentName: string =
    "sv-template-renderer";
  // public static get cssType(): string {
  //   return surveyCss.currentType;

SurveyJS Form Library · class QuestionRankingModel

packages/survey-core/src/question_ranking.ts · 23–36 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
export class QuestionRankingModel extends QuestionCheckboxModel {
  private domNode: HTMLElement = null;
  private dragOrClickHelper: DragOrClickHelper;

  constructor(name: string) {
    super(name);
    this.dragOrClickHelper = new DragOrClickHelper(this.startDrag);
  }
  protected onPropertyValueChanged(name: string, oldValue: any, newValue: any): void {
    super.onPropertyValueChanged(name, oldValue, newValue);
    if (name === "selectToRankEnabled") {
      this.clearValue(true);
      this.setDragDropRankingChoices();
      this.updateRankingChoicesSync();

SurveyJS Form Library · public runCondition(

packages/survey-core/src/question.ts · 2258–2271 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
  public runCondition(properties: HashTable<any>): void {
    if (this.isDesignMode) return;
    if (!properties) properties = {};
    properties["question"] = this;
    this.runConditionCore(properties);
    if (this.canApplyDefaultValue() && (!this.isClearValueOnHidden || this.isVisibleInSurvey)) {
      if (!this.canSkipDefaultValueExpression()) {
        this.runDefaultValueExpression(properties);
      }
    }
  }
  // The inputs and the result of the last completed default value run of the conditions pass.
  // Copies, not references: a defaultValue or a value changed in place must count as changed.
  private lastDefaultValueRun: { expression: string, defaultValue: any, value: any };

SurveyJS Form Library · class QuestionMatrixModel

packages/survey-core/src/question_matrix.ts · 351–364 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
export class QuestionMatrixModel
  extends Question
  implements IMatrixData, IMatrixCellsOwner {
  protected generatedVisibleRows: Array<MatrixRowModel> = null;
  public visibleRowsChangedCallback: () => void;
  private isRowChanging = false;
  private cellsValue: MatrixCells;

  protected createColumnValues(): any {
    return this.createItemValues("columns");
  }

  constructor(name: string) {
    super(name);

Taguette

BSD-3-Clause。 项目仓库 · 许可入口

Taguette · class Highlight

taguette/database/models.py · 592–605 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Highlight(Base):
    __tablename__ = 'highlights'
    __table_args__ = ({'sqlite_autoincrement': True},)

    id = Column(Integer, primary_key=True)
    document_id = Column(Integer, ForeignKey('documents.id',
                                             ondelete='CASCADE'),
                         nullable=False, index=True)
    document = relationship('Document', back_populates='highlights')
    start_offset = Column(Integer, nullable=False)
    end_offset = Column(Integer, nullable=False)
    snippet = Column(Text, nullable=False)
    tags = relationship('Tag', secondary='highlight_tags',
                        back_populates='highlights')

Taguette · def _get_highlights_for_export(

taguette/export.py · 74–87 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def _get_highlights_for_export(db, project_id, path):
    if path:
        t_highlight = database.Highlight.__table__
        t_highlight_tag = database.highlight_tags
        t_tag = database.Tag.__table__
        t_document = database.Document.__table__
        # Join with tags a second time to find highlights that match the
        # given path, while returning all tags for those highlights
        t_highlight_tag_m = database.highlight_tags.alias()
        t_tag_m = database.Tag.__table__.alias()
        query = (
            sqlalchemy.select([
                t_highlight.c.id,
                t_highlight.c.snippet,

Taguette · class Tag

taguette/database/models.py · 617–630 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class Tag(Base):
    __tablename__ = 'tags'
    __table_args__ = ({'sqlite_autoincrement': True},)

    id = Column(Integer, primary_key=True)
    project_id = Column(Integer, ForeignKey('projects.id', ondelete='CASCADE'),
                        nullable=False, index=True)
    project = relationship('Project', back_populates='tags')

    path = Column(String(200), nullable=False, index=True)
    description = Column(Text, nullable=False)

    __table_args__ = (
        UniqueConstraint('project_id', 'path'),

Temporal Python SDK

MIT,限 SDK。 项目仓库 · 许可入口

Temporal Python SDK · async def create_schedule(

temporalio/client/_client.py · 2652–2665 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    async def create_schedule(
        self,
        id: str,
        schedule: Schedule,
        *,
        trigger_immediately: bool = False,
        backfill: Sequence[ScheduleBackfill] = [],
        memo: Mapping[str, Any] | None = None,
        search_attributes: None
        | (
            temporalio.common.TypedSearchAttributes | temporalio.common.SearchAttributes
        ) = None,
        rpc_metadata: Mapping[str, str | bytes] = {},
        rpc_timeout: timedelta | None = None,

Temporal Python SDK · async def wait_condition(

temporalio/workflow/_context.py · 1028–1041 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
async def wait_condition(
    fn: Callable[[], bool],
    *,
    timeout: timedelta | float | None = None,
    timeout_summary: str | None = None,
    event_groups: Sequence[EventGroup] | None = None,
) -> None:
    """Wait on a callback to become true.

    This function returns when the callback returns true (invoked each loop
    iteration) or the timeout has been reached.

    Importantly, using `None` value for ``timeout`` means that no Temporal timer is created. This
    means changing from `None` to a positive value (or the inverse) constitutes a nondeterministic

Temporal Python SDK · async def execute_activity(

temporalio/workflow/_activities.py · 337–350 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
async def execute_activity(
    activity: CallableAsyncNoParam[ReturnType],
    *,
    task_queue: str | None = None,
    schedule_to_close_timeout: timedelta | None = None,
    schedule_to_start_timeout: timedelta | None = None,
    start_to_close_timeout: timedelta | None = None,
    heartbeat_timeout: timedelta | None = None,
    retry_policy: temporalio.common.RetryPolicy | None = None,
    cancellation_type: ActivityCancellationType = ActivityCancellationType.TRY_CANCEL,
    activity_id: str | None = None,
    versioning_intent: VersioningIntent | None = None,
    summary: str | None = None,
    event_groups: Sequence[EventGroup] | None = None,

Temporal Python SDK · def get_workflow_handle(

temporalio/client/_client.py · 868–881 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def get_workflow_handle(
        self,
        workflow_id: str,
        *,
        run_id: str | None = None,
        first_execution_run_id: str | None = None,
        result_type: type | None = None,
    ) -> WorkflowHandle[Any, Any]:
        """Get a workflow handle to an existing workflow by its ID.

        Args:
            workflow_id: Workflow ID to get a handle to.
            run_id: Run ID that will be used for all calls.
            first_execution_run_id: First execution run ID used for cancellation

Temporal Python SDK · async def cancel(

temporalio/client/_workflow.py · 326–339 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    async def cancel(
        self,
        *,
        reason: str = "",
        rpc_metadata: Mapping[str, str | bytes] = {},
        rpc_timeout: timedelta | None = None,
    ) -> None:
        """Cancel the workflow.

        This will issue a cancellation for :py:attr:`run_id` if present. This
        call will make sure to use the run chain starting from
        :py:attr:`first_execution_run_id` if present. To create handles with
        these values, use :py:meth:`Client.get_workflow_handle`.

Temporal Python SDK · class RetryPolicy

temporalio/common.py · 37–50 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class RetryPolicy:
    """Options for retrying workflows and activities."""

    initial_interval: timedelta = timedelta(seconds=1)
    """Backoff interval for the first retry. Default 1s."""

    backoff_coefficient: float = 2.0
    """Coefficient to multiply previous backoff interval by to get new
    interval. Default 2.0.
    """

    maximum_interval: timedelta | None = None
    """Maximum backoff interval between retries. Default 100x
    :py:attr:`initial_interval`.

TigerBeetle

Apache-2.0。 项目仓库 · 许可入口

TigerBeetle · fn post_or_void_pending_transfer(

src/state_machine.zig · 4036–4049 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
        fn post_or_void_pending_transfer(
            self: *StateMachine,
            timestamp_event: u64,
            t: *const Transfer,
        ) CreateTransferStatusUnion {
            assert(t.id != 0);
            assert(t.id != std.math.maxInt(u128));
            assert(self.get_transfer(t.id) == null);
            assert(t.flags.padding == 0);
            assert(timestamp_event != 0);
            assert(timestamp_event > self.commit_timestamp or t.flags.imported);
            assert(t.flags.post_pending_transfer or t.flags.void_pending_transfer);

            if (t.flags.post_pending_transfer and t.flags.void_pending_transfer) {

TigerBeetle · fn create_transfer(

src/state_machine.zig · 3693–3706 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
        fn create_transfer(
            self: *StateMachine,
            timestamp_event: u64,
            t: *const Transfer,
        ) CreateTransferStatusUnion {
            assert(timestamp_event != 0);
            assert(timestamp_event > self.commit_timestamp or
                t.flags.imported or
                self.aof_recovery);

            if (t.flags.padding != 0) return .reserved_flag;

            if (t.id == 0) return .id_must_not_be_zero;
            if (t.id == math.maxInt(u128)) return .id_must_not_be_int_max;

Valhalla

MIT 代码。 项目仓库 · 许可入口

Valhalla · actor_t::route(

src/tyr/actor.cc · 97–110 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
actor_t::route(const std::string& request_str, const std::function<void()>* interrupt, Api* api) {
  auto scoped_cleaner = make_finally([this]() {
    if (auto_cleanup)
      cleanup();
  });
  // set the interrupts
  pimpl->set_interrupts(interrupt);
  // if the caller doesn't want a copy we'll use this dummy
  Api dummy;
  if (!api) {
    api = &dummy;
  }
  // parse the request
  ParseApi(request_str, Options::route, *api);

Velero

Apache-2.0。 项目仓库 · 许可入口

Velero · func (r *restoreReconciler) Reconcile(

pkg/controller/restore_controller.go · 179–192 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
func (r *restoreReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	// Developer note: any error returned by this method will
	// cause the restore to be re-enqueued and re-processed by
	// the controller.
	log := r.logger.WithField("Restore", req.NamespacedName.String())

	restore := &api.Restore{}
	err := r.kbClient.Get(ctx, client.ObjectKey{Namespace: req.Namespace, Name: req.Name}, restore)
	if err != nil {
		if apierrors.IsNotFound(err) {
			log.Debugf("restore[%s] not found", req.Name)
			return ctrl.Result{}, nil
		}
  • Copyright The Velero Contributors.

Wagtail

BSD-3-Clause。 项目仓库 · 许可入口

Wagtail · def save_revision(

wagtail/models/revisions.py · 384–397 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
    def save_revision(
        self,
        user=None,
        approved_go_live_at=None,
        changed=True,
        log_action=False,
        previous_revision=None,
        clean=True,
        overwrite_revision=None,
    ):
        """
        Creates and saves a revision.

        :param user: The user performing the action.

Wagtail · class StreamBlock(BaseStreamBlock

wagtail/blocks/stream_block.py · 509–522 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class StreamBlock(BaseStreamBlock, metaclass=DeclarativeSubBlocksMetaclass):
    pass


class StreamValue(MutableSequence):
    """
    Custom type used to represent the value of a StreamBlock; behaves as a sequence of BoundBlocks
    (which keep track of block types in a way that the values alone wouldn't).
    """

    class StreamChild(BoundBlock):
        """
        Iterating over (or indexing into) a StreamValue returns instances of StreamChild.
        These are wrappers for the individual data items in the stream, extending BoundBlock

Wagtail · class WorkflowState(models.Model)

wagtail/models/workflows.py · 121–134 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class WorkflowState(models.Model):
    """Tracks the status of a started Workflow on an object."""

    STATUS_IN_PROGRESS = "in_progress"
    STATUS_APPROVED = "approved"
    STATUS_NEEDS_CHANGES = "needs_changes"
    STATUS_CANCELLED = "cancelled"
    STATUS_CHOICES = (
        (STATUS_IN_PROGRESS, _("In progress")),
        (STATUS_APPROVED, _("Approved")),
        (STATUS_NEEDS_CHANGES, _("Needs changes")),
        (STATUS_CANCELLED, _("Cancelled")),
    )

Wagtail · class PublishRevisionAction

wagtail/actions/publish_revision.py · 29–42 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
class PublishRevisionAction(BaseAction):
    """
    Publish or schedule revision for publishing.

    :param revision: revision to publish
    :param user: the publishing user
    :param changed: indicated whether content has changed
    :param log_action:
        flag for the logging action. Pass False to skip logging. Cannot pass an action string as the method
        performs several actions: "publish", "revert" (and publish the reverted revision),
        "schedule publishing with a live revision", "schedule revision reversal publishing, with a live revision",
        "schedule publishing", "schedule revision reversal publishing"
    :param previous_revision: indicates a revision reversal. Should be set to the previous revision instance
    """

Whisper

MIT(本仓库代码与权重,见上游)。 项目仓库 · 许可入口

Whisper · def transcribe(

whisper/transcribe.py · 38–51 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def transcribe(
    model: "Whisper",
    audio: Union[str, np.ndarray, torch.Tensor],
    *,
    verbose: Optional[bool] = None,
    temperature: Union[float, Tuple[float, ...]] = (0.0, 0.2, 0.4, 0.6, 0.8, 1.0),
    compression_ratio_threshold: Optional[float] = 2.4,
    logprob_threshold: Optional[float] = -1.0,
    no_speech_threshold: Optional[float] = 0.6,
    condition_on_previous_text: bool = True,
    initial_prompt: Optional[str] = None,
    carry_initial_prompt: bool = False,
    word_timestamps: bool = False,
    prepend_punctuations: str = "\"'“¿([{-",

Zou

AGPL-3.0。 项目仓库 · 许可入口

Zou · def create_shot(

zou/app/services/shots_service.py · 920–933 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def create_shot(
    project_id,
    sequence_id,
    name,
    data=None,
    nb_frames=0,
    description=None,
    created_by=None,
    index=True,
):
    """
    Create shot for given project and sequence. A bulk import passes
    index=False and indexes all its shots at the end.
    """

Zou · def create_task(

zou/app/services/tasks_service.py · 771–784 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def create_task(task_type, entity, name="main"):
    """
    Create a new task for given task type and entity.
    """
    task_status = task_types_service.get_default_task_status(
        for_concept=entity["entity_type_id"]
        == entity_types_service.get_concept_type()["id"]
    )
    try:
        try:
            current_user_id = persons_service.get_current_user()["id"]
        except RuntimeError:
            current_user_id = None
        task = Task.create(

Zou · def create_asset(

zou/app/services/assets_service.py · 503–516 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def create_asset(
    project_id,
    asset_type_id,
    name,
    description,
    data,
    is_shared=False,
    source_id=None,
    created_by=None,
    ready_for=None,
    index=True,
):
    """
    Create a new asset from given parameters. A bulk import passes

Zou · def create_comment(

zou/app/services/comments_service.py · 92–105 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def create_comment(
    person_id,
    task_id,
    task_status_id,
    text,
    checklist=None,
    files=None,
    created_at="",
    links=None,
    with_hashtags=True,
    for_client=False,
    _fired_automations=None,
    _automation_depth=0,
):

Zou · def assign_task(

zou/app/services/tasks_service.py · 919–932 行。 在 GitHub 查看源码 · 许可证与声明

源码片段
def assign_task(task_id, person_id, assigner_id=None):
    """
    Assign given person to given task. Emit a *task:assign* event.
    """
    task = get_task_raw(task_id)
    project_id = str(task.project_id)
    person = persons_service.get_person_raw(person_id)
    check_no_preview_assignee([person_id])
    if person not in task.assignees:
        task.assignees.append(person)
    if assigner_id is not None:
        task.assigner_id = assigner_id
    task.save()
    task_dict = task.serialize(relations=True)