text:
"""High level conversion support."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
import imp

import gast

from tensorflow.contrib.autograph import operators
from tensorflow.contrib.autograph import utils
from tensorflow.contrib.autograph.converters import asserts
from tensorflow.contrib.autograph.converters import break_statements
from tensorflow.contrib.autograph.converters import builtin_functions
from tensorflow.contrib.autograph.converters import call_trees
from tensorflow.contrib.autograph.converters import continue_statements
from tensorflow.contrib.autograph.converters import control_flow
from tensorflow.contrib.autograph.converters import decorators
from tensorflow.contrib.autograph.converters import ifexp
from tensorflow.contrib.autograph.converters import lists
from tensorflow.contrib.autograph.converters import logical_expressions
from tensorflow.contrib.autograph.converters import name_scopes
from tensorflow.contrib.autograph.converters import side_effect_guards
from tensorflow.contrib.autograph.converters import single_return
from tensorflow.contrib.autograph.impl import config
from tensorflow.contrib.autograph.impl import naming
from tensorflow.contrib.autograph.pyct import ast_util
from tensorflow.contrib.autograph.pyct import context
from tensorflow.contrib.autograph.pyct import inspect_utils
from tensorflow.contrib.autograph.pyct import parser
from tensorflow.contrib.autograph.pyct import qual_names
from tensorflow.contrib.autograph.pyct.static_analysis import activity
from tensorflow.contrib.autograph.pyct.static_analysis import live_values
from tensorflow.contrib.autograph.pyct.static_analysis import type_info
from tensorflow.contrib.autograph.utils import type_hints
from tensorflow.python.util import tf_inspect

# TODO(mdan): Might we not need any renaming at all?

class ConversionMap(object):
  """ConversionMap keeps track of converting function hierarchies.

  This object is mutable, and is updated as functions are converted.

  Attributes:
    recursive: Whether to recursively convert any functions that the decorator
        function may call.
    nocompile_decorators: tuple of decorator functions that toggle compilation
        off.
    dependency_cache: dict[object]: ast; maps original entities to their
        converted AST
    additional_imports: set(object); additional entities which for any reason
        cannot be attached after loading and need to be explicitly imported
        in the generated code
    name_map: dict[string]: string; maps original entities to the name of
        their converted counterparts
    api_module: A reference to the api module. The reference needs to be passed
        to avoid circular dependencies.
  """

  # TODO(mdan): Rename to ConversionContext, and pull in additional flags.

  def __init__(self, recursive, nocompile_decorators, partial_types,
               api_module):
    self.recursive = recursive
    self.nocompile_decorators = nocompile_decorators
    self.partial_types = partial_types if partial_types else ()
    # Required to output dependencies in discovery order, which should match
    # the reverse dependency order.
    self.dependency_cache = collections.OrderedDict()
    self.additional_imports = set()
    self.name_map = {}
    self.api_module = api_module

  def new_namer(self, namespace):
    return naming.Namer(namespace, self.recursive, self.name_map,
                        self.partial_types)

  def update_name_map(self, namer):
    for o, name in namer.renamed_calls.items():
      if o in self.name_map:
        if self.name_map[o] != name:
          raise ValueError(
              'Calls to %s were converted using multiple names (%s). This is '
              'possible when an entity with one of these names already '
              'existed. To fix, avoid using any of these names.')
      else:
        self.name_map[o] = name

  def add_to_cache(self, original_entity, converted_ast):
    self.dependency_cache[original_entity] = converted_ast

def is_whitelisted_for_graph(o):
  """Check whether an entity is whitelisted for use in graph mode.

  Examples of whitelisted entities include all members of the tensorflow
  package.

  Args:
    o: A Python entity.
  Returns:
    Boolean
  """
  m = tf_inspect.getmodule(o)
  for prefix, in config.DEFAULT_UNCOMPILED_MODULES:
    if m.__name__.startswith(prefix):
      return True
  return False

def entity_to_graph(o, conversion_map, arg_values, arg_types):
  """Compile a Python entity into equivalent TensorFlow.

  The function will also recursively compile all the entities that `o`
  references, updating `dependency_cache`.

  This function is reentrant, and relies on dependency_cache to avoid
  generating duplicate code.

  Args:
    o: A Python entity.
    conversion_map: A ConversionMap object.
    arg_values: A dict containing value hints for symbols like function
        parameters.
    arg_types: A dict containing type hints for symbols like function
        parameters.

  Returns:
    A tuple (ast, new_name, namespace):
        * ast: An AST representing an entity with interface equivalent to `o`,
            but which when executed it creates TF a graph.
        * new_name: The symbol name under which the new entity can be found.
        * namespace: A dict mapping all symbols visible to the converted entity,
            keyed by their symbol name.

  Raises:
    ValueError: if the entity type is not supported.
  """
  if tf_inspect.isclass(o):
    node, name, ns = class_to_graph(o, conversion_map)
  elif tf_inspect.isfunction(o):
    # TODO(mdan): This is not a reliable mechanism.
    # The most reliable way is to check the source code, the AST will contain
    # a Lambda node instead of a FunctionDef
    if o.__name__ == '<lambda>':
      raise NotImplementedError(
          'lambda functions are not yet supported; declare the function'
          ' using def instead: %s' % o)
    else:
      node, name, ns = function_to_graph(o, conversion_map, arg_values,
                                         arg_types)
  elif tf_inspect.ismethod(o):
    node, name, ns = function_to_graph(o, conversion_map, arg_values, arg_types)
  else:
    raise ValueError(
        'Entity "%s" has unsupported type "%s". Only functions and classes are '
        'supported for now.' % (o, type(o)))

  conversion_map.add_to_cache(o, node)
  if conversion_map.recursive:
    while True:
      candidate = None
      for obj in conversion_map.name_map.keys():
        if obj not in conversion_map.dependency_cache:
          candidate = obj
          break
      if candidate is None:
        break
      if (hasattr(candidate, 'im_class') and
          getattr(candidate, 'im_class') not in conversion_map.partial_types):
        # Class members are converted with their objects, unless they're
        # only converted partially.
        continue
      entity_to_graph(candidate, conversion_map, {}, {})

  return node, name, ns

def class_to_graph(c, conversion_map):
  """Specialization of `entity_to_graph` for classes."""
  converted_members = {}
  method_filter = lambda m: tf_inspect.isfunction(m) or tf_inspect.ismethod(m)
  members = tf_inspect.getmembers(c, predicate=method_filter)
  if not members:
    raise ValueError('Cannot convert %s: it has no member methods.' % c)

  class_namespace = {}
  for _, m in members:
    # Only convert the members that are directly defined by the class.
    if inspect_utils.getdefiningclass(m, c) is not c:
      continue
    node, _, namespace = function_to_graph(
        m,
        conversion_map=conversion_map,
        arg_values={},
        arg_types={'self': (c.__name__, c)},
        owner_type=c)
    if class_namespace is None:
      class_namespace = namespace
    else:
      class_namespace.update(namespace)
    converted_members[m] = node
  namer = conversion_map.new_namer(class_namespace)
  class_name = namer.compiled_class_name(c.__name__, c)

  # TODO(mdan): This needs to be explained more thoroughly.
  # Process any base classes: if the sueprclass if of a whitelisted type, an
  # absolute import line is generated. Otherwise, it is marked for conversion
  # (as a side effect of the call to namer.compiled_class_name() followed by
  # conversion_map.update_name_map(namer)).
  output_nodes = []
  renames = {}
  bases = []
  for base in c.__bases__:
    if isinstance(object, base):
      bases.append('object')
      continue
    if is_whitelisted_for_graph(base):
      alias = namer.new_symbol(base.__name__, ())
      output_nodes.append(
          gast.ImportFrom(
              module=base.__module__,
              names=[gast.alias(name=base.__name__, asname=alias)],
              level=0))
    else:
      # This will trigger a conversion into a class with this name.
      alias = namer.compiled_class_name(base.__name__, base)
    bases.append(alias)
    renames[qual_names.QN(base.__name__)] = qual_names.QN(alias)
  conversion_map.update_name_map(namer)

  # Generate the definition of the converted class.
  output_nodes.append(
      gast.ClassDef(
          class_name,
          bases=bases,
          keywords=[],
          body=list(converted_members.values()),
          decorator_list=[]))
  node = gast.Module(output_nodes)

  # Make a final pass to replace references to the class or its base classes.
  # Most commonly, this occurs when making super().__init__() calls.
  # TODO(mdan): Making direct references to superclass' superclass will fail.
  node = qual_names.resolve(node)
  renames[qual_names.QN(c.__name__)] = qual_names.QN(class_name)
  node = ast_util.rename_symbols(node, renames)

  return node, class_name, class_namespace

def _add_reserved_symbol(namespace, name, entity):
  if name not in namespace:
    namespace[name] = entity
  elif namespace[name] != entity:
    raise ValueError('The name "%s" is reserved and may not be used.' % name)

ag_internal = None

def _add_self_references(namespace, api_module):
  """Adds namespace references to the module that exposes the api itself."""
  global ag_internal
  if ag_internal is None:
    # Craft a module that exposes parts of the external API as well as certain
    # internal modules.
    ag_internal = imp.new_module('autograph')
    ag_internal.converted_call = api_module.converted_call
    ag_internal.utils = utils
    # TODO(mdan): Add safeguards against name clashes.
    # We don't want to create a submodule because we want the operators to be
    # accessible as ag__.<operator>
    ag_internal.__dict__.update(operators.__dict__)

  _add_reserved_symbol(namespace, 'ag__', ag_internal)

def function_to_graph(f, conversion_map, arg_values, arg_types,
                      owner_type=None):
  """Specialization of `entity_to_graph` for callable functions."""
  node, source = parser.parse_entity(f)
  node = node.body[0]

  namespace = inspect_utils.getnamespace(f)
  _add_self_references(namespace, conversion_map.api_module)
  namer = conversion_map.new_namer(namespace)

  ctx = context.EntityContext(
      namer=namer,
      source_code=source,
      source_file='<fragment>',
      namespace=namespace,
      arg_values=arg_values,
      arg_types=arg_types,
      owner_type=owner_type,
      recursive=conversion_map.recursive,
      type_annotation_func=type_hints.set_element_type)
  node, deps = node_to_graph(node, ctx, conversion_map.nocompile_decorators)

  # TODO(mdan): This somewhat duplicates the call rename logic in call_treest.py
  new_name, did_rename = namer.compiled_function_name(f.__name__, f, owner_type)
  if not did_rename:
    new_name = f.__name__
    if node.name != f.__name__:
      raise NotImplementedError('Strange corner case. Send us offending code!')

  node.name = new_name
  conversion_map.update_name_map(namer)
  # TODO(mdan): Use this at compilation.
  conversion_map.additional_imports.update(deps)

  return node, new_name, namespace

def _static_analysis_pass(node, ctx):
  node = qual_names.resolve(node)
  node = activity.resolve(node, ctx, None)
  node = live_values.resolve(node, ctx, config.PYTHON_LITERALS)
  node = type_info.resolve(node, ctx)
  return node

def node_to_graph(node, ctx, nocompile_decorators):
  """Convert Python code to equivalent TF graph mode code.

  Args:
    node: A Python AST node representing the code to convert.
    ctx: An EntityContext object.
    nocompile_decorators: A tuple containing decorators to be stripped from
        functions during conversion.

  Returns:
    A tuple (node, deps):
        * node: A Python ast node, representing the converted code.
        * deps: A set of strings, the fully qualified names of entity
            dependencies that this node has.
  """
  # TODO(mdan): Verify arguments for correctness.

  # TODO(mdan): Factor out common elements.
  # These include:
  #   * code move between blocks
  #   * visiting blocks in transformers

  # Certain steps, especially canonicalization, insert new symbols into the
  # tree, which must be accounted. Although less efficient, it is most robust
  # to re-run the analysis.

  node = _static_analysis_pass(node, ctx)

  # TODO(mdan): Clean this up.
  # Some intermediate analyses are not required, and some comments got orphaned.

  # Past this point, line numbers are no longer accurate so we ignore the
  # source.
  # TODO(mdan): Is it feasible to reconstruct intermediate source code?
  ctx.source_code = None
  node = ifexp.transform(node, ctx)
  node, deps = decorators.transform(node, nocompile_decorators)
  node = break_statements.transform(node, ctx)
  node = _static_analysis_pass(node, ctx)

  node = asserts.transform(node, ctx)

  # Note: sequencing continue canonicalization before for loop one avoids
  # dealing with the extra loop increment operation that the for
  # canonicalization creates.
  node = continue_statements.transform(node, ctx)
  ctx.namespace['len'] = len

  node = _static_analysis_pass(node, ctx)
  node = single_return.transform(node, ctx)

  node = _static_analysis_pass(node, ctx)
  node = lists.transform(node, ctx)
  node = builtin_functions.transform(node, ctx)

  node = _static_analysis_pass(node, ctx)
  node = call_trees.transform(node, ctx, config.DEFAULT_UNCOMPILED_MODULES,
                              nocompile_decorators)
  node = control_flow.transform(node, ctx)

  # control_flow may create new symbols and change scopes.
  node = _static_analysis_pass(node, ctx)
  node = logical_expressions.transform(node, ctx)
  node = side_effect_guards.transform(node, ctx)
  node = name_scopes.transform(node, ctx)

  return node, deps


text:
"""TestFlinger meta-test execution framework

When writing a master test script that runs several scripts, this module
can be used to execute those tests in a detached process (sandbox).
Thus, if the test case fails by a segfault or timeout, this can be
detected and the upper-level script simply moves on to the next script.
"""

import os
import time
import subprocess
import sys
import time

g_default_timeout = 300

class TestCase:
    """Test running wrapper object."""

    def __init__(self, TestDict = {}, Logfile = None):
        """Set up the test runner object.

        TestDict: dictionary with the test properties.  (string: value).  The
                  recognized properties are:

                  filename - name of executable test file
                      Type: string
                      Required: yes

                  args - command line arguments for test
                      Type: list of strings, or None
                      Required: no
                      Default: None

                  timeout - upper limit on execution time (secs).  If test takes
                      this long to run, then it is deemed a failure
                      Type: integer
                      Required: no
                      Default: TestFlinger.g_default_timeout (typ. 300 sec)

                  expect-fail - If the test is expected to fail (return non-zero)
                      in order to pass, set this to True
                      Type: bool
                      Required: no
                      Default: False

                  expect-signal If the test is expected to fail because of
                      a signal (e.g. SIGTERM, SIGSEGV) then this is considered success
                      Type: bool
                      Required: no
                      Default: False

        Logfile: a file object where stdout/stderr for the tests should be dumped.
            If null, then no logging will be done.  (See also TestFlinger.setup_logfile()
            and TestFlinger.close_logfile().
        """
        global g_default_timeout

        self._program = None
        self._args = None
        self._timeout = g_default_timeout # Default timeout
        self._verdict = None
        self._expect_fail = False
        self._expect_signal = False
        self._logfile = Logfile

        self._proc = None
        self._time_expire = None

        self._program = TestDict['filename']
        if 'args' in TestDict:
            self._args = TestDict['args']
        if 'timeout' in TestDict and TestDict['timeout'] is not None:
            self._timeout = TestDict['timeout']
        if 'expect-fail' in TestDict and TestDict['expect-fail'] is not None:
            self._expect_fail = TestDict['expect-fail']
        if 'expect-signal' in TestDict and TestDict['expect-signal'] is not None:
            self._expect_signal = TestDict['expect-signal']

    def __del__(self):
        pass

    def start(self):
        """Starts the test in another process.  Returns True if the
        test was successfully spawned.  False if there was an error.
        """

        command = os.path.abspath(self._program)

        if not os.path.exists(command):
            print "ERROR: The program to execute does not exist (%s)" % (command,)
            return False

        timestamp = time.strftime("%Y.%m.%d %H:%M:%S")
        now = time.time()
        self._time_expire = self._timeout + now
        self._kill_timeout = False

        self._log_write("====================================================================\n")
        self._log_write("BEGINNG TEST '%s' at %s\n" % (self._program, timestamp))
        self._log_write("--------------------------------------------------------------------\n")
        self._log_flush()

        self._proc = subprocess.Popen(args=command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

        return (self._proc is not None)

    def wait(self):
        """Blocks until the test completes or times out, whichever
        comes first.  If test fails, returns False.  Otherwise returns
        true.
        """

        if self._proc is None:
            print "ERROR: Test was never started"
            return False

        self._proc.poll()
        while (time.time() < self._time_expire) and (self._proc.poll() is None):
            self._process_logs()
            time.sleep(.5)

        if self._proc.returncode is None:
            self.kill()
            return False

        self._process_logs()
        self._finalize_log()

        return True

    def kill(self):
        """Kill the currently running test (if there is one).
        """

        if self._proc is None:
            print "WARNING: killing a test was never started"
            return False

        self._kill_timeout = True
        self._proc.terminate()
        time.sleep(2)
        self._proc.kill()
        self._log_write("\nKilling process by request...\n")
        self._log_flush()
        self._finalize_log()

        return True

    def verdict(self):
        """Returns a string, either 'PASS', 'FAIL', 'FAIL/TIMEOUT', or 'FAIL/SIGNAL(n)
        '"""
        self._proc.poll()

        rc = self._proc.returncode

        if rc is None:
            print "ERROR: test is still running"

        if self._kill_timeout:
            return "FAIL/TIMOUT"

        if rc < 0 and self._expect_signal:
            return "PASS"
        elif rc < 0:
            return "FAIL/SIGNAL(%d)" % (-rc,)

        if self._expect_fail:
            if rc != 0:
                return "PASS"
            else:
                return "FAIL"
        else:
            if rc == 0:
                return "PASS"
            else:
                return "FAIL"

    def _process_logs(self):
        if self._logfile is not None:
            data = self._proc.stdout.read()
            self._logfile.write(data)
            self._logfile.flush()

    def _finalize_log(self):
        timestamp = time.strftime("%Y.%m.%d %H:%M:%S")
        self._log_write("--------------------------------------------------------------------\n")
        self._log_write("ENDING TEST '%s' at %s\n" % (self._program, timestamp))
        self._log_write("====================================================================\n")
        self._log_flush()

    def _log_write(self, data):
        if self._logfile is not None:
            self._logfile.write(data)

    def _log_flush(self):
        if self._logfile is not None:
            self._logfile.flush()

def setup_logfile(override_logfile_name = None):
    """Open a logfile and prepare it for use with TestFlinger logging.
    The filename will be generated based on the current date/time.

    If override_logfile_name is not None, then that filename will be
    used instead.

    See also: close_logfile()
    """

    tmpfile = None
    if override_logfile_name is not None:
        tmpfile = override_logfile_name
        if os.path.exists(tmpfile):
            os.unlink(tmpfile)
    else:
        tmpfile = time.strftime("test-log-%Y.%m.%d.%H%M%S.txt")
        while os.path.exists(tmpfile):
            tmpfile = time.strftime("test-log-%Y.%m.%d.%H%M%S.txt")
    fobj = open(tmpfile, 'wt')
    print "Logging to", tmpfile
    timestamp = time.strftime("%Y.%m.%d %H:%M:%S")
    fobj.write("BEGINNING TEST SET %s\n" % (timestamp,))
    fobj.write("====================================================================\n")
    return fobj

def close_logfile(fobj):
    """Convenience function for closing a TestFlinger log file.

    fobj: an open and writeable file object

    See also : setup_logfile()
    """

    timestamp = time.strftime("%Y.%m.%d %H:%M:%S")
    fobj.write("====================================================================\n")
    fobj.write("CLOSING TEST SET %s\n" % (timestamp,))

if __name__ == "__main__":
    pass

redpajama_set_name: RedPajamaGithub


text:
using GitHub.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using UnityEditor;
using UnityEngine;
using Application = UnityEngine.Application;

namespace GitHub.Unity
{
    sealed class ApplicationCache : ScriptObjectSingleton<ApplicationCache>
    {
        [SerializeField] private bool firstRun = true;
        [SerializeField] public string firstRunAtString;
        [SerializeField] public string instanceIdString;
        [SerializeField] private bool initialized = false;
        [NonSerialized] private Guid? instanceId;
        [NonSerialized] private bool? firstRunValue;
        [NonSerialized] public DateTimeOffset? firstRunAtValue;

        public bool FirstRun
        {
            get
            {
                EnsureFirstRun();
                return firstRunValue.Value;
            }
        }

        public DateTimeOffset FirstRunAt
        {
            get
            {
                EnsureFirstRun();

                if (!firstRunAtValue.HasValue)
                {
                    DateTimeOffset dt;
                    if (!DateTimeOffset.TryParseExact(firstRunAtString.ToEmptyIfNull(), Constants.Iso8601Formats,
                            CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
                    {
                        dt = DateTimeOffset.Now;
                    }
                    FirstRunAt = dt;
                }

                return firstRunAtValue.Value;
            }
            private set
            {
                firstRunAtString = value.ToString(Constants.Iso8601Format);
                firstRunAtValue = value;
            }
        }

        private void EnsureFirstRun()
        {
            if (!firstRunValue.HasValue)
            {
                firstRunValue = firstRun;
            }
        }

        public Guid InstanceId
        {
            get
            {
                EnsureInstanceId();
                return instanceId.Value;
            }
        }

        private void EnsureInstanceId()
        {
            if (instanceId.HasValue)
            {
                return;
            }

            if (string.IsNullOrEmpty(instanceIdString))
            {
                instanceId = Guid.NewGuid();
                instanceIdString = instanceId.ToString();
            }
            else
            {
                instanceId = new Guid(instanceIdString);
            }
        }

        public bool Initialized
        {
            get { return initialized; }
            set
            {
                initialized = value;
                if (initialized && firstRun)
                {
                    firstRun = false;
                    FirstRunAt = DateTimeOffset.Now;
                }
                Save(true);
            }
        }
    }

    sealed class EnvironmentCache : ScriptObjectSingleton<EnvironmentCache>
    {
        [NonSerialized] private IEnvironment environment;
        [SerializeField] private string extensionInstallPath;
        [SerializeField] private string repositoryPath;
        [SerializeField] private string unityApplication;
        [SerializeField] private string unityApplicationContents;
        [SerializeField] private string unityAssetsPath;
        [SerializeField] private string unityVersion;

        public void Flush()
        {
            repositoryPath = Environment.RepositoryPath;
            unityApplication = Environment.UnityApplication;
            unityApplicationContents = Environment.UnityApplicationContents;
            unityAssetsPath = Environment.UnityAssetsPath;
            extensionInstallPath = Environment.ExtensionInstallPath;
            Save(true);
        }

        private NPath DetermineInstallationPath()
        {
            // Juggling to find out where we got installed
            var shim = CreateInstance<RunLocationShim>();
            var script = MonoScript.FromScriptableObject(shim);
            var scriptPath = Application.dataPath.ToNPath().Parent.Combine(AssetDatabase.GetAssetPath(script).ToNPath());
            DestroyImmediate(shim);
            return scriptPath.Parent;
        }

        public IEnvironment Environment
        {
            get
            {
                if (environment == null)
                {
                    var cacheContainer = new CacheContainer();
                    cacheContainer.SetCacheInitializer(CacheType.Branches, () => BranchesCache.Instance);
                    cacheContainer.SetCacheInitializer(CacheType.GitAheadBehind, () => GitAheadBehindCache.Instance);
                    cacheContainer.SetCacheInitializer(CacheType.GitLocks, () => GitLocksCache.Instance);
                    cacheContainer.SetCacheInitializer(CacheType.GitLog, () => GitLogCache.Instance);
                    cacheContainer.SetCacheInitializer(CacheType.GitFileLog, () => GitFileLogCache.Instance);
                    cacheContainer.SetCacheInitializer(CacheType.GitStatus, () => GitStatusCache.Instance);
                    cacheContainer.SetCacheInitializer(CacheType.GitUser, () => GitUserCache.Instance);
                    cacheContainer.SetCacheInitializer(CacheType.RepositoryInfo, () => RepositoryInfoCache.Instance);

                    environment = new DefaultEnvironment(cacheContainer);
                    if (unityApplication == null)
                    {
                        unityAssetsPath = Application.dataPath;
                        unityApplication = EditorApplication.applicationPath;
                        unityApplicationContents = EditorApplication.applicationContentsPath;
                        extensionInstallPath = DetermineInstallationPath();
                        unityVersion = Application.unityVersion;
                    }
                    environment.Initialize(unityVersion, extensionInstallPath.ToNPath(), unityApplication.ToNPath(),
                        unityApplicationContents.ToNPath(), unityAssetsPath.ToNPath());
                    NPath? path = null;
                    if (!String.IsNullOrEmpty(repositoryPath))
                        path = repositoryPath.ToNPath();
                    environment.InitializeRepository(path);
                    Flush();
                }
                return environment;
            }
        }
    }

    abstract class ManagedCacheBase<T> : ScriptObjectSingleton<T> where T : ScriptableObject, IManagedCache
    {
        [SerializeField] private CacheType cacheType;
        [SerializeField] private string lastUpdatedAtString = DateTimeOffset.MinValue.ToString(Constants.Iso8601Format);
        [SerializeField] private string initializedAtString = DateTimeOffset.MinValue.ToString(Constants.Iso8601Format);
        [NonSerialized] private DateTimeOffset? lastUpdatedAtValue;
        [NonSerialized] private DateTimeOffset? initializedAtValue;
        [NonSerialized] private bool isInvalidating;
        [NonSerialized] protected bool forcedInvalidation;

        public event Action<CacheType> CacheInvalidated;
        public event Action<CacheType, DateTimeOffset> CacheUpdated;

        protected ManagedCacheBase(CacheType type)
        {
            Logger = LogHelper.GetLogger(GetType());
            CacheType = type;
        }

        public bool ValidateData()
        {
            var isInitialized = IsInitialized;
            var timedOut = DateTimeOffset.Now - LastUpdatedAt > DataTimeout;
            var needsInvalidation = !isInitialized || timedOut;
            if (needsInvalidation && !isInvalidating)
            {
                Logger.Trace("needsInvalidation isInitialized:{0} timedOut:{1}", isInitialized, timedOut);
                Invalidate();
            }
            return !needsInvalidation;
        }

        public void InvalidateData()
        {
            forcedInvalidation = true;
            Invalidate();
        }

        private void Invalidate()
        {
            isInvalidating = true;
            LastUpdatedAt = DateTimeOffset.MinValue;
            CacheInvalidated.SafeInvoke(CacheType);
        }

        public void ResetInvalidation()
        {
            isInvalidating = false;
        }

        protected void SaveData(DateTimeOffset now, bool isChanged)
        {
            var isInitialized = IsInitialized;
            isChanged = isChanged || !isInitialized;

            InitializedAt = !isInitialized || InitializedAt == DateTimeOffset.MinValue ? now : InitializedAt;
            LastUpdatedAt = isChanged || LastUpdatedAt == DateTimeOffset.MinValue ? now : LastUpdatedAt;

            Save(true);

            isInvalidating = false;

            if (isChanged)
            {
                CacheUpdated.SafeInvoke(CacheType, now);
            }
        }

        public abstract TimeSpan DataTimeout { get; }
        public string LastUpdatedAtString
        {
            get { return lastUpdatedAtString; }
            private set { lastUpdatedAtString = value; }
        }

        public string InitializedAtString
        {
            get { return initializedAtString; }
            private set { initializedAtString = value; }
        }

        public bool IsInitialized { get { return ApplicationCache.Instance.FirstRunAt <= InitializedAt; } }

        public DateTimeOffset LastUpdatedAt
        {
            get
            {
                if (!lastUpdatedAtValue.HasValue)
                {
                    DateTimeOffset result;
                    if (DateTimeOffset.TryParseExact(LastUpdatedAtString.ToEmptyIfNull(), Constants.Iso8601Formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
                    {
                        lastUpdatedAtValue = result;
                    }
                    else
                    {
                        LastUpdatedAt = DateTimeOffset.MinValue;
                    }
                }

                return lastUpdatedAtValue.Value;
            }
            set
            {
                LastUpdatedAtString = value.ToString(Constants.Iso8601Format);
                lastUpdatedAtValue = value;
            }
        }

        public DateTimeOffset InitializedAt
        {
            get
            {
                if (!initializedAtValue.HasValue)
                {
                    DateTimeOffset result;
                    if (DateTimeOffset.TryParseExact(InitializedAtString.ToEmptyIfNull(), Constants.Iso8601Formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
                    {
                        initializedAtValue = result;
                    }
                    else
                    {
                        InitializedAt = DateTimeOffset.MinValue;
                    }
                }

                return initializedAtValue.Value;
            }
            set
            {
                InitializedAtString = value.ToString(Constants.Iso8601Format);
                initializedAtValue = value;
            }
        }

        public CacheType CacheType { get { return cacheType; } private set { cacheType = value; } }

        protected ILogging Logger { get; private set; }
    }

    [Serializable]
    class LocalConfigBranchDictionary : SerializableDictionary<string, ConfigBranch>, ILocalConfigBranchDictionary
    {
        public LocalConfigBranchDictionary()
        { }

        public LocalConfigBranchDictionary(IDictionary<string, ConfigBranch> dictionary) : base()
        {
            foreach (var pair in dictionary)
            {
                this.Add(pair.Key, pair.Value);
            }
        }
    }

    [Serializable]
    public class ArrayContainer<T>
    {
        [SerializeField] public T[] Values = new T[0];
    }

    [Serializable]
    public class StringArrayContainer : ArrayContainer<string>
    {}

    [Serializable]
    public class ConfigBranchArrayContainer : ArrayContainer<ConfigBranch>
    {}

    [Serializable]
    class RemoteConfigBranchDictionary : Dictionary<string, Dictionary<string, ConfigBranch>>, ISerializationCallbackReceiver, IRemoteConfigBranchDictionary
    {
        [SerializeField] private string[] keys = new string[0];
        [SerializeField] private StringArrayContainer[] subKeys = new StringArrayContainer[0];
        [SerializeField] private ConfigBranchArrayContainer[] subKeyValues = new ConfigBranchArrayContainer[0];

        public RemoteConfigBranchDictionary()
        { }

        public RemoteConfigBranchDictionary(Dictionary<string, Dictionary<string, ConfigBranch>> dictionary)
        {
            foreach (var pair in dictionary)
            {
                Add(pair.Key, pair.Value.ToDictionary(valuePair => valuePair.Key, valuePair => valuePair.Value));
            }
        }

        // save the dictionary to lists
        public void OnBeforeSerialize()
        {
            var keyList = new List<string>();
            var subKeysList = new List<StringArrayContainer>();
            var subKeysValuesList = new List<ConfigBranchArrayContainer>();

            foreach (var pair in this)
            {
                var pairKey = pair.Key;
                keyList.Add(pairKey);

                var serializeSubKeys = new List<string>();
                var serializeSubKeyValues = new List<ConfigBranch>();

                var subDictionary = pair.Value;
                foreach (var subPair in subDictionary)
                {
                    serializeSubKeys.Add(subPair.Key);
                    serializeSubKeyValues.Add(subPair.Value);
                }

                subKeysList.Add(new StringArrayContainer { Values = serializeSubKeys.ToArray() });
                subKeysValuesList.Add(new ConfigBranchArrayContainer { Values = serializeSubKeyValues.ToArray() });
            }

            keys = keyList.ToArray();
            subKeys = subKeysList.ToArray();
            subKeyValues = subKeysValuesList.ToArray();
        }

        // load dictionary from lists
        public void OnAfterDeserialize()
        {
            Clear();

            if (keys.Length != subKeys.Length || subKeys.Length != subKeyValues.Length)
            {
                throw new SerializationException("Deserialization length mismatch");
            }

            for (var remoteIndex = 0; remoteIndex < keys.Length; remoteIndex++)
            {
                var remote = keys[remoteIndex];

                var subKeyContainer = subKeys[remoteIndex];
                var subKeyValueContainer = subKeyValues[remoteIndex];

                if (subKeyContainer.Values.Length != subKeyValueContainer.Values.Length)
                {
                    throw new SerializationException("Deserialization length mismatch");
                }

                var branchesDictionary = new Dictionary<string, ConfigBranch>();
                for (var branchIndex = 0; branchIndex < subKeyContainer.Values.Length; branchIndex++)
                {
                    var remoteBranchKey = subKeyContainer.Values[branchIndex];
                    var remoteBranch = subKeyValueContainer.Values[branchIndex];

                    branchesDictionary.Add(remoteBranchKey, remoteBranch);
                }

                Add(remote, branchesDictionary);
            }
        }
    }

    [Serializable]
    class ConfigRemoteDictionary : SerializableDictionary<string, ConfigRemote>, IConfigRemoteDictionary
    {
        public ConfigRemoteDictionary()
        { }

        public ConfigRemoteDictionary(IDictionary<string, ConfigRemote> dictionary)
        {
            foreach (var pair in dictionary)
            {
                this.Add(pair.Key, pair.Value);
            }
        }
    }

    [Location("cache/repoinfo.yaml", LocationAttribute.Location.LibraryFolder)]
    sealed class RepositoryInfoCache : ManagedCacheBase<RepositoryInfoCache>, IRepositoryInfoCache
    {
        [SerializeField] private GitRemote currentGitRemote;
        [SerializeField] private GitBranch currentGitBranch;
        [SerializeField] private ConfigBranch currentConfigBranch;
        [SerializeField] private ConfigRemote currentConfigRemote;
        [SerializeField] private string currentHead;

        public RepositoryInfoCache() : base(CacheType.RepositoryInfo)
        { }

        public void UpdateData(IRepositoryInfoCacheData data)
        {
            var now = DateTimeOffset.Now;
            var isUpdated = false;

            if (forcedInvalidation || !Nullable.Equals(currentGitRemote, data.CurrentGitRemote))
            {
                currentGitRemote = data.CurrentGitRemote ?? GitRemote.Default;
                isUpdated = true;
            }

            if (forcedInvalidation || !Nullable.Equals(currentGitBranch, data.CurrentGitBranch))
            {
                currentGitBranch = data.CurrentGitBranch ?? GitBranch.Default;
                isUpdated = true;
            }

            if (forcedInvalidation || !Nullable.Equals(currentConfigRemote, data.CurrentConfigRemote))
            {
                currentConfigRemote = data.CurrentConfigRemote ?? ConfigRemote.Default;
                isUpdated = true;
            }

            if (forcedInvalidation || !Nullable.Equals(currentConfigBranch, data.CurrentConfigBranch))
            {
                currentConfigBranch = data.CurrentConfigBranch ?? ConfigBranch.Default;
                isUpdated = true;
            }

            if (forcedInvalidation || !String.Equals(currentHead, data.CurrentHead))
            {
                currentHead = data.CurrentHead;
                isUpdated = true;
            }

            SaveData(now, isUpdated);
        }

        public GitRemote? CurrentGitRemote
        {
            get
            {
                ValidateData();
                return currentGitRemote.Equals(GitRemote.Default) ? (GitRemote?)null : currentGitRemote;
            }
        }

        public GitBranch? CurrentGitBranch
        {
            get
            {
                ValidateData();
                return currentGitBranch.Equals(GitBranch.Default) ? (GitBranch?)null : currentGitBranch;
            }
        }

        public ConfigRemote? CurrentConfigRemote
        {
            get
            {
                ValidateData();
                return currentConfigRemote.Equals(ConfigRemote.Default) ? (ConfigRemote?)null : currentConfigRemote;
            }
        }

        public ConfigBranch? CurrentConfigBranch
        {
            get
            {
                ValidateData();
                return currentConfigBranch.Equals(ConfigBranch.Default) ? (ConfigBranch?)null : currentConfigBranch;
            }
        }

        public string CurrentHead
        {
            get
            {
                ValidateData();
                return currentHead;
            }
        }

        public override TimeSpan DataTimeout { get { return TimeSpan.FromDays(1); } }
    }

    [Location("cache/branches.yaml", LocationAttribute.Location.LibraryFolder)]
    sealed class BranchesCache : ManagedCacheBase<BranchesCache>, IBranchCache
    {
        [SerializeField] private GitBranch[] localBranches = new GitBranch[0];
        [SerializeField] private GitBranch[] remoteBranches = new GitBranch[0];
        [SerializeField] private GitRemote[] remotes = new GitRemote[0];

        [SerializeField] private LocalConfigBranchDictionary localConfigBranches = new LocalConfigBranchDictionary();
        [SerializeField] private RemoteConfigBranchDictionary remoteConfigBranches = new RemoteConfigBranchDictionary();
        [SerializeField] private ConfigRemoteDictionary configRemotes = new ConfigRemoteDictionary();

        public BranchesCache() : base(CacheType.Branches)
        { }

        public void SetRemotes(Dictionary<string, ConfigRemote> remoteConfigs, Dictionary<string, Dictionary<string, ConfigBranch>> configBranches, GitRemote[] gitRemotes, GitBranch[] gitBranches)
        {
            var now = DateTimeOffset.Now;
            configRemotes = new ConfigRemoteDictionary(remoteConfigs);
            remoteConfigBranches = new RemoteConfigBranchDictionary(configBranches);
            remotes = gitRemotes;
            remoteBranches = gitBranches;
            SaveData(now, true);
        }

        public void SetLocals(Dictionary<string, ConfigBranch> configBranches, GitBranch[] gitBranches)
        {
            var now = DateTimeOffset.Now;
            localConfigBranches = new LocalConfigBranchDictionary(configBranches);
            localBranches = gitBranches;
            SaveData(now, true);
        }

        public ILocalConfigBranchDictionary LocalConfigBranches { get { return localConfigBranches; } }
        public IRemoteConfigBranchDictionary RemoteConfigBranches { get { return remoteConfigBranches; } }
        public IConfigRemoteDictionary ConfigRemotes { get { return configRemotes; } }
        public GitBranch[] LocalBranches { get { return localBranches; } }
        public GitBranch[] RemoteBranches { get { return remoteBranches; } }
        public GitRemote[] Remotes { get { return remotes; } }
        public override TimeSpan DataTimeout { get { return TimeSpan.FromDays(1); } }
    }

    [Location("cache/gitlog.yaml", LocationAttribute.Location.LibraryFolder)]
    sealed class GitLogCache : ManagedCacheBase<GitLogCache>, IGitLogCache
    {
        [SerializeField] private List<GitLogEntry> log = new List<GitLogEntry>();

        public GitLogCache() : base(CacheType.GitLog)
        { }

        public List<GitLogEntry> Log
        {
            get
            {
                ValidateData();
                return log;
            }
            set
            {
                var now = DateTimeOffset.Now;
                var isUpdated = false;

                if (value == null)
                {
                    if (forcedInvalidation || log.Count > 0)
                    {
                        log.Clear();
                        isUpdated = true;
                    }
                }
                else if (forcedInvalidation || !log.SequenceEqual(value))
                {
                    log = value;
                    isUpdated = true;
                }

                SaveData(now, isUpdated);
            }
        }

        public override TimeSpan DataTimeout { get { return TimeSpan.FromMinutes(1); } }
    }

    [Location("cache/gitfilelog.yaml", LocationAttribute.Location.LibraryFolder)]
    sealed class GitFileLogCache : ManagedCacheBase<GitFileLogCache>, IGitFileLogCache
    {
        [SerializeField] private GitFileLog fileLog = GitFileLog.Default;

        public GitFileLogCache() : base(CacheType.GitFileLog)
        { }

        public GitFileLog FileLog
        {
            get
            {
                ValidateData();
                return fileLog;
            }
            set
            {
                var now = DateTimeOffset.Now;
                var isUpdated = false;

                var shouldUpdate = forcedInvalidation;

                if (!shouldUpdate)
                {
                    shouldUpdate = true;
                }

                if (shouldUpdate)
                {
                    fileLog = value;
                    isUpdated = true;
                }

                SaveData(now, isUpdated);
            }
        }

        public override TimeSpan DataTimeout { get { return TimeSpan.FromMinutes(1); } }
    }

    [Location("cache/gittrackingstatus.yaml", LocationAttribute.Location.LibraryFolder)]
    sealed class GitAheadBehindCache : ManagedCacheBase<GitAheadBehindCache>, IGitAheadBehindCache
    {
        [SerializeField] private int ahead;
        [SerializeField] private int behind;

        public GitAheadBehindCache() : base(CacheType.GitAheadBehind)
        { }

        public int Ahead
        {
            get
            {
                ValidateData();
                return ahead;
            }
            set
            {
                var now = DateTimeOffset.Now;
                var isUpdated = false;

                if (forcedInvalidation || ahead != value)
                {
                    ahead = value;
                    isUpdated = true;
                }

                SaveData(now, isUpdated);
            }
        }

        public int Behind
        {
            get
            {
                ValidateData();
                return behind;
            }
            set
            {
                var now = DateTimeOffset.Now;
                var isUpdated = false;

                if (forcedInvalidation || behind != value)
                {
                    behind = value;
                    isUpdated = true;
                }

                SaveData(now, isUpdated);
            }
        }

        public override TimeSpan DataTimeout { get { return TimeSpan.FromMinutes(1); } }
    }

    [Location("cache/gitstatusentries.yaml", LocationAttribute.Location.LibraryFolder)]
    sealed class GitStatusCache : ManagedCacheBase<GitStatusCache>, IGitStatusCache
    {
        [SerializeField] private List<GitStatusEntry> entries = new List<GitStatusEntry>();

        public GitStatusCache() : base(CacheType.GitStatus)
        { }

        public List<GitStatusEntry> Entries
        {
            get
            {
                ValidateData();
                return entries;
            }
            set
            {
                var now = DateTimeOffset.Now;
                var isUpdated = false;

                if (value == null)
                {
                    if (forcedInvalidation || entries.Count > 0)
                    {
                        entries.Clear();
                        isUpdated = true;
                    }
                }
                else if (forcedInvalidation || !entries.SequenceEqual(value))
                {
                    entries = value;
                    isUpdated = true;
                }

                SaveData(now, isUpdated);
            }
        }

        public override TimeSpan DataTimeout { get { return TimeSpan.FromMinutes(1); } }
    }

    [Location("cache/gitlocks.yaml", LocationAttribute.Location.LibraryFolder)]
    sealed class GitLocksCache : ManagedCacheBase<GitLocksCache>, IGitLocksCache
    {
        [SerializeField] private List<GitLock> gitLocks = new List<GitLock>();

        public GitLocksCache() : base(CacheType.GitLocks)
        { }

        public List<GitLock> GitLocks
        {
            get
            {
                ValidateData();
                return gitLocks;
            }
            set
            {
                var now = DateTimeOffset.Now;
                var isUpdated = false;

                if (value == null)
                {
                    if (forcedInvalidation || gitLocks.Count > 0)
                    {
                        gitLocks.Clear();
                        isUpdated = true;
                    }
                }
                else if (forcedInvalidation || !gitLocks.SequenceEqual(value))
                {
                    gitLocks = value;
                    isUpdated = true;
                }

                SaveData(now, isUpdated);
            }
        }

        public override TimeSpan DataTimeout { get { return TimeSpan.FromMinutes(1); } }
    }

    [Location("cache/gituser.yaml", LocationAttribute.Location.LibraryFolder)]
    sealed class GitUserCache : ManagedCacheBase<GitUserCache>, IGitUserCache
    {
        [SerializeField] private string gitName;
        [SerializeField] private string gitEmail;

        public GitUserCache() : base(CacheType.GitUser)
        {}

        public string Name
        {
            get
            {
                ValidateData();
                return gitName;
            }
            set
            {
                var now = DateTimeOffset.Now;
                var isUpdated = false;

                if (forcedInvalidation || gitName != value)
                {
                    gitName = value;
                    isUpdated = true;
                }

                SaveData(now, isUpdated);
            }
        }

        public string Email
        {
            get
            {
                ValidateData();
                return gitEmail;
            }
            set
            {
                var now = DateTimeOffset.Now;
                var isUpdated = false;

                if (forcedInvalidation || gitEmail != value)
                {
                    gitEmail = value;
                    isUpdated = true;
                }

                SaveData(now, isUpdated);
            }
        }

        public override TimeSpan DataTimeout { get { return TimeSpan.FromMinutes(10); } }
    }
}


text:
#pragma once
#include <aws/iotanalytics/IoTAnalytics_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace IoTAnalytics
{
namespace Model
{

  /**
   *
 Used to store data used by IoT SiteWise in an Amazon S3 bucket that you
   * manage. You can't change the choice of Amazon S3 storage after your data store
   * is created.

See Also:
   AWS
   * API Reference

   */
  class AWS_IOTANALYTICS_API IotSiteWiseCustomerManagedDatastoreS3Storage
  {
  public:
    IotSiteWiseCustomerManagedDatastoreS3Storage();
    IotSiteWiseCustomerManagedDatastoreS3Storage(Aws::Utils::Json::JsonView jsonValue);
    IotSiteWiseCustomerManagedDatastoreS3Storage& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
 The name of the Amazon S3 bucket where your data is stored.

     */
    inline const Aws::String& GetBucket() const{ return m_bucket; }

    /**
     *
 The name of the Amazon S3 bucket where your data is stored.

     */
    inline bool BucketHasBeenSet() const { return m_bucketHasBeenSet; }

    /**
     *
 The name of the Amazon S3 bucket where your data is stored.

     */
    inline void SetBucket(const Aws::String& value) { m_bucketHasBeenSet = true; m_bucket = value; }

    /**
     *
 The name of the Amazon S3 bucket where your data is stored.

     */
    inline void SetBucket(Aws::String&& value) { m_bucketHasBeenSet = true; m_bucket = std::move(value); }

    /**
     *
 The name of the Amazon S3 bucket where your data is stored.

     */
    inline void SetBucket(const char* value) { m_bucketHasBeenSet = true; m_bucket.assign(value); }

    /**
     *
 The name of the Amazon S3 bucket where your data is stored.

     */
    inline IotSiteWiseCustomerManagedDatastoreS3Storage& WithBucket(const Aws::String& value) { SetBucket(value); return *this;}

    /**
     *
 The name of the Amazon S3 bucket where your data is stored.

     */
    inline IotSiteWiseCustomerManagedDatastoreS3Storage& WithBucket(Aws::String&& value) { SetBucket(std::move(value)); return *this;}

    /**
     *
 The name of the Amazon S3 bucket where your data is stored.

     */
    inline IotSiteWiseCustomerManagedDatastoreS3Storage& WithBucket(const char* value) { SetBucket(value); return *this;}

    /**
     *
 (Optional) The prefix used to create the keys of the data store data
     * objects. Each object in an Amazon S3 bucket has a key that is its unique
     * identifier in the bucket. Each object in a bucket has exactly one key. The
     * prefix must end with a forward slash (/).

     */
    inline const Aws::String& GetKeyPrefix() const{ return m_keyPrefix; }

    /**
     *
 (Optional) The prefix used to create the keys of the data store data
     * objects. Each object in an Amazon S3 bucket has a key that is its unique
     * identifier in the bucket. Each object in a bucket has exactly one key. The
     * prefix must end with a forward slash (/).

     */
    inline bool KeyPrefixHasBeenSet() const { return m_keyPrefixHasBeenSet; }

    /**
     *
 (Optional) The prefix used to create the keys of the data store data
     * objects. Each object in an Amazon S3 bucket has a key that is its unique
     * identifier in the bucket. Each object in a bucket has exactly one key. The
     * prefix must end with a forward slash (/).

     */
    inline void SetKeyPrefix(const Aws::String& value) { m_keyPrefixHasBeenSet = true; m_keyPrefix = value; }

    /**
     *
 (Optional) The prefix used to create the keys of the data store data
     * objects. Each object in an Amazon S3 bucket has a key that is its unique
     * identifier in the bucket. Each object in a bucket has exactly one key. The
     * prefix must end with a forward slash (/).

     */
    inline void SetKeyPrefix(Aws::String&& value) { m_keyPrefixHasBeenSet = true; m_keyPrefix = std::move(value); }

    /**
     *
 (Optional) The prefix used to create the keys of the data store data
     * objects. Each object in an Amazon S3 bucket has a key that is its unique
     * identifier in the bucket. Each object in a bucket has exactly one key. The
     * prefix must end with a forward slash (/).

     */
    inline void SetKeyPrefix(const char* value) { m_keyPrefixHasBeenSet = true; m_keyPrefix.assign(value); }

    /**
     *
 (Optional) The prefix used to create the keys of the data store data
     * objects. Each object in an Amazon S3 bucket has a key that is its unique
     * identifier in the bucket. Each object in a bucket has exactly one key. The
     * prefix must end with a forward slash (/).

     */
    inline IotSiteWiseCustomerManagedDatastoreS3Storage& WithKeyPrefix(const Aws::String& value) { SetKeyPrefix(value); return *this;}

    /**
     *
 (Optional) The prefix used to create the keys of the data store data
     * objects. Each object in an Amazon S3 bucket has a key that is its unique
     * identifier in the bucket. Each object in a bucket has exactly one key. The
     * prefix must end with a forward slash (/).

     */
    inline IotSiteWiseCustomerManagedDatastoreS3Storage& WithKeyPrefix(Aws::String&& value) { SetKeyPrefix(std::move(value)); return *this;}

    /**
     *
 (Optional) The prefix used to create the keys of the data store data
     * objects. Each object in an Amazon S3 bucket has a key that is its unique
     * identifier in the bucket. Each object in a bucket has exactly one key. The
     * prefix must end with a forward slash (/).

     */
    inline IotSiteWiseCustomerManagedDatastoreS3Storage& WithKeyPrefix(const char* value) { SetKeyPrefix(value); return *this;}

  private:

    Aws::String m_bucket;
    bool m_bucketHasBeenSet = false;

    Aws::String m_keyPrefix;
    bool m_keyPrefixHasBeenSet = false;
  };

} // namespace Model
} // namespace IoTAnalytics
} // namespace Aws


text:
drop table if exists grand_child1;
drop table if exists grand_child2;
drop table if exists grand_child3;
drop table if exists grand_child4;
drop table if exists child1;
drop table if exists child2;
drop table if exists parent;
create table parent (a int primary key);
create table child1 (a int, b int primary key, foreign key (a) references parent(a) on delete CASCADE);
create table child2 (a int, b int primary key, foreign key (a) references parent(a) on delete CASCADE);
create table grand_child1 (b int, c int primary key, foreign key (b) references child1(b) on delete CASCADE);
create table grand_child2 (b int, c int primary key, foreign key (b) references child1(b) on delete CASCADE);
create table grand_child3 (b int, c int primary key, foreign key (b) references child2(b) on delete CASCADE);
create table grand_child4 (b int, c int primary key, foreign key (b) references child2(b) on delete CASCADE);
insert into parent values(3);
insert into child1 values(3,3);
insert into child2 values(3,3);
insert into grand_child1 values(3,3);
insert into grand_child2 values(3,3);
insert into grand_child3 values(3,3);
insert into grand_child4 values(3,3);
truncate parent;
select count(*) from parent;
select count(*) from child1;
select count(*) from child2;
select count(*) from grand_child1;
select count(*) from grand_child2;
select count(*) from grand_child3;
select count(*) from grand_child4;
truncate parent cascade;
select count(*) from parent;
select count(*) from child1;
select count(*) from child2;
select count(*) from grand_child1;
select count(*) from grand_child2;
select count(*) from grand_child3;
select count(*) from grand_child4;
drop grand_child1;
drop grand_child2;
drop grand_child3;
drop grand_child4;
drop child1;
drop child2;
drop parent;


text:
require 'ffi'

# rubocop:disable Style/SymbolArray

# A module wrapping all of the needed calls for libuv
module UV
  extend FFI::Library
  ffi_lib 'uv'

  # Constants
  DEFAULT_BACKLOG = 128
  EOF = -4095

  # Types
  class Buf < FFI::Struct
    layout :base, :pointer,
           :len,  :size_t
  end

  # Wrapper class for struct sockaddr_in
  if /darwin/.match? RUBY_PLATFORM
    # struct sockaddr_in for macOS
    class SockAddrIn < FFI::Struct
      layout :sin_len,    :uint8,
             :sin_family, :sa_family_t,
             :sin_port,   :ushort,
             :sin_addr,   :uint32,
             :sin_zero,   [:uint8, 8]
    end
  else
    # struct sockaddr_in for everyone else
    class SockAddrIn < FFI::Struct #:nodoc:
      layout :sin_family, :sa_family_t,
             :sin_port,   :ushort,
             :sin_addr,   :uint32,
             :sin_zero,   [:uint8, 8]
    end
  end

  typedef :pointer, :uv_async_t
  typedef :pointer, :uv_buf_t
  typedef :pointer, :uv_fs_event_t
  typedef :pointer, :uv_handle_t
  typedef :pointer, :uv_idle_t
  typedef :pointer, :uv_loop_t
  typedef :pointer, :uv_signal_t
  typedef :pointer, :uv_stream_t
  typedef :pointer, :uv_tcp_t
  typedef :pointer, :uv_timer_t

  # Callbacks
  callback :uv_alloc_callback,      [:uv_handle_t, :size_t, :uv_buf_t],    :void
  callback :uv_async_callback,      [:uv_async_t],                         :void
  callback :uv_close_callback,      [:uv_handle_t],                        :void
  callback :uv_connection_callback, [:uv_stream_t, :int],                  :void
  callback :uv_fs_event_callback,   [:uv_fs_event_t, :string, :int, :int], :void
  callback :uv_idle_callback,       [:uv_idle_t],                          :void
  callback :uv_read_callback,       [:uv_stream_t, :ssize_t, :uv_buf_t],   :void
  callback :uv_signal_callback,     [:uv_signal_t, :int],                  :void
  callback :uv_timer_callback,      [:uv_timer_t],                         :void
  callback :uv_walk_callback,       [:uv_handle_t, :pointer],              :void

  # Enums
  enum :uv_fs_event, [
    :rename, 1,
    :change, 2
  ]

  enum :uv_fs_event_flags, [
    :watch_entry, 1,
    :stat,        2,
    :recursive,   4
  ]

  enum :uv_handle_type, [
    :unknown, 0,
    :async,
    :check,
    :fs_event,
    :fs_poll,
    :handle,
    :idle,
    :named_pipe,
    :poll,
    :prepare,
    :process,
    :stream,
    :tcp,
    :timer,
    :tty,
    :udp,
    :signal,
    :file,
    :handle_type_max
  ]

  enum :uv_run_mode, [
    :default, 0,
    :once,
    :nowait
  ]

  # Utility Methods
  attach_function 'strerror', :uv_strerror, [:int], :string, blocking: true
  attach_function 'version', :uv_version, [], :uint
  attach_function 'version_string', :uv_version_string, [], :string, blocking: true
  attach_function 'walk', :uv_walk, [:uv_loop_t, :uv_walk_callback, :pointer], :void, blocking: true

  # Loop Methods
  attach_function 'default_loop', :uv_default_loop, [], :uv_loop_t, blocking: true
  attach_function 'loop_close', :uv_loop_close, [:uv_loop_t], :int, blocking: true
  attach_function 'loop_init', :uv_loop_init, [:uv_loop_t], :int, blocking: true
  attach_function 'loop_size', :uv_loop_size, [], :size_t, blocking: true
  attach_function 'now', :uv_now, [:uv_loop_t], :uint64, blocking: true
  attach_function 'run', :uv_run, [:uv_loop_t, :uv_run_mode], :int, blocking: true
  attach_function 'stop', :uv_stop, [:uv_loop_t], :void, blocking: true

  # Handle Methods
  attach_function 'close', :uv_close, [:uv_handle_t, :uv_close_callback], :void, blocking: true
  attach_function 'handle_size', :uv_handle_size, [:uv_handle_type], :size_t
  attach_function 'is_closing', :uv_is_closing, [:uv_handle_t], :int
  attach_function 'is_active', :uv_is_active, [:uv_handle_t], :int, blocking: true

  # Async
  attach_function 'async_init', :uv_async_init, [:uv_loop_t, :uv_async_t, :uv_async_callback], :int, blocking: true
  attach_function 'async_send', :uv_async_send, [:uv_async_t], :int, blocking: true

  # FS Event Methods
  attach_function 'fs_event_init', :uv_fs_event_init, [:uv_loop_t, :uv_fs_event_t], :int, blocking: true
  attach_function 'fs_event_start', :uv_fs_event_start, [:uv_fs_event_t, :uv_fs_event_callback, :string, :int], :int, blocking: true
  attach_function 'fs_event_stop', :uv_fs_event_stop, [:uv_fs_event_t], :int, blocking: true

  # Idle Methods
  attach_function 'idle_init', :uv_idle_init, [:uv_loop_t, :uv_idle_t], :int, blocking: true
  attach_function 'idle_start', :uv_idle_start, [:uv_idle_t, :uv_idle_callback], :int, blocking: true
  attach_function 'idle_stop', :uv_idle_stop, [:uv_idle_t], :int, blocking: true

  # Networking Methods
  attach_function 'accept', :uv_accept, [:uv_loop_t, :uv_stream_t], :int, blocking: true
  attach_function 'ip4_addr', :uv_ip4_addr, [:string, :int, :pointer], :int, blocking: true
  attach_function 'listen', :uv_listen, [:uv_stream_t, :int, :uv_connection_callback], :int, blocking: true

  # Signal Methods
  attach_function 'signal_init', :uv_signal_init, [:uv_loop_t, :uv_signal_t], :int, blocking: true
  attach_function 'signal_start', :uv_signal_start, [:uv_signal_t, :uv_signal_callback, :int], :int, blocking: true
  attach_function 'signal_stop', :uv_signal_stop, [:uv_signal_t], :int, blocking: true

  # Stream Methods
  attach_function 'read_start', :uv_read_start, [:uv_stream_t, :uv_alloc_callback, :uv_read_callback], :int, blocking: true

  # TCP Methods
  attach_function 'tcp_bind', :uv_tcp_bind, [:uv_tcp_t, :pointer, :int], :int, blocking: true
  attach_function 'tcp_init', :uv_tcp_init, [:uv_loop_t, :uv_tcp_t], :int, blocking: true

  # Timer Methods
  attach_function 'timer_init', :uv_timer_init, [:uv_loop_t, :uv_timer_t], :int, blocking: true
  attach_function 'timer_restart', :uv_timer_again, [:uv_timer_t], :int, blocking: true
  attach_function 'timer_start', :uv_timer_start, [:uv_timer_t, :uv_timer_callback, :uint64, :uint64], :int, blocking: true
  attach_function 'timer_stop', :uv_timer_stop, [:uv_timer_t], :int, blocking: true
end

# rubocop:enable Style/SymbolArray


text:
FactoryGirl.define do
  factory :weather do
    provider_name 'openweatherdata'
    provider_city_id 2988507
    latitude 48.88
    longitude 2.35
    main 'Clear'
    secondary 'clear sky'
    wind 7.2
    clouds 0.0
    temperature 10.33
    humidity 37
    sunset Time.now
    sunrise Time.now
  end
end


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.VisualStudio.Debugger.Interop;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Microsoft.DebugEngineHost.VSCode
{
    sealed public class ExceptionSettings
    {
        public enum TriggerState
        {
            unhandled = enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE,
            userUnhandled = enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT,
            thrown = enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE | enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_FIRST_CHANCE,
            all = enum_EXCEPTION_STATE.EXCEPTION_STOP_FIRST_CHANCE | enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_FIRST_CHANCE |
                enum_EXCEPTION_STATE.EXCEPTION_STOP_USER_UNCAUGHT | enum_EXCEPTION_STATE.EXCEPTION_STOP_SECOND_CHANCE
        };

        sealed public class CategoryConfiguration
        {
            [JsonRequired]
            public string Name;

            [JsonRequired]
            public Guid Id;

            public Dictionary<string, TriggerState> DefaultTriggers = new Dictionary<string, TriggerState>();
        }

        private IList<CategoryConfiguration> _categories = new List<CategoryConfiguration>();
        private IList<ExceptionBreakpointFilter> _exceptionFilters = new List<ExceptionBreakpointFilter>();

        public IList<CategoryConfiguration> Categories
        {
            get { return _categories; }
        }

        /// <summary>
        /// /*OPTIONAL*/ Set of exception breakpoints that appears in VS Code
        /// </summary>
        public IList<ExceptionBreakpointFilter> ExceptionBreakpointFilters
        {
            get { return _exceptionFilters; }
        }

        internal ExceptionSettings()
        {
        }

        internal void MakeReadOnly()
        {
            _categories = new ReadOnlyCollection<CategoryConfiguration>(_categories);
            _exceptionFilters = new ReadOnlyCollection<ExceptionBreakpointFilter>(_exceptionFilters);
        }
    }
}


text:
package christophedelory.rss;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import christophedelory.rss.media.BaseMedia;
import christophedelory.rss.media.Content;
import christophedelory.rss.media.Group;

/**
 * An item may represent a "story" -- much like a story in a newspaper or magazine;
 * if so its description is a synopsis of the story, and the link points to the full story.
 * An item may also be complete in itself, if so, the description contains the text (entity-encoded HTML is allowed), and the link and title may be omitted.
 * All elements of an item are optional, however at least one of title or description must be present.
 *

 * RSS Media note:
 *

 * While both media contents and media groups have no limitations on the number of times they can appear,
 * the general nature of RSS should be preserved:
 * an item represents a "story".
 * Simply stated, this is similar to the blog style of syndication.
 * However, if one is using this module to strictly publish media, there should be one item element for each media object/group.
 * This is to allow for proper attribution for the origination of the media content through the link element.
 * It also allows the full benefit of the other RSS elements to be realized.
 * @author Christophe Delory
 * @version $Revision: 92 $
 * @castor.class xml="item"
 */
public class Item extends BaseMedia // I don't want regular RSS item to directly extend the group element (Group), as they do not share the same namespace.
{
    /**
     * The title of the item.
     */
    private String _title = null;

    /**
     * The URL of the item.
     */
    private URI _link = null;

    /**
     * The item synopsis.
     */
    private String _description = null;

    /**
     * Email address of the author of the item.
     */
    private String _author = null;

    /**
     * Includes the item in one or more categories.
     */
    private final List<Category> _categories = new ArrayList<Category>();

    /**
     * URL of a page for comments relating to the item.
     */
    private String _comments = null;

    /**
     * Describes a media object that is attached to the item.
     */
    private Enclosure _enclosure = null;

    /**
     * A string that uniquely identifies the item.
     */
    private GUID _guid = null;

    /**
     * Indicates when the item was published.
     */
    private Date _pubDate = null;

    /**
     * The RSS channel that the item came from.
     */
    private Source _source = null;

    /**
     * A list of media contents.
     */
    private final List<Content> _mediaContents = new ArrayList<Content>();

    /**
     * A list of media groups.
     */
    private final List<Group> _mediaGroups = new ArrayList<Group>();

    /**
     * The parent channel element.
     */
    private transient Channel _channel = null;

    /**
     * Returns the title of the item.
     * In 0.91, title is a required sub-element of item.
     * In 0.92, all sub-elements of item are optional.
     * Why? When a RSS file reflects the content of a weblog or "blog" site,
     * the structure required by previous versions of RSS was often impossible to synthesize.
     * For example, there is no actual limit on the number of links a weblog item can have.
     * Example: "Venice Film Festival Tries to Quit Sinking".
     * No default value.
     * @return the item's title. May be null.
     * @see #setTitle
     * @castor.field
     *  get-method="getTitle"
     *  set-method="setTitle"
     * @castor.field-xml
     *  name="title"
     *  node="element"
     */
    public String getTitle()
    {
        return _title;
    }

    /**
     * Initializes the title of the item.
     * @param title the item's title. May be null.
     * @see #getTitle
     */
    public void setTitle(final String title)
    {
        _title = title;
    }

    /**
     * Initializes the URL of the item.
     * @param link an URL as a string. Shall not be null.
     * @throws NullPointerException if link is null.
     * @throws URISyntaxException if the given string violates RFC 2396, as augmented by the {@link URI} deviations.
     * @see #getLinkString
     * @see #setLink
     */
    public void setLinkString(final String link) throws URISyntaxException
    {
        _link = new URI(link); // Throws NullPointerException if link is null. May throw URISyntaxException.
    }

    /**
     * Returns the URL of the item.
     * @return an URL as a string. May be null.
     * @see #setLinkString
     * @see #getLink
     * @castor.field
     *  get-method="getLinkString"
     *  set-method="setLinkString"
     * @castor.field-xml
     *  name="link"
     *  node="element"
     */
    public String getLinkString()
    {
        String ret = null;

        if (_link != null)
        {
            ret = _link.toString();
        }

        return ret;
    }

    /**
     * Initializes the URL of the item.
     * @param link an URL. May be null.
     * @see #getLink
     * @see #setLinkString
     */
    public void setLink(final URI link)
    {
        _link = link;
    }

    /**
     * Returns the URL of the item.
     * In 0.91, link is a required sub-element of item.
     * In 0.92, all sub-elements of item are optional.
     * Why? When a RSS file reflects the content of a weblog or "blog" site,
     * the structure required by previous versions of RSS was often impossible to synthesize.
     * For example, there is no actual limit on the number of links a weblog item can have.
     * Example: "http://nytimes.com/2004/12/07FEST.html".
     * No default value.
     * @return an URL. May be null.
     * @see #setLink
     * @see #getLinkString
     */
    public URI getLink()
    {
        return _link;
    }

    /**
     * Returns the item synopsis.
     * 0.92 allows entity-encoded HTML in the description of an item, to reflect actual practice by bloggers, who are often proficient HTML coders.
     * Example: "Some of the most heated chatter at the Venice Film Festival this week was about the way that the arrival of the stars at the Palazzo del Cinema was being staged.".
     * No default value.
     * @return the item's description. May be null.
     * @see #setDescription
     * @castor.field
     *  get-method="getDescription"
     *  set-method="setDescription"
     * @castor.field-xml
     *  name="description"
     *  node="element"
     */
    public String getDescription()
    {
        return _description;
    }

    /**
     * Initializes the item synopsis.
     * @param description the item's description. May be null.
     * @see #getDescription
     */
    public void setDescription(final String description)
    {
        _description = description;
    }

    /**
     * Returns the email address of the author of the item.
     * For newspapers and magazines syndicating via RSS, the author is the person who wrote the article that the item describes.
     * For collaborative weblogs, the author of the item might be different from the managing editor or webmaster.
     * For a weblog authored by a single individual it would make sense to omit the element.
     * Example: "lawyer@boyer.net (Lawyer Boyer)".
     * No default value.
     * @return the author's email. May be null.
     * @see #setAuthor
     * @since 2.0
     * @castor.field
     *  get-method="getAuthor"
     *  set-method="setAuthor"
     * @castor.field-xml
     *  name="author"
     *  node="element"
     */
    public String getAuthor()
    {
        return _author;
    }

    /**
     * Initializes the email address of the author of the item.
     * @param author the author's email. May be null.
     * @see #getAuthor
     * @since 2.0
     */
    public void setAuthor(final String author)
    {
        _author = author;
    }

    /**
     * Returns a list of one or more item's categories.
     * You may include as many category elements as you need to, for different domains,
     * and to have an item cross-referenced in different parts of the same domain.
     * The list is initially empty.
     * @return a list of categories. May be empty but not null.
     * @see #addCategory
     * @since 0.92
     * @castor.field
     *  get-method="getCategories"
     *  set-method="addCategory"
     *  type="christophedelory.rss.Category"
     *  collection="arraylist"
     * @castor.field-xml
     *  name="category"
     *  node="element"
     */
    public List<Category> getCategories()
    {
        return _categories;
    }

    /**
     * Includes the item in a category.
     * @param category an item's category. Shall not be null.
     * @throws NullPointerException if category is null.
     * @see #getCategories
     * @since 0.92
     */
    public void addCategory(final Category category)
    {
        if (category == null)
        {
            throw new NullPointerException("no category");
        }

        _categories.add(category);
    }

    /**
     * Returns an URL of a page for comments relating to the item.
     * If present, it is the url of the comments page for the item.
     * Example: "http://ekzemplo.com/entry/4403/comments".
     * More about comments here.
     * No default value.
     * @return an URL as a string. May be null.
     * @see #setComments
     * @since 2.0
     * @castor.field
     *  get-method="getComments"
     *  set-method="setComments"
     * @castor.field-xml
     *  name="comments"
     *  node="element"
     */
    public String getComments()
    {
        return _comments;
    }

    /**
     * Initializes an URL of a page for comments relating to the item.
     * @param comments an URL as a string. May be null.
     * @see #getComments
     * @since 2.0
     */
    public void setComments(final String comments)
    {
        _comments = comments;
    }

    /**
     * Describes a media object that is attached to the item.
     * No default value.
     * @return a media descriptor. May be null.
     * @see #setEnclosure
     * @since 0.92
     * @castor.field
     *  get-method="getEnclosure"
     *  set-method="setEnclosure"
     * @castor.field-xml
     *  name="enclosure"
     *  node="element"
     */
    public Enclosure getEnclosure()
    {
        return _enclosure;
    }

    /**
     * Describes a media object that is attached to the item.
     * @param enclosure a media descriptor. May be null.
     * @see #getEnclosure
     * @since 0.92
     */
    public void setEnclosure(final Enclosure enclosure)
    {
        _enclosure = enclosure;
    }

    /**
     * Returns a string that uniquely identifies the item.
     * A frequently asked question about guids is how do they compare to links.
     * Aren't they the same thing?
     * Yes, in some content systems, and no in others.
     * In some systems, link is a permalink to a weblog item.
     * However, in other systems, each item is a synopsis of a longer article, link points to the article, and guid is the permalink to the weblog entry.
     * In all cases, it's recommended that you provide the guid, and if possible make it a permalink.
     * This enables aggregators to not repeat items, even if there have been editing changes.
     * No default value.
     * @return a GUID. May be null.
     * @see #setGuid
     * @since 2.0
     * @castor.field
     *  get-method="getGuid"
     *  set-method="setGuid"
     * @castor.field-xml
     *  name="guid"
     *  node="element"
     */
    public GUID getGuid()
    {
        return _guid;
    }

    /**
     * Initializes a string that uniquely identifies the item.
     * @param guid a GUID. May be null.
     * @see #getGuid
     * @since 2.0
     */
    public void setGuid(final GUID guid)
    {
        _guid = guid;
    }

    /**
     * Indicates when the item was published.
     * @param pubDate a date as a string. Shall not be null.
     * @throws NullPointerException if pubDate is null.
     * @see #getPubDateString
     * @see #setPubDate
     * @since 2.0
     */
    public void setPubDateString(final String pubDate)
    {
        _pubDate = RFC822.valueOf(pubDate); // Throws NullPointerException if pubDate is null.
    }

    /**
     * Indicates when the item was published.
     * @return a date as a string. May be null.
     * @see #setPubDateString
     * @see #getPubDate
     * @since 2.0
     * @castor.field
     *  get-method="getPubDateString"
     *  set-method="setPubDateString"
     * @castor.field-xml
     *  name="pubDate"
     *  node="element"
     */
    public String getPubDateString()
    {
        String ret = null;

        if (_pubDate != null)
        {
            ret = RFC822.toString(_pubDate);
        }

        return ret;
    }

    /**
     * Indicates when the item was published.
     * Its value is a date, indicating when the item was published.
     * If it's a date in the future, aggregators may choose to not display the item until that date.
     * Example: "Sun, 19 May 2002 15:21:36 GMT".
     * No default value.
     * @return a date. May be null.
     * @see #setPubDate
     * @see #getPubDateString
     * @since 2.0
     */
    public Date getPubDate()
    {
        return _pubDate;
    }

    /**
     * Indicates when the item was published.
     * @param pubDate a date. May be null.
     * @see #getPubDate
     * @see #setPubDateString
     * @since 2.0
     */
    public void setPubDate(final Date pubDate)
    {
        _pubDate = pubDate;
    }

    /**
     * Returns the RSS channel that the item came from.
     * No default value.
     * @return the item's source. May be null.
     * @see #setSource
     * @since 0.92
     * @castor.field
     *  get-method="getSource"
     *  set-method="setSource"
     * @castor.field-xml
     *  name="source"
     *  node="element"
     */
    public Source getSource()
    {
        return _source;
    }

    /**
     * Initializes the RSS channel that the item came from.
     * @param source the item's source. May be null.
     * @see #getSource
     * @since 0.92
     */
    public void setSource(final Source source)
    {
        _source = source;
    }

	/**
	 * Adds a media content.
     * @param mediaContent a media content. Shall not be null.
     * @throws NullPointerException if mediaContent is null.
	 * @see #getMediaContents
	 */
	public void addMediaContent(final Content mediaContent)
	{
        if (mediaContent == null)
        {
            throw new NullPointerException("no media content");
        }

		_mediaContents.add(mediaContent);
	}

	/**
	 * Returns the list of media contents.
     * @return a list of media contents. May be empty but not null.
	 * @see #addMediaContent
     * @castor.field
     *  type="christophedelory.rss.media.Content"
     *  get-method="getMediaContents"
     *  set-method="addMediaContent"
     *  collection="arraylist"
     * @castor.field-xml
     *  name="media:content"
     *  node="element"
	 */
	public List<Content> getMediaContents()
	{
		return _mediaContents;
	}

	/**
     * Returns the list of media groups.
     * @return a list of media groups. May be empty but not null.
	 * @see #addMediaGroup
     * @castor.field
     *  type="christophedelory.rss.media.Group"
     *  get-method="getMediaGroups"
     *  set-method="addMediaGroup"
     *  collection="arraylist"
     * @castor.field-xml
     *  name="media:group"
     *  node="element"
	 */
	public List<Group> getMediaGroups()
	{
		return _mediaGroups;
	}

	/**
	 * Adds a media group.
     * @param mediaGroup a media group. Shall not be null.
     * @throws NullPointerException if mediaGroup is null.
	 * @see #getMediaGroups
	 */
	public void addMediaGroup(final Group mediaGroup)
	{
        if (mediaGroup == null)
        {
            throw new NullPointerException("no media group");
        }

		_mediaGroups.add(mediaGroup);
	}

    /**
     * Initializes the parent channel.
     * @param channel the parent channel. May be null.
     * @see #getChannel
     */
    void setChannel(final Channel channel)
    {
        _channel = channel;
    }

    /**
     * Returns the parent channel, if any.
     * @return the parent channel. May be null.
     */
    public Channel getChannel()
    {
        return _channel;
    }
}


text:
layout: errors
title: 500 - Interner Serverfehler
canonical: errors/500.html
sitemap: false
---

Startseite

Blog

Ressourcen

{{ page.title }}

    Ups, da ist wohl etwas schiefgelaufen. Offenbar konnte die angeforderte
    Seite aufgrund von einem internen Serverfehler nicht ausgeliefert werden.

    Dies kann folgende Gründe haben:

Die Seite enthält einen Programmierfehler.

Der Server wurde fehlerhaft konfiguriert.

Der Server ist überlastet.

    Das klingt schrecklich? Keine Angst, ich stehe dir zur Seite!

    Folgendes kannst du z.B. tun:

Überprüfe, ob die komplette Website oder nur einzelne Seiten betroffen sind.

Melde mir den Fehler per E-Mail oder Twitter, damit ich ihn schnellstmöglich beheben kann.

Startseite

Blog

Ressourcen

Impressum

Datenschutz


text:
layout: publication
categories: publication
title: Compositional Computational Reflection
authors: Gregory Malecha, Thomas Braibant, and Adam Chlipala
where: ITP'14
tags:
- mirror-core
- coq
- computational reflection
- automation
abstract: |
  Current work on computational reflection is single-minded; each reflective procedure is written with a specific application or scope in mind. Composition of these reflective procedures is done by a proof- generating tactic language such as Ltac. This composition, however, comes at the cost of both larger proof terms and redundant preprocessing. In this work, we propose a methodology for writing composable reflective procedures that solve many small tasks in a single invocation. The key technical insights are techniques for reasoning semantically about extensible syntax in intensional type theory. Our techniques make it possible to compose sound procedures and write generic procedures parametrized by lemmas mimicking Coq's support for hint databases.
links:
 - download: /publications/files/ccr-itp14.pdf
 - slides: /publications/files/malecha-itp14-slides.pdf
 - publisher's link: http://link.springer.com/chapter/10.1007%2F978-3-319-08970-6_24
 - conference link: http://www.cs.uwyo.edu/~ruben/itp-2014/
---
@incollection{
  year={2014},
  isbn={978-3-319-08969-0},
  booktitle={Interactive Theorem Proving},
  volume={8558},
  series={Lecture Notes in Computer Science},
  editor={Klein, Gerwin and Gamboa, Ruben},
  doi={10.1007/978-3-319-08970-6_24},
  title={Compositional Computational Reflection},
  url={http://dx.doi.org/10.1007/978-3-319-08970-6_24},
  publisher={Springer International Publishing},
  keywords={Computational reflection; automation; Coq; verification},
  author={Malecha, Gregory and Chlipala, Adam and Braibant, Thomas},
  pages={374-389},
  language={English}
}


text:
describe Fastlane::Helper::SentryConfig do
  describe "parse_api_params" do
    it "fails with no API key or auth token" do
      expect do
        Fastlane::Helper::SentryConfig.parse_api_params({})
      end.to raise_error("No API key or authentication token found for SentryAction given, pass using `api_key: 'key'` or `auth_token: 'token'`")
    end

    it "fails with API key and auth token" do
      expect do
        Fastlane::Helper::SentryConfig.parse_api_params({
          api_key: 'something123',
          auth_token: 'something123'
        })
      end.to raise_error("Both API key and authentication token found for SentryAction given, please only give one")
    end
  end
  describe "fallback .sentryclirc" do
    it "auth failing calling sentry-cli info" do
      expect(Fastlane::Helper::SentryConfig.fallback_sentry_cli).to be_falsey
    end
  end
end


text:
'use strict';

const { promisify } = require('util');
const sleep = promisify(setTimeout);

const a = () => sleep(1000).then(() => `scheduler demo - ${(''+Math.floor(Date.now()/1000)).slice(-1)}`);

module.exports = a;


text:
This guide is intended to assist in the migration from the `azure-storage-blob-go` module, or previous betas of `azblob`, to the latest releases of the `azblob` module.

## Simplified API surface area

The redesign of the `azblob` module separates clients into various sub-packages.
In previous versions, the public surface area was "flat", so all clients and supporting types were in the `azblob` package.
This made it difficult to navigate the public surface area.

## Clients

In `azure-storage-blob-go` a client constructor always requires a `url.URL` and `Pipeline` parameters.

In `azblob` a client constructor always requires a `string` URL, any specified credential type, and a `*ClientOptions` for optional values.  You pass `nil` to accept default options.

```go
// new code
client, err := azblob.NewClient("<my storage account URL>", cred, nil)
```

## Authentication

In `azure-storage-blob-go` you created a `Pipeline` with the required credential type. This pipeline was then passed to the client constructor.

In `azblob`, you pass the required credential directly to the client constructor.

```go
// new code.  cred is an AAD token credential created from the azidentity module
client, err := azblob.NewClient("<my storage account URL>", cred, nil)
```

The `azure-storage-blob-go` module provided limited support for OAuth token authentication via `NewTokenCredential`.
This been replaced by using Azure Identity credentials from [azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity#section-readme).

Authentication with a shared key via `NewSharedKeyCredential` remains unchanged.

In `azure-storage-blob-go` you created a `Pipeline` with `NewAnonymousCredential` to support anonymous or SAS authentication.

In `azblob` you use the construtor `NewClientWithNoCredential()` instead.

```go
// new code
client, err := azblob.NewClientWithNoCredential("<public blob or blob with SAS URL>", nil)
```

## Listing blobs/containers

In `azure-storage-blob-go` you explicitly created a `Marker` type that was used to page over results ([example](https://pkg.go.dev/github.com/Azure/azure-storage-blob-go/azblob?utm_source=godoc#example-package)).

In `azblob`, operations that return paginated values return a `*runtime.Pager[T]`.

```go
// new code
pager := client.NewListBlobsFlatPager("my-container", nil)
for pager.More() {
	page, err := pager.NextPage(context.TODO())
	// process results
}
```

## Configuring the HTTP pipeline

In `azure-storage-blob-go` you explicitly created a HTTP pipeline with configuration before creating a client.
This pipeline instance was then passed as an argument to the client constructor ([example](https://pkg.go.dev/github.com/Azure/azure-storage-blob-go/azblob?utm_source=godoc#example-NewPipeline)).

In `azblob` a HTTP pipeline is created during client construction.  The pipeline is configured through the `azcore.ClientOptions` type.

```go
// new code
client, err := azblob.NewClient(account, cred, &azblob.ClientOptions{
	ClientOptions: azcore.ClientOptions{
		// configure HTTP pipeline options here
	},
})
```


text:
'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Items', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING
      },
      long: {
        type: Sequelize.DECIMAL
      },
      lat: {
        type: Sequelize.DECIMAL
      },
      place_id: {
        type: Sequelize.STRING
      },
      place_name: {
        type: Sequelize.STRING
      },
      photo_url: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Items');
  }
};


text:
package org.spanna.command.defaults;

import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.spanna.BanList;
import org.spanna.Spanna;
import org.spanna.ChatColor;
import org.spanna.command.Command;
import org.spanna.command.CommandSender;
import org.spanna.entity.Player;

import com.google.common.collect.ImmutableList;

public class BanIpCommand extends VanillaCommand {
    public static final Pattern ipValidity = Pattern.compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");

    public BanIpCommand() {
        super("ban-ip");
        this.description = "Prevents the specified IP address from using this server";
        this.usageMessage = "/ban-ip <address|player> [reason ...]";
        this.setPermission("spanna.command.ban.ip");
    }

    @Override
    public boolean execute(CommandSender sender, String currentAlias, String[] args) {
        if (!testPermission(sender)) return true;
        if (args.length < 1)  {
            sender.sendMessage(ChatColor.RED + "[ERROR] Usage: " + usageMessage);
            return false;
        }

        String reason = args.length > 0 ? StringUtils.join(args, ' ', 1, args.length) : null;

        if (ipValidity.matcher(args[0]).matches()) {
            processIPBan(args[0], sender, reason);
        } else {
            Player player = Spanna.getPlayer(args[0]);

            if (player == null) {
                sender.sendMessage(ChatColor.RED + "[ERROR] Usage: " + usageMessage);
                return false;
            }

            processIPBan(player.getAddress().getAddress().getHostAddress(), sender, reason);
        }

        return true;
    }

    private void processIPBan(String ip, CommandSender sender, String reason) {
        Bukkit.getBanList(BanList.Type.IP).addBan(ip, reason, null, sender.getName());

        // Find all matching players and kick
        for (Player player : Spanna.getOnlinePlayers()) {
            if (player.getAddress().getAddress().getHostAddress().equals(ip)) {
                player.kickPlayer("We're sorry, but your IP has been banned from this server.");
            }
        }

        Command.broadcastCommandMessage(sender, "[SERVER] Banned IP Address " + ip);
    }

    @Override
    public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
        Validate.notNull(sender, "Sender cannot be null");
        Validate.notNull(args, "Arguments cannot be null");
        Validate.notNull(alias, "Alias cannot be null");

        if (args.length == 1) {
            return super.tabComplete(sender, alias, args);
        }
        return ImmutableList.of();
    }
}


text:
require 'rack'
require 'filewatcher'

class MachineGun

  def self.run opts = {}
    pid = start_server

    interval = opts[:interval] || 0.5

    FileWatcher.new("./**/*.rb").watch interval do
      Process.kill "INT", pid
      Process.wait pid

      pid = start_server
    end
  end

  private

  def self.start_server
    pid = fork do
      $0 = "rack"
      Rack::Server.start
    end

    pid
  end

end


text:
@interface SBDaemonRequest : NSObject
{
    CDUnknownBlockType _enabler;
    CDUnknownBlockType _disabler;
}

+ (id)requestWithEnabler:(CDUnknownBlockType)arg1 disabler:(CDUnknownBlockType)arg2;
@property(copy, nonatomic) CDUnknownBlockType disabler; // @synthesize disabler=_disabler;
@property(copy, nonatomic) CDUnknownBlockType enabler; // @synthesize enabler=_enabler;
- (void)dispatchDisablerOnQueue:(id)arg1;
- (void)dispatchEnablerOnQueue:(id)arg1;
- (void)dealloc;

@end


text:
<?php
	if(is_active_sidebar('first-footer') ) : ?>

	<?php dynamic_sidebar( 'first-footer' );  else: ?>

			<?php the_widget( 'WP_Widget_Tag_Cloud', '', array('before_title' => '
', 'after_title' => '
')); ?>

<?php endif ?>


text:
<?php

use Framework2\Routing\Route;

class ConsoleRoutes
{
    const LIST_ROUTES = 'routing:list';

    const MATCH_ROUTE = 'routing:match';

    const LIST_CONFIG = 'config:list';
}

return [
    ConsoleRoutes::LIST_ROUTES =>
    new Route(
            ConsoleRoutes::LIST_ROUTES, \Framework2\Console\Routing::class,
            'listRoutes', [], [Route::CONSOLE]),
    ConsoleRoutes::MATCH_ROUTE =>
    new Route(
            ConsoleRoutes::MATCH_ROUTE, \Framework2\Console\Routing::class,
            'matchRoute', [], [Route::CONSOLE]),
    ConsoleRoutes::LIST_CONFIG =>
    new Route(
            ConsoleRoutes::LIST_CONFIG, \Framework2\Console\AppConfig::class,
            'listConfig', [], [Route::CONSOLE]),
];


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Listing_types extends CI_Controller {

	function __construct(){
		parent::__construct();
		$this->load->library('form_validation');
		//$this->load->model('be/main_model');
		$this->load->model('be/listing_types_model');
	}
	function index(){
		if($this->session->userdata('nhub_loginstate')) {
			$data['listing_types'] = $this->listing_types_model->get_listing_types_list();
			$data['page_title'] = 'Listing Types | ';
			$data['main_content'] = 'be/listing_types';
			$this->load->view('be/includes/template',$data);
        }
		else {
            redirect('be/auth');
		}
	}
	function save(){
		$data = array(
			'listing_type_name' => $this->input->post('listing_type_name'),
			'listing_type_description' => $this->input->post('listing_type_description')
		);
		$listing_type_name = $this->input->post('listing_type_name');
		if($this->listing_types_model->listing_type_exists($listing_type_name) == false){

			$q = $this->listing_types_model->save($data);
			if ($q['res'] == true){
				$resp = array('status' => 'SUCCESS','message' => $q['dt']);
			}else{
				$resp = array('status' => 'ERR','message' => $q['dt']);
			}
		}else{
			$resp = array('status' => 'ERR','message' => 'This Listing Type already exists in the database');
		}

		echo json_encode($resp);
	}
	function loadjs(){
		$data['listing_types'] = $this->listing_types_model->get_listing_types_list();
		$this->load->view('be/jsloads/listing_types',$data);

	}
	function get_listing_type($listing_type_id){
		$listing_type = $this->listing_types_model->get_listing_type($listing_type_id);
		echo json_encode($listing_type);
	}
	function update(){
		$listing_type_id = $this->input->post('listing_type_id');
		$listing_type_name = $this->input->post('listing_type_name');
		$data = array(
			'listing_type_name' => $this->input->post('listing_type_name'),
			'listing_type_description' => $this->input->post('listing_type_description')
		);
		if($this->listing_types_model->listing_type_update_exists($listing_type_id,$listing_type_name) == false){
			$q = $this->listing_types_model->update($data,$listing_type_id);
			if ($q['res'] == true){
				$resp = array('status' => 'SUCCESS','message' => 'Listing Type updated successfully.');
			}else{
				$resp = array('status' => 'ERR','message' => $q['dt']);
			}
		}else{
			$resp = array('status' => 'ERR','message' => 'This Listing Type already exists in the database');
		}
		echo json_encode($resp);
	}
	function delete($listing_type_id){
		if($this->session->userdata('nhub_loginstate')){
			$q = $this->listing_types_model->delete($listing_type_id);
			if($q['res'] == TRUE){
				$resp = array('status' => 'SUCCESS','message' => 'Listing Type deleted successfully');
			}else{
				$resp = array('status' => 'ERR','message' => $q['dt']);
			}
		}else{
			$resp = array('status' => 'ERR','message' => 'Your session seems to have expired. Please login again to continue');
    	}
		echo json_encode($resp);
	}

}