public void TestThatApplyingConfigThrowsOnNonWriteableSetting() { _configurator.ReadConfiguration("ATestRule.ASetting=value"); var rules = new Rules(typeof (ATestRule).Assembly); _configurator.ApplyConfiguration(rules); // should throw }
internal static async Task<Character> LoadFromFileAsync (string filename, Rules rules) { Character character = null; Stopwatch timer = Stopwatch.StartNew(); try { string xmlString; using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 0x1000, useAsync: true)) { using (var reader = new StreamReader(file)) { xmlString = await reader.ReadToEndAsync(); } } // cleanup campaign settings // CBuilder sometimes seems to insert invalid XML values? var endStr = "</D20CampaignSetting>"; int start = xmlString.IndexOf("<D20CampaignSetting"); int end = xmlString.IndexOf(endStr) + endStr.Length; if (start != -1 && end != -1 && start < end) { xmlString = xmlString.Remove(start, end - start + 1); } ImportCharacter import = await xmlString.DeserializeXmlAsync<ImportCharacter>(); character = import.ToCharacter(rules); } finally { timer.Stop(); Trace.TraceInformation("Deserializing Character [{0}] from CB took {1}ms", Path.GetFileName(filename), timer.ElapsedMilliseconds); } return character; }
public DocumentMngr() { //Factory = new DaoFactory(); WType = new WmsTypes(Factory); Rules = new Rules(Factory); }
public Setting(Config.Config config) { this.config = config; stores = new Stores(this); hosts = new Hosts(this); rules = new Rules(this); }
/// <summary> /// Generate SonarQube specifc rules based on Roslyn based diagnostics /// </summary> public Rules GenerateRules(IEnumerable<DiagnosticAnalyzer> analyzers) { if (analyzers == null) { throw new ArgumentNullException("analyzers"); } Rules rules = new Rules(); foreach (DiagnosticAnalyzer analyzer in analyzers) { Rules analyzerRules = GetAnalyzerRules(analyzer); foreach (Rule analyzerRule in analyzerRules) { if (rules.Any(r => String.Equals(r.Key, analyzerRule.Key, Rule.RuleKeyComparer))) { logger.LogWarning(UIResources.RuleGen_DuplicateKey, analyzerRule.Key); continue; } rules.Add(analyzerRule); } } return rules; }
public static void SetDefaultSettings() { startState = new GameState(); boardType = BoardType.square; skillEnabled.SetAll(true); rules = Rules.INVISIBLE_TOWERS; }
public DnsAgent(Options options, Rules rules, string listenOn, DnsMessageCache cache) { Options = options ?? new Options(); Rules = rules ?? new Rules(); _listenOn = listenOn; Cache = cache ?? new DnsMessageCache(); }
public void Initialize() { var puzzle = new Puzzle(6, 5, new List<byte> {0, 1, 3}, new List<byte> {1, 2}, new List<byte> {3, 4}, false); var rules = new Rules { ProhibitedFields = {{0, 2}, {0, 4}, {5, 2}, {5, 4}} }; }
public void setRules(Rules[] nrule, int size) { int[] rule = new int[size]; for (int i = 0; i < size; i++) { rule [i] = (int)nrule [i]; } jo.Call ("setRules", rule); }
public void TestFindRuleByNameWithoutRuleSuffix() { var rules = new Rules(typeof(IRule).Assembly); var soughtRule = rules.RuleByName("LimitAssertsPerTestCase"); Assert.IsNotNull(soughtRule); }
public static void SetDefaultSettings() { fieldSize = 9; startState = new GameState(); startState.SetDefault(); skillEnabled.SetAll(true); rules = Rules.INVISIBLE_TOWERS; }
//private TransactionMngr TranMngr { get; set; } public ErpDataMngr() { //Factory = new DaoFactory(); WType = new WmsTypes(Factory); DocMngr = new DocumentMngr(); //TranMngr = new TransactionMngr(); Rules = new Rules(Factory); }
public void Execute(Rules.ExecutionStatus executionStatus, YellowstonePathology.Business.Test.AccessionOrder accessionOrder, YellowstonePathology.Business.Test.PanelSetOrder panelSetOrder) { this.m_AccessionOrder = accessionOrder; this.m_PanelSetOrder = panelSetOrder; this.m_ExecutionStatus = executionStatus; this.m_Rule.Execute(executionStatus); }
public void MyOwnScoreShouldBe0() { var assemblyFile = new Uri(GetType().Assembly.CodeBase).LocalPath; var repo = TestCases.LoadFromFile(assemblyFile); var rules = new Rules(typeof(IRule).Assembly); var results = AnalysisResults.Create(repo, rules, new ViolationScorer()); var score = results.Applications.Sum(a => a.Score); PrintViolationsToConsole(results); Assert.AreEqual(0m, score); }
//Constructor public TransactionMngr() { Factory = new DaoFactory(); WType = new WmsTypes(Factory); LblMngr = new LabelMngr(); DocMngr = new DocumentMngr(); ErpMngr = new ErpDataMngr(); Rules = new Rules(Factory); }
public void TestFindRulesInSuppliedAssembly() { var rules = new Rules(typeof(IRule).Assembly); var foundRules = rules; //.AllRules; // Rules are not singleton, so find by type... var soughtRule = foundRules.Where(r => r.GetType() == typeof(LimitAssertsPerTestCaseRule)); Assert.IsNotNull(soughtRule.FirstOrDefault()); }
/// <summary>Assigns all needed attributes to the tag</summary> /// <returns>This instance downcasted to base class</returns> public virtual IndexedTag attr( string summary = null, Length width = null, int? border = null, Frame? frame = null, Rules? rules = null, Length cellspacing = null, Length cellpadding = null, string id = null, string @class = null, string style = null, string title = null, LangCode lang = null, string xmllang = null, Dir? dir = null, string onclick = null, string ondblclick = null, string onmousedown = null, string onmouseup = null, string onmouseover = null, string onmousemove = null, string onmouseout = null, string onkeypress = null, string onkeydown = null, string onkeyup = null ) { Summary = summary; Width = width; Border = border; Frame = frame; Rules = rules; CellSpacing = cellspacing; CellPadding = cellpadding; Id = id; Class = @class; Style = style; Title = title; Lang = lang; XmlLang = xmllang; Dir = dir; OnClick = onclick; OnDblClick = ondblclick; OnMouseDown = onmousedown; OnMouseUp = onmouseup; OnMouseOver = onmouseover; OnMouseMove = onmousemove; OnMouseOut = onmouseout; OnKeyPress = onkeypress; OnKeyDown = onkeydown; OnKeyUp = onkeyup; return this; }
public LevelGrammar generateNew(Rules[] pRules) { ruleset = pRules; roomList = new List<Room> (); roomList.Add (specialRoomList [0]); nph = 4; return null; }
private string GetRuleName(Rules rule) { switch (rule) { case Rules.ShortAboutGame: return "ShortAboutGame"; case Rules.HowToPlay: return "HowToPlay"; case Rules.Bear: return "AndSuddenly"; default: throw new NotImplementedException(); } }
private string GetRuleIdentifier(Rules rule) { switch (rule) { case Rules.ShortAboutGame: return "one"; case Rules.HowToPlay: return "two"; case Rules.Bear: return "three"; default: throw new NotImplementedException(); } }
public void tryMoveTestEmptyPit() { Rules daRules = new Rules(1); Assert.IsFalse(daRules.gamestate.isOver()); Assert.IsFalse(daRules.tryMove(-1)); Assert.IsFalse(daRules.tryMove(6)); //move player 1 location 0 daRules.tryMove(0); if (daRules.gamestate.currentPlayer != 2) { Assert.Fail("should be player twos turn"); } Assert.IsFalse(daRules.tryMove(-1)); Assert.IsFalse(daRules.tryMove(6)); //move player 2 location 0 daRules.tryMove(0); if (daRules.gamestate.currentPlayer != 1) { Assert.Fail("should be player one's turn"); } //try to move player 1 location 0 again, this should return false(can't move an empty space) if (daRules.tryMove(0) == true) { Assert.Fail("was allowed to move when not allowed"); } if (daRules.gamestate.currentPlayer != 1) { Assert.Fail("should stay player one's turn"); } daRules.tryMove(2); daRules.tryMove(5); daRules.tryMove(0); //try to move player 2 location 5 again, this should return false(can't move an empty space) if (daRules.tryMove(5) == true) { Assert.Fail("was allowed to move when not allowed"); } if (daRules.gamestate.currentPlayer != 2) { Assert.Fail("should stay player one's turn"); } }
public static bool ReadNetworkPackage(string s) { string[] split = s.Split('.'); if(split.Length == 2){ int rulesReceived = System.Convert.ToInt32(split[0]); Debug.Log("String: "+s+". Rules found: "+rulesReceived+"."); rules = (Rules)rulesReceived; return skillEnabled.ReadFromString(split[1]); } Debug.Log("string: "+s+". discarded."); return false; }
/// <summary> /// Parse warrior files in project parameter considering parser options and rules /// </summary> /// <param name="aProject">files, rules, options</param> /// <param name="aConsole">output console, could be null</param> /// <returns>list of errors</returns> public override ParseResult Parse(IProject aProject, ISimpleOutput aConsole) { //cache and ceck rules if (cachedRules==null) { cachedRules = aProject.Rules; } else if (!cachedRules.Equals(aProject.Rules)) { throw new ParserException("Caching parser can cache only warriors compiled under same rules"); } return base.Parse(aProject, aConsole); }
/// <summary> /// Initializes a new instance. /// </summary> internal CustomRule( Rules rule, string code, string settingName, string description, Image exampleImage) { Rule = rule; Code = code; SettingName = settingName; Description = description; ExampleImage = exampleImage; }
private void ReloadMagnets() { // only one item at a time. ListMagnets.MultiSelect = false; // remove everything ListMagnets.Items.Clear(); // the current list of magnets. var magnets = _engine.GetMagnets(); // the rules. var rules = new Rules(); // get the categories. ListMagnets.BeginUpdate(); foreach (var magnet in magnets ) { // look for the category var category =_categories.FindCategoryById(magnet.Category); // look for the rule. var rule = rules.Find(magnet.Rule); var item = new ListViewItem() { Text = magnet.Name, ToolTipText = magnet.Name, Tag = magnet, SubItems = { rule, (category == null ? "n/a" : category.Name) } }; ListMagnets.Items.Add(item); } ListMagnets.EndUpdate(); // do we have anything at all? if (0 == magnets.Count) { DisableButtons(); } else { // just select the first item in the list. ListMagnets.Items[0].Selected = true; ListMagnets.Select(); // enable the buttons. EnableButtons(); } }
private Rules GetAnalyzerRules(DiagnosticAnalyzer analyzer) { // For info on SonarQube rules see http://docs.sonarqube.org/display/SONAR/Rules Rules rules = new Rules(); foreach (DiagnosticDescriptor diagnostic in analyzer.SupportedDiagnostics) { if (String.IsNullOrWhiteSpace(diagnostic.Id)) { logger.LogWarning(UIResources.RuleGen_EmptyKey, analyzer.ToString()); continue; } Rule newRule = new Rule(); newRule.Key = diagnostic.Id; newRule.InternalKey = diagnostic.Id; newRule.Description = GetDescriptionAsRawHtml(diagnostic); newRule.Name = diagnostic.Title.ToString(CultureInfo.InvariantCulture); newRule.Severity = GetSonarQubeSeverity(diagnostic.DefaultSeverity); // Rule XML properties that don't have an obvious Diagnostic equivalent: newRule.Cardinality = Cardinality; newRule.Status = Status; // Diagnostic properties that don't have an obvious Rule xml equivalent: // diagnostic.Category // diagnostic.IsEnabledByDefault // diagnostic.MessageFormat /* Remark: Custom tags are used so that Visual Studio handles diagnostics and are not equivalent to SonarQube's tags * * http://stackoverflow.com/questions/24257222/relevance-of-new-parameters-for-diagnosticdescriptor-constructor * customTags is a general way to mark that a diagnostic should be treated or displayed somewhat * different than normal diagnostics. The "unnecessary" tag means that in the IDE we fade out the span * that the diagnostic applies to: this is how we fade out unnecessary usings or casts or such in the IDE. * In some fancy scenarios you might want to define your own, but for the most part you'll either leave that empty * or pass Unnecessary if you want the different UI handling. * The EditAndContinue tag is for errors that are created if an edit-and-continue edit can't be applied * (which are also displayed somewhat differently)...that's just for us (n.b. Roslyn) to use. */ rules.Add(newRule); } return rules; }
/// <summary> /// Applies the configuration to the rules found in the given repository. /// </summary> /// <param name="rules">A repository of rules.</param> /// <exception cref="NoSuchRuleException">Thrown if a rule in the configuration cannot be found. /// </exception> /// <exception cref="MalformedRuleConfiguration">Thrown if a public, writeable setting cannot be /// found on a rule, or if the value of the setting has the wrong type.</exception> public void ApplyConfiguration(Rules rules) { foreach (var entry in _rulesSettings) { var rule = rules.RuleByName(entry.Key); foreach (var setting in entry.Value) { var prop = FindProperty(rule, setting.Name); if (prop == null) throw new MalformedRuleConfiguration("Missing or non-writeable setting: " + setting.Name); try { var typedValue = Convert.ChangeType(setting.Value, prop.PropertyType); prop.SetValue(rule, typedValue, BindingFlags.Default, null, null, null); } catch (FormatException) { throw new MalformedRuleConfiguration(string.Format("Value for setting {0} does not match the setting type: {1}", setting.Name, setting.Value)); } } } }
public static List<ExportItem> ToItems(this List<Character.Item> import, Rules d20Rules) { List<ExportItem> output = new List<ExportItem>(); foreach (var item in import) { Rule baseRule = CompleteRule(item.Rules[0], d20Rules); Rule magicRule = item.Rules.Count > 1 ? CompleteRule(item.Rules[1], d20Rules) : null; var export = new ExportItem() { Name = item.Name, Count = item.Count, EquippedCount = item.EquippedCount, ArmorCategory = baseRule.Specifics.SafeGetValue("Armor Category"), ArmorType = baseRule.Specifics.SafeGetValue("Armor Type"), Category = baseRule.Specifics.SafeGetValue("Category"), Flavor = baseRule.Flavor.FixWhitespace(), ItemSlot = baseRule.Specifics.SafeGetValue("Item Slot"), Text = baseRule.Text.FixWhitespace(), Type = baseRule.Type, Weight = baseRule.Specifics.SafeGetValue("Weight"), }; output.Add(export); } return output; }
public Game(IPlayer creator, Rules rules, TradeRules tradeRules, Action<Game> endCallback) { GameId = IdGenerator.GenerateId(); InProgress = true; CurrentPlayer = FirstPlayer = creator; Rules = rules; TradeRule = tradeRules; GameEnded = endCallback; ReconnectTimer = new Timer(); ReconnectTimer.Enabled = false; ReconnectTimer.Elapsed += (s, ea) => { if (FirstPlayer == null) { SecondPlayerScore = 0; Winner = SecondPlayer; } else if (SecondPlayer == null) { FirstPlayerScore = 0; Winner = FirstPlayer; } InProgress = false; GameEnded(this); }; Season = DbRepository.Current.Single<DbSeason>(s => true); if (Season == null) { DbRepository.Current.Add(new DbSeason() { Name = "Season 1", CreatedBy = "SYSTEM", ModifiedBy = "SYSTEM" }); Season = DbRepository.Current.Single<DbSeason>(s => true); } }
public static ExportCharacter ToCharacter(this ImportCharacter import, Rules d20Rules) { Rules rules = d20Rules ?? import.Sheet.Rules; var export = new ExportCharacter(); export.AbilityScores = import.AbilityScores.ToDictionary(); export.ActionPoints = import.Sheet.Stats["_BaseActionPoints"]; export.Alignment = import.SafeGetRuleNameByType("Alignment").ToAlignment(); export.Class = import.SafeGetRuleNameByType("Class"); export.ClassFeatures = import.Sheet.Rules.ByType()["Class Feature"].ToFeats(rules); export.Defenses = import.Defenses.ToDictionary(); export.Experience = import.Sheet.Details.Experience.SafeToInt(); export.Feats = import.Sheet.Rules.ByType()["Feat"].ToFeats(rules); export.Gender = import.SafeGetRuleNameByType("Gender"); export.Handle = import.ToHandle(); export.HealingSurges = import.HealingSurges; export.HitPoints = import.HitPoints; export.Initiative = import.Initiative; export.Items = import.Items.ToItems(rules); export.Languages = import.ToRuleNamesList("Language"); export.Level = import.Level; export.Name = import.Name; export.PassiveInsight = import.PassiveInsight; export.PassivePerception = import.PassivePerception; export.Powers = import.Powers.ToPowers(import.Sheet.Rules, rules); export.PowerSource = import.SafeGetRuleNameByType("Power Source"); export.Race = import.SafeGetRuleNameByType("Race"); export.RacialTraits = import.Sheet.Rules.ByType()["Racial Trait"].ToFeats(rules); export.Role = import.SafeGetRuleNameByType("Role"); export.Skills = import.ToSkills(); export.Size = import.SafeGetRuleNameByType("Size"); export.Speed = import.Sheet.Stats["Speed"].Value; export.Vision = import.SafeGetRuleNameByType("Vision"); return export; }
public Derivated1(Rules rules) { }
public override void LoadFromRules() { base.LoadFromArtEssential(); if (IsVoxel) { var vxl = new VoxelDrawable(Rules, Art); vxl.OwnerCollection = OwnerCollection; vxl.Props = Props; vxl.LoadFromRules(); vxl.Vxl = VFS.Open <VxlFile>(vxl.Image + ".vxl"); vxl.Hva = VFS.Open <HvaFile>(vxl.Image + ".hva"); SubDrawables.Add(vxl); } else { var shp = new ShpDrawable(Rules, Art); shp.Props = Props; shp.OwnerCollection = OwnerCollection; shp.LoadFromRules(); shp.Shp = VFS.Open <ShpFile>(shp.GetFilename()); shp.Props.FrameDecider = FrameDeciders.SHPVehicleFrameDecider(shp.StartStandFrame, shp.StandingFrames, shp.Facings); SubDrawables.Add(shp); } if (Rules.ReadBool("Turret") && IsVoxel) { var turretVxl = VFS.Open <VxlFile>(Image + "TUR.vxl"); var turretHva = VFS.Open <HvaFile>(Image + "TUR.hva"); var turret = new VoxelDrawable(turretVxl, turretHva); turret.Props.Offset = Props.Offset; turret.Props.Offset += new Size(Rules.ReadInt("TurretAnimX"), Rules.ReadInt("TurretAnimY")); turret.Props.TurretVoxelOffset = Art.ReadFloat("TurretOffset"); SubDrawables.Add(turret); var barrelVxl = VFS.Open <VxlFile>(Image + "BARL.vxl"); var barrelHva = VFS.Open <HvaFile>(Image + "BARL.hva"); if (barrelVxl != null && barrelHva != null) { var barrel = new VoxelDrawable(barrelVxl, barrelHva); barrel.Props = turret.Props; SubDrawables.Add(barrel); } } }
/// <summary> /// Evaluate the rule sets to see which ones match the from connection and send on to the toConnections. /// </summary> /// <param name="Item"></param> /// <param name="routedItem"></param> /// <returns></returns> public List <ConnectionSet> Eval(Rules Item, RoutedItem routedItem) { Throw.IfNull(Item); var taskInfo = $"task: {routedItem.TaskID} id: {routedItem.id}"; var connList = new List <ConnectionSet>(); if (routedItem.toConnections.Count > 0) { //we've already been told where to send the request, just return it _logger.Log(LogLevel.Debug, $"{taskInfo} toConnections already populated, skipping eval."); return(routedItem.toConnections); } else { foreach (var destRule in Item.destRules.FindAll(e => e.fromConnectionName == routedItem.fromConnection && e.enabled == true)) { //2018-08-07 shb BOUR-630 check the destination connections to see if they are enabled. If there is no enabled destination then don't add the connection set int enabledDest = 0; foreach (var dest in destRule.toConnections) { enabledDest += _profileStorage.Current.connections.FindAll(e => e.name == dest.connectionName && e.enabled == true).Count; } if (enabledDest > 0) { if (_doesRuleMatchService.DoesRuleMatch(routedItem, destRule)) { _logger.Log(LogLevel.Debug, $"{taskInfo} evaluates to {destRule.toConnections.Count} connections."); connList.AddRange(destRule.toConnections); if (destRule.Type == DestRule.RuleType.AddressableRoute) { foreach (var con in connList) { //amend the connlist sharing destintations with matches foreach (var match in destRule.matches) { ShareDestinations sd = new ShareDestinations { boxUuid = match.ToString() }; con.shareDestinations.Add(sd); } } } } } } if (connList.Count == 0) { _logger.Log(LogLevel.Warning, $"{taskInfo} There are no routes for {routedItem.fromConnection}."); } } //do we need to flatten in case of duplicates? // foreach (var conn in profile.connections.FindAll(e => e.enabled == true)) // { // if (conn.enabled == true) // { // foreach (var connectionSet in connListNames) // { // if (conn.name.Equals(connectionSet.connectionName)) // { // if(Logger.logger.FileTraceLevel == "Verbose") _logger.Log(LogLevel.Debug, $"conn {conn.name} succeeds because == {connectionSet.connectionName}"); // connList.Add(connectionSet); // } // else // { // if(Logger.logger.FileTraceLevel == "Verbose") _logger.Log(LogLevel.Debug, $"conn {conn.name} fails because != {connectionSet.connectionName}"); // } // } // } // } //for request/response mechanism route to connections that can provide this functionality //trim the connList to only those connections that support request/response if (routedItem.type == RoutedItem.Type.RPC) { foreach (var conn in connList.ToArray()) { if (_profileStorage.Current.connections.FindAll(e => e.name == conn.connectionName && e.enabled && e.requestResponseEnabled).Count == 0) { _logger.Log(LogLevel.Debug, $"{conn.connectionName} is being removed from destinations because requestResponseEnabled: false"); connList.Remove(conn); } } } return(connList); }
private void TextBoxPreviewTextInput(object sender, TextCompositionEventArgs e) { e.Handled = !Rules.IsTextAllowed(e.Text); }
public void On(RuleDeleted @event, EnvelopeHeaders headers) { Rules.Remove(@event.RuleId); }
private void UpdateRule(RuleEvent @event, EnvelopeHeaders headers, Action <JsonRuleEntity> updater = null) { var id = @event.RuleId; Rules = Rules.SetItem(id, x => x.Clone().Update(@event, headers, updater)); }
private void InitializeValidation( ) { Rules.Add(new ValidationRule(nameof(OutputFolder), "Output Folder can not be empty!", () => string.IsNullOrEmpty(OutputFolder))); Rules.Add(new ValidationRule(nameof(OutputFolder), "Output Folder is not a valid Folder!", () => !Directory.Exists(OutputFolder))); Rules.Add(new ValidationRule(nameof(SelectedMmDeviceId), "Recording Device must be selected!", () => string.IsNullOrEmpty(SelectedMmDeviceId))); }
/// <summary> /// Initializes a new instance of the <see cref="RuleSet" /> class. /// </summary> /// Element created at 07/11/2014,6:13 AM by Charles public RuleSet() { Actions = new Actions(); Rules = new Rules(); Rules.CollectionChanged += RulesCollectionChanged; }