text:
"""
Timed event scheduling for Axiom databases.

With this module, applications can schedule an L{Item} to have its C{run} method
called at a particular point in the future.  This call will happen even if the
process which initially schedules it exits and the database is later re-opened
by another process (of course, if the scheduled time comes and goes while no
process is using the database, then the call will be delayed until some process
opens the database and starts its services).

This module contains two implementations of the L{axiom.iaxiom.IScheduler}
interface, one for site stores and one for sub-stores.  Items can only be
scheduled using an L{IScheduler} implementations from the store containing the
item.  This means a typical way to schedule an item to be run is::

    IScheduler(item.store).schedule(item, when)

The scheduler service can also be retrieved from the site store's service
collection by name::

    IServiceCollection(siteStore).getServiceNamed(SITE_SCHEDULER)
"""

import warnings

from zope.interface import implementer

from twisted.internet import reactor

from twisted.application.service import IService, Service
from twisted.python import log, failure

from epsilon.extime import Time

from axiom.iaxiom import IScheduler
from axiom.item import Item, declareLegacyItem
from axiom.attributes import AND, timestamp, reference, integer, inmemory, bytes
from axiom.dependency import uninstallFrom
from axiom.upgrade import registerUpgrader
from axiom.substore import SubStore

VERBOSE = False

SITE_SCHEDULER = "Site Scheduler"

class TimedEventFailureLog(Item):
    typeName = 'timed_event_failure_log'
    schemaVersion = 1

    desiredTime = timestamp()
    actualTime = timestamp()

    runnable = reference()
    traceback = bytes()

class TimedEvent(Item):
    typeName = 'timed_event'
    schemaVersion = 1

    time = timestamp(indexed=True)
    runnable = reference()

    running = inmemory(doc='True if this event is currently running.')

    def activate(self):
        self.running = False

    def _rescheduleFromRun(self, newTime):
        """
        Schedule this event to be run at the indicated time, or if the
        indicated time is None, delete this event.
        """
        if newTime is None:
            self.deleteFromStore()
        else:
            self.time = newTime

    def invokeRunnable(self):
        """
        Run my runnable, and reschedule or delete myself based on its result.
        Must be run in a transaction.
        """
        runnable = self.runnable
        if runnable is None:
            self.deleteFromStore()
        else:
            try:
                self.running = True
                newTime = runnable.run()
            finally:
                self.running = False
            self._rescheduleFromRun(newTime)

    def handleError(self, now, failureObj):
        """ An error occurred running my runnable.  Check my runnable for an
        error-handling method called 'timedEventErrorHandler' that will take
        the given failure as an argument, and execute that if available:
        otherwise, create a TimedEventFailureLog with information about what
        happened to this event.

        Must be run in a transaction.
        """
        errorHandler = getattr(self.runnable, 'timedEventErrorHandler', None)
        if errorHandler is not None:
            self._rescheduleFromRun(errorHandler(self, failureObj))
        else:
            self._defaultErrorHandler(now, failureObj)

    def _defaultErrorHandler(self, now, failureObj):
        tracebackText = failureObj.getTraceback()
        if not isinstance(tracebackText, bytes):
            tracebackText = tracebackText.encode("utf-8")
        TimedEventFailureLog(store=self.store,
                             desiredTime=self.time,
                             actualTime=now,
                             runnable=self.runnable,
                             traceback=tracebackText)
        self.deleteFromStore()

class _WackyControlFlow(Exception):
    def __init__(self, eventObject, failureObject):
        Exception.__init__(self, "User code failed during timed event")
        self.eventObject = eventObject
        self.failureObject = failureObject

MAX_WORK_PER_TICK = 10

class SchedulerMixin:
    def _oneTick(self, now):
        theEvent = self._getNextEvent(now)
        if theEvent is None:
            return False
        try:
            theEvent.invokeRunnable()
        except:
            raise _WackyControlFlow(theEvent, failure.Failure())
        self.lastEventAt = now
        return True

    def _getNextEvent(self, now):
        # o/` gonna party like it's 1984 o/`
        theEventL = list(self.store.query(TimedEvent,
                                          TimedEvent.time <= now,
                                          sort=TimedEvent.time.ascending,
                                          limit=1))
        if theEventL:
            return theEventL[0]

    def tick(self):
        now = self.now()
        self.nextEventAt = None
        workBeingDone = True
        workUnitsPerformed = 0
        errors = 0
        while workBeingDone and workUnitsPerformed < MAX_WORK_PER_TICK:
            try:
                workBeingDone = self.store.transact(self._oneTick, now)
            except _WackyControlFlow as wcf:
                self.store.transact(wcf.eventObject.handleError, now, wcf.failureObject)
                log.err(wcf.failureObject)
                errors += 1
                workBeingDone = True
            if workBeingDone:
                workUnitsPerformed += 1
        x = list(self.store.query(TimedEvent, sort=TimedEvent.time.ascending, limit=1))
        if x:
            self._transientSchedule(x[0].time, now)
        if errors or VERBOSE:
            log.msg("The scheduler ran %(eventCount)s events%(errors)s." % dict(
                    eventCount=workUnitsPerformed,
                    errors=(errors and (" (with %d errors)" % (errors,))) or ''))

    def schedule(self, runnable, when):
        TimedEvent(store=self.store, time=when, runnable=runnable)
        self._transientSchedule(when, self.now())

    def reschedule(self, runnable, fromWhen, toWhen):
        for evt in self.store.query(TimedEvent,
                                    AND(TimedEvent.time == fromWhen,
                                        TimedEvent.runnable == runnable)):
            evt.time = toWhen
            self._transientSchedule(toWhen, self.now())
            break
        else:
            raise ValueError("{!r} is not scheduled to run at {!r}".format(runnable, fromWhen))

    def unscheduleFirst(self, runnable):
        """
        Remove from given item from the schedule.

        If runnable is scheduled to run multiple times, only the temporally first
        is removed.
        """
        for evt in self.store.query(TimedEvent, TimedEvent.runnable == runnable, sort=TimedEvent.time.ascending):
            evt.deleteFromStore()
            break

    def unscheduleAll(self, runnable):
        for evt in self.store.query(TimedEvent, TimedEvent.runnable == runnable):
            evt.deleteFromStore()

    def scheduledTimes(self, runnable):
        """
        Return an iterable of the times at which the given item is scheduled to
        run.
        """
        events = self.store.query(
            TimedEvent, TimedEvent.runnable == runnable)
        return (event.time for event in events if not event.running)

_EPSILON = 1e-20      # A very small amount of time.

@implementer(IScheduler)
class _SiteScheduler(SchedulerMixin, Service, object):
    """
    Adapter from a site store to L{IScheduler}.
    """
    timer = None
    callLater = reactor.callLater
    now = Time

    def __init__(self, store):
        self.store = store
        self.setName(SITE_SCHEDULER)

    def startService(self):
        """
        Start calling persistent timed events whose time has come.
        """
        super(_SiteScheduler, self).startService()
        self._transientSchedule(self.now(), self.now())

    def stopService(self):
        """
        Stop calling persistent timed events.
        """
        super(_SiteScheduler, self).stopService()
        if self.timer is not None:
            self.timer.cancel()
            self.timer = None

    def tick(self):
        self.timer = None
        return super(_SiteScheduler, self).tick()

    def _transientSchedule(self, when, now):
        """
        If the service is currently running, schedule a tick to happen no
        later than C{when}.

        @param when: The time at which to tick.
        @type when: L{epsilon.extime.Time}

        @param now: The current time.
        @type now: L{epsilon.extime.Time}
        """
        if not self.running:
            return
        if self.timer is not None:
            if self.timer.getTime() < when.asPOSIXTimestamp():
                return
            self.timer.cancel()
        delay = when.asPOSIXTimestamp() - now.asPOSIXTimestamp()

        # reactor.callLater allows only positive delay values.  The scheduler
        # may want to have scheduled things in the past and that's OK, since we
        # are dealing with Time() instances it's impossible to predict what
        # they are relative to the current time from user code anyway.
        delay = max(_EPSILON, delay)
        self.timer = self.callLater(delay, self.tick)
        self.nextEventAt = when

@implementer(IScheduler)
class _UserScheduler(SchedulerMixin, Service, object):
    """
    Adapter from a non-site store to L{IScheduler}.
    """
    def __init__(self, store):
        self.store = store

    def now(self):
        """
        Report the current time, as reported by the parent's scheduler.
        """
        return IScheduler(self.store.parent).now()

    def _transientSchedule(self, when, now):
        """
        If this service's store is attached to its parent, ask the parent to
        schedule this substore to tick at the given time.

        @param when: The time at which to tick.
        @type when: L{epsilon.extime.Time}

        @param now: Present for signature compatibility with
            L{_SiteScheduler._transientSchedule}, but ignored otherwise.
        """
        if self.store.parent is not None:
            subStore = self.store.parent.getItemByID(self.store.idInParent)
            hook = self.store.parent.findOrCreate(
                _SubSchedulerParentHook,
                subStore=subStore)
            hook._schedule(when)

    def migrateDown(self):
        """
        Remove the components in the site store for this SubScheduler.
        """
        subStore = self.store.parent.getItemByID(self.store.idInParent)
        ssph = self.store.parent.findUnique(
            _SubSchedulerParentHook,
            _SubSchedulerParentHook.subStore == subStore,
            default=None)
        if ssph is not None:
            te = self.store.parent.findUnique(TimedEvent,
                                              TimedEvent.runnable == ssph,
                                              default=None)
            if te is not None:
                te.deleteFromStore()
            ssph.deleteFromStore()

    def migrateUp(self):
        """
        Recreate the hooks in the site store to trigger this SubScheduler.
        """
        te = self.store.findFirst(TimedEvent, sort=TimedEvent.time.descending)
        if te is not None:
            self._transientSchedule(te.time, None)

@implementer(IScheduler)
class _SchedulerCompatMixin(object):
    """
    Backwards compatibility helper for L{Scheduler} and L{SubScheduler}.

    This mixin provides all the attributes from L{IScheduler}, but provides
    them by adapting the L{Store} the item is in to L{IScheduler} and
    getting them from the resulting object.  Primarily in support of test
    code, it also supports rebinding those attributes by rebinding them on
    the L{IScheduler} powerup.

    @see: L{IScheduler}
    """
    def forwardToReal(name):
        def get(self):
            return getattr(IScheduler(self.store), name)
        def set(self, value):
            setattr(IScheduler(self.store), name, value)
        return property(get, set)

    now = forwardToReal("now")
    tick = forwardToReal("tick")
    schedule = forwardToReal("schedule")
    reschedule = forwardToReal("reschedule")
    unschedule = forwardToReal("unschedule")
    unscheduleAll = forwardToReal("unscheduleAll")
    scheduledTimes = forwardToReal("scheduledTimes")

    def activate(self):
        """
        Whenever L{Scheduler} or L{SubScheduler} is created, either newly or
        when loaded from a database, emit a deprecation warning referring
        people to L{IScheduler}.
        """
        # This is unfortunate.  Perhaps it is the best thing which works (it is
        # the first I found). -exarkun
        if '_axiom_memory_dummy' in vars(self):
            stacklevel = 7
        else:
            stacklevel = 5
        warnings.warn(
            self.__class__.__name__ + " is deprecated since Axiom 0.5.32.  "
            "Just adapt stores to IScheduler.",
            category=PendingDeprecationWarning,
            stacklevel=stacklevel)

@implementer(IService)
class Scheduler(Item, _SchedulerCompatMixin):
    """
    Track and execute persistent timed events for a I{site} store.

    This is deprecated and present only for backwards compatibility.  Adapt
    the store to L{IScheduler} instead.
    """
    typeName = 'axiom_scheduler'
    schemaVersion = 2

    dummy = integer()

    def activate(self):
        _SchedulerCompatMixin.activate(self)

    def setServiceParent(self, parent):
        """
        L{Scheduler} is no longer an L{IService}, but still provides this
        method as a no-op in case an instance which was still an L{IService}
        powerup is loaded (in which case it will be used like a service
        once).
        """

declareLegacyItem(
    Scheduler.typeName, 1,
    dict(eventsRun=integer(default=0),
         lastEventAt=timestamp(),
         nextEventAt=timestamp()))

def scheduler1to2(old):
    new = old.upgradeVersion(Scheduler.typeName, 1, 2)
    new.store.powerDown(new, IService)
    new.store.powerDown(new, IScheduler)
    return new

registerUpgrader(scheduler1to2, Scheduler.typeName, 1, 2)

class _SubSchedulerParentHook(Item):
    schemaVersion = 4
    typeName = 'axiom_subscheduler_parent_hook'

    subStore = reference(
        doc="""
        The L{SubStore} for which this scheduling hook exists.
        """, reftype=SubStore)

    def run(self):
        """
        Tick our C{subStore}'s L{SubScheduler}.
        """
        IScheduler(self.subStore).tick()

    def _schedule(self, when):
        """
        Ensure that this hook is scheduled to run at or before C{when}.
        """
        sched = IScheduler(self.store)
        for scheduledAt in sched.scheduledTimes(self):
            # https://github.com/twisted/epsilon/issues/38
            if when._time < scheduledAt._time:
                sched.reschedule(self, scheduledAt, when)
            break
        else:
            sched.schedule(self, when)

def upgradeParentHook1to2(oldHook):
    """
    Add the scheduler attribute to the given L{_SubSchedulerParentHook}.
    """
    newHook = oldHook.upgradeVersion(
        oldHook.typeName, 1, 2,
        loginAccount=oldHook.loginAccount,
        scheduledAt=oldHook.scheduledAt,
        scheduler=oldHook.store.findFirst(Scheduler))
    return newHook

registerUpgrader(upgradeParentHook1to2, _SubSchedulerParentHook.typeName, 1, 2)

declareLegacyItem(
    _SubSchedulerParentHook.typeName, 2,
    dict(loginAccount=reference(),
         scheduledAt=timestamp(default=None),
         scheduler=reference()))

def upgradeParentHook2to3(old):
    """
    Copy the C{loginAccount} attribute, but drop the others.
    """
    return old.upgradeVersion(
        old.typeName, 2, 3,
        loginAccount=old.loginAccount)

registerUpgrader(upgradeParentHook2to3, _SubSchedulerParentHook.typeName, 2, 3)

declareLegacyItem(
    _SubSchedulerParentHook.typeName, 3,
    dict(loginAccount=reference(),
         scheduler=reference()))

def upgradeParentHook3to4(old):
    """
    Copy C{loginAccount} to C{subStore} and remove the installation marker.
    """
    new = old.upgradeVersion(
        old.typeName, 3, 4, subStore=old.loginAccount)
    uninstallFrom(new, new.store)
    return new

registerUpgrader(upgradeParentHook3to4, _SubSchedulerParentHook.typeName, 3, 4)

class SubScheduler(Item, _SchedulerCompatMixin):
    """
    Track and execute persistent timed events for a substore.

    This is deprecated and present only for backwards compatibility.  Adapt
    the store to L{IScheduler} instead.
    """
    schemaVersion = 2
    typeName = 'axiom_subscheduler'

    dummy = integer()

    def activate(self):
        _SchedulerCompatMixin.activate(self)

def subscheduler1to2(old):
    new = old.upgradeVersion(SubScheduler.typeName, 1, 2)
    try:
        new.store.powerDown(new, IScheduler)
    except ValueError:
        # Someone might have created a SubScheduler but failed to power it
        # up.  Fine.
        pass
    return new

registerUpgrader(subscheduler1to2, SubScheduler.typeName, 1, 2)


text:
.class public Landroid/security/net/config/ResourceCertificateSource;
.super Ljava/lang/Object;
.source "ResourceCertificateSource.java"

# interfaces
.implements Landroid/security/net/config/CertificateSource;

# instance fields
.field private mCertificates:Ljava/util/Set;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/Set",
            "<",
            "Ljava/security/cert/X509Certificate;",
            ">;"
        }
    .end annotation
.end field

.field private mContext:Landroid/content/Context;

.field private mIndex:Lcom/android/org/conscrypt/TrustedCertificateIndex;

.field private final mLock:Ljava/lang/Object;

.field private final mResourceId:I

# direct methods
.method public constructor <init>(ILandroid/content/Context;)V
    .locals 1

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    new-instance v0, Ljava/lang/Object;

    invoke-direct {v0}, Ljava/lang/Object;-><init>()V

    iput-object v0, p0, Landroid/security/net/config/ResourceCertificateSource;->mLock:Ljava/lang/Object;

    iput p1, p0, Landroid/security/net/config/ResourceCertificateSource;->mResourceId:I

    iput-object p2, p0, Landroid/security/net/config/ResourceCertificateSource;->mContext:Landroid/content/Context;

    return-void
.end method

.method private ensureInitialized()V
    .locals 13

    iget-object v10, p0, Landroid/security/net/config/ResourceCertificateSource;->mLock:Ljava/lang/Object;

    monitor-enter v10

    :try_start_0
    iget-object v9, p0, Landroid/security/net/config/ResourceCertificateSource;->mCertificates:Ljava/util/Set;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    if-eqz v9, :cond_0

    monitor-exit v10

    return-void

    :cond_0
    :try_start_1
    new-instance v3, Landroid/util/ArraySet;

    invoke-direct {v3}, Landroid/util/ArraySet;-><init>()V
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    const/4 v7, 0x0

    :try_start_2
    const-string/jumbo v9, "X.509"

    invoke-static {v9}, Ljava/security/cert/CertificateFactory;->getInstance(Ljava/lang/String;)Ljava/security/cert/CertificateFactory;

    move-result-object v6

    iget-object v9, p0, Landroid/security/net/config/ResourceCertificateSource;->mContext:Landroid/content/Context;

    invoke-virtual {v9}, Landroid/content/Context;->getResources()Landroid/content/res/Resources;

    move-result-object v9

    iget v11, p0, Landroid/security/net/config/ResourceCertificateSource;->mResourceId:I

    invoke-virtual {v9, v11}, Landroid/content/res/Resources;->openRawResource(I)Ljava/io/InputStream;

    move-result-object v7

    invoke-virtual {v6, v7}, Ljava/security/cert/CertificateFactory;->generateCertificates(Ljava/io/InputStream;)Ljava/util/Collection;
    :try_end_2
    .catch Ljava/security/cert/CertificateException; {:try_start_2 .. :try_end_2} :catch_0
    .catchall {:try_start_2 .. :try_end_2} :catchall_1

    move-result-object v4

    :try_start_3
    invoke-static {v7}, Llibcore/io/IoUtils;->closeQuietly(Ljava/lang/AutoCloseable;)V

    new-instance v8, Lcom/android/org/conscrypt/TrustedCertificateIndex;

    invoke-direct {v8}, Lcom/android/org/conscrypt/TrustedCertificateIndex;-><init>()V

    invoke-interface {v4}, Ljava/lang/Iterable;->iterator()Ljava/util/Iterator;

    move-result-object v2

    :goto_0
    invoke-interface {v2}, Ljava/util/Iterator;->hasNext()Z

    move-result v9

    if-eqz v9, :cond_1

    invoke-interface {v2}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Ljava/security/cert/Certificate;

    move-object v0, v1

    check-cast v0, Ljava/security/cert/X509Certificate;

    move-object v9, v0

    invoke-interface {v3, v9}, Ljava/util/Set;->add(Ljava/lang/Object;)Z

    check-cast v1, Ljava/security/cert/X509Certificate;

    invoke-virtual {v8, v1}, Lcom/android/org/conscrypt/TrustedCertificateIndex;->index(Ljava/security/cert/X509Certificate;)Ljava/security/cert/TrustAnchor;
    :try_end_3
    .catchall {:try_start_3 .. :try_end_3} :catchall_0

    goto :goto_0

    :catchall_0
    move-exception v9

    monitor-exit v10

    throw v9

    :catch_0
    move-exception v5

    :try_start_4
    new-instance v9, Ljava/lang/RuntimeException;

    new-instance v11, Ljava/lang/StringBuilder;

    invoke-direct {v11}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v12, "Failed to load trust anchors from id "

    invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v11

    iget v12, p0, Landroid/security/net/config/ResourceCertificateSource;->mResourceId:I

    invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v11

    invoke-virtual {v11}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v11

    invoke-direct {v9, v11, v5}, Ljava/lang/RuntimeException;-><init>(Ljava/lang/String;Ljava/lang/Throwable;)V

    throw v9
    :try_end_4
    .catchall {:try_start_4 .. :try_end_4} :catchall_1

    :catchall_1
    move-exception v9

    :try_start_5
    invoke-static {v7}, Llibcore/io/IoUtils;->closeQuietly(Ljava/lang/AutoCloseable;)V

    throw v9

    :cond_1
    iput-object v3, p0, Landroid/security/net/config/ResourceCertificateSource;->mCertificates:Ljava/util/Set;

    iput-object v8, p0, Landroid/security/net/config/ResourceCertificateSource;->mIndex:Lcom/android/org/conscrypt/TrustedCertificateIndex;

    const/4 v9, 0x0

    iput-object v9, p0, Landroid/security/net/config/ResourceCertificateSource;->mContext:Landroid/content/Context;
    :try_end_5
    .catchall {:try_start_5 .. :try_end_5} :catchall_0

    monitor-exit v10

    return-void
.end method

# virtual methods
.method public findAllByIssuerAndSignature(Ljava/security/cert/X509Certificate;)Ljava/util/Set;
    .locals 5
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/security/cert/X509Certificate;",
            ")",
            "Ljava/util/Set",
            "<",
            "Ljava/security/cert/X509Certificate;",
            ">;"
        }
    .end annotation

    invoke-direct {p0}, Landroid/security/net/config/ResourceCertificateSource;->ensureInitialized()V

    iget-object v4, p0, Landroid/security/net/config/ResourceCertificateSource;->mIndex:Lcom/android/org/conscrypt/TrustedCertificateIndex;

    invoke-virtual {v4, p1}, Lcom/android/org/conscrypt/TrustedCertificateIndex;->findAllByIssuerAndSignature(Ljava/security/cert/X509Certificate;)Ljava/util/Set;

    move-result-object v2

    invoke-interface {v2}, Ljava/util/Set;->isEmpty()Z

    move-result v4

    if-eqz v4, :cond_0

    invoke-static {}, Ljava/util/Collections;->emptySet()Ljava/util/Set;

    move-result-object v4

    return-object v4

    :cond_0
    new-instance v3, Landroid/util/ArraySet;

    invoke-interface {v2}, Ljava/util/Set;->size()I

    move-result v4

    invoke-direct {v3, v4}, Landroid/util/ArraySet;-><init>(I)V

    invoke-interface {v2}, Ljava/lang/Iterable;->iterator()Ljava/util/Iterator;

    move-result-object v1

    :goto_0
    invoke-interface {v1}, Ljava/util/Iterator;->hasNext()Z

    move-result v4

    if-eqz v4, :cond_1

    invoke-interface {v1}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/security/cert/TrustAnchor;

    invoke-virtual {v0}, Ljava/security/cert/TrustAnchor;->getTrustedCert()Ljava/security/cert/X509Certificate;

    move-result-object v4

    invoke-interface {v3, v4}, Ljava/util/Set;->add(Ljava/lang/Object;)Z

    goto :goto_0

    :cond_1
    return-object v3
.end method

.method public findByIssuerAndSignature(Ljava/security/cert/X509Certificate;)Ljava/security/cert/X509Certificate;
    .locals 3

    const/4 v2, 0x0

    invoke-direct {p0}, Landroid/security/net/config/ResourceCertificateSource;->ensureInitialized()V

    iget-object v1, p0, Landroid/security/net/config/ResourceCertificateSource;->mIndex:Lcom/android/org/conscrypt/TrustedCertificateIndex;

    invoke-virtual {v1, p1}, Lcom/android/org/conscrypt/TrustedCertificateIndex;->findByIssuerAndSignature(Ljava/security/cert/X509Certificate;)Ljava/security/cert/TrustAnchor;

    move-result-object v0

    if-nez v0, :cond_0

    return-object v2

    :cond_0
    invoke-virtual {v0}, Ljava/security/cert/TrustAnchor;->getTrustedCert()Ljava/security/cert/X509Certificate;

    move-result-object v1

    return-object v1
.end method

.method public findBySubjectAndPublicKey(Ljava/security/cert/X509Certificate;)Ljava/security/cert/X509Certificate;
    .locals 3

    const/4 v2, 0x0

    invoke-direct {p0}, Landroid/security/net/config/ResourceCertificateSource;->ensureInitialized()V

    iget-object v1, p0, Landroid/security/net/config/ResourceCertificateSource;->mIndex:Lcom/android/org/conscrypt/TrustedCertificateIndex;

    invoke-virtual {v1, p1}, Lcom/android/org/conscrypt/TrustedCertificateIndex;->findBySubjectAndPublicKey(Ljava/security/cert/X509Certificate;)Ljava/security/cert/TrustAnchor;

    move-result-object v0

    if-nez v0, :cond_0

    return-object v2

    :cond_0
    invoke-virtual {v0}, Ljava/security/cert/TrustAnchor;->getTrustedCert()Ljava/security/cert/X509Certificate;

    move-result-object v1

    return-object v1
.end method

.method public getCertificates()Ljava/util/Set;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/util/Set",
            "<",
            "Ljava/security/cert/X509Certificate;",
            ">;"
        }
    .end annotation

    invoke-direct {p0}, Landroid/security/net/config/ResourceCertificateSource;->ensureInitialized()V

    iget-object v0, p0, Landroid/security/net/config/ResourceCertificateSource;->mCertificates:Ljava/util/Set;

    return-object v0
.end method

.method public handleTrustStorageUpdate()V
    .locals 0

    return-void
.end method

redpajama_set_name: RedPajamaGithub


text:
//
// BayesianFilter.h
//
// Non-linear Baysian filtering for EMG Enveloppe Extraction.
// Based on Matlab code by Terence Sanger : kidsmove.org/bayesemgdemo.html
//
// Reference:
// - Sanger, T. (2007). Bayesian filtering of myoelectric signals. Journal of neurophysiology, 1839–1845.
//
//
// Copyright (C) 2013-2014 by IRCAM - Centre Pompidou. All Rights Reserved.
// author: Jules Francoise
// contact: jules.francoise@ircam.fr
//
// created 2013-12-24
//

#ifndef __emg_bayesfilter__BayesianFilter__
#define __emg_bayesfilter__BayesianFilter__

#include <algorithm>
#include <iostream>
#include <cmath>
#include <vector>

using namespace std;

/*!
	@class BayesianFilter
	@brief Main class for non-linear Bayesian fitering

	@copyright Copyright 2013 Ircam - Jules Francoise. All Rights Reserved.
	@author Jules Francoise - Ircam - jules.francoise@ircam.fr
	@date 2013-12-26
 */
class BayesianFilter {
public:
#pragma mark -
#pragma mark Public attributes
    vector<float> output; //<! bayes estimates

#pragma mark -
#pragma mark Constructors
    /*!
     Constructor
     @param _samplerate Sampling frequency of input stream
     @param _clipping Signal Clipping
     @param _alpha Diffusion rate
     @param _beta Probability of sudden jumps
     @param _levels number of output levels
     @param _rectification signal rectification
     */
    BayesianFilter();

    ~BayesianFilter();

    void resize(std::size_t size);
    std::size_t size() const;

#pragma mark -
#pragma mark Main Algorithm
    /*!
     @brief Initialize filter
     Resets Prior to uniform distribution
     */
    void init();

    /*!
     @brief Update filter state and compute prediction.

     The output of the system (envelope estimated by Maximum A Posteriori) is stored in the public member output
     @param observation observation (input) vector
     */
    void update(vector<float> const& observation);

#pragma mark -
#pragma mark Python
#ifdef SWIGPYTHON
	void update(int _inchannels, double *observation, int _outchannels, double *_output)
	{
	    vector<float> observation_vec(_inchannels);
        for (unsigned int t=0; t<_inchannels; t++)
            observation_vec[t] = float(observation[t]);

        this->update(observation_vec);

	    for (unsigned int t=0; t<_inchannels; t++)
            _output[t] = double(this->output[t]);
	}
#endif

    /**
     @brief Maximum Value contraction (estimated using Standard deviation on isometric max contraction)
     */
    std::vector<double> mvc;

    /**
     @brief Number of output levels
     */
    unsigned int levels = 100;

    /**
     @brief Sampling frequency
     */
    double samplerate = 200.;

    /**
     @brief Diffusion rate (typically 1e-9 <> 1e-1)
     */
    double diffusion = 0.1;

    /**
     @brief Probability of sudden jumps (typically 1e-24 <> 1e-1)
     */
    double jump_rate = 0.1;

protected:
    /**
     @brief Number of input channels
     */
    std::size_t channels = 1;

    /**
     @brief Latent variable (the driving rate)
     */
    vector< vector<double> > state;

    /**
     @brief Prior
     */
    vector< vector<double> > prior;

    /**
     @brief Approximate spatial second derivative operator
     */
    vector< vector<double> > g;
};

#endif


text:
package org.xmlcml.cmine.files;

import java.util.ArrayList;

import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/** list of CTree objects.
 *
 * @author pm286
 *
 */
public class CTreeList implements Iterable<CTree> {

	private static final Logger LOG = Logger
			.getLogger(CTreeList.class);
	static {
		LOG.setLevel(Level.DEBUG);
	}

	private List<CTree> cmTreeList;

	public CTreeList() {
		ensureCTreeList();
	}

	public CTreeList(List<CTree> cTrees) {
		ensureCTreeList();
		for (CTree cTree : cTrees) {
			cmTreeList.add(cTree);
		}
	}

	private void ensureCTreeList() {
		if (cmTreeList == null) {
			cmTreeList = new ArrayList<CTree>();
		}
	}

	public int size() {
		ensureCTreeList();
		return cmTreeList.size();
	}

	public Iterator<CTree> iterator() {
		ensureCTreeList();
		return cmTreeList.iterator();
	}

	public CTree get(int i) {
		ensureCTreeList();
		return cmTreeList.get(i);
	}

	public void add(CTree cmTree) {
		ensureCTreeList();
		cmTreeList.add(cmTree);
	}

	/** gets CTree by name .
	 *
	 * @param name (uses getName())
	 * @return
	 */
	public CTree getCTreeByName(String name) {
		if (name != null) {
			for (CTree cTree : cmTreeList) {
				if (cTree.getName().equals(name)) {
					return cTree;
				}
			}
		}
		return null;
	}

}


text:
struct SwitchDesc {
  shell::Switch sw;
  const fml::StringView flag;
  const char* help;
};

#undef DEF_SWITCHES_START
#undef DEF_SWITCH
#undef DEF_SWITCHES_END

// clang-format off
#define DEF_SWITCHES_START static const struct SwitchDesc gSwitchDescs[] = {
#define DEF_SWITCH(p_swtch, p_flag, p_help) \
  { shell::Switch:: p_swtch, p_flag, p_help },
#define DEF_SWITCHES_END };
// clang-format on

// Include again for struct definition.
#include "flutter/shell/common/switches.h"

namespace shell {

void PrintUsage(const std::string& executable_name) {
  std::cerr << std::endl << "  " << executable_name << std::endl << std::endl;

  std::cerr << "Versions: " << std::endl << std::endl;

  std::cerr << "Flutter Engine Version: " << GetFlutterEngineVersion()
            << std::endl;
  std::cerr << "Skia Version: " << GetSkiaVersion() << std::endl;

  std::cerr << "Dart Version: " << GetDartVersion() << std::endl << std::endl;

  std::cerr << "Available Flags:" << std::endl;

  const uint32_t column_width = 80;

  const uint32_t flags_count = static_cast<uint32_t>(Switch::Sentinel);

  uint32_t max_width = 2;
  for (uint32_t i = 0; i < flags_count; i++) {
    auto desc = gSwitchDescs[i];
    max_width = std::max<uint32_t>(desc.flag.size() + 2, max_width);
  }

  const uint32_t help_width = column_width - max_width - 3;

  std::cerr << std::string(column_width, '-') << std::endl;
  for (uint32_t i = 0; i < flags_count; i++) {
    auto desc = gSwitchDescs[i];

    std::cerr << std::setw(max_width)
              << std::string("--") + desc.flag.ToString() << " : ";

    std::istringstream stream(desc.help);
    int32_t remaining = help_width;

    std::string word;
    while (stream >> word && remaining > 0) {
      remaining -= (word.size() + 1);
      if (remaining <= 0) {
        std::cerr << std::endl
                  << std::string(max_width, ' ') << "   " << word << " ";
        remaining = help_width;
      } else {
        std::cerr << word << " ";
      }
    }

    std::cerr << std::endl;
  }
  std::cerr << std::string(column_width, '-') << std::endl;
}

const fml::StringView FlagForSwitch(Switch swtch) {
  for (uint32_t i = 0; i < static_cast<uint32_t>(Switch::Sentinel); i++) {
    if (gSwitchDescs[i].sw == swtch) {
      return gSwitchDescs[i].flag;
    }
  }
  return fml::StringView();
}

template <typename T>
static bool GetSwitchValue(const fml::CommandLine& command_line,
                           shell::Switch sw,
                           T* result) {
  std::string switch_string;

  if (!command_line.GetOptionValue(shell::FlagForSwitch(sw), &switch_string)) {
    return false;
  }

  std::stringstream stream(switch_string);
  T value = 0;
  if (stream >> value) {
    *result = value;
    return true;
  }

  return false;
}

blink::Settings SettingsFromCommandLine(const fml::CommandLine& command_line) {
  blink::Settings settings = {};

  // Enable Observatory
  settings.enable_observatory =
      !command_line.HasOption(FlagForSwitch(Switch::DisableObservatory));

  // Set Observatory Port
  if (command_line.HasOption(FlagForSwitch(Switch::DeviceObservatoryPort))) {
    if (!GetSwitchValue(command_line, Switch::DeviceObservatoryPort,
                        &settings.observatory_port)) {
      FML_LOG(INFO)
          << "Observatory port specified was malformed. Will default to "
          << settings.observatory_port;
    }
  }

  // Checked mode overrides.
  settings.dart_non_checked_mode =
      command_line.HasOption(FlagForSwitch(Switch::DartNonCheckedMode));

  settings.ipv6 = command_line.HasOption(FlagForSwitch(Switch::IPv6));

  settings.start_paused =
      command_line.HasOption(FlagForSwitch(Switch::StartPaused));

  settings.enable_dart_profiling =
      command_line.HasOption(FlagForSwitch(Switch::EnableDartProfiling));

  settings.enable_software_rendering =
      command_line.HasOption(FlagForSwitch(Switch::EnableSoftwareRendering));

  settings.endless_trace_buffer =
      command_line.HasOption(FlagForSwitch(Switch::EndlessTraceBuffer));

  settings.trace_startup =
      command_line.HasOption(FlagForSwitch(Switch::TraceStartup));

  settings.skia_deterministic_rendering_on_cpu =
      command_line.HasOption(FlagForSwitch(Switch::SkiaDeterministicRendering));

  settings.verbose_logging =
      command_line.HasOption(FlagForSwitch(Switch::VerboseLogging));

  command_line.GetOptionValue(FlagForSwitch(Switch::FLX), &settings.flx_path);

  command_line.GetOptionValue(FlagForSwitch(Switch::FlutterAssetsDir),
                              &settings.assets_path);

  command_line.GetOptionValue(FlagForSwitch(Switch::MainDartFile),
                              &settings.main_dart_file_path);

  command_line.GetOptionValue(FlagForSwitch(Switch::Packages),
                              &settings.packages_file_path);

  std::string aot_shared_library_path;
  command_line.GetOptionValue(FlagForSwitch(Switch::AotSharedLibraryPath),
                              &aot_shared_library_path);

  std::string aot_snapshot_path;
  command_line.GetOptionValue(FlagForSwitch(Switch::AotSnapshotPath),
                              &aot_snapshot_path);

  std::string aot_vm_snapshot_data_filename;
  command_line.GetOptionValue(FlagForSwitch(Switch::AotVmSnapshotData),
                              &aot_vm_snapshot_data_filename);

  std::string aot_vm_snapshot_instr_filename;
  command_line.GetOptionValue(FlagForSwitch(Switch::AotVmSnapshotInstructions),
                              &aot_vm_snapshot_instr_filename);

  std::string aot_isolate_snapshot_data_filename;
  command_line.GetOptionValue(FlagForSwitch(Switch::AotIsolateSnapshotData),
                              &aot_isolate_snapshot_data_filename);

  std::string aot_isolate_snapshot_instr_filename;
  command_line.GetOptionValue(
      FlagForSwitch(Switch::AotIsolateSnapshotInstructions),
      &aot_isolate_snapshot_instr_filename);

  if (aot_shared_library_path.size() > 0) {
    settings.application_library_path = aot_shared_library_path;
  } else if (aot_snapshot_path.size() > 0) {
    settings.vm_snapshot_data_path = fml::paths::JoinPaths(
        {aot_snapshot_path, aot_vm_snapshot_data_filename});
    settings.vm_snapshot_instr_path = fml::paths::JoinPaths(
        {aot_snapshot_path, aot_vm_snapshot_instr_filename});
    settings.isolate_snapshot_data_path = fml::paths::JoinPaths(
        {aot_snapshot_path, aot_isolate_snapshot_data_filename});
    settings.isolate_snapshot_instr_path = fml::paths::JoinPaths(
        {aot_snapshot_path, aot_isolate_snapshot_instr_filename});
  }

  command_line.GetOptionValue(FlagForSwitch(Switch::CacheDirPath),
                              &settings.temp_directory_path);

  command_line.GetOptionValue(FlagForSwitch(Switch::ICUDataFilePath),
                              &settings.icu_data_path);

  settings.use_test_fonts =
      command_line.HasOption(FlagForSwitch(Switch::UseTestFonts));

  command_line.GetOptionValue(FlagForSwitch(Switch::LogTag), &settings.log_tag);
  std::string all_dart_flags;
  if (command_line.GetOptionValue(FlagForSwitch(Switch::DartFlags),
                                  &all_dart_flags)) {
    std::stringstream stream(all_dart_flags);
    std::istream_iterator<std::string> end;
    for (std::istream_iterator<std::string> it(stream); it != end; ++it)
      settings.dart_flags.push_back(*it);
  }

#if FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_RELEASE && \
    FLUTTER_RUNTIME_MODE != FLUTTER_RUNTIME_MODE_DYNAMIC_RELEASE
  settings.trace_skia =
      command_line.HasOption(FlagForSwitch(Switch::TraceSkia));
#endif

  return settings;
}

}  // namespace shell


text:
<?php

declare(strict_types=1);

namespace LizardsAndPumpkins\Context\DataVersion;

use LizardsAndPumpkins\Context\ContextBuilder;
use LizardsAndPumpkins\Context\ContextPartBuilder;
use LizardsAndPumpkins\Http\HttpRequest;

class ContextVersion implements ContextPartBuilder
{
    const DATA_VERSION_REQUEST_PARAM = 'dataVersion';

    /**
     * @var DataVersion
     */
    private $defaultDataVersion;

    public function __construct(DataVersion $defaultDataVersion)
    {
        $this->defaultDataVersion = $defaultDataVersion;
    }

    /**
     * @param mixed[] $inputDataSet
     * @return string
     */
    public function getValue(array $inputDataSet): string
    {
        if ($this->hasVersionInDataSet($inputDataSet)) {
            return $this->getVersionFromDataSet($inputDataSet);
        }

        if ($this->hasVersionRequestParam($inputDataSet)) {
            return (string) $this->getVersionRequestParamValue($inputDataSet);
        }

        return (string) $this->defaultDataVersion;
    }

    public function getCode(): string
    {
        return DataVersion::CONTEXT_CODE;
    }

    private function hasVersionInDataSet(array $inputDataSet): bool
    {
        return isset($inputDataSet[DataVersion::CONTEXT_CODE]);
    }

    private function getVersionFromDataSet(array $inputDataSet): string
    {
        return $inputDataSet[DataVersion::CONTEXT_CODE];
    }

    private function hasRequest(array $inputDataSet): bool
    {
        return isset($inputDataSet[ContextBuilder::REQUEST]);
    }

    private function getRequest(array $inputDataSet): HttpRequest
    {
        return $inputDataSet[ContextBuilder::REQUEST];
    }

    private function hasVersionRequestParam(array $inputDataSet): bool
    {
        return $this->hasRequest($inputDataSet) &&
               $this->getRequest($inputDataSet)->hasQueryParameter(self::DATA_VERSION_REQUEST_PARAM);
    }

    private function getVersionRequestParamValue(array $inputDataSet): ?string
    {
        return $this->getRequest($inputDataSet)->getQueryParameter(self::DATA_VERSION_REQUEST_PARAM);
    }
}


text:
require 'chef/knife/digital_ocean_base'

class Chef
  class Knife
    class DigitalOceanDomainDestroy < Knife
      include Knife::DigitalOceanBase

      banner 'knife digital_ocean domain destroy (options)'

      option :domain,
             short: '-D Name',
             long: '--domain-name Name',
             description: 'The domain name'

      def run
        $stdout.sync = true

        validate!

        unless locate_config_value(:domain)
          ui.error('Domain cannot be empty. => -D <domain-name>')
          exit 1
        end

        result = client.domains.delete(name: locate_config_value(:domain))
        ui.info 'OK' if result == true || ui.error(JSON.parse(result)['message'])
      end
    end
  end
end


text:
import React from 'react';
import Magnifier from 'react-magnifier';

const Heavy = ({ imageUrl, ...rest }) => (
  <Magnifier src={imageUrl} {...rest} />
);

export default Heavy;


text:
namespace Microsoft.Azure.Management.Compute.Fluent.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Describes virtual machine scale set operating system disk Update
    /// Object. This should be used for Updating VMSS OS Disk.
    /// </summary>
    public partial class VirtualMachineScaleSetUpdateOSDisk
    {
        /// <summary>
        /// Initializes a new instance of the
        /// VirtualMachineScaleSetUpdateOSDisk class.
        /// </summary>
        public VirtualMachineScaleSetUpdateOSDisk()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the
        /// VirtualMachineScaleSetUpdateOSDisk class.
        /// </summary>
        /// <param name="caching">The caching type. Possible values include:
        /// 'None', 'ReadOnly', 'ReadWrite'</param>
        /// <param name="writeAcceleratorEnabled">Specifies whether
        /// writeAccelerator should be enabled or disabled on the disk.</param>
        /// <param name="image">The Source User Image VirtualHardDisk. This
        /// VirtualHardDisk will be copied before using it to attach to the
        /// Virtual Machine. If SourceImage is provided, the destination
        /// VirtualHardDisk should not exist.</param>
        /// <param name="vhdContainers">The list of virtual hard disk container
        /// uris.</param>
        /// <param name="managedDisk">The managed disk parameters.</param>
        public VirtualMachineScaleSetUpdateOSDisk(CachingTypes? caching = default(CachingTypes?), bool? writeAcceleratorEnabled = default(bool?), VirtualHardDisk image = default(VirtualHardDisk), IList<string> vhdContainers = default(IList<string>), VirtualMachineScaleSetManagedDiskParameters managedDisk = default(VirtualMachineScaleSetManagedDiskParameters))
        {
            Caching = caching;
            WriteAcceleratorEnabled = writeAcceleratorEnabled;
            Image = image;
            VhdContainers = vhdContainers;
            ManagedDisk = managedDisk;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the caching type. Possible values include: 'None',
        /// 'ReadOnly', 'ReadWrite'
        /// </summary>
        [JsonProperty(PropertyName = "caching")]
        public CachingTypes? Caching { get; set; }

        /// <summary>
        /// Gets or sets specifies whether writeAccelerator should be enabled
        /// or disabled on the disk.
        /// </summary>
        [JsonProperty(PropertyName = "writeAcceleratorEnabled")]
        public bool? WriteAcceleratorEnabled { get; set; }

        /// <summary>
        /// Gets or sets the Source User Image VirtualHardDisk. This
        /// VirtualHardDisk will be copied before using it to attach to the
        /// Virtual Machine. If SourceImage is provided, the destination
        /// VirtualHardDisk should not exist.
        /// </summary>
        [JsonProperty(PropertyName = "image")]
        public VirtualHardDisk Image { get; set; }

        /// <summary>
        /// Gets or sets the list of virtual hard disk container uris.
        /// </summary>
        [JsonProperty(PropertyName = "vhdContainers")]
        public IList<string> VhdContainers { get; set; }

        /// <summary>
        /// Gets or sets the managed disk parameters.
        /// </summary>
        [JsonProperty(PropertyName = "managedDisk")]
        public VirtualMachineScaleSetManagedDiskParameters ManagedDisk { get; set; }

    }
}


text:
title: ECMAScript 2015 (ES6) e além
layout: docs.hbs
---

# ECMAScript 2015 (ES6) e além

O Node.js é construído com as novas versões do [V8](https://v8.dev/). Mantendo-se em dia com as últimas atualizações desta engine, nós garantimos que as novas funcionalidades da [especificação JavaScript ECMA-262](http://www.ecma-international.org/publications/standards/Ecma-262.htm) são trazidas para os desenvolvedores Node.js em tempo hábil, assim como as melhorias contínuas de performance e estabilidade.

Todas as funcionalidades do ECMAScript 2015 (ES6) são divididas em três grupos:

* Todas as funcionalidades em **lançamento** (shipping), que o V8 considera estáveis, são **ativadas por padrão no Node.js** e **NÃO** necessitam de nenhum tipo de flag de tempo de execução.
* As funcionalidades **em homologação**, que estão quase completas, mas não são consideradas estáveis pelo time do V8 necessitam da flag `--harmony`.
* As funcionalidades **em progresso** podem ser ativadas individualmente por sua respectiva flag "harmony", entretanto isto é altamente desencorajado a menos que seja para propósito de teste. Nota: estas flags são expostas pelo V8 e podem mudar sem aviso.

## Quais funcionalidades são embarcadas com cada versão do Node.js por padrão?

O site [node.green](https://node.green/) oferece uma excelente visão sobre quais são as funcionalidades do ECMAScript suportadas em diversas versões do Node.js, baseadas na [tabela de compatibilidade](https://github.com/kangax/compat-table) de kangax.

## Quais funcionalidades estão em progresso?

Novas funcionalidades estão constantemente sendo adicionadas na engine do V8. É esperado que elas apareçam em alguma versão futura do Node.js, porém sem uma previsão precisa de quando isso pode acontecer.

Você pode listar todas as funcionalidades *em progresso* disponíveis em cada versão do Node.js utilizando o `grep` em conjunto com o argumento `--v8-options`. É importante notar que essas funcionalidades podem estar incompletas ou quebradas no V8, portanto use-as por sua conta e risco:

```bash
node --v8-options | grep "in progress"
```

## Eu tenho a minha infraestrutura configurada para suportar a flag --harmony. Eu devo remove-la?

O comportamento atual da flag `--harmony` é habilitar somente funcionalidades **em homologação**. Além disso, ela agora é um sinônimo da flag `--es_staging`. Como mencionado anteriormente, estas funcionalidades estão completas, mas não foram consideradas estáveis ainda. Se você deseja rodar sua aplicação de forma segura, especialmente em ambientes de produção, considere remover esta flag até que ela seja lançada por padrão no V8 e, consequentemente, no Node.js. Se você deseja a manter habilitada, você deve estar preparado para atualizações futuras do Node.js que podem quebrar o seu código caso o V8 mude a sua semântica para seguir o padrão de maneira mais fiel.

## Como eu encontro qual versão do V8 foi embarcada com uma versão particular do Node.js?

O Node.js provê uma maneira simples de listar todas as dependências e suas respectivas versões que são lançadas com um binário específico através do objeto global `process`. No caso da engine do V8, digite o seguinte comando no seu terminal para recuperar a sua versão:

```bash
node -p process.versions.v8
```


text:
<macros>
    <token name="@TOOL_VERSION@">0.7.5</token>
    <token name="@VERSION_SUFFIX@">1</token>
    <xml name="requirements">
        <requirements>
            <requirement type="package" version="@TOOL_VERSION@">anndata</requirement>
            <requirement type="package" version="2.0.17">loompy</requirement>
            <yield />
        </requirements>
    </xml>
    <xml name="citations">
        <citations>
            <citation type="doi">10.1186/s13059-017-1382-0</citation>
        </citations>
    </xml>
    <xml name="version_command">
        <version_command><![CDATA[python -c "import anndata as ad;print('anndata version: %s' % ad.__version__); import loompy;print('\nloompy version: %s' % loompy.__version__)"]]></version_command>
    </xml>
    <token name="@CMD@"><![CDATA[
cat '$script_file' &&
python '$script_file'
    ]]>
    </token>
    <token name="@LOOMCMD@"><![CDATA[
mkdir ./output &&
mkdir ./attributes &&
python '$__tool_directory__/loompy_to_tsv.py' -f '${hd5_format.input}'
    ]]>
    </token>
    <token name="@CMD_imports@"><![CDATA[
import anndata as ad
    ]]>
    </token>
    <token name="@HELP@"><![CDATA[
**AnnData**

AnnData provides a scalable way of keeping track of data together with learned annotations. It is used within `Scanpy <https://github.com/theislab/scanpy>`__, for which it was initially developed.

AnnData stores a data matrix `X` together with annotations of observations `obs`, variables `var` and unstructured annotations `uns`.

.. image:: https://falexwolf.de/img/scanpy/anndata.svg

AnnData stores observations (samples) of variables (features) in the rows of a matrix. This is the convention of the modern classics
of statistics (`Hastie et al., 2009 <https://web.stanford.edu/~hastie/ElemStatLearn/>`__)  and machine learning (Murphy, 2012), the convention of dataframes both in R and Python and the established statistics
and machine learning packages in Python (statsmodels, scikit-learn).

More details on the `AnnData documentation
<https://anndata.readthedocs.io/en/latest/generated/anndata.AnnData.html>`__

**Loom data**

Loom files are an efficient file format for very large omics datasets, consisting of a main matrix, optional additional layers, a variable number of row and column annotations, and sparse graph objects.

.. image:: https://linnarssonlab.org/loompy/_images/Loom_components.png

Loom files to store single-cell gene expression data: the main matrix contains the actual expression values (one column per cell, one row per gene); row and column annotations contain metadata for genes
and cells, such as Name, Chromosome, Position (for genes), and Strain, Sex, Age (for cells).

    ]]>
    </token>
    <xml name="params_chunk_X">
        <conditional name="chunk">
            <param name="info" type="select" label="How to select the chunk?">
                <option value="random">Random chunk of defined size</option>
                <option value="specified">Specified indices</option>
            </param>
            <when value="random">
                <param name="size" type="integer" value="1000" label="Size of chunk to randomly select"/>
                <param name="replace" type="boolean" truevalue="True" falsevalue="False" checked="true" label="Random sampling of indices with replacement?"/>
            </when>
            <when value="specified">
                <param name="list" type="text" value="" label="List of comma-separated indices to return"/>
            </when>
        </conditional>
    </xml>
</macros>


text:
package tracepkts

import (
	"bufio"
	"log"
)

type GenericTracePacketv4 struct {
	// header byte
}

type TracePacket interface {
	String() string
}

func DecodePacket(header byte, reader *bufio.Reader) TracePacket {
	var pkt TracePacket
	switch {
	case header == 0x00:
		next_byte, err := reader.Peek(1)
		if err != nil {
			log.Println("Malformed extended packet, next byte doesn't exist!")
			return nil
		}
		switch next_byte[0] {
		case 0x00:
			// Continue reading Async
			pkt = DecodeAsync(header, reader)
		case 0x05:
			// Overflow
			pkt = DecodeOverflow(header, reader)
		}
	case header == 0x01:
		pkt = DecodeTraceInfo(header, reader)
	case header >= 0x02 && header <= 0x03:
		pkt = DecodeTimestamp(header, reader)
	case header == 0x04:
		pkt = DecodeTraceOn(header, reader)
	case header == 0x06:
		pkt = DecodeException(header, reader)
	case header == 0x07:
		pkt = DecodeExceptionReturn(header, reader)
	case header >= 0x0c && header <= 0x0d:
		pkt = DecodeCycleCountFmt2(header, reader)
	case header >= 0x0e && header <= 0x0f:
		pkt = DecodeCycleCountFmt1(header, reader)
	case header >= 0x10 && header <= 0x1f:
		pkt = DecodeCycleCountFmt3(header, reader)
	case header == 0x2d:
		pkt = DecodeCommit(header, reader)
	case header >= 0x71 && header <= 0x7f:
		pkt = DecodeEvent(header, reader)
	case header >= 0x80 && header <= 0x81:
		pkt = DecodeContext(header, reader)
	case header >= 0x90 && header <= 0x93:
		pkt = DecodeExactAddr(header, reader)
	case header >= 0x95 && header <= 0x96:
		pkt = DecodeShortAddr(header, reader)
	case header >= 0x9a && header <= 0x9b:
		pkt = DecodeLong32b(header, reader)
	case header >= 0x9d && header <= 0x9e:
		pkt = DecodeLong64b(header, reader)
	case header >= 0xf6 && header <= 0xf7:
		pkt = DecodeAtomFmt1(header, reader)
	}
	return pkt
}


text:
<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/toggle"
    android:background="@color/rc_normal_bg"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <FrameLayout
        android:id="@id/rc_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout><!-- From: file:/Users/rhj/AndroidStudioProjects/EveryDayBuild/TestRongCloud01/IMKit/src/main/res/layout/rc_activity.xml -->


text:
var embedded = embedded || {};

(function ($) {
    /**
     * Embedded Logic.
     * @param {object} options configuration options
     */
    function Embedded(options)
    {
        this.files = null;
        this.uploadFieldName = null;
        this.formId = 'form[data-embedded="1"]';
        this.api_token = api_options.hasOwnProperty('token') ? api_options.token : null;
        this.attachEvents();
    }

    /**
     * Initialize method.
     *
     * @return {void}
     */
    Embedded.prototype.init = function () {
        var that = this;

        $(that.formId).submit(function (e) {
            e.preventDefault();
            that._submitForm(this);
        });
    };

    /**
     * Attach events needed for the embedded form.
     * @return void
     */
    Embedded.prototype.attachEvents = function () {
        var that = this;
        $(document).on('updateFiles', function (event, files, fieldName) {
            that.files = files;
            that.uploadFieldName = fieldName;
        });
    };

    /**
     * Method that handles form submission.
     *
     * @param  {object} form Form element
     * @return {void}
     * @todo display form errors
     */
    Embedded.prototype._submitForm = function (form) {
        var that = this;

        $.ajax({
            url: $(form).attr('action'),
            type: 'post',
            data: JSON.stringify(this.serializeObject(form)),
            dataType: 'json',
            contentType: 'application/json',
            headers: {
                'Authorization': 'Bearer ' + that.api_token
            },
            success: function (data, textStatus, jqXHR) {
                // set related field display-field and value
                that._setRelatedField(data.data.id, form);

                // reset embedded form
                $(form)[0].reset();

                // hide modal
                $($(form).closest('.modal')).modal('hide');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(jqXHR);
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
    };

    /**
     * Serialize Form to JSON.
     *
     * @param {string} form_id Form identifier
     * @return {object}
     * @link https://css-tricks.com/snippets/jquery/serialize-form-to-json
     */
    Embedded.prototype.serializeObject = function (form_id) {
        var data = {};

        $.each($(form_id).serializeArray(), function () {
            var matches = this.name.match(/\[(.*?)\]/);
            this.name = matches ? matches[1] : this.name;

            if (data[this.name]) {
                if (! data[this.name].push) {
                    data[this.name] = [data[this.name]];
                }
                data[this.name].push(this.value || '');
            } else {
                data[this.name] = this.value || '';
            }
        });

        return data;
    }

    /**
     * Set value and display field for related field after successful form submission.
     *
     * @param {string} id record id
     * @param {object} form Form element
     * @return {void}
     */
    Embedded.prototype._setRelations = function (id, form) {
        var that = this;

        var associationName = $(form).data('embedded-association-name');
        var relatedModel = $(form).data('embedded-related-model');
        var relatedId = $(form).data('embedded-related-id');
        var data = {[associationName] : {'_ids' : [id]}};

        $.ajax({
            url: '/' + relatedModel + '/link/' + relatedId + '/' + associationName,
            type: 'post',
            dataType: 'json',
            data: JSON.stringify(data),
            contentType: 'application/json',
            headers: {
                'Authorization': 'Bearer ' + that.api_token
            },
            success: function (response, textStatus, jqXHR) {
                that._setRelatedField(id, form)
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(jqXHR);
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
    };

    /**
     * Set value and display field for related field after successful form submission.
     *
     * @param {string} id record id
     * @param {object} form Form element
     * @return {void}
     */
    Embedded.prototype._setRelatedField = function (id, form) {
        var that = this;
        var url = $(form).attr('action').replace('/add', '/view/' + id + '.json');

        $.ajax({
            url: url,
            type: 'get',
            dataType: 'json',
            contentType: 'application/json',
            headers: {
                'Authorization': 'Bearer ' + that.api_token
            },
            success: function (data, textStatus, jqXHR) {
                // get select2 field
                var label = data.data[$(form).data('embedded-display-field')];
                var field = $('#' + $(form).data('embedded-field-id'));
                var option = $('<option selected>' + label + '</option>').val(id);
                field.append(option).trigger('change');
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(jqXHR);
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
    };

    $(document).ready(function () {
        embedded = new Embedded([]);

        embedded.init();
    });

})(jQuery);


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace SalInfoSender
{
    public static class SalUtils
    {
        private static string GetDBServer()
        {
            return LoadKeyFromRegistry("DBServer");
        }

        private static string LoadKeyFromRegistry(string keyName)
        {
            Microsoft.Win32.RegistryKey key = null;
            using (key = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("Software"))
            {
                key = key.CreateSubKey("Nexus");
                key = key.CreateSubKey("Sal");

                return Converter.ObjToString(key.GetValue(keyName, null));
            }
        }
    }

    public static class Converter
    {
        public static uint ObjToUInt(object o)
        {
            try
            {
                uint tryInt = 0;
                if (uint.TryParse(ObjToString(o), out tryInt))
                    return tryInt;
                return 0;
            }
            catch
            {
                return 0;
            }
        }

        public static byte? ObjToByte(object o)
        {
            try
            {
                byte tryInt = 0;
                if (byte.TryParse(ObjToString(o), out tryInt))
                    return tryInt;
                return null;
            }
            catch
            {
                return null;
            }
        }

        public static string ObjToString(object o)
        {
            try
            {
                string tryStr = Convert.ToString(o);
                return tryStr == string.Empty ? null : tryStr;
            }
            catch
            {
                return null;
            }
        }

        public static string ObjToString(string str)
        {
            try
            {
                return str == string.Empty ? null : str;
            }
            catch
            {
                return null;
            }
        }

        public static int? ObjToInt(object o)
        {
            try
            {
                int tryInt = 0;
                if (int.TryParse(ObjToString(o), out tryInt))
                    return tryInt;
                return null;
            }
            catch
            {
                return null;
            }
        }

        public static int ObjToInt(object o, int defaultValue)
        {
            try
            {
                int tryInt = 0;
                if (int.TryParse(ObjToString(o), out tryInt))
                    return tryInt;
                return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        public static int? ObjToIntZeroToNull(object o)
        {
            try
            {
                int tryInt = 0;
                if (int.TryParse(ObjToString(o), out tryInt))
                {
                    if (tryInt == 0)
                        return null;
                    else
                        return tryInt;
                }
                return null;
            }
            catch
            {
                return null;
            }
        }

        public static int OTI(object o)
        {
            try
            {
                int tryInt = 0;
                if (int.TryParse(ObjToString(o), out tryInt))
                    return tryInt;
                return int.MinValue;
            }
            catch
            {
                return int.MinValue;
            }
        }

        public static bool? ObjToBool(object o)
        {
            try
            {
                bool tryBool = false;
                if (bool.TryParse(ObjToString(o), out tryBool))
                    return tryBool;
                return null;
            }
            catch
            {
                return null;
            }
        }

        public static bool ObjToBool(object o, bool defaultValue)
        {
            try
            {
                bool tryBool = false;
                if (bool.TryParse(ObjToString(o), out tryBool))
                    return tryBool;
                return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        public static decimal? ObjToValidSQLYear(object o)
        {
            try
            {
                decimal tryDecimal = 0;
                if (decimal.TryParse(ObjToString(o), out tryDecimal))
                {
                    if (tryDecimal > 1753 && tryDecimal < 9999)
                        return tryDecimal;
                }
                return null;
            }
            catch
            {
                return null;
            }
        }

        public static decimal? ObjToDecimal(object o)
        {
            try
            {
                decimal tryDecimal = 0;
                if (decimal.TryParse(ObjToString(o), out tryDecimal))
                    return tryDecimal;
                return null;
            }
            catch
            {
                return null;
            }
        }

        public static decimal ObjToDecimal(object o, decimal defaultValue)
        {
            try
            {
                decimal tryDecimal = 0;
                if (decimal.TryParse(ObjToString(o), out tryDecimal))
                    return tryDecimal;
                return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        public static double? ObjToDouble(object o)
        {
            try
            {
                double tryDecimal = 0;
                if (double.TryParse(ObjToString(o), out tryDecimal))
                    return tryDecimal;
                return null;
            }
            catch
            {
                return null;
            }
        }

        public static double ObjToDouble(object o, double defaultValue)
        {
            try
            {
                double tryDecimal = 0;
                if (double.TryParse(ObjToString(o), out tryDecimal))
                    return tryDecimal;
                return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        public static DateTime? ObjToDateTime(object o)
        {
            try
            {
                DateTime tryDateTime;
                if (DateTime.TryParse(ObjToString(o), out tryDateTime))
                    return tryDateTime;
                return null;
            }
            catch
            {
                return null;
            }
        }

        public static DateTime? ObjToDateTime(object o, string cultureName)
        {
            try
            {
                System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(cultureName);
                DateTime tryDateTime;
                if (DateTime.TryParse(ObjToString(o), ci.DateTimeFormat, System.Globalization.DateTimeStyles.None, out tryDateTime))
                    return tryDateTime;
                return null;
            }
            catch
            {
                return null;
            }
        }

        public static DateTime ObjToDateTime(object o, DateTime defaultValue)
        {
            try
            {
                DateTime tryDateTime;
                if (DateTime.TryParse(ObjToString(o), out tryDateTime))
                    return tryDateTime;
                return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        public static DateTime ObjToDateTime(object o, string cultureName, DateTime defaultValue)
        {
            try
            {
                System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(cultureName);
                DateTime tryDateTime;
                if (DateTime.TryParse(ObjToString(o), ci.DateTimeFormat, System.Globalization.DateTimeStyles.None, out tryDateTime))
                    return tryDateTime;
                return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }

        public static Guid? ObjToGuid(object o)
        {
            try
            {
                return new Guid(ObjToString(o));
            }
            catch
            {
                return null;
            }
        }

        public static T ObjToEnum<T>(object value)
        {
            return (T)Enum.Parse(typeof(T), ObjToString(value));
        }

        public static string Decimal(string decimalString)
        {
            return Decimal(decimalString, System.Globalization.CultureInfo.CurrentCulture.NumberFormat.PercentDecimalSeparator);
        }

        public static string Decimal(string decimalString, string decimalSeparator)
        {
            return decimalString.Replace(",", decimalSeparator).
                    Replace(".", decimalSeparator);
        }

        public static string XmlSerialize<T>(T obj) where T : class, new()
        {
            if (obj == null) throw new ArgumentNullException("obj");

            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            using (var writer = new System.IO.StringWriter())
            {
                serializer.Serialize(writer, obj);
                return writer.ToString();
            }
        }

        public static T XmlDeserialize<T>(string xml) where T : class, new()
        {
            if (xml == null) throw new ArgumentNullException("xml");

            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            using (var reader = new System.IO.StreamReader(xml))
            {
                try { return (T)serializer.Deserialize(reader); }
                catch { return null; }
            }
        }
    }

}


text:
import yaml

from tacker.sol_refactored.common import common_script_utils
from tacker.sol_refactored.common import vnf_instance_utils as inst_utils
from tacker.sol_refactored.infra_drivers.openstack import userdata_utils

class UserData(userdata_utils.AbstractUserData):

    @staticmethod
    def instantiate(req, inst, grant_req, grant, tmp_csar_dir):
        def _get_param_port(cp_name, grant, req):
            # see grant first then instantiateVnfRequest
            vls = grant.get('extVirtualLinks', []) + req.get('extVirtualLinks',
                                                             [])
            port_ids = []
            for vl in vls:
                link_port_ids = []
                for extcp in vl['extCps']:
                    if extcp['cpdId'] == cp_name:
                        link_port_ids = _get_link_port_ids_from_extcp(extcp)
                if 'extLinkPorts' not in vl:
                    continue
                for extlp in vl['extLinkPorts']:
                    if extlp['id'] in link_port_ids:
                        port_ids.append(extlp['resourceHandle']['resourceId'])
            return port_ids

        def _get_link_port_ids_from_extcp(extcp):
            link_port_ids = []
            for cp_conf in extcp['cpConfig'].values():
                if 'linkPortId' in cp_conf:
                    link_port_ids.append(cp_conf['linkPortId'])
            return link_port_ids

        vnfd = common_script_utils.get_vnfd(inst['vnfdId'], tmp_csar_dir)
        flavour_id = req['flavourId']

        hot_dict = vnfd.get_base_hot(flavour_id)
        top_hot = hot_dict['template']

        nfv_dict = common_script_utils.init_nfv_dict(top_hot)

        vdus = nfv_dict.get('VDU', {})
        for vdu_name, vdu_value in vdus.items():
            if 'computeFlavourId' in vdu_value:
                vdu_value['computeFlavourId'] = (
                    common_script_utils.get_param_flavor(
                        vdu_name, flavour_id, vnfd, grant))
            if 'vcImageId' in vdu_value:
                vdu_value['vcImageId'] = common_script_utils.get_param_image(
                    vdu_name, flavour_id, vnfd, grant)
            if 'locationConstraints' in vdu_value:
                vdu_value['locationConstraints'] = (
                    common_script_utils.get_param_zone(
                        vdu_name, grant_req, grant))
            if 'desired_capacity' in vdu_value:
                vdu_value['desired_capacity'] = (
                    common_script_utils.get_param_capacity(
                        vdu_name, inst, grant_req))

        cps = nfv_dict.get('CP', {})
        for cp_name, cp_value in cps.items():
            if 'network' in cp_value:
                cp_value['network'] = common_script_utils.get_param_network(
                    cp_name, grant, req)
            if 'fixed_ips' in cp_value:
                ext_fixed_ips = common_script_utils.get_param_fixed_ips(
                    cp_name, grant, req)
                fixed_ips = []
                for i in range(len(ext_fixed_ips)):
                    if i not in cp_value['fixed_ips']:
                        break
                    ips_i = cp_value['fixed_ips'][i]
                    if 'subnet' in ips_i:
                        ips_i['subnet'] = ext_fixed_ips[i].get('subnet')
                    if 'ip_address' in ips_i:
                        ips_i['ip_address'] = ext_fixed_ips[i].get(
                            'ip_address')
                    fixed_ips.append(ips_i)
                cp_value['fixed_ips'] = fixed_ips
            # NOTE: In the case where multiple cpConfigs corresponding
            # to a single cpdId are defined, always get the first element
            # of cpConfig. This is because, according to the current
            # SOL definitions, the key of cpConfig is the ID managed by
            # the API consumer, and it is not possible to uniquely determine
            # which element of cpConfig should be selected by cpdId.
            # See SOL003 v3.3.1 4.4.1.10 Type: VnfExtCpData.
            if 'port' in cp_value:
                cp_value['port'] = _get_param_port(
                    cp_name, grant, req).pop()

        common_script_utils.apply_ext_managed_vls(top_hot, req, grant)

        if 'nfv' in req.get('additionalParams', {}):
            nfv_dict = inst_utils.json_merge_patch(nfv_dict,
                    req['additionalParams']['nfv'])
        if 'nfv' in grant.get('additionalParams', {}):
            nfv_dict = inst_utils.json_merge_patch(nfv_dict,
                    grant['additionalParams']['nfv'])

        fields = {
            'template': yaml.safe_dump(top_hot),
            'parameters': {'nfv': nfv_dict},
            'files': {}
        }
        for key, value in hot_dict.get('files', {}).items():
            fields['files'][key] = yaml.safe_dump(value)

        return fields


text:
.class public Lcom/android/settings/Settings$PersonalPageSettingsActivity;
.super Lcom/samsung/android/settings/SettingsActivityWrapper;
.source "Settings.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/settings/Settings;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "PersonalPageSettingsActivity"
.end annotation

# direct methods
.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Lcom/samsung/android/settings/SettingsActivityWrapper;-><init>()V

    return-void
.end method

# virtual methods
.method public onOptionsItemSelected(Landroid/view/MenuItem;)Z
    .locals 4

    invoke-interface {p1}, Landroid/view/MenuItem;->getItemId()I

    move-result v2

    packed-switch v2, :pswitch_data_0

    :cond_0
    invoke-super {p0, p1}, Lcom/samsung/android/settings/SettingsActivityWrapper;->onOptionsItemSelected(Landroid/view/MenuItem;)Z

    move-result v2

    return v2

    :pswitch_0
    invoke-static {}, Lcom/android/settings/Utils;->readSalesCode()Ljava/lang/String;

    move-result-object v1

    const-string/jumbo v2, "VZW"

    invoke-virtual {v2, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_0

    new-instance v0, Landroid/content/Intent;

    invoke-direct {v0}, Landroid/content/Intent;-><init>()V

    const-string/jumbo v2, "com.android.settings"

    const-string/jumbo v3, "com.android.settings.Settings$SafetyCareSettingsActivity"

    invoke-virtual {v0, v2, v3}, Landroid/content/Intent;->setClassName(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;

    invoke-virtual {p0, v0}, Lcom/android/settings/Settings$PersonalPageSettingsActivity;->startActivity(Landroid/content/Intent;)V

    invoke-virtual {p0}, Lcom/android/settings/Settings$PersonalPageSettingsActivity;->finish()V

    const/4 v2, 0x1

    return v2

    nop

    :pswitch_data_0
    .packed-switch 0x102002c
        :pswitch_0
    .end packed-switch
.end method


text:
@echo off
rem

setlocal
if "%HOMEDRIVE%"=="" goto MISSINGVARS
if "%HOMEPATH%"=="" goto MISSINGVARS
if "%HAXEPATH%"=="" goto NOTINSTALLED

set path=%HAXEPATH%;%HAXEPATH%\..\neko;%path%

rem # invoke Thrift comnpiler
thrift -r -gen haxe  ..\..\..\test\ThriftTest.thrift
thrift -r -gen haxe  ..\..\..\contrib\async-test\aggr.thrift
thrift -r -gen haxe  ..\..\..\lib\rb\benchmark\Benchmark.thrift
if errorlevel 1 goto STOP

rem # invoke Haxe compiler for all targets
for %%a in (*.hxml) do (
	rem * filter Python, as it is not supported by Haxe 3.1.3 (but will be in 3.1.4)
	if not "%%a"=="python.hxml" (
		echo --------------------------
		echo Building %%a ...
		echo --------------------------
		haxe  --cwd .  %%a
	)
)

echo.
echo done.
pause
goto eof

:NOTINSTALLED
echo FATAL: Either Haxe is not installed, or the HAXEPATH variable is not set.
pause
goto eof

:MISSINGVARS
echo FATAL: Unable to locate home folder.
echo.
echo Both HOMEDRIVE and HOMEPATH need to be set to point to your Home folder.
echo The current values are:
echo HOMEDRIVE=%HOMEDRIVE%
echo HOMEPATH=%HOMEPATH%
pause
goto eof

:STOP
pause
goto eof

:eof


text:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;

namespace HeadRaceTimingSite.Migrations
{
    public partial class TimingPointName : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<string>(
                name: "Name",
                table: "TimingPoints",
                nullable: true);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "Name",
                table: "TimingPoints");
        }
    }
}


text:
var bitmessage = require('../lib/main')('localhost', 8442, 'user', 'password');

try {
  bitmessage.messages.sent.list(function(value) {
    console.dir(value);
  });
}
catch(err) {
  console.dir(err);
}


text:
import Phaser from 'phaser'
import Backbone from 'backbone'
import ChromosomeView from '../views/ChromosomeView'
import NucleusView from '../views/NucleusView'
import HudView from '../views/HudView'
import ChromosomeModel from '../models/ChromosomeModel'
import CellModel from '../models/CellModel'
import { centerGameObjects } from '../utils'

export default class extends Phaser.State {
  init () {}

  preload () {
    this.loaderBg = this.add.sprite(this.game.world.centerX, this.game.world.centerY, 'loaderBg')
    this.loaderBar = this.add.sprite(this.game.world.centerX, this.game.world.centerY, 'loaderBar')
    centerGameObjects([this.loaderBg, this.loaderBar])

    this.load.setPreloadSprite(this.loaderBar)
    //
    // load your assets
    //

    //Common
    this.load.image('circle', 'assets/images/circle.png')
    this.load.image('square', 'assets/images/square.png')
    this.load.image('circle_outline', 'assets/images/circle_outline.png')
    this.load.image('dotted_circle', 'assets/images/dotted_circle.png')
    this.load.image('dashed_circle', 'assets/images/dashed_circle.png')
    this.load.image('hexagon', 'assets/images/common/hexagon.png')
    this.load.image('color_sparkles', 'assets/images/common/color_sparkles.png')
    this.load.image('mouse_trail', 'assets/images/mouse_trail.png')

    this.load.image('white_radial_gradient', 'assets/images/white_radial_gradient.png')
    this.load.image('small_white_blur', 'assets/images/small_white_blur.png')
    this.load.image('medium_white_blur', 'assets/images/medium_white_blur.png')
    this.load.image('large_white_blur', 'assets/images/large_white_blur.png')
    this.load.image('blobs', 'assets/images/blobs256.png')

    this.load.image('white_drake', 'assets/images/white_drake.png')
    this.load.image('red_drake', 'assets/images/red_drake.png')
    this.load.image('shine_drake', 'assets/images/shine_drake.png')

    this.load.image('chromoscope_circle01', 'assets/images/chromoscope/chromoscope_circle01.png')
    this.load.image('chromoscope_circle02', 'assets/images/chromoscope/chromoscope_circle02.png')
    this.load.image('chromoscope_arrow_down', 'assets/images/chromoscope/arrow_down.png')

    this.load.image('chromoscope_charcoal', 'assets/images/chromoscope/chromoscope_charcoal.png')
    this.load.image('chromoscope_steel', 'assets/images/chromoscope/chromoscope_steel.png')
    this.load.image('chromoscope_ash', 'assets/images/chromoscope/chromoscope_ash.png')
    this.load.image('chromoscope_silver', 'assets/images/chromoscope/chromoscope_silver.png')
    this.load.image('chromoscope_lava', 'assets/images/chromoscope/chromoscope_lava.png')
    this.load.image('chromoscope_copper', 'assets/images/chromoscope/chromoscope_copper.png')
    this.load.image('chromoscope_sand', 'assets/images/chromoscope/chromoscope_sand.png')
    this.load.image('chromoscope_gold', 'assets/images/chromoscope/chromoscope_gold.png')
    this.load.image('chromoscope_frost', 'assets/images/chromoscope/chromoscope_frost.png')

    //size
    this.load.image('sizeMelanosome', 'assets/images/size_melanosome.png')
    this.load.image('sizeMelanosomeOutline', 'assets/images/size_melanosome_outline.png')
    this.load.image('size_goal', 'assets/images/size_goal.png')
    this.load.image('tyrosine', 'assets/images/tyrosine.png')
    this.load.image('tyr', 'assets/images/tyr.png')
    this.load.image('disc', 'assets/images/disc.png')
    this.load.image('trp_01', 'assets/images/trp_01.png')
    this.load.image('trp_02', 'assets/images/trp_02.png')
    this.load.image('trp_bar', 'assets/images/trp_bar.png')
    this.load.image('trp_flower', 'assets/images/trp_flower.png')
    this.load.image('tyrosine_crazy', 'assets/images/tyrosine_crazy_christina.png')

    this.load.image('whiteMelanosome', 'assets/images/white_melanosome.png')

    //ftue
    this.load.image('ftue_container', 'assets/images/ftue/action_container.png');
    this.load.image('ftue_step_container', 'assets/images/ftue/step_container.png');
    this.load.image('ftue_step_selection', 'assets/images/ftue/step_selection.png');
    this.load.image('ftue_check_container', 'assets/images/ftue/check_container.png');
    this.load.image('ftue_check', 'assets/images/ftue/check.png');
    this.load.image('ftue_check_active', 'assets/images/ftue/check_active.png');

    this.load.image('ftue_working_protein_assembled', 'assets/images/ftue/working_protein_assembled.png');
    this.load.image('ftue_disc_destroyed', 'assets/images/ftue/disc_destroyed.png');
    this.load.image('ftue_protein_broken', 'assets/images/ftue/protein_broken.png');
    this.load.image('ftue_tri_pushed_into_small_gear', 'assets/images/ftue/tri_pushed_into_small_gear.png');

    //motor
    this.load.image('motor_melanosome', 'assets/images/motor_melanosome.png')
    this.load.image('propeller_foot', 'assets/images/propeller_foot.png')
    this.load.image('myocin', 'assets/images/myocin.png')
    this.load.image('grabber', 'assets/images/grabber.png')
    this.load.image('gears', 'assets/images/gears.png')

    //gate
    this.load.image('gate_half', 'assets/images/gate_half.png')
    this.load.image('tunnel', 'assets/images/tunnel.png')
    this.load.image('gate_stopper_wing', 'assets/images/gate_stopper_wing_pink.png')
    this.load.image('gate_stopper_body_working', 'assets/images/gate_stopper_body_working.png')
    this.load.image('gate_stopper_body_broken', 'assets/images/gate_stopper_body_broken.png')
    this.load.image('gate_stopper_tail', 'assets/images/gate_stopper_tail.png')
    this.load.image('gate_melanosome', 'assets/images/melanocyte.png')
    this.load.image('dark_melanosome', 'assets/images/dark_melanosome.png')

    this.load.image("meter_outline", "assets/images/meter_outline.png")
    this.load.image("meter_fill", "assets/images/meter_fill.png")
    this.load.image("meter_indicator", "assets/images/meter_indicator.png")
    this.load.image("sparkle", "assets/images/sparkle_star.png")

    //audio

    //music

    //http://tones.wolfram.com/generate/GhYhjzvOhAbBmBxzvrfdz7G4VZwKpV0MNginSuDph50J
    // this.game.load.audio("bg-music", ["assets/audio/music/NKM-G-50-31-37641278-1-34056-64-75-4-2773-48-0-9-545-0-0-109-102-0-0-109-351-0.mp3", "assets/audio/music/NKM-G-50-31-37641278-1-34056-64-75-4-2773-48-0-9-545-0-0-109-102-0-0-109-351-0.ogg"]);

    //sfx
    this.game.load.audio("pop", ["assets/audio/sfx/244654__greenvwbeetle__pop-2.mp3", "assets/audio/sfx/244654__greenvwbeetle__pop-2.ogg"]);
    this.game.load.audio("squirt", ["assets/audio/sfx/167073__drminky__squelchy-squirt.mp3", "assets/audio/sfx/167073__drminky__squelchy-squirt.ogg"]);
    this.game.load.audio("squitch", ["assets/audio/sfx/233343__otisjames__squitch.mp3", "assets/audio/sfx/233343__otisjames__squitch.ogg"]);

    this.game.load.audio("click_hit", ["assets/audio/sfx/click_generic.mp3", "assets/audio/sfx/click_generic.ogg"])
    this.game.load.audio("dumbbell_attach", ["assets/audio/sfx/dumbbell_attach.mp3", "assets/audio/sfx/dumbbell_attach.ogg"])
    this.game.load.audio("dumbbell_break", ["assets/audio/sfx/dumbbell_break.mp3", "assets/audio/sfx/dumbbell_break.ogg"])
    this.game.load.audio("gate_close", ["assets/audio/sfx/gate_close.mp3", "assets/audio/sfx/gate_close.ogg"])
    this.game.load.audio("pleasing_ding", ["assets/audio/sfx/star_form.mp3", "assets/audio/sfx/star_form.ogg"])
    this.game.load.audio("popout", ["assets/audio/sfx/blocker_popout.mp3", "assets/audio/sfx/blocker_popout.ogg"])
    this.game.load.audio("rip", ["assets/audio/sfx/star_break.mp3", "assets/audio/sfx/star_break.ogg"])
    this.game.load.audio("blocker_insert", ["assets/audio/sfx/blocker_insert.mp3", "assets/audio/sfx/blocker_insert.ogg"])
    this.game.load.audio("forcefield", ["assets/audio/sfx/forcefield.mp3", "assets/audio/sfx/forcefield.ogg"])
    this.game.load.audio("compile", ["assets/audio/sfx/compile.mp3", "assets/audio/sfx/compile.ogg"])

    this.game.load.audio("win", ["assets/audio/sfx/win_state.mp3"]);

    this.load.json('cell_data', "assets/data/chromosome_data.json");
    this.load.json('all_working_data', "assets/data/all_working.json");
    this.load.json('tutorials', "assets/data/tutorials.json");
    // this.load.json('all_broken_data', "assets/data/all_broken.json");
    // this.load.json('all_hetero_data', "assets/data/hetero.json");

    // this.load.json('charcoal_hetero_trp', "assets/data/charcoal_hetero_trp.json");
    // this.load.json('lava_homozygous_broken_trp', "assets/data/lava_homozygous_broken_trp.json");
    // this.load.json('frost_homozygous_broken_tyr', "assets/data/frost_homozygous_broken_tyr.json");
    // this.load.json('copper_broken_tyr_hetero_asip', "assets/data/copper_broken_tyr_hetero_asip.json");
    // this.load.json('sand_broken_trp_hetero_myocin', "assets/data/sand_broken_trp_hetero_myocin.json");

  }

  create () {
    this.loaderBar.alpha = 0;
    this.loaderBg.alpha = 0;
    this.game.physics.startSystem(Phaser.Physics.ARCADE);
        // this.chromosomeView = new ChromosomeView({el: "#chromosome", model: chromosome1AModel });
    this.game.nucleusView = new NucleusView({el: "#nucleus", model: this.game.cellModel, game: this.game});
    this.game.hudView = new HudView({el: "#hud", model: this.game.cellModel, game: this.game });
    if(this.game.showStats) {
        this.game.hudView.showStats();
    }

    var initialState = game.initialState;

    game.phone.post("activityLoaded", {"hasTutorial":this.game.tutorialData != null});

    switch(initialState){
        case "size":
            this.game.state.start('SizeActivity');
            break;
        case "motor":
            this.game.state.start('MotorActivity');
            break;
        case "gate":
            this.game.state.start('GateActivity');
            break;
        case "nucleus":
            this.game.nucleusOnly = true; //hacky temp flag
            this.game.hudView.showNucleus();
            this.game.hideHud();
            break;

        default:
            this.game.state.start('SizeActivity');
            break;
    }

    game.stage.disableVisibilityChange = true;

  }

}


text:
  #define LED_RCC       RCC_AHB1Periph_GPIOD
  #define LED_PORT      GPIOD
  #define LED_PIN       GPIO_Pin_12

  #define PIN1_RCC      RCC_AHB1Periph_GPIOD
  #define PIN1_PORT     GPIOD
  #define PIN1_PIN      GPIO_Pin_2

  #define PIN2_RCC      RCC_AHB1Periph_GPIOD
  #define PIN2_PORT     GPIOD
  #define PIN2_PIN      GPIO_Pin_6

  #define BUTTON_RCC      RCC_AHB1Periph_GPIOA
  #define BUTTON_PORT     GPIOA
  #define BUTTON_PIN      GPIO_Pin_0

  #define BIT_COND        Bit_SET

#endif

#ifdef _STM_IAR_BOARD_
  #define LED_RCC       RCC_AHB1Periph_GPIOF
  #define LED_PORT      GPIOF
  #define LED_PIN       GPIO_Pin_6

  #define PIN1_RCC      RCC_AHB1Periph_GPIOF
  #define PIN1_PORT     GPIOF
  #define PIN1_PIN      GPIO_Pin_8

  #define PIN2_RCC      RCC_AHB1Periph_GPIOF
  #define PIN2_PORT     GPIOF
  #define PIN2_PIN      GPIO_Pin_6

  #define BUTTON_RCC      RCC_AHB1Periph_GPIOG
  #define BUTTON_PORT     GPIOG
  #define BUTTON_PIN      GPIO_Pin_6

  #define BIT_COND        Bit_RESET

#endif

#endif


text:
import { arrayFromNSArray, toJSON } from './lib/nsdict'
import uuidv4 from './lib/uuid'
import { open } from './lib/libc'
import { getDataAttrForPath } from './lib/foundation'

export function ls(path, root) {
  const { NSFileManager, NSProcessInfo, NSBundle } = ObjC.classes

  const prefix = root === 'bundle'
    ? NSBundle.mainBundle().bundlePath().toString()
    : NSProcessInfo.processInfo().environment().objectForKey_('HOME').toString()

  const pErr = Memory.alloc(Process.pointerSize)
  Memory.writePointer(pErr, NULL)
  const cwd = [prefix, path].join('/')
  const nsArray = NSFileManager.defaultManager().contentsOfDirectoryAtPath_error_(cwd, pErr)
  const err = Memory.readPointer(pErr)

  if (!err.isNull()) {
    const description = new ObjC.Object(err).localizedDescription()
    throw new Error(description)
  }

  if (!nsArray)
    return { cwd, list: [] }

  const isDir = Memory.alloc(Process.pointerSize)
  const list = arrayFromNSArray(nsArray, 100).map((filename) => {
    const fullPath = [prefix, path, filename].join('/')
    NSFileManager.defaultManager().fileExistsAtPath_isDirectory_(fullPath, isDir)

    return {
      /* eslint eqeqeq:0 */
      type: Memory.readPointer(isDir) == 0 ? 'file' : 'directory',
      name: filename,
      path: fullPath,
      attribute: getDataAttrForPath(fullPath) || {}
    }
  })

  return { cwd, list }
}

export function plist(path) {
  const { NSDictionary } = ObjC.classes
  const info = NSDictionary.dictionaryWithContentsOfFile_(path)
  if (info === null)
    throw new Error(`malformed plist file: ${path}`)
  return toJSON(info)
}

export function text(path) {
  const name = Memory.allocUtf8String(path)
  const size = 10 * 1024 // max read size: 10k

  return new Promise((resolve, reject) => {
    const fd = open(name, 0, 0)
    if (fd === -1)
      reject(new Error(`unable to open file ${path}`))

    const stream = new UnixInputStream(fd, { autoClose: true })
    stream.read(size).then(resolve).catch(reject)
  })
}

export function download(path) {
  const session = uuidv4()
  const name = Memory.allocUtf8String(path)
  const watermark = 10 * 1024 * 1024
  const subject = 'download'
  const { size } = getDataAttrForPath(path)

  const fd = open(name, 0, 0)
  if (fd === -1)
    throw new Error(`unable to open file ${path}`)

  const stream = new UnixInputStream(fd, { autoClose: true })
  const read = () => {
    stream.read(watermark).then((buffer) => {
      send({
        subject,
        event: 'data',
        session
      }, buffer)

      if (buffer.byteLength === watermark) {
        setImmediate(read)
      } else {
        send({
          subject,
          event: 'end',
          session
        })
      }
    }).catch((error) => {
      send({
        subject,
        event: 'error',
        session,
        error: error.message
      })
    })
  }
  send({
    subject,
    event: 'start',
    session
  })
  setImmediate(read)
  return {
    size,
    session
  }
}


text: Back end of the Internet of Trash project


text:
<?php
namespace In2code\Powermail\ViewHelpers\BeCheck;

use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper;

/**
 * Backend Check Viewhelper: Check if Extension Manager Settings are available
 *
 * @package TYPO3
 * @subpackage Fluid
 */
class ExtMngConfigViewHelper extends AbstractViewHelper
{

    /**
     * Check if Extension Manager Settings are available
     *
     * @return bool
     */
    public function render()
    {
        $confArr = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['powermail']);
        if (is_array($confArr) && count($confArr) > 2) {
            return true;
        }
        return false;
    }
}