text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using BrightcoveMapiWrapper.Api;
using BrightcoveMapiWrapper.Api.Connectors;
using BrightcoveMapiWrapper.Model;
using BrightcoveMapiWrapper.Model.Containers;
using BrightcoveMapiWrapper.Model.Items;
using NUnit.Framework;

namespace BrightcoveOS.NET_MAPI_Wrapper.Tests.IntegrationTests.VideoRead
{
	/// <summary>
	/// Integration tests of video search url construction.
	/// </summary>
	[TestFixture(ApiKeys.ReadToken)]
	public class SearchVideosUrlConstructionTests
	{
		public BrightcoveApi Api { get; set; }
		public string ApiKey { get; set; }

		private List<FieldValuePair> _allFieldValues;
		private IEnumerable<FieldValuePair> AllFieldValues
		{
			get
			{
				if (_allFieldValues == null)
				{
					_allFieldValues = new List<FieldValuePair>
										  {
											  new FieldValuePair("display_name", "martian"),
											  new FieldValuePair("tag", "alien")
										  };
				}
				return _allFieldValues;
			}
		}

		private List<FieldValuePair> _anyFieldValues;
		private IEnumerable<FieldValuePair> AnyFieldValues
		{
			get
			{
				if (_anyFieldValues == null)
				{
					_anyFieldValues = new List<FieldValuePair>
										  {
											  new FieldValuePair("search_text", "foreigner"),
											  new FieldValuePair("custom_fields", "xenophobe")
										  };
				}
				return _anyFieldValues;
			}
		}

		private List<FieldValuePair> _noneFieldValues;
		private IEnumerable<FieldValuePair> NoneFieldValues
		{
			get
			{
				if (_noneFieldValues == null)
				{
					_noneFieldValues = new List<FieldValuePair>
										  {
											  new FieldValuePair(null, "american"),
											  new FieldValuePair("reference_id", "1234")
										  };
				}
				return _noneFieldValues;
			}
		}

		public delegate void CreateApiCall();

		public SearchVideosUrlConstructionTests(string apiKey)
		{
			ApiKey = apiKey;
		}

		public SearchVideosUrlConstructionTests() : this(null)
		{
		}

		[SetUp]
		public void Create_Brightcove_Api()
		{
			// Instantiate an API object by using the provided factory
			Api = BrightcoveApiFactory.CreateApi(ApiKey);
		}

		/// <summary>
		/// Tests if you can connect to Brightcove at all.
		/// </summary>
		[Test]
		public void SearchVideos_Connection_Test()
		{
			// Perform the API call
			Api.SearchVideos(new List<FieldValuePair>(),
			                 new List<FieldValuePair>(),
			                 new List<FieldValuePair>());
		}

		/// <summary>
		/// Tests if a listing of blank parameters produces the correct url.
		/// </summary>
		[Test]
		public void SearchVideos_No_All_Any_None_Parameters_Url()
		{
			Api.SearchVideos(new List<FieldValuePair>(),
			                 new List<FieldValuePair>(),
			                 new List<FieldValuePair>());

			String url = ((BrightcoveApiConnector)Api.Connector).RequestUrl;
			String expectedUrl = String.Format("http://api.brightcove.com/services/library?command=search_videos&token={0}&sort_by=CREATION_DATE%3aASC&exact=false&page_size=100&page_number=0&get_item_count=true", HttpUtility.UrlEncode(ApiKey));

			Assert.AreEqual(expectedUrl, url);
		}

		/// <summary>
		/// Tests if a listing of non-blank all/any/none parameters products a correct url.
		/// </summary>
		[Test]
		public void SearchVideos_All_Any_None_Parameters_Url()
		{
			Api.SearchVideos(AllFieldValues,
			                 AnyFieldValues,
			                 NoneFieldValues);

			String url = ((BrightcoveApiConnector)Api.Connector).RequestUrl;
			StringBuilder builder = new StringBuilder("http://api.brightcove.com/services/library?command=search_videos&token={0}")
				.Append("&all=display_name%3amartian&all=tag%3aalien")
				.Append("&any=search_text%3aforeigner&any=custom_fields%3axenophobe")
				.Append("&none=american&none=reference_id%3a1234")
				.Append("&sort_by=CREATION_DATE%3aASC")
				.Append("&exact=false&page_size=100&page_number=0&get_item_count=true");
			String expectedUrl = String.Format(builder.ToString(), HttpUtility.UrlEncode(ApiKey));

			Assert.AreEqual(expectedUrl, url);
		}

		/// <summary>
		/// Tests if non blank parameters with one sort field products the correct url.
		/// </summary>
		[Test]
		public void SearchVideos_With_Parameters_With_One_Sort()
		{
			Api.SearchVideos(AllFieldValues,
			                 AnyFieldValues,
			                 NoneFieldValues,
			                 100,
			                 0,
			                 false,
			                 new SortedFieldDictionary(SortBy.ModifiedDate, SortOrder.Ascending));

			String url = ((BrightcoveApiConnector)Api.Connector).RequestUrl;
			StringBuilder builder = new StringBuilder("http://api.brightcove.com/services/library?command=search_videos&token={0}")
				.Append("&all=display_name%3amartian&all=tag%3aalien")
				.Append("&any=search_text%3aforeigner&any=custom_fields%3axenophobe")
				.Append("&none=american&none=reference_id%3a1234")
				.Append("&sort_by=MODIFIED_DATE%3aASC")
				.Append("&exact=false&page_size=100&page_number=0&get_item_count=true");
			String expectedUrl = String.Format(builder.ToString(), HttpUtility.UrlEncode(ApiKey));

			Assert.AreEqual(expectedUrl, url);
		}

		/// <summary>
		/// Tests if non blank parameters with multiple sort fields products the correct url.
		/// </summary>
		[Test]
		public void SearchVideos_With_Parameters_With_Multiple_Sorts()
		{

			Api.SearchVideos(AllFieldValues,
			                 AnyFieldValues,
			                 NoneFieldValues,
			                 100,
			                 0,
			                 false,
			                 new SortedFieldDictionary(SortBy.ModifiedDate, SortOrder.Ascending, SortBy.DisplayName, SortOrder.Descending, SortBy.PlaysTotal, SortOrder.Descending));

			String url = ((BrightcoveApiConnector)Api.Connector).RequestUrl;
			StringBuilder builder = new StringBuilder("http://api.brightcove.com/services/library?command=search_videos&token={0}")
				.Append("&all=display_name%3amartian&all=tag%3aalien")
				.Append("&any=search_text%3aforeigner&any=custom_fields%3axenophobe")
				.Append("&none=american&none=reference_id%3a1234")
				.Append("&sort_by=MODIFIED_DATE%3aASC%2cDISPLAY_NAME%3aDESC%2cPLAYS_TOTAL%3aDESC")
				.Append("&exact=false&page_size=100&page_number=0&get_item_count=true");
			String expectedUrl = String.Format(builder.ToString(), HttpUtility.UrlEncode(ApiKey));

			Assert.AreEqual(expectedUrl, url);
		}

		[Test]
		public void Use_Japanese_Url()
		{
			// Override the default API.
			Api = BrightcoveApiFactory.CreateApi(ApiKey, BrightcoveRegion.Japan);

			// The token doesn't work with the Japanese version of the API, and so it should throw an Invalid Token error; nonetheless, we want to check to see if the URL was properly constructed.
			try
			{
				var videos = Api.SearchVideos(new List<FieldValuePair>(),
											  new List<FieldValuePair>(),
											  new List<FieldValuePair>());
			}
			catch (BrightcoveApiException ex)
			{
				// Check to see whether the code references the Brightcove invalid token code (as of December 2012).
				if (ex.Error.Code != 210)
				{
					throw;
				}
			}

			String url = ((BrightcoveApiConnector)Api.Connector).RequestUrl;
			String expectedUrl = String.Format("http://api.brightcove.co.jp/services/library?command=search_videos&token={0}&sort_by=CREATION_DATE%3aASC&exact=false&page_size=100&page_number=0&get_item_count=true", HttpUtility.UrlEncode(ApiKey));

			Assert.AreEqual(expectedUrl, url);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace GrumPHPTest\Unit\Task;

use GrumPHP\Task\Context\ContextInterface;
use GrumPHP\Task\Context\GitPreCommitContext;
use GrumPHP\Task\Context\RunContext;
use GrumPHP\Task\TaskInterface;
use GrumPHP\Task\PhpVersion;
use GrumPHP\Test\Task\AbstractTaskTestCase;
use GrumPHP\Util\PhpVersion as PhpVersionUtility;
use Prophecy\Prophecy\ObjectProphecy;

class PhpVersionTest extends AbstractTaskTestCase
{
    /**
     * @var PhpVersionUtility|ObjectProphecy
     */
    private $versionUtility;

    protected function provideTask(): TaskInterface
    {
        $this->versionUtility = $this->prophesize(PhpVersionUtility::class);

        return new PhpVersion($this->versionUtility->reveal());
    }

    public function provideConfigurableOptions(): iterable
    {
        yield 'defaults' => [
            [],
            [
                'project' => null,
            ]
        ];
    }

    public function provideRunContexts(): iterable
    {
        yield 'run-context' => [
            true,
            $this->mockContext(RunContext::class)
        ];

        yield 'pre-commit-context' => [
            true,
            $this->mockContext(GitPreCommitContext::class)
        ];

        yield 'other' => [
            false,
            $this->mockContext()
        ];
    }

    public function provideFailsOnStuff(): iterable
    {
        yield 'current-version-not-supported' => [
            [
                'project' => '7.4'
            ],
            $this->mockContext(RunContext::class, ['hello.xml']),
            function (array $options, ContextInterface $context) {
                $this->versionUtility->isSupportedVersion(PHP_VERSION)->willReturn(false);
            },
            'PHP version '.PHP_VERSION.' is unsupported'
        ];
        yield 'project-version-bigger' => [
            [
                'project' => '99.99.1'
            ],
            $this->mockContext(RunContext::class, ['hello.xml']),
            function (array $options, ContextInterface $context) {
                $this->versionUtility->isSupportedVersion(PHP_VERSION)->willReturn(true);
                $this->versionUtility->isSupportedProjectVersion(PHP_VERSION, $options['project'])->willReturn(false);
            },
            'This project requires PHP version 99.99.1, you have '.PHP_VERSION
        ];
    }

    public function providePassesOnStuff(): iterable
    {
        yield 'project-version-lower' => [
            [
                'project' => '4.0'
            ],
            $this->mockContext(RunContext::class, ['hello.xml']),
            function (array $options, ContextInterface $context) {
                $this->versionUtility->isSupportedVersion(PHP_VERSION)->willReturn(true);
                $this->versionUtility->isSupportedProjectVersion(PHP_VERSION, $options['project'])->willReturn(true);
            }
        ];
    }

    public function provideSkipsOnStuff(): iterable
    {
        yield 'no-project' => [
            [],
            $this->mockContext(RunContext::class),
            function () {}
        ];
    }
}


text:
/**
 * 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.
 */
/**
 * 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
 * <p>
 * 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.github.pires.obd.commands.protocol;

import com.github.pires.obd.commands.ObdCommand;

/**
 * Created by Shaun on 2015/07/20.
 */
public class ResetTroubleCodes extends ObdCommand {

    public ResetTroubleCodes() {
        super("04");
    }

    @Override
    protected void performCalculations() {

    }

    @Override
    public String getFormattedResult() {
        return getResult();
    }

    @Override
    public String getCalculatedResult() {
        return getResult();
    }

    @Override
    public String getName() {
        return getResult();
    }

}


text:
<?xml version="1.0"?>
<package version="2.0" xmlns="http://pear.php.net/dtd/package-2.0"
    xmlns:tasks="http://pear.php.net/dtd/tasks-1.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0
http://pear.php.net/dtd/tasks-1.0.xsd
http://pear.php.net/dtd/package-2.0
http://pear.php.net/dtd/package-2.0.xsd">
  <name>trace</name>
  <channel>pecl.php.net</channel>
  <summary>Trace is a low-overhead tracing tool for PHP</summary>
  <description>
    Trace is a low-overhead tracing tool for PHP.
    It can trace all PHP executing, function calls, request information during
    run-time. And provides features like Filter, Statistics, Current Status and
    so on.
    It is very useful to locate blocking, heavy-load problems and debug in all
    environments, especially in production environments.
  </description>
  <lead>
    <name>Yuchen Wang</name>
    <user>monque</user>
    <email>phobosw@gmail.com</email>
    <active>yes</active>
  </lead>
  <lead>
    <name>Anan Zhao</name>
    <user>flabby</user>
    <email>flabbyan@gmail.com</email>
    <active>yes</active>
  </lead>
  <date>2015-05-21</date>
  <version>
    <release>0.3.0</release>
    <api>0.3.0</api>
  </version>
  <stability>
    <release>stable</release>
    <api>stable</api>
  </stability>
  <license uri="http://www.apache.org/licenses/LICENSE-2.0.html">Apache 2.0</license>

  <notes>
### Added

- Added support for special function calls: `main`, `include`, `require`, `Closure`, `Labmda`, `eval()`
- Added support for PHP 5.1
- Keep collecting and sending back trace information after PHP bailout
- Added duplexing to communication module
- Compatible with Trait Alias
- Added checking for ZTS (Thread-safety support) during configuration

### Changed

- Refactor the PHP extension
- Unified the naming convention of Type, Function, Macro
- Change License to Apache 2.0
- Change Extension's name to "trace" (php is redundant for a PHP extension)
- Improve representation of `zval` and support for Array, Object
- Improve performance when trace if off
- Limit the length of print arguments and retvalue

### Fixed

- Fixed handling of large or small double value that needs scientific notation
- Fixed memory leaks related with SDS
  </notes>

  <contents>
    <dir name="/">
      <file role="doc" name="CHANGES.md"/>
      <file role="doc" name="CHANGES_ZH.md"/>
      <file role="doc" name="LICENSE"/>
      <file role="src" name="Makefile"/>
      <file role="doc" name="README.md"/>
      <file role="doc" name="README_ZH.md"/>
      <dir name="cmdtool">
        <file role="src" name="Makefile"/>
        <file role="src" name="log.c"/>
        <file role="src" name="log.h"/>
        <file role="src" name="phptrace"/>
        <file role="src" name="sys_trace.c"/>
        <file role="src" name="sys_trace.h"/>
        <file role="src" name="trace.c"/>
        <file role="src" name="trace.h"/>
        <file role="src" name="trace_count.c"/>
        <file role="src" name="trace_count.h"/>
        <file role="src" name="trace_status.c"/>
        <file role="src" name="trace_status.h"/>
        <file role="src" name="trace_util.c"/>
        <file role="src" name="trace_util.h"/>
      </dir> <!-- cmdtool -->
      <dir name="common">
        <dir name="sds">
          <file role="doc" name="LICENSE"/>
          <file role="src" name="Makefile"/>
          <file role="doc" name="README.md"/>
          <file role="src" name="sds.c"/>
          <file role="src" name="sds.h"/>
          <file role="src" name="testhelp.h"/>
        </dir> <!-- sds -->
        <file role="src" name="trace_comm.c"/>
        <file role="src" name="trace_comm.h"/>
        <file role="src" name="trace_ctrl.c"/>
        <file role="src" name="trace_ctrl.h"/>
        <file role="src" name="trace_mmap.c"/>
        <file role="src" name="trace_mmap.h"/>
        <file role="src" name="trace_time.h"/>
        <file role="src" name="trace_type.c"/>
        <file role="src" name="trace_type.h"/>
        <file role="src" name="uthash.h"/>
      </dir> <!-- common -->
      <dir name="extension">
        <file role="src" name="config.m4"/>
        <file role="src" name="make_test_on.sh"/>
        <file role="src" name="php_trace.h"/>
        <dir name="tests">
          <file role="test" name="skipif.inc"/>
          <file role="test" name="trace_001.phpt"/>
          <file role="test" name="trace_002.phpt"/>
          <file role="test" name="trace_002_include.inc"/>
          <file role="test" name="trace_002_require.inc"/>
          <file role="test" name="trace_003.phpt"/>
          <file role="test" name="trace_004.phpt"/>
          <file role="test" name="trace_005.phpt"/>
          <file role="test" name="trace_006.phpt"/>
          <file role="test" name="trace_006_include.inc"/>
          <file role="test" name="trace_007.phpt"/>
          <file role="test" name="trace_008.phpt"/>
          <file role="test" name="trace_009.phpt"/>
          <file role="test" name="trace_010.phpt"/>
          <file role="test" name="trace_011.phpt"/>
          <file role="test" name="trace_012.phpt"/>
        </dir> <!-- tests -->
        <file role="src" name="trace.c"/>
      </dir> <!-- extension -->
      <file role="src" name="release.sh"/>
    </dir> <!-- / -->
  </contents>
  <dependencies>
    <required>
      <php>
        <min>5.1</min>
      </php>
      <pearinstaller>
        <min>1.4.0</min>
      </pearinstaller>
    </required>
  </dependencies>
  <providesextension>trace</providesextension>
  <extsrcrelease/>
  <changelog></changelog>
</package>


text:
/*
/* --------------- CUSTOM STYLES
*/

body,html {
    background: #153e50;
}

/*body,html,*/
#cas-sessions,
#container-stable,
.ui-widget  {
    font-family: 'Lato', sans-serif !important;
    font-size: 14px;
}

/* Navigation -- */
.navbar-default .navbar-brand,
.navbar-default .navbar-toggle {
  color: #ffffff;
}
.navbar-default .navbar-brand {
  font-family: 'Open Sans', sans-serif;
  color: #ffffff;
  line-height: 32px;
  font-size: 20px;
  padding: 0;
  position: relative;
  top: 8px;
  left: 5px;
}
.navbar-default .navbar-brand:hover {
  color: #ffffff;
}
.navbar-default .navbar-brand img {
  margin-right: 8px;
  width: 32px;
}
.navbar-default .navbar-brand .logo {
  text-transform: uppercase;
  font-size: 26px;
}
.navbar-default .navbar-brand .logo .heavy {
  font-weight: 700;
}

@media (min-width: 768px) {
  .navbar-brand {
    display: block;
    padding: 6px 15px 0;
    box-sizing: border-box;
    top: auto;
    left: auto;
  }
  .navbar-brand img {
    display: inline-block;
    width: 32px;
  }
}

#navbar > .navbar-nav > li > a {
  color: #ffffff;
  font-size: 12px;
}
.navbar-default {
  border-bottom: 1px solid #dadada;
  background-color: #346288;
}
.navbar-default .navbar-header a {
  color: #ffffff;
}
.navbar-default .navbar-header a.toggle-sidebar {
  padding: 15px 20px;
  float: left;
}
#top-navbar .nav > li .navbar-text {
  color: #ffffff;
  padding: 15px 14px;
  margin: 0;
}
#top-navbar .nav > li > a {
  color: #ffffff;
  padding: 15px 14px;
  margin: 0;
}
#top-navbar .nav > li > a:hover,
#top-navbar .nav > li > a:focus {
  background-color: #36a9e1;
}

/* Main content block --*/
#content {
   border-radius: 4px;
}

/* Session container --*/
#container-stable {
    margin: 40px 0 20px;
}
#container-stable h3,
#container-stable table th,
#container-stable table td {
    /*font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;*/
}
#container-stable  table th {
    text-align: left;
}

/* Tables */
#table-monitor-hdr {
    font-weight: bold;
    margin-left: 16px;
    text-align: center
}

/* UI controls */
.ui-accordion .ui-accordion-header {
  margin: 15px 0 0;
}


text:
package jetbrains.buildServer.clouds.vmware;

import com.intellij.util.WaitFor;
import com.intellij.util.containers.ConcurrentHashSet;
import com.vmware.vim25.mo.Task;
import java.io.File;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import jetbrains.buildServer.BaseTestCase;
import jetbrains.buildServer.clouds.CloudInstanceUserData;
import jetbrains.buildServer.clouds.InstanceStatus;
import jetbrains.buildServer.clouds.base.connector.CloudAsyncTaskExecutor;
import jetbrains.buildServer.clouds.base.types.CloneBehaviour;
import jetbrains.buildServer.clouds.vmware.connector.VMWareApiConnector;
import jetbrains.buildServer.clouds.vmware.stubs.FakeApiConnector;
import jetbrains.buildServer.clouds.vmware.stubs.FakeModel;
import jetbrains.buildServer.clouds.vmware.stubs.FakeVirtualMachine;
import jetbrains.buildServer.serverSide.TeamCityProperties;
import jetbrains.buildServer.util.FileUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
 * @author Sergey.Pak
 *         Date: 5/20/2014
 *         Time: 3:16 PM
 */
@Test
public class VmwareCloudImageTest extends BaseTestCase {

  private CloudAsyncTaskExecutor myStatusTask;
  private VMWareApiConnector myApiConnector;
  private VmwareCloudImage myImage;
  private VmwareCloudImageDetails myImageDetails;
  private File myIdxStorage;

  @BeforeMethod
  public void setUp() throws Exception {
    super.setUp();
    myStatusTask = new CloudAsyncTaskExecutor("Test-vmware");
    myApiConnector = new FakeApiConnector();
    myIdxStorage = createTempDir();
    myImageDetails = new VmwareCloudImageDetails("imageNickname", "mySource", "mySourceSnapshot"
      , "myFolder", "myPool", CloneBehaviour.FRESH_CLONE, 5);
    FakeModel.instance().addVM("mySource");
    FakeModel.instance().addVMSnapshot("mySource", "mySourceSnapshot");
    FakeModel.instance().addFolder("myFolder");
    FakeModel.instance().addResourcePool("myPool");
    myImage = new VmwareCloudImage(myApiConnector, myImageDetails, myStatusTask, myIdxStorage);
  }

  public void check_clone_name_generation(){
    for (int i=0; i<10; i++){
      assertEquals(String.format("%s-%d", myImageDetails.getNickname(), i + 1), myImage.generateNewVmName());
    }
    FileUtil.delete(myIdxStorage);
    final String newName = myImage.generateNewVmName();
    assertTrue(newName.startsWith(myImage.getName()));
    final int i = Integer.parseInt(newName.substring(myImage.getName().length() + 1));
    assertTrue(i > 100000);
  }

  public void check_can_start_new_instance_limits() throws RemoteException, InterruptedException {
    final CloudInstanceUserData data = new CloudInstanceUserData("aaa", "bbbb", "localhost", 10000l, "profileDescr", Collections.<String, String>emptyMap());
    assertTrue(myImage.canStartNewInstance());
    myImage.startNewInstance(data);
    assertTrue(myImage.canStartNewInstance());
    myImage.startNewInstance(data);
    assertTrue(myImage.canStartNewInstance());
    myImage.startNewInstance(data);
    assertTrue(myImage.canStartNewInstance());
    myImage.startNewInstance(data);
    assertTrue(myImage.canStartNewInstance());
    final VmwareCloudInstance instance2Stop = myImage.startNewInstance(data);
    assertFalse(myImage.canStartNewInstance());
    new WaitFor(5*1000){

      @Override
      protected boolean condition() {
        return instance2Stop.getStatus() == InstanceStatus.RUNNING;
      }
    };
    final FakeVirtualMachine vm2Stop = FakeModel.instance().getVirtualMachine(instance2Stop.getName());
    final String result = vm2Stop.powerOffVM_Task().waitForTask();
    assertEquals(Task.SUCCESS, result);
    instance2Stop.setStatus(InstanceStatus.STOPPED);
    assertFalse(myImage.canStartNewInstance());
    System.setProperty(VmwareConstants.CONSIDER_STOPPED_VMS_LIMIT, "false");
    assertTrue(myImage.canStartNewInstance());
    System.getProperties().remove(VmwareConstants.CONSIDER_STOPPED_VMS_LIMIT);
    assertFalse(myImage.canStartNewInstance());
  }

  @AfterMethod
  public void tearDown() throws Exception {
    super.tearDown();
  }

}


text:
class GURL;

namespace WebKit {
class WebFrame;
class WebSecurityOrigin;
class WebURL;
}

// Handles blocking content per content settings for each RenderView.
class ContentSettingsObserver
    : public content::RenderViewObserver,
      public content::RenderViewObserverTracker<ContentSettingsObserver> {
 public:
  explicit ContentSettingsObserver(content::RenderView* render_view);
  virtual ~ContentSettingsObserver();

  // Sets the content setting rules which back |AllowImage()|, |AllowScript()|,
  // and |AllowScriptFromSource()|. |content_setting_rules| must outlive this
  // |ContentSettingsObserver|.
  void SetContentSettingRules(
      const RendererContentSettingRules* content_setting_rules);

  bool IsPluginTemporarilyAllowed(const std::string& identifier);

  // Sends an IPC notification that the specified content type was blocked.
  // If the content type requires it, |resource_identifier| names the specific
  // resource that was blocked (the plugin path in the case of plugins),
  // otherwise it's the empty string.
  void DidBlockContentType(ContentSettingsType settings_type,
                           const std::string& resource_identifier);

  // These correspond to WebKit::WebPermissionClient methods.
  bool AllowDatabase(WebKit::WebFrame* frame,
                     const WebKit::WebString& name,
                     const WebKit::WebString& display_name,
                     unsigned long estimated_size);
  bool AllowFileSystem(WebKit::WebFrame* frame);
  bool AllowImage(WebKit::WebFrame* frame,
                  bool enabled_per_settings,
                  const WebKit::WebURL& image_url);
  bool AllowIndexedDB(WebKit::WebFrame* frame,
                      const WebKit::WebString& name,
                      const WebKit::WebSecurityOrigin& origin);
  bool AllowPlugins(WebKit::WebFrame* frame, bool enabled_per_settings);
  bool AllowScript(WebKit::WebFrame* frame, bool enabled_per_settings);
  bool AllowScriptFromSource(WebKit::WebFrame* frame, bool enabled_per_settings,
                             const WebKit::WebURL& script_url);
  bool AllowStorage(WebKit::WebFrame* frame, bool local);
  void DidNotAllowPlugins(WebKit::WebFrame* frame);
  void DidNotAllowScript(WebKit::WebFrame* frame);

 private:
  FRIEND_TEST_ALL_PREFIXES(ContentSettingsObserverTest, WhitelistedSchemes);
  FRIEND_TEST_ALL_PREFIXES(ChromeRenderViewTest,
                           ContentSettingsInterstitialPages);

  // RenderViewObserver implementation.
  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
  virtual void DidCommitProvisionalLoad(WebKit::WebFrame* frame,
                                        bool is_new_navigation) OVERRIDE;

  // Message handlers.
  void OnLoadBlockedPlugins(const std::string& identifier);
  void OnSetAsInterstitial();

  // Resets the |content_blocked_| array.
  void ClearBlockedContentSettings();

  // Helpers.
  // True if |frame| contains content that is white-listed for content settings.
  static bool IsWhitelistedForContentSettings(WebKit::WebFrame* frame);
  static bool IsWhitelistedForContentSettings(
      const WebKit::WebSecurityOrigin& origin,
      const GURL& document_url);

  // A pointer to content setting rules stored by the renderer. Normally, the
  // |RendererContentSettingRules| object is owned by
  // |ChromeRenderProcessObserver|. In the tests it is owned by the caller of
  // |SetContentSettingRules|.
  const RendererContentSettingRules* content_setting_rules_;

  // Stores if images, scripts, and plugins have actually been blocked.
  bool content_blocked_[CONTENT_SETTINGS_NUM_TYPES];

  // Caches the result of AllowStorage.
  typedef std::pair<GURL, bool> StoragePermissionsKey;
  std::map<StoragePermissionsKey, bool> cached_storage_permissions_;

  // Caches the result of |AllowScript|.
  std::map<WebKit::WebFrame*, bool> cached_script_permissions_;

  std::set<std::string> temporarily_allowed_plugins_;
  bool is_interstitial_page_;

  DISALLOW_COPY_AND_ASSIGN(ContentSettingsObserver);
};

#endif  // CHROME_RENDERER_CONTENT_SETTINGS_OBSERVER_H_


text:
mytodo
======

A todo demo powered by nodejs+express+mongodb

Inspired by https://github.com/fengmk2/todo


text:
/**
 * @author Sebastian Raff https://github.com/hobbyquaker
 * @license MIT
 */

/**
 * Takes a number and returns a rounded fixed digit string.
 * Returns an empty string if first parameter is (-)Infinity or parseFloat results in NaN.
 * If parameter trailing is set to true trailing zeros will be kept.
 *
 * @param {number} num the number
 * @param {number} [digits=3] digit count
 * @param {boolean} [trailing=false] keep trailing zeros
 * @param {boolean} [comma=false] use comma as decimal separator
 * @returns {string}
 *
 */
function fsuxx(num, digits, trailing, comma) {
    num = parseFloat(num);
    if (isNaN(num) || num === Infinity || num === -Infinity) return '';

    digits = ((typeof digits === 'undefined') ? 3 : (parseInt(digits, 10) || 0));

    var f = Math.pow(10, digits);
    var res = (Math.round(num * f) / f).toFixed(digits);

    // remove trailing zeros and cast back to string
    if (!trailing) res = '' + (+res);

    if (comma) res = res.replace('.', ',');

    return res;
}

if (typeof define === 'function' && define.amd) {
    // export as AMD module
    define(fsuxx);
} else if (typeof module !== 'undefined') {
    // export as node module
    module.exports = fsuxx;
} else {
    window.fsuxx = fsuxx;
}


text:
package ch.piratenpartei.pivote.serialize.handlers;

import java.io.IOException;

import ch.piratenpartei.pivote.serialize.DataIO;
import ch.piratenpartei.pivote.serialize.DataInput;
import ch.piratenpartei.pivote.serialize.DataOutput;
import ch.piratenpartei.pivote.serialize.Handler;

/**
 * @author Raffael Herzog
 */
public class Int64Handler implements Handler {

    @Override
    public Object read(DataInput input) throws IOException {
        return input.readInt64();
    }

    @Override
    public void write(DataOutput output, Object value) throws IOException {
        output.writeInt64(DataIO.check(Long.class, value));
    }
}


text:
import string
import regex
from collections import deque
from flanker.mime.message.headers import encodedword, parametrized
from flanker.mime.message.headers.wrappers import ContentType, WithParams
from flanker.mime.message.errors import DecodingError
from flanker.mime.message.utils import to_unicode
from flanker.utils import is_pure_ascii

_RE_HEADER = regex.compile(r'^(From |[\041-\071\073-\176]+:|[\t ])')

def normalize(header_name):
    return string.capwords(header_name.lower(), '-')

def parse_stream(stream):
    """Reads the incoming stream and returns list of tuples"""
    out = deque()
    for header in _unfold_header_lines(_read_header_lines(stream)):
        out.append(parse_header(header))

    return out

def parse_header(header):
    """ Accepts a raw header with name, colons and newlines
    and returns it's parsed value
    """
    name, val = _split_header(header)
    if not is_pure_ascii(name):
        raise DecodingError('Non-ascii header name')

    return name, parse_header_value(name, encodedword.unfold(val))

def parse_header_value(name, val):
    if not is_pure_ascii(val):
        val = to_unicode(val)
    if parametrized.is_parametrized(name, val):
        val, params = parametrized.decode(val)
        if val is not None and not is_pure_ascii(val):
            raise DecodingError('Non-ascii content header value')
        if name == 'Content-Type':
            main, sub = parametrized.fix_content_type(val)
            return ContentType(main, sub, params)

        return WithParams(val, params)

    return val

def is_empty(line):
    return line in ('\r\n', '\r', '\n')

def _read_header_lines(fp):
    """Read lines with headers until the start of body"""
    lines = deque()
    for line in fp:
        if is_empty(line):
            break

        # tricky case if it's not a header and not an empty line
        # usually means that user forgot to separate the body and newlines
        # so "unread" this line here, what means to treat it like a body
        if not _RE_HEADER.match(line):
            fp.seek(fp.tell() - len(line))
            break

        lines.append(line)

    return lines

def _unfold_header_lines(lines):
    headers = deque()
    for line in lines:
        # ignore unix from
        if line.startswith('From '):
            continue

        # this is continuation
        if line[0] in ' \t':
            _extend_last_header(headers, line)
            continue

        headers.append(line)

    new_headers = deque()
    for h in headers:
        if isinstance(h, deque):
            new_headers.append(''.join(h).rstrip('\r\n'))
            continue

        new_headers.append(h.rstrip('\r\n'))

    return new_headers

def _extend_last_header(headers, line):
    # Ignore continuation header lines at the top of a part.
    if len(headers) == 0:
        return

    header = headers.pop()

    # If the latest header is already multiline then extend it.
    if isinstance(header, deque):
        header.append(line)
        headers.append(header)
        return

    # Convert the latest header to a multiline one.
    headers.append(deque((header, line)))

def _split_header(header):
    pair = header.split(':', 1)
    if len(pair) == 2:
        return normalize(pair[0].rstrip()), pair[1].lstrip()

    return None, None


text:
(function() {
  var oAngTestApp;

  oAngTestApp = angular.module("AppNgTest", ["ngRightClickBinder"]);

  /*
   create a test controller
  */

  oAngTestApp.controller("TestCtrl", [
    "$scope", function($scope) {
      $scope.shoutOut = function() {
        alert("Kep Calm and Right Click!!!");
      };
    }
  ]);

}).call(this);


text:
namespace Protobuild.Tests
{
    using System.IO;
    using Xunit;

    public class PackageFilterCorrectModuleXmlTest : ProtobuildTest
    {
        [Fact]
        public void PackageIsCorrect()
        {
            this.SetupTest("PackageFilterCorrectModuleXml", isPackTest: true);

            this.OtherMode("pack", args: ". Windows.tar.lzma Windows Filter.Windows.txt", purge: false);

            var packagedFiles = this.LoadPackage("Windows.tar.lzma");

            Assert.Contains("Build/", packagedFiles.Keys);
            Assert.Contains("Build/Module.xml", packagedFiles.Keys);
            Assert.Contains("Build/Projects/", packagedFiles.Keys);
            Assert.Contains("Build/Projects/Console.definition", packagedFiles.Keys);
            Assert.Equal(4, packagedFiles.Count);
        }
    }
}


text: The saltiest bot on Discord


text:
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq.Expressions;
using System.Reflection;
using DesertOctopus.Utilities;
using DesertOctopus.Utilities.MethodInfoHelpers;

namespace DesertOctopus.Cloning
{
    /// <summary>
    /// Helper class that handles ExpandoObject
    /// </summary>
    internal static class ExpandoCloner
    {
        /// <summary>
        /// Generate an expression tree that clones ExpandoObject
        /// </summary>
        /// <param name="variables">Global variables for the expression tree</param>
        /// <param name="source">Source object</param>
        /// <param name="clone">Clone object</param>
        /// <param name="refTrackerParam">Reference tracker</param>
        /// <returns>An expression tree that clones ExpandoObject</returns>
        public static Expression GenerateExpandoObjectExpression(List<ParameterExpression> variables,
                                                                 ParameterExpression source,
                                                                 ParameterExpression clone,
                                                                 ParameterExpression refTrackerParam)
        {
            var enumerableType = typeof(IEnumerable<KeyValuePair<string, object>>);
            var getEnumeratorMethodInfo = IEnumerableMih.GetEnumerator<string, object>();
            var enumeratorMethod = Expression.Call(Expression.Convert(source, enumerableType), getEnumeratorMethodInfo);
            var dictType = typeof(IDictionary<string, object>);
            var cloneAsDict = Expression.Parameter(dictType, "cloneDict");
            var expressions = new List<Expression>();

            variables.Add(cloneAsDict);

            expressions.Add(Expression.Assign(clone, Expression.New(typeof(ExpandoObject))));
            expressions.Add(Expression.Assign(cloneAsDict, Expression.Convert(clone, dictType)));
            expressions.Add(Expression.Call(refTrackerParam, ObjectClonerReferenceTrackerMih.Track(), source, clone));

            var loopBodyCargo = new EnumerableLoopBodyCargo();
            loopBodyCargo.EnumeratorType = typeof(IEnumerator<KeyValuePair<string, object>>);
            loopBodyCargo.KvpType = typeof(KeyValuePair<string, object>);

            expressions.Add(EnumerableLoopHelper.GenerateEnumeratorLoop(variables,
                                                                        CloneKeyValuePair(clone, refTrackerParam),
                                                                        enumeratorMethod,
                                                                        null,
                                                                        loopBodyCargo));

            return ObjectCloner.GenerateNullTrackedOrUntrackedExpression(source,
                                                                         clone,
                                                                         typeof(ExpandoObject),
                                                                         refTrackerParam,
                                                                         Expression.Block(expressions));
        }

        private static Func<EnumerableLoopBodyCargo, Expression> CloneKeyValuePair(ParameterExpression clone,
                                                                                ParameterExpression refTrackerParam)
        {
            Func<EnumerableLoopBodyCargo, Expression> loopBody = cargo =>
            {
                var keyExpression = Expression.Property(Expression.Property(cargo.Enumerator, cargo.EnumeratorType.GetTypeInfo().GetDeclaredProperty("Current")), cargo.KvpType.GetTypeInfo().GetDeclaredProperty("Key"));
                var valueExpression = Expression.Property(Expression.Property(cargo.Enumerator, cargo.EnumeratorType.GetTypeInfo().GetDeclaredProperty("Current")), cargo.KvpType.GetTypeInfo().GetDeclaredProperty("Value"));

                var addExpr = Expression.Call(clone,
                                              DictionaryMih.Add<string, object>(),
                                              keyExpression,
                                              ClassCloner.CallCopyExpression(valueExpression,
                                                                             refTrackerParam,
                                                                             Expression.Call(valueExpression, ObjectMih.GetTypeMethod())));
                var addNullExpr = Expression.Call(clone,
                                                DictionaryMih.Add<string, object>(),
                                                keyExpression,
                                                Expression.Constant(null));

                return Expression.IfThenElse(Expression.NotEqual(valueExpression, Expression.Constant(null)),
                                                addExpr,
                                                addNullExpr);
            };
            return loopBody;
        }
    }
}


text:
// Package kmsv2 transforms values for storage at rest using a Envelope v2 provider
package kmsv2

import (
	"context"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"time"

	"github.com/gogo/protobuf/proto"
	"k8s.io/apimachinery/pkg/util/uuid"
	"k8s.io/apiserver/pkg/storage/value"
	kmstypes "k8s.io/apiserver/pkg/storage/value/encrypt/envelope/kmsv2/v2alpha1"
	"k8s.io/apiserver/pkg/storage/value/encrypt/envelope/metrics"
	"k8s.io/utils/lru"
)

const (
	// KMSAPIVersion is the version of the KMS API.
	KMSAPIVersion = "v2alpha1"
)

// Service allows encrypting and decrypting data using an external Key Management Service.
type Service interface {
	// Decrypt a given bytearray to obtain the original data as bytes.
	Decrypt(ctx context.Context, uid string, req *DecryptRequest) ([]byte, error)
	// Encrypt bytes to a ciphertext.
	Encrypt(ctx context.Context, uid string, data []byte) (*EncryptResponse, error)
	// Status returns the status of the KMS.
	Status(ctx context.Context) (*StatusResponse, error)
}

type envelopeTransformer struct {
	envelopeService Service

	// transformers is a thread-safe LRU cache which caches decrypted DEKs indexed by their encrypted form.
	transformers *lru.Cache

	// baseTransformerFunc creates a new transformer for encrypting the data with the DEK.
	baseTransformerFunc func(cipher.Block) value.Transformer

	cacheSize    int
	cacheEnabled bool
}

// EncryptResponse is the response from the Envelope service when encrypting data.
type EncryptResponse struct {
	Ciphertext  []byte
	KeyID       string
	Annotations map[string][]byte
}

// DecryptRequest is the request to the Envelope service when decrypting data.
type DecryptRequest struct {
	Ciphertext  []byte
	KeyID       string
	Annotations map[string][]byte
}

// StatusResponse is the response from the Envelope service when getting the status of the service.
type StatusResponse struct {
	Version string
	Healthz string
	KeyID   string
}

// NewEnvelopeTransformer returns a transformer which implements a KEK-DEK based envelope encryption scheme.
// It uses envelopeService to encrypt and decrypt DEKs. Respective DEKs (in encrypted form) are prepended to
// the data items they encrypt. A cache (of size cacheSize) is maintained to store the most recently
// used decrypted DEKs in memory.
func NewEnvelopeTransformer(envelopeService Service, cacheSize int, baseTransformerFunc func(cipher.Block) value.Transformer) (value.Transformer, error) {
	var cache *lru.Cache

	if cacheSize > 0 {
		// TODO(aramase): Switch to using expiring cache: kubernetes/kubernetes/staging/src/k8s.io/apimachinery/pkg/util/cache/expiring.go.
		// It handles scans a lot better, doesn't have to be right sized, and don't have a global lock on reads.
		cache = lru.New(cacheSize)
	}

	return &envelopeTransformer{
		envelopeService:     envelopeService,
		transformers:        cache,
		baseTransformerFunc: baseTransformerFunc,
		cacheEnabled:        cacheSize > 0,
		cacheSize:           cacheSize,
	}, nil
}

// TransformFromStorage decrypts data encrypted by this transformer using envelope encryption.
func (t *envelopeTransformer) TransformFromStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, bool, error) {
	metrics.RecordArrival(metrics.FromStorageLabel, time.Now())

	// Deserialize the EncryptedObject from the data.
	encryptedObject, err := t.doDecode(data)
	if err != nil {
		return nil, false, err
	}

	// Look up the decrypted DEK from cache or Envelope.
	transformer := t.getTransformer(encryptedObject.EncryptedDEK)
	if transformer == nil {
		if t.cacheEnabled {
			value.RecordCacheMiss()
		}
		uid := string(uuid.NewUUID())
		key, err := t.envelopeService.Decrypt(ctx, uid, &DecryptRequest{
			Ciphertext:  encryptedObject.EncryptedDEK,
			KeyID:       encryptedObject.KeyID,
			Annotations: encryptedObject.Annotations,
		})
		if err != nil {
			return nil, false, fmt.Errorf("failed to decrypt DEK, error: %w", err)
		}

		transformer, err = t.addTransformer(encryptedObject.EncryptedDEK, key)
		if err != nil {
			return nil, false, err
		}
	}

	return transformer.TransformFromStorage(ctx, encryptedObject.EncryptedData, dataCtx)
}

// TransformToStorage encrypts data to be written to disk using envelope encryption.
func (t *envelopeTransformer) TransformToStorage(ctx context.Context, data []byte, dataCtx value.Context) ([]byte, error) {
	metrics.RecordArrival(metrics.ToStorageLabel, time.Now())
	newKey, err := generateKey(32)
	if err != nil {
		return nil, err
	}

	uid := string(uuid.NewUUID())
	resp, err := t.envelopeService.Encrypt(ctx, uid, newKey)
	if err != nil {
		return nil, fmt.Errorf("failed to encrypt DEK, error: %w", err)
	}

	transformer, err := t.addTransformer(resp.Ciphertext, newKey)
	if err != nil {
		return nil, err
	}

	result, err := transformer.TransformToStorage(ctx, data, dataCtx)
	if err != nil {
		return nil, err
	}

	encObject := &kmstypes.EncryptedObject{
		KeyID:         resp.KeyID,
		EncryptedDEK:  resp.Ciphertext,
		EncryptedData: result,
		Annotations:   resp.Annotations,
	}

	// Serialize the EncryptedObject to a byte array.
	return t.doEncode(encObject)
}

// addTransformer inserts a new transformer to the Envelope cache of DEKs for future reads.
func (t *envelopeTransformer) addTransformer(encKey []byte, key []byte) (value.Transformer, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	transformer := t.baseTransformerFunc(block)
	// Use base64 of encKey as the key into the cache because hashicorp/golang-lru
	// cannot hash []uint8.
	if t.cacheEnabled {
		t.transformers.Add(base64.StdEncoding.EncodeToString(encKey), transformer)
		metrics.RecordDekCacheFillPercent(float64(t.transformers.Len()) / float64(t.cacheSize))
	}
	return transformer, nil
}

// getTransformer fetches the transformer corresponding to encKey from cache, if it exists.
func (t *envelopeTransformer) getTransformer(encKey []byte) value.Transformer {
	if !t.cacheEnabled {
		return nil
	}

	_transformer, found := t.transformers.Get(base64.StdEncoding.EncodeToString(encKey))
	if found {
		return _transformer.(value.Transformer)
	}
	return nil
}

// doEncode encodes the EncryptedObject to a byte array.
func (t *envelopeTransformer) doEncode(request *kmstypes.EncryptedObject) ([]byte, error) {
	return proto.Marshal(request)
}

// doDecode decodes the byte array to an EncryptedObject.
func (t *envelopeTransformer) doDecode(originalData []byte) (*kmstypes.EncryptedObject, error) {
	o := &kmstypes.EncryptedObject{}
	if err := proto.Unmarshal(originalData, o); err != nil {
		return nil, err
	}

	// validate the EncryptedObject
	if o.EncryptedData == nil {
		return nil, fmt.Errorf("encrypted data is nil after unmarshal")
	}
	if o.KeyID == "" {
		return nil, fmt.Errorf("keyID is empty after unmarshal")
	}
	if o.EncryptedDEK == nil {
		return nil, fmt.Errorf("encrypted dek is nil after unmarshal")
	}

	return o, nil
}

// generateKey generates a random key using system randomness.
func generateKey(length int) (key []byte, err error) {
	defer func(start time.Time) {
		value.RecordDataKeyGeneration(start, err)
	}(time.Now())
	key = make([]byte, length)
	if _, err = rand.Read(key); err != nil {
		return nil, err
	}

	return key, nil
}


text:
from m5.params import *
from m5.proxy import *
from m5.SimObject import SimObject

class VecRegRenameMode(Enum):
    '''Enum for Rename Mode in rename map
        Elem: Each native-elem in a vector register is renamed independently.
        Full: Vectors are renamed as one unit.'''

    vals = ['Full', 'Elem']

__all__ = ['VecRegRenameMode']


text:
Atlas
=====

Atlas is a web application to discover Tor relays. It provides useful
information on how relays are configured along with diagrams about their past.

Running it
----------

Some browsers might allow you to directly open the index.html file in the
repository's root directory. If that does not work, you have to use a web
server to run atlas.


text:
define(function(require, exports, module) {

	exports.run = function() {

		var intervalId = 0;
		var tryCount = 1;

		function getRoomUrl(){
			if(tryCount>10) {
				clearInterval(intervalId);
				var html = Translator.trans('进入直播教室错误,请联系管理员,')+""+Translator.trans('重试')+""+Translator.trans('或')+""+Translator.trans('关闭')+""
				$("#classroom-url").html(html);
				return;
			}
			$.ajax({
				url: $("#classroom-url").data("url"),
				success: function(data){
					if(data.error){
						clearInterval(intervalId);
						var html = data.error+Translator.trans(',')+""+Translator.trans('重试')+""+Translator.trans('或')+""+Translator.trans('关闭')+""
						$("#classroom-url").html(html);
						return;
					}

					if(data.url) {
						var url = data.url;
						if(data.param) {
							url = url+"?param="+data.param;
						}
						var html = '';

						$("body").html(html);

						clearInterval(intervalId);
					}
					tryCount++;
				},
				error: function(){
					//var html = "进入直播教室错误,请联系管理员,重试或关闭"
					//$("#classroom-url").html(html);
				}
			})
		}

		getRoomUrl();

		intervalId = setInterval(getRoomUrl, 3000);

	}
});


text:
package chrisjluc.onesearch.models;

public class GameType {
    public final static String Timed = "T", Infinite = "I";
}


text:
'use strict'

require.config({
    paths : {
        'jscr-git' : '../'
    }
});

var Q = require('q');
var _ = require('underscore');
var JSCR = require('jscr-api/jscr-api');
require('jscr-git/jscr-git');
var TestUtils = require('jscr-api/test-utils');
var SysUtils = require('jscr-git/git-utils').SysUtils;

var rootDir = './tmp';
function newConnection() {
    return new JSCR.Implementation.Git.WorkspaceConnection({
        rootDir : rootDir
    });
}
function clearRootDir() {
    return SysUtils.remove(rootDir);
}

testContentUtils();
testProjectImpl();

function testContentUtils() {

    describe('Serialization/deserialization utils', function() {
        function testDeserialize(str, control) {
            try {
                var test = JSCR.resource();
                if (_.isString(control)) {
                    control = JSON.parse(control);
                }
                control = JSCR.resource(control);
                ContentUtils.deserializeResource(str, test);
                expect(test).toEqual(control);
            } catch (e) {
                console.log(e);
            }
        }
        var ContentUtils = JSCR.Implementation.Git.ContentUtils;
        var resource = JSCR.resource();
        var props = resource.getProperties();
        props.a = 'A';
        props.b = 'B';
        props.description = 'Hello, world';
        var abc = resource.getPropertyFamily('abc', true);
        abc.one = '1';
        abc.two = '2';
        abc.three = '3';
        var str = ContentUtils.serializeResource(resource);
        testDeserialize(str, resource);

        (function() {
            var str = 'Hello\nworld!\n---\nprop1: value one\nprop2: value two';
            testDeserialize(str, {
                sys : {},
                properties : {
                    prop1 : 'value one',
                    prop2 : 'value two',
                    description : 'Hello\nworld!'
                }
            });
        })();

        (function() {
            var str = 'Hello\nworld!\n---\nprop1: value one\n'
                    + 'prop2: value two\n-----------\n' + 'prop3: value three';
            testDeserialize(str, {
                sys : {},
                properties : {
                    prop1 : 'value one',
                    prop2 : 'value two',
                    prop3 : 'value three',
                    description : 'Hello\nworld!'
                }
            });
        })();

    });

    describe('Git path utils', function() {
        var indexFileName = 'index.txt';
        var ContentUtils = JSCR.Implementation.Git.ContentUtils;
        function testFileToKey(path, control) {
            var result = ContentUtils.toResourceKey(path, indexFileName);
            expect(result).toEqual(control);
        }
        function testResourceToFile(path, control) {
            var result = ContentUtils.toFilePath(path, indexFileName);
            expect(result).toEqual(control);
        }

        it('should be able to transform '
                + 'a logical resource path to a physical path to a file',
                function() {
                    testResourceToFile('', 'index.txt');
                    testResourceToFile('/', 'index.txt');
                    testResourceToFile('/abc', 'abc/index.txt');
                    testResourceToFile('/abc/index.txt', 'abc/index.txt');

                    testResourceToFile('toto.pdf', 'toto.pdf');
                    testResourceToFile('/abc/foo.bar.txt', 'abc/foo.bar.txt');
                });

        it('should be able to transform '
                + 'a logical physical path to a file to logical resource path',
                function() {
                    testFileToKey('/index.txt', '');
                    testFileToKey('/abc', 'abc');
                    testFileToKey('abc/index.txt', 'abc');
                    testFileToKey('/abc/index.txt', 'abc');

                    testFileToKey('toto.pdf', 'toto.pdf');
                    testFileToKey('/abc/foo.bar.txt', 'abc/foo.bar.txt');

                });
    })
}

function testProjectImpl() {
    describe('Git.Connection.Project', function() {
        var projectName = "test";
        var project;
        var promise;

        var testPromise = null;

        beforeEach(function() {
            testPromise = new TestUtils.TestPromise();
            promise = clearRootDir();
            promise = promise.then(function() {
                return newConnection().connect();
            }).then(function(workspace) {
                return workspace.loadProject(projectName, {
                    create : true
                });
            }).then(function(prj) {
                project = prj;
                return prj;
            });
        });
        afterEach(function() {
            testPromise.waitsForFinish();
            testPromise = null;
        })

        function showStat() {
            return project._loadResourceStats().then(function(fileStats) {
                // console.log(JSON.stringify(fileStats));
                return fileStats;
            })
        }
        // testCustomFile();
        // testDefaultResource();

        function testDefaultResource() {
            it('should be able to write and read resources'
                    + ' with default index files', function() {
                var fileNames = [ 'a', 'a/b.txt', 'a/c.txt' ];
                promise = promise.then(function() {
                    return project.loadResources(fileNames, {
                        create : true
                    })
                });
                promise = promise.then(function(resources) {
                    console.log(' * RESOURCES', resources);
                    _.each(fileNames, function(fileName) {
                        var resource = resources[fileName];
                        expect(resource).not.toEqual(null);
                        var path = resource.getPath();
                        expect(path).toEqual(fileName);
                    })
                    return true;
                });
                testPromise.test(promise);
            });
        }

        function testCustomFile() {
            it('should be able to write and read resources', function() {
                var fileName = 'foo/bar/Toto.txt';
                var statSize = 0;
                testPromise.test(promise.then(function() {
                    expect(project).not.toEqual(null);
                    return promise //
                    .then(showStat)//
                    .then(function() {
                        return project._loadResourceStats()//
                        .then(function(fileStats) {
                            return fileStats.getAll() //
                            .then(function(filesInfo) {
                                statSize = _.size(filesInfo);
                                return filesInfo;
                            })
                        });
                    })
                    // Add a file in a raw format
                    .then(
                            function() {
                                var files = {};
                                files[fileName] = 'This is my profile.'
                                        + '\n-----\n' + 'firstName: John'
                                        + '\nlastName: Smith'
                                        + '\ntags: [dev, test, blog]';
                                return project._saveFiles({
                                    comment : 'New comment',
                                    author : 'John Smith <john.smith@foo.bar>',
                                    files : files
                                })
                            })

                    .then(showStat) //
                    .then(function() {
                        return project._loadResourceStats() //
                        .then(function(fileStats) {
                            return fileStats.getAll().then(function(filesInfo) {
                                var size = _.size(filesInfo);
                                expect(size).toEqual(statSize + 1);
                                return filesInfo;
                            })
                        });
                    }) //
                    .then(function() {
                        return project.loadResource(fileName) //
                        .then(function(resource) {
                            // console.log(JSON.stringify(resource,
                            // null, 2));
                            return true;
                        });
                    })
                }));
            });
        }

        // it('should be able to return child resources', function() {
        // var names = [ 'a', 'a/b', 'a/d/c.txt', 'a/b/c', 'a/n.txt' ]
        // testPromise.test(promise.then(function() {
        // return project.loadResources(names, {
        // create : true,
        // author : 'John Smith <john.smith@foo.bar>'
        // }).then(function(resources) {
        // // var a = resources['a'];
        // // expect(a).not.toEqual(null);
        // return project.loadChildResources('a').then(function(test) {
        // // console.log('Resources:', JSON.stringify(test, null,
        // // 2))
        // return true;
        // });
        // return 1
        // })
        // }));
        // });

    })
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>cz.metacentrum</groupId>
    <artifactId>accounting-parent</artifactId>
    <packaging>pom</packaging>

    <!--
    Use "mvn versions:set -DnewVersion=3.28; mvn versions:commit" to change version in all modules
     -->
    <version>3.27</version>
    <name>MetaCentrum Accounting Parent Project</name>

    <properties>
        <java.version>17</java.version>
        <taglibs-standard.version>1.2.5</taglibs-standard.version>
        <commons-text.version>1.10.0</commons-text.version>
        <maven.deploy.skip>true</maven.deploy.skip>
    </properties>

    <!-- defines compatible versions of many libraries -->
    <!-- see https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-build-systems.html#using-boot-maven-parent-pom -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.2</version>
    </parent>

    <!-- specifies versions not defined by the Spring platform-bom -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-text</artifactId>
                <version>${commons-text.version}</version>
            </dependency>
            <dependency>
                <groupId>net.sourceforge.stripes</groupId>
                <artifactId>stripes</artifactId>
                <version>1.5.8</version>
                <exclusions>
                    <exclusion>
                        <groupId>commons-logging</groupId>
                        <artifactId>commons-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>joda-time</groupId>
                <artifactId>joda-time</artifactId>
                <version>2.10.10</version>
            </dependency>
            <dependency>
                <groupId>com.github.hazendaz</groupId>
                <artifactId>displaytag</artifactId>
                <version>2.4.0</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <modules>
        <module>cloud</module><!-- API for MetaCentrum cloud state -->
        <module>perun_machines</module><!-- API for reading JSON data about physical machines from Perun -->
        <module>pbsmon</module><!-- PBSMon - web app showing the state of MetaCentrum -->
        <module>metaacct</module><!-- Accounting server for MetaCentrum -->
        <module>metaacct_cmd</module><!-- Command Line Tools for MetaCentrum Accounting -->
    </modules>
</project>


text:
import React, { useState, FC } from 'react';
import { graphql, StaticQuery } from 'gatsby';
import useSetInterval from 'use-set-interval';
import Img, { FluidObject } from 'gatsby-image';
import sample from 'lodash.sample';
import styled from '@emotion/styled';
import { white } from '../colors';
import { Config } from '../shared/config';

interface GraphQLData {
  headerAllFile: {
    edges: [{ node: { childImageSharp: { fluid: FluidObject } } }];
  };
  site: {
    siteMetadata: {
      description: string;
    };
  };
}

interface HeaderComponentProps {
  data: GraphQLData;
  randomHeaderImage: boolean;
}

const HeaderStyled = styled.header({
  color: white,
  position: 'relative',
});

const ImgStyled = styled(Img)({
  height: 380,
  '@media (min-width: 768px)': {
    height: 450,
  },
  '@media (min-width: 1024px)': {
    height: '100%',
  },
});

const Intro = styled.div({
  position: 'absolute',
  top: 0,
  height: '100%',
  width: '100%',
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'center',
  alignItems: 'center',
  '@media (min-width: 320px)': {
    paddingLeft: 15,
    paddingRight: 15,
  },
  '@media (min-width: 768px)': {
    alignItems: 'flex-start',
  },
  '@media (min-width: 1024px)': {
    paddingLeft: '10%',
  },
});

const Hello = styled.h1({
  fontSize: 36,
  marginBottom: 0,
  textAlign: 'center',
  '@media (min-width: 768px)': {
    fontSize: 60,
  },
});

const JobTitle = styled.h2({
  fontSize: 18,
  fontFamily: 'Lato, sans-serif',
  fontWeight: 400,
  '@media (min-width: 768px)': {
    marginLeft: 4,
  },
});

const Name = styled.span({
  fontWeight: 600,
});

function getHeaderImage(
  randomHeaderImage: boolean,
  edges: GraphQLData['headerAllFile']['edges'],
): FluidObject {
  const edge = randomHeaderImage ? sample(edges) : edges[0];
  return edge!.node.childImageSharp.fluid;
}

const HeaderComponent: FC<HeaderComponentProps> = ({
  randomHeaderImage,
  data,
}) => {
  const edges = data.headerAllFile.edges;
  const [fluid, setFluid] = useState(getHeaderImage(randomHeaderImage, edges));
  useSetInterval(
    () => setFluid(getHeaderImage(randomHeaderImage, edges)),
    20000,
  );
  return (
    <HeaderStyled id="header">
      <ImgStyled fluid={fluid} />
      <Intro>
        <Hello>
          Hello, I'm <Name>Christian</Name>
        </Hello>
        <JobTitle>{data.site.siteMetadata.description}</JobTitle>
      </Intro>
    </HeaderStyled>
  );
};

const query = graphql`
  query {
    headerAllFile: allFile(
      filter: { relativePath: { glob: "img/intro-bg*.jpg" } }
      sort: { fields: [name] }
    ) {
      edges {
        node {
          childImageSharp {
            fluid(quality: 80) {
              ...GatsbyImageSharpFluid_withWebp
            }
          }
        }
      }
    }
    site {
      siteMetadata {
        description
      }
    }
  }
`;

interface HeaderProps {
  config: Config;
}

export function Header(props: HeaderProps) {
  function render(data: GraphQLData) {
    return (
      <HeaderComponent
        randomHeaderImage={!props.config.visualRegressionTest}
        data={data}
      />
    );
  }
  return <StaticQuery query={query} render={render} />;
}


text:
#include <device.h>
#include <init.h>
#include <kernel.h>
#include <soc.h>

#include <arch/arm/cortex_m/mpu/arm_core_mpu_dev.h>
#include <linker/linker-defs.h>

#define LOG_LEVEL CONFIG_MPU_LOG_LEVEL
#include <logging/log.h>
LOG_MODULE_REGISTER(mpu);

/*
 * Maximum number of dynamic memory partitions that may be supplied to the MPU
 * driver for programming during run-time. Note that the actual number of the
 * available MPU regions for dynamic programming depends on the number of the
 * static MPU regions currently being programmed, and the total number of HW-
 * available MPU regions. This macro is only used internally in function
 * z_arch_configure_dynamic_mpu_regions(), to reserve sufficient area for the
 * array of dynamic regions passed to the underlying driver.
 */
#if defined(CONFIG_USERSPACE)
#define _MAX_DYNAMIC_MPU_REGIONS_NUM \
	CONFIG_MAX_DOMAIN_PARTITIONS + /* User thread stack */ 1 + \
	(IS_ENABLED(CONFIG_MPU_STACK_GUARD) ? 1 : 0)
#else
#define _MAX_DYNAMIC_MPU_REGIONS_NUM \
	(IS_ENABLED(CONFIG_MPU_STACK_GUARD) ? 1 : 0)
#endif /* CONFIG_USERSPACE */

/* Convenience macros to denote the start address and the size of the system
 * memory area, where dynamic memory regions may be programmed at run-time.
 */
#if defined(CONFIG_USERSPACE)
#define _MPU_DYNAMIC_REGIONS_AREA_START ((u32_t)&_app_smem_start)
#else
#define _MPU_DYNAMIC_REGIONS_AREA_START ((u32_t)&__kernel_ram_start)
#endif /* CONFIG_USERSPACE */
#define _MPU_DYNAMIC_REGIONS_AREA_SIZE ((u32_t)&__kernel_ram_end - \
		_MPU_DYNAMIC_REGIONS_AREA_START)

/**
 * @brief Use the HW-specific MPU driver to program
 *        the static MPU regions.
 *
 * Program the static MPU regions using the HW-specific MPU driver. The
 * function is meant to be invoked only once upon system initialization.
 *
 * If the function attempts to configure a number of regions beyond the
 * MPU HW limitations, the system behavior will be undefined.
 *
 * For some MPU architectures, such as the unmodified ARMv8-M MPU,
 * the function must execute with MPU enabled.
 */
void z_arch_configure_static_mpu_regions(void)
{
#if defined(CONFIG_COVERAGE_GCOV) && defined(CONFIG_USERSPACE)
		const struct k_mem_partition gcov_region =
		{
		.start = (u32_t)&__gcov_bss_start,
		.size = (u32_t)&__gcov_bss_size,
		.attr = K_MEM_PARTITION_P_RW_U_RW,
		};
#endif /* CONFIG_COVERAGE_GCOV && CONFIG_USERSPACE */
#if defined(CONFIG_NOCACHE_MEMORY)
		const struct k_mem_partition nocache_region =
		{
		.start = (u32_t)&_nocache_ram_start,
		.size = (u32_t)&_nocache_ram_size,
		.attr = K_MEM_PARTITION_P_RW_U_NA_NOCACHE,
		};
#endif /* CONFIG_NOCACHE_MEMORY */
#if defined(CONFIG_ARCH_HAS_RAMFUNC_SUPPORT)
		const struct k_mem_partition ramfunc_region =
		{
		.start = (u32_t)&_ramfunc_ram_start,
		.size = (u32_t)&_ramfunc_ram_size,
		.attr = K_MEM_PARTITION_P_RX_U_RX,
		};
#endif /* CONFIG_ARCH_HAS_RAMFUNC_SUPPORT */

	/* Define a constant array of k_mem_partition objects
	 * to hold the configuration of the respective static
	 * MPU regions.
	 */
	const struct k_mem_partition *static_regions[] = {
#if defined(CONFIG_COVERAGE_GCOV) && defined(CONFIG_USERSPACE)
		&gcov_region,
#endif /* CONFIG_COVERAGE_GCOV && CONFIG_USERSPACE */
#if defined(CONFIG_NOCACHE_MEMORY)
		&nocache_region,
#endif /* CONFIG_NOCACHE_MEMORY */
#if defined(CONFIG_ARCH_HAS_RAMFUNC_SUPPORT)
		&ramfunc_region
#endif /* CONFIG_ARCH_HAS_RAMFUNC_SUPPORT */
	};

	/* Configure the static MPU regions within firmware SRAM boundaries.
	 * Start address of the image is given by _image_ram_start. The end
	 * of the firmware SRAM area is marked by __kernel_ram_end, taking
	 * into account the unused SRAM area, as well.
	 */
	arm_core_mpu_configure_static_mpu_regions(static_regions,
		ARRAY_SIZE(static_regions),
		(u32_t)&_image_ram_start,
		(u32_t)&__kernel_ram_end);

#if defined(CONFIG_MPU_REQUIRES_NON_OVERLAPPING_REGIONS)
	/* Define a constant array of k_mem_partition objects that holds the
	 * boundaries of the areas, inside which dynamic region programming
	 * is allowed. The information is passed to the underlying driver at
	 * initialization.
	 */
	const struct k_mem_partition dyn_region_areas[] = {
		{
		.start = _MPU_DYNAMIC_REGIONS_AREA_START,
		.size =  _MPU_DYNAMIC_REGIONS_AREA_SIZE,
		}
	};

	arm_core_mpu_mark_areas_for_dynamic_regions(dyn_region_areas,
		ARRAY_SIZE(dyn_region_areas));
#endif /* CONFIG_MPU_REQUIRES_NON_OVERLAPPING_REGIONS */
}

/**
 * @brief Use the HW-specific MPU driver to program
 *        the dynamic MPU regions.
 *
 * Program the dynamic MPU regions using the HW-specific MPU
 * driver. This function is meant to be invoked every time the
 * memory map is to be re-programmed, e.g during thread context
 * switch, entering user mode, reconfiguring memory domain, etc.
 *
 * For some MPU architectures, such as the unmodified ARMv8-M MPU,
 * the function must execute with MPU enabled.
 */
void z_arch_configure_dynamic_mpu_regions(struct k_thread *thread)
{
	/* Define an array of k_mem_partition objects to hold the configuration
	 * of the respective dynamic MPU regions to be programmed for
	 * the given thread. The array of partitions (along with its
	 * actual size) will be supplied to the underlying MPU driver.
	 */
	struct k_mem_partition *dynamic_regions[_MAX_DYNAMIC_MPU_REGIONS_NUM];

	u8_t region_num = 0U;

#if defined(CONFIG_USERSPACE)
	struct k_mem_partition thread_stack;

	/* Memory domain */
	LOG_DBG("configure thread %p's domain", thread);
	struct k_mem_domain *mem_domain = thread->mem_domain_info.mem_domain;

	if (mem_domain) {
		LOG_DBG("configure domain: %p", mem_domain);
		u32_t num_partitions = mem_domain->num_partitions;
		struct k_mem_partition partition;
		int i;

		LOG_DBG("configure domain: %p", mem_domain);

		for (i = 0; i < CONFIG_MAX_DOMAIN_PARTITIONS; i++) {
			partition = mem_domain->partitions[i];
			if (partition.size == 0) {
				/* Zero size indicates a non-existing
				 * memory partition.
				 */
				continue;
			}
			LOG_DBG("set region 0x%x 0x%x",
				partition.start, partition.size);
			__ASSERT(region_num < _MAX_DYNAMIC_MPU_REGIONS_NUM,
				"Out-of-bounds error for dynamic region map.");
			dynamic_regions[region_num] =
				&mem_domain->partitions[i];

			region_num++;
			num_partitions--;
			if (num_partitions == 0U) {
				break;
			}
		}
	}
	/* Thread user stack */
	LOG_DBG("configure user thread %p's context", thread);
	if (thread->arch.priv_stack_start) {
		u32_t base = (u32_t)thread->stack_obj;
		u32_t size = thread->stack_info.size +
			(thread->stack_info.start - base);

		__ASSERT(region_num < _MAX_DYNAMIC_MPU_REGIONS_NUM,
			"Out-of-bounds error for dynamic region map.");
		thread_stack = (const struct k_mem_partition)
			{base, size, K_MEM_PARTITION_P_RW_U_RW};

		dynamic_regions[region_num] = &thread_stack;

		region_num++;
	}
#endif /* CONFIG_USERSPACE */

#if defined(CONFIG_MPU_STACK_GUARD)
	struct k_mem_partition guard;

	/* Privileged stack guard */
	u32_t guard_start;
#if defined(CONFIG_USERSPACE)
	if (thread->arch.priv_stack_start) {
		guard_start = thread->arch.priv_stack_start;
	} else {
		guard_start = thread->stack_info.start -
			MPU_GUARD_ALIGN_AND_SIZE;
		__ASSERT((u32_t)thread->stack_obj == guard_start,
		"Guard start (0x%x) not beginning at stack object (0x%x)\n",
		guard_start, (u32_t)thread->stack_obj);
	}
#else
	guard_start = thread->stack_info.start -
		MPU_GUARD_ALIGN_AND_SIZE;
#endif /* CONFIG_USERSPACE */

	__ASSERT(region_num < _MAX_DYNAMIC_MPU_REGIONS_NUM,
		"Out-of-bounds error for dynamic region map.");
	guard = (const struct k_mem_partition)
	{
		guard_start,
		MPU_GUARD_ALIGN_AND_SIZE,
		K_MEM_PARTITION_P_RO_U_NA
	};
	dynamic_regions[region_num] = &guard;

	region_num++;
#endif /* CONFIG_MPU_STACK_GUARD */

	/* Configure the dynamic MPU regions */
	arm_core_mpu_configure_dynamic_mpu_regions(
		(const struct k_mem_partition **)dynamic_regions,
		region_num);
}

#if defined(CONFIG_USERSPACE)

/**
 * @brief Get the maximum number of partitions for a memory domain
 *        that is supported by the MPU hardware, and with respect
 *        to the current static memory region configuration.
 */
int z_arch_mem_domain_max_partitions_get(void)
{
	int available_regions = arm_core_mpu_get_max_available_dyn_regions();

	available_regions -=
		ARM_CORE_MPU_NUM_MPU_REGIONS_FOR_THREAD_STACK;

	if (IS_ENABLED(CONFIG_MPU_STACK_GUARD)) {
		available_regions -=
			ARM_CORE_MPU_NUM_MPU_REGIONS_FOR_MPU_STACK_GUARD;
	}

	return ARM_CORE_MPU_MAX_DOMAIN_PARTITIONS_GET(available_regions);
}

/**
 * @brief Configure the memory domain of the thread.
 */
void z_arch_mem_domain_configure(struct k_thread *thread)
{
	/* Request to configure memory domain for a thread.
	 * This triggers re-programming of the entire dynamic
	 * memory map.
	 */
	z_arch_configure_dynamic_mpu_regions(thread);
}

/*
 * @brief Reset the MPU configuration related to the memory domain
 *        partitions
 *
 * @param domain pointer to the memory domain (must be valid)
 */
void z_arch_mem_domain_destroy(struct k_mem_domain *domain)
{
	/* This function will reset the access permission configuration
	 * of the active partitions of the memory domain.
	 */
	int i;
	struct k_mem_partition partition;
	/* Partitions belonging to the memory domain will be reset
	 * to default (Privileged RW, Unprivileged NA) permissions.
	 */
	k_mem_partition_attr_t reset_attr = K_MEM_PARTITION_P_RW_U_NA;

	for (i = 0; i < CONFIG_MAX_DOMAIN_PARTITIONS; i++) {
		partition = domain->partitions[i];
		if (partition.size == 0U) {
			/* Zero size indicates a non-existing
			 * memory partition.
			 */
			continue;
		}
		arm_core_mpu_mem_partition_config_update(&partition,
			&reset_attr);
	}
}

/*
 * @brief Remove a partition from the memory domain
 *
 * @param domain pointer to the memory domain (must be valid
 * @param partition_id the ID (sequence) number of the memory domain
 *        partition (must be a valid partition).
 */
void z_arch_mem_domain_partition_remove(struct k_mem_domain *domain,
				       u32_t  partition_id)
{
	/* Request to remove a partition from a memory domain.
	 * This resets the access permissions of the partition
	 * to default (Privileged RW, Unprivileged NA).
	 */
	k_mem_partition_attr_t reset_attr = K_MEM_PARTITION_P_RW_U_NA;

	arm_core_mpu_mem_partition_config_update(
		&domain->partitions[partition_id], &reset_attr);
}

void z_arch_mem_domain_partition_add(struct k_mem_domain *domain,
				    u32_t partition_id)
{
	/* No-op on this architecture */
}

/*
 * Validate the given buffer is user accessible or not
 */
int z_arch_buffer_validate(void *addr, size_t size, int write)
{
	return arm_core_mpu_buffer_validate(addr, size, write);
}

#endif /* CONFIG_USERSPACE */


text:
namespace Tests
{
	public static class CustomizationSupport
	{
		//Replace this instance with a custom implementation to override default behaviour
		public static readonly CustomizationSupportInterceptor Interceptor = new Db2iInterceptor();

		public static void Init()
		{
			LinqToDB.DataProvider.DB2iSeries.DB2iSeriesTools.RegisterProviderDetector();
		}
	}
}


text:
<?php
/**
 * The base configurations of bbPress.
 *
 * This file has the following configurations: MySQL settings, Table Prefix,
 * Secret Keys and bbPress Language. You can get the MySQL settings from your
 * web host.
 *
 * This file is used by the installer during installation.
 *
 * @package bbPress
 */

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for bbPress */
define( 'BBDB_NAME', 'bbpress' );

/** MySQL database username */
define( 'BBDB_USER', 'username' );

/** MySQL database password */
define( 'BBDB_PASSWORD', 'password' );

/** MySQL hostname */
define( 'BBDB_HOST', 'localhost' );

/** Database Charset to use in creating database tables. */
define( 'BBDB_CHARSET', 'utf8' );

/** The Database Collate type. Don't change this if in doubt. */
define( 'BBDB_COLLATE', '' );

/**#@+
 * Authentication Unique Keys.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/bbpress/ WordPress.org secret-key service}
 *
 * @since 1.0
 */
define( 'BB_AUTH_KEY', 'put your unique phrase here' );
define( 'BB_SECURE_AUTH_KEY', 'put your unique phrase here' );
define( 'BB_LOGGED_IN_KEY', 'put your unique phrase here' );
define( 'BB_NONCE_KEY', 'put your unique phrase here' );
/**#@-*/

/**
 * bbPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each a unique
 * prefix. Only numbers, letters, and underscores please!
 */
$bb_table_prefix = 'bb_';

/**
 * bbPress Localized Language, defaults to English.
 *
 * Change this to localize bbPress. A corresponding MO file for the chosen
 * language must be installed to a directory called "my-languages" in the root
 * directory of bbPress. For example, install de.mo to "my-languages" and set
 * BB_LANG to 'de' to enable German language support.
 */
define( 'BB_LANG', '' );


text:
package com.heatonresearch.aifh.learning;

/**
 * A regression algorithm provides an output for the given input.  This allows the machine learning algorithm to
 * approximate a function.
 */
public interface RegressionAlgorithm extends MachineLearningAlgorithm {
    /**
     * Compute the output for the specified input.
     *
     * @param input The input.
     * @return The regression output.
     */
    double[] computeRegression(double[] input);
}


text:
package org.emboss.jemboss.soap;

import java.util.*;

import org.emboss.jemboss.JembossParams;

/**
*
* Run showdb and find the available scoring matrices
* and codon usage tables on the Jemboss server
*
*/
public class ShowDB
{

  /** status message */
  private String statusmsg;
  /** status */
  private String status;
  /** showdb output */
  private String dbText;
  /** scoring matrices */
  private Vector matrices;
  /** codon usage tables */
  private Vector codons;
  /** indicates whether connected jemboss server have PDF support */
  private boolean serverSupportsPDF;

  /**
  *
  * @param mysettings 	jemboss properties
  *
  */
  public ShowDB(JembossParams mysettings) throws JembossSoapException
  {

    PublicRequest dbReq = null;

    dbReq = new PublicRequest(mysettings, "show_db");

    statusmsg = dbReq.getVal("msg");
    status = dbReq.getVal("status");
    dbText= dbReq.getVal("showdb");
    String mat = dbReq.getVal("matrices");

    matrices = new Vector();
    StringTokenizer stMat = new StringTokenizer(mat,"\n");
    while (stMat.hasMoreTokens())
      matrices.add(stMat.nextToken());

    mat = dbReq.getVal("codons");
    codons = new Vector();
    stMat = new StringTokenizer(mat,"\n");
    while (stMat.hasMoreTokens())
      codons.add(stMat.nextToken());

    serverSupportsPDF = Boolean.valueOf(dbReq.
            getVal("doesJembossServerSupportPDFoutput")).booleanValue();
  }

  /**
  *
  * Get the status of the request
  * @return 	0 for success
  *
  */
  public String getStatus()
  {
    return status;
  }

  /**
  *
  * Get the status message
  * @return 	status message or contains a
  * 		description of any error.
  *
  */
  public String getStatusMsg()
  {
    return statusmsg;
  }

  /**
  *
  * Get the output from showdb
  * @return  output from showdb
  *
  */
  public String getDBText()
  {
    return dbText;
  }

  /**
  *
  * Get the available matrices
  * @return  	matrices names
  *
  */
  public Vector getMatrices()
  {
    return matrices;
  }

  /**
  *
  * Get the codon usage tables
  * @return  	codon usage table names
  *
  */
  public Vector getCodonUsage()
  {
    return codons;
  }

  /**
  *
  * Returns whether connected jemboss server have PDF support
  * @return     true or false
  *
  */
  public boolean serverSupportsPDF()
  {
    return serverSupportsPDF;
  }

}


text:
using namespace llvm;
using namespace impala_udf;

namespace impala {

Literal::Literal(const TExprNode& node)
  : Expr(node) {
  switch (type_.type) {
    case TYPE_BOOLEAN:
      DCHECK_EQ(node.node_type, TExprNodeType::BOOL_LITERAL);
      DCHECK(node.__isset.bool_literal);
      value_.bool_val = node.bool_literal.value;
      break;
    case TYPE_TINYINT:
      DCHECK_EQ(node.node_type, TExprNodeType::INT_LITERAL);
      DCHECK(node.__isset.int_literal);
      value_.tinyint_val = node.int_literal.value;
      break;
    case TYPE_SMALLINT:
      DCHECK_EQ(node.node_type, TExprNodeType::INT_LITERAL);
      DCHECK(node.__isset.int_literal);
      value_.smallint_val = node.int_literal.value;
      break;
    case TYPE_INT:
      DCHECK_EQ(node.node_type, TExprNodeType::INT_LITERAL);
      DCHECK(node.__isset.int_literal);
      value_.int_val = node.int_literal.value;
      break;
    case TYPE_BIGINT:
      DCHECK_EQ(node.node_type, TExprNodeType::INT_LITERAL);
      DCHECK(node.__isset.int_literal);
      value_.bigint_val = node.int_literal.value;
      break;
    case TYPE_FLOAT:
      DCHECK_EQ(node.node_type, TExprNodeType::FLOAT_LITERAL);
      DCHECK(node.__isset.float_literal);
      value_.float_val = node.float_literal.value;
      break;
    case TYPE_DOUBLE:
      DCHECK_EQ(node.node_type, TExprNodeType::FLOAT_LITERAL);
      DCHECK(node.__isset.float_literal);
      value_.double_val = node.float_literal.value;
      break;
    case TYPE_STRING:
    case TYPE_VARCHAR: {
      DCHECK_EQ(node.node_type, TExprNodeType::STRING_LITERAL);
      DCHECK(node.__isset.string_literal);
      value_.Init(node.string_literal.value);
      if (type_.type == TYPE_VARCHAR) {
        value_.string_val.len = min(type_.len, value_.string_val.len);
      }
      break;
    }
    case TYPE_CHAR: {
      DCHECK_EQ(node.node_type, TExprNodeType::STRING_LITERAL);
      DCHECK(node.__isset.string_literal);
      string str = node.string_literal.value;
      int str_len = str.size();
      DCHECK_GT(str_len, 0);
      str.resize(type_.len);
      if (str_len < type_.len) {
        // Pad out literal with spaces.
        str.replace(str_len, type_.len - str_len, type_.len - str_len, ' ');
      }
      value_.Init(str);
      break;
    }
    case TYPE_DECIMAL: {
      DCHECK_EQ(node.node_type, TExprNodeType::DECIMAL_LITERAL);
      DCHECK(node.__isset.decimal_literal);
      const uint8_t* buffer =
          reinterpret_cast<const uint8_t*>(&node.decimal_literal.value[0]);
      int len = node.decimal_literal.value.size();
      DCHECK_GT(len, 0);

      switch (type().GetByteSize()) {
        case 4:
          DCHECK_LE(len, 4);
          DecimalUtil::DecodeFromFixedLenByteArray(buffer, len, &value_.decimal4_val);
          break;
        case 8:
          DCHECK_LE(len, 8);
          DecimalUtil::DecodeFromFixedLenByteArray(buffer, len, &value_.decimal8_val);
          break;
        case 16:
          DCHECK_LE(len, 16);
          DecimalUtil::DecodeFromFixedLenByteArray(buffer, len, &value_.decimal16_val);
          break;
        default:
          DCHECK(false) << type_.DebugString();
      }
      break;
    }
    case TYPE_TIMESTAMP: {
      DCHECK_EQ(node.node_type, TExprNodeType::TIMESTAMP_LITERAL);
      DCHECK(node.__isset.timestamp_literal);
      const string& ts_val = node.timestamp_literal.value;
      DCHECK_EQ(type_.GetSlotSize(), ts_val.size());
      memcpy(&value_.timestamp_val, ts_val.data(), type_.GetSlotSize());
      break;
    }
    default:
      DCHECK(false) << "Invalid type: " << TypeToString(type_.type);
  }
}

Literal::Literal(ColumnType type, bool v)
  : Expr(type, true, false) {
  DCHECK_EQ(type.type, TYPE_BOOLEAN) << type;
  value_.bool_val = v;
}

Literal::Literal(ColumnType type, int8_t v)
  : Expr(type, true, false) {
  DCHECK_EQ(type.type, TYPE_TINYINT) << type;
  value_.tinyint_val = v;
}

Literal::Literal(ColumnType type, int16_t v)
  : Expr(type, true, false) {
  DCHECK_EQ(type.type, TYPE_SMALLINT) << type;
  value_.smallint_val = v;
}

Literal::Literal(ColumnType type, int32_t v)
  : Expr(type, true, false) {
  DCHECK_EQ(type.type, TYPE_INT) << type;
  value_.int_val = v;
}

Literal::Literal(ColumnType type, int64_t v)
  : Expr(type, true, false) {
  DCHECK_EQ(type.type, TYPE_BIGINT) << type;
  value_.bigint_val = v;
}

Literal::Literal(ColumnType type, float v)
  : Expr(type, true, false) {
  DCHECK_EQ(type.type, TYPE_FLOAT) << type;
  value_.float_val = v;
}

Literal::Literal(ColumnType type, double v)
  : Expr(type, true, false) {
  if (type.type == TYPE_DOUBLE) {
    value_.double_val = v;
  } else if (type.type == TYPE_TIMESTAMP) {
    value_.timestamp_val = TimestampValue(v);
  } else if (type.type == TYPE_DECIMAL) {
    bool overflow = false;
    switch (type.GetByteSize()) {
      case 4:
        value_.decimal4_val = Decimal4Value::FromDouble(type, v, true, &overflow);
        break;
      case 8:
        value_.decimal8_val = Decimal8Value::FromDouble(type, v, true, &overflow);
        break;
      case 16:
        value_.decimal16_val = Decimal16Value::FromDouble(type, v, true, &overflow);
        break;
    }
    DCHECK(!overflow);
  } else {
    DCHECK(false) << type.DebugString();
  }
}

Literal::Literal(ColumnType type, const string& v) : Expr(type, true, false) {
  value_.Init(v);
  DCHECK(type.type == TYPE_STRING || type.type == TYPE_CHAR || type.type == TYPE_VARCHAR)
      << type;
}

Literal::Literal(ColumnType type, const StringValue& v) : Expr(type, true, false) {
  value_.Init(v.DebugString());
  DCHECK(type.type == TYPE_STRING || type.type == TYPE_CHAR) << type;
}

Literal::Literal(ColumnType type, const TimestampValue& v)
  : Expr(type, true, false) {
  DCHECK_EQ(type.type, TYPE_TIMESTAMP) << type;
  value_.timestamp_val = v;
}

bool Literal::IsLiteral() const {
  return true;
}

template<class T>
bool ParseString(const string& str, T* val) {
  istringstream stream(str);
  stream >> *val;
  return !stream.fail();
}

template<>
bool ParseString(const string& str, TimestampValue* val) {
  boost::gregorian::date date;
  boost::posix_time::time_duration time;
  bool success = TimestampParser::Parse(str.data(), str.length(), &date, &time);
  val->set_date(date);
  val->set_time(time);
  return success;
}

Literal* Literal::CreateLiteral(const ColumnType& type, const string& str) {
  switch (type.type) {
    case TYPE_BOOLEAN: {
      bool v = false;
      DCHECK(ParseString<bool>(str, &v)) << str;
      return new Literal(type, v);
    }
    case TYPE_TINYINT: {
      int8_t v = 0;
      DCHECK(ParseString<int8_t>(str, &v)) << str;
      return new Literal(type, v);
    }
    case TYPE_SMALLINT: {
      int16_t v = 0;
      DCHECK(ParseString<int16_t>(str, &v)) << str;
      return new Literal(type, v);
    }
    case TYPE_INT: {
      int32_t v = 0;
      DCHECK(ParseString<int32_t>(str, &v)) << str;
      return new Literal(type, v);
    }
    case TYPE_BIGINT: {
      int64_t v = 0;
      DCHECK(ParseString<int64_t>(str, &v)) << str;
      return new Literal(type, v);
    }
    case TYPE_FLOAT: {
      float v = 0;
      DCHECK(ParseString<float>(str, &v)) << str;
      return new Literal(type, v);
    }
    case TYPE_DOUBLE: {
      double v = 0;
      DCHECK(ParseString<double>(str, &v)) << str;
      return new Literal(type, v);
    }
    case TYPE_STRING:
    case TYPE_VARCHAR:
    case TYPE_CHAR:
      return new Literal(type, str);
    case TYPE_TIMESTAMP: {
      TimestampValue v;
      DCHECK(ParseString<TimestampValue>(str, &v));
      return new Literal(type, v);
    }
    case TYPE_DECIMAL: {
      double v = 0;
      DCHECK(ParseString<double>(str, &v)) << str;
      return new Literal(type, v);
    }
    default:
      DCHECK(false) << "Invalid type: " << type.DebugString();
      return NULL;
  }
}

BooleanVal Literal::GetBooleanVal(ExprContext* context, const TupleRow* row) {
  DCHECK_EQ(type_.type, TYPE_BOOLEAN) << type_;
  return BooleanVal(value_.bool_val);
}

TinyIntVal Literal::GetTinyIntVal(ExprContext* context, const TupleRow* row) {
  DCHECK_EQ(type_.type, TYPE_TINYINT) << type_;
  return TinyIntVal(value_.tinyint_val);
}

SmallIntVal Literal::GetSmallIntVal(ExprContext* context, const TupleRow* row) {
  DCHECK_EQ(type_.type, TYPE_SMALLINT) << type_;
  return SmallIntVal(value_.smallint_val);
}

IntVal Literal::GetIntVal(ExprContext* context, const TupleRow* row) {
  DCHECK_EQ(type_.type, TYPE_INT) << type_;
  return IntVal(value_.int_val);
}

BigIntVal Literal::GetBigIntVal(ExprContext* context, const TupleRow* row) {
  DCHECK_EQ(type_.type, TYPE_BIGINT) << type_;
  return BigIntVal(value_.bigint_val);
}

FloatVal Literal::GetFloatVal(ExprContext* context, const TupleRow* row) {
  DCHECK_EQ(type_.type, TYPE_FLOAT) << type_;
  return FloatVal(value_.float_val);
}

DoubleVal Literal::GetDoubleVal(ExprContext* context, const TupleRow* row) {
  DCHECK_EQ(type_.type, TYPE_DOUBLE) << type_;
  return DoubleVal(value_.double_val);
}

StringVal Literal::GetStringVal(ExprContext* context, const TupleRow* row) {
  DCHECK(type_.IsStringType()) << type_;
  StringVal result;
  value_.string_val.ToStringVal(&result);
  return result;
}

DecimalVal Literal::GetDecimalVal(ExprContext* context, const TupleRow* row) {
  DCHECK_EQ(type_.type, TYPE_DECIMAL) << type_;
  switch (type().GetByteSize()) {
    case 4:
      return DecimalVal(value_.decimal4_val.value());
    case 8:
      return DecimalVal(value_.decimal8_val.value());
    case 16:
      return DecimalVal(value_.decimal16_val.value());
    default:
      DCHECK(false) << type_.DebugString();
  }
  // Quieten GCC.
  return DecimalVal();
}

TimestampVal Literal::GetTimestampVal(ExprContext* context, const TupleRow* row) {
  DCHECK_EQ(type_.type, TYPE_TIMESTAMP) << type_;
  TimestampVal result;
  value_.timestamp_val.ToTimestampVal(&result);
  return result;
}

string Literal::DebugString() const {
  stringstream out;
  out << "Literal(value=";
  switch (type_.type) {
    case TYPE_BOOLEAN:
      out << value_.bool_val;
      break;
    case TYPE_TINYINT:
      out << value_.tinyint_val;
      break;
    case TYPE_SMALLINT:
      out << value_.smallint_val;
      break;
    case TYPE_INT:
      out << value_.int_val;
      break;
    case TYPE_BIGINT:
      out << value_.bigint_val;
      break;
    case TYPE_FLOAT:
      out << value_.float_val;
      break;
    case TYPE_DOUBLE:
      out << value_.double_val;
      break;
    case TYPE_STRING:
      out << value_.string_val;
      break;
    case TYPE_DECIMAL:
      switch (type().GetByteSize()) {
        case 4:
          out << value_.decimal4_val.ToString(type());
          break;
        case 8:
          out << value_.decimal8_val.ToString(type());
          break;
        case 16:
          out << value_.decimal16_val.ToString(type());
          break;
        default:
          DCHECK(false) << type_.DebugString();
      }
      break;
    case TYPE_TIMESTAMP:
      out << value_.timestamp_val;
      break;
    default:
      out << "[bad type! " << type_ << "]";
  }
  out << Expr::DebugString() << ")";
  return out.str();
}

// IR produced for bigint literal 10:
//
// define { i8, i64 } @Literal(i8* %context, %"class.impala::TupleRow"* %row) {
// entry:
//   ret { i8, i64 } { i8 0, i64 10 }
// }
Status Literal::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function** fn) {
  if (ir_compute_fn_ != NULL) {
    *fn = ir_compute_fn_;
    return Status::OK();
  }

  DCHECK_EQ(GetNumChildren(), 0);
  Value* args[2];
  *fn = CreateIrFunctionPrototype(codegen, "Literal", &args);
  BasicBlock* entry_block = BasicBlock::Create(codegen->context(), "entry", *fn);
  LlvmBuilder builder(entry_block);

  CodegenAnyVal v = CodegenAnyVal::GetNonNullVal(codegen, &builder, type_);
  switch (type_.type) {
    case TYPE_BOOLEAN:
      v.SetVal(value_.bool_val);
      break;
    case TYPE_TINYINT:
      v.SetVal(value_.tinyint_val);
      break;
    case TYPE_SMALLINT:
      v.SetVal(value_.smallint_val);
      break;
    case TYPE_INT:
      v.SetVal(value_.int_val);
      break;
    case TYPE_BIGINT:
      v.SetVal(value_.bigint_val);
      break;
    case TYPE_FLOAT:
      v.SetVal(value_.float_val);
      break;
    case TYPE_DOUBLE:
      v.SetVal(value_.double_val);
      break;
    case TYPE_STRING:
    case TYPE_VARCHAR:
    case TYPE_CHAR:
      v.SetLen(builder.getInt32(value_.string_val.len));
      v.SetPtr(codegen->GetStringConstant(
          &builder, value_.string_val.ptr, value_.string_val.len));
      break;
    case TYPE_DECIMAL:
      switch (type().GetByteSize()) {
        case 4:
          v.SetVal(value_.decimal4_val.value());
          break;
        case 8:
          v.SetVal(value_.decimal8_val.value());
          break;
        case 16:
          v.SetVal(value_.decimal16_val.value());
          break;
        default:
          DCHECK(false) << type_.DebugString();
      }
      break;
    case TYPE_TIMESTAMP:
      v.SetTimeOfDay(builder.getInt64(
          *reinterpret_cast<const int64_t*>(&value_.timestamp_val.time())));
      v.SetDate(builder.getInt32(
          *reinterpret_cast<const int32_t*>(&value_.timestamp_val.date())));
      break;
    default:
      stringstream ss;
      ss << "Invalid type: " << type_;
      DCHECK(false) << ss.str();
      return Status(ss.str());
  }

  builder.CreateRet(v.GetLoweredValue());
  *fn = codegen->FinalizeFunction(*fn);
  ir_compute_fn_ = *fn;
  return Status::OK();
}

}


text:
package com.intellij.usages.impl;

import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.Project;
import com.intellij.usages.rules.UsageGroupingRule;
import org.jetbrains.annotations.Nullable;

public interface FileStructureGroupRuleProvider {
  ExtensionPointName<FileStructureGroupRuleProvider> EP_NAME = new ExtensionPointName<>("com.intellij.fileStructureGroupRuleProvider");

  @Nullable
  UsageGroupingRule getUsageGroupingRule(final Project project);
}


text:
import {PluginApi} from '@gerritcodereview/typescript-api/plugin';
import {
  ActionInfo,
  ConfigInfo,
  RepoName,
} from '@gerritcodereview/typescript-api/rest-api';
import {css, html, LitElement} from 'lit';
import {customElement, property, query, state} from 'lit/decorators.js';

// TODO: This should be defined and exposed by @gerritcodereview/typescript-api
type GrOverlay = Element & {
  open(): void;
  close(): void;
};

declare global {
  interface HTMLElementTagNameMap {
    'gr-delete-repo': GrDeleteRepo;
  }
  interface Window {
    CANONICAL_PATH?: string;
  }
}

@customElement('gr-delete-repo')
export class GrDeleteRepo extends LitElement {
  @query('#deleteRepoOverlay')
  deleteRepoOverlay?: GrOverlay;

  @query('#preserveGitRepoCheckBox')
  preserveGitRepoCheckBox?: HTMLInputElement;

  @query('#forceDeleteOpenChangesCheckBox')
  forceDeleteOpenChangesCheckBox?: HTMLInputElement;

  /** Guaranteed to be provided by the 'repo-command' endpoint. */
  @property({type: Object})
  plugin!: PluginApi;

  /** Guaranteed to be provided by the 'repo-command' endpoint. */
  @property({type: Object})
  config!: ConfigInfo;

  /** Guaranteed to be provided by the 'repo-command' endpoint. */
  @property({type: String})
  repoName!: RepoName;

  @state()
  private error?: string;

  static override styles = css`
    :host {
      display: block;
      margin-bottom: var(--spacing-xxl);
    }
    /* TODO: Find a way to use shared styles in lit elements in plugins. */
    h3 {
      font: inherit;
      margin: 0;
    }
    .error {
      color: red;
    }
  `;

  get action(): ActionInfo | undefined {
    return this.config.actions?.[this.actionId];
  }

  get actionId(): string {
    return `${this.plugin.getPluginName()}~delete`;
  }

  private renderError() {
    if (!this.error) return;
    return html`<div class="error">${this.error}</div>`;
  }

  override render() {
    if (!this.action) return;
    return html`

${this.action.label}

      <gr-button
        title="${this.action.title}"
        ?disabled="${!this.action.enabled}"
        @click="${() => {
          this.error = undefined;
          this.deleteRepoOverlay?.open();
        }}"
      >
        ${this.action.label}
      </gr-button>
      ${this.renderError()}
      <gr-overlay id="deleteRepoOverlay" with-backdrop>
        <gr-dialog
          id="deleteRepoDialog"
          confirm-label="Delete"
          @confirm="${this.deleteRepo}"
          @cancel="${() => this.deleteRepoOverlay?.close()}"
        >

            Are you really sure you want to delete the repo: "${this.repoName}"?

                  <input type="checkbox" id="forceDeleteOpenChangesCheckBox" />
                  Delete repo even if open changes exist?

                  <input type="checkbox" id="preserveGitRepoCheckBox" />
                  Preserve GIT Repository?

        </gr-dialog>
      </gr-overlay>
    `;
  }

  private deleteRepo() {
    if (!this.action) {
      this.error = 'delete action undefined';
      this.deleteRepoOverlay?.close();
      return;
    }
    if (!this.action.method) {
      this.error = 'delete action does not have a HTTP method set';
      this.deleteRepoOverlay?.close();
      return;
    }
    this.error = undefined;

    const endpoint = `/projects/${encodeURIComponent(this.repoName)}/${
      this.actionId
    }`;
    const json = {
      force: this.forceDeleteOpenChangesCheckBox?.checked ?? false,
      preserve: this.preserveGitRepoCheckBox?.checked ?? false,
    };
    return this.plugin
      .restApi()
      .send(this.action.method, endpoint, json)
      .then(_ => {
        this.plugin.restApi().invalidateReposCache();
        this.deleteRepoOverlay?.close();
        window.location.href = `${this.getBaseUrl()}/admin/repos`;
      })
      .catch(e => {
        this.error = e;
        this.deleteRepoOverlay?.close();
      });
  }

  private getBaseUrl() {
    return window.CANONICAL_PATH || '';
  }
}


text:
package signer

import (
	"io"
	"net/http"
	"strings"
	"testing"
)

func TestRequestHost(t *testing.T) {
	req, _ := buildRequest("dynamodb", "us-east-1", "{}")
	req.URL.RawQuery = "Foo=z&Foo=o&Foo=m&Foo=a"
	req.Host = "myhost"
	canonicalHeaders := getCanonicalHeaders(*req, v4IgnoredHeaders)

	if !strings.Contains(canonicalHeaders, "host:"+req.Host) {
		t.Errorf("canonical host header invalid")
	}
}

func buildRequest(serviceName, region, body string) (*http.Request, io.ReadSeeker) {
	endpoint := "https://" + serviceName + "." + region + ".amazonaws.com"
	reader := strings.NewReader(body)
	req, _ := http.NewRequest("POST", endpoint, reader)
	req.URL.Opaque = "//example.org/bucket/key-._~,!@#$%^&*()"
	req.Header.Add("X-Amz-Target", "prefix.Operation")
	req.Header.Add("Content-Type", "application/x-amz-json-1.0")
	req.Header.Add("Content-Length", string(len(body)))
	req.Header.Add("X-Amz-Meta-Other-Header", "some-value=!@#$%^&* (+)")
	req.Header.Add("X-Amz-Meta-Other-Header_With_Underscore", "some-value=!@#$%^&* (+)")
	req.Header.Add("X-amz-Meta-Other-Header_With_Underscore", "some-value=!@#$%^&* (+)")
	return req, reader
}