Exemplo n.º 1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                //get values from form
                string transactionAmountz = transactionAmount.Text;
                string customerAmountz = customerAmount.Text;

                //convert values
                double transactionAmount2 = Convert.ToDouble(transactionAmountz);
                double customerAmount2 = Convert.ToDouble(customerAmountz);
                double result = customerAmount2 - transactionAmount2;

                //class
                Change checking = new Change();

                //set accessor
                checking.setValues(result);
                results.Text += "<h1>Change</h1>";
                results.Text += "<div id='changeTotalDiv'><b>CHANGE AMOUNT = "+ result +"</b></div>";

                //get accessor display results
                results.Text += checking.getValues();

                form1.Visible = false;
                results.Visible = true;
               
            }
        }
    }
 public Change UpcastIfRequired(Change toUpcast)
 {
     if (toUpcast.Version == Change.LatestVersion) return toUpcast;
     if (!UpcasterExistsFor(toUpcast)) return toUpcast;
     
     return GetUpcaster(toUpcast).Upcast(toUpcast);
 }
Exemplo n.º 3
0
 public void AddChange(Change c)
 {
     if (!this.Changes.Contains(c)) {
         this.Changes.Add(c);
         if (this.OnChange != null) { this.OnChange(this, c); }
     }
 }
        private void Recurse(int amount, int index, Stack<Change> coins, Action<IEnumerable<Change>> emit)
        {
            if(amount == 0)
            {
                if(coins.Count!=0) emit(coins);
                return;
            }

            if(amount<0 || index<0) return;

            // It's the combination of solutions without the current coin : Recurse(amount, index - 1)
            // and the combination of the solutions minus the current amount and including the current coin
            Recurse(amount, index-1, coins, emit);

            if(m_Coins[index].Quantity>0)
            {
                var temp=m_Coins[index];
                m_Coins[index]=new Change(temp.Coin,Math.Max(0, temp.Quantity-1));

                coins.Push(new Change(m_Coins[index].Coin, 1));
                Recurse(amount-m_Coins[index].Coin, index, coins, emit);

                m_Coins[index]=temp;
                coins.Pop();
            }
        }
        /// <summary>
        /// Converts a given <see cref="T:XElement"/> into a <see cref="T:ChangeSetHistory"/>.
        /// </summary>
        /// <param name="element">The <see cref="T:XElement"/> to convert.</param>
        /// <returns>The newly created <see cref="T:ChangeSetHistory"/>.</returns>
        public ChangeSetHistory FromXElement(XElement element)
        {
            ChangeSetHistory history = new ChangeSetHistory();
            foreach (XElement changeSetElement in element.Nodes()) {
                ChangeSet changeSet = new ChangeSet();

                // Get the change set details
                foreach (XElement changeSetElementChild in changeSetElement.Nodes()) {
                    if (changeSetElementChild.Name.LocalName == "Applied") {
                        changeSet.Applied = DateTime.Parse(changeSetElementChild.Value);
                    } else if (changeSetElementChild.Name.LocalName == "Username") {
                        changeSet.Username = changeSetElementChild.Value;
                    } else if (changeSetElementChild.Name.LocalName == "Change") {
                        Change change = new Change();
                        foreach (XElement changeElement in changeSetElementChild.Nodes()) {
                            if (changeElement.Name.LocalName == "PropertyName") {
                                change.PropertyName = changeElement.Value;
                            } else if (changeElement.Name.LocalName == "OldValue") {
                                change.OldValue = changeElement.Value;
                            } else if (changeElement.Name.LocalName == "NewValue") {
                                change.NewValue = changeElement.Value;
                            }
                        }
                        changeSet.Changes.Add(change);
                    }
                }
                history.Append(changeSet);
            }
            return history;
        }
Exemplo n.º 6
0
        public void UpdateChanges()
        {
            _changes.Clear();

            var snapshot = _view.VisualSnapshot;
            var span = new SnapshotSpan(snapshot, 0, snapshot.Length);

            foreach (var tag in _aggregator.GetTags(span))
            {
                ITextBuffer buffer = tag.Span.BufferGraph.TopBuffer;
                SnapshotPoint? start_pos = tag.Span.Start.GetPoint(buffer, PositionAffinity.Successor);
                SnapshotPoint? end_pos = tag.Span.End.GetPoint(buffer, PositionAffinity.Predecessor);
                if (start_pos.HasValue && end_pos.HasValue)
                {
                    var change = new Change();
                    change.start_line = buffer.CurrentSnapshot.GetLineNumberFromPosition(start_pos.Value.Position);
                    change.end_line = buffer.CurrentSnapshot.GetLineNumberFromPosition(end_pos.Value.Position);
                    change.saved = !tag.Tag.ChangeTypes.HasFlag(ChangeTypes.ChangedSinceSaved);
                    _changes.Add(change);
                }
            }

            if (ChangesChanged != null)
                ChangesChanged(this, EventArgs.Empty);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:AclChangedEventArgs" /> class.
        /// </summary>
        /// <param name="entries">The entries that changed.</param>
        /// <param name="change">The change.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="entries"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="entries"/> is empty.</exception>
        public AclChangedEventArgs(AclEntry[] entries, Change change)
        {
            if(entries == null) throw new ArgumentNullException("entry");
            if(entries.Length == 0) throw new ArgumentException("Entries cannot be empty", "entries");

            this.entries = entries;
            this.change = change;
        }
Exemplo n.º 8
0
 /// <summary>
 /// constructor
 /// </summary>
 /// <param name="ChangingObject">changing object</param>
 /// <param name="ChangingPropertyName">changing property name pass "" if don't want </param>
 /// <param name="AutoAdd">pass true if you want to automatically push a change to undo or redo stack when desposing this object</param>
 /// <param name="UndoOrRedo">true = push change to undo stack when desposing  false = push change to redo stack when desposing</param>
 /// <param name="ChangeToAdd">change to auto push</param>
 public ObjectChanging(object ChangingObject,string ChangingPropertyName,bool AutoAdd=false,bool UndoOrRedo=true,Change ChangeToAdd=null)
 {
     URD.NowChangingObject = ChangingObject;
     if (ChangingPropertyName != "" && ChangingPropertyName!=null)
         URD.NowChangingPropertyName = ChangingPropertyName;
     _AutoAdd = AutoAdd;
     _UndoOrRedo = UndoOrRedo;
     _ChangeToAdd = ChangeToAdd;
 }
Exemplo n.º 9
0
        public void Remove()
        {
            var person = new Person("Person", 10);
            var update = new Change<Person, string>(ChangeReason.Remove, "Person", person);

            Assert.AreEqual("Person", update.Key);
            Assert.AreEqual(ChangeReason.Remove, update.Reason);
            Assert.AreEqual(person, update.Current);
            Assert.AreEqual(Optional.None<Person>(), update.Previous);
        }
        public void Add()
        {
            var person = new Person("Person", 10);
            var update = new Change<Person,Person>(ChangeReason.Add, person,person);

            Assert.AreEqual(person, update.Key);
            Assert.AreEqual(ChangeReason.Add, update.Reason);
            Assert.AreEqual(person, update.Current);
            Assert.AreEqual(Optional.None<Person>(), update.Previous);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:RecentChange" /> class.
 /// </summary>
 /// <param name="page">The page pame.</param>
 /// <param name="title">The page title.</param>
 /// <param name="messageSubject">The message subject (or <c>null</c>).</param>
 /// <param name="dateTime">The date/time.</param>
 /// <param name="user">The user.</param>
 /// <param name="change">The change.</param>
 /// <param name="descr">The description (optional).</param>
 public RecentChange(string page, string title, string messageSubject, DateTime dateTime, string user, Change change, string descr)
 {
     this.page = page;
     this.title = title;
     this.messageSubject = messageSubject;
     this.dateTime = dateTime;
     this.user = user;
     this.change = change;
     this.descr = descr;
 }
Exemplo n.º 12
0
 public ChangeViewModel(IParserFinder parserFinder, 
                        IRunnerFactory runnerFactory, 
                        String workingDirectory, 
                        Change change)
 {
     _parserFinder = parserFinder;
     _runnerFactory = runnerFactory;
     _workingDirectory = workingDirectory;
     _change = change;
 }
Exemplo n.º 13
0
		internal void Show(Change change)
		{
			if (change == null)
			{
				Clear();
				return;
			}
			var a = (change.ReferenceObject != null ? (change.ReferenceObject as Blob).RawData : new byte[0]);
			var b = (change.ComparedObject != null ? (change.ComparedObject as Blob).RawData : new byte[0]);
			Init(new Diff(a, b));
		}
Exemplo n.º 14
0
        public void Update()
        {
            var current = new Person("Person", 10);
            var previous = new Person("Person", 9);
            var update = new Change<Person, string>(ChangeReason.Update, "Person", current, previous);

            Assert.AreEqual("Person", update.Key);
            Assert.AreEqual(ChangeReason.Update, update.Reason);
            Assert.AreEqual(current, update.Current);
            Assert.IsTrue(update.Previous.HasValue);
            Assert.AreEqual(previous, update.Previous.Value);
        }
Exemplo n.º 15
0
    public IEnumerator Load(string objName, string mtlName, string pngName)
    {
        Debug.Log (" ------------------------------------------- " + objName + ", " + mtlName + ", " + pngName);
        c = GameObject.Find ("Canvas").GetComponent<Change> ();
        loading = true;
        if (objData != null && objData.gameObjects != null) {
            for (var i = 0; i < objData.gameObjects.Length; i++) {
                Destroy (objData.gameObjects[i]);
            }
        }
        if(!mtlName.Equals("") && !pngName.Equals("")) {
            objFileName = URL_API + objName;
            objData = ObjReader.use.ConvertFileAsync (objFileName, true, standardMaterial, mtlName, pngName);
        } else {
            objData = ObjReader.use.ConvertFileAsync (objFileName, true, standardMaterial);
        }
        objData = ObjReader.use.ConvertFileAsync (objFileName, true, standardMaterial);
        while (!objData.isDone) {
            loadingText = "Loading... " + (objData.progress*100).ToString("f0") + "%";
            if (Input.GetKeyDown (KeyCode.Escape)) {
                objData.Cancel();
                loadingText = "Cancelled download";
                loading = false;
                loadingText = "Error loading file";
                c.ExitPanel ();
                yield break;
            }
            yield return null;
        }
        loading = false;

        if (objData == null || objData.gameObjects == null) {
            loadingText = "Error loading file";
            c.ExitPanel ();
            yield return null;
            yield break;
        }

        //GameObject loadtext = GameObject.Find ("Canvas").transform.FindChild ("PanelPopupLoad").FindChild ("LoadText").gameObject;

        loadingText = "Import completed";
        GameObject objecLoad = GameObject.Find ("material0");
        GameObject model = GameObject.Find ("GameObjectModel").transform.FindChild("header").FindChild("default").gameObject;
        model.GetComponent<MeshFilter> ().mesh = objecLoad.GetComponent<MeshFilter> ().mesh;
        model.GetComponent<MeshRenderer> ().material = objecLoad.GetComponent<MeshRenderer> ().material;
        model.transform.position = new Vector3(model.transform.position.x,model.transform.position.y,model.transform.position.z);
        c.ExitPanel ();
        Destroy (objecLoad);
        objecLoad = GameObject.Find ("material0");
        if(objecLoad != null)
            Destroy (objecLoad);
        //FocusOnObjects();
    }
Exemplo n.º 16
0
		internal void Show(Change change)
		{
			if (change == null)
			{
				Clear();
				return;
			}
			var a = (change.ReferenceObject != null ? (change.ReferenceObject as Blob).RawData : new byte[0]);
			var b = (change.ComparedObject != null ? (change.ComparedObject as Blob).RawData : new byte[0]);
			a = (Diff.IsBinary(a)==true ? Encoding.ASCII.GetBytes("Binary content\nFile size: "+a.Length) : a);
			b = (Diff.IsBinary(b) == true ? Encoding.ASCII.GetBytes("Binary content\nFile size: " + b.Length) : b);
			Init(new Diff(a, b));
		}
Exemplo n.º 17
0
        public void Equality()
        {
            var a = new Change("file.txt", Change.StatusCode.Modified);
            Assert.Equal(a, a);

            var b = new Change("file.txt", Change.StatusCode.Modified);
            Assert.Equal(a, b);

            var c = new Change("file2.txt", Change.StatusCode.Modified);
            Assert.NotEqual(a, c);

            var d = new Change("fIlE.txt", Change.StatusCode.Modified);
            Assert.Equal(a, d);
        }
Exemplo n.º 18
0
        public void Track(string activityKey, string fromKey, string toKey, DateTime timestamp)
        {
            var activity = _repository.GetActivity(activityKey);
            var from = _repository.GetState(fromKey);
            var to = _repository.GetState(toKey);

            var change = new Change
            {
                Activity = activity,
                From = from,
                To = to,
                Timestamp = timestamp
            };

            _repository.Add(change);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Adds a new change.
        /// </summary>
        /// <param name="page">The page name.</param>
        /// <param name="title">The page title.</param>
        /// <param name="messageSubject">The message subject.</param>
        /// <param name="dateTime">The date/time.</param>
        /// <param name="user">The user.</param>
        /// <param name="change">The change.</param>
        /// <param name="descr">The description (optional).</param>
        public static void AddChange(string page, string title, string messageSubject, DateTime dateTime, string user, Change change, string descr)
        {
            RecentChange[] allChanges = GetAllChanges();
            if(allChanges.Length > 0) {
                RecentChange lastChange = allChanges[allChanges.Length - 1];
                if(lastChange.Page == page && lastChange.Title == title &&
                    lastChange.MessageSubject == messageSubject + "" &&
                    lastChange.User == user &&
                    lastChange.Change == change &&
                    (dateTime - lastChange.DateTime).TotalMinutes <= 60) {

                    // Skip this change
                    return;
                }
            }

            Settings.Provider.AddRecentChange(page, title, messageSubject, dateTime, user, change, descr);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Performs a greedy algorithm change algorithm over the available coins.
        /// NOTE: It is valid for the changeAvailable sequence to have null values to
        /// indicate the absence of change. This simplifies the backtracking algorithm
        /// </summary>
        /// <param name="changeRequired">The change we need to give</param>
        /// <param name="changeAvailable">The change available for the algorithm</param>
        /// <returns>The outcome of the vending action</returns>
        protected VendingResult Greedy(int changeRequired, IEnumerable<Change> changeAvailable)
        {
            if(changeRequired < 0) throw new ArgumentException("change required must be at least zero", "changeRequired");
            if(changeAvailable == null) throw new ArgumentNullException("changeAvailable");

            int outstandingChangeRequired = changeRequired;
            List<Change> changeToGive = new List<Change>();

            if(outstandingChangeRequired != 0)
            {
                foreach(Change change in changeAvailable)
                {
                    if(change == null) continue;

                    if(change.Denomination <= outstandingChangeRequired)
                    {
                        // We can use this denomination, work out how many we need
                        int quantityNeeded = Math.Min(change.Quantity, outstandingChangeRequired / change.Denomination);

                        // NOTE: Don't remove the change yet as this will invalidate the foreach enumeration
                        Change changeToReturn = new Change(change.Denomination, quantityNeeded);
                        changeToGive.Add(changeToReturn);

                        outstandingChangeRequired -= changeToReturn.TotalValue;

                        // Finished..?
                        if(outstandingChangeRequired == 0)
                        {
                            break;
                        }
                    }
                }
            }

            if(outstandingChangeRequired == 0)
            {
                return VendingResult.CreateSuccess(changeToGive);
            }
            else
            {
                return VendingResult.CreateFailed();
            }
        }
Exemplo n.º 21
0
        static bool TryRepresent(string value, string[] suffix, Change producer, out DateTime result)
        {
            result = DateTime.MinValue;
            foreach (var s in suffix)
            {
                if (!value.EndsWith(s, StringComparison.InvariantCultureIgnoreCase))
                {
                    continue;
                }
                var trimmed = value.Remove(value.Length - s.Length, s.Length).TrimEnd();
                float res;

                if (!float.TryParse(trimmed, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out res))
                {
                    continue;
                }
                result = producer(res, DateTime.Now);
                return true;
            }
            return false;
        }
        private int Count(int amount, int index)
        {
            if(amount==0) return 1;

            if(amount<0 || index<0) return 0;

            // It's the sum of the solutions without the current coin : Count(amount, index - 1)
            // plus the sum of the solutions minus the current amount and including the current coin
            int count1=Count(amount, index-1);
            int count2=0;

            if(m_Coins[index].Quantity>0)
            {
                var temp=m_Coins[index];
                m_Coins[index]=new Change(temp.Coin, Math.Max(0,temp.Quantity-1));

                count2=Count(amount-m_Coins[index].Coin, index);
                m_Coins[index]=temp;
            }

            return count1+count2;
        }
Exemplo n.º 23
0
        public static void RecordChangeInWebhookHistory(ClientContext cc, List changeList, Change change, ILogger log, string resourceId)
        {
            #region Grab the list used to write the webhook history
            // Ensure reference to the history list, create when not available
            List   historyList     = null;
            string historyListName = CloudConfigurationManager.GetSetting("HistoryListName");
            if (!string.IsNullOrEmpty(historyListName))
            {
                historyList = cc.Web.GetListByTitle(historyListName);
                if (historyList == null)
                {
                    historyList = cc.Web.CreateList(ListTemplateType.GenericList, historyListName, false);
                    cc.ExecuteQueryRetry();
                }
            }
            #endregion

            if (historyList == null)
            {
                return;
            }
            try
            {
                ListItemCreationInformation newItem = new ListItemCreationInformation();
                ListItem item = historyList.AddItem(newItem);
                item["Title"] = $"List {changeList.Title} had a Change of type \"{change.ChangeType.ToString()}\" on the item with Id {(change as ChangeItem).ItemId}. Change Token: {(change as ChangeItem).ChangeToken.StringValue}";
                item.Update();
                cc.ExecuteQueryRetry();
            }
            catch (Exception ex)
            {
                log.LogError($"ERROR: {ex.Message}");
            }
        }
Exemplo n.º 24
0
 protected void OnChange() => Change?.Invoke();
 internal AreaChangeEntry(string sourcePath, string targetPath, Change change)
     : base("Area", sourcePath, targetPath, change)
 {
 }
Exemplo n.º 26
0
        public void Commit(IStorageTracer tracer)
        {
            if (_currentPosition == -1)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace("No storage changes to commit");
                }
                return;
            }

            if (_logger.IsTrace)
            {
                _logger.Trace("Committing storage changes");
            }

            if (_changes[_currentPosition] == null)
            {
                throw new InvalidOperationException($"Change at current position {_currentPosition} was null when commiting {nameof(StorageProvider)}");
            }

            if (_changes[_currentPosition + 1] != null)
            {
                throw new InvalidOperationException($"Change after current position ({_currentPosition} + 1) was not null when commiting {nameof(StorageProvider)}");
            }

            HashSet <Address> toUpdateRoots = new HashSet <Address>();

            bool isTracing = tracer != null;
            Dictionary <StorageAddress, ChangeTrace> trace = null;

            if (isTracing)
            {
                trace = new Dictionary <StorageAddress, ChangeTrace>();
            }

            for (int i = 0; i <= _currentPosition; i++)
            {
                Change change = _changes[_currentPosition - i];
                if (!isTracing && change.ChangeType == ChangeType.JustCache)
                {
                    continue;
                }

                if (_committedThisRound.Contains(change.StorageAddress))
                {
                    if (isTracing && change.ChangeType == ChangeType.JustCache)
                    {
                        trace[change.StorageAddress] = new ChangeTrace(change.Value, trace[change.StorageAddress].After);
                    }

                    continue;
                }

//                if (_destructedStorages.ContainsKey(change.StorageAddress.Address))
//                {
//                    if (_destructedStorages[change.StorageAddress.Address].ChangeIndex > _currentPosition - i)
//                    {
//                        continue;
//                    }
//                }

                _committedThisRound.Add(change.StorageAddress);

                if (change.ChangeType == ChangeType.Destroy)
                {
                    continue;
                }

                int forAssertion = _intraBlockCache[change.StorageAddress].Pop();
                if (forAssertion != _currentPosition - i)
                {
                    throw new InvalidOperationException($"Expected checked value {forAssertion} to be equal to {_currentPosition} - {i}");
                }

                switch (change.ChangeType)
                {
                case ChangeType.Destroy:
                    break;

                case ChangeType.JustCache:
                    break;

                case ChangeType.Update:
                    if (_logger.IsTrace)
                    {
                        _logger.Trace($"  Update {change.StorageAddress.Address}_{change.StorageAddress.Index} V = {change.Value.ToHexString(true)}");
                    }

                    StorageTree tree = GetOrCreateStorage(change.StorageAddress.Address);
                    Metrics.StorageTreeWrites++;
                    toUpdateRoots.Add(change.StorageAddress.Address);
                    tree.Set(change.StorageAddress.Index, change.Value);
                    if (isTracing)
                    {
                        trace[change.StorageAddress] = new ChangeTrace(change.Value);
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            foreach (Address address in toUpdateRoots)
            {
                // since the accounts could be empty accounts that are removing (EIP-158)
                if (_stateProvider.AccountExists(address))
                {
                    Keccak root = RecalculateRootHash(address);
                    _stateProvider.UpdateStorageRoot(address, root);
                }
            }

            Resettable <Change> .Reset(ref _changes, ref _capacity, ref _currentPosition, StartCapacity);

            _committedThisRound.Reset();
            _intraBlockCache.Reset();
            _originalValues.Reset();
//            _destructedStorages.Clear();

            if (isTracing)
            {
                ReportChanges(tracer, trace);
            }
        }
 private async Task DocumentChanged(Change change)
 {
     UpdateTree();
 }
Exemplo n.º 28
0
        private void addTransformer(Dictionary <int, Func <TNode, Scope, TNode> > transformers, Change change)
        {
            var transform = change.Transform;

            Func <TNode, Scope, TNode> existing;

            if (transformers.TryGetValue(change.ID, out existing))
            {
                var newTransform = transform;
                transform = (node, scope) =>
                {
                    var result = existing(node, scope);
                    return(newTransform(result, scope));
                };
            }

            transformers[change.ID] = transform;
        }
Exemplo n.º 29
0
        private void addTransformer(Dictionary <int, Func <TNode, TNode, TModel, Scope, TNode> > transformers, Change change)
        {
            var transform = change.SemanticalTransform;

            if (transform == null)
            {
                Debug.Assert(change.Transform != null);
                transform = (oldNode, newNode, model, scope) => change.Transform(oldNode, scope);
            }

            Func <TNode, TNode, TModel, Scope, TNode> existing;

            if (transformers.TryGetValue(change.ID, out existing))
            {
                var newTransform = transform;
                transform = (oldNode, newNode, model, scope) =>
                {
                    var result = existing(oldNode, newNode, model, scope);
                    return(newTransform(oldNode, result, model, scope));
                };
            }

            transformers[change.ID] = transform;
        }
Exemplo n.º 30
0
 private void addString(Change change)
 {
     jsonString.Append("{'changeType':'" + change.ChangeType + "','name':'" + change.Name + "','patientID':'"
                       + change.PatientId + "','numVisits':'" + change.NumVisits + "'},");
 }
Exemplo n.º 31
0
 public PlayerChangedEventArgs(Change registeredChange, int currentNumberOfPlayers)
 {
     RegisteredChange       = registeredChange;
     CurrentNumberOfPlayers = currentNumberOfPlayers;
 }
Exemplo n.º 32
0
 /// <summary>
 /// Adds a new change.
 /// </summary>
 /// <param name="wiki">The wiki.</param>
 /// <param name="page">The page name.</param>
 /// <param name="title">The page title.</param>
 /// <param name="messageSubject">The message subject.</param>
 /// <param name="dateTime">The date/time.</param>
 /// <param name="user">The user.</param>
 /// <param name="change">The change.</param>
 /// <param name="descr">The description (optional).</param>
 public static void AddChange(string wiki, string page, string title, string messageSubject, DateTime dateTime, string user, Change change, string descr)
 {
     RecentChange[] allChanges = GetAllChanges(wiki);
     if (allChanges.Length > 0)
     {
         RecentChange lastChange = allChanges[allChanges.Length - 1];
         if (lastChange.Page == page && lastChange.Title == title &&
             lastChange.MessageSubject == messageSubject + "" &&
             lastChange.User == user &&
             lastChange.Change == change &&
             (dateTime - lastChange.DateTime).TotalMinutes <= 60)
         {
             // Skip this change
             return;
         }
     }
     Settings.GetProvider(wiki).AddRecentChange(page, title, messageSubject, dateTime, user, change, descr);
 }
        /// <summary>
        /// Used to modify recordset with value from api gateway code deploy in another account.
        /// </summary>
        /// <param name="jobEvent">CodePipeline event.</param>
        /// <param name="context">Lambda Context</param>
        /// <returns>Job success of the Lambda</returns>
        public async Task <AmazonWebServiceResponse> UpdateApiGatewayAliasRecordSet(CodePipelineJobEvent jobEvent, ILambdaContext context)
        {
            var jobId = jobEvent.CodePipelineJob.Id;

            context.Logger.LogLine($"JobId: {jobId}");

            using (var codePipelineClient = new AmazonCodePipelineClient())
                using (var s3Client = new AmazonS3Client())
                    using (var dnsClient = new AmazonRoute53Client())
                    {
                        // Prep the user parameters
                        var userParameters = jobEvent.CodePipelineJob.Data.ActionConfiguration.Configuration["UserParameters"];
                        context.Logger.LogLine("UserParameters:");
                        context.Logger.LogLine(userParameters);
                        var paramDict = JsonConvert.DeserializeObject <Dictionary <string, string> >(userParameters);

                        try
                        {
                            DnsSettings dnsSettings = null;

                            // Get the first (only) input artifact
                            var artifact           = jobEvent.CodePipelineJob.Data.InputArtifacts.First();
                            var artifactBucketName = artifact.Location.S3Location.BucketName;
                            var artifactBucketKey  = artifact.Location.S3Location.ObjectKey;

                            // Unzip and get json
                            using (var getResponse = await s3Client.GetObjectAsync(artifactBucketName, artifactBucketKey))
                            {
                                var memoryStream = new MemoryStream();
                                using (var objectStream = getResponse.ResponseStream)
                                {
                                    objectStream.CopyTo(memoryStream);
                                }


                                var searchFile = paramDict["DnsJson"];
                                context.Logger.LogLine("Unziping artifact");
                                context.Logger.LogLine($"Searching for {searchFile}");
                                using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Read))
                                {
                                    foreach (var entry in archive.Entries)
                                    {
                                        var fileName = entry.Name;
                                        context.Logger.LogLine("Checking File: " + entry.Name);

                                        if (searchFile == fileName)
                                        {
                                            using (var fileStream = entry.Open())
                                                using (var streamReader = new StreamReader(fileStream))
                                                {
                                                    var dnsJson = await streamReader.ReadToEndAsync();

                                                    dnsSettings = JsonConvert.DeserializeObject <DnsSettings>(dnsJson);
                                                }

                                            break;
                                        }
                                    }
                                }
                            }

                            // Get the hosted zones in the tools region
                            context.Logger.LogLine($"Searching for {dnsSettings.HostedZoneLookupDomainName}");
                            var hostedZones = await dnsClient.ListHostedZonesAsync();

                            var myHostedZone = hostedZones.HostedZones.FirstOrDefault(z => z.Name == dnsSettings.HostedZoneLookupDomainName);
                            if (myHostedZone == null)
                            {
                                var noZoneMessage = $"Hosted Zone {dnsSettings.HostedZoneLookupDomainName} could not be found";
                                context.Logger.LogLine(noZoneMessage);
                                var failureDetails = new FailureDetails
                                {
                                    Message = noZoneMessage,
                                    Type    = FailureType.ConfigurationError
                                };
                                return(await codePipelineClient.PutJobFailureResultAsync(jobId, failureDetails));
                            }

                            // The record set we need to create
                            var recordSet = new ResourceRecordSet
                            {
                                Name            = dnsSettings.WebApiDnsDomain,
                                Type            = RRType.A,
                                ResourceRecords = new List <ResourceRecord> {
                                    new ResourceRecord {
                                        Value = $"ALIAS {dnsSettings.RegionalDomainName}"
                                    }
                                }
                            };
                            var rsChange = new Change
                            {
                                Action            = ChangeAction.UPSERT,
                                ResourceRecordSet = recordSet
                            };
                            var rsChangeBatch = new ChangeBatch
                            {
                                Changes = new List <Change> {
                                    rsChange
                                }
                            };


                            // Create/Update the recordset
                            var changeDnsRequest = new ChangeResourceRecordSetsRequest
                            {
                                ChangeBatch  = rsChangeBatch,
                                HostedZoneId = myHostedZone.Id
                            };
                            var changeResponse = await dnsClient.ChangeResourceRecordSetsAsync(changeDnsRequest);

                            // Log and send the success response
                            context.Logger.LogLine($"Request Id {changeResponse.ChangeInfo.Id} submitted");
                            context.Logger.LogLine($"{dnsSettings.WebApiDnsDomain} => A ALIAS {dnsSettings.RegionalDomainName}");
                            var successResultRequest = new PutJobSuccessResultRequest
                            {
                                JobId = jobId
                            };
                            return(await codePipelineClient.PutJobSuccessResultAsync(successResultRequest));
                        }
                        catch (Exception ex)
                        {
                            // Send the failure response and log
                            return(await DoException(codePipelineClient, ex, jobId, context));
                        }
                    }
        }
Exemplo n.º 34
0
 public static Change CreateChange(int changeset, string path)
 {
     Change change = new Change();
     change.Changeset = changeset;
     change.Path = path;
     return change;
 }
Exemplo n.º 35
0
        /// <summary>
        /// Generates a new fuzzed file, returns a string representing the path to the generated file.
        /// </summary>
        /// <returns></returns>
        public override string Next()
        {
            this.Changes.Clear();
            string testFile = this.GetFileName();
            FileStream fuzzedFile = new FileStream(testFile, FileMode.Create, FileAccess.Write);

            this.BaseFileStream.Position = 0;
            this.BaseFileStream.CopyTo(fuzzedFile);
            fuzzedFile.Flush();

            Change change = new Change();
            change.CurrentValue = new byte[(int)this.sizes[this.sizeCount]];
            change.FuzzModificationByte = this.modificationValues[this.modificationValueCount];
            change.FuzzModificationOperation = this.modifications[this.modificationCount];
            change.Offset = this.currentPosition;

            this.BaseFileStream.Position = this.currentPosition;
            this.BaseFileStream.Read(change.CurrentValue, 0, change.CurrentValue.Length);
            byte[] temp = new byte[change.CurrentValue.Length];

            for (int index = 0; index < temp.Length; ++index)
                temp[index] = (byte)this.modificationValues[this.modificationValueCount];

            change.NewValue = this.Modify(change.CurrentValue, temp, this.GetOperation(change.FuzzModificationOperation));
            fuzzedFile.Position = this.currentPosition;
            fuzzedFile.Write(change.NewValue, 0, change.NewValue.Length);
            fuzzedFile.Close();
            this.Changes.Add(change);
            this.currentPosition += (int)this.increments[this.incrementCount];

            if (currentPosition > this.endingByte)
            {
                this.currentPosition = this.startingByte;
                if(++this.modificationValueCount >= this.modificationValues.Count)
                {
                    this.modificationValueCount = 0;
                    if(++this.modificationCount >= this.modifications.Count)
                    {
                        this.modificationCount = 0;
                        if (++this.sizeCount >= this.sizes.Count)
                        {
                            this.sizeCount = 0;
                            if (++this.incrementCount >= this.increments.Count)
                                this.incrementCount = 0;
                        }
                    }
                }
            }

            return testFile;
        }
Exemplo n.º 36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object"/> class.
 /// </summary>
 public UpdateWithFilter(bool isMatch, Change <TObject, TKey> change)
 {
     IsMatch = isMatch;
     Change  = change;
 }
Exemplo n.º 37
0
        /// <summary>
        /// Atomically update the ResourceRecordSet collection.
        /// Documentation https://developers.google.com/dns/v2beta1/reference/changes/create
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated dns service.</param>
        /// <param name="project">Identifies the project addressed by this request.</param>
        /// <param name="managedZone">Identifies the managed zone addressed by this request. Can be the managed zone name or id.</param>
        /// <param name="body">A valid dns v2beta1 body.</param>
        /// <param name="optional">Optional paramaters.</param>        /// <returns>ChangeResponse</returns>
        public static Change Create(dnsService service, string project, string managedZone, Change body, ChangesCreateOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (project == null)
                {
                    throw new ArgumentNullException(project);
                }
                if (managedZone == null)
                {
                    throw new ArgumentNullException(managedZone);
                }

                // Building the initial request.
                var request = service.Changes.Create(body, project, managedZone);

                // Applying optional parameters to the request.
                request = (ChangesResource.CreateRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Changes.Create failed.", ex);
            }
        }
Exemplo n.º 38
0
        // Internal action methods Sale will forward requests to
        // - As the base class for all states, any common logic can be included here
        // - To keep the core logic encapsulated in the Sale class, these methods call internal methods on the sale class

        internal virtual ActionResult AddChange(Change change)
        {
            return(Sale.AddChangeInternal(change));
        }
Exemplo n.º 39
0
        /// Output method
        protected void Output(TextWriter writer, string[] tokens, FileSystemWatcher source, Change type, string name)
        {
            foreach (var token in tokens)
            {
                var path = Path.Combine(source.Path, name);
                switch (token[0])
                {
                case 'e':
                    writer.Write(type);
                    if (Directory.Exists(path))
                    {
                        writer.Write(",ISDIR");
                    }
                    break;

                case 'f': writer.Write(Path.GetFileName(path)); break;

                case 'w': writer.Write(Path.Combine(source.Path, Path.GetDirectoryName(path))); break;

                case 'T': writer.Write(DateTime.Now); break;

                default: writer.Write(token); break;
                }
            }
            writer.WriteLine();
        }
Exemplo n.º 40
0
 public void Advise(Lifetime lifetime, Action <R> handler) => Change.Advise(lifetime, handler);
Exemplo n.º 41
0
        public void Restore(int snapshot)
        {
            if (_logger.IsTrace)
            {
                _logger.Trace($"Restoring storage snapshot {snapshot}");
            }

            if (snapshot > _currentPosition)
            {
                throw new InvalidOperationException($"{nameof(StorageProvider)} tried to restore snapshot {snapshot} beyond current position {_currentPosition}");
            }

            if (snapshot == _currentPosition)
            {
                return;
            }

            List <Change> keptInCache = new List <Change>();

            for (int i = 0; i < _currentPosition - snapshot; i++)
            {
                Change change = _changes[_currentPosition - i];
                if (_intraBlockCache[change.StorageAddress].Count == 1)
                {
                    if (_changes[_intraBlockCache[change.StorageAddress].Peek()].ChangeType == ChangeType.JustCache)
                    {
                        int actualPosition = _intraBlockCache[change.StorageAddress].Pop();
                        if (actualPosition != _currentPosition - i)
                        {
                            throw new InvalidOperationException($"Expected actual position {actualPosition} to be equal to {_currentPosition} - {i}");
                        }

                        keptInCache.Add(change);
                        _changes[actualPosition] = null;
                        continue;
                    }
                }

                int forAssertion = _intraBlockCache[change.StorageAddress].Pop();
                if (forAssertion != _currentPosition - i)
                {
                    throw new InvalidOperationException($"Expected checked value {forAssertion} to be equal to {_currentPosition} - {i}");
                }

//                if (change.ChangeType == ChangeType.Destroy)
//                {
//                    _storages[change.StorageAddress.Address] = _destructedStorages[change.StorageAddress.Address].Storage;
//                    _destructedStorages.Remove(change.StorageAddress.Address);
//                }

                _changes[_currentPosition - i] = null;

                if (_intraBlockCache[change.StorageAddress].Count == 0)
                {
                    _intraBlockCache.Remove(change.StorageAddress);
                }
            }

            _currentPosition = snapshot;
            foreach (Change kept in keptInCache)
            {
                _currentPosition++;
                _changes[_currentPosition] = kept;
                _intraBlockCache[kept.StorageAddress].Push(_currentPosition);
            }
        }
Exemplo n.º 42
0
        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            //PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            int budgetID = GetQueryIntValue("id");

            if (budgetID > 0)
            {
                Infobasis.Data.DataEntity.BudgetTemplate data = DB.BudgetTemplates
                                                                .Where(u => u.ID == budgetID).FirstOrDefault();
                if (data == null)
                {
                    // 参数错误,首先弹出Alert对话框然后关闭弹出窗口
                    Alert.Show("参数错误!", String.Empty, ActiveWindow.GetHideReference());
                    return;
                }
                data.Code         = tbxCode.Text.Trim();
                data.Name         = tbxName.Text;
                data.DisplayOrder = Change.ToInt(tbxDisplayOrder.Text);

                if (Change.ToInt(DropDownProvince.SelectedValue) > 0)
                {
                    data.ProvinceID   = Change.ToInt(DropDownProvince.SelectedValue);
                    data.ProvinceName = DropDownProvince.SelectedText;
                }

                if (Change.ToInt(DropDownBoxBudgetType.SelectedValue) > 0)
                {
                    data.BudgetTypeID   = Change.ToInt(DropDownBoxBudgetType.SelectedValue);
                    data.BudgetTypeName = DropDownBoxBudgetType.SelectedText;
                }

                data.IsActive             = tbxIsActive.Checked;
                data.BudgetTemplateStatus = tbxIsActive.Checked ? BudgetTemplateStatus.Enabled : BudgetTemplateStatus.Disabled;
                data.LastUpdateDatetime   = DateTime.Now;
                data.Remark           = tbxRemark.Text;
                data.LastUpdateByID   = UserInfo.Current.ID;
                data.LastUpdateByName = UserInfo.Current.ChineseName;
            }
            else
            {
                Infobasis.Data.DataEntity.BudgetTemplate data = new Infobasis.Data.DataEntity.BudgetTemplate()
                {
                    CreateDatetime       = DateTime.Now,
                    Code                 = tbxCode.Text.Trim(),
                    Name                 = tbxName.Text,
                    Remark               = tbxRemark.Text,
                    BudgetTemplateStatus = Infobasis.Data.DataEntity.BudgetTemplateStatus.Enabled
                };

                data.DisplayOrder = Change.ToInt(tbxDisplayOrder.Text);

                if (Change.ToInt(DropDownProvince.SelectedValue) > 0)
                {
                    data.ProvinceID   = Change.ToInt(DropDownProvince.SelectedValue);
                    data.ProvinceName = DropDownProvince.SelectedText;
                }

                if (Change.ToInt(DropDownBoxBudgetType.SelectedValue) > 0)
                {
                    data.BudgetTypeID   = Change.ToInt(DropDownBoxBudgetType.SelectedValue);
                    data.BudgetTypeName = DropDownBoxBudgetType.Text;
                }

                data.IsActive             = tbxIsActive.Checked;
                data.BudgetTemplateStatus = tbxIsActive.Checked ? BudgetTemplateStatus.Enabled : BudgetTemplateStatus.Disabled;

                DB.BudgetTemplates.Add(data);
            }

            SaveChanges();
            ShowNotify("添加成功");
            PageContext.RegisterStartupScript(ActiveWindow.GetHideRefreshReference());
        }
Exemplo n.º 43
0
        public async Task <ChangeResourceRecordSetsResponse> ChangeResourceRecordSetsAsync(string zoneId, ResourceRecordSet resourceRecordSet, Change change)
        {
            var sw       = Stopwatch.StartNew();
            int _timeout = 5 * 60 * 10000;
            PriorRequestNotCompleteException exception = null;

            do
            {
                try
                {
                    return(await _stopWatch.TimeLock(_rateLimit, _locker, async() =>
                    {
                        return await _client.ChangeResourceRecordSetsAsync(
                            new ChangeResourceRecordSetsRequest()
                        {
                            ChangeBatch = new ChangeBatch()
                            {
                                Changes = new List <Change>()
                                {
                                    change
                                }
                            },
                            HostedZoneId = zoneId
                        }).EnsureSuccessAsync();
                    }));
                }
                catch (PriorRequestNotCompleteException ex) //requires client reconnection
                {
                    exception = ex;
                    await Task.Delay(5000);

                    _locker.Lock(() =>
                    {
                        Initialize();
                    });
                }
            } while (sw.ElapsedMilliseconds < _timeout);

            throw exception;
        }
Exemplo n.º 44
0
        /// <summary>
        /// Method doing actually something with the changes obtained via the web hook notification.
        /// In this demo we're just logging to a list, in your implementation you do what you need to do :-)
        /// </summary>
        private static void DoWork(ClientContext approvalCC, List approvalList, ClientContext notificationCC, List notificationSourceList, Change change, NotificationModel notification, TraceWriter log)
        {
            try
            {
                log.Info("Loading source item with id: " + ((ChangeItem)change).ItemId);
                log.Info("Notification Source List name:" + notificationSourceList.Title + " " + notificationSourceList.ParentWebUrl);
                ListItem li = notificationSourceList.GetItemById(((ChangeItem)change).ItemId);
                notificationCC.Load(li);
                notificationCC.ExecuteQuery();
                log.Info("Loaded source item with ID: " + ((ChangeItem)change).ItemId);
                // Only add approval item if in PEnding approval status
                if (li.FieldValues["_ModerationStatus"].ToString() == "2")
                {
                    var changeItem = change as ChangeItem;

                    CamlQuery camlQuery = new CamlQuery();
                    camlQuery.ViewXml  = "<View><Query><Where><And><And>";
                    camlQuery.ViewXml += $"<Eq><FieldRef Name='ClientState' /><Value Type='Text'>{notification.ClientState}</Value></Eq>";
                    camlQuery.ViewXml += $"<Eq><FieldRef Name='Resource' /><Value Type='Text'>{notification.Resource}</Value></Eq></And>";
                    camlQuery.ViewXml += $"<And><Eq><FieldRef Name='ItemId' /><Value Type='Text'>{changeItem.ItemId}</Value></Eq>";
                    camlQuery.ViewXml += $"<Eq><FieldRef Name='ActivityId' /><Value Type='Text'>{changeItem.UniqueId}</Value></Eq>";
                    camlQuery.ViewXml += $"</And></And></Where></Query></View>";

                    ListItemCollection matchingItems = approvalList.GetItems(camlQuery);
                    approvalCC.Load(matchingItems);
                    approvalCC.ExecuteQuery();

                    if (matchingItems.Count() == 0)
                    {
                        ListItemCreationInformation newItem = new ListItemCreationInformation();
                        ListItem item   = approvalList.AddItem(newItem);
                        var      editor = li.FieldValues["Editor"] as FieldUserValue;

                        item["Title"]              = string.Format("List {0} had a Change of type \"{1}\" on the item with Id {2}.", notificationSourceList.Title, change.ChangeType.ToString(), (change as ChangeItem).ItemId);
                        item["ClientState"]        = notification.ClientState;
                        item["SubscriptionId"]     = notification.SubscriptionId;
                        item["ExpirationDateTime"] = notification.ExpirationDateTime;
                        item["Resource"]           = notification.Resource;
                        item["TenantId"]           = notification.TenantId;
                        item["SiteUrl"]            = notification.SiteUrl;
                        item["WebId"]              = notification.WebId;
                        item["ItemId"]             = changeItem.ItemId;
                        item["ActivityId"]         = changeItem.UniqueId;
                        item["EditorEmail"]        = editor.Email;
                        item["Activity"]           = change.ChangeType.ToString();
                        item.Update();
                        approvalCC.ExecuteQueryRetry();
                    }
                }
            }
            catch (Exception exp)
            {
                log.Error("Unable to log approval: " + exp.Message + ":::" + exp.StackTrace);
            }
        }
 private void changeChange_execute(Change change) //Change preferences
 {
     Data.Instance.ChangeSettings(change.Name);
 }
 protected NodeChangeEntry(string source, string sourcePath, string targetPath, Change change)
     : base("AreasOrIteration", sourcePath, targetPath, change.ToString())
 {
 }
Exemplo n.º 47
0
 /// <summary>Translates to.</summary>
 /// <param name="idiom">The idiom.</param>
 public static void TranslateTo(Idiom idiom)
 {
     Change.Invoke(null, idiom);
 }
 public override string ToString()
 {
     return($"[{Change.ToString()}] {AttOriginId}/{Path.GetFileName(FilePath)}");
 }
 IChangeUpcaster GetUpcaster(Change toUpcast)
 {
     return upcasters.Single(u => u.ChangeType == toUpcast.GetType());
 }
Exemplo n.º 50
0
        private Change compareGeometry(RevitElement current, RevitElement previous)
        {
            // try to do a comparison based on bounding boxes and locations...
            // this is CERTAINLY imperfect

            double tolerance = 0.0006;  // decimal feet - 1/128"?

            double dist = -1;

            if (didMove(current.LocationPoint, previous.LocationPoint, tolerance, out dist))
            {
                Change c = new Change()
                {
                    ChangeType        = Change.ChangeTypeEnum.Move,
                    Category          = current.Category,
                    ElementId         = current.ElementId,
                    UniqueId          = current.UniqueId,
                    ChangeDescription = "Location Offset " + dist + " ft."
                };
                if (current.BoundingBox != null)
                {
                    c.BoundingBoxDescription = Utilities.RevitUtils.SerializeBoundingBox(current.BoundingBox);
                }

                // we want to check if the LocationPoint2 also moved?
                if ((current.LocationPoint2 != null) && (previous.LocationPoint2 != null) &&
                    (didMove(current.LocationPoint2, previous.LocationPoint2, tolerance, out dist)))
                {
                    // both moved. record both.
                    c.MoveDescription = Utilities.RevitUtils.SerializeDoubleMove(previous.LocationPoint, current.LocationPoint,
                                                                                 previous.LocationPoint2, current.LocationPoint2);
                }
                else
                {
                    // single move.
                    c.MoveDescription = Utilities.RevitUtils.SerializeMove(previous.LocationPoint, current.LocationPoint);
                }

                return(c);
            }

            // only a move of the second one...
            if ((current.LocationPoint2 != null) && (previous.LocationPoint2 != null) &&
                didMove(previous.LocationPoint2, current.LocationPoint2, tolerance, out dist))
            {
                Change c = new Change()
                {
                    ChangeType        = Change.ChangeTypeEnum.Move,
                    Category          = current.Category,
                    ElementId         = current.ElementId,
                    UniqueId          = current.UniqueId,
                    ChangeDescription = "Location Offset " + dist + " ft.",
                    Level             = current.Level
                };
                if (current.BoundingBox != null)
                {
                    c.BoundingBoxDescription = Utilities.RevitUtils.SerializeBoundingBox(current.BoundingBox);
                }

                // only one side moved though...
                c.MoveDescription = Utilities.RevitUtils.SerializeMove(previous.LocationPoint2, current.LocationPoint2);
                return(c);
            }

            // check rotation
            float rotationTolerance = 0.0349f; // two degrees?
            float rotationDiff      = current.Rotation - previous.Rotation;

            if (Math.Abs(rotationDiff) > rotationTolerance)
            {
                Change c = new Change()
                {
                    ChangeType        = Change.ChangeTypeEnum.Rotate,
                    Category          = current.Category,
                    ElementId         = current.ElementId,
                    UniqueId          = current.UniqueId,
                    ChangeDescription = "Rotation: " + ((rotationDiff) * 180.0 / Math.PI).ToString("F2") + " degrees",
                    Level             = current.Level
                };
                if (current.BoundingBox != null)
                {
                    c.BoundingBoxDescription = Utilities.RevitUtils.SerializeBoundingBox(current.BoundingBox);
                }
                c.RotationDescription = Utilities.RevitUtils.SerializeRotation(current.LocationPoint, XYZ.BasisZ, rotationDiff);

                return(c);
            }

            // now the bounding box...
            if ((current.BoundingBox != null) && (previous.BoundingBox != null))
            {
                double maxDist = Math.Max(current.BoundingBox.Min.DistanceTo(previous.BoundingBox.Min),
                                          current.BoundingBox.Max.DistanceTo(previous.BoundingBox.Max));

                if (maxDist > tolerance)
                {
                    Change c = new Change()
                    {
                        ChangeType        = Change.ChangeTypeEnum.GeometryChange,
                        Category          = current.Category,
                        ElementId         = current.ElementId,
                        UniqueId          = current.UniqueId,
                        ChangeDescription = "BoundingBox Offset " + maxDist + " ft.",
                    };
                    c.BoundingBoxDescription = Utilities.RevitUtils.SerializeBoundingBox(current.BoundingBox);
                    return(c);
                }
            }

            return(null);
        }
 private void OnNext(Change<JObject> obj, ref int onNext)
 {
     Console.WriteLine("On Next");
     obj.Dump();
     onNext++;
 }
Exemplo n.º 52
0
        private void ApplyChange(Change change)
        {
            // Zero-change
            if (change.Parameter == ModificationParameter.None || Mathf.Abs(change.Amount) < 1e-6)
            {
                return;
            }

            var oldHp      = _hp;
            var hpFraction = _hp / MaxHealth;

            switch (change.Parameter)
            {
            case ModificationParameter.HpFlat:
                _hp = Mathf.Min(_hp + change.Amount, MaxHealth);
                break;

            case ModificationParameter.HpMult:
                _hp = Mathf.Min(_hp * (1 + change.Amount), MaxHealth);
                break;

            case ModificationParameter.MaxHpFlat:
                _maxHpFlatModSum += change.Amount;
                _hp = hpFraction * MaxHealth;
                break;

            case ModificationParameter.MaxHpMult:
                _maxHpMultModSum += change.Amount;
                _hp = hpFraction * MaxHealth;
                break;

            case ModificationParameter.DmgFlat:
                _dmgFlatModSum += change.Amount;
                break;

            case ModificationParameter.DmgMult:
                _dmgMultModSum += change.Amount;
                break;

            case ModificationParameter.EvasionChanceFlat:
                _evasionModMulProduct *= change.Amount;
                break;

            case ModificationParameter.CritChanceFlat:
                throw new NotImplementedException();

            case ModificationParameter.SpeedFlat:
                _speedFlatModSum += change.Amount;
                break;

            case ModificationParameter.SpeedMult:
                _speedMultModSum += change.Amount;
                break;

            case ModificationParameter.SizeFlat:
                _sizeFlatModSum += change.Amount;
                break;

            case ModificationParameter.SizeMult:
                _sizeMultModSum += change.Amount;
                break;

            case ModificationParameter.SpellStacksFlat:
                _assFlatModSum += change.Amount;
                break;

            case ModificationParameter.SpellDamageAmpFlat:
                _spellDamageAmpFlatModSum += change.Amount;
                break;

            case ModificationParameter.Stun:
                _stunScale += change.Amount;
                break;
            }

            switch (change.Parameter)
            {
            // Update transform scale if changed
            case ModificationParameter.SizeFlat:
            case ModificationParameter.SizeMult:
                transform.localScale = _baseScale * Size;
                break;

            // Process hp change events
            case ModificationParameter.HpFlat:
            case ModificationParameter.HpMult:
            case ModificationParameter.MaxHpMult:
            case ModificationParameter.MaxHpFlat:
                // If taking damage
                if (_hp < oldHp)
                {
                    if (_hp <= 0f)
                    {
                        HandleDeath();
                    }
                    else
                    {
                        _animationController.PlayHitImpactAnimation();
                    }
                }

                HealthChanged?.Invoke(_hp);
                break;
            }
        }
Exemplo n.º 53
0
 public void AddToChanges(Change change)
 {
     base.AddObject("Changes", change);
 }
Exemplo n.º 54
0
        private IEnumerable <TurtleData> CompileQueue(List <ParsedData> data, CancellationToken token)
        {
            List <TurtleData> interData = new List <TurtleData>();
            ParsedData        current;

            UpdateVars(From);
            UpdateVars(To);

            int FromInt   = From.Evaluate();
            int ToInt     = To.Evaluate();
            int ChangeInt = 1;

            if (Operator == OperatorType.MinusEquals || Operator == OperatorType.PlusEquals)
            {
                UpdateVars(Change);
                ChangeInt = Change.Evaluate();
            }

            void Exec(int i)
            {
                token.ThrowIfCancellationRequested();
                for (int counter = 0; counter < data.Count; counter++)
                {
                    current = data[counter];

                    current.Variables[LoopVariable] = i;
                    foreach (var item in Variables)
                    {
                        current.Variables[item.Key] = item.Value;
                    }

                    if (current.IsBlock)
                    {
                        interData.AddRange(current.CompileBlock(token));
                    }
                    else if (current is VariableData variableChange)
                    {
                        current.UpdateVars(variableChange.Value);
                        Variables[variableChange.VariableName] = variableChange.Value.Evaluate();
                    }
                    else
                    {
                        interData.Add(current.Compile(token));
                    }
                }
            }

            switch (Condition)
            {
            case ConditionType.Greater:
            {
                if (Operator == OperatorType.PlusPlus)
                {
                    for (int i = FromInt; i > ToInt; i++)
                    {
                        Exec(i);
                    }
                }
                if (Operator == OperatorType.PlusEquals)
                {
                    for (int i = FromInt; i > ToInt; i += ChangeInt)
                    {
                        Exec(i);
                    }
                }
                if (Operator == OperatorType.MinMin)
                {
                    for (int i = FromInt; i > ToInt; i--)
                    {
                        Exec(i);
                    }
                }
                if (Operator == OperatorType.MinusEquals)
                {
                    for (int i = FromInt; i > ToInt; i -= ChangeInt)
                    {
                        Exec(i);
                    }
                }
                break;
            }

            case ConditionType.Less:
            {
                if (Operator == OperatorType.PlusPlus)
                {
                    for (int i = FromInt; i < ToInt; i++)
                    {
                        Exec(i);
                    }
                }
                if (Operator == OperatorType.PlusEquals)
                {
                    for (int i = FromInt; i < ToInt; i += ChangeInt)
                    {
                        Exec(i);
                    }
                }
                if (Operator == OperatorType.MinMin)
                {
                    for (int i = FromInt; i < ToInt; i--)
                    {
                        Exec(i);
                    }
                }
                if (Operator == OperatorType.MinusEquals)
                {
                    for (int i = FromInt; i < ToInt; i -= ChangeInt)
                    {
                        Exec(i);
                    }
                }
                break;
            }

            case ConditionType.GreaterOrEqual:
            {
                if (Operator == OperatorType.PlusPlus)
                {
                    for (int i = FromInt; i >= ToInt; i++)
                    {
                        Exec(i);
                    }
                }
                if (Operator == OperatorType.PlusEquals)
                {
                    for (int i = FromInt; i >= ToInt; i += ChangeInt)
                    {
                        Exec(i);
                    }
                }
                if (Operator == OperatorType.MinMin)
                {
                    for (int i = FromInt; i >= ToInt; i--)
                    {
                        Exec(i);
                    }
                }
                if (Operator == OperatorType.MinusEquals)
                {
                    for (int i = FromInt; i >= ToInt; i -= ChangeInt)
                    {
                        Exec(i);
                    }
                }
                break;
            }

            case ConditionType.LessOrEqual:
            {
                if (Operator == OperatorType.PlusPlus)
                {
                    for (int i = FromInt; i <= ToInt; i++)
                    {
                        Exec(i);
                    }
                }
                if (Operator == OperatorType.PlusEquals)
                {
                    for (int i = FromInt; i <= ToInt; i += ChangeInt)
                    {
                        Exec(i);
                    }
                }
                if (Operator == OperatorType.MinMin)
                {
                    for (int i = FromInt; i <= ToInt; i--)
                    {
                        Exec(i);
                    }
                }
                if (Operator == OperatorType.MinusEquals)
                {
                    for (int i = FromInt; i <= ToInt; i -= ChangeInt)
                    {
                        Exec(i);
                    }
                }
                break;
            }
            }
            return(interData);
        }
Exemplo n.º 55
0
        private void BuildChanges()
        {
            changes = new Dictionary<int, Change>();

            for (int i = 0; i < config.changes.Length; ++i)
            {
                Change change = new Change(config.changes[i]);
                changes.Add(change.code, change);
            }
        }
Exemplo n.º 56
0
        List <ChangeSet> GetChangeSetsInternal(string path)
        {
            var        change_sets = new List <ChangeSet> ();
            GitCommand git;

            string log_args = "--since=1.month --name-status --date=iso --find-renames --no-merges --no-color";

            if (path == null)
            {
                git = new GitCommand(LocalPath, "--no-pager log " + log_args);
            }
            else
            {
                path = path.Replace("\\", "/");
                git  = new GitCommand(LocalPath, "--no-pager log " + log_args + " -- \"" + path + "\"");
            }

            string output = git.StartAndReadStandardOutput();

            if (path == null && string.IsNullOrWhiteSpace(output))
            {
                git    = new GitCommand(LocalPath, "--no-pager log -n 75 " + log_args);
                output = git.StartAndReadStandardOutput();
            }


            // Offset the output so our log_regex can be simpler
            string commit_sep = "commit ";

            if (output.StartsWith(commit_sep))
            {
                output = output.Substring(commit_sep.Length) + "\n\n" + commit_sep;
            }


            MatchCollection matches = this.log_regex.Matches(output);

            foreach (Match match in matches)
            {
                ChangeSet change_set = ParseChangeSet(match);

                if (change_set == null)
                {
                    continue;
                }

                int count = 0;
                foreach (string line in match.Groups["files"].Value.Split("\n".ToCharArray()))
                {
                    if (count++ == 256)
                    {
                        break;
                    }

                    Change change = ParseChange(line);

                    if (change == null)
                    {
                        continue;
                    }

                    change.Timestamp = change_set.Timestamp;
                    change_set.Changes.Add(change);
                }


                if (path == null && change_sets.Count > 0)
                {
                    ChangeSet last_change_set = change_sets [change_sets.Count - 1];

                    // If a change set set already exists for this user and day, group into that one
                    if (change_set.Timestamp.Year == last_change_set.Timestamp.Year &&
                        change_set.Timestamp.Month == last_change_set.Timestamp.Month &&
                        change_set.Timestamp.Day == last_change_set.Timestamp.Day &&
                        change_set.User.Name.Equals(last_change_set.User.Name))
                    {
                        last_change_set.Changes.AddRange(change_set.Changes);

                        if (DateTime.Compare(last_change_set.Timestamp, change_set.Timestamp) < 1)
                        {
                            last_change_set.FirstTimestamp = last_change_set.Timestamp;
                            last_change_set.Timestamp      = change_set.Timestamp;
                            last_change_set.Revision       = change_set.Revision;
                        }
                        else
                        {
                            last_change_set.FirstTimestamp = change_set.Timestamp;
                        }
                    }
                    else
                    {
                        change_sets.Add(change_set);
                    }
                }
                else if (path != null)
                {
                    // Don't show removals or moves in the history list of a file
                    var changes = new Change [change_set.Changes.Count];
                    change_set.Changes.CopyTo(changes);

                    foreach (Change change in changes)
                    {
                        if (!change.Path.Equals(path))
                        {
                            continue;
                        }

                        if (change.Type == ChangeType.Deleted || change.Type == ChangeType.Moved)
                        {
                            change_set.Changes.Remove(change);
                        }
                    }

                    change_sets.Add(change_set);
                }
                else
                {
                    change_sets.Add(change_set);
                }
            }

            return(change_sets);
        }
Exemplo n.º 57
0
 /// Output method
 protected void Output(TextWriter writer, string[] tokens, FileSystemWatcher source, Change type, string name)
 {
     foreach (var token in tokens)
     {
         var path = Path.Combine(source.Path, name);
         switch (token[0])
         {
             case 'e':
                 writer.Write(type);
                 if (Directory.Exists(path))
                 {
                     writer.Write(",ISDIR");
                 }
                 break;
             case 'f': writer.Write(Path.GetFileName(path)); break;
             case 'w': writer.Write(Path.Combine(source.Path, Path.GetDirectoryName(path))); break;
             case 'T': writer.Write(DateTime.Now); break;
             default: writer.Write(token); break;
         }
     }
     writer.WriteLine();
 }
Exemplo n.º 58
0
        Change ParseChange(string line)
        {
            // Skip lines containing backspace characters or the .sparkleshare file
            if (line.Contains("\\177") || line.Contains(".sparkleshare"))
            {
                return(null);
            }

            // File lines start with a change type letter and then a tab character
            if (!line.StartsWith("A\t") &&
                !line.StartsWith("M\t") &&
                !line.StartsWith("D\t") &&
                !line.StartsWith("R100\t"))
            {
                return(null);
            }

            Change change = new Change()
            {
                Type = ChangeType.Added
            };
            string file_path;

            int first_tab_pos = line.IndexOf('\t');
            int last_tab_pos  = line.LastIndexOf('\t');

            if (first_tab_pos == last_tab_pos)
            {
                char type_letter = line [0];

                if (type_letter == 'M')
                {
                    change.Type = ChangeType.Edited;
                }

                if (type_letter == 'D')
                {
                    change.Type = ChangeType.Deleted;
                }

                file_path = line.Substring(first_tab_pos + 1);
            }
            else
            {
                change.Type = ChangeType.Moved;

                // The "to" and "from" file paths are separated by a tab
                string [] parts = line.Split("\t".ToCharArray());

                file_path = parts [1];
                string to_file_path = parts [2];

                to_file_path       = to_file_path.Replace("\\\"", "\"");
                change.MovedToPath = to_file_path;
            }

            file_path   = file_path.Replace("\\\"", "\"");
            change.Path = file_path;

            string empty_name = ".empty";

            // Handle .empty files as if they were folders
            if (change.Path.EndsWith(empty_name))
            {
                change.Path = change.Path.Substring(0, change.Path.Length - empty_name.Length);

                if (change.Type == ChangeType.Moved)
                {
                    change.MovedToPath = change.MovedToPath.Substring(0, change.MovedToPath.Length - empty_name.Length);
                }

                change.IsFolder = true;
            }

            try {
                change.Path = EnsureSpecialChars(change.Path);

                if (change.Type == ChangeType.Moved)
                {
                    change.MovedToPath = EnsureSpecialChars(change.MovedToPath);
                }
            } catch (Exception e) {
                Logger.LogInfo("Local", string.Format("Error parsing line due to special character: '{0}'", line), e);
                return(null);
            }

            return(change);
        }
		private void OnAclChanged(AclEntry[] entries, Change change) {
			if(AclChanged != null) {
				AclChanged(this, new AclChangedEventArgs(entries, change));
			}
		}
Exemplo n.º 60
0
        public static Optional <Change <TObject, TKey> > Reduce <TObject, TKey>(Optional <Change <TObject, TKey> > previous, Change <TObject, TKey> next)
        {
            if (!previous.HasValue)
            {
                return(next);
            }
            var previousValue = previous.Value;

            switch (previousValue.Reason)
            {
            case ChangeReason.Add when next.Reason == ChangeReason.Remove:
                return(Optional <Change <TObject, TKey> > .None);

            case ChangeReason.Remove when next.Reason == ChangeReason.Add:
                return(new Change <TObject, TKey>(ChangeReason.Update, next.Key, next.Current, previousValue.Current, next.CurrentIndex, previousValue.CurrentIndex));

            case ChangeReason.Add when next.Reason == ChangeReason.Update:
                return(new Change <TObject, TKey>(ChangeReason.Add, next.Key, next.Current, next.CurrentIndex));

            case ChangeReason.Update when next.Reason == ChangeReason.Update:
                return(new Change <TObject, TKey>(ChangeReason.Update, previousValue.Key, next.Current, previousValue.Previous, next.CurrentIndex, previousValue.PreviousIndex));

            default:
                return(next);
            }
        }