Example #1
0
 public void Parse()
 {
     var categoryPattern = new Regex(@"<a href='\/(.+)'.+перейти к разделу (.+)' class.+</a>");
     var subcategoryPattern = new Regex("<a href=\"(\\/grid[0-9]+?)\"  class=\"LinksDown\">(.+?)<\\/a>");
     var request = (HttpWebRequest) WebRequest.Create(SiteAddress);
     request.ContentType = @"text/html; charset=windows-1251";
     var reader = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.Default);
     var html = reader.ReadToEnd();
     var matches = categoryPattern.Matches(html);
     var categories = new Dictionary<string, string>();
     var subcategories = new Dictionary<string, string>();
     for (var i = 0; i < matches.Count; i++) {
         categories.Add(matches[i].Groups[2].ToString(), matches[i].Groups[1].ToString());
         Console.WriteLine(categories.Last().Key + "   " + categories.Last().Value);
     }
     Console.WriteLine("\n");
     foreach (var category in categories) {
         request = (HttpWebRequest)WebRequest.Create(SiteAddress + category.Value);
         reader = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.Default);
         html = reader.ReadToEnd();
         matches = subcategoryPattern.Matches(html);
         for (var i = 0; i < matches.Count; i++) {
             if (!subcategories.ContainsKey(matches[i].Groups[2].ToString())) {
                 subcategories.Add(matches[i].Groups[2].ToString(), matches[i].Groups[1].ToString());
             }
             // Console.WriteLine(subcategories.Last().Key + "   " + subcategories.Last().Value + "\n");
         }
     }
 }
        public void StringJoinTestCase()
        {
            var dictionary = new Dictionary<String, String>
            {
                { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() },
                { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() }
            };

            var actual = dictionary.StringJoin();
            var expected = "{0}={1}{2}={3}".F( dictionary.First()
                                                         .Key,
                                               dictionary.First()
                                                         .Value,
                                               dictionary.Last()
                                                         .Key,
                                               dictionary.Last()
                                                         .Value );
            Assert.AreEqual( expected, actual );

            actual = dictionary.StringJoin( ",", ";" );
            expected = "{0},{1};{2},{3}".F( dictionary.First()
                                                      .Key,
                                            dictionary.First()
                                                      .Value,
                                            dictionary.Last()
                                                      .Key,
                                            dictionary.Last()
                                                      .Value );
            Assert.AreEqual( expected, actual );
        }
        public Dictionary<DateTime, decimal> Calculate()
        {
            var returnDictionary = new Dictionary<DateTime, decimal>();

            if (this.signals.Any())
            {
                returnDictionary.Add(this.signals.ElementAt(0).Date, this.startingEquity);

                var count = this.signals.Count();

                for (var i = 0; i <= count - 2; i++)
                {
                    var originalSignal = this.signals.ElementAt(i).SignalType;
                    if (originalSignal == SignalType.TakeProfits)
                    {
                        returnDictionary.Add(this.signals.ElementAt(i + 1).Date,
                                             returnDictionary.OrderBy(d => d.Key).Last().Value);
                        continue;
                    }

                    var startTradePrice = this.signals.ElementAt(i).Price;
                    var finalTradePrice = this.signals.ElementAt(i + 1).Price;
                    var percentageDifference = (finalTradePrice - startTradePrice)/startTradePrice;
                    var percentageDifferenceToEquity = originalSignal == SignalType.Buy && percentageDifference > 0 ||
                                                       originalSignal == SignalType.Sell && percentageDifference < 0
                                                           ? Math.Abs(percentageDifference)
                                                           : -Math.Abs(percentageDifference);
                    var newEquityValue = returnDictionary.Last().Value +
                                         (returnDictionary.Last().Value*percentageDifferenceToEquity);
                    returnDictionary.Add(this.signals.ElementAt(i + 1).Date, newEquityValue);
                }
            }

            return returnDictionary;
        }
        public void Parse_Normal_String()
        {
            const string attributes = "media:print";
            var destination = new Dictionary<string, string>();

            HtmlAttributesStringParser.ParseIntoDictionary(attributes, destination);

            Assert.AreEqual(1, destination.Count);
            Assert.AreEqual("print", destination.Last().Value);
            Assert.AreEqual("media", destination.Last().Key);

        }
        public void Parse_Delimited_String_With_Comma()
        {
            const string attributes = "media:'print, projection'";
            var destination = new Dictionary<string, string>();
            
            HtmlAttributesStringParser.ParseIntoDictionary(attributes, destination);
            
            Assert.AreEqual(1, destination.Count);
            Assert.AreEqual("print, projection", destination.Last().Value);
            Assert.AreEqual("media", destination.Last().Key);

        }
        public void Parse_Media_Query()
        {
            const string attributes = "media:(max-width:560px)";
            var destination = new Dictionary<string, string>();

            HtmlAttributesStringParser.ParseIntoDictionary(attributes, destination);

            Assert.AreEqual(1, destination.Count);
            Assert.AreEqual("(max-width:560px)", destination.Last().Value);
            Assert.AreEqual("media", destination.Last().Key);

        }
 public TagCloudService(Dictionary<string, int> Tags, int Width, int Height)
 {
     _Increment = It => It + _SpiralRoom;
         _Decrement = It => It - _SpiralRoom;
         if (null == Tags || 0 == Tags.Count)
             _Die("Argument Exception, No Tags to disorganize");
         if (Width < 30 || Height < 30)
             _Die("Way too low Width or Height for the cloud to be useful");
         _Width = Width;
         _Height = Height;
         _MainArea = new RectangleF(0, 0, Width, Height);
         _MaxEdgeSize = Width >= Height ? Width : Height;
         /* Sentinel is a definitely out of bounds point that the spiral normally
          * should never reach. */
         _SpiralEndSentinel = new PointF(_MaxEdgeSize + 10, _MaxEdgeSize + 10);
         var Sorted = from Tag in Tags
                      orderby Tag.Value descending
                      select new {Tag.Key, Tag.Value};
         _TagsSorted = Sorted.ToDictionary(x => x.Key, x => x.Value);
         _LowestWeight = _TagsSorted.Last().Value;
         _HighestWeight = _TagsSorted.First().Value;
         _Occupied = new List<RectangleF>(_TagsSorted.Count + 4);
         WordsSkipped = new Dictionary<string, int>();
         ApplyDefaults();
 }
Example #8
0
 internal List<Right> GetBexisRights(string dataBase,  Dictionary<int, int> dataSetsMapping)
 {
     List<Right> bexisRights = new List<Right>();
     string datasetQuery = "";
     foreach (var dataSetMapping in dataSetsMapping)
     {
         datasetQuery += "DATASETID = "+ dataSetMapping.Key;
         if (dataSetsMapping.Last().Key != dataSetMapping.Key)
             datasetQuery += " or ";
     }
     if (dataSetsMapping.Any())
     {
         datasetQuery = "where " + datasetQuery + "";
     }
     // DB query
     string mySelectQuery = "SELECT ROLENAME, DATASETID, FOREDIT, APPLICATIONNAME FROM \"PROVIDER\".\"RIGHTS\"   "+ datasetQuery;
     DB2Connection connect = new DB2Connection(dataBase);
     DB2Command myCommand = new DB2Command(mySelectQuery, connect);
     connect.Open();
     DB2DataReader myReader = myCommand.ExecuteReader();
     while (myReader.Read())
     {
         bexisRights.Add(new Right()
         {
             RoleName = myReader.GetString(0),
             DataSetId = (int)(myReader.GetValue(1)),
             CanEdit = myReader.GetString(2)=="N"?false:true
         });
     }
     myReader.Close();
     connect.Close();
     return bexisRights;
 }
Example #9
0
 public TagCloudService(Dictionary<string, int> tags, int width, int height)
 {
     increment = x => x + spiralRoom;
     decrement = x => x - spiralRoom;
     if (null == tags || 0 == tags.Count)
         die("Argument Exception, No Tags to disorganize");
     if (width < 30 || height < 30)
         die("Way too low Width or Height for the cloud to be useful");
     this.width = width;
     this.height = height;
     mainArea = new RectangleF(0, 0, width, height);
     MaxEdgeSize = width >= height ? width : height;
     /* Sentinel is a definitely out of bounds point that the spiral normally
      * should never reach. */
     spiralEndSentinel = new PointF(MaxEdgeSize + 10, MaxEdgeSize + 10);
     var sorted = from tag in tags
                  orderby tag.Value descending
                  select new {tag.Key, tag.Value};
     tagsSorted = sorted.ToDictionary(x => x.Key, x => x.Value);
     lowestWeight = tagsSorted.Last().Value;
     highestWeight = tagsSorted.First().Value;
     Occupied = new List<RectangleF>(tagsSorted.Count + 4);
     WordsSkipped = new Dictionary<string, int>();
     ApplyDefaults();
 }
            public void AggregatesDataIntoDictionary()
            {
                var lastReductionTime = new DateTime(2011, 11, 11, 5, 30, 0, 0);
                var reduceLevel = new ReduceLevel { Resolution = 5000 };
                var sourceAggregationList = new List<MonitorRecord<double>>
                                                {
                                                    new MonitorRecord<double>(new DateTime(2011, 11, 11, 5, 30, 0, 500), 5, 5),
                                                    new MonitorRecord<double>(new DateTime(2011, 11, 11, 5, 30, 1, 0), 25, 4),
                                                    new MonitorRecord<double>(new DateTime(2011, 11, 11, 5, 30, 1, 500), 7, 8),
                                                    new MonitorRecord<double>(new DateTime(2011, 11, 11, 5, 30, 40, 0), 3, 3)
                                                };
                var destination = new Dictionary<DateTime, IList<MonitorRecord<double>>>();

                var aggregater = new RecordReduceAggregate();
                var result = aggregater.Aggregate(lastReductionTime, reduceLevel, sourceAggregationList, destination);

                Assert.Equal(2, destination.Count());

                var firstItem = destination.First();
                Assert.Equal(new DateTime(2011, 11, 11, 5, 30, 2, 500), firstItem.Key);
                Assert.Equal(3, firstItem.Value.Count);

                var lastItem = destination.Last();
                Assert.Equal(new DateTime(2011, 11, 11, 5, 30, 42, 500), lastItem.Key);
                Assert.Equal(1, lastItem.Value.Count);
            }
        public void ContainsAllKeyTestCase()
        {
            var dictionary = new Dictionary<String, String>
            {
                { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() },
                { RandomValueEx.GetRandomString(), RandomValueEx.GetRandomString() }
            };

            Assert.IsTrue( dictionary.ContainsAllKey( dictionary.First()
                                                                .Key,
                                                      dictionary.Last()
                                                                .Key ) );
            Assert.IsFalse( dictionary.ContainsAllKey( dictionary.First()
                                                                 .Key,
                                                       dictionary.Last()
                                                                 .Key,
                                                       "test" ) );
        }
        //creates a single list of strings from a Dictionary doesnt preserve ItemTypes!
        // deprecated
        private List<string> concatLists(Dictionary<string,List<string>> tokens)
        {
            List<string> result = new List<string>();
            object last = tokens.Last();

            foreach (KeyValuePair<string,List<string>> ol in tokens) {
                result.AddRange(ol.Value);
            }
            return result;
        }
Example #13
0
        public static string ConvertToJsObject(Dictionary<string, object> options)
        {
            var config = new StringBuilder();

            config.Append("{");
            foreach (var item in options)
            {
                config.AppendFormat(" {0}: {1}{2} ", item.Key, item.Value, options.Last().Equals(item) ? "" : ",");
            }
            config.Append("}");
            return config.ToString();
        }
 public void GetDictionaryFromSessionWhenStoredInSessionAsSerializedStringShouldReturnTheDictionary()
 {
     var environment = GetEnvironment();
     var expected = new Dictionary<Guid, string>();
     expected.Add(Guid.NewGuid(), "Main");
     expected.Add(Guid.NewGuid(), "Sub");
     _sessionMock.Setup(s => s["testdictionary"]).Returns(JsonConvert.SerializeObject(expected));
     var result = environment.GetFromSession<Dictionary<Guid, string>>("testdictionary");
     Assert.IsNotNull(result);
     Assert.AreEqual(expected.First().Key, result.First().Key);
     Assert.AreEqual(expected.Last().Value, result.Last().Value);
 }
Example #15
0
        public static string ToJson(Dictionary<string, string> variables)
        {
            var builder = new StringBuilder();
            builder.AppendLine("{");
            var last = variables.Last().Key;
            foreach (var variable in variables)
            {
                var isLast = (variable.Key == last);
                int value;
                if (int.TryParse(variable.Value, out value))
                    builder.AppendLineFormat("  \"{0}\":{1}{2}", variable.Key, value, isLast ? string.Empty : ",");
                else
                    builder.AppendLineFormat("  \"{0}\":\"{1}\"{2}", variable.Key, variable.Value, isLast ? string.Empty : ",");
            }

            builder.Append("}");
            return builder.ToString();
        }
Example #16
0
        public async Task<Dictionary<string, List<MalProfileHistoryEntry>>> GetProfileHistory()
        {
            var output = new Dictionary<string, List<MalProfileHistoryEntry>>();

            var raw = await GetRequestResponse();
            if (string.IsNullOrEmpty(raw))
                return null;
            var doc = new HtmlDocument();
            doc.LoadHtml(raw);
            foreach (var historyRow in doc.DocumentNode.Descendants("tr"))
            {
                try
                {
                    //so this is one big table if it contains only on chld it means that it's day/week header so
                    if (historyRow.ChildNodes.Count == 3)
                    {
                        if(historyRow.InnerText.Trim() == "&nbsp;")
                            continue;
                        output.Add(historyRow.InnerText.Trim(), new List<MalProfileHistoryEntry>());
                    }
                    else
                    {
                        var current = new MalProfileHistoryEntry();

                        var link = historyRow.Descendants("a").First();
                        current.Id = int.Parse(link.Attributes["href"].Value.Split('=').Last());
                        current.IsAnime = link.Attributes["href"].Value.Contains("/anime");
                        current.WatchedEpisode = int.Parse(historyRow.Descendants("strong").First().InnerText);
                        current.Date = historyRow.Descendants("td").Last().InnerText; //skip "Edit" button
                        output.Last().Value.Add(current);
                    }
                }
                catch (Exception e)
                {
                    //html
                }

            }

            return output;
        }
		/// <summary>
		/// Строит диаграмму для интервального ряда
		/// </summary>
		/// <param name="intervalFreq">Интервальный ряд</param>
		public void Plot(Dictionary<Range, double> data, Color color)
		{
			//Вывод графика
			var pane = graph.GraphPane;
			double maxY = 0;

			//Находим интервалы
			var intervals = new double[data.Count];
			var height = new double[data.Count];
			var xi = new double[data.Count];

			//МЕГАКОСТЫЛь. Зря я использовал Dictionary
			int i = 0;
			foreach (var x in data)
			{
				intervals[i] = x.Key.Length;
				height[i] = x.Value / intervals[i];
				xi[i] = x.Key.Left;
				i++;
			}

			//Рисуем гистограмму
			for (i = 0; i < height.Length; i++)
			{
				var box = new BoxObj((float)xi[i], (float)height[i], (float)intervals[i], (float)height[i], Color.Black, color);

				pane.GraphObjList.Add(box);
				if (height[i] > maxY) maxY = height[i];
			}



			//Настраиваем масштаб
			pane.XAxis.Scale.Min = data.First().Key.Left;
			pane.XAxis.Scale.Max = data.Last().Key.Right;
			pane.YAxis.Scale.Min = 0;
			pane.YAxis.Scale.Max = maxY * 1.1;

			graph.AxisChange();
			graph.Invalidate();
		}
        // The rules of this error is specified here: https://github.com/stubbornella/csslint/wiki/Disallow-duplicate-properties
        public ItemCheckResult CheckItem(ParseItem item, ICssCheckerContext context)
        {
            RuleBlock rule = (RuleBlock)item;

            if (!rule.IsValid || context == null)
                return ItemCheckResult.Continue;

            Dictionary<string, string> dic = new Dictionary<string, string>();

            foreach (Declaration declaration in rule.Declarations)
            {
                ParseItem prop = declaration.PropertyName;
                if (prop == null || prop.Text == "filter")
                    continue;

                string error = null;

                if (!dic.ContainsKey(declaration.Text))
                {
                    if (dic.ContainsValue(prop.Text) && dic.Last().Value != prop.Text)
                    {
                        // The same property name is specified, but not by the immidiate previous declaration
                        error = string.Format(CultureInfo.InvariantCulture, Resources.BestPracticeDuplicatePropertyInRule, prop.Text);
                    }

                    dic.Add(declaration.Text, prop.Text);
                }
                else
                {
                    // The same property and value exist more than once in the rule. The exact declaration duplicate
                    error = string.Format(CultureInfo.InvariantCulture, Resources.BestPracticeDuplicatePropertyWithSameValueInRule, prop.Text);
                }

                if (error != null)
                {
                    context.AddError(new SimpleErrorTag(prop, error));
                }
            }

            return ItemCheckResult.Continue;
        }
Example #19
0
        void TestXml(string input, string output)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(input);

            string xdimension;
            string ydimension;
            Dictionary<string, string> properties = new Dictionary<string, string>();

            XmlNode mapNode = doc.DocumentElement.SelectSingleNode("/map");
            XmlNode propertiesNode = doc.DocumentElement.SelectSingleNode("/map/properties");
            XmlNode dataNode = doc.DocumentElement.SelectSingleNode("/map/layer[@name='Tiles']/data");

            xdimension = mapNode.Attributes["width"].InnerText;
            ydimension = mapNode.Attributes["height"].InnerText;

            foreach (XmlNode node in propertiesNode.ChildNodes)
            {
                properties.Add(node.Attributes["name"].Value, node.Attributes["value"].Value);
            }
            string level = dataNode.InnerText.Replace(",", "");
            level = Regex.Replace(level, @"\r\n?|\n", "");

            string json = "{ \"level\":\"" + level + "\",\"xdimension\":" + xdimension + ",\"ydimension\":" + ydimension + ",";

            foreach (KeyValuePair<string, string> entry in properties)
            {
                json += "\"" + entry.Key + "\":" + entry.Value;
                if (!properties[entry.Key].Equals(properties.Last().Value))
                {
                    json += ",";
                }
            }
            json += "}";

            Console.WriteLine("Writing " + json);
            Console.WriteLine("To " + output);
            File.WriteAllText(output, json);
        }
        protected override VerificationResult CreateResult(
            string asm, 
            string list, 
            Dictionary<int, string> testValues, 
            CpuErrorCode error)
        {
            var ast = AphidParser.Parse(asm);

            if (testValues.Any(x => x.Value == "x"))
            {
                var r = testValues.Last(x => x.Value == "1");

                var exp = ast[r.Key];

                return new VerificationResult(
                    false,
                    string.Format("Instruction hung: {0}", exp),
                    list,
                    error);
            }

            return new VerificationResult(testValues.All(x => x.Value == "1"), list, error);
        }
        public ApplicationCanvas()
        {
            r.Fill = Brushes.Red;
            r.AttachTo(this);
            r.MoveTo(8, 8);
            this.SizeChanged += (s, e) => r.SizeTo(this.Width - 16.0, this.Height - 16.0);

            var Options = new Dictionary<Type, Func<int>>
			{
				{ typeof(Canvas), 
					() => 78
				},
				{ typeof(ApplicationCanvas), 
					() => 88
				}
            };

            var t = new TextBox { AcceptsReturn = true, IsReadOnly = true }.AttachTo(this);

            t.AppendTextLine(new { First = new { Options.First().Key.Name } }.ToString());
            t.AppendTextLine(new { Last = new { Options.Last().Key.Name } }.ToString());

            t.AppendTextLine(new { FirstKey = new { Options.Keys.First().Name } }.ToString());
            t.AppendTextLine(new { LastKey = new { Options.Keys.Last().Name } }.ToString());


            Options
                //.ForEach(
               .Select(Option => new { Option.Key, Option.Value })
               .WithEachIndex(
               (Option, Index) =>
               {
                   t.AppendTextLine(new { Option.Key.Name }.ToString());

               }
           );
        }
            /// <summary>
            /// Searches for duplicates or similar images and groups them into a DuplicateImage-Instance.
            /// </summary>
            /// <param name="path">The directory to search through.</param>
            protected override IEnumerable<DuplicateImages> FindDuplicates(Dictionary<FileInfo, ulong> images)
            {
                if (images != null)
                {
                    var __distance = GetHammingDistance(images.First().Value, images.Last().Value);

                    //todo: Plainest approach, find something smarter...
                    var __copyList = new Dictionary<FileInfo, ulong>(images);
                    var __duplicates = new List<DuplicateImages>();

                    foreach (var __image in __copyList)
                    {
                        if (images.ContainsKey(__image.Key))
                        {
                            var __group = __copyList.Where(i => GetHammingDistance(__image.Value, i.Value) < 4).ToList();   //todo: Hamming distance max. 3
                            if (__group.Count() > 1) __duplicates.Add(new DuplicateImages(__group.Select(e => new DuplicateImage(e.Key, e.Value))));
                            __group.ForEach(e => images.Remove(e.Key)); //Remove from the list, so the images won't be found twice
                        }
                    }
                    return __duplicates;
                }

                return null;
            }
 public void LoadState()
 {
     using (var sr = new StreamReader(new FileStream(_featureRequestsFilePath, FileMode.OpenOrCreate)))
     {
         var str = sr.ReadToEnd();
         if (str.Length > 0)
         {
             Dictionary<int, string> config = null;
             try
             {
                 config = JsonConvert.DeserializeObject<Dictionary<int, string>>(str);
             }
             catch (Exception ex)
             {
                 Log.Logger.Error("An error as occured during parsing of {0} file. Error message: {1}", _featureRequestsFilePath, ex.Message);
             }
             if (config != null)
             {
                 _requests = config;
                 _requestIndex = _requests.Last().Key + 1;
             }
         }
         else
         {
             Log.Logger.Warning("The file {0} was expected to be populated with data, but was empty.", _featureRequestsFilePath);
         }
     }
 }
        /// <summary>
        /// salt Split Degradation Calculator
        /// </summary>
        /// <param name="numberOfWeeks">number of Weeks</param>
        /// <param name="maximumDegradationSaltSplit">maximum Degradation Salt Split</param>
        /// <param name="startingSaltSplit">Starting Salt Split</param>
        /// <returns>Returns dictionary</returns>
        private Dictionary<double, double> SaltSplitDegradationCalculator(double numberOfWeeks, double maximumDegradationSaltSplit, double startingSaltSplit)
        {
            try
            {
                Dictionary<double, double> saltSplitDegradation = new Dictionary<double, double>();
                Dictionary<double, double> saltSplitCurve = new Dictionary<double, double>();
                double baseCurveFactor = numberOfWeeks / 312;
                double[] degPoly = new double[5];
                degPoly[0] = 1.93647597707001E-10;
                degPoly[1] = -1.71818433081473E-07;
                degPoly[2] = 0.0000450031960953974;
                degPoly[3] = -0.001102430677463;
                degPoly[4] = 0.009638951553683;
                double degradation = 0;
                for (int week = 1; week <= 312; week++)
                {
                    if (week > 6)
                    {
                        degradation = (Math.Pow(week, 4) * degPoly[0]) + (Math.Pow(week, 3) * degPoly[1]) + (Math.Pow(week, 2) * degPoly[2]) + (week * degPoly[3]) + degPoly[4];
                        saltSplitDegradation.Add(week, degradation);
                    }
                    else
                    {
                        if (week != 1)
                        {
                            degradation += 0.0001;
                        }
                        saltSplitDegradation.Add(week, degradation);
                    }

                }
                foreach (var wklyReductionVal in saltSplitDegradation)
                {
                    double finalVal = saltSplitDegradation.Last().Value;
                    double curveValue = ((wklyReductionVal.Value * maximumDegradationSaltSplit * 0.01) / (finalVal != 0 ? finalVal : 1));
                    double weekNum = wklyReductionVal.Key * baseCurveFactor;
                    saltSplitCurve.Add(weekNum, curveValue);

                }
                Dictionary<double, double> curve = CurveSlopeSmoother(saltSplitCurve, startingSaltSplit);
                return curve;
            }
            catch
            {
                throw;
            }
        }
Example #25
0
    /// <summary>
    /// returns the highest quality download options for a given preferred quality
    /// </summary>
    internal static KeyValuePair<string, string> GetPreferredQualityOption(Dictionary<string, string> downloadOptions, string preferredQuality)
    {
      // available mp4 options are:
      // 1. 320x240
      // 2. 426x240
      // 3. 640x360
      // 4. 1280x720
      // 5. 1920x1080 (currently no high resolutions supported by OV due to split video/audio and missing support in URLsplitter)

      IEnumerable<KeyValuePair<string, string>> options;
      switch (preferredQuality)
      {
        case "FHD":
          options = downloadOptions.Where(o => o.Key.Contains("1080"));
          if (options.Any())
          {
            return new KeyValuePair<string, string>(options.First().Key, options.First().Value);
          }
          else
          {
            return GetPreferredQualityOption(downloadOptions, "HD");
          }
        case "HD":
          options = downloadOptions.Where(o => o.Key.Contains("720"));
          if (options.Any())
          {
            return new KeyValuePair<string, string>(options.First().Key, options.First().Value);
          }
          else
          {
            return GetPreferredQualityOption(downloadOptions, "HQ");
          }
        case "HQ":
          options = downloadOptions.Where(o => o.Key.Contains("640x360 | mp4"));
          if (options.Any())
          {
            return new KeyValuePair<string, string>(options.First().Key, options.First().Value);
          }
          else
          {
            return GetPreferredQualityOption(downloadOptions, "LQ");
          }
        case "LQ":
          options = downloadOptions.Where(o => o.Key.Contains("426x240 | mp4"));
          if (options.Any())
          {
            return new KeyValuePair<string, string>(options.First().Key, options.First().Value);
          }
          else
          {
            return GetPreferredQualityOption(downloadOptions, "BadQ");
          }
        case "BadQ":
          options = downloadOptions.Where(o => o.Key.Contains("320x240 | mp4"));
          if (options.Any())
          {
            return new KeyValuePair<string, string>(options.First().Key, options.First().Value);
          }
          else
          {
            // use any available ...
            return GetPreferredQualityOption(downloadOptions, "");
          }

        default:
          // return any trailer, take last in the list, assuming that is best quality
          if (downloadOptions.Any())
          {
            return new KeyValuePair<string, string>(downloadOptions.Last().Key, downloadOptions.Last().Value);
          }
          break;
      }

      // no videos available
      return new KeyValuePair<string, string>(null, null);
    }
Example #26
0
        public void NavigateToFolder(string path, Dictionary<string, IEnumerable<string>> neighborList)
        {
            var navigationList = PathToDirectoryList(path);
            if (!navigationList.Any())
                return;

            if (_fileCombo != null && _fileCombo.Visible)
            {
                _fileCombo.Visible = false;
                Controls.Remove(_fileCombo);
            }

            //check for higher level roots
            while (neighborList.Last().Key != navigationList.First())
            {
                if (navigationList.Count == 1)
                    return;
                navigationList[0] = Path.Combine(navigationList[0], navigationList[1]);
                navigationList.RemoveAt(1);
            }

            ShowHiddenCrumbs();

            //confirm or set root
            if (BreadCrumbTrail.Items.Count < 3
                || BreadCrumbTrail.Items[2].Text != navigationList[0])
                SetRoot(navigationList[0], neighborList);

            var pathSoFar = new StringBuilder(navigationList[0].TrimEnd('\\'));
            navigationList.RemoveAt(0);
            var expectedNext = 4;

            //go through, add as needed and remove where not
            foreach (var item in navigationList)
            {
                pathSoFar.AppendFormat(@"\{0}", item);
                if (BreadCrumbTrail.Items.Count > expectedNext)
                {
                    var fullName = ((string) BreadCrumbTrail.Items[expectedNext].Tag);
                    if (fullName.ToLower() == pathSoFar.ToString().ToLower())
                    {
                        expectedNext += 2;
                        continue;
                    }
                    for (var x = BreadCrumbTrail.Items.Count - 1; x >= expectedNext - 1; x--)
                    {
                        var itemToRemove = BreadCrumbTrail.Items[x];
                        if (_itemNeighbors.ContainsKey((ToolStripMenuItem) itemToRemove))
                            _itemNeighbors.Remove((ToolStripMenuItem) itemToRemove);
                        BreadCrumbTrail.Items.Remove(itemToRemove);
                    }
                }

                //add neighbor directories
                var neighborTSMI = new ToolStripMenuItem(Properties.Resources.Right_Arrow)
                                       {Padding = new Padding(0), ImageScaling = ToolStripItemImageScaling.None};
                foreach (var dir in neighborList[pathSoFar.ToString()])
                {
                    var newitem = new ToolStripMenuItem(Path.GetFileName(dir)) {Tag = dir};
                    newitem.Click += ClickItem;
                    neighborTSMI.DropDownItems.Add(newitem);
                }
                BreadCrumbTrail.Items.Add(neighborTSMI);

                //add main directory
                var mainTSMI = new ToolStripMenuItem(item) {Tag = pathSoFar.ToString()};
                mainTSMI.Click += ClickItem;
                BreadCrumbTrail.Items.Add(mainTSMI);
                expectedNext += 2;

                _itemNeighbors.Add(mainTSMI, neighborTSMI);
            }

            for (var x = BreadCrumbTrail.Items.Count - 1; x >= expectedNext - 1; x--)
            {
                var itemToRemove = BreadCrumbTrail.Items[x];
                if (_itemNeighbors.ContainsKey((ToolStripMenuItem) itemToRemove))
                    _itemNeighbors.Remove((ToolStripMenuItem) itemToRemove);
                BreadCrumbTrail.Items.RemoveAt(x);
            }

            _overflowStack = new Stack<ToolStripMenuItem>();
            CheckBreadcrumbSize();
        }
Example #27
0
        protected string ParseHosterLinks(string link, VideoInfo video)
        {
            string webData = GetWebData<string>(link);
            Dictionary<string, string> options = new Dictionary<string, string>();

            foreach (HosterBase hosterUtil in HosterFactory.GetAllHosters())
            {
                string regEx = @"(""|')(?<url>[^(""|')]+" + hosterUtil.GetHosterUrl().ToLower() + @"[^(""|')]+)(""|')";

                MatchCollection n = Regex.Matches(webData, regEx);
                List<string> results = new List<string>();
                foreach (Match m in n)
                {
                    if (!results.Contains(m.Groups["url"].Value))
                        results.Add(m.Groups["url"].Value);
                }

                foreach (string url in results)
                {
                    string decodedUrl = HttpUtility.HtmlDecode(url);
                    if (Uri.IsWellFormedUriString(decodedUrl, System.UriKind.Absolute))
                    {
                        Uri uri = new Uri(decodedUrl);
                        if (!(uri.Host.Length == uri.AbsoluteUri.Length))
                        {
                            if (decodedUrl.Contains("\\/")) decodedUrl = decodedUrl.Replace("\\/", "/");

                            if (results.Count > 1)
                            {
                                int i = 1;
                                string playbackName = hosterUtil.GetHosterUrl() + " - " + i + "/" + results.Count;
                                while (options.ContainsKey(playbackName))
                                {
                                    i++;
                                    playbackName = hosterUtil.GetHosterUrl() + " - " + i + "/" + results.Count;
                                }
                                options.Add(playbackName, decodedUrl);
                            }
                            else
                                options.Add(hosterUtil.GetHosterUrl(), decodedUrl);
                        }
                    }
                }
            }
            if (options != null && options.Count > 0)
            {
                if (video.PlaybackOptions == null)
                {
                    if (options.Count > 1)
                    {
                        video.PlaybackOptions = new Dictionary<string, string>();
                        foreach (KeyValuePair<String, String> entry in options) video.PlaybackOptions.Add(entry.Key, entry.Value);
                    }
                    else
                        return options.Last().Value;
                }
                else
                    foreach (KeyValuePair<String, String> entry in options)
                    {
                        if (video.PlaybackOptions.ContainsKey(entry.Key))
                        {
                            int i = 2;
                            while (video.PlaybackOptions.ContainsKey(entry.Key + " - " + i))
                                i++;
                            video.PlaybackOptions.Add(entry.Key + " - " + i, entry.Value);
                        }
                        else
                            video.PlaybackOptions.Add(entry.Key, entry.Value);
                    }
                return options.Last().Value;

            }
            else
                return String.Empty;
        }
        /// <summary>
        /// Standard Deviation Data By Week
        /// </summary>
        /// <param name="conductivityData">conductivity Data</param>
        /// <param name="sourceNumber">source Number</param>
        private void StandardDeviationDataByWeek(Dictionary<DateTime, Tuple<int, int>> conductivityData, int sourceNumber)
        {
            try
            {
                DateTime firstDate = new DateTime();
                if (conductivityData != null && conductivityData.Count > 0)
                {
                    firstDate = conductivityData.FirstOrDefault().Key;
                }
                DateTime lastDate = new DateTime();
                if (conductivityData != null && conductivityData.Count > 0)
                {
                    lastDate = conductivityData.Last().Key;
                }
                int weeks = Convert.ToInt32(((lastDate - firstDate).TotalDays / 7) + 1);
                List<int>[] groupedWeekCondData = new List<int>[weeks];
                DateTime previousDate = new DateTime();
                if (conductivityData != null && conductivityData.Count > 0)
                {
                    previousDate = conductivityData.FirstOrDefault().Key;
                }
                int nextWeek = 0;
                if (conductivityData != null && conductivityData.Count > 0)
                {
                    nextWeek = WeekNumberCalculator(conductivityData.FirstOrDefault().Key.AddDays(7));
                }
                int i = 0;
                foreach (var entry in conductivityData)
                {
                    int currentWeek = WeekNumberCalculator(entry.Key);
                    int standardDeviation;
                    if (currentWeek != nextWeek && !this.dataForWeekToAverage.Keys.Contains(entry.Key))
                    {
                        this.dataForWeekToAverage.Add(entry.Key, entry.Value);
                    }
                    else
                    {
                        List<int> valuesForWeek = new List<int>();
                        foreach (var condVal in this.dataForWeekToAverage.Values)
                        {
                            valuesForWeek.Add(condVal.Item2);
                        }
                        groupedWeekCondData[i] = valuesForWeek;
                        if (valuesForWeek.Count > 1)
                        {
                            standardDeviation = Convert.ToInt32(StandardDeviation(valuesForWeek));

                        }
                        else
                        {
                            standardDeviation = 0;
                        }
                        Tuple<int, int, List<int>> weekCondVal = new Tuple<int, int, List<int>>(currentWeek, standardDeviation, groupedWeekCondData[i]);
                        if (sourceNumber == 1)
                        {
                            weeklyStandardDeviationConductivityDataSource1.Add(entry.Key, weekCondVal);
                        }
                        else
                        {
                            this.weeklyStandardDeviationConductivityDataSource2.Add(entry.Key, weekCondVal);
                        }
                        nextWeek = WeekNumberCalculator(entry.Key.AddDays(7));
                        this.dataForWeekToAverage.Clear();
                    }
                    previousDate = entry.Key;
                }
            }
            catch
            {
                throw;
            }
        }
Example #29
0
        public override String GetVideoUrl(VideoInfo video)
        {
            string webData = GetWebData(video.VideoUrl);
            if (!webData.StartsWith("{")) // videos in serwisy informacyjne
            {
                Match m = Regex.Match(webData, @"<iframe\s*src=""//www\.tvp\.pl/sess/tvplayer\.php\?object_id=(?<id>[^&]*)&amp;autoplay=true""", defaultRegexOptions);
                if (m.Success)
                {
                    string newUrl = String.Format(videoListRegExFormatString, m.Groups["id"].Value);
                    webData = GetWebData(newUrl);
                }
            }
            JObject content = JObject.Parse(webData);

            if (content != null)
            {
                JArray formats = content["formats"] as JArray;
                if (formats != null)
                {
                    SortedList<int, SortedList<string, string>> bitrateList = new SortedList<int, SortedList<string, string>>();
                    //inner sortedlist is extention->url
                    foreach (JToken format in formats)
                    {
                        int bitrate = format.Value<int>("totalBitrate");
                        string url = format.Value<string>("url");
                        string ext = System.IO.Path.GetExtension(url);

                        if (!bitrateList.ContainsKey(bitrate))
                            bitrateList.Add(bitrate, new SortedList<string, string>());
                        bitrateList[bitrate].Add(ext, url);
                    }
                    Dictionary<string, string> result = new Dictionary<string, string>();
                    foreach (KeyValuePair<int, SortedList<string, string>> option in bitrateList)
                    {
                        SortedList<string, string> extList = option.Value;
                        foreach (var ext in extList)
                        {
                            string key = String.Format("{0}Kb", option.Key / 1000) + ext.Key;
                            if (!result.ContainsKey(key))
                                result.Add(key, ext.Value);
                        }
                    }
                    if (result.Count > 1)
                        video.PlaybackOptions = result;

                    if (result.Count >= 1)
                        return result.Last().Value;

                    return null;
                }
            }
            return null;

        }
Example #30
0
 public static void Clone(string path, ProductEntry productEntry, Dictionary<FileEntry, string> files, byte[] checksum = null)
 {
     try
     {
         if (!Directory.Exists(Path.GetDirectoryName(path)) && !String.IsNullOrEmpty(Path.GetDirectoryName(path)))
             Directory.CreateDirectory(Path.GetDirectoryName(path) );
         using (var stream = File.Create(path))
         {
             stream.WriteByte(0x0);
             WriteProductEntry(productEntry, stream);
             stream.WriteByte(0x0);
             files.Add(new FileEntry(null, "", 0, 0, 0, 0, _file), "");
             foreach (var entry in files.Keys)
             {
                 WriteFileEntry(stream, entry);
             }
             files.Remove(files.Last().Key);
             foreach (var file in files.Values)
             {
                 var buffer = new byte[2949120];
                 using (var open = File.OpenRead(file))
                 {
                     int bytesRead;
                     while ((bytesRead =
                                  open.Read(buffer, 0, 2949120)) > 0)
                     {
                         stream.Write(buffer, 0, bytesRead);
                     }
                 }
             }
             if(checksum != null && checksum.Any(b => b!=0))
             {
                 stream.WriteByte(0x0);
                 stream.Write(checksum, 0, checksum.Length);
             }
             else if (checksum == null)
             {
                 stream.Position = 0;
                 byte[] hash;
                 using (var sha1 = new SHA1Managed())
                 {
                     hash = sha1.ComputeHash(stream);
                 }
                 stream.WriteByte(0x0);
                 stream.Write(hash, 0, 20);
             }
         }
     }
     catch (Exception)
     {
         throw;
     }
 }