public override void Import(Lookup settings) { Dictionary<string, OptionItem> optionLookup = new Dictionary<string, OptionItem>(); StoryProgression.Main.GetOptionLookup(optionLookup); foreach(KeyValuePair<string,OptionItem> option in optionLookup) { string value = settings.GetString(option.Key); if (value == null) continue; try { option.Value.PersistValue = value; } catch (Exception e) { Common.Exception(option.Key, e); } } StoryProgression.Main.Options.ImportCastes(settings); foreach (OptionItem option in optionLookup.Values) { IAfterImportOptionItem afterOption = option as IAfterImportOptionItem; if (afterOption == null) continue; afterOption.PerformAfterImport(); } }
/// <summary> /// Creates an instance of this class using the given bucket data. /// </summary> /// <param name="itemNames">Item types being batched on: null indicates no batching is occurring</param> /// <param name="itemMetadata">Hashtable of item metadata values: null indicates no batching is occurring</param> internal ItemBucket ( ICollection<string> itemNames, Dictionary<string, string> metadata, Lookup lookup, int bucketSequenceNumber ) { ErrorUtilities.VerifyThrow(lookup != null, "Need lookup."); // Create our own lookup just for this bucket _lookup = lookup.Clone(); // Push down the items, so that item changes in this batch are not visible to parallel batches _lookupEntry = _lookup.EnterScope("ItemBucket()"); // Add empty item groups for each of the item names, so that (unless items are added to this bucket) there are // no item types visible in this bucket among the item types being batched on if (itemNames != null) { foreach (string name in itemNames) { _lookup.PopulateWithItems(name, new List<ProjectItemInstance>()); } } _metadata = metadata; _expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(_lookup.ReadOnlyLookup, _lookup.ReadOnlyLookup, new StringMetadataTable(metadata)); _bucketSequenceNumber = bucketSequenceNumber; }
public override void Export(Lookup settings) { List<OptionItem> allOptions = new List<OptionItem>(); StoryProgression.Main.GetOptions(allOptions, false, IsExportable); StoryProgression.Main.Options.ExportCastes(settings); foreach (OptionItem option in StoryProgression.Main.Options.GetOptions(StoryProgression.Main, "Town", false)) { allOptions.Add(option); } foreach (OptionItem option in StoryProgression.Main.Options.GetImmigrantOptions(StoryProgression.Main)) { allOptions.Add(option); } foreach (OptionItem option in allOptions) { try { List<string> names = GetExportKey(option); if ((names == null) || (names.Count == 0)) continue; settings.Add(names[0], option.GetExportValue()); } catch (Exception e) { Common.Exception(option.Name, e); } } }
public void AddShouldThrowIfKeyIsNullOrWhiteSpace() { var lookup = new Lookup<object>(); Should.Throw<ArgumentException>(() => lookup.Add(null, new object())); Should.Throw<ArgumentException>(() => lookup.Add(string.Empty, new object())); Should.Throw<ArgumentException>(() => lookup.Add(" ", new object())); }
public void TestConstructorNullTarget() { ProjectInstance project = CreateTestProject(true /* Returns enabled */); BuildRequestConfiguration config = new BuildRequestConfiguration(1, new BuildRequestData("foo", new Dictionary<string, string>(), "foo", new string[0], null), "2.0"); BuildRequestEntry requestEntry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "foo" }), config); Lookup lookup = new Lookup(new ItemDictionary<ProjectItemInstance>(project.Items), new PropertyDictionary<ProjectPropertyInstance>(project.Properties), null); TargetEntry entry = new TargetEntry(requestEntry, this, null, lookup, null, _host, false); }
private void HandleFrameResult(object result) { if (result is Frame) { var lookup = new Lookup(task_master, null, new[] {"value"}, ((Frame) result).Context); lookup.Notify(HandleFinalResult); } }
/// <summary> /// Determines how many times the batchable object needs to be executed (each execution is termed a "batch"), and prepares /// buckets of items to pass to the object in each batch. /// </summary> /// <returns>ArrayList containing ItemBucket objects, each one representing an execution batch.</returns> internal static List<ItemBucket> PrepareBatchingBuckets ( List<string> batchableObjectParameters, Lookup lookup, ElementLocation elementLocation ) { return PrepareBatchingBuckets(batchableObjectParameters, lookup, null, elementLocation); }
public void TestGenericGetEnumerator() { IEnumerable<IGrouping<string, int>> lookup = new Lookup<string, int> { {"one", 1}, {"two", 2}, {"one", -1} }; AssertContents(lookup.GetEnumerator()); }
protected override void RecieveItemInteraction(Entity actor, Entity item, Lookup<ItemCapabilityType, ItemCapabilityVerb> verbs) { base.RecieveItemInteraction(actor, item, verbs); if (verbs[ItemCapabilityType.Tool].Contains(ItemCapabilityVerb.Wrench)) { } else PlaceItem(actor, item); }
/// <summary> /// Builds the specified targets of an entry. The cancel event should only be set to true if we are planning /// on simulating execution time when a target is built /// </summary> public Task<BuildResult> BuildTargets(ProjectLoggingContext loggingContext, BuildRequestEntry entry, IRequestBuilderCallback callback, string[] targetNames, Lookup baseLookup, CancellationToken cancellationToken) { _requestEntry = entry; _projectLoggingContext = loggingContext; _requestCallBack = callback; _testDefinition = _testDataProvider[entry.Request.ConfigurationId]; _cancellationToken = cancellationToken; BuildResult result = GenerateResults(targetNames); return Task<BuildResult>.FromResult(result); }
public void TestContains() { Lookup<string, int> lookup = new Lookup<string, int> { {"one", 1}, {"two", 2}, {"one", -1} }; Assert.IsTrue(lookup.Contains("one")); Assert.IsTrue(lookup.Contains("two")); Assert.IsFalse(lookup.Contains("three")); }
/// <summary> /// This is the Evaluate Method /// </summary> /// <param name="s"></param> /// <param name="varEvaluator"></param> /// <returns></returns> public static int Evaluate(String s, Lookup varEvaluator) { Stack<string> operatorStack = new Stack<string>(); Stack<double> numberStack = new Stack<double>(); try{ //This helps to split strings to the proper operator. string[] substrings = Regex.Split(s, "(\\()|(\\))|(-)|(\\+)|(\\*)|(/)", RegexOptions.IgnorePatternWhitespace); //run through each string and do things to it. //Lets populate the stacks here. foreach(String t in substrings) { if (isNum(t)) { double newNum = Double.Parse(t); string newOp = operatorStack.Peek(); if (newOp.Equals("*") || newOp.Equals("/")) { numberStack.Pop(); operatorStack.Pop(); } } else if (isVar(t)) { varEvaluator(t); } else if (isOp(t)) { if (operatorStack.Peek().Equals("+") || operatorStack.Peek().Equals("-")) { double x = numberStack.Pop(); double y = numberStack.Pop(); string poppedOp = operatorStack.Pop(); if(poppedOp.Equals("+")) { x = x + y; } else { x = x - y; } } } } }catch(ArgumentException){ } return 0; }
public override void Export(Lookup settings) { settings.Add("Enabled", DebugEnabler.Settings.mEnabled); settings.Add("HotKeyCount", DebugEnabler.Settings.mInteractions.Count); int i = 0; foreach (Type type in DebugEnabler.Settings.mInteractions.Keys) { settings.Add("HotKey" + i, type); i++; } }
public override void ReportLookupError(Lookup lookup, Type fail_type) { Dirty = true; if (fail_type == null) { Console.Error.WriteLine("Undefined name “{0}”. Lookup was as follows:", lookup.Name); } else { Console.Error.WriteLine("Non-frame type {1} while resolving name “{0}”. Lookup was as follows:", lookup.Name, fail_type); } var col_width = Math.Max((int) Math.Log(lookup.FrameCount, 10) + 1, 3); for (var name_it = 0; name_it < lookup.NameCount; name_it++) { col_width = Math.Max(col_width, lookup.GetName(name_it).Length); } for (var name_it = 0; name_it < lookup.NameCount; name_it++) { Console.Error.Write("│ {0}", lookup.GetName(name_it).PadRight(col_width, ' ')); } Console.Error.WriteLine("│"); for (var name_it = 0; name_it < lookup.NameCount; name_it++) { Console.Error.Write(name_it == 0 ? "├" : "┼"); for (var s = 0; s <= col_width; s++) { Console.Error.Write("─"); } } Console.Error.WriteLine("┤"); var seen = new Dictionary<SourceReference, bool>(); var known_frames = new Dictionary<Frame, string>(); var frame_list = new List<Frame>(); var null_text = "│ ".PadRight(col_width + 2, ' '); for (var frame_it = 0; frame_it < lookup.FrameCount; frame_it++) { for (var name_it = 0; name_it < lookup.NameCount; name_it++) { var frame = lookup[name_it, frame_it]; if (frame == null) { Console.Error.Write(null_text); continue; } if (!known_frames.ContainsKey(frame)) { frame_list.Add(frame); known_frames[frame] = frame_list.Count.ToString().PadRight(col_width, ' '); } Console.Error.Write("│ {0}", known_frames[frame]); } Console.Error.WriteLine("│"); } for (var it = 0; it < frame_list.Count; it++) { Console.Error.WriteLine("Frame {0} defined:", it + 1); frame_list[it].SourceReference.Write(Console.Error, " ", seen); } Console.Error.WriteLine("Lookup happened here:"); lookup.SourceReference.Write(Console.Error, " ", seen); }
public BaseViewModel() { List<KeyValuePair<string, string>> _properties = new List<KeyValuePair<string, string>>(); foreach (var property in GetType().GetProperties()) { foreach (var d in (DependsUponAttribute[])property.GetCustomAttributes(typeof(DependsUponAttribute), true)) { _properties.Add(new KeyValuePair<string, string>(d.DependancyName, property.Name)); } } DependentProperties = (Lookup<string, string>)_properties.ToLookup(p => p.Key, p => p.Value); }
public void TestGetByIndex() { Lookup<string, int> lookup = new Lookup<string, int> { {"one", 1}, {"two", 2}, {"one", -1} }; Assert.AreEqual(2, lookup.Count); int[] one = lookup["one"].ToArray(); Assert.IsTrue(one.Contains(1)); Assert.IsTrue(one.Contains(-1)); Assert.AreEqual(2, one.Length); }
public override void Import(Lookup settings) { DebugEnabler.Settings.mEnabled = settings.GetBool("Enabled", true); DebugEnabler.Settings.mInteractions.Clear(); int count = settings.GetInt("HotKeyCount", 0); for (int i = 0; i < count; i++) { Type type = settings.GetType("HotKey" + i); if (type == null) continue; DebugEnabler.Settings.mInteractions[type] = true; } }
protected override void RecieveItemInteraction(Entity actor, Entity item, Lookup<ItemCapabilityType, ItemCapabilityVerb> verbs) { base.RecieveItemInteraction(actor, item, verbs); if (verbs[ItemCapabilityType.Tool].Contains(ItemCapabilityVerb.Pry)) { ToggleDoor(true); } else if (verbs[ItemCapabilityType.Tool].Contains(ItemCapabilityVerb.Hit)) { var cm = IoCManager.Resolve<IChatManager>(); cm.SendChatMessage(ChatChannel.Default, actor.Name + " hit the " + Owner.Name + " with a " + item.Name + ".", null, item.Uid); } else if (verbs[ItemCapabilityType.Tool].Contains(ItemCapabilityVerb.Emag)) { OpenDoor(); disabled = true; } }
protected void Page_Load(object sender, EventArgs e) { LookupCollection validNumbers = new LookupCollection(new Guid("11B4ADEC-CB8C-4D01-B99E-7A0FFE2007B5")); StringBuilder sb = new StringBuilder(); foreach (String s in AllowedPhoneNumbersSetting.Split(',')) { Lookup lk = new Lookup(Convert.ToInt32(s)); sb.AppendLine(String.Format("ddl.append('<option value=\"{0}\">{1}</option>');", Arena.Custom.HDC.Twilio.TwilioSMS.CleanPhone(lk.Qualifier), Server.HtmlEncode(lk.Value))); } ltSelect.Text = sb.ToString(); if (!String.IsNullOrEmpty(Request.Params["MEDIUM"]) && Request.Params["MEDIUM"] == "email") { IsMediumEmail = 1; FromEmail = CurrentPerson.Emails.FirstActive; ReplyToEmail = CurrentPerson.Emails.FirstActive; } }
public static Dictionary<ulong,Lookup> ReadBinaryFile(string filename) { Dictionary<ulong, Lookup> lookup = new Dictionary<ulong, Lookup>(); if (File.Exists(filename)) { FileStream inFile = new FileStream(filename, FileMode.Open, FileAccess.Read); using (BinaryReader file = new BinaryReader(inFile, Encoding.Unicode)) { byte[] buffer = new byte[7]; file.Read(buffer, 0, 7); uint count = file.ReadUInt32(); file.Read(buffer, 0, 6); for (uint i = 0; i < count; i++) { ulong id = file.ReadUInt64(); uint len = file.ReadUInt32(); char[] text = file.ReadChars((int)len); Lookup value; if (!lookup.TryGetValue(id, out value)) { value = new Lookup("0x" + id.ToString("X16"), new string(text), false); lookup.Add(id, value); } else { value.mText = new string (text); } } } } return lookup; }
protected override bool Run() { if (mappings.Count == 0) { interlock = categories.Count + 2; Computation input_lookup = new Lookup(master, source_reference, new []{"arg"}, context); input_lookup.Notify(input_result => { if (input_result is Stringish) { input = input_result.ToString(); if (Interlocked.Decrement(ref interlock) == 0) { master.Slot(this); } } else { master.ReportOtherError(source_reference, "Input argument must be a string."); } }); master.Slot(input_lookup); foreach (var entry in categories) { var lookup = new Lookup(master, source_reference, new []{ entry.Value }, context); lookup.Notify(cat_result => { mappings[entry.Key] = cat_result; if (Interlocked.Decrement(ref interlock) == 0) { master.Slot(this); } }); master.Slot(lookup); } if (Interlocked.Decrement(ref interlock) > 0) { return false; } } var frame = new Frame(master, master.NextId(), source_reference, context, container); for(int it = 0; it < input.Length; it++) { frame[TaskMaster.OrdinalNameStr(it + 1)] = mappings[Char.GetUnicodeCategory(input[it])]; } result = frame; return true; }
/// <summary> /// Seed the Category Lookup for Assets /// </summary> public void SeedCategoryLookup() { LookupType categoryType = new LookupType { Description = EnumHelper.LookupTypes.Category.ToString() }; _context.LookupTypes.Add(categoryType); _context.SaveChanges(); string[] categories = { "Desktop", "Notebook", "Server", "Tablet" }; foreach (string category in categories) { Lookup initLookup = new Lookup { Description = category, Type = categoryType }; _context.Lookups.Add(initLookup); } _context.SaveChanges(); }
/// <summary> /// Evaluates an an infix expression. /// </summary> /// <param name="exp"> A string representing the expression to be evaluated. </param> /// <param name="variableEvaluator"> Delegate method which will return the int value of a variable. </param> /// <returns> Returns int value of evaluated expression. </returns> public static int Evaluate(String exp, Lookup variableEvaluator) { Stack<double> nums = new Stack<double>(); Stack<String> operators = new Stack<string>(); exp = Regex.Replace(exp, " ", ""); string[] substrings = Regex.Split(exp, "(\\()|(\\))|(-)|(\\+)|(\\*)|(/)"); for(int i = 0; i < substrings.Length; i++) { Double Result; if (Double.TryParse(substrings[i], out Result)) numInstructions(Result, nums, operators); else if (substrings[i] == "+" || substrings[i] == "-") addsubInstructions(substrings[i], nums, operators); else if (substrings[i] == "*" || substrings[i] == "/" || substrings[i] == "(") multdivInstructions(substrings[i], nums, operators); else if (substrings[i] == ")") closeParenInstruction(nums, operators); else if (substrings[i] != "" && Char.IsLetter(substrings[i][0])) numInstructions(variableEvaluator(substrings[i]), nums, operators); else if(substrings[i] != "") throw new ArgumentException("Invalid Character in Expression"); } while (operators.Count != 0) nums.Push(Operate(nums.Pop(), nums.Pop(), operators.Pop())); return (int) nums.Pop(); }
private void CreateLookupAndEnterScope() { lookupPassedBetweenThreads = LookupHelpers.CreateEmptyLookup(); lookupPassedBetweenThreads.EnterScope(); }
/// <summary> /// Builds the specified targets. /// </summary> /// <param name="loggingContext">The logging context for the project.</param> /// <param name="entry">The BuildRequestEntry for which we are building targets.</param> /// <param name="callback">The callback to be used to handle new project build requests.</param> /// <param name="targetNames">The names of the targets to build.</param> /// <param name="baseLookup">The Lookup containing all current items and properties for this target.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to use when building the targets.</param> /// <returns>The target's outputs and result codes</returns> public async Task <BuildResult> BuildTargets(ProjectLoggingContext loggingContext, BuildRequestEntry entry, IRequestBuilderCallback callback, string[] targetNames, Lookup baseLookup, CancellationToken cancellationToken) { ErrorUtilities.VerifyThrowArgumentNull(loggingContext, "projectLoggingContext"); ErrorUtilities.VerifyThrowArgumentNull(entry, "entry"); ErrorUtilities.VerifyThrowArgumentNull(callback, "requestBuilderCallback"); ErrorUtilities.VerifyThrowArgumentNull(targetNames, "targetNames"); ErrorUtilities.VerifyThrowArgumentNull(baseLookup, "baseLookup"); ErrorUtilities.VerifyThrow(targetNames.Length > 0, "List of targets must be non-empty"); ErrorUtilities.VerifyThrow(_componentHost != null, "InitializeComponent must be called before building targets."); _requestEntry = entry; _requestBuilderCallback = callback; _projectLoggingContext = loggingContext; _cancellationToken = cancellationToken; // Clone the base lookup so that if we are re-entered by another request while this one in blocked, we don't have visibility to // their state, and they have no visibility into ours. _baseLookup = baseLookup.Clone(); _targetsToBuild = new ConcurrentStack <TargetEntry>(); // Get the actual target objects from the names BuildRequestConfiguration configuration = _requestEntry.RequestConfiguration; bool previousCacheableStatus = configuration.IsCacheable; configuration.IsCacheable = false; configuration.RetrieveFromCache(); _projectInstance = configuration.Project; // Now get the current results cache entry. IResultsCache resultsCache = (IResultsCache)_componentHost.GetComponent(BuildComponentType.ResultsCache); BuildResult existingBuildResult = resultsCache.GetResultsForConfiguration(_requestEntry.Request.ConfigurationId); _buildResult = new BuildResult(entry.Request, existingBuildResult, null); if (existingBuildResult == null) { // Add this result so that if our project gets re-entered we won't rebuild any targets we have already built. resultsCache.AddResult(_buildResult); } List <TargetSpecification> targets = new List <TargetSpecification>(targetNames.Length); foreach (string targetName in targetNames) { var targetExists = _projectInstance.Targets.ContainsKey(targetName); if (!targetExists && entry.Request.BuildRequestDataFlags.HasFlag(BuildRequestDataFlags.SkipNonexistentTargets)) { _projectLoggingContext.LogComment(Framework.MessageImportance.Low, "TargetSkippedWhenSkipNonexistentTargets", targetName); continue; } targets.Add(new TargetSpecification(targetName, targetExists ? _projectInstance.Targets[targetName].Location : _projectInstance.ProjectFileLocation)); } // Push targets onto the stack. This method will reverse their push order so that they // get built in the same order specified in the array. await PushTargets(targets, null, baseLookup, false, false, TargetBuiltReason.None); // Now process the targets ITaskBuilder taskBuilder = _componentHost.GetComponent(BuildComponentType.TaskBuilder) as ITaskBuilder; try { await ProcessTargetStack(taskBuilder); } finally { // If there are still targets left on the stack, they need to be removed from the 'active targets' list foreach (TargetEntry target in _targetsToBuild) { configuration.ActivelyBuildingTargets.Remove(target.Name); } ((IBuildComponent)taskBuilder).ShutdownComponent(); } if (_cancellationToken.IsCancellationRequested) { throw new BuildAbortedException(); } // Gather up outputs for the requested targets and return those. All of our information should be in the base lookup now. BuildResult resultsToReport = new BuildResult(_buildResult, targetNames); // Return after-build project state if requested. if (_requestEntry.Request.BuildRequestDataFlags.HasFlag(BuildRequestDataFlags.ProvideProjectStateAfterBuild)) { resultsToReport.ProjectStateAfterBuild = _projectInstance; } if (_requestEntry.Request.RequestedProjectState != null) { resultsToReport.ProjectStateAfterBuild = _projectInstance.FilteredCopy(_requestEntry.Request.RequestedProjectState); } configuration.IsCacheable = previousCacheableStatus; return(resultsToReport); }
private void ExecutedSearchSecurity(object sender, ExecutedRoutedEventArgs e) { Lookup.SafeInvoke(Filter); }
public static void Run() { var authId = Environment.GetEnvironmentVariable("SMARTY_AUTH_ID"); var authToken = Environment.GetEnvironmentVariable("SMARTY_AUTH_TOKEN"); var client = new ClientBuilder(authId, authToken).BuildUsZipCodeApiClient(); var lookup1 = new Lookup { ZipCode = "12345" }; var lookup2 = new Lookup { City = "Phoenix", State = "Arizona" }; var lookup3 = new Lookup("cupertino", "CA", "95014"); // You can also set these with arguments var batch = new Batch(); try { batch.Add(lookup1); batch.Add(lookup2); batch.Add(lookup3); client.Send(batch); } catch (BatchFullException) { Console.WriteLine("Error. The batch is already full."); } catch (SmartyException ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } catch (IOException ex) { Console.WriteLine(ex.StackTrace); } for (var i = 0; i < batch.Count; i++) { var result = batch[i].Result; Console.WriteLine("Lookup " + i + ":\n"); if (result.Status != null) { Console.WriteLine("Status: " + result.Status); Console.WriteLine("Reason: " + result.Reason); continue; } var cityStates = result.CityStates; Console.WriteLine(cityStates.Length + " City and State match" + ((cityStates.Length == 1) ? ":" : "es:")); foreach (var cityState in cityStates) { Console.WriteLine("City: " + cityState.City); Console.WriteLine("State: " + cityState.State); Console.WriteLine("Mailable City: " + cityState.MailableCity); Console.WriteLine(); } var zipCodes = result.ZipCodes; Console.WriteLine(zipCodes.Length + " ZIP Code match" + ((cityStates.Length == 1) ? ":" : "es:")); foreach (var zipCode in zipCodes) { Console.WriteLine("ZIP Code: " + zipCode.ZipCode); Console.WriteLine("County: " + zipCode.CountyName); Console.WriteLine("Latitude: " + zipCode.Latitude); Console.WriteLine("Longitude: " + zipCode.Longitude); Console.WriteLine(); } Console.WriteLine("***********************************"); } }
/// <summary> /// Evaluates this Formula, using the Lookup delegate to determine the values of variables. (The /// delegate takes a variable name as a parameter and returns its value (if it has one) or throws /// an UndefinedVariableException (otherwise). Uses the standard precedence rules when doing the evaluation. /// /// If no undefined variables or divisions by zero are encountered when evaluating /// this Formula, its value is returned. Otherwise, throws a FormulaEvaluationException /// with an explanatory Message. /// </summary> public double Evaluate(Lookup lookup) { Stack <char> operators = new Stack <char>(); Stack <double> value = new Stack <double>(); foreach (var t in normalizedTokens) { // t is a double if (t.type == TokenType.Number) { double number = double.Parse(t.text);; if (operators.Count > 0) { if (operators.Peek() == '*' || operators.Peek() == '/') { double pop = value.Pop(); char oper = operators.Pop(); double ans = 0; if (oper.Equals('*')) { ans = number * pop; value.Push(ans); } else if (oper.Equals('/')) { if (number == 0) { throw new FormulaEvaluationException("Cannot divide by zero"); } ans = pop / number; value.Push(ans); } } else { value.Push(number); } } else { value.Push(number); } } // t is a variable else if (t.type == TokenType.Var) { double lookupVal = 0; try { lookupVal = lookup(t.text); } catch { throw new FormulaEvaluationException("The given string is unmapped to a value"); } if (operators.Count > 0) { if (operators.Peek() == '*' || operators.Peek() == '/') { double pop = value.Pop(); char oper = operators.Pop(); double ans = 0; if (oper.Equals('*')) { ans = lookupVal * pop; value.Push(ans); } else if (oper.Equals('/')) { if (lookupVal == 0) { throw new FormulaEvaluationException("Cannot divide by zero"); } ans = pop / lookupVal; value.Push(ans); } } else { value.Push(lookupVal); } } else { value.Push(lookupVal); } } // t is + or - else if (t.text.Equals("+") || t.text.Equals("-")) { if (operators.Count > 0) { char peekChar = operators.Peek(); double ans; if (peekChar.Equals('+') || peekChar.Equals('-')) { double popped1 = value.Pop(); double popped2 = value.Pop(); double popChar = operators.Pop(); if (popChar.Equals('+')) { ans = popped1 + popped2; value.Push(ans); } else if (popChar.Equals('-')) { ans = popped2 - popped1; value.Push(ans); operators.Push('-'); } } } if (t.text.Equals("+")) { operators.Push('+'); } else if (t.text.Equals("-")) { operators.Push('-'); } } // t is * or / else if (t.text.Equals("*") || t.text.Equals("/")) { if (t.text.Equals("*")) { operators.Push('*'); } else if (t.text.Equals("/")) { operators.Push('/'); } } // t is ( else if (t.type == TokenType.LParen) { operators.Push('('); } // t is ) else if (t.type == TokenType.RParen) { double opPeek = operators.Peek(); if (opPeek.Equals('+') || opPeek.Equals('-')) { double popVal1 = value.Pop(); double popVal2 = value.Pop(); char popOp = operators.Pop(); double ans; if (popOp.Equals('+')) { ans = popVal1 + popVal2; value.Push(ans); } else if (popOp.Equals('-')) { ans = popVal2 - popVal1; value.Push(ans); } } char popLeft = operators.Pop(); if (operators.Count > 0) { opPeek = operators.Peek(); if (opPeek.Equals('*') || opPeek.Equals('/')) { double popVal1 = value.Pop(); double popVal2 = value.Pop(); char popOp = operators.Pop(); double ans; if (popOp.Equals('*')) { ans = popVal1 * popVal2; value.Push(ans); } else if (popOp.Equals('/')) { if (popVal1 == 0) { throw new FormulaEvaluationException("Cannot divide by zero"); } ans = popVal2 / popVal1; value.Push(ans); } } } } } // end of tokens, do last two things if (operators.Count == 0) { double popVal = value.Pop(); return(popVal); } else if (operators.Count != 0) { double popVal1 = value.Pop(); double popVal2 = value.Pop(); char opPop = operators.Pop(); if (opPop.Equals('+')) { return(popVal1 + popVal2); } else if (opPop.Equals('-')) { return(popVal2 - popVal1); } } //Shouldnt ever get here return(0); }
protected override string Token_To_String(EnumType token) { return(Lookup.Keyword(token)); }
public Lookup <int, object> calculate(List <NeuroLay> .Enumerator enumerator, Lookup <int, object> groupings) { var neuronsOutput = from n in neurons select new { id = neurons.IndexOf(n), value = n.get(groupings[neurons.IndexOf(n)].ToList()) }; var returnValues = from s in synapses join c in neuronsOutput on s.fromId equals c.id select new { id = s.toId, value = s.weight != Double.NaN ? (double)c.value * s.weight : c.value }; var lookupList = (Lookup <int, object>)returnValues.ToLookup(p => p.id, p => p.value); if (enumerator.MoveNext()) { return(enumerator.Current.calculate(enumerator, lookupList)); } else { return(lookupList); } }
/// <summary> /// Invokes the specified targets using Dev9 behavior. /// </summary> /// <param name="targets">The targets to build.</param> /// <param name="continueOnError">True to continue building the remaining targets if one fails.</param> /// <param name="taskLocation">The <see cref="ElementLocation"/> of the task.</param> /// <returns>The results for each target.</returns> /// <remarks> /// Dev9 behavior refers to the following: /// 1. The changes made during the calling target up to this point are NOT visible to this target. /// 2. The changes made by this target are NOT visible to the calling target. /// 3. Changes made by the calling target OVERRIDE changes made by this target. /// </remarks> async Task <ITargetResult[]> ITargetBuilderCallback.LegacyCallTarget(string[] targets, bool continueOnError, ElementLocation taskLocation) { List <TargetSpecification> targetToPush = new List <TargetSpecification>(); ITargetResult[] results = new TargetResult[targets.Length]; bool originalLegacyCallTargetContinueOnError = _legacyCallTargetContinueOnError; _legacyCallTargetContinueOnError = _legacyCallTargetContinueOnError || continueOnError; // Our lookup is the one used at the beginning of the calling target. Lookup callTargetLookup = _baseLookup; // We now record this lookup in the calling target's entry so that it may // leave the scope just before it commits its own changes to the base lookup. TargetEntry currentTargetEntry = _targetsToBuild.Peek(); currentTargetEntry.EnterLegacyCallTargetScope(callTargetLookup); ITaskBuilder taskBuilder = _componentHost.GetComponent(BuildComponentType.TaskBuilder) as ITaskBuilder; try { // Flag set to true if one of the targets we call fails. bool errorResult = false; // Now walk through the list of targets, invoking each one. for (int i = 0; i < targets.Length; i++) { if (_cancellationToken.IsCancellationRequested || errorResult) { results[i] = new TargetResult(Array.Empty <TaskItem>(), new WorkUnitResult(WorkUnitResultCode.Skipped, WorkUnitActionCode.Continue, null)); } else { targetToPush.Clear(); targetToPush.Add(new TargetSpecification(targets[i], taskLocation)); // We push the targets one at a time to emulate the original CallTarget behavior. bool pushed = await PushTargets(targetToPush, currentTargetEntry, callTargetLookup, false, true, TargetBuiltReason.None); ErrorUtilities.VerifyThrow(pushed, "Failed to push any targets onto the stack. Target: {0} Current Target: {1}", targets[i], currentTargetEntry.Target.Name); await ProcessTargetStack(taskBuilder); if (!_cancellationToken.IsCancellationRequested) { results[i] = _buildResult[targets[i]]; if (results[i].ResultCode == TargetResultCode.Failure) { errorResult = true; } } else { results[i] = new TargetResult(Array.Empty <TaskItem>(), new WorkUnitResult(WorkUnitResultCode.Skipped, WorkUnitActionCode.Continue, null)); } } } } finally { // Restore the state of the TargetBuilder to that it was prior to the CallTarget call. // Any targets we have pushed on at this point we need to get rid of since we aren't going to process them. // If there were normal task errors, standard error handling semantics would have taken care of them. // If there was an exception, such as a circular dependency error, items may still be on the stack so we must clear them. while (!Object.ReferenceEquals(_targetsToBuild.Peek(), currentTargetEntry)) { _targetsToBuild.Pop(); } _legacyCallTargetContinueOnError = originalLegacyCallTargetContinueOnError; ((IBuildComponent)taskBuilder).ShutdownComponent(); } return(results); }
/// <summary> /// Creates a set of complicated item metadata and properties, and items to exercise /// the Expander class. The data here contains escaped characters, metadata that /// references properties, properties that reference items, and other complex scenarios. /// </summary> /// <param name="pg"></param> /// <param name="primaryItemsByName"></param> /// <param name="secondaryItemsByName"></param> /// <param name="itemMetadata"></param> private void CreateComplexPropertiesItemsMetadata ( out ReadOnlyLookup readOnlyLookup, out StringMetadataTable itemMetadata ) { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); Dictionary<string, string> itemMetadataTable = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); itemMetadataTable["Culture"] = "abc%253bdef;$(Gee_Aych_Ayee)"; itemMetadataTable["Language"] = "english"; itemMetadata = new StringMetadataTable(itemMetadataTable); PropertyDictionary<ProjectPropertyInstance> pg = new PropertyDictionary<ProjectPropertyInstance>(); pg.Set(ProjectPropertyInstance.Create("Gee_Aych_Ayee", "ghi")); pg.Set(ProjectPropertyInstance.Create("OutputPath", @"\jk ; l\mno%253bpqr\stu")); pg.Set(ProjectPropertyInstance.Create("TargetPath", "@(IntermediateAssembly->'%(RelativeDir)')")); List<ProjectItemInstance> intermediateAssemblyItemGroup = new List<ProjectItemInstance>(); ProjectItemInstance i1 = new ProjectItemInstance(project, "IntermediateAssembly", @"subdir1\engine.dll", project.FullPath); intermediateAssemblyItemGroup.Add(i1); i1.SetMetadata("aaa", "111"); ProjectItemInstance i2 = new ProjectItemInstance(project, "IntermediateAssembly", @"subdir2\tasks.dll", project.FullPath); intermediateAssemblyItemGroup.Add(i2); i2.SetMetadata("bbb", "222"); List<ProjectItemInstance> contentItemGroup = new List<ProjectItemInstance>(); ProjectItemInstance i3 = new ProjectItemInstance(project, "Content", "splash.bmp", project.FullPath); contentItemGroup.Add(i3); i3.SetMetadata("ccc", "333"); List<ProjectItemInstance> resourceItemGroup = new List<ProjectItemInstance>(); ProjectItemInstance i4 = new ProjectItemInstance(project, "Resource", "string$(p).resx", project.FullPath); resourceItemGroup.Add(i4); i4.SetMetadata("ddd", "444"); ProjectItemInstance i5 = new ProjectItemInstance(project, "Resource", "dialogs%253b.resx", project.FullPath); resourceItemGroup.Add(i5); i5.SetMetadata("eee", "555"); List<ProjectItemInstance> contentItemGroup2 = new List<ProjectItemInstance>(); ProjectItemInstance i6 = new ProjectItemInstance(project, "Content", "about.bmp", project.FullPath); contentItemGroup2.Add(i6); i6.SetMetadata("fff", "666"); ItemDictionary<ProjectItemInstance> secondaryItemsByName = new ItemDictionary<ProjectItemInstance>(); secondaryItemsByName.ImportItems(resourceItemGroup); secondaryItemsByName.ImportItems(contentItemGroup2); Lookup lookup = new Lookup(secondaryItemsByName, pg, null); // Add primary items lookup.EnterScope("x"); lookup.PopulateWithItems("IntermediateAssembly", intermediateAssemblyItemGroup); lookup.PopulateWithItems("Content", contentItemGroup); readOnlyLookup = new ReadOnlyLookup(lookup); }
/// <summary> /// Called to execute a task within a target. This method instantiates the task, sets its parameters, and executes it. /// </summary> /// <param name="lookup">The lookup used for expansion and to receive created items and properties.</param> internal abstract void ExecuteTask(Lookup lookup);
/// <summary> /// Evaluates this Formula, using the Lookup delegate to determine the values of variables. (The /// delegate takes a variable name as a parameter and returns its value (if it has one) or throws /// an UndefinedVariableException (otherwise). Uses the standard precedence rules when doing the evaluation. /// /// If no undefined variables or divisions by zero are encountered when evaluating /// this Formula, its value is returned. Otherwise, throws a FormulaEvaluationException /// with an explanatory Message. /// </summary> public double Evaluate(Lookup lookup) { return 0; }
// // Called on the Window delete icon clicked // void OnDelete(object sender, DeleteEventArgs a) { LookupBox = null; }
/// <summary> /// This method takes a string math equation and solves it returning the answer. /// The method only evaluates equations with tokens: +,-,*,/,(,), positives integers /// including zero, and variables in the form of a letter or more followed by a /// number or more, should throw an argument exception if invalid argument divition /// by zero, or invalid variable /// </summary> /// <param name="exp">The math equation that will be solved</param> /// <param name="variableEvaluator">a function used to look up a variable /// and return its value</param> /// <returns></returns> public static int Evaluate(String exp, Lookup variableEvaluator) { valuesStack = new Stack <int>(); /// <summary> /// This is a stack used to hold the operator that an equation might have /// </summary> operatorsStack = new Stack <String>(); /// <summary> /// this int keeps track of the number of operators in the operator stack, /// so the user knows not to remove from a stack that is empty /// </summary> operatorsCounter = 0; /// <summary> /// this keeps track of the number of values in the value stack, /// so the user knows not to remove from a stack that is empty /// </summary> valueCounter = 0; /// <summary> /// This is a checker used to make sure we only use a value once /// </summary> MultDivchecker = true; /// <summary> /// this a variable that will return the answer to the math equation /// </summary> result = 0; /// <summary> /// The result is set to zero, this checks that we went through the last steps /// even if we don't find nothing, it makes sure for example if argument "()" /// is past it throughs an exeption insead of zero. /// </summary> checkerResult = false; string[] substrings = Regex.Split(exp, "(\\()|(\\))|(-)|(\\+)|(\\*)|(/)"); try { foreach (String el in substrings) { // If next token is an Integer, blank space, or Variable if (!el.Contains("+") && !el.Contains("-") && !el.Contains("/") && !el.Contains("*") && !el.Contains("(") && !el.Contains(")")) { MultDivchecker = true; String possibleInteger = el.Trim(); // Checks if token was not a blank space if (possibleInteger.Length > 0) { //Checks if the integer or varible have any unique symbols if (Regex.IsMatch(possibleInteger, "[^a-zA-Z0-9]")) { throw new ArgumentException("Your agument does not seem to be valid, " + "invalid variables"); } int numberOfLetters = 0; numberOfLetters = Regex.Matches(possibleInteger, @"[a-zA-Z]").Count; int integerValue; if (numberOfLetters > 0) { if (Regex.IsMatch(possibleInteger, "[0-9]+[a-zA-Z]+") || !Regex.IsMatch(possibleInteger, "[a-zA-Z]+[0-9]+")) { throw new ArgumentException("Your agument does not seem to be valid, " + "invalid variables"); } integerValue = variableEvaluator(possibleInteger); } else { integerValue = int.Parse(possibleInteger); } if (operatorsCounter > 0) { String peek = operatorsStack.Peek(); if (peek.Contains("*") || peek.Contains("/")) { int secondValue = valuesStack.Pop(); valueCounter -= 1; MultDivchecker = false; multAndDiv(integerValue, peek, secondValue); } } if (operatorsCounter > 0) { String peek = operatorsStack.Peek(); if (!peek.Contains("*") || !peek.Contains("/")) { if (MultDivchecker) { valuesStack.Push(integerValue); valueCounter += 1; } } } else { if (MultDivchecker) { valuesStack.Push(integerValue); valueCounter += 1; } } } } // If next token is - or + else if (el.Contains("+") || el.Contains("-")) { if (operatorsCounter > 0) { String peek = operatorsStack.Peek(); addAndSub(peek); } //Adds operator to stack operatorsStack.Push(el); operatorsCounter += 1; } else if (el.Contains("*") || el.Contains("/")) { operatorsCounter += 1; operatorsStack.Push(el); } else if (el.Contains("(")) { operatorsCounter += 1; operatorsStack.Push(el); } else if (el.Contains(")")) { if (operatorsCounter > 0) { String peek = operatorsStack.Peek(); addAndSub(peek); if (operatorsCounter > 0) { peek = operatorsStack.Peek(); if (peek.Contains("(")) { operatorsStack.Pop(); operatorsCounter -= 1; } } if (operatorsCounter > 0) { peek = operatorsStack.Peek(); if (peek.Contains("*") || peek.Contains("/")) { int firstValue = valuesStack.Pop(); int secondValue = valuesStack.Pop(); valueCounter -= 2; multAndDiv(firstValue, peek, secondValue); } } } } } if (valueCounter == 1) { result = valuesStack.Pop(); valueCounter -= 1; checkerResult = true; } if (operatorsCounter == 1) { if (valueCounter == 2) { String peek = operatorsStack.Peek(); int firstValue = valuesStack.Pop(); int secondValue = valuesStack.Pop(); valueCounter -= 2; if (peek.Contains("+")) { int sum = firstValue + secondValue; operatorsStack.Pop(); operatorsCounter -= 1; result = sum; checkerResult = true; } if (peek.Contains("-")) { int difference = secondValue - firstValue; operatorsStack.Pop(); operatorsCounter -= 1; result = difference; checkerResult = true; } } } if (checkerResult == false) { throw new System.ArgumentException("Your argument does seem to be valid"); } if (valueCounter != 0 || operatorsCounter != 0) { throw new System.ArgumentException("Your argument does seem to be valid"); } } catch (DivideByZeroException e) { throw new System.ArgumentException("Divivision by Zero is not allowed"); } catch (InvalidOperationException e) { throw new System.ArgumentException("Your argument does not seem to be valid"); } return(result); }
public static IEnumerable <WorkAssignment> filterOnSkill( viewOptions o, IQueryable <WorkAssignment> q, ILookupRepository l, Worker worker) { // "Machete --A series of good intentions, marinated in panic." // // Kludge panic. horrible flattening job of relational data. // Skills have hierarchy (painter, skilled painter, master painter) // kludge assumes hierarchy tree will never lead to more than 6 skill IDs to // match against. Hacked this late one night. int?skill1 = null; int?skill2 = null; int?skill3 = null; int?skill4 = null; int?skill5 = null; int?skill6 = null; IEnumerable <WorkAssignment> filteredWA = q.AsEnumerable(); Stack <int> primeskills = new Stack <int>(); Stack <int> skills = new Stack <int>(); //Worker worker = wcache.FirstOrDefault(w => w.dwccardnum == o.dwccardnum); if (worker != null) { if (worker.skill1 != null) { primeskills.Push((int)worker.skill1); } if (worker.skill2 != null) { primeskills.Push((int)worker.skill2); } if (worker.skill3 != null) { primeskills.Push((int)worker.skill3); } foreach (var skillid in primeskills) { skills.Push(skillid); Lookup skill = l.GetById(skillid); foreach (var subskill in l.GetManyQ(a => a.category == skill.category && a.subcategory == skill.subcategory && a.level < skill.level)) { skills.Push(subskill.ID); } } if (skills.Count() != 0) { skill1 = skills.Pop(); } if (skills.Count() != 0) { skill2 = skills.Pop(); } if (skills.Count() != 0) { skill3 = skills.Pop(); } if (skills.Count() != 0) { skill4 = skills.Pop(); } if (skills.Count() != 0) { skill5 = skills.Pop(); } if (skills.Count() != 0) { skill6 = skills.Pop(); } filteredWA = filteredWA.Join(l.GetAllQ(), //LINQ wa => wa.skillID, sk => sk.ID, (wa, sk) => new { wa, sk } ) .Where(jj => jj.wa.englishLevelID <= worker.englishlevelID && jj.sk.typeOfWorkID.Equals(worker.typeOfWorkID) && ( jj.wa.skillID.Equals(skill1) || jj.wa.skillID.Equals(skill2) || jj.wa.skillID.Equals(skill3) || jj.wa.skillID.Equals(skill4) || jj.wa.skillID.Equals(skill5) || jj.wa.skillID.Equals(skill6) || jj.sk.speciality == false) ) .Select(jj => jj.wa).AsEnumerable(); } return(filteredWA); }
/// <summary> /// Execute an ItemGroup element, including each child item expression /// </summary> /// <param name="lookup">The lookup used for evaluation and as a destination for these items.</param> internal override void ExecuteTask(Lookup lookup) { foreach (ProjectItemGroupTaskItemInstance child in _taskInstance.Items) { List <ItemBucket> buckets = null; try { List <string> parameterValues = new List <string>(); GetBatchableValuesFromBuildItemGroupChild(parameterValues, child); buckets = BatchingEngine.PrepareBatchingBuckets(parameterValues, lookup, child.ItemType, _taskInstance.Location); // "Execute" each bucket foreach (ItemBucket bucket in buckets) { bool condition = ConditionEvaluator.EvaluateCondition ( child.Condition, ParserOptions.AllowAll, bucket.Expander, ExpanderOptions.ExpandAll, Project.Directory, child.ConditionLocation, LoggingContext.LoggingService, LoggingContext.BuildEventContext, FileSystems.Default); if (condition) { HashSet <string> keepMetadata = null; HashSet <string> removeMetadata = null; HashSet <string> matchOnMetadata = null; MatchOnMetadataOptions matchOnMetadataOptions = MatchOnMetadataConstants.MatchOnMetadataOptionsDefaultValue; if (!String.IsNullOrEmpty(child.KeepMetadata)) { var keepMetadataEvaluated = bucket.Expander.ExpandIntoStringListLeaveEscaped(child.KeepMetadata, ExpanderOptions.ExpandAll, child.KeepMetadataLocation).ToList(); if (keepMetadataEvaluated.Count > 0) { keepMetadata = new HashSet <string>(keepMetadataEvaluated); } } if (!String.IsNullOrEmpty(child.RemoveMetadata)) { var removeMetadataEvaluated = bucket.Expander.ExpandIntoStringListLeaveEscaped(child.RemoveMetadata, ExpanderOptions.ExpandAll, child.RemoveMetadataLocation).ToList(); if (removeMetadataEvaluated.Count > 0) { removeMetadata = new HashSet <string>(removeMetadataEvaluated); } } if (!String.IsNullOrEmpty(child.MatchOnMetadata)) { var matchOnMetadataEvaluated = bucket.Expander.ExpandIntoStringListLeaveEscaped(child.MatchOnMetadata, ExpanderOptions.ExpandAll, child.MatchOnMetadataLocation).ToList(); if (matchOnMetadataEvaluated.Count > 0) { matchOnMetadata = new HashSet <string>(matchOnMetadataEvaluated); } Enum.TryParse(child.MatchOnMetadataOptions, out matchOnMetadataOptions); } if ((child.Include.Length != 0) || (child.Exclude.Length != 0)) { // It's an item -- we're "adding" items to the world ExecuteAdd(child, bucket, keepMetadata, removeMetadata); } else if (child.Remove.Length != 0) { // It's a remove -- we're "removing" items from the world ExecuteRemove(child, bucket, matchOnMetadata, matchOnMetadataOptions); } else { // It's a modify -- changing existing items ExecuteModify(child, bucket, keepMetadata, removeMetadata); } } } } finally { if (buckets != null) { // Propagate the item changes to the bucket above foreach (ItemBucket bucket in buckets) { bucket.LeaveScope(); } } } } }
/// <summary> /// Pushes the list of targets specified onto the target stack in reverse order specified, so that /// they will be built in the order specified. /// </summary> /// <param name="targets">List of targets to build.</param> /// <param name="parentTargetEntry">The target which should be considered the parent of these targets.</param> /// <param name="baseLookup">The lookup to be used to build these targets.</param> /// <param name="addAsErrorTarget">True if this should be considered an error target.</param> /// <param name="stopProcessingOnCompletion">True if target stack processing should terminate when the last target in the list is processed.</param> /// <param name="buildReason">The reason the target is being built by the parent.</param> /// <returns>True if we actually pushed any targets, false otherwise.</returns> private async Task <bool> PushTargets(IList <TargetSpecification> targets, TargetEntry parentTargetEntry, Lookup baseLookup, bool addAsErrorTarget, bool stopProcessingOnCompletion, TargetBuiltReason buildReason) { List <TargetEntry> targetsToPush = new List <TargetEntry>(targets.Count); // Iterate the list in reverse order so that the first target in the list is the last pushed, and thus the first to be executed. for (int i = targets.Count - 1; i >= 0; i--) { TargetSpecification targetSpecification = targets[i]; if (buildReason == TargetBuiltReason.BeforeTargets || buildReason == TargetBuiltReason.AfterTargets) { // Don't build any Before or After targets for which we already have results. Unlike other targets, // we don't explicitly log a skipped-with-results message because it is not interesting. if (_buildResult.HasResultsForTarget(targetSpecification.TargetName)) { if (_buildResult[targetSpecification.TargetName].ResultCode != TargetResultCode.Skipped) { continue; } } } ElementLocation targetLocation = targetSpecification.ReferenceLocation; // See if this target is already building under a different build request. If so, we need to wait. int idOfAlreadyBuildingRequest = BuildRequest.InvalidGlobalRequestId; if (_requestEntry.RequestConfiguration.ActivelyBuildingTargets.TryGetValue(targetSpecification.TargetName, out idOfAlreadyBuildingRequest)) { if (idOfAlreadyBuildingRequest != _requestEntry.Request.GlobalRequestId) { // Another request elsewhere is building it. We need to wait. await _requestBuilderCallback.BlockOnTargetInProgress(idOfAlreadyBuildingRequest, targetSpecification.TargetName, null); // If we come out of here and the target is *still* active, it means the scheduler detected a circular dependency and told us to // continue so we could throw the exception. if (_requestEntry.RequestConfiguration.ActivelyBuildingTargets.ContainsKey(targetSpecification.TargetName)) { ProjectErrorUtilities.ThrowInvalidProject(targetLocation, "CircularDependency", targetSpecification.TargetName); } } else { if (buildReason == TargetBuiltReason.AfterTargets) { // If the target we are pushing is supposed to run after the current target and it is already set to run after us then skip adding it now. continue; } // We are already building this target on this request. That's a circular dependency. ProjectErrorUtilities.ThrowInvalidProject(targetLocation, "CircularDependency", targetSpecification.TargetName); } } else { // Does this target exist in our direct parent chain, if it is a before target (since these can cause circular dependency issues) if (buildReason == TargetBuiltReason.BeforeTargets || buildReason == TargetBuiltReason.DependsOn || buildReason == TargetBuiltReason.None) { TargetEntry currentParent = parentTargetEntry; while (currentParent != null) { if (String.Equals(currentParent.Name, targetSpecification.TargetName, StringComparison.OrdinalIgnoreCase)) { // We are already building this target on this request. That's a circular dependency. ProjectErrorUtilities.ThrowInvalidProject(targetLocation, "CircularDependency", targetSpecification.TargetName); } currentParent = currentParent.ParentEntry; } } else { // For an after target, if it is already ANYWHERE on the stack, we don't need to push it because it is already going to run // after whatever target is causing it to be pushed now. bool alreadyPushed = false; foreach (TargetEntry entry in _targetsToBuild) { if (String.Equals(entry.Name, targetSpecification.TargetName, StringComparison.OrdinalIgnoreCase)) { alreadyPushed = true; break; } } if (alreadyPushed) { continue; } } } // Add to the list of targets to push. We don't actually put it on the stack here because we could run into a circular dependency // during this loop, in which case the target stack would be out of whack. TargetEntry newEntry = new TargetEntry(_requestEntry, this as ITargetBuilderCallback, targetSpecification, baseLookup, parentTargetEntry, buildReason, _componentHost, stopProcessingOnCompletion); newEntry.ErrorTarget = addAsErrorTarget; targetsToPush.Add(newEntry); stopProcessingOnCompletion = false; // The first target on the stack (the last one to be run) always inherits the stopProcessing flag. } // Now push the targets since this operation cannot fail. foreach (TargetEntry targetToPush in targetsToPush) { _targetsToBuild.Push(targetToPush); } bool pushedTargets = (targetsToPush.Count > 0); return(pushedTargets); }
public void AddsAreCombinedWithPopulates() { // One item in the project BuildItemGroup group1 = new BuildItemGroup(); group1.AddNewItem("i1", "a1"); Hashtable table1 = new Hashtable(StringComparer.OrdinalIgnoreCase); table1.Add("i1", group1); Lookup lookup = LookupHelpers.CreateLookup(table1); // We see the one item Assertion.AssertEquals("a1", lookup.GetItems("i1")[0].FinalItemSpec); // One item in the project Assertion.AssertEquals("a1", group1[0].FinalItemSpec); Assertion.AssertEquals(1, group1.Count); // Start a target lookup.EnterScope(); // We see the one item Assertion.AssertEquals("a1", lookup.GetItems("i1")[0].FinalItemSpec); // One item in the project Assertion.AssertEquals("a1", group1[0].FinalItemSpec); Assertion.AssertEquals(1, group1.Count); // Start a task (eg) and add a new item lookup.EnterScope(); lookup.AddNewItem(new BuildItem("i1", "a2")); // Now we see two items Assertion.AssertEquals("a1", lookup.GetItems("i1")[0].FinalItemSpec); Assertion.AssertEquals("a2", lookup.GetItems("i1")[1].FinalItemSpec); // But there's still one item in the project Assertion.AssertEquals("a1", group1[0].FinalItemSpec); Assertion.AssertEquals(1, group1.Count); // Finish the task lookup.LeaveScope(); // We still see two items Assertion.AssertEquals("a1", lookup.GetItems("i1")[0].FinalItemSpec); Assertion.AssertEquals("a2", lookup.GetItems("i1")[1].FinalItemSpec); // But there's still one item in the project Assertion.AssertEquals("a1", group1[0].FinalItemSpec); Assertion.AssertEquals(1, group1.Count); // Finish the target lookup.LeaveScope(); // We still see two items Assertion.AssertEquals("a1", lookup.GetItems("i1")[0].FinalItemSpec); Assertion.AssertEquals("a2", lookup.GetItems("i1")[1].FinalItemSpec); // And now the items have gotten put into the global group Assertion.AssertEquals("a1", group1[0].FinalItemSpec); Assertion.AssertEquals("a2", group1[1].FinalItemSpec); Assertion.AssertEquals(2, group1.Count); }
public override IInternalActorRef GetSingleChild(string name) { return(Lookup.GetSingleChild(name)); }
public T GetByKeyParts(params string[] keyParts) { var key = Key(keyParts); T value; if (TryGetByKey(key, out value)) { return(value); } else { throw new ArgumentException(string.Format("Cannot lookup with key: {0}. Available keys: {1} ({2} keys in total)", key, GetKeyList(50), Lookup.Count())); } }
/// <summary> /// Evaluates a simple mathematical equation that may contain the following operators: * / + - ( ). /// </summary> /// <param name="exp">The equation to be evaluated</param> /// <param name="variableEvaluator">A function used to determine the value of any variables present in the equation</param> /// <returns></returns> public static int Evaluate(String exp, Lookup variableEvaluator) { //Split the mathematical expression into an array string[] expression = splitter(exp); //Iterate through the expression array for (int i = 0; i < expression.Length; i++) { //Take the element and store it in a new string variable for readability string token = expression[i]; //TODO: Errors switch (token) { //If the token is a null, ignore case "": break; //If the token is a /, *, or a (, push onto the operators stack case "/": case "*": case "(": operators.Push(token); break; //If the token is a + or -, check to see if there //is an unresolved prior + or - operation //and then push the token onto the operators stack case "+": case "-": //Check to make sure the stack isn't empty before peeking if (operators.Count != 0) { if (operators.Peek().Equals("+") || operators.Peek().Equals("-")) { values.Push(applyMath()); } } operators.Push(token); break; //Resolve the inside of the parenthesis, and then pop the left parenthesis //Also resolve any * or / that may require the value of the operations inside case ")": //Check to make sure the stack isn't empty before peeking if (operators.Count != 0) { //Resolve the inside if (operators.Peek().Equals("+") || operators.Peek().Equals("-")) { values.Push(applyMath()); } } //If there is no operators on the stack, throw an exception if (operators.Count == 0) { throw new ArgumentException(); } //If there is an operator but it's not the left parenthesis, //Throw an exception if (!operators.Pop().Equals("(")) { throw new ArgumentException(); } //Check to make sure the stack isn't empty before peeking if (operators.Count != 0) { //Resolve any * or / modifying the result of the parenthesis if (operators.Peek().Equals("*") || operators.Peek().Equals("/")) { if (values.Count() < 1) { throw new ArgumentException(); } values.Push(applyMath(values.Pop())); } } break; //If the token is not an operand default: double result; //Check to see if the token is a number. If so, //resolve any outlying * or / operators if (double.TryParse(token, out result)) { //Check to make sure the stack isn't empty before peeking if (operators.Count != 0) { //Resolve any outlying * or / operators if (operators.Peek().Equals("*") || operators.Peek().Equals("/")) { values.Push(applyMath(result)); } else { values.Push(result); } } //It is the first number, so there are no operators //It is simply pushed to values else { values.Push(result); } } //Check for variable else if (Char.IsLetter(token.First()) && token.Length > 1) { //Indicates if we have found where the letters in a variable name have changed to numbers bool foundNumber = false; //Iterate through the token starting at 1 (since we already looked at the first element) for (int count = 1; count < token.Length; count++) { //If we haven't found a number if (!foundNumber) { //Check to see if the element is a number if (Char.IsNumber(token[count])) { foundNumber = true; } //Check to see if the element is a letter else if (!Char.IsLetter(token[count])) { //Throw error if the element is neither a letter or a number throw new ArgumentException(); } else { //Continue iterating } } //We have started using numbers instead of letters else if (Char.IsNumber(token[count])) { //Continue iterating } else { //Throw error if the element wasn't a number throw new ArgumentException(); } } //Retrieve the value of the variable result = variableEvaluator(token); //Continue as if it was a number //Check to make sure the stack isn't empty before peeking if (operators.Count != 0) { if (operators.Peek().Equals("*") || operators.Peek().Equals("/")) { values.Push(applyMath(result)); } else { values.Push(result); } } else { values.Push(result); } } else { throw new ArgumentException(); } break; } } //All the math has been calculated, and the result is the last value //in the values stack if (values.Count == 1 && operators.Count == 0) { return((int)values.Pop()); } //There is a left over + or - operation that still needs to be calculated else if (values.Count == 2 && operators.Count == 1) { switch (operators.Peek()) {//Resolve the operation and return the result case "+": case "-": return((int)applyMath()); //The remaining operator wasn't a + or -, so throw an exception default: throw new ArgumentException(); } } //There are extra operators or values where there shouldn't be //Throw an exception else { throw new ArgumentException(); } }
public bool TryGetByKey(out T value, params string[] keyParts) { return(Lookup.TryGetValue(Key(keyParts), out value)); }
protected override EnumType String_To_Token(ReadOnlyMemory <char> str) { return(Lookup.Enum <EnumType>(str)); }
public int validate_USPSAddress(string Street, string Secondary, string City, string State, string Zip) { /* * Return codes: * 0 Good USPS address * -1 SmartyException exception * -2 IOException exception * 1 Address entered does not match USPS * 2 State returned does not match the Zip code entered * 3 Zip code returned does not match Zip code entered * 4 City entered does not match SmartyStreets database */ var authId = "4d6ae97b-1625-654a-d23d-f141e4b24dd3"; var authToken = "AjHklAjoKpJ67yj9r5uV"; //For PRODUCTION store keys out side of code; environment variables or DB //var authId = Environment.GetEnvironmentVariable("SMARTY_AUTH_ID"); //var authToken = Environment.GetEnvironmentVariable("SMARTY_AUTH_TOKEN"); var client = new ClientBuilder(authId, authToken) .BuildUsStreetApiClient(); // Documentation for input fields can be found at: // https://smartystreets.com/docs/us-street-api#input-fields var lookup = new Lookup { Street = Street, Secondary = Secondary, City = City, State = State, ZipCode = Zip, MaxCandidates = 1, MatchStrategy = Lookup.STRICT // The API will ONLY return candidates that are valid USPS addresses. }; try { client.Send(lookup); } // for PRODUCTION exception messages should be sent to a log that is monitored catch (SmartyException ex) { MessageBox.Show(ex.Message); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); return(-1); } catch (System.IO.IOException ex) { Console.WriteLine(ex.StackTrace); MessageBox.Show(ex.Message); return(-2); } var candidates = lookup.Result; if (candidates.Count == 0) { Console.WriteLine("No candidates. This means the address is not valid."); return(1); } var firstCandidate = candidates[0]; if (State != firstCandidate.Components.State) { return(2); //State returned does not match the Zip code entered } if ((firstCandidate.Components.Plus4Code.Length > 0) && (Zip.Length == 9)) { if (Zip != firstCandidate.Components.ZipCode + firstCandidate.Components.Plus4Code) { return(3); //Zip code entered does not match City/State } } else if (Zip != firstCandidate.Components.ZipCode) { return(3); //Zip code entered does not match City/State } if (City.ToLower() != firstCandidate.Components.CityName.ToLower()) { return(4); //City entered does not match SmartyStreets database } Console.WriteLine("Address is valid. (There is at least one candidate)\n"); Console.WriteLine("ZIP Code: " + firstCandidate.Components.ZipCode); Console.WriteLine("City: " + firstCandidate.Components.CityName); Console.WriteLine("State: " + firstCandidate.Components.State); return(0); }
/// <summary> /// Recieve an item interaction. woop. /// </summary> /// <param name="item"></param> protected virtual void RecieveItemInteraction(IEntity actor, IEntity item, Lookup <ItemCapabilityType, ItemCapabilityVerb> verbs) { }
public void ModifyItemTwiceInSameScope2() { Hashtable table1 = new Hashtable(StringComparer.OrdinalIgnoreCase); Lookup lookup = LookupHelpers.CreateLookup(table1); // Add an item with m=m1 and n=n1 and o=o1 BuildItem item1 = new BuildItem("i1", "a2"); item1.SetMetadata("m", "m1"); item1.SetMetadata("n", "n1"); item1.SetMetadata("o", "o1"); lookup.PopulateWithItem(item1); lookup.EnterScope(); // It's still m=m1, n=n1, o=o1 BuildItemGroup group = lookup.GetItems("i1"); Assertion.AssertEquals(1, group.Count); Assertion.AssertEquals("m1", group[0].GetMetadata("m")); Assertion.AssertEquals("n1", group[0].GetMetadata("n")); Assertion.AssertEquals("o1", group[0].GetMetadata("o")); // Make a modification to the item to be m=m2 and n=n2 Dictionary <string, string> newMetadata = new Dictionary <string, string>(); newMetadata.Add("m", "m2"); newMetadata.Add("n", "n2"); group = new BuildItemGroup(); group.AddItem(item1); lookup.ModifyItems("i1", group, newMetadata); // It's now m=m2, n=n2, o=o1 BuildItemGroup foundGroup = lookup.GetItems("i1"); Assertion.AssertEquals(1, foundGroup.Count); Assertion.AssertEquals("m2", foundGroup[0].GetMetadata("m")); Assertion.AssertEquals("n2", foundGroup[0].GetMetadata("n")); Assertion.AssertEquals("o1", foundGroup[0].GetMetadata("o")); // Make a modification to the item to be n=n3 newMetadata = new Dictionary <string, string>(); newMetadata.Add("n", "n3"); lookup.ModifyItems("i1", group, newMetadata); // It's now m=m2, n=n3, o=o1 foundGroup = lookup.GetItems("i1"); Assertion.AssertEquals(1, foundGroup.Count); Assertion.AssertEquals("m2", foundGroup[0].GetMetadata("m")); Assertion.AssertEquals("n3", foundGroup[0].GetMetadata("n")); Assertion.AssertEquals("o1", foundGroup[0].GetMetadata("o")); // But the original item hasn't changed yet Assertion.AssertEquals("m1", item1.GetMetadata("m")); Assertion.AssertEquals("n1", item1.GetMetadata("n")); Assertion.AssertEquals("o1", item1.GetMetadata("o")); lookup.LeaveScope(); // It's still m=m2, n=n3, o=o1 foundGroup = lookup.GetItems("i1"); Assertion.AssertEquals(1, foundGroup.Count); Assertion.AssertEquals("m2", foundGroup[0].GetMetadata("m")); Assertion.AssertEquals("n3", foundGroup[0].GetMetadata("n")); Assertion.AssertEquals("o1", foundGroup[0].GetMetadata("o")); // And the original item has changed Assertion.AssertEquals("m2", item1.GetMetadata("m")); Assertion.AssertEquals("n3", item1.GetMetadata("n")); Assertion.AssertEquals("o1", item1.GetMetadata("o")); }
public static int SortedLookup <T>(ref T searchSpace, int offset, int length, ref T value, Lookup lookup, KeyComparer <T> comparer = default) { // ReSharper disable once RedundantLogicalConditionalExpressionOperand if (Settings.UseInterpolatedSearchForKnownTypes && KeyComparer <T> .IsDiffableSafe) { return(InterpolationLookup(ref searchSpace, offset, length, ref value, lookup, comparer)); } return(BinaryLookup(ref searchSpace, offset, length, ref value, lookup, comparer)); }
private static Function[] ProduceFunctions() { Function[] retval = new Function[368]; retval[0] = new Count(); // COUNT retval[FunctionID.IF] = new If(); // IF retval[2] = LogicalFunction.ISNA; // IsNA retval[3] = LogicalFunction.ISERROR; // IsERROR retval[FunctionID.SUM] = AggregateFunction.SUM; // SUM retval[5] = AggregateFunction.AVERAGE; // AVERAGE retval[6] = AggregateFunction.MIN; // MIN retval[7] = AggregateFunction.MAX; // MAX retval[8] = new Row(); // ROW retval[9] = new Column(); // COLUMN retval[10] = new Na(); // NA retval[11] = new Npv(); // NPV retval[12] = AggregateFunction.STDEV; // STDEV retval[13] = NumericFunction.DOLLAR; // DOLLAR retval[14] = new NotImplementedFunction(); // FIXED retval[15] = NumericFunction.SIN; // SIN retval[16] = NumericFunction.COS; // COS retval[17] = NumericFunction.TAN; // TAN retval[18] = NumericFunction.ATAN; // ATAN retval[19] = new Pi(); // PI retval[20] = NumericFunction.SQRT; // SQRT retval[21] = NumericFunction.EXP; // EXP retval[22] = NumericFunction.LN; // LN retval[23] = NumericFunction.LOG10; // LOG10 retval[24] = NumericFunction.ABS; // ABS retval[25] = NumericFunction.INT; // INT retval[26] = NumericFunction.SIGN; // SIGN retval[27] = NumericFunction.ROUND; // ROUND retval[28] = new Lookup(); // LOOKUP retval[29] = new Index(); // INDEX retval[30] = new NotImplementedFunction(); // REPT retval[31] = TextFunction.MID; // MID retval[32] = TextFunction.LEN; // LEN retval[33] = new Value(); // VALUE retval[34] = new True(); // TRUE retval[35] = new False(); // FALSE retval[36] = new And(); // AND retval[37] = new Or(); // OR retval[38] = new Not(); // NOT retval[39] = NumericFunction.MOD; // MOD retval[40] = new NotImplementedFunction(); // DCOUNT retval[41] = new NotImplementedFunction(); // DSUM retval[42] = new NotImplementedFunction(); // DAVERAGE retval[43] = new NotImplementedFunction(); // DMIN retval[44] = new NotImplementedFunction(); // DMAX retval[45] = new NotImplementedFunction(); // DSTDEV retval[46] = new NotImplementedFunction(); // VAR retval[47] = new NotImplementedFunction(); // DVAR retval[48] = TextFunction.TEXT; // TEXT retval[49] = new NotImplementedFunction(); // LINEST retval[50] = new NotImplementedFunction(); // TREND retval[51] = new NotImplementedFunction(); // LOGEST retval[52] = new NotImplementedFunction(); // GROWTH retval[53] = new NotImplementedFunction(); // GOTO retval[54] = new NotImplementedFunction(); // HALT retval[56] = new NotImplementedFunction(); // PV retval[57] = FinanceFunction.FV; // FV retval[58] = FinanceFunction.NPER; // NPER retval[59] = FinanceFunction.PMT; // PMT retval[60] = new NotImplementedFunction(); // RATE retval[61] = new NotImplementedFunction(); // MIRR retval[62] = new Irr(); // IRR retval[63] = new Rand(); // RAND retval[64] = new Match(); // MATCH retval[65] = DateFunc.instance; // DATE retval[66] = new TimeFunc(); // TIME retval[67] = CalendarFieldFunction.DAY; // DAY retval[68] = CalendarFieldFunction.MONTH; // MONTH retval[69] = CalendarFieldFunction.YEAR; // YEAR retval[70] = new NotImplementedFunction(); // WEEKDAY retval[71] = CalendarFieldFunction.HOUR; retval[72] = CalendarFieldFunction.MINUTE; retval[73] = CalendarFieldFunction.SECOND; retval[74] = new Now(); retval[75] = new NotImplementedFunction(); // AREAS retval[76] = new Rows(); // ROWS retval[77] = new Columns(); // COLUMNS retval[FunctionID.OFFSET] = new Offset(); // Offset.Evaluate has a different signature retval[79] = new NotImplementedFunction(); // ABSREF retval[80] = new NotImplementedFunction(); // RELREF retval[81] = new NotImplementedFunction(); // ARGUMENT retval[82] = TextFunction.SEARCH; retval[83] = new NotImplementedFunction(); // TRANSPOSE retval[84] = new NotImplementedFunction(); // ERROR retval[85] = new NotImplementedFunction(); // STEP retval[86] = new NotImplementedFunction(); // TYPE retval[87] = new NotImplementedFunction(); // ECHO retval[88] = new NotImplementedFunction(); // SetNAME retval[89] = new NotImplementedFunction(); // CALLER retval[90] = new NotImplementedFunction(); // DEREF retval[91] = new NotImplementedFunction(); // WINDOWS retval[92] = new NotImplementedFunction(); // SERIES retval[93] = new NotImplementedFunction(); // DOCUMENTS retval[94] = new NotImplementedFunction(); // ACTIVECELL retval[95] = new NotImplementedFunction(); // SELECTION retval[96] = new NotImplementedFunction(); // RESULT retval[97] = NumericFunction.ATAN2; // ATAN2 retval[98] = NumericFunction.ASIN; // ASIN retval[99] = NumericFunction.ACOS; // ACOS retval[FunctionID.CHOOSE] = new Choose(); retval[101] = new Hlookup(); // HLOOKUP retval[102] = new Vlookup(); // VLOOKUP retval[103] = new NotImplementedFunction(); // LINKS retval[104] = new NotImplementedFunction(); // INPUT retval[105] = LogicalFunction.ISREF; // IsREF retval[106] = new NotImplementedFunction(); // GetFORMULA retval[107] = new NotImplementedFunction(); // GetNAME retval[108] = new NotImplementedFunction(); // SetVALUE retval[109] = NumericFunction.LOG; // LOG retval[110] = new NotImplementedFunction(); // EXEC retval[111] = TextFunction.CHAR; // CHAR retval[112] = TextFunction.LOWER; // LOWER retval[113] = TextFunction.UPPER; // UPPER retval[114] = new NotImplementedFunction(); // PROPER retval[115] = TextFunction.LEFT; // LEFT retval[116] = TextFunction.RIGHT; // RIGHT retval[117] = TextFunction.EXACT; // EXACT retval[118] = TextFunction.TRIM; // TRIM retval[119] = new Replace(); // Replace retval[120] = new Substitute(); // SUBSTITUTE retval[121] = new NotImplementedFunction(); // CODE retval[122] = new NotImplementedFunction(); // NAMES retval[123] = new NotImplementedFunction(); // DIRECTORY retval[124] = TextFunction.FIND; // Find retval[125] = new NotImplementedFunction(); // CELL retval[126] = new NotImplementedFunction(); // IsERR retval[127] = LogicalFunction.ISTEXT; // IsTEXT retval[128] = LogicalFunction.ISNUMBER; // IsNUMBER retval[129] = LogicalFunction.ISBLANK; // IsBLANK retval[130] = new T(); // T retval[131] = new NotImplementedFunction(); // N retval[132] = new NotImplementedFunction(); // FOPEN retval[133] = new NotImplementedFunction(); // FCLOSE retval[134] = new NotImplementedFunction(); // FSIZE retval[135] = new NotImplementedFunction(); // FReadLN retval[136] = new NotImplementedFunction(); // FRead retval[137] = new NotImplementedFunction(); // FWriteLN retval[138] = new NotImplementedFunction(); // FWrite retval[139] = new NotImplementedFunction(); // FPOS retval[140] = new NotImplementedFunction(); // DATEVALUE retval[141] = new NotImplementedFunction(); // TIMEVALUE retval[142] = new NotImplementedFunction(); // SLN retval[143] = new NotImplementedFunction(); // SYD retval[144] = new NotImplementedFunction(); // DDB retval[145] = new NotImplementedFunction(); // GetDEF retval[146] = new NotImplementedFunction(); // REFTEXT retval[147] = new NotImplementedFunction(); // TEXTREF retval[FunctionID.INDIRECT] = null; // Indirect.Evaluate has different signature retval[149] = new NotImplementedFunction(); // REGISTER retval[150] = new NotImplementedFunction(); // CALL retval[151] = new NotImplementedFunction(); // AddBAR retval[152] = new NotImplementedFunction(); // AddMENU retval[153] = new NotImplementedFunction(); // AddCOMMAND retval[154] = new NotImplementedFunction(); // ENABLECOMMAND retval[155] = new NotImplementedFunction(); // CHECKCOMMAND retval[156] = new NotImplementedFunction(); // RenameCOMMAND retval[157] = new NotImplementedFunction(); // SHOWBAR retval[158] = new NotImplementedFunction(); // DELETEMENU retval[159] = new NotImplementedFunction(); // DELETECOMMAND retval[160] = new NotImplementedFunction(); // GetCHARTITEM retval[161] = new NotImplementedFunction(); // DIALOGBOX retval[162] = TextFunction.CLEAN; // CLEAN retval[163] = new NotImplementedFunction(); // MDETERM retval[164] = new NotImplementedFunction(); // MINVERSE retval[165] = new NotImplementedFunction(); // MMULT retval[166] = new NotImplementedFunction(); // FILES retval[167] = new NotImplementedFunction(); // IPMT retval[168] = new NotImplementedFunction(); // PPMT retval[169] = new Counta(); // COUNTA retval[170] = new NotImplementedFunction(); // CANCELKEY retval[175] = new NotImplementedFunction(); // INITIATE retval[176] = new NotImplementedFunction(); // REQUEST retval[177] = new NotImplementedFunction(); // POKE retval[178] = new NotImplementedFunction(); // EXECUTE retval[179] = new NotImplementedFunction(); // TERMINATE retval[180] = new NotImplementedFunction(); // RESTART retval[181] = new NotImplementedFunction(); // HELP retval[182] = new NotImplementedFunction(); // GetBAR retval[183] = AggregateFunction.PRODUCT; // PRODUCT retval[184] = NumericFunction.FACT; // FACT retval[185] = new NotImplementedFunction(); // GetCELL retval[186] = new NotImplementedFunction(); // GetWORKSPACE retval[187] = new NotImplementedFunction(); // GetWINDOW retval[188] = new NotImplementedFunction(); // GetDOCUMENT retval[189] = new NotImplementedFunction(); // DPRODUCT retval[190] = LogicalFunction.ISNONTEXT; // IsNONTEXT retval[191] = new NotImplementedFunction(); // GetNOTE retval[192] = new NotImplementedFunction(); // NOTE retval[193] = new NotImplementedFunction(); // STDEVP retval[194] = new NotImplementedFunction(); // VARP retval[195] = new NotImplementedFunction(); // DSTDEVP retval[196] = new NotImplementedFunction(); // DVARP retval[197] = NumericFunction.TRUNC; // TRUNC retval[198] = LogicalFunction.ISLOGICAL; // IsLOGICAL retval[199] = new NotImplementedFunction(); // DCOUNTA retval[200] = new NotImplementedFunction(); // DELETEBAR retval[201] = new NotImplementedFunction(); // UNREGISTER retval[204] = new NotImplementedFunction(); // USDOLLAR retval[205] = new NotImplementedFunction(); // FindB retval[206] = new NotImplementedFunction(); // SEARCHB retval[207] = new NotImplementedFunction(); // ReplaceB retval[208] = new NotImplementedFunction(); // LEFTB retval[209] = new NotImplementedFunction(); // RIGHTB retval[210] = new NotImplementedFunction(); // MIDB retval[211] = new NotImplementedFunction(); // LENB retval[212] = NumericFunction.ROUNDUP; // ROUNDUP retval[213] = NumericFunction.ROUNDDOWN; // ROUNDDOWN retval[214] = new NotImplementedFunction(); // ASC retval[215] = new NotImplementedFunction(); // DBCS retval[216] = new NotImplementedFunction(); // RANK retval[219] = new Address(); // AddRESS retval[220] = new Days360(); // DAYS360 retval[221] = new NotImplementedFunction(); // TODAY retval[222] = new NotImplementedFunction(); // VDB retval[227] = AggregateFunction.MEDIAN; // MEDIAN retval[228] = new Sumproduct(); // SUMPRODUCT retval[229] = NumericFunction.SINH; // SINH retval[230] = NumericFunction.COSH; // COSH retval[231] = NumericFunction.TANH; // TANH retval[232] = NumericFunction.ASINH; // ASINH retval[233] = NumericFunction.ACOSH; // ACOSH retval[234] = NumericFunction.ATANH; // ATANH retval[235] = new NotImplementedFunction(); // DGet retval[236] = new NotImplementedFunction(); // CreateOBJECT retval[237] = new NotImplementedFunction(); // VOLATILE retval[238] = new NotImplementedFunction(); // LASTERROR retval[239] = new NotImplementedFunction(); // CUSTOMUNDO retval[240] = new NotImplementedFunction(); // CUSTOMREPEAT retval[241] = new NotImplementedFunction(); // FORMULAConvert retval[242] = new NotImplementedFunction(); // GetLINKINFO retval[243] = new NotImplementedFunction(); // TEXTBOX retval[244] = new NotImplementedFunction(); // INFO retval[245] = new NotImplementedFunction(); // GROUP retval[246] = new NotImplementedFunction(); // GetOBJECT retval[247] = new NotImplementedFunction(); // DB retval[248] = new NotImplementedFunction(); // PAUSE retval[250] = new NotImplementedFunction(); // RESUME retval[252] = new NotImplementedFunction(); // FREQUENCY retval[253] = new NotImplementedFunction(); // AddTOOLBAR retval[254] = new NotImplementedFunction(); // DELETETOOLBAR retval[FunctionID.EXTERNAL_FUNC] = null; // ExternalFunction is a FreeREfFunction retval[256] = new NotImplementedFunction(); // RESetTOOLBAR retval[257] = new NotImplementedFunction(); // EVALUATE retval[258] = new NotImplementedFunction(); // GetTOOLBAR retval[259] = new NotImplementedFunction(); // GetTOOL retval[260] = new NotImplementedFunction(); // SPELLINGCHECK retval[261] = new NotImplementedFunction(); // ERRORTYPE retval[262] = new NotImplementedFunction(); // APPTITLE retval[263] = new NotImplementedFunction(); // WINDOWTITLE retval[264] = new NotImplementedFunction(); // SAVETOOLBAR retval[265] = new NotImplementedFunction(); // ENABLETOOL retval[266] = new NotImplementedFunction(); // PRESSTOOL retval[267] = new NotImplementedFunction(); // REGISTERID retval[268] = new NotImplementedFunction(); // GetWORKBOOK retval[269] = AggregateFunction.AVEDEV; // AVEDEV retval[270] = new NotImplementedFunction(); // BETADIST retval[271] = new NotImplementedFunction(); // GAMMALN retval[272] = new NotImplementedFunction(); // BETAINV retval[273] = new NotImplementedFunction(); // BINOMDIST retval[274] = new NotImplementedFunction(); // CHIDIST retval[275] = new NotImplementedFunction(); // CHIINV retval[276] = NumericFunction.COMBIN; // COMBIN retval[277] = new NotImplementedFunction(); // CONFIDENCE retval[278] = new NotImplementedFunction(); // CRITBINOM retval[279] = new Even(); // EVEN retval[280] = new NotImplementedFunction(); // EXPONDIST retval[281] = new NotImplementedFunction(); // FDIST retval[282] = new NotImplementedFunction(); // FINV retval[283] = new NotImplementedFunction(); // FISHER retval[284] = new NotImplementedFunction(); // FISHERINV retval[285] = NumericFunction.FLOOR; // FLOOR retval[286] = new NotImplementedFunction(); // GAMMADIST retval[287] = new NotImplementedFunction(); // GAMMAINV retval[288] = NumericFunction.CEILING; // CEILING retval[289] = new NotImplementedFunction(); // HYPGEOMDIST retval[290] = new NotImplementedFunction(); // LOGNORMDIST retval[291] = new NotImplementedFunction(); // LOGINV retval[292] = new NotImplementedFunction(); // NEGBINOMDIST retval[293] = new NotImplementedFunction(); // NORMDIST retval[294] = new NotImplementedFunction(); // NORMSDIST retval[295] = new NotImplementedFunction(); // NORMINV retval[296] = new NotImplementedFunction(); // NORMSINV retval[297] = new NotImplementedFunction(); // STANDARDIZE retval[298] = new Odd(); // ODD retval[299] = new NotImplementedFunction(); // PERMUT retval[300] = new NotImplementedFunction(); // POISSON retval[301] = new NotImplementedFunction(); // TDIST retval[302] = new NotImplementedFunction(); // WEIBULL retval[303] = new Sumxmy2(); // SUMXMY2 retval[304] = new Sumx2my2(); // SUMX2MY2 retval[305] = new Sumx2py2(); // SUMX2PY2 retval[306] = new NotImplementedFunction(); // CHITEST retval[307] = new NotImplementedFunction(); // CORREL retval[308] = new NotImplementedFunction(); // COVAR retval[309] = new NotImplementedFunction(); // FORECAST retval[310] = new NotImplementedFunction(); // FTEST retval[311] = new NotImplementedFunction(); // INTERCEPT retval[312] = new NotImplementedFunction(); // PEARSON retval[313] = new NotImplementedFunction(); // RSQ retval[314] = new NotImplementedFunction(); // STEYX retval[315] = new NotImplementedFunction(); // SLOPE retval[316] = new NotImplementedFunction(); // TTEST retval[317] = new NotImplementedFunction(); // PROB retval[318] = AggregateFunction.DEVSQ; // DEVSQ retval[319] = new NotImplementedFunction(); // GEOMEAN retval[320] = new NotImplementedFunction(); // HARMEAN retval[321] = AggregateFunction.SUMSQ; // SUMSQ retval[322] = new NotImplementedFunction(); // KURT retval[323] = new NotImplementedFunction(); // SKEW retval[324] = new NotImplementedFunction(); // ZTEST retval[325] = AggregateFunction.LARGE; // LARGE retval[326] = AggregateFunction.SMALL; // SMALL retval[327] = new NotImplementedFunction(); // QUARTILE retval[328] = new NotImplementedFunction(); // PERCENTILE retval[329] = new NotImplementedFunction(); // PERCENTRANK retval[330] = new Mode(); // MODE retval[331] = new NotImplementedFunction(); // TRIMMEAN retval[332] = new NotImplementedFunction(); // TINV retval[334] = new NotImplementedFunction(); // MOVIECOMMAND retval[335] = new NotImplementedFunction(); // GetMOVIE retval[336] = TextFunction.CONCATENATE; // CONCATENATE retval[337] = NumericFunction.POWER; // POWER retval[338] = new NotImplementedFunction(); // PIVOTAddDATA retval[339] = new NotImplementedFunction(); // GetPIVOTTABLE retval[340] = new NotImplementedFunction(); // GetPIVOTFIELD retval[341] = new NotImplementedFunction(); // GetPIVOTITEM retval[342] = NumericFunction.RADIANS;; // RADIANS retval[343] = NumericFunction.DEGREES; // DEGREES retval[344] = new Subtotal(); // SUBTOTAL retval[345] = new Sumif(); // SUMIF retval[346] = new Countif(); // COUNTIF retval[347] = new Countblank(); // COUNTBLANK retval[348] = new NotImplementedFunction(); // SCENARIOGet retval[349] = new NotImplementedFunction(); // OPTIONSLISTSGet retval[350] = new NotImplementedFunction(); // IsPMT retval[351] = new NotImplementedFunction(); // DATEDIF retval[352] = new NotImplementedFunction(); // DATESTRING retval[353] = new NotImplementedFunction(); // NUMBERSTRING retval[354] = new NotImplementedFunction(); // ROMAN retval[355] = new NotImplementedFunction(); // OPENDIALOG retval[356] = new NotImplementedFunction(); // SAVEDIALOG retval[357] = new NotImplementedFunction(); // VIEWGet retval[358] = new NotImplementedFunction(); // GetPIVOTDATA retval[359] = new NotImplementedFunction(); // HYPERLINK retval[360] = new NotImplementedFunction(); // PHONETIC retval[361] = new NotImplementedFunction(); // AVERAGEA retval[362] = new Maxa(); // MAXA retval[363] = new Mina(); // MINA retval[364] = new NotImplementedFunction(); // STDEVPA retval[365] = new NotImplementedFunction(); // VARPA retval[366] = new NotImplementedFunction(); // STDEVA retval[367] = new NotImplementedFunction(); // VARA return(retval); }
public static int SearchToLookup2(int offset, int length, Lookup lookup, int i) { if (i >= offset) { if (lookup.IsEqualityOK()) { return(i); } if (lookup == Lookup.LT) { if (i == offset) { return(~offset); } i--; } else // depends on if (eqOk) above { Debug.Assert(lookup == Lookup.GT); if (i == offset + length - 1) { return(~(offset + length)); } i++; } } else { if (lookup == Lookup.EQ) { return(i); } i = ~i; // LT or LE if (((uint)lookup & (uint)Lookup.LT) != 0) { // i is idx of element that is larger, nothing here for LE/LT if (i == offset) { return(~offset); } i--; } else { Debug.Assert(((uint)lookup & (uint)Lookup.GT) != 0); Debug.Assert(i <= offset + length); // if was negative, if it was ~length then there are no more elements for GE/GT if (i == offset + length) { return(~(offset + length)); } // i is the same, ~i is idx of element that is GT the value } } Debug.Assert(unchecked ((uint)i) - offset < unchecked ((uint)length)); return(i); }
public void ModifyItemInOutsideScope() { Lookup lookup = LookupHelpers.CreateLookup(new Hashtable()); lookup.AddNewItem(new BuildItem("x", "y")); }
static public void Show (Browser browser) { if (LookupBox == null) LookupBox = new Lookup (browser); LookupBox.lookup.Show (); }
public static int SearchToLookup(int offset, int length, Lookup lookup, int i) { // TODO benchmark two implementations and review which branch could be mis-predicted // E.g. for LE i >= offset could be problematic // Current benchmarks for lookups are very simplistic and are faster with branches. ThrowHelper.DebugAssert(i < 0 || i >= offset, "i < 0 || i >= offset or wrong search result"); if (lookup == Lookup.EQ) { return(i); } int iAdj; if (i >= offset) { if (lookup.IsEqualityOK()) { return(i); } // -1 if direction is less, +1 if direction is greater than var directionFoundAdj = (3 - ((int)lookup & 0b_101)) >> 1; iAdj = i + directionFoundAdj; } else { // depends on excluding EQ case // 1 if direction is less, 0 otherwise var directionNotFoundAdj = (((int)lookup & 0b_100) >> 2); iAdj = ~i - directionNotFoundAdj; } if ((uint)(iAdj - offset) < length) { return(iAdj); } return(iAdj < offset ? ~offset : ~iAdj); // unchecked // { // // -1 if direction is less, +1 if direction is greater than // var directionFoundAdj = (3 - ((int) lookup & 0b_101)) >> 1; // // 1 if direction is less, 0 otherwise // var directionNotFoundAdj = (((int) lookup & 0b_100) >> 2); // // 1 if equality is not OK // var noEq = (~((int) lookup) & 0b_010) >> 1; // var notFound = i >> 31; // // if not found need to subtract 1 for LT/LE // // iAdj = (notFound & (~i - directionNotFoundAdj)) | (~notFound & i + directionFoundAdj * noEq); // // if ((uint) (iAdj - offset) < length) // return iAdj; // return iAdj < offset ? ~offset : ~iAdj; // } }
/// <summary> /// Creates a 'Lookup' used to deal with projects. /// </summary> /// <param name="project">The project for which to create the lookup</param> /// <returns>The lookup</returns> private Lookup CreateStandardLookup(ProjectInstance project) { Lookup lookup = new Lookup(new ItemDictionary<ProjectItemInstance>(project.Items), new PropertyDictionary<ProjectPropertyInstance>(project.Properties), null); return lookup; }
public static int InterpolationLookup <T>(ref T searchSpace, int length, ref T value, Lookup lookup, KeyComparer <T> comparer = default) { return(InterpolationLookup(ref searchSpace, offset: 0, length, ref value, lookup, comparer)); }
private static void AddParameter(string parameter, string description, Lookup<DatabaseTrackInfo> map) { parameters.Add(parameter); parameterDescriptions.Add(parameter, description); parameterMaps.Add(parameter, map); }
public static int InterpolationLookup <T>(ref T searchSpace, int offset, int length, ref T value, Lookup lookup, KeyComparer <T> comparer = default) { Debug.Assert(length >= 0); var i = InterpolationSearch(ref searchSpace, offset, length, value, comparer); var li = SearchToLookup2(offset, length, lookup, i); if (li != i & li >= 0) // not && { value = UnsafeEx.ReadUnaligned(ref Unsafe.Add(ref searchSpace, li)); } return(li); }
/// <summary> /// This method is used to get attributes from a specified entity. It returns Dictionary containing all the required attributes values. /// </summary> /// <param name="entityGuid">GUID of the entity</param> /// <param name="entityName_">The entity name type (contact,lead,...)</param> ///<param name="entityAttributes">The ArrayList containing the attributes names types you want to retrieve (firstname,lastname,...)</param> public Dictionary<string, string> getEntity(Guid entityGuid, string entityName_, ArrayList entityAttributes) { Dictionary<string, string> arrayData = new Dictionary<string, string>(); try { isconnected(); ArrayList arrayResults = new ArrayList(); // Create the retrieve target. TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic(); // Set the properties of the target. targetRetrieve.EntityName = entityName_; targetRetrieve.EntityId = entityGuid; // Create the request object. RetrieveRequest retrieve = new RetrieveRequest(); ColumnSet col = new ColumnSet(); // Set the properties of the request object. retrieve.Target = targetRetrieve; for (int i = 0; i < entityAttributes.Count; i++) { col.AddColumn(entityAttributes[i].ToString()); } retrieve.ColumnSet = col; // Indicate that the BusinessEntity should be retrieved as a // DynamicEntity. retrieve.ReturnDynamicEntities = true; // Execute the request. RetrieveResponse retrieved = (RetrieveResponse)m_crmService.Execute(retrieve); // Extract the DynamicEntity from the request. DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntity; Microsoft.Crm.Sdk.CrmDateTime crmDateTimeVar = new Microsoft.Crm.Sdk.CrmDateTime(); Microsoft.Crm.Sdk.CrmNumber crmNumberVar = new Microsoft.Crm.Sdk.CrmNumber(); Picklist crmPickList = new Picklist(); Guid crmGuid = new Guid(); Microsoft.Crm.Sdk.Key keyVar = new Microsoft.Crm.Sdk.Key(); Lookup lookupVar = new Lookup(); Microsoft.Crm.Sdk.CrmBoolean boolVar = new Microsoft.Crm.Sdk.CrmBoolean(); for (int i = 0; i < entityAttributes.Count; i++) { if (entity.Properties.Contains(entityAttributes[i].ToString())) { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmDateTimeVar.GetType())) { crmDateTimeVar = (Microsoft.Crm.Sdk.CrmDateTime)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(),crmDateTimeVar.date.ToString()); } else { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmNumberVar.GetType())) { crmNumberVar = (Microsoft.Crm.Sdk.CrmNumber)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(), crmNumberVar.Value.ToString()); } else { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(keyVar.GetType())) { keyVar = (Microsoft.Crm.Sdk.Key)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(), keyVar.Value.ToString()); } else { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(lookupVar.GetType())) { lookupVar = (Microsoft.Crm.Sdk.Lookup)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(), lookupVar.Value.ToString()); } else { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(boolVar.GetType())) { boolVar = (Microsoft.Crm.Sdk.CrmBoolean)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(), boolVar.Value.ToString()); } else { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmPickList.GetType())) { crmPickList = (Microsoft.Crm.Sdk.Picklist)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(), crmPickList.Value.ToString()); } else { if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmGuid.GetType())) { crmGuid = (Guid)entity.Properties[entityAttributes[i].ToString()]; arrayData.Add(entityAttributes[i].ToString(), crmGuid.ToString()); } else { arrayData.Add(entityAttributes[i].ToString(), entity.Properties[entityAttributes[i].ToString()].ToString()); } } } } } } } } else { arrayData.Add(entityAttributes[i].ToString(), ""); } } return arrayData; } catch (SoapException ex) { throw new InvalidPluginExecutionException("!SoapException!\n" + ex.Detail.SelectSingleNode("//description").InnerText); } catch (Exception ex) { throw new ESC_CRM_EX.getEntityException(ex.Message, entityName_, entityGuid); } }
public static int SortedLookup <T>(ref T searchSpace, int length, ref T value, Lookup lookup, KeyComparer <T> comparer = default) { return(SortedLookup(ref searchSpace, 0, length, ref value, lookup, comparer)); }