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 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 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 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 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_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 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 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(); }
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; }
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(); }
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; }
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); }
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 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(); }
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() == " ") 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; }
// 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; }
/// <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(); }
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; }
private IReadOnlyList <ColumnModification> GenerateColumnModifications() { var adding = EntityState == EntityState.Added; var columnModifications = new List <ColumnModification>(); if (_comparer != null) { _entries.Sort(_comparer); } var columnMap = _entries.Count == 1 ? null : new Dictionary <string, ColumnModification>(); Dictionary <IUpdateEntry, List <ColumnModification> > conflictingColumnValues = null; Dictionary <IUpdateEntry, List <ColumnModification> > conflictingOriginalColumnValues = null; foreach (var entry in _entries) { Dictionary <string, IProperty> sharedIdentityEntryProperties = null; if (entry.SharedIdentityEntry != null) { if (entry.EntityState == EntityState.Deleted) { continue; } sharedIdentityEntryProperties = new Dictionary <string, IProperty>(); foreach (var property in entry.SharedIdentityEntry.EntityType.GetProperties()) { sharedIdentityEntryProperties[property.Relational().ColumnName] = property; } } foreach (var property in entry.EntityType.GetProperties()) { var propertyAnnotations = property.Relational(); var isKey = property.IsPrimaryKey(); var isConcurrencyToken = property.IsConcurrencyToken; var isCondition = !adding && (isKey || isConcurrencyToken); var readValue = entry.IsStoreGenerated(property); var writeValue = false; if (!readValue) { if (adding) { writeValue = property.BeforeSaveBehavior == PropertySaveBehavior.Save; } else { if (property.AfterSaveBehavior == PropertySaveBehavior.Save && entry.IsModified(property)) { writeValue = true; } else if (sharedIdentityEntryProperties != null && (property.BeforeSaveBehavior == PropertySaveBehavior.Save || property.AfterSaveBehavior == PropertySaveBehavior.Save)) { writeValue = !sharedIdentityEntryProperties.TryGetValue(propertyAnnotations.ColumnName, out var originalProperty) || !Equals(entry.SharedIdentityEntry.GetOriginalValue(originalProperty), entry.GetCurrentValue(property)); } } } if (readValue || writeValue || isCondition) { if (readValue) { _requiresResultPropagation = true; } var columnModification = new ColumnModification( entry, property, propertyAnnotations, _generateParameterName, readValue, writeValue, isKey, isCondition, isConcurrencyToken); if (columnMap != null) { if (columnMap.TryGetValue(columnModification.ColumnName, out var existingColumnModification)) { if (columnModification.UseCurrentValueParameter && !Equals(columnModification.Value, existingColumnModification.Value)) { conflictingColumnValues = AddConflictingColumnValues( conflictingColumnValues, columnModification, existingColumnModification); } else if (columnModification.UseOriginalValueParameter && !Equals(columnModification.OriginalValue, existingColumnModification.OriginalValue)) { conflictingOriginalColumnValues = AddConflictingColumnValues( conflictingOriginalColumnValues, columnModification, existingColumnModification); } continue; } columnMap.Add(columnModification.ColumnName, columnModification); } columnModifications.Add(columnModification); } } } if (conflictingColumnValues != null) { var firstPair = conflictingColumnValues.First(); var firstEntry = firstPair.Key; var firstProperties = firstPair.Value.Select(c => c.Property).ToList(); var lastPair = conflictingColumnValues.Last(); var lastEntry = lastPair.Key; var lastProperties = lastPair.Value.Select(c => c.Property); if (_sensitiveLoggingEnabled) { throw new InvalidOperationException( RelationalStrings.ConflictingRowValuesSensitive( firstEntry.EntityType.DisplayName(), lastEntry.EntityType.DisplayName(), firstEntry.BuildCurrentValuesString(firstEntry.EntityType.FindPrimaryKey().Properties), firstEntry.BuildCurrentValuesString(firstProperties), lastEntry.BuildCurrentValuesString(lastProperties), firstProperties.FormatColumns())); } throw new InvalidOperationException( RelationalStrings.ConflictingRowValues( firstEntry.EntityType.DisplayName(), lastEntry.EntityType.DisplayName(), Property.Format(firstProperties), Property.Format(lastProperties), firstProperties.FormatColumns())); } if (conflictingOriginalColumnValues != null) { var firstPair = conflictingOriginalColumnValues.First(); var firstEntry = firstPair.Key; var firstProperties = firstPair.Value.Select(c => c.Property).ToList(); var lastPair = conflictingOriginalColumnValues.Last(); var lastEntry = lastPair.Key; var lastProperties = lastPair.Value.Select(c => c.Property); if (_sensitiveLoggingEnabled) { throw new InvalidOperationException( RelationalStrings.ConflictingOriginalRowValuesSensitive( firstEntry.EntityType.DisplayName(), lastEntry.EntityType.DisplayName(), firstEntry.BuildCurrentValuesString(firstEntry.EntityType.FindPrimaryKey().Properties), firstEntry.BuildOriginalValuesString(firstProperties), lastEntry.BuildOriginalValuesString(lastProperties), firstProperties.FormatColumns())); } throw new InvalidOperationException( RelationalStrings.ConflictingOriginalRowValues( firstEntry.EntityType.DisplayName(), lastEntry.EntityType.DisplayName(), Property.Format(firstProperties), Property.Format(lastProperties), firstProperties.FormatColumns())); } return(columnModifications); }
public async Task RunScript(string scriptRelativePath) { string scriptFile = Path.Combine(_config.ScriptRootDir, scriptRelativePath); if (!File.Exists(scriptFile)) { throw new FileNotFoundException("Script file does not exist: " + scriptFile); } HashSet <string> enabledDefines = GetEnabledDefines(); LogProcessingReproInfo(scriptFile, enabledDefines); string[] scriptLines = File.ReadAllLines(scriptFile); Dictionary <string, bool> activeDefines = new Dictionary <string, bool>(); bool isActiveDefineRegionEnabled = IsActiveDefineRegionEnabled(activeDefines, enabledDefines); int i = 0; try { for (; i < scriptLines.Length; i++) { string line = scriptLines[i].TrimStart(); if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#")) { continue; } else if (line.StartsWith("IFDEF:")) { string define = line.Substring("IFDEF:".Length); activeDefines.Add(define, true); isActiveDefineRegionEnabled = IsActiveDefineRegionEnabled(activeDefines, enabledDefines); } else if (line.StartsWith("!IFDEF:")) { string define = line.Substring("!IFDEF:".Length); activeDefines.Add(define, false); isActiveDefineRegionEnabled = IsActiveDefineRegionEnabled(activeDefines, enabledDefines); } else if (line.StartsWith("ENDIF:")) { string define = line.Substring("ENDIF:".Length); if (!activeDefines.Last().Key.Equals(define)) { throw new Exception("Mismatched IFDEF/ENDIF. IFDEF: " + activeDefines.Last().Key + " ENDIF: " + define); } activeDefines.Remove(define); isActiveDefineRegionEnabled = IsActiveDefineRegionEnabled(activeDefines, enabledDefines); } else if (!isActiveDefineRegionEnabled) { WriteLine(" SKIPPING: {0}", line); continue; } else if (line.StartsWith("LOADSOS")) { await LoadSosExtension(); } else if (line.StartsWith("CONTINUE")) { await ContinueExecution(); } else if (line.StartsWith("SOSCOMMAND:")) { string input = line.Substring("SOSCOMMAND:".Length).TrimStart(); if (!await RunSosCommand(input)) { throw new Exception($"SOS command FAILED: {input}"); } } else if (line.StartsWith("COMMAND:")) { string input = line.Substring("COMMAND:".Length).TrimStart(); if (!await RunCommand(input)) { throw new Exception($"Debugger command FAILED: {input}"); } } else if (line.StartsWith("VERIFY:")) { string verifyLine = line.Substring("VERIFY:".Length); VerifyOutput(verifyLine); } else { continue; } } if (activeDefines.Count != 0) { throw new Exception("Error unbalanced IFDEFs. " + activeDefines.First().Key + " has no ENDIF."); } await QuitDebugger(); } catch (Exception e) { WriteLine("SOSRunner error at " + scriptFile + ":" + (i + 1)); WriteLine("Excerpt from " + scriptFile + ":"); for (int j = Math.Max(0, i - 2); j < Math.Min(i + 3, scriptLines.Length); j++) { WriteLine((j + 1).ToString().PadLeft(5) + " " + scriptLines[j]); } WriteLine(e.ToString()); throw; } }
private void CalculateExample(IEnumerable <string> example) { var num = 0; var VarCount = _uniqueVarsSet.Count; var table = new Dictionary <string, List <bool> >(); for (int i = 0; i < VarCount; i++) { var col = new List <bool>(); int k = 0; bool defenition = false; /////////////////////////////////////////////////////////////// //filling the data of variables for (int j = 0; j < Math.Pow(2, VarCount); j++, k++) { if (k >= Math.Pow(2, VarCount - i - 1)) { defenition = !defenition; k = 0; } col.Add(defenition); } table.Add(_uniqueVarsSet[i], col); } //////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////calculating postfix var stack = new Stack <List <bool> >(); foreach (var m in example) { if (!_operations.Contains(m)) { if (m.Contains('1')) { stack.Push(Enumerable.Repeat(true, (int)Math.Pow(2, VarCount)).ToList()); // access to const 1 } else if (m.Contains('0')) { stack.Push(Enumerable.Repeat(false, (int)Math.Pow(2, VarCount)).ToList()); // access to const 0 } else { stack.Push(table[m]); } } else { List <bool> b = stack.Pop(); if (m == "!") // if un oper { stack.Push(CalculateOper(m, b)); table.Add((++num).ToString(), stack.First()); } else //if duo oper { List <bool> a = stack.Pop(); stack.Push(CalculateOper(m, a, b)); table.Add((++num).ToString(), stack.First()); } } } /////////////////////////////////////////////////////////////////////////////////////// var keys = new List <string>(table.Keys); // for (var j = 0; j < keys.Count; j++) { Console.Write(" |" + keys[j].PadLeft(2)); } Console.WriteLine(" |"); Console.WriteLine(); for (var i = 0; i < table.Last().Value.Count; i++) { for (var j = 0; j < keys.Count; j++) { Console.Write(" |" + Convert.ToByte(table[keys[j]][i]).ToString().PadLeft(2)); } Console.WriteLine(" |"); } Console.WriteLine(); var SDNf = GetSDNF(table); var SKNf = GetSKNF(table); _sw.WriteLine("СКНФ: " + SKNf); _sw.WriteLine("СДНФ: " + SDNf); Console.WriteLine("СДНФ: " + SDNf); Console.WriteLine("СКНФ: " + SKNf); Console.WriteLine(""); }
internal static string ConvertToJsObject(Dictionary <string, object> options) { var config = new StringBuilder(); config.Append("{"); if (options != null) { foreach (var item in options) { config.AppendFormat(" {0}: {1}{2} ", item.Key, JsonConvert.SerializeObject(item.Value), options.Last().Equals(item) ? "" : ","); } } config.Append("}"); return(config.ToString()); }
/// <summary> /// Allows the script to maintain itself /// </summary> public bool poll() { //Should we check game state yet? int now = Environment.TickCount; if (now - _lastGameCheck <= Arena.gameCheckInterval) { return(true); } _lastGameCheck = now; //Do we have enough players ingame? int playing = _arena.PlayerCount; //Update our tickers if (_tickGameStart > 0 && now - _arena._tickGameStarted > 2000) { if (now - _lastTickerUpdate > _tickerUpdateRate) { updateTickers(); _lastTickerUpdate = now; } } if ((_tickGameStart == 0 || _tickGameStarting == 0) && playing < _minPlayers) { //Stop the game! _arena.setTicker(1, 1, 0, "Not Enough Players"); _arena.gameReset(); } //Do we have enough players to start a game? else if (_tickGameStart == 0 && _tickGameStarting == 0 && playing >= _minPlayers) { //Great! Get going _tickGameStarting = now; _arena.setTicker(1, 1, _config.flag.startDelay * 100, "Next game: ", delegate() { //Make sure any HQ's spawned are cleaned up before real game start _hqs.Clear(); //Trigger the game start _arena.gameStart(); } ); } //Game is in progress else { ///////////////////////////////////// // Flag Resource Capture // ///////////////////////////////////// int flagDelay = 500; //In miliseconds //If enough time has passed... if (now - _lastFlagCheck >= flagDelay) { //Loop through every flag in the arena... foreach (Arena.FlagState fs in _arena._flags.Values) { //Ore Generator is captured... if (fs.flag == AssetManager.Manager.getLioByID(101) && fs.team != null) { //Add resources to the team that captured it fs.team.inventoryModify(ORE_ID, RESOURCE_CHANGE); } //Hydrocarbon Generator is captured... else if (fs.flag == AssetManager.Manager.getLioByID(103) && fs.team != null) { //Add resources to the team that captured it fs.team.inventoryModify(HYDROCARB_ID, RESOURCE_CHANGE); } } _lastFlagCheck = now; } } //TODO: Refactor this... wrong way of maintainings reward and levels foreach (HQ hq in _hqs.Values) { //Reward time? if ((now - tickLastUpdate) > (rewardDelay * 1000)) { Events.periodicReward(hq); //Last HQ in line if (hq == _hqs.Last().Value) { tickLastUpdate = now; } } //Level up time? if ((now - tickLastUpdate) > 1000) { if (hq.bounty >= hq.nextLvl) { Events.onHQLevelUp(hq); } } } //////////////////////////////////////// // Pilot Auto Repair // //////////////////////////////////////// int repairDelay = 1000; //in miliseconds //If enough time has passed... if (now - _tickLastRepair > repairDelay) { //Loop through every player in the arena foreach (Player player in _arena.Players) { if (player._occupiedVehicle != null && //Inside a vehicle and... player._baseVehicle._type.Id == 116 || player._baseVehicle._type.Id == 216) //of the pilot class (id = 116/216) { //Amount to repair int repairAmount = 1; //Apply repair player.inventoryModify(AssetManager.Manager.getItemByName("PlusHealth"), repairAmount); } } _tickLastRepair = now; } return(true); }
public static void ShowDictionary() { Console.WriteLine("Part1"); Dictionary <int, object> testDictionary = new Dictionary <int, object>(); testDictionary.Add(1, "asdas"); testDictionary.Add(2, 12); testDictionary.Add(3, 11.3); testDictionary.Add(4, 'a'); Console.WriteLine($"Count = {testDictionary.Count}"); Console.WriteLine($"First = {testDictionary.First()}, last = {testDictionary.Last()}"); var varr = testDictionary.Values; Console.WriteLine($"{varr}"); var var2 = testDictionary[2]; Console.WriteLine($"Value = {var2}, type {var2.GetType()} "); Console.WriteLine("Part2"); Dictionary <char, Pers> people = new Dictionary <char, Pers>(); people.Add('b', new Pers() { Name = "Bill" }); people.Add('t', new Pers() { Name = "Tom" }); people.Add('j', new Pers() { Name = "John" }); foreach (KeyValuePair <char, Pers> keyValue in people) { // keyValue.Value представляет класс Person Console.WriteLine(keyValue.Key + " - " + keyValue.Value.Name); } // перебор ключей foreach (char c in people.Keys) { Console.WriteLine(c); } // перебор по значениям foreach (Pers p in people.Values) { Console.WriteLine(p.Name); } Console.WriteLine("\nPart3"); //Инициализация словарей Dictionary <string, string> countries1 = new Dictionary <string, string> { { "Франция", "Париж" }, { "Германия", "Берлин" }, { "Великобритания", "Лондон" } }; foreach (var pair in countries1) { Console.WriteLine("{0} - {1}", pair.Key, pair.Value); } Dictionary <string, string> countries2 = new Dictionary <string, string> { ["Франция"] = "Париж", ["Германия"] = "Берлин", ["Великобритания"] = "Лондон" }; }
public void Start(int NumOfPlayers, Program.Map Map) { IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(HostIP), Port); Socket ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); string Title = $"Waiting for Players to connect - {NumOfPlayers - 1 - ConnectedPlayers.Count}"; string[] NullArray = new string[0]; Interface.AnswerInterface(Title, NullArray); Console.CursorTop += 2; int OrigTop = Console.CursorTop; ListenSocket.Bind(ipPoint); ListenSocket.Listen(NumOfPlayers - 1); while (ConnectedPlayers.Count < NumOfPlayers - 1) { Socket newPlayer = ListenSocket.Accept(); ConnectedPlayers.Add(newPlayer, ReceiveData(newPlayer) as Player); SendLobbyInfo(NumOfPlayers, Map); Title = $"Waiting for Players to connect - {NumOfPlayers - 1 - ConnectedPlayers.Count}"; Interface.AnswerInterfaceTitleChange(Title); Console.SetCursorPosition(6, OrigTop + 2 * ConnectedPlayers.Count - 1); Console.Write("\x4 {0} - {1} is connected.", (char)ConnectedPlayers.Count, ConnectedPlayers.Last().Key.AddressFamily.ToString()); } Console.Clear(); PlayerInitializing(); List <Player> Players = ConnectedPlayers.Values.ToList(); Players.Add(HostPlayer); Game = new Multiplayer.MultiplayerGame(); Game.Map = Map; Game.Players = Players; Game.StartAsync(); while (Game.State == false) { } while (true) { SendGameInfo(); HostPlayer.MovementAsync(Map);//Host player movement for (int i = 0; i < ConnectedPlayers.Count; i++) { PlayerMovement(ConnectedPlayers.Keys.ToArray()[i]); } Players = ConnectedPlayers.Values.ToList(); Players.Add(HostPlayer); Game.Players = Players; } }
public virtual bool Save(DbTransaction transaction) { TableNameAttribute tableNameAttribute = (TableNameAttribute)Table.GetType().GetCustomAttributes(typeof(TableNameAttribute), false).FirstOrDefault(); GeneratorNameAttribute generatorNameAttribute = (GeneratorNameAttribute)Table.GetType().GetCustomAttributes(typeof(GeneratorNameAttribute), false).FirstOrDefault(); ColumnAttribute idAttribute = (ColumnAttribute)GetType().GetProperty("Id").GetCustomAttributes(typeof(ColumnAttribute), false).First(); bool result = false; lock (FieldsPreviousValue) { if (FieldsPreviousValue.Count() > 0) { PropertyInfo lastField = FieldsPreviousValue.Last().Key; if (tableNameAttribute != null && !string.IsNullOrWhiteSpace(tableNameAttribute.Name)) { StringBuilder cb = new StringBuilder(); bool inserting = Id == NoId; long id = Id; if (inserting) { if (generatorNameAttribute != null && !string.IsNullOrWhiteSpace(generatorNameAttribute.Name)) { var vb = new StringBuilder(" (@ID, "); cb.Append("insert into \"").Append(tableNameAttribute.Name).Append("\" (").Append(idAttribute.Name).Append(", "); id = Connector.GenNextGenValue(generatorNameAttribute.Name, (FbTransaction)transaction); foreach (PropertyInfo field in FieldsPreviousValue.Keys) { ColumnAttribute an = (ColumnAttribute)(field.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault()); string fieldName = (an == null) ? field.Name.ToUpperInvariant() : an.Name; cb.Append(fieldName); vb.Append("@").Append(fieldName); if (field != lastField) { cb.Append(", "); vb.Append(", "); } else { cb.Append(")"); vb.Append(")"); } } cb.Append(" values").Append(vb); } else { throw new ApplicationException("No generator name provided to insert data"); } Id = id; } else { cb.Append("update \"").Append(tableNameAttribute.Name).Append("\" set "); foreach (PropertyInfo field in FieldsPreviousValue.Keys) { ColumnAttribute an = (ColumnAttribute)(field.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault()); string fieldName = (an == null) ? field.Name.ToUpperInvariant() : an.Name; cb.Append(fieldName).Append("=@").Append(fieldName); if (field != lastField) { cb.Append(", "); } else { cb.Append(" "); } } cb.Append("where ").Append(idAttribute.Name).Append("=@ID"); } var command = new FbCommand(cb.ToString(), Connector.Connection); command.Transaction = (FbTransaction)transaction; command.Parameters.Add("@ID", id); PropertyInfo[] fields = this.GetType().GetProperties(); foreach (var field in FieldsPreviousValue) { ColumnAttribute an = (ColumnAttribute)(field.Key.GetCustomAttributes(typeof(ColumnAttribute), true).FirstOrDefault()); string fieldName = (an == null) ? field.Key.Name.ToUpperInvariant() : an.Name; command.Parameters.Add("@" + fieldName, field.Key.GetValue(this, null) ?? DBNull.Value); } command.ExecuteNonQuery(); FieldsPreviousValue.Clear(); RefreshAutoUpdatedFields(transaction, inserting); result = true; } else { throw new ApplicationException("No table name provided"); } } Modified = false; } return(result); }
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(); }
private void SampleStratifiedPopulation(List <int> cellIndexToInfectedCounts, Tuple <Tuple <int, int>, Tuple <int, int> > strataBbox, Dictionary <int, int> currentCellIndexToPopulationDensity, List <int> cellIndexToPopulationDensity, int sampleSize) { // Progressively accumulate the total population densities in a series -> grid index Dictionary <int, int> cumulativePopulationDensitiesToCellIndex = CumulativePopulationDensitiesToCellIndex(currentCellIndexToPopulationDensity); // Iterate all Natural numbers (0, max cumulative density) int populationDensityValueMax = 0; List <int> populationDensityValueToCellIndex = new List <int>(); if (cumulativePopulationDensitiesToCellIndex.Count > 0) { populationDensityValueMax = cumulativePopulationDensitiesToCellIndex.Keys.Max(); int rangeMin = 0; int currentCellIndex = cumulativePopulationDensitiesToCellIndex.First().Value; for (int i = 0; i < populationDensityValueMax; i++) { populationDensityValueToCellIndex.Add(currentCellIndex); } foreach (KeyValuePair <int, int> keyValuePair in cumulativePopulationDensitiesToCellIndex) { int rangeMax = keyValuePair.Key; for (int i = rangeMin; i < rangeMax; i++) { populationDensityValueToCellIndex[i] = keyValuePair.Value; } rangeMin = rangeMax; } } // Sample within the distribution (0, maxCumulativePopulationDensity) if (populationDensityValueMax > 0) { for (int i = 0; i < sampleSize;) { int randomInt = _random.Next(0, populationDensityValueMax); if (populationDensityValueToCellIndex.Count > randomInt) { cellIndexToInfectedCounts[populationDensityValueToCellIndex[randomInt]]++; i++; } } } else { for (int i = 0; i < sampleSize; i++) { int cellIndex = Get1DIndex(new Tuple <int, int>( _random.Next(0, Get2DIndex(currentCellIndexToPopulationDensity.Last().Key).Item1), _random.Next(0, Get2DIndex(currentCellIndexToPopulationDensity.Last().Key).Item2))); cellIndexToInfectedCounts[cellIndex]++; } } // Print results int minX = strataBbox.Item1.Item1; int minY = strataBbox.Item1.Item2; int maxX = strataBbox.Item2.Item1; int maxY = strataBbox.Item2.Item2; if (chkShowTextLog.Checked) { txtSamples.Clear(); int sumSamples = 0; for (int index = 0; index < _cellCount; index++) { int x = Get2DIndex(index).Item1; int y = Get2DIndex(index).Item2; int currentSamples = cellIndexToInfectedCounts[index]; if (currentSamples > 0 || (x >= minX && x < maxX && y >= minY && y < maxY)) { sumSamples += currentSamples; txtSamples.AppendText($"[{x}, " + $"{y}]: {currentSamples} samples" + $" (Population Density: {cellIndexToPopulationDensity[index]})\r\n"); } } txtSamples.AppendText($"\r\nTotal Samples: {sumSamples}"); } }
/// <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; } }
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; } }
public void testStockManipulation() { // this should test all situations: // - client leaving, stock given to another trader // - client leaving, stock taken away (because no one is online) // - first client joining, stock given to him // - client not reconnecting within 5 seconds, stock given to another trader // - client not reconnecting within 5 seconds, stock taken away (because no one is online) // similar looking test is done in ClientsTests.FunctionalityTests.testServerReset // but this one using using market perspective Dictionary <int, Client> clients = joinClients(2); // ensureServerRuns checks for "Server" process, but when unit testing, the process isn't called "Server" // so it starts a new one, which is bad //clients.First().Value.ensureServerRuns(); while (market == null) { market = server.market; Thread.Sleep(10); } // (just in case if server was killed last time and stock was about to be given/released within 5 seconds) // (to original owner) if (!market.hasTrader(market.StockHolderId)) { market.releaseStock(); } // disconnect stock holder int stock_holder_id = market.StockHolderId; clients[stock_holder_id].Dispose(); clients.Remove(stock_holder_id); Thread.Sleep(1500); Client remaining_client = clients.First().Value; int remaining_client_id = remaining_client.id; // only 1 trader is remaining at this point, so he should be the new stock holder Assert.AreEqual(remaining_client_id, market.StockHolderId, "The only remaining client didn't get stock after stock holder left."); // disconnect the only client remaining_client.Dispose(); // at this point the stock should belong to no one Thread.Sleep(1500); Assert.AreEqual(-1, market.StockHolderId, $"Stock wasn't released after the last client left."); //Dictionary<int, Client> new_clients = joinClients(1); Client client = joinClients(1).First().Value; Thread.Sleep(1500); int client_id = client.id; Assert.AreEqual(client_id, market.StockHolderId, $"Stock wasn't given to the first connected client."); // join additional clients and add stock to one of them clients = joinClients(5); Client new_stock_holder = clients.Last().Value; client.requestStockTransfer(new_stock_holder.id); Thread.Sleep(1500); Assert.AreEqual(new_stock_holder.id, market.StockHolderId, "Stock wasn't given to arbitrary (not-first) trader."); /* restarting server (not as a separate process) doesn't work well here * because clients restart it on their own... * * killServer(); * Assert.IsNull(market, "Market isn't null after server reset (it should be to ensure the values got restored, and didn't just stay)."); * * //startServer(); * * Thread.Sleep(4000); * foreach (Client c in clients.Values) * c.connect(); * * client.connect(); * Thread.Sleep(3000); * * Assert.AreEqual(new_stock_holder.id, market.stock_holder_id, "Stock wasn't restored to original stock holder after server restart.");*/ }
void KeyPressed(ConsoleKeyInfo key) { if (key.Modifiers == 0) { KeyValuePair <DateTime, List <CommandOutput> > _page; switch (key.Key) { case ConsoleKey.LeftArrow: //mouth.Speak( "Left arrow key pressed" ); if (currentPageIndex == null) { //mouth.Speak( "No page loaded yet." ); if (pages.Any( )) { //mouth.Speak( "There is some page stored already." ); _page = pages.Last( ); //mouth.Speak( "Load last stored page." ); loadPage(_page); //mouth.Speak( "Store temporary page." ); storePage( ); } } else { //mouth.Speak( "There is some page loaded." ); IOrderedEnumerable <DateTime> _sortedKey = pages.Keys.OrderBy(_k => _k.Ticks); var _currentKeyIndex = currentKeyIndex(_sortedKey); //mouth.Speak( "The current page index is {0}".Format( currentPageIndex ) ); //mouth.Speak( // "Current key index check: {0}".Format( // currentPageIndex == _sortedKey.ElementAt( _currentKeyIndex ) ) ); //mouth.Speak( "The current key index is {0}".Format( _currentKeyIndex ) ); if (_currentKeyIndex > 0) { //mouth.Speak( "Getting previous page index." ); DateTime _preKey = _sortedKey.ElementAt(--_currentKeyIndex); //mouth.Speak( "Load previous page." ); _page = new KeyValuePair <DateTime, List <CommandOutput> >( _preKey, pages[_preKey]); loadPage( _page); } } //mouth.Speak( "Left arrow processing done." ); displayPageIndicator( ); break; case ConsoleKey.RightArrow: if (currentPageIndex == null) { if (pages.Any( )) { _page = pages.First( ); loadPage(_page); storePage( ); } } else { IOrderedEnumerable <DateTime> _sortedKey = pages.Keys.OrderBy(_k => _k.Ticks); var _currentKeyIndex = currentKeyIndex(_sortedKey); if (_currentKeyIndex < pages.Count - 1) { DateTime _preKey = _sortedKey.ElementAt(++_currentKeyIndex); _page = new KeyValuePair <DateTime, List <CommandOutput> >( _preKey, pages[_preKey]); loadPage( _page); } } displayPageIndicator( ); break; } } }
private void addRule(Dictionary <string, string> ruleBook, string key, string value) { ruleBook.Add(key, value); log.Fine(ruleBook.Last().Value); }
/// <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; } }
public ActionResult Index() { List <Song> songs = (from s in db.Songs orderby s.NumberOfPlays descending select s).Take(10).ToList(); List <Album> albums = (from a in db.Albums select a).ToList(); List <Artist> artists = (from a in db.Artists select a).ToList(); Dictionary <Artist, int> artistPlays = new Dictionary <Artist, int>(); Dictionary <Album, int> albumPlays = new Dictionary <Album, int>(); foreach (var artist in artists) { artistPlays.Add(artist, 0); foreach (var album in artist.Albums) { albumPlays.Add(album, 0); int plays = 0; foreach (var song in album.Songs) { plays += song.NumberOfPlays; } albumPlays[album] += plays; } artistPlays[artist] += albumPlays.Last().Value; } var orderedAlbums = albumPlays.OrderByDescending(kvp => kvp.Value); albumPlays = orderedAlbums.Take(10).ToDictionary(k => k.Key, k => k.Value); albums = albumPlays.Keys.ToList(); var orderedArtists = artistPlays.OrderByDescending(kvp => kvp.Value); artistPlays = orderedArtists.Take(10).ToDictionary(k => k.Key, k => k.Value); artists = artistPlays.Keys.ToList(); //foreach (var item in songs) //{ // int newPosition = songs.IndexOf(item); // if (item.Position == -1 && item.PositionImg == null) // { // item.PositionImg = "/Content/images/position-up.png"; // item.Position = newPosition; // } // db.Entry<Song>(item).State = System.Data.EntityState.Modified; //} //foreach (var item in albums) //{ // int newPosition = albums.IndexOf(item); // if (item.Position == -1 && item.PositionImg == null) // { // item.PositionImg = "/Content/images/position-up.png"; // item.Position = newPosition; // } // db.Entry<Album>(item).State = System.Data.EntityState.Modified; //} //foreach (var item in artists) //{ // int newPosition = artists.IndexOf(item); // if (item.Position == -1 && item.PositionImg == null) // { // item.PositionImg = "/Content/images/position-up.png"; // item.Position = newPosition; // } // db.Entry<Artist>(item).State = System.Data.EntityState.Modified; //} //db.SaveChanges(); //if (DateTime.Now.Minute % 2 == 0) { foreach (var item in songs) { int newPosition = songs.IndexOf(item); if (item.Position == -1 || item.Position > newPosition) { item.PositionImg = "/Content/images/position-up.png"; } else if (item.Position == newPosition) { item.PositionImg = "/Content/images/position-same.png"; } else { item.PositionImg = "/Content/images/position-down.png"; } item.Position = newPosition; db.Entry <Song>(item).State = System.Data.EntityState.Modified; } foreach (var item in albums) { int newPosition = albums.IndexOf(item); if (item.Position == -1 || item.Position > newPosition) { item.PositionImg = "/Content/images/position-up.png"; } else if (item.Position == newPosition) { item.PositionImg = "/Content/images/position-same.png"; } else { item.PositionImg = "/Content/images/position-down.png"; } item.Position = newPosition; db.Entry <Album>(item).State = System.Data.EntityState.Modified; } foreach (var item in artists) { int newPosition = artists.IndexOf(item); if (item.Position == -1 || item.Position > newPosition) { item.PositionImg = "/Content/images/position-up.png"; } else if (item.Position == newPosition) { item.PositionImg = "/Content/images/position-same.png"; } else { item.PositionImg = "/Content/images/position-down.png"; } item.Position = newPosition; db.Entry <Artist>(item).State = System.Data.EntityState.Modified; } db.SaveChanges(); } List <string> covers = new List <string>(); foreach (var item in songs) { Artist aa = (from a in db.Artists where a.Name == item.ArtistName select a).FirstOrDefault(); covers.Add((from a in aa.Albums where a.Name == item.AlbumName select a.Cover).FirstOrDefault()); } List <Tuple <Song, string> > songs1 = new List <Tuple <Song, string> >(); int i = 0; foreach (var item in songs) { songs1.Add(new Tuple <Song, string>(item, covers[i])); ++i; } return(View(new Top() { Songs = songs1, Albums = albums, Artists = artists })); }
public void AddNewClientCommand() { // сделать проверку clients.Add(ClientCommand.nextID, serverCommand.AcceptClientCommand()); clients.Last().Value.EventHandlersListForServer += new ClientCommand.ClientCommandActionEventHandlerForServer(Process); }
/// <summary> /// /// </summary> private void ComposePerShareData() { try { List <Dictionary <DateTime, decimal> > printMe = new List <Dictionary <DateTime, decimal> >(); Dictionary <DateTime, decimal> earningsPerShare = new Dictionary <DateTime, decimal>(); Dictionary <DateTime, decimal> freeCashFlowPerShare = new Dictionary <DateTime, decimal>(); Dictionary <DateTime, decimal> dividendsPerShare = new Dictionary <DateTime, decimal>(); foreach (Financials finance in _stockData.Financials) { if (finance.IsTTM) { earningsPerShare[DateTime.Now] = finance.EarningsPerShare; if (!(0 < dividendsPerShare.Count && dividendsPerShare.Last().Value == finance.Dividends)) { dividendsPerShare[DateTime.Now] = finance.Dividends; } } else { earningsPerShare[finance.Date] = finance.EarningsPerShare; freeCashFlowPerShare[finance.Date] = finance.FreeCashFlowPerShare; dividendsPerShare[finance.Date] = finance.Dividends; } } printMe.Add(earningsPerShare); printMe.Add(freeCashFlowPerShare); printMe.Add(dividendsPerShare); ChartPerShare.DataContext = printMe; LegendItem legend = (LegendItem)ChartPerShare.LegendItems[0]; legend.Content = "Earnings per share"; var style = new Style { TargetType = typeof(LineDataPoint) }; style.Setters.Add(new Setter(BackgroundProperty, Brushes.GreenYellow)); CharLineEarningsPerShare.DataPointStyle = style; legend = (LegendItem)ChartPerShare.LegendItems[1]; legend.Content = "Free cashflow p.share"; style = new Style { TargetType = typeof(LineDataPoint) }; style.Setters.Add(new Setter(BackgroundProperty, Brushes.CornflowerBlue)); CharLineFreeCashFlowPerShare.DataPointStyle = style; legend = (LegendItem)ChartPerShare.LegendItems[2]; legend.Content = "Dividends p.share"; style = new Style { TargetType = typeof(LineDataPoint) }; style.Setters.Add(new Setter(BackgroundProperty, Brushes.Green)); CharLineDividendsPerShare.DataPointStyle = style; } catch (Exception x) { MessageBox.Show(x.Message); Log.Error(x); } }
public override string Print(int indent) { if (Value.Count == 0) { return("{}"); } string TAB_INDENT = ""; for (int i = 0; i < indent; i++) { TAB_INDENT += "\t"; } string result = "\n" + TAB_INDENT + "{\n"; indent++; foreach (KeyValuePair <string, BaseObject> item in Value) { result += TAB_INDENT + "\t\"" + item.Key + "\": " + @item.Value.Print(indent) + (item.Key != Value.Last().Key ? "," : "") + "\n"; } result += TAB_INDENT + "}"; return(result); }
private void BGW_DoWork(object sender, DoWorkEventArgs e) { //取得列印紙張 int sizeIndex = GetSizeIndex(); //取得需列印的項目清單 List <String> DisplayList = GetUserType(); //取得資料 BGW.ReportProgress(10, "取得所選班級"); #region 取得使用者所選擇的班級學生 //取得所選班級紀錄 List <ClassRecord> allClasses = Class.SelectByIDs(K12.Presentation.NLDPanels.Class.SelectedSource); //從班級紀錄取得學生清單 List <StudentRecord> studentList = new List <StudentRecord>(); //學生記錄清單 List <String> StudentIDList = new List <string>(); //學生ID清單 foreach (ClassRecord classrecord in allClasses) { if (!_ClassNameDic.ContainsKey(classrecord.ID)) //儲存班級ID及Name方便往後查詢 { _ClassNameDic.Add(classrecord.ID, classrecord.Name); } foreach (StudentRecord student in classrecord.Students) //取得班級學生 { //只取得狀態為一般及延修的學生 if (student.Status == StudentRecord.StudentStatus.一般 || student.Status == StudentRecord.StudentStatus.延修) { studentList.Add(student); StudentIDList.Add(student.ID); } } } //建立班級字典存放各班級的學生 Dictionary <String, List <StudentRecord> > classDic = new Dictionary <string, List <StudentRecord> >(); foreach (StudentRecord student in studentList) { if (!classDic.ContainsKey(student.RefClassID)) //若該班級ID不存在就建立key { classDic.Add(student.RefClassID, new List <StudentRecord>()); } classDic[student.RefClassID].Add(student); //按對應班級ID將學生加入 } int totalStudent = studentList.Count; //全部學生的總數,進度回報用 foreach (String classid in classDic.Keys) { classDic[classid].Sort(SortStudent); //按學生座號排序字典內的清單 } #endregion BGW.ReportProgress(20, "取得資料紀錄"); #region 取得獎懲和缺曠紀錄 //獎勵紀錄 Dictionary <string, RewardRecord> MeritDemeritAttDic = new Dictionary <string, RewardRecord>(); foreach (String id in StudentIDList) //建立清單中全部學生的獎懲紀錄字典 { if (!MeritDemeritAttDic.ContainsKey(id)) { MeritDemeritAttDic.Add(id, new RewardRecord()); } } foreach (SHMeritRecord each in SHMerit.SelectByStudentIDs(StudentIDList)) { //if (_Semester == 1) //{ // if (each.SchoolYear != _Schoolyear || each.Semester != _Semester) // continue; //} //else //{ // if (each.SchoolYear != _Schoolyear) continue; //} if (each.SchoolYear != _Schoolyear || each.Semester != _Semester) { continue; } else { MeritDemeritAttDic[each.RefStudentID].MeritACount += each.MeritA.HasValue ? each.MeritA.Value : 0; MeritDemeritAttDic[each.RefStudentID].MeritBCount += each.MeritB.HasValue ? each.MeritB.Value : 0; MeritDemeritAttDic[each.RefStudentID].MeritCCount += each.MeritC.HasValue ? each.MeritC.Value : 0; } } //懲罰紀錄 foreach (SHDemeritRecord each in SHDemerit.SelectByStudentIDs(StudentIDList)) { //if (_Semester == 1) //{ // if (each.SchoolYear != _Schoolyear || each.Semester != _Semester) // continue; //} //else //{ // if (each.SchoolYear != _Schoolyear) continue; //} if (each.SchoolYear != _Schoolyear || each.Semester != _Semester) { continue; } else { if (each.Cleared == "是") { continue; } if (each.SchoolYear != _Schoolyear || each.Semester != _Semester) { continue; } else { MeritDemeritAttDic[each.RefStudentID].DemeritACount += each.DemeritA.HasValue ? each.DemeritA.Value : 0; MeritDemeritAttDic[each.RefStudentID].DemeritBCount += each.DemeritB.HasValue ? each.DemeritB.Value : 0; MeritDemeritAttDic[each.RefStudentID].DemeritCCount += each.DemeritC.HasValue ? each.DemeritC.Value : 0; } } //留查紀錄 if (each.MeritFlag == "2") { MeritDemeritAttDic[each.RefStudentID].Flag = true; } //MeritDemeritAttDic[each.RefStudentID].DemeritACount += each.DemeritA.HasValue ? each.DemeritA.Value : 0; //MeritDemeritAttDic[each.RefStudentID].DemeritBCount += each.DemeritB.HasValue ? each.DemeritB.Value : 0; //MeritDemeritAttDic[each.RefStudentID].DemeritCCount += each.DemeritC.HasValue ? each.DemeritC.Value : 0; } //取得節次對照表 Dictionary <String, String> periodDic = new Dictionary <String, String>(); foreach (PeriodMappingInfo var in PeriodMapping.SelectAll()) { if (!periodDic.ContainsKey(var.Name)) { periodDic.Add(var.Name, var.Type); //key=升降旗,一,二,三,午休...etc , value=一般,集會...etc } } //取得影響缺曠紀錄的假別清單 List <AbsenceMappingInfo> infoList = K12.Data.AbsenceMapping.SelectAll(); List <String> Noabsence = new List <string>(); foreach (AbsenceMappingInfo info in infoList) { if (!info.Noabsence) //若該假別會影響全勤就加入清單 { if (!Noabsence.Contains(info.Name)) { Noabsence.Add(info.Name); } } } //缺曠紀錄 foreach (SHAttendanceRecord each in SHAttendance.SelectByStudentIDs(StudentIDList)) { if (each.SchoolYear != _Schoolyear || each.Semester != _Semester) { continue; } foreach (AttendancePeriod record in each.PeriodDetail) { if (periodDic.ContainsKey(record.Period)) //確認是否有此節次 { string typename = periodDic[record.Period] + "_" + record.AbsenceType; //ex...一般_曠課,集會_曠課 if (!DisplayList.Contains(typename)) { continue; } if (Noabsence.Contains(record.AbsenceType)) //如果此缺曠紀錄的假別會影響全勤,該學生的前勤紀錄則為false { MeritDemeritAttDic[each.RefStudentID].全勤 = false; } if (!MeritDemeritAttDic[each.RefStudentID].Attendance.ContainsKey(record.AbsenceType)) { MeritDemeritAttDic[each.RefStudentID].Attendance.Add(record.AbsenceType, 0); } MeritDemeritAttDic[each.RefStudentID].Attendance[record.AbsenceType]++; } } } #endregion //產生表格 BGW.ReportProgress(30, "產生表格"); #region 產生表格 Workbook template = new Workbook(); Workbook prototype = new Workbook(); //列印尺寸 if (sizeIndex == 0) { template.Open(new MemoryStream(Properties.Resources.班級缺曠獎懲總表A3)); } else if (sizeIndex == 1) { template.Open(new MemoryStream(Properties.Resources.班級缺曠獎懲總表A4)); } else if (sizeIndex == 2) { template.Open(new MemoryStream(Properties.Resources.班級缺曠獎懲總表B4)); } prototype.Copy(template); Worksheet prototypeSheet; #region 範本sheet製作 //在範本sheet新增假別欄位 prototypeSheet = prototype.Worksheets[0]; _AbsenceType.Clear(); foreach (string item in DisplayList) { string type = item.Split('_')[1]; if (!_AbsenceType.Contains(type)) { _AbsenceType.Add(type); } } for (int i = 0; i < _AbsenceType.Count; i++) //依照勾選的顯示清單數量插入新的欄位 { prototypeSheet.Cells.InsertColumn(_DynamicIndex + 1); } //刪除兩個範本格式Column prototypeSheet.Cells.DeleteColumn(_DynamicIndex); prototypeSheet.Cells.DeleteColumn(_DynamicIndex); //標記新增的假別項目欄位索引 Dictionary <string, int> columnIndexTable = new Dictionary <string, int>(); //Excel欄位索引 //標記欄位索引 int index = _DynamicIndex; columnIndexTable.Add("座號", 0); columnIndexTable.Add("學號", 1); columnIndexTable.Add("姓名", 2); columnIndexTable.Add("嘉獎", 3); columnIndexTable.Add("小功", 4); columnIndexTable.Add("大功", 5); columnIndexTable.Add("警告", 6); columnIndexTable.Add("小過", 7); columnIndexTable.Add("大過", 8); columnIndexTable.Add("累嘉獎", 9); columnIndexTable.Add("累小功", 10); columnIndexTable.Add("累大功", 11); columnIndexTable.Add("累警告", 12); columnIndexTable.Add("累小過", 13); columnIndexTable.Add("累大過", 14); columnIndexTable.Add("留查", 15); //標記動態欄位索引並列印標題 //Dictionary<String, int> mergeIndex = new Dictionary<string, int>(); //紀錄需要merge的column數量 foreach (String type in _AbsenceType) { if (!columnIndexTable.ContainsKey(type)) { columnIndexTable.Add(type, index); prototypeSheet.Cells.CreateRange(1, columnIndexTable[type], 2, 1).Merge(); prototypeSheet.Cells[1, columnIndexTable[type]].PutValue(type); index++; } //columnIndexTable.Add(str, index); //標記動態欄位索引 //String[] strs = str.Split('_'); //將"一般_曠課"字串以_字元拆開 //prototypeSheet.Cells[2, columnIndexTable[str]].PutValue(strs[1]); //列印標題...ex:曠課 //if (!mergeIndex.ContainsKey(strs[0])) //若是相同title,則數量加1 //{ //mergeIndex.Add(strs[0], 0); //} //mergeIndex[strs[0]]++; //若是相同title,則數量加1 } //int start = _DynamicIndex; //merge的起始值 //foreach (String s in mergeIndex.Keys) //{ // prototypeSheet.Cells.CreateRange(1, start, 1, mergeIndex[s]).Merge(); // prototypeSheet.Cells[1, start].PutValue(s); // start += mergeIndex[s]; //} //全勤為最後標記 columnIndexTable.Add("全勤", index); for (int i = 3; i <= index; i++) { prototypeSheet.Cells.SetColumnWidth(i, 11); } #endregion #region 各班級sheet製作 int page = 1; foreach (String id in classDic.Keys) { prototype.Worksheets.AddCopy(0); //複製範本sheet prototypeSheet = prototype.Worksheets[page]; //從第二個分頁開始畫製表格,page++; prototypeSheet.Name = GetClassName(id); //sheet.Name = 班級名稱 //每5行加一條分隔線 Range eachFiveLine = prototype.Worksheets[0].Cells.CreateRange(_StartIndex, 5, false); //從第一個sheet複製 for (int i = _StartIndex; i < classDic[id].Count + _StartIndex; i += 5) //依照該班級學生數給予適量的分隔線 { prototypeSheet.Cells.CreateRange(i, 5, false).CopyStyle(eachFiveLine); } page++; //完成一個班級換下個sheet的畫製 } prototype.Worksheets.RemoveAt(0); //都完成後刪除第一個範本sheet #endregion #endregion //填入表格 BGW.ReportProgress(40, "填入表格"); #region 填入表格 _WK = new Workbook(); int sheetIndex = 0; _WK.Copy(prototype); //複製畫製好欄位的範本 Worksheet ws; Cells cs; //取得功過換算比例 MeritDemeritReduceRecord mdrr = MeritDemeritReduce.Select(); int?MAB = mdrr.MeritAToMeritB; int?MBC = mdrr.MeritBToMeritC; int?DAB = mdrr.DemeritAToDemeritB; int?DBC = mdrr.DemeritBToDemeritC; float progress = 50; float rate = (float)(100 - progress) / totalStudent; //進度百分比計算 foreach (String classid in classDic.Keys) { ws = _WK.Worksheets[sheetIndex]; cs = ws.Cells; index = _StartIndex; //列印起始索引 _CountAllColumnValue = new Dictionary <int, int>(); //重制個項目的總數 foreach (StudentRecord student in classDic[classid]) { progress += rate; BGW.ReportProgress((int)progress, "正在填入資料..."); String id = student.ID; int? 獎 = MeritDemeritAttDic[id].MeritCCount; int? 小功 = MeritDemeritAttDic[id].MeritBCount; int? 大功 = MeritDemeritAttDic[id].MeritACount; int? 警告 = MeritDemeritAttDic[id].DemeritCCount; int? 小過 = MeritDemeritAttDic[id].DemeritBCount; int? 大過 = MeritDemeritAttDic[id].DemeritACount; //將功過轉為嘉獎和警告,做功過相抵計算 獎 = 大功 * MAB * MBC + 小功 * MBC + 獎; 警告 = 大過 * DAB * DBC + 小過 * DBC + 警告; int?[] i = 功過相抵(獎, 警告); 獎 = i[0]; 警告 = i[1]; //獎勵換算 int?累嘉獎 = 獎 % MBC; int?累小功 = (獎 / MBC) % MAB; int?累大功 = (獎 / MBC) / MAB; //懲戒換算 int?累警告 = 警告 % DBC; int?累小過 = (警告 / DBC) % DAB; int?累大過 = (警告 / DBC) / DAB; cs[index, columnIndexTable["座號"]].PutValue(student.SeatNo); cs[index, columnIndexTable["學號"]].PutValue(student.StudentNumber); cs[index, columnIndexTable["姓名"]].PutValue(student.Name); SetColumnValue(cs[index, columnIndexTable["嘉獎"]], MeritDemeritAttDic[id].MeritCCount); SetColumnValue(cs[index, columnIndexTable["小功"]], MeritDemeritAttDic[id].MeritBCount); SetColumnValue(cs[index, columnIndexTable["大功"]], MeritDemeritAttDic[id].MeritACount); SetColumnValue(cs[index, columnIndexTable["警告"]], MeritDemeritAttDic[id].DemeritCCount); SetColumnValue(cs[index, columnIndexTable["小過"]], MeritDemeritAttDic[id].DemeritBCount); SetColumnValue(cs[index, columnIndexTable["大過"]], MeritDemeritAttDic[id].DemeritACount); SetColumnValue(cs[index, columnIndexTable["累嘉獎"]], 累嘉獎); SetColumnValue(cs[index, columnIndexTable["累小功"]], 累小功); SetColumnValue(cs[index, columnIndexTable["累大功"]], 累大功); SetColumnValue(cs[index, columnIndexTable["累警告"]], 累警告); SetColumnValue(cs[index, columnIndexTable["累小過"]], 累小過); SetColumnValue(cs[index, columnIndexTable["累大過"]], 累大過); SetColumnValue(cs[index, columnIndexTable["留查"]], MeritDemeritAttDic[id].Flag ? "是" : ""); SetColumnValue(cs[index, columnIndexTable["全勤"]], MeritDemeritAttDic[id].全勤 ? "是" : ""); foreach (String type in _AbsenceType) //列印勾選的假別 { if (MeritDemeritAttDic[id].Attendance.ContainsKey(type)) { SetColumnValue(cs[index, columnIndexTable[type]], MeritDemeritAttDic[id].Attendance[type]); } } index++; //換下一列 } //最後總計 index = FixIndex(index); Range endRow = cs.CreateRange(0, 1, false); cs.CreateRange(index, 1, false).Copy(endRow); cs[index, 0].PutValue("總計"); foreach (int cloumnIndex in _CountAllColumnValue.Keys) { cs[index, cloumnIndex].PutValue(_CountAllColumnValue[cloumnIndex]); } //列印日期及學校班級資訊 cs[0, 0].PutValue("列印日期:" + DateTime.Today.ToShortDateString()); cs.CreateRange(0, 3, 1, columnIndexTable.Last().Value - 2).Merge(); //合併標題欄位的儲存格 String title = String.Format("{0} {1} 學年度 {2} 學期 {3} 缺曠獎懲總表", K12.Data.School.ChineseName, _Schoolyear, _Semester == 1 ? "上" : "下", GetClassName(classid)); cs[0, 3].PutValue(title); cs[0, 3].Style.Font.Size = 28; //設定標題文字大小 cs[0, 3].Style.Font.IsBold = true; sheetIndex++; //換下一個sheet(下一個班級班) } //int sheet = _WK.Worksheets.Count; //for (int i = 0; i < sheet; i++) //{ // _WK.Worksheets[i].AutoFitColumns(); // _WK.Worksheets[i].AutoFitRows(); //} BGW.ReportProgress(100, "已完成 班級缺曠獎懲總表"); #endregion }
public override List <String> GetMultipleVideoUrls(VideoInfo video, bool inPlaylist = false) { List <String> urls = new List <String>(); string resultUrl = GetVideoUrl(video); if (video.PlaybackOptions != null && video.PlaybackOptions.Count > 0) { List <string> valueList = video.PlaybackOptions.Values.ToList(); video.PlaybackOptions.Clear(); foreach (string value in valueList) { urls.Add(value); } } else { if (!string.IsNullOrEmpty(resultUrl)) { urls.Add(resultUrl); Uri uri = new Uri(resultUrl); foreach (HosterBase hosterUtil in HosterFactory.GetAllHosters()) { if (uri.Host.ToLower().Contains(hosterUtil.GetHosterUrl().ToLower())) { Dictionary <string, string> options = hosterUtil.GetPlaybackOptions(resultUrl); if (options != null && options.Count > 0) { string chosenoption = options.Last().Key; List <string> availoptions = options.Keys.ToList(); for (int i = availoptions.Count - 1; i >= 0; i--) { if (useMP4Playback && availoptions[i].IndexOf("mp4", StringComparison.InvariantCultureIgnoreCase) > -1) { chosenoption = availoptions[i]; break; } else if (!useMP4Playback && availoptions[i].IndexOf("flv", StringComparison.InvariantCultureIgnoreCase) > -1) { chosenoption = availoptions[i]; break; } } if (autoChoose) { urls.Clear(); urls.Add(options[chosenoption]); break; } else { urls.Clear(); video.PlaybackOptions = options; urls.Add(options[chosenoption]); break; } } } } } } return(urls); }
/// <summary> /// Builds the layout (sections) of the modern page /// </summary> /// <param name="pageData">Information about the source page</param> public void Transform(Tuple <Pages.PageLayout, List <WebPartEntity> > pageData) { bool includeVerticalColumn = false; int verticalColumnEmphasis = 0; if (pageData.Item1 == Pages.PageLayout.PublishingPage_AutoDetectWithVerticalColumn) { includeVerticalColumn = true; verticalColumnEmphasis = GetVerticalColumnBackgroundEmphasis(); } // First drop all sections...ensure the default section is gone page.Sections.Clear(); // Should not occur, but to be at the safe side... if (pageData.Item2.Count == 0) { page.AddSection(CanvasSectionTemplate.OneColumn, 1, GetBackgroundEmphasis(1)); return; } var firstRow = pageData.Item2.OrderBy(p => p.Row).First().Row; var lastRow = pageData.Item2.OrderBy(p => p.Row).Last().Row; // Loop over the possible rows...will take in account possible row gaps // Each row means a new section int sectionOrder = 1; for (int rowIterator = firstRow; rowIterator <= lastRow; rowIterator++) { var webpartsInRow = pageData.Item2.Where(p => p.Row == rowIterator); if (webpartsInRow.Any()) { // Determine max column number int maxColumns = 1; foreach (var wpInRow in webpartsInRow) { if (wpInRow.Column > maxColumns) { maxColumns = wpInRow.Column; } } // Deduct the vertical column if (includeVerticalColumn && rowIterator == firstRow) { maxColumns--; } if (maxColumns > 3) { LogError(LogStrings.Error_Maximum3ColumnsAllowed, LogStrings.Heading_PublishingLayoutTransformator); throw new Exception("Publishing transformation layout mapping can maximum use 3 columns"); } else { if (maxColumns == 1) { if (includeVerticalColumn && rowIterator == firstRow) { page.AddSection(CanvasSectionTemplate.OneColumnVerticalSection, sectionOrder, GetBackgroundEmphasis(rowIterator), verticalColumnEmphasis); } else { page.AddSection(CanvasSectionTemplate.OneColumn, sectionOrder, GetBackgroundEmphasis(rowIterator)); } } else if (maxColumns == 2) { // if we've only an image in one of the columns then make that one the 'small' column var imageWebPartsInRow = webpartsInRow.Where(p => p.Type == WebParts.WikiImage); if (imageWebPartsInRow.Any()) { Dictionary <int, int> imageWebPartsPerColumn = new Dictionary <int, int>(); foreach (var imageWebPart in imageWebPartsInRow.OrderBy(p => p.Column)) { if (imageWebPartsPerColumn.TryGetValue(imageWebPart.Column, out int wpCount)) { imageWebPartsPerColumn[imageWebPart.Column] = wpCount + 1; } else { imageWebPartsPerColumn.Add(imageWebPart.Column, 1); } } var firstImageColumn = imageWebPartsPerColumn.First(); var secondImageColumn = imageWebPartsPerColumn.Last(); if (firstImageColumn.Key == secondImageColumn.Key) { // there was only one column with images var firstImageColumnOtherWebParts = webpartsInRow.Where(p => p.Column == firstImageColumn.Key && p.Type != WebParts.WikiImage); if (firstImageColumnOtherWebParts.Count() == 0) { // no other web parts in this column var orderedList = webpartsInRow.OrderBy(p => p.Column).First(); if (orderedList.Column == firstImageColumn.Key) { // image left if (includeVerticalColumn && rowIterator == firstRow) { page.AddSection(CanvasSectionTemplate.TwoColumnRightVerticalSection, sectionOrder, GetBackgroundEmphasis(rowIterator), verticalColumnEmphasis); } else { page.AddSection(CanvasSectionTemplate.TwoColumnRight, sectionOrder, GetBackgroundEmphasis(rowIterator)); } } else { // image right if (includeVerticalColumn && rowIterator == firstRow) { page.AddSection(CanvasSectionTemplate.TwoColumnLeftVerticalSection, sectionOrder, GetBackgroundEmphasis(rowIterator), verticalColumnEmphasis); } else { page.AddSection(CanvasSectionTemplate.TwoColumnLeft, sectionOrder, GetBackgroundEmphasis(rowIterator)); } } } else { if (includeVerticalColumn && rowIterator == firstRow) { page.AddSection(CanvasSectionTemplate.TwoColumnVerticalSection, sectionOrder, GetBackgroundEmphasis(rowIterator), verticalColumnEmphasis); } else { page.AddSection(CanvasSectionTemplate.TwoColumn, sectionOrder, GetBackgroundEmphasis(rowIterator)); } } } else { if (firstImageColumn.Value == 1 || secondImageColumn.Value == 1) { // does one of the two columns have anything else besides image web parts var firstImageColumnOtherWebParts = webpartsInRow.Where(p => p.Column == firstImageColumn.Key && p.Type != WebParts.WikiImage); var secondImageColumnOtherWebParts = webpartsInRow.Where(p => p.Column == secondImageColumn.Key && p.Type != WebParts.WikiImage); if (firstImageColumnOtherWebParts.Count() == 0 && secondImageColumnOtherWebParts.Count() == 0) { // two columns with each only one image... if (includeVerticalColumn && rowIterator == firstRow) { page.AddSection(CanvasSectionTemplate.TwoColumnVerticalSection, sectionOrder, GetBackgroundEmphasis(rowIterator), verticalColumnEmphasis); } else { page.AddSection(CanvasSectionTemplate.TwoColumn, sectionOrder, GetBackgroundEmphasis(rowIterator)); } } else if (firstImageColumnOtherWebParts.Count() == 0 && secondImageColumnOtherWebParts.Count() > 0) { if (includeVerticalColumn && rowIterator == firstRow) { page.AddSection(CanvasSectionTemplate.TwoColumnRightVerticalSection, sectionOrder, GetBackgroundEmphasis(rowIterator), verticalColumnEmphasis); } else { page.AddSection(CanvasSectionTemplate.TwoColumnRight, sectionOrder, GetBackgroundEmphasis(rowIterator)); } } else if (firstImageColumnOtherWebParts.Count() > 0 && secondImageColumnOtherWebParts.Count() == 0) { if (includeVerticalColumn && rowIterator == firstRow) { page.AddSection(CanvasSectionTemplate.TwoColumnLeftVerticalSection, sectionOrder, GetBackgroundEmphasis(rowIterator), verticalColumnEmphasis); } else { page.AddSection(CanvasSectionTemplate.TwoColumnLeft, sectionOrder, GetBackgroundEmphasis(rowIterator)); } } else { if (includeVerticalColumn && rowIterator == firstRow) { page.AddSection(CanvasSectionTemplate.TwoColumnVerticalSection, sectionOrder, GetBackgroundEmphasis(rowIterator), verticalColumnEmphasis); } else { page.AddSection(CanvasSectionTemplate.TwoColumn, sectionOrder, GetBackgroundEmphasis(rowIterator)); } } } else { if (includeVerticalColumn && rowIterator == firstRow) { page.AddSection(CanvasSectionTemplate.TwoColumnVerticalSection, sectionOrder, GetBackgroundEmphasis(rowIterator), verticalColumnEmphasis); } else { page.AddSection(CanvasSectionTemplate.TwoColumn, sectionOrder, GetBackgroundEmphasis(rowIterator)); } } } } else { if (includeVerticalColumn && rowIterator == firstRow) { page.AddSection(CanvasSectionTemplate.TwoColumnVerticalSection, sectionOrder, GetBackgroundEmphasis(rowIterator), verticalColumnEmphasis); } else { page.AddSection(CanvasSectionTemplate.TwoColumn, sectionOrder, GetBackgroundEmphasis(rowIterator)); } } } else if (maxColumns == 3) { if (includeVerticalColumn && rowIterator == firstRow) { page.AddSection(CanvasSectionTemplate.ThreeColumnVerticalSection, sectionOrder, GetBackgroundEmphasis(rowIterator), verticalColumnEmphasis); } else { page.AddSection(CanvasSectionTemplate.ThreeColumn, sectionOrder, GetBackgroundEmphasis(rowIterator)); } } sectionOrder++; } } else { // non used row...ignore } } }
public void MoveParticipants() { //Initialize SectionData nextSection = _positions.First().Value; SectionData hiddenSectionData = new SectionData(); bool enteredOnce = false; IParticipant participant1 = _positions.Last().Value.Left; IParticipant participant2 = _positions.Last().Value.Right; //Iterate through all the positions, reverse the positions because otherwise it's checking the wrong way foreach (KeyValuePair <Section, SectionData> kvPair in _positions.Reverse()) { SectionData currentSectionSD = kvPair.Value; if (currentSectionSD.Left != null) { SaveSectionTimes(kvPair.Key, kvPair.Value, DateTime.Now, "left"); if (!currentSectionSD.Left.Equipment.IsBroken) { if (Section.Length > currentSectionSD.DistanceLeft) { currentSectionSD.DistanceLeft += currentSectionSD.Left.Equipment.Speed * currentSectionSD.Left.Equipment.Performance; } if (currentSectionSD.DistanceLeft >= Section.Length) { if (kvPair.Key.SectionType == SectionTypes.Finish) { CheckFinishes(kvPair.Value, "left"); } MoveParticipantsLeftSection(nextSection, currentSectionSD); } } } if (currentSectionSD.Right != null) { SaveSectionTimes(kvPair.Key, kvPair.Value, DateTime.Now, "right"); if (!currentSectionSD.Right.Equipment.IsBroken) { if (Section.Length > currentSectionSD.DistanceRight) { currentSectionSD.DistanceRight += currentSectionSD.Right.Equipment.Speed * currentSectionSD.Right.Equipment.Performance; } if (currentSectionSD.DistanceRight >= Section.Length) { if (kvPair.Key.SectionType == SectionTypes.Finish) { CheckFinishes(kvPair.Value, "right"); } MoveParticipantsRightSection(nextSection, currentSectionSD); } } } //If you moved it, don't move it again. if (!enteredOnce) { //Check if any of them has moved from the end of the track to the start if (participant1 == _positions.First().Value.Left || participant1 == _positions.First().Value.Right || participant2 == _positions.First().Value.Left || participant2 == _positions.First().Value.Right) { hideParticipant(_positions.First().Value, hiddenSectionData, participant1, participant2); } //So the if condition only executes once at the start of the foreach enteredOnce = true; } //Compare next two sections, backwards nextSection = kvPair.Value; } //No point on revealing if there is nothing on the hiddensection if (hiddenSectionData.Left != null || hiddenSectionData.Right != null) { RevealParticipant(_positions.First().Value, hiddenSectionData); } }
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); } } }
private void button3_Click(object sender, EventArgs e) { string prywatne = textBox4.Text; string[] k = prywatne.Split(','); int[] priv = { Convert.ToInt32(k[0]), Convert.ToInt32(k[1]) }; if (radioButton1.Checked) { Dictionary <int, double> potegi2 = new Dictionary <int, double>(); double dor = Convert.ToDouble(textBox5.Text); potegi2.Add(1, dor % priv[1]); do { potegi2.Add(potegi2.Last().Key * 2, Math.Pow(potegi2.Last().Value, 2) % priv[1]); } while (potegi2.Last().Key < priv[0] / 2); BigInteger sum = 1; while (priv[0] != 0) { if (priv[0] >= potegi2.Last().Key) { sum *= Convert.ToInt64(potegi2.Last().Value); priv[0] -= potegi2.Last().Key; //MessageBox.Show(Convert.ToString(sum)); } else { potegi2.Remove(potegi2.Last().Key); } } sum = sum % priv[1]; textBox7.Text = sum.ToString(); } else if (radioButton2.Checked) { string wyraz = ""; string[] sar; sar = textBox5.Text.Split(','); var slist = sar.ToList(); slist.RemoveAt(0); sar = slist.ToArray(); string s = sar.ToString(); int temppriv0 = priv[0]; foreach (string str in sar) { priv[0] = temppriv0; double strval = Convert.ToDouble(str); Dictionary <int, double> potegi2 = new Dictionary <int, double>(); potegi2.Add(1, strval % priv[1]); do { potegi2.Add(potegi2.Last().Key * 2, Math.Pow(potegi2.Last().Value, 2) % priv[1]); } while (potegi2.Last().Key < priv[0] / 2); BigInteger sum = 1; while (priv[0] != 0) { if (priv[0] >= potegi2.Last().Key) { sum *= Convert.ToInt64(potegi2.Last().Value); priv[0] -= potegi2.Last().Key; //MessageBox.Show(Convert.ToString(sum)); } else { potegi2.Remove(potegi2.Last().Key); } } sum = sum % priv[1]; char c = (char)sum; //textBox7.Text = c.ToString(); wyraz += c.ToString(); } textBox7.Text = wyraz; } }
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>[^&]*)&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; }
public override void update() { sectionHelpers_.Clear(); if (size_ == 2) //single period { ISectionHelper singleHelper = new EverywhereConstantHelper(yBegin_[1], 0.0, xBegin_[0]); sectionHelpers_.Add(xBegin_[1], singleHelper); extrapolationHelper_ = singleHelper; return; } List <double> f = new InitializedList <double>(size_); sectionHelpers_ = new Dictionary <double, ISectionHelper>(preSectionHelpers_); int startPoint = sectionHelpers_.Count + 1; //first derive the boundary forwards. for (int i = startPoint; i < size_ - 1; ++i) { double dxPrev = xBegin_[i] - xBegin_[i - 1]; double dx = xBegin_[i + 1] - xBegin_[i]; f[i] = dxPrev / (dx + dxPrev) * yBegin_[i] + dx / (dx + dxPrev) * yBegin_[i + 1]; } if (startPoint > 1) { f[startPoint - 1] = preSectionHelpers_.Last().Value.fNext(); } if (startPoint == 1) { f[0] = 1.5 * yBegin_[1] - 0.5 * f[1]; } f[size_ - 1] = 1.5 * yBegin_[size_ - 1] - 0.5 * f[size_ - 2]; if (forcePositive_) { if (f[0] < 0) { f[0] = 0.0; } if (f[size_ - 1] < 0.0) { f[size_ - 1] = 0.0; } } double primitive = 0.0; for (int i = 0; i < startPoint - 1; ++i) { primitive += yBegin_[i + 1] * (xBegin_[i + 1] - xBegin_[i]); } int endPoint = size_; if (constantLastPeriod_) { endPoint = endPoint - 1; } for (int i = startPoint; i < endPoint; ++i) { double gPrev = f[i - 1] - yBegin_[i]; double gNext = f[i] - yBegin_[i]; //first deal with the zero gradient case if (Math.Abs(gPrev) < 1.0E-14 && Math.Abs(gNext) < 1.0E-14) { ISectionHelper singleHelper = new ConstantGradHelper(f[i - 1], primitive, xBegin_[i - 1], xBegin_[i], f[i]); sectionHelpers_.Add(xBegin_[i], singleHelper); } else { double quadraticity = quadraticity_; ISectionHelper quadraticHelper = null; ISectionHelper convMonotoneHelper = null; if (quadraticity_ > 0.0) { if (gPrev >= -2.0 * gNext && gPrev > -0.5 * gNext && forcePositive_) { quadraticHelper = new QuadraticMinHelper(xBegin_[i - 1], xBegin_[i], f[i - 1], f[i], yBegin_[i], primitive); } else { quadraticHelper = new QuadraticHelper(xBegin_[i - 1], xBegin_[i], f[i - 1], f[i], yBegin_[i], primitive); } } if (quadraticity_ < 1.0) { if ((gPrev > 0.0 && -0.5 * gPrev >= gNext && gNext >= -2.0 * gPrev) || (gPrev < 0.0 && -0.5 * gPrev <= gNext && gNext <= -2.0 * gPrev)) { quadraticity = 1.0; if (quadraticity_.IsEqual(0.0)) { if (forcePositive_) { quadraticHelper = new QuadraticMinHelper( xBegin_[i - 1], xBegin_[i], f[i - 1], f[i], yBegin_[i], primitive); } else { quadraticHelper = new QuadraticHelper( xBegin_[i - 1], xBegin_[i], f[i - 1], f[i], yBegin_[i], primitive); } } } else if ((gPrev < 0.0 && gNext > -2.0 * gPrev) || (gPrev > 0.0 && gNext < -2.0 * gPrev)) { double eta = (gNext + 2.0 * gPrev) / (gNext - gPrev); double b2 = (1.0 + monotonicity_) / 2.0; if (eta < b2) { convMonotoneHelper = new ConvexMonotone2Helper( xBegin_[i - 1], xBegin_[i], gPrev, gNext, yBegin_[i], eta, primitive); } else { if (forcePositive_) { convMonotoneHelper = new ConvexMonotone4MinHelper( xBegin_[i - 1], xBegin_[i], gPrev, gNext, yBegin_[i], b2, primitive); } else { convMonotoneHelper = new ConvexMonotone4Helper( xBegin_[i - 1], xBegin_[i], gPrev, gNext, yBegin_[i], b2, primitive); } } } else if ((gPrev > 0.0 && gNext < 0.0 && gNext > -0.5 * gPrev) || (gPrev < 0.0 && gNext > 0.0 && gNext < -0.5 * gPrev)) { double eta = gNext / (gNext - gPrev) * 3.0; double b3 = (1.0 - monotonicity_) / 2.0; if (eta > b3) { convMonotoneHelper = new ConvexMonotone3Helper( xBegin_[i - 1], xBegin_[i], gPrev, gNext, yBegin_[i], eta, primitive); } else { if (forcePositive_) { convMonotoneHelper = new ConvexMonotone4MinHelper( xBegin_[i - 1], xBegin_[i], gPrev, gNext, yBegin_[i], b3, primitive); } else { convMonotoneHelper = new ConvexMonotone4Helper( xBegin_[i - 1], xBegin_[i], gPrev, gNext, yBegin_[i], b3, primitive); } } } else { double eta = gNext / (gPrev + gNext); double b2 = (1.0 + monotonicity_) / 2.0; double b3 = (1.0 - monotonicity_) / 2.0; if (eta > b2) { eta = b2; } if (eta < b3) { eta = b3; } if (forcePositive_) { convMonotoneHelper = new ConvexMonotone4MinHelper( xBegin_[i - 1], xBegin_[i], gPrev, gNext, yBegin_[i], eta, primitive); } else { convMonotoneHelper = new ConvexMonotone4Helper( xBegin_[i - 1], xBegin_[i], gPrev, gNext, yBegin_[i], eta, primitive); } } } if (quadraticity.IsEqual(1.0)) { sectionHelpers_.Add(xBegin_[i], quadraticHelper); } else if (quadraticity.IsEqual(0.0)) { sectionHelpers_.Add(xBegin_[i], convMonotoneHelper); } else { sectionHelpers_.Add(xBegin_[i], new ComboHelper(quadraticHelper, convMonotoneHelper, quadraticity)); } } primitive += yBegin_[i] * (xBegin_[i] - xBegin_[i - 1]); } if (constantLastPeriod_) { sectionHelpers_.Add(xBegin_[size_ - 1], new EverywhereConstantHelper(yBegin_[size_ - 1], primitive, xBegin_[size_ - 2])); extrapolationHelper_ = sectionHelpers_[xBegin_[size_ - 1]]; } else { extrapolationHelper_ = new EverywhereConstantHelper((sectionHelpers_.Last()).Value.value(xBegin_.Last()), primitive, xBegin_.Last()); } }
public string FormatReplication() { if (DataScriptSize <= 0) { return(String.Empty); } var replicatedObjects = new List <IUnrealNetObject>(); if (Variables != null) { replicatedObjects.AddRange(Variables.Where(prop => prop.HasPropertyFlag(Flags.PropertyFlagsLO.Net) && prop.RepOffset != ushort.MaxValue)); } if (Package.Version < VReliableDeprecation && Functions != null) { replicatedObjects.AddRange(Functions.Where(func => func.HasFunctionFlag(Flags.FunctionFlags.Net) && func.RepOffset != ushort.MaxValue)); } if (replicatedObjects.Count == 0) { return(String.Empty); } var statements = new Dictionary <uint, List <IUnrealNetObject> >(); replicatedObjects.Sort((ro, ro2) => ro.RepKey.CompareTo(ro2.RepKey)); for (int netIndex = 0; netIndex < replicatedObjects.Count; ++netIndex) { var firstObject = replicatedObjects[netIndex]; var netObjects = new List <IUnrealNetObject> { firstObject }; for (int nextIndex = netIndex + 1; nextIndex < replicatedObjects.Count; ++nextIndex) { var nextObject = replicatedObjects[nextIndex]; if (nextObject.RepOffset != firstObject.RepOffset || nextObject.RepReliable != firstObject.RepReliable ) { netIndex = nextIndex - 1; break; } netObjects.Add(nextObject); } netObjects.Sort((o, o2) => String.Compare(o.Name, o2.Name, StringComparison.Ordinal)); if (!statements.ContainsKey(firstObject.RepKey)) { statements.Add(firstObject.RepKey, netObjects); } } replicatedObjects.Clear(); var output = new StringBuilder("\r\n" + "replication" + UnrealConfig.PrintBeginBracket()); UDecompilingState.AddTab(); foreach (var statement in statements) { try { var pos = (ushort)(statement.Key & 0x0000FFFF); var rel = Convert.ToBoolean(statement.Key & 0xFFFF0000); output.Append("\r\n" + UDecompilingState.Tabs); if (!UnrealConfig.SuppressComments) { output.AppendFormat("// Pos:0x{0:X3}\r\n{1}", pos, UDecompilingState.Tabs); } ByteCodeManager.Deserialize(); ByteCodeManager.JumpTo(pos); string statementCode; try { statementCode = ByteCodeManager.CurrentToken.Decompile(); } catch (Exception e) { statementCode = String.Format("/* An exception occurred while decompiling condition ({0}) */", e); } var statementType = Package.Version < VReliableDeprecation ? rel ? "reliable" : "unreliable" : String.Empty; var statementFormat = String.Format("{0} if({1})", statementType, statementCode); output.Append(statementFormat); UDecompilingState.AddTab(); // NetObjects for (int i = 0; i < statement.Value.Count; ++i) { var shouldSplit = i % 2 == 0; if (shouldSplit) { output.Append("\r\n" + UDecompilingState.Tabs); } var netObject = statement.Value[i]; output.Append(netObject.Name); var isNotLast = i != statement.Value.Count - 1; output.Append(isNotLast ? ", " : ";"); } UDecompilingState.RemoveTab(); // IsNotLast if (statements.Last().Key != statement.Key) { output.Append("\r\n"); } } catch (Exception e) { output.AppendFormat("/* An exception occurred while decompiling a statement! ({0}) */", e); } } UDecompilingState.RemoveTab(); output.Append(UnrealConfig.PrintEndBracket() + "\r\n"); return(output.ToString()); }
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(); }
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; }
//public int IntParseFast(string value) //{ // int result = 0; // for (int i = 0; i < value.Length; i++) // { // char letter = value[i]; // result = 10 * result + (letter - 48); // } // return result; //} /// <summary> /// Parse RidBags ex. %[content:binary]; where [content:binary] is the actual binary base64 content. /// </summary> /// <param name="i"></param> /// <param name="recordString"></param> /// <param name="document"></param> /// <param name="fieldName"></param> /// <returns></returns> private int ParseRidBags(int i, string recordString, ODocument document, string fieldName) { //move to first base64 char i++; StringBuilder builder = new StringBuilder(); while (recordString[i] != ';') { builder.Append(recordString[i]); i++; } // use a list as it preserves order at this stage which may be important when using ordered edges var rids = new List <ORID>(); var value = Convert.FromBase64String(builder.ToString()); using (var stream = new MemoryStream(value)) using (var reader = new BinaryReader(stream)) { var first = reader.ReadByte(); int offset = 1; if ((first & 2) == 2) { // uuid parsing is not implemented offset += 16; } if ((first & 1) == 1) // 1 - embedded,0 - tree-based { var entriesSize = reader.ReadInt32EndianAware(); for (int j = 0; j < entriesSize; j++) { var clusterid = reader.ReadInt16EndianAware(); var clusterposition = reader.ReadInt64EndianAware(); rids.Add(new ORID(clusterid, clusterposition)); } } else { // Maybe not parse this type of Field and only then Requested retrieve ? // Lazy loading if (_connection == null || !_connection.IsActive) { throw new OException(OExceptionType.Connection, "Connection is not opened or is null"); } // Tree based RidBag - (collectionPointer)(size:int)(changes) // Collection Pointer - (fileId:long)(pageIndex:long)(pageOffset:int) var fileId = reader.ReadInt64EndianAware(); var pageIndex = reader.ReadInt64EndianAware(); var pageOffset = reader.ReadInt32EndianAware(); // size var size = reader.ReadInt32EndianAware(); //only process ridbag if size > 0, otherwise the call to SBTreeBonsaiFirstKey operation makes the connection crash (the server probably isn't expecting this use case) if (size > 0) { // Changes - (changesSize:int)[(link:rid)(changeType:byte)(value:int)]* var changesSize = reader.ReadInt32EndianAware(); for (int j = 0; j < changesSize; j++) { throw new NotImplementedException("RidBag Changes not yet implemented"); } var operation = new SBTreeBonsaiFirstKey(null); operation.FileId = fileId; operation.PageIndex = pageIndex; operation.PageOffset = pageOffset; // Not realy quiete about this var connection = OClient.ReleaseConnection(_connection.Alias); var entries = new Dictionary <ORID, int>(); try { var orid = connection.ExecuteOperation(operation); var ft = true; var key = orid.GetField <ORID>("rid"); do { var op = new SBTreeBonsaiGetEntriesMajor(null); op.FileId = fileId; op.PageIndex = pageIndex; op.PageOffset = pageOffset; op.FirstKey = key; op.Inclusive = ft; var res = connection.ExecuteOperation(op); entries = res.GetField <Dictionary <ORID, int> >("entries"); rids.AddRange(entries.Keys); if (entries.Count == 0) { break; } key = entries.Last().Key; ft = false; } while (true); } finally { OClient.ReturnConnection(connection); } } } } document[fieldName] = rids; //move past ';' i++; return(i); }
/// <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); }
private void CalculateCyclePoint( Dictionary <int, int> numberToCycleTable, Dictionary <int, int> spNumberToCycleTable, Dictionary <int, LotteryListRecord> listModels, List <AnalyzeResult> result, int samplingCount) { int currentTime = listModels.Last().Key; int extensionTime = 0; Dictionary <int, double> numberToPointTable = new Dictionary <int, double>(); Dictionary <int, double> spNumberToPointTable = new Dictionary <int, double>(); while (numberToPointTable.Count < 25) { int point = samplingCount - (int)Math.Pow(2, extensionTime); if (point <= 0) { break; } foreach (var pair in numberToCycleTable) { int target = currentTime - pair.Value + 1; LotteryListRecord tmpList; if (listModels.TryGetValue(target - extensionTime, out tmpList) && tmpList.NormalList.Contains(pair.Key)) { if (numberToPointTable.ContainsKey(pair.Key)) { numberToPointTable[pair.Key] += point; } else { numberToPointTable.Add(pair.Key, point); } } if (listModels.TryGetValue(target + extensionTime, out tmpList) && tmpList.NormalList.Contains(pair.Key)) { if (numberToPointTable.ContainsKey(pair.Key)) { numberToPointTable[pair.Key] += point; } else { numberToPointTable.Add(pair.Key, point); } } } extensionTime++; } extensionTime = 0; while (!spNumberToPointTable.Any()) { int point = samplingCount - (int)Math.Pow(2, extensionTime); if (point <= 0) { break; } foreach (var pair in spNumberToCycleTable) { int target = currentTime - pair.Value + 1; if (listModels.TryGetValue(target - extensionTime, out var value) && value.Sp == pair.Key) { if (spNumberToPointTable.ContainsKey(pair.Key)) { spNumberToPointTable[pair.Key] += point; } else { spNumberToPointTable.Add(pair.Key, point); } } if (listModels.TryGetValue(target + extensionTime, out value) && value.Sp == pair.Key) { if (spNumberToPointTable.ContainsKey(pair.Key)) { spNumberToPointTable[pair.Key] += point; } else { spNumberToPointTable.Add(pair.Key, point); } } } extensionTime++; } result.AddRange(numberToPointTable.Select(p => new AnalyzeResult { IsSpecial = false, Number = p.Key, Point = p.Value })); result.AddRange(spNumberToPointTable.Select(p => new AnalyzeResult { IsSpecial = true, Number = p.Key, Point = p.Value })); }
public List <Slot> GetAvailableAppointmentTimesForInjectorByPeriod(Guid periodGuid, Guid accountGuid, Guid serviceGuid) { List <Slot> timeslots = new List <Slot>(); Dictionary <DateTime, TimeSpan> unavailables = new Dictionary <DateTime, TimeSpan>(); Dictionary <DateTime, TimeSpan> availables = new Dictionary <DateTime, TimeSpan>(); Period period = GetPeriodByPeriodGuid(periodGuid); Service service = new ServiceManager().Read(serviceGuid); TimeSpan requestedDuration = new TimeSpan(service.Hours, service.Minutes, 0); List <Appointment> appointments = new AppointmentManager().GetAppointmentsByPeriodGuid(periodGuid).OrderBy(model => model.AppointmentStart.Hour).ToList(); if (appointments.Count > 0) { // build unavailable slots foreach (Appointment app in appointments) { TimeSpan appDuration = app.AppointmentEnd - app.AppointmentStart; unavailables.Add(app.AppointmentStart, appDuration); } if (unavailables.Count > 0) { // build available slots // calculate the time in between unavailable slots // to get available slots DateTime currentStartTime = period.StartDate; foreach (KeyValuePair <DateTime, TimeSpan> bookedSlot in unavailables) { // get the difference slot based on the unavailable slot and start time TimeSpan potentialSlotTime = bookedSlot.Key - currentStartTime; // check if that available slot is long enough for the duration if (potentialSlotTime >= requestedDuration) { // it's long enough, we should add it to the availables availables.Add(currentStartTime, potentialSlotTime); } else { // it's not long enough, discard it's use } } // now we can check the timespan after all of the appointments // based on the last appointments end time // get last appointments end time DateTime lastAppointmentEndTime = unavailables.Last().Key.Add(unavailables.Last().Value); // subtract it from the end of the work period to get the remaining time TimeSpan remainingWorkPeriodTime = period.StopDate - lastAppointmentEndTime; // we can add the remaining work period time to the availables because it's not booked availables.Add(lastAppointmentEndTime, remainingWorkPeriodTime); // now we can loop through the availables and build some slots // set a start time to keep up with each available DateTime availableStartTime = new DateTime(); foreach (KeyValuePair <DateTime, TimeSpan> emptyWorkPeriodSpan in availables) { // set the start time availableStartTime = emptyWorkPeriodSpan.Key; TimeSpan allowedTime = emptyWorkPeriodSpan.Value; if (allowedTime >= requestedDuration) { // we have an empty work period span that is longer than the requested duration do { Slot slot = new Slot { PeriodGuid = period.PeriodGuid, Duration = requestedDuration, StartTime = availableStartTime, EndTime = availableStartTime.Add(requestedDuration) }; allowedTime -= requestedDuration; if (slot.StartTime >= DateTime.Now.AddMinutes(15)) { timeslots.Add(slot); } } while (allowedTime >= requestedDuration); } } } } else { // set the current start time DateTime currentStartTime = period.StartDate; // set the total time for the current work period TimeSpan totalPeriod = period.StopDate - period.StartDate; do { // create a new slot Slot slot = new Slot { PeriodGuid = period.PeriodGuid, Duration = requestedDuration, StartTime = currentStartTime, EndTime = currentStartTime.Add(requestedDuration) }; // check if the slot's start time is later than 15 minutes from now if (slot.StartTime > DateTime.Now.AddMinutes(15)) { timeslots.Add(slot); } // set the start time to the next available time based on duration currentStartTime = currentStartTime.Add(requestedDuration); // subtract the duration from the work period totalPeriod -= requestedDuration; } while (totalPeriod > requestedDuration); } return(timeslots); }
public void Page_Write_CorruptPage_Read(int count) { var ms = new MemoryStream(); var meta = VolumeMetadataBuilder.Make("Volume-1", "raw"); var v1 = new DefaultVolume(CryptoMan, meta, ms); var page = new Page(0); Aver.IsTrue(page.State == Page.Status.Unset); page.BeginWriting(new DateTime(1980, 7, 1, 15, 0, 0, DateTimeKind.Utc), Atom.Encode("app"), "*****@*****.**"); var data = new Dictionary <int, byte[]>(); for (var i = 0; i < count; i++) { //generate 1/2 empty arrays for best compression, another 1/2/ filled with random data var buf = ((i & 1) == 0) ? new byte[1 + (i & 0x7f)] : Platform.RandomGenerator.Instance.NextRandomBytes(1 + (i & 0x7f)); var adr = page.Append(new ArraySegment <byte>(buf)); data[adr] = buf; } Aver.AreEqual(data.Count, data.Keys.Distinct().Count());//all addresses are unique page.EndWriting(); var pid = v1.AppendPage(page); //append to volume page = new Page(0); //we could have reused the existing page but we re-allocate for experiment cleanness v1.ReadPage(pid, page); //Aver that all are readable foreach (var kvp in data) { var got = page[kvp.Key]; Aver.IsTrue(got.State == Entry.Status.Valid); Aver.IsTrue(IOUtils.MemBufferEquals(kvp.Value, got.Raw.ToArray())); } //now corrupt First var cadr = data.First().Key; page.Data.Array[cadr] = 0xff; //corrupt underlying page memory data[cadr] = null; //corrupted //corrupt last cadr = data.Last().Key; page.Data.Array[cadr] = 0x00; //corrupt underlying page memory data[cadr] = null; //corrupted var keys = data.Keys.ToArray(); //corrupt a half of written for (var i = 0; i < data.Count / 2; i++) { cadr = keys[Platform.RandomGenerator.Instance.NextScaledRandomInteger(2, data.Count - 2)]; page.Data.Array[cadr] = 0xff; //corrupt underlying page memory data[cadr] = null; //corrupted } "\nStream size is: {0:n0} bytes".SeeArgs(ms.Length); "{0:n0} total entries, {1:n0} are corrupt \n".SeeArgs(data.Count, data.Where(kvp => kvp.Value == null).Count()); //Aver that all which are SET are still readable, others are corrupt foreach (var kvp in data) { var got = page[kvp.Key]; if (kvp.Value != null)//was not corrupted { Aver.IsTrue(got.State == Entry.Status.Valid); Aver.IsTrue(IOUtils.MemBufferEquals(kvp.Value, got.Raw.ToArray())); } else { Aver.IsTrue(got.State == Entry.Status.BadHeader); } } }
private static void MessagingTest() { var sendTokenPair = userKeyTokens.Last(); userKeyTokens.Remove(sendTokenPair.Key); var rcvTokenPair = userKeyTokens.Last(); userKeyTokens.Remove(rcvTokenPair.Key); var senderCypherApi = new NtkCypher(ntkApi, keyStore); var rcvCypherApi = new NtkCypher(ntkApi, keyStore); NtkCryptoEntity sender, receiver; try { var message = "Hello world!"; Console.WriteLine("Using keytoken {0} for send", sendTokenPair); // BootstrapEntity returns NtkCryptoEntity object with Pkey field identifying current user, that can be used as receiver identifier // Pkey.Expired can be used for check if key needs to be bootstraped again sender = senderCypherApi.BootstrapEntity(sendTokenPair.Key).GetAwaiter().GetResult(); Console.WriteLine("Registered key for sender {0} ({1}):\n{2}", sender.UserId, sender.Pkey.Uuid, sender.Pkey.ToString()); if (!sender.Pkey.Expired) { Console.WriteLine("Sender key is valid, can receive messages until {0}", sender.Pkey.ValidBefore); } Console.WriteLine("Using keytoken {0} for receive", rcvTokenPair); receiver = rcvCypherApi.BootstrapEntity(rcvTokenPair.Key).GetAwaiter().GetResult(); Console.WriteLine("Registered key for receiver {0} ({1}):\n{2}", receiver.UserId, receiver.Pkey.Uuid, receiver.Pkey.ToString()); if (rcvCypherApi.QueryOwner().Expired) { Console.WriteLine("Receiver key has expired"); // request new authentication and trade rcvTokenPair.Key for new key // makes sense to do this before key has already expired receiver = rcvCypherApi.BootstrapEntity(rcvTokenPair.Key).GetAwaiter().GetResult(); } // binary format var cypherB = senderCypherApi.SendTo(receiver.Pkey.Uuid, System.Text.Encoding.UTF8.GetBytes(message)).GetAwaiter().GetResult(); Console.WriteLine("Sending cypher to user {0}:\n{1} ({2} bytes)", receiver.UserId, "<binary data>", cypherB.Length); var resB = rcvCypherApi.ReceiveMsg(cypherB).GetAwaiter().GetResult(); var gotMessage = System.Text.Encoding.UTF8.GetString(resB); Console.WriteLine("Decrypted cypher from user {0}:\n{1}", sender.UserId, gotMessage); // serialized string in base64 and reversed sender / receiver var cypher = rcvCypherApi.SendTo(sender.Pkey.Uuid, "Cool, got your message: " + gotMessage).GetAwaiter().GetResult(); Console.WriteLine("Sending cypher to user {0}:\n{1} ({2} bytes)", sender.UserId, cypher, cypher.Length); var res = senderCypherApi.ReceiveMsg(cypher).GetAwaiter().GetResult(); Console.WriteLine("Decrypted cypher from user {0}:\n{1}", receiver.UserId, res); } catch (Exception ex) { Console.WriteLine("Caught exception: {0} {1}", nameof(ex), ex.Message); } }
private static int RecursiveSetSudokuValue(ref Dictionary <int, int> dOldValue, ref Dictionary <string, string> dict, int pos, ref int RecCheck, int Value) { bool CheckCol = true; bool CheckRow = true; bool CheckSq = true; bool ValueAdded = false; int OldKey; int OldValue; int iRes = 0; // Create List object that will hold zero list List <int> dZList = new List <int>(); RecCheck++; Debug.WriteLine("Inside RecursiveSetSudokuValue for the: " + RecCheck + " time"); for (int i = Value; i <= 9; i++) { //Check unique value for Column CheckCol = GetColumn(dict, pos, i.ToString()); //Check unique value for Row CheckRow = GetRow(dict, pos, i.ToString()); //Check unique value for Square CheckSq = GetSquare(dict, pos, i.ToString()); if ((CheckCol && CheckRow && CheckSq) == true) { Debug.WriteLine("Found a value to set; position: " + pos + " Value: " + i.ToString()); //Put values in the dictionary object that holds old values dOldValue.Add(pos, i); //Add new value to the given position on the Sudoku dict [pos.ToString()] = i.ToString(); ValueAdded = true; //Take the next square from the zero array only if not backtracked iRes = BuildZeroList(ref dZList, dict); //Search for end condition if (dZList.Count != 0) { Debug.WriteLine("Still there exists zeros: " + dZList.Count); Debug.WriteLine(" "); //call recursive function, set value to 1 since it's time to start from the beginning on the new position return(RecursiveSetSudokuValue(ref dOldValue, ref dict, dZList.First(), ref RecCheck, 1)); } else { Debug.WriteLine("Found a solution!"); return(1); } } } // In this case we have a problem; we couldn't find a number to add //So we have to backtrack using our list of previous added numbers while (true) { if (ValueAdded == false) { //OldKey = dOldValue.ElementAt(0).Key; OldKey = dOldValue.Last().Key; //Set back to zero OldValue = dOldValue.Last().Value; //Check that oldvalue is not greater than nine if ((OldValue + 1) != 10) { //Add a zero to the old key in the Sudoku dict[OldKey.ToString()] = 0.ToString(); //Remove the key, value numbers from the list of previous added numbers dOldValue.Remove(dOldValue.Last().Key); //Check if there still exists old values to backtrack if (dOldValue.Count != 0) { //Recursive call to SetSudokuValue Debug.WriteLine("Didn't find any values to set in position " + pos); Debug.WriteLine("Calling RecursiveSetSudokuValue with position: " + OldKey + " and value: " + OldValue); Debug.WriteLine(" "); return(RecursiveSetSudokuValue(ref dOldValue, ref dict, OldKey, ref RecCheck, OldValue + 1)); } return(0); } //We have reach a nine, we need to backtrack once more else { //Add a zero to the Zudoku dict[OldKey.ToString()] = 0.ToString(); //Remove the key, value numbers from the list of previous added numbers dOldValue.Remove(dOldValue.Last().Key); } } } }