text:
namespace page_load_metrics {

// This enum represents how a page load ends. If the action occurs before the
// page load finishes (or reaches some point like first paint), then we consider
// the load to be aborted.
//
// These values are persisted to logs and the history DB. Entries should not be
// renumbered and numeric values should never be reused. For any additions, also
// update the corresponding PageEndReason enum in enums.xml.
enum PageEndReason {
  // Page lifetime has not yet ended (page is still active). Pages that
  // become hidden are logged in END_HIDDEN, so we expect low numbers in this
  // bucket from the end of May 2020.
  END_NONE = 0,

  // The page was reloaded, possibly by the user.
  END_RELOAD = 1,

  // The page was navigated away from, via a back or forward navigation.
  END_FORWARD_BACK = 2,

  // The navigation is replaced with a navigation with the qualifier
  // ui::PAGE_TRANSITION_CLIENT_REDIRECT, which is caused by Javascript, or the
  // meta refresh tag.
  END_CLIENT_REDIRECT = 3,

  // If the page load is replaced by a new navigation. This includes link
  // clicks, typing in the omnibox (not a reload), and form submissions.
  END_NEW_NAVIGATION = 4,

  // The page load was stopped (e.g. the user presses the stop X button).
  END_STOP = 5,

  // Page load ended due to closing the tab or browser.
  END_CLOSE = 6,

  // The provisional load for this page load failed before committing.
  END_PROVISIONAL_LOAD_FAILED = 7,

  // The render process hosting the page terminated unexpectedly.
  END_RENDER_PROCESS_GONE = 8,

  // We don't know why the page load ended. This is the value we assign to a
  // terminated provisional load if the only signal we get is the load finished
  // without committing, either without error or with net::ERR_ABORTED.
  END_OTHER = 9,

  // The page became hidden but is still active. Added end of May 2020 for
  // Navigation.PageEndReason2. Deprecated Jan 2021 with
  // Navigation.PageEndReason3.
  END_HIDDEN = 10,

  // The page load has not yet ended but we need to flush the metrics because
  // the app has entered the background.
  END_APP_ENTER_BACKGROUND = 11,

  PAGE_END_REASON_COUNT
};

}  // namespace page_load_metrics

#endif  // COMPONENTS_PAGE_LOAD_METRICS_COMMON_PAGE_END_REASON_H_


text:
<?php

function sdk_autoloader() {

    $file_map = array('MonetaSdkStorage.php', 'MonetaSdkUtils.php', 'MonetaSdkException.php', 'MonetaSdkError.php',
                'MonetaSdkResult.php', 'MonetaSdkRender.php', 'MonetaSdkEmptyStorage.php', 'MonetaSdkFilesStorage.php',
                'MonetaSdkMysqlStorage.php', 'MonetaWebServiceConnector.php', 'MonetaWebService.php', 'MonetaSdkJsonConnector.php',
                'MonetaSdkSoapConnector.php', 'MonetaSdkMethods.php', 'MonetaSdk.php', 'MonetaSdkKassa.php',
                'MonetaSdkEmptyKassa.php', 'MonetaSdkModuleKassa.php', 'MonetaSdkAtolonlineKassa.php',
                'MonetaSdkPayanywayKassa.php', 'MonetaSdkStarrysKassa.php', 'MonetaSdkBuhsoftKassa.php',
                'MonetaSdkKomtetKassa.php', 'MonetaSdkIretailKassa.php', 'MonetaSdkOrangedataKassa.php',
		'MonetaSdkDreamkassKassa.php');

    $vendorDir = dirname(__DIR__) . "/moneta-sdk-lib/src/Moneta/";

    foreach ($file_map AS $one_file) {
        $filepath = $vendorDir . $one_file;
        require_once($filepath);
    }

}

function moneta_base_types_autoloader() {
    $file_map = array('Entity.php', 'EntityBatchRequestType.php', 'TransactionRequestType.php', 'VerifyTransferResponseType.php',
                      'OperationInfo.php', 'OperationInfoList.php', 'BankAccount.php', 'Document.php');

    $vendorDir = dirname(__DIR__) . "/moneta-sdk-lib/src/Moneta/Types/";

    foreach ($file_map AS $one_file) {
        $filepath = $vendorDir . $one_file;
        require_once($filepath);
    }

    if ($handle = opendir($vendorDir)) {
        while (false !== ($entry = readdir($handle))) {
            $filepath = $vendorDir . $entry;
            if (file_exists($filepath) && !is_dir($filepath) && strpos($entry, 'Type.php')) {
                require_once($filepath);
            }
        }
    }

    if ($handle = opendir($vendorDir)) {
        while (false !== ($entry = readdir($handle))) {
            $filepath = $vendorDir . $entry;
            if (file_exists($filepath) && !is_dir($filepath) && !strpos($entry, 'Type.php')) {
                require_once($filepath);
            }
        }
    }

}

function show_directory() {
    $vendorDir = dirname(__DIR__) . "/moneta-sdk-lib/src/Moneta/Types/";

    if ($handle = opendir($vendorDir)) {
        while (false !== ($entry = readdir($handle))) {
            $filepath = $vendorDir . $entry;
            if (file_exists($filepath) && !is_dir($filepath) && strpos($entry, 'Type.php')) {
                echo "{$filepath}<br/>";
                require_once($filepath);
            }
        }
    }
}

spl_autoload_register('moneta_base_types_autoloader');
spl_autoload_register('sdk_autoloader');

redpajama_set_name: RedPajamaGithub


text:
import BaseSyntax from './BaseSyntax';

/**
 * The class to define the TemplateElement syntax
 */
export default
class TemplateElement extends BaseSyntax {
  /**
   * Create a template literal
   *
   * @param {Object} cfg
   * @param {String} cfg.raw As it looks in source, with escapes added
   * @param {String} cfg.cooked The actual value
   * @param {Boolean} cfg.tail True to signify the last element in TemplateLiteral
   */
  constructor({raw = '', cooked = '', tail = false}) {
    super('TemplateElement');

    this.value = {raw, cooked};
    this.tail = tail;
  }
}


text:
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/*!
Primitive traits representing basic 'kinds' of types

Rust types can be classified in various useful ways according to
intrinsic properties of the type. These classifications, often called
'kinds', are represented as traits.

They cannot be implemented by user code, but are instead implemented
by the compiler automatically for the types to which they apply.

*/

/// Types able to be transferred across task boundaries.
#[lang="send"]
pub trait Send {
    // empty.
}

/// Types with a constant size known at compile-time.
#[lang="sized"]
pub trait Sized {
    // Empty.
}

/// Types that can be copied by simply copying bits (i.e. `memcpy`).
#[lang="copy"]
pub trait Copy {
    // Empty.
}

/// Types that can be safely shared between tasks when aliased.
///
/// The precise definition is: a type `T` is `Share` if `&T` is
/// thread-safe. In other words, there is no possibility of data races
/// when passing `&T` references between tasks.
///
/// As one would expect, primitive types like `u8` and `f64` are all
/// `Share`, and so are simple aggregate types containing them (like
/// tuples, structs and enums). More instances of basic `Share` types
/// include "immutable" types like `&T` and those with simple
/// inherited mutability, such as `Box<T>`, `Vec<T>` and most other
/// collection types. (Generic parameters need to be `Share` for their
/// container to be `Share`.)
///
/// A somewhat surprising consequence of the definition is `&mut T` is
/// `Share` (if `T` is `Share`) even though it seems that it might
/// provide unsynchronised mutation. The trick is a mutable reference
/// stored in an aliasable reference (that is, `& &mut T`) becomes
/// read-only, as if it were a `& &T`, hence there is no risk of a data
/// race.
///
/// Types that are not `Share` are those that have "interior
/// mutability" in a non-thread-safe way, such as `Cell` and `RefCell`
/// in `std::cell`. These types allow for mutation of their contents
/// even when in an immutable, aliasable slot, e.g. the contents of
/// `&Cell<T>` can be `.set`, and do not ensure data races are
/// impossible, hence they cannot be `Share`. A higher level example
/// of a non-`Share` type is the reference counted pointer
/// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new
/// reference, which modifies the reference counts in a non-atomic
/// way.
///
/// For cases when one does need thread-safe interior mutability,
/// types like the atomics in `std::sync` and `Mutex` & `RWLock` in
/// the `sync` crate do ensure that any mutation cannot cause data
/// races.  Hence these types are `Share`.
///
/// Users writing their own types with interior mutability (or anything
/// else that is not thread-safe) should use the `NoShare` marker type
/// (from `std::kinds::marker`) to ensure that the compiler doesn't
/// consider the user-defined type to be `Share`.  Any types with
/// interior mutability must also use the `std::ty::Unsafe` wrapper
/// around the value(s) which can be mutated when behind a `&`
/// reference; not doing this is undefined behaviour (for example,
/// `transmute`-ing from `&T` to `&mut T` is illegal).
#[lang="share"]
pub trait Share {
    // Empty
}

/// Marker types are special types that are used with unsafe code to
/// inform the compiler of special constraints. Marker types should
/// only be needed when you are creating an abstraction that is
/// implemented using unsafe code. In that case, you may want to embed
/// some of the marker types below into your type.
pub mod marker {

    /// A marker type whose type parameter `T` is considered to be
    /// covariant with respect to the type itself. This is (typically)
    /// used to indicate that an instance of the type `T` is being stored
    /// into memory and read from, even though that may not be apparent.
    ///
    /// For more information about variance, refer to this Wikipedia
    /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
    ///
    /// *Note:* It is very unusual to have to add a covariant constraint.
    /// If you are not sure, you probably want to use `InvariantType`.
    ///
    /// # Example
    ///
    /// Given a struct `S` that includes a type parameter `T`
    /// but does not actually *reference* that type parameter:
    ///
    /// ```ignore
    /// use std::mem;
    ///
    /// struct S<T> { x: *() }
    /// fn get<T>(s: &S<T>) -> T {
    ///    unsafe {
    ///        let x: *T = mem::transmute(s.x);
    ///        *x
    ///    }
    /// }
    /// ```
    ///
    /// The type system would currently infer that the value of
    /// the type parameter `T` is irrelevant, and hence a `S<int>` is
    /// a subtype of `S<~[int]>` (or, for that matter, `S<U>` for
    /// any `U`). But this is incorrect because `get()` converts the
    /// `*()` into a `*T` and reads from it. Therefore, we should include the
    /// a marker field `CovariantType<T>` to inform the type checker that
    /// `S<T>` is a subtype of `S<U>` if `T` is a subtype of `U`
    /// (for example, `S<&'static int>` is a subtype of `S<&'a int>`
    /// for some lifetime `'a`, but not the other way around).
    #[lang="covariant_type"]
    #[deriving(PartialEq,Clone)]
    pub struct CovariantType<T>;

    /// A marker type whose type parameter `T` is considered to be
    /// contravariant with respect to the type itself. This is (typically)
    /// used to indicate that an instance of the type `T` will be consumed
    /// (but not read from), even though that may not be apparent.
    ///
    /// For more information about variance, refer to this Wikipedia
    /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
    ///
    /// *Note:* It is very unusual to have to add a contravariant constraint.
    /// If you are not sure, you probably want to use `InvariantType`.
    ///
    /// # Example
    ///
    /// Given a struct `S` that includes a type parameter `T`
    /// but does not actually *reference* that type parameter:
    ///
    /// ```
    /// use std::mem;
    ///
    /// struct S<T> { x: *() }
    /// fn get<T>(s: &S<T>, v: T) {
    ///    unsafe {
    ///        let x: fn(T) = mem::transmute(s.x);
    ///        x(v)
    ///    }
    /// }
    /// ```
    ///
    /// The type system would currently infer that the value of
    /// the type parameter `T` is irrelevant, and hence a `S<int>` is
    /// a subtype of `S<~[int]>` (or, for that matter, `S<U>` for
    /// any `U`). But this is incorrect because `get()` converts the
    /// `*()` into a `fn(T)` and then passes a value of type `T` to it.
    ///
    /// Supplying a `ContravariantType` marker would correct the
    /// problem, because it would mark `S` so that `S<T>` is only a
    /// subtype of `S<U>` if `U` is a subtype of `T`; given that the
    /// function requires arguments of type `T`, it must also accept
    /// arguments of type `U`, hence such a conversion is safe.
    #[lang="contravariant_type"]
    #[deriving(PartialEq,Clone)]
    pub struct ContravariantType<T>;

    /// A marker type whose type parameter `T` is considered to be
    /// invariant with respect to the type itself. This is (typically)
    /// used to indicate that instances of the type `T` may be read or
    /// written, even though that may not be apparent.
    ///
    /// For more information about variance, refer to this Wikipedia
    /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
    ///
    /// # Example
    ///
    /// The Cell type is an example which uses unsafe code to achieve
    /// "interior" mutability:
    ///
    /// ```
    /// pub struct Cell<T> { value: T }
    /// # fn main() {}
    /// ```
    ///
    /// The type system would infer that `value` is only read here and
    /// never written, but in fact `Cell` uses unsafe code to achieve
    /// interior mutability.
    #[lang="invariant_type"]
    #[deriving(PartialEq,Clone)]
    pub struct InvariantType<T>;

    /// As `CovariantType`, but for lifetime parameters. Using
    /// `CovariantLifetime<'a>` indicates that it is ok to substitute
    /// a *longer* lifetime for `'a` than the one you originally
    /// started with (e.g., you could convert any lifetime `'foo` to
    /// `'static`). You almost certainly want `ContravariantLifetime`
    /// instead, or possibly `InvariantLifetime`. The only case where
    /// it would be appropriate is that you have a (type-casted, and
    /// hence hidden from the type system) function pointer with a
    /// signature like `fn(&'a T)` (and no other uses of `'a`). In
    /// this case, it is ok to substitute a larger lifetime for `'a`
    /// (e.g., `fn(&'static T)`), because the function is only
    /// becoming more selective in terms of what it accepts as
    /// argument.
    ///
    /// For more information about variance, refer to this Wikipedia
    /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
    #[lang="covariant_lifetime"]
    #[deriving(PartialEq,Clone)]
    pub struct CovariantLifetime<'a>;

    /// As `ContravariantType`, but for lifetime parameters. Using
    /// `ContravariantLifetime<'a>` indicates that it is ok to
    /// substitute a *shorter* lifetime for `'a` than the one you
    /// originally started with (e.g., you could convert `'static` to
    /// any lifetime `'foo`). This is appropriate for cases where you
    /// have an unsafe pointer that is actually a pointer into some
    /// memory with lifetime `'a`, and thus you want to limit the
    /// lifetime of your data structure to `'a`. An example of where
    /// this is used is the iterator for vectors.
    ///
    /// For more information about variance, refer to this Wikipedia
    /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
    #[lang="contravariant_lifetime"]
    #[deriving(PartialEq,Clone)]
    pub struct ContravariantLifetime<'a>;

    /// As `InvariantType`, but for lifetime parameters. Using
    /// `InvariantLifetime<'a>` indicates that it is not ok to
    /// substitute any other lifetime for `'a` besides its original
    /// value. This is appropriate for cases where you have an unsafe
    /// pointer that is actually a pointer into memory with lifetime `'a`,
    /// and this pointer is itself stored in an inherently mutable
    /// location (such as a `Cell`).
    #[lang="invariant_lifetime"]
    #[deriving(PartialEq,Clone)]
    pub struct InvariantLifetime<'a>;

    /// A type which is considered "not sendable", meaning that it cannot
    /// be safely sent between tasks, even if it is owned. This is
    /// typically embedded in other types, such as `Gc`, to ensure that
    /// their instances remain thread-local.
    #[lang="no_send_bound"]
    #[deriving(PartialEq,Clone)]
    pub struct NoSend;

    /// A type which is considered "not POD", meaning that it is not
    /// implicitly copyable. This is typically embedded in other types to
    /// ensure that they are never copied, even if they lack a destructor.
    #[lang="no_copy_bound"]
    #[deriving(PartialEq,Clone)]
    pub struct NoCopy;

    /// A type which is considered "not shareable", meaning that
    /// its contents are not threadsafe, hence they cannot be
    /// shared between tasks.
    #[lang="no_share_bound"]
    #[deriving(PartialEq,Clone)]
    pub struct NoShare;

    /// A type which is considered managed by the GC. This is typically
    /// embedded in other types.
    #[lang="managed_bound"]
    #[deriving(PartialEq,Clone)]
    pub struct Managed;
}


text:
```ruby
describe secretsmanager('my-secret') do
  it { should exist }
end
```

### have_tag

```ruby
describe secretsmanager('my-secret') do
  it { should have_tag('Name').value('my-secret') }
end
```


text:
import Recaptcha from "./-recaptcha";
import { isNone } from '@ember/utils';

/**
 * Recaptcha v2 is when the user much check the challenge box to verify they
 * are not a robot. This process is manual. There is no need to override any
 * of the default functionality since there is no need to automatically execute
 * the verification process.
 */
export default class RecaptchaV2 extends Recaptcha {
  isNextDisabled () {
    return isNone (this.response);
  }
}


text:
<?php

namespace Google\AdsApi\AdWords\v201705\cm;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class AdGroupAdErrorReason
{
    const AD_GROUP_AD_LABEL_DOES_NOT_EXIST = 'AD_GROUP_AD_LABEL_DOES_NOT_EXIST';
    const AD_GROUP_AD_LABEL_ALREADY_EXISTS = 'AD_GROUP_AD_LABEL_ALREADY_EXISTS';
    const AD_NOT_UNDER_ADGROUP = 'AD_NOT_UNDER_ADGROUP';
    const CANNOT_OPERATE_ON_REMOVED_ADGROUPAD = 'CANNOT_OPERATE_ON_REMOVED_ADGROUPAD';
    const CANNOT_CREATE_DEPRECATED_ADS = 'CANNOT_CREATE_DEPRECATED_ADS';
    const CANNOT_CREATE_TEXT_ADS = 'CANNOT_CREATE_TEXT_ADS';
    const EMPTY_FIELD = 'EMPTY_FIELD';
    const ENTITY_REFERENCED_IN_MULTIPLE_OPS = 'ENTITY_REFERENCED_IN_MULTIPLE_OPS';
    const UNSUPPORTED_OPERATION = 'UNSUPPORTED_OPERATION';

}


text:
#include "ofc/parse.h"

static unsigned ofc_parse_stmt__dimension_virtual(
	const ofc_sparse_t* src, const char* ptr,
	ofc_parse_debug_t* debug,
	ofc_parse_keyword_e keyword,
	ofc_parse_stmt_t* stmt)
{
	unsigned dpos = ofc_parse_debug_position(debug);

	unsigned i = ofc_parse_keyword(
		src, ptr, debug, keyword);
	if (i == 0) return 0;

	unsigned len;
	stmt->dimension = ofc_parse_lhs_list(
		src, &ptr[i], debug, &len);
	if (!stmt->dimension)
	{
		ofc_parse_debug_rewind(debug, dpos);
		return 0;
	}
	i += len;

	stmt->type = OFC_PARSE_STMT_DIMENSION;
	return i;
}

unsigned ofc_parse_stmt_dimension(
	const ofc_sparse_t* src, const char* ptr,
	ofc_parse_debug_t* debug,
	ofc_parse_stmt_t* stmt)
{
	return ofc_parse_stmt__dimension_virtual(
		src, ptr, debug, OFC_PARSE_KEYWORD_DIMENSION, stmt);
}

/* http://docs.oracle.com/cd/E19957-01/805-4939/6j4m0vnbo/index.html */
unsigned ofc_parse_stmt_virtual(
	const ofc_sparse_t* src, const char* ptr,
	ofc_parse_debug_t* debug,
	ofc_parse_stmt_t* stmt)
{
	return ofc_parse_stmt__dimension_virtual(
		src, ptr, debug, OFC_PARSE_KEYWORD_VIRTUAL, stmt);
}

bool ofc_parse_stmt_dimension_print(
	ofc_colstr_t* cs, const ofc_parse_stmt_t* stmt)
{
	if (!stmt)
		return false;

	return (ofc_colstr_keyword_atomic_writez(cs, "DIMENSION")
		&& ofc_colstr_atomic_writef(cs, " ")
		&& ofc_parse_lhs_list_print(cs, stmt->dimension, true));
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using BuildsAppReborn.Contracts.Composition;
using BuildsAppReborn.Contracts.Models;

namespace BuildsAppReborn.Access.UI.ViewModel
{
    [IdentifierExport(typeof(VstsBuildProviderViewModel), VstsBuildProvider.Id)]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    internal class VstsBuildProviderViewModel : TfsBuildProviderViewModelBase
    {
        [ImportingConstructor]
        public VstsBuildProviderViewModel(IEqualityComparer<IBuildDefinition> buildDefinitionEqualityComparer)
            : base(buildDefinitionEqualityComparer)
        {
        }

        protected override String ProviderName => VstsBuildProvider.Name;
    }
}


text:
from pymel.util.common import path
import os
import json
import pymel.core as pm

# Patch for the broken getTransform in older pymel versions
pm.nt.Shape.getTransform = lambda x: x.getParent(generations=1)

title = 'Unreal Pipeline'
version = '1.07'

def UI():
    if pm.window('pbudk', exists=True):
        pm.deleteUI('pbudk')

    optspath = '%s/pbUDK.json' % pm.internalVar(usd=True)
    defaultdata = {'phyType': 1,
                   'maxVerts': 32,
                   'center': True,
                   'child': True,
                   'fbxPath': '%sdata/' % pm.workspace(q=True, rd=True),
                   'presetFile': '%s/UDKexport/UDK-FBX.fbxexportpreset' % pm.internalVar(usd=True),
                   'version': version,
                   'prefix': False,
                   'prefix_text': '',
                   'suffix': False,
                   'suffix_text': ''}

    with pm.window('pbudk', title="{0} - {1}".format(title, version), width=250, sizeable=True) as window:
        with pm.columnLayout():
            opts = JSONDict(optspath, defaultdata)
            PhyUI(opts)
            FbxUI(opts)
        window.show()

class PhyUI(object):
    def __init__(self, opts):
        self.opts = opts
        with pm.frameLayout('Physics', collapsable=True, cl=False, bs='out'):
            with pm.columnLayout(width=250):
                pm.text(l='Collision Type:')
                self.phyType = pm.radioButtonGrp(labelArray3=['Convex Hull', 'Box', 'Sphere'],
                                                 sl=self.opts['phyType'], nrb=3, cc=self.save,
                                                 cw3=[94, 64, 64], width=250)
                self.maxVerts = pm.intSliderGrp(field=True, l='Max Vertices:', v=self.opts['maxVerts'],
                                                cl3=['left', 'left', 'left'], cw3=[64, 48, 128], cc=self.save)
                pm.button(l='Add Hull', w=250, c=self._addHull)
        self.save()

    def _addHull(self, *args):
        if not pm.selected():
            return
        i = self.phyType.getSelect()
        if i == 1:
            self.convexHull()
        elif i == 2:
            self.boxHull()
        elif i == 3:
            self.sphereHull()

    def convexHull(self):
        sel = pm.selected()
        if not isinstance(sel[0], pm.nt.Transform):
            oldSel = sel
            sel = sel[0].node().getParent()
        else:
            oldSel = sel
            sel = sel[0]

        inputMesh = sel.getShape()
        hullNode = pm.createNode('DDConvexHull')
        outputNode = pm.createNode('mesh', n='UCX_{0}Shape_01'.format(sel))

        pm.connectAttr('%s.outMesh' % inputMesh, '%s.input[0].inputPolymesh' % hullNode)
        pm.connectAttr('%s.output' % hullNode, '%s.inMesh' % outputNode)

        hullNode.maxVertices.set(self.maxVerts.getValue())
        outputNode.getParent().setParent(sel)
        outputNode.getParent().translate.set(0, 0, 0)
        if not isinstance(oldSel[0], pm.nt.Transform):
            self.setComponents(oldSel, hullNode)

    def setComponents(self, sel, hullNode):
        coms = [str(i.name().split('.')[1]) for i in sel]
        hullNode.input[0].inputComponents.set(len(coms), *coms, type='componentList')

    @staticmethod
    def _get_bounds(sel):
        if sel > 1 and isinstance(sel[0], pm.Component):
            transform = sel[0].node().getTransform()
            t = pm.polyEvaluate(bc=True)
            bb = pm.dt.BoundingBox(pm.dt.Point(t[0][0], t[1][0], t[2][0]), pm.dt.Point(t[0][1], t[1][1], t[2][1]))
            verts = [i.getPosition() for i in pm.ls(pm.polyListComponentConversion(sel, tv=True), fl=True)]
            center = sum(verts) / len(verts)
        else:
            transform = sel[0]
            bb = sel[0].getBoundingBox()
            center = pm.objectCenter(sel[0])
        return bb, center, transform

    def boxHull(self):
        sel = pm.ls(sl=True, fl=True)
        bb, cnt, transform = self._get_bounds(sel)
        hull = pm.polyCube(w=bb.width(), h=bb.height(), d=bb.depth(), n='UCX_{0}_01'.format(transform))
        hull[0].setTranslation(cnt)
        sg = pm.PyNode('initialShadingGroup')
        sg.remove(hull[0].getShape())
        hull[0].setParent(transform)

    def sphereHull(self):
        sel = pm.ls(sl=True, fl=True)
        bb, cnt, transform = self._get_bounds(sel)
        hull = pm.polySphere(radius=max(bb.width(), bb.height(), bb.depth()) / 2, sx=8, sy=8,
                             n='UCX_{0}_01'.format(transform))
        hull[0].setTranslation(cnt)
        sg = pm.PyNode('initialShadingGroup')
        sg.remove(hull[0].getShape())
        hull[0].setParent(transform)

    def save(self, *args):
        self.opts['phyType'] = self.phyType.getSelect()
        self.opts['maxVerts'] = self.maxVerts.getValue()
        if self.phyType.getSelect() == 1:
            self.maxVerts.setEnable(True)
        else:
            self.maxVerts.setEnable(False)

class FbxUI(object):
    def __init__(self, opts):
        self.opts = opts
        with pm.frameLayout('Export Meshes (.FBX)', collapsable=True, cl=False, bs='out'):
            with pm.columnLayout(width=250):
                pm.text(l='Export List:')
                pm.separator(height=4)
                self.meshList = pm.textScrollList(height=250, width=250, ams=True, dkc=self._remove)
                with pm.rowColumnLayout(nc=3, cw=[(1, 82), (2, 82), (3, 82)]):
                    pm.button(l='Add', c=self._add)
                    pm.button(l='Remove', c=self._remove)
                    pm.button(l='Clear', c=self._clear)

                with pm.rowColumnLayout(nc=2, cw=[(1, 124), (2,124)]):
                    self.prefix = pm.checkBox(label='Prefix', value=self.opts['prefix'], cc=self.save)
                    self.suffix = pm.checkBox(label='Suffix', value=self.opts['suffix'], cc=self.save)
                    self.prefix_text = pm.textField(en=self.prefix.getValue(), text=self.opts['prefix_text'], cc=self.save)
                    self.suffix_text = pm.textField(en=self.suffix.getValue(), text=self.opts['suffix_text'], cc=self.save)

                pm.text(l='Export Path:')
                with pm.rowColumnLayout(nc=2, cw=[(1, 215), (2, 32)]):
                    self.fbxPath = pm.textField(text=self.opts['fbxPath'], cc=self._pathRefreash)
                    pm.button(l='...', c=self._path)

                with pm.rowColumnLayout(nc=3):
                    self.center = pm.checkBox(label='Move to Orgin', v=self.opts['center'], cc=self.save)
                    self.child = pm.checkBox(label='Export Childern', v=self.opts['child'], cc=self.save)
                    pm.button(l='FBXPreset', c=self._fbxPreset)

                with pm.rowColumnLayout(nc=2, cw=[(1, 124), (2, 124)]):
                    pm.button(l='Selected', c=self._selected)
                    pm.button(l='All', c=self._all)

        self._refresh()

    def _path(self, *args):
        exportPath = pm.fileDialog2(dir=path, fm=3, okc='Select Folder', cap='Select Export Folder')
        if exportPath:
            self.fbxPath.setText(exportPath[0])
            self.opts['fbxPath'] = exportPath[0]

    def _pathRefreash(self, text):
        self.opts['fbxPath'] = text

    def _selected(self, *args):
        self.export(self.fbxPath.getText(), all=False, center=self.center.getValue(), child=self.child.getValue())

    def _all(self, *args):
        self.export(self.fbxPath.getText(), all=True, center=self.center.getValue(), child=self.child.getValue())

    def _fbxPreset(self, *args):
        tempData = pm.fileDialog2(dir=path(self.opts['presetFile']).parent, fm=1, okc='Select Preset File',
                                  cap='Sselect FPXExportPreset File', ff='FBX Export Presets (*.fbxexportpreset)')
        if tempData:
            self.opts['presetFile'] = tempData[0]

    def _add(self, *args):
        sel = pm.selected()
        for i in sel:
            if isinstance(i, pm.nt.Transform):
                try:
                    i.pbExport.set(True)
                except:
                    i.addAttr('pbExport', at='bool')
                    i.pbExport.set(True)
        self._refresh()

    def _remove(self, *args):
        sel = self.meshList.getSelectItem()
        for i in sel:
            i = pm.PyNode(i)
            i.pbExport.delete()
        self._refresh()

    def _clear(self, *args):
        sel = pm.ls()
        for i in sel:
            if hasattr(i, 'pbExport'):
                i.pbExport.delete()
        self._refresh()

    def _refresh(self):
        self.meshList.removeAll()
        sel = pm.ls(type=pm.nt.Transform)
        for i in sel:
            if hasattr(i, 'pbExport') and i.pbExport.get() is True:
                self.meshList.append(i)

    def export(self, dirpath, all=False, center=True, child=True):
        if os.path.isfile(self.opts['presetFile']):
            pm.mel.FBXLoadExportPresetFile(f=self.opts['presetFile'])
        ext = '.fbx'

        if all:
            pm.select(self.meshList.getAllItems())
            sel = pm.selected()
        else:
            sel = pm.selected()

        if len(sel) == 0:
            pm.warning('Nothing is selected!')
        else:
            for obj in sel:
                pm.select(obj)
                if center:
                    oldLoc = obj.getRotatePivot()
                    self.centerPiv(obj)
                exportPath = self._get_filename(dirpath, obj.name(), ext)
                if child:
                    children = obj.getChildren()
                    for i in children:
                        if isinstance(i, pm.nt.Transform):
                            pm.select(i, add=True)
                pm.mel.FBXExport(f=exportPath, s=True)
                if center:
                    obj.setTranslation([oldLoc[0], oldLoc[1], oldLoc[2]])

    def _get_filename(self, dir, name, ext):
        file_name = "{0}{1}{2}{3}".format(
            self.prefix_text.getText() if self.prefix.getValue() else "",
            name,
            self.suffix_text.getText() if self.suffix.getValue() else "",
            ext
        )
        return dir + os.sep + file_name;

    def centerPiv(self, obj):
        pm.select(obj)
        pm.makeIdentity(apply=True, t=True, r=True, s=True, n=False)
        pos = obj.getRotatePivot()
        obj.translate.set(-1 * pos.x, -1 * pos.y, -1 * pos.z)
        pm.makeIdentity(apply=True, t=True, r=True, s=True, n=False)

    def save(self, *args):
        self.prefix_text.setEnable(self.prefix.getValue())
        self.suffix_text.setEnable(self.suffix.getValue())

        self.opts['center'] = self.center.getValue()
        self.opts['child'] = self.child.getValue()
        self.opts['fbxPath'] = self.fbxPath.getText()
        self.opts['prefix'] = self.prefix.getValue()
        self.opts['prefix_text'] = self.prefix_text.getText()
        self.opts['suffix'] = self.suffix.getValue()
        self.opts['suffix_text'] = self.suffix_text.getText()

class JSONDict(dict):
    def __init__(self, filename, defaults, *args, **kwargs):
        super(JSONDict, self).__init__(**kwargs)
        self.filename = filename
        self.defaults = defaults
        self._load()
        self.update(*args, **kwargs)

    def _load(self):
        if os.path.isfile(self.filename) and os.path.getsize(self.filename) > 0:
            with open(self.filename, 'r') as f:
                data = json.load(f)
                if 'version' in data and data['version'] == version:
                    self.update(data)
                else:
                    self._dumpdefaults()
        else:
            self._dumpdefaults()

    def _dump(self):
        with open(self.filename, 'w') as f:
            json.dump(self, f, sort_keys=True, indent=4)

    def _dumpdefaults(self):
        with open(self.filename, 'w') as f:
            json.dump(self.defaults, f, sort_keys=True, indent=4)
        self._load()

    def __getitem__(self, key):
        return dict.__getitem__(self, key)

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)
        self._dump()

    def __repr__(self):
        dictrepr = dict.__repr__(self)
        return '%s(%s)' % (type(self).__name__, dictrepr)

    def update(self, *args, **kwargs):
        for k, v in dict(*args, **kwargs).items():
            self[k] = v
        self._dump()

if __name__ == "__main__":
    UI()


text:
from astropy.io import fits as pyfits

# Conversion table from full filter names to single-letter abbreviations
# used in STARDUST and other S.Rodney code
FilterAlpha = {'unknown': '?',
               'F225W': 'S', 'F275W': 'T', 'F336W': 'U', 'F390W': 'C',
               'F350LP': 'W',
               'F435W': 'B', 'F475W': 'G', 'F606W': 'V', 'F625W': 'R',
               'F775W': 'X', 'F814W': 'I', 'F850LP': 'Z',
               'F125W': 'J', 'F160W': 'H', 'F125W+F160W': 'A',
               'F105W': 'Y', 'F110W': 'M', 'F140W': 'N',
               'F098M': 'L', 'F127M': 'O', 'F139M': 'P', 'F153M': 'Q',
               'G141': '4', 'G102': '2', 'blank': '0',
               'F689M': '6', 'F763M': '7', 'F845M': '8',
               }

def getheaderanddata(image, ext=None):
    """ Return a fits image header and data array.

    :param image: a string giving a fits filename, a pyfits hdulist or hdu,
      a pyfits primaryhdu object, a tuple or list giving [hdr,data]
    :param ext: (optional) extension number for science array
    :return:  pyfits.header.Header object and numpy data array
    """
    if isinstance(image, str):
        imfilename = image
        image = pyfits.open(imfilename)
    if isinstance(image, pyfits.hdu.hdulist.HDUList):
        if ext is not None:
            hdr = image[ext].header
            data = image[ext].data
        else:
            extnamelist = [hdu.name.lower() for hdu in image]
            if 'sci' in extnamelist:
                isci = extnamelist.index('sci')
                hdr = image[isci].header
                data = image[isci].data
            else:
                hdr = image[0].header
                data = image[0].data
    elif isinstance(image, pyfits.hdu.image.PrimaryHDU):
        hdr = image.header
        data = image.data
    elif isinstance(image, (tuple, list)):
        if len(image) == 2:
            hdr, data = image
        else:
            raise RuntimeError('Input list/tuple must have exactly'
                               ' 2 entries, giving [hdr,data]')
    else:
        raise RuntimeError('input object type %s is unrecognized')

    return hdr, data

def getcamera(image):
    """ Determine the camera name (e.g. ACS-WFC or WFC3-IR)
    from the header of the given image.

    :param image: any valid input to getheader(), namely:
      a string giving a fits filename, a pyfits hdulist or hdu, a pyfits
      header object, a tuple or list giving [hdr,data]

    :return: string giving the dash-separated camera name
    """
    hdr = getheader(image)
    instrument, detector = '', ''
    if 'CAMERA' in hdr:
        instrument = hdr['CAMERA']
        detector = ''
    elif 'INSTRUME' in hdr:
        instrument = hdr['INSTRUME']
    if 'DETECTOR' in hdr:
        detector = hdr['DETECTOR']
    camera = '-'.join([instrument, detector]).rstrip('-')
    return camera

def getfilter(image):
    """ Determine the filter name from the header of the given image.

    :param image: any valid input to getheader(), namely:
      a string giving a fits filename, a pyfits hdulist or hdu, a pyfits
      header object, a tuple or list giving [hdr,data]

    :return: string giving the filter name as it appears in the fits header.
    """
    hdr = getheader(image)
    if 'FILTER' in hdr:
        return hdr['FILTER']
    elif 'FILTER1' in hdr:
        if hdr['FILTER1'].startswith('CLEAR'):
            return hdr['FILTER2']
        else:
            return hdr['FILTER1']

def getheader(fitsfile, ext=None):
    """ Return a fits image header.

    :param image: a string giving a fits filename, a pyfits hdulist or hdu,
      a pyfits header object, a tuple or list giving [hdr,data]

    :return: the pyfits header object
    """
    from astropy.io import fits as pyfits

    if isinstance(fitsfile, (tuple, list)):
        hdr, data = fitsfile
    else:
        if isinstance(fitsfile, str):
            fitsfile = pyfits.open(fitsfile)
        if isinstance(fitsfile, pyfits.header.Header):
            hdr = fitsfile
        elif isinstance(fitsfile, pyfits.hdu.hdulist.HDUList):
            if ext is not None:
                hdr = fitsfile[ext].header
            else:
                extnamelist = [hdu.name.lower() for hdu in fitsfile]
                if 'sci' in extnamelist:
                    isci = extnamelist.index('sci')
                    hdr = fitsfile[isci].header
                else:
                    hdr = fitsfile[0].header
        elif isinstance(fitsfile, pyfits.hdu.image.PrimaryHDU):
            hdr = fitsfile.header
        else:
            raise RuntimeError('input object type %s is unrecognized')
    return hdr

def getwcsobj(imfile_or_hdr, ext=0):
    """Create a WCS object from the header of the given image file.
    Checks if the WCS SIP distortion coefficients are included in the header,
    and removes them if redundant.
    """
    from astropy.io import fits
    from astropy.wcs import WCS

    drizzled = False
    fobj = None
    imfilename = ''
    if isinstance(imfile_or_hdr, str):
        fobj = fits.open(imfile_or_hdr)
        header = fits.getheader(imfile_or_hdr, ext=ext)
        imfilename = imfile_or_hdr.lower()
    elif isinstance(imfile_or_hdr, fits.Header):
        header = imfile_or_hdr
        if 'FILENAME' in header:
            imfilename = header['FILENAME']
    else:
        return None

    if imfilename.endswith('_drz.fits') or imfilename.endswith('_drc.fits'):
        drizzled = True

    # decide if this is a drizzled image file with SIP coefficients
    gotsip = False
    if not drizzled and 'DRIZCORR' in header:
        drizzled = header['DRIZCORR'].lower() == 'complete'
    if 'A_ORDER' in header:
        gotsip = True

    if drizzled and gotsip:
        for coeff in ['A','B']:
            for ix in range(header[coeff+'_ORDER']):
                for iy in range(header[coeff+'_ORDER']):
                    key = '%s_%i_%i'%(coeff, ix, iy)
                    if key in header:
                        header.remove(key)
            if coeff+'_ORDER' in header:
                header.remove(coeff+'_ORDER')

    try:
        wcs = WCS(fobj=fobj, header=header)
        if fobj is not None:
            fobj.close()
    except KeyError:
        wcs = WCS(header=header)
    return wcs

def getxycenter(image, x, y, ext=0, radec=False,
                fitsconvention=False, verbose=False):
    """ Use a gaussian centroid algorithm to locate the center of a star
    near position x,y.

    :param image: any valid input to get_header_and_data(), namely:
      a string giving a fits filename, a pyfits hdulist or hdu, a pyfits
      primaryhdu object, a tuple or list giving [hdr,data]
    :param ext: (optional) extension number for science array
    :param radec: input coordinates are in RA,Dec instead of pixels
    :param fitsconvention: if True, then the input and output x,y pixel
        positions use the fits pixel indexing convention, with the center of
        the lower left pixel at (1,1). Otherwise this function uses the
        numpy/scipy convention which sets the center of the lower left pixel
        at (0,0).
    :param verbose: report progress verbosely
    :return: string giving the filter name as it appears in the fits header.
    """
    from PythonPhot import cntrd
    from astropy.io import fits as pyfits

    if radec:
        x, y = radec2xy(image, x, y, ext=ext)
    fwhmpix = getfwhmpix(image, ext=ext)
    imhdr, imdat = getheaderanddata(image, ext=ext)
    if fitsconvention:
        x, y = x - 1, y - 1
    xc, yc = cntrd.cntrd(imdat, x, y, fwhmpix, verbose=verbose)
    if xc == -1:
        if verbose:
            print('Recentering within a 5-pixel box')
        xc, yc = cntrd.cntrd(imdat, x, y, fwhmpix,
                             verbose=verbose, extendbox=5)
        if xc == -1: raise RuntimeError('Error : centroiding failed!')
    if fitsconvention:
        xc, yc = xc + 1, yc + 1
    return xc, yc

def getpixscale(image, returntuple=False, ext=None):
    """ Compute the pixel scale of the reference pixel in arcsec/pix in
    each direction from the fits header cd matrix.

    :param image: any valid input to getheader(), namely:
      a string giving a fits filename, a pyfits hdulist or hdu, a pyfits
      header object, a tuple or list giving [hdr,data]
    :param returntuple: bool. When True, return the two pixel scale values
         along the x and y axes.  When False, return the average of the two.
    :param ext: (optional) extension number for science array
    :return: float value or tuple giving the pixel scale in arcseconds/pixel.
    """
    from math import sqrt
    hdr = getheader(image, ext=ext)
    if 'CD1_1' in hdr:
        cd11 = hdr['CD1_1']
        cd12 = hdr['CD1_2']
        cd21 = hdr['CD2_1']
        cd22 = hdr['CD2_2']
        # define the sign based on determinant
        det = cd11 * cd22 - cd12 * cd21
        if det < 0:
            sgn = -1
        else:
            sgn = 1

        if cd12 == 0 and cd21 == 0:
            # no rotation: x=RA, y=Dec
            cdelt1 = cd11
            cdelt2 = cd22
        else:
            cdelt1 = sgn * sqrt(cd11 ** 2 + cd12 ** 2)
            cdelt2 = sqrt(cd22 ** 2 + cd21 ** 2)
    elif 'CDELT1' in hdr.keys() and \
            (hdr['CDELT1'] != 1 and hdr['CDELT2'] != 1):
        cdelt1 = hdr['CDELT1']
        cdelt2 = hdr['CDELT2']
    else:
        raise exceptions.RuntimeError(
            "Cannot identify CD matrix in %s" % image)
    cdelt1 *= 3600.
    cdelt2 *= 3600.
    if returntuple:
        return cdelt1, cdelt2
    else:
        return (abs(cdelt1) + abs(cdelt2)) / 2.

def getfwhmpix(image, ext=0):
    """ Determine the FWHM in pixels for this HST image.

    :param image: any valid input to getheader(), namely:
      a string giving a fits filename, a pyfits hdulist or hdu, a pyfits
      header object, a tuple or list giving [hdr,data]
    :param ext: (optional) extension number for science array
    :return: string giving the filter name as it appears in the fits header.
    """
    hdr = getheader(image, ext=ext)
    if ext != 0:
        hdr0 = getheader(image, ext=0)
    else:
        hdr0 = hdr
    camera = getcamera(hdr0)

    if camera == 'ACS-WFC':
        fwhmarcsec = 0.13
    elif camera == 'WFC3-UVIS':
        fwhmarcsec = 0.07
    elif camera == 'WFC3-IR':
        fwhmarcsec = 0.14
    elif ('TELESCOP' in hdr) and (hdr['TELESCOP'] == 'HST'):
        fwhmarcsec = 0.1
    else:
        print("WARNING : no instrument, detector or telescope identified."
              "  so we are arbitrarily setting the FWHM to 2.5 pixels for "
              "centroiding")
        return 2.5

    try:
        pixscale = getpixscale(hdr)
    except KeyError:
        print("WARNING : Can't determine the pixel scale from the header, "
              "  so we are arbitrarily setting the FWHM to 2.5 pixels for "
              "centroiding")
        return 2.5

    fwhmpix = fwhmarcsec / pixscale
    return fwhmpix

def xy2radec(imfile_or_hdr, x, y, ext=0):
    """ Convert the given x,y pixel position into
    ra,dec sky coordinates (in decimal degrees) for the given image.

    NOTE : this program assumes the input position follows the fits convention,
    with the center of the lower left pixel at (1,1).  The numpy/scipy
    convention sets the center of the lower left pixel at (0,0).

    :param imfile_or_hdr: image filename or astropy.io.fits Header object
    """
    wcs = getwcsobj(imfile_or_hdr, ext=ext)
    if wcs is None:
        print("WARNING: could not convert x,y to ra,dec for %s" %
              str(imfile_or_hdr))
        return 0, 0
    ra, dec = wcs.wcs_pix2world(x, y, 1)
    return ra, dec

def radec2xy(imfile, ra, dec, ext=0):
    """ Convert the given ra,dec position (in decimal degrees) into
    x,y pixel coordinates on the given image.
    NOTE : the pixel values returned are in the fits style, with the center
      of the lower left pixel at (1,1).  The numpy/scipy convention sets
      the center of the lower left pixel at (0,0).
    """
    wcs = getwcsobj(imfile, ext=ext)
    x, y = wcs.wcs_world2pix(ra, dec, 1)
    return x, y


text:
class Jena < Formula
  desc "Framework for building semantic web and linked data apps"
  homepage "https://jena.apache.org/"
  url "https://archive.apache.org/dist/jena/binaries/apache-jena-3.7.0.tar.gz"
  sha256 "b8127906690704b48f03c9d6bada29fae7744f67e7ccc9d8102b32486111818b"

  bottle :unneeded

  def shim_script(target)
    <<~EOS
      #!/usr/bin/env bash
      export JENA_HOME="#{libexec}"
      "$JENA_HOME/bin/#{target}" "$@"
    EOS
  end

  def install
    rm_rf "bat" # Remove Windows scripts

    prefix.install %w[LICENSE NOTICE README]
    libexec.install Dir["*"]
    Dir.glob("#{libexec}/bin/*") do |path|
      bin_name = File.basename(path)
      (bin/bin_name).write shim_script(bin_name)
    end
  end

  test do
    system "#{bin}/sparql", "--version"
  end
end


text:
import os
from random import Random
from typing import Optional
import unittest

from hwt.simulator.agentConnector import autoAddAgents, \
    collect_processes_from_sim_agents
from hwt.simulator.rtlSimulatorVcd import BasicRtlSimulatorVcd
from hwt.simulator.utils import reconnectUnitSignalsToModel, valToInt,\
    allValuesToInts
from hwt.synthesizer.dummyPlatform import DummyPlatform
from hwt.synthesizer.unit import Unit
from hwtSimApi.constants import CLK_PERIOD
from hwtSimApi.hdlSimulator import HdlSimulator
from hwtSimApi.triggers import Timer

class DummySimPlatform(DummyPlatform):
    """
    DummyPlatform which ignores the constraints
    (hardware constranints which specifying something for circuit synthesis for a vendor tool)
    """

_UNSPECIFIED = object()

class SimTestCase(unittest.TestCase):
    """
    This is TestCase class contains methods which are usually used during
    hdl simulation.

    :attention: self.procs has to be specified before runSim()
    :cvar _defaultSeed: default seed for random generator
    :cvar rtl_simulator_cls: class for RTL simulator to use
        (constructed in compileSim())
    :ivar ~.u: instance of current :class:`hwt.synthesizer.unit.Unit` for test, created in restartSim()
    :ivar ~.rtl_simulator: RTL simulator used for simulation of unit,
        created in restartSim()
    :ivar ~.hdl_simulator: the simulator which manages the communication
        between Python code and rtl_simulator instance
    :ivar ~.procs: list of simulation processes (Python generator instances),
        created in restartSim()
    :ivar ~.DEFAULT_BUILD_DIR: default directory where files for simulation should be stored
    :ivar ~.DEFAULT_LOG_DIR: default directory where simulation outputs should be stored
    :ivar ~.DEFAULT_SIMULATOR: default RTL simulator generator used on background of the test
    :ivar ~.RECOMPILE: if False the compilation of the simulation is dissabled.
        This is usefull while debugging of the simulation because compilation of simulation
        may take significant amount of time and may not be required.
    """
    # value chosen because in this position bits are changing frequently
    _defaultSeed = 317
    RECOMPILE = True
    rtl_simulator_cls = None
    hdl_simulator = None
    DEFAULT_BUILD_DIR = None  # "tmp"
    DEFAULT_LOG_DIR = "tmp"
    DEFAULT_SIMULATOR = BasicRtlSimulatorVcd

    def assertValEqual(self, first, second, msg=None):
        try:
            first = first.read()
        except AttributeError:
            pass

        if not isinstance(first, int) and first is not None:
            first = valToInt(first)

        return unittest.TestCase.assertEqual(self, first, second, msg=msg)

    def assertEmpty(self, val, msg=None):
        return unittest.TestCase.assertEqual(self, len(val), 0, msg=msg)

    def assertValSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
        """
        An equality assertion for ordered sequences (like lists and tuples).
        For the purposes of this function, a valid ordered sequence type is one
        which can be indexed, has a length, and has an equality operator.

        Args:

        :param seq1: can contain instance of values or nested list of them
        :param seq2: items are not converted, if item is None it is not checked
        :param seq_type: The expected data type of the sequences, or None if no
            data type should be enforced.
        :param msg: Optional message to use on failure instead of a list of
            differences.
        """
        seq1 = allValuesToInts(seq1)
        if len(seq1) == len(seq2):
            _seq2 = []
            # replace None in seq2 with values from seq1
            for v1, v2 in zip(seq1, seq2):
                if v2 is None:
                    v2 = v1
                _seq2.append(v2)
            seq2 = _seq2
        self.assertSequenceEqual(seq1, seq2, msg, seq_type)

    def getTestName(self):
        className, testName = self.id().split(".")[-2:]
        return f"{className:s}_{testName:s}"

    def runSim(self, until: float, name=None):
        if name is None:
            if self.DEFAULT_LOG_DIR is None:
                outputFileName = None
            else:
                outputFileName = os.path.join(self.DEFAULT_LOG_DIR,
                                              self.getTestName() + ".vcd")
        else:
            outputFileName = name

        if outputFileName is not None:
            d = os.path.dirname(outputFileName)
            if d:
                os.makedirs(d, exist_ok=True)

            self.rtl_simulator.set_trace_file(outputFileName, -1)
        procs = collect_processes_from_sim_agents(self.u)
        # run simulation, stimul processes are register after initial
        # initialization
        self.hdl_simulator.run(until=until, extraProcesses=self.procs + procs)
        self.rtl_simulator.finalize()
        return self.hdl_simulator

    def randomize(self, intf):
        """
        Randomly disable and enable interface for testing purposes
        """
        assert intf._isExtern, intf
        assert intf._ag is not None, intf
        randomEnProc = simpleRandomizationProcess(self, intf._ag)
        self.procs.append(randomEnProc())

    def restartSim(self):
        """
        Set simulator to initial state and connect it to

        :return: tuple (fully loaded unit with connected simulator,
            connected simulator,
            simulation processes
            )
        """
        rtl_simulator = self.rtl_simulator_cls()
        hdl_simulator = HdlSimulator(rtl_simulator)

        unit = self.u
        reconnectUnitSignalsToModel(unit, rtl_simulator)
        autoAddAgents(unit, hdl_simulator)
        self.procs = []
        self.u, self.rtl_simulator, self.hdl_simulator = \
            unit, rtl_simulator, hdl_simulator

        return unit, rtl_simulator, self.procs

    @classmethod
    def get_unique_name(cls, unit: Unit):
        uniq_name = unit._getDefaultName()
        return f"{cls.__name__:s}__{uniq_name:s}"

    @classmethod
    def compileSim(cls, unit, build_dir: Optional[str]=_UNSPECIFIED,
                   unique_name: Optional[str]=None, onAfterToRtl=None,
                   target_platform=DummySimPlatform()):
        """
        Create simulation model and connect it with interfaces of original unit
        and decorate it with agents

        :param unit: interface level unit which you wont prepare for simulation
        :param target_platform: target platform for this synthesis
        :param build_dir: folder to where to put sim model files,
            if None temporary folder is used and then deleted
            (or simulator will be constructed in memory if possible)
        :param unique_name: name which is used as name of the module for simulation
            (if is None it is automatically generated)
        :param onAfterToRtl: callback fn(unit) which will be called
            after unit will be synthesised to RTL
            and before :class:`hwt.synthesizer.unit.Unit` instance signals are replaced
            with simulator specific ones
        """
        if build_dir == _UNSPECIFIED:
            build_dir = cls.DEFAULT_BUILD_DIR

        if unique_name is None:
            unique_name = cls.get_unique_name(unit)

        cls.rtl_simulator_cls = cls.DEFAULT_SIMULATOR.build(
            unit,
            unique_name=unique_name,
            build_dir=build_dir,
            target_platform=target_platform,
            do_compile=cls.RECOMPILE)

        if onAfterToRtl:
            onAfterToRtl(unit)

        cls.u = unit

    def compileSimAndStart(
            self,
            unit: Unit,
            build_dir: Optional[str]=DEFAULT_BUILD_DIR,
            unique_name: Optional[str]=None,
            onAfterToRtl=None,
            target_platform=DummySimPlatform()):
        """
        Use this method if you did not used compileSim()
        to setup the simulator and DUT
        """
        if unique_name is None:
            t_name = self.getTestName()
            u_name = unit._getDefaultName()
            unique_name = f"{t_name:s}__{u_name:s}"
        self.compileSim(unit, build_dir, unique_name,
                        onAfterToRtl, target_platform)
        self.u = unit
        SimTestCase.setUp(self)
        return self.u

    def setUp(self):
        self._rand = Random(self._defaultSeed)
        if self.rtl_simulator_cls is not None:
            # if the simulator is not compiled it is expected
            # that it will be compiled in the test and this function
            # will be called later
            self.restartSim()

def simpleRandomizationProcess(tc: SimTestCase, agent, timeQuantum=CLK_PERIOD):
    """
    A process for simulator which will randomly enable/dissable the egent for an interface
    """
    seed = tc._rand.getrandbits(64)
    random = Random(seed)

    def randomEnProc():
        # small space at start to modify agents when they are inactive
        yield Timer(timeQuantum // 4)
        while True:
            en = random.random() < 0.5
            if agent.getEnable() != en:
                agent.setEnable(en)
            delay = int(random.random() * 2) * timeQuantum
            yield Timer(delay)

    return randomEnProc


text:
var args = arguments[0] || {};
var submittedFlag = false;
var current = args.date || new Date();

// 日時選択キャンセル
function cancelWindow(e) {
  submittedFlag = false;
  $.dateWindow.close();
}

// 現在に設定
function setToday() {
  $.datePicker.setValue(new Date());
}

// 日時選択決定
function submitWindow(e) {
  submittedFlag = true;
  $.dateWindow.close();
}

// 日時変更
function changeDate(e) {
  current = $.datePicker.getValue();
}

// ボタン位置調整
function adjustWidth() {
  var width = +$.wrapView2.width.replace('dp', '');
  var buttonWidth = (+$.cancelButton.width.replace('dp', '')) +
                    (+$.todayButton.width.replace('dp', '')) +
                    (+$.submitButton.width.replace('dp', ''));
  var interval = (width - buttonWidth) / 4;

  $.cancelButton.left = interval + 'dp';
  $.todayButton.left = interval + 'dp';
  $.submitButton.left = interval + 'dp';
}

// 設定した日時を他のコントローラから取得する
exports.getDate = function() {
  if(submittedFlag === true) {
    return current;
  } else {
    return null;
  }
};

adjustWidth();
$.datePicker.setValue(current);