text:
namespace HackerRankTests
{
	using System;
	using System.IO;

	using NUnit.Framework;

	[TestFixture()]
	public class GreedyFloristTests
	{
		[Test()]
		public void ProvidedOne()
		{
			var str = @"3 3
			            2 5 6";

			using(var sr = new StringReader(str))
			using(var sw = new StringWriter())
			{
				HackerRank.Algorithms.Greedy.GreedyFlorist.RunTest(sr, sw);
				Assert.AreEqual("13" + Environment.NewLine, sw.ToString());
			}
		}

		[Test()]
		public void ProvidedTwo()
		{
			var str = @"3 2
			            2 5 6";

			using(var sr = new StringReader(str))
			using(var sw = new StringWriter())
			{
				HackerRank.Algorithms.Greedy.GreedyFlorist.RunTest(sr, sw);
				Assert.AreEqual("15" + Environment.NewLine, sw.ToString());
			}
		}

		[Test()]
		public void KGreaterThanN()
		{
			var str = @"3 4
			            2 5 6";

			using(var sr = new StringReader(str))
			using(var sw = new StringWriter())
			{
				HackerRank.Algorithms.Greedy.GreedyFlorist.RunTest(sr, sw);
				Assert.AreEqual("13" + Environment.NewLine, sw.ToString());
			}
		}

		[Test()]
		public void Complicated()
		{
			var str = @"9 2
			            2 5 6 4 2 8 6 4 8";

			using(var sr = new StringReader(str))
			using(var sw = new StringWriter())
			{
				HackerRank.Algorithms.Greedy.GreedyFlorist.RunTest(sr, sw);
				Assert.AreEqual("101" + Environment.NewLine, sw.ToString());
			}
		}

		[Test()]
		public void MoreComplicated()
		{
			var str = @"9 3
			            2 5 6 4 2 8 6 4 10 8 1 9 1 7";

			using(var sr = new StringReader(str))
			using(var sw = new StringWriter())
			{
				HackerRank.Algorithms.Greedy.GreedyFlorist.RunTest(sr, sw);
				Assert.AreEqual("156" + Environment.NewLine, sw.ToString());
			}
		}
	}
}


text:
function r = sind(p)
%overloaded gcmfaces sind function :
%  simply calls double sind function for each face data

r=p;

for iFace=1:r.nFaces;
   iF=num2str(iFace);
   eval(['r.f' iF '=sind(p.f' iF ');']);
end;

redpajama_set_name: RedPajamaGithub


text:
use crate::prometheus::construct_query_with_extra_labels;
use again::RetryPolicy;
use anyhow::{anyhow, bail};
use once_cell::sync::Lazy;
use prometheus_http_query::response::Sample;
use prometheus_http_query::Client as PrometheusClient;
use serde::Serialize;
use std::collections::BTreeMap;
use std::time::Duration;

#[derive(Default, Clone, Debug)]
pub struct SystemMetrics {
    cpu_core_metrics: Vec<Sample>,
    memory_bytes_metrics: Vec<Sample>,
}

// This retry policy is used for important client calls necessary for setting
// up the test (e.g. account creation) and collecting its results (e.g. checking
// account sequence numbers). If these fail, the whole test fails. We do not use
// this for submitting transactions, as we have a way to handle when that fails.
// This retry policy means an operation will take 8 seconds at most.
static RETRY_POLICY: Lazy<RetryPolicy> = Lazy::new(|| {
    RetryPolicy::exponential(Duration::from_millis(125))
        .with_max_retries(6)
        .with_jitter(true)
});

impl SystemMetrics {
    pub fn new(cpu_metrics: Vec<Sample>, memory_metrics: Vec<Sample>) -> Self {
        Self {
            cpu_core_metrics: cpu_metrics,
            memory_bytes_metrics: memory_metrics,
        }
    }
}

#[derive(Default, Clone, Debug, Serialize)]
pub struct MetricsThreshold {
    max: usize,
    // % of the data point that can breach the max threshold
    max_breach_pct: usize,
}

impl MetricsThreshold {
    pub fn new(max: usize, max_breach_pct: usize) -> Self {
        Self {
            max,
            max_breach_pct,
        }
    }
}

#[derive(Default, Clone, Debug, Serialize)]
pub struct SystemMetricsThreshold {
    cpu_threshold: MetricsThreshold,
    memory_threshold: MetricsThreshold,
}

impl SystemMetricsThreshold {
    pub fn ensure_threshold(&self, metrics: &SystemMetrics) -> anyhow::Result<()> {
        ensure_metrics_threshold("cpu", &self.cpu_threshold, &metrics.cpu_core_metrics)?;
        ensure_metrics_threshold(
            "memory",
            &self.memory_threshold,
            &metrics.memory_bytes_metrics,
        )?;
        Ok(())
    }
    pub fn new(cpu_threshold: MetricsThreshold, memory_threshold: MetricsThreshold) -> Self {
        Self {
            cpu_threshold,
            memory_threshold,
        }
    }
}

fn ensure_metrics_threshold(
    metrics_name: &str,
    threshold: &MetricsThreshold,
    metrics: &Vec<Sample>,
) -> anyhow::Result<()> {
    if metrics.is_empty() {
        bail!("Empty metrics provided");
    }
    let breach_count = metrics
        .iter()
        .filter(|sample| sample.value() > threshold.max as f64)
        .count();
    let breach_pct = (breach_count * 100) / metrics.len();
    if breach_pct > threshold.max_breach_pct {
        bail!(
            "{:?} metric violated threshold of {:?}, max_breach_pct: {:?}, breach_pct: {:?} ",
            metrics_name,
            threshold.max,
            threshold.max_breach_pct,
            breach_pct
        );
    }
    Ok(())
}

async fn query_prometheus_range_metrics(
    query: &str,
    client: &PrometheusClient,
    start_time: i64,
    end_time: i64,
    internal_secs: f64,
    namespace: &str,
) -> anyhow::Result<Vec<Sample>> {
    RETRY_POLICY
        .retry(move || {
            get_prometheus_range_metrics(
                query,
                client,
                start_time,
                end_time,
                internal_secs,
                namespace,
            )
        })
        .await
        .map_err(|e| anyhow!("Failed to query prometheus for system metrics: {}", e))
}

async fn get_prometheus_range_metrics(
    query: &str,
    client: &PrometheusClient,
    start_time: i64,
    end_time: i64,
    internal_secs: f64,
    namespace: &str,
) -> anyhow::Result<Vec<Sample>> {
    let mut labels_map = BTreeMap::new();
    labels_map.insert("namespace".to_string(), namespace.to_string());
    let response = client
        .query_range(
            construct_query_with_extra_labels(query, labels_map),
            start_time,
            end_time,
            internal_secs,
            None,
        )
        .await?;
    Ok(response
        .as_range()
        .ok_or_else(|| anyhow!("Failed to get range from prometheus response"))?
        .first()
        .ok_or_else(|| anyhow!("Empty range vector returned from prometheus"))?
        .samples()
        .to_vec())
}

pub async fn query_prometheus_system_metrics(
    client: &PrometheusClient,
    start_time: i64,
    end_time: i64,
    internal_secs: f64,
    namespace: &str,
) -> anyhow::Result<SystemMetrics> {
    let cpu_query = r#"avg(rate(container_cpu_usage_seconds_total{container=~"validator"}[30s]))"#;
    let memory_query = r#"avg(container_memory_rss{container=~"validator"})"#;

    let cpu_samples = query_prometheus_range_metrics(
        cpu_query,
        client,
        start_time,
        end_time,
        internal_secs,
        namespace,
    )
    .await?;

    let memory_samples = query_prometheus_range_metrics(
        memory_query,
        client,
        start_time,
        end_time,
        internal_secs,
        namespace,
    )
    .await?;

    Ok(SystemMetrics::new(cpu_samples, memory_samples))
}

#[cfg(test)]
mod tests {

    use super::*;
    #[tokio::test]
    async fn test_empty_metrics_threshold() {
        let cpu_threshold = MetricsThreshold::new(10, 30);
        let memory_threshold = MetricsThreshold::new(100, 40);
        let threshold = SystemMetricsThreshold::new(cpu_threshold, memory_threshold);
        let metrics = SystemMetrics::new(vec![], vec![]);
        threshold.ensure_threshold(&metrics).unwrap_err();
    }
}


text:
package me.time6628.clag.sponge.api.events;

import me.time6628.clag.sponge.CatClearLag;
import me.time6628.clag.sponge.api.Type;
import org.spongepowered.api.event.Cancellable;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.cause.EventContext;
import org.spongepowered.api.event.impl.AbstractEvent;

public class ClearLagEvent extends AbstractEvent {

    @Override
    public Cause getCause() {
        return Cause.of(EventContext.empty(), CatClearLag.instance);
    }

    @Override
    public Object getSource() {
        return CatClearLag.instance;
    }

    @Override
    public EventContext getContext() {
        return EventContext.empty();
    }

    public static class Pre extends ClearLagEvent implements Cancellable {
        private boolean cancel;
        private final Type clearType;

        public Pre(Type clearType) {
            this.clearType = clearType;
        }

        @Override
        public boolean isCancelled() {
            return cancel;
        }

        @Override
        public void setCancelled(boolean cancel) {
            this.cancel = cancel;
        }

        public Type getClearType() {
            return clearType;
        }
    }

    public static class Post extends ClearLagEvent {

        private final Type type;
        private final int amount;

        public Post(Type type, int i) {
            this.type = type;
            this.amount = i;
        }

        public Type getType() {
            return type;
        }

        public int getAmount() {
            return amount;
        }
    }
}


text:
using System;
using FluentValidation.TestHelper;
using Moq;
using NUnit.Framework;
using Weapsy.Domain.Pages.Commands;
using Weapsy.Domain.Pages.Validators;
using Weapsy.Domain.Pages.Rules;
using Weapsy.Domain.Sites.Rules;
using FluentValidation;
using Weapsy.Domain.Languages.Rules;
using System.Collections.Generic;
using Weapsy.Domain.Pages;

namespace Weapsy.Domain.Tests.Pages.Validators
{
    [TestFixture]
    public class PageDetailsValidatorTests
    {
        [Test]
        public void Should_have_error_when_page_name_is_empty()
        {
            var pageRulesMock = new Mock<IPageRules>();
            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.Name, new PageDetails
            {
                SiteId = Guid.NewGuid(),
                Id = Guid.NewGuid(),
                Name = string.Empty,
                Url = "url",
                Title = "Title",
                MetaDescription = "Meta Description",
                MetaKeywords = "Meta Keywords"
            });
        }

        [Test]
        public void Should_have_error_when_page_name_is_too_short()
        {
            var pageRulesMock = new Mock<IPageRules>();
            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.Name, new PageDetails
            {
                SiteId = Guid.NewGuid(),
                Id = Guid.NewGuid(),
                Name = "My",
                Url = "url",
                Title = "Title",
                MetaDescription = "Meta Description",
                MetaKeywords = "Meta Keywords"
            });
        }

        [Test]
        public void Should_have_error_when_page_name_is_too_long()
        {
            var pageRulesMock = new Mock<IPageRules>();
            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            var name = "";
            for (int i = 0; i < 101; i++) name += i;

            validator.ShouldHaveValidationErrorFor(x => x.Name, new PageDetails
            {
                SiteId = Guid.NewGuid(),
                Id = Guid.NewGuid(),
                Name = name,
                Url = "url",
                Title = "Title",
                MetaDescription = "Meta Description",
                MetaKeywords = "Meta Keywords"
            });
        }

        [Test]
        public void Should_have_error_when_page_name_is_not_valid()
        {
            Guid siteId = Guid.NewGuid();
            const string name = "My@Page";

            var pageRulesMock = new Mock<IPageRules>();
            pageRulesMock.Setup(x => x.IsPageNameValid(name)).Returns(false);

            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.Name, new PageDetails
            {
                SiteId = siteId,
                Id = Guid.NewGuid(),
                Name = name,
                Url = "url",
                Title = "Title",
                MetaDescription = "Meta Description",
                MetaKeywords = "Meta Keywords"
            });
        }

        [Test]
        public void Should_have_error_when_page_name_already_exists()
        {
            Guid siteId = Guid.NewGuid();
            Guid pageId = Guid.NewGuid();
            const string name = "My Page";

            var pageRulesMock = new Mock<IPageRules>();
            pageRulesMock.Setup(x => x.IsPageNameUnique(siteId, name, pageId)).Returns(false);

            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.Name, new PageDetails
            {
                SiteId = siteId,
                Id = pageId,
                Name = name,
                Url = "url"
            });
        }

        [Test]
        public void Should_have_error_when_page_url_is_empty()
        {
            var pageRulesMock = new Mock<IPageRules>();
            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.Url, new PageDetails
            {
                SiteId = Guid.NewGuid(),
                Id = Guid.NewGuid(),
                Name = "Name",
                Url = string.Empty,
                Title = "Title",
                MetaDescription = "Meta Description",
                MetaKeywords = "Meta Keywords"
            });
        }

        [Test]
        public void Should_have_error_when_page_url_is_too_long()
        {
            var pageRulesMock = new Mock<IPageRules>();
            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            var url = "";
            for (int i = 0; i < 201; i++) url += i;

            validator.ShouldHaveValidationErrorFor(x => x.Url, new PageDetails
            {
                SiteId = Guid.NewGuid(),
                Id = Guid.NewGuid(),
                Name = "Name",
                Url = url,
                Title = "Title",
                MetaDescription = "Meta Description",
                MetaKeywords = "Meta Keywords"
            });
        }

        [Test]
        public void Should_have_error_when_page_url_is_not_valid()
        {
            Guid siteId = Guid.NewGuid();
            const string url = "My@Url";

            var pageRulesMock = new Mock<IPageRules>();
            pageRulesMock.Setup(x => x.IsPageUrlValid(url)).Returns(false);

            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.Url, new PageDetails
            {
                SiteId = Guid.NewGuid(),
                Id = Guid.NewGuid(),
                Name = "Name",
                Url = url,
                Title = "Title",
                MetaDescription = "Meta Description",
                MetaKeywords = "Meta Keywords"
            });
        }

        [Test]
        public void Should_have_error_when_page_url_is_reserved()
        {
            const string url = "admin";

            var pageRulesMock = new Mock<IPageRules>();
            pageRulesMock.Setup(x => x.IsPageUrlReserved(url)).Returns(true);

            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.Url, new PageDetails
            {
                SiteId = Guid.NewGuid(),
                Id = Guid.NewGuid(),
                Name = "Name",
                Url = url
            });
        }

        [Test]
        public void Should_have_error_when_page_slug_already_exists()
        {
            Guid siteId = Guid.NewGuid();
            Guid pageId = Guid.NewGuid();
            const string slug = "something";

            var pageRulesMock = new Mock<IPageRules>();
            pageRulesMock.Setup(x => x.IsSlugUnique(Guid.NewGuid(), slug, Guid.Empty)).Returns(false);

            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.Url, new PageDetails
            {
                SiteId = siteId,
                Id = pageId,
                Name = "Name",
                Url = slug,
                Title = "Title",
                MetaDescription = "Meta Description",
                MetaKeywords = "Meta Keywords"
            });
        }

        [Test]
        public void Should_have_error_when_page_head_title_is_too_long()
        {
            var pageRulesMock = new Mock<IPageRules>();
            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            var title = "";
            for (int i = 0; i < 251; i++) title += i;

            validator.ShouldHaveValidationErrorFor(x => x.Title, new PageDetails
            {
                SiteId = Guid.NewGuid(),
                Id = Guid.NewGuid(),
                Name = "Name",
                Url = "url",
                Title = title,
                MetaDescription = string.Empty,
                MetaKeywords = string.Empty
            });
        }

        [Test]
        public void Should_have_error_when_page_meta_description_is_too_long()
        {
            var pageRulesMock = new Mock<IPageRules>();
            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            var metaDescription = "";
            for (int i = 0; i < 501; i++) metaDescription += i;

            validator.ShouldHaveValidationErrorFor(x => x.MetaDescription, new PageDetails
            {
                SiteId = Guid.NewGuid(),
                Id = Guid.NewGuid(),
                Name = "Name",
                Url = "url",
                Title = string.Empty,
                MetaDescription = metaDescription,
                MetaKeywords = string.Empty
            });
        }

        [Test]
        public void Should_have_error_when_page_meta_keywords_is_too_long()
        {
            var pageRulesMock = new Mock<IPageRules>();
            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            var metaKeywords = "";
            for (int i = 0; i < 251; i++) metaKeywords += i;

            validator.ShouldHaveValidationErrorFor(x => x.MetaKeywords, new PageDetails
            {
                SiteId = Guid.NewGuid(),
                Id = Guid.NewGuid(),
                Name = "Name",
                Url = "url",
                Title = string.Empty,
                MetaDescription = string.Empty,
                MetaKeywords = metaKeywords
            });
        }

        [Test]
        public void Should_have_error_when_localisations_are_missing()
        {
            var pageRulesMock = new Mock<IPageRules>();
            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            languageRulesMock.Setup(x => x.AreAllSupportedLanguagesIncluded(It.IsAny<Guid>(), It.IsAny<IEnumerable<Guid>>())).Returns(false);
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object, siteRulesMock.Object, languageRulesMock.Object, localisationValidatorMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.PageLocalisations, new PageDetails
            {
                SiteId = Guid.NewGuid(),
                Id = Guid.NewGuid(),
                Name = "Name",
                Url = "Url"
            });
        }

        [Test]
        public void Should_have_error_when_localised_page_slug_is_not_unique()
        {
            var pageId = Guid.NewGuid();
            const string slug = "My@Url";

            var pageRulesMock = new Mock<IPageRules>();
            pageRulesMock.Setup(x => x.IsSlugUnique(Guid.NewGuid(), slug, pageId)).Returns(false);
            var siteRulesMock = new Mock<ISiteRules>();
            var languageRulesMock = new Mock<ILanguageRules>();
            var localisationValidatorMock = new Mock<IValidator<PageLocalisation>>();
            var validator = new PageDetailsValidator<PageDetails>(pageRulesMock.Object,
                siteRulesMock.Object,
                languageRulesMock.Object,
                localisationValidatorMock.Object);

            validator.ShouldHaveValidationErrorFor(x => x.PageLocalisations, new PageDetails());
        }
    }
}


text:
package com.singhaiuklimited

import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import com.singhaiuklimited.routing.Service
import com.typesafe.config.ConfigFactory

//import scala.io.StdIn
import scala.util.Try

object Boot extends App with Service {
  override implicit val system = ActorSystem("akka-http-circe-geoip-heroku")
  // needed for the future flatMap/onComplete in the end
  override implicit val executor = system.dispatcher
  override implicit val materializer = ActorMaterializer()

  override val config = ConfigFactory.load()
  override val logger = Logging(system, getClass)

  system.registerOnTermination {
    system.log.info("Akka HTTP microservice shutdown.")
  }

  private val httpInterface: String = Try(config.getString("http.interface")).getOrElse("0.0.0.0")
  private val httpPort: Int = Try(config.getInt("http.port")).getOrElse(80)
  private val bindingFuture = Http().bindAndHandle(handler = logRequestResult("log")(routes), interface = httpInterface, port = httpPort)

  logger.info(s"Server online at http://$httpInterface:$httpPort/")
  /* Commented out as readLine was causing crash in Heroku
  logger.info("Press RETURN to stop...")
  StdIn.readLine() // let it run until user presses return
  bindingFuture
    .flatMap(_.unbind()) // trigger unbinding from the port
    .onComplete(_ => system.terminate()) // and shutdown when done
  */
}


text:
const { Command } = require('discord.js-commando');

const { EXAMPLE_CHANNEL } = process.env;
const Tag = require('../../models/Tag');
const Util = require('../../util/Util');

module.exports = class ExampleAddCommand extends Command {
	constructor(client) {
		super(client, {
			name: 'add-example',
			aliases: ['example-add', 'tag-add-example', 'add-example-tag'],
			group: 'tags',
			memberName: 'add-example',
			description: 'Adds an example.',
			details: `Adds an example and posts it into the #examples channel. (Markdown can be used.)`,
			guildOnly: true,
			throttling: {
				usages: 2,
				duration: 3
			},

			args: [
				{
					key: 'name',
					label: 'examplename',
					prompt: 'what would you like to name it?\n',
					type: 'string'
				},
				{
					key: 'content',
					label: 'examplecontent',
					prompt: 'what content would you like to add?\n',
					type: 'string',
					max: 1800
				}
			]
		});
	}

	hasPermission(msg) {
		return this.client.isOwner(msg.author) || msg.member.roles.exists('name', 'Server Staff');
	}

	async run(msg, args) {
		const name = Util.cleanContent(msg, args.name.toLowerCase());
		const content = Util.cleanContent(msg, args.content);
		const tag = await Tag.findOne({ where: { name, guildID: msg.guild.id } });
		if (tag) return msg.say(`An example with the name **${name}** already exists, ${msg.author}`);

		await Tag.create({
			userID: msg.author.id,
			userName: `${msg.author.tag}`,
			guildID: msg.guild.id,
			guildName: msg.guild.name,
			channelID: msg.channel.id,
			channelName: msg.channel.name,
			name,
			content,
			type: true,
			example: true
		});

		const message = await msg.guild.channels.get(EXAMPLE_CHANNEL).send(content);
		Tag.update({ exampleID: message.id }, { where: { name, guildID: msg.guild.id } });

		return msg.say(`An example with the name **${name}** has been added, ${msg.author}`);
	}
};


text:
===================
Development roadmap
===================

This document outlines Fabric's intended development path. Please make sure
you're reading `the latest version
<http://docs.fabfile.org/en/latest/roadmap.html>`_ of this document!

.. warning::
    This information is subject to change without warning, and should not be
    used as a basis for any life- or career-altering decisions!

Fabric 1.x
==========

Fabric 1.x, while not end-of-life'd, has reached a tipping point regarding
internal tech debt & ability to make significant improvements without harming
backwards compatibility.

As such, future 1.x releases (**1.6** onwards) will emphasize small-to-medium
features (new features not requiring major overhauls of the internals) and
bugfixes.

Invoke, Fabric 2.x and Patchwork
================================

While 1.x moves on as above, we are working on a reimagined 2.x version of the
tool, and plan to:

* Finish and release `the Invoke tool/library
  <https://github.com/pyinvoke/invoke>`_ (see also :issue:`565`), which is a
  revamped and standalone version of Fabric's task running components.

    * Initially it will be basic, matching Fabric's current functionality, but
      with a cleaner base to build on.
    * Said cleaner base then gives us a jumping-off point for new task-oriented
      features such as before/after hooks / call chains, task collections,
      improved namespacing and so forth.

* Start putting together Fabric 2.0, a partly/mostly rewritten Fabric core:

    * Leverage Invoke for task running, which will leave Fabric itself much
      more library oriented.
    * Implement object-oriented hosts/host lists and all the fun stuff that
      provides (e.g. no more hacky host string and unintuitive env var
      manipulation.)
    * No (or optional & non-default) shared state.
    * Any other core overhauls difficult to do in a backwards compatible
      fashion.
    * `Current issue list
      <https://github.com/fabric/fabric/issues?labels=2.x>`_

* Spin off ``fabric.contrib.*`` into a standalone "super-Fabric" (as in, "above Fabric") library, `Patchwork <https://github.com/fabric/patchwork>`_.

    * This lets core "execute commands on hosts" functionality iterate
      separately from "commonly useful shortcuts using Fabric core".
    * Lots of preliminary work & prior-art scanning has been done in
      :issue:`461`.
    * A public-but-alpha codebase for Patchwork exists as we think about the
      API, and is currently based on Fabric 1.x. It will likely be Fabric 2.x
      based by the time it is stable.


text:
/*
 * GifFile.cpp
 *
 *  Created on: 4 de fev de 2017
 *      Author: gifuser
 */

#include "GifFile.h"
#include "gif.h"
#include <stdexcept>

GifFile::GifFile(const char *fileName, uint16_t w, uint16_t h, uint16_t delay)
{
    if (fileName == NULL)
    {
        throw std::invalid_argument("fileName cannot be null");
    }

    if (w == 0)
    {
        throw std::invalid_argument("width must be positive");
    }

    if (h == 0)
    {
        throw std::invalid_argument("height must be positive");
    }

    GifWriter *gwriter = new GifWriter();
    _writer = (void *)gwriter;
    GifBegin(gwriter, fileName, w, h, delay);
}

GifFile::~GifFile()
{
    GifWriter *gwriter = (GifWriter *)_writer;
    GifEnd(gwriter);
    delete gwriter;
}

void GifFile::write(GifFrame *frame)
{
    if (frame == NULL)
    {
        throw std::invalid_argument("frame cannot be null");
    }

    GifWriteFrame((GifWriter *)_writer, frame->getBuffer(), frame->getWidth(), frame->getHeight(), frame->getDelay());
}


text:
package gh3.models

import gh3._
import net.liftweb.json.JsonAST.JValue
import org.joda.time.LocalDateTime

case class GH3Deployment(
                           url: String,
                           id: Long,
                           sha: String,
                           ref: String,
                           task: String,
                           environment: String,
                           description: Option[String],
                           creator: GH3Sender,
                           created_at: LocalDateTime,
                           updated_at: LocalDateTime,
                           statuses_url: String,
                           repository_url: String

                        )

object GH3Deployment
{
   def apply(json: JValue): Option[GH3Deployment] =
   {
      val n2s = node2String(json)(_)

      val url = n2s("url")
      val id = node2Long(json)("id")
      val sha = n2s("sha")
      val ref = n2s("ref")
      val task = n2s("task")
      val environment = n2s("environment")
      val description = node2OptionString(json)("description")
      val creator = GH3Sender(json \ "creator")
      val created_at = node2LocalDateTime(json)("created_at")
      val updated_at = node2LocalDateTime(json)("updated_at")
      val statuses_url = n2s("statuses_url")
      val repository_url = n2s("repository_url")

      val params = Seq(url, id, sha, ref, task, environment, description, creator, created_at, updated_at, statuses_url, repository_url)

      if(params.forall(_.isDefined))
         Some(new GH3Deployment( url.get, id.get, sha.get, ref.get, task.get, environment.get, description.get,
                                 creator.get, created_at.get, updated_at.get, statuses_url.get, repository_url.get))
      else None
   }
}


text:
from django.utils.translation import ugettext_lazy as _

from horizon import exceptions

from openstack_dashboard.api import glance

def get_available_images(request, project_id=None, images_cache=None):
    """Returns a list of available images

    Returns a list of images that are public, shared, community or owned by
    the given project_id. If project_id is not specified, only public and
    community images are returned.

    :param images_cache: An optional dict-like object in which to
    cache public and per-project id image metadata.
    """

    if images_cache is None:
        images_cache = {}
    public_images = images_cache.get('public_images', [])
    community_images = images_cache.get('community_images', [])
    images_by_project = images_cache.get('images_by_project', {})
    shared_images = images_cache.get('shared_images', [])
    if 'public_images' not in images_cache:
        public = {"is_public": True,
                  "status": "active"}
        try:
            images, _more, _prev = glance.image_list_detailed(
                request, filters=public)
            public_images += images
            images_cache['public_images'] = public_images
        except Exception:
            exceptions.handle(request,
                              _("Unable to retrieve public images."))

    # Preempt if we don't have a project_id yet.
    if project_id is None:
        images_by_project[project_id] = []

    if project_id not in images_by_project:
        owner = {"property-owner_id": project_id,
                 "status": "active"}
        try:
            owned_images, _more, _prev = glance.image_list_detailed(
                request, filters=owner)
            images_by_project[project_id] = owned_images
        except Exception:
            owned_images = []
            exceptions.handle(request,
                              _("Unable to retrieve images for "
                                "the current project."))
    else:
        owned_images = images_by_project[project_id]

    if 'community_images' not in images_cache:
        community = {"visibility": "community",
                     "status": "active"}
        try:
            images, _more, _prev = glance.image_list_detailed(
                request, filters=community)
            community_images += images
            images_cache['community_images'] = community_images
        except Exception:
            exceptions.handle(request,
                              _("Unable to retrieve community images."))

    if 'shared_images' not in images_cache:
        shared = {"visibility": "shared",
                  "status": "active"}
        try:
            shared_images, _more, _prev = \
                glance.image_list_detailed(request, filters=shared)
            images_cache['shared_images'] = shared_images
        except Exception:
            exceptions.handle(request,
                              _("Unable to retrieve shared images."))

    if 'images_by_project' not in images_cache:
        images_cache['images_by_project'] = images_by_project

    images = owned_images + public_images + community_images + shared_images

    image_ids = []
    final_images = []
    for image in images:
        if image.id not in image_ids and \
                image.container_format not in ('aki', 'ari'):
            image_ids.append(image.id)
            final_images.append(image)
    return final_images


text:
package com.intellij.codeInspection.dataFlow.instructions;

import com.intellij.codeInspection.dataFlow.DataFlowRunner;
import com.intellij.codeInspection.dataFlow.DfaInstructionState;
import com.intellij.codeInspection.dataFlow.DfaMemoryState;
import com.intellij.codeInspection.dataFlow.InstructionVisitor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiKeyword;
import com.intellij.psi.PsiType;
import org.jetbrains.annotations.NotNull;

/**
 * @author peter
 */
public class InstanceofInstruction extends BinopInstruction {
  @NotNull private final PsiExpression myLeft;
  @NotNull private final PsiType myCastType;

  public InstanceofInstruction(PsiElement psiAnchor, @NotNull Project project, PsiExpression left, PsiType castType) {
    super(PsiKeyword.INSTANCEOF, psiAnchor, project);
    myLeft = left;
    myCastType = castType;
  }

  @Override
  public DfaInstructionState[] accept(DataFlowRunner runner, DfaMemoryState stateBefore, InstructionVisitor visitor) {
    return visitor.visitInstanceof(this, runner, stateBefore);
  }

  @NotNull
  public PsiExpression getLeft() {
    return myLeft;
  }

  @NotNull
  public PsiType getCastType() {
    return myCastType;
  }
}


text:
class AudioPlayer : public QObject
{
    Q_OBJECT
public:
    explicit AudioPlayer(QObject *parent = 0);
    ~AudioPlayer();

signals:

public slots:
    void playClick(int bar, int measure, int soundId);

#if USE_RESOURCE
private slots:
    void resourceAcquiredHandler(const QList<ResourcePolicy::ResourceType>&);
    void resourceLostHandler();

private:
    ResourcePolicy::ResourceSet *m_resourceSet;
    ResourcePolicy::AudioResource *m_audioResource;
#endif

private:
#if USE_QSOUNDEFFECT
    QSoundEffect sounds[4];
#endif
#if USE_PULSEAUDIO
    WavFile wavs[4];
    PulseSimple pulse;
#endif
};

#endif // AUDIOPLAYER_H


text:
using ActiveListExtensions.ListModifiers.Bases;
using ActiveListExtensions.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ActiveListExtensions
{
	internal class ActiveRange : ActiveBase<int>
	{
		public override int Count => _resultList.Count;

		public override int this[int index] => _resultList[index];

		private ObservableList<int, int> _resultList;

		private int _start;
		private ValueWatcher<int> _startWatcher;

		private ValueWatcher<int> _countWatcher;

		public ActiveRange(IActiveValue<int> start, IActiveValue<int> count)
		{
			_resultList = new ObservableList<int, int>(i => i);
			_resultList.CollectionChanged += (s, e) => NotifyOfCollectionChange(e);
			_resultList.PropertyChanged += (s, e) => NotifyOfPropertyChange(e);

			_startWatcher = new ValueWatcher<int>(start, null);
			_startWatcher.ValueOrValuePropertyChanged += StartChanged;

			_countWatcher = new ValueWatcher<int>(count, null);
			_countWatcher.ValueOrValuePropertyChanged += CountChanged;

			CountChanged();
		}

		private void StartChanged()
		{
			if (_startWatcher.Value > _start)
			{
				var max = _startWatcher.Value - _start;

				if (max > _resultList.Count)
					max = _resultList.Count;

				for (int i = max - 1; i >= 0; --i)
					_resultList.Remove(i);

				_start = _startWatcher.Value;

				for (int i = _resultList.Count; i < _countWatcher.Value; ++i)
					_resultList.Add(i, _start + i);
			}
			else if (_startWatcher.Value < _start)
			{
				var min = _startWatcher.Value - _start;

				if (min < 0)
					min = 0;

				for (int i = _resultList.Count - 1; i >= min; --i)
					_resultList.Remove(i);

				_start = _startWatcher.Value;

				var max = _countWatcher.Value - _resultList.Count;

				for (int i = 0; i < max; ++i)
					_resultList.Add(i, _start + i);
			}
		}

		private void CountChanged()
		{
			var count = _countWatcher.Value;

			if (count < 0)
				count = 0;

			if (count > _resultList.Count)
			{
				for (int i = _resultList.Count; i < count; ++i)
					_resultList.Add(i, _startWatcher.Value + i);
			}
			else if (count < _resultList.Count)
			{
				for (int i = _resultList.Count - 1; i >= count; --i)
					_resultList.Remove(i);
			}
		}

		protected override void OnDisposed()
		{
			_startWatcher.Dispose();
			_countWatcher.Dispose();
		}
		public override IEnumerator<int> GetEnumerator() => _resultList.GetEnumerator();
	}
}


text:
package cloudcallcenter

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// CommitContactFlowVersionModification invokes the cloudcallcenter.CommitContactFlowVersionModification API synchronously
// api document: https://help.aliyun.com/api/cloudcallcenter/commitcontactflowversionmodification.html
func (client *Client) CommitContactFlowVersionModification(request *CommitContactFlowVersionModificationRequest) (response *CommitContactFlowVersionModificationResponse, err error) {
	response = CreateCommitContactFlowVersionModificationResponse()
	err = client.DoAction(request, response)
	return
}

// CommitContactFlowVersionModificationWithChan invokes the cloudcallcenter.CommitContactFlowVersionModification API asynchronously
// api document: https://help.aliyun.com/api/cloudcallcenter/commitcontactflowversionmodification.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CommitContactFlowVersionModificationWithChan(request *CommitContactFlowVersionModificationRequest) (<-chan *CommitContactFlowVersionModificationResponse, <-chan error) {
	responseChan := make(chan *CommitContactFlowVersionModificationResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.CommitContactFlowVersionModification(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// CommitContactFlowVersionModificationWithCallback invokes the cloudcallcenter.CommitContactFlowVersionModification API asynchronously
// api document: https://help.aliyun.com/api/cloudcallcenter/commitcontactflowversionmodification.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) CommitContactFlowVersionModificationWithCallback(request *CommitContactFlowVersionModificationRequest, callback func(response *CommitContactFlowVersionModificationResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *CommitContactFlowVersionModificationResponse
		var err error
		defer close(result)
		response, err = client.CommitContactFlowVersionModification(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// CommitContactFlowVersionModificationRequest is the request struct for api CommitContactFlowVersionModification
type CommitContactFlowVersionModificationRequest struct {
	*requests.RpcRequest
	Canvas               string `position:"Body" name:"Canvas"`
	InstanceId           string `position:"Query" name:"InstanceId"`
	ContactFlowVersionId string `position:"Query" name:"ContactFlowVersionId"`
	Content              string `position:"Body" name:"Content"`
}

// CommitContactFlowVersionModificationResponse is the response struct for api CommitContactFlowVersionModification
type CommitContactFlowVersionModificationResponse struct {
	*responses.BaseResponse
	RequestId          string             `json:"RequestId" xml:"RequestId"`
	Success            bool               `json:"Success" xml:"Success"`
	Code               string             `json:"Code" xml:"Code"`
	Message            string             `json:"Message" xml:"Message"`
	HttpStatusCode     int                `json:"HttpStatusCode" xml:"HttpStatusCode"`
	ContactFlowVersion ContactFlowVersion `json:"ContactFlowVersion" xml:"ContactFlowVersion"`
}

// CreateCommitContactFlowVersionModificationRequest creates a request to invoke CommitContactFlowVersionModification API
func CreateCommitContactFlowVersionModificationRequest() (request *CommitContactFlowVersionModificationRequest) {
	request = &CommitContactFlowVersionModificationRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("CloudCallCenter", "2017-07-05", "CommitContactFlowVersionModification", "", "")
	request.Method = requests.POST
	return
}

// CreateCommitContactFlowVersionModificationResponse creates a response to parse from CommitContactFlowVersionModification response
func CreateCommitContactFlowVersionModificationResponse() (response *CommitContactFlowVersionModificationResponse) {
	response = &CommitContactFlowVersionModificationResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text: sed 's/#.*//' $ZSH/AptFile | xargs sudo apt install --yes


text:
from nose.tools import *  # noqa: F403
import datetime as datetime
import pytest

from django.test import RequestFactory
from django.db.models import Q
from django.contrib.auth.models import Group
from django.core.exceptions import ValidationError, PermissionDenied
from django.contrib.admin.sites import AdminSite
from django.forms.models import model_to_dict
from django.http import QueryDict

from tests.base import AdminTestCase

from osf_tests.factories import SubjectFactory, UserFactory, RegistrationFactory, PreprintFactory

from osf.models import Subject, OSFUser, Collection, Embargo
from osf.models.provider import rules_to_subjects
from admin.base.utils import get_subject_rules, change_embargo_date
from osf.admin import OSFUserAdmin

import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
pytestmark = pytest.mark.django_db

class TestSubjectRules(AdminTestCase):

    def setUp(self):
        super(TestSubjectRules, self).setUp()

        self.parent_one = SubjectFactory()  # 0
        self.parent_two = SubjectFactory()  # 1

        self.child_one_1 = SubjectFactory(parent=self.parent_one)  # 2
        self.child_one_2 = SubjectFactory(parent=self.parent_one)  # 3
        self.grandchild_one_1 = SubjectFactory(parent=self.child_one_1)  # 4
        self.grandchild_one_2 = SubjectFactory(parent=self.child_one_1)  # 5

        self.child_two_1 = SubjectFactory(parent=self.parent_two)  # 6
        self.child_two_2 = SubjectFactory(parent=self.parent_two)  # 7

    def test_error_when_child_called_without_parent(self):
        subjects_selected = [self.child_one_1]

        with self.assertRaises(AttributeError):
            get_subject_rules(subjects_selected)

    def test_just_toplevel_subject(self):
        subjects_selected = [self.parent_one]
        rules_returned = get_subject_rules(subjects_selected)
        rules_ideal = [[[self.parent_one._id], False]]
        assert rules_returned == rules_ideal

    def test_two_toplevel_subjects(self):
        subjects_selected = [
            self.parent_one,
            self.parent_two
        ]
        rules_returned = get_subject_rules(subjects_selected)
        rules_ideal = [
            [[self.parent_one._id], False],
            [[self.parent_two._id], False]
        ]
        assert rules_returned == rules_ideal

    def test_one_child(self):
        subjects_selected = [
            self.parent_one,
            self.child_one_1
        ]
        rules_returned = get_subject_rules(subjects_selected)
        rules_ideal = [[[self.parent_one._id, self.child_one_1._id], False]]
        assert rules_returned == rules_ideal

    def test_one_child_all_grandchildren(self):
        subjects_selected = [
            self.parent_one,
            self.child_one_1,
            self.grandchild_one_1,
            self.grandchild_one_2,
        ]
        rules_returned = get_subject_rules(subjects_selected)
        rules_ideal = [[[self.parent_one._id, self.child_one_1._id], True]]
        assert rules_returned == rules_ideal

    def test_all_children_all_grandchildren(self):
        subjects_selected = [
            self.parent_one,
            self.child_one_1,
            self.grandchild_one_1,
            self.grandchild_one_2,
            self.child_one_2
        ]
        rules_returned = get_subject_rules(subjects_selected)
        rules_ideal = [[[self.parent_one._id], True]]
        assert rules_returned == rules_ideal

    def test_one_child_with_one_grandchild(self):
        subjects_selected = [
            self.parent_one,
            self.child_one_1,
            self.grandchild_one_1
        ]
        rules_returned = get_subject_rules(subjects_selected)
        rules_ideal = [
            [[self.parent_one._id, self.child_one_1._id, self.grandchild_one_1._id], False]
        ]
        assert rules_returned == rules_ideal

    def test_rules_to_subjects(self):
        rules = [
            [[self.parent_one._id, self.child_one_1._id], False]
        ]
        subject_queryset_ideal = Subject.objects.filter(Q(id=self.parent_one.id) | Q(id=self.child_one_1.id))
        returned_subjects = rules_to_subjects(rules)
        assert list(subject_queryset_ideal) == list(returned_subjects)

class TestNodeChanges(AdminTestCase):
    def setUp(self):
        super(TestNodeChanges, self).setUp()
        self.registration = RegistrationFactory(is_public=True)
        self.user = UserFactory()
        self.user.is_staff = True
        self.user.groups.add(Group.objects.get(name='osf_admin'))
        self.user.save()

        self.date_valid = self.registration.registered_date + datetime.timedelta(days=365)
        self.date_valid2 = self.registration.registered_date + datetime.timedelta(days=375)
        self.date_too_late = self.registration.registered_date + datetime.timedelta(days=1825)
        self.date_too_soon = self.registration.registered_date + datetime.timedelta(days=-1)

    def test_change_embargo_date(self):

        assert_false(self.registration.embargo)
        assert_true(self.registration.is_public)
        assert_true(Embargo.objects.count() == 0)

        # Note: Date comparisons accept a difference up to a day because embargoes start at midnight

        # Create an embargo from a registration with none
        change_embargo_date(self.registration, self.user, self.date_valid)
        assert_almost_equal(self.registration.embargo.end_date, self.date_valid, delta=datetime.timedelta(days=1))
        assert_true(Embargo.objects.count() == 1)

        # Make sure once embargo is set, registration is made private
        self.registration.reload()
        assert_false(self.registration.is_public)

        # Update an embargo end date
        change_embargo_date(self.registration, self.user, self.date_valid2)
        assert_almost_equal(self.registration.embargo.end_date, self.date_valid2, delta=datetime.timedelta(days=1))
        assert_true(Embargo.objects.count() == 1)

        # Test invalid dates
        with assert_raises(ValidationError):
            change_embargo_date(self.registration, self.user, self.date_too_late)
        with assert_raises(ValidationError):
            change_embargo_date(self.registration, self.user, self.date_too_soon)

        # Test that checks user has permission
        with assert_raises(PermissionDenied):
            change_embargo_date(self.registration, UserFactory(), self.date_valid)

        assert_almost_equal(self.registration.embargo.end_date, self.date_valid2, delta=datetime.timedelta(days=1))
        assert_true(Embargo.objects.count() == 1)

        assert_false(self.registration.is_public)

site = AdminSite()

class TestGroupCollectionsPreprints:
    @pytest.mark.enable_bookmark_creation
    @pytest.fixture()
    def user(self):
        return UserFactory()

    @pytest.fixture()
    def admin_url(self, user):
        return '/admin/osf/osfuser/{}/change/'.format(user.id)

    @pytest.fixture()
    def preprint(self, user):
        return PreprintFactory(creator=user)

    @pytest.fixture()
    def get_request(self, admin_url, user):
        request = RequestFactory().get(admin_url)
        request.user = user
        return request

    @pytest.fixture()
    def post_request(self, admin_url, user):
        request = RequestFactory().post(admin_url)
        request.user = user
        return request

    @pytest.fixture()
    def osf_user_admin(self):
        return OSFUserAdmin(OSFUser, site)

    @pytest.mark.enable_bookmark_creation
    def test_admin_app_formfield_collections(self, preprint, user, get_request, osf_user_admin):
        """ Testing OSFUserAdmin.formfield_many_to_many.
        This should not return any bookmark collections or preprint groups, even if the user is a member.
        """

        formfield = (osf_user_admin.formfield_for_manytomany(OSFUser.groups.field, request=get_request))
        queryset = formfield.queryset

        collections_group = Collection.objects.filter(creator=user, is_bookmark_collection=True)[0].get_group('admin')
        assert(collections_group not in queryset)

        assert(preprint.get_group('admin') not in queryset)

    @pytest.mark.enable_bookmark_creation
    def test_admin_app_save_related_collections(self, post_request, osf_user_admin, user, preprint):
        """ Testing OSFUserAdmin.save_related
        This should maintain the bookmark collections and preprint groups the user is a member of
        even though they aren't explicitly returned by the form.
        """

        form = osf_user_admin.get_form(request=post_request, obj=user)
        data_dict = model_to_dict(user)
        post_form = form(data_dict, instance=user)

        # post_form.errors.keys() generates a list of fields causing JSON Related errors
        # which are preventing the form from being valid (which is required for the form to be saved).
        # By setting the field to '{}', this makes the form valid and resolves JSON errors.

        for field in post_form.errors.keys():
            if field == 'groups':
                data_dict['groups'] = []
            else:
                data_dict[field] = '{}'
        post_form = form(data_dict, instance=user)
        assert(post_form.is_valid())
        post_form.save(commit=False)
        qdict = QueryDict('', mutable=True)
        qdict.update(data_dict)
        post_request.POST = qdict
        osf_user_admin.save_related(request=post_request, form=post_form, formsets=[], change=True)

        collections_group = Collection.objects.filter(creator=user, is_bookmark_collection=True)[0].get_group('admin')
        assert(collections_group in user.groups.all())

        assert(preprint.get_group('admin') in user.groups.all())


text:
The `symbols()` function allows counter styles to be defined inline, directly as the value of the CSS property. Unlike styles defines with [`@counter-style`][0], these styles are anonymous. The `symbols()` function doesn't have all the capabilities and options of the [`@counter-style`][0] at-rule, but is useful in cases such as when the style is used only once and you don't need all the the options provided by [`@counter-style`][0].

### Syntax

    symbols() = symbols( <symbols-type>? [ <string> | <image> ]+ );

`<symbols-type>` is one of the following keyword:

* `cyclic`, meaning that the system repeatedly goes through the different values, in the order of their definition and in an endless cycle.
* `numeric`, meaning that the system interprets the given values as the successive units of a place-value numerical system.
* `alphabetic`, meaning that the system interprets the given values as the digits of an alphabetic numbering system, as a place-value numerical system, but without `0`.
* `symbolic`, meaning that the system cycles through the values, printing them one more time at each cycle (one time for the first cycle, two times for the second, ...).
* `fixed`, meaning that the system prints each symbol once, then falls back to arab numericals.

### Example

    ol {
        list-style: symbols(cyclic "*" "\2020" "\2021");
    }

The above example code will render a list like this:

* \* One
* † Two
* ‡ Three
* \* Four
* † Five

[0]: https://developer.mozilla.org/en/docs/Web/CSS/@counter-style "The @counter-style CSS at-rule defines a specific counter style that are not part of the predefined set of styles. A @counter-style rule defines how to convert a counter value into a string representation."


text:
package org.apache.camel.component.milo.client;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.component.milo.Messages;
import org.apache.camel.component.milo.client.MiloClientConnection.MonitorHandle;
import org.apache.camel.support.DefaultConsumer;
import org.apache.camel.support.DefaultMessage;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.ExpandedNodeId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static java.util.Objects.requireNonNull;

public class MiloClientConsumer extends DefaultConsumer {

    private static final Logger LOG = LoggerFactory.getLogger(MiloClientConsumer.class);

    private final MiloClientConnection connection;

    private MonitorHandle handle;

    private ExpandedNodeId node;

    private Double samplingInterval;

    public MiloClientConsumer(final MiloClientEndpoint endpoint, final Processor processor, final MiloClientConnection connection) {
        super(endpoint, processor);

        requireNonNull(connection);

        this.connection = connection;
        this.node = endpoint.getNodeId();
        this.samplingInterval = endpoint.getSamplingInterval();
    }

    @Override
    protected void doStart() throws Exception {
        super.doStart();

        this.handle = this.connection.monitorValue(this.node, this.samplingInterval, this::handleValueUpdate);
    }

    @Override
    protected void doStop() throws Exception {
        if (this.handle != null) {
            this.handle.unregister();
            this.handle = null;
        }

        super.doStop();
    }

    private void handleValueUpdate(final DataValue value) {
        LOG.debug("Handle item update - {} = {}", node, value);

        final Exchange exchange = getEndpoint().createExchange();
        exchange.setIn(mapMessage(value));
        try {
            getAsyncProcessor().process(exchange);
        } catch (final Exception e) {
            LOG.debug("Failed to process message", e);
        }
    }

    private Message mapMessage(final DataValue value) {
        if (value == null) {
            return null;
        }

        final DefaultMessage result = new DefaultMessage(getEndpoint().getCamelContext());

        Messages.fillFromDataValue(value, result);

        return result;
    }

}


text:
/********************************
 *** Admin Portal Controllers ***
 ********************************/

/* Manage Jobs */
controllerMappings
        .adminController()
        .path('/shortUrl/')
        .enabled(true)
        .defaultView(views.templateView('shortUrl/manageUrlJobs'))
        .addMethod('GET', 'manageUrlJobs')
        .addMethod('POST', 'addUrlJob', 'jobName')
        .addMethod('POST', 'reindexLogs', 'reindex')
        .build();

controllerMappings
        .adminController()
        .path('/shortUrl/_historicData$')
        .addPathResolver('website', 'resolveWebsiteId')
        .enabled(true)
        .addMethod('GET', 'urlJobsHistoricData')
        .build();

/* Manage Website Collections Redirect */
controllerMappings
        .adminController()
        .path('/shortUrl$')
        .enabled(true)
        .addMethod('GET', 'checkRedirect')
        .build();

/* Manage URL code for a job */
controllerMappings
        .adminController()
        .path('/shortUrl/(?<jobCode>[^/]*)/$')
        .addPathResolver('jobCode', 'resolveJobCode')
        .enabled(true)
        .defaultView(views.templateView('shortUrl/manageUrlJob'))
        .addMethod('GET', 'manageUrlJob')
        .addMethod('POST', 'saveJobDetails', 'details')
        .addMethod('POST', 'generateShortCode')
        .addMethod('DELETE', 'deleteUrlJob')
        .build();

controllerMappings
        .adminController()
        .path('/shortUrl/(?<jobCode>[^/]*)/_historicData$')
        .addPathResolver('jobCode', 'resolveJobCode')
        .enabled(true)
        .addMethod('GET', 'urlJobHistoricData')
        .build();

/* Manage URL Code for a website Redirect */
controllerMappings
        .adminController()
        .path('/shortUrl/(?<jobCode>[^/]*)$')
        .addPathResolver('jobCode', 'resolveJobCode')
        .enabled(true)
        .addMethod('GET', 'checkRedirect')
        .addMethod('DELETE', 'deleteUrlJob')
        .build();

/* Manage URL Code */
controllerMappings
        .adminController()
        .path('/shortUrl/(?<jobCode>[^/]*)/(?<urlCode>[^/]*)/$')
        .addPathResolver('jobCode', 'resolveJobCode')
        .addPathResolver('urlCode', 'resolveUrlCode')
        .enabled(true)
        .defaultView(views.templateView('shortUrl/manageUrlCode'))
        .addMethod('POST', 'updateCodeDetails', 'details')
        .addMethod('DELETE', 'deleteUrlCode')
        .build();

controllerMappings
        .adminController()
        .path('/shortUrl/(?<jobCode>[^/]*)/(?<urlCode>[^/]*)/_historicData$')
        .addPathResolver('jobCode', 'resolveJobCode')
        .addPathResolver('urlCode', 'resolveUrlCode')
        .enabled(true)
        .addMethod('GET', 'urlCodeHistoricData')
        .build();

/* Manage URL Code Redirect */
controllerMappings
        .adminController()
        .path('/shortUrl/(?<jobCode>[^/]*)/(?<urlCode>[^/]*)$')
        .addPathResolver('jobCode', 'resolveJobCode')
        .addPathResolver('urlCode', 'resolveUrlCode')
        .enabled(true)
        .addMethod('GET', 'checkRedirect')
        .addMethod('DELETE', 'deleteUrlCode')
        .build();

/********************************
 ***   Website Controllers    ***
 ********************************/
controllerMappings
        .websiteController()
        .path('/(?<urlCode>.*)')
        .enabled(true)
        .isPublic(true)
        .addPathResolver('urlCode', 'resolveUrlCode')
        .addMethod('GET', 'serveUrlCode')
        .build();

/* Save app settings */
var saveSettings = function (page, params, files) {
    var anonUser = safeString(params.anonUser);

    var org = page.closest('organisation');
    var orgData = org.orgData;

    var p = orgData.findProfile(anonUser);

    if (isNotNull(p)) {
        page.setAppSetting(APP_ID, "anonUser", anonUser);

        return views.jsonResult(true);
    } else {
        return views.jsonResult(false, 'a User with the userId or email "' + anonUser + '" could not be found.');
    }
};

var onAppEnabled = function (orf, wrf) {
    var db = getOrCreateUrlDb(orf);
    db.updateTypeMappings(RECORD_TYPES.ACCESS_LOG, JSON.stringify(accessLogsMappings));
};