text:
ADDR=${1:-255.255.255.255}

# The first step is to add a FIB entry to direct the discovery interests to
# the broadcast address.  This has a short timeout so that the prefix
# goes away in a little while.
ccndc -t 3 add ccnx:/%C1.M.S.neighborhood/%C1.M.SRV/ccnd/KEY udp $ADDR

# Now use ccnls to do the discovery work for us.
# The scope restriction will keep our interests from getting forwarded
# farther than the nodes that can hear us directly.
CCN_SCOPE=2 ccnls ccnx:/%C1.M.S.neighborhood/%C1.M.SRV/ccnd/KEY

# Let's destroy this face now, so that it will not cause confusion.
ccndc destroy udp $ADDR

# Show the status, which has the IP addresses of our new-found neighbors.
ccndstatus

# Save the content objects that have been collected in the cache.
# This also makes them stale, which reduces the possibility that they
# might be served up to somebody else.
ccnrm -o neighborhood.ccnb ccnx:/%C1.M.S.neighborhood/%C1.M.SRV/ccnd/KEY

# Show the names of the keys we have collected.
ccnnamelist neighborhood.ccnb

# BUGS
# This script is intended as a basic demonstration of discovery of
# local peers using broadcast.  It has a number of problems:
# - We may end up destroying a broadcast face that we did not create.
# - The association between peer keys and IP addresses is not recorded.
# - If CCND_AUTOREG is in use on the peers, they will start forwarding
#   interests to us.  That may not be our intent.
# - If CCND_AUTOREG is in use our our node, we will start forwarding
#   interests to our neighbors.  This might not be our intention, either.
# - Since the neighbors won't realize they have received a broadcast,
#   their answer will be unicast, and will not have the approriate
#   randomized delays.


text:
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.android;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.OutputGroupProvider;
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.actions.SpawnAction;
import com.google.devtools.build.lib.analysis.config.CompilationMode;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.rules.RuleConfiguredTargetFactory;
import com.google.devtools.build.lib.rules.android.AndroidLibraryAarProvider.Aar;
import com.google.devtools.build.lib.rules.android.AndroidResourcesProvider.ResourceContainer;
import com.google.devtools.build.lib.rules.android.AndroidResourcesProvider.ResourceType;
import com.google.devtools.build.lib.rules.cpp.LinkerInput;
import com.google.devtools.build.lib.rules.java.JavaCommon;
import com.google.devtools.build.lib.rules.java.JavaNeverlinkInfoProvider;
import com.google.devtools.build.lib.rules.java.JavaSemantics;
import com.google.devtools.build.lib.rules.java.JavaSkylarkApiProvider;
import com.google.devtools.build.lib.rules.java.JavaSourceJarsProvider;
import com.google.devtools.build.lib.rules.java.JavaTargetAttributes;
import com.google.devtools.build.lib.rules.java.JavaUtil;
import com.google.devtools.build.lib.vfs.PathFragment;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * An implementation for the "android_library" rule.
 */
public abstract class AndroidLibrary implements RuleConfiguredTargetFactory {

  protected abstract JavaSemantics createJavaSemantics();
  protected abstract AndroidSemantics createAndroidSemantics();

  @Override
  public ConfiguredTarget create(RuleContext ruleContext) throws InterruptedException {
    JavaSemantics javaSemantics = createJavaSemantics();
    AndroidSemantics androidSemantics = createAndroidSemantics();
    if (!AndroidSdkProvider.verifyPresence(ruleContext)) {
      return null;
    }
    List<? extends TransitiveInfoCollection> deps =
        ruleContext.getPrerequisites("deps", Mode.TARGET);
    checkResourceInlining(ruleContext);
    checkIdlRootImport(ruleContext);
    NestedSet<AndroidResourcesProvider.ResourceContainer> transitiveResources =
        AndroidCommon.getTransitiveResourceContainers(ruleContext, true);
    NestedSetBuilder<Aar> transitiveAars = collectTransitiveAars(ruleContext);
    NestedSet<LinkerInput> transitiveNativeLibraries =
        AndroidCommon.collectTransitiveNativeLibraries(deps);
    NestedSet<Artifact> transitiveProguardConfigs =
        collectTransitiveProguardConfigs(ruleContext);
    AndroidIdlProvider transitiveIdlImportData = collectTransitiveIdlImports(ruleContext);
    if (LocalResourceContainer.definesAndroidResources(ruleContext.attributes())) {
      try {
        if (!LocalResourceContainer.validateRuleContext(ruleContext)) {
          throw new RuleConfigurationException();
        }
        JavaCommon javaCommon = new JavaCommon(ruleContext, javaSemantics);
        AndroidCommon androidCommon = new AndroidCommon(ruleContext, javaCommon);

        ApplicationManifest applicationManifest = androidSemantics.getManifestForRule(ruleContext);
        ResourceApk resourceApk = applicationManifest.packWithDataAndResources(
            ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_RESOURCES_APK),
            ruleContext, transitiveResources,
            ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_R_TXT),
            ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_SYMBOLS_TXT),
            ImmutableList.<String>of(), /* configurationFilters */
            ImmutableList.<String>of(), /* uncompressedExtensions */
            ImmutableList.<String>of(), /* densities */
            null /* applicationId */,
            null /* versionCode */,
            null /* versionName */,
            false,
            null /* proguardCfgOut */);

        JavaTargetAttributes javaTargetAttributes = androidCommon.init(
            javaSemantics,
            androidSemantics,
            resourceApk,
            transitiveIdlImportData,
            false /* addCoverageSupport */,
            true /* collectJavaCompilationArgs */,
            AndroidRuleClasses.ANDROID_LIBRARY_GEN_JAR);
        if (javaTargetAttributes == null) {
          return null;
        }

        Artifact classesJar = mergeJarsFromSrcs(ruleContext,
            ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_CLASS_JAR));

        Artifact aarOut = ruleContext.getImplicitOutputArtifact(
            AndroidRuleClasses.ANDROID_LIBRARY_AAR);

        new AarGeneratorBuilder(ruleContext)
                .withPrimary(resourceApk.getPrimaryResource())
                .withManifest(resourceApk.getPrimaryResource().getManifest())
                .withRtxt(resourceApk.getPrimaryResource().getRTxt())
                .withClasses(classesJar)
                .strictResourceMerging()
                .setAAROut(aarOut)
                .build(ruleContext);

        Aar aar = new Aar(aarOut, applicationManifest.getManifest());

        RuleConfiguredTargetBuilder builder = new RuleConfiguredTargetBuilder(ruleContext);
        androidCommon.addTransitiveInfoProviders(builder);
        androidSemantics.addTransitiveInfoProviders(
            builder, ruleContext, javaCommon, androidCommon,
            null, resourceApk, null, ImmutableList.<Artifact>of());

        return builder
            .add(AndroidNativeLibraryProvider.class,
                new AndroidNativeLibraryProvider(transitiveNativeLibraries))
            .add(JavaSourceJarsProvider.class, new JavaSourceJarsProvider(
                androidCommon.getTransitiveSourceJars(),
                androidCommon.getTopLevelSourceJars()))
            .addSkylarkTransitiveInfo(JavaSkylarkApiProvider.NAME, new JavaSkylarkApiProvider())
            .add(JavaNeverlinkInfoProvider.class,
                new JavaNeverlinkInfoProvider(androidCommon.isNeverLink()))
            .add(AndroidCcLinkParamsProvider.class,
                new AndroidCcLinkParamsProvider(androidCommon.getCcLinkParamsStore()))
            .add(ProguardSpecProvider.class, new ProguardSpecProvider(transitiveProguardConfigs))
            .add(AndroidLibraryAarProvider.class, new AndroidLibraryAarProvider(aar,
                transitiveAars.add(aar).build()))
            .addOutputGroup(OutputGroupProvider.HIDDEN_TOP_LEVEL, transitiveProguardConfigs)
            .build();
      } catch (RuleConfigurationException e) {
        // RuleConfigurations exceptions will only be thrown after the RuleContext is updated.
        // So, exit.
        return null;
      }
    } else {
      JavaCommon javaCommon = new JavaCommon(ruleContext, javaSemantics);
      AndroidCommon androidCommon = new AndroidCommon(ruleContext, javaCommon);
      ResourceApk resourceApk = ResourceApk.fromTransitiveResources(transitiveResources);

      JavaTargetAttributes javaTargetAttributes = androidCommon.init(
          javaSemantics,
          androidSemantics,
          resourceApk,
          transitiveIdlImportData,
          false /* addCoverageSupport */,
          true /* collectJavaCompilationArgs */,
          AndroidRuleClasses.ANDROID_LIBRARY_GEN_JAR);
      if (javaTargetAttributes == null) {
        return null;
      }

      RuleConfiguredTargetBuilder targetBuilder = androidCommon.addTransitiveInfoProviders(
          new RuleConfiguredTargetBuilder(ruleContext));

      androidSemantics.addTransitiveInfoProviders(
          targetBuilder, ruleContext, javaCommon, androidCommon,
          null, null, null, ImmutableList.<Artifact>of());
      targetBuilder
          .add(AndroidNativeLibraryProvider.class,
              new AndroidNativeLibraryProvider(transitiveNativeLibraries))
          .add(JavaSourceJarsProvider.class, androidCommon.getJavaSourceJarsProvider())
          .add(AndroidCcLinkParamsProvider.class,
              new AndroidCcLinkParamsProvider(androidCommon.getCcLinkParamsStore()))
          .addSkylarkTransitiveInfo(JavaSkylarkApiProvider.NAME, new JavaSkylarkApiProvider())
          .add(JavaNeverlinkInfoProvider.class,
              new JavaNeverlinkInfoProvider(androidCommon.isNeverLink()))
          .add(ProguardSpecProvider.class, new ProguardSpecProvider(transitiveProguardConfigs))
          .addOutputGroup(OutputGroupProvider.HIDDEN_TOP_LEVEL, transitiveProguardConfigs);

      Artifact aarOut = ruleContext.getImplicitOutputArtifact(
          AndroidRuleClasses.ANDROID_LIBRARY_AAR);

      Artifact classesJar = mergeJarsFromSrcs(ruleContext,
          ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_LIBRARY_CLASS_JAR));

      ResourceContainer primaryResources;

      if (AndroidCommon.getAndroidResources(ruleContext) != null) {
        primaryResources = Iterables.getOnlyElement(
            AndroidCommon.getAndroidResources(ruleContext).getTransitiveAndroidResources());

        Aar aar = new Aar(aarOut, primaryResources.getManifest());
        targetBuilder.add(AndroidLibraryAarProvider.class, new AndroidLibraryAarProvider(
            aar, transitiveAars.add(aar).build()));
      } else {
        // there are no local resources and resources attribute was not specified either
        ApplicationManifest applicationManifest =
            ApplicationManifest.generatedManifest(ruleContext);

        Artifact apk = ruleContext.getImplicitOutputArtifact(
            AndroidRuleClasses.ANDROID_RESOURCES_APK);

        String javaPackage;
        if (apk.getExecPath().getFirstSegment(ImmutableSet.of("java", "javatests"))
            != PathFragment.INVALID_SEGMENT) {
          javaPackage = JavaUtil.getJavaPackageName(apk.getExecPath());
        } else {
          // This is a workaround for libraries that don't follow the standard Bazel package format
          javaPackage = apk.getRootRelativePath().getPathString().replace('/', '.');
        }
        if (ruleContext.attributes().isAttributeValueExplicitlySpecified("custom_package")) {
          javaPackage = ruleContext.attributes().get("custom_package", Type.STRING);
        }

        primaryResources = new ResourceContainer(ruleContext.getLabel(),
            javaPackage, null /* renameManifestPackage */, false /* inlinedConstants */,
            apk, applicationManifest.getManifest(),
            ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_JAVA_SOURCE_JAR),
            ImmutableList.<Artifact>of(), ImmutableList.<Artifact>of(),
            ImmutableList.<PathFragment>of(), ImmutableList.<PathFragment>of(),
            ruleContext.attributes().get("exports_manifest", Type.BOOLEAN),
            ruleContext.getImplicitOutputArtifact(AndroidRuleClasses.ANDROID_R_TXT), null);

        primaryResources = new AndroidResourcesProcessorBuilder(ruleContext)
                .setApkOut(apk)
                .setRTxtOut(primaryResources.getRTxt())
                .setSourceJarOut(primaryResources.getJavaSourceJar())
                .setJavaPackage(primaryResources.getJavaPackage())
                .withPrimary(primaryResources)
                .withDependencies(transitiveResources)
                .setDebug(
                    ruleContext.getConfiguration().getCompilationMode() != CompilationMode.OPT)
                .setWorkingDirectory(ruleContext.getUniqueDirectory("_resources"))
                .build(ruleContext);

        targetBuilder.add(AndroidLibraryAarProvider.class, new AndroidLibraryAarProvider(
            null, transitiveAars.build()));
      }

      new AarGeneratorBuilder(ruleContext)
          .withPrimary(primaryResources)
          .withManifest(primaryResources.getManifest())
          .withRtxt(primaryResources.getRTxt())
          .withClasses(classesJar)
          .setAAROut(aarOut)
          .build(ruleContext);

      return targetBuilder.build();
    }
  }

  private static Artifact mergeJarsFromSrcs(RuleContext ruleContext, Artifact inputJar)
      throws InterruptedException {
    ImmutableList<Artifact> jarSources =
        ruleContext
        .getPrerequisiteArtifacts("srcs", Mode.TARGET).filter(JavaSemantics.JAR).list();
    if (jarSources.isEmpty()) {
      return inputJar;
    }
    Artifact mergedJar = ruleContext.getImplicitOutputArtifact(
        AndroidRuleClasses.ANDROID_LIBRARY_AAR_CLASSES_JAR);
    new SingleJarBuilder(ruleContext)
        .setOutputJar(mergedJar)
        .addInputJar(inputJar)
        .addInputJars(jarSources)
        .build();
    return mergedJar;
  }

  private AndroidIdlProvider collectTransitiveIdlImports(RuleContext ruleContext) {
    NestedSetBuilder<String> rootsBuilder = NestedSetBuilder.naiveLinkOrder();
    NestedSetBuilder<Artifact> importsBuilder = NestedSetBuilder.naiveLinkOrder();

    for (AndroidIdlProvider dep : ruleContext.getPrerequisites(
        "deps", Mode.TARGET, AndroidIdlProvider.class)) {
      rootsBuilder.addTransitive(dep.getTransitiveIdlImportRoots());
      importsBuilder.addTransitive(dep.getTransitiveIdlImports());
    }

    Collection<Artifact> idlImports = getIdlImports(ruleContext);
    if (!hasExplicitlySpecifiedIdlImportRoot(ruleContext)) {
      for (Artifact idlImport : idlImports) {
        PathFragment javaRoot = JavaUtil.getJavaRoot(idlImport.getExecPath());
        if (javaRoot == null) {
          ruleContext.ruleError("Cannot determine java/javatests root for import "
              + idlImport.getExecPathString());
        } else {
          rootsBuilder.add(javaRoot.toString());
        }
      }
    } else {
      PathFragment pkgFragment = ruleContext.getLabel().getPackageFragment();
      Set<PathFragment> idlImportRoots = new HashSet<>();
      for (Artifact idlImport : idlImports) {
        idlImportRoots.add(idlImport.getRoot().getExecPath()
            .getRelative(pkgFragment)
            .getRelative(getIdlImportRoot(ruleContext)));
      }
      for (PathFragment idlImportRoot : idlImportRoots) {
        rootsBuilder.add(idlImportRoot.toString());
      }
    }
    importsBuilder.addAll(idlImports);

    return new AndroidIdlProvider(rootsBuilder.build(), importsBuilder.build());
  }

  private void checkIdlRootImport(RuleContext ruleContext) {
    if (hasExplicitlySpecifiedIdlImportRoot(ruleContext)
        && !hasExplicitlySpecifiedIdlSrcsOrParcelables(ruleContext)) {
      ruleContext.attributeError("idl_import_root",
          "Neither idl_srcs nor idl_parcelables were specified, "
              + "but 'idl_import_root' attribute was set");
    }
  }

  private void checkResourceInlining(RuleContext ruleContext) {
    AndroidResourcesProvider resources = AndroidCommon.getAndroidResources(ruleContext);
    if (resources == null) {
      return;
    }

    ResourceContainer container = Iterables.getOnlyElement(
        resources.getTransitiveAndroidResources());

    if (container.getConstantsInlined()
        && !container.getArtifacts(ResourceType.RESOURCES).isEmpty()) {
      ruleContext.ruleError("This android library has some resources assigned, so the target '"
          + resources.getLabel() + "' should have the attribute inline_constants set to 0");
    }
  }

  private NestedSetBuilder<Aar> collectTransitiveAars(RuleContext ruleContext) {
    NestedSetBuilder<Aar> builder = NestedSetBuilder.naiveLinkOrder();
    for (AndroidLibraryAarProvider library :
        ruleContext.getPrerequisites("deps", Mode.TARGET, AndroidLibraryAarProvider.class)) {
      builder.addTransitive(library.getTransitiveAars());
    }
    return builder;
  }

  private boolean hasExplicitlySpecifiedIdlImportRoot(RuleContext ruleContext) {
    return ruleContext.getRule().isAttributeValueExplicitlySpecified("idl_import_root");
  }

  private boolean hasExplicitlySpecifiedIdlSrcsOrParcelables(RuleContext ruleContext) {
    return ruleContext.getRule().isAttributeValueExplicitlySpecified("idl_srcs")
        || ruleContext.getRule().isAttributeValueExplicitlySpecified("idl_parcelables");
  }

  private String getIdlImportRoot(RuleContext ruleContext) {
    return ruleContext.attributes().get("idl_import_root", Type.STRING);
  }

  /**
   * Returns the union of "idl_srcs" and "idl_parcelables", i.e. all .aidl files
   * provided by this library that contribute to .aidl --> .java compilation.
   */
  private static Collection<Artifact> getIdlImports(RuleContext ruleContext) {
    return ImmutableList.<Artifact>builder()
        .addAll(AndroidCommon.getIdlParcelables(ruleContext))
        .addAll(AndroidCommon.getIdlSrcs(ruleContext))
        .build();
  }

  private NestedSet<Artifact> collectTransitiveProguardConfigs(RuleContext ruleContext) {
    NestedSetBuilder<Artifact> specsBuilder = NestedSetBuilder.naiveLinkOrder();

    for (ProguardSpecProvider dep : ruleContext.getPrerequisites(
        "deps", Mode.TARGET, ProguardSpecProvider.class)) {
      specsBuilder.addTransitive(dep.getTransitiveProguardSpecs());
    }

    // Pass our local proguard configs through the validator, which checks a whitelist.
    if (!getProguardConfigs(ruleContext).isEmpty()) {
      FilesToRunProvider proguardWhitelister = ruleContext
        .getExecutablePrerequisite("$proguard_whitelister", Mode.HOST);
      for (Artifact specToValidate : getProguardConfigs(ruleContext)) {
        //If we're validating j/a/b/testapp/proguard.cfg, the output will be:
        //j/a/b/testapp/proguard.cfg_valid
        Artifact output = ruleContext.getUniqueDirectoryArtifact(
            "validated_proguard",
            specToValidate.getRootRelativePath().replaceName(
                specToValidate.getFilename() + "_valid"),
            ruleContext.getBinOrGenfilesDirectory());
        ruleContext.registerAction(new SpawnAction.Builder()
            .addInput(specToValidate)
            .setExecutable(proguardWhitelister)
            .setProgressMessage("Validating proguard configuration")
            .setMnemonic("ValidateProguard")
            .addArgument("--path")
            .addArgument(specToValidate.getExecPathString())
            .addArgument("--output")
            .addArgument(output.getExecPathString())
            .addOutput(output)
            .build(ruleContext));
        specsBuilder.add(output);
      }
    }
    return specsBuilder.build();
  }

  private Collection<Artifact> getProguardConfigs(RuleContext ruleContext) {
    return ruleContext.getPrerequisiteArtifacts("proguard_specs", Mode.TARGET).list();
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace TableTennisChampionship.Model.DataBaseModel
{
  public   class Game
    {
        [Key]
        public int GameID { get; set; }
        [Required(ErrorMessage="Няма пореден номер на гейм!")]
        public int GameNumber { get; set; }
        public int PointsWin{get;set;}
        public int PoinsLost{get;set;}

        [Display(Name = "Спечелил играч")]

        public virtual Player WonPlayer { get; set; }

        [Display(Name = "Загубил играч")]

        public virtual Player LostPlayer { get; set; }
    }

}


text:
//	Copyright © 2013 - 2014, Alain Metge. All rights reserved.
//
//		This file is part of Hyperstore (http://www.hyperstore.org)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#region Imports

using Hyperstore.Modeling.Events;
using Hyperstore.Modeling.Platform;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

#endregion

namespace Hyperstore.Modeling.Messaging
{
    /// <summary>
    /// </summary>
    internal sealed class EventBus : IDisposable, IEventBus
    {
        private readonly object _sync = new object();
        private List<IEventBusChannel> _channels;
        private readonly Dictionary<IDomainModel, PoliciesInfo> _policies = new Dictionary<IDomainModel, PoliciesInfo>();

        private class PoliciesInfo
        {
            public ChannelPolicy Output;
            public ChannelPolicy Input;
        }

        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Event queue for all listeners interested in EventBusStarted events.
        /// </summary>
        ///-------------------------------------------------------------------------------------------------
        public event EventHandler EventBusStarted;

        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Gets the channels.
        /// </summary>
        /// <value>
        ///  The channels.
        /// </value>
        ///-------------------------------------------------------------------------------------------------
        public IEnumerable<IEventBusChannel> Channels { get { return _channels; } }

        private bool _disposed;
        private readonly IHyperstore _store;

        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Gets the store.
        /// </summary>
        /// <value>
        ///  The store.
        /// </value>
        ///-------------------------------------------------------------------------------------------------
        public IHyperstore Store { get { return _store; } }

        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Gets the default event dispatcher.
        /// </summary>
        /// <value>
        ///  The default event dispatcher.
        /// </value>
        ///-------------------------------------------------------------------------------------------------
        public IEventDispatcher DefaultEventDispatcher
        {
            get;
            private set;
        }

        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Constructor.
        /// </summary>
        /// <param name="services">
        ///  The services.
        /// </param>
        ///-------------------------------------------------------------------------------------------------
        public EventBus(IServicesContainer services)
        {
            DebugContract.Requires(services);
            _store = services.Resolve<IHyperstore>();
            DefaultEventDispatcher = services.Resolve<IEventDispatcher>();
        }

        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged
        ///  resources.
        /// </summary>
        ///-------------------------------------------------------------------------------------------------
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Starts the asynchronous.
        /// </summary>
        /// <exception cref="ObjectDisposedException">
        ///  Thrown when a supplied object has been disposed.
        /// </exception>
        /// <returns>
        ///  A Task.
        /// </returns>
        ///-------------------------------------------------------------------------------------------------
        public async Task OpenAsync(params IEventBusChannel[] channels)
        {
            if (_disposed)
                throw new ObjectDisposedException("EventBus");

            List<IEventBusChannel> channelList = null;
            lock (_sync)
            {
                if (_channels == null)
                    _channels = new List<IEventBusChannel>();

                _channels.AddRange(channels);
                channelList = _channels.ToList();
            }

            if (channelList == null || channelList.Count == 0)
            {
                OnEventBusStarted();
                return;
            }

            Dictionary<IDomainModel, PoliciesInfo> policies;
            lock (_policies)
            {
                policies = new Dictionary<IDomainModel, PoliciesInfo>(_policies);
            }

            if (policies.Count == 0)
            {
                OnEventBusStarted();
                return;
            }

            Task[] tasks = new Task[channelList.Count];
            var i = 0;
            foreach (var channel in channelList)
            {
                foreach(var info in policies)
                {
                    channel.RegisterFilter(new ChannelFilter(info.Value.Output, info.Value.Input, info.Key));
                }

                tasks[i++] = channel.StartAsync(this);
            }

            await Task.WhenAll(tasks);

            _store.SessionCompleting += OnSessionCompleted;

            OnEventBusStarted();
        }

        private void OnEventBusStarted()
        {
            var tmp = EventBusStarted;
            if( tmp !=null)
            {
                tmp(this, new EventArgs());
            }
        }

        private void OnSessionCompleted(object sender, SessionCompletingEventArgs e)
        {
            if (_channels == null || e.Session.IsAborted)
                return;

            PlatformServices.Current.Parallel_ForEach(_channels, channel => channel.SendEvents(e.Session));
        }

        private void Dispose(bool releaseManagedResources)
        {
            if (_disposed)
                return;

            _disposed = true;

            _store.SessionCompleting -= OnSessionCompleted;

            if (_channels != null)
            {
                foreach (var item in _channels)
                {
                    try
                    {
                        var disposable = item as IDisposable;
                        if (disposable != null)
                            disposable.Dispose();
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            _channels = null;
        }

        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Registers this instance.
        /// </summary>
        /// <param name="domain">
        ///  The domain.
        /// </param>
        /// <param name="outputProperty">
        ///  The output property.
        /// </param>
        /// <param name="inputProperty">
        ///  (Optional) the input property.
        /// </param>
        ///-------------------------------------------------------------------------------------------------
        public void RegisterDomainPolicies(IDomainModel domain, ChannelPolicy outputProperty, ChannelPolicy inputProperty = null)
        {
            Contract.Requires(domain, "domain");
            if (outputProperty == null && inputProperty == null)
                return;

            lock (_policies)
            {
                PoliciesInfo info;
                if (_policies.TryGetValue(domain, out info))
                {
                    info.Input = inputProperty;
                    info.Output = outputProperty;
                    return;
                }

                info = new PoliciesInfo { Output = outputProperty, Input = inputProperty };
                _policies.Add(domain, info);
            }
        }
    }
}


text:
namespace ArcGIS.Test.Integration
{
    using ArcGIS.ServiceModel;
    using ArcGIS.ServiceModel.Common;
    using ArcGIS.ServiceModel.Operation;
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using Xunit;
    using Xunit.Abstractions;

    public class SecureGISGatewayTests : IClassFixture<IntegrationTestFixture>
    {
        public SecureGISGatewayTests(IntegrationTestFixture fixture, ITestOutputHelper output)
        {
            fixture.SetTestOutputHelper(output);
            CryptoProviderFactory.Disabled = true;
        }

        [Theory]
        [InlineData("https://serverapps10.esri.com/arcgis", "user1", "pass.word1")]
        public async Task CanGenerateToken(string rootUrl, string username, string password)
        {
            var tokenProvider = new TokenProvider(rootUrl, username, password);
            var token = await IntegrationTestFixture.TestPolicy.ExecuteAsync(() =>
            {
                return tokenProvider.CheckGenerateToken(CancellationToken.None);
            });

            Assert.NotNull(token);
            Assert.NotNull(token.Value);
            Assert.False(token.IsExpired);
            Assert.Null(token.Error);
        }

        [Theory]
        [InlineData("https://serverapps10.esri.com/arcgis", "user1", "pass.word1")]
        public async Task CanUseServerInfoToGenerateToken(string rootUrl, string username, string password)
        {
            var gateway = new PortalGateway(rootUrl);
            var serverInfo = await IntegrationTestFixture.TestPolicy.ExecuteAsync(() =>
            {
                return gateway.Info();
            });

            var tokenProvider = new TokenProvider(serverInfo.AuthenticationInfo.TokenServicesUrl, username, password);
            var token = await IntegrationTestFixture.TestPolicy.ExecuteAsync(() =>
            {
                return tokenProvider.CheckGenerateToken(CancellationToken.None);
            });

            Assert.NotNull(token);
            Assert.NotNull(token.Value);
            Assert.False(token.IsExpired);
            Assert.Null(token.Error);
        }

        [Theory]
        [InlineData("https://serverapps10.esri.com/arcgis", "user1", "pass.word1")]
        public async Task CanDescribeSecureSite(string rootUrl, string username, string password)
        {
            var gateway = new SecurePortalGateway(rootUrl, username, password);

            var response = await IntegrationTestFixture.TestPolicy.ExecuteAsync(() =>
            {
                return gateway.DescribeSite();
            });

            Assert.NotNull(response);
            Assert.True(response.Version > 0);

            foreach (var resource in response.ArcGISServerEndpoints)
            {
                var ping = await IntegrationTestFixture.TestPolicy.ExecuteAsync(() =>
                {
                    return gateway.Ping(resource);
                });
                Assert.Null(ping.Error);
            }
        }

        [Theory]
        [InlineData("https://serverapps10.esri.com/arcgis", "user1", "pass.word1")]
        public async Task CanDescribeSecureSiteServices(string rootUrl, string username, string password)
        {
            var gateway = new SecurePortalGateway(rootUrl, username, password);
            var siteResponse = await IntegrationTestFixture.TestPolicy.ExecuteAsync(() =>
            {
                return gateway.DescribeSite();
            });

            Assert.NotNull(siteResponse);
            Assert.True(siteResponse.Version > 0);

            var response = await IntegrationTestFixture.TestPolicy.ExecuteAsync(() =>
            {
                return gateway.DescribeServices(siteResponse);
            });

            foreach (var serviceDescription in response)
            {
                Assert.NotNull(serviceDescription);
                Assert.Null(serviceDescription.Error);
                Assert.NotNull(serviceDescription.ServiceDescription);
            }
        }

        [Theory]
        [InlineData("https://serverapps10.esri.com/arcgis", "Oil/MapServer")]
        public async Task CannotAccessSecureResourceWithoutToken(string rootUrl, string relativeUrl)
        {
            var gateway = new PortalGateway(rootUrl);
            var endpoint = new ArcGISServerEndpoint(relativeUrl);

            var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => gateway.Ping(endpoint));
            Assert.NotNull(exception);
            Assert.Contains("Unauthorized access", exception.Message);
        }

        [Theory]
        [InlineData("https://serverapps10.esri.com/arcgis", "user1", "pass.word1", "Oil/MapServer")]
        public async Task InvalidTokenReported(string rootUrl, string username, string password, string relativeUrl)
        {
            var tokenProvider = new TokenProvider(rootUrl, username, password);
            var gateway = new PortalGateway(rootUrl, tokenProvider: tokenProvider);
            var endpoint = new ArcGISServerEndpoint(relativeUrl);

            var token = await IntegrationTestFixture.TestPolicy.ExecuteAsync(() =>
            {
                return tokenProvider.CheckGenerateToken(CancellationToken.None);
            });

            Assert.NotNull(token);
            Assert.NotNull(token.Value);
            Assert.False(token.IsExpired);
            Assert.Null(token.Error);

            token.Value += "chuff";
            var query = new Query(endpoint)
            {
                Token = token.Value
            };

            var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => gateway.Query<Point>(query));
            Assert.NotNull(exception);
            Assert.Contains("Invalid token", exception.Message);
        }
    }
}


text:
use strict;
use warnings;
use DBI;
use CGI qw (:standard escapeHTML escape);
#@ _PREAMBLE_

use Cwd;
# option file that should contain connection parameters for UNIX
my $option_file = "/usr/local/apache/conf/sampdb.cnf";
my $option_drive_root;
# override file location for Windows
if ($^O =~ /^MSWin/i || $^O =~ /^dos/)
{
  $option_drive_root = "C:/";
  $option_file = "/Apache/conf/sampdb.cnf";
}

# construct data source and connect to server (under Windows, save
# current working directory first, change location to option file
# drive, connect, and restore current directory)
my $orig_dir;
if (defined ($option_drive_root))
{
  $orig_dir = cwd ();
  chdir ($option_drive_root)
    or die "Cannot chdir to $option_drive_root: $!\n";
}
my $dsn = "DBI:mysql:sampdb;mysql_read_default_file=$option_file";
my %conn_attrs = (RaiseError => 1, PrintError => 0, AutoCommit => 1);
my $dbh = DBI->connect ($dsn, undef, undef, \%conn_attrs);
if (defined ($option_drive_root))
{
  chdir ($orig_dir)
    or die "Cannot chdir to $orig_dir: $!\n";
}

#@ _MAIN_BODY_
my $db_name = "sampdb";

# put out initial part of page
my $title = "$db_name Database Browser";
print header ();
print start_html (-title => $title, -bgcolor => "white");
print h1 ($title);

# parameters to look for in URL
my $tbl_name = param ("tbl_name");
my $sort_col = param ("sort_col");

# If $tbl_name has no value, display a clickable list of tables.
# Otherwise, display contents of the given table.  $sort_col, if
# set, indicates which column to sort by.

if (!defined ($tbl_name))
{
  display_table_names ($dbh, $db_name)
}
else
{
  display_table_contents ($dbh, $db_name, $tbl_name, $sort_col);
}

print end_html ();
#@ _MAIN_BODY_

$dbh->disconnect ();

#@ _DISPLAY_TABLE_NAMES_
sub display_table_names
{
my ($dbh, $db_name) = @_;

  print p ("Select a table by clicking on its name:");

  # retrieve reference to single-column array of table names
  my $sth = $dbh->prepare (qq{
              SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
              WHERE TABLE_SCHEMA = ? ORDER BY TABLE_NAME
            });
  $sth->execute ($db_name);

  # Construct a bullet list using the ul() (unordered list) and
  # li() (list item) functions.  Each item is a hyperlink that
  # re-invokes the script to display a particular table.
  my @item;
  while (my ($tbl_name) = $sth->fetchrow_array ())
  {
    my $url = sprintf ("%s?tbl_name=%s", url (), escape ($tbl_name));
    my $link = a ({-href => $url}, escapeHTML ($tbl_name));
    push (@item, li ($link));
  }
  print ul (@item);
}
#@ _DISPLAY_TABLE_NAMES_

#@ _DISPLAY_TABLE_CONTENTS_
sub display_table_contents
{
my ($dbh, $db_name, $tbl_name, $sort_col) = @_;
my $sort_clause = "";
my @rows;
my @cells;

  # if sort column is specified, use it to sort the results
  if (defined ($sort_col))
  {
    $sort_clause = " ORDER BY " . $dbh->quote_identifier ($sort_col);
  }

  # present a link that returns user to table list page
  print p (a ({-href => url ()}, "Show Table List"));

  print p (strong ("Contents of $tbl_name table:"));

  my $sth = $dbh->prepare (
              "SELECT * FROM "
            . $dbh->quote_identifier ($db_name, $tbl_name)
            . "$sort_clause LIMIT 200"
            );
  $sth->execute ();

  # Use the names of the columns in the database table as the
  # headings in an HTML table.  Make each name a hyperlink that
  # causes the script to be reinvoked to redisplay the table,
  # sorted by the named column.

  foreach my $col_name (@{$sth->{NAME}})
  {
    my $url = sprintf ("%s?tbl_name=%s;sort_col=%s",
                       url (),
                       escape ($tbl_name),
                       escape ($col_name));
    my $link = a ({-href => $url}, escapeHTML ($col_name));
    push (@cells, th ($link));
  }
  push (@rows, Tr (@cells));

  # display table rows
  while (my @ary = $sth->fetchrow_array ())
  {
    @cells = ();
    foreach my $val (@ary)
    {
      # display value if non-empty, else display non-breaking space
      if (defined ($val) && $val ne "")
      {
        $val = escapeHTML ($val);
      }
      else
      {
        $val = " ";
      }
      push (@cells, td ($val));
    }
    push (@rows, Tr (@cells));
  }

  # display table with a border
  print table ({-border => "1"}, @rows);
}
#@ _DISPLAY_TABLE_CONTENTS_


text:
/* Generated SBE (Simple Binary Encoding) message codec */
package uk.co.real_logic.sbe.ir.generated;

import org.agrona.MutableDirectBuffer;

@javax.annotation.Generated(value = {"uk.co.real_logic.sbe.ir.generated.MessageHeaderEncoder"})
@SuppressWarnings("all")
public class MessageHeaderEncoder
{
    public static final int ENCODED_LENGTH = 8;
    private MutableDirectBuffer buffer;
    private int offset;

    public MessageHeaderEncoder wrap(final MutableDirectBuffer buffer, final int offset)
    {
        this.buffer = buffer;
        this.offset = offset;
        return this;
    }

    public int encodedLength()
    {
        return ENCODED_LENGTH;
    }

    public static int blockLengthNullValue()
    {
        return 65535;
    }

    public static int blockLengthMinValue()
    {
        return 0;
    }

    public static int blockLengthMaxValue()
    {
        return 65534;
    }

    public MessageHeaderEncoder blockLength(final int value)
    {
        buffer.putShort(offset + 0, (short)value, java.nio.ByteOrder.LITTLE_ENDIAN);
        return this;
    }

    public static int templateIdNullValue()
    {
        return 65535;
    }

    public static int templateIdMinValue()
    {
        return 0;
    }

    public static int templateIdMaxValue()
    {
        return 65534;
    }

    public MessageHeaderEncoder templateId(final int value)
    {
        buffer.putShort(offset + 2, (short)value, java.nio.ByteOrder.LITTLE_ENDIAN);
        return this;
    }

    public static int schemaIdNullValue()
    {
        return 65535;
    }

    public static int schemaIdMinValue()
    {
        return 0;
    }

    public static int schemaIdMaxValue()
    {
        return 65534;
    }

    public MessageHeaderEncoder schemaId(final int value)
    {
        buffer.putShort(offset + 4, (short)value, java.nio.ByteOrder.LITTLE_ENDIAN);
        return this;
    }

    public static int versionNullValue()
    {
        return 65535;
    }

    public static int versionMinValue()
    {
        return 0;
    }

    public static int versionMaxValue()
    {
        return 65534;
    }

    public MessageHeaderEncoder version(final int value)
    {
        buffer.putShort(offset + 6, (short)value, java.nio.ByteOrder.LITTLE_ENDIAN);
        return this;
    }

}


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

	<string-array name="status_bar_variant_names">
		<item>Aggiungi & mostra icona nera</item>
		<item>Aggiungi & mostra icona bianca</item>
		<item>Aggiungi & nascondi icona</item>
		<item>Non aggiungere</item>
	</string-array>

	<string-array name="status_bar_variant_values">
		<item>2</item>
		<item>3</item>
		<item>1</item>
		<item>0</item>
	</string-array>

	<string-array name="appearance_variant_names">
		<item>Schermo intero</item>
		<item>Finestra dialogo</item>
	</string-array>

	<string-array name="appearance_variant_values">
		<item>0</item>
		<item>1</item>
	</string-array>

	<string-array name="flashlight_names">
		<item>Torcia a schermo</item>
		<item>Torcia LED</item>
		<item>Nessuna torcia</item>
	</string-array>

	<string-array name="flashlight_values">
		<item>0</item>
		<item>1</item>
		<item>2</item>
	</string-array>

	<string-array name="apn_modifier_names">
		<item>Classico: \"[disabled]\"</item>
		<item>APNdroid: \"apndroid\"</item>
		<item>Prefisso semplice: \"-\"</item>
	</string-array>

	<string-array name="apn_modifier_values">
		<item>1</item>
		<item>0</item>
		<item>2</item>
	</string-array>

	<string-array name="flashlight_switch_names">
		<item>In base al cambiamento di orientamento</item>
		<item>Dopo un ritardo</item>
		<item>Agitando il telefono</item>
	</string-array>

	<string-array name="flashlight_switch_values">
		<item>0</item>
		<item>1</item>
		<item>2</item>
	</string-array>

</resources>


text:
package org.apache.wink.bv.server.internal.validation.bv;

import org.apache.wink.bv.server.spi.ConstraintViolationEntityFactory;
import org.apache.wink.common.utils.SpiUtils;

import javax.validation.ConstraintViolation;
import javax.validation.ValidationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

@Provider
public class BeanValidationExceptionMapper implements ExceptionMapper<ValidationException> {

    @Override
    public Response toResponse(ValidationException e) {
        MediaType targetMediaType = MediaType.TEXT_PLAIN_TYPE;
        Response.Status targetStatus = Response.Status.INTERNAL_SERVER_ERROR;
        Object entity = e.getMessage();

        if (e instanceof InvocationTargetViolationException) {
            InvocationTargetViolationException constraintViolationException = (InvocationTargetViolationException)e;

            EntityResult result = createViolationEntityResult(constraintViolationException);
            targetMediaType = result.mediaType;
            entity = result.entity;

            //violation in result -> INTERNAL_SERVER_ERROR (before it is BAD_REQUEST)
            //alternative: check for javax.validation.ElementKind.RETURN_VALUE
            targetStatus = constraintViolationException.getTargetStatusCode();
        }
        return Response.status(targetStatus).type(targetMediaType).entity(entity).build();
    }

    private EntityResult createViolationEntityResult(InvocationTargetViolationException e) {
        EntityResult entityResult = new EntityResult();
        ConstraintViolationEntityFactory entityFactory =
                getConstraintViolationEntityFactory(e.getAcceptableMediaTypes(), entityResult);

        entityResult.entity = entityFactory.createEntity(e.getConstraintViolations());
        return entityResult;
    }

    private ConstraintViolationEntityFactory getConstraintViolationEntityFactory(
            List<MediaType> acceptableMediaTypes, EntityResult entityResult) {

        List<ConstraintViolationEntityFactory> entityFactories =
                SpiUtils.loadServices(ConstraintViolationEntityFactory.class); //TODO discuss and add cache

        for (MediaType mediaType : acceptableMediaTypes) {
            for (ConstraintViolationEntityFactory entityFactory : entityFactories) {
                if (entityFactory.isResponsibleFor(mediaType)) {
                    entityResult.mediaType = mediaType;
                    return entityFactory;
                }
            }
        }
        return new ConstraintViolationEntityFactory() {
            @Override
            public boolean isResponsibleFor(MediaType mediaType) {
                throw new UnsupportedOperationException("calling the method externally isn't supported");
            }

            @Override
            public Object createEntity(Set<ConstraintViolation<?>> constraintViolations) {
                List<String> violationMessages = new ArrayList<String>();
                for (ConstraintViolation constraintViolation : constraintViolations) {
                    //TODO discuss: check/extract jax-rs annotations from the property-path to provide external names
                    //otherwise it shows e.g. resMethod.arg0, names of the instance-variables of resource-classes,...
                    violationMessages.add("'" +
                            constraintViolation.getPropertyPath().toString() + "' " + constraintViolation.getMessage());
                }
                //a deterministic result is easier for testing,...
                Collections.sort(violationMessages);

                StringBuilder result = new StringBuilder();

                for (String violation : violationMessages) {
                    if (result.length() != 0) {
                        result.append("; ");
                    }
                    result.append(violation);
                }

                return result.toString();
            }
        };
    }

    private class EntityResult {
        private Object entity;
        private MediaType mediaType = MediaType.TEXT_PLAIN_TYPE;
    }
}


text:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

using SphereStudio.Base;

namespace SphereStudio.Ide.Forms
{
    partial class AboutDialogForm : Form, IStyleAware
    {
        public AboutDialogForm()
        {
            InitializeComponent();

            this.labelProductName.Text = $"{Versioning.Name} {Versioning.Version}";
            this.labelCopyright.Text = $"\xA9 {Versioning.Copyright}";
            this.labelCompanyName.Text = Versioning.Author;
            this.creditsTextBox.Text = Versioning.Credits;

            // get the installed Windows version
            var os = Environment.OSVersion;
            var windowsVersion = os.Version.Major == 5 && os.Version.Minor == 1 ? "XP"
                : os.Version.Major == 6 && os.Version.Minor == 0 ? "Vista"
                : os.Version.Major == 6 && os.Version.Minor == 1 ? "7"
                : os.Version.Major == 6 && os.Version.Minor == 2 ? "8"
                : os.Version.Major == 6 && os.Version.Minor == 3 ? "8.1"
                : os.Version.Major == 10 && os.Version.Minor == 0 ? "10"
                : $"{os.Version.Major}.{os.Version.Minor}";
            string updateName = os.ServicePack;
            if (os.Version.Major == 10 && os.Version.Minor == 0)
            {
                // Windows 11 still reports v10.0, have to detect via build number
                if (os.Version.Build >= 22000)
                    windowsVersion = "11";

                // for Windows 10, there are multiple releases.  figure out which one is in use
                // based on the build number.
                updateName = os.Version.Build == 10240 ? "RTM"
                    : os.Version.Build == 10586 ? "November Update"
                    : os.Version.Build == 14393 ? "Anniversary Update"
                    : os.Version.Build == 15063 ? "Creators Update"
                    : os.Version.Build == 16299 ? "Fall Creators Update"
                    : os.Version.Build == 17134 ? "Apr. 2018 Update"
                    : os.Version.Build == 17763 ? "Oct. 2018 Update"
                    : os.Version.Build == 18362 ? "May 2019 Update"
                    : os.Version.Build == 18363 ? "Nov. 2019 Update"
                    : os.Version.Build == 19041 ? "May 2020 Update"
                    : os.Version.Build == 19042 ? "Oct. 2020 Update"
                    : os.Version.Build == 19043 ? "May 2021 Update"
                    : os.Version.Build == 22000 ? "v. 21H2"
                    : $"build {os.Version.Build}";
            }
            var architecture = RuntimeInformation.OSArchitecture == Architecture.X64 ? "x64"
                : RuntimeInformation.OSArchitecture == Architecture.Arm64 ? "ARM64"
                : RuntimeInformation.OSArchitecture == Architecture.Arm ? "ARM"
                : "x86";
            this.labelPlatform.Text = $"Windows {windowsVersion} {architecture}\n{updateName}";

            StyleManager.AutoStyle(this);
        }

        public void ApplyStyle(UIStyle style)
        {
            style.AsUIElement(this);
            style.AsHeading(header);
            style.AsHeading(versionHeader);
            style.AsHeading(footerPanel);
            style.AsAccent(versionPanel);
            style.AsAccent(closeButton);
            style.AsTextView(creditsTextBox);
        }

        private void websiteUrlLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(websiteUrlLink.Text.Substring(
                websiteUrlLink.LinkArea.Start,
                websiteUrlLink.LinkArea.Length));
        }
    }
}


text:
'use strict';

const fse = require('fs-extra');
const httpPost = require('../../httpPost');

const mime = require('mime-types');

const fileName = '../../../../ui/src/favicon-32x32.png';
const contentType = mime.lookup(fileName);
console.log(contentType);

fse.readFile(fileName)
    .then(content => httpPost('http://localhost:8790/v1/blob/test/favicon.png', content, contentType))
    .then(response => {
        console.log(response);
    })
    .catch(console.error);


text:
package strategy

import (
	"reflect"
	"strings"
	"testing"

	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/validation"
	kapi "k8s.io/kubernetes/pkg/api"
	kapihelper "k8s.io/kubernetes/pkg/api/helper"
	"k8s.io/kubernetes/pkg/api/v1"

	buildapi "github.com/openshift/origin/pkg/build/apis/build"
	_ "github.com/openshift/origin/pkg/build/apis/build/install"
	"github.com/openshift/origin/pkg/build/util"
)

func TestDockerCreateBuildPod(t *testing.T) {
	strategy := DockerBuildStrategy{
		Image: "docker-test-image",
		Codec: kapi.Codecs.LegacyCodec(buildapi.LegacySchemeGroupVersion),
	}

	build := mockDockerBuild()
	actual, err := strategy.CreateBuildPod(build)
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}

	if expected, actual := buildapi.GetBuildPodName(build), actual.ObjectMeta.Name; expected != actual {
		t.Errorf("Expected %s, but got %s!", expected, actual)
	}
	if !reflect.DeepEqual(map[string]string{buildapi.BuildLabel: buildapi.LabelValue(build.Name)}, actual.Labels) {
		t.Errorf("Pod Labels does not match Build Labels!")
	}
	if !reflect.DeepEqual(nodeSelector, actual.Spec.NodeSelector) {
		t.Errorf("Pod NodeSelector does not match Build NodeSelector.  Expected: %v, got: %v", nodeSelector, actual.Spec.NodeSelector)
	}

	container := actual.Spec.Containers[0]
	if container.Name != "docker-build" {
		t.Errorf("Expected docker-build, but got %s!", container.Name)
	}
	if container.Image != strategy.Image {
		t.Errorf("Expected %s image, got %s!", container.Image, strategy.Image)
	}
	if container.ImagePullPolicy != v1.PullIfNotPresent {
		t.Errorf("Expected %v, got %v", v1.PullIfNotPresent, container.ImagePullPolicy)
	}
	if actual.Spec.RestartPolicy != v1.RestartPolicyNever {
		t.Errorf("Expected never, got %#v", actual.Spec.RestartPolicy)
	}
	if len(container.Env) != 10 {
		var keys []string
		for _, env := range container.Env {
			keys = append(keys, env.Name)
		}
		t.Fatalf("Expected 10 elements in Env table, got %d:\n%s", len(container.Env), strings.Join(keys, ", "))
	}
	if len(container.VolumeMounts) != 4 {
		t.Fatalf("Expected 4 volumes in container, got %d", len(container.VolumeMounts))
	}
	if *actual.Spec.ActiveDeadlineSeconds != 60 {
		t.Errorf("Expected ActiveDeadlineSeconds 60, got %d", *actual.Spec.ActiveDeadlineSeconds)
	}
	for i, expected := range []string{dockerSocketPath, DockerPushSecretMountPath, DockerPullSecretMountPath, sourceSecretMountPath} {
		if container.VolumeMounts[i].MountPath != expected {
			t.Fatalf("Expected %s in VolumeMount[%d], got %s", expected, i, container.VolumeMounts[i].MountPath)
		}
	}
	if len(actual.Spec.Volumes) != 4 {
		t.Fatalf("Expected 4 volumes in Build pod, got %d", len(actual.Spec.Volumes))
	}
	if !kapihelper.Semantic.DeepEqual(container.Resources, util.CopyApiResourcesToV1Resources(&build.Spec.Resources)) {
		t.Fatalf("Expected actual=expected, %v != %v", container.Resources, build.Spec.Resources)
	}
	found := false
	foundIllegal := false
	for _, v := range container.Env {
		if v.Name == "BUILD_LOGLEVEL" && v.Value == "bar" {
			found = true
		}
		if v.Name == "ILLEGAL" {
			foundIllegal = true
		}
	}
	if !found {
		t.Fatalf("Expected variable BUILD_LOGLEVEL be defined for the container")
	}
	if foundIllegal {
		t.Fatalf("Found illegal environment variable 'ILLEGAL' defined on container")
	}

	buildJSON, _ := runtime.Encode(kapi.Codecs.LegacyCodec(buildapi.LegacySchemeGroupVersion), build)
	errorCases := map[int][]string{
		0: {"BUILD", string(buildJSON)},
	}
	for index, exp := range errorCases {
		if e := container.Env[index]; e.Name != exp[0] || e.Value != exp[1] {
			t.Errorf("Expected %s:%s, got %s:%s!\n", exp[0], exp[1], e.Name, e.Value)
		}
	}
}

func TestDockerBuildLongName(t *testing.T) {
	strategy := DockerBuildStrategy{
		Image: "docker-test-image",
		Codec: kapi.Codecs.LegacyCodec(buildapi.LegacySchemeGroupVersion),
	}
	build := mockDockerBuild()
	build.Name = strings.Repeat("a", validation.DNS1123LabelMaxLength*2)
	pod, err := strategy.CreateBuildPod(build)
	if err != nil {
		t.Fatalf("unexpected: %v", err)
	}
	if pod.Labels[buildapi.BuildLabel] != build.Name[:validation.DNS1123LabelMaxLength] {
		t.Errorf("Unexpected build label value: %s", pod.Labels[buildapi.BuildLabel])
	}
}

func mockDockerBuild() *buildapi.Build {
	timeout := int64(60)
	return &buildapi.Build{
		ObjectMeta: metav1.ObjectMeta{
			Name: "dockerBuild",
			Labels: map[string]string{
				"name": "dockerBuild",
			},
		},
		Spec: buildapi.BuildSpec{
			CommonSpec: buildapi.CommonSpec{
				Revision: &buildapi.SourceRevision{
					Git: &buildapi.GitSourceRevision{},
				},
				Source: buildapi.BuildSource{
					Git: &buildapi.GitBuildSource{
						URI: "http://my.build.com/the/dockerbuild/Dockerfile",
						Ref: "master",
					},
					ContextDir:   "my/test/dir",
					SourceSecret: &kapi.LocalObjectReference{Name: "secretFoo"},
				},
				Strategy: buildapi.BuildStrategy{
					DockerStrategy: &buildapi.DockerBuildStrategy{
						PullSecret: &kapi.LocalObjectReference{Name: "bar"},
						Env: []kapi.EnvVar{
							{Name: "ILLEGAL", Value: "foo"},
							{Name: "BUILD_LOGLEVEL", Value: "bar"},
						},
					},
				},
				Output: buildapi.BuildOutput{
					To: &kapi.ObjectReference{
						Kind: "DockerImage",
						Name: "docker-registry/repository/dockerBuild",
					},
					PushSecret: &kapi.LocalObjectReference{Name: "foo"},
				},
				Resources: kapi.ResourceRequirements{
					Limits: kapi.ResourceList{
						kapi.ResourceName(kapi.ResourceCPU):    resource.MustParse("10"),
						kapi.ResourceName(kapi.ResourceMemory): resource.MustParse("10G"),
					},
				},
				CompletionDeadlineSeconds: &timeout,
				NodeSelector:              nodeSelector,
			},
		},
		Status: buildapi.BuildStatus{
			Phase: buildapi.BuildPhaseNew,
		},
	}
}


text:
<phpunit bootstrap="test/Bootstrap.php" colors="true">
    <testsuites>
        <testsuite name="Eye4web Zf2AbacTest">
            <directory>./test</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist addUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./src</directory>
            <exclude>
                <directory suffix=".php">./config</directory>
                <directory suffix=".php">./src/Eye4web/Zf2Abac/Collcetions</directory>
                <directory suffix=".php">./src/Eye4web/Zf2Abac/Entity</directory>
                <directory suffix=".php">./src/Eye4web/Zf2Abac/Exception</directory>
                <file>./Module.php</file>
                <file>./src/Eye4web/Zf2Abac/Assertion/AssertionPluginManager.php</file>
                <file>./src/Eye4web/Zf2Abac/Assertion/AssertionInterface.php</file>
                <file>./src/Eye4web/Zf2Abac/Permission/PermissionInterface.php</file>
                <file>./src/Eye4web/Zf2Abac/Provider/ProviderInterface.php</file>
                <file>./src/Eye4web/Zf2Abac/Service/AuthorizationServiceInterface.php</file>
            </exclude>
        </whitelist>
    </filter>
</phpunit>


text:
<?php

namespace Doctrine\Tests\DBAL\Driver\PDOPgSql;

use Doctrine\DBAL\Driver\PDOPgSql\Driver;
use Doctrine\Tests\DBAL\Driver\AbstractPostgreSQLDriverTest;
use PDO;
use PDOException;

class DriverTest extends AbstractPostgreSQLDriverTest
{
    public function testReturnsName()
    {
        $this->assertSame('pdo_pgsql', $this->driver->getName());
    }

    /**
     * @group DBAL-920
     */
    public function testConnectionDisablesPreparesOnPhp56()
    {
        $this->skipWhenNotUsingPhp56AndPdoPgsql();

        $connection = $this->createDriver()->connect(
            array(
                'host' => $GLOBALS['db_host'],
                'port' => $GLOBALS['db_port']
            ),
            $GLOBALS['db_username'],
            $GLOBALS['db_password']
        );

        $this->assertInstanceOf('Doctrine\DBAL\Driver\PDOConnection', $connection);

        try {
            $this->assertTrue($connection->getAttribute(PDO::PGSQL_ATTR_DISABLE_PREPARES));
        } catch (PDOException $ignored) {
            /** @link https://bugs.php.net/bug.php?id=68371 */
            $this->markTestIncomplete('See https://bugs.php.net/bug.php?id=68371');
        }
    }

    /**
     * @group DBAL-920
     */
    public function testConnectionDoesNotDisablePreparesOnPhp56WhenAttributeDefined()
    {
        $this->skipWhenNotUsingPhp56AndPdoPgsql();

        $connection = $this->createDriver()->connect(
            array(
                'host' => $GLOBALS['db_host'],
                'port' => $GLOBALS['db_port']
            ),
            $GLOBALS['db_username'],
            $GLOBALS['db_password'],
            array(PDO::PGSQL_ATTR_DISABLE_PREPARES => false)
        );

        $this->assertInstanceOf('Doctrine\DBAL\Driver\PDOConnection', $connection);

        try {
            $this->assertNotSame(true, $connection->getAttribute(PDO::PGSQL_ATTR_DISABLE_PREPARES));
        } catch (PDOException $ignored) {
            /** @link https://bugs.php.net/bug.php?id=68371 */
            $this->markTestIncomplete('See https://bugs.php.net/bug.php?id=68371');
        }
    }

    /**
     * @group DBAL-920
     */
    public function testConnectionDisablePreparesOnPhp56WhenDisablePreparesIsExplicitlyDefined()
    {
        $this->skipWhenNotUsingPhp56AndPdoPgsql();

        $connection = $this->createDriver()->connect(
            array(
                'host' => $GLOBALS['db_host'],
                'port' => $GLOBALS['db_port']
            ),
            $GLOBALS['db_username'],
            $GLOBALS['db_password'],
            array(PDO::PGSQL_ATTR_DISABLE_PREPARES => true)
        );

        $this->assertInstanceOf('Doctrine\DBAL\Driver\PDOConnection', $connection);

        try {
            $this->assertTrue($connection->getAttribute(PDO::PGSQL_ATTR_DISABLE_PREPARES));
        } catch (PDOException $ignored) {
            /** @link https://bugs.php.net/bug.php?id=68371 */
            $this->markTestIncomplete('See https://bugs.php.net/bug.php?id=68371');
        }
    }

    /**
     * {@inheritDoc}
     */
    protected function createDriver()
    {
        return new Driver();
    }

    /**
     * @throws \PHPUnit_Framework_SkippedTestError
     */
    private function skipWhenNotUsingPhp56AndPdoPgsql()
    {
        if (PHP_VERSION_ID < 50600) {
            $this->markTestSkipped('Test requires PHP 5.6+');
        }

        if (! (isset($GLOBALS['db_type']) && $GLOBALS['db_type'] === 'pdo_pgsql')) {
            $this->markTestSkipped('Test enabled only when using pdo_pgsql specific phpunit.xml');
        }
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import theme from '../Tile.module.scss';

function Body(props) {
	return
{props.children}
;
}

Body.propTypes = {
	children: PropTypes.node,
};

export default Body;


text:
'use strict';

module.exports = function(app) {
	var users = require('../../app/controllers/users.server.controller');
	var flies = require('../../app/controllers/flies.server.controller');

	// Flies Routes
	app.route('/flies')
		.get(flies.list)
		.post(users.requiresLogin, flies.create);

	app.route('/flies/:flyId')
		.get(flies.read)
		.put(users.requiresLogin, flies.hasAuthorization, flies.update)
		.delete(users.requiresLogin, flies.hasAuthorization, flies.delete);

	// Finish by binding the Fly middleware
	app.param('flyId', flies.flyByID);
};


text:
package br.com.cybereagle.androidlibrary.util;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import roboguice.inject.ContextSingleton;

import javax.inject.Inject;

@ContextSingleton
public class ConnectivityUtils {

    private ConnectivityManager connectivityManager;

    @Inject
    public ConnectivityUtils(ConnectivityManager connectivityManager) {
        this.connectivityManager = connectivityManager;
    }

    public boolean isOnline() {
        NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected() && netInfo.isAvailable()) {
            return true;
        }
        return false;
    }

}


text:
using namespace std;
using namespace Eigen;
int main() {
  RigidBodyTree* model =
      new RigidBodyTree("examples/Atlas/urdf/atlas_minimal_contact.urdf");
  if (!model) {
    cerr << "ERROR: Failed to load model" << endl;
  }
  Vector2d tspan;
  tspan << 0, 1;
  VectorXd q0 = model->getZeroConfiguration();
  q0(3) = 0.8;
  Vector3d com_des = Vector3d::Zero();
  com_des(2) = std::numeric_limits<double>::quiet_NaN();
  WorldCoMConstraint* com_kc = new WorldCoMConstraint(model, com_des, com_des);
  int num_constraints = 1;
  RigidBodyConstraint** constraint_array =
      new RigidBodyConstraint* [num_constraints];
  constraint_array[0] = com_kc;
  IKoptions ikoptions(model);
  VectorXd q_sol(model->number_of_positions());
  int info;
  approximateIK(model, q0, q0, num_constraints, constraint_array,
                ikoptions, &q_sol, &info);
  printf("info = %d\n", info);
  delete com_kc;
  delete[] constraint_array;
  return 0;
}


text:
{% extends "impala/base_shared.html" %}

{% block bodyclass %}collections{% endblock %}

{% block content %}
  <section class="secondary">
    {% include "bandwagon/impala/collection_sidebar.html" %}
  </section>
  {% block primary %}{% endblock %}
{% endblock %}


text:
import collections
import contextlib
import functools
import sys

import discord
from discord.ext import commands

class _ContextSession(collections.namedtuple('_ContextSession', 'ctx')):
    __slots__ = ()

    def __await__(self):
        return self.ctx._acquire().__await__()

    async def __aenter__(self):
        return await self.ctx._acquire()

    async def __aexit__(self, exc_type, exc, tb):
        return await self.ctx._release(exc_type, exc, tb)

class Context(commands.Context):
    # Default for whether or not the global error handlers should ignore errors
    # in commands with local error handlers.
    __bypass_local_error__ = False

    # Used for getting the current parameter when generating an example
    _current_parameter = None

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.db = None

    @property
    def pool(self):
        return self.bot.pool

    @property
    def clean_prefix(self):
        """The cleaned up invoke prefix. (mentions are @name instead of <@id>)."""
        user = self.bot.user
        return self.prefix.replace(user.mention, f'@{user.name}')

    async def _acquire(self):
        if self.db is None:
            self.db = await self.pool.acquire()
        return self.db

    def acquire(self):
        """Acquires a database session.

        Can be used in an async context manager: ::
            async with ctx.acquire():
                await ctx.db.execute(...)
        or: ::
            await ctx.acquire()
            try:
                await ctx.db.execute(...)
            finally:
                await ctx.release()
        """
        # DatabaseInterface.get_session doesn't support a timeout kwarg sadly...
        return _ContextSession(self)

    async def _release(self, exc_type, exc, tb):
        """Internal method used for properly propagating the exceptions
        in the session's __aexit__.

        This is the method that is called automatically by the bot,
        NOT Context.release.
        """
        if self.db is not None:
            await self.pool.release(self.db)
            self.db = None

    async def release(self):
        """Closes the current database session.

        Useful if needed for "long" interactive commands where
        we want to release the connection and re-acquire later.
        """
        return await self._release(*sys.exc_info())

    # Credit to Danny#0007 for making the original
    async def confirm(self, message, *, timeout=60.0, delete_after=True, reacquire=True,
                      author_id=None, destination=None):
        """Prompts the user with either yes or no."""

        # We can also wait for a message confirmation as well. This is faster, but
        # it's risky if there are two prompts going at the same time.
        # TODO: Possibly support messages again?

        destination = destination or self.channel
        with contextlib.suppress(AttributeError):
            if not destination.permissions_for(self.me).add_reactions:
                raise RuntimeError('Bot does not have Add Reactions permission.')

        config = self.bot.emoji_config
        confirm_emoji, deny_emoji = emojis = [config.confirm, config.deny]
        is_valid_emoji = frozenset(map(str, emojis)).__contains__

        instructions = f'{confirm_emoji} \N{EM DASH} Yes\n{deny_emoji} \N{EM DASH} No'

        if isinstance(message, discord.Embed):
            message.add_field(name="Choices", value=instructions, inline=False)
            msg = await destination.send(embed=message)
        else:
            message = f'{message}\n\n{instructions}'
            msg = await destination.send(message)

        author_id = author_id or self.author.id

        def check(data):
            return (data.message_id == msg.id
                    and data.user_id == author_id
                    and is_valid_emoji(str(data.emoji)))

        for em in emojis:
            await msg.add_reaction(em)

        if reacquire:
            await self.release()

        try:
            data = await self.bot.wait_for('raw_reaction_add', check=check, timeout=timeout)
            return str(data.emoji) == str(confirm_emoji)
        finally:
            if reacquire:
                await self.acquire()

            if delete_after:
                await msg.delete()

    ask_confirmation = confirm

    def bot_has_permissions(self, **permissions):
        perms = self.channel.permissions_for(self.me)
        return all(getattr(perms, perm) == value for perm, value in permissions.items())

    bot_has_embed_links = functools.partialmethod(bot_has_permissions, embed_links=True)


text:
all:
	ghc -O2 --make -isrc -o nerf -outputdir tmp -rtsopts -threaded Main


text:
package org.kie.workbench.common.stunner.client.widgets.components.glyph;

import java.util.function.Supplier;

import com.google.gwtmockito.GwtMockitoTestRunner;
import org.gwtbootstrap3.client.ui.Icon;
import org.gwtbootstrap3.client.ui.constants.IconType;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.core.client.components.views.WidgetElementRendererView;
import org.mockito.Mock;
import org.uberfire.mvp.Command;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(GwtMockitoTestRunner.class)
public class BS3IconTypeGlyphRendererTest {

    @Mock
    private WidgetElementRendererView view;

    @Mock
    private Supplier<WidgetElementRendererView> viewSupplier;

    @Mock
    private Command viewDestroyer;

    private BS3IconTypeGlyphRenderer tested;

    @Before
    public void setup() throws Exception {
        when(viewSupplier.get()).thenReturn(view);
        this.tested = new BS3IconTypeGlyphRenderer(viewSupplier,
                                                   viewDestroyer);
    }

    @Test
    public void testType() {
        assertEquals(BS3IconTypeGlyph.class,
                     tested.getGlyphType());
    }

    @Test
    public void testRender() {
        final BS3IconTypeGlyph glyph = BS3IconTypeGlyph.create(IconType.ADN);
        tested.render(glyph,
                      100,
                      200);
        verify(viewSupplier,
               times(1)).get();
        verify(view,
               times(1)).setWidget(any(Icon.class));
    }

    @Test
    public void testDestroy() {
        tested.destroy();
        verify(viewDestroyer, times(1)).execute();
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Bull. Herb. Boissier sér. 2, 5:664. 1905

#### Original name
null

### Remarks
null


text:
<?php

namespace IHorse\BackendBundle\Test\Controller;

use IHorse\TestBundle\Classes\CustomTestCase;

class UserControllerTest extends CustomTestCase
{
    protected function setUp() {
        parent::setUp();
    }

    public function testAll()
    {
        $crawler = $this->client->request('GET', '/users/');
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
        $this->assertEquals(0, $crawler->filter('html:contains("Test")')->count());
    }

    public function testPost()
    {
        $crawler = $this->client->request('GET', '/users/new');
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
        $form = $crawler->selectButton('Guardar')
        ->form(array('admin_user[name]' => 'Test',
                'admin_user[email]' => self::USERNAME,
                'admin_user[password]'=>123456,
                'admin_user[last_name]'=>'testeando',
                'admin_user[idiom]' => 'ES'));
        $crawler = $this->client->submit($form);
        $crawler = $this->client->followRedirect();

        $this->assertGreaterThan(0, $crawler->filter('html:contains("Test")')->count());
    }

    public function testView()
    {
        $crawler = $this->client->request('GET', '/users/');
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
        $link = $crawler->filter('a .fa-eye')->first()->parents()->first()->link();
        $crawler = $this->client->click($link);
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
        $this->assertGreaterThan(0, $crawler->filter('html:contains("usuario")')->count());
    }

    public function testPut()
    {
        $crawler = $this->client->request('GET', '/users/');
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
        $link = $crawler->filter('a .fa-pencil')->first()->parents()->first()->link();
        $crawler = $this->client->click($link);
        $form = $crawler->selectButton('Guardar')
        ->form(array('admin_user[name]' => 'TestActualizado',
                'admin_user[email]' => self::USERNAME,
                'admin_user[password]'=>123456,
                'admin_user[last_name]'=>'testeando',
                'admin_user[idiom]' => 'ES'));
        $crawler = $this->client->submit($form);
        $crawler = $this->client->followRedirect();

        $this->assertGreaterThan(0, $crawler->filter('html:contains("TestActualizado")')->count());
    }

    public function testDelete()
    {
        $crawler = $this->client->request('GET', '/users/');
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
        $link = $crawler->filter('a .fa-trash-o')->first()->parents()->first()->link();
        $crawler = $this->client->click($link);
        $crawler = $this->client->followRedirect();
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
        $this->assertEquals(0, $crawler->filter('html:contains("Test")')->count());
    }
}


text:
title: Serial Console Setup
authors: fromani
wiki_title: Serial Console Setup
wiki_revision_count: 22
wiki_last_updated: 2015-10-12
---

# Serial Console Setup

## General

The purpose of this page is to document how to properly setup and troubleshoot the [Serial_Console](Serial_Console) feature, available in oVirt 3.6.0.

## Setup

The Serial Console can be setup either automatically, using engine-setup, or manually (not recommended). In both cases, the ovirt-vmconsole-proxy services must run on the same host on which Engine runs. This requirement will be lifted in a future release. The following sections documents fresh install of oVirt 3.6.x. For upgrading from 3.5.x, please see **upgrade notes** and **troubleshooting** below.

### Automatic Setup

1.  make sure you have all the required package installed. Alongside ovirt-engine and ovirt-engine setup, you must make sure you have the *ovirt-vmconsole-proxy* package installed in the same host on which ovirt-engine runs.
2.  to make ovirt-vmconsole-proxy host accessible, make sure the port "2222" is open. The setup procedure will setup "firewalld" accordingly.
3.  run engine-setup and follow instructions provided interactively. Please note that the vmconsole proxy setup is disabled if the *ovirt-vmconsole-proxy* package is NOT detected when the setup runs.
4.  once the setup succesfully run, and once ovirt-engine is running, you can log in and register a SSH key. (TODO: add picture)
5.  when you install an hypervisor host, the deploy procedure will automatically install and setup the "ovirt-vmconsole-host" package.
6.  make sure the user which want to use the serial console feature has permissions on the VM on which he wants to connect.
7.  make sure the relevant VM have the "Virtio Console Device" enabled
8.  congratulations! setup is now done. Please check **Connecting to consoles** below.

### Manual Setup

**This is NOT the recommended way**. The setup is a complex procedure. Use automatic setup whenever possible, and report bugs! Consider the following more like a checklist for troubleshooting rather than an HOWTO!

#### step 1: proxy and Engine setup

**TODO: verify the steps**

You need to have ovirt-engine installed. "password", below, is the ovirt-engine PKI password. As usual, "#" represents the root prompt. Since you need to leverage Engine's PKI, execute the following on the host on which Engine runs:

First, create certificates and keys for the vmconsole proxy helper:

       # /usr/share/ovirt-engine/bin/pki-enroll-pkcs12.sh --name=vmconsole-proxy-helper --password=password --subject="/C=COUNTRY/O=ORG/CN=FQDN" --ku=digitalSignature --eku=1.3.6.1.4.1.2312.13.1.2.1.1
       # /usr/share/ovirt-engine/bin/pki-pkcs12-extract.sh --name=vmconsole-proxy-helper --password=password
       # chown ovirt-vmconsole:ovirt-vmconsole /etc/pki/ovirt-engine/certs/vmconsole-proxy-helper.cert
       # chown ovirt-vmconsole:ovirt-vmconsole /etc/pki/ovirt-engine/keys/vmconsole-proxy-helper.key.nopass
       # chmod 0600 /etc/pki/ovirt-engine/keys/vmconsole-proxy-helper.key.nopass

Now configure the helper:

*   edit the helper configuration file $PREFIX/etc/ovirt-engine/ovirt-vmconsole-proxy-helper.conf.d/10-setup.conf
*   add content:

       ENGINE_BASE_URL=`[`https://$ENGINE_IP`](https://$ENGINE_IP)`:$ENGINE_PORT/ovirt-engine
       TOKEN_CERTIFICATE=$PREFIX/etc/pki/ovirt-engine/certs/vmconsole-proxy-helper.cer
       TOKEN_KEY=$PREFIX/etc/pki/ovirt-engine/keys/vmconsole-proxy-helper.key.nopass

**please note:** there is no shell variable expansion support. Here $PREFIX and $ENGINE_ADDRESS and $ENGINE_PORT are just a placeholders for the actual values you should use. The reminder are the default paths assumed.

Full example:

` ENGINE_BASE_URL=`[`https://sercon.test.lan:8443/ovirt-engine/`](https://sercon.test.lan:8443/ovirt-engine/)
       TOKEN_CERTIFICATE=/usr/local/etc/pki/ovirt-engine/certs/vmconsole-proxy-helper.cer
       TOKEN_KEY=/usr/local/etc/pki/ovirt-engine/keys/vmconsole-proxy-helper.key.nopass

Now, configure the ovirt-vmconsole-proxy package to use the helper.

*   edit the proxy configuration file /etc/ovirt-vmconsole/ovirt-vmconsole-proxy/conf.d/10-engine-setup.conf
*   add content:

       [proxy]
       key_list = exec $PREFIX/libexec/ovirt-vmconsole-proxy-helper/ovirt-vmconsole-list.py --version {version} keys
       console_list = exec $PREFIX/libexec/ovirt-vmconsole-proxy-helper/ovirt-vmconsole-list.py --version {version} consoles --entityid {entityid}"

**please note:** ovirt-vmconsole package expands {version} and {entityid}, not $PREFIX. Here $PREFIX is just a placeholder for the actual prefix on which you installed ovirt-engine. For example if you installed ovirt-engine with PREFIX=/usr/local, the above should read

       [proxy]
       key_list = exec /usr/local/libexec/ovirt-vmconsole-proxy-helper/ovirt-vmconsole-list.py --version {version} keys
       console_list = exec /usr/local/libexec/ovirt-vmconsole-proxy-helper/ovirt-vmconsole-list.py --version {version} consoles --entityid {entityid}"

That should be it! Now you can verify the helper is running OK

       # developer installation
       [root@sercon ~]# /usr/local/ovirt/sercon/libexec/ovirt-vmconsole-proxy-helper/ovirt-vmconsole-list.py --version 1 keys
        {"content": "key_list", "keys": [{"username": "admin", "entityid": "fdfc627c-d875-11e0-90f0-83df133b58cc", "key": "ssh-rsa AAAB3NzaC1yc2EAAAADAQABAAABAQDSosmEQPVsPPysLmAJQy5vfbb8qf2x8+3jLQAqYc7Zhp4kIasHZ2lLOxFJ5hZR3ajaB/JsdMmblMMMkxZlv9YPZhd+1rHsjt85AS+Yt1AGRFK5KK9f3MIyj8nlOERr+N96L7nCRJ4y0r+Wtnrs5b6iYhciohpexVUBXAcu4LTrqw4kvm67lvTv0CgTxTQAMcrIgAhvdqNy4VfWmprKj0zTIWC5A4Hw4WFRftri3cJZL/onl/z+3WZjMcbApKXw6Ir7aFwFOgwDK8eqLQLt8ZGcevchYnS6XUyYbWyFQxxwCxpRea3M+/s2LCAyKQsCID+HRvT+1CWHW7nJnw3eMs59 fromani@musashi.rokugan.lan", "entity": "user-id"}], "version": 1}

And that the proxy package is working OK as well:

       [root@sercon ~]# su - ovirt-vmconsole -c 'ovirt-vmconsole-proxy-keys list'
       command="exec "/usr/sbin/ovirt-vmconsole-proxy-shell"  accept --entityid="fdfc627c-d875-11e0-90f0-83df133b58cc" --entity="user-id"",no-agent-forwarding,no-port-forwarding,no-user-rc,no-X11-forwarding ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDSosmEQPVsPPysLmAJQy5vfbb8qf2x8+3jLQAqYc7Zhp4kIasHZ2lLOxFJ5hZR3ajaB/JsdMmblMMMkxZlv9YPZhd+1rHsjt85AS+Yt1AGRFK5KK9f3MIyj8nlOERr+N96L7nCRJ4y0r+Wtnrs5b6iYhciohpexVUBXAcu4LTrqw4kvm67lvTv0CgTxTQAMcrIgAhvdqNy4VfWmprKj0zTIWC5A4Hw4WFRftri3cJZL/onl/z+3WZjMcbApKXw6Ir7aFwFOgwDK8eqLQLt8ZGcevchYnS6XUyYbWyFQxxwCxpRea3M+/s2LCAyKQsCID+HRvT+1CWHW7nJnw3eMs59 fromani@musashi.rokugan.lan[root@sercon ~]#

#### step 2: host connection setup

Install the needed packages on the hypervisor hosts:

       ovirt-vmconsole
       ovirt-vmconsole-host

Make sure the port 2223 is open on the hypervisor hosts

You need to have ovirt-engine installed. "password", below, is the ovirt-engine PKI password. As usual, "#" represents the root prompt. Since you need to leverage Engine's PKI, execute the following on the host on which Engine runs:

       # /usr/share/ovirt-engine/bin/pki-enroll-pkcs12.sh --name=proxy1-host --password=password --subject="/CN=proxy1"
       # /usr/share/ovirt-engine/bin/pki-enroll-pkcs12.sh --name=proxy1-user --password=password --subject="/CN=proxy1"
       # /usr/share/ovirt-engine/bin/pki-enroll-openssh-cert.sh --name=proxy1-host --id=proxy1 --host --principals=@PROXY_FQDN@
       # /usr/share/ovirt-engine/bin/pki-enroll-openssh-cert.sh --name=proxy1-user --id=proxy1 --principals=ovirt-vmconsole-proxy
       # cp /etc/pki/ovirt-engine/certs/proxy1-host-cert.pub /etc/pki/ovirt-vmconsole/proxy-ssh_host_rsa-cert.pub
       # cp /etc/pki/ovirt-engine/certs/proxy1-user-cert.pub /etc/pki/ovirt-vmconsole/proxy-ssh_user_rsa-cert.pub
       # openssl pkcs12 -passin password -in /etc/pki/ovirt-engine/keys/proxy1-host.p12 -nodes -nocerts > /etc/pki/ovirt-vmconsole/proxy-ssh_host_rsa
       # openssl pkcs12 -passin password -in /etc/pki/ovirt-engine/keys/proxy1-user.p12 -nodes -nocerts > /etc/pki/ovirt-vmconsole/proxy-ssh_user_rsa
       # chown ovirt-vmconsole:ovirt-vmconsole /etc/pki/ovirt-vmconsole/proxy-ssh_host_rsa /etc/pki/ovirt-vmconsole/proxy-ssh_user_rsa
       # chmod 0600 /etc/pki/ovirt-vmconsole/proxy-ssh_host_rsa /etc/pki/ovirt-vmconsole/proxy-ssh_user_rsa

## Connecting to consoles

Access to proxy by user is perform using the following command, a menu with the available consoles will be presented:

       $ ssh -t -p 2222 ovirt-vmconsole@proxy-host connect

Access to specify console can be done using the following command:

       $ ssh -t -p 2222 ovirt-vmconsole@proxy-host connect --vm-id=1E12DF323

List available consoles:

       $ ssh -t -p 2222 ovirt-vmconsole@proxy-host list

Usage:

       $ ssh -t  -p 2222 ovirt-vmconsole@proxy-host -- --help

### Serial console on boot

It's possible to use serial console immediately from the virtual machine startup with recent development versions of Engine and VDSM, if the BIOS of the virtual machine supports serial console. Then you can see BIOS bootup messages, select booting method, choose GRUB menu items, etc. on the console.

Just note that serial console is not a very powerful editing tool. For instance, when using arrow keys or Escape you may need to press them multiple times to take effect. Also the screen output may not be pretty and some things may be hard to achieve.

When you want to use serial console on boot, it may be a good idea to start the virtual machine in paused mode. Then you can connect to the console before the machine actually starts.

One of the features the recent Engine versions provide to make serial console available on boot is switching from hv0 to ttyS0 console device. So make sure your getty process runs on ttyS0. This is not important to see the bootup messages but it is important to be able to log into your system using serial console.

## Upgrade Notes

If you are upgrading fro oVirt 3.5.x, to use the serial consone feature you must perform engine-setup and key registration in Engine exactly as per fresh start. Hoever, additional care is needed.

1.  the upgrade procedure **will automatically upgrade the existing VM to use the new Serial Console Device**. Please see "Troubleshooting" below if you still need to manually connect to your consoles. Otherwise, the upgrade
2.  to use the new Serial Console Device, you must redeploy all existing host, to make sure the correct setup is performed.

Please note that installing the needed package on your hypervisor hosts (ovirt-vmconsole, ovirt-vmconsole-host), is necessary, but not sufficient to use the feature. You also must enroll keys and certificates, and this is what reinstall will do.

## How to change the serial console TCP port

In some special cases, you may need to change the TCP port the serial-console infrastructure uses
to connect to emulated serial ports. This can be done manually, but it is not recommended way
since it may easily broken by updates.

It is worth reminding that the serial console infrastructure uses special-configured standard ssh
tools so it boils down to change those ssh options and fix the selinux policy.

1. The sshd options can be overridden using OPTIONS variable at:

    /etc/sysconfig/ovirt-vmconsole-host-sshd

This has to be done on each virtualization host.
On the proxy host, you will need to edit

    /etc/sysconfig/ovirt-vmconsole-proxy-sshd

On the proxy host, you will also need to override the *ssh* options using

   /etc/ovirt-vmconsole/ovirt-vmconsole-proxy/conf.d/90-custom-options.conf

Look for the

   console_attach_ssh_args=""

Option.

Finally, the SELinux should be customized:
On the proxy host:

  # semanage port -a -t ovirt_vmconsole_proxy_port_t -p tcp XXX

On *each* virtualization host:

  # semanage port -a -t ovirt_vmconsole_host_port_t -p tcp XXX

## Troubleshooting

### Cannot connect to VM/VM not present in the available consoles list

Make sure the user has the permissions on the VM (s)he wants to connect to. In webadmin: VM panel -> permissions subpanel.

### I need to access the console the old way

Starting 3.6.x. the VM console are no longer connected to PTYs, but to unix domain socket. In 3.5.x days, the way to connect to VM consoles was something like

       ssh hypervisor-host
       virsh console $VM_NAME

in 3.6.x, if you need to manually connect to console, you can connect to unix domain socket:

       ssh hypervisor-host
       minicom -D unix#$VM_SOCKET

Please note that the user which runs minicom must be part of the **ovirt-vmconsole** group the socket will have paths like

       /var/run/ovirt-vmconsole-console/$VM_UUID.sock

another option is using socat:

       socat -,raw,echo=0,escape=1 UNIX-LISTEN:/var/run/ovirt-vmconsole-console/$VM_UUID.sock,user=ovirt-vmconsole

### SELinux denials running ovirt-vmconsole-list.py

This should be handled by packaging, so it is highly unlikley you ever encounter this. If it happens, however, please make sure that

*   You have this patch applied:

` `[`https://gerrit.ovirt.org/#/c/43655/`](https://gerrit.ovirt.org/#/c/43655/)

*   the ovirt-vmconsole-list.py helper has the right SELinux label:

       # chcon -t bin_t $PREFIX/libexec/ovirt-vmconsole-proxy-helper/ovirt-vmconsole-list.py

*   As last resort, on Fedora/RHEL/Centos/Scientifix Linux, please make sure this boolean is enabled:

       # setsebool -P nis_enabled 1
       This was reported to help, and it is only slightly better than disabling selinux alltogether.

if you still get SELinux denials after checking the above, please file a bug.

### I succesfully selected a console, but now I get just a blank screen

This most likely means that the system set up the connection properly, but nothing is listening on the guest side of the connection. You need to make sure the a getty is spawned on the guest, so something is actually listening.

For example, in CentOS 7.x, you need to make sure the serial-getty is running

       # systemctl status serial-getty@hvc0.service

and start it if not

       # systemctl start serial-getty@hvc0.service

You may also want to enable the serial console emulation. This boils down to set the console type to "serial" instead of "virtio" (This is going to be fixed in oVirt 3.6.0-final thanks to [this patch](https://gerrit.ovirt.org/#/c/46700/)) for greater compatibility. In modern systems, like CentOS 7, this will likely make the getty listen on the console automatically.


text:
package com.bn.tag;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 *
 *
 *
 */
public class GameOverView extends SurfaceView
implements SurfaceHolder.Callback  //ʵ���������ڻص��ӿ�
{
	TafangGameActivity activity;
	Paint paint;//����
	int currentAlpha=0;//��ǰ�IJ�͸��ֵ

	float screenWidth=Constant.SCREEN_HEIGHT;//��Ļ���
	float screenHeight=Constant.SCREEN_WIDTH;//��Ļ�߶�
	int sleepSpan=50;//������ʱ��ms

	Bitmap bitmapGameOver;//��ǰlogoͼƬ����
	int currentX;
	int currentY;

	public GameOverView(TafangGameActivity activity) {
		super(activity);
		this.activity = activity;
		this.getHolder().addCallback(this);//�����������ڻص��ӿڵ�ʵ����
		paint = new Paint();//��������
		paint.setAntiAlias(true);//�򿪿����

		//����ͼƬ
		bitmapGameOver=BitmapFactory.decodeResource(activity.getResources(), R.drawable.gameover);

	}
	public void onDraw(Canvas canvas){
		//���ƺ��������屳��
		paint.setColor(Color.BLACK);//���û�����ɫ
		paint.setAlpha(255);
		canvas.drawRect(0, 0, screenWidth, screenHeight, paint);

		//����ƽ����ͼ
		if(bitmapGameOver==null)return;
		paint.setAlpha(currentAlpha);
		canvas.drawBitmap(bitmapGameOver, currentX, currentY, paint);
	}

	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {

	}
	public void surfaceCreated(SurfaceHolder holder) {//����ʱ������
		new Thread()
		{
			public void run()
			{
					//����ͼƬλ��
					currentX=(int) (activity.screenWidth/2-bitmapGameOver.getWidth()/2);
					currentY=(int) (activity.screenHeight/2-bitmapGameOver.getHeight()/2);

					for(int i=255;i>-10;i=i-5)
					{//��̬����ͼƬ��͸����ֵ�������ػ�
						currentAlpha=i;
						if(currentAlpha<0)
						{
							currentAlpha=0;
						}
						SurfaceHolder myholder=GameOverView.this.getHolder();
						Canvas canvas = myholder.lockCanvas();//��ȡ����
						try{
							synchronized(myholder){
								onDraw(canvas);//����
							}
						}
						catch(Exception e){
							e.printStackTrace();
						}
						finally{
							if(canvas != null){
								myholder.unlockCanvasAndPost(canvas);
							}
						}
						try
						{
							if(i==255)
							{//������ͼƬ����ȴ�һ��
								Thread.sleep(1000);
							}
							Thread.sleep(sleepSpan);
						}
						catch(Exception e)
						{
							e.printStackTrace();
						}
					}

				//����������Ϻ�ȥ���˵�����
				 activity.sendMessage(1);
			}
		}.start();
	}

	public void surfaceDestroyed(SurfaceHolder arg0) {//����ʱ������

	}
}


text:
import unittest
import pkgutil
import logging
import sys

def all_names():
    for _, modname, _ in pkgutil.iter_modules(__path__):
        yield 'analytics.test.' + modname

def all():
    logging.basicConfig(stream=sys.stderr)
    return unittest.defaultTestLoader.loadTestsFromNames(all_names())


text:
import React from "react";
import {EuiTextAlign, EuiTextColor} from "@elastic/eui";

/**
 * Contains the commands used to control a query.
 */
export const InfoToolbar = ({info}) => {

   if (info == null) return <EuiTextAlign textAlign="right"/>

   let processed = null;
   if (info.recordsPolled) {
      processed = <>Records Polled: {info.recordsPolled}  </>
   }

   return <>
      <EuiTextAlign textAlign="right">
         <EuiTextColor color="subdued">
            <i>
               {processed}
               Execution Time: {info.executionTimeInMillis}ms
            </i>
         </EuiTextColor>
      </EuiTextAlign>
   </>
}


text:
import os
import sentry_sdk
from flask import Flask
from flask_cors import CORS
from flask_restful import Api
from previews.routes import (
  PreviewRequests,
  HealthzEndpoint,
)
from flask_prom import monitor

sentry_sdk.init(
    dsn=os.getenv("SENTRY_DSN"),
    environment=os.getenv("SENTRY_ENVIRONMENT"),
)

app = Flask("preview")
CORS(app)
api = Api(app)

app.wsgi_app = monitor(app)

api.add_resource(PreviewRequests, "/")
api.add_resource(HealthzEndpoint, "/healthz")

if __name__ == "__main__":
  app.run(debug=os.environ.get("FLASK_DEBUG", False))