text:
using NLog.Config;

namespace NLog.UnitTests.Layouts
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using NLog.Layouts;
    using NLog.Targets;
    using Xunit;

    public class JsonLayoutTests : NLogTestBase
    {
        private const string ExpectedIncludeAllPropertiesWithExcludes = "{ \"StringProp\": \"ValueA\", \"IntProp\": 123, \"DoubleProp\": 123.123, \"DecimalProp\": 123.123, \"BoolProp\": true, \"NullProp\": null, \"DateTimeProp\": \"2345-01-23T12:34:56Z\" }";
        private const string ExpectedExcludeEmptyPropertiesWithExcludes = "{ \"StringProp\": \"ValueA\", \"IntProp\": 123, \"DoubleProp\": 123.123, \"DecimalProp\": 123.123, \"BoolProp\": true, \"DateTimeProp\": \"2345-01-23T12:34:56Z\", \"NoEmptyProp4\": \"hello\" }";

        [Fact]
        public void JsonLayoutRendering()
        {
            var jsonLayout = new JsonLayout()
            {
                Attributes =
                    {
                        new JsonAttribute("date", "${longdate}"),
                        new JsonAttribute("level", "${level}"),
                        new JsonAttribute("message", "${message}"),
                    }
            };

            var logEventInfo = new LogEventInfo
            {
                TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
                Level = LogLevel.Info,
                Message = "hello, world"
            };

            Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"hello, world\" }", jsonLayout.Render(logEventInfo));
        }

        [Fact]
        public void JsonLayoutRenderingNoSpaces()
        {
            var jsonLayout = new JsonLayout()
            {
                Attributes =
                    {
                        new JsonAttribute("date", "${longdate}"),
                        new JsonAttribute("level", "${level}"),
                        new JsonAttribute("message", "${message}"),
                    },
                SuppressSpaces = true
            };

            var logEventInfo = new LogEventInfo
            {
                TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
                Level = LogLevel.Info,
                Message = "hello, world"
            };

            Assert.Equal("{\"date\":\"2010-01-01 12:34:56.0000\",\"level\":\"Info\",\"message\":\"hello, world\"}", jsonLayout.Render(logEventInfo));
        }

        [Fact]
        public void JsonLayoutRenderingEscapeUnicode()
        {
            var jsonLayout = new JsonLayout()
            {
                Attributes =
                    {
                        new JsonAttribute("logger", "${logger}") { EscapeUnicode = true },
                        new JsonAttribute("level", "${level}"),
                        new JsonAttribute("message", "${event-properties:msg}") { EscapeUnicode = false },
                    },
                SuppressSpaces = true,
                IncludeEventProperties = true,
            };

            var logEventInfo = LogEventInfo.Create(LogLevel.Info, "\u00a9", null, "{$a}", new object[] { "\\" });
            logEventInfo.Properties["msg"] = "\u00a9";
            Assert.Equal("{\"logger\":\"\\u00a9\",\"level\":\"Info\",\"message\":\"\u00a9\",\"a\":\"\\\\\",\"msg\":\"\u00a9\"}", jsonLayout.Render(logEventInfo));
        }

        [Fact]
        public void JsonLayoutRenderingAndEncodingSpecialCharacters()
        {
            var jsonLayout = new JsonLayout()
            {
                Attributes =
                    {
                        new JsonAttribute("date", "${longdate}"),
                        new JsonAttribute("level", "${level}"),
                        new JsonAttribute("message", "${message}"),
                    }
            };

            var logEventInfo = new LogEventInfo
            {
                TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
                Level = LogLevel.Info,
                Message = "\"hello, world\""
            };

            Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"\\\"hello, world\\\"\" }", jsonLayout.Render(logEventInfo));
        }

        [Fact]
        public void JsonLayoutRenderingAndEncodingLineBreaks()
        {
            var jsonLayout = new JsonLayout()
            {
                Attributes =
                    {
                        new JsonAttribute("date", "${longdate}"),
                        new JsonAttribute("level", "${level}"),
                        new JsonAttribute("message", "${message}"),
                    }
            };

            var logEventInfo = new LogEventInfo
            {
                TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
                Level = LogLevel.Info,
                Message = "hello,\n\r world"
            };

            Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"hello,\\n\\r world\" }", jsonLayout.Render(logEventInfo));
        }

        [Fact]
        public void JsonLayoutRenderingAndNotEncodingMessageAttribute()
        {
            var jsonLayout = new JsonLayout()
            {
                Attributes =
                    {
                        new JsonAttribute("date", "${longdate}"),
                        new JsonAttribute("level", "${level}"),
                        new JsonAttribute("message", "${message}", false),
                    }
            };

            var logEventInfo = new LogEventInfo
            {
                TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
                Level = LogLevel.Info,
                Message = "{ \"hello\" : \"world\" }"
            };

            Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": { \"hello\" : \"world\" } }", jsonLayout.Render(logEventInfo));
        }

        [Fact]
        public void JsonLayoutRenderingAndEncodingMessageAttribute()
        {
            var jsonLayout = new JsonLayout()
            {
                Attributes =
                    {
                        new JsonAttribute("date", "${longdate}"),
                        new JsonAttribute("level", "${level}"),
                        new JsonAttribute("message", "${message}"),
                    }
            };

            var logEventInfo = new LogEventInfo
            {
                TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
                Level = LogLevel.Info,
                Message = "{ \"hello\" : \"world\" }"
            };

            Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"{ \\\"hello\\\" : \\\"world\\\" }\" }", jsonLayout.Render(logEventInfo));
        }

        [Fact]
        public void JsonLayoutValueTypeAttribute()
        {
            var jsonLayout = new JsonLayout()
            {
                Attributes =
                    {
                        new JsonAttribute("date", "${longdate}") { ValueType = typeof(DateTime) },
                        new JsonAttribute("level", "${level}"),
                        new JsonAttribute("message", "${message}"),
                    }
            };

            var logEventInfo = new LogEventInfo
            {
                TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
                Level = LogLevel.Info,
                Message = "{ \"hello\" : \"world\" }"
            };

            Assert.Equal("{ \"date\": \"2010-01-01T12:34:56Z\", \"level\": \"Info\", \"message\": \"{ \\\"hello\\\" : \\\"world\\\" }\" }", jsonLayout.Render(logEventInfo));
        }

        [Fact]
        public void JsonAttributeThreadAgnosticTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets async='true'>
                <target name='debug' type='Debug'>
                 <layout type='JsonLayout'>
                    <attribute name='type' layout='${exception:format=Type}'/>
                    <attribute name='message' layout='${exception:format=Message}'/>
                    <attribute name='threadid' layout='${threadid}'/>
                 </layout>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("B");

            var logEventInfo = CreateLogEventWithExcluded();

            logger.Debug(logEventInfo);

            var target = LogManager.Configuration.AllTargets.OfType<DebugTarget>().First();
            LogManager.Configuration = null;    // Flush

            var message = target.LastMessage;
            Assert.Contains(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), message);
        }

        [Fact]
        public void JsonAttributeStackTraceUsageTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='debug' type='Debug'  >
                 <layout type='JsonLayout'>
                    <attribute name='type' layout='${exception:format=Type}'/>
                    <attribute name='message' layout='${exception:format=Message}'/>
                    <attribute name='className' layout='${callsite:className=true}'/>
                 </layout>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("C");

            var logEventInfo = CreateLogEventWithExcluded();

            logger.Debug(logEventInfo);

            var message = GetDebugLastMessage("debug");
            Assert.Contains(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, message);
        }

        [Fact]
        public void NestedJsonAttrTest()
        {
            var jsonLayout = new JsonLayout
            {
                Attributes =
                {
                    new JsonAttribute("type", "${exception:format=Type}"),
                    new JsonAttribute("message", "${exception:format=Message}"),
                    new JsonAttribute("innerException", new JsonLayout
                    {

                        Attributes =
                        {
                            new JsonAttribute("type", "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                            new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                        }
                    },
                    //don't escape layout
                    false)
                }
            };

            var logEventInfo = new LogEventInfo
            {
                Exception = new NLogRuntimeException("test", new NullReferenceException("null is bad!"))
            };

            var json = jsonLayout.Render(logEventInfo);
            Assert.Equal("{ \"type\": \"NLog.NLogRuntimeException\", \"message\": \"test\", \"innerException\": { \"type\": \"System.NullReferenceException\", \"message\": \"null is bad!\" } }", json);

        }

        [Fact]
        public void NestedJsonAttrDoesNotRenderEmptyLiteralIfRenderEmptyObjectIsFalseTest()
        {
            var jsonLayout = new JsonLayout
            {
                Attributes =
                {
                    new JsonAttribute("type", "${exception:format=Type}"),
                    new JsonAttribute("message", "${exception:format=Message}"),
                    new JsonAttribute("innerException", new JsonLayout
                    {

                        Attributes =
                        {
                            new JsonAttribute("type", "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                            new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                        },
                        RenderEmptyObject = false
                    },
                    //don't escape layout
                    false)
                }
            };

            var logEventInfo = new LogEventInfo
            {
                Exception = new NLogRuntimeException("test", (Exception)null)
            };

            var json = jsonLayout.Render(logEventInfo);
            Assert.Equal("{ \"type\": \"NLog.NLogRuntimeException\", \"message\": \"test\" }", json);

        }

        [Fact]
        public void NestedJsonAttrRendersEmptyLiteralIfRenderEmptyObjectIsTrueTest()
        {
            var jsonLayout = new JsonLayout
            {
                Attributes =
                {
                    new JsonAttribute("type", "${exception:format=Type}"),
                    new JsonAttribute("message", "${exception:format=Message}"),
                    new JsonAttribute("innerException", new JsonLayout
                    {

                        Attributes =
                        {
                            new JsonAttribute("type", "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                            new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                        },
                        RenderEmptyObject = true
                    },
                    //don't escape layout
                    false)
                }
            };

            var logEventInfo = new LogEventInfo
            {
                Exception = new NLogRuntimeException("test", (Exception)null)
            };

            var json = jsonLayout.Render(logEventInfo);
            Assert.Equal("{ \"type\": \"NLog.NLogRuntimeException\", \"message\": \"test\", \"innerException\": {  } }", json);

        }

        [Fact]
        public void NestedJsonAttrTestFromXML()
        {
            var configXml = @"
<nlog>
  <targets>
    <target name='jsonFile' type='File' fileName='log.json'>
      <layout type='JsonLayout'>
        <attribute name='time' layout='${longdate}' />
        <attribute name='level' layout='${level:upperCase=true}'/>
        <attribute name='nested' encode='false'  >
          <layout type='JsonLayout'>
            <attribute name='message' layout='${message}' />
            <attribute name='exception' layout='${exception:message}' />
          </layout>
        </attribute>
      </layout>
    </target>
  </targets>
  <rules>
  </rules>
</nlog>
";

            var config = XmlLoggingConfiguration.CreateFromXmlString(configXml);

            Assert.NotNull(config);
            var target = config.FindTargetByName<FileTarget>("jsonFile");
            Assert.NotNull(target);
            var jsonLayout = target.Layout as JsonLayout;
            Assert.NotNull(jsonLayout);
            var attrs = jsonLayout.Attributes;
            Assert.NotNull(attrs);
            Assert.Equal(3, attrs.Count);
            Assert.Equal(typeof(SimpleLayout), attrs[0].Layout.GetType());
            Assert.Equal(typeof(SimpleLayout), attrs[1].Layout.GetType());
            Assert.Equal(typeof(JsonLayout), attrs[2].Layout.GetType());
            var nestedJsonLayout = (JsonLayout)attrs[2].Layout;
            Assert.Equal(2, nestedJsonLayout.Attributes.Count);
            Assert.Equal("${message}", nestedJsonLayout.Attributes[0].Layout.ToString());
            Assert.Equal("${exception:message}", nestedJsonLayout.Attributes[1].Layout.ToString());

            var logEventInfo = new LogEventInfo
            {
                TimeStamp = new DateTime(2016, 10, 30, 13, 30, 55),
                Message = "this is message",
                Level = LogLevel.Info,
                Exception = new NLogRuntimeException("test", new NullReferenceException("null is bad!"))
            };

            var json = jsonLayout.Render(logEventInfo);
            Assert.Equal("{ \"time\": \"2016-10-30 13:30:55.0000\", \"level\": \"INFO\", \"nested\": { \"message\": \"this is message\", \"exception\": \"test\" } }", json);
        }

        [Fact]
        public void IncludeAllJsonProperties()
        {
            var jsonLayout = new JsonLayout()
            {
                IncludeEventProperties = true
            };

            jsonLayout.ExcludeProperties.Add("Excluded1");
            jsonLayout.ExcludeProperties.Add("Excluded2");

            var logEventInfo = CreateLogEventWithExcluded();

            Assert.Equal(ExpectedIncludeAllPropertiesWithExcludes, jsonLayout.Render(logEventInfo));
        }

        [Fact]
        public void PropertyKeyWithQuote()
        {
            var jsonLayout = new JsonLayout()
            {
                IncludeEventProperties = true,
            };

            var logEventInfo = new LogEventInfo();
            logEventInfo.Properties.Add(@"fo""o", "bar");
            Assert.Equal(@"{ ""fo\""o"": ""bar"" }", jsonLayout.Render(logEventInfo));
        }

        [Fact]
        public void AttributerKeyWithQuote()
        {
            var jsonLayout = new JsonLayout();
            jsonLayout.Attributes.Add(new JsonAttribute(@"fo""o", "bar"));

            Assert.Equal(@"{ ""fo\""o"": ""bar"" }", jsonLayout.Render(LogEventInfo.CreateNullEvent()));
        }

        [Fact]
        public void ExcludeEmptyJsonProperties()
        {
            var jsonLayout = new JsonLayout()
            {
                IncludeEventProperties = true,
                ExcludeEmptyProperties = true
            };

            jsonLayout.ExcludeProperties.Add("Excluded1");
            jsonLayout.ExcludeProperties.Add("Excluded2");

            var logEventInfo = CreateLogEventWithExcluded();
            logEventInfo.Properties.Add("EmptyProp", "");
            logEventInfo.Properties.Add("EmptyProp1", null);
            logEventInfo.Properties.Add("EmptyProp2", new DummyContextLogger() { Value = null });
            logEventInfo.Properties.Add("EmptyProp3", new DummyContextLogger() { Value = "" });
            logEventInfo.Properties.Add("NoEmptyProp4", new DummyContextLogger() { Value = "hello" });

            Assert.Equal(ExpectedExcludeEmptyPropertiesWithExcludes, jsonLayout.Render(logEventInfo));
        }

        [Fact]
        public void IncludeAllJsonPropertiesMaxRecursionLimit()
        {
            var jsonLayout = new JsonLayout()
            {
                IncludeEventProperties = true,
                MaxRecursionLimit = 1,
            };

            LogEventInfo logEventInfo = new LogEventInfo()
            {
                TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
                Level = LogLevel.Info,
            };
            logEventInfo.Properties["Message"] = new
            {
                data = new Dictionary<int, string>() { { 42, "Hello" } }
            };

            Assert.Equal(@"{ ""Message"": {""data"":{}} }", jsonLayout.Render(logEventInfo));
        }

        [Fact]
        [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
        public void IncludeMdcJsonProperties()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'>
                <target name='debug' type='Debug'  >
                 <layout type=""JsonLayout"" IncludeMdc='true' ExcludeProperties='Excluded1,Excluded2'>
                 </layout>
                </target>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='asyncDebug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("A");

            var logEventInfo = CreateLogEventWithExcluded();

            MappedDiagnosticsContext.Clear();
            foreach (var prop in logEventInfo.Properties)
                if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2")
                    MappedDiagnosticsContext.Set(prop.Key.ToString(), prop.Value);
            logEventInfo.Properties.Clear();

            logger.Debug(logEventInfo);

            LogManager.Flush();

            AssertDebugLastMessage("debug", ExpectedIncludeAllPropertiesWithExcludes);
        }

        [Fact]
        [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
        public void IncludeMdcNoEmptyJsonProperties()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'>
                <target name='debug' type='Debug'  >
                 <layout type=""JsonLayout"" IncludeMdc='true' ExcludeProperties='Excluded1,Excluded2' ExcludeEmptyProperties='true'>
                 </layout>
                </target>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='asyncDebug' />
                </rules>
            </nlog>");

            ILogger logger = LogManager.GetLogger("A");

            var logEventInfo = CreateLogEventWithExcluded();
            logEventInfo.Properties.Add("EmptyProp", "");
            logEventInfo.Properties.Add("EmptyProp1", null);
            logEventInfo.Properties.Add("EmptyProp2", new DummyContextLogger() { Value = null });
            logEventInfo.Properties.Add("EmptyProp3", new DummyContextLogger() { Value = "" });
            logEventInfo.Properties.Add("NoEmptyProp4", new DummyContextLogger() { Value = "hello" });

            MappedDiagnosticsContext.Clear();
            foreach (var prop in logEventInfo.Properties)
                if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2")
                    MappedDiagnosticsContext.Set(prop.Key.ToString(), prop.Value);
            logEventInfo.Properties.Clear();

            logger.Debug(logEventInfo);

            LogManager.Flush();

            AssertDebugLastMessage("debug", ExpectedExcludeEmptyPropertiesWithExcludes);
        }

        [Fact]
        public void IncludeGdcJsonProperties()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'>
                <target name='debug' type='Debug'  >
                 <layout type=""JsonLayout"" IncludeGdc='true' ExcludeProperties='Excluded1,Excluded2'>
                 </layout>
                </target>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='asyncDebug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("A");

            var logEventInfo = CreateLogEventWithExcluded();

            GlobalDiagnosticsContext.Clear();
            foreach (var prop in logEventInfo.Properties)
                if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2")
                    GlobalDiagnosticsContext.Set(prop.Key.ToString(), prop.Value);
            logEventInfo.Properties.Clear();

            logger.Debug(logEventInfo);

            LogManager.Flush();

            AssertDebugLastMessage("debug", ExpectedIncludeAllPropertiesWithExcludes);
        }

        [Fact]
        public void IncludeGdcNoEmptyJsonProperties()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'>
                <target name='debug' type='Debug'  >
                 <layout type=""JsonLayout"" IncludeGdc='true' ExcludeProperties='Excluded1,Excluded2' ExcludeEmptyProperties='true'>
                 </layout>
                </target>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='asyncDebug' />
                </rules>
            </nlog>");

            ILogger logger = LogManager.GetLogger("A");

            var logEventInfo = CreateLogEventWithExcluded();
            logEventInfo.Properties.Add("EmptyProp", "");
            logEventInfo.Properties.Add("EmptyProp1", null);
            logEventInfo.Properties.Add("EmptyProp2", new DummyContextLogger() { Value = null });
            logEventInfo.Properties.Add("EmptyProp3", new DummyContextLogger() { Value = "" });
            logEventInfo.Properties.Add("NoEmptyProp4", new DummyContextLogger() { Value = "hello" });

            GlobalDiagnosticsContext.Clear();
            foreach (var prop in logEventInfo.Properties)
                if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2")
                    GlobalDiagnosticsContext.Set(prop.Key.ToString(), prop.Value);
            logEventInfo.Properties.Clear();

            logger.Debug(logEventInfo);

            LogManager.Flush();

            AssertDebugLastMessage("debug", ExpectedExcludeEmptyPropertiesWithExcludes);
        }

        [Fact]
        [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
        public void IncludeMdlcJsonProperties()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'>
                <target name='debug' type='Debug'  >
                 <layout type=""JsonLayout"" IncludeMdlc='true' ExcludeProperties='Excluded1,Excluded2'>
                 </layout>
                </target>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='asyncDebug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("A");

            var logEventInfo = CreateLogEventWithExcluded();

            MappedDiagnosticsLogicalContext.Clear();
            foreach (var prop in logEventInfo.Properties)
                if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2")
                    MappedDiagnosticsLogicalContext.Set(prop.Key.ToString(), prop.Value);
            logEventInfo.Properties.Clear();

            logger.Debug(logEventInfo);

            LogManager.Flush();

            AssertDebugLastMessage("debug", ExpectedIncludeAllPropertiesWithExcludes);
        }

        [Fact]
        [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
        public void IncludeMdlcNoEmptyJsonProperties()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'>
                <target name='debug' type='Debug'  >
                 <layout type=""JsonLayout"" IncludeMdlc='true' ExcludeProperties='Excluded1,Excluded2' ExcludeEmptyProperties='true'>
                 </layout>
                </target>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='asyncDebug' />
                </rules>
            </nlog>");

            ILogger logger = LogManager.GetLogger("A");

            var logEventInfo = CreateLogEventWithExcluded();
            logEventInfo.Properties.Add("EmptyProp", "");
            logEventInfo.Properties.Add("EmptyProp1", null);
            logEventInfo.Properties.Add("EmptyProp2", new DummyContextLogger() { Value = null });
            logEventInfo.Properties.Add("EmptyProp3", new DummyContextLogger() { Value = "" });
            logEventInfo.Properties.Add("NoEmptyProp4", new DummyContextLogger() { Value = "hello" });

            MappedDiagnosticsLogicalContext.Clear();
            foreach (var prop in logEventInfo.Properties)
                if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2")
                    MappedDiagnosticsLogicalContext.Set(prop.Key.ToString(), prop.Value);
            logEventInfo.Properties.Clear();

            logger.Debug(logEventInfo);

            LogManager.Flush();

            AssertDebugLastMessage("debug", ExpectedExcludeEmptyPropertiesWithExcludes);
        }

        [Fact]
        [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")]
        public void IncludeMdlcJsonNestedProperties()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='asyncDebug' type='AsyncWrapper' timeToSleepBetweenBatches='0'>
                    <target name='debug' type='Debug'>
                        <layout type='JsonLayout'>
                            <attribute name='scope' encode='false' >
                                <layout type='JsonLayout' includeMdlc='true' />
                            </attribute>
                        </layout>
                    </target>
                </target>
                </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='asyncDebug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("A");

            var logEventInfo = CreateLogEventWithExcluded();

            MappedDiagnosticsLogicalContext.Clear();
            foreach (var prop in logEventInfo.Properties)
                if (prop.Key.ToString() != "Excluded1" && prop.Key.ToString() != "Excluded2")
                    MappedDiagnosticsLogicalContext.Set(prop.Key.ToString(), prop.Value);
            logEventInfo.Properties.Clear();

            logger.Debug(logEventInfo);

            LogManager.Flush();

            AssertDebugLastMessageContains("debug", ExpectedIncludeAllPropertiesWithExcludes);
        }

        /// <summary>
        /// Test from XML, needed for the list (ExcludeProperties)
        /// </summary>
        [Fact]
        public void IncludeAllJsonPropertiesXml()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='debug' type='Debug'  >
                 <layout type=""JsonLayout"" IncludeAllProperties='true' ExcludeProperties='Excluded1,EXCLUDED2'>

                 </layout>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("A");

            var logEventInfo = CreateLogEventWithExcluded();

            logger.Debug(logEventInfo);

            AssertDebugLastMessage("debug", ExpectedIncludeAllPropertiesWithExcludes);
        }

        [Fact]
        public void IncludeAllJsonPropertiesMutableXml()
        {
            // Arrange
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
                <targets>
                    <target name='asyncDebug' type='BufferingWrapper'>
                        <target name='debug' type='Debug'>
                            <layout type='JsonLayout' IncludeAllProperties='true' ExcludeProperties='Excluded1,Excluded2' maxRecursionLimit='0' />
                        </target>
                    </target>
                </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='asyncDebug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("A");

            // Act
            var logEventInfo = CreateLogEventWithExcluded();
            var stringPropBuilder = new System.Text.StringBuilder(logEventInfo.Properties["StringProp"].ToString());
            logEventInfo.Properties["StringProp"] = stringPropBuilder;
            logger.Debug(logEventInfo);
            stringPropBuilder.Clear();

            LogManager.Flush();

            // Assert
            AssertDebugLastMessage("debug", ExpectedIncludeAllPropertiesWithExcludes);
        }

        [Fact]
        public void IncludeAllJsonPropertiesMutableNestedXml()
        {
            // Arrange
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
                <targets>
                    <target name='asyncDebug' type='BufferingWrapper'>
                        <target name='debug' type='Debug'>
                            <layout type='JsonLayout' maxRecursionLimit='0'>
                                <attribute name='properties' encode='false' >
                                    <layout type='JsonLayout' IncludeAllProperties='true' ExcludeProperties='Excluded1,Excluded2' maxRecursionLimit='0'/>
                                </attribute>
                            </layout>
                        </target>
                    </target>
                </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='asyncDebug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("A");

            // Act
            var logEventInfo = CreateLogEventWithExcluded();
            var stringPropBuilder = new System.Text.StringBuilder(logEventInfo.Properties["StringProp"].ToString());
            logEventInfo.Properties["StringProp"] = stringPropBuilder;
            logger.Debug(logEventInfo);
            stringPropBuilder.Clear();

            LogManager.Flush();

            // Assert
            AssertDebugLastMessageContains("debug", ExpectedIncludeAllPropertiesWithExcludes);
        }

        /// <summary>
        /// Serialize object deep
        /// </summary>
        [Fact]
        public void SerializeObjectRecursionSingle()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='debug' type='Debug'  >
                 <layout type=""JsonLayout"" IncludeAllProperties='true' maxRecursionLimit='1' >
                 </layout>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("A");

            var logEventInfo1 = new LogEventInfo();

            logEventInfo1.Properties.Add("nestedObject", new List<object> { new { val = 1, val2 = "value2" }, new { val3 = 3, val4 = "value4" } });

            logger.Debug(logEventInfo1);

            AssertDebugLastMessage("debug", "{ \"nestedObject\": [{\"val\":1, \"val2\":\"value2\"},{\"val3\":3, \"val4\":\"value4\"}] }");

            var logEventInfo2 = new LogEventInfo();

            logEventInfo2.Properties.Add("nestedObject", new { val = 1, val2 = "value2" });

            logger.Debug(logEventInfo2);

            AssertDebugLastMessage("debug", "{ \"nestedObject\": {\"val\":1, \"val2\":\"value2\"} }");

            var logEventInfo3 = new LogEventInfo();

            logEventInfo3.Properties.Add("nestedObject", new List<object> { new List<object> { new { val = 1, val2 = "value2" } } });

            logger.Debug(logEventInfo3);

            AssertDebugLastMessage("debug", "{ \"nestedObject\": [[\"{ val = 1, val2 = value2 }\"]] }");  // Allows nested collection, but then only ToString
        }

        [Fact]
        public void SerializeObjectRecursionZero()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='debug' type='Debug'  >
                 <layout type=""JsonLayout"" IncludeAllProperties='true' maxRecursionLimit='0' >
                 </layout>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("A");

            var logEventInfo1 = new LogEventInfo();

            logEventInfo1.Properties.Add("nestedObject", new List<object> { new { val = 1, val2 = "value2" }, new { val3 = 3, val4 = "value5" } });

            logger.Debug(logEventInfo1);

            AssertDebugLastMessage("debug", "{ \"nestedObject\": [\"{ val = 1, val2 = value2 }\",\"{ val3 = 3, val4 = value5 }\"] }");  // Allows single collection recursion

            var logEventInfo2 = new LogEventInfo();

            logEventInfo2.Properties.Add("nestedObject", new { val = 1, val2 = "value2" });

            logger.Debug(logEventInfo2);

            AssertDebugLastMessage("debug", "{ \"nestedObject\": \"{ val = 1, val2 = value2 }\" }");    // Never object recursion, only ToString

            var logEventInfo3 = new LogEventInfo();

            logEventInfo3.Properties.Add("nestedObject", new List<object> { new List<object> { new { val = 1, val2 = "value2" } } });

            logger.Debug(logEventInfo3);

            AssertDebugLastMessage("debug", "{ \"nestedObject\": [[]] }");  // No support for nested collections
        }

        [Fact]
        public void EncodesInvalidCharacters()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='debug' type='Debug'  >
                 <layout type=""JsonLayout"" IncludeAllProperties='true' escapeForwardSlash='true'>
                 </layout>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("A");

            var logEventInfo1 = new LogEventInfo();

            logEventInfo1.Properties.Add("InvalidCharacters", "|#{}%&\"~+\\/:*?<>".ToCharArray());

            logger.Debug(logEventInfo1);

            AssertDebugLastMessage("debug", "{ \"InvalidCharacters\": [\"|\",\"#\",\"{\",\"}\",\"%\",\"&\",\"\\\"\",\"~\",\"+\",\"\\\\\",\"\\/\",\":\",\"*\",\"?\",\"<\",\">\"] }");
        }

        [Fact]
        public void EncodesInvalidDoubles()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='debug' type='Debug'  >
                 <layout type=""JsonLayout"" IncludeAllProperties='true' >
                 </layout>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("A");

            var logEventInfo1 = new LogEventInfo();

            logEventInfo1.Properties.Add("DoubleNaN", double.NaN);
            logEventInfo1.Properties.Add("DoubleInfPositive", double.PositiveInfinity);
            logEventInfo1.Properties.Add("DoubleInfNegative", double.NegativeInfinity);
            logEventInfo1.Properties.Add("FloatNaN", float.NaN);
            logEventInfo1.Properties.Add("FloatInfPositive", float.PositiveInfinity);
            logEventInfo1.Properties.Add("FloatInfNegative", float.NegativeInfinity);

            logger.Debug(logEventInfo1);

            AssertDebugLastMessage("debug", "{ \"DoubleNaN\": \"NaN\", \"DoubleInfPositive\": \"Infinity\", \"DoubleInfNegative\": \"-Infinity\", \"FloatNaN\": \"NaN\", \"FloatInfPositive\": \"Infinity\", \"FloatInfNegative\": \"-Infinity\" }");
        }

        [Fact]
        public void EscapeForwardSlashDefaultTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets>
                <target name='debug' type='Debug'  >
                  <layout type='JsonLayout' escapeForwardSlash='false' includeAllProperties='true'>
                    <attribute name='myurl1' layout='${event-properties:myurl}' />
                    <attribute name='myurl2' layout='${event-properties:myurl}' escapeForwardSlash='true' />
                  </layout>
                </target>
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            var logger = LogManager.GetLogger("A");

            var logEventInfo1 = new LogEventInfo();
            logEventInfo1.Properties.Add("myurl", "http://hello.world.com/");
            logger.Debug(logEventInfo1);

            AssertDebugLastMessage("debug", "{ \"myurl1\": \"http://hello.world.com/\", \"myurl2\": \"http:\\/\\/hello.world.com\\/\", \"myurl\": \"http://hello.world.com/\" }");
        }

        [Fact]
        public void SkipInvalidJsonPropertyValues()
        {
            var jsonLayout = new JsonLayout() { IncludeEventProperties = true };

            var logEventInfo = new LogEventInfo
            {
                TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
                Level = LogLevel.Info,
                Message = string.Empty,
            };

            var expectedValue = Guid.NewGuid();
            logEventInfo.Properties["BadObject"] = new BadObject();
            logEventInfo.Properties["RequestId"] = expectedValue;

            Assert.Equal($"{{ \"RequestId\": \"{expectedValue}\" }}", jsonLayout.Render(logEventInfo));
        }

        class BadObject : IFormattable
        {
            public string ToString(string format, IFormatProvider formatProvider)
            {
                throw new ApplicationException("BadObject");
            }

            public override string ToString()
            {
                return ToString(null, null);
            }
        }

        private static LogEventInfo CreateLogEventWithExcluded()
        {
            var logEventInfo = new LogEventInfo
            {
                TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
                Level = LogLevel.Info,
                Message = "hello, world"
            };

            logEventInfo.Properties.Add("StringProp", "ValueA");
            logEventInfo.Properties.Add("IntProp", 123);
            logEventInfo.Properties.Add("DoubleProp", 123.123);
            logEventInfo.Properties.Add("DecimalProp", 123.123m);
            logEventInfo.Properties.Add("BoolProp", true);
            logEventInfo.Properties.Add("NullProp", null);
            logEventInfo.Properties.Add("DateTimeProp", new DateTime(2345, 1, 23, 12, 34, 56, DateTimeKind.Utc));
            logEventInfo.Properties.Add("Excluded1", "ExcludedValue");
            logEventInfo.Properties.Add("Excluded2", "Also excluded");
            return logEventInfo;
        }

        public class DummyContextLogger
        {
            internal string Value { get; set; }

            public override string ToString()
            {
                return Value;
            }
        }
    }
}


text:
import ast
import re

class OS(object):
    """
    Class that parses either /etc/os-release or the output of 'lsb_release -a'
    and provides OS name and version information.

    Must be initialized with OS.from_lsb_release or OS.from_os_release
    """

    __slots__ = ['name', 'version', 'codename', 'package_type']

    _deb_distros = ('debian', 'ubuntu')
    _rpm_distros = ('fedora', 'rhel', 'centos', 'suse')

    def __init__(self, name=None, version=None, codename=None):
        self.name = name
        self.version = version
        self.codename = codename
        self._set_package_type()

    @classmethod
    def from_python(cls, python_val):
        """
        Parse output from platform.linux_distribution() and populate attributes

        Given a tuple or str()'ed tuple like this:
            ('Ubuntu', '14.04', 'trusty')

        Attributes will be:
            name = 'ubuntu'
            version = '14.04'
            codename = 'trusty'
        Additionally, we set the package type:
            package_type = 'deb'
        """
        if not isinstance(python_val, tuple):
            python_val = ast.literal_eval(python_val)

        (name, version, codename) = python_val
        name = name.lower().replace(' ', '')
        if name.startswith('redhat'):
            name = 'rhel'
        elif name.startswith('centos'):
            name = 'centos'
        elif name.startswith('fedora'):
            name = 'fedora'
        obj = cls()
        obj.name = name
        obj.version = version
        obj.codename = codename.lower()
        obj._set_package_type()
        return obj

    @classmethod
    def from_lsb_release(cls, lsb_release_str):
        """
        Parse output from lsb_release -a and populate attributes

        Given output like:
            Distributor ID: Ubuntu
            Description:    Ubuntu 12.04.4 LTS
            Release:        12.04
            Codename:       precise

        Attributes will be:
            name = 'ubuntu'
            version = '12.04'
            codename = 'precise'
        Additionally, we set the package type:
            package_type = 'deb'
        """
        obj = cls()
        str_ = lsb_release_str.strip()
        name = obj._get_value(str_, 'Distributor ID')
        if name == 'RedHatEnterpriseServer':
            name = 'rhel'
        obj.name = name.lower()

        obj.version = obj._get_value(str_, 'Release')
        obj.codename = obj._get_value(str_, 'Codename').lower()

        obj._set_package_type()

        return obj

    @classmethod
    def from_os_release(cls, os_release_str):
        """
        Parse /etc/os-release and populate attributes

        Given output like:
            NAME="Ubuntu"
            VERSION="12.04.4 LTS, Precise Pangolin"
            ID=ubuntu
            ID_LIKE=debian
            PRETTY_NAME="Ubuntu precise (12.04.4 LTS)"
            VERSION_ID="12.04"

        Attributes will be:
            name = 'ubuntu'
            version = '12.04'
            codename = None
        Additionally, we set the package type:
            package_type = 'deb'
        """
        obj = cls()
        str_ = os_release_str.strip()
        obj.name = cls._get_value(str_, 'ID').lower()
        obj.version = cls._get_value(str_, 'VERSION_ID')
        obj.codename = None

        obj._set_package_type()

        return obj

    @staticmethod
    def _get_value(str_, name):
        regex = '^%s[:=](.+)' % name
        match = re.search(regex, str_, flags=re.M)
        if match:
            return match.groups()[0].strip(' \t"\'')
        return ''

    def _set_package_type(self):
        if self.name in self._deb_distros:
            self.package_type = "deb"
        elif self.name in self._rpm_distros:
            self.package_type = "rpm"

    def to_dict(self):
        return dict(
            name=self.name,
            version=self.version,
            codename=self.codename,
        )

    def __str__(self):
        return " ".join([self.name, self.version]).strip()

    def __repr__(self):
        return "OS(name={name}, version={version}, codename={codename})"\
            .format(name=repr(self.name),
                    version=repr(self.version),
                    codename=repr(self.codename))

redpajama_set_name: RedPajamaGithub


text:
{% extends "server/computer_info.html" %}
{% block button %}
        {% if not perms.server.can_approve %}
            {% if can_request %}
            Request Key
            {% else %}
            <button class="btn btn-disabled btn-info">Request Pending</button>
            {% endif %}
            {% else %}
            Get Key
        {% endif %}
{% endblock %}


text:
package rp

import (
	"github.com/google/go-cmp/cmp"
	"github.com/watermint/toolbox/infra/control/app_control"
	"github.com/watermint/toolbox/infra/report/rp_writer_impl"
	"github.com/watermint/toolbox/quality/recipe/qtr_endtoend"
	"testing"
)

func TestNewSmallCache(t *testing.T) {
	qtr_endtoend.TestWithControl(t, func(ctl app_control.Control) {
		w := rp_writer_impl.NewMock()
		scw := rp_writer_impl.NewSmallCacheWithThreshold("small_cache_test", w, 3)
		if err := scw.Open(ctl, &rp_writer_impl.MockRecord{}); err != nil {
			t.Error(err)
			return
		}

		if x := len(w.Records()); x != 0 {
			t.Error(x)
		}

		records := []interface{}{
			&rp_writer_impl.MockRecord{SKU: "A001", Quantity: 23},
			&rp_writer_impl.MockRecord{SKU: "A005", Quantity: 48},
			&rp_writer_impl.MockRecord{SKU: "A007", Quantity: 65},
			&rp_writer_impl.MockRecord{SKU: "A013", Quantity: 79},
		}

		// write until threshold
		for i := 0; i < 3; i++ {
			scw.Row(records[i])
			if x := len(w.Records()); x != 0 {
				t.Error(x)
			}
		}

		scw.Row(records[3])

		wroteRecords := w.Records()
		if x := cmp.Diff(records, wroteRecords); x != "" {
			t.Error(x)
		}
	})
}

func TestNewSmallCacheCloseBeforeThreshold(t *testing.T) {
	qtr_endtoend.TestWithControl(t, func(ctl app_control.Control) {
		w := rp_writer_impl.NewMock()
		scw := rp_writer_impl.NewSmallCacheWithThreshold("small_cache_test", w, 10)
		if err := scw.Open(ctl, &rp_writer_impl.MockRecord{}); err != nil {
			t.Error(err)
			return
		}

		if x := len(w.Records()); x != 0 {
			t.Error(x)
		}

		records := []interface{}{
			&rp_writer_impl.MockRecord{SKU: "A001", Quantity: 23},
			&rp_writer_impl.MockRecord{SKU: "A005", Quantity: 48},
			&rp_writer_impl.MockRecord{SKU: "A007", Quantity: 65},
			&rp_writer_impl.MockRecord{SKU: "A013", Quantity: 79},
		}

		// write until threshold
		for _, record := range records {
			scw.Row(record)
		}
		scw.Close()

		wroteRecords := w.Records()
		if x := cmp.Diff(records, wroteRecords); x != "" {
			t.Error(x)
		}
	})
}


text:
namespace NutzCode.CloudFileSystem.Plugins.OneDrive
{
    public class OneDriveRoot : OneDriveDirectory
    {
        public override string Id => "";
        internal string FsName=string.Empty;

        public OneDriveRoot(OneDriveFileSystem fs) : base(string.Empty, fs)
        {
            IsRoot = true;
        }

        public override string Name => FsName;

    }
}


text:
from __future__ import absolute_import

# Import 3rd-party libs
import salt.ext.six as six

# define the module's virtual name
__virtualname__ = 'sysrc'

def __virtual__():
    '''
    Only load if sysrc executable exists
    '''
    return __salt__['cmd.has_exec']('sysrc')

def managed(name, value, **kwargs):
    '''
    Ensure a sysrc variable is set to a specific value.

    name
        The variable name to set
    value
        Value to set the variable to
    file
        (optional) The rc file to add the variable to.
    jail
        (option) the name or JID of the jail to set the value in.
    '''

    ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}

    # Check the current state
    current_state = __salt__['sysrc.get'](name=name, **kwargs)
    if current_state is not None:
        for rcname, rcdict in six.iteritems(current_state):
            if rcdict[name] == value:
                ret['result'] = True
                ret['comment'] = '{0} is already set to the desired value.'.format(name)
                return ret

    if __opts__['test'] is True:
        ret['comment'] = 'The value of "{0}" will be changed!'.format(name)
        ret['changes'] = {
            'old': current_state,
            'new': name+' = '+value+' will be set.'
        }

        # When test=true return none
        ret['result'] = None

        return ret

    new_state = __salt__['sysrc.set'](name=name, value=value, **kwargs)

    ret['comment'] = 'The value of "{0}" was changed!'.format(name)

    ret['changes'] = {
        'old': current_state,
        'new': new_state
    }

    ret['result'] = True

    return ret

def absent(name, **kwargs):
    '''
    Ensure a sysrc variable is absent.

    name
        The variable name to set
    file
        (optional) The rc file to add the variable to.
    jail
        (option) the name or JID of the jail to set the value in.
    '''

    ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}

    # Check the current state
    current_state = __salt__['sysrc.get'](name=name, **kwargs)
    if current_state is None:
        ret['result'] = True
        ret['comment'] = '"{0}" is already absent.'.format(name)
        return ret

    if __opts__['test'] is True:
        ret['comment'] = '"{0}" will be removed!'.format(name)
        ret['changes'] = {
            'old': current_state,
            'new': '"{0}" will be removed.'.format(name)
        }

        # When test=true return none
        ret['result'] = None

        return ret

    new_state = __salt__['sysrc.remove'](name=name, **kwargs)

    ret['comment'] = '"{0}" was removed!'.format(name)

    ret['changes'] = {
        'old': current_state,
        'new': new_state
    }

    ret['result'] = True

    return ret


text:
package net.dsys.snio.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import net.dsys.snio.api.buffer.MessageBufferConsumer;
import net.dsys.snio.api.channel.MessageChannel;
import net.dsys.snio.api.pool.SelectorPool;
import net.dsys.snio.impl.channel.MessageChannels;
import net.dsys.snio.impl.channel.builder.ChannelConfig;
import net.dsys.snio.impl.channel.builder.ClientConfig;
import net.dsys.snio.impl.handler.MessageHandlers;
import net.dsys.snio.impl.pool.SelectorPools;

/**
 * Oneway echo server using UDP.
 *
 * @author Ricardo Padilha
 */
public final class UDPOnewayServer {

	private UDPOnewayServer() {
		return;
	}

	public static void main(final String[] args) throws IOException, InterruptedException, ExecutionException {
		final int threads = Integer.parseInt(getArg("threads", "1", args));
		final int buffers = Integer.parseInt(getArg("buffers", "256", args));
		final int length = Integer.parseInt(getArg("length", "1024", args));
		final int port = Integer.parseInt(getArg("port", "12345", args));

		final SelectorPool pool = SelectorPools.open("server", threads);
		final ChannelConfig<ByteBuffer> common = new ChannelConfig<ByteBuffer>()
				.setPool(pool)
				.setBufferCapacity(buffers)
				.useRingBuffer();
		final ClientConfig server = new ClientConfig()
				.setMessageLength(length);
		final MessageChannel<ByteBuffer> channel = MessageChannels.openUDPChannel(common, server);

		channel.bind(new InetSocketAddress(port));
		channel.getBindFuture().get();

		final MessageBufferConsumer<ByteBuffer> in = channel.getInputBuffer();

		// one thread per client
		final ExecutorService executor = Executors.newCachedThreadPool(); // unbounded!
		executor.execute(MessageHandlers.syncConsumer(in, new EchoConsumer()));

		pool.getCloseFuture().get();
		executor.shutdown();
	}

	private static String getArg(final String name, final String defaultValue, final String[] args) {
		if (args == null || name == null) {
			return defaultValue;
		}
		final String key = "--" + name;
		final int k = args.length - 1;
		for (int i = 0; i < k; i++) {
			if (key.equals(args[i])) {
				return args[i + 1];
			}
		}
		return defaultValue;
	}
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Flora, Jena 71: 24 (1888)

#### Original name
Sticta leylandii Taylor

### Remarks
null


text:
package in.kvineet.bigdata.ghcn_mapreduce;

import java.io.IOException;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import in.kvineet.bigdata.ghcn_mapreduce.io.WeatherDataWritable;

public class GcdnReducer extends Reducer<Text, WeatherDataWritable, NullWritable, WeatherDataWritable>{

	private static WeatherDataWritable max=null;

	@Override
	protected void reduce(Text key, Iterable<WeatherDataWritable> value,
			Reducer<Text, WeatherDataWritable, NullWritable, WeatherDataWritable>.Context context) throws IOException, InterruptedException {
		for(WeatherDataWritable w : value){
			if(max==null)
				max=w;
			else if(max.compareTo(w)<0){
				max=w;
			}
		}
//		String strValue = max.getID()+"\t"+max.getDate()+"\t"+max.getValue();
		context.write(null, max);
	}
}


text:
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;

namespace MediaBrowser.Theater.Presentation.Controls
{
    public class UpperCaseConverter : MarkupExtension, IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var str = value as string;

            return str != null ? str.ToUpper() : value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        private static UpperCaseConverter _converter;
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (_converter == null)
            {
                _converter = new UpperCaseConverter();
            }
            return _converter;
        }
    }

    public class LowerCaseConverter : MarkupExtension, IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var str = value as string;

            return str != null ? str.ToLower(culture) : value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        private static LowerCaseConverter _converter;
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (_converter == null)
            {
                _converter = new LowerCaseConverter();
            }
            return _converter;
        }
    }
}


text:
package org.apache.ignite.ml.selection.cv;

import org.apache.ignite.ml.dataset.feature.extractor.Vectorizer;
import org.apache.ignite.ml.dataset.feature.extractor.impl.DoubleArrayVectorizer;
import org.apache.ignite.ml.nn.UpdatesStrategy;
import org.apache.ignite.ml.optimization.updatecalculators.SimpleGDParameterUpdate;
import org.apache.ignite.ml.optimization.updatecalculators.SimpleGDUpdateCalculator;
import org.apache.ignite.ml.pipeline.Pipeline;
import org.apache.ignite.ml.regressions.logistic.LogisticRegressionModel;
import org.apache.ignite.ml.regressions.logistic.LogisticRegressionSGDTrainer;
import org.apache.ignite.ml.selection.paramgrid.ParamGrid;
import org.apache.ignite.ml.selection.paramgrid.RandomStrategy;
import org.apache.ignite.ml.selection.scoring.metric.MetricName;
import org.apache.ignite.ml.tree.DecisionTreeClassificationTrainer;
import org.apache.ignite.ml.tree.DecisionTreeNode;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

import static org.apache.ignite.ml.common.TrainerTest.twoLinearlySeparableClasses;
import static org.junit.Assert.*;

/**
 * Tests for {@link CrossValidation}.
 */
public class CrossValidationTest {
    /** */
    @Test
    public void testScoreWithGoodDataset() {
        Map<Integer, double[]> data = new HashMap<>();

        for (int i = 0; i < 1000; i++)
            data.put(i, new double[] {i > 500 ? 1.0 : 0.0, i});

        DecisionTreeClassificationTrainer trainer = new DecisionTreeClassificationTrainer(1, 0);

        DebugCrossValidation<DecisionTreeNode, Integer, double[]> scoreCalculator =
            new DebugCrossValidation<>();

        Vectorizer<Integer, double[], Integer, Double> vectorizer = new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.FIRST);

        int folds = 4;

        scoreCalculator
            .withUpstreamMap(data)
            .withAmountOfParts(1)
            .withTrainer(trainer)
            .withMetric(MetricName.ACCURACY)
            .withPreprocessor(vectorizer)
            .withAmountOfFolds(folds)
            .isRunningOnPipeline(false);

        verifyScores(folds, scoreCalculator.scoreByFolds());
    }

    /** */
    @Test
    public void testScoreWithGoodDatasetAndBinaryMetrics() {
        Map<Integer, double[]> data = new HashMap<>();

        for (int i = 0; i < 1000; i++)
            data.put(i, new double[] {i > 500 ? 1.0 : 0.0, i});

        Vectorizer<Integer, double[], Integer, Double> vectorizer = new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.FIRST);

        DecisionTreeClassificationTrainer trainer = new DecisionTreeClassificationTrainer(1, 0);

        DebugCrossValidation<DecisionTreeNode, Integer, double[]> scoreCalculator =
            new DebugCrossValidation<>();

        int folds = 4;

        scoreCalculator
            .withUpstreamMap(data)
            .withAmountOfParts(1)
            .withTrainer(trainer)
            .withMetric(MetricName.ACCURACY)
            .withPreprocessor(vectorizer)
            .withAmountOfFolds(folds)
            .isRunningOnPipeline(false);

        verifyScores(folds, scoreCalculator.scoreByFolds());
    }

    /**
     *
     */
    @Test
    public void testBasicFunctionality() {
        Map<Integer, double[]> data = new HashMap<>();

        for (int i = 0; i < twoLinearlySeparableClasses.length; i++)
            data.put(i, twoLinearlySeparableClasses[i]);

        LogisticRegressionSGDTrainer trainer = new LogisticRegressionSGDTrainer()
            .withUpdatesStgy(new UpdatesStrategy<>(new SimpleGDUpdateCalculator(0.2),
                SimpleGDParameterUpdate.SUM_LOCAL, SimpleGDParameterUpdate.AVG))
            .withMaxIterations(100000)
            .withLocIterations(100)
            .withBatchSize(14)
            .withSeed(123L);

        Vectorizer<Integer, double[], Integer, Double> vectorizer = new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.FIRST);

        DebugCrossValidation<LogisticRegressionModel, Integer, double[]> scoreCalculator =
            new DebugCrossValidation<>();

        int folds = 4;

        scoreCalculator
            .withUpstreamMap(data)
            .withAmountOfParts(1)
            .withTrainer(trainer)
            .withMetric(MetricName.ACCURACY)
            .withPreprocessor(vectorizer)
            .withAmountOfFolds(folds)
            .isRunningOnPipeline(false);

        double[] scores = scoreCalculator.scoreByFolds();

        assertEquals(0.8389830508474576, scores[0], 1e-6);
        assertEquals(0.9402985074626866, scores[1], 1e-6);
        assertEquals(0.8809523809523809, scores[2], 1e-6);
        assertEquals(0.9921259842519685, scores[3], 1e-6);
    }

    /**
     *
     */
    @Test
    public void testGridSearch() {
        Map<Integer, double[]> data = new HashMap<>();

        for (int i = 0; i < twoLinearlySeparableClasses.length; i++)
            data.put(i, twoLinearlySeparableClasses[i]);

        LogisticRegressionSGDTrainer trainer = new LogisticRegressionSGDTrainer()
            .withUpdatesStgy(new UpdatesStrategy<>(new SimpleGDUpdateCalculator(0.2),
                SimpleGDParameterUpdate.SUM_LOCAL, SimpleGDParameterUpdate.AVG))
            .withMaxIterations(100000)
            .withLocIterations(100)
            .withBatchSize(14)
            .withSeed(123L);

        Vectorizer<Integer, double[], Integer, Double> vectorizer = new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.FIRST);

        ParamGrid paramGrid = new ParamGrid()
            .addHyperParam("maxIterations", trainer::withMaxIterations, new Double[]{10.0, 100.0, 1000.0, 10000.0})
            .addHyperParam("locIterations", trainer::withLocIterations, new Double[]{10.0, 100.0, 1000.0, 10000.0})
            .addHyperParam("batchSize", trainer::withBatchSize, new Double[]{1.0, 2.0, 4.0, 8.0, 16.0});

        DebugCrossValidation<LogisticRegressionModel, Integer, double[]> scoreCalculator =
            (DebugCrossValidation<LogisticRegressionModel, Integer, double[]>) new DebugCrossValidation<LogisticRegressionModel, Integer, double[]>()
                .withUpstreamMap(data)
                .withAmountOfParts(1)
                .withTrainer(trainer)
                .withMetric(MetricName.ACCURACY)
                .withPreprocessor(vectorizer)
                .withAmountOfFolds(4)
                .isRunningOnPipeline(false)
                .withParamGrid(paramGrid);

        CrossValidationResult crossValidationRes = scoreCalculator.tuneHyperParameters();

        assertArrayEquals(crossValidationRes.getBestScore(), new double[]{0.9745762711864406, 1.0, 0.8968253968253969, 0.8661417322834646}, 1e-6);
        assertEquals(crossValidationRes.getBestAvgScore(), 0.9343858500738256, 1e-6);
        assertEquals(crossValidationRes.getScoringBoard().size(), 80);
    }

    /**
     *
     */
    @Test
    public void testRandomSearch() {
        Map<Integer, double[]> data = new HashMap<>();

        for (int i = 0; i < twoLinearlySeparableClasses.length; i++)
            data.put(i, twoLinearlySeparableClasses[i]);

        LogisticRegressionSGDTrainer trainer = new LogisticRegressionSGDTrainer()
            .withUpdatesStgy(new UpdatesStrategy<>(new SimpleGDUpdateCalculator(0.2),
                SimpleGDParameterUpdate.SUM_LOCAL, SimpleGDParameterUpdate.AVG))
            .withMaxIterations(100000)
            .withLocIterations(100)
            .withBatchSize(14)
            .withSeed(123L);

        Vectorizer<Integer, double[], Integer, Double> vectorizer = new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.FIRST);

        ParamGrid paramGrid = new ParamGrid()
            .withParameterSearchStrategy(
                new RandomStrategy()
                    .withMaxTries(10)
                    .withSeed(1234L)
                    .withSatisfactoryFitness(0.9)
            )
            .addHyperParam("maxIterations", trainer::withMaxIterations, new Double[]{10.0, 100.0, 1000.0, 10000.0})
            .addHyperParam("locIterations", trainer::withLocIterations, new Double[]{10.0, 100.0, 1000.0, 10000.0})
            .addHyperParam("batchSize", trainer::withBatchSize, new Double[]{1.0, 2.0, 4.0, 8.0, 16.0});

        DebugCrossValidation<LogisticRegressionModel, Integer, double[]> scoreCalculator =
            (DebugCrossValidation<LogisticRegressionModel, Integer, double[]>) new DebugCrossValidation<LogisticRegressionModel, Integer, double[]>()
                .withUpstreamMap(data)
                .withAmountOfParts(1)
                .withTrainer(trainer)
                .withMetric(MetricName.ACCURACY)
                .withPreprocessor(vectorizer)
                .withAmountOfFolds(4)
                .isRunningOnPipeline(false)
                .withParamGrid(paramGrid);

        CrossValidationResult crossValidationRes = scoreCalculator.tuneHyperParameters();

        assertEquals(crossValidationRes.getBestAvgScore(), 0.9343858500738256, 1e-6);
        assertEquals(crossValidationRes.getScoringBoard().size(), 10);
    }

    /**
     *
     */
    @Test
    public void testRandomSearchWithPipeline() {
        Map<Integer, double[]> data = new HashMap<>();

        for (int i = 0; i < twoLinearlySeparableClasses.length; i++)
            data.put(i, twoLinearlySeparableClasses[i]);

        LogisticRegressionSGDTrainer trainer = new LogisticRegressionSGDTrainer()
            .withUpdatesStgy(new UpdatesStrategy<>(new SimpleGDUpdateCalculator(0.2),
                SimpleGDParameterUpdate.SUM_LOCAL, SimpleGDParameterUpdate.AVG))
            .withMaxIterations(100000)
            .withLocIterations(100)
            .withBatchSize(14)
            .withSeed(123L);

        Vectorizer<Integer, double[], Integer, Double> vectorizer = new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.FIRST);

        ParamGrid paramGrid = new ParamGrid()
            .withParameterSearchStrategy(
                new RandomStrategy()
                    .withMaxTries(10)
                    .withSeed(1234L)
                    .withSatisfactoryFitness(0.9)
            )
            .addHyperParam("maxIterations", trainer::withMaxIterations, new Double[]{10.0, 100.0, 1000.0, 10000.0})
            .addHyperParam("locIterations", trainer::withLocIterations, new Double[]{10.0, 100.0, 1000.0, 10000.0})
            .addHyperParam("batchSize", trainer::withBatchSize, new Double[]{1.0, 2.0, 4.0, 8.0, 16.0});

        Pipeline<Integer, double[], Integer, Double> pipeline = new Pipeline<Integer, double[], Integer, Double>()
            .addVectorizer(vectorizer)
            .addTrainer(trainer);

        DebugCrossValidation<LogisticRegressionModel, Integer, double[]> scoreCalculator =
            (DebugCrossValidation<LogisticRegressionModel, Integer, double[]>) new DebugCrossValidation<LogisticRegressionModel, Integer, double[]>()
                .withUpstreamMap(data)
                .withAmountOfParts(1)
                .withPipeline(pipeline)
                .withMetric(MetricName.ACCURACY)
                .withPreprocessor(vectorizer)
                .withAmountOfFolds(4)
                .isRunningOnPipeline(true)
                .withParamGrid(paramGrid);

        CrossValidationResult crossValidationRes = scoreCalculator.tuneHyperParameters();

        assertEquals(crossValidationRes.getBestAvgScore(), 0.9343858500738256, 1e-6);
        assertEquals(crossValidationRes.getScoringBoard().size(), 10);
    }

    /** */
    @Test
    public void testScoreWithBadDataset() {
        Map<Integer, double[]> data = new HashMap<>();

        for (int i = 0; i < 1000; i++)
            data.put(i, new double[] { i, i % 2 == 0 ? 1.0 : 0.0});

        Vectorizer<Integer, double[], Integer, Double> vectorizer = new DoubleArrayVectorizer<Integer>().labeled(Vectorizer.LabelCoordinate.LAST);

        DecisionTreeClassificationTrainer trainer = new DecisionTreeClassificationTrainer(1, 0);

        DebugCrossValidation<DecisionTreeNode, Integer, double[]> scoreCalculator =
            new DebugCrossValidation<>();

        int folds = 4;

        scoreCalculator
            .withUpstreamMap(data)
            .withAmountOfParts(1)
            .withTrainer(trainer)
            .withMetric(MetricName.ACCURACY)
            .withPreprocessor(vectorizer)
            .withAmountOfFolds(folds)
            .isRunningOnPipeline(false);

        double[] scores = scoreCalculator.scoreByFolds();

        assertEquals(folds, scores.length);

        for (int i = 0; i < folds; i++)
            assertTrue(scores[i] < 0.6);
    }

    /** */
    private void verifyScores(int folds, double[] scores) {
        assertEquals(folds, scores.length);

        for (int i = 0; i < folds; i++)
            assertEquals(1, scores[i], 1e-1);
    }
}


text:
TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

    gem 'prcti09'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install prcti09

## Usage

TODO: Write usage instructions here

## Diseño

- Matriz Densa y Dispersa.

	Matriz densa: Matriz normal.
	Matriz dispersa: Matriz con pocos datos.
- Operadores de la clase:

	+ , - , * , @-, [], <=>

- Herencia

	La clase Matriz dispersa heredará métodos de la clase Matriz densa,
	ya que la matriz dispersa tiene unas caracteristicas diferentes y habrá 	que redefinir los métodos.

- Estructura de datos.

	Matriz dispersa: Tabla hash.
	Matriz densa: Array de array.

- Métodos.

	Tratar a la hora de realizar alguna operación de conversión de tipo que
	permita la utilización o compatibilidad de tipo de datos para los casos 	en que se utilicen datos diferentes.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package com.azure.security.confidentialledger;

import com.azure.core.http.rest.RequestOptions;
import com.azure.core.http.rest.Response;
import com.azure.core.util.BinaryData;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.security.confidentialledger.certificate.ConfidentialLedgerCertificateClient;
import com.azure.security.confidentialledger.certificate.ConfidentialLedgerCertificateClientBuilder;

public class GetLedgerIdentitySample {
    public static void main(String[] args) {
        ConfidentialLedgerCertificateClient confidentialLedgerCertificateClient =
                new ConfidentialLedgerCertificateClientBuilder()
                        .credential(new DefaultAzureCredentialBuilder().build())
                        .certificateEndpoint("identity.accledger.azure.com")
                        .buildClient();
        RequestOptions requestOptions = new RequestOptions();
        String ledgerId = "your_ledger_name";
        Response<BinaryData> response =
                confidentialLedgerCertificateClient.getLedgerIdentityWithResponse(ledgerId, requestOptions);
    }
}


text:
#!/usr/bin/env bash
#
#
#
# run a singa job
#

usage="Usage: singa-run.sh [ arguments ]\n
        -exec <binary or python script> : if want to use own singa driver\n
        -conf <job config file> : need cluster conf if train in a cluster
        -resume                 : if want to recover a job"

# parse arguments
#  extract and remove '-exec' and '-conf'
#  other arguments remain untouched
exe=./singa
while [ $# != 0 ]; do
  if [ $1 == "-exec" ]; then
    shift
    exe=$1
  elif [ $1 == "-conf" ]; then
    shift
    conf=$1
  else
    args="$args $1"
  fi
  shift
done

# get environment variables
. `dirname "${BASH_SOURCE-$0}"`/singa-env.sh

# change conf to an absolute path
if [ ! -z $conf ]; then
  conf_dir=`dirname "$conf"`
  conf_dir=`cd "$conf_dir">/dev/null; pwd`
  conf_base=`basename "$conf"`
  job_conf=$conf_dir/$conf_base
  if [ ! -f $job_conf ]; then
    echo $job_conf not exists
    exit 1
  fi
fi

# go to singa home to execute binary
cd $SINGA_HOME

# generate unique job id
job_id=`./singatool create`
[ $? == 0 ] || exit 1
echo Unique JOB_ID is $job_id

# generate job info dir
# format: job-JOB_ID-YYYYMMDD-HHMMSS
log_dir=$SINGA_LOG/job-info/job-$job_id-$(date '+%Y%m%d-%H%M%S')
mkdir -p $log_dir
echo Record job information to $log_dir

# generate host file
host_file=$log_dir/job.hosts
./singatool genhost $job_conf 1>$host_file || exit 1

# set command to run singa
singa_run="$exe $args \
            -singa_conf $SINGA_HOME/conf/singa.conf \
            -singa_job $job_id"
# add -conf if exists
if [ ! -z $job_conf ]; then
  singa_run="$singa_run -conf $job_conf"
fi
singa_sshrun="cd $SINGA_HOME; source $SINGA_HOME/conf/profile; $singa_run"

# ssh and start singa processes
ssh_options="-oStrictHostKeyChecking=no \
-oUserKnownHostsFile=/dev/null \
-oLogLevel=quiet"
hosts=`cat $host_file | cut -d ' ' -f 1`
for i in ${hosts[@]} ; do
  if [ $i = localhost ] ; then
    echo Executing : $singa_run
    $singa_run &
  else
    echo Executing @ $i : $singa_sshrun
    ssh $ssh_options $i $singa_sshrun " -host " $i &
  fi
done

# generate pid list for this job
sleep 2
./singatool view $job_id 1>$log_dir/job.pids || exit 1
wait


text:
    <md-card>
      <md-card-title>Admin</md-card-title>
      <md-tab-group class="app-mat-tab">
        <md-tab label="Adaugare activitati predare">

            <md-card fxFlex="100%">

                <form #ta_uploadForm="ngForm" fxFlex="100">

                      <md-select name="academicYear"
                                 (change)="changeTarget()"
                                 fxFlex="100" placeholder="{{'ACADEMIC_YEAR_PLACEHOLDER' | translate}}"
                                 [(ngModel)]="selectedAcademicYear"
                                 required="true">
                        <md-option *ngFor="let ay of academicYearOptions  | async" [value]="ay?.name">{{ ay?.name }}
                        </md-option>
                      </md-select>

                      <md-select name="semester"
                                 placeholder="{{'SEMESTER_PLACEHOLDER' | translate}}"
                                 (change)="changeTarget()"
                                 [(ngModel)]="selectedSemester"
                                 required="true">
                        <md-option *ngFor="let sem of semesterOptions" [value]="sem">{{ sem}}</md-option>
                      </md-select>

Drop

                      <input type="file" class="app-hidden" #teaching_activity_file ng2FileSelect [uploader]="teachingActivityUploader"/>

                        <ngx-datatable
                          class="material ml-0 mr-0 mrgn-b-md"
                          [rows]="teachingActivityUploader.queue"
                          [columnMode]="'flex'"
                          [headerHeight]="50"
                          [footerHeight]="0"
                          [rowHeight]="'auto'">
                          <ngx-datatable-column name="Name" [flexGrow]="2">
                            <ng-template let-row="row" ngx-datatable-cell-template>
                              {{ row?.file?.name }}
                            </ng-template>
                          </ngx-datatable-column>
                          <ngx-datatable-column name="Progress" *ngIf="teachingActivityUploader.options.isHTML5" [flexGrow]="1">
                            <ng-template let-row="row" ngx-datatable-cell-template>
                              <md-progress-bar mode="determinate" value="{{row.progress}}"></md-progress-bar>
                            </ng-template>
                          </ngx-datatable-column>
                          <ngx-datatable-column name="Status" [flexGrow]="1">
                            <ng-template let-row="row" ngx-datatable-cell-template>
                              <md-icon>check</md-icon>
                              <md-icon>cancel</md-icon>
                              <md-icon>delete</md-icon>
                            </ng-template>
                          </ngx-datatable-column>
                          <ngx-datatable-column name="Action" [flexGrow]="2">
                            <ng-template let-row="row" ngx-datatable-cell-template>
                              <button md-raised-button md-button-sm type="button"
                                      (click)="row.upload()"
                                      [disabled]="row.isReady || row.isUploading || row.isSuccess">
                                Upload
                              </button>
                              <button md-raised-button md-button-sm type="button"
                                      (click)="row.cancel()" [disabled]="!row.isUploading">Cancel
                              </button>
                              <button md-raised-button md-button-sm type="button"
                                      (click)="row.remove()">Remove
                              </button>
                            </ng-template>
                          </ngx-datatable-column>
                        </ngx-datatable>

                </form>

            </md-card>

        </md-tab>
        <md-tab label="Adaugare activitati de evaluare">

            <md-card fxFlex="100%">

                <form #ea_uploadForm="ngForm" fxFlex="100">

                      <md-select name="academicYear"
                                 (change)="changeTarget()"
                                 fxFlex="100" placeholder="{{'ACADEMIC_YEAR_PLACEHOLDER' | translate}}"
                                 [(ngModel)]="selectedAcademicYear"
                                 required="true">
                        <md-option *ngFor="let ay of academicYearOptions  | async" [value]="ay?.name">{{ ay?.name }}
                        </md-option>
                      </md-select>

                      <md-select name="evaluationType"
                                 placeholder="{{'EVALUATION_ACTIVITY_TYPE_PLACEHOLDER' | translate}}"
                                 (change)="changeTarget()"
                                 [(ngModel)]="selectedEvaluationType"
                                 required="true">
                        <md-option *ngFor="let type of evaluationActivityTypeOptions" [value]="type">{{ type}}</md-option>
                      </md-select>

Drop

                      <input type="file" class="app-hidden" #teaching_activity_file ng2FileSelect [uploader]="evaluationActivityUploader"/>

                        <ngx-datatable
                          class="material ml-0 mr-0 mrgn-b-md"
                          [rows]="evaluationActivityUploader.queue"
                          [columnMode]="'flex'"
                          [headerHeight]="50"
                          [footerHeight]="0"
                          [rowHeight]="'auto'">
                          <ngx-datatable-column name="Name" [flexGrow]="2">
                            <ng-template let-row="row" ngx-datatable-cell-template>
                              {{ row?.file?.name }}
                            </ng-template>
                          </ngx-datatable-column>
                          <ngx-datatable-column name="Progress" *ngIf="evaluationActivityUploader.options.isHTML5" [flexGrow]="1">
                            <ng-template let-row="row" ngx-datatable-cell-template>
                              <md-progress-bar mode="determinate" value="{{row.progress}}"></md-progress-bar>
                            </ng-template>
                          </ngx-datatable-column>
                          <ngx-datatable-column name="Status" [flexGrow]="1">
                            <ng-template let-row="row" ngx-datatable-cell-template>
                              <md-icon>check</md-icon>
                              <md-icon>cancel</md-icon>
                              <md-icon>delete</md-icon>
                            </ng-template>
                          </ngx-datatable-column>
                          <ngx-datatable-column name="Action" [flexGrow]="2">
                            <ng-template let-row="row" ngx-datatable-cell-template>
                              <button md-raised-button md-button-sm type="button"
                                      (click)="row.upload()"
                                      [disabled]="row.isReady || row.isUploading || row.isSuccess">
                                Upload
                              </button>
                              <button md-raised-button md-button-sm type="button"
                                      (click)="row.cancel()" [disabled]="!row.isUploading">Cancel
                              </button>
                              <button md-raised-button md-button-sm type="button"
                                      (click)="row.remove()">Remove
                              </button>
                            </ng-template>
                          </ngx-datatable-column>
                        </ngx-datatable>

                </form>

            </md-card>

        </md-tab>
      </md-tab-group>
    </md-card>

<ng-template #error_modal_duplicate_activities>

    <button color="primary" class="close" (click)="close()">
      <md-icon>close</md-icon>
    </button>

    <app-duplicate-teaching-activity-component [duplicateFields]="duplicateActivities" >
    </app-duplicate-teaching-activity-component>

  <md-icon (click)="close()" class="modal-confirm-btn">done</md-icon>
</ng-template>

<ng-template #error_modal_not_found_elements>

    <button color="primary" class="close" (click)="close()">
      <md-icon>close</md-icon>
    </button>

    <app-not-found-elements [notFoundedFields]="notFoundedElements" >
    </app-not-found-elements>

  <md-icon (click)="close()" class="modal-confirm-btn">done</md-icon>
</ng-template>


text:
package com.nec.strudel.bench.auction.populate;

import java.util.List;

import com.nec.strudel.bench.auction.entity.AuctionItem;
import com.nec.strudel.bench.auction.entity.Bid;
import com.nec.strudel.bench.auction.entity.BuyNowAuction;
import com.nec.strudel.bench.auction.entity.ItemId;
import com.nec.strudel.bench.auction.populate.AuctionParamSet;
import com.nec.strudel.bench.auction.populate.AuctionParamSet.InParam;
import com.nec.strudel.bench.auction.populate.base.AbstractPopulateAuctionItem;
import com.nec.strudel.bench.test.populate.PopulateUtil;
import com.nec.strudel.workload.api.Populator;

public class AuctionItemParams {
	private final int userId;
	private final int userNum;
	private int itemsPerUser = 1;
	private int bidsPerItem = 1;

	int itemNameLen = 12;
	double initialBid = 100.0;
	int buyNowAdjuster = 1;
	int endDateAdjuster = 1;
	int bidDateAdjuster = 1;
	int bnaDateAdjuster = 1;
	int buynowRatio = 100;

	public AuctionItemParams(int userId, int userNum) {
		this.userId = userId;
		this.userNum = userNum;
	}

	public PopulateUtil.ParamBuilder getParam() {
    	PopulateUtil.ParamBuilder pb = PopulateUtil.param(userId)
    		.param(InParam.ITEMS_PER_USER.name(), itemsPerUser)
    		.param(InParam.ITEM_NAME_LEN.name(), itemNameLen)
    		.param(InParam.INITIAL_BID.name(), initialBid)
    		.param(InParam.BUYNOW_ADJUSTER.name(), buyNowAdjuster)
    		.param(InParam.END_DATE_ADJUSTER.name(), endDateAdjuster)
    		.param(InParam.BIDS_PER_ITEM.name(), bidsPerItem)
    		.param(InParam.USER_NUM.name(), userNum)
    		.param(InParam.BID_DATE_ADJUSTER.name(), bidDateAdjuster)
    		.param(InParam.BUYNOW_RATIO.name(), buynowRatio)
    		.param(InParam.BNA_DATE_ADJUSTER.name(), bnaDateAdjuster);
    	return pb;
	}
	public AuctionParamSet create(Populator<?, AuctionParamSet> pop) {
		return pop.createParameter(getParam().build());
	}
	public AuctionParamSet create() {
		return create(new AbstractPopulateAuctionItem<Object>() {

			@Override
			public void process(Object db, AuctionParamSet param) {
			}

			@Override
			protected List<AuctionItem> getItemsBySeller(Object db, int sellerId) {
				return null;
			}

			@Override
			protected AuctionItem getItem(Object db, ItemId id) {
				return null;
			}

			@Override
			protected BuyNowAuction getBuyNowAuction(Object db, ItemId id) {
				return null;
			}

			@Override
			protected List<Bid> getBidsByItemId(Object db, ItemId id) {
				return null;
			}
		});
	}
	public AuctionItemParams setItemsPerUser(int itemsPerUser) {
		this.itemsPerUser = itemsPerUser;
		return this;
	}
	public AuctionItemParams setBuynowRatio(int buynowRatio) {
		this.buynowRatio = buynowRatio;
		return this;
	}
	public AuctionItemParams setNumOfBids(int bidsPerItem) {
		this.bidsPerItem = bidsPerItem;
		return this;
	}

	public int getItemsPerUser() {
		return itemsPerUser;
	}

	public int sellerId() {
		return userId;
	}
	double getInitialBid() {
		return initialBid;
	}

	public int numOfBids() {
		return bidsPerItem;
	}

}


text:
<?php
require __DIR__ . '/../vendor/autoload.php';

use Symfony\Component\Console\Application;
use src\TeamcityCodeAnalysisTransformCommand;

$application = new Application();

$application->add(new TeamcityCodeAnalysisTransformCommand());
$application->run();


text:
from django.core.urlresolvers import reverse
from django.test import TestCase

from ..models import Blog

def create_new_post(author='John', title='A Blog',
                    content='Something useful.'):
    return Blog.objects.create(author=author, title=title,
                               content=content)

class HomePageTest(TestCase):

    def test_root_url_resolves_to_blog_home_view(self):
        response = self.client.get(reverse('blog:home'))
        self.assertTemplateUsed(response, 'blog/home.html')
        self.assertEqual(response.status_code, 200)

    def test_blog_home_page_with_no_blog_posts(self):
        response = self.client.get(reverse('blog:home'))
        self.assertQuerysetEqual(response.context['blog_list'], [])

    def test_blog_home_page_with_blog_posts(self):
        blog = create_new_post()
        response = self.client.get(reverse('blog:home'))
        self.assertEqual(response.context['blog_list'][0].pk, blog.pk)

class CreateBlogViewTest(TestCase):

    def test_url_to_create_blog_view(self):
        response = self.client.get(reverse('blog:new-post'))
        self.assertTemplateUsed(response, 'blog/new_post.html')
        self.assertEqual(response.status_code, 200)

    def test_create_post_with_full_info(self):
        """If all info was filled by the user, it will be redirect to the blog
        detail view with the newly created item pk.
        """
        response = self.client.post(reverse('blog:new-post'),
                                    {'author': 'Tom',
                                     'title': 'a new post',
                                     'content': 'This is a new post'})
        new_post = Blog.objects.all()[0]
        self.assertRedirects(response,
                             reverse('blog:post-detail', args=(new_post.pk,)),
                             status_code=302, target_status_code=200)

    def test_create_post_with_no_info(self):
        """Because all the fields are required, so if they're not filled in,
        the same view will be rerendered with the form errors.
        """
        response = self.client.post(reverse('blog:new-post'))
        self.assertEqual(response.status_code, 200)
        self.assertFormError(response, 'form',
                             'author', 'This field is required.')
        self.assertFormError(response, 'form',
                             'title', 'This field is required.')
        self.assertFormError(response, 'form',
                             'content', 'This field is required.')

class BlogDetailViewTest(TestCase):

    def setUp(self):
        self.new_post = create_new_post(author='Jack', title='Jack blog',
                                        content='Hello world!')
        self.response = self.client.get(reverse('blog:post-detail',
                                                args=(self.new_post.pk,)))

    def test_url_to_blog_detail_view(self):
        self.assertTemplateUsed(self.response, 'blog/post_detail.html')
        self.assertEqual(self.response.status_code, 200)

    def test_blog_detail_view_contains_correct_info(self):
        self.assertEqual(self.response.context_data['post_detail'],
                         self.new_post)

class BlogUpdateViewTest(TestCase):

    def setUp(self):
        self.new_post = create_new_post()
        self.response = self.client.get(reverse('blog:post-edit',
                                                args=(self.new_post.pk,)))

    def test_url_to_blog_update_view(self):
        self.assertTemplateUsed(self.response, 'blog/post_edit.html')
        self.assertEqual(self.response.status_code, 200)

class BlogDeleteViewTest(TestCase):

    def setUp(self):
        self.new_post = create_new_post()
        self.response = self.client.get(reverse('blog:post-delete',
                                                args=(self.new_post.pk,)))

    def test_url_to_blog_delete_view(self):
        self.assertTemplateUsed(self.response, 'blog/post_delete.html')
        self.assertEqual(self.response.status_code, 200)