; // Update earliest date
      }
      if (latest == null || point.endDate.isAfter(latest)) {
        latest = point.endDate; // Update latest date
      }
    }

    // Return the time range with additional padding of 7 days on each end
    return DateTimeRange(
      start: earliest!.subtract(
        const Duration(days: 7),
      ), // Padding before the earliest date
      end: latest!.add(
        const Duration(days: 7),
      ), // Padding after the latest date
    );
  }
}
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'models.dart';
import 'painter.dart';

/// A customizable Gantt Chart widget that displays tasks over a timeline.
///
/// This widget provides a graphical representation of tasks with
/// start and end dates. It supports user interactions such as taps
/// and hovers to provide more information about each task.
///
/// The chart can be customized using the provided style options.
class MaterialGanttChart extends StatefulWidget {
  /// A list of Gantt data representing the tasks.
  final List<GanttData> data;

  /// The width of the Gantt chart.
  final double width;

  /// The height of the Gantt chart.
  final double height;

  /// Style properties for customizing the appearance of the Gantt chart.
  final GanttChartStyle style;

  /// Enables or disables interactive features (hovering and tapping).
  final bool interactive;

  /// Callback function that is called when a point is tapped.
  final void Function(GanttData)? onPointTap;

  /// Callback function that is called when a point is hovered over.
  final void Function(GanttData)? onPointHover;

  /// Callback function that is called when the animation completes.
  final VoidCallback? onAnimationComplete;

  /// Constructs a [MaterialGanttChart] widget.
  ///
  /// Throws a [GanttChartException] if the provided data is empty
  /// or if the width and height are non-positive values.
  MaterialGanttChart({
    super.key,
    required this.data,
    required this.width,
    required this.height,
    this.style = const GanttChartStyle(),
    this.interactive = true,
    this.onPointTap,
    this.onPointHover,
    this.onAnimationComplete,
  }) {
    if (data.isEmpty) {
      throw GanttChartException('Gantt data cannot be empty');
    }
    if (width <= 0 || height <= 0) {
      throw GanttChartException('Width and height must be positive values');
    }
  }

  /// Creates a [MaterialGanttChart] from JSON configuration.
  /// Supports both simple and Plotly-compatible formats.
  ///
  /// Example Plotly JSON format:
  /// ```json
  /// {
  ///   "data": [
  ///     {
  ///       "Task": "Task 1",
  ///       "Start": "2024-01-01",
  ///       "Finish": "2024-01-15",
  ///       "Resource": "Team A"
  ///     }
  ///   ],
  ///   "layout": {
  ///     "title": "Project Timeline",
  ///     "width": 800,
  ///     "height": 600
  ///   }
  /// }
  /// ```
  factory MaterialGanttChart.fromJson(Map<String, dynamic> json) {
    final config = GanttChartJsonConfig.fromJson(json);
    return MaterialGanttChart(
      data: config.getGanttChartData(),
      width: config.width,
      height: config.height,
      style: config.getGanttChartStyle(),
      interactive: config.interactive,
      onAnimationComplete: config.onAnimationComplete,
    );


41010dad1f40eb51b6dae3ded216.html#a39f05934bf2f0201344b464449248f4c">FragmentC const &C) const {

  246

  247     // Alias types for underlying real-valued matrix multiply operator

  248     using MmaOperandA = typename Policy::Operator::FragmentA;

  249     using MmaOperandB = typename Policy::Operator::FragmentB;

  250     using MmaOperandC = typename Policy::Operator::FragmentC;

  251

  252     static_assert(MmaOperandA::kElements == 1,

  253       "This implementation only supports math instructions in which exactly one element is needed for the A operand."

  254       "We can geneneralize later.");

  255

  256     static_assert(MmaOperandB::kElements == 1,

  257       "This implementation only supports math instructions in which exactly one element is needed for the A operand."

  258       "We can geneneralize later.");

  259

  260     D = C;

  261

  262     <a class="code" href="cutlass_8h.html#a4b1c9f25ab6eaa25e1f2258dd63e6c


_inc_range(I.uses())) {
          auto *UserI = cast<Instruction>(U.getUser());
          U.set(V);

          // Do not bother dealing with unreachable code.
          if (!DT.isReachableFromEntry(UserI->getParent()))
            continue;

          // If the instruction is used by a PHI node we have already processed
          // we'll need to iterate on the loop body to converge, so add it to
          // the next set.
          if (auto *UserPI = dyn_cast<PHINode>(UserI))
            if (VisitedPHIs.count(UserPI)) {
              Next->insert(UserPI);
              continue;
            }

          // If we are only simplifying targeted instructions and the user is an
          // instruction in the loop body, add it to our set of targeted
          // instructions. Because we process defs before uses (outside of PHIs)
          // we won't have visited it yet.
          //
          // We also skip any uses outside of the loop being simplified. Those
          // should always be PHI nodes due to LCSSA form, and we don't want to
          // try to simplify those away.
          assert((L.contains(UserI) || isa<PHINode>(UserI)) &&
                 "Uses outside the loop should be PHI nodes due to LCSSA!");
          if (!IsFirstIteration && L.contains(UserI))
            ToSimplify->insert(UserI);
        }

        if (MSSAU)
          if (Instruction *SimpleI = dyn_cast_or_null<Instruction>(V))
            if (MemoryAccess *MA = MSSA->getMemoryAccess(&I))
              if (MemoryAccess *ReplacementMA = MSSA->getMemoryAccess(SimpleI))
                MA->replaceAllUsesWith(ReplacementMA);

        assert(I.use_empty() && "Should always have replaced all uses!");
        if (isInstructionTriviallyDead(&I, &TLI))
          DeadInsts.push_back(&I);
        ++NumSimplified;
        Changed = true;
      }
    }

    // Delete any dead instructions found thus far now that we've finished an
    // iteration over all instructions in all the loop blocks.
    if (!DeadInsts.empty()) {
      Changed = true;
      RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, &TLI, MSSAU);
    }

    if (MSSAU && VerifyMemorySSA)
      MSSA->verifyMemorySSA();

    // If we never found a PHI that needs to be simplified in the next
    // iteration, we're done.
    if (Next->empty())
      break;

    // Otherwise, put the next set in place for the next iteration and reset it
    // and the visited PHIs for that iteration.
    std::swap(Next, ToSimplify);
    Next->clear();
    VisitedPHIs.clear();
    DeadInsts.clear();
  }

  return Changed;
}

PreservedAnalyses LoopInstSimplifyPass::run(Loop &L, LoopAnalysisManager &AM,
                                            LoopStandardAnalysisResults &AR,
                                            LPMUpdater &) {
  std::optional<MemorySSAUpdater> MSSAU;
  if (AR.MSSA) {
    MSSAU = MemorySSAUpdater(AR.MSSA);
    if (VerifyMemorySSA)
      AR.MSSA->verifyMemorySSA();
  }
  if (!simplifyLoopInst(L, AR.DT, AR.LI, AR.AC, AR.TLI,
                        MSSAU ? &*MSSAU : nullptr))
    return PreservedAnalyses::all();

  auto PA = getLoopPassPreservedAnalyses();
  PA.preserveSet<CFGAnalyses>();
  if (AR.MSSA)
    PA.preserve<MemorySSAAnalysis>();
  return PA;
}
//===-------- LoopDataPrefetch.cpp - Loop Data Prefetching Pass -----------===//
//
// Part of the LLVM Project, under the Apache License v2.0


cript-eslint/no-unnecessary-condition
                validate: t => t == null || t >= minValue,
                error: `Value cannot be less than ${minValue}`
            });
    }
}interface AddCasterEpisodeRequest {
    "RegionId"?: string;
    /**
    * 节点类型。 取值：
    *
    * - **Resource**：视频源
    * - **Component**：组件
    *
    * @example `Resource`
    */ "EpisodeType": string;
    /**
    * 起始时间。
    *
    * UTC格式，例如：`2016-06-29T19:00:00Z` 。
    *
    * @example `2016-06-29T19:00:00Z`
    */ "StartTime": string;
    /**
    * 结束时间。
    * UTC 格式，例如：`2016-06-29T19:10:00Z `。
    *
    * @example `2016-06-29T19:10:00Z`
    */ "EndTime": string;
    /**
    * 切换策略。取值：
    *
    * - **TimeFirst**：时间优先
    * - **ContentFirst**：内容优先
    * <note>直播类视频源只允许采用时间优先，当节点类型为Resource时有效。 </note>
    * @example `TimeFirst`
    */ "SwitchType": string;
    "OwnerId"?: number;
    /**
    * 导播台ID。
    * @example `a2b8e671-2fe5-4642-a2ec-bf93880e1a49`
    */ "CasterId": string;
    /**
    * 节目名称。
    * @example `episode_1`
    */ "EpisodeName"?: string;
    /**
    * 视频源ID。
    *
    * > - 若节点类型为**Resource**时，参数有效且必选，
    * - 若节点类型为**Component**时，参数无效。
    * @example `a2b8e671-2fe5-4642-a2ec-bf93880e1a41`
    */ "ResourceId"?: string;
    "ComponentId"?: string[];
}
export { AddCasterEpisodeRequest };'use strict';

/*Reuse your Sharpie class
Create SharpieSet class
it contains a list of Sharpie
countUsable() -> sharpie is usable if it has ink in it
removeTrash() -> removes all unusable sharpies*/

export class Sharpie {
    color: string;
    width: number;
    inkAmount: number;

    constructor(color: string, width: number) {
      this.color = color;
      this.width = width;
      this.inkAmount = 100;
    }

    use(): void {
      if (this.inkAmount !== 0) {
        this.inkAmount--;
      }
    }

    getInkAmount(): number {
      return this.inkAmount;
    }
  }import type { Color, Mesh } from "three";

import { Component } from "../../../core/Component";
import type { Mutable } from "../../types";

export type MeshBuilderComponentProps = {
	shape: "square" | "circle";
	color?: string;
	colorFilter?: (color: Color) => Color;
	scale?: number;
	shadow?: string;
	opacity?: number;
	shadows?: boolean;
	mutator?: (mesh: Mesh) => void;
};

type InnerProps = MeshBuilderComponentProps & { targetable: boolean };

export class MeshBuilderComponent extends Component<[InnerProps]> {
	readonly shape!: "square" | "circle";
	readonly targetable!: boolean;
	readonly color?: string;
	readonly colorFilter?: (color: Color) => Color;
	readonly scale!: number;
	readonly shadow?: string;
	readonly opacity!: number;
	readonly shadows!: boolean;
	readonly mutator?: (mesh: Mesh) => void;

	initialize({
		shape,
		targetable,
		color,
		colorFilter,
		scale = 1,
		shadow,
		opacity = 1,
		shadows = true,
		mutator,
	}: InnerProps): vo


 chartData;

    const chartLabels: Array<string> = [];
    this.lineChartLabels.forEach((record) => {
      chartLabels.push(record.toString());
    });

    dest.lineChartLabels = chartLabels;

    dest.lineChartOptions = this.lineChartOptions;

    dest.lineChartOptionsThumbnail = this.lineChartOptionsThumbnail;

    const chartColors: Array<LineChartColors> = [];
    this.lineChartColors.forEach((record) => {
      chartColors.push(record);
    });

    dest.lineChartColors = chartColors;
    dest.lineChartLegend = this.lineChartLegend;
    dest.lineChartType = this.lineChartType.toString();
    dest.tag = this.tag;
  }

}

export class LineChartColors {
  constructor(public backgroundColor: Array<any>,
              public borderColor,
              public borderWidth,
              public pointBackgroundColor = null,
              public pointBorderColor = null,
              public pointHoverBackgroundColor = null,
              public pointHoverBorderColor = null) {
  }

  public static getGreyTheme(): LineChartColors {
    const t = new LineChartColors(
      ['rgba(148,159,177,0.2)'],
      'rgba(148,159,177,1)',
      2,
      'rgba(148,159,177,1)',
      '#fff',
      '#fff',
      'rgba(148,159,177,0.8)'
    );
    return t;
  }

  public static getDarkGreyTheme(): LineChartColors {
    const t = new LineChartColors(
      ['rgba(77,83,96,0.2)'],
      'rgba(77,83,96,1)',
      2,
      'rgba(77,83,96,1)',
      '#fff',
      '#fff',
      'rgba(77,83,96,1)'
    );
    return t;
  }

  public static getGreenTheme(): LineChartColors {
    const t = new LineChartColors(
      ['rgba(10,240,10,1)'],
      'rgba(0,0,96,1)',
      2,
      'rgba(0,0,64,1)',
      '#fff',
      '#fff',
      'rgba(96,96,160,1)'
    );
    return t;
  }

  public static getRedTheme(): LineChartColors {
    const t = new LineChartColors(
      ['rgba(200,10,10,1)'],
      'rgba(0,0,96,1)',
      2,
      'rgba(0,0,64,1)',
      '#fff',
      '#fff',
      'rgba(96,96,160,1)'
    );
    return t;
  }

  public static getBlueTheme(): LineChartColors {
    const t = new LineChartColors(
      ['rgba(10,10, 240,1)'],
      'rgba(0,0,96,1)',
      2,
      'rgba(0,0,64,1)',
      '#fff',
      '#fff',
      'rgba(96,96,160,1)'
    );
    return t;
  }

  public static getGraphBarTheme(): LineChartColors {
    const t = new LineChartColors(
      [
        'rgba(33, 142, 236, 0.8)',
        'rgba(255, 211, 44, 0.8)',
        'rgba(5, 27, 255, 0.8)',
        'rgba(50, 224, 55, 0.8)'
      ],
      '#000000',
      2
    );
    return t;
  }
}
import { timetableScraper } from './scraper'
import Database from './database'
import { dbReadParams, dbUpdateParams, dbAddParams } from './database'

const main = async () => {
  //writing the data to the database
  const date = new Date()
  const year = date.getFullYear().toString(10)
  const terms = await timetableScraper(date.getFullYear())

  // Error occured in scraper. Could not scrape data
  if (!terms) {
    return false
  }


            fail(fs, ex.getClass());
        } finally {
            try {
                if (fos != null)
                    fos.close();
                if (fis != null)
                    fis.close();
            } catch (IOException ex) {
                fail(fs, ex.getClass());
            }
        }
    }

    private static void tryCatch(String fs, Class<?> ex) {
        boolean caught = false;
        try {
            test(fs);
        } catch (Throwable x) {
            if (ex.isAssignableFrom(x.getClass()))
                caught = true;
        }
        if (!caught)
            fail(fs, ex);
        else
            pass();
    }

    private static void tryCatch(String fs, Class<?> ex, Object ... args) {
        boolean caught = false;
        try {
            test(fs, args);
        } catch (Throwable x) {
            if (ex.isAssignableFrom(x.getClass()))
                caught = true;
        }
        if (!caught)
            fail(fs, ex);
        else
            pass();
    }

    private static float create(double v) {
        return (float) v;
    }

    private static float negate(double v) {
        return (float) -v;
    }

    private static float mult(float v, double mul) {
        return v * (float) mul;
    }

    private static float recip(float v) {
        return 1.0f / v;
    }

    public static void test() {
        TimeZone.setDefault(TimeZone.getTimeZone("GMT-0800"));

        // Any characters not explicitly defined as conversions, date/time
        // conversion suffixes, or flags are illegal and are reserved for
        // future extensions.  Use of such a character in a format string will
        // cause an UnknownFormatConversionException or
        // UnknownFormatFlagsException to be thrown.
        tryCatch("%q", UnknownFormatConversionException.class);
        tryCatch("%t&", UnknownFormatConversionException.class);
        tryCatch("%&d", UnknownFormatConversionException.class);
        tryCatch("%^b", UnknownFormatConversionException.class);

        //---------------------------------------------------------------------
        // Formatter.java class javadoc examples
        //---------------------------------------------------------------------
        test(Locale.FRANCE, "e = %+10.4f", "e =    +2,7183", Math.E);
        test("%4$2s %3$2s %2$2s %1$2s", " d  c  b  a", "a", "b", "c", "d");
        test("Amount gained or lost since last statement: $ %,(.2f",
             "Amount gained or lost since last statement: $ (6,217.58)",
             (new BigDecimal("-6217.58")));
        Calendar c = new GregorianCalendar(1969, JULY, 20, 16, 17, 0);
        testSysOut("Local time: %tT", "Local time: 16:17:00", c);

        test("Unable to open file '%1$s': %2$s",
             "Unable to open file 'food': No such file or directory",
             "food", "No such file or directory");
        Calendar duke = new GregorianCalendar(1995, MAY, 23, 19, 48, 34);
        duke.set(Calendar.MILLISECOND, 584);
        test("Duke's Birthday: %1$tB %1$te, %1$tY",
             "Duke's Birthday: May 23, 1995",
             duke);
        test("Duke's Birthday: %1$tB %1$te, %1$tY",
             "Duke's Birthday: May 23, 1995",
             duke.getTime());
        test("Duke's Birthday: %1$tB %1$te, %1$tY",
             "Duke's Birthday: May 23, 1995",
             duke.getTimeInMillis());

        test("%4$s %3$s %2$s %1$s %4$s %3$s %2$s %1$s",


, 0x61, 0x6c, 0x70, 0x6e, 0x03, 0x6e,
                                     0x70, 0x6e, 0x04, 0x68, 0x74, 0x74, 0x70};
  EnableAlpn(alpn);
  Connect();
  CheckAlpn("npn");
}

TEST_P(TlsConnectGeneric, ConnectAlpnClone) {
  EnsureModelSockets();
  client_model_->EnableAlpn(alpn_dummy_val_, sizeof(alpn_dummy_val_));
  server_model_->EnableAlpn(alpn_dummy_val_, sizeof(alpn_dummy_val_));
  Connect();
  CheckAlpn("a");
}

TEST_P(TlsConnectGeneric, ConnectAlpnWithCustomCallbackA) {
  // "ab" "alpn"
  const std::vector<uint8_t> client_alpn = {0x02, 0x61, 0x62, 0x04,
                                            0x61, 0x6c, 0x70, 0x6e};
  EnableAlpnWithCallback(client_alpn, "alpn");
  Connect();
  CheckAlpn("alpn");
}

TEST_P(TlsConnectGeneric, ConnectAlpnWithCustomCallbackB) {
  // "ab" "alpn"
  const std::vector<uint8_t> client_alpn = {0x02, 0x61, 0x62, 0x04,
                                            0x61, 0x6c, 0x70, 0x6e};
  EnableAlpnWithCallback(client_alpn, "ab");
  Connect();
  CheckAlpn("ab");
}

TEST_P(TlsConnectGeneric, ConnectAlpnWithCustomCallbackC) {
  // "cd" "npn" "alpn"
  const std::vector<uint8_t> client_alpn = {0x02, 0x63, 0x64, 0x03, 0x6e, 0x70,
                                            0x6e, 0x04, 0x61, 0x6c, 0x70, 0x6e};
  EnableAlpnWithCallback(client_alpn, "npn");
  Connect();
  CheckAlpn("npn");
}

TEST_P(TlsConnectDatagram, ConnectSrtp) {
  EnableSrtp();
  Connect();
  CheckSrtp();
  SendReceive();
}

TEST_P(TlsConnectGeneric, ConnectSendReceive) {
  Connect();
  SendReceive();
}

class SaveTlsRecord : public TlsRecordFilter {
 public:
  SaveTlsRecord(const std::shared_ptr<TlsAgent>& a, size_t index)
      : TlsRecordFilter(a), index_(index), count_(0), contents_() {}

  const DataBuffer& contents() const { return contents_; }

 protected:
  PacketFilter::Action FilterRecord(const TlsRecordHeader& header,
                                    const DataBuffer& data,
                                    DataBuffer* changed) override {
    if (count_++ == index_) {
      contents_ = data;
    }
    return KEEP;
  }

 private:
  const size_t index_;
  size_t count_;
  DataBuffer contents_;
};

// Check that decrypting filters work and can read any record.
// This test (currently) only works in TLS 1.3 where we can decrypt.
TEST_F(TlsConnectStreamTls13, DecryptRecordClient) {
  EnsureTlsSetup();
  // 0 = ClientHello, 1 = Finished, 2 = SendReceive, 3 = SendBuffer
  auto saved = MakeTlsFilter<SaveTlsRecord>(client_, 3);
  saved->EnableDecryption();
  Connect();
  SendReceive();

  static const uint8_t data[] = {0xde, 0xad, 0xdc};
  DataBuffer buf(data, sizeof(data));
  client_->SendBuffer(buf);
  EXPECT_EQ(buf, saved->contents());
}

TEST_F(TlsConnectStreamTls13, DecryptRecordServer) {
  EnsureTlsSetup();
  // Disable tickets so that we are sure to not get NewSessionTicket.
  EXPECT_EQ(SECSuccess, SSL_OptionSet(server_->ssl_fd(),
                                      SSL_ENABLE_SESSION_TICKETS, PR_FALSE));
  // 0 = ServerHello, 1 = other hand


2, #0x0
	bl      Function_223c4c0
	mov     r0, r4
	bl      Function_223c5f4
	mov     r0, r4
	bl      Function_22442e4
	mov     r0, #0x3
	add     sp, #0x4
	pop     {r3,r4,pc}
@ 0x22438c0

.word 0xf0f @ 0x22438c0
.word 0xb94 @ 0x22438c4
.thumb
Function_22438c8: @ 22438c8 :thumb
	push    {r3,lr}
	ldr     r1, [r0, #0x3c]
	mov     r2, #0x94
	add     r1, #0xf
	cmp     r1, #0xe
	bhi     branch_2243908
	add     r1, r1, r1
	add     r1, pc
	ldrh    r1, [r1, #0x6]
	lsl     r1, r1, #16
	asr     r1, r1, #16
	add     pc, r1
@ 0x22438e0

Jumppoints_22438e0:
.hword branch_2243908 - Jumppoints_22438e0 - 2
.hword branch_2243906 - Jumppoints_22438e0 - 2
.hword branch_2243908 - Jumppoints_22438e0 - 2
.hword branch_2243908 - Jumppoints_22438e0 - 2
.hword branch_22438fe - Jumppoints_22438e0 - 2
.hword branch_22438fe - Jumppoints_22438e0 - 2
.hword branch_22438fe - Jumppoints_22438e0 - 2
.hword branch_22438fe - Jumppoints_22438e0 - 2
.hword branch_22438fe - Jumppoints_22438e0 - 2
.hword branch_22438fe - Jumppoints_22438e0 - 2
.hword branch_2243908 - Jumppoints_22438e0 - 2
.hword branch_2243908 - Jumppoints_22438e0 - 2
.hword branch_2243908 - Jumppoints_22438e0 - 2
.hword branch_2243906 - Jumppoints_22438e0 - 2
.hword branch_2243902 - Jumppoints_22438e0 - 2
.thumb
branch_22438fe: @ 22438fe :thumb
	mov     r2, #0x1a
	b       branch_2243908
@ 0x2243902

.thumb
branch_2243902: @ 2243902 :thumb
	mov     r2, #0x91
	b       branch_2243908
@ 0x2243906

.thumb
branch_2243906: @ 2243906 :thumb
	mov     r2, #0x96
.thumb
branch_2243908: @ 2243908 :thumb
	ldr     r1, [pc, #0xc] @ 0x2243918, (=0xf0f)
	mov     r3, #0x1
	str     r1, [sp, #0x0]
	ldr     r1, [pc, #0xc] @ 0x224391c, (=0xb94)
	ldr     r1, [r0, r1]
	bl      Function_2245824
	pop     {r3,pc}
@ 0x2243918

.word 0xf0f @ 0x2243918
.word 0xb94 @ 0x224391c
.thumb
Function_2243920: @ 2243920 :thumb
	push    {r4,lr}
	mov     r4, r0
	bl      Function_22438c8
	mov     r0, r4


utOfRangeException.ThrowIfNegative(length);

		if (length == 0)
		{
			return [];
		}

		T[] array = new T[length];
		for (int i = 0; i < length; i++)
		{
			array[i] = new();
		}
		return array;
	}

	public ShaderSubProgram GetSubProgram(uint blobIndex)
	{
		if (m_cachedSubPrograms.TryGetValue((blobIndex, blobIndex), out ShaderSubProgram? subProgram))
		{
			return subProgram;
		}

		using MemoryStream blobMem = new MemoryStream(m_decompressedBlobSegments[Entries[blobIndex].Segment]);
		using AssetReader blobReader = new AssetReader(blobMem, m_shaderCollection);

		subProgram = new ShaderSubProgram();
		ReadSubProgram(blobReader, subProgram, blobIndex, true, true);

		m_cachedSubPrograms.TryAdd((blobIndex, blobIndex), subProgram);
		return subProgram;
	}

	public ShaderSubProgram GetSubProgram(uint blobIndex, uint paramBlobIndex)
	{
		if (m_cachedSubPrograms.TryGetValue((blobIndex, paramBlobIndex), out ShaderSubProgram? subProgram))
		{
			return subProgram;
		}

		using MemoryStream blobMem = new MemoryStream(m_decompressedBlobSegments[Entries[blobIndex].Segment]);
		using AssetReader blobReader = new AssetReader(blobMem, m_shaderCollection);

		subProgram = new ShaderSubProgram();
		ReadSubProgram(blobReader, subProgram, blobIndex, true, false);
		ReadSubProgram(blobReader, subProgram, paramBlobIndex, false, true);

		m_cachedSubPrograms.TryAdd((blobIndex, paramBlobIndex), subProgram);
		return subProgram;
	}

	private void ReadSubProgram(AssetReader reader, ShaderSubProgram subProgram, uint index, bool readProgramData, bool readParams)
	{
		ShaderSubProgramEntry entry = Entries[index];
		reader.BaseStream.Position = entry.Offset;

		subProgram.Read(reader, readProgramData, readParams);
		if (reader.BaseStream.Position != entry.Offset + entry.Length)
		{
			throw new Exception($"Read {reader.BaseStream.Position - entry.Offset} less than expected {entry.Length}");
		}
	}

	public ShaderSubProgramEntry[] Entries { get; set; } = [];

	private AssetCollection m_shaderCollection;
	private List<byte[]> m_decompressedBlobSegments = [];
	private readonly Dictionary<(uint, uint), ShaderSubProgram> m_cachedSubPrograms = new();

	public const string GpuProgramIndexName = "GpuProgramIndex";
}


from .._tier0 import execute
from .._tier0 import plugin_function
from .._tier0 import Image

@plugin_function(categories=['combine', 'neighbor', 'map', 'in assistant'])
def mode_of_touching_neighbors_map(parametric_map : Image, label_map : Image, parametric_map_destination : Image = None, radius : int = 1, ignore_touching_background : bool = True) -> Image:
    """Takes a label image and a parametric intensity image and will replace each labels value in the parametric image
    by the mode value of neighboring labels. The radius of the neighborhood can be configured:
    * radius 0: Nothing is replaced
    * radius 1: direct neighbors are taken into account
    * radius 2: neighbors and neighbors or neighbors are taken into account
    * radius n: ...

    Notes
    -----
    * Values of all pixels in a label each must be identical.

    Parameters
    ----------
    parametric_map : Image
    label_map : Image
    parametric_map_destination : Image, optional
    radius : int, optional
    ignore_touching_background : bool, optional

    Returns
    -------
    parametric_map_destination

    References
    ----------
    .. [1] https://clij.github.io/clij2-docs/reference_modeOfTouchingNeighbors
    """
    from .._tier1 import copy
    from .._tier1 import generate_touch_matrix
    from .._tier2 import neighbors_of_neighbors
    from .._tier1 import read_intensities_from_map
    from .._tier2 import mode_of_touching_neighbors
    from .._tier1 import replace_intensities
    from .._tier1 import set_column

    if radius == 0:
        return copy(parametric_map, parametric_map_destination)

    touch_matrix = generate_touch_matrix(label_map)
    if ignore_touching_background:
        set_column(touch_matrix, 0)

    for i in range(1, int(radius)):
        touch_matrix = neighbors_of_neighbors(touch_matrix)
        if ignore_touching_background:
            set_column(touch_matrix, 0)

    intensities = read_intensities_from_map(label_map, parametric_map)

    new_intensities = mode_of_touching_neighbors(intensities, touch_matrix)

    parametric_map_destination = replace_intensities(label_map, new_intensities, parametric_map_destination)

    return parametric_map_destination


Reader.hasNext()) {
        processXmlStreamReaderEvent(xmlStreamReader)
      }
    } catch (e: XMLStreamException) {
      // ignore parser errors
    }

    if (this.pos < code.length) addTextWithWhitespace(code.substring(this.pos))
    return this
  }

  private fun processXmlStreamReaderEvent(xmlStreamReader: XMLStreamReader) {
    val eventType: Int = xmlStreamReader.next()
    val oldPos: Int = this.pos
    this.pos = xmlStreamReader.location.characterOffset
    var skippedCode: String = this.code.substring(oldPos, this.pos)
    var interpretAs = ""

    Logging.LOGGER.finest(
      "Position " + this.pos + " (" +
        xmlStreamReader.location.lineNumber +
        "," + xmlStreamReader.location.columnNumber + "): Event type = " +
        eventType + ", skippedCode = '" + skippedCode + "'",
    )

    if (this.nextText.isNotEmpty()) {
      if (this.nextText.replace("\r\n", "\n") == skippedCode.replace("\r\n", "\n")) {
        addTextWithWhitespace(skippedCode)
      } else {
        addMarkup(skippedCode, this.nextText)
      }

      skippedCode = ""
      this.nextText = ""
    }

    when (eventType) {
      XMLStreamReader.START_ELEMENT -> {
        val elementName: String = xmlStreamReader.localName
        this.elementNameStack.addLast(elementName)
        Logging.LOGGER.finest("START_ELEMENT: elementName = '" + xmlStreamReader.localName + "'")

        when (elementName) {
          "body", "div", "h1", "h2", "h3", "h4", "h5", "h6", "p", "table", "tr" -> {
            interpretAs += "\n\n"
          }
          "br", "li" -> {
            interpretAs += "\n"
          }
        }
      }
      XMLStreamReader.END_ELEMENT -> {
        Logging.LOGGER.finest("END_ELEMENT")
        this.elementNameStack.removeLastOrNull()
      }
      XMLStreamReader.CHARACTERS -> {
        val elementName: String =
          if (this.elementNameStack.isEmpty()) "" else this.elementNameStack.last()
        val text: String = xmlStreamReader.text
        Logging.LOGGER.finest("CHARACTERS: text = '$text'")
        if ((elementName != "script") && (elementName != "style")) this.nextText = text
      }
      XMLStreamReader.ENTITY_REFERENCE -> {
        this.nextText = xmlStreamReader.text
        Logging.LOGGER.finest("ENTITY_REFERENCE: text = '" + this.nextText + "'")
      }
      else -> {
        // ignore other event types
      }
    }

    addMarkup(skippedCode, interpretAs)
  }

  private fun addTextWithWhitespace(text: String): CodeAnnotatedTextBuilder {
    var pos = 0

    for (matchResult: MatchResult in WHITESPACE_REGEX.findAll(text)) {
      if (matchResult.range.first > pos) addText(text.substring(pos, matchResult.range.first))
      val space: String = (if (this.lastSpace.isEmpty()) " " else "")
      addMarkup(matchResult.value, space)
      pos = matchResult.range.last + 1
    }

    if (pos < text.length) addText(text.substring(pos))
    return this
  }

  companion object {
    private val WHITESPACE_REGEX = Regex("(?: |\r?\n)+")
  }
}
/* Copyright (C) 2019-2025
 * Julian Valentin, Daniel Spitzer, LTeX+ Development Community
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

package org.bsplines.ltexls.parsing.latex

class LatexCommandSignatureMatcher(
  val commandSignatures: List<LatexCommandSignature>,
  escapeCommandP


position:absolute;
    width:100%;
    z-index:1001;

    top: $picker-height*0.5;
    left: 0px;

    height: $picker-label-height;
    margin-top: -($picker-label-height*0.5) - ($picker-highlight-border-width);

    border-top:  $picker-highlight-border-width solid $picker-highlight-color;
    border-bottom:  $picker-highlight-border-width solid $picker-highlight-color;
  }
}
.root {
  @include background($navigationpage-background);
  font-weight: normal;
}

.page {
  /* Disable touch behaviors, like pan and zoom for IE10*/
  @include touch-action(none);
  @include backface-visibility(hidden);
  @include background($navigationpage-background);

  position: absolute;
  height: 100%;
  width:100%;
}

.page.active:not(.animationChild) {
  z-index: 100;
}

.content:not(.group) .form-title {
  text-indent:px-to-rem(15);
}

.root, .scroll {
  font-family:  $application-font;
  color:  $application-text-color;
}

.group {
  padding: px-to-rem(10);
}

.group.bordered {
  @include border-radius($group-border-radius);
  @include background($group-background);

  border: px-to-rem(1) solid $group-border-color;
  margin: px-to-rem(10);
}

.qx-hbox:not(.qx-flex-reverse) > .gap:not(.exclude) + .gap {
  margin-left: px-to-rem(5);
}

div:not(.qx-hbox):not(.qx-flex-reverse) > .gap:not(.exclude) + .gap {
  margin-top: px-to-rem(5);
}

.qx-hbox.qx-flex-reverse > .gap:not(.exclude) + .gap {
  margin-right: px-to-rem(5);
}

div:not(.qx-hbox).qx-flex-reverse > .gap:not(.exclude) + .gap {
  margin-bottom: px-to-rem(5);
}

//
// POPUP
//

$dialog-arrow-space: px-to-rem(2);

.popup {
  @include background($dialog-background);
  @include border-radius($dialog-border-radius);
  @include touch-action(none);

  position: absolute;
  width: auto;
  padding: px-to-rem(6);
  max-width: 90%;
  z-index: 101;
  clear: both;

  // Fallback if no gradient could be set.
  background-color: nth($dialog-background,1);

  border: px-to-rem(2) solid $dialog-border-color;
  color: $dialog-title-text-color;
}

.anchor-target {
  @include pointer-none();
}

.root.ios .popup {
  -webkit-filter: drop-shadow(0 px-to-rem(2) px-to-rem(7) rgba(0,0,0,0.5));
}

.root:not(.ios) .popup {
  @include box-shadow(0px px-to-rem(2) px-to-rem(7) 0px rgba(0,0,0,0.5));
}

.popup-title {
  font-weight: $dialog-font-weight;
  font-size: px-to-rem(16);
  margin-bottom: px-to-rem(3);
}

.popup-content {
  height : 100%;
}

@mixin arrow {
  position:absolute;
  content:"";
}

.anchor.top {
  margin-top: $dialog-arrow-size;
}

.anchor.bottom {
  margin-to


%r5)
	fstdx,s %fr6,%r4(%sr0,%r5)
	fstdx,m %fr6,%r4(%sr0,%r5)
	fstdx,sm %fr6,%r4(%sr0,%r5)
	fstqx %fr6,%r4(%sr0,%r5)
	fstqx,s %fr6,%r4(%sr0,%r5)
	fstqx,m %fr6,%r4(%sr0,%r5)
	fstqx,sm %fr6,%r4(%sr0,%r5)

	fldws 0(%sr0,%r5),%fr6
	fldws,mb 0(%sr0,%r5),%fr6
	fldws,ma 0(%sr0,%r5),%fr6
	fldds 0(%sr0,%r5),%fr6
	fldds,mb 0(%sr0,%r5),%fr6
	fldds,ma 0(%sr0,%r5),%fr6
	fstws %fr6,0(%sr0,%r5)
	fstws,mb %fr6,0(%sr0,%r5)
	fstws,ma %fr6,0(%sr0,%r5)
	fstds %fr6,0(%sr0,%r5)
	fstds,mb %fr6,0(%sr0,%r5)
	fstds,ma %fr6,0(%sr0,%r5)
	fstqs %fr6,0(%sr0,%r5)
	fstqs,mb %fr6,0(%sr0,%r5)
	fstqs,ma %fr6,0(%sr0,%r5)


( 'height', 512 );\n\t\t\t\t\tupcomingSlide.setAttribute( 'src', upcomingURL );\n\t\t\t\t\tdocument.querySelector( '#upcoming-slide' ).appendChild( upcomingSlide );\n\n\t\t\t\t\twhitelistedWindows.push( currentSlide.contentWindow, upcomingSlide.contentWindow );\n\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * Setup the notes UI.\n\t\t\t\t */\n\t\t\t\tfunction setupNotes() {\n\n\t\t\t\t\tnotes = document.querySelector( '.speaker-controls-notes' );\n\t\t\t\t\tnotesValue = document.querySelector( '.speaker-controls-notes .value' );\n\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * We send out a heartbeat at all times to ensure we can\n\t\t\t\t * reconnect with the main presentation window after reloads.\n\t\t\t\t */\n\t\t\t\tfunction setupHeartbeat() {\n\n\t\t\t\t\tsetInterval( () => {\n\t\t\t\t\t\twindow.opener.postMessage( JSON.stringify({ namespace: 'reveal-notes', type: 'heartbeat'} ), '*' );\n\t\t\t\t\t}, 1000 );\n\n\t\t\t\t}\n\n\t\t\t\tfunction getTimings( callback ) {\n\n\t\t\t\t\tcallRevealApi( 'getSlidesAttributes', [], function ( slideAttributes ) {\n\t\t\t\t\t\tcallRevealApi( 'getConfig', [], function ( config ) {\n\t\t\t\t\t\t\tvar totalTime = config.totalTime;\n\t\t\t\t\t\t\tvar minTimePerSlide = config.minimumTimePerSlide || 0;\n\t\t\t\t\t\t\tvar defaultTiming = config.defaultTiming;\n\t\t\t\t\t\t\tif ((defaultTiming == null) && (totalTime == null)) {\n\t\t\t\t\t\t\t\tcallback(null);\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t// Setting totalTime overrides defaultTiming\n\t\t\t\t\t\t\tif (totalTime) {\n\t\t\t\t\t\t\t\tdefaultTiming = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tvar timings = [];\n\t\t\t\t\t\t\tfor ( var i in slideAttributes ) {\n\t\t\t\t\t\t\t\tvar slide = slideAttributes[ i ];\n\t\t\t\t\t\t\t\tvar timing = defaultTiming;\n\t\t\t\t\t\t\t\tif( slide.hasOwnProperty( 'data-timing' )) {\n\t\t\t\t\t\t\t\t\tvar t = slide[ 'data-timing' ];\n\t\t\t\t\t\t\t\t\ttiming = parseInt(t);\n\t\t\t\t\t\t\t\t\tif( isNaN(timing) ) {\n\t\t\t\t\t\t\t\t\t\tconsole.warn(\"Could not parse timing '\" + t + \"' of slide \" + i + \"; using default of \" + defaultTiming);\n\t\t\t\t\t\t\t\t\t\


/**
  \file     LH_QtPlugin_Dial.h
  @author   Andy Bridges <andy@bridgesuk.com>
  Copyright (c) 2011 Andy Bridges

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.

  */

#ifndef LH_QTPLUGIN_DIAL_H
#define LH_QTPLUGIN_DIAL_H

#include "LH_QtPlugin.h"

class LH_QtPlugin_Dial : public LH_QtPlugin
{
    Q_OBJECT
};

#endif // LH_QTPLUGIN_DIAL_H


--[[
Copyright (C) 2020, 2021 penguin0616

This file is part of Insight.

The source code of this program is shared under the RECEX
SHARED SOURCE LICENSE (version 1.0).
The source code is shared for referrence and academic purposes
with the hope that people can read and learn from it. This is not
Free and Open Source software, and code is not redistributable
without permission of the author. Read the RECEX SHARED
SOURCE LICENSE for details
The source codes does not come with any warranty including
the implied warranty of merchandise.
You should have received a copy of the RECEX SHARED SOURCE
LICENSE in the form of a LICENSE file in the root of the source
directory. If not, please refer to
<https://raw.githubusercontent.com/Recex/Licenses/master/SharedSourceLicense/LICENSE.txt>
]]

-- hunter.lua
local module = {
	initialized = false,
	active_hunts = {},
}
local world_type = GetWorldType()

--- Calculates the chance of getting one of the alternate beasts, i.e. not a Koalefant.
--- @return number
local function GetAlternateBeastChance()
	if world_type == 0 then
		return nil
	end

    local day = world_type == -1 and TheWorld.state.cycles or GetClock():GetNumCycles()
    local chance = Lerp(TUNING.HUNT_ALTERNATE_BEAST_CHANCE_MIN, TUNING.HUNT_ALTERNATE_BEAST_CHANCE_MAX, day/100)
    return math.clamp(chance, TUNING.HUNT_ALTERNATE_BEAST_CHANCE_MIN, TUNING.HUNT_ALTERNATE_BEAST_CHANCE_MAX)
end

--- Fetches the active hunt data from the dirt track.
--- @param inst EntityScript The dirt track.
--- @return table @The hunt data.
local function GetHuntFromTrack(inst)
	for i = 1, #module.active_hunts do
		local hunt = module.active_hunts[i]

		if hunt.lastdirt == inst then
			return hunt
		end
	end
end

--- Fetches
local function GetHuntDataFromTrack(inst)
	local hunt = GetHuntFromTrack(inst)

	if not hunt then
		return
	end

	return {
		trackspawned = hunt.trackspawned,
		numtrackstospawn = hunt.numtrackstospawn,
		ambush_track_num = hunt.ambush_track_num,
		chance_of_alternate_beast = GetAlternateBeastChance() -- consider caching?
	}
end

local function DescribeTrack(inst, context)
	--[[
	for _, hunt in pairs(Insight.active_hunts) do
			if hunt.lastdirt == inst then
				local ambush_track_num = hunt.ambush_track_num
				description = string.format(context.lstr.hunt_progress, hunt.trackspawned + 1, hunt.numtrackstospawn)

				if ambush_track_num == hunt.trackspawned + 1 then
					description = CombineLines(description, "There is an ambush waiting on the next track.")
				end
				break
			end
		end
	--]]
	local hunt_data = GetHuntDataFromTrack(inst)

	if not hunt_data then
		return
	end

	local progress = string.format(context.lstr.hunter.hunt_progress, hunt_data.trackspawned + 1, hunt_data.numtrackstospawn) -- +1 to make it look better
	local ambush = nil
	if hunt_data.ambush_track_num and hunt_data.ambush_track_num == hunt_data.trackspawned + 1 then -- will it spawn on the next track?
		ambush = context.lstr.hunter.impending_ambush
	end
	local chance = hunt_data.chance_of_alternate_beast and (hunt_data.trackspawned+1 == hunt_data.numtrackstospa


? collectionType = freezed,Object? playlistItemId = freezed,Object? overview = freezed,Object? productionYear = freezed,Object? albumId = freezed,Object? albumName = freezed,Object? albumArtist = freezed,Object? albumArtists = null,Object? backdropImageTags = null,Object? imageTags = null,Object? userData = null,}) {
  return _then(_ItemDTO(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable
as String,type: null == type ? _self.type : type // ignore: cast_nullable_to_non_nullable
as String,indexNumber: null == indexNumber ? _self.indexNumber : indexNumber // ignore: cast_nullable_to_non_nullable
as int,runTimeTicks: null == runTimeTicks ? _self.runTimeTicks : runTimeTicks // ignore: cast_nullable_to_non_nullable
as int,path: freezed == path ? _self.path : path // ignore: cast_nullable_to_non_nullable
as String?,collectionType: freezed == collectionType ? _self.collectionType : collectionType // ignore: cast_nullable_to_non_nullable
as String?,playlistItemId: freezed == playlistItemId ? _self.playlistItemId : playlistItemId // ignore: cast_nullable_to_non_nullable
as String?,overview: freezed == overview ? _self.overview : overview // ignore: cast_nullable_to_non_nullable
as String?,productionYear: freezed == productionYear ? _self.productionYear : productionYear // ignore: cast_nullable_to_non_nullable
as int?,albumId: freezed == albumId ? _self.albumId : albumId // ignore: cast_nullable_to_non_nullable
as String?,albumName: freezed == albumName ? _self.albumName : albumName // ignore: cast_nullable_to_non_nullable
as String?,albumArtist: freezed == albumArtist ? _self.albumArtist : albumArtist // ignore: cast_nullable_to_non_nullable
as String?,albumArtists: null == albumArtists ? _self._albumArtists : albumArtists // ignore: cast_nullable_to_non_nullable
as List<ArtistDTO>,backdropImageTags: null == backdropImageTags ? _self._backdropImageTags : backdropImageTags // ignore: cast_nullable_to_non_nullable
as List<String>,imageTags: null == imageTags ? _self._imageTags : imageTags // ignore: cast_nullable_to_non_nullable
as Map<String, String>,userData: null == userData ? _self.userData : userData // ignore: cast_nullable_to_non_nullable
as UserData,
  ));
}

/// Create a copy of ItemDTO
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$UserDataCopyWith<$Res> get userData {

  return $UserDataCopyWith<$Res>(_self.userData, (value) {
    return _then(_self.copyWith(userData: value));
  });
}
}

/// @nodoc
mixin _$DownloadedAlbumDTO {

 List<String> get backdropImageTags; Map<String, String> get imageTags; DateTime get downloadDate; String get id; String get name; String get type; int get runTimeTicks; String? get overview; int? get productionYear; String? get albumArtist;@JsonKey(name: 'SizeInBytes') int get sizeInBytes;

  /// Serializes this DownloadedAlbumDTO to a JSON map.
  Map<String, dynamic> toJson();

@override
bool operator ==(Object other) {
  return identical(this, other) || (other.runtimeType == runtimeType&&other is DownloadedAlbumDTO&&const DeepCollectionEquality().equals(other.backdropImageTags, backdropImageTags


Bundle = new PropertyResourceBundle(
                TestGetBaseBundleName.class.getResourceAsStream(
                    PROPERTY_BUNDLE_NAME+".properties"));

        if (getBaseName(propertyBundle) != null) {
            throw new RuntimeException("Expected null baseName, got "
                    + getBaseName(propertyBundle));
        }

        ResourceBundle listBundle = new resources.ListBundle_fr();
        if (getBaseName(listBundle) != null) {
            throw new RuntimeException("Expected null baseName, got "
                    + getBaseName(listBundle));
        }

    }
}
/*
 * Copyright (c) 2007, 2022, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
/*
 * @test
 * @bug 4303146 5102289 6272060
 * @summary Test non-standard loading strategies with ResourceBundle.Control subclasses
 */

import java.io.*;
import java.util.*;

public class LoadingStrategiesTest {

    static int errors;

    public static void main(String[] args) {
        ResourceBundle rb;
        String s;

        // Test zh_TW -> root, zh_CN -> zh -> root
        rb = ResourceBundle.getBundle("Chinese", Locale.TAIWAN, new ChineseControl());
        s = rb.getString("data");
        check("chinese with Locale.TAIWAN", s, "root");

        rb = ResourceBundle.getBundle("Chinese", Locale.CHINA, new ChineseControl());
        s = rb.getString("data");
        check("chinese with Locale.CHINA", s, "zh");

        // Test use of per-locale packaging
        preparePerLocalePackageProperties();

        rb = ResourceBundle.getBundle("test.package.Messages", Locale.US,
                                      new PerLocalePackageControl());
        s = rb.getString("data");
        check("Per-locale package with Locale.US", s, "");

        rb = ResourceBundle.getBundle("test.package.Messages", Locale.GERMAN,
                                      new PerLocalePackageControl());
        s = rb.getString("data");
        check("Per-locale package with Locale.GERMAN", s, "de");

        rb = ResourceBundle.getBundle("test.package.Messages", Locale.JAPAN,
                                      new PerLocalePackageControl());
        s = rb.getString("data");
        check("Per-locale package with Locale.JAPAN", s, "ja_JP");

        // Check any errors
        if (errors > 0) {
            throw new RuntimeException("FAILED: " + errors + " error(s)");
        }
    }

    private static void check(String msg, String got, String expected) {
        if (!got.equals(expected)) {
            error("%s: got \"%s\", expected \"%s\"%n", msg, got, expected);
        }
    }

    private static class ChineseControl extends ResourceBundle.Control {
        @Override
        public List<Locale> getCandidateLocales(String baseName,
                                                Locale locale) {
            if (locale.equals(Locale.TAIWAN)) {
                return Arrays.asList(locale,
                                     // no Locale("zh")
                                     Locale.of(


() - 0.5) * 8.0 // ±4 degrees for biking (more straight)
            }
            currentDirection + smallVariation
        } else {
            // Weak bias: allow larger direction change but still limited to maxDirectionChange
            val maxChange = when (movementType) {
                MovementType.STATIONARY -> 45.0 // Stationary can change direction more
                MovementType.WALKING -> 30.0 // Walking has moderate direction changes
                MovementType.BIKING -> 20.0 // Biking has smaller direction changes
            }
            val directionChange = (kotlin.random.Random.nextDouble() - 0.5) * 2 * maxChange
            currentDirection + directionChange
        }

        // Normalize direction to 0-360 degrees
        val normalizedDirection = ((newDirection % 360.0) + 360.0) % 360.0

        // Update the peer's current direction
        synchronized(simulatedPeerCurrentDirections) {
            simulatedPeerCurrentDirections[peerId] = normalizedDirection
        }

        // Use CoordinateUtils for standardized calculations
        val bearingRadians = CoordinateUtils.toRadians(normalizedDirection)
        val (newLat, newLon) = CoordinateUtils.calculateNewPosition(
            current.latitude,
            current.longitude,
            stepMeters,
            bearingRadians
        )

        // Clamp to radius using cached distance calculation
        val dist = getCachedDistance(center, LatLng(newLat, newLon))
        val maxDistance = radiusMiles * 1609.34

        val finalLat: Double
        val finalLon: Double

        if (dist > maxDistance) {
            // Snap back to edge - calculate point on edge at current bearing
            val (edgeLat, edgeLon) = CoordinateUtils.calculateNewPosition(
                center.latitude,
                center.longitude,
                maxDistance,
                bearingRadians
            )
            finalLat = edgeLat
            finalLon = edgeLon
        } else {
            finalLat = newLat
            finalLon = newLon
        }

        Log.d("MeshNetworkService", "SimPeer $peerId (${movementType.displayName}): current=${currentDirection.toInt()}°, new=${normalizedDirection.toInt()}°, bias=${(straightBias * 100).toInt()}%, speed=${String.format("%.1f", speedMps)}m/s, step=${String.format("%.1f", stepMeters)}m")

        return PeerLocationEntry(
            timestamp = System.currentTimeMillis(),
            latitude = finalLat,
            longitude = finalLon
        )
    }

    /**
     * Move peer with error handling and validation
     */
    private fun movePeerWithErrorHandling(
        peerId: String,
        current: PeerLocationEntry,
        center: LatLng,
        radiusMiles: Double
    ): PeerLocationEntry? {
        return try {
            val newEntry = movePeer(peerId, current, center, radiusMiles)
            if (validatePeerLocation(newEntry)) {
                newEntry
            } else {
                Log.w("MeshNetworkService", "Invalid peer location calculated for $peerId")
                current // Return current location if new location is invalid
            }
        } catch (e: Exception) {
            Log.e("MeshNetworkService", "Error moving peer $peerId: ${e.message}")
            current // Return current location on error
        }
    }

    fun sendLocationUpdate(latitude: Double, longitude: Double, userStatus: com.tak.lite.model.UserStatus? = null) {
        // Use HybridSyncManager for dual-mode location updates (mesh + server)
        hybridSyncManager.sendLocationUpdate(latitude, longitude, userStatus = userStatus)
    }

    fun sendAudioData(audioData: ByteArray, channelId: String = "default") {
        meshProtocol.sendAudioData(audioData, channelId)
    }

    fun requestPeerLocation(peerId: Strin


x < 0 || index >= length) {
      throw new RangeError.index(index, this, "index");
    }
    _setIndexedInt32(index, _toInt32(value));
  }

  // Method(s) implementing the TypedData interface.
  int get elementSizeInBytes {
    return Int32List.bytesPerElement;
  }

  // Internal utility methods.
  Int32List _createList(int length) {
    return new Int32List(length);
  }

  int _getIndexedInt32(int index) {
    return _getInt32(index * Int32List.bytesPerElement);
  }

  void _setIndexedInt32(int index, int value) {
    _setInt32(index * Int32List.bytesPerElement, value);
  }
}

@pragma("vm:entry-point")
class _ExternalUint32Array extends _TypedList
    with _IntListMixin, _TypedIntListMixin<Uint32List>
    implements Uint32List {
  factory _ExternalUint32Array._uninstantiable() {
    throw "Unreachable";
  }

  // Method(s) implementing the List interface.
  int operator [](int index) {
    if (index < 0 || index >= length) {
      throw new RangeError.index(index, this, "index");
    }
    return _getIndexedUint32(index);
  }

  void operator []=(int index, int value) {
    if (index < 0 || index >= length) {
      throw new RangeError.index(index, this, "index");
    }
    _setIndexedUint32(index, _toUint32(value));
  }

  // Method(s) implementing the TypedData interface.
  int get elementSizeInBytes {
    return Uint32List.bytesPerElement;
  }

  // Internal utility methods.
  Uint32List _createList(int length) {
    return new Uint32List(length);
  }

  int _getIndexedUint32(int index) {
    return _getUint32(index * Uint32List.bytesPerElement);
  }

  void _setIndexedUint32(int index, int value) {
    _setUint32(index * Uint32List.bytesPerElement, value);
  }
}

@pragma("vm:entry-point")
class _ExternalInt64Array extends _TypedList
    with _IntListMixin, _TypedIntListMixin<Int64List>
    implements Int64List {
  factory _ExternalInt64Array._uninstantiable() {
    throw "Unreachable";
  }

  // Method(s) implementing the List interface.
  int operator [](int index) {
    if (index < 0 || index >= length) {
      throw new RangeError.index(index, this, "index");
    }
    return _getIndexedInt64(index);
  }

  void operator []=(int index, int value) {
    if (index < 0 || index >= length) {
      throw new RangeError.index(index, this, "index");
    }
    _setIndexedInt64(index, value);
  }

  // Method(s) implementing the TypedData interface.
  int get elementSizeInBytes {
    return Int64List.bytesPerElement;
  }

  // Internal utility methods.
  Int64List _createList(int length) {
    return new Int64List(length);
  }

  int _getIndexedInt64(int index) {
    return _getInt64(index * Int64List.bytesPerElement);
  }

  void _setIndexedInt64(int index, int value) {
    _setInt64(index * Int64List.bytesPerElement, value);
  }
}

@pragma("vm:entry-point")
class _ExternalUint64Array extends _TypedList
    with _IntListMixin, _TypedIntListMixin<Uint64List>
    implements Uint64List {
  factory _ExternalUint64Array._uninstantiable() {
    throw "Unreachable";
  }

  // Method(s) implementing the List interface.


kingdayCultureInfo.Name);
            Assert.IsInstanceOf<PT_PTHolidayStrategy>(workingdayCultureInfo.LocateHolidayStrategy(name, null));
        }

        [Test]
        public void can_locate_by_culture_info()
        {
            string name = "pt-PT";
            new CultureInfo(name).SetCurrentCultureInfo();
            WorkingDayCultureInfo workingdayCultureInfo = new WorkingDayCultureInfo();
            Assert.IsTrue(name == workingdayCultureInfo.Name);
            Assert.IsInstanceOf<PT_PTHolidayStrategy>(workingdayCultureInfo.LocateHolidayStrategy(name, null));
        }
    }
}


from CLASES import *
import pygame, sys
pygame.init()

VENTANA = pygame.display.set_mode((ALTURA, ANCHURA))
pygame.key.set_repeat(400, 30)
pygame.display.set_caption('Juego rompe labrillos')
reloj = pygame.time.Clock()
marcador = 0

LISTA_GLOBAL_SPRITES = pygame.sprite.Group()
LISTA_RAQUETA_LADRILLOS = pygame.sprite.Group()
LISTA_LADRILLOS = pygame.sprite.Group()

pelota = PELOTA('PELOTA.png', PELOTA_VELOCIDAD, -PELOTA_VELOCIDAD)
LISTA_GLOBAL_SPRITES.add(pelota)

raqueta = RAQUETA('RAQUETA.png')
LISTA_GLOBAL_SPRITES.add(raqueta)
LISTA_RAQUETA_LADRILLOS.add(raqueta)

for i in range(8):
    for j in range(8):
        ladrillo = LADRILLO('LADRILLO.png', (i+1)*LADRILLO_ALTURA + 5, (j+3)*LADRILLO_ANCHURA + 5)
        LISTA_GLOBAL_SPRITES.add(ladrillo)
        LISTA_RAQUETA_LADRILLOS.add(ladrillo)
        LISTA_LADRILLOS.add(ladrillo)

while True:
    if pelota.rect.y > ANCHURA:
        print ("Perdido:)")
        pygame.quit()
        sys.exit()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                raqueta.MoverIzquierda()
            elif event.key == pygame.K_RIGHT:
                raqueta.MoverDerecha()

    REBOTES = pygame.sprite.spritecollide(pelota, LISTA_RAQUETA_LADRILLOS, False)
    if REBOTES:
        RECT = REBOTES[0].rect
        if RECT.left > pelota.rect.left or pelota.rect.right < RECT.right:
            pelota.VELOCIDAD_Y *= -1
        else:
            pelota.VELOCIDAD_X *= -1

        if pygame.sprite.spritecollide(pelota, LISTA_LADRILLOS, True):
            marcador += len(REBOTES)
            print( "%s puntos" % marcador)

        if len(LISTA_LADRILLOS) == 0:
          print("Ganado, bravo :)")
          pygame.quit()
          sys.exit()

    VENTANA.fill((0, 0, 0))
    LISTA_GLOBAL_SPRITES.draw(VENTANA)

    LISTA_GLOBAL_SPRITES.update()
    reloj.tick(60)
    pygame.display.flip()


    _captureStream(process.stdout, 'stdout').ignore();
    _captureStream(process.stderr, 'stderr').ignore();

    await Future<void>.delayed(const Duration(seconds: 2));
    // check if process is still running and did not exit with an exit code
    final isProcessRunning = await _isProcessRunning(_processId ?? -1, port);
    if (!isProcessRunning) {
      _processId = null;
      throw Exception(
          'Failed to start $driverName. Process $_processId not running');
    }

    print('$driverName started on port $port (PID: $_processId)');
  }

  Future<void> stopDriver() async {
    if (_processId == null) {
      print('Cannot stop $driverName: no pid - likely not running or started');
      return;
    }

    try {
      print('Attempting to stop $driverName with PID $_processId');
      if (Platform.isWindows) {
        await _killWindowsProcess(_processId!);
      } else {
        await _killUnixProcess(_processId!);
      }
      _processId = null;
    } catch (e) {
      print('Error stopping $driverName: $e');
    }

    print('$driverName stopped');
  }

  Future<void> _killUnixProcess(int pid) async {
    final result = await Process.run('kill', ['-9', pid.toString()]);
    if (result.exitCode != 0) {
      print(
        'Warning: Failed to kill $driverName process: ${result.stderr}',
      );
    }
  }

  Future<void> _killWindowsProcess(int pid) async {
    final result = await Process.run(
      'taskkill',
      ['/F', '/PID', pid.toString()],
    );
    if (result.exitCode != 0) {
      print(
        'Warning: Failed to kill $driverName process: ${result.stderr}',
      );
    }
  }
}

Future<bool> _isProcessRunning(int pid, int port) async {
  if (pid <= 0) {
    return false;
  }

  bool isRunning = true;
  if (Platform.isWindows) {
    isRunning = await _isWindowsProcessRunning(pid);
  } else {
    isRunning = await _isUnixProcessRunning(pid);
  }

  if (!isRunning) {
    return false;
  }

  try {
    final socket = await Socket.connect('127.0.0.1', port);
    await socket.close();
  } on SocketException catch (_) {
    return false;
  }

  return true;
}

Future<bool> _isUnixProcessRunning(int pid) async {
  final result = await Process.run(
    'ps',
    ['-p', pid.toString()],
  );
  if (result.exitCode != 0) {
    return false;
  }

  return true;
}

Future<bool> _isWindowsProcessRunning(int pid) async {
  final result = await Process.run(
    'tasklist',
    ['/FI', 'PID eq $pid'],
  );
  if (result.exitCode != 0) {
    return false;
  }

  return true;
}

Future<bool> _isProcessRunningByName(String processName) async {
  bool isRunning;
  if (Platform.isWindows) {
    isRunning = await _isWindowsProcessRunningByName(processName);
  } else {
    isRunning = await _isUnixProcessRunningByName(processName);
  }
  return isRunning;
}

Future<bool> _isUnixProcessRunningByName(String processName) async {
  final result = await Process.run('ps', ['-A']);


крови",nil, {"Не будем тратить драгоценное время на ерунду, |3-6(нежить). Пора пополнить запасы огненного плавня – они уже совсем на исходе. nnВот что мне от тебя нужно: nn*Чешуя пламезавра nn*Королевская кровь nn*Уголь nnМне нужно все, что ты сможешь предложить! И поторопись, если хочешь угодить Братству."}},
[7737] = {"Завоевать благосклонность",nil, {"Ты быстро продвигаешься по служебной лестнице в Братстве, |3-6(нежить). Ты начинаешь в самом деле завоевывать нашу благосклонность. nnЕсли хочешь заслужить еще большее уважение, слушай внимательно. nnМы хотим повысить качество нашего огненного плавня путем добавления в него окалины черного железа. Окалину можно добыть в Глубинах Черной горы. nnПринеси мне как можно больше!"}},
[7738] = {"Безупречная шкура йети",nil, {"Отнесите безупречную шкуру йети Джангору Быстрому Страннику в Лагерь Мохаче в Фераласе."}},
[7741] = {"Похвала Изумрудного Круга <NYI> <TXT>",nil, nil},
[7761] = {"Приказ Чернорука",nil, {"Вот уж действительно идиот... Похоже, вам нужно найти это клеймо и выжечь на руке метку Драккисата, чтобы получить доступ к сфере Приказа.nnВ письме ясно сказано, что генерал Драккисат охраняет клеймо. Наверное, стоит проверить."}},
[7781] = {"Владыка Черной горы",nil, {"Отнесите голову Нефариана Верховному лорду Болвару Фордрагону в Штормград."}},
[7782] = {"Владыка Черной горы",nil, {"Поговорите с фельдмаршалом Афрасиаби в Аллее Героев рядом со Штормградом."}},
[7783] = {"Владыка Черной горы",nil, {"Отнесите голову Нефариана Траллу в Оргриммар."}},
[7784] = {"Владыка Черной горы",nil, {"Поговори с верховным воеводой Саурфангом. Он ждет тебя на аллее Силы в Оргриммаре."}},
[7785] = {"Сосуд Возрождения",nil, {"Изучите Сосуд Возрождения и вернитесь к верховному лорду Демитриану."}},
[7786] = {"Громораан Ветроносец


]
   if t == nil then
      return nil
   end
   return t[_id]
end

function theme.reload_all(log_cb)
   log_cb = log_cb or Log.info

   Log.debug("Reloading theme.")

   bmp_convert.clear_cache()

   local _overrides, _active_themes = theme.build_overrides()
   local map_tiles = table.values(_overrides["base.map_tile"])
   local chip_tiles = table.values(_overrides["base.chip"])
   local portrait_tiles = table.values(_overrides["base.portrait"])

   local sw = Stopwatch:new()

   log_cb("Loading tilemaps (tile)...")
   local tile_atlas = theme.load_tilemap_tile(map_tiles)
   Log.debug("%s", sw:measure_and_format("Load tilemap: tile"))

   log_cb("Loading tilemaps (overhang)...")
   local tile_overhang_atlas = theme.load_tilemap_tile_overhang(map_tiles)
   Log.debug("%s", sw:measure_and_format("Load tilemap: overhang"))

   log_cb("Loading tilemaps (item shadow)...")
   local item_shadow_atlas = theme.load_tilemap_item_shadow(chip_tiles)
   Log.debug("%s", sw:measure_and_format("Load tilemap: item shadow"))

   log_cb("Loading tilemaps (chip)...")
   local chip_atlas = theme.load_tilemap_chip(chip_tiles)
   Log.debug("%s", sw:measure_and_format("Load tilemap: chip"))

   log_cb("Loading tilemaps (portrait)...")
   local portrait_atlas = theme.load_tilemap_portrait(portrait_tiles)
   Log.debug("%s", sw:measure_and_format("Load tilemap: portrait"))

   local atlases = require("internal.global.atlases")
   atlases.set(tile_atlas,


1
  kind: ClusterConfiguration
  clusterDomain: cluster.local
  clusterType: Static
  kubernetesVersion: "Automatic"
  podSubnetCIDR: 10.111.0.0/16
  podSubnetNodeCIDRPrefix: "24"
  serviceSubnetCIDR: 10.222.0.0/16
discovery:
  clusterMasterCount: 3
  prometheusScrapeInterval: 30
  kubernetesVersion: "1.21.16"
  d8SpecificNodeCountByRole:
    system: 1
modules:
  https:
    mode: CustomCertificate
  publicDomainTemplate: "%s.example.com"
  placement: {}
`
	cniCiliumValues = `
bpfLBMode: "DSR"
internal:
  mode: "Direct"
  masqueradeMode: "BPF"
  hubble:
    certs:
      ca:
        cert: CERT
        key: KEY
      server:
        ca: CA
        key: KEY
        cert: CERT
  egressGatewaysMap:
    myeg:
      name: myeg
      nodeSelector:
        role: worker
      sourceIP:
        mode: VirtualIPAddress
        virtualIPAddress:
          ip: 10.2.2.8
  egressGatewayPolicies:
  - name: egp-dev
    egressGatewayName: myeg
    selectors:
    - podSelector:
        matchLabels:
          app: nginx
    destinationCIDRs:
    - 192.168.0.0/16
    excludedCIDRs:
    - 192.168.3.0/24
resourcesManagement:
  mode: VPA
  vpa:
    mode: Auto
    cpu:
      min: "50m"
      max: "2"
    memory:
      min: "256Mi"
      max: "2Gi"
`
)

func getSubdirs(dir string) ([]string, error) {
	var subdirs []string
	err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if info.IsDir() && path != dir && filepath.Base(path) == info.Name() {
			subdirs = append(subdirs, info.Name())
			return filepath.SkipDir
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return subdirs, nil
}

const (
	ciliumEETempaltesPath = "/deckhouse/ee/se-plus/modules/021-cni-cilium/templates/"
	ciliumCETempaltesPath = "/deckhouse/modules/021-cni-cilium/templates/"
)

var _ = Describe("Module :: cniCilium :: helm template ::", func() {

	BeforeSuite(func() {
		subDirs, err := getSubdirs(ciliumEETempaltesPath)
		Expect(err).ShouldNot(HaveOccurred())
		for _, subDir := range subDirs {
			err := os.Symlink(ciliumEETempaltesPath+subDir, ciliumCETempaltesPath+subDir)
			Expect(err).ShouldNot(HaveOccurred())
		}
	})

	AfterSuite(func() {
		subDirs, err := getSubdirs(ciliumEETempaltesPath)
		Expect(err).ShouldNot(HaveOccurred())
		for _, subDir := range subDirs {
			err := os.Remove(ciliumCETempaltesPath + subDir)
			Expect(err).ShouldNot(HaveOccurred())
		}
	})

	f := SetupHelmConfig(``)

	Context("Cluster with cniCilium", func() {
		BeforeEach(func() {
			f.ValuesSetFromYaml("global", globalValues)
			f.ValuesSet("global.modulesImages", GetModulesImages())
			f.ValuesSetFromYaml("cniCilium", cniCiliumValues)
			f.HelmRender()
		})

		It("Everything must render properly", func() {
			Expect(f.RenderError).ShouldNot(HaveOccurred())
			cegp := f.KubernetesGlobalResource("CiliumEgressGatewayPolicy", "d8.myeg")
			Expect(cegp.Exists()).To(BeTrue())

			Expect(cegp.Field("spec.destinationCIDRs").String()).To(MatchJSON(`["192.168.0.0/16"]`))

			Expect(cegp.Field("spec.excludedCIDRs").String()).To(MatchJSON(`["192.168.3.0/24"]`))

			Expect(cegp.Field("spec.sel


 t = a.view(index, axis)
            t shouldBeExactly expected
            return t
        }
        m(a)
        val d1 = identityGradientofSameKind(a).view(index, axis)
        val d1r = d1.leftTranspose(a.shape.remove(axis), a.shape)
        forwardDerivative(a) { aa -> m(aa) } shouldBeExactly d1
        reverseDerivative(a) { aa -> m(aa) } shouldBeExactly d1r
    }
    @Test fun view01() {
        val a = tensorOf(1F, 2F, 3F).reshape(1, 3)
        val index = 1
        val axis = 1
        val expected = FloatScalar(2F).reshape(1)
        testView(a, index, axis, expected)
    }
    @Test fun view02() {
        val a = tensorOf(1F, 2F, 3F)
        val index = 1
        val axis = 0
        val expected = FloatScalar(2F)
        testView(a, index, axis, expected)
    }
    fun testView(a: DTensor, index: IntArray, expected: DTensor) {
        fun m(a: DTensor): DTensor {
            val t = a.view(index)
            t shouldBeExactly expected
            return t
        }
        m(a)
        val d1 = identityGradientofSameKind(a).view(index)
        val d1r = d1.leftTranspose(a.shape.drop(index.size), a.shape)
        forwardDerivative(a) { aa -> m(aa) } shouldBeExactly d1
        reverseDerivative(a) { aa -> m(aa) } shouldBeExactly d1r
    }
    @Test fun view03() {
        val a = tensorOf(1F, 2F, 3F).reshape(1, 3)
        val index = intArrayOf(0, 1)
        val expected = FloatScalar(2F)
        testView(a, index, expected)
    }
    @Test fun view04() {
        val a = tensorOf(1F, 2F, 3F).reshape(3, 1)
        val index = intArrayOf(1)
        val expected = FloatScalar(2F).reshape(1)
        testView(a, index, expected)
    }
    @Test fun withChangeRange() {
        val a = tensorOf(
                1F, 2F, 3F, 4F,
                5F, 6F, 7F, 8F,
                9F, 10F, 11F, 12F).reshape(3, 4)
        val b = tensorOf(
                21F, 22F,
                23F, 24F,
                25F, 26F).reshape(3, 2)
        val index = 1..2
        val axis = 1
        val expected = tensorOf(
                1F, 21F, 22F, 4F,
                5F, 23F, 24F, 8F,
                9F, 25F, 26F, 12F).reshape(3, 4)
        testWithChange(a, b, index, axis, expected)
    }
}
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package org.diffkt

import org.diffkt.random.RandomKey
import kotlin.reflect.KClass
import kotlin.reflect.full.allSuperclasses
import kotlin.reflect.full.isSuperclassOf

/**
 * An interface that is capable of wrapping individual values.  To be used by an
 * implementation of [Differentiable] to wrap the individual values.
 */
abstract class Wrapper {
    fun <T> wrap(value: T): T {
        @Suppress("UNCHECKED_CAST")
        return wrapRaw((value ?: return value)::class, value) as T
    }

    abstract fun wrapDTensor(value: DTensor): DTensor

    open fun wrapRandomKey(value: RandomKey): RandomKey = value

    private fun wrapRaw(type: KClass<*>, value: Any?): Any? {
        if (value == null)
            return null
        if (value is Wrappable<*>)
            return value.wrap(this)

        if (type.java.isArray) {
            // Support wrapping arrays.
            val elementType = type


m_R;
	Tag::AddValue(pt, &hGen, p.m_Witness.m_V);
	pt += Context::get().J * ser;
	pt.Export(lst.m_vec[p.m_Witness.m_L]);

	if (bMpc)
	{
		proof.m_SpendPk = ptSpendPk;

		pt = Context::get().G * p.m_Witness.m_R_Output;
		Tag::AddValue(pt, &hGen, p.m_Witness.m_V);
		proof.m_Commitment = pt;
	}

	if (bWithAsset)
	{
		// add blinding to the asset
		Scalar::Native skGen = 77345U;
		hGen = hGen + Context::get().G * skGen;

		skGen *= p.m_Witness.m_V;

		p.m_Witness.m_R_Adj = p.m_Witness.m_R_Output;
		p.m_Witness.m_R_Adj += -skGen;
	}

	beam::ByteBuffer bufProof;

	PseudoRandomGenerator prg = *PseudoRandomGenerator::s_pOverride; // save prnd state

	for (uint32_t iCycle = 0; iCycle < 3; iCycle++)
	{
		beam::ExecutorMT_R ex;
		ex.set_Threads(1 << iCycle);

		beam::Executor::Scope scope(ex);

		uint32_t t = beam::GetTime_ms();

		*PseudoRandomGenerator::s_pOverride = prg; // restore prnd state

		Oracle oracle;
		Hash::Value seed = Zero;

		if (bMpc)
		{
			// proof phase1 generation, Sigma with 0 blinding factor, SigGen is deferred
			p.Generate(seed, oracle, &hGen, beam::Lelantus::Prover::Phase::Step1);

			// Complete SigGen (normally this is done on another device, we just reuse this code)
			p.GenerateSigGen(&hGen);

			Scalar::Native sVal = 432123U; // custom tau[0]
			Point::Native ptG0;
			verify_test(ptG0.Import(proof.m_Part1.m_vG.front()));
			ptG0 += Context::get().G * sVal;
			proof.m_Part1.m_vG.front() = ptG0;

			Oracle o2(oracle); // copy
			proof.m_Part1.Expose(o2);

			Scalar::Native x;
			o2 >> x; // challenge

			// calculate initial zR
			Scalar::Native xPwr(x);

			for (uint32_t j = 1; j < proof.m_Cfg.M; j++)
				xPwr *= x;

			x = p.m_Witness.m_R - p.m_Witness.m_R_Output;

			sVal = -sVal;
			sVal += x * xPwr;

			proof.m_Part2.m_zR = sVal;

			// hide p.m_Witness.m_R
			x = p.m_Witness.m_R;
			p.m_Witness.m_R = Zero;
			p.Generate(seed, oracle, &hGen, beam::Lelantus::Prover::Phase::Step2);
			p.m_Witness.m_R = x;
		}
		else
			p.Generate(seed, oracle, &hGen);

		if (!bSpecial)
			printf("\tProof time = %u ms, Threads=%u\n", beam::GetTime_ms() - t, ex.get_Threads());

		// serialization
		beam::Serializer ser_;
		ser_ & proof;

		if (iCycle)
		{
			// verify the result is the same (doesn't depend on thread num)
			beam::SerializeBuffer sb = ser_.buffer();
			verify_test((sb.second == buf


onfigurar un "Error Workflow" global para la instancia de n8n (desde "Settings" / "Configuración" de n8n) sirve como una red de seguridad final para capturar y manejar cualquier error no controlado que pueda ocurrir en cualquier flujo de trabajo.
6.  **Registro (Logging) Significativo:** Implementar el registro de eventos importantes, parámetros de entrada clave y errores en puntos críticos de los flujos de trabajo. Utilizar el nodo `n8n-nodes-base.logMessage` o herramientas de observabilidad externas. Esto es crucial para la depuración y el monitoreo. (Ver "Pruebas y Depuración > Interpretación de Logs").

El cumplimiento de estos principios es fundamental y se detalla o ejemplifica en secciones posteriores como [Pruebas y Depuración](#pruebas-y-depuración) y [Manejo de Errores Globales en el Flujo Principal del Servidor MCP](#manejo-de-errores-globales-en-el-flujo-principal-del-servidor-mcp).

## Arquitectura General

### Estructura Básica
La arquitectura MCP se basa en un flujo principal (el servidor MCP) que utiliza un `@n8n/n8n-nodes-langchain.mcpTrigger` como punto de entrada. Este flujo orquesta la ejecución de subworkflows (herramientas) a través de nodos `@n8n/n8n-nodes-langchain.toolWorkflow`.

```mermaid
graph TD
    A[@n8n/n8n-nodes-langchain.mcpTrigger] --> B{Nodo Switch (Enrutador basado en nombre de herramienta del Agente AI)};
    B -- tool_A_name --> C1["@n8n/n8n-nodes-langchain.toolWorkflow (configurado para SWF_Tool_A)"];
    B -- tool_B_name --> C2["@n8n/n8n-nodes-langchain.toolWorkflow (configurado para SWF_Tool_B)"];
    C1 --> D[Manejo de Respuesta / Preparación para Agente AI];
    C2 --> D;
```
El `mcpTrigger` recibe una solicitud, un nodo `Switch` (o lógica similar) determina qué herramienta ejecutar, y un nodo `toolWorkflow` específico llama al subworkflow correspondiente.

### Ventajas del Uso de Subworkflows
*   **Modularidad:** Descomponer problemas complejos en partes más pequeñas y manejables.
*   **Reutilización:** Utilizar la misma lógica en diferentes partes del sistema o en diferentes servidores MCP.
*   **Mantenibilidad:** Facilitar la actualización y corrección de errores al aislar la lógica en unidades independientes.
*   **Testabilidad:** Probar cada subworkflow (herramienta) de forma aislada.

## Diseño de Herramientas MCP (Subworkflows)

### Formato Estándar de Salida

#### Éxito
El campo `status` siempre será `"success"`. El campo `data` contiene el resultado útil de la herramienta.

```json
{
  "status": "success",
  "data": {
    "resultado_especifico": "valor",
    "otro_dato": 123
  },
  "meta": {
    "timestamp": "2023-10-27T10:30:00Z"
  }
}
```
*(Nota: `meta.timestamp` se puede generar con `{{ $now }}` en un nodo `Set`)*.

#### Error
El campo `status` siempre será `"error"`. El campo `data` contiene detalles del error. El campo `message` o `text` dentro de `data` proporciona un mensaje legible.

```json
{
  "status": "error",
  "data": {
    "code": "CODIGO_ERROR_UNICO",


])
    }

    fn append_event<T>(&self, stream_id: String, expected_location: i64) -> Result<(), String> {
        Ok(())
    }
}
#![doc="Quick sort algorithms
"]

// std imports
use std::ptr;
use std::fmt;

/// Quick sort algorithm on a slice of data
pub fn quick_sort_slice<T: PartialOrd>(xs: &mut [T]){
    if xs.len() <= 1 {
        return;
    }
    // Compute the pivot as median between left-right and center.
    let pivot = {
        let (l, r) = (0, xs.len() - 1);
        // identify the index of middle element
        let m = l + ((r - l) / 2);
        let (left, middle, right) = (&xs[l], &xs[m], &xs[r]);
        if middle >= left && middle <= right {
            m
        } else if left >= middle && left <= right {
            l
        } else {
            r
        }
    };
    // Partition the array in two parts around the pivot
    let lasti = xs.len() - 1;
    // Send the pivot to the end.
    xs.swap(lasti, pivot);
    // now start from the beginning
    let (mut i, mut pivot) = (0, 0);
    while i < lasti {
        if xs[i] <= xs[lasti] {
            xs.swap(i, pivot);
            pivot = pivot + 1;
        }
        i = i + 1;
    }
    xs.swap(pivot, lasti);
    // Now run quick sort recursively
    // we split original slice into two slices
    // the left slide [0, pivot-1]
    quick_sort_slice(&mut xs[..pivot]);
    // the right slice [pivot + 1, end]
    quick_sort_slice(&mut xs[(pivot+1)..]);
}

// Helper function for debugging
pub unsafe fn  print_arr<T: PartialOrd + fmt::Display>(data : *mut T, n : usize){
    for i in 0..n{
        print!("{} ", *data.offset(i as isize));
    }
    println!("");
}

/// Orders three elements in the array as ascending order
unsafe fn median_data_buffer<T: PartialOrd>(data : *mut T,
    l : isize, m: isize, r: isize) -> isize {
    let pl = data.offset(l);
    let pm = data.offset(m);
    let pr = data.offset(r);
    if *pr < *pl {
        ptr::swap(pl, pr);
    }
    if *pm < *pl {
        ptr::swap(pl, pm);
    }
    if *pr < *pm {
        ptr::swap(pm, pr);
    }
    m
}

/// Quick sort algorithm on a buffer of data
pub unsafe fn quick_sort_buffer<T: PartialOrd>(data : *mut T, n : usize){
    if n <= 1 {
        return;
    }
    let right = (n - 1) as isize;
    // pointer to the last entry
    let pright = data.offset(right);
    let mut pleft = data;
    // Compute the pivot as median between left-right and center.
    let pivot = median_data_buffer(data, 0, right/2, right);
    // Partition the array in two parts around the pivot
    // Send the pivot to the end.
    let mut ppivot = data.offset(pivot);
    //println!("swapping pivot: {}, right: {}", *ppivot, *pright);
    ptr::swap(pright, ppivot);
    //print_arr(data, n);
    // now start from the beginning
    let (mut i, mut pivot) = (0, 0);
    ppivot = data.offset(pivot);
    while i < right {
        if *ple


ingStyle             string       `cli:"opt-heading-style" usage:"Option HeadingStyle"`
	OptHorizontalRule           string       `cli:"opt-horizontal-rule" usage:"Option HorizontalRule"`
	OptBulletListMarker         string       `cli:"opt-bullet-list-marker" usage:"Option BulletListMarker"`
	OptCodeBlockStyle           string       `cli:"opt-code-block-style" usage:"Option CodeBlockStyle"`
	OptFence                    string       `cli:"opt-fence" usage:"Option Fence"`
	OptEmDelimiter              string       `cli:"opt-em-delimiter" usage:"Option EmDelimiter"`
	OptStrongDelimiter          string       `cli:"opt-strong-delimiter" usage:"Option StrongDelimiter"`
	OptLinkStyle                string       `cli:"opt-link-style" usage:"Option LinkStyle"`
	OptLinkReferenceStyle       string       `cli:"opt-link-reference-style" usage:"Option LinkReferenceStyle"`
	OptEscapeMode               string       `cli:"opt-escape-mode" usage:"Option EscapeMode\n"`
	PluginBrToNewline           bool         `cli:"plugin-br-to-newline" usage:"Plugin BrToNewline"`
	PluginConfluenceAttachments bool         `cli:"A,plugin-conf-attachment" usage:"Plugin ConfluenceAttachments"`
	PluginConfluenceCodeBlock   bool         `cli:"C,plugin-conf-code" usage:"Plugin ConfluenceCodeBlock"`
	PluginFrontMatter           bool         `cli:"F,plugin-frontmatter" usage:"Plugin FrontMatter"`
	PluginGitHubFlavored        bool         `cli:"G,plugin-gfm" usage:"Plugin GitHubFlavored"`
	PluginStrikethrough         bool         `cli:"S,plugin-strikethrough" usage:"Plugin Strikethrough"`
	PluginTable                 bool         `cli:"T,plugin-table" usage:"Plugin Table"`
	PluginTableCompat           bool         `cli:"plugin-table-compat" usage:"Plugin TableCompat"`
	PluginTaskListItems         bool         `cli:"L,plugin-task-list" usage:"Plugin TaskListItems"`
	PluginVimeoEmbed            bool         `cli:"V,plugin-vimeo" usage:"Plugin VimeoEmbed"`
	PluginYoutubeEmbed          bool         `cli:"Y,plugin-youtube" usage:"Plugin YoutubeEmbed"`
}

var root = &cli.Command{
	Name: "html2md",
	Desc: "HTML to Markdown\nVersion " + version + " built on " + date +
		"\nCopyright (C) 2020-2024, Tong Sun",
	Text: "HTML to Markdown converter on command line" +
		"\n\nUsage:\n  html2md [Options...]",
	Argv: func() interface{} { return new(rootT) },
	Fn:   Html2md,

	NumOption: cli.AtLeast(1),
}

// Template for main starts here
////////////////////////////////////////////////////////////////////////////
// Constant and data type/structure definitions

// The OptsT type defines all the configurable options from cli.
//  type OptsT struct {
//  	Filei	*clix.Reader
//  	Domain	string
//  	Sel	string
//  	Excl	[]string
//  	ExclChildren	bool
//  	Verbose	cli.Counter
//  	OptHeadingStyle	string
//  	OptHorizontalRule	string
//  	OptBulletListMarker	string
//  	OptCodeBlockStyle	string
//  	OptFence	string
//  	OptEmDelimiter	string
//  	OptStrongDelimiter	string
//  	OptLinkStyle	string
//  	OptLinkReferenceStyle	string
//  	OptEscapeMode	string
//  	PluginBrToNew


              state.update({"plan": plan_result})
            results["training_plan"] = plan_result

            # 関連情報の検索
            self.logger.log_info("Searching relevant information...", agent="search")
            search_result = await self.agents["search"].run(plan_result)
            if state:
                state.update({"search_results": search_result})
            results["search_results"] = search_result

            # 最終サマリーの生成
            self.logger.log_info("Generating final summary...", agent="summarize")

            # ★ 修正箇所: persona=persona_data, policy=policy_data を追加
            final_summary = await self.agents["summarize"].run(
                analysis=motion_analysis_result,
                goal=goal_result.get("goal_setting_result", ""),
                plan=plan_result,
                persona=persona_data,
                policy=policy_data
            )
            if state:
                state.update({"summary": final_summary})
            results["final_summary"] = final_summary

            return results

        except Exception as e:
            self.logger.log_error_details(error=e, agent="system")
            raise

    def cleanup(self):
        """リソースのクリーンアップ"""
        self.video_display.cleanup()
        """リソースのクリーンアップ"""
        self.video_display.cleanup()
        self.video_display.cleanup()


		//actual offset address
    secpos=offaddr/STM_SECTOR_SIZE;			  //sector address 0~127 for STM32F103RBT6
    secoff=(offaddr%STM_SECTOR_SIZE)/2;		//offset in sector (must be multiple of 2)
    secremain=STM_SECTOR_SIZE/2-secoff;		//surplus space of sector
    if(NumToWrite<=secremain)secremain=NumToWrite;//below the value of sector
    while(1)
    {
        HF_Flash_Read(secpos*STM_SECTOR_SIZE+STM32_FLASH_BASE,STMFLASH_BUF,STM_SECTOR_SIZE/2);//read all data from sector
        for(i=0;i<secremain;i++)//check data
        {
            if(STMFLASH_BUF[secoff+i]!=0XFFFF)break;//need Erase
        }
        if(i<secremain)//need Erase
        {
            FLASH_ErasePage(secpos*STM_SECTOR_SIZE+STM32_FLASH_BASE);//Erase this sector
            for(i=0;i<secremain;i++)//copy
            {
                STMFLASH_BUF[i+secoff]=pBuffer[i];
            }
            STMFLASH_Write_NoCheck(secpos*STM_SECTOR_SIZE+STM32_FLASH_BASE,STMFLASH_BUF,STM_SECTOR_SIZE/2);//write to all sector
        }else STMFLASH_Write_NoCheck(WriteAddr,pBuffer,secremain);//write to surplus sector
        if(NumToWrite==secremain)break;//end of writing
        else//not end writing
        {
            secpos++;				//sector address add 1
            secoff=0;				//the offset address is 0
            pBuffer+=secremain;  	//offset of pointer
            WriteAddr+=secremain;	//offset of write address
            NumToWrite-=secremain;	//number of bytes is Decreasing
            if(NumToWrite>(STM_SECTOR_SIZE/2))secremain=STM_SECTOR_SIZE/2;//next sector is not enough
            else secremain=NumToWrite;//next sector is enough
        }
    };
    FLASH_Lock();//lock
}

#ifdef __cplusplus
}
#endif


rn rootView;
		}

		public String Title(){
			return "Item reorder";
		}

		public void OnReorderFinished ()
		{

		}

		public void OnReorderItem (int p0, int p1)
		{

		}

		public void OnReorderStarted (int p0)
		{

		}

	}

	class ReorderListViewAdapter : ListViewAdapter {

		public ReorderListViewAdapter(IList items) : base(items){

		}

		public override Android.Support.V7.Widget.RecyclerView.ViewHolder OnCreateViewHolder (ViewGroup p0, int p1)
		{
			LayoutInflater inflater = LayoutInflater.From(p0.Context);
			View itemView = inflater.Inflate(Resource.Layout.example_list_view_item_reorder_layout, p0, false);
			ReorderCustomViewHolder customHolder = new ReorderCustomViewHolder(itemView);
			return customHolder;
		}
		public override void OnBindListViewHolder (ListViewHolder p0, int p1)
		{
			ReorderCustomViewHolder customVH = (ReorderCustomViewHolder) p0;
			customVH.txtItemText.Text = this.GetItem(p1).ToString();
		}
	}

	class ReorderCustomViewHolder : ListViewHolder {

		public TextView txtItemText;

		public ReorderCustomViewHolder(View itemView) : base(itemView){
			this.txtItemText = (TextView) itemView.FindViewById(Resource.Id.txtItemText);
		}
	}
}


5206\u53bf\u90fd\u66fe\u53d1\u73b0\uff0c\u7279\u522b\u662f\u4e71\u62d8\u7559\u3001\u4e71\u6ca1\u6536\u3001\u4e71\u6597\u4e89\u7684\u73b0\u8c61\u66f4\u4e3a\u7a81\u51fa\u3002\u4ec5\u4eca\u5e74\u7b2c\u4e00\u5b63\u5ea6\uff0c\u63a7\u544a\u5230\u68c0\u67e5\u90e8\u95e8\u7684\u6709\u5173\u5e72\u90e8\u4e25\u91cd\u8fdd\u6cd5\u4e71\u7eaa\u6848\u4ef6\uff0c\u6bd4\u53bb\u5e74\u7b2c\u56db\u5b63\u5ea6\u589e\u957f39%\u3002", "type": "paragraph"}, {"text": "\u6765\u6e90\uff1a1962\u5e746\u67088\u65e5\u65b0\u534e\u793e\u300a\u5185\u90e8\u53c2\u8003\u300b\u3002", "type": "paragraph"}, {"text": "\u6765\u6e90\uff1a", "type": "source"}, {"text": "\u7f8e\u56fd\u56fe\u4e66\u9986\u6536\u85cf", "type": "paragraph"}]}
  </script>

    [返回索引页面]

   广东农村不断发生基层干部违法乱纪的案件

   日期：1962-6-8 作者：新华通讯社, 陈炳光

   新华通讯社、陈炳光

   新华社广州讯　今春以来，广东农村不断发生基层干部违法乱纪的案件。

   在已发生的案件中，以潮阳县金玉公社潮下大队党总支书记吴又吉打死贫农社员吴汉音和恩平县公安特派员染拍刑讯逼供贫农冯如操造成四尸五命的两案最为严重。吴汉音是金玉公社潮下大队的理发员，去年秋收期间因偷稻谷三十斤，被大队拘留三十天后罚款一百一十元，吴当时交不出款曾外出理发。今年内2月2日回家过春节，外出理发所得的全部钱款被大队追缴一空。吴因无法过春节，当时又到大队的谷仓偷谷。被抓后，总支书记吴双吉立即召集十多个干部和民兵将吴吊打一顿，接着又到他家中搜查，将全部用具没收，所有食物合伙吃掉。然后吴双吉又下令将吴汉音的脚骨打断。打断一支脚骨后，其他干部不忍再打，


using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace ModToolFramework.Utils
{
    /// <summary>
    /// A wrapper around a struct which performs value-type equality checks, meaning it works in HashSet / Dictionary / List / etc.
    /// </summary>
    public class StructWrapper<TStruct>
        where TStruct : struct
    {
        /// <summary>
        /// The wrapped struct value.
        /// </summary>
        public TStruct Value;

        /// <summary>
        /// Creates a new instance of <see cref="StructWrapper{TStruct}"/> with a pre-existing value.
        /// </summary>
        /// <param name="value">The value to copy to the struct.</param>
        public StructWrapper(ref TStruct value) {
            this.Value = value;
        }

        /// <summary>
        /// Creates a new instance of <see cref="StructWrapper{TStruct}"/> with a pre-existing value.
        /// </summary>
        /// <param name="value">The value to copy to the struct.</param>
        public StructWrapper(TStruct value) {
            this.Value = value;
        }

        /// <summary>
        /// Creates a new instance of <see cref="StructWrapper{TStruct}"/> using the default value type.
        /// </summary>
        public StructWrapper() : this(default) {
        }

        /// <inheritdoc cref="object.Equals(object)"/>
        public override bool Equals(object obj) {
            return (obj is StructWrapper<TStruct> otherWrapper) && otherWrapper.Value.Equals(this.Value);
        }

        /// <inheritdoc cref="object.GetHashCode"/>
        [Su


elog [\#276](https://github.com/kubeops/config-syncer/pull/276) ([tamalsaha](https://github.com/tamalsaha))
- Use same config for chart and script installer [\#274](https://github.com/kubeops/config-syncer/pull/274) ([tamalsaha](https://github.com/tamalsaha))
- Prepare docs for 7.0.0-rc.0 [\#273](https://github.com/kubeops/config-syncer/pull/273) ([tamalsaha](https://github.com/tamalsaha))
- Add concourse test [\#272](https://github.com/kubeops/config-syncer/pull/272) ([tahsinrahman](https://github.com/tahsinrahman))
- Improve installer [\#271](https://github.com/kubeops/config-syncer/pull/271) ([tamalsaha](https://github.com/tamalsaha))
- Improve e2e test [\#270](https://github.com/kubeops/config-syncer/pull/270) ([hossainemruz](https://github.com/hossainemruz))
- Revendor dependencies [\#269](https://github.com/kubeops/config-syncer/pull/269) ([tamalsaha](https://github.com/tamalsaha))
- Add missing RBAC rules [\#268](https://github.com/kubeops/config-syncer/pull/268) ([hossainemruz](https://github.com/hossainemruz))
- Don't panic if admission options is nil [\#264](https://github.com/kubeops/config-syncer/pull/264) ([tamalsaha](https://github.com/tamalsaha))
- Disable admission controllers for webhook server [\#263](https://github.com/kubeops/config-syncer/pull/263) ([tamalsaha](https://github.com/tamalsaha))
- Sync secret Kind [\#262](https://github.com/kubeops/config-syncer/pull/262) ([farcaller](https://github.com/farcaller))
- Update client-go to 7.0.0 [\#261](https://github.com/kubeops/config-syncer/pull/261) ([tamalsaha](https://github.com/tamalsaha))
- Support private registry for chart [\#259](https://github.com/kubeops/config-syncer/pull/259) ([tamalsaha](https://github.com/tamalsaha))
- Improve installer [\#258](https://github.com/kubeops/config-syncer/pull/258) ([tamalsaha](https://github.com/tamalsaha))
- Add support for SSL certificate for S3 compatible custom server \(i.e. Minio\) [\#257](https://github.com/kubeops/config-syncer/pull/257) ([hossainemruz](https://github.com/hossainemruz))
- Rename snapshot command to backup [\#255](https://github.com/kubeops/config-syncer/pull/255) ([tamalsaha](https://github.com/tamalsaha))
- Correctly load default config [\#253](https://github.com/kubeops/config-syncer/pull/253) ([tamalsaha](https://github.com/tamalsaha))
- Add RBAC instructions for GKE cluster [\#252](https://github.com/kubeops/config-syncer/pull/252) ([tamalsaha](https://github.com/tamalsaha))
- Update chart repository location [\#251](https://github.com/kubeops/config-syncer/pull/251) ([tamalsaha](https://github.com/tamalsaha))
- Support installing from local installer scripts [\#250](https://github.com/kubeops/config-syncer/pull/250) ([tamalsaha](https://github.com/tamalsaha))
- Move swagger.json to openapi-spec/v2 [\#249](https://github.com/kubeops/config-sync


rm) in any
# way that is inconsistent with the permitted uses described
# herein. You agree not to use any name or emblem of Harvard, Toronto
# or Sherbrooke, or any of their subdivisions for any purpose, or to
# falsely suggest any relationship between End User (or its
# Institution) and Harvard, Toronto and/or Sherbrooke, or in any
# manner that would infringe or violate any of their rights.
#
# 13. End User represents and warrants that it has the legal authority
# to enter into this License and Terms of Use on behalf of itself and
# its Institution.

from abc import ABCMeta, abstractmethod

from ..utils import param as hyperparameter_utils

class AbstractSampler(object):
    __metaclass__ = ABCMeta

    def __init__(self, *params_to_sample, **sampler_options):
        self.params          = params_to_sample
        self.sampler_options = sampler_options
        self.current_ll      = None

        # Note: thinning is currently implemented such that each sampler does its thinning
        # We could also do a different type of thinning, implemented in SamplerCollection,
        # where all samplers produce a sample, and then you thin (ABABAB rather than AAABBB)
        self.thinning_overrideable = not sampler_options.has_key('thinning') # Thinning can be overrided if True
        self.thinning              = sampler_options.get('thinning', 0)

    @abstractmethod
    def logprob(self, x, model):
        pass

    @abstractmethod
    def sample(self, model):
        pass

    def print_diagnostics(self):
        params_array = hyperparameter_utils.params_to_array(self.params)
        for param in self.params:
            param.print_diagnostics()


    fscanf(fp, "%14c", buf); *nrow = atoi(buf);
    fscanf(fp, "%14c", buf); *ncol = atoi(buf);
    fscanf(fp, "%14c", buf); *nonz = atoi(buf);
    fscanf(fp, "%14c", buf); tmp = atoi(buf);

    if (tmp != 0)
	  printf("This is not an assembled matrix!\n");
    if (*nrow != *ncol)
	printf("Matrix is not square.\n");
    dDumpLine(fp);

    /* Allocate storage for the three arrays ( nzval, rowind, colptr ) */
    dallocateA(*ncol, *nonz, nzval, rowind, colptr);

    /* Line 4: format statement */
    fscanf(fp, "%16c", buf);
    dParseIntFormat(buf, &colnum, &colsize);
    fscanf(fp, "%16c", buf);
    dParseIntFormat(buf, &rownum, &rowsize);
    fscanf(fp, "%20c", buf);
    dParseFloatFormat(buf, &valnum, &valsize);
    fscanf(fp, "%20c", buf);
    dDumpLine(fp);

    /* Line 5: right-hand side */
    if ( rhscrd ) dDumpLine(fp); /* skip RHSFMT */

#ifdef DEBUG
    printf("%d rows, %lld nonzeros\n", *nrow, (long long) *nonz);
    printf("colnum %d, colsize %d\n", colnum, colsize);
    printf("rownum %d, rowsize %d\n", rownum, rowsize);
    printf("valnum %d, valsize %d\n", valnum, valsize);
#endif

    ReadVector(fp, *ncol+1, *colptr, colnum, colsize);
    ReadVector(fp, *nonz, *rowind, rownum, rowsize);
    if ( numer_lines ) {
        dReadValues(fp, *nonz, *nzval, valnum, valsize);
    }

    sym = (type[1] == 'S' || type[1] == 's');
    if ( sym ) {
	FormFullA(*ncol, nonz, nzval, rowind, colptr);
    }

    fclose(fp);
}


) {
    const rooms = this.#findRoomTargets(roomId)

    rooms.forEach(room => {
      if (room.dataset.sortedListPriority) {
        room.dataset.sortedListPriority = "1"
      }
      room.classList.remove(this.unreadClass, this.badgeClass)
      if (Current.room?.id === roomId) {
        this.#keepCurrentRoomUnread = false
      }
      this.dispatch("read", { detail: { targetId: roomId } })
    })
  }

  #channelConnected() {
    if (this.#disconnected) {
      this.#disconnected = false
      this.element.reload()
    }
  }

  #channelDisconnected() {
    this.#disconnected = true
  }

  #unread({ roomId, roomSize, roomUpdatedAt, forceUnread }) {
    const unreadRooms = this.#findRoomTargets(roomId)

    unreadRooms.forEach(unreadRoom => {
      const sortedListTarget = unreadRoom.closest('[data-sorted-list-target]')
      if (!sortedListTarget) return

      if (sortedListTarget.dataset.sortedListPriority) {
        sortedListTarget.dataset.sortedListPriority = "0"
      }
      sortedListTarget.dataset.updatedAt = roomUpdatedAt
      sortedListTarget.dataset.size = roomSize

      if (forceUnread || Current.room?.id != roomId) {
        unreadRoom.classList.add(this.unreadClass)
      }

      if (forceUnread) {
        this.#keepCurrentRoomUnread = true
      }
    })

    this.dispatch("unread", { detail: { roomId: roomId } })
  }

  #addBadge({ roomId }) {
    const unreadRooms = this.#findRoomTargets(roomId)

    unreadRooms.forEach(unreadRoom => {
      if (Current.room?.id != roomId) {
        unreadRoom.classList.add(this.badgeClass)
      }
    })
  }

  #roomUpdated({ roomId, sortableName }) {
    const rooms = this.#findRoomTargets(roomId)

    rooms.forEach(room => {
      const sortedListTarget = room.closest('[data-sorted-list-target]')
      if (!sortedListTarget) return

      sortedListTarget.dataset.name = sortableName
    })

    this.dispatch("renamed", { detail: { roomId: roomId } })
  }

  #updateInvolvement({ roomId, involvement }) {
    const rooms = this.#findRoomTargets(roomId)

    rooms.forEach(room => {
      const list_node = room.closest('[data-type=list_node]')
      if (!list_node) return

      list_node.dataset.involvement = involvement
    })

    this.dispatch("involved", { detail: { roomId: roomId } })
  }

  #findRoomTargets(roomId) {
    return this.roomTargets.filter(roomTarget => roomTarget.dataset.roomId == roomId)
  }

  #readCurrentRoom() {
    this.read({ detail: { roomId: Current.room?.id } })
  }
}
import { Controller } from "@hotwired/stimulus"
import { cable } from "@hotwired/turbo-rails"
import { delay, nextFrame } from "helpers/timing_helpers"

const REFRESH_INTERVAL = 50 * 1000 // 50 seconds

// We delay transmitting visibility changes to ignore brief periods of invisibility,
// like switching to another tab and back
const VISIBILITY_CHANGE_DELAY = 5000 // 5 seconds

export default class extends Controller {
  async connect() {
    this.channel = await cable.subscribeTo({ channel: "PresenceChannel", room_id: Current.room.id }, {
      connected: this.#websocketConnected,
      disconnected: this.#websocketDisconnected
    })

    this.wasVisible = true

    await nextFrame()
    this.dispatch("present


from collections import Counter

dict1 = {
    # "Full_Name" : "Walid Lemnaizi",
    "Age" : 21,
    "Skills" : 7,
    "hobbies" : 3,
    # "experience" : "3 mois",
    "Diplome" : 3
}

dict2 = {
    # "Full_Name" : "Yassine kabbaj",
    "Age" : 21,
    "Skills" : 5,
    "hobbies" : 3,
    # "experience" : "5 mois",
    "Diplome" : 2
}

def fusionner_dicts(dict1,dict2):
    return dict(Counter(dict1) + Counter(dict2))

print(fusionner_dicts(dict1,dict2))


# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

import os
from dataclasses import dataclass, field

@dataclass
class OutdirArgs:
    CONFIG_KEY = "outdir_args"

    root: str = field(default=f'{os.getcwd()}/experiments', metadata={
        "help": "Root folder where to put the experiments"
    })

    name: str = field(default="experiment", metadata={
        "help": "Name of each experiment folder"
    })

    folder_number: str = field(default=None, metadata={
        "help": "Suffix of each folder (e.g., '00001')"
    })

    def create_folder_name(self):
        """ Gets a unique folder name and creates it if it does not exist """
        folder_name = self._get_folder_path()
        os.makedirs(folder_name, exist_ok=True)
        return os.path.abspath(folder_name)

    def _get_folder_path(self):
        """ Get an unused folder name in the root directory. """
        if self.folder_number is None:
            os.makedirs(self.root, exist_ok=True)
            numbers = [0]
            for folder in [x for x in os.listdir(self.root) if self.name in x]:
                numbers.append(int(folder.split(self.name + "_")[1]))
            self.folder_number = str(int(max(numbers) + 1)).zfill(5)
        return os.path.join(self.root, f'{self.name}_{self.folder_number}')