text:
{-# LANGUAGE CPP             #-}
{-# LANGUAGE KindSignatures  #-}
{-# LANGUAGE Rank2Types      #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeOperators   #-}

-- | Resources used by node and ways to deal with them.

module Pos.Launcher.Resource
       (
         -- * Full resources
         NodeResources (..)

       , bracketNodeResources

         -- * Smaller resources
       , loggerBracket
       ) where

import           Universum

import           Control.Concurrent.Async.Lifted (Async)
import qualified Control.Concurrent.Async.Lifted as Async
import           Control.Concurrent.STM (newEmptyTMVarIO, newTBQueueIO)
import           Control.Exception.Base (ErrorCall (..))
import           Data.Default (Default)
import qualified Data.Time as Time
import           Formatting (sformat, shown, (%))
import           System.IO (BufferMode (..), hClose, hSetBuffering)
import qualified System.Metrics as Metrics

import           Network.Broadcast.OutboundQueue.Types (NodeType (..))
import           Pos.Binary ()
import           Pos.Chain.Block (HasBlockConfiguration)
import           Pos.Chain.Delegation (DelegationVar, HasDlgConfiguration)
import           Pos.Chain.Genesis as Genesis (Config, configEpochSlots,
                     configStartTime)
import           Pos.Chain.Ssc (SscParams, SscState, createSscContext)
import           Pos.Configuration
import           Pos.Context (ConnectedPeers (..), NodeContext (..),
                     StartTime (..))
import           Pos.Core (Timestamp)
import           Pos.Core.Reporting (initializeMisbehaviorMetrics)
import           Pos.DB (MonadDBRead, NodeDBs)
import           Pos.DB.Block (consolidateWorker, mkSlogContext)
import           Pos.DB.Delegation (mkDelegationVar)
import           Pos.DB.Lrc (LrcContext (..), mkLrcSyncData)
import           Pos.DB.Rocks (closeNodeDBs, openNodeDBs)
import           Pos.DB.Ssc (mkSscState)
import           Pos.DB.Txp (GenericTxpLocalData (..), TxpGlobalSettings,
                     mkTxpLocalData, recordTxpMetrics)
import           Pos.DB.Update (mkUpdateContext)
import qualified Pos.DB.Update as GState
import qualified Pos.GState as GS
import           Pos.Infra.DHT.Real (KademliaParams (..))
import           Pos.Infra.InjectFail (FInjects)
import           Pos.Infra.Network.Types (NetworkConfig (..))
import           Pos.Infra.Shutdown.Types (ShutdownContext (..))
import           Pos.Infra.Slotting (SimpleSlottingStateVar,
                     mkSimpleSlottingStateVar)
import           Pos.Infra.Slotting.Types (SlottingData)
import           Pos.Infra.StateLock (newStateLock)
import           Pos.Infra.Util.JsonLog.Events (JsonLogConfig (..),
                     jsonLogConfigFromHandle)
import           Pos.Launcher.Mode (InitMode, InitModeContext (..), runInitMode)
import           Pos.Launcher.Param (BaseParams (..), LoggingParams (..),
                     NodeParams (..))
import           Pos.Util (bracketWithLogging, newInitFuture)
import           Pos.Util.Log.Internal (LoggingHandler)
import           Pos.Util.Log.LoggerConfig (defaultInteractiveConfiguration,
                     isWritingToConsole, lcLoggerTree, ltHandlers)
import           Pos.Util.Wlog (LoggerConfig (..), Severity (..), WithLogger,
                     logDebug, logInfo, parseLoggerConfig, removeAllHandlers,
                     setupLogging')

#ifdef linux_HOST_OS
import qualified Pos.Util.Wlog as Logger
import qualified System.Systemd.Daemon as Systemd
#endif

----------------------------------------------------------------------------
-- Data type
----------------------------------------------------------------------------

-- | This data type contains all resources used by node.
data NodeResources ext = NodeResources
    { nrContext       :: !NodeContext
    , nrDBs           :: !NodeDBs
    , nrSscState      :: !SscState
    , nrTxpState      :: !(GenericTxpLocalData ext)
    , nrDlgState      :: !DelegationVar
    , nrJsonLogConfig :: !JsonLogConfig
    -- ^ Config for optional JSON logging.
    , nrEkgStore      :: !Metrics.Store
    , nrConsolidate   :: !(Async ())
    , nrFInjects      :: !(FInjects IO)
    }

----------------------------------------------------------------------------
-- Allocation/release/bracket
----------------------------------------------------------------------------

-- | Allocate all resources used by node. They must be released eventually.
allocateNodeResources
    :: forall ext .
       ( Default ext
       , HasNodeConfiguration
       , HasDlgConfiguration
       , HasBlockConfiguration
       )
    => Genesis.Config
    -> NodeParams
    -> SscParams
    -> TxpGlobalSettings
    -> InitMode ()
    -> IO (NodeResources ext)
allocateNodeResources genesisConfig np@NodeParams {..} sscnp txpSettings initDB = do
    logInfo "Allocating node resources..."
    npDbPath <- case npDbPathM of
        Nothing -> do
            let dbPath = "node-db" :: FilePath
            logInfo $ sformat ("DB path not specified, defaulting to "%
                               shown) dbPath
            return dbPath
        Just dbPath -> return dbPath
    db <- openNodeDBs npRebuildDb npDbPath
    (futureLrcContext, putLrcContext) <- newInitFuture "lrcContext"
    (futureSlottingVar, putSlottingVar) <- newInitFuture "slottingVar"
    (futureSlottingContext, putSlottingContext) <- newInitFuture "slottingContext"
    let putSlotting sv sc = do
            putSlottingVar sv
            putSlottingContext sc
        initModeContext = InitModeContext
            db
            futureSlottingVar
            futureSlottingContext
            futureLrcContext
    logDebug "Opened DB, created some futures, going to run InitMode"
    runInitMode initModeContext $ do
        initDB
        logDebug "Initialized DB"

        consAsync <- Async.async $ consolidateWorker genesisConfig
        logDebug "Initialized block/epoch consolidation"

        nrEkgStore <- liftIO $ Metrics.newStore
        logDebug "Created EKG store"

        txpVar <- mkTxpLocalData -- doesn't use slotting or LRC
        let ancd =
                AllocateNodeContextData
                { ancdNodeParams = np
                , ancdSscParams = sscnp
                , ancdPutSlotting = putSlotting
                , ancdNetworkCfg = npNetworkConfig
                , ancdEkgStore = nrEkgStore
                , ancdTxpMemState = txpVar
                }
        ctx@NodeContext {..} <-
            allocateNodeContext genesisConfig ancd txpSettings nrEkgStore
        putLrcContext ncLrcContext
        logDebug "Filled LRC Context future"
        dlgVar <- mkDelegationVar
        logDebug "Created DLG var"
        sscState <- mkSscState $ configEpochSlots genesisConfig
        logDebug "Created SSC var"
        jsonLogHandle <-
            case npJLFile of
                Nothing -> pure Nothing
                Just fp -> do
                    h <- openFile fp WriteMode
                    liftIO $ hSetBuffering h LineBuffering
                    return $ Just h
        jsonLogConfig <- maybe
            (pure JsonLogDisabled)
            jsonLogConfigFromHandle
            jsonLogHandle
        logDebug "JSON configuration initialized"

        logDebug "Finished allocating node resources!"
        return NodeResources
            { nrContext = ctx
            , nrDBs = db
            , nrSscState = sscState
            , nrTxpState = txpVar
            , nrDlgState = dlgVar
            , nrJsonLogConfig = jsonLogConfig
            , nrConsolidate = consAsync
            , nrFInjects = npFInjects
            , ..
            }

-- | Release all resources used by node. They must be released eventually.
releaseNodeResources ::
       NodeResources ext -> IO ()
releaseNodeResources NodeResources {..} = do
    case nrJsonLogConfig of
        JsonLogDisabled -> return ()
        JsonLogConfig mVarHandle _ -> do
            h <- takeMVar mVarHandle
            (liftIO . hClose) h
            putMVar mVarHandle h
    closeNodeDBs nrDBs
    Async.cancel nrConsolidate
    releaseNodeContext nrContext

-- | Run computation which requires 'NodeResources' ensuring that
-- resources will be released eventually.
bracketNodeResources :: forall ext a.
      ( Default ext
      , HasNodeConfiguration
      , HasDlgConfiguration
      , HasBlockConfiguration
      )
    => Genesis.Config
    -> NodeParams
    -> SscParams
    -> TxpGlobalSettings
    -> InitMode ()
    -> (NodeResources ext -> IO a)
    -> IO a
bracketNodeResources genesisConfig np sp txp initDB action = do
    let msg = "`NodeResources'"
    bracketWithLogging msg
            (allocateNodeResources genesisConfig np sp txp initDB)
            releaseNodeResources $ \nodeRes ->do
        -- Notify systemd we are fully operative
        -- FIXME this is not the place to notify.
        -- The network transport is not up yet.
        notifyReady
        action nodeRes

----------------------------------------------------------------------------
-- Logging
----------------------------------------------------------------------------

getRealLoggerConfig :: MonadIO m => LoggingParams -> m LoggerConfig
getRealLoggerConfig LoggingParams{..} = do
    case lpConfigPath of
        Just configPath -> parseLoggerConfig configPath
        Nothing         -> return (mempty :: LoggerConfig)
    >>= \lc -> return $ (overridePrefixPath . overrideConsoleLog) lc
  where
    overridePrefixPath :: LoggerConfig -> LoggerConfig
    overridePrefixPath = case lpHandlerPrefix of
        Nothing -> identity
        Just _  -> \lc -> lc { _lcBasePath = lpHandlerPrefix }
    overrideConsoleLog :: LoggerConfig -> LoggerConfig
    overrideConsoleLog = case lpConsoleLog of
        Nothing    -> identity
        Just True  -> (<> defaultInteractiveConfiguration Info)
                      -- add output to the console with severity filter >= Info
        Just False -> lcLoggerTree . ltHandlers %~ filter (not . isWritingToConsole)

setupLoggers :: MonadIO m => Text -> LoggingParams -> m LoggingHandler
setupLoggers cfoKey params = setupLogging' cfoKey =<< getRealLoggerConfig params

-- | RAII for Logging.
loggerBracket :: Text -> LoggingParams -> IO a -> IO a
loggerBracket cfoKey lp action = bracket (setupLoggers cfoKey lp) removeAllHandlers (const action)

----------------------------------------------------------------------------
-- NodeContext
----------------------------------------------------------------------------

data AllocateNodeContextData ext = AllocateNodeContextData
    { ancdNodeParams  :: !NodeParams
    , ancdSscParams   :: !SscParams
    , ancdPutSlotting :: (Timestamp, TVar SlottingData) -> SimpleSlottingStateVar -> InitMode ()
    , ancdNetworkCfg  :: NetworkConfig KademliaParams
    , ancdEkgStore    :: !Metrics.Store
    , ancdTxpMemState :: !(GenericTxpLocalData ext)
    }

allocateNodeContext
    :: forall ext .
      (HasNodeConfiguration, HasBlockConfiguration)
    => Genesis.Config
    -> AllocateNodeContextData ext
    -> TxpGlobalSettings
    -> Metrics.Store
    -> InitMode NodeContext
allocateNodeContext genesisConfig ancd txpSettings ekgStore = do
    let epochSlots = configEpochSlots genesisConfig
    let AllocateNodeContextData { ancdNodeParams = np@NodeParams {..}
                                , ancdSscParams = sscnp
                                , ancdPutSlotting = putSlotting
                                , ancdNetworkCfg = networkConfig
                                , ancdEkgStore = store
                                , ancdTxpMemState = TxpLocalData {..}
                                } = ancd
    logInfo "Allocating node context..."
    ncLoggerConfig <- getRealLoggerConfig $ bpLoggingParams npBaseParams
    logDebug "Got logger config"
    ncStateLock <- newStateLock =<< GS.getTip
    logDebug "Created a StateLock"
    ncStateLockMetrics <- liftIO $ recordTxpMetrics store txpMemPool
    logDebug "Created StateLock metrics"
    lcLrcSync <- mkLrcSyncData >>= newTVarIO
    logDebug "Created LRC sync"
    ncSlottingVar <- (configStartTime genesisConfig,) <$> mkSlottingVar
    logDebug "Created slotting variable"
    ncSlottingContext <- mkSimpleSlottingStateVar epochSlots
    logDebug "Created slotting context"
    putSlotting ncSlottingVar ncSlottingContext
    logDebug "Filled slotting future"
    ncUserSecret <- newTVarIO $ npUserSecret
    logDebug "Created UserSecret variable"
    ncBlockRetrievalQueue <- liftIO $ newTBQueueIO blockRetrievalQueueSize
    ncRecoveryHeader <- liftIO newEmptyTMVarIO
    logDebug "Created block retrieval queue, recovery and progress headers"
    ncShutdownFlag <- newTVarIO Nothing
    ncStartTime <- StartTime <$> liftIO Time.getCurrentTime
    ncLastKnownHeader <- newTVarIO Nothing
    logDebug "Created last known header and shutdown flag variables"
    ncUpdateContext <- mkUpdateContext epochSlots
    logDebug "Created context for update"
    ncSscContext <- createSscContext sscnp
    logDebug "Created context for ssc"
    ncSlogContext <- mkSlogContext genesisConfig store
    logDebug "Created context for slog"
    -- TODO synchronize the NodeContext peers var with whatever system
    -- populates it.
    peersVar <- newTVarIO mempty
    logDebug "Created peersVar"
    mm <- initializeMisbehaviorMetrics ekgStore

    logDebug ("Dequeue policy to core:  " <> (show ((ncDequeuePolicy networkConfig) NodeCore)))
        `catch` \(ErrorCall msg) -> logDebug (toText msg)
    logDebug ("Dequeue policy to relay: " <> (show ((ncDequeuePolicy networkConfig) NodeRelay)))
        `catch` \(ErrorCall msg) -> logDebug (toText msg)
    logDebug ("Dequeue policy to edge: " <> (show ((ncDequeuePolicy networkConfig) NodeEdge)))
        `catch` \(ErrorCall msg) -> logDebug (toText msg)

    logDebug "Finished allocating node context!"
    let ctx =
            NodeContext
            { ncConnectedPeers = ConnectedPeers peersVar
            , ncLrcContext = LrcContext {..}
            , ncShutdownContext = ShutdownContext ncShutdownFlag npFInjects
            , ncNodeParams = np
            , ncTxpGlobalSettings = txpSettings
            , ncNetworkConfig = networkConfig
            , ncMisbehaviorMetrics = Just mm
            , ..
            }
    return ctx

releaseNodeContext :: forall m . MonadIO m => NodeContext -> m ()
releaseNodeContext _ = return ()

-- Create new 'SlottingVar' using data from DB. Probably it would be
-- good to have it in 'infra', but it's complicated.
mkSlottingVar :: (MonadIO m, MonadDBRead m) => m (TVar SlottingData)
mkSlottingVar = newTVarIO =<< GState.getSlottingData

-- | Notify process manager tools like systemd the node is ready.
-- Available only on Linux for systems where `libsystemd-dev` is installed.
-- It defaults to a noop for all the other platforms.
#ifdef linux_HOST_OS
notifyReady :: (MonadIO m, WithLogger m) => m ()
notifyReady = do
    res <- liftIO Systemd.notifyReady
    case res of
        Just () -> return ()
        Nothing -> Logger.logWarning "notifyReady failed to notify systemd."
#else
notifyReady :: (WithLogger m) => m ()
notifyReady = logInfo "notifyReady: no systemd support enabled"
#endif


text:
<!--
  Copyright 2014 Google Inc. All rights reserved.

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

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  -->
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:iosched="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/menu_search"
        android:icon="@drawable/ic_action_search"
        android:orderInCategory="1"
        android:title="@string/description_search"
        iosched:showAsAction="always" />

    <item android:id="@+id/menu_refresh"
        android:orderInCategory="1"
        android:icon="@drawable/refresh_icon_white"
        android:title="@string/description_refresh"
        iosched:showAsAction="always" />

    <item android:id="@+id/menu_map"
        android:orderInCategory="100"
        android:title="@string/description_map"
        android:visible="false"
        iosched:showAsAction="never" />

    <item android:id="@+id/menu_about"
        android:orderInCategory="99"
        android:title="@string/description_about"
        iosched:showAsAction="never" />

</menu>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.javaee7.extra.nosql</groupId>
        <artifactId>extra-nosql-samples</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <groupId>org.javaee7.extra.nosql</groupId>
    <artifactId>hbase</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-core</artifactId>
            <version>0.20.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase</artifactId>
            <version>0.94.2</version>
        </dependency>
    </dependencies>
</project>


text:
Imports SolidEdgeCommunity
Imports SolidEdgeCommunity.Extensions
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Threading.Tasks

Friend Class Program
    <STAThread> _
    Shared Sub Main(ByVal args() As String)
        ' Dictionary variables to hold before and after settings.
        Dim snapshot1 = New Dictionary(Of SolidEdgeFramework.ApplicationGlobalConstants, Object)()
        Dim snapshot2 = New Dictionary(Of SolidEdgeFramework.ApplicationGlobalConstants, Object)()

        ' Connect to Solid Edge.
        Dim application = SolidEdgeUtils.Connect()

        ' Begin snapshot 1 of application global constants.
        CaptureApplicationGlobalConstants(application, snapshot1)

        ' Force break-point. Change the Solid Edge setting in question.
        System.Diagnostics.Debugger.Break()

        ' Begin snapshot 2 of application global constants.
        CaptureApplicationGlobalConstants(application, snapshot2)

        ' Report the changes from snapshot 1 and snapshot 2.
        Dim enumerator = snapshot1.GetEnumerator()

        Do While enumerator.MoveNext()
            Dim enumConstant = enumerator.Current.Key
            Dim enumValue1 = enumerator.Current.Value
            Dim enumValue2 = snapshot2(enumConstant)

            ' We can safely ignore seApplicationGlobalSystemInfo. It's just noise for our purpose.
            If enumConstant.Equals(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalSystemInfo) Then
                Continue Do
            End If

            ' Check to see if the snapshot 1 and snapshot 2 value is equal.
            If Object.Equals(enumValue1, enumValue2) = False Then
                Console.WriteLine("{0}: '{1}' '{2}'", enumConstant, enumValue1, enumValue2)
            End If
        Loop

        ' This will pause the console window.
        Console.WriteLine()
        Console.WriteLine("Press enter to contine.")
        Console.ReadLine()
    End Sub

    Private Shared Sub CaptureApplicationGlobalConstants(ByVal application As SolidEdgeFramework.Application, ByVal dictionary As Dictionary(Of SolidEdgeFramework.ApplicationGlobalConstants, Object))
        ' Get list of SolidEdgeFramework.ApplicationGlobalConstants names and values.
        Dim enumConstants = System.Enum.GetNames(GetType(SolidEdgeFramework.ApplicationGlobalConstants)).ToArray()
        Dim enumValues = System.Enum.GetValues(GetType(SolidEdgeFramework.ApplicationGlobalConstants)).Cast(Of SolidEdgeFramework.ApplicationGlobalConstants)().ToArray()

        ' Populate the dictionary.
        For i As Integer = 0 To enumValues.Length - 1
            Dim enumConstant = enumConstants(i)
            Dim enumValue = enumValues(i)
            Dim value As Object = Nothing

            If enumValue.Equals(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalOpenAsReadOnly3DFile) Then
                Continue For
            End If

            ' We can safely ignore seApplicationGlobalSystemInfo. It's just noise for our purpose.
            If enumConstant.Equals(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalSystemInfo) Then
                Continue For
            End If

            application.GetGlobalParameter(enumValue, value)
            dictionary.Add(enumValue, value)
        Next i
    End Sub
End Class


text:
package smtlib
package lexer

import common._

object Tokens {

  sealed class Token(val kind: TokenKind) extends Positioned {
    override def toString = kind.toString
  }
  object Token {
    def apply(kind: TokenKind): Token = new Token(kind)
    def unapply(token: Token): Option[TokenKind] = Some(token.kind)
  }

  case class StringLit(content: String) extends Token(StringLitKind) {
    override def toString = "\"" + content + "\""
  }
  case class SymbolLit(content: String) extends Token(SymbolLitKind) {
    override def toString = s"$content"
  }
  case class Keyword(name: String) extends Token(KeywordKind) {
    override def toString = s":$name"
  }

  case class NumeralLit(n: BigInt) extends Token(NumeralLitKind) {
    override def toString = n.toString
  }
  case class DecimalLit(d: Double) extends Token(DecimalLitKind) {
    override def toString = d.toString
  }
  case class BinaryLit(content: Seq[Boolean]) extends Token(BinaryLitKind) {
    override def toString = content.map(d => if(d) "1" else "0").mkString
  }
  case class HexadecimalLit(content: Hexadecimal) extends Token(HexadecimalLitKind) {
    override def toString = content.toString
  }

  sealed abstract class TokenKind

  case object OParen extends TokenKind /* ( */
  case object CParen extends TokenKind /* ) */

  case object StringLitKind extends TokenKind /* "hello" */
  case object SymbolLitKind extends TokenKind /* hello */
  case object KeywordKind extends TokenKind /* :bar */
  case object NumeralLitKind extends TokenKind /* 42 */
  case object DecimalLitKind extends TokenKind /* 42.24 */
  case object BinaryLitKind extends TokenKind /* #b0101 */
  case object HexadecimalLitKind extends TokenKind /* #xFF1D */

  sealed trait ReservedWord extends TokenKind
  case object BINARY extends ReservedWord
  case object DECIMAL extends ReservedWord
  case object HEXADECIMAL extends ReservedWord
  case object NUMERAL extends ReservedWord
  case object STRING extends ReservedWord
  case object Underscore extends ReservedWord /* _ */
  case object ExclamationMark extends ReservedWord /* ! */
  case object As extends ReservedWord /* as */
  case object Let extends ReservedWord /* let */
  case object Forall extends ReservedWord /* forall */
  case object Exists extends ReservedWord /* exists */
  case object Par extends ReservedWord

  case object Assert extends ReservedWord
  case object CheckSat extends ReservedWord
  case object CheckSatAssuming extends ReservedWord
  case object DeclareConst extends ReservedWord
  case object DeclareFun extends ReservedWord
  case object DeclareSort extends ReservedWord
  case object DefineFun extends ReservedWord
  case object DefineFunRec extends ReservedWord
  case object DefineFunsRec extends ReservedWord
  case object DefineSort extends ReservedWord
  case object Echo extends ReservedWord
  case object Exit extends ReservedWord
  case object GetAssertions extends ReservedWord
  case object GetAssignment extends ReservedWord
  case object GetInfo extends ReservedWord
  case object GetModel extends ReservedWord
  case object GetOption extends ReservedWord
  case object GetProof extends ReservedWord
  case object GetUnsatAssumptions extends ReservedWord
  case object GetUnsatCore extends ReservedWord
  case object GetValue extends ReservedWord
  case object Pop extends ReservedWord
  case object Push extends ReservedWord
  case object Reset extends ReservedWord
  case object ResetAssertions extends ReservedWord
  case object SetInfo extends ReservedWord
  case object SetLogic extends ReservedWord
  case object SetOption extends ReservedWord

  case object DeclareDatatypes extends ReservedWord

  def reservedToSymbol(word: ReservedWord): String = word match {
    case BINARY => "BINARY"
    case DECIMAL => "DECIMAL"
    case HEXADECIMAL => "HEXADECIMAl"
    case NUMERAL => "NUMERAL"
    case STRING => "STRING"
    case Underscore => "_"
    case ExclamationMark => "!"
    case As => "as"
    case Let => "let"
    case Forall => "forall"
    case Exists => "exists"
    case Par => "par"

    case Assert => "assert"
    case CheckSat => "check-sat"
    case CheckSatAssuming => "check-sat-assuming"
    case DeclareConst => "declare-const"
    case DeclareFun => "declare-fun"
    case DeclareSort => "ddeclare-sort"
    case DefineFun => "define-fun"
    case DefineFunRec => "define-fun-rec"
    case DefineFunsRec => "define-funs-rec"
    case DefineSort => "define-sort"
    case Echo => "echo"
    case Exit => "exit"
    case GetAssertions => "get-assertions"
    case GetAssignment => "get-assignment"
    case GetInfo => "get-info"
    case GetModel => "get-model"
    case GetOption => "get-option"
    case GetProof => "get-proof"
    case GetUnsatAssumptions => "get-unsat-assumptions"
    case GetUnsatCore => "get-unsat-core"
    case GetValue => "get-value"
    case Pop => "pop"
    case Push => "push"
    case Reset => "reset"
    case ResetAssertions => "reset-assetions"
    case SetInfo => "set-info"
    case SetLogic => "set-logic"
    case SetOption => "set-option"

    case DeclareDatatypes => "declare-datatypes"

  }
}


text:
package org.openkoala.security.taglibs;

import java.util.Collection;
import java.util.Set;

import javax.servlet.jsp.JspException;

import org.springframework.util.StringUtils;

/**
 * 角色标签,支持与或非(and or not)。
 * 不支持复杂的与或非嵌套使用。
 * 具体的实现交给了{@link org.openkoala.security.taglibs.Authz}。
 *
 * @author lucas
 */
public class RoleTag extends AbstractAuthorizationTag {

    private static final long serialVersionUID = -2908081619697933536L;

    protected Authz authz = null;

    protected String ifAnyRoles = null;

    protected String ifAllRoles = null;

    protected String ifNotRoles = null;

    private boolean hasTextAllRole = false;

    private boolean hasTextAnyRole = false;

    private boolean hasTextNotRole = false;

    /**
     * 验证属性,hasTextAllRole、hasTextAnyRole和hasTextNotRole中必须有一个不为空。
     *
     * @throws JspException 如果hasTextAllRole、hasTextAnyRole和hasTextNotRole属性值都为空,将抛出异常
     */
    @Override
    protected void verifyAttributes() throws JspException {

        hasTextAllRole = StringUtils.hasText(getIfAllRoles());
        hasTextAnyRole = StringUtils.hasText(getIfAnyRoles());
        hasTextNotRole = StringUtils.hasText(getIfNotRoles());

        if ((!hasTextAllRole) && (!hasTextAnyRole) && (!hasTextNotRole)) {
            String msg = "The 'ifAnyRoles' or 'ifNotRoles' or 'ifAllRoles' must be set the another!";
            throw new JspException(msg);
        }
    }

    @Override
    public int onDoStartTag() throws JspException {

        if (authz == null) {
            authz = new AuthzImpl();
        }

        if (hasTextAllRole) {
            final Collection<String> requiredRoles = splitAuthorities(getIfAllRoles());
            if (authz.ifAllRole(requiredRoles)) {
                return EVAL_BODY_INCLUDE;
            }
        }

        if (hasTextAnyRole) {
            final Set<String> expectOneOfRoles = splitAuthorities(getIfAnyRoles());
            if (authz.ifAnyRole(expectOneOfRoles)) {
                return EVAL_BODY_INCLUDE;
            }
        }

        if (hasTextNotRole) {
            final Set<String> expectNoneOfRoles = splitAuthorities(getIfNotRoles());
            if (authz.ifNotRole(expectNoneOfRoles)) {
                return EVAL_BODY_INCLUDE;
            }
        }

        return SKIP_BODY;
    }

    public String getIfAnyRoles() {
        return ifAnyRoles;
    }

    public void setIfAnyRoles(String ifAnyRole) {
        this.ifAnyRoles = ifAnyRole;
    }

    public String getIfAllRoles() {
        return ifAllRoles;
    }

    public void setIfAllRoles(String ifAllRole) {
        this.ifAllRoles = ifAllRole;
    }

    public String getIfNotRoles() {
        return ifNotRoles;
    }

    public void setIfNotRoles(String ifNotRole) {
        this.ifNotRoles = ifNotRole;
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
jml.optimization
</TITLE>

<META NAME="date" CONTENT="2014-02-02">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

jml.optimization

Interfaces

Projection

ProximalMapping

Classes

AcceleratedGradientDescent

AcceleratedProximalGradient

BoundConstrainedPLBFGS

GeneralQP

GeneralQPViaPrimalDualInteriorPoint

LBFGS

LBFGSOnSimplex

NonlinearConjugateGradient

NonnegativePLBFGS

PhaseIResult

PrimalDualInteriorPoint

ProjL1

ProjL2

ProjLInfinity

Prox

ProxL1

ProxL2

ProxLInfinity

ProxPlus

QPSolution

QPWithBoundConstraints

ShrinkageOperator


text:
package hotelmania.group4.client;

import com.google.inject.Inject;
import hotelmania.group4.HotelManiaAgent;
import hotelmania.group4.domain.HotelManiaCalendar;
import hotelmania.group4.domain.HotelRepositoryService;
import hotelmania.group4.domain.client.Client;
import hotelmania.group4.domain.client.ClientGenerator;
import hotelmania.group4.guice.GuiceConfigurer;
import hotelmania.group4.platform.OnDayEvent;
import hotelmania.group4.settings.Settings;
import hotelmania.group4.utils.OnEndOfSimulation;
import hotelmania.group4.utils.SubscribeToDayEvents;
import hotelmania.group4.utils.SubscribeToEndOfSimulation;
import hotelmania.ontology.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * First client is created after day 1 notification has been received.
 *
 * @author Marek Lewandowski <marek.lewandowski@icompass.pl>
 * @since 18/05/14
 */
public class ClientAgent extends HotelManiaAgent {

    Logger logger = LoggerFactory.getLogger(getClass());

    Client client;

    @Inject
    ClientGenerator clientGenerator;

    @Inject
    HotelManiaCalendar calendar;

    @Inject
    HotelRepositoryService hotelRepositoryService;

    @Inject
    Settings settings;

    boolean isStayingInHotel = false;

    volatile boolean bookedRoom = false;

    private Map<HotelInformation, Price> hotelToPrice = new HashMap<>();

    private class BestOffer {
        private final HotelInformation hotelInformation;

        private final Price price;

        private BestOffer (HotelInformation hotelInformation, Price price) {
            this.hotelInformation = hotelInformation;
            this.price = price;
        }

        private HotelInformation getHotelInformation () {
            return hotelInformation;
        }

        private Price getPrice () {
            return price;
        }
    }

    @Override protected void setupHotelManiaAgent () {
        GuiceConfigurer.getInjector().injectMembers(this);

        client = clientGenerator.generateClient(calendar.today().getDay());

        final SubscribeToDayEvents subscribeToDayEvents = new SubscribeToDayEvents(this, new OnDayEvent() {
            @Override public void onDayEvent (NotificationDayEvent notificationDayEvent) {
                doClientStuff(notificationDayEvent.getDayEvent());
            }
        });

        subscribeToDayEvents.doSubscription();

        final SubscribeToEndOfSimulation subscribeToEndOfSimulation = new SubscribeToEndOfSimulation(this, new OnEndOfSimulation() {
            @Override public void onEndOfSimulation () {
                // TODO do something during end of simulation
            }
        });

        subscribeToEndOfSimulation.doSubscription();

        performStuffToday();
    }

    private void performStuffToday () {
        doClientStuff(calendar.today());
    }

    /**
     * TODO client logic. so far it books first offer it gets
     *
     * @param dayEvent
     */
    private void doClientStuff (DayEvent dayEvent) {
        logger.info(getName() + " doing client stuff during day {}", dayEvent.getDay());

        if (bookedRoom) {
            // TODO wait for checkOut day and then ask for staff during days and then give rating
        } else {

            final Set<HotelInformation> hotelInformation = hotelRepositoryService.getHotelInformation();
            final AskHotelsForPrice.OnPrices onPrices = new AskHotelsForPrice.OnPrices() {
                @Override public void prices (Map<HotelInformation, Price> prices) {
                    logger.debug("Got prices {}", prices.toString());

                    List<BestOffer> bestOffers = findBestOffers(prices);
                    if (bestOffers.size() > 0) {
                        final BestOffer next = bestOffers.iterator().next();
                        BookRoom bookRoom = new BookRoom();
                        bookRoom.setPrice(next.getPrice());
                        bookRoom.setStay(client.getStay());
                        final DoBookRoom doBookRoom = new DoBookRoom(ClientAgent.this, next.getHotelInformation().getHotel().getHotelAgent(), bookRoom, new DoBookRoom.BookResult() {
                            @Override public void success () {
                                logger.info("{} booked room", getName());
                                bookedRoom = true;
                            }

                            @Override public void fail () {
                                // TODO try second best or do something else depends on the day
                            }
                        });
                        addBehaviour(doBookRoom);
                    }
                }
            };
            final AskHotelsForPrice askHotelsForPrice = new AskHotelsForPrice(hotelInformation, getTimeout(), this, client.getStay(), onPrices);
            askHotelsForPrice.askForPrices();

        }
    }

    private List<BestOffer> findBestOffers (Map<HotelInformation, Price> prices) {
        // TODO implement it according to spec
        List<BestOffer> bestOffers = new ArrayList<>();

        final Map.Entry<HotelInformation, Price> next = prices.entrySet().iterator().next();

        final HotelInformation key = next.getKey();
        final Price value = next.getValue();

        bestOffers.add(new BestOffer(key, value));

        return bestOffers;
    }

    public long getTimeout () {
        return settings.getDayLengthInSeconds() / 2;
    }
}


text:
package javassist.tools.rmi;

import java.io.*;

import javassist.tools.web.*;
import javassist.CannotCompileException;
import javassist.NotFoundException;
import javassist.ClassPool;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.Vector;

/**
 * An AppletServer object is a web server that an ObjectImporter
 * communicates with.  It makes the objects specified by
 * exportObject() remotely accessible from applets.
 * If the classes of the exported objects are requested by the client-side
 * JVM, this web server sends proxy classes for the requested classes.
 *
 * @see ObjectImporter
 */
public class AppletServer extends Webserver {
    private StubGenerator stubGen;
    private Hashtable<String, ExportedObject> exportedNames;
    private Vector<ExportedObject> exportedObjects;

    private static final byte[] okHeader
                                = "HTTP/1.0 200 OK\r\n\r\n".getBytes();

    /**
     * Constructs a web server.
     *
     * @param port      port number
     */
    public AppletServer(String port)
        throws IOException, NotFoundException, CannotCompileException
    {
        this(Integer.parseInt(port));
    }

    /**
     * Constructs a web server.
     *
     * @param port      port number
     */
    public AppletServer(int port)
        throws IOException, NotFoundException, CannotCompileException
    {
        this(ClassPool.getDefault(), new StubGenerator(), port);
    }

    /**
     * Constructs a web server.
     *
     * @param port      port number
     * @param src       the source of classs files.
     */
    public AppletServer(int port, ClassPool src)
        throws IOException, NotFoundException, CannotCompileException
    {
        this(new ClassPool(src), new StubGenerator(), port);
    }

    private AppletServer(ClassPool loader, StubGenerator gen, int port)
        throws IOException, NotFoundException, CannotCompileException
    {
        super(port);
        exportedNames = new Hashtable<String, ExportedObject>();
        exportedObjects = new Vector<ExportedObject>();
        stubGen = gen;
        addTranslator(loader, gen);
    }

    /**
     * Begins the HTTP service.
     */
    public void run() {
        super.run();
    }

    /**
     * Exports an object.
     * This method produces the bytecode of the proxy class used
     * to access the exported object.  A remote applet can load
     * the proxy class and call a method on the exported object.
     *
     * @param name      the name used for looking the object up.
     * @param obj       the exported object.
     * @return          the object identifier
     *
     * @see ObjectImporter#lookupObject(String)
     */
    public synchronized int exportObject(String name, Object obj)
        throws CannotCompileException
    {
        Class<?> clazz = obj.getClass();
        ExportedObject eo = new ExportedObject();
        eo.object = obj;
        eo.methods = clazz.getMethods();
        exportedObjects.addElement(eo);
        eo.identifier = exportedObjects.size() - 1;
        if (name != null)
            exportedNames.put(name, eo);

        try {
            stubGen.makeProxyClass(clazz);
        }
        catch (NotFoundException e) {
            throw new CannotCompileException(e);
        }

        return eo.identifier;
    }

    /**
     * Processes a request from a web browser (an ObjectImporter).
     */
    public void doReply(InputStream in, OutputStream out, String cmd)
        throws IOException, BadHttpRequest
    {
        if (cmd.startsWith("POST /rmi "))
            processRMI(in, out);
        else if (cmd.startsWith("POST /lookup "))
            lookupName(cmd, in, out);
        else
            super.doReply(in, out, cmd);
    }

    private void processRMI(InputStream ins, OutputStream outs)
        throws IOException
    {
        ObjectInputStream in = new ObjectInputStream(ins);

        int objectId = in.readInt();
        int methodId = in.readInt();
        Exception err = null;
        Object rvalue = null;
        try {
            ExportedObject eo
                = (ExportedObject)exportedObjects.elementAt(objectId);
            Object[] args = readParameters(in);
            rvalue = convertRvalue(eo.methods[methodId].invoke(eo.object,
                                                               args));
        }
        catch(Exception e) {
            err = e;
            logging2(e.toString());
        }

        outs.write(okHeader);
        ObjectOutputStream out = new ObjectOutputStream(outs);
        if (err != null) {
            out.writeBoolean(false);
            out.writeUTF(err.toString());
        }
        else
            try {
                out.writeBoolean(true);
                out.writeObject(rvalue);
            }
            catch (NotSerializableException e) {
                logging2(e.toString());
            }
            catch (InvalidClassException e) {
                logging2(e.toString());
            }

        out.flush();
        out.close();
        in.close();
    }

    private Object[] readParameters(ObjectInputStream in)
        throws IOException, ClassNotFoundException
    {
        int n = in.readInt();
        Object[] args = new Object[n];
        for (int i = 0; i < n; ++i) {
            Object a = in.readObject();
            if (a instanceof RemoteRef) {
                RemoteRef ref = (RemoteRef)a;
                ExportedObject eo
                    = (ExportedObject)exportedObjects.elementAt(ref.oid);
                a = eo.object;
            }

            args[i] = a;
        }

        return args;
    }

    private Object convertRvalue(Object rvalue)
        throws CannotCompileException
    {
        if (rvalue == null)
            return null;        // the return type is void.

        String classname = rvalue.getClass().getName();
        if (stubGen.isProxyClass(classname))
            return new RemoteRef(exportObject(null, rvalue), classname);
        else
            return rvalue;
    }

    private void lookupName(String cmd, InputStream ins, OutputStream outs)
        throws IOException
    {
        ObjectInputStream in = new ObjectInputStream(ins);
        String name = DataInputStream.readUTF(in);
        ExportedObject found = (ExportedObject)exportedNames.get(name);
        outs.write(okHeader);
        ObjectOutputStream out = new ObjectOutputStream(outs);
        if (found == null) {
            logging2(name + "not found.");
            out.writeInt(-1);           // error code
            out.writeUTF("error");
        }
        else {
            logging2(name);
            out.writeInt(found.identifier);
            out.writeUTF(found.object.getClass().getName());
        }

        out.flush();
        out.close();
        in.close();
    }
}

class ExportedObject {
    public int identifier;
    public Object object;
    public Method[] methods;
}


text:
This App assumes the API will have to support and serve multiple versions. To do this, ``Accept-Version`` header can be
specified by the client. If none is spcified, then the application default will be used.

Versions will respect [semver](http://semver.org/) convention.

The files in this directory are certified to work with API version 1.0.0 of the ``/fligts`` api


text:
package be.seriousbusiness.brusselnieuws.rss.datastore.model.dto.stub;

import java.math.BigInteger;

import be.seriousbusiness.brusselnieuws.rss.datastore.model.dto.MediumTypeDTO;

/**
 * {@link MediumTypeDTO} stub implementation.
 * @author Serious Business
 * @author Stefan Borghys
 * @version 1.0
 * @since 1.0
 */
public class MediumTypeDTOStub implements MediumTypeDTO {

	@Override
	public BigInteger getId() {
		return BigInteger.valueOf(123123123l);
	}

	@Override
	public void setId(final BigInteger id) {}

	@Override
	public String getType() {
		return "image/png";
	}

	@Override
	public void setType(final String type) {}

}


text:
<?
// Copyright 2014 Tera Insights, LLC. All Rights Reserved.

function SegmenterState(array $targs) {
    $classname = generate_name('SegmenterState');

     $gla = $targs['gla'];
     $npasses = $targs['passes'];
     $segments = $targs['segments'];

     $cArgs = [];
     $configurable = $gla->has_state() && $gla->state()->configurable();

     if( $configurable ) {
        $cArgs['json'] = 'Json::Value';
     }

     $reqStates = $gla->req_states();
     $hasReqStates = \count($reqStates) > 0;
     if( $hasReqStates ) {
        foreach( $reqStates as $name => $type ) {
            $cArgs[$name] = $type;
        }
     }

     $sys_headers = ['cstddef'];

    $splitState = lookupResource('BASE::SplitState', [
        'type' => $gla,
        'size' => $segments
    ]);

     $iterable = $npasses > 1;
?>

struct <?=$classname?> {
    using SplitState = <?=$splitState?>;

    static constexpr const size_t N_PASSES = <?=$npasses?>;

    mutable SplitState segments;

    // Current pass number
    size_t pass;

<?  if($gla->has_state()): ?>
    // Inner GLAs constant state
    <?=$gla->state()?> inner_cstate;
<?  endif; // gla has state ?>

    <?=$classname?>(<?=const_typed_ref_args($cArgs)?>):
        segments()
        , pass(0)
<?  if($gla->has_state()): ?>
        , inner_cstate(<?=args($cArgs)?>)
<?  endif; // gla has state ?>
    {}

    void Reset() {

    }
};

<?
    return [
        'kind'              => 'RESOURCE',
        'name'              => $classname,
        'system_headers'    => $sys_headers,
        'configurable'      => $configurable,
    ];
}

function Segmenter( array $t_args, array $input, array $output, array $given_states) {
    $resType = [ 'fragment', 'multi' ];
    $system_headers = [ 'array', 'vector', 'memory', 'cinttypes' ];
    $user_headers = [ 'HashFunctions.h' ];
    $lib_headers = [];

    $nInputs = \count($input);

    grokit_assert($nInputs > 1, 'Segmenter: Not enough inputs specified!');

    $keyName = array_keys($input)[0];
    $keyType = array_get_index($input, 0);

    $innerInputs = array_slice($input, 1, $nInputs - 1, true);

    $gla = get_first_key($t_args, [ 'gla', 'GLA', 0 ]);
    grokit_assert( is_gla($gla), 'Segmenter: [gla] argument must be a valid GLA');
    $gla = $gla->apply($innerInputs, $output, $given_states);

    $n_passes = get_default($t_args, 'passes', 1);
    grokit_assert(is_int($n_passes), 'Segmenter: [passes] argument must be an integer');
    grokit_assert($n_passes > 0, 'Segmenter: [passes] argument must be > 0');

    $libraries = $gla->libraries();

    $innerRes = get_first_value($gla->result_type(), ['multi', 'fragment']);
    $innerInputs = $gla->input();
    $innerOutput = $gla->output();
    $input = array_merge([ $keyName => $keyType ], $innerInputs);
    $output = $innerOutput;

    $segments = get_default($t_args, 'segments', 64);
    $constState = lookupResource('BASE::SegmenterState', [
        'gla' => $gla,
        'passes' => $n_passes,
        'segments' => $segments
    ]);

    $className = generate_name('Segmenter_');

    $savedArgs = [];
    $cArgs = [];
    $innerCArgs = [];
    if( $gla->configurable() ) {
        $savedArgs['json_init'] = 'Json::Value';
        $cArgs['json_init'] = 'Json::Value';
        $innerCArgs[] = 'json_init';
    }

    $cArgs['const_state'] = $constState;
    if( $gla->has_state() ) {
        $innerCArgs[] = 'constState.inner_cstate';
    }

    $cstStr = \count($innerCArgs) > 0 ? '(' . implode(',',$innerCArgs) . ')' : '';

    grokit_assert(!$gla->iterable(), 'Segementer does not support iterable GLAs');

    $iterable = $n_passes > 1;
?>

class <?=$className?> {
private:

    using ConstantState = <?=$constState?>;
    using SplitState = ConstantState::SplitState;

    static constexpr const size_t NUM_STATES = SplitState::NUM_STATES;

    using InnerGLA = <?=$gla?>;
    using InnerGLAPtr = std::unique_ptr<InnerGLA>;
    using GLA_Array = std::array<InnerGLAPtr, NUM_STATES>;

public:
    using size_type = std::size_t;

<?  if( $innerRes == 'fragment' ) { ?>
    class Iterator {
    private:
        InnerGLA * gla;
        int fragmentNum;

        InnerGLA::Iterator * innerIter;
        int fragNo;
        int nFrags;

    public:
        Iterator( InnerGLA * _gla, int _fragmentNum ) : gla(_gla), fragmentNum(_fragmentNum) {
            fragNo = 0;
            nFrags = gla->GetNumFragments();

            innerIter = gla->Finalize(fragNo);
        }

        ~Iterator(void) {
            if( innerIter != nullptr ) {
                delete innerIter;
                innerIter = nullptr;
            }
        }

        bool GetNextResult( <?=typed_ref_args($gla->output())?> ) {
            bool haveRes = false;
            bool resPossible = fragNo < nFrags; //>

            while( !haveRes && resPossible ) {
                if( innerIter->GetNextResult(<?=args($gla->output())?>) ) {
                    haveRes = true;
                } else {
                    fragNo++;
                    resPossible = fragNo < nFrags; //>
                    delete innerIter;
                    innerIter = nullptr;

                    if( resPossible ) {
                        innerIter = gla->Finalize(fragNo);
                    }
                }
            }

            return haveRes;
        }

        int FragmentNumber() {
            return fragmentNum;
        }
    };
<?  } else { // if inner result type is fragment ?>
    class Iterator {
    private:
        InnerGLA * gla;
        int fragmentNum;

    public:
        Iterator( InnerGLA * _gla, int fragNo ) : gla(_gla), fragmentNum(fragNo) {
            gla->Finalize();
        }

        ~Iterator(void) { }

        bool GetNextResult( <?=typed_ref_args($gla->output())?> ) {
            return gla->GetNextResult(<?=args($gla->output())?>);
        }

        int FragmentNumber() {
            return fragmentNum;
        }
    };
<?  } // if inner result type is multi ?>

private:

    const ConstantState & constState;
    GLA_Array localState;

    // Iteration state for multi result type
    int multiFragNo;
    Iterator * multiIter;

<?  foreach($savedArgs as $name => $type) { ?>
    const <?=$type?> <?=$name?>;
<?  } // foreach saved arg ?>

public:

    // Constructor
    <?=$className?>( <?=const_typed_ref_args($cArgs)?> ) :
        constState(const_state)
        , localState()
        , multiFragNo(0)
        , multiIter(nullptr)
<?  foreach($savedArgs as $name => $type) { ?>
        , <?=$name?>(<?=$name?>)
<?  } // foreach constructor arg to save ?>
    {
        for( auto & elem : localState ) {
            elem.reset(new InnerGLA<?=$cstStr?>);
        }
    }

    void AddItem( <?=const_typed_ref_args($input)?> ) {
        uint64_t hashVal = CongruentHash(Hash(<?=$keyName?>), H_b + 1);
        uint64_t passNum = (hashVal / NUM_STATES) % ConstantState::N_PASSES;
        uint64_t segNum = hashVal % NUM_STATES;

<?  if( $n_passes > 1 ): ?>
        if( passNum != constState.pass ) {
            return;
        }
<?  endif; // more than 1 pass ?>
        localState[segNum]->AddItem(<?=args($innerInputs)?>);
    }

    void ChunkBoundary(void) {
        // Merge local states into the global state

        SplitState & globalStates = constState.segments;

        int theseAreOk[NUM_STATES];
        for( int i = 0; NUM_STATES > i; i++ ) {
            theseAreOk[i] = 1;
        }

        int segsLeft = NUM_STATES;

        while( segsLeft > 0 ) {
            InnerGLA * checkedOut = nullptr;
            int whichOne = globalStates.CheckOutOne( theseAreOk, checkedOut );

            if( checkedOut == NULL ) {
                checkedOut = new InnerGLA<?=$cstStr?>;
            }

            checkedOut->AddState( *(localState[whichOne]) );

            globalStates.CheckIn( whichOne, checkedOut );

            theseAreOk[whichOne] = 0;
            segsLeft--;
        }

        // Re-initialize the local states
        for( auto & elem : localState ) {
<?  if( $gla->is('resettable') ) { ?>
            elem->Reset();
<?  } else { // if resettable ?>
            elem.reset(new InnerGLA<?=$cstStr?>);
<?  } // if not resettable ?>
        }
    }

    void AddState( <?=$className?> & o ) {
        // Do nothing
    }

    void Finalize() {
        SplitState & globalStates = constState.segments;

        if( multiIter != nullptr)
            delete multiIter;

        multiFragNo = 0;
        multiIter = new Iterator(globalStates.Peek(multiFragNo), multiFragNo);
    }

    bool GetNextResult(<?=typed_ref_args($output)?>) {
        bool gotResult = false;
        SplitState & globalStates = constState.segments;

        while( (NUM_STATES > multiFragNo && multiIter != nullptr) && !gotResult ) {
            gotResult = multiIter->GetNextResult(<?=args($output)?>);

            if( !gotResult ) {
                multiFragNo++;
                delete multiIter;

                if( NUM_STATES > multiFragNo ) {
                    multiIter = new Iterator(globalStates.Peek(multiFragNo), multiFragNo);
                } else {
                    multiIter = nullptr;
                }
            }
        }

        return gotResult;
    }

    int GetNumFragments(void) {
        return NUM_STATES;
    }

    Iterator * Finalize( int fragment ) {
        SplitState & globalStates = constState.segments;
        return new Iterator(globalStates.Peek(fragment), fragment);
    }

    bool GetNextResult( Iterator * it, <?=typed_ref_args($output)?> ) {
        bool ret = it->GetNextResult(<?=args($output)?>);

        return ret;
    }

<?  if($iterable): ?>
    bool ShouldIterate( ConstantState & modible ) {
        modible.pass++;

        return modible.pass < ConstantState::N_PASSES;
    }

    void PostFinalize() {
        constState.segments.Reset();
    }
<?  endif; // iterable ?>

<?  if( $gla->is('finite container') ) { ?>
    size_type size() {
        SplitState & globalStates = constState.segments;
        size_type s = 0;
        for( int i = 0; NUM_STATES > i; i++ ) {
            InnerGLA * ptr = globalStates.Peek(i);
            s += ptr->size();
        }

        return s;
    }

    size_type size(int frag) {
        SplitState & globalStates = constState.segments;
        return globalStates.Peek(frag)->size();
    }
<?  } // if the gla is a container ?>
};

typedef <?=$className?>::Iterator <?=$className?>_Iterator;

<?
    return [
        'kind'              => 'GLA',
        'name'              => $className,
        'system_headers'    => $system_headers,
        'user_headers'      => $user_headers,
        'lib_headers'       => $lib_headers,
        'libraries'         => $libraries,
        'input'             => $input,
        'output'            => $output,
        'result_type'       => $resType,
        'generated_state'   => $constState,
        'required_states'   => $gla->req_states(),
        'chunk_boundary'    => true,
        'configurable'      => $gla->configurable(),
        'iterable'          => $iterable,
        'post_finalize'     => $iterable,
        'intermediates'     => true,
    ];
}
?>


text:
package com.intellij.index;

import com.intellij.psi.stubs.StubSharedIndexExtension;
import com.intellij.psi.stubs.StubUpdatingIndex;
import com.intellij.util.indexing.FileBasedIndexExtension;
import com.intellij.util.indexing.ID;
import com.intellij.util.indexing.provided.OnDiskSharedIndexChunkLocator;
import com.intellij.util.indexing.provided.SharedIndexExtension;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.KeyDescriptor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.nio.file.Path;

public class SharedIndexExtensions {
  private static final String SHARED_INDEX_ENABLED = "shared.index.enabled";

  public static boolean areSharedIndexesEnabled() {
    return System.getProperty(OnDiskSharedIndexChunkLocator.ROOT_PROP) != null || System.getProperty(SHARED_INDEX_ENABLED) != null;
  }

  @SuppressWarnings("unchecked")
  @NotNull
  public static <K, V> SharedIndexExtension<K, V> findExtension(@NotNull FileBasedIndexExtension<K, V> extension) {
    if (extension.getName().equals(StubUpdatingIndex.INDEX_ID)) {
      return (SharedIndexExtension<K, V>)new StubSharedIndexExtension();
    }
    return new SharedIndexExtensionImpl<>(extension);
  }

  private static class SharedIndexExtensionImpl<K, V> implements SharedIndexExtension<K, V> {
    private final FileBasedIndexExtension<K, V> myOriginalExtension;

    SharedIndexExtensionImpl(@NotNull FileBasedIndexExtension<K, V> originalExtension) {
      myOriginalExtension = originalExtension;
    }

    @NotNull
    @Override
    public KeyDescriptor<K> createKeyDescriptor(@NotNull Path indexPath) {
      return myOriginalExtension.getKeyDescriptor();
    }

    @NotNull
    @Override
    public DataExternalizer<V> createValueExternalizer(@NotNull Path indexPath) {
      return myOriginalExtension.getValueExternalizer();
    }
  }
}


text:
  {{ if .Paginator.HasPrev }}
  {{ if eq .Paginator.PageNumber 2 }}
  Newer
  {{ else }}
  Newer
  {{ end }}
  {{ else }}
  Newer
  {{ end }}

  {{ if .Paginator.HasNext }}
  Older
  {{ else }}
  Older
  {{ end }}


text:
from django.contrib.auth.decorators import login_required
from django_ajax.decorators import ajax
@ajax
def my_view(request):
    c = 2 + 3
    return {'result': c}


text:
layout: story
category: short story
issue: 93, July 2021
issue-cover: issue-93-cover.png
issue-buy-link: https://store.firesidefiction.com/products/fireside-magazine-issue-93-july-2021
title: T-E-E-T-H
subtitle:
author: imogen-archer
author-2:
author-3:
editor: lillian-boyd
illustrator:
copyeditor: chelle-parker
selector:
translator:
narrator:
letterer:
word-count: 3048
date: 2021-07-27 01:00:01 -0500
permalink: t-e-e-t-h
audiourl:
teaser:
art:
artcaption:
spanish-language:
spanish-date:
english-url:
spanish-url:
serial-name:
serial-url:
part:
previous-url:
next-url:
contentnote:
generalnote:
published: true
---
Samena couldn't shake the feeling she was forgetting something. Two days ago, Thea had lost her last baby tooth, and Samena could think about little else. Her watch buzzed — she had a half hour, plenty of time to get home and prep the strawberries for Thea's after-school snack. Frowning, she ran the tip of her tongue along her teeth, bumping around the curves of the _U_ and the _O_, poking it through the twin bars of her _H_ until it stung.

She adjusted her mask, and— Damn, did she remind Robert about the laundry soap? Mrs. Waters made her own from her garden, and it was so much nicer than the store brand. Instead of liquid flowers made in a lab, hers smelled real, like petals, leaves. Like the sun.

Today, Mr. Ramos had traded her a jar of honey for a bit of her _HOUSE_ magic; really, she'd just helped him install an unmetered home assistant to track his new apiary. She would sweeten Thea's strawberries with the honey. The glass was smooth under her thumb as she rubbed it absently, going over the list of things she had to do this afternoon. Her boots were a metronome on the sidewalk as she hurried down the street.

"Hellooo!" Her neighbor's shrill cheer startled her into a stutter step. "Any news, Samena?"

Avril didn't wear a mask, just let her teeth show in front of god and everyone: C-A-B-B-A-G-E. It wasn't terrible, but it wasn't auspicious either. It had taken Samena a few conversations over the mailboxes to get the entire thing; Avril's mouth wasn't that large. Plus Samena didn't want to be caught staring. She had manners.

"Nothing yet. Her gums are sore though, so probably not long."

Avril gave her a sympathetic smile. "How does it go in your families? Mine and my ma's, they came in fast, pop-pop-pop, not even three days." Her silly laugh tinkled out, making the space between them feel crowded. "I was sure glad of that when Desmond lost his last baby tooth."

"I remember. You both — you three — are so fortunate. _RENEW_ could go a lot of ways." She talked over her shoulder, desperate to get indoors. She went over her list like a mantra. Put away her outdoor things. Wash berries, hull, slice. Drizzle the honey. Make dinner. Stop worrying. Don't think about teeth. Make Thea feel safe. Keep a welcome home.

"I know, Donny bought him an engineering kit not an hour after his last tooth came in. My ma gave him a yoga block and biographies of great gurus, I swear…." Avril was looking at her mail, chattering away, and Samena used her distraction to escape.

If Thea was like her, her teeth should come in any day now. Samena was so nervous, she could barely eat. Making lists helped, but she could feel anxiety vibrate her bones.

Her own teeth were fine: H-O-U-S-E. Maybe a little boring but sweetly curved in the middle, sharp on the ends.  She didn't really need to keep them covered in public. It was a plain word, nothing to be ashamed of, but she wore her mask anyways, out of propriety.

----

Coat in the closet, boots on the rug. She dropped her scarf on the table in the hall, started towards the kitchen, then went back, folded it neatly. Their home was lovely.

----

As a child, she'd hated being indoors, acting like a proper young lady. When _HOUSE_ had come in, Samena had been crushed. She had spent her childhood playing archeologist, explorer, astronaut, never expecting her adulthood would be anything less thrilling. Instead, she got a lifetime of safe hearths, putting everything in its proper place. Her parents had always encouraged her to be open to possibility, but she saw their poorly hidden disappointment.

Her mother had started her early on proper tooth maintenance; you couldn't be too careful with the letters that had thin strokes. Everyone knew about the Jeffries over on Seventh, all those kids, so many *T*s and *H*s, *Q*s that became *O*s that became hanging half-moons and then just nonsense. They were too prideful or too foolish to wear masks even before their letters started chipping, and now no decent person would talk to any of them. At least they didn't switch to dentures full-time. Revolting.

----

Damn, did they have a new pack of floss in the cabinet? All those seeds.

----

After Thea had lost her second incisor, Robert had gotten tired of Samena's fretting. "Whatever Thea's word is, she'll be fine. We have good genes; we raised her properly."

"Your cousin Lisa wasn't okay. She had to get _dentures_. She'll never get a decent job."

"I don't think my uncle was as enlightened as he pretended." Lisa's mouth had sported a slur so vile she couldn't open her lips in public. At least Rob's uncle had known a dental surgeon willing to discreetly fit her dentures. Samena had only heard about it because they had had to postpone their wedding while the whole family was investigated. The American Dental Association always had studies running. They had left several cases of toothbrushes for the family when they had finished the interviews, though.

"Could he really be that xenophobic? Besides, no one knows if parenting or genes actually have any effect on a child's word. And this is her life, Rob, her whole life."

"Look at PINKIE Benson, hon. Great life, ridiculous word."

Samena had snorted in response. PINKIE Benson. He had a very popular variety show on USNews 15, every night at eight. "He's handsome. And a comedian. And a man."

"Still, he overcame what he got. And you know we can't do anything, even if we could afford a scan."

She'd sighed. God, how she'd wished they were rich enough to try diagnostics. The truly wealthy had tried to buy a way out of waiting to see if their offspring would embarrass the family. Dental x-rays, MRIs, nano-mapping of hard tissue, anything their doctors could dream up. Unfortunately for them, all children born after the US borders closed had two small bony plates just above the gums in their upper jaws. X-rays were useless, MRIs showed solid bone, and nanites couldn't get in between the plates. Though it rankled, the fact this was the same for them all, rich and poor, had given Samena a certain amount of grim satisfaction. Even though she would've done the same if she could.

----

The strawberries were small but jewel-red in Thea's favorite bowl, the one with the face of a pensive-looking owl. Samena drizzled the honey over them, a teaspoonful, and then another.

----

She'd met Rob in college. Her parents had wanted her to be educated, _HOUSE_ be damned. She'd abandoned the idea of a major, taking whichever classes interested her most. Disasters, Catastrophes, and Human Behavior. Punk Technology. The Politics of Refusal. Discordant Biology in the Golden Age. Expression of Self Within American Exceptionalism. Robert's advanced accounting class had got out at the same time as her math class (Narrative Mathematics) on Tuesdays and Thursdays. He'd had an on-campus job in the student center, she in the library next door. He'd found that a convenient excuse to start walking with her.

Revealing your tooth word was an intimacy that most ordinary people didn't share lightly. On their fourth date, Robert had been helping her into her coat outside the crowded cloak room at the ballet. In a sudden surge of bodies, his hand had gotten tangled in the loop of her mask. Her mouth had opened in a gasp as she was exposed, and he'd read her. He'd met her eyes, a little shocked and very embarrassed, but she'd also found approval. They'd started off for his apartment, rushing a little more with every block until they were running. Breathless, Robert had pulled his own mask off to reveal S-O-L-I-D. Acceptable. Dependable. Samena had already liked him. She could do much, much worse than _SOLID_. She'd kissed him, and he'd held her tightly along his body. They'd married six months later.

----

She snapped the wall screen on to distract herself. The food segment of _This Afternoon With You!_ had a new host, a woman who looked impossibly young. When she smiled over her absurdly red tomatoes, her teeth read Y-U-M-M-Y, clear as day.

"Oh, come _on_," Samena said to the screen, rolling her eyes.

She had talked to Thea last week about how mutable language was, how many layers of meaning could be found in just one word, but maybe she should tell her again. She didn't have to live under other people's expectations.

She didn't have to be a coward like her mother. Samena sighed.

----

Thea was a compromise. Samena had never wanted children. She'd felt entirely unprepared to shepherd a new life through the world, waiting for the time when she could do nothing to protect her child but only try to mitigate the damage. Dread had seemed a bad place to start parenthood.

Rob hadn't pushed her. Instead, he'd made a prayer of her body. He'd whispered little worships along the curve of her neck, the inside of her forearms, where her belly was the softest, where her thighs were smooth and warm. Bit by bit, he'd built her a place where she could forget the ugliness of the world outside. His confidence had let her believe that maybe trouble wasn't a guarantee, and one night she'd held his face in her hands and looked into his eyes.

"Yes," she'd said. "Yes, let's make a baby."

----

One of the toy magnets fell off the refrigerator as she shut it with her hip. She picked up the plastic broccoli and snapped it back onto the door.

Three years ago, she had had a conversation with Thea. She remembered her daughter's six-year-old body, quickly stretching from chubby toddler to girl but still soft. They had been speculating about her word after she'd lost her first baby tooth. "I think it's gonna be _SPARKLES_, mama."

"_SPARKLES_, huh? What will you do with that?" She'd handed her daughter one of the stuffed animals squished in the small blanket cave with them. "Will you be a champion tooth-brusher?" She had given a big cheesy grin.

"No way! Maybe a dancer, with a fancy costume." Thea had carefully sat her family of floppy bunnies in a half-circle.

"What if it's… _CARROT_? We'd have to plant you in the garden!"

Thea had giggled and Samena had laughed with her, trying to hide the hysteria she'd felt pushing up at the edges of her voice. Her daughter deserved more — a life that was hers because she chose it, not ordained by what was in her mouth.

----

Marisol TRUST on USNews 08 interrupted _This Afternoon With You!_ to read a breaking report that Timothy STAR was not, in fact, a _STAR_, but rather a _STARE_ with a carefully engineered denture on one end. Oh, that was bold. Samena didn't understand how he thought he'd get away with it; someone would always talk if they got paid enough. She counted back — almost four years since the last alteration scandal. Had it really been that long? Jess LADY was the last one she could remember. She'd had the original _Z_ pulled and replaced with a manufactured _D_. The public vitriol at her fraud trial had been shocking.

Samena started preheating the oven and pulled out a pan, letting her thoughts wander. Did people in Japan have kanji? She knew people whose primary languages weren't English, but all their words were still in the Latin alphabet. For the millionth time, she wished they got actual news from outside the US. She turned the television off.

----

When she was a girl, she'd begged her grandmother to tell her about when people had had plain teeth their whole lives. Her grandparents hadn't like to talk about those times, but on her birthday one year, she'd decided to ask.

"Well, they closed the borders about ten years before your mother was born. Do you know what that means?"

Samena had scrunched up her forehead. "No one can come in or out?"

"That's right. No people and no stuff. And that meant a lot of things we got from other countries, we had to make ourselves."

The ADA had hired thousands of investigators and researchers in the weeks after the first letter teeth had come in. First they'd looked at the new US-manufactured toothpaste; hundreds of factories had popped up to keep up with demand, run by people who had only the faintest knowledge of how to make dentifrice. When that didn't seem to be the cause, they'd had state agencies run massive testing on water pipe infrastructure. The Department of Agriculture and the FDA had checked soil and farms and food producers. The CDC had eventually gotten involved. Seventy years of research — three generations of children with words in their mouths — and still not a single explanation.

"Your uncle Rav was the first one in our neighborhood. We heard the reports, of course, it was all over the news, but it's different when it's in your own home. When we saw that little _A_ pop through, golly, everyone came over and put their guess on the wall in the garage. It was fun, then, seeing what would come up. I guess things around us were so bad, it was nice to have a distraction. Teeth words didn't seem like they mattered so much."

The west wall of her grandparents' garage had been covered in hundreds of handwritten words. She'd used to stare at them for hours. No one would tell her what they said or even talk about them. Her uncle Rav had moved away before she was born and had never come back. There were so many things no one told her.

"So why did Uncle Rav go away, then?"

"Oh, sweetheart, things just got a little too complicated for your uncle. It was a different time back then." Her grandmother had looked out the window silently for a long minute, twisting her hands together, and then had turned back to Samena.  "But that's something you don't need to worry about. Your word is a fine one."

Samena had opened her mouth to ask more questions, but her grandmother had shushed her and given her another slice of cake.

----

The drawer under the kitchen towels held all their masks. She had made Thea some already — so small, in bright florals, and some with little unicorns and shooting stars. They hadn't decided yet whether she should wear one. Rob thought it would be a good idea, no matter what she got. Samena wanted to wait and see, and let Thea choose.

----

When she was pregnant, she and Rob had fought about everything. Her body had been even less her own and it had made her glow with fury. The worst fights had been over names. He'd wanted a classic name, something like Sarah or Emily or April. She'd thought those were unforgivably bland. Samena had wanted their daughter to have a name with meaning.

Their constant bickering eventually got so bitter she'd just stopped talking to him altogether. She'd tidied the house in silence. She'd put dinner on the table in silence. She'd watched Robert eat in silence, hating him a little bit as the green of his spinach had been ground to mush behind S-O-L-I-D. Why the hell couldn't he just chew with his damn mouth closed? Everything he did had annoyed her. She'd kept it up for two horrible weeks, until it was time to leave for the hospital.

She'd been ashamed later for being so unkind, especially when she'd remembered how sweet he'd been, cradling her and their daughter, sweaty, tearful.

He'd gently patted her face dry. "Sweetheart, they won't let us leave until we name her."

"I don't want her to have a boring name." Her daughter had given a wide, perfect yawn, arms windmilling gently. "She's wonderful. She's not a Sarah or an Emily. She needs a little flair."

"I surrender! You're right, she's not an Emily." He'd moved aside so the nurse could record her vitals, never taking his hand off her.

It had taken a few days, marveling over her daughter's tiny little fingers and eyebrows and feet, getting a better sense of this brand new person they had made. And then one morning, Samena had just known. She'd named her Thea, after the goddess of light, hoping the tribute to the mother of the sun and moon would act as a talisman for her future. _Thea_. Thea.

----

The berries gleamed under the kitchen lights, and Samena snuck one for herself. The flavor of the fruit was bright, the honey herbaceous and quietly sweet.

She wondered what the Germans carried in their mouths, if this happened there too. They could smile at her a single word for the strange wistful longing she could never escape. Did she doom her child by bringing her into this world? Though maybe teeth like these only happened here, and no one else knew about it. Maybe they all were stuck in these little loops, shoved into them only by the stupid choices they made, unable to find the momentum to break free. Maybe it was just fate. What else could she do but give her daughter her very best and hope that was enough? It didn't feel like enough to Samena.

The silence pressed down on her. She sagged a little against the counter, head bowed.

Then there was a clatter at the front door and a burst of noise as Thea tumbled into the house, shrieking wildly. "Mom! Mom! It started coming out! My tooth started coming out! You gotta see!"

Samena's stomach swooped unpleasantly, and she gripped the counter's edge until her knuckles turned white. No, not yet, she wasn't ready, her daughter was just a little girl. And then she dragged a deep breath in. Her daughter _was_ a little girl, and there was only one thing to be done. So she plastered on a smile, and went out to Thea.


text:
#include "mainwindow.hpp"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}


text:
recurrent-title: 'Wellpoint kiosk'
recurrent-description: 'Stop by for a free health check.'
recurrent-day: Mondays, Thursdays and Fridays
recurrent-times: 1500-close
recurrent-location: chantry-library
recurrent-location-display-name: Chantry Library
recurrent-location-display-url: /branches/chantry-library/
recurrent-category: health
---


text:
using System;
using System.IO;
using System.Collections;
using System.Diagnostics;

namespace OTFontFile
{
    abstract public class OTTable
    {
        /************************
         * constructors
         */

        /// Construct abstract base class tag and buffer
        public OTTable(OTTag tag, MBOBuffer buf)
        {
            m_tag = new OTTag(tag);
            m_bufTable = buf;
        }

        /************************
         * public methods
         */

        /// Calculate checksum for all except for 'head'
        public virtual uint CalcChecksum()
        {
            // NOTE: this method gets overridden by the head table class

            return m_bufTable.CalcChecksum();
        }

        /// Accessor of <c>m_bufTable</c>
        public MBOBuffer GetBuffer()
        {
            return m_bufTable;
        }

        /// Return <c>true</c> iff <c>offset</c> is at the same
        /// <c>m_bufTable.GetFilePos()</c>, and <c>length</c> is equal to
        /// <c>m_bufTable.GetLength()</c>.
        ///
        public bool MatchFileOffsetLength(uint offset, uint length)
        {
            bool bRet = true;

            if (m_bufTable == null)
            {
                bRet = false;
            }
            else
            {
                if (offset != (uint)m_bufTable.GetFilePos())
                {
                    bRet = false;
                }
                if (length != m_bufTable.GetLength())
                {
                    bRet = false;
                }
            }

            return bRet;
        }

        /// Return <c>true</c> iff <c>de</c> is for a
        /// <c>DirectoryEntry</c> for a table equal to this one in
        /// tag, checksum, file offset and length.
        ///
        public bool MatchDirectoryEntry(DirectoryEntry de)
        {
            bool bRet = true;

            if (de.tag != m_tag)
            {
                bRet = false;
            }

            if (de.checkSum != CalcChecksum())
            {
                bRet = false;
            }

            if (!MatchFileOffsetLength(de.offset, de.length))
            {
                bRet = false;
            }

            return bRet;
        }

        /// Return length of <c>m_bufTable</c> or 0, if none.
        public uint GetLength()
        {
            uint nLength = 0;

            if (m_bufTable != null)
            {
                nLength = m_bufTable.GetLength();
            }

            return nLength;
        }

        /// Accessor for <c>m_tag</c>
        public OTTag GetTag()
        {
            return m_tag;
        }

        /************************
         * nested class for
         * holding cached data
         */

        public abstract class DataCache
        {
            public DataCache()
            {
                m_bDirty = false;
            }

            public bool IsDirty()
            {
                return m_bDirty;
            }

            public abstract OTTable GenerateTable();
            protected bool m_bDirty;
        }

        ///
        /// derived classes should override this method to
        /// create their cache on demand
        ///
        public virtual DataCache GetCache()
        {
            return m_cache;
        }

        /************************
         * member data
         */

        public MBOBuffer m_bufTable;
        public OTTag m_tag;
        protected DataCache m_cache;
    }
}


text:
<?php

namespace dhawton\OAuth\SignatureMethods;

class RSA_SHA1 extends SignatureMethodInterface
{
    private $cert = false;

    public function getName()
    {
        return "RSA-SHA1";
    }

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

    /**
     * @param \dhawton\OAuth\Request $request
     *
     * @return string   Return string representation of cert
     */
    private function fetchPrivateCert(\dhawton\OAuth\Request &$request)
    {
        return $this->cert;
    }

    public function buildSignature(\dhawton\OAuth\Request $request, \dhawton\OAuth\Consumer $consumer, \dhawton\OAuth\Token $token)
    {
        $baseString = $request->getSignatureBaseString();
        $request->baseString = $baseString;

        $cert = $this->fetchPrivateCert($request);
        $privatekeyid = openssl_get_privatekey($cert);
        $ok = openssl_sign($baseString, $signature, $privatekeyid);
        openssl_free_key($privatekeyid);

        return base64_encode($signature);
    }
}


text:
from memberinfo.cn_jp import cn2jp

from memberinfo.models import MemberInfo

for m in MemberInfo.objects.exclude(officialinfo__mid__isnull=False):
    l = []
    for c in m.name:
        l.append(cn2jp(c))
    m.name = ''.join(l)
    m.save()