public void ConcatenateTest() {
			string[] vs = null;
			Assert.IsNull(vs.Concatenate());
			Assert.IsTrue(string.IsNullOrEmpty(vs.Concatenate()));

			vs = new string[0];
			Assert.IsNull(vs.Concatenate());
			Assert.IsTrue(string.IsNullOrEmpty(vs.Concatenate()));

			vs = new string[] { string.Empty };
			Assert.IsTrue(string.IsNullOrEmpty(vs.Concatenate()));

			vs[0] = "test";
			Assert.AreEqual("test", vs.Concatenate());

			vs = new string[] { "test1", "test2" };
			Assert.AreEqual("test1; test2", vs.Concatenate());
			Assert.AreEqual("test1/test2", vs.Concatenate("/"));

			List<string> vs1 = null;
			Assert.IsTrue(string.IsNullOrWhiteSpace(vs1.Concatenate()));
			vs1 = new List<string>();
			Assert.IsTrue(string.IsNullOrEmpty(vs1.Concatenate()));

			vs1.Add("test1");
			Assert.AreEqual("test1", vs1.Concatenate());

			vs1.AddRange(new string[] { "test2", "test3" });
			Assert.AreEqual("test1; test2; test3", vs1.Concatenate());
		}
        public void string_list_concatenate()
        {
            var list = new List <string>();

            Assert.Equal(string.Empty, list.Concatenate(x => x, ASCII.COMMA));

            list.Add("a");
            Assert.Equal("a", list.Concatenate(x => x, ASCII.COMMA));

            list.Add("b");
            Assert.Equal("a,b", list.Concatenate());
        }
        public void Concatenate()
        {
            var list = new List <string> {
                "Fizz", "Buzz"
            };

            var result1 = list.Concatenate();
            var result2 = list.Concatenate(x => x + x);

            Assert.AreEqual("FizzBuzz", result1);
            Assert.AreEqual("FizzFizzBuzzBuzz", result2);
        }
        public void tuple_list_concatenate()
        {
            var list = new List <Tuple <int, int, string> >();

            Assert.Equal(string.Empty, list.Concatenate());

            list.Add(new Tuple <int, int, string>(1, 1, "2"));
            Assert.Equal("1", list.Concatenate(x => x.Item1.ToString()));

            list.Add(new Tuple <int, int, string>(10, 1, "2"));
            Assert.Equal("1,10", list.Concatenate(x => x.Item1.ToString()));
            Assert.Equal("2,2", list.Concatenate(x => x.Item3));
        }
Beispiel #5
0
        private static int ParseJoinSlotTags(this RcSlotRegion region, SubArray <string> textLines)
        {
            textLines = region.FindJoinSlotTagsLines(textLines);

            var tagStringLinesList = new List <string>(textLines.Length);

            for (var i = 1; i <= textLines.LastIndex; i++)
            {
                var textLine = textLines[i];

                var m = region.SlotTagMarker.MarkerRegex.Match(textLine);

                if (m.Success == false)
                {
                    break;
                }

                tagStringLinesList.Add(textLine.Substring(m.Index + m.Length));
            }

            if (tagStringLinesList.Count > 0)
            {
                region.AddSlotTag(tagStringLinesList.Concatenate(Environment.NewLine));
            }

            return(textLines.Length);
        }
Beispiel #6
0
        public void listextensions___concatenate_empty_list_returns_empty_string()
        {
            var list = new List <string>();

            var result = list.Concatenate(",");

            result.Should().Be(string.Empty);
        }
Beispiel #7
0
        public void Concatenate_SupplyNullConverter_ThrowArgumentNullException()
        {
            IList <string> item = new List <string>();

            item.Add("cat");
            item.Add("dog");
            var exception = Assert.Throws <ArgumentNullException>(() => item.Concatenate(",", null) == string.Empty);

            exception.Message.ShouldContain("converter");
        }
        private void formEditDSLSourceFiles_Load(object sender, EventArgs e)
        {
            if (_sourceFilesList.Count > 0)
            {
                textBoxFilesList.Text =
                    _sourceFilesList.Concatenate(Environment.NewLine, "", Environment.NewLine);
            }

            textBoxFilesList.Focus();
        }
Beispiel #9
0
        public void Concatenate()
        {
            List <int> listA = new List <int> {
                29, 15, 11, 28, 32
            };

            string x = listA.Concatenate(", ");

            Assert.Equal("29, 15, 11, 28, 32", x);
        }
Beispiel #10
0
        public void Concatenate_SupplyNoDelimiter_Match()
        {
            IList <string> item = new List <string>();

            item.Add("cat");
            item.Add("dog");
            item.Add("horse");
            var result = item.Concatenate(string.Empty, s => s.Substring(0, 1));

            result.ShouldBe("cdh");
        }
Beispiel #11
0
        public void Concatenate_SupplyItemsAndDelimiter_EnsureLastDelimiterRemoved()
        {
            IList <string> item = new List <string>();

            item.Add("cat");
            item.Add("dog");
            item.Add("horse");
            var result = item.Concatenate(";", s => s.Substring(0, 1));

            result.ShouldBe("c;d;h");
        }
Beispiel #12
0
        public void Concatenate_SupplyEmptyItems_EnsureLastDelimiterRemoved()
        {
            IList <string> item = new List <string>();

            item.Add(string.Empty);
            item.Add(string.Empty);
            item.Add(string.Empty);
            var result = item.Concatenate("|", s => s);

            result.ShouldBe("||");
        }
Beispiel #13
0
        public void ConcatenateTest3()
        {
            List <byte[]> input = new List <byte[]>()
            {
                vs1, vs2, vs3, vs4
            };

            byte[] exp = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
            var    res = input.Concatenate();

            Assert.AreEqual(14, res.Length);
            Assert.IsFalse(res.HasChanges(exp));
        }
        public string ConcatenateElements(
            HttpMethod method,
            Uri url,
            IEnumerable <KeyValuePair <string, string> > parameters)
        {
            var allParameters = new List <KeyValuePair <string, string> >();

            allParameters.AddRange(parameters);

            if (_consumerKey != null)
            {
                allParameters.Add(
                    new KeyValuePair <string, string>(
                        OAuth1ParameterEnum.ConsumerKey.EnumToString(),
                        _consumerKey));
            }
            if (_oauthToken != null)
            {
                allParameters.Add(
                    new KeyValuePair <string, string>(
                        OAuth1ParameterEnum.OAuthToken.EnumToString(),
                        _oauthToken));
            }
            if (_verifier != null)
            {
                allParameters.Add(
                    new KeyValuePair <string, string>(
                        OAuth1ParameterEnum.Verifier.EnumToString(),
                        _verifier));
            }

            allParameters.Add(
                new KeyValuePair <string, string>(
                    OAuth1ParameterEnum.SignatureMethod.EnumToString(),
                    SIGNATURE_METHOD));
            allParameters.Add(
                new KeyValuePair <string, string>(
                    OAuth1ParameterEnum.Version.EnumToString(),
                    VERSION));

            var elements = new List <string>
            {
                method.ToString(),
                url.UrlEncodeRelaxed(),
                allParameters.Normalize().Concatenate("=", "&").UrlEncodeRelaxed()
            };

            return(elements.Concatenate("&"));
        }
Beispiel #15
0
            private void VerifyEntryIDsAndXPaths(string requestUri, TestWebRequest request, int[] expectedIDs, params string[] xpaths)
            {
                var           response = UnitTestsUtil.GetResponseAsAtomXLinq(request, requestUri);
                List <string> ids      = response.Root.Elements(UnitTestsUtil.AtomNamespace + "entry").Elements(UnitTestsUtil.AtomNamespace + "id")
                                         .Select(e => (string)e).ToList();

                Assert.AreEqual(expectedIDs.Length, ids.Count, "The number of returned entries doesn't match.");
                for (int i = 0; i < expectedIDs.Length; i++)
                {
                    if (!ids[i].Contains("(" + expectedIDs[i].ToString() + ")"))
                    {
                        Assert.Fail("Entries not reported correctly, \r\nexpected: " + expectedIDs.Select(n => n.ToString()).Concatenate(", ") +
                                    "\r\nactual: " + ids.Concatenate(", ") +
                                    "\r\n" + response.ToString());
                    }
                }

                UnitTestsUtil.VerifyXPathExists(response, xpaths);
            }
Beispiel #16
0
        private static string GetGroupedUsers(HtmlHelper html, string name, string objectId, List <UserLinkModel> explicitUsers, int?userCount, bool isOrganization, NewsFeedItemModel item)
        {
            string user;

            if (!userCount.HasValue || userCount == 0)
            {
                if (isOrganization)
                {
                    return(html.ActionLinkWithReturnUrl(name, MVC.Organization.Details(objectId, name.ToSeoUrl(), null, null, null, null)).ToString());
                }
                else
                {
                    return(html.ActionLinkWithReturnUrl(name, MVC.Account.Details(objectId, name.ToSeoUrl(), null)).ToString());
                }
            }
            else
            {
                if (explicitUsers != null && explicitUsers.Count > 0)
                {
                    user =
                        explicitUsers.Concatenate(
                            itm => html.ActionLinkWithReturnUrl(itm.FullName, MVC.Account.Details(itm.ObjectId, itm.FullName.ToSeoUrl(), null)).ToString(), ", ");

                    if (userCount > 0)
                    {
                        user += " " +
                                string.Format(Resource.AndSomeMore,
                                              GlobalizedSentences.GetUsersString(userCount.Value),
                                              GetNewsFeedGroupUsersLink(html, item));
                    }
                }
                else
                {
                    user = string.Format(Resource.NumberUsers,
                                         GlobalizedSentences.GetUsersString(userCount.Value),
                                         GetNewsFeedGroupUsersLink(html, item));
                }
            }

            return(user);
        }
Beispiel #17
0
        public void ApplySettings(IActivityMonitor m)
        {
            List <string> lines = TextContent != null
                                    ? TextContent
                                  .Split(new[] { "\r\n" }, StringSplitOptions.None)
                                  .ToList()
                                    : new List <string>();

            EnsureLine(lines, "[Bb]in/");
            EnsureLine(lines, "[Oo]bj/");
            EnsureLine(lines, "[Rr]elease/");
            EnsureLine(lines, "[Rr]eleases/");
            EnsureLine(lines, ".vs/");
            EnsureLine(lines, "*.suo");
            EnsureLine(lines, "*.user");
            EnsureLine(lines, "CodeCakeBuilder/UnitTestsDone.*.txt");

            if (!_solutionSpec.NoDotNetUnitTests)
            {
                EnsureLine(lines, "Tests/**/TestResult*.xml");
                EnsureLine(lines, "CodeCakeBuilder/MemoryKey.*.txt");
                EnsureLine(lines, "Tests/**/Logs/");
                EnsureLine(lines, "Tests/**/CKSetup-WorkingDir/");
            }
            else
            {
                RemoveLine(lines, "Tests/**/TestResult*.xml");
                RemoveLine(lines, "CodeCakeBuilder/MemoryKey.*.txt");
                RemoveLine(lines, "Tests/**/Logs/");
                RemoveLine(lines, "Tests/**/CKSetup-WorkingDir/");
            }
            if (lines != null)
            {
                CreateOrUpdate(m, lines.Concatenate("\r\n"));
            }
        }
Beispiel #18
0
 public static string Concatenate <T>(this List <T> list)
 {
     return(list.Concatenate(String.Empty));
 }
        public override void Import()
        {
            base.Import();

            Console.Out.WriteLine("Importing shapefile from \"" + Path + "\"...");

            try
            {
                Dictionary <string, string> importOptionValue = new Dictionary <string, string>();
                string importOptionsPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Path), System.IO.Path.GetFileNameWithoutExtension(Path) + ".att");
                if (File.Exists(importOptionsPath))
                {
                    foreach (string line in File.ReadLines(importOptionsPath))
                    {
                        string[] parts = line.Split('=');
                        importOptionValue.Add(parts[0].Trim(), parts[1].Trim());
                    }
                }

                if (_sourceSRID > 0 && _targetSRID > 0)
                {
                    importOptionValue["reprojection"] = _sourceSRID + ":" + _targetSRID;
                }

                if (!string.IsNullOrWhiteSpace(Name))
                {
                    importOptionValue["name"] = Name;
                }

                List <string> neededValues = new List <string>();
                if (!importOptionValue.ContainsKey("reprojection") || string.IsNullOrWhiteSpace(importOptionValue["reprojection"]))
                {
                    neededValues.Add("reprojection");
                }
                if (!importOptionValue.ContainsKey("name") || string.IsNullOrWhiteSpace(importOptionValue["name"]))
                {
                    neededValues.Add("name");
                }
                if (neededValues.Count > 0)
                {
                    if (_shapefileInfoRetriever == null)
                    {
                        throw new Exception("Missing the following shapefile options, and no information retriever was present:  " + neededValues.Concatenate(","));
                    }
                    else
                    {
                        _shapefileInfoRetriever.GetShapefileInfo(Path, neededValues, importOptionValue);
                    }
                }

                string missingValues = neededValues.Where(v => !importOptionValue.ContainsKey(v) || string.IsNullOrWhiteSpace(importOptionValue[v])).Concatenate(", ");
                if (missingValues != "")
                {
                    throw new Exception("Failed to provide needed values for shapefile import:  " + missingValues);
                }

                string reprojection      = importOptionValue["reprojection"];
                Match  reprojectionMatch = new Regex("(?<from>[0-9]+):(?<to>[0-9]+)").Match(reprojection);
                if (!reprojectionMatch.Success)
                {
                    throw new Exception("Invalid shapefile reprojection \"" + reprojection + "\". Must be in 1234:1234 format.");
                }

                int fromSRID = int.Parse(reprojectionMatch.Groups["from"].Value);
                int toSRID   = int.Parse(reprojectionMatch.Groups["to"].Value);
                if (fromSRID == toSRID)
                {
                    reprojection = fromSRID.ToString();
                }

                string name = importOptionValue["name"];
                if (string.IsNullOrWhiteSpace(name))
                {
                    throw new Exception("Empty name given for shapefile \"" + Path + "\".");
                }

                Name = name; // to make sure names retrieved from *.att files get back to the object and ultimately back to the DB

                File.WriteAllText(importOptionsPath, "reprojection=" + fromSRID + ":" + toSRID + Environment.NewLine +
                                  "name=" + name);

                Shapefile.ShapefileType type;
                if (this is FeatureShapefileImporter)
                {
                    type = Shapefile.ShapefileType.Feature;
                }
                else if (this is AreaShapefileImporter)
                {
                    type = Shapefile.ShapefileType.Area;
                }
                else if (this is IncidentShapefileImporter)
                {
                    type = Shapefile.ShapefileType.Incident;
                }
                else
                {
                    throw new NotImplementedException("Unrecognized shapefile importer type:  " + GetType());
                }

                _importedShapefile = Shapefile.Create(name, toSRID, type);

                string sql;
                string error;
                using (Process process = new Process())
                {
                    process.StartInfo.FileName               = Configuration.Shp2PgsqlPath;
                    process.StartInfo.Arguments              = "-I -g " + ShapefileGeometry.Columns.Geometry + " -s " + reprojection + " \"" + Path + "\" " + _importedShapefile.GeometryTable;
                    process.StartInfo.CreateNoWindow         = true;
                    process.StartInfo.UseShellExecute        = false;
                    process.StartInfo.RedirectStandardError  = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.Start();

                    Console.Out.WriteLine("Converting shapefile \"" + name + "\".");

                    sql   = process.StandardOutput.ReadToEnd().Replace("BEGIN;", "").Replace("COMMIT;", "");
                    error = process.StandardError.ReadToEnd().Trim().Replace(Environment.NewLine, "; ").Replace("\n", "; ");

                    process.WaitForExit();
                }

                Console.Out.WriteLine(error);

                DB.Connection.ExecuteNonQuery(sql);

                // if there's an id column already, rename it native_id
                if (DB.Connection.GetColumnNames(_importedShapefile.GeometryTable).Select(c => c.ToLower()).Contains("id"))
                {
                    DB.Connection.ExecuteNonQuery("ALTER TABLE " + _importedShapefile.GeometryTable + " DROP COLUMN IF EXISTS native_id;" +
                                                  "ALTER TABLE " + _importedShapefile.GeometryTable + " RENAME COLUMN id TO native_id");
                }

                // rename primary key column to ShapefileGeometry.Columns.Id
                List <string> primaryKeyColumns = DB.Connection.GetPrimaryKeyColumns(_importedShapefile.GeometryTable).ToList();
                if (primaryKeyColumns.Count == 1)
                {
                    if (primaryKeyColumns[0] != ShapefileGeometry.Columns.Id)
                    {
                        DB.Connection.ExecuteNonQuery("ALTER TABLE " + _importedShapefile.GeometryTable + " DROP COLUMN IF EXISTS " + ShapefileGeometry.Columns.Id + ";" +
                                                      "ALTER TABLE " + _importedShapefile.GeometryTable + " RENAME COLUMN " + primaryKeyColumns[0] + " TO " + ShapefileGeometry.Columns.Id);
                    }
                }
                else
                {
                    throw new Exception("Imported shapefile database does not contain a single primary key column.");
                }

                Console.Out.WriteLine("Shapefile import succeeded.");
            }
            catch (Exception ex)
            {
                if (_importedShapefile != null)
                {
                    try { _importedShapefile.Delete(); }
                    catch (Exception ex2) { Console.Out.WriteLine("Failed to delete shapefile:  " + ex2.Message); }
                }

                _importedShapefile = null;

                throw new Exception("Shapefile import failed:  " + ex.Message);
            }
        }
Beispiel #20
0
        /// <summary>
        /// Construct an instance of PersonName by parsing the text provided.
        /// </summary>
        /// <param name="text">The text to parse into a name.</param>
        public PersonName(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                throw new ArgumentNullException(nameof(text));
            }

            // Temp value to be search/changed
            string working = text.Trim();

            // Eliminate all double-spaces.
            while (working.Contains("  "))
            {
                working = working.Replace("  ", " ");
            }

            // Initialize variables
            Prefix   = string.Empty;
            Last     = string.Empty;
            First    = string.Empty;
            Middle   = string.Empty;
            Suffix   = string.Empty;
            Nickname = string.Empty;

            // Check for nicknames (in quotes)
            if (working.Contains("\""))
            {
                int x1 = working.IndexOf("\"");
                int x2 = working.IndexOf("\"", x1 + 1);
                if (x2 > x1)
                {
                    Nickname = working.Substring(x1 + 1, x2 - x1 - 1).Trim();
                    working  = text.Replace("\"" + Nickname + "\"", string.Empty);
                }
            }
            else if (working.Contains("'"))
            {
                int x1 = working.IndexOf("'");
                int x2 = working.IndexOf("'", x1 + 1);
                if (x2 > x1)
                {
                    Nickname = working.Substring(x1 + 1, x2 - x1 - 1).Trim();
                    working  = working.Replace("'" + Nickname + "'", string.Empty);
                }
            }

            // Temp array for catching prefix
            List <string> vsP = new List <string>();

            StringBuilder m = new StringBuilder();

            // Check to see if text contains comma.
            if (working.Contains(","))
            {
                int commaInd = working.IndexOf(",");
                int spaceInd = working.IndexOf(" ");
                // If a space occurs before the comma, it's most likely formatted as [First Last, Suffix]
                if (spaceInd > 0 && spaceInd < commaInd)
                {
                    Suffix  = working.Substring(commaInd + 1).Trim();
                    working = working.Substring(0, commaInd);
                    // Check for known prefixes.
                    foreach (var prefix in Honorifics.ForParsingName)
                    {
                        if (working.ToLower().StartsWith(prefix.ToLower()))
                        {
                            vsP.Add(prefix);
                            working = working.Substring(prefix.Length).Trim();
                        }
                    }
                    Prefix = vsP.Concatenate(" ");
                    vsP.Clear();

                    var split = splitText(working).ToList();
                    if (split.Count > 2)
                    {
                        First = split.First().Trim();
                        Last  = split.Last().Trim();
                        foreach (var s in split.Skip(1).Take(split.Count - 2))
                        {
                            m.Append(" ");
                            m.Append(s);
                        }
                        Middle = m.ToString().Trim();
                    }
                    else if (split.Count == 2)
                    {
                        First = split.First().Trim();
                        Last  = split.Last().Trim();
                    }
                    else
                    {
                        Last = split[0].Trim();
                    }
                }
                else                     // If there is no space before the comma, it's most likely formatted as [Last, First]
                {
                    Last    = working.Substring(0, commaInd).Trim();
                    working = working.Substring(commaInd + 1).Trim();

                    // Check for known prefixes.
                    foreach (var prefix in Honorifics.ForParsingName)
                    {
                        if (working.ToLower().StartsWith(prefix.ToLower()))
                        {
                            vsP.Add(prefix);
                            working = working.Substring(prefix.Length).Trim();
                        }
                    }

                    Prefix = vsP.Concatenate(" ");
                    vsP.Clear();
                    // Check for additional comma. If exists, what follows is suffix
                    int index = working.IndexOf(",");
                    if (index > 0)
                    {
                        Suffix  = working.Substring(index + 1).Trim();
                        working = working.Substring(0, index).Trim();
                    }

                    if (!working.Contains(" "))
                    {
                        First = working.Trim();
                    }
                    else
                    {
                        var split = splitText(working);
                        First = split.First().Trim();
                        foreach (var s in split.Skip(1))
                        {
                            m.Append(" ");
                            m.Append(s.Trim());
                        }
                        Middle = m.ToString().Trim();
                    }
                }
            }
            else                            // No commas. Search for common suffixes and assume it's formatted as [First Last]
            {
                if (!working.Contains(" ")) // No space. It's just a last name.
                {
                    Last = working.Trim();
                }
                else
                {
                    // Check for known prefixes.
                    foreach (var prefix in Honorifics.ForParsingName)
                    {
                        if (working.ToLower().StartsWith(prefix.ToLower()))
                        {
                            vsP.Add(prefix);
                            working = working.Substring(prefix.Length).Trim();
                        }
                    }
                    Prefix = vsP.Concatenate(" ");
                    vsP.Clear();

                    var    split = splitText(working).ToList();
                    string suff  = string.Empty;
                    foreach (var s in split)
                    {
                        if (CommonSuffixes.Contains(s, StringComparer.OrdinalIgnoreCase))
                        {
                            suff = s;
                        }
                    }
                    if (!string.IsNullOrEmpty(suff))
                    {
                        split.Remove(suff);
                        Suffix = suff.Trim();
                    }
                    if (split.Count == 1)
                    {
                        Last = split.First().Trim();
                    }
                    else if (split.Count == 2)
                    {
                        First = split.First().Trim();
                        Last  = split.Last().Trim();
                    }
                    else
                    {
                        First = split.First().Trim();
                        Last  = split.Last().Trim();
                        foreach (var s in split.Skip(1).Take(split.Count - 2))
                        {
                            m.Append(" ");
                            m.Append(s);
                        }
                        Middle = m.ToString().Trim();
                    }
                }
            }
        }
        public override void Import()
        {
            base.Import();

            Console.Out.WriteLine("Importing shapefile from \"" + Path + "\"...");

            try
            {
                Dictionary<string, string> importOptionValue = new Dictionary<string, string>();
                string importOptionsPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Path), System.IO.Path.GetFileNameWithoutExtension(Path) + ".att");
                if (File.Exists(importOptionsPath))
                    foreach (string line in File.ReadLines(importOptionsPath))
                    {
                        string[] parts = line.Split('=');
                        importOptionValue.Add(parts[0].Trim(), parts[1].Trim());
                    }

                if (_sourceSRID > 0 && _targetSRID > 0)
                    importOptionValue["reprojection"] = _sourceSRID + ":" + _targetSRID;

                if (!string.IsNullOrWhiteSpace(Name))
                    importOptionValue["name"] = Name;

                List<string> neededValues = new List<string>();
                if (!importOptionValue.ContainsKey("reprojection") || string.IsNullOrWhiteSpace(importOptionValue["reprojection"])) neededValues.Add("reprojection");
                if (!importOptionValue.ContainsKey("name") || string.IsNullOrWhiteSpace(importOptionValue["name"])) neededValues.Add("name");
                if (neededValues.Count > 0)
                {
                    if (_shapefileInfoRetriever == null)
                        throw new Exception("Missing the following shapefile options, and no information retriever was present:  " + neededValues.Concatenate(","));
                    else
                        _shapefileInfoRetriever.GetShapefileInfo(Path, neededValues, importOptionValue);
                }

                string missingValues = neededValues.Where(v => !importOptionValue.ContainsKey(v) || string.IsNullOrWhiteSpace(importOptionValue[v])).Concatenate(", ");
                if (missingValues != "")
                    throw new Exception("Failed to provide needed values for shapefile import:  " + missingValues);

                string reprojection = importOptionValue["reprojection"];
                Match reprojectionMatch = new Regex("(?<from>[0-9]+):(?<to>[0-9]+)").Match(reprojection);
                if (!reprojectionMatch.Success)
                    throw new Exception("Invalid shapefile reprojection \"" + reprojection + "\". Must be in 1234:1234 format.");

                int fromSRID = int.Parse(reprojectionMatch.Groups["from"].Value);
                int toSRID = int.Parse(reprojectionMatch.Groups["to"].Value);
                if (fromSRID == toSRID)
                    reprojection = fromSRID.ToString();

                string name = importOptionValue["name"];
                if (string.IsNullOrWhiteSpace(name))
                    throw new Exception("Empty name given for shapefile \"" + Path + "\".");

                Name = name; // to make sure names retrieved from *.att files get back to the object and ultimately back to the DB

                File.WriteAllText(importOptionsPath, "reprojection=" + fromSRID + ":" + toSRID + Environment.NewLine +
                                                     "name=" + name);

                Shapefile.ShapefileType type;
                if (this is FeatureShapefileImporter)
                    type = Shapefile.ShapefileType.Feature;
                else if (this is AreaShapefileImporter)
                    type = Shapefile.ShapefileType.Area;
                else if (this is IncidentShapefileImporter)
                    type = Shapefile.ShapefileType.Incident;
                else
                    throw new NotImplementedException("Unrecognized shapefile importer type:  " + GetType());

                _importedShapefile = Shapefile.Create(name, toSRID, type);

                string sql;
                string error;
                using (Process process = new Process())
                {
                    process.StartInfo.FileName = Configuration.Shp2PgsqlPath;
                    process.StartInfo.Arguments = "-I -g " + ShapefileGeometry.Columns.Geometry + " -s " + reprojection + " \"" + Path + "\" " + _importedShapefile.GeometryTable;
                    process.StartInfo.CreateNoWindow = true;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardError = true;
                    process.StartInfo.RedirectStandardOutput = true;
                    process.Start();

                    Console.Out.WriteLine("Converting shapefile \"" + name + "\".");

                    sql = process.StandardOutput.ReadToEnd().Replace("BEGIN;", "").Replace("COMMIT;", "");
                    error = process.StandardError.ReadToEnd().Trim().Replace(Environment.NewLine, "; ").Replace("\n", "; ");

                    process.WaitForExit();
                }

                Console.Out.WriteLine(error);

                DB.Connection.ExecuteNonQuery(sql);

                // if there's an id column already, rename it native_id
                if (DB.Connection.GetColumnNames(_importedShapefile.GeometryTable).Select(c => c.ToLower()).Contains("id"))
                {
                    DB.Connection.ExecuteNonQuery("ALTER TABLE " + _importedShapefile.GeometryTable + " DROP COLUMN IF EXISTS native_id;" +
                                                  "ALTER TABLE " + _importedShapefile.GeometryTable + " RENAME COLUMN id TO native_id");
                }

                // rename primary key column to ShapefileGeometry.Columns.Id
                List<string> primaryKeyColumns = DB.Connection.GetPrimaryKeyColumns(_importedShapefile.GeometryTable).ToList();
                if (primaryKeyColumns.Count == 1)
                {
                    if (primaryKeyColumns[0] != ShapefileGeometry.Columns.Id)
                    {
                        DB.Connection.ExecuteNonQuery("ALTER TABLE " + _importedShapefile.GeometryTable + " DROP COLUMN IF EXISTS " + ShapefileGeometry.Columns.Id + ";" +
                                                      "ALTER TABLE " + _importedShapefile.GeometryTable + " RENAME COLUMN " + primaryKeyColumns[0] + " TO " + ShapefileGeometry.Columns.Id);
                    }
                }
                else
                    throw new Exception("Imported shapefile database does not contain a single primary key column.");

                Console.Out.WriteLine("Shapefile import succeeded.");
            }
            catch (Exception ex)
            {
                if (_importedShapefile != null)
                {
                    try { _importedShapefile.Delete(); }
                    catch (Exception ex2) { Console.Out.WriteLine("Failed to delete shapefile:  " + ex2.Message); }
                }

                _importedShapefile = null;

                throw new Exception("Shapefile import failed:  " + ex.Message);
            }
        }
        private void exportThreatSurfaceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CurrentThreatSurface == null)
                MessageBox.Show("No threat surface displayed. Nothing to export.");
            else
            {
                List<string> filters = new List<string>();
                Dictionary<string, ImageFormat> extensionImageFormat = new Dictionary<string, ImageFormat>();
                foreach (ImageFormat format in new ImageFormat[] { ImageFormat.Bmp, ImageFormat.Emf, ImageFormat.Exif, ImageFormat.Gif, ImageFormat.Icon, ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Tiff, ImageFormat.Wmf })
                {
                    string extension = format.ToString().ToLower();
                    filters.Add(format + " image files (*." + extension + ")|*." + extension);
                    extensionImageFormat.Add(extension, format);
                }

                filters.Add("ESRI shapefiles (*.shp)|*.shp");

                filters.Sort();

                string path = LAIR.IO.File.PromptForSavePath("Select export location...", filters.Concatenate("|"));
                if (path != null)
                {
                    if (File.Exists(path))
                        File.Delete(path);

                    string extension = Path.GetExtension(path).Trim('.').ToLower();

                    if (extensionImageFormat.ContainsKey(extension))
                        CurrentThreatSurface.Save(path, extensionImageFormat[extension]);
                    else if (extension == "shp")
                    {
                        NpgsqlCommand cmd = DB.Connection.NewCommand(null);
                        try
                        {
                            cmd.CommandText = "CREATE TABLE temp (" +
                                              "id SERIAL PRIMARY KEY," +
                                              "region GEOMETRY(POLYGON," + DisplayedPrediction.PredictionArea.Shapefile.SRID + ")," +
                                              "level DOUBLE PRECISION," +
                                              "type VARCHAR)";
                            cmd.ExecuteNonQuery();

                            Dictionary<long, List<Tuple<RectangleF, double, string>>> sliceSquareThreatType = new Dictionary<long, List<Tuple<RectangleF, double, string>>>();
                            GetThreatSurfaces(new Rectangle(0, 0, CurrentThreatSurface.Width, CurrentThreatSurface.Height), false, sliceSquareThreatType);
                            string basePath = path;
                            foreach (long slice in sliceSquareThreatType.Keys)
                            {
                                if (slice != -1)
                                    path = Path.Combine(Path.GetDirectoryName(basePath), Path.GetFileNameWithoutExtension(basePath), "_" + slice, Path.GetExtension(basePath));

                                cmd.CommandText = "DELETE FROM temp";
                                cmd.ExecuteNonQuery();

                                int insertNum = 0;
                                int insertsPerBatch = 500;
                                StringBuilder cmdTxt = new StringBuilder();
                                foreach (Tuple<RectangleF, double, string> squareThreatType in sliceSquareThreatType[slice])
                                {
                                    float bottom = squareThreatType.Item1.Bottom;
                                    float left = squareThreatType.Item1.Left;
                                    float top = squareThreatType.Item1.Top;
                                    float right = squareThreatType.Item1.Right;
                                    PostGIS.Polygon polygon = new PostGIS.Polygon(new PostGIS.Point[]{
                                    GetPostGisPointFromDrawingPoint(new PointF(left, bottom)),
                                    GetPostGisPointFromDrawingPoint(new PointF(left, top)),
                                    GetPostGisPointFromDrawingPoint(new PointF(right, top)),
                                    GetPostGisPointFromDrawingPoint(new PointF(right, bottom)),
                                    GetPostGisPointFromDrawingPoint(new PointF(left, bottom))}, DisplayedPrediction.PredictionArea.Shapefile.SRID);

                                    cmdTxt.Append((cmdTxt.Length == 0 ? "INSERT INTO temp (region,level,type) VALUES " : ",") + "(" + polygon.StGeometryFromText + "," +
                                                                                                                                      squareThreatType.Item2 + "," +
                                                                                                                                      "'" + squareThreatType.Item3 + "')");
                                    if ((insertNum++ % insertsPerBatch) == 0)
                                    {
                                        cmd.CommandText = cmdTxt.ToString();
                                        cmd.ExecuteNonQuery();
                                        cmdTxt.Clear();
                                    }
                                }

                                if (cmdTxt.Length > 0)
                                {
                                    cmd.CommandText = cmdTxt.ToString();
                                    cmd.ExecuteNonQuery();
                                    cmdTxt.Clear();
                                }

                                using (Process process = new Process())
                                {
                                    process.StartInfo.FileName = ATT.Configuration.Pgsql2ShpPath;
                                    process.StartInfo.Arguments = "-f \"" + path + "\" " +
                                                                  "-h " + ATT.Configuration.PostgresHost + " " +
                                                                  "-u " + ATT.Configuration.PostgresUser + " " +
                                                                  "-P " + ATT.Configuration.PostgresPassword + " " +
                                                                  ATT.Configuration.PostgresDatabase + " " +
                                                                  "temp";

                                    process.StartInfo.CreateNoWindow = true;
                                    process.StartInfo.UseShellExecute = false;
                                    process.StartInfo.RedirectStandardError = true;
                                    process.StartInfo.RedirectStandardOutput = true;
                                    process.Start();

                                    Console.Out.WriteLine("Exporting threat surface to shapefile \"" + path + "\".");

                                    string output = process.StandardOutput.ReadToEnd().Trim();
                                    string error = process.StandardError.ReadToEnd().Trim();
                                    Console.Out.WriteLine(output + Environment.NewLine + error);

                                    process.WaitForExit();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.Out.WriteLine("Error while exporting threat surface as shapefile:  " + ex.Message);
                            throw ex;
                        }
                        finally
                        {
                            try
                            {
                                cmd.CommandText = "DROP TABLE temp";
                                cmd.ExecuteNonQuery();
                            }
                            catch (Exception ex) { Console.Out.WriteLine("Failed to drop temp table for threat surface export:  " + ex.Message); }

                            DB.Connection.Return(cmd.Connection);
                        }
                    }
                    else
                        MessageBox.Show("The file extension \"" + extension + "\" is not a supported export type.");

                    Console.Out.WriteLine("Export finished.");
                }
            }
        }
Beispiel #23
0
        /// <summary>
        /// Updates the queued report status.
        /// I would prefer this to be an instance method on the GenerationDao (but this is ok for now)
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="reportGenerationQueueId">The report generation queue id.</param>
        /// <param name="reportStatus">The report status.</param>
        /// <param name="executionLog">The execution log.</param>
        /// <param name="queryText">The query text.</param>
        public static void UpdateQueuedReportStatus(
            IReportQueueStatusService service,
            int reportGenerationQueueId,
            ReportStatus reportStatus,
            List<string> executionLog,
            string queryText)
        {
            string executionLogStr = string.Empty;
            string queryTextStr = string.Empty;

            if (reportStatus == ReportStatus.Completed || reportStatus == ReportStatus.Failed)
            {
                executionLogStr = " Execution Log : " + executionLog.Concatenate(System.Environment.NewLine);
                queryTextStr = "QueryText: " + queryText;
            }
            else if (reportStatus == ReportStatus.Cancelled)
            {
                executionLogStr = "-- Report cancelled due to deactivated ReportType";
                queryTextStr = "-- Report cancelled due to deactivated ReportType";
            }

            service.UpdateReportGenerationQueue(new ReportGenerationQueueStatusDto()
            {
                ReportGenerationQueueId = reportGenerationQueueId,
                ReportStatus = reportStatus,
                QueryText = queryTextStr,
                ExecutionLog = executionLogStr
            });
        }
Beispiel #24
0
        bool DumpGitFolders(IActivityMonitor m, IEnumerable <GitFolder> gitFolders)
        {
            bool      isLogFilterDefault = false;
            LogFilter final = m.ActualFilter;

            if (final == LogFilter.Undefined)
            {
                final = ActivityMonitor.DefaultFilter;
                isLogFilterDefault = true;
            }
            var msg = $"Monitor filters: User:'******' => Final:'{final}'{(isLogFilterDefault ? "(AppDomain's default)" : "")}.";

            m.UnfilteredLog(ActivityMonitor.Tags.Empty, LogLevel.Info, msg, m.NextLogTime(), null);

            int  gitFoldersCount    = 0;
            bool hasPluginInitError = false;
            var  dirty = new List <string>();

            foreach (var git in gitFolders)
            {
                ++gitFoldersCount;
                string commitAhead = git.Head.AheadOriginCommitCount != null ? $"{git.Head.AheadOriginCommitCount} commits ahead origin" : "Untracked";
                using (m.OpenInfo($"{git.SubPath} - branch: {git.CurrentBranchName} ({commitAhead})."))
                {
                    string pluginInfo;
                    if (!git.EnsureCurrentBranchPlugins(m))
                    {
                        hasPluginInitError = true;
                        pluginInfo         = "Plugin initialization error.";
                    }
                    else
                    {
                        pluginInfo = $"({git.PluginManager.BranchPlugins[git.CurrentBranchName].Count} plugins)";
                    }

                    if (git.CheckCleanCommit(m))
                    {
                        m.CloseGroup("Up-to-date. " + pluginInfo);
                    }
                    else
                    {
                        dirty.Add(git.SubPath);
                        m.CloseGroup("Dirty. " + pluginInfo);
                    }
                }
            }
            if (gitFoldersCount == 0)
            {
                m.Error("No git folder found.");
            }
            else
            {
                m.CloseGroup($"{dirty.Count} dirty (out of {gitFoldersCount}).");
                if (dirty.Count > 0)
                {
                    m.Info($"Dirty: {dirty.Concatenate()}");
                }
                var byActiveBranch = gitFolders.GroupBy(g => g.CurrentBranchName);
                if (byActiveBranch.Count() > 1)
                {
                    using (m.OpenWarn($"{byActiveBranch.Count()} different branches:"))
                    {
                        foreach (var b in byActiveBranch)
                        {
                            using (m.OpenWarn($"Branch '{b.Key}':"))
                            {
                                m.Warn(b.Select(g => g.SubPath.Path).Concatenate());
                            }
                        }
                    }
                }
                else
                {
                    m.Info($"All {gitFoldersCount} git folders are on '{byActiveBranch.First().Key}' branch.");
                }

                if (hasPluginInitError)
                {
                    m.Error("At least one git folder is unable to initialize its plugins.");
                }
            }
            return(!hasPluginInitError);
        }
Beispiel #25
0
 public override string ToString()
 {
     return(_items.Concatenate(" "));
 }
Beispiel #26
0
        /// <summary>
        /// Renders this surveillance plot
        /// </summary>
        /// <param name="height">Height in pixels</param>
        /// <param name="width">Width in pixels</param>
        /// <param name="includeTitle">Whether or not to include the title</param>
        /// <param name="plotSeriesDifference">Pass non-null to plot a series difference. If both elements are null, the series difference with largest difference is plotted. Or you can pass specific series names to plot a specific difference. If only one series name is provided, the maximum difference between that series and another will be computed.</param>
        /// <param name="blackAndWhite">Whether or not to use black and white only</param>
        /// <param name="args">Additional arguments:  (0) plot margins in 0,0,0,0 format (default is 5,4,4,2), (1) additional arguments to plot and lines commands (e.g., cex), (2) additional arguments to legend command (e.g., cex)</param>
        /// <returns>Path to rendered image file</returns>
        protected override string CreateImageOnDisk(int height, int width, bool includeTitle, Tuple <string, string> plotSeriesDifference, bool blackAndWhite, params string[] args)
        {
            if (args != null && args.Length == 0)
            {
                args = null;
            }

            string        imageOutputPath = Path.GetTempFileName();
            List <string> tmpPaths        = new List <string>();

            #region difference series
            // make sure we have more than one series and that all series have the same x coordinates across the series (i.e., they're comparable)
            if (SeriesPoints.Count == 1 || !SeriesPoints.Keys.All(series => SeriesPoints[series].Count == SeriesPoints.Values.First().Count&& SeriesPoints[series].Zip(SeriesPoints.Values.First(), (p1, p2) => new Tuple <PointF, PointF>(p1, p2)).All(t => t.Item1.X == t.Item2.X)))
            {
                plotSeriesDifference = null;
            }

            string diffSeriesPath = null;
            PointF diffMax        = PointF.Empty;
            PointF diffMin        = PointF.Empty;
            if (plotSeriesDifference != null)
            {
                diffSeriesPath = Path.GetTempFileName();
                tmpPaths.Add(diffSeriesPath);

                Func <List <PointF>, List <PointF>, List <PointF> > seriesDifferencer = new Func <List <PointF>, List <PointF>, List <PointF> >((series1, series2) =>
                                                                                                                                                series1.Zip(series2, (p1, p2) =>
                {
                    if (p1.X != p2.X)
                    {
                        throw new Exception("Differing x values in series comparison");
                    }

                    return(new PointF(p1.X, p2.Y - p1.Y));
                }).ToList());

                List <PointF> diffSeries = null;
                if (plotSeriesDifference.Item1 == null && plotSeriesDifference.Item2 == null)
                {
                    diffSeries = SeriesPoints.Values.SelectMany(series1 => SeriesPoints.Values.Select(series2 => seriesDifferencer(series1, series2))).OrderBy(dSeries => dSeries.Max(p => p.Y)).Last();
                }
                else if (plotSeriesDifference.Item1 != null && plotSeriesDifference.Item2 != null)
                {
                    diffSeries = seriesDifferencer(SeriesPoints[plotSeriesDifference.Item1], SeriesPoints[plotSeriesDifference.Item2]);
                }
                else if (plotSeriesDifference.Item1 != null)
                {
                    diffSeries = SeriesPoints.Values.Select(series2 => seriesDifferencer(SeriesPoints[plotSeriesDifference.Item1], series2)).OrderBy(dSeries => dSeries.Max(p => p.Y)).Last();
                }
                else if (plotSeriesDifference.Item2 != null)
                {
                    diffSeries = SeriesPoints.Values.Select(series1 => seriesDifferencer(series1, SeriesPoints[plotSeriesDifference.Item2])).OrderBy(dSeries => dSeries.Max(p => p.Y)).Last();
                }
                else
                {
                    throw new Exception("Cannot determine difference series");
                }

                using (StreamWriter diffSeriesFile = new StreamWriter(diffSeriesPath))
                {
                    foreach (PointF diffPoint in diffSeries)
                    {
                        diffSeriesFile.WriteLine(diffPoint.X + "," + diffPoint.Y);

                        if (diffMax == PointF.Empty || diffPoint.Y > diffMax.Y)
                        {
                            diffMax = diffPoint;
                        }

                        if (diffMin == PointF.Empty || diffPoint.Y < diffMin.Y)
                        {
                            diffMin = diffPoint;
                        }
                    }

                    diffSeriesFile.Close();
                }
            }
            #endregion

            string imageDevice;
            if (ImageFormat == Format.EPS)
            {
                imageDevice = "postscript(file=\"" + imageOutputPath.Replace(@"\", @"\\") + "\",onefile=FALSE,horizontal=FALSE,width=" + width + ",height=" + height + ")";
            }
            else if (ImageFormat == Format.JPEG)
            {
                imageDevice = "jpeg(filename=\"" + imageOutputPath.Replace(@"\", @"\\") + "\",width=" + width + ",height=" + height + ")";
            }
            else
            {
                throw new Exception("Unrecognized image format:  " + ImageFormat);
            }

            StringBuilder rCmd = new StringBuilder(@"
library(zoo)
" + imageDevice + @"
" + (args == null ? "" : "par(mar=c(" + args[0] + "))") + @"
legend_labels=c()
title.lines = strsplit(strwrap(""" + Title.Replace("\"", "\\\"") + @""",width=0.6*getOption(""width"")), ""\n"")
if(length(title.lines) > 3) { title.lines = title.lines[1:3] }
main.title = paste(title.lines, sep=""\n"")");

            int           seriesNum       = 0;
            string[]      seriesOrder     = new string[SeriesPoints.Count];
            string[]      seriesDiffDummy = plotSeriesDifference == null ? new string[] { } : new string[] { "dummy" };
            List <string> plotCharacters  = SeriesPoints.Keys.OrderBy(k => k).Union(seriesDiffDummy).Select((s, i) => ((i + 1) % 25).ToString()).ToList();                        // R has 25 plot characters indexed starting at 1
            List <string> plotColors      = SeriesPoints.Keys.OrderBy(k => k).Union(seriesDiffDummy).Select((s, i) => blackAndWhite ? "\"black\"" : (i + 1).ToString()).ToList(); // R color numbers start at 1 and wrap
            string        aucOutputPath   = Path.GetTempFileName();
            tmpPaths.Add(aucOutputPath);
            float minY = diffMin == PointF.Empty ? 0f : Math.Min(0, diffMin.Y);
            foreach (string series in SeriesPoints.Keys.OrderBy(k => k))
            {
                string pointsInputPath = Path.GetTempFileName();
                using (StreamWriter pointFile = new StreamWriter(pointsInputPath))
                {
                    foreach (PointF point in SeriesPoints[series])
                    {
                        pointFile.WriteLine(point.X + "," + point.Y);
                    }
                    pointFile.Close();
                }

                tmpPaths.Add(pointsInputPath);

                string plotCharacterVector = "c(" + plotCharacters[seriesNum] + ",rep(NA_integer_," + (SeriesPoints[series].Count / 10) + "))";  // show 10 plot characters for series
                string plotColor           = plotColors[seriesNum];

                string seriesTitle = series.Replace("\"", "\\\"");
                if (seriesTitle.Length > 20)
                {
                    seriesTitle = seriesTitle.Substring(0, 20);
                }

                string plotCommand;
                if (seriesNum == 0)
                {
                    plotCommand = "plot(x,y,type=\"o\",col=" + plotColor + ",pch=" + plotCharacterVector + ",xlim=c(0,1),xlab=\"% area surveilled\",ylim=c(" + minY + ",1),ylab=\"% incidents captured\"" + (includeTitle ? ",main=main.title" : ""); // for the first series, plot the series
                }
                else
                {
                    plotCommand = "lines(x,y,type=\"o\",col=" + plotColor + ",pch=" + plotCharacterVector; // for subsequent series, just plot the series line
                }
                if (args != null)
                {
                    plotCommand += "," + args[1]; // add additional plot arguments, which are passed in
                }
                plotCommand += ")";               // close plot command

                if (seriesNum == 0)
                {
                    plotCommand += Environment.NewLine + "abline(0,1,lty=\"dashed\")"; //  and add the diagonal line for the first series
                }
                rCmd.Append(@"
points = read.csv(""" + pointsInputPath.Replace(@"\", @"\\") + @""",header=FALSE)
x = points[,1]
y = points[,2]
" + plotCommand + @"
idx = order(x)
auc = round(sum(diff(x[idx])*rollmean(y[idx],2)),digits=" + _aucDigits + @")
legend_labels=c(legend_labels,paste(""" + seriesTitle + @" (AUC="",auc,"")"",sep=""""))" + @"
cat(as.character(auc),file=""" + aucOutputPath.Replace(@"\", @"\\") + @""",sep=""\n"",append=TRUE)");

                seriesOrder[seriesNum++] = series;
            }

            #region difference series
            if (plotSeriesDifference != null && diffMax.Y != 0)
            {
                string plotCharacterVector = "c(" + plotCharacters.Last() + ",rep(NA_integer_," + (SeriesPoints.Values.First().Count / 10) + "))";  // show 10 plot characters for series

                rCmd.Append(@"
points = read.csv(""" + diffSeriesPath.Replace(@"\", @"\\") + @""",header=FALSE)
x = points[,1]
y = points[,2]
lines(x,y,type=""o"",col=" + plotColors.Last() + ",pch=" + plotCharacterVector + (args == null ? "" : "," + args[1]) + @")
legend_labels=c(legend_labels,expression(paste(Delta, "" - Peak @ (" + string.Format("{0:0.00},{1:0.00}", diffMax.X, diffMax.Y) + @")"")))
abline(v=" + diffMax.X + @",lty=""dotted"",col=""grey"")
abline(h=" + diffMax.Y + @",lty=""dotted"",col=""grey"")");
            }
            #endregion

            rCmd.Append(@"
grid()
legend(0.4,0.4,legend_labels,pch=c(" + plotCharacters.Concatenate(",") + @"),col=c(" + plotColors.Concatenate(",") + @")" + (args == null ? "" : "," + args[2]) + @",bg=""white"")
dev.off()");

            R.Execute(rCmd.ToString(), false);

            string[] aucOutput = File.ReadLines(aucOutputPath).ToArray();
            if (aucOutput.Length != seriesOrder.Length)
            {
                throw new Exception("Failed to compute AUC for all " + seriesOrder + " surveillance plot series:  " + aucOutput.Length + " of " + seriesOrder.Length + " succeeded.");
            }

            _seriesAUC = new Dictionary <string, float>();
            for (int i = 0; i < aucOutput.Length; ++i)
            {
                _seriesAUC.Add(seriesOrder[i], aucOutput[i] == "NA" ? float.NaN : float.Parse(aucOutput[i]));
            }

            foreach (string tmpPath in tmpPaths)
            {
                File.Delete(tmpPath);
            }

            return(imageOutputPath);
        }