{-# LANGUAGE NamedFieldPuns  #-}
{-# LANGUAGE RankNTypes      #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE RecursiveDo     #-}
module Distribution.Server.Features.Core (
    CoreFeature(..),
    CoreResource(..),
    initCoreFeature,

    -- * Change events
    PackageUpdate(..),
    PackageChange(..),
    isPackageChangeAny,
    isPackageAdd,
    isPackageDelete,
    isPackageIndexChange,

    -- * Misc other utils
    packageExists,
    packageIdExists,
  ) where

-- stdlib
import qualified Codec.Compression.GZip                             as GZip
import           Data.Aeson                                         (Value (..))
import           Data.ByteString.Lazy                               (ByteString)
import qualified Data.Foldable                                      as Foldable
import qualified Data.HashMap.Strict                                as HashMap
import qualified Data.Text                                          as Text
import           Data.Time.Clock                                    (UTCTime, getCurrentTime)
import           Data.Time.Format                                   (formatTime)
import           Data.Time.Locale.Compat                            (defaultTimeLocale)
import qualified Data.Vector                                        as Vec

-- hackage
import           Distribution.Server.Prelude

import           Distribution.Server.Features.Core.Backup
import           Distribution.Server.Features.Core.State
import           Distribution.Server.Features.Security.Migration
import           Distribution.Server.Features.Users
import           Distribution.Server.Framework
import qualified Distribution.Server.Framework.BlobStorage          as BlobStorage
import qualified Distribution.Server.Framework.ResponseContentTypes as Resource
import           Distribution.Server.Packages.Index                 (TarIndexEntry (..))
import qualified Distribution.Server.Packages.Index                 as Packages.Index
import           Distribution.Server.Packages.PackageIndex          (PackageIndex)
import qualified Distribution.Server.Packages.PackageIndex          as PackageIndex
import           Distribution.Server.Packages.Types
import           Distribution.Server.Users.Types                    (UserId,
                                                                     userName)
import           Distribution.Server.Users.Users                    (lookupUserId,
                                                                     userIdToName)

-- Cabal
import           Distribution.Package
import           Distribution.Text                                  (display)
import           Distribution.Version                               (nullVersion)

-- | The core feature, responsible for the main package index and all access
-- and modifications of it.
--
-- All packages must have a Cabal file, uploader, and upload time, and may have
-- a source tarball.
data CoreFeature = CoreFeature {
    -- | The core `HackageFeature`.
    coreFeatureInterface :: HackageFeature,

    -- | Core package resources and combinators.
    coreResource :: CoreResource,

    -- Queries
    -- | Retrieves the entire main package index.
    queryGetPackageIndex :: forall m. MonadIO m => m (PackageIndex PkgInfo),

    -- | Retrieve the raw tarball info
    queryGetIndexTarballInfo :: forall m. MonadIO m => m IndexTarballInfo,

    -- Update transactions
    -- | Adds a version of a package which did not previously exist in the
    -- index. This requires a Cabal file and context, and optionally a
    -- reference to a tarball blob, and does not do any consistency checking
    -- of these.
    --
    -- If a package was able to be newly added, runs a `PackageChangeAdd` hook
    -- when done and returns True.
    updateAddPackage         :: forall m. MonadIO m => PackageId ->
                                CabalFileText -> UploadInfo ->
                                Maybe PkgTarball -> m Bool,
    -- | Deletes a version of an existing package, deleting the package if it
    -- was the last version.
    --
    -- If a package was found and deleted, runs a `PackageChangeDelete` hook
    -- when done and returns True.
    updateDeletePackage      :: forall m. MonadIO m => PackageId -> m Bool,

    -- | Adds a new Cabal file for this package version, creating it if
    -- necessary. Previous Cabal files are kept around.
    --
    -- Runs either a `PackageChangeAdd` or `PackageChangeInfo` hook, depending
    -- on whether a package with the given version already existed.
    updateAddPackageRevision :: forall m. MonadIO m => PackageId ->
                                CabalFileText -> UploadInfo -> m (),
    -- | Sets the source tarball for an existing package version. References to
    -- previous tarballs, if any, are kept around.
    --
    -- If this package was found, runs a `PackageChangeInfo` hook when done and
    -- returns True.
    updateAddPackageTarball  :: forall m. MonadIO m => PackageId ->
                                PkgTarball -> UploadInfo -> m Bool,
    -- | Sets the uploader of an existing package version.
    --
    -- If this package was found, runs a `PackageChangeInfo` hook when done and
    -- returns True.
    updateSetPackageUploader :: forall m. MonadIO m => PackageId -> UserId -> m Bool,
    -- | Sets the upload time of an existing package version.
    --
    -- If this package was found, runs a `PackageChangeInfo` hook when done and
    -- returns True.
    updateSetPackageUploadTime :: forall m. MonadIO m => PackageId -> UTCTime -> m Bool,

    -- | Set an entry in the 00-index.tar file.
    --
    -- The 00-index.tar file contains all the package entries, but it is an
    -- extensible format and we can add more stuff. E.g. version preferences
    -- or crypto signatures. This requires a file name, file contents, and
    -- modification time for the tar entry.
    --
    -- This runs a `PackageChangeIndexExtra` hook when done.
    updateArchiveIndexEntry :: forall m. MonadIO m => FilePath -> ByteString -> UTCTime -> m (),

    -- | Notification of package or index changes.
    packageChangeHook :: Hook PackageChange (),

    -- | Additional entries to be added before the index is updated/prodded
    --
    -- NOTE: Unlike a call to 'updateArchiveIndexEntry', this does NOT call
    -- any additional hooks.
    preIndexUpdateHook :: Hook PackageChange [TarIndexEntry],

    -- | Notification of tarball downloads.
    packageDownloadHook :: Hook PackageId (),

    -- | Notification that the index was updated
    -- The hook will be called when the index cache was actually updated.
    indexUpdatedHook :: Hook IndexTarballInfo ()
}

instance IsHackageFeature CoreFeature where
    getFeatureInterface = coreFeatureInterface

-- | How was a package updated?
data PackageUpdate
    -- | Cabal file was updated
    = PackageUpdatedCabalFile
    -- | A new tarball was uploaded
    | PackageUpdatedTarball
    -- | Package uploader was modified
    | PackageUpdatedUploader
    -- | Package upload time was modified
    | PackageUpdatedUploadTime

-- | This is designed so that you can pattern match on just the kinds of
-- events you are interested in.
data PackageChange
    -- | A package was newly added with this `PkgInfo`.
    = PackageChangeAdd    PkgInfo
    -- | A package was deleted, and this `PkgInfo` is no longer accessible in
    -- the package index.
    | PackageChangeDelete PkgInfo
    -- | A package was updated from the first `PkgInfo` to the second.
    | PackageChangeInfo PackageUpdate PkgInfo PkgInfo
    -- | A file has changed in the package index tar not covered by any of the
    -- other change types.
    | PackageChangeIndexExtra String ByteString UTCTime

-- | A predicate to use with `packageChangeHook` and `registerHookJust` for
-- keeping other features synchronized with the main package index.
--
-- This indicates an update for a given `PackageId`, and the new `PkgInfo` if
-- a new one has been added (`Nothing` in the case of deletion).
isPackageChangeAny :: PackageChange -> Maybe (PackageId, Maybe PkgInfo)
isPackageChangeAny (PackageChangeAdd        pkginfo) = Just (packageId pkginfo, Just pkginfo)
isPackageChangeAny (PackageChangeDelete     pkginfo) = Just (packageId pkginfo, Nothing)
isPackageChangeAny (PackageChangeInfo   _ _ pkginfo) = Just (packageId pkginfo, Just pkginfo)
isPackageChangeAny  PackageChangeIndexExtra {}       = Nothing

-- | A predicate to use with `packageChangeHook` and `registerHookJust` for
-- newly added packages.
isPackageAdd :: PackageChange -> Maybe PkgInfo
isPackageAdd (PackageChangeAdd pkginfo) = Just pkginfo
isPackageAdd _                          = Nothing

-- | A predicate to use with `packageChangeHook` and `registerHookJust` for
-- deleted packages.
isPackageDelete :: PackageChange -> Maybe PkgInfo
isPackageDelete (PackageChangeDelete pkginfo) = Just pkginfo
isPackageDelete _                             = Nothing

-- | A predicate to use with `packageChangeHook` and `registerHookJust` for
-- any kind of change to packages or extras.
isPackageIndexChange ::  PackageChange -> Maybe PackageChange
isPackageIndexChange = Just

{-
-- Other examples we may want later...
isPackageAddVersion                :: Maybe PackageId,
isPackageDeleteVersion             :: Maybe PackageId,
isPackageChangeCabalFile           :: Maybe (PackageId, CabalFileText),
isPackageChangeCabalFileUploadInfo :: Maybe (PackageId, UploadInfo),
isPackageChangeTarball             :: Maybe (PackageId, PkgTarball),
isPackageIndexExtraChange          :: Maybe (String, ByteString, UTCTime)
-}

data CoreResource = CoreResource {
    -- | The collection all packages.
    corePackagesPage    :: Resource,
    -- | An individual package.
    corePackagePage     :: Resource,
    -- | A Cabal file for a package version.
    coreCabalFile       :: Resource,
    -- | A tarball for a package version.
    corePackageTarball  :: Resource,

    -- Rendering resources.
    -- | URI for `corePackagesPage`, given a format (blank for none).
    indexPackageUri    :: String -> String,
    -- | URI for `corePackagePage`, given a format and `PackageId`.
    corePackageIdUri   :: String -> PackageId -> String,
    -- | URI for `corePackagePage`, given a format and `PackageName`.
    corePackageNameUri :: String -> PackageName -> String,
    -- | URI for `coreCabalFile`, given a PackageId.
    coreCabalUri       :: PackageId -> String,
    -- | URI for `corePackageTarball`, given a PackageId.
    coreTarballUri     :: PackageId -> String,

    -- | Find a PackageId or PackageName inside a path.
    packageInPath :: forall m a. (MonadPlus m, FromReqURI a) => DynamicPath -> m a,

    -- | Find a tarball's PackageId from inside a path, doing some checking
    -- for consistency between the package and tarball.
    --
    -- TODO: This is a rather ad-hoc function. Do we really need it?
    packageTarballInPath :: forall m. MonadPlus m => DynamicPath -> m PackageId,

    -- | Check that a particular version of a package exists (guard fails if
    -- version is empty)
    guardValidPackageId   :: PackageId   -> ServerPartE (),
    -- | Check that a package exists.
    guardValidPackageName :: PackageName -> ServerPartE (),

    -- | Find a package in the package DB, failing if not found. This uses the
    -- highest version number of a package.
    --
    -- In the presence of deprecation or preferred versions,
    -- `withPackagePreferred` should generally be used instead for user-facing
    -- version resolution.
    lookupPackageName :: PackageName -> ServerPartE [PkgInfo],
    -- | Find a package version in the package DB, failing if not found. Behaves
    -- like `lookupPackageName` if the version is empty.
    lookupPackageId   :: PackageId   -> ServerPartE PkgInfo
}

initCoreFeature :: ServerEnv -> IO (UserFeature -> IO CoreFeature)
initCoreFeature env@ServerEnv{serverStateDir, serverCacheDelay,
                              serverVerbosity = verbosity} = do
    -- Canonical state
    packagesState <- packagesStateComponent verbosity False serverStateDir

    -- Hooks
    packageChangeHook   <- newHook
    preIndexUpdateHook  <- newHook
    packageDownloadHook <- newHook

    return $ \users -> do

      -- One-off complex migration
      --
      -- As part of the support for TUF we made two changes to the state:
      --
      -- * We made the index append-only, and added a package update log
      --   to support this.
      -- * We changed the PkgTarball data structure to contain BlobInfo rather
      --   rather than BlobId; that is, we additionally record the length and
      --   SHA256 hash for all blobs.
      --
      -- Additionally, we now need `package.json` files for all versions of all
      -- packages. For new packages we add these when the package is uploaded,
      -- but for previously uploaded packages we need to add them.
      --
      -- Migrating the package tarball info and introducing metadata for
      -- pre-existing packages requires a full search through the package DB.
      -- Fortunately, since all these changes were introduced at the same time,
      -- we can use the check for the existence of the update log to see if we
      -- need any other kind of migration.

      migrateUpdateLog <- (isLeft . packageUpdateLog) <$>
                             queryState packagesState GetPackagesState
      when migrateUpdateLog $ do
        -- Migrate PackagesState (introduce package update log)
        logTiming verbosity "migrating package update log" $ do
          userdb <- queryGetUserDb users
          updateState packagesState (MigrateAddUpdateLog userdb)

        -- Migrate PkgTarball
        logTiming verbosity "migrating PkgTarball" $
          migratePkgTarball_v1_to_v2 env packagesState

        -- Create a checkpoint
        --
        -- Creating a checkpoint after the migration is important for two
        -- reasons: one, the migration is expensive and we don't want to  repeat
        -- it. But there is a second, more important reason. Until we have
        -- migrated we do not have a package log. This means that if we have a
        -- DB with no checkpoints at all but some old style (pre introduction of
        -- the package log) transactions as well as some new style transactions
        -- (post introduction of the package log), those new transactions will
        -- not be updating the package log. Since migration does not happen
        -- until _after_ replaying all those transactions, this means we would
        -- reconstruct the package log rather than use the package log as it was
        -- constructed in the first place, and we might potentially lose
        -- information.
        createCheckpoint (stateHandle packagesState)

      rec let (feature, getIndexTarball)
                = coreFeature env users
                              packagesState indexTar
                              packageChangeHook
                              preIndexUpdateHook
                              packageDownloadHook

          -- Caches
          -- The index.tar.gz file
          indexTar <- newAsyncCacheNF getIndexTarball
                        defaultAsyncCachePolicy {
                          asyncCacheName = "index tarball",
                          asyncCacheUpdateDelay  = serverCacheDelay,
                          asyncCacheSyncInit     = False,
                          asyncCacheLogVerbosity = verbosity
                        }

      registerHookJust packageChangeHook isPackageIndexChange $ \packageChange -> do
        -- NOTE: Adding a package adds the additional entries _atomically_ with a package
        -- This makes sure we never get a successful upload with no attendant package.json file.
        -- In all other cases, entries are allowed to be added nonatomically with the main index change.
        -- We may wish to refactor in the future, but as of this comment, the preIndexUpdateHook is effectively a
        -- no-op in all other significant cases.
        case packageChange of
             PackageChangeAdd _ -> return ()
             _ -> do
                     additionalEntries <- concat <$> runHook preIndexUpdateHook packageChange
                     forM_ additionalEntries $ updateState packagesState . AddOtherIndexEntry
        prodAsyncCache indexTar "package change"

      return feature

packagesStateComponent :: Verbosity -> Bool -> FilePath -> IO (StateComponent AcidState PackagesState)
packagesStateComponent verbosity freshDB stateDir = do
  let stateFile = stateDir </> "db" </> "PackagesState"
  st <- logTiming verbosity "Loaded PackagesState" $
          openLocalStateFrom stateFile (initialPackagesState freshDB)
  return StateComponent {
       stateDesc    = "Main package database"
     , stateHandle  = st
     , getState     = query st GetPackagesState
     , putState     = update st . ReplacePackagesState
     , backupState  = \_ -> indexToAllVersions
     , restoreState = packagesBackup
     , resetState   = packagesStateComponent verbosity True
     }

coreFeature :: ServerEnv
            -> UserFeature
            -> StateComponent AcidState PackagesState
            -> AsyncCache IndexTarballInfo
            -> Hook PackageChange ()
            -> Hook PackageChange [TarIndexEntry]
            -> Hook PackageId ()
            -> ( CoreFeature
               , IO IndexTarballInfo )

coreFeature ServerEnv{serverBlobStore = store} UserFeature{..}
            packagesState cacheIndexTarball
            packageChangeHook
            preIndexUpdateHook
            packageDownloadHook
  = (CoreFeature{..}, getIndexTarball)
  where
    coreFeatureInterface = (emptyHackageFeature "core") {
        featureDesc = "Core functionality"
      , featureResources = [
            coreLegacyIndexTarballTarGz
          , coreIncremIndexTarballTarGz
          , coreIncremIndexTarballTar
          , corePackagesPage
          , corePackagePage
          , corePackageRedirect
          , corePackageTarball
          , coreCabalFile
          , coreCabalFileRevs
          , coreCabalFileRev
          , coreUserDeauth
          , coreAdminDeauth
          , corePackUserDeauth
          ]
      , featureState    = [abstractAcidStateComponent packagesState]
      , featureCaches   = [
            CacheComponent {
              cacheDesc       = "main package index tarball",
              getCacheMemSize = memSize <$> readAsyncCache cacheIndexTarball
            }
          ]
      , featurePostInit = syncAsyncCache cacheIndexTarball
      }

    -- the rudimentary HTML resources are for when we don't want an additional HTML feature
    coreResource = CoreResource {..}
    coreLegacyIndexTarballTarGz = (resourceAt "/packages/index.tar.gz") {
        resourceDesc = [(GET, "tarball of package descriptions (legacy format, not incremental)")]
      , resourceGet  = [("tarball", serveLegacyPackagesIndexTarGz)]
      }
    coreIncremIndexTarballTarGz = (resourceAt "/01-index.tar.gz") {
        resourceDesc = [(GET, "tarball of package descriptions (incremental, compressed)")]
      , resourceGet  = [("tarball", serveIncremPackagesIndexTarGz)]
      }
    coreIncremIndexTarballTar = (resourceAt "/01-index.tar") {
        resourceDesc = [(GET, "tarball of package descriptions (incremental, uncompressed)")]
      , resourceGet  = [("tarball", serveIncremPackagesIndexTar)]
      }
    corePackagesPage = (resourceAt "/packages/.:format") {
        resourceDesc = [(GET, "List of all packages")]
      , resourceGet  = [("json", servePackageList)]
      }
    corePackagePage = resourceAt "/package/:package.:format"
    corePackageRedirect = (resourceAt "/package/") {
        resourceDesc = [(GET,  "Redirect to /packages/")]
      , resourceGet  = [("", \_ -> seeOther "/packages/" $ toResponse ())]
      }
    corePackageTarball = (resourceAt "/package/:package/:tarball.tar.gz") {
        resourceDesc = [(GET, "Get package tarball")]
      , resourceGet  = [("tarball", servePackageTarball)]
      }
    coreCabalFile = (resourceAt "/package/:package/:cabal.cabal") {
        resourceDesc = [(GET, "Get package .cabal file")]
      , resourceGet  = [("cabal", serveCabalFile)]
      }
    coreCabalFileRevs = (resourceAt "/package/:package/revisions/.:format") {
        resourceDesc = [(GET, "List all package .cabal file revisions")]
      , resourceGet  = [("json", serveCabalFileRevisionsList)]
      }
    coreCabalFileRev = (resourceAt "/package/:package/revision/:revision.:format") {
        resourceDesc = [(GET, "Get package .cabal file revision")]
      , resourceGet  = [("cabal", serveCabalFileRevision)]
      }

    coreUserDeauth = (resourceAt "/packages/deauth") {
        resourceDesc = [(GET,  "Deauth Package user")]
      , resourceGet  = [("", deauth)]
      }
    coreAdminDeauth = (resourceAt "/admin/deauth") {
        resourceDesc = [(GET,  "Deauth Admin")]
      , resourceGet  = [("", deauth)]
      }
    corePackUserDeauth = (resourceAt "/user/:user/deauth") {
        resourceDesc = [(GET,  "Deauth User")]
      , resourceGet  = [("", deauth)]
      }
    indexPackageUri = \format ->
      renderResource corePackagesPage [format]
    corePackageIdUri  = \format pkgid ->
      renderResource corePackagePage [display pkgid, format]
    corePackageNameUri = \format pkgname ->
      renderResource corePackagePage [display pkgname, format]
    coreCabalUri    = \pkgid ->
      renderResource coreCabalFile [display pkgid, display (packageName pkgid)]
    coreTarballUri  = \pkgid ->
      renderResource corePackageTarball [display pkgid, display pkgid]

    packageInPath dpath = maybe mzero return (lookup "package" dpath >>= fromReqURI)

    packageTarballInPath dpath = do
      PackageIdentifier name version <- packageInPath dpath
      case lookup "tarball" dpath >>= fromReqURI of
        Nothing -> mzero
        Just pkgid@(PackageIdentifier name' version') -> do
          -- rules:
          -- * the package name and tarball name must be the same
          -- * the tarball must specify a version
          -- * the package must either have no version or the same version as the tarball
          guard $ name == name' && version' /= nullVersion && (version == version' || version == nullVersion)
          return pkgid

    guardValidPackageId pkgid = do
      guard (pkgVersion pkgid /= nullVersion)
      void $ lookupPackageId pkgid

    guardValidPackageName pkgname =
      void $ lookupPackageName pkgname

    -- Queries
    --
    queryGetPackageIndex :: MonadIO m => m (PackageIndex PkgInfo)
    queryGetPackageIndex = return . packageIndex =<< queryState packagesState GetPackagesState

    queryGetIndexTarballInfo :: MonadIO m => m IndexTarballInfo
    queryGetIndexTarballInfo = readAsyncCache cacheIndexTarball

    -- Hooks
    indexUpdatedHook :: Hook IndexTarballInfo ()
    indexUpdatedHook = asyncCacheUpdatedHook cacheIndexTarball

    -- Update transactions
    --
    updateAddPackage :: MonadIO m => PackageId
                     -> CabalFileText -> UploadInfo
                     -> Maybe PkgTarball -> m Bool
    updateAddPackage pkgid cabalFile uploadinfo@(_, uid) mtarball = logTiming maxBound ("updateAddPackage " ++ display pkgid) $ do
      usersdb <- queryGetUserDb
      let Just userInfo = lookupUserId uid usersdb

      let pkginfo = mkPackageInfo pkgid cabalFile uploadinfo mtarball
      additionalEntries <- concat `liftM` runHook preIndexUpdateHook  (PackageChangeAdd pkginfo)

      successFlag <- updateState packagesState $
        AddPackage3
          pkginfo
          uploadinfo
          (userName userInfo)
          additionalEntries

      loginfo maxBound ("updateState(AddPackage3," ++ display pkgid ++ ") -> " ++ show successFlag)
      if successFlag
        then runHook_ packageChangeHook (PackageChangeAdd pkginfo)
        else return ()
      return successFlag

    updateDeletePackage :: MonadIO m => PackageId -> m Bool
    updateDeletePackage pkgid = logTiming maxBound ("updateDeletePackage " ++ display pkgid) $ do
      mpkginfo <- updateState packagesState (DeletePackage pkgid)
      case mpkginfo of
        Nothing -> return False
        Just pkginfo -> do
          runHook_ packageChangeHook (PackageChangeDelete pkginfo)
          return True

    updateAddPackageRevision :: MonadIO m => PackageId -> CabalFileText -> UploadInfo -> m ()
    updateAddPackageRevision pkgid cabalfile uploadinfo@(_, uid) = logTiming maxBound ("updateAddPackageRevision " ++ display pkgid) $ do
      usersdb <- queryGetUserDb
      let Just userInfo = lookupUserId uid usersdb
      (moldpkginfo, newpkginfo) <- updateState packagesState $
        AddPackageRevision2
          pkgid
          cabalfile
          uploadinfo
          (userName userInfo)
      loginfo maxBound ("updateState(AddPackageRevision2," ++ display pkgid ++ ") -> " ++ maybe "Nothing" (const "Just _") moldpkginfo)
      case moldpkginfo of
        Nothing ->
          runHook_ packageChangeHook  (PackageChangeAdd newpkginfo)
        Just oldpkginfo ->
          runHook_ packageChangeHook  (PackageChangeInfo PackageUpdatedCabalFile oldpkginfo newpkginfo)

    updateAddPackageTarball :: MonadIO m => PackageId -> PkgTarball -> UploadInfo -> m Bool
    updateAddPackageTarball pkgid tarball uploadinfo = logTiming maxBound ("updateAddPackageTarball " ++ display pkgid) $ do
      mpkginfo <- updateState packagesState (AddPackageTarball pkgid tarball uploadinfo)

      case mpkginfo of
        Nothing -> return False
        Just (oldpkginfo, newpkginfo) -> do
          runHook_ packageChangeHook  (PackageChangeInfo PackageUpdatedTarball oldpkginfo newpkginfo)
          return True

    updateSetPackageUploader pkgid userid = do
      mpkginfo <- updateState packagesState (SetPackageUploader pkgid userid)
      case mpkginfo of
        Nothing -> return False
        Just (oldpkginfo, newpkginfo) -> do
          runHook_ packageChangeHook  (PackageChangeInfo PackageUpdatedUploader oldpkginfo newpkginfo)
          return True

    updateSetPackageUploadTime pkgid time = do
      mpkginfo <- updateState packagesState (SetPackageUploadTime pkgid time)
      case mpkginfo of
        Nothing -> return False
        Just (oldpkginfo, newpkginfo) -> do
          runHook_ packageChangeHook  (PackageChangeInfo PackageUpdatedUploadTime oldpkginfo newpkginfo)
          return True

    updateArchiveIndexEntry :: MonadIO m => FilePath -> ByteString -> UTCTime -> m ()
    updateArchiveIndexEntry entryName entryData entryTime = logTiming maxBound ("updateArchiveIndexEntry " ++ show entryName) $ do
      updateState packagesState $
        AddOtherIndexEntry $ ExtraEntry entryName entryData entryTime
      runHook_ packageChangeHook (PackageChangeIndexExtra entryName entryData entryTime)

    -- Cache updates
    --
    getIndexTarball :: IO IndexTarballInfo
    getIndexTarball = do
      users <- queryGetUserDb  -- note, changes here don't automatically propagate
      time  <- getCurrentTime
      PackagesState index (Right updateSeq) <- queryState packagesState GetPackagesState
      let updateLog     = Foldable.toList updateSeq
          legacyTarball = Packages.Index.writeLegacy
                            users
                            (Packages.Index.legacyExtras updateLog)
                            index
          incremTarball = Packages.Index.writeIncremental
                            index
                            updateLog
          -- We use the standard compression for the legacy tarball so that the
          -- legacy tarball is identical to what we served before the intro of
          -- the incremental tarball. For the incremental tarball however we
          -- use maximum compression; this is more important here because the
          -- ordering of the incremental tarball is less compression friendly.
          legacyTarballGz = GZip.compress
                              legacyTarball
          incremTarballGz = GZip.compressWith
                              GZip.defaultCompressParams {
                                  GZip.compressLevel = GZip.bestCompression
                                }
                              incremTarball
          -- lazy construction, since it's forced by the async cache
          resourceInfo = IndexTarballInfo {
              indexTarballLegacyGz = mkTarballCompressed   time legacyTarballGz
            , indexTarballIncremUn = mkTarballUncompressed time incremTarball
            , indexTarballIncremGz = mkTarballCompressed   time incremTarballGz
            }
      return resourceInfo

    ------------------------------------------------------------------------------
    packageError :: [MessageSpan] -> ServerPartE a
    packageError = errNotFound "Package not found"

    lookupPackageName :: PackageName -> ServerPartE [PkgInfo]
    lookupPackageName pkgname = do
      pkgsIndex <- queryGetPackageIndex
      case PackageIndex.lookupPackageName pkgsIndex pkgname of
        []   -> packageError [MText "No such package in package index"]
        pkgs -> return pkgs

    lookupPackageId :: PackageId -> ServerPartE PkgInfo
    lookupPackageId (PackageIdentifier name v) | nullVersion == v = do
      pkgs <- lookupPackageName name
      -- pkgs is sorted by version number and non-empty
      return (last pkgs)
    lookupPackageId pkgid = do
      pkgsIndex <- queryGetPackageIndex
      case PackageIndex.lookupPackageId pkgsIndex pkgid of
        Just pkg -> return pkg
        _ -> packageError [MText $ "No such package version for " ++ display (packageName pkgid)]

    ------------------------------------------------------------------------

    serveLegacyPackagesIndexTarGz :: DynamicPath -> ServerPartE Response
    serveLegacyPackagesIndexTarGz _ = do
      tarball <- indexTarballLegacyGz <$> readAsyncCache cacheIndexTarball
      let tarballmd5 = show $ tarGzHashMD5 tarball
      cacheControl [Public, NoTransform, maxAgeMinutes 5] (ETag tarballmd5)
      enableRange
      return $ toResponse tarball

    serveIncremPackagesIndexTarGz :: DynamicPath -> ServerPartE Response
    serveIncremPackagesIndexTarGz _ = do
      tarball <- indexTarballIncremGz <$> readAsyncCache cacheIndexTarball
      let tarballmd5 = show $ tarGzHashMD5 tarball
      cacheControl [Public, NoTransform, maxAgeMinutes 5] (ETag tarballmd5)
      enableRange
      return $ toResponse tarball

    serveIncremPackagesIndexTar :: DynamicPath -> ServerPartE Response
    serveIncremPackagesIndexTar _ = do
      tarball <- indexTarballIncremUn <$> readAsyncCache cacheIndexTarball
      let tarballmd5 = show $ tarHashMD5 tarball
      cacheControl [Public, NoTransform, maxAgeMinutes 5] (ETag tarballmd5)
      enableRange
      return $ toResponse tarball

    -- TODO: should we include more information here? description and
    -- category for instance (but they are not readily available as long
    -- as we don't keep the parsed cabal files in memory)
    servePackageList :: DynamicPath -> ServerPartE Response
    servePackageList _ = do
      pkgIndex <- queryGetPackageIndex
      let pkgs = PackageIndex.allPackagesByName pkgIndex
          list = [display . pkgName . pkgInfoId $ pkg | pkg <- map head pkgs]
      -- We construct the JSON manually so that we control what it looks like;
      -- in particular, we use objects for the packages so that we can add
      -- additional fields later without (hopefully) breaking clients
      let json = flip map list $ \str ->
            Object . HashMap.fromList $ [
                (Text.pack "packageName", String (Text.pack str))
              ]
      return . toResponse $ Array (Vec.fromList json)

    -- result: tarball or not-found error
    servePackageTarball :: DynamicPath -> ServerPartE Response
    servePackageTarball dpath = do
      pkgid <- packageTarballInPath dpath
      guard (pkgVersion pkgid /= nullVersion)
      pkg <- lookupPackageId pkgid
      case pkgLatestTarball pkg of
        Nothing -> errNotFound "Tarball not found"
                     [MText "No tarball exists for this package version."]
        Just (tarball, (uploadtime, _uid), _revNo) -> do
          let blobId = blobInfoId $ pkgTarballGz tarball
          cacheControl [Public, NoTransform, maxAgeDays 30]
                       (BlobStorage.blobETag blobId)
          file <- liftIO $ BlobStorage.fetch store blobId
          runHook_ packageDownloadHook pkgid
          return $ toResponse $ Resource.PackageTarball file blobId uploadtime

    -- result: cabal file or not-found error
    serveCabalFile :: DynamicPath -> ServerPartE Response
    serveCabalFile dpath = do
      pkginfo <- packageInPath dpath >>= lookupPackageId
      -- check that the cabal name matches the package
      guard (lookup "cabal" dpath == Just (display $ packageName pkginfo))
      let (fileRev, (utime, _uid)) = pkgLatestRevision pkginfo
          cabalfile = Resource.CabalFile (cabalFileByteString fileRev) utime
      return $ toResponse cabalfile

    serveCabalFileRevisionsList :: DynamicPath -> ServerPartE Response
    serveCabalFileRevisionsList dpath = do
      pkginfo <- packageInPath dpath >>= lookupPackageId
      users   <- queryGetUserDb
      let revisions = pkgMetadataRevisions pkginfo
          revisionToObj rev (_, (utime, uid)) =
            let uname = userIdToName users uid in
            Object $ HashMap.fromList
              [ (Text.pack "number", Number (fromIntegral rev))
              , (Text.pack "user", String (Text.pack (display uname)))
              , (Text.pack "time", String (Text.pack (formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%EZ" utime)))
              ]
          revisionsJson = Array $ Vec.imap revisionToObj revisions
      return (toResponse revisionsJson)

    serveCabalFileRevision :: DynamicPath -> ServerPartE Response
    serveCabalFileRevision dpath = do
      pkginfo <- packageInPath dpath >>= lookupPackageId
      let mrev      = lookup "revision" dpath >>= fromReqURI
          revisions = pkgMetadataRevisions pkginfo
      case mrev >>= \rev -> revisions Vec.!? rev of
        Just (fileRev, (utime, _uid)) -> return $ toResponse cabalfile
          where
            cabalfile = Resource.CabalFile (cabalFileByteString fileRev) utime
        Nothing -> errNotFound "Package revision not found"
                     [MText "Cannot parse revision, or revision out of range."]

    deauth :: DynamicPath -> ServerPartE Response
    deauth _ = do
      return $ (toResponse ("<script>window.location='/'</script>"::String)) {
          rsCode = 401
        , rsHeaders   = mkHeaders ([("Content-Type",  "text/html")])
      }

packageExists, packageIdExists :: (Package pkg, Package pkg') => PackageIndex pkg -> pkg' -> Bool
-- | Whether a package exists in the given package index.
packageExists   pkgs pkg = not . null $ PackageIndex.lookupPackageName pkgs (packageName pkg)
-- | Whether a particular package version exists in the given package index.
packageIdExists pkgs pkg = maybe False (const True) $ PackageIndex.lookupPackageId pkgs (packageId pkg)

{'repo_name': 'haskell/hackage-server', 'stars': '285', 'repo_language': 'Haskell', 'file_name': 'hackage.css', 'mime_type': 'text/plain', 'hash': 9013994836316267752, 'source_dataset': 'data'}


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.fridayapp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

</manifest>

{'repo_name': 'AmitM30/react-native-typescript-boilerplate', 'stars': '125', 'repo_language': 'TypeScript', 'file_name': 'home.tsx', 'mime_type': 'text/x-java', 'hash': 1005257415258166067, 'source_dataset': 'data'}


package main

import (
	"fmt"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestExtractFromTag(t *testing.T) {
	cases := []struct {
		Name            string
		Tag             string
		ExpectedBinary  string
		ExpectedVersion string
	}{
		// Successful cases
		{"No hyphen in binary", "federation-v1.0.0", "federation", "v1.0.0"},
		{"hyphen in binary", "stellar-sign-v1.0.0", "stellar-sign", "v1.0.0"},
		{"non-semver", "federation-master", "federation", "master"},
		// Faileds cases
		{"capitalized", "Federation-v1.0.0", "", ""},
	}

	for _, kase := range cases {
		b, v := extractFromTag(kase.Tag)
		assert.Equal(t, kase.ExpectedBinary, b,
			fmt.Sprintf("Case \"%s\" failed the binary assertion", kase.Name))
		assert.Equal(t, kase.ExpectedVersion, v,
			fmt.Sprintf("Case \"%s\" failed the version assertion", kase.Name))
	}
}

{'repo_name': 'stellar/go', 'stars': '741', 'repo_language': 'Go', 'file_name': 'graph.go', 'mime_type': 'text/plain', 'hash': -4524590712718294638, 'source_dataset': 'data'}


###  TEMPLATE.txt.tpl; coding: utf-8 ---

#  Author(s): Christophe Prud'homme <christophe.prudhomme@ujf-grenoble.fr>
#       Date: 2012-04-12
#
#  Copyright (C) 2012 Université Joseph Fourier (Grenoble I)
#
# Distributed under the GPL(GNU Public License):
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#

#set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -mavx")

{'repo_name': 'feelpp/feelpp', 'stars': '203', 'repo_language': 'C++', 'file_name': 'aneurysm.geo', 'mime_type': 'text/plain', 'hash': -2754245706252937370, 'source_dataset': 'data'}


export interface EnvVarObject {
	[name: string]: string;
}

export interface LabelObject {
	[name: string]: string;
}

{'repo_name': 'balena-io/balena-supervisor', 'stars': '112', 'repo_language': 'TypeScript', 'file_name': 'extlinux.conf', 'mime_type': 'text/plain', 'hash': -6259200729914820653, 'source_dataset': 'data'}


/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * 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.
 */

package com.android.server.locksettings.recoverablekeystore;

import android.annotation.Nullable;
import android.app.PendingIntent;
import android.util.ArraySet;
import android.util.Log;
import android.util.SparseArray;

import com.android.internal.annotations.GuardedBy;

/**
 * In memory storage for listeners to be notified when new recovery snapshot is available. This
 * class is thread-safe. It is used on two threads - the service thread and the thread that runs the
 * {@link KeySyncTask}.
 *
 * @hide
 */
public class RecoverySnapshotListenersStorage {
    private static final String TAG = "RecoverySnapshotLstnrs";

    @GuardedBy("this")
    private SparseArray<PendingIntent> mAgentIntents = new SparseArray<>();

    @GuardedBy("this")
    private ArraySet<Integer> mAgentsWithPendingSnapshots = new ArraySet<>();

    /**
     * Sets new listener for the recovery agent, identified by {@code uid}.
     *
     * @param recoveryAgentUid uid of the recovery agent.
     * @param intent PendingIntent which will be triggered when new snapshot is available.
     */
    public synchronized void setSnapshotListener(
            int recoveryAgentUid, @Nullable PendingIntent intent) {
        Log.i(TAG, "Registered listener for agent with uid " + recoveryAgentUid);
        mAgentIntents.put(recoveryAgentUid, intent);

        if (mAgentsWithPendingSnapshots.contains(recoveryAgentUid)) {
            Log.i(TAG, "Snapshot already created for agent. Immediately triggering intent.");
            tryToSendIntent(recoveryAgentUid, intent);
        }
    }

    /**
     * Returns {@code true} if a listener has been set for the recovery agent.
     */
    public synchronized boolean hasListener(int recoveryAgentUid) {
        return mAgentIntents.get(recoveryAgentUid) != null;
    }

    /**
     * Notifies recovery agent that new snapshot is available. If a recovery agent has not yet
     * registered a {@link PendingIntent}, remembers that a snapshot is pending for it, so that
     * when it does register, that intent is immediately triggered.
     *
     * @param recoveryAgentUid uid of recovery agent.
     */
    public synchronized void recoverySnapshotAvailable(int recoveryAgentUid) {
        PendingIntent intent = mAgentIntents.get(recoveryAgentUid);
        if (intent == null) {
            Log.i(TAG, "Snapshot available for agent " + recoveryAgentUid
                    + " but agent has not yet initialized. Will notify agent when it does.");
            mAgentsWithPendingSnapshots.add(recoveryAgentUid);
            return;
        }

        tryToSendIntent(recoveryAgentUid, intent);
    }

    /**
     * Attempts to send {@code intent} for the recovery agent. If this fails, remembers to notify
     * the recovery agent immediately if it registers a new intent.
     */
    private synchronized void tryToSendIntent(int recoveryAgentUid, PendingIntent intent) {
        try {
            intent.send();
            mAgentsWithPendingSnapshots.remove(recoveryAgentUid);
            Log.d(TAG, "Successfully notified listener.");
        } catch (PendingIntent.CanceledException e) {
            Log.e(TAG,
                    "Failed to trigger PendingIntent for " + recoveryAgentUid,
                    e);
            // As it failed to trigger, trigger immediately if a new intent is registered later.
            mAgentsWithPendingSnapshots.add(recoveryAgentUid);
        }
    }
}

{'repo_name': 'LineageOS/android_frameworks_base', 'stars': '249', 'repo_language': 'Java', 'file_name': 'strings.xml', 'mime_type': 'text/xml', 'hash': 8164907962070867271, 'source_dataset': 'data'}


From 075b5cf8d3940ed2c39fb37c1e14a652e4a6f2fc Mon Sep 17 00:00:00 2001
From: Romain Naour <romain.naour@smile.fr>
Date: Sun, 1 Apr 2018 16:21:31 +0200
Subject: [PATCH] configure.in: convert AC_RUN_IFELSE to AC_COMPILE_IFELSE

Prevent configure script from trying to run programs in a cross
compilation environment.

Signed-off-by: Romain Naour <romain.naour@smile.fr>
Cc: Sergio Prado <sergio.prado@e-labworks.com>
---
 configure.in | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/configure.in b/configure.in
index 571322b..e489037 100644
--- a/configure.in
+++ b/configure.in
@@ -431,7 +431,7 @@ if test "x$LPCAP" = "xno"; then
 fi

 AC_MSG_CHECKING([for pcap_lex_destroy])
-AC_RUN_IFELSE(
+AC_COMPILE_IFELSE(
 [AC_LANG_PROGRAM(
 [[
 #include <pcap.h>
@@ -823,7 +823,7 @@ if test "x$have_daq_data_channel_separate_ip_versions" = "xyes"; then
 fi

 AC_MSG_CHECKING([for DAQ_VERDICT_RETRY])
-AC_RUN_IFELSE(
+AC_COMPILE_IFELSE(
 [AC_LANG_PROGRAM(
 [[
 #include <daq.h>
@@ -886,7 +886,7 @@ if eval "echo $host_cpu|grep -i sparc >/dev/null"; then
     OLD_CFLAGS="$CFLAGS"
     CFLAGS="$CFLAGS -mcpu=v9 "
     AC_MSG_CHECKING([for sparc %time register])
-    AC_RUN_IFELSE(
+    AC_COMPILE_IFELSE(
     [AC_LANG_PROGRAM(
     [[]],
     [[
--
2.14.3

{'repo_name': 'teslamotors/buildroot', 'stars': '492', 'repo_language': 'Makefile', 'file_name': 'linux-ext-aufs.mk', 'mime_type': 'text/plain', 'hash': -2418449293243956377, 'source_dataset': 'data'}


// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: tensorflow/core/protobuf/saved_model.proto

#ifndef PROTOBUF_tensorflow_2fcore_2fprotobuf_2fsaved_5fmodel_2eproto__INCLUDED
#define PROTOBUF_tensorflow_2fcore_2fprotobuf_2fsaved_5fmodel_2eproto__INCLUDED

#include <string>

#include <google/protobuf/stubs/common.h>

#if GOOGLE_PROTOBUF_VERSION < 3000000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please update
#error your headers.
#endif
#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please
#error regenerate this file with a newer version of protoc.
#endif

#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/unknown_field_set.h>
#include "tensorflow/core/protobuf/meta_graph.pb.h"
// @@protoc_insertion_point(includes)

namespace tensorflow {

// Internal implementation detail -- do not call these.
void protobuf_AddDesc_tensorflow_2fcore_2fprotobuf_2fsaved_5fmodel_2eproto();
void protobuf_AssignDesc_tensorflow_2fcore_2fprotobuf_2fsaved_5fmodel_2eproto();
void protobuf_ShutdownFile_tensorflow_2fcore_2fprotobuf_2fsaved_5fmodel_2eproto();

class SavedModel;

// ===================================================================

class SavedModel : public ::google::protobuf::Message {
 public:
  SavedModel();
  virtual ~SavedModel();

  SavedModel(const SavedModel& from);

  inline SavedModel& operator=(const SavedModel& from) {
    CopyFrom(from);
    return *this;
  }

  inline ::google::protobuf::Arena* GetArena() const { return GetArenaNoVirtual(); }
  inline void* GetMaybeArenaPointer() const {
    return MaybeArenaPtr();
  }
  static const ::google::protobuf::Descriptor* descriptor();
  static const SavedModel& default_instance();

  void UnsafeArenaSwap(SavedModel* other);
  void Swap(SavedModel* other);

  // implements Message ----------------------------------------------

  inline SavedModel* New() const { return New(NULL); }

  SavedModel* New(::google::protobuf::Arena* arena) const;
  void CopyFrom(const ::google::protobuf::Message& from);
  void MergeFrom(const ::google::protobuf::Message& from);
  void CopyFrom(const SavedModel& from);
  void MergeFrom(const SavedModel& from);
  void Clear();
  bool IsInitialized() const;

  int ByteSize() const;
  bool MergePartialFromCodedStream(
      ::google::protobuf::io::CodedInputStream* input);
  void SerializeWithCachedSizes(
      ::google::protobuf::io::CodedOutputStream* output) const;
  ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
  int GetCachedSize() const { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const;
  void InternalSwap(SavedModel* other);
  protected:
  explicit SavedModel(::google::protobuf::Arena* arena);
  private:
  static void ArenaDtor(void* object);
  inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
  private:
  inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
    return _internal_metadata_.arena();
  }
  inline void* MaybeArenaPtr() const {
    return _internal_metadata_.raw_arena_ptr();
  }
  public:

  ::google::protobuf::Metadata GetMetadata() const;

  // nested types ----------------------------------------------------

  // accessors -------------------------------------------------------

  // optional int64 saved_model_schema_version = 1;
  void clear_saved_model_schema_version();
  static const int kSavedModelSchemaVersionFieldNumber = 1;
  ::google::protobuf::int64 saved_model_schema_version() const;
  void set_saved_model_schema_version(::google::protobuf::int64 value);

  // repeated .tensorflow.MetaGraphDef meta_graphs = 2;
  int meta_graphs_size() const;
  void clear_meta_graphs();
  static const int kMetaGraphsFieldNumber = 2;
  const ::tensorflow::MetaGraphDef& meta_graphs(int index) const;
  ::tensorflow::MetaGraphDef* mutable_meta_graphs(int index);
  ::tensorflow::MetaGraphDef* add_meta_graphs();
  ::google::protobuf::RepeatedPtrField< ::tensorflow::MetaGraphDef >*
      mutable_meta_graphs();
  const ::google::protobuf::RepeatedPtrField< ::tensorflow::MetaGraphDef >&
      meta_graphs() const;

  // @@protoc_insertion_point(class_scope:tensorflow.SavedModel)
 private:

  ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
  friend class ::google::protobuf::Arena;
  typedef void InternalArenaConstructable_;
  typedef void DestructorSkippable_;
  bool _is_default_instance_;
  ::google::protobuf::int64 saved_model_schema_version_;
  ::google::protobuf::RepeatedPtrField< ::tensorflow::MetaGraphDef > meta_graphs_;
  mutable int _cached_size_;
  friend void  protobuf_AddDesc_tensorflow_2fcore_2fprotobuf_2fsaved_5fmodel_2eproto();
  friend void protobuf_AssignDesc_tensorflow_2fcore_2fprotobuf_2fsaved_5fmodel_2eproto();
  friend void protobuf_ShutdownFile_tensorflow_2fcore_2fprotobuf_2fsaved_5fmodel_2eproto();

  void InitAsDefaultInstance();
  static SavedModel* default_instance_;
};
// ===================================================================

// ===================================================================

#if !PROTOBUF_INLINE_NOT_IN_HEADERS
// SavedModel

// optional int64 saved_model_schema_version = 1;
inline void SavedModel::clear_saved_model_schema_version() {
  saved_model_schema_version_ = GOOGLE_LONGLONG(0);
}
inline ::google::protobuf::int64 SavedModel::saved_model_schema_version() const {
  // @@protoc_insertion_point(field_get:tensorflow.SavedModel.saved_model_schema_version)
  return saved_model_schema_version_;
}
inline void SavedModel::set_saved_model_schema_version(::google::protobuf::int64 value) {

  saved_model_schema_version_ = value;
  // @@protoc_insertion_point(field_set:tensorflow.SavedModel.saved_model_schema_version)
}

// repeated .tensorflow.MetaGraphDef meta_graphs = 2;
inline int SavedModel::meta_graphs_size() const {
  return meta_graphs_.size();
}
inline void SavedModel::clear_meta_graphs() {
  meta_graphs_.Clear();
}
inline const ::tensorflow::MetaGraphDef& SavedModel::meta_graphs(int index) const {
  // @@protoc_insertion_point(field_get:tensorflow.SavedModel.meta_graphs)
  return meta_graphs_.Get(index);
}
inline ::tensorflow::MetaGraphDef* SavedModel::mutable_meta_graphs(int index) {
  // @@protoc_insertion_point(field_mutable:tensorflow.SavedModel.meta_graphs)
  return meta_graphs_.Mutable(index);
}
inline ::tensorflow::MetaGraphDef* SavedModel::add_meta_graphs() {
  // @@protoc_insertion_point(field_add:tensorflow.SavedModel.meta_graphs)
  return meta_graphs_.Add();
}
inline ::google::protobuf::RepeatedPtrField< ::tensorflow::MetaGraphDef >*
SavedModel::mutable_meta_graphs() {
  // @@protoc_insertion_point(field_mutable_list:tensorflow.SavedModel.meta_graphs)
  return &meta_graphs_;
}
inline const ::google::protobuf::RepeatedPtrField< ::tensorflow::MetaGraphDef >&
SavedModel::meta_graphs() const {
  // @@protoc_insertion_point(field_list:tensorflow.SavedModel.meta_graphs)
  return meta_graphs_;
}

#endif  // !PROTOBUF_INLINE_NOT_IN_HEADERS

// @@protoc_insertion_point(namespace_scope)

}  // namespace tensorflow

// @@protoc_insertion_point(global_scope)

#endif  // PROTOBUF_tensorflow_2fcore_2fprotobuf_2fsaved_5fmodel_2eproto__INCLUDED

{'repo_name': 'miyosuda/TensorFlowAndroidDemo', 'stars': '280', 'repo_language': 'C++', 'file_name': 'build_defs.bzl', 'mime_type': 'text/plain', 'hash': 6920839360903804195, 'source_dataset': 'data'}


 &control
    calculation='scf'
    restart_mode='from_scratch',
    tstress = .true.
    prefix='LiH',
    pseudo_dir = './',
    outdir='out'
    disk_io='low'
    wf_collect=.false.
 /
 &system
    ibrav=2, celldm(1) =7.100, nat=  2, ntyp= 2,
    nspin=1,
    degauss=0.001,
    smearing='mp',
    occupations='smearing',
    ecutwfc = 450
    ecutrho =1800
 /
 &electrons
    conv_thr =  1.0d-10
    mixing_beta = 0.7
 /
ATOMIC_SPECIES
 Li  9.01  Li.ncpp
 H   1.01  H.ncpp
ATOMIC_POSITIONS
 Li 0.00 0.00 0.00
 H  0.50 0.50 0.50
K_POINTS AUTOMATIC
8 8 8 1 1 1

{'repo_name': 'QMCPACK/qmcpack', 'stars': '124', 'repo_language': 'C++', 'file_name': 'H.plt', 'mime_type': 'text/plain', 'hash': -2390111184560933537, 'source_dataset': 'data'}


// Copyright 2015 The etcd Authors
//
// 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.

package rafthttp

import "github.com/coreos/etcd/raft/raftpb"

type encoder interface {
	// encode encodes the given message to an output stream.
	encode(m *raftpb.Message) error
}

type decoder interface {
	// decode decodes the message from an input stream.
	decode() (raftpb.Message, error)
}

{'repo_name': 'seata/seata-go-server', 'stars': '262', 'repo_language': 'Go', 'file_name': 'main.go', 'mime_type': 'text/x-c', 'hash': 1380983911464067578, 'source_dataset': 'data'}


sprintf-js

JavaScript sprintf implementation

{'repo_name': 'lokenx/plexrequests-meteor', 'stars': '532', 'repo_language': 'JavaScript', 'file_name': 'security.js', 'mime_type': 'text/plain', 'hash': -7060690088310982878, 'source_dataset': 'data'}


import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
import numpy as np

class Flatten(nn.Module):

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

    def forward(self, x):
        """
        Arguments:
            x: a float tensor with shape [batch_size, c, h, w].
        Returns:
            a float tensor with shape [batch_size, c*h*w].
        """

        # without this pretrained model isn't working
        x = x.transpose(3, 2).contiguous()

        return x.view(x.size(0), -1)

class PNet(nn.Module):

    def __init__(self):

        super(PNet, self).__init__()

        # suppose we have input with size HxW, then
        # after first layer: H - 2,
        # after pool: ceil((H - 2)/2),
        # after second conv: ceil((H - 2)/2) - 2,
        # after last conv: ceil((H - 2)/2) - 4,
        # and the same for W

        self.features = nn.Sequential(OrderedDict([
            ('conv1', nn.Conv2d(3, 10, 3, 1)),
            ('prelu1', nn.PReLU(10)),
            ('pool1', nn.MaxPool2d(2, 2, ceil_mode=True)),

            ('conv2', nn.Conv2d(10, 16, 3, 1)),
            ('prelu2', nn.PReLU(16)),

            ('conv3', nn.Conv2d(16, 32, 3, 1)),
            ('prelu3', nn.PReLU(32))
        ]))

        self.conv4_1 = nn.Conv2d(32, 2, 1, 1)
        self.conv4_2 = nn.Conv2d(32, 4, 1, 1)

        weights = np.load('mtcnn_pytorch/src/weights/pnet.npy', allow_pickle=True)[()]
        for n, p in self.named_parameters():
            p.data = torch.FloatTensor(weights[n])

    def forward(self, x):
        """
        Arguments:
            x: a float tensor with shape [batch_size, 3, h, w].
        Returns:
            b: a float tensor with shape [batch_size, 4, h', w'].
            a: a float tensor with shape [batch_size, 2, h', w'].
        """
        x = self.features(x)
        a = self.conv4_1(x)
        b = self.conv4_2(x)
        a = F.softmax(a, dim=-1)
        return b, a

class RNet(nn.Module):

    def __init__(self):

        super(RNet, self).__init__()

        self.features = nn.Sequential(OrderedDict([
            ('conv1', nn.Conv2d(3, 28, 3, 1)),
            ('prelu1', nn.PReLU(28)),
            ('pool1', nn.MaxPool2d(3, 2, ceil_mode=True)),

            ('conv2', nn.Conv2d(28, 48, 3, 1)),
            ('prelu2', nn.PReLU(48)),
            ('pool2', nn.MaxPool2d(3, 2, ceil_mode=True)),

            ('conv3', nn.Conv2d(48, 64, 2, 1)),
            ('prelu3', nn.PReLU(64)),

            ('flatten', Flatten()),
            ('conv4', nn.Linear(576, 128)),
            ('prelu4', nn.PReLU(128))
        ]))

        self.conv5_1 = nn.Linear(128, 2)
        self.conv5_2 = nn.Linear(128, 4)

        weights = np.load('mtcnn_pytorch/src/weights/rnet.npy', allow_pickle=True)[()]
        for n, p in self.named_parameters():
            p.data = torch.FloatTensor(weights[n])

    def forward(self, x):
        """
        Arguments:
            x: a float tensor with shape [batch_size, 3, h, w].
        Returns:
            b: a float tensor with shape [batch_size, 4].
            a: a float tensor with shape [batch_size, 2].
        """
        x = self.features(x)
        a = self.conv5_1(x)
        b = self.conv5_2(x)
        a = F.softmax(a, dim=-1)
        return b, a

class ONet(nn.Module):

    def __init__(self):

        super(ONet, self).__init__()

        self.features = nn.Sequential(OrderedDict([
            ('conv1', nn.Conv2d(3, 32, 3, 1)),
            ('prelu1', nn.PReLU(32)),
            ('pool1', nn.MaxPool2d(3, 2, ceil_mode=True)),

            ('conv2', nn.Conv2d(32, 64, 3, 1)),
            ('prelu2', nn.PReLU(64)),
            ('pool2', nn.MaxPool2d(3, 2, ceil_mode=True)),

            ('conv3', nn.Conv2d(64, 64, 3, 1)),
            ('prelu3', nn.PReLU(64)),
            ('pool3', nn.MaxPool2d(2, 2, ceil_mode=True)),

            ('conv4', nn.Conv2d(64, 128, 2, 1)),
            ('prelu4', nn.PReLU(128)),

            ('flatten', Flatten()),
            ('conv5', nn.Linear(1152, 256)),
            ('drop5', nn.Dropout(0.25)),
            ('prelu5', nn.PReLU(256)),
        ]))

        self.conv6_1 = nn.Linear(256, 2)
        self.conv6_2 = nn.Linear(256, 4)
        self.conv6_3 = nn.Linear(256, 10)

        weights = np.load('mtcnn_pytorch/src/weights/onet.npy', allow_pickle=True)[()]
        for n, p in self.named_parameters():
            p.data = torch.FloatTensor(weights[n])

    def forward(self, x):
        """
        Arguments:
            x: a float tensor with shape [batch_size, 3, h, w].
        Returns:
            c: a float tensor with shape [batch_size, 10].
            b: a float tensor with shape [batch_size, 4].
            a: a float tensor with shape [batch_size, 2].
        """
        x = self.features(x)
        a = self.conv6_1(x)
        b = self.conv6_2(x)
        c = self.conv6_3(x)
        a = F.softmax(a, dim = -1)
        return c, b, a

{'repo_name': 'taotaonice/FaceShifter', 'stars': '110', 'repo_language': 'Jupyter Notebook', 'file_name': 'align_trans.py', 'mime_type': 'text/x-python', 'hash': -6069860620228500593, 'source_dataset': 'data'}


package io.branch.referral;

import android.content.Context;

/**
 * Created by sojanpr on 3/7/18.
 * <p>
 * Class for handling the SDK user data or state tracking features
 * If tracking disabled SDK will not track any user data or state.
 * SDK will not send any network calls when tracking is disabled
 * </p>
 */

class TrackingController {
    /* Flag for controlling the user data tracking state. If disabled SDK will not track any user data or state. SDK will not send any network calls when tracking is disabled*/
    private boolean trackingDisabled = true;

    TrackingController(Context context) {
        updateTrackingState(context);
    }

    void disableTracking(Context context, boolean disableTracking) {
        if (trackingDisabled != disableTracking) {
            trackingDisabled = disableTracking;
            if (disableTracking) {
                onTrackingDisabled(context);
            } else {
                onTrackingEnabled();
            }
            PrefHelper.getInstance(context).setBool(PrefHelper.KEY_TRACKING_STATE, disableTracking);
        }
    }

    boolean isTrackingDisabled() {
        return trackingDisabled;
    }

    void updateTrackingState(Context context) {
        trackingDisabled = PrefHelper.getInstance(context).getBool(PrefHelper.KEY_TRACKING_STATE);
    }

    private void onTrackingDisabled(Context context) {
        // Clear all pending requests
        Branch.getInstance().clearPendingRequests();

        // Clear  any tracking specific preference items
        PrefHelper prefHelper = PrefHelper.getInstance(context);
        prefHelper.setSessionID(PrefHelper.NO_STRING_VALUE);
        prefHelper.setLinkClickID(PrefHelper.NO_STRING_VALUE);
        prefHelper.setLinkClickIdentifier(PrefHelper.NO_STRING_VALUE);
        prefHelper.setAppLink(PrefHelper.NO_STRING_VALUE);
        prefHelper.setInstallReferrerParams(PrefHelper.NO_STRING_VALUE);
        prefHelper.setGooglePlayReferrer(PrefHelper.NO_STRING_VALUE);
        prefHelper.setGoogleSearchInstallIdentifier(PrefHelper.NO_STRING_VALUE);
        prefHelper.setExternalIntentUri(PrefHelper.NO_STRING_VALUE);
        prefHelper.setExternalIntentExtra(PrefHelper.NO_STRING_VALUE);
        prefHelper.setSessionParams(PrefHelper.NO_STRING_VALUE);
        prefHelper.saveLastStrongMatchTime(0);
    }

    private void onTrackingEnabled() {
        Branch branch = Branch.getInstance();
        if (branch != null) {
            branch.registerAppInit(branch.getInstallOrOpenRequest(null), true);
        }
    }
}

{'repo_name': 'BranchMetrics/android-branch-deep-linking-attribution', 'stars': '326', 'repo_language': 'HTML', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 195364079657800314, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8"?>
<!--
 *************************************************************************
 * Copyright (c) 2004, 2006 Actuate Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *  Actuate Corporation  - initial API and implementation
 *
 *************************************************************************
 *
 *  build.xml
 *
 *  Build script for project org.eclipse.birt.report.designer.ui.nl
 *
 * "Clean" - Clean nl.jar file and *.properties files generated from
 *           native2ascii.exe.
 * "NativeToAscii"   - Convert *_xx_YY.msg files into *_xx_YY.properties files by native2ascii.exe
 *
 * "Export" - Export the project, for instance, jar files are copied to a designated folder.
 *            this task must be called after calling Jar task, so it needn't depend on Jar explicitly
 *
 *  Usage:
 *    ant [any one or more of the public targets]
 *        -Declipse.home=<your eclipse home>
 *		  -Ddtp.home=<your DTP plugins source home>  [optional]
 *
 *  Default target is "Jar".
 *
 *  Notes:
 *  1. classpath need to be set for junit.jar
 *  2. The build script requires Ant 1.6
 *
-->

<project name="org.eclipse.birt.report.designer.ui.nl" default="Jar" basedir=".">
	<description>NL Fragment for org.eclipse.birt.report.designer.ui</description>

	<property file="META-INF/MANIFEST.MF" />
    <property name="dir.src" value="src" />
 	<property name="dir.bin" value="bin" />
	<property name="nl.group" value="1" />
	<property name="module.name" value="org.eclipse.birt.report.designer.ui.nl" />
	<property name="jar.name" value="${module.name}${nl.group}_${Bundle-Version}.jar" />
	<property name="replaceBuildInfo" value="2.5.0"/>

	<target name="Clean">
		<delete>
			<fileset dir="." includes="**/*_??_??.properties" />
			<fileset dir="." includes="${jar.name}" />
		</delete>
	</target>

	<target name="NativeToAscii"
	     description="Execute native2ascii for *.msg files">

		<native2ascii encoding="Cp1252"
					  src="."
					  dest="."
					  ext=".properties"
					  includes="**/*_de_DE.msg, **/*_fr_FR.msg, **/*_es_ES.msg"/>
		<native2ascii encoding="GBK"
					  src="."
					  dest="."
					  ext=".properties"
					  includes="**/*_zh_CN.msg"/>
		<native2ascii encoding="SJIS"
					  src="."
					  dest="."
					  ext=".properties"
					  includes="**/*_ja_JP.msg"/>
		<native2ascii encoding="MS949"
					  src="."
					  dest="."
					  ext=".properties"
					  includes="**/*_ko_KR.msg"/>
	</target>

	<target name="nl-jar">
		<jar destfile="${jar.name}" manifest="./META-INF/MANIFEST.MF">
			<zipfileset dir="."  includes="about.html,plugin_??_??.properties,nl/??/templates/*.xml"/>
		</jar>
	</target>

	<target name="Jar" depends="NativeToAscii, replaceBuildInfo, nl-jar" >
	</target>
	<target name="Export">
		<copy todir="${export.dir}">
	        <fileset dir="." includes="${jar.name}"/>
	  </copy>
	</target>
	<target name="replaceBuildInfo">
        <replace dir="." value="${BranchVersion}.${buildId}" token="@BUILD@">
                <include name="plugin_??_??.properties" />
        </replace>
	</target>

</project>

{'repo_name': 'eclipse/birt', 'stars': '201', 'repo_language': 'Java', 'file_name': 'Messages.properties', 'mime_type': 'text/plain', 'hash': 7542716048669424572, 'source_dataset': 'data'}


;;;;;;;;;;;;;;;;;;; -*- Mode: Lisp; Package: Macsyma -*- ;;;;;;;;;;;;;;;;;;;
;;;     (c) Copyright 1980 Massachusetts Institute of Technology         ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(macsyma-module newdet)

;; THIS IS A VERSION OF THE GENTLEMAN-JOHNSON TREE-MINOR DETERMINANT
;; USING RATIONAL FUNCTIONS.  "A" CAN BE A MATRIX OR AN ARRAY.
;; ANSWER IS IN RATIONAL FORM.
;; RJF  5/2/73

(DECLARE (SPECIAL VLIST VARLIST GENVAR ARYP)
	 (FIXNUM RR K J OLD NEW BINOM I PASCAL N M)
	 (ARRAY* (NOTYPE INPUT 2 BINOM 2 MINOR1 2 I 1)))

(DEFMFUN $NEWDET N
       ((LAMBDA (A)
		(COND ((= N 2)
		       (COND ((NOT (FIXP (ARG 2)))
			      (merror "Wrong arg to NEWDET: ~M" (ARG 2))))
		       (SETQ A (ARG 1) N (ARG 2)))
		      ((AND (= N 1) ($MATRIXP (SETQ A (ARG 1))))
		       (SETQ N (LENGTH (CDR (ARG 1)))))
		      (T (merror "Wrong number of args to NEWDET")))
		(NEWDET A N NIL))
	NIL))

(DEFMFUN $PERMANENT N
       ((LAMBDA (A)
		(COND ((= N 2)
		       (COND ((NOT (FIXP (ARG 2)))
			      (merror "Wrong arg to PERM: ~M" (ARG 2))))
		       (SETQ A (ARG 1) N (ARG 2)))
		      ((AND (= N 1) ($MATRIXP (SETQ A (ARG 1))))
		       (SETQ N (LENGTH (CDR (ARG 1)))))
		      (T (merror "Wrong number of args to PERM")))
		(NEWDET A N T))
	NIL))

(DEFUN NEWDET (A N PERM)
       (PROG (RR R K J OLD NEW VLIST M LOC ADDR SIGN)
	     (COND ((> N 50.)
		    (merror "Array too big - NEWDET: ~M" N)))
	     (ARRAY BINOM T (ADD1 N) (ADD1 N))
	     (ARRAY MINOR1 T 2. (ADD1 (SETQ RR (PASCAL N))))
	     (ARRAY I T (PLUS 2. N))
	     (DO K
		 0.
		 (ADD1 K)
		 (> K 1.)
		 (DO J
		     0.
		     (ADD1 J)
		     (> J RR)
		     (STORE (MINOR1 K J) '(0. . 1.))))
	     (DO K 0. (ADD1 K) (> K (ADD1 N)) (STORE (I K) -1.))
	     (ARRAY INPUT T (ADD1 N) (ADD1 N))
	     (DO K
		 1.
		 (ADD1 K)
		 (> K N)
		 (DO J
		     1.
		     (ADD1 J)
		     (> J N)
		     (NEWVAR1 (STORE (INPUT K J)
				     ((LAMBDA (ARYP)
				       (MEVAL (LIST (LIST A 'ARRAY) K J)))
				      T)))))
	     (NEWVAR (CONS '(MTIMES) VLIST))
	     (DO K
		 1.
		 (ADD1 K)
		 (> K N)
		 (DO J
		     1.
		     (ADD1 J)
		     (> J N)
		     (STORE (INPUT K J)
			    (CDR (RATREP* (INPUT K J))))))
	     (SETQ NEW 1.)
	     (SETQ OLD 0.)
	     (STORE (I 0.) N)
	     (DO LOC
		 1.
		 (ADD1 LOC)
		 (> LOC N)
		 (STORE (MINOR1 OLD (SUB1 LOC)) (INPUT 1. LOC)))
	(SETQ M 1.)
	G0193(COND ((> M (SUB1 N)) (GO RET)))
	     (SETQ LOC 0.)
	     (SETQ J 1.)
	G0189(COND ((> J M) (GO NEXTMINOR)))
	     (STORE (I J) (DIFFERENCE M J))
	     (SETQ J (+ J 1.))
	     (GO G0189)
	NEXTMINOR
	     (COND ((NOT (EQUAL (MINOR1 OLD LOC) '(0. . 1.)))
		    (SETQ K (SUB1 N))
		    (SETQ J 0.)
		    (SETQ ADDR (PLUS LOC (BINOM K (ADD1 M))))
		    (SETQ SIGN 1.))
		   (T (GO OVER)))
	NEXTUSE
	     (COND
	      ((EQUAL K (I (ADD1 J)))
	       (SETQ J (ADD1 J))
	       (SETQ SIGN (MINUS SIGN)))
	      (T
	       (STORE
		(MINOR1 NEW ADDR)
		(RATPLUS
		 (MINOR1 NEW ADDR)
		 (RATTIMES (MINOR1 OLD LOC)
			   (COND ((OR (EQUAL SIGN 1.) PERM)
				  (INPUT (ADD1 M) (ADD1 K)))
				 (T (RATMINUS (INPUT (ADD1 M)
						     (ADD1 K)))))
			   T)))))
	     (COND ((> K 0.)
		    (SETQ K (SUB1 K))
		    (SETQ ADDR
			  (DIFFERENCE ADDR
				      (BINOM K (DIFFERENCE M J))))
		    (GO NEXTUSE)))
	     (STORE (MINOR1 OLD LOC)  '(0 . 1))
	OVER (SETQ LOC (ADD1 LOC))
	     (SETQ J M)
	BACK (COND ((> 1. J) (SETQ M (ADD1 M))(SETQ OLD(DIFFERENCE 1 OLD))(SETQ NEW (DIFFERENCE 1 NEW))(GO G0193)))
	     (STORE (I J) (ADD1 (I J)))
	     (COND ((> (I (SUB1 J)) (I J)) (GO NEXTMINOR))
		   (T (STORE (I J) (DIFFERENCE M J))))

	     (SETQ J (SUB1 J))
	     (GO BACK)
	RET(*REARRAY 'BINOM)
(*REARRAY 'INPUT)
  (SETQ R (CONS (LIST 'MRAT
				 'SIMP
				 VARLIST
				 GENVAR)
			   (MINOR1 OLD 0.)))
(*REARRAY 'MINOR1)
(RETURN R)))

(DEFUN PASCAL (N)
       (PROG NIL
	     (STORE (BINOM 0. 0.) 1.)
	     (DO H
		 1.
		 (ADD1 H)
		 (> H N)
		 (STORE (BINOM H 0.) 1.)
		 (STORE (BINOM (SUB1 H) H) 0.)
		 (DO J
		     1.
		     (ADD1 J)
		     (> J H)
		     (STORE (BINOM H J)
			    (PLUS (BINOM (SUB1 H) (SUB1 J))
				  (BINOM (SUB1 H) J)))))
	     (RETURN (SUB1 (BINOM N (LSH N -1.))))))

(DECLARE (UNSPECIAL VLIST VARLIST GENVAR ARYP))

{'repo_name': 'PDP-10/its', 'stars': '490', 'repo_language': 'Assembly', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -7530489719861224947, 'source_dataset': 'data'}


/*******************************************************************************
 * Copyright (c) 2017, 2019 IBM Corp. and others
 *
 * This program and the accompanying materials are made available under
 * the terms of the Eclipse Public License 2.0 which accompanies this
 * distribution and is available at http://eclipse.org/legal/epl-2.0
 * or the Apache License, Version 2.0 which accompanies this distribution
 * and is available at https://www.apache.org/licenses/LICENSE-2.0.
 *
 * This Source Code may also be made available under the following Secondary
 * Licenses when the conditions for such availability set forth in the
 * Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
 * version 2 with the GNU Classpath Exception [1] and GNU General Public
 * License, version 2 with the OpenJDK Assembly Exception [2].
 *
 * [1] https://www.gnu.org/software/classpath/license.html
 * [2] http://openjdk.java.net/legal/assembly-exception.html
 *
 * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
 *******************************************************************************/

#include "ilgen.hpp"
#include "omrcfg.h"
#include "compiler_util.hpp"

#include "compile/ResolvedMethod.hpp"
#include "il/Block.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"

#include <string>

std::map<std::string, TR::ILOpCodes> Tril::OpCodeTable::_opcodeNameMap;

/*
 * The general algorithm for generating a TR::Node from it's AST representation
 * is like this:
 *
 * 1. Convert AST node into TRNode using the AST node's name and opcode
 * 2. Recursively call this function to generate the child nodes and set them
 *    as children of the current TR::Node
 *
 * However, certain opcodes must be created using a special interface. For this
 * reason, special opcodes are detected using opcode properties.
 */
TR::Node* Tril::TRLangBuilder::toTRNode(const ASTNode* const tree, IlGenState* state) {
    TR::Node* node = _converter->convert(tree, state);
    if (node == NULL)
        return NULL;
    node->setFlags(parseFlags(tree));

    TraceIL("  node address %p\n", node);
    TraceIL("  node index n%dn\n", node->getGlobalIndex());

    auto nodeIdArg = tree->getArgByName("id");
    if (nodeIdArg != NULL) {
        auto id = nodeIdArg->getValue()->getString();
        state->setNodePair(id, node);
        TraceIL("  node ID %s\n", id);
    }

    // create a set child nodes
    const ASTNode* t = tree->getChildren();
    int i = 0;
    while (t) {
        auto child = toTRNode(t, state);
        if (child == NULL)
            return NULL;
        TraceIL("Setting n%dn (%p) as child %d of n%dn (%p)\n", child->getGlobalIndex(), child, i, node->getGlobalIndex(), node);
        node->setAndIncChild(i, child);
        t = t->next;
        ++i;
    }

    return node;
}

/*
 * The CFG is generated by doing a post-order walk of the AST and creating edges
 * whenever opcodes that affect control flow are visited. As is the case in
 * `toTRNode`, the opcode properties are used to determine how a particular
 * opcode affects the control flow.
 *
 * For the fall-through edge, the assumption is that one is always needed unless
 * a node specifically adds one (e.g. goto, return, etc.).
 */
bool Tril::TRLangBuilder::cfgFor(const ASTNode* const tree, IlGenState* state) {
   auto isFallthroughNeeded = true;

   // visit the children first
   const ASTNode* t = tree->getChildren();
   while (t) {
       isFallthroughNeeded = isFallthroughNeeded && cfgFor(t, state);
       t = t->next;
   }

   auto opcode = OpCodeTable(tree->getName());

   if (opcode.isReturn()) {
       cfg()->addEdge(_currentBlock, cfg()->getEnd());
       isFallthroughNeeded = false;
       TraceIL("Added CFG edge from block %d to @exit -> %s\n", _currentBlockNumber, tree->getName());
   }
   else if (opcode.isBranch()) {
      const auto targetName = tree->getArgByName("target")->getValue()->getString();
      auto targetId = state->findBlockByName(targetName);
      cfg()->addEdge(_currentBlock, _blocks[targetId]);
      isFallthroughNeeded = isFallthroughNeeded && opcode.isIf();
      TraceIL("Added CFG edge from block %d to block %d (\"%s\") -> %s\n", _currentBlockNumber, targetId, targetName, tree->getName());
   }

   if (!isFallthroughNeeded) {
       TraceIL("  (no fall-through needed)\n", "");
   }

   return isFallthroughNeeded;
}

/*
 * Generating IL from a Tril AST is done in three steps:
 *
 * 1. Generate basic blocks for each block represented in the AST
 * 2. Generate the IL itself (Trees) by walking the AST
 * 3. Generate the CFG by walking the AST
 */
bool Tril::TRLangBuilder::injectIL() {
    auto state = new IlGenState();
    state->setType(typeDictionary());
    state->setSymRefTab(_symRefTab);
    state->setMethodSymbol(_methodSymbol);
    state->setComp(comp());
    TraceIL("=== %s ===\n", "Generating Blocks");

    // the top level nodes of the AST should be all the basic blocks
    createBlocks(countNodes(_trees));
    // evaluate the arguments for each basic block
    const ASTNode* block = _trees;
    auto blockIndex = 0;

    // assign block names
    while (block) {
       if (block->getArgByName("name") != NULL) {
           auto name = block->getArgByName("name")->getValue()->getString();
           state->setBlockPair(name, blockIndex);
           TraceIL("Name of block %d set to \"%s\"\n", blockIndex, name);
       }
       ++blockIndex;
       block = block->next;
    }

    TraceIL("=== %s ===\n", "Generating IL");
    block = _trees;
    generateToBlock(0);

    // iterate over each treetop in each basic block
    state->setBlocks(_blocks);
    while (block) {
       const ASTNode* t = block->getChildren();
       while (t) {
           TR::Node* node = NULL;
            try {
                node = toTRNode(t, state);
            } catch (ILGenError &e) {
                char* e_cstr = new char[e.what().size() + 1];
                strcpy(e_cstr, e.what().c_str());
                TraceIL(e_cstr);
                return false;
            }
           const auto tt = genTreeTop(node);
           TraceIL("Created TreeTop %p for node n%dn (%p)\n", tt, node->getGlobalIndex(), node);
           t = t->next;
       }
       generateToBlock(_currentBlockNumber + 1);
       block = block->next;
    }

    TraceIL("=== %s ===\n", "Generating CFG");
    block = _trees;
    generateToBlock(0);

    // iterate over each basic block
    while (block) {
       auto isFallthroughNeeded = true;

       // create CFG edges from the nodes withing the current basic block
       const ASTNode* t = block->getChildren();
       while (t) {
           isFallthroughNeeded = isFallthroughNeeded && cfgFor(t, state);
           t = t->next;
       }

       // create fall-through edge
       auto fallthroughArg = block->getArgByName("fallthrough");
       if (fallthroughArg != NULL) {
           auto target = std::string(fallthroughArg->getValue()->getString());
           if (target == "@exit") {
               cfg()->addEdge(_currentBlock, cfg()->getEnd());
               TraceIL("Added fallthrough edge from block %d to \"%s\"\n", _currentBlockNumber, target.c_str());
           }
           else if (target == "@none") {
               // do nothing, no fall-throught block specified
           }
           else {
               char* targetName = new char[target.size() + 1];
               strcpy(targetName, target.c_str());
               auto destBlock = state->findBlockByName(targetName);
               cfg()->addEdge(_currentBlock, _blocks[destBlock]);
               TraceIL("Added fallthrough edge from block %d to block %d \"%s\"\n", _currentBlockNumber, destBlock, target.c_str());
           }
       }
       else if (isFallthroughNeeded) {
           auto dest = _currentBlockNumber + 1 == numBlocks() ? cfg()->getEnd() : _blocks[_currentBlockNumber + 1];
           cfg()->addEdge(_currentBlock, dest);
           TraceIL("Added fallthrough edge from block %d to following block\n", _currentBlockNumber);
       }

       generateToBlock(_currentBlockNumber + 1);
       block = block->next;
    }

    return true;
}

{'repo_name': 'eclipse/omr', 'stars': '751', 'repo_language': 'C++', 'file_name': 'CMakeLists.txt', 'mime_type': 'text/plain', 'hash': -4774183946327201599, 'source_dataset': 'data'}


// Copyright (c) 2016 Ryan Prichard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

#ifndef LIBWINPTY_WINPTY_INTERNAL_H
#define LIBWINPTY_WINPTY_INTERNAL_H

#include <memory>
#include <string>

#include "../include/winpty.h"

#include "../shared/Mutex.h"
#include "../shared/OwnedHandle.h"

// The structures in this header are not intended to be accessed directly by
// client programs.

struct winpty_error_s {
    winpty_result_t code;
    const wchar_t *msgStatic;
    // Use a pointer to a std::shared_ptr so that the struct remains simple
    // enough to statically initialize, for the benefit of static error
    // objects like kOutOfMemory.
    std::shared_ptr<std::wstring> *msgDynamic;
};

struct winpty_config_s {
    uint64_t flags = 0;
    int cols = 80;
    int rows = 25;
    int mouseMode = WINPTY_MOUSE_MODE_AUTO;
    DWORD timeoutMs = 30000;
};

struct winpty_s {
    Mutex mutex;
    OwnedHandle agentProcess;
    OwnedHandle controlPipe;
    DWORD agentTimeoutMs = 0;
    OwnedHandle ioEvent;
    std::wstring spawnDesktopName;
    std::wstring coninPipeName;
    std::wstring conoutPipeName;
    std::wstring conerrPipeName;
};

struct winpty_spawn_config_s {
    uint64_t winptyFlags = 0;
    std::wstring appname;
    std::wstring cmdline;
    std::wstring cwd;
    std::wstring env;
};

#endif // LIBWINPTY_WINPTY_INTERNAL_H

{'repo_name': 'rprichard/winpty', 'stars': '935', 'repo_language': 'C++', 'file_name': 'common_ship.py', 'mime_type': 'text/x-python', 'hash': -2218174333201026246, 'source_dataset': 'data'}


aws s3 --region us-east-1 cp s3://parallelcluster-mnp-final-0ymk3bktyjgsbdmm/batch/job-mnp-script-1543511354863.sh /tmp/batch/job-mnp-script-1543511354863.sh; bash /tmp/batch/job-mnp-script-1543511354863.sh

aws s3 --region us-east-1 cp s3://parallelcluster-mnp-final-0ymk3bktyjgsbdmm/batch/job-array-script-fail-1543502731807.sh /tmp/batch/job-array-script-fail-1543502731807.sh; bash /tmp/batch/job-array-script-fail-1543502731807.sh

{'repo_name': 'aws/aws-parallelcluster', 'stars': '527', 'repo_language': 'Python', 'file_name': 'pcluster.config.ini', 'mime_type': 'text/plain', 'hash': -8579761049899962145, 'source_dataset': 'data'}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.fasterxml.jackson.databind.jsontype Class Hierarchy (jackson-databind 2.11.0.rc1 API)</title>
<meta name="date" content="2020-03-24">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.fasterxml.jackson.databind.jsontype

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator.Builder

com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator.NameMatcher

com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator.TypeMatcher

com.fasterxml.jackson.databind.jsontype.NamedType (implements java.io.Serializable)

com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator (implements java.io.Serializable)

com.fasterxml.jackson.databind.jsontype.DefaultBaseTypeLimitingValidator (implements java.io.Serializable)

com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator.Base (implements java.io.Serializable)

com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator (implements java.io.Serializable)

com.fasterxml.jackson.databind.jsontype.SubtypeResolver

com.fasterxml.jackson.databind.jsontype.TypeDeserializer

com.fasterxml.jackson.databind.jsontype.TypeSerializer

Interface Hierarchy

com.fasterxml.jackson.databind.jsontype.TypeIdResolver

com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder<T>

Enum Hierarchy

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator.Validity

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2008–2020 FasterXML. All rights reserved.

{'repo_name': 'FasterXML/jackson-databind', 'stars': '2575', 'repo_language': 'Java', 'file_name': 'package-use.html', 'mime_type': 'text/html', 'hash': 5144942468889556244, 'source_dataset': 'data'}


[Rank]
Dominica infra Octavam Ascensionis;;Semiduplex;;5;;ex Tempora/Pasc5-4

[Rank1960]
Dominica post Ascensionem;;Semiduplex;;5

[Rule]
ex Tempora/Pasc5-4;
Gloria
Credo

[Comment]
# Niedziela po Wniebowstąpieniu
! 2 klasy
! Szaty białe
Od chwili Wniebowstąpienia Chrystusa cechą charakterystyczną życia Kościoła jest tęsknota za Jego powrotem. Nie jest to jednak bierne oczekiwanie. Kościół, prowadzony przez Ducha Świętego, składa świadectwo o swoim Założycielu, zwłaszcza przez praktykę miłości. Modlimy się dzisiaj o wierność w służbie Bożej (kolekta) i wzmocnienie naszych dusz łaską niebieską (sekreta).

[Introitus]
!Ps 26:7; 26:8; 26:9
v. Usłysz, Panie, głos mój, którym wołam, alleluja, do Ciebie mówi serce moje, oblicze moje Cię szuka, szukam o Panie Twojego oblicza; oblicza Twego nie kryj przede mną, alleluja, alleluja.
!Ps 26:1
Pan światłością i zbawieniem moim: kogóż mam się lękać?
&Gloria
v. Usłysz, Panie, głos mój, którym wołam, alleluja, do Ciebie mówi serce moje, oblicze moje Cię szuka, szukam o Panie Twojego oblicza; oblicza Twego nie kryj przede mną, alleluja, alleluja.

[Oratio]
Wszechmogący, wieczny Boże, spraw, aby nasza wola zawsze była Ci oddana i abyśmy szczerym sercem służyli Twojemu majestatowi.
$Per Dominum

[Commemoratio Oratio]
!Przez Oktawę Wniebowstąpienia Pańskiego.
@Tempora/Pasc5-3:Oratio

[Lectio]
Czytanie z Listu świętego Piotra Apostoła.
!1 P 4:7-11
Najmilsi: Bądźcie roztropni i czuwajcie w modlitwach. A nade wszystko miejcie trwałą miłość jedni ku drugim, bo miłość osłania mnóstwo grzechów. Bądźcie gościnni jedni dla drugich bez szemrania, jako każdy z was otrzymał łaskę, tak niech usługuje jeden drugiemu, na wzór dobrych szafarzy rozlicznej łaski Bożej. Kto przemawia, niech wygłasza słowa Boże; kto posługuje, niech czyni to z przekonania, którego udziela Bóg, aby we wszystkim Bóg był uwielbiony przez Jezusa Chrystusa Pana naszego.

[Graduale]
Alleluja, alleluja
!Ps 46:9
V. Pan króluje nad narodami, Bóg zasiada na swym świętym tronie. Alleluja.
!J 14:18
V. Nie pozostawię was sierotami, odchodzę i znowu przyjdę do was, i radować się będzie serce wasze. Alleluja.

[Evangelium]
Ciąg dalszy ++ Ewangelii świętej według Jana.
!J 15:26-27; 16:1-4
!x! Duch Święty zawsze udziela Kościołowi sił potrzebnych do złożenia świadectwo Chrystusowi, zwłaszcza w chwilach prześladowań.
Onego czasu: Rzekł Jezus uczniom swoim: «Gdy przyjdzie Pocieszyciel, którego ja wam poślę od Ojca, Duch prawdy, który od Ojca pochodzi, On o mnie świadectwo dawać będzie i wy świadectwo dawać będziecie, bo ze mną od początku jesteście.
To wam powiedziałem, abyście się nie zrażali. Wyłączą was z synagog, a zbliża się godzina, że każdy, kto Was zabijać będzie, uczyni to mniemając, że Bogu wyświadcza przysługę. A to wam uczynią, bo nie znają Ojca ani Mnie. Ale to wam powiedziałem, abyście, gdy nadejdzie ich godzina, wspomnieli na to, żem ja wam powiedział».

[Offertorium]
!Ps 46:6
Wstępuje Bóg wśród radosnych okrzyków, wstępuje Pan przy dźwięku trąby, alleluja.

[Secreta]
Panie, niechaj niepokalana ofiara oczyści nas i umocni nasze dusze łaską niebieską.
$Per Dominum

[Commemoratio Secreta]
!Przez Oktawę Wniebowstąpienia Pańskiego.
@Tempora/Pasc5-3:Secreta

[Communio]
!J 17:12-13; 17:15
Ojcze, gdy byłem z nimi, strzegłem tych, których mi dałeś, alleluja: a teraz idę do Ciebie. Nie proszę, abyś ich zabrał ze świata, lecz żebyś ich zachował od złego, alleluja, alleluja.

[Postcommunio]
Nasyceni świętymi darami, prosimy Cię, Panie, abyśmy zawsze trwali w dziękczynieniu.
$Per Dominum

[Commemoratio Postcommunio]
!Przez Oktawę Wniebowstąpienia Pańskiego
@Tempora/Pasc5-3:Postcommunio

{'repo_name': 'DivinumOfficium/divinum-officium', 'stars': '123', 'repo_language': 'HTML', 'file_name': 'C5b.txt', 'mime_type': 'text/plain', 'hash': -7535138894123296332, 'source_dataset': 'data'}