text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Implementation.InlineRename;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor
{
    internal static class FSharpInlineRenameReplacementKindHelpers
    {
        public static InlineRenameReplacementKind ConvertTo(FSharpInlineRenameReplacementKind kind)
        {
            switch (kind)
            {
                case FSharpInlineRenameReplacementKind.NoConflict:
                    {
                        return InlineRenameReplacementKind.NoConflict;
                    }

                case FSharpInlineRenameReplacementKind.ResolvedReferenceConflict:
                    {
                        return InlineRenameReplacementKind.ResolvedReferenceConflict;
                    }

                case FSharpInlineRenameReplacementKind.ResolvedNonReferenceConflict:
                    {
                        return InlineRenameReplacementKind.ResolvedNonReferenceConflict;
                    }

                case FSharpInlineRenameReplacementKind.UnresolvedConflict:
                    {
                        return InlineRenameReplacementKind.UnresolvedConflict;
                    }

                case FSharpInlineRenameReplacementKind.Complexified:
                    {
                        return InlineRenameReplacementKind.Complexified;
                    }

                default:
                    {
                        throw ExceptionUtilities.UnexpectedValue(kind);
                    }
            }
        }
    }

    [Obsolete]
    internal class FSharpInlineRenameReplacementInfoLegacyWrapper : IInlineRenameReplacementInfo
    {
        private readonly IFSharpInlineRenameReplacementInfo _info;

        public FSharpInlineRenameReplacementInfoLegacyWrapper(IFSharpInlineRenameReplacementInfo info)
        {
            _info = info;
        }

        public Solution NewSolution => _info.NewSolution;

        public bool ReplacementTextValid => _info.ReplacementTextValid;

        public IEnumerable<DocumentId> DocumentIds => _info.DocumentIds;

        public IEnumerable<InlineRenameReplacement> GetReplacements(DocumentId documentId)
        {
            return _info.GetReplacements(documentId)?.Select(x =>
                new InlineRenameReplacement(FSharpInlineRenameReplacementKindHelpers.ConvertTo(x.Kind), x.OriginalSpan, x.NewSpan));
        }
    }

    [Obsolete]
    internal class FSharpInlineRenameLocationSetLegacyWrapper : IInlineRenameLocationSet
    {
        private readonly IFSharpInlineRenameLocationSet _set;
        private readonly IList<InlineRenameLocation> _locations;

        public FSharpInlineRenameLocationSetLegacyWrapper(IFSharpInlineRenameLocationSet set)
        {
            _set = set;
            _locations = set.Locations?.Select(x => new InlineRenameLocation(x.Document, x.TextSpan)).ToList();
        }

        public IList<InlineRenameLocation> Locations => _locations;

        public async Task<IInlineRenameReplacementInfo> GetReplacementsAsync(string replacementText, SymbolRenameOptions options, CancellationToken cancellationToken)
        {
            var info = await _set.GetReplacementsAsync(replacementText, optionSet: null, cancellationToken).ConfigureAwait(false);
            if (info != null)
            {
                return new FSharpInlineRenameReplacementInfoLegacyWrapper(info);
            }
            else
            {
                return null;
            }
        }
    }

    [Obsolete]
    internal class FSharpInlineRenameInfoLegacyWrapper : IInlineRenameInfo
    {
        private readonly IFSharpInlineRenameInfo _info;

        public FSharpInlineRenameInfoLegacyWrapper(IFSharpInlineRenameInfo info)
        {
            _info = info;
        }

        public bool CanRename => _info.CanRename;

        public string LocalizedErrorMessage => _info.LocalizedErrorMessage;

        public TextSpan TriggerSpan => _info.TriggerSpan;

        public bool HasOverloads => _info.HasOverloads;

        public bool MustRenameOverloads => _info.ForceRenameOverloads;

        public string DisplayName => _info.DisplayName;

        public string FullDisplayName => _info.FullDisplayName;

        public Glyph Glyph => FSharpGlyphHelpers.ConvertTo(_info.Glyph);

        // This property isn't currently supported in F# since it would involve modifying the IFSharpInlineRenameInfo interface.
        public ImmutableArray<DocumentSpan> DefinitionLocations => default;

        public async Task<IInlineRenameLocationSet> FindRenameLocationsAsync(SymbolRenameOptions options, CancellationToken cancellationToken)
        {
            var set = await _info.FindRenameLocationsAsync(optionSet: null, cancellationToken).ConfigureAwait(false);
            if (set != null)
            {
                return new FSharpInlineRenameLocationSetLegacyWrapper(set);
            }
            else
            {
                return null;
            }
        }

        public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken)
        {
            return _info.GetConflictEditSpan(new FSharpInlineRenameLocation(location.Document, location.TextSpan), replacementText, cancellationToken);
        }

        public string GetFinalSymbolName(string replacementText)
        {
            return _info.GetFinalSymbolName(replacementText);
        }

        public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken)
        {
            return _info.GetReferenceEditSpan(new FSharpInlineRenameLocation(location.Document, location.TextSpan), cancellationToken);
        }

        public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText)
        {
            return _info.TryOnAfterGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText);
        }

        public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText)
        {
            return _info.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocumentIDs, replacementText);
        }
    }

#nullable enable
    [Shared]
    [ExportLanguageService(typeof(IEditorInlineRenameService), LanguageNames.FSharp)]
    internal class FSharpEditorInlineRenameService : IEditorInlineRenameService
    {
        [Obsolete]
        private readonly IFSharpEditorInlineRenameService? _legacyService;

        private readonly FSharpInlineRenameServiceImplementation? _service;

        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public FSharpEditorInlineRenameService(
            [Import(AllowDefault = true)] IFSharpEditorInlineRenameService? legacyService,
            [Import(AllowDefault = true)] FSharpInlineRenameServiceImplementation? service)
        {
            _legacyService = legacyService;
            _service = service;
        }

        public async Task<IInlineRenameInfo> GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken)
        {
#pragma warning disable CS0612 // Type or member is obsolete
            if (_legacyService != null)
            {
                var info = await _legacyService.GetRenameInfoAsync(document, position, cancellationToken).ConfigureAwait(false);
                return (info != null) ? new FSharpInlineRenameInfoLegacyWrapper(info) : AbstractEditorInlineRenameService.DefaultFailureInfo;
            }
#pragma warning restore CS0612 // Type or member is obsolete

            if (_service != null)
            {
                return await _service.GetRenameInfoAsync(document, position, cancellationToken).ConfigureAwait(false) ?? AbstractEditorInlineRenameService.DefaultFailureInfo;
            }

            return AbstractEditorInlineRenameService.DefaultFailureInfo;
        }
    }
}


text:
import React from 'react'
import PT from 'prop-types'
import { Link } from 'react-router-dom'
import { css } from 'emotion'

import examplesIndex from '-/examples-index'

const tagStyle = css`
  font-size: 0.7em;
  color: #888;
  background-color: #eee;
  padding: 0 5px;
  height: 20px;
  border: 1px solid #bbb;
  border-radius: 5px;
  margin-left: 1em;
  cursor: pointer;
  display: inline-block;
  opacity: 0.5;
  transition: all 0.25s;

  &:hover {
    opacity: 1;
  }

  &.threejs {
    background-color: #ddeeff;
    border-color: #bbccff;
  }
  &.webvr {
    background-color: #ffe6e6;
    border-color: #ddc6c6;
  }
  &.gpgpu {
    background-color: #e6ffe6;
    border-color: #c6ddc6;
  }
`

const Tags = ({ tags, setFilter }) => {
  return (
    <>
      {tags.split(',').map((tag) => (
        <div
          key={tag}
          className={`${tagStyle} ${tag} tag`}
          onClick={() => setFilter(tag)}
        >
          {tag}

      ))}
    </>
  )
}

Tags.propTypes = {
  tags: PT.string,
  setFilter: PT.func,
}

const menuItemStyle = css`
  font-size: 1em;
  margin-bottom: 0.4em;
  display: flex !important;
`

const MenuItem = ({ title, to, tags, setFilter }) => (
  <div className={`item ${menuItemStyle}`}>
    <Link to={`/examples/${to}`}>{title}</Link>
    <Tags tags={tags} setFilter={setFilter} />

)

MenuItem.propTypes = {
  title: PT.string,
  to: PT.string,
  tags: PT.string,
  setFilter: PT.func,
}

const Menu = () => {
  const [filter, setFilter] = React.useState('')

  const examples = examplesIndex.filter(
    (x) =>
      x.title.toLowerCase().match(new RegExp(filter.toLowerCase())) ||
      x.tags.toLowerCase().match(new RegExp(filter.toLowerCase()))
  )

  const className = `ui input fluid transparent small ${
    filter !== '' ? 'left icon' : ''
  }`

  return (
    <>

        {filter !== '' && (
          <button
            onClick={() => setFilter('')}
            className="ui button basic"
            style={{ boxShadow: 'none', padding: 0, margin: 0 }}
          >

          </button>
        )}
        <input
          type="text"
          placeholder="Search..."
          value={filter}
          onChange={(event) => setFilter(event.target.value)}
        />

        {examples.map(({ title, slug, tags }) => {
          return (
            <MenuItem
              key={slug}
              title={title}
              to={slug}
              tags={tags}
              setFilter={setFilter}
            />
          )
        })}

    </>
  )
}

export default React.memo(Menu)

redpajama_set_name: RedPajamaGithub


text:
This is a simple node.js server to allow access to the Twitter API.

Make sure that you get the consumer key, consumer secret, Access Token and Access Token Secret before running this.

Also ensure that you have installed the twit library using `npm install twit`


text:
                        Outline Mail is a project by Matt Harris

                        View this email in your browser | Unsubscribe


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="reopen">Ailagor</string>
  <string name="className">Enw\'r dosbarth</string>
  <string name="passwordX">Cyfrinair: %s</string>
  <string name="realName">Enw go iawn</string>
  <string name="welcomeToClass">Croeso i\'r dosbarth: %s
Dyma\'r ddolen i gael mynediad.</string>
  <string name="lastActiveDate">Gweithredol</string>
  <string name="teachers">Athrawon</string>
  <string name="students">Myfyrwyr</string>
  <string name="na">N/A</string>
  <string name="news">Newyddion y dosbarth</string>
  <string name="editNews">Addasu\'r newyddion</string>
</resources>


text:
{-# LANGUAGE RecordWildCards #-}
module Main (main) where

import           Control.Applicative    hiding (many)
import           Control.Exception
import           Control.Monad
import           Data.Char
import           Data.Maybe
import           Prelude                hiding (negate)
import           System.Environment     (getArgs)
import           System.FilePath
import           System.Posix.Directory
import           System.Posix.Files
import           Text.Parsec            hiding ((<|>))
import qualified Data.Map               as M

type Variables = M.Map String String

type Parser a = Parsec String Variables a

data Positivity
    = Positive
    | Negative
    deriving (Show)

applyPositivity :: Positivity -> Bool -> Bool
applyPositivity Positive = id
applyPositivity Negative = not

data FileInfo
    = FileInfo {
        fiName :: FilePath
      , fiPath :: FilePath
      , fiStatus :: FileStatus
      }

type Test = Positivity -> FileInfo -> TestResult

data TestResult
    = TestResult {
        trAction :: Bool
      , trDescend :: Maybe Test
      }

allContents :: Test
allContents Positive _fi = TestResult { trAction = True, trDescend = Just allContents }
allContents Negative _fi = TestResult { trAction = False, trDescend = Nothing }

noContents :: Test
noContents = negate allContents

leafTest :: (FileInfo -> Bool) -> Test
leafTest tst = t
    where t Positive fi = case tst fi of
                             True -> TestResult { trAction = True, trDescend = Just t }
                             False -> TestResult { trAction = False, trDescend = Just t }
          t Negative fi = case tst fi of
                             True -> TestResult { trAction = False, trDescend = Just nt }
                             False -> TestResult { trAction = True, trDescend = Just nt }
          nt = negate t

-- TODO: use glob
testName :: FilePath -> Test
testName x = leafTest $ \FileInfo{fiName=n} -> n == x

negate :: Test -> Test
negate t Positive = t Negative
negate t Negative = t Positive

cut :: Test -> Test
cut t Positive fi = case t Positive fi of
                      TestResult{trAction=True} -> TestResult{trAction=True, trDescend=Nothing}
                      TestResult{trAction=False,trDescend=d} -> TestResult{trAction=False, trDescend=fmap cut d}
cut t Negative fi = case t Positive fi of
                      TestResult{trAction=True} -> TestResult{trAction=False, trDescend=Just allContents}
                      TestResult{trAction=False,trDescend=d} -> TestResult{trAction=True, trDescend=fmap (negate . cut) d}

intersection :: Test -> Test -> Test
intersection a b Positive = \fi -> let TestResult{trAction=a1,trDescend=d1} = a Positive fi
                                       TestResult{trAction=a2,trDescend=d2} = b Positive fi
                                   in TestResult{trAction=a1&&a2, trDescend=liftM2 intersection d1 d2}
intersection a b Negative = (negate a `union` negate b) Positive

-- lolwut
compose :: Test -> Test -> Test
compose = intersection

union :: Test -> Test -> Test
union a b Positive = \fi -> let TestResult{trAction=a1,trDescend=d1} = a Positive fi
                                TestResult{trAction=a2,trDescend=d2} = b Positive fi
                            in TestResult{
                                     trAction  = a1 || a2
                                   , trDescend = case (d1,d2) of
                                                   (Nothing,Nothing) -> Nothing
                                                   (_,Nothing) -> d1
                                                   (Nothing,_) -> d2
                                                   (Just x, Just y) -> Just (x `union` y)
                                   }
union a b Negative = (negate a `intersection` negate b) Positive

difference :: Test -> Test -> Test
difference a b = a `intersection` negate b

makeFileInfo :: FilePath -> IO FileInfo
makeFileInfo path = makeFileInfo' (takeFileName path) path

makeFileInfo' :: FilePath -> FilePath -> IO FileInfo
makeFileInfo' name path = do
  stat <- getFileStatus path
  return FileInfo{fiName=name, fiPath=path, fiStatus=stat}

traverse :: (FilePath -> IO ()) -> Test -> FileInfo -> IO ()
traverse action test fi@FileInfo{fiPath=path}
    = do let TestResult{..} = test Positive fi
         when trAction $ action path
         when (isDirectory $ fiStatus fi) $
              case trDescend of
                Just nextTest -> bracket (openDirStream path) closeDirStream (go nextTest)
                Nothing -> return ()
    where
      go nextTest stream = do
        name <- readDirStream stream
        case name of
          [] -> return ()
          _ -> do case name of
                    "." -> return ()
                    ".." -> return ()
                    _ -> traverse action nextTest =<< makeFileInfo' name (path </> name)
                  go nextTest stream

testWithNegation :: Test -> FilePath -> IO ()
testWithNegation t dir = do
  fi <- makeFileInfo dir
  putStrLn "Positive:"
  traverse putStrLn t fi
  putStrLn "\nNegative:"
  traverse putStrLn (negate t) fi

quote :: Parser String
quote = xquote '"' <|> xquote '\''
    where xquote q = between (char q) (char q) innerQuote <?> "quote <" ++ q : ">"
              where innerQuote = concat <$> many ((escaped <|> interpolated <|> normal) <?> "text")
                    escaped = do char '~'
                                 c <- oneOf "$~'\"0n"
                                 return $ case c of
                                            '0' -> "\0"
                                            'n' -> "\n"
                                            _   -> [c]
                    normal = (:[]) <$> noneOf [q]
                    interpolated = do char '$'
                                      name <- between (char '{') (char '}') varname <|> varname
                                      findVar name

bareword :: Parser String
bareword = many1 (oneOf $ "./-" ++ filter (\c -> isLetter c || isNumber c) [minBound..maxBound]) <?> "bareword"

variable :: Parser String
variable = do char '$'
              findVar =<< varname

findVar :: String -> Parser String
findVar name = do vars <- getState
                  case M.lookup name vars of
                    Nothing -> fail ("Unknown variable " ++ name)
                    Just x -> return x

varname :: Parser String
varname = (:) <$> oneOf ('_' : ['A'..'Z']++['a'..'z']) <*> many (oneOf $ '_' : ['A'..'Z']++['a'..'z']++['0'..'9'])

word :: Parser String
word = (variable <|> quote <|> bareword) <* spaces

expression :: Parser Test
expression = chainl factor expop allContents
    where
      expop = (<* spaces) $ union <$ char '+'
                            <|> intersection <$ char '&'
                            <|> difference <$ oneOf "%\\"
      factor = name <|> between (char '(' <* spaces) (char ')' <* spaces) expression
      name = testName <$> word

main :: IO ()
main = do
  args <- getArgs
  let dir = case args of
              [] -> "."
              (x:_) -> x
  testWithNegation (testName "x" `difference` cut (testName "x")) dir


text:
assertEquals(Infinity, Math.min());
assertEquals(1, Math.min(1));
assertEquals(1, Math.min(1, 2));
assertEquals(1, Math.min(2, 1));
assertEquals(1, Math.min(1, 2, 3));
assertEquals(1, Math.min(3, 2, 1));
assertEquals(1, Math.min(2, 3, 1));
assertEquals(1.1, Math.min(1.1, 2.2, 3.3));
assertEquals(1.1, Math.min(3.3, 2.2, 1.1));
assertEquals(1.1, Math.min(2.2, 3.3, 1.1));

// Prepare a non-Smi zero value.
function returnsNonSmi(){ return 0.25; }
var ZERO = (function() {
  var z;
  // We have to have a loop here because the first time we get a Smi from the
  // runtime system.  After a while the binary op IC settles down and we get
  // a non-Smi from the generated code.
  for (var i = 0; i < 10; i++) {
    z = returnsNonSmi() - returnsNonSmi();
  }
  return z;
})();
assertEquals(0, ZERO);
assertEquals(Infinity, 1/ZERO);
assertEquals(-Infinity, 1/-ZERO);
assertFalse(%_IsSmi(ZERO));
assertFalse(%_IsSmi(-ZERO));

var o = {};
o.valueOf = function() { return 1; };
assertEquals(1, Math.min(2, 3, '1'));
assertEquals(1, Math.min(3, o, 2));
assertEquals(1, Math.min(o, 2));
assertEquals(-Infinity, Infinity / Math.min(-0, +0));
assertEquals(-Infinity, Infinity / Math.min(+0, -0));
assertEquals(-Infinity, Infinity / Math.min(+0, -0, 1));
assertEquals(-Infinity, Infinity / Math.min(-0, ZERO));
assertEquals(-Infinity, Infinity / Math.min(ZERO, -0));
assertEquals(-Infinity, Infinity / Math.min(ZERO, -0, 1));
assertEquals(-1, Math.min(+0, -0, -1));
assertEquals(-1, Math.min(-1, +0, -0));
assertEquals(-1, Math.min(+0, -1, -0));
assertEquals(-1, Math.min(-0, -1, +0));
assertNaN(Math.min('oxen'));
assertNaN(Math.min('oxen', 1));
assertNaN(Math.min(1, 'oxen'));

// Test Math.max().

assertEquals(Number.NEGATIVE_INFINITY, Math.max());
assertEquals(1, Math.max(1));
assertEquals(2, Math.max(1, 2));
assertEquals(2, Math.max(2, 1));
assertEquals(3, Math.max(1, 2, 3));
assertEquals(3, Math.max(3, 2, 1));
assertEquals(3, Math.max(2, 3, 1));
assertEquals(3.3, Math.max(1.1, 2.2, 3.3));
assertEquals(3.3, Math.max(3.3, 2.2, 1.1));
assertEquals(3.3, Math.max(2.2, 3.3, 1.1));

var o = {};
o.valueOf = function() { return 3; };
assertEquals(3, Math.max(2, '3', 1));
assertEquals(3, Math.max(1, o, 2));
assertEquals(3, Math.max(o, 1));
assertEquals(Infinity, Infinity / Math.max(-0, +0));
assertEquals(Infinity, Infinity / Math.max(+0, -0));
assertEquals(Infinity, Infinity / Math.max(+0, -0, -1));
assertEquals(Infinity, Infinity / Math.max(-0, ZERO));
assertEquals(Infinity, Infinity / Math.max(ZERO, -0));
assertEquals(Infinity, Infinity / Math.max(ZERO, -0, -1));
assertEquals(1, Math.max(+0, -0, +1));
assertEquals(1, Math.max(+1, +0, -0));
assertEquals(1, Math.max(+0, +1, -0));
assertEquals(1, Math.max(-0, +1, +0));
assertNaN(Math.max('oxen'));
assertNaN(Math.max('oxen', 1));
assertNaN(Math.max(1, 'oxen'));

assertEquals(Infinity, 1/Math.max(ZERO, -0));
assertEquals(Infinity, 1/Math.max(-0, ZERO));


text:
MWC1616-PRNG-CPP
================

Super-Fast MWC1616 Pseudo-Random Number Generator for Intel/AMD Processors (using SSE or SSE4 instruction set)

Should be compiled with Intel compiler and optimization flags

-xCORE-AVX-I -O3 -ipo

for example: icpc -xCORE-AVX-I -O3 -ipo -g -o main example.cpp random.cpp


text:
import {
    Node,
    isInstanceOf,
} from 'j0';
export default function isNode(x) {
    return isInstanceOf(x, Node);
}


text:
<?php
require 'dbconnect.php';

if(!empty($_POST["pid"]))
{
$chk = 0;
$pid=mysqli_real_escape_string($con,$_POST['pid']);

$query=mysqli_query($con,"SELECT * FROM photo WHERE pid='".$pid."'");
while($row = mysqli_fetch_array($query))
{
$pic=$row['pcode'];
}
$query1=mysqli_query($con,"SELECT * FROM assign WHERE pid='".$pid."'");
while($row1 = mysqli_fetch_array($query1))
{
$cid=$row1['cid'];
}
unlink("uploads/photos/".$pic);
unlink("uploads/photos/thumbs/".$pic);
mysqli_query($con,"DELETE FROM photo WHERE pid=".$pid."" );
mysqli_query($con,"DELETE FROM assign WHERE pid=".$pid."" );

$query2=mysqli_query($con,"SELECT * FROM assign WHERE cid='".$cid."' AND pid != 0");
while($row2 = mysqli_fetch_array($query2))
{
$chk = 1;
}

if($chk == 0)
echo "end";
else
echo "done";
}
else
echo "<script>window.location.assign('../?p=error6');</script>";

mysqli_close($con);
?>


text:
package Main;

import GUI.GUI;

/**
 *
 * @author Aleksandr Šmailov
 */
public class Main {
    private static GUI gui;

    public Main(){
        // Create window and set it visible.
        gui = new GUI();
        gui.setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main();
    }

}


text:
package com.indignado.games;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.ilargia.games.egdx.EGEventBus;
import com.ilargia.games.egdx.api.managers.ProfileManager;
import com.ilargia.games.egdx.base.managers.BaseAssetsManager;
import com.ilargia.games.egdx.base.managers.BasePreferencesManager;
import com.ilargia.games.egdx.base.managers.BaseProfileManager;
import com.indignado.games.states.options.Profile;
import com.indignado.games.states.splash.SplashState;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import net.engio.mbassy.bus.MBassador;
import net.engio.mbassy.bus.error.IPublicationErrorHandler;
import net.engio.mbassy.bus.error.PublicationError;

public class SuperMariano implements ApplicationListener {
    public static final int SCREEN_WIDTH = 800;
    public static final int SCREEN_HEIGHT = 480;
    private static SMGame game;

    @Override
    public void create() {
        AssetManager assetsManager = new AssetManager();
        BasePreferencesManager preferencesManager = new BasePreferencesManager();
        SMEngine engine = new SMEngine();
        ProfileManager profileManager = new BaseProfileManager(new Profile(new ObjectArrayList<>()), preferencesManager);
        engine.addManager(preferencesManager);
        engine.addManager(profileManager);
        engine.addManager(new BaseAssetsManager(assetsManager, preferencesManager));
        game = new SMGame(engine, new EGEventBus(new MBassador(new IPublicationErrorHandler() {
            @Override
            public void handleError(PublicationError error) {
                Gdx.app.error("BusException", error.toString());
            }
        })));
        game.init();
        game.pushState(new SplashState(engine));

    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void render() {
        game.update(Gdx.graphics.getDeltaTime());
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void dispose() {

    }
}


text:
namespace blink {

namespace {

// Helper class that streams all the bytes from a vector of RawData RefPtrs to
// a mojo data pipe. Instances will delete themselves when all data has been
// written, or when the data pipe is disconnected.
class BlobBytesStreamer {
  USING_FAST_MALLOC(BlobBytesStreamer);

 public:
  BlobBytesStreamer(Vector<scoped_refptr<RawData>> data,
                    mojo::ScopedDataPipeProducerHandle pipe)
      : data_(std::move(data)),
        pipe_(std::move(pipe)),
        watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::AUTOMATIC) {
    watcher_.Watch(pipe_.get(), MOJO_HANDLE_SIGNAL_WRITABLE,
                   MOJO_WATCH_CONDITION_SATISFIED,
                   WTF::BindRepeating(&BlobBytesStreamer::OnWritable,
                                      WTF::Unretained(this)));
  }

  void OnWritable(MojoResult result, const mojo::HandleSignalsState& state) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

    if (result == MOJO_RESULT_CANCELLED ||
        result == MOJO_RESULT_FAILED_PRECONDITION) {
      delete this;
      return;
    }
    DCHECK_EQ(result, MOJO_RESULT_OK);

    while (true) {
      uint32_t num_bytes = base::saturated_cast<uint32_t>(
          data_[current_item_]->length() - current_item_offset_);
      MojoResult write_result =
          pipe_->WriteData(data_[current_item_]->data() + current_item_offset_,
                           &num_bytes, MOJO_WRITE_DATA_FLAG_NONE);
      if (write_result == MOJO_RESULT_OK) {
        current_item_offset_ += num_bytes;
        if (current_item_offset_ >= data_[current_item_]->length()) {
          data_[current_item_] = nullptr;
          current_item_++;
          current_item_offset_ = 0;
          if (current_item_ >= data_.size()) {
            // All items were sent completely.
            delete this;
            return;
          }
        }
      } else if (write_result == MOJO_RESULT_SHOULD_WAIT) {
        break;
      } else {
        // Writing failed. This isn't necessarily bad, as this could just mean
        // the browser no longer needs the data for this blob. So just delete
        // this as sending data is definitely finished.
        delete this;
        return;
      }
    }
  }

 private:
  // The index of the item currently being written.
  wtf_size_t current_item_ GUARDED_BY_CONTEXT(sequence_checker_) = 0;
  // The offset into the current item of the first byte not yet written to the
  // data pipe.
  size_t current_item_offset_ GUARDED_BY_CONTEXT(sequence_checker_) = 0;
  // The data being written.
  Vector<scoped_refptr<RawData>> data_ GUARDED_BY_CONTEXT(sequence_checker_);

  mojo::ScopedDataPipeProducerHandle pipe_
      GUARDED_BY_CONTEXT(sequence_checker_);
  mojo::SimpleWatcher watcher_ GUARDED_BY_CONTEXT(sequence_checker_);

  SEQUENCE_CHECKER(sequence_checker_);
};

// This keeps the process alive while blobs are being transferred.
void IncreaseChildProcessRefCount() {
  if (!WTF::IsMainThread()) {
    PostCrossThreadTask(*Thread::MainThread()->GetDeprecatedTaskRunner(),
                        FROM_HERE,
                        CrossThreadBindOnce(&IncreaseChildProcessRefCount));
    return;
  }
  Platform::Current()->SuddenTerminationChanged(false);
}

void DecreaseChildProcessRefCount() {
  if (!WTF::IsMainThread()) {
    PostCrossThreadTask(*Thread::MainThread()->GetDeprecatedTaskRunner(),
                        FROM_HERE,
                        CrossThreadBindOnce(&DecreaseChildProcessRefCount));
    return;
  }
  Platform::Current()->SuddenTerminationChanged(true);
}

}  // namespace

constexpr size_t BlobBytesProvider::kMaxConsolidatedItemSizeInBytes;

BlobBytesProvider::BlobBytesProvider() {
  IncreaseChildProcessRefCount();
}

BlobBytesProvider::~BlobBytesProvider() {
  DecreaseChildProcessRefCount();
}

void BlobBytesProvider::AppendData(scoped_refptr<RawData> data) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!data_.IsEmpty()) {
    uint64_t last_offset = offsets_.IsEmpty() ? 0 : offsets_.back();
    offsets_.push_back(last_offset + data_.back()->length());
  }
  data_.push_back(std::move(data));
}

void BlobBytesProvider::AppendData(base::span<const char> data) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (data_.IsEmpty() ||
      data_.back()->length() + data.size() > kMaxConsolidatedItemSizeInBytes) {
    AppendData(RawData::Create());
  }
  data_.back()->MutableData()->Append(
      data.data(), base::checked_cast<wtf_size_t>(data.size()));
}

// static
void BlobBytesProvider::Bind(
    std::unique_ptr<BlobBytesProvider> provider,
    mojo::PendingReceiver<mojom::blink::BytesProvider> receiver) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(provider->sequence_checker_);
  DETACH_FROM_SEQUENCE(provider->sequence_checker_);

  auto task_runner = base::ThreadPool::CreateSequencedTaskRunner(
      {base::MayBlock(), base::TaskPriority::USER_VISIBLE});
  // TODO(mek): Consider binding BytesProvider on the IPC thread instead, only
  // using the MayBlock taskrunner for actual file operations.
  PostCrossThreadTask(
      *task_runner, FROM_HERE,
      CrossThreadBindOnce(
          [](std::unique_ptr<BlobBytesProvider> provider,
             mojo::PendingReceiver<mojom::blink::BytesProvider> receiver) {
            DCHECK_CALLED_ON_VALID_SEQUENCE(provider->sequence_checker_);
            mojo::MakeSelfOwnedReceiver(std::move(provider),
                                        std::move(receiver));
          },
          std::move(provider), std::move(receiver)));
}

void BlobBytesProvider::RequestAsReply(RequestAsReplyCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // TODO(mek): Once better metrics are created we could experiment with ways
  // to reduce the number of copies of data that are made here.
  Vector<uint8_t> result;
  for (const auto& d : data_)
    result.Append(d->data(), base::checked_cast<wtf_size_t>(d->length()));
  std::move(callback).Run(result);
}

void BlobBytesProvider::RequestAsStream(
    mojo::ScopedDataPipeProducerHandle pipe) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // BlobBytesStreamer will self delete when done.
  new BlobBytesStreamer(std::move(data_), std::move(pipe));
}

void BlobBytesProvider::RequestAsFile(uint64_t source_offset,
                                      uint64_t source_size,
                                      base::File file,
                                      uint64_t file_offset,
                                      RequestAsFileCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!file.IsValid()) {
    std::move(callback).Run(absl::nullopt);
    return;
  }

  int64_t seek_distance = file.Seek(base::File::FROM_BEGIN,
                                    base::checked_cast<int64_t>(file_offset));
  bool seek_failed = seek_distance < 0;
  if (seek_failed) {
    std::move(callback).Run(absl::nullopt);
    return;
  }

  // Find first data item that should be read from (by finding the first offset
  // that starts after the offset we want to start reading from).
  wtf_size_t data_index = static_cast<wtf_size_t>(
      std::upper_bound(offsets_.begin(), offsets_.end(), source_offset) -
      offsets_.begin());

  // Offset of the current data chunk in the overall stream provided by this
  // provider.
  uint64_t offset = data_index == 0 ? 0 : offsets_[data_index - 1];
  for (; data_index < data_.size(); ++data_index) {
    const auto& data = data_[data_index];

    // We're done if the beginning of the current chunk is past the end of the
    // data to write.
    if (offset >= source_offset + source_size)
      break;

    // Offset within this chunk where writing needs to start from.
    uint64_t data_offset = offset > source_offset ? 0 : source_offset - offset;
    uint64_t data_size =
        std::min(data->length() - data_offset,
                 source_offset + source_size - offset - data_offset);
    size_t written = 0;
    while (written < data_size) {
      int writing_size = base::saturated_cast<int>(data_size - written);
      int actual_written = file.WriteAtCurrentPos(
          data->data() + data_offset + written, writing_size);
      bool write_failed = actual_written < 0;
      if (write_failed) {
        std::move(callback).Run(absl::nullopt);
        return;
      }
      written += actual_written;
    }

    offset += data->length();
  }

  if (!file.Flush()) {
    std::move(callback).Run(absl::nullopt);
    return;
  }
  base::File::Info info;
  if (!file.GetInfo(&info)) {
    std::move(callback).Run(absl::nullopt);
    return;
  }
  std::move(callback).Run(info.last_modified);
}

}  // namespace blink


text:
"""-------------------------------------------------
Satay Game Engine Copyright (C) 2013 Andy Brennan

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.

Satay on GitHub: https://github.com/Valdez42/Satay

 Game.py --
   Game module for use in game creation.
   Here, game settings are set, commands are registered,
   and the game is actually played.
-------------------------------------------------"""

from ..Base import *
from ..Exceptions import *
from Functions import *
import cPickle

class Map(EntBase):
    """Class representing map entity (places the player and items inhabit)"""
    def __init__(self, **props):
        if "itemlist" not in props:
            raise EntityError("Missing itemlist in map!")
        super(Map, self).__init__(**props)

class Item(EntBase):
    """Class representing item entity (things the player interacts with)"""
    def __init__(self, **props):
        super(Item, self).__init__(**props)

class NPC(EntBase):
    """Class representing NPCs (non player characters)."""
    def __init__(self, **props):
        if "dialog" not in props:
            raise EntityError("Missing dialog map in NPC!")
        if not isinstance(props["dialog"], DialogMap):
            raise EntityError("Dialog map must be of type 'DialogMap'!")
        super(NPC, self).__init__(**props)

class BaseGame(object):
    """Base class for any kind of game."""
    def __init__(self, settings, funcCls=BaseGameFuncs):
        if "title" not in settings:
            settings["title"] = "Untitled"
        if "author" not in settings:
            settings["author"] = "Anonymous"
        if "objects" not in settings:
            raise SettingsError("No maps/items defined!")
        if "start" not in settings:
            raise SettingsError("No startmap defined!")
        if "items" in settings:
            self.inventory = settings["items"]
        else:
            self.inventory = NumeratedList()
        if "commands" not in settings:
            raise SettingsError("No commands defined for game!")
        if "variables" in settings:
            if type(settings["variables"]) != dict:
                raise SettingsError("Game variables must be a dictionary!")
            self.variables = settings["variables"]
        else:
            self.variables = dict()
        self.title = settings["title"]
        self.author = settings["author"]
        self.__objects__ =  self.__setids__(settings["objects"])
        self.__commands__ = settings["commands"]
        self.curmap = settings['start']
        self.caller = funcCls(self)
        self.history = History.New(self.__objects__, self.__commands__)
        super(BaseGame, self).__init__()

    def __getattr__(self, attr):
        return self.caller.__getattribute__(attr)

    def __setids__(self, objs):
        newObjs = {}
        for objID, obj in objs.items():
            obj.id = objID
            newObjs[EntRef(objID)] = obj
        return newObjs

    def __lOpen__(self, fname):
        """Unpickle loaddata from fname as file."""
        try:
            f = open(fname, 'r')
        except IOError:
            raise LoadGameError("Could not open file!")
        else:
            loaddata = cPickle.load(f)
        finally:
            f.close()
        return loaddata

    def __sOpen__(self, fname, savedata):
        """Open fname as file and pickle savedata."""
        try:
            f = open(fname, 'w')
        except IOError:
            raise SaveGameError("Could not create save file!")
        else:
            # Dump with protocol 2 (for efficiency)
            cPickle.dump(savedata, f)
        finally:
            f.close()

    def Save(self, fname, savedata={}):
        """Save a game."""
        savedata["inventory"] = self.inventory
        savedata["curmap"] = self.curmap
        savedata["variables"] = self.variables
        savedata["history"] = self.history.Dump()
        itemlists = {}
        for ID, obj in self.__objects__.items():
            if isinstance(obj, Map):
                itemlists[ID] = list(obj.itemlist())
        savedata["itemlists"] = itemlists
        self.__sOpen__(fname, savedata)

    def Load(self, fname, loaddata=None):
        """Load a game."""
        if loaddata is None:
            loaddata = self.__lOpen__(fname)

        if len(set(["inventory", "curmap", "itemlists", "history", "variables"]) - set(loaddata)) != 0:
            raise LoadGameError("Missing data in savefile!")

        for ID, itemlist in loaddata["itemlists"].items():
            self.__objects__[ID].itemlist[''] = NumeratedList.FromList(itemlist)
        self.curmap = loaddata["curmap"]
        self.inventory = loaddata["inventory"]
        self.variables = loaddata["variables"]
        self.history = History.Load(loaddata["history"])

    def GetCurmap(self):
        return self.__objects__[self.curmap]

    def CheckScope(self, *ents):
        """Check if an entity is in the current scope (curmap or inventory)"""
        ents = self.__toref__(*ents, forcelist=True)
        return all([r in self.inventory or r in self.GetCurmap().itemlist() for r in ents])

    def CheckMapScope(self, *ents):
        """Check if entities are in the curmap scope."""
        ents = self.__toref__(*ents, forcelist=True)
        return all([r in self.GetCurmap().itemlist() for r in ents])

    def CheckInvScope(self, *ents):
        """Check if entities are in the inventory scope."""
        ents = self.__toref__(*ents, forcelist=True)
        return all([r in self.inventory for r in ents])


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

namespace DatabasePerformance
{
    class SQLiteFileConnectionProvider : IConnectionProvider
    {
        private string databasePath;

        public SQLiteFileConnectionProvider(string databasePath)
        {
            this.databasePath = databasePath;
        }

        public string GetConnectionName()
        {
            return "Data Source=" + this.databasePath + ";FailIfMissing=True;";
        }

        public string GetProviderName()
        {
            return "System.Data.SQLite";
        }
    }
}


text:
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using mel = Microsoft.Extensions.Logging;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;

namespace Google.Ads.GoogleAds.V11.Services
{
    /// Settings for <see cref="CustomerManagerLinkServiceClient"/> instances.
    public sealed partial class CustomerManagerLinkServiceSettings : gaxgrpc::ServiceSettingsBase
    {
        /// Get a new instance of the default <see cref="CustomerManagerLinkServiceSettings"/>.
        /// <returns>A new instance of the default <see cref="CustomerManagerLinkServiceSettings"/>.</returns>
        public static CustomerManagerLinkServiceSettings GetDefault() => new CustomerManagerLinkServiceSettings();

        ///
        /// Constructs a new <see cref="CustomerManagerLinkServiceSettings"/> object with default settings.
        ///
        public CustomerManagerLinkServiceSettings()
        {
        }

        private CustomerManagerLinkServiceSettings(CustomerManagerLinkServiceSettings existing) : base(existing)
        {
            gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
            MutateCustomerManagerLinkSettings = existing.MutateCustomerManagerLinkSettings;
            MoveManagerLinkSettings = existing.MoveManagerLinkSettings;
            OnCopy(existing);
        }

        partial void OnCopy(CustomerManagerLinkServiceSettings existing);

        ///
        /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
        /// <c>CustomerManagerLinkServiceClient.MutateCustomerManagerLink</c> and
        /// <c>CustomerManagerLinkServiceClient.MutateCustomerManagerLinkAsync</c>.
        ///
        /// <remarks>
        /// <list type="bullet">
        /// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
        /// <item><description>Retry delay multiplier: 1.3</description></item>
        /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
        /// <item><description>Maximum attempts: Unlimited</description></item>
        /// <item>
        /// <description>
        /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
        /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
        /// </description>
        /// </item>
        /// <item><description>Timeout: 14400 seconds.</description></item>
        /// </list>
        /// </remarks>
        public gaxgrpc::CallSettings MutateCustomerManagerLinkSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(14400000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));

        ///
        /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
        /// <c>CustomerManagerLinkServiceClient.MoveManagerLink</c> and
        /// <c>CustomerManagerLinkServiceClient.MoveManagerLinkAsync</c>.
        ///
        /// <remarks>
        /// <list type="bullet">
        /// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
        /// <item><description>Retry delay multiplier: 1.3</description></item>
        /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
        /// <item><description>Maximum attempts: Unlimited</description></item>
        /// <item>
        /// <description>
        /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
        /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
        /// </description>
        /// </item>
        /// <item><description>Timeout: 14400 seconds.</description></item>
        /// </list>
        /// </remarks>
        public gaxgrpc::CallSettings MoveManagerLinkSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(14400000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));

        /// Creates a deep clone of this object, with all the same property values.
        /// <returns>A deep clone of this <see cref="CustomerManagerLinkServiceSettings"/> object.</returns>
        public CustomerManagerLinkServiceSettings Clone() => new CustomerManagerLinkServiceSettings(this);
    }

    ///
    /// Builder class for <see cref="CustomerManagerLinkServiceClient"/> to provide simple configuration of credentials,
    /// endpoint etc.
    ///
    internal sealed partial class CustomerManagerLinkServiceClientBuilder : gaxgrpc::ClientBuilderBase<CustomerManagerLinkServiceClient>
    {
        /// The settings to use for RPCs, or <c>null</c> for the default settings.
        public CustomerManagerLinkServiceSettings Settings { get; set; }

        /// Creates a new builder with default settings.
        public CustomerManagerLinkServiceClientBuilder() : base(CustomerManagerLinkServiceClient.ServiceMetadata)
        {
        }

        partial void InterceptBuild(ref CustomerManagerLinkServiceClient client);

        partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CustomerManagerLinkServiceClient> task);

        /// Builds the resulting client.
        public override CustomerManagerLinkServiceClient Build()
        {
            CustomerManagerLinkServiceClient client = null;
            InterceptBuild(ref client);
            return client ?? BuildImpl();
        }

        /// Builds the resulting client asynchronously.
        public override stt::Task<CustomerManagerLinkServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
        {
            stt::Task<CustomerManagerLinkServiceClient> task = null;
            InterceptBuildAsync(cancellationToken, ref task);
            return task ?? BuildAsyncImpl(cancellationToken);
        }

        private CustomerManagerLinkServiceClient BuildImpl()
        {
            Validate();
            grpccore::CallInvoker callInvoker = CreateCallInvoker();
            return CustomerManagerLinkServiceClient.Create(callInvoker, Settings, Logger);
        }

        private async stt::Task<CustomerManagerLinkServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
        {
            Validate();
            grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
            return CustomerManagerLinkServiceClient.Create(callInvoker, Settings, Logger);
        }

        /// Returns the channel pool to use when no other options are specified.
        protected override gaxgrpc::ChannelPool GetChannelPool() => CustomerManagerLinkServiceClient.ChannelPool;
    }

    /// CustomerManagerLinkService client wrapper, for convenient use.
    /// <remarks>
    /// Service to manage customer-manager links.
    /// </remarks>
    public abstract partial class CustomerManagerLinkServiceClient
    {
        ///
        /// The default endpoint for the CustomerManagerLinkService service, which is a host of
        /// "googleads.googleapis.com" and a port of 443.
        ///
        public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";

        /// The default CustomerManagerLinkService scopes.
        /// <remarks>
        /// The default CustomerManagerLinkService scopes are:
        /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
        /// </remarks>
        public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
        {
            "https://www.googleapis.com/auth/adwords",
        });

        /// The service metadata associated with this client type.
        public static gaxgrpc::ServiceMetadata ServiceMetadata { get; } = new gaxgrpc::ServiceMetadata(CustomerManagerLinkService.Descriptor, DefaultEndpoint, DefaultScopes, true, gax::ApiTransports.Grpc, PackageApiMetadata.ApiMetadata);

        internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(ServiceMetadata);

        ///
        /// Asynchronously creates a <see cref="CustomerManagerLinkServiceClient"/> using the default credentials,
        /// endpoint and settings. To specify custom credentials or other settings, use
        /// <see cref="CustomerManagerLinkServiceClientBuilder"/>.
        ///
        /// <param name="cancellationToken">
        /// The <see cref="st::CancellationToken"/> to use while creating the client.
        /// </param>
        /// <returns>The task representing the created <see cref="CustomerManagerLinkServiceClient"/>.</returns>
        public static stt::Task<CustomerManagerLinkServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
            new CustomerManagerLinkServiceClientBuilder().BuildAsync(cancellationToken);

        ///
        /// Synchronously creates a <see cref="CustomerManagerLinkServiceClient"/> using the default credentials,
        /// endpoint and settings. To specify custom credentials or other settings, use
        /// <see cref="CustomerManagerLinkServiceClientBuilder"/>.
        ///
        /// <returns>The created <see cref="CustomerManagerLinkServiceClient"/>.</returns>
        public static CustomerManagerLinkServiceClient Create() => new CustomerManagerLinkServiceClientBuilder().Build();

        ///
        /// Creates a <see cref="CustomerManagerLinkServiceClient"/> which uses the specified call invoker for remote
        /// operations.
        ///
        /// <param name="callInvoker">
        /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
        /// </param>
        /// <param name="settings">Optional <see cref="CustomerManagerLinkServiceSettings"/>.</param>
        /// <param name="logger">Optional <see cref="mel::ILogger"/>.</param>
        /// <returns>The created <see cref="CustomerManagerLinkServiceClient"/>.</returns>
        internal static CustomerManagerLinkServiceClient Create(grpccore::CallInvoker callInvoker, CustomerManagerLinkServiceSettings settings = null, mel::ILogger logger = null)
        {
            gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
            grpcinter::Interceptor interceptor = settings?.Interceptor;
            if (interceptor != null)
            {
                callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
            }
            CustomerManagerLinkService.CustomerManagerLinkServiceClient grpcClient = new CustomerManagerLinkService.CustomerManagerLinkServiceClient(callInvoker);
            return new CustomerManagerLinkServiceClientImpl(grpcClient, settings, logger);
        }

        ///
        /// Shuts down any channels automatically created by <see cref="Create()"/> and
        /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
        /// affected.
        ///
        /// <remarks>
        /// After calling this method, further calls to <see cref="Create()"/> and
        /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
        /// by another call to this method.
        /// </remarks>
        /// <returns>A task representing the asynchronous shutdown operation.</returns>
        public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();

        /// The underlying gRPC CustomerManagerLinkService client
        public virtual CustomerManagerLinkService.CustomerManagerLinkServiceClient GrpcClient => throw new sys::NotImplementedException();

        ///
        /// Updates customer manager links. Operation statuses are returned.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [ManagerLinkError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>The RPC response.</returns>
        public virtual MutateCustomerManagerLinkResponse MutateCustomerManagerLink(MutateCustomerManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
            throw new sys::NotImplementedException();

        ///
        /// Updates customer manager links. Operation statuses are returned.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [ManagerLinkError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<MutateCustomerManagerLinkResponse> MutateCustomerManagerLinkAsync(MutateCustomerManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
            throw new sys::NotImplementedException();

        ///
        /// Updates customer manager links. Operation statuses are returned.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [ManagerLinkError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<MutateCustomerManagerLinkResponse> MutateCustomerManagerLinkAsync(MutateCustomerManagerLinkRequest request, st::CancellationToken cancellationToken) =>
            MutateCustomerManagerLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));

        ///
        /// Updates customer manager links. Operation statuses are returned.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [ManagerLinkError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="customerId">
        /// Required. The ID of the customer whose customer manager links are being modified.
        /// </param>
        /// <param name="operations">
        /// Required. The list of operations to perform on individual customer manager links.
        /// </param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>The RPC response.</returns>
        public virtual MutateCustomerManagerLinkResponse MutateCustomerManagerLink(string customerId, scg::IEnumerable<CustomerManagerLinkOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
            MutateCustomerManagerLink(new MutateCustomerManagerLinkRequest
            {
                CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
                Operations =
                {
                    gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
                },
            }, callSettings);

        ///
        /// Updates customer manager links. Operation statuses are returned.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [ManagerLinkError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="customerId">
        /// Required. The ID of the customer whose customer manager links are being modified.
        /// </param>
        /// <param name="operations">
        /// Required. The list of operations to perform on individual customer manager links.
        /// </param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<MutateCustomerManagerLinkResponse> MutateCustomerManagerLinkAsync(string customerId, scg::IEnumerable<CustomerManagerLinkOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
            MutateCustomerManagerLinkAsync(new MutateCustomerManagerLinkRequest
            {
                CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
                Operations =
                {
                    gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
                },
            }, callSettings);

        ///
        /// Updates customer manager links. Operation statuses are returned.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [ManagerLinkError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="customerId">
        /// Required. The ID of the customer whose customer manager links are being modified.
        /// </param>
        /// <param name="operations">
        /// Required. The list of operations to perform on individual customer manager links.
        /// </param>
        /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<MutateCustomerManagerLinkResponse> MutateCustomerManagerLinkAsync(string customerId, scg::IEnumerable<CustomerManagerLinkOperation> operations, st::CancellationToken cancellationToken) =>
            MutateCustomerManagerLinkAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));

        ///
        /// Moves a client customer to a new manager customer.
        /// This simplifies the complex request that requires two operations to move
        /// a client customer to a new manager, for example:
        /// 1. Update operation with Status INACTIVE (previous manager) and,
        /// 2. Update operation with Status ACTIVE (new manager).
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>The RPC response.</returns>
        public virtual MoveManagerLinkResponse MoveManagerLink(MoveManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
            throw new sys::NotImplementedException();

        ///
        /// Moves a client customer to a new manager customer.
        /// This simplifies the complex request that requires two operations to move
        /// a client customer to a new manager, for example:
        /// 1. Update operation with Status INACTIVE (previous manager) and,
        /// 2. Update operation with Status ACTIVE (new manager).
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<MoveManagerLinkResponse> MoveManagerLinkAsync(MoveManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
            throw new sys::NotImplementedException();

        ///
        /// Moves a client customer to a new manager customer.
        /// This simplifies the complex request that requires two operations to move
        /// a client customer to a new manager, for example:
        /// 1. Update operation with Status INACTIVE (previous manager) and,
        /// 2. Update operation with Status ACTIVE (new manager).
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<MoveManagerLinkResponse> MoveManagerLinkAsync(MoveManagerLinkRequest request, st::CancellationToken cancellationToken) =>
            MoveManagerLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));

        ///
        /// Moves a client customer to a new manager customer.
        /// This simplifies the complex request that requires two operations to move
        /// a client customer to a new manager, for example:
        /// 1. Update operation with Status INACTIVE (previous manager) and,
        /// 2. Update operation with Status ACTIVE (new manager).
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="customerId">
        /// Required. The ID of the client customer that is being moved.
        /// </param>
        /// <param name="previousCustomerManagerLink">
        /// Required. The resource name of the previous CustomerManagerLink.
        /// The resource name has the form:
        /// `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}`
        /// </param>
        /// <param name="newManager">
        /// Required. The resource name of the new manager customer that the client wants to move
        /// to. Customer resource names have the format: "customers/{customer_id}"
        /// </param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>The RPC response.</returns>
        public virtual MoveManagerLinkResponse MoveManagerLink(string customerId, string previousCustomerManagerLink, string newManager, gaxgrpc::CallSettings callSettings = null) =>
            MoveManagerLink(new MoveManagerLinkRequest
            {
                CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
                PreviousCustomerManagerLink = gax::GaxPreconditions.CheckNotNullOrEmpty(previousCustomerManagerLink, nameof(previousCustomerManagerLink)),
                NewManager = gax::GaxPreconditions.CheckNotNullOrEmpty(newManager, nameof(newManager)),
            }, callSettings);

        ///
        /// Moves a client customer to a new manager customer.
        /// This simplifies the complex request that requires two operations to move
        /// a client customer to a new manager, for example:
        /// 1. Update operation with Status INACTIVE (previous manager) and,
        /// 2. Update operation with Status ACTIVE (new manager).
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="customerId">
        /// Required. The ID of the client customer that is being moved.
        /// </param>
        /// <param name="previousCustomerManagerLink">
        /// Required. The resource name of the previous CustomerManagerLink.
        /// The resource name has the form:
        /// `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}`
        /// </param>
        /// <param name="newManager">
        /// Required. The resource name of the new manager customer that the client wants to move
        /// to. Customer resource names have the format: "customers/{customer_id}"
        /// </param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<MoveManagerLinkResponse> MoveManagerLinkAsync(string customerId, string previousCustomerManagerLink, string newManager, gaxgrpc::CallSettings callSettings = null) =>
            MoveManagerLinkAsync(new MoveManagerLinkRequest
            {
                CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
                PreviousCustomerManagerLink = gax::GaxPreconditions.CheckNotNullOrEmpty(previousCustomerManagerLink, nameof(previousCustomerManagerLink)),
                NewManager = gax::GaxPreconditions.CheckNotNullOrEmpty(newManager, nameof(newManager)),
            }, callSettings);

        ///
        /// Moves a client customer to a new manager customer.
        /// This simplifies the complex request that requires two operations to move
        /// a client customer to a new manager, for example:
        /// 1. Update operation with Status INACTIVE (previous manager) and,
        /// 2. Update operation with Status ACTIVE (new manager).
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="customerId">
        /// Required. The ID of the client customer that is being moved.
        /// </param>
        /// <param name="previousCustomerManagerLink">
        /// Required. The resource name of the previous CustomerManagerLink.
        /// The resource name has the form:
        /// `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}`
        /// </param>
        /// <param name="newManager">
        /// Required. The resource name of the new manager customer that the client wants to move
        /// to. Customer resource names have the format: "customers/{customer_id}"
        /// </param>
        /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public virtual stt::Task<MoveManagerLinkResponse> MoveManagerLinkAsync(string customerId, string previousCustomerManagerLink, string newManager, st::CancellationToken cancellationToken) =>
            MoveManagerLinkAsync(customerId, previousCustomerManagerLink, newManager, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
    }

    /// CustomerManagerLinkService client wrapper implementation, for convenient use.
    /// <remarks>
    /// Service to manage customer-manager links.
    /// </remarks>
    public sealed partial class CustomerManagerLinkServiceClientImpl : CustomerManagerLinkServiceClient
    {
        private readonly gaxgrpc::ApiCall<MutateCustomerManagerLinkRequest, MutateCustomerManagerLinkResponse> _callMutateCustomerManagerLink;

        private readonly gaxgrpc::ApiCall<MoveManagerLinkRequest, MoveManagerLinkResponse> _callMoveManagerLink;

        ///
        /// Constructs a client wrapper for the CustomerManagerLinkService service, with the specified gRPC client and
        /// settings.
        ///
        /// <param name="grpcClient">The underlying gRPC client.</param>
        /// <param name="settings">
        /// The base <see cref="CustomerManagerLinkServiceSettings"/> used within this client.
        /// </param>
        /// <param name="logger">Optional <see cref="mel::ILogger"/> to use within this client.</param>
        public CustomerManagerLinkServiceClientImpl(CustomerManagerLinkService.CustomerManagerLinkServiceClient grpcClient, CustomerManagerLinkServiceSettings settings, mel::ILogger logger)
        {
            GrpcClient = grpcClient;
            CustomerManagerLinkServiceSettings effectiveSettings = settings ?? CustomerManagerLinkServiceSettings.GetDefault();
            gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings, logger);
            _callMutateCustomerManagerLink = clientHelper.BuildApiCall<MutateCustomerManagerLinkRequest, MutateCustomerManagerLinkResponse>("MutateCustomerManagerLink", grpcClient.MutateCustomerManagerLinkAsync, grpcClient.MutateCustomerManagerLink, effectiveSettings.MutateCustomerManagerLinkSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
            Modify_ApiCall(ref _callMutateCustomerManagerLink);
            Modify_MutateCustomerManagerLinkApiCall(ref _callMutateCustomerManagerLink);
            _callMoveManagerLink = clientHelper.BuildApiCall<MoveManagerLinkRequest, MoveManagerLinkResponse>("MoveManagerLink", grpcClient.MoveManagerLinkAsync, grpcClient.MoveManagerLink, effectiveSettings.MoveManagerLinkSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
            Modify_ApiCall(ref _callMoveManagerLink);
            Modify_MoveManagerLinkApiCall(ref _callMoveManagerLink);
            OnConstruction(grpcClient, effectiveSettings, clientHelper);
        }

        partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;

        partial void Modify_MutateCustomerManagerLinkApiCall(ref gaxgrpc::ApiCall<MutateCustomerManagerLinkRequest, MutateCustomerManagerLinkResponse> call);

        partial void Modify_MoveManagerLinkApiCall(ref gaxgrpc::ApiCall<MoveManagerLinkRequest, MoveManagerLinkResponse> call);

        partial void OnConstruction(CustomerManagerLinkService.CustomerManagerLinkServiceClient grpcClient, CustomerManagerLinkServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);

        /// The underlying gRPC CustomerManagerLinkService client
        public override CustomerManagerLinkService.CustomerManagerLinkServiceClient GrpcClient { get; }

        partial void Modify_MutateCustomerManagerLinkRequest(ref MutateCustomerManagerLinkRequest request, ref gaxgrpc::CallSettings settings);

        partial void Modify_MoveManagerLinkRequest(ref MoveManagerLinkRequest request, ref gaxgrpc::CallSettings settings);

        ///
        /// Updates customer manager links. Operation statuses are returned.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [ManagerLinkError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>The RPC response.</returns>
        public override MutateCustomerManagerLinkResponse MutateCustomerManagerLink(MutateCustomerManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null)
        {
            Modify_MutateCustomerManagerLinkRequest(ref request, ref callSettings);
            return _callMutateCustomerManagerLink.Sync(request, callSettings);
        }

        ///
        /// Updates customer manager links. Operation statuses are returned.
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [FieldMaskError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [ManagerLinkError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public override stt::Task<MutateCustomerManagerLinkResponse> MutateCustomerManagerLinkAsync(MutateCustomerManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null)
        {
            Modify_MutateCustomerManagerLinkRequest(ref request, ref callSettings);
            return _callMutateCustomerManagerLink.Async(request, callSettings);
        }

        ///
        /// Moves a client customer to a new manager customer.
        /// This simplifies the complex request that requires two operations to move
        /// a client customer to a new manager, for example:
        /// 1. Update operation with Status INACTIVE (previous manager) and,
        /// 2. Update operation with Status ACTIVE (new manager).
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>The RPC response.</returns>
        public override MoveManagerLinkResponse MoveManagerLink(MoveManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null)
        {
            Modify_MoveManagerLinkRequest(ref request, ref callSettings);
            return _callMoveManagerLink.Sync(request, callSettings);
        }

        ///
        /// Moves a client customer to a new manager customer.
        /// This simplifies the complex request that requires two operations to move
        /// a client customer to a new manager, for example:
        /// 1. Update operation with Status INACTIVE (previous manager) and,
        /// 2. Update operation with Status ACTIVE (new manager).
        ///
        /// List of thrown errors:
        /// [AuthenticationError]()
        /// [AuthorizationError]()
        /// [DatabaseError]()
        /// [FieldError]()
        /// [HeaderError]()
        /// [InternalError]()
        /// [MutateError]()
        /// [QuotaError]()
        /// [RequestError]()
        ///
        /// <param name="request">The request object containing all of the parameters for the API call.</param>
        /// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
        /// <returns>A Task containing the RPC response.</returns>
        public override stt::Task<MoveManagerLinkResponse> MoveManagerLinkAsync(MoveManagerLinkRequest request, gaxgrpc::CallSettings callSettings = null)
        {
            Modify_MoveManagerLinkRequest(ref request, ref callSettings);
            return _callMoveManagerLink.Async(request, callSettings);
        }
    }
}


text:
package org.wso2.carbon.apimgt.rest.api.store.v1;

import org.wso2.carbon.apimgt.rest.api.store.v1.dto.ErrorDTO;
import org.wso2.carbon.apimgt.rest.api.store.v1.dto.WebhookSubscriptionListDTO;
import org.wso2.carbon.apimgt.rest.api.store.v1.WebhooksApiService;
import org.wso2.carbon.apimgt.rest.api.store.v1.impl.WebhooksApiServiceImpl;
import org.wso2.carbon.apimgt.api.APIManagementException;

import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.inject.Inject;

import io.swagger.annotations.*;
import java.io.InputStream;

import org.apache.cxf.jaxrs.ext.MessageContext;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.Multipart;

import java.util.Map;
import java.util.List;
import javax.validation.constraints.*;
@Path("/webhooks")

@Api(description = "the webhooks API")

public class WebhooksApi  {

  @Context MessageContext securityContext;

WebhooksApiService delegate = new WebhooksApiServiceImpl();

    @GET
    @Path("/subscriptions")

    @Produces({ "application/json" })
    @ApiOperation(value = "Get available web hook subscriptions for a given application. ", notes = "This operation will provide a list of web hook topic subscriptions for a given application. If the api id is provided results will be filtered by the api Id. ", response = WebhookSubscriptionListDTO.class, authorizations = {
        @Authorization(value = "OAuth2Security", scopes = {

        })
    }, tags={ "Webhooks" })
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = "OK. Topic list returned. ", response = WebhookSubscriptionListDTO.class),
        @ApiResponse(code = 404, message = "Not Found. The specified resource does not exist.", response = ErrorDTO.class),
        @ApiResponse(code = 500, message = "Internal Server Error.", response = ErrorDTO.class) })
    public Response webhooksSubscriptionsGet( @ApiParam(value = "**Application Identifier** consisting of the UUID of the Application. ")  @QueryParam("applicationId") String applicationId,  @ApiParam(value = "**API ID** consisting of the **UUID** of the API. ")  @QueryParam("apiId") String apiId,  @ApiParam(value = "For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be   retrieved from. " )@HeaderParam("X-WSO2-Tenant") String xWSO2Tenant) throws APIManagementException{
        return delegate.webhooksSubscriptionsGet(applicationId, apiId, xWSO2Tenant, securityContext);
    }
}


text:
const merge = require('webpack-merge');
const baseConfig = require('./webpack.base.config.js');

module.exports = merge(baseConfig, {
    mode: 'development',
    devtool: 'cheap-module-source-map',
    devServer: {
        port: 8080,
        publicPath: baseConfig.publicPath
    },
    optimization: {
        minimizer: []
    }
});


text:
/**
 * Mockito injection internals.
 */
package org.mockito.internal.configuration.injection;


text:
using System.Collections.Generic;

using MediatR;

using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;

using vivego.Collection.EventStore.Append;
using vivego.Collection.EventStore.Delete;
using vivego.Collection.EventStore.GetAll;
using vivego.Collection.EventStore.GetOptions;
using vivego.Collection.EventStore.GetReverse;
using vivego.Collection.EventStore.GetState;
using vivego.Collection.EventStore.SetOptions;
using vivego.Collection.EventStore.SetState;
using vivego.EventStore;
using vivego.MediatR;
using vivego.ServiceBuilder;

using Version = vivego.EventStore.Version;

namespace vivego.Collection.EventStore
{
	public sealed class EventStoreBuilder : DefaultServiceBuilder<IEventStore>
	{
		public EventStoreBuilder(
			string name,
			IServiceCollection serviceCollection) : base(name, serviceCollection)
		{
			Services.AddSingleton<IEventStore>(sp => ActivatorUtilities.CreateInstance<DefaultEventStore>(sp, name));

			DependsOn<IMemoryCache>();
			Services.AddSingleton<IRequestHandler<GetStateRequest, EventStoreState>, GetStateRequestHandler>();
			Services.AddSingleton<IRequestHandler<SetStateRequest, Unit>, SetStateRequestHandler>();
			Services.AddSingleton<IRequestHandler<AppendRequest, Version>, AppendRequestHandler>();
			Services.AddSingleton<IRequestHandler<DeleteRequest, Unit>, DeleteRequestHandler>();
			Services.AddSingleton<IRequestHandler<SetOptionsRequest, Unit>, SetOptionsRequestHandler>();
			Services.AddSingleton<IRequestHandler<GetOptionsRequest, EventStreamOptions>, GetOptionsRequestHandler>();
			Services.AddSingleton<GetRequestHandler>();
			Services.AddSingleton<IRequestHandler<GetRequest, IAsyncEnumerable<RecordedEvent>>>(sp => sp.GetRequiredService<GetRequestHandler>());
			Services.AddSingleton<IPipelineBehavior<GetRequest, IAsyncEnumerable<RecordedEvent>>>(sp => sp.GetRequiredService<GetRequestHandler>());

			Services.AddSingleton<IRequestHandler<GetReverseRequest, IAsyncEnumerable<RecordedEvent>>, GetReverseRequestHandler>();

			// Exception Handlers
			Services.AddExceptionLoggingPipelineBehaviour<AppendRequest>(request => $"Error while appending event to stream: {request.StreamId}");
			Services.AddExceptionLoggingPipelineBehaviour<DeleteRequest>(request => $"Error while deleting event store stream: {request.StreamId}");
			Services.AddExceptionLoggingPipelineBehaviour<GetRequest>(request => $"Error while retrieving all data from event store stream: {request.StreamId}");
			Services.AddExceptionLoggingPipelineBehaviour<GetOptionsRequest>(request => $"Error while retrieving options from event store stream: {request.StreamId}");
			Services.AddExceptionLoggingPipelineBehaviour<GetReverseRequest>(request => $"Error while retrieving all data in reverse from event store stream: {request.StreamId}");
			Services.AddExceptionLoggingPipelineBehaviour<GetStateRequest>(request => $"Error while retrieving state for stream: {request.StreamId}");
			Services.AddExceptionLoggingPipelineBehaviour<SetOptionsRequest>(request => $"Error while setting stream options for stream stream: {request.StreamId}");
			Services.AddExceptionLoggingPipelineBehaviour<SetStateRequest>(request => $"Error while setting state for stream stream: {request.StreamId}");
		}
	}
}


text:
export { JiraSettings } from './jiraSettings';
export { JiraConnectionFormFields } from './jiraConnectionFormFields';


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

<title>org.hibernate.integrator.spi (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.hibernate.integrator.spi

Interfaces

Integrator

IntegratorService

ServiceContributingIntegrator


text:
{% extends 'base.html' %}
{% load i18n %}
{% block title %}{{ page_title }}{% endblock %}

{% block main %}
    {% include 'project/volume_groups/_create_snapshot.html' %}
{% endblock %}


text:
using Atata;
using NUnit.Framework;

namespace SampleApp.UITests
{
    public class UserTests : UITestFixture
    {
        [Test]
        public void Create() =>
            Login() // Returns UsersPage.
                .New.ClickAndGo() // Returns UserEditWindow.
                    .ModalTitle.Should.Equal("New User")
                    .General.FirstName.SetRandom(out string firstName)
                    .General.LastName.SetRandom(out string lastName)
                    .General.Email.SetRandom(out string email)
                    .General.Office.SetRandom(out Office office)
                    .General.Gender.SetRandom(out Gender gender)
                    .Save.ClickAndGo() // Returns UsersPage.
                .Users.Rows[x => x.Email == email].View.ClickAndGo() // Returns UserDetailsPage.
                    .AggregateAssert(page => page
                        .Header.Should.Equal($"{firstName} {lastName}")
                        .Email.Should.Equal(email)
                        .Office.Should.Equal(office)
                        .Gender.Should.Equal(gender)
                        .Birthday.Should.Not.Exist()
                        .Notes.Should.Not.Exist());
    }
}


text:
import unittest

from pangram import is_pangram

class PangramTests(unittest.TestCase):

    def test_empty_string(self):
        self.assertFalse(is_pangram(''))

    def test_valid_pangram(self):
        self.assertTrue(
            is_pangram('the quick brown fox jumps over the lazy dog'))

    def test_missing_x(self):
        self.assertFalse(is_pangram('a quick movement of the enemy will '
                                    'jeopardize five gunboats'))

    def test_mixedcase_and_punctuation(self):
        self.assertTrue(is_pangram('"Five quacking Zephyrs jolt my wax bed."'))

    def test_unchecked_german_umlaute(self):
        self.assertTrue(is_pangram('Victor jagt zwölf Boxkämpfer quer über den'
                                   ' großen Sylter Deich.'))

if __name__ == '__main__':
    unittest.main()


text:
<component name="libraryTable">
  <library name="kotlin-test" type="repository">
    <properties maven-id="org.jetbrains.kotlin:kotlin-test:1.4.32">
      <exclude>
        <dependency maven-id="org.jetbrains.kotlin:kotlin-stdlib-common" />
        <dependency maven-id="org.jetbrains.kotlin:kotlin-stdlib" />
      </exclude>
    </properties>
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-test/1.4.32/kotlin-test-1.4.32.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-test-common/1.4.32/kotlin-test-common-1.4.32.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-test/1.4.32/kotlin-test-1.4.32-sources.jar!/" />
      <root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-test-common/1.4.32/kotlin-test-common-1.4.32-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
describe("$ref 05", function () {

	it("inline addressing for fragments", function () {
		var schema = {
			"type": "array",
			"items": {"$ref": "#test"},
			"testSchema": {
				"id": "#test",
				"type": "boolean"
			}
		};
		var error = {
			code: 0,
			message: 'Invalid type: number (expected boolean)',
			dataPath: '/0',
			schemaPath: '/items/type',
			subErrors: null
		};

		var data = [0, false];
		var valid = tv4.validate(data, schema);
		assert.isFalse(valid, 'inline addressing invalid 0, false');
		assert.propertyValues(tv4.error, error, 'errors equal');
	});

	it("don't trust non sub-paths", function () {
		var examplePathBase = "http://example.com/schema";
		var examplePath = examplePathBase + "/schema";
		var schema = {
			"id": examplePath,
			"type": "array",
			"items": {"$ref": "other-schema"},
			"testSchema": {
				"id": "/other-schema",
				"type": "boolean"
			}
		};
		tv4.addSchema(examplePath, schema);
		var data = [0, false];
		var valid = tv4.validate(data, examplePath);

		assert.length(tv4.missing, 1, "should have missing schema");
		assert.strictEqual(tv4.missing[0], examplePathBase + "/other-schema", "incorrect schema missing: " + tv4.missing[0]);
		assert.isTrue(valid, "should pass, as remote schema not found");

		//this.assert(tv4.missing.length == 1, "should have missing schema");
		//this.assert(tv4.missing[0] == examplePathBase + "/other-schema", "incorrect schema missing: " + tv4.missing[0]);
		//this.assert(valid, "should pass, as remote schema not found");
	});
});


text:
package org.chocosolver.graphsolver.cstrs.basic;

import gnu.trove.list.array.TIntArrayList;
import org.chocosolver.graphsolver.variables.GraphEventType;
import org.chocosolver.graphsolver.variables.GraphVar;
import org.chocosolver.graphsolver.variables.delta.GraphDeltaMonitor;
import org.chocosolver.solver.constraints.Propagator;
import org.chocosolver.solver.constraints.PropagatorPriority;
import org.chocosolver.solver.exception.ContradictionException;
import org.chocosolver.util.ESat;
import org.chocosolver.util.objects.setDataStructures.ISet;
import org.chocosolver.util.procedure.PairProcedure;

/**
 * Propagator that ensures that the relation of the graph is transitive : (a,b) + (b,c) implies (a,c)
 *
 * @author Jean-Guillaume Fages
 */
public class PropTransitivity<V extends GraphVar> extends Propagator<V> {

	//***********************************************************************************
	// VARIABLES
	//***********************************************************************************

	private V g;
	private GraphDeltaMonitor gdm;
	private PairProcedure arcEnforced, arcRemoved;
	private TIntArrayList eF, eT, rF, rT;

	//***********************************************************************************
	// CONSTRUCTORS
	//***********************************************************************************

	public PropTransitivity(V graph) {
		super((V[]) new GraphVar[]{graph}, PropagatorPriority.LINEAR, true);
		g = graph;
		gdm = g.monitorDelta(this);
		int n = g.getNbMaxNodes();
		eF = new TIntArrayList(n);
		eT = new TIntArrayList(n);
		rF = new TIntArrayList(n);
		rT = new TIntArrayList(n);
		arcEnforced = this::arcEnforced;
		arcRemoved = this::arcRemoved;
	}

	//***********************************************************************************
	// PROPAGATIONS
	//***********************************************************************************

	@Override
	public void propagate(int evtmask) throws ContradictionException {
		int n = g.getNbMaxNodes();
		for (int i : g.getPotentialNodes()) {
			for (int j = 0; j < n; j++) {
				if (g.getMandSuccOrNeighOf(i).contains(j)) {
					arcEnforced(i, j);
				} else if (!g.getPotSuccOrNeighOf(i).contains(j)) {
					arcRemoved(i, j);
				}
			}
		}
		filter();
		gdm.unfreeze();
	}

	@Override
	public void propagate(int idxVarInProp, int mask) throws ContradictionException {
		gdm.freeze();
		rT.clear();
		rF.clear();
		eT.clear();
		eF.clear();
		gdm.forEachArc(arcEnforced, GraphEventType.ADD_ARC);
		gdm.forEachArc(arcRemoved, GraphEventType.REMOVE_ARC);
		filter();
		gdm.unfreeze();
	}

	private void filter() throws ContradictionException {
		// Fix point
		assert eF.size() == eT.size();
		while (!eF.isEmpty()) {
			assert eF.size() == eT.size();
			enfArc(eF.removeAt(eF.size() - 1), eT.removeAt(eT.size() - 1));
		}
		assert rF.size() == rT.size();
		while (!rF.isEmpty()) {
			assert rF.size() == rT.size();
			remArc(rF.removeAt(rF.size() - 1), rT.removeAt(rT.size() - 1));
		}
		assert eF.size() == eT.size();
		if (!eF.isEmpty()) {
			filter();
		}
	}

	//***********************************************************************************
	// INFO
	//***********************************************************************************

	@Override
	public int getPropagationConditions(int vIdx) {
		return GraphEventType.REMOVE_ARC.getMask() + GraphEventType.ADD_ARC.getMask();
	}

	@Override
	public ESat isEntailed() {
		int n = g.getNbMaxNodes();
		for (int i = 0; i < n; i++) {
			for (int j : g.getMandSuccOrNeighOf(i)) {
				if (i != j) {
					for (int j2 : g.getMandSuccOrNeighOf(j)) {
						if (j2 != i && !g.getPotSuccOrNeighOf(i).contains(j2)) {
							return ESat.FALSE;
						}
					}
				}
			}
		}
		if (g.isInstantiated()) {
			return ESat.TRUE;
		}
		return ESat.UNDEFINED;
	}

	//***********************************************************************************
	// PROCEDURE
	//***********************************************************************************

	private void arcEnforced(int x, int y) {
		eF.add(x);
		eT.add(y);
	}

	private void arcRemoved(int x, int y) {
		rF.add(x);
		rT.add(y);
	}

	// --- Arc enforcings
	private void enfArc(int from, int to) throws ContradictionException {
		if (from != to) {
			ISet ker = g.getMandSuccOrNeighOf(to);
			ISet env = g.getPotSuccOrNeighOf(to);
			for (int i : env) {
				if (i != to && i != from) {
					if (ker.contains(i)) {
						if (g.enforceArc(from, i, this)) {
							arcEnforced(from, i);
						}
					} else if (!g.getPotSuccOrNeighOf(from).contains(i)) {
						if (g.removeArc(to, i, this)) {
							arcRemoved(to, i);
						}
					}
				}
			}
			ker = g.getMandPredOrNeighOf(from);
			env = g.getPotPredOrNeighOf(from);
			for (int i : env) {
				if (i != to && i != from) {
					if (ker.contains(i)) {
						if (g.enforceArc(i, to, this)) {
							arcEnforced(i, to);
						}
					} else if (!g.getPotSuccOrNeighOf(i).contains(to)) {
						if (g.removeArc(i, from, this)) {
							arcRemoved(i, from);
						}
					}
				}
			}
		}
	}

	// --- Arc removals
	private void remArc(int from, int to) throws ContradictionException {
		if (from != to) {
			for (int i : g.getMandSuccOrNeighOf(from)) {
				if (g.removeArc(i, to, this)) {
					arcRemoved(i, to);
				}
			}
			for (int i : g.getMandPredOrNeighOf(to)) {
				if (g.removeArc(from, i, this)) {
					arcRemoved(from, i);
				}
			}
		}
	}
}


text:
package org.sakaiproject.nakamura.search;

import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.sakaiproject.nakamura.api.doc.BindingType;
import org.sakaiproject.nakamura.api.doc.ServiceBinding;
import org.sakaiproject.nakamura.api.doc.ServiceDocumentation;
import org.sakaiproject.nakamura.api.doc.ServiceExtension;
import org.sakaiproject.nakamura.api.doc.ServiceMethod;
import org.sakaiproject.nakamura.api.doc.ServiceResponse;
import org.sakaiproject.nakamura.api.doc.ServiceSelector;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

/**
 * The JsonQueryServletBlocker blocks the default sling JsonQueryServlet
 */
@ServiceDocumentation(
  name = "Json Query Servlet Blocker", okForVersion = "1.2",
  shortDescription = "Blocks the default sling JsonQueryServlet",
  description = "Blocks the default sling JsonQueryServlet",
  bindings = {
    @ServiceBinding(
      type = BindingType.TYPE,
      bindings = { "sling/servlet/default" },
      selectors = { @ServiceSelector(name = "query", description = "Binds to the query selector.") },
      extensions = @ServiceExtension(name = "json", description = "javascript object notation")
    )
  },
  methods = {
    @ServiceMethod(
      name = "GET",
      description = "Create an external repository document.",
      response = {
        @ServiceResponse(code = 501, description = "Unimplemented.")
      }
    )
  }
)
@SlingServlet(extensions={"json"}, methods={"GET"}, resourceTypes={"sling/servlet/default"}, selectors={"query"} )
@Properties(value={
 @Property(name="sling.servlet.prefix", value={"-1"}),
 @Property(name="service.description", value={"Blocks the default sling JsonQueryServlet."}),
 @Property(name="service.vendor", value={"The Sakai Foundation"})
})
public class JsonQueryServletBlocker extends SlingSafeMethodsServlet {

  private static final long serialVersionUID = 9135814126478411413L;

  @Override
  protected void doGet(SlingHttpServletRequest request,
      SlingHttpServletResponse response) throws ServletException, IOException {
    response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
  }
}