Пример #1
0
        private void Clear()
        {
            var removeNode = _handlderList.LastOrDefault();

            if (removeNode != null)
            {
                removeNode.X          = 0;
                removeNode.Y          = 0;
                removeNode.BottomNode = null;
                removeNode.RightNode  = null;
                removeNode.IsHandle   = false;
                _handlderList.Remove(removeNode);

                //清除父节点的引用
                var parentNode = _handlderList.LastOrDefault();
                if (parentNode != null)
                {
                    if (parentNode.BottomNode == removeNode)
                    {
                        parentNode.BottomNode = null;
                    }
                    else if (parentNode.RightNode == removeNode)
                    {
                        parentNode.RightNode = null;
                    }
                }
                PrintHandlderList();
            }
        }
Пример #2
0
        public IMenuBuilder EndChildren()
        {
            var lastItem = _parentItems.LastOrDefault();

            _parentItems.Remove(lastItem);
            return(this);
        }
        /// <summary>
        /// Gets the property by identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="property">The property.</param>
        /// <param name="userLocale">The user locale.</param>
        /// <returns>
        /// The content node.
        /// </returns>
        public ApproveProperty GetPropertyById(int id, string property, string userLocale)
        {
            // Get the Umbraco db
            var db = ApplicationContext.DatabaseContext.Database;

            // Gets the content being visualized from the approveit DB
            IList <ChangeHistory> changeHistoryArray = db.Fetch <ChangeHistory>(
                string.Format("SELECT * FROM {0} WHERE [nodeId]=@0 AND [propertyAlias]=@1", Settings.APPROVE_IT_CHANGE_HISTORY_TABLE),
                id,
                property);

            // Get content being visualized
            IContent content = ApplicationContext.Services.ContentService.GetById(id);

            // Get the user that updated the content
            IUser writer = ApplicationContext.Services.UserService.GetUserById(content.WriterId);

            CultureInfo userCulture = new CultureInfo(userLocale);

            ApproveProperty updatedContent = new ApproveProperty()
            {
                Id                = content.Id,
                Name              = content.Name,
                WriterName        = writer.Username,
                WriterEmail       = writer.Email,
                UpdateDate        = content.UpdateDate.ToString("F", userCulture),
                CurrentValue      = changeHistoryArray.LastOrDefault().CurrentValue,
                PreviousValue     = changeHistoryArray.FirstOrDefault().PreviousValue,
                PropertyTypeAlias = changeHistoryArray.LastOrDefault().PropertyTypeAlias
            };

            return(updatedContent);
        }
 private static ICSharpTypeMemberDeclaration GetAnchorMember(IList<ICSharpTypeMemberDeclaration> members)
 {
     var anchor = members.LastOrDefault(member =>
         member.DeclaredElement is IProperty && !member.IsStatic &&
         member.GetAccessRights() == AccessRights.PRIVATE) ??
                  members.LastOrDefault(member =>
                      member.DeclaredElement is IField && !member.IsStatic &&
                      member.GetAccessRights() == AccessRights.PRIVATE);
     return anchor;
 }
        private static ICSharpTypeMemberDeclaration GetAnchorMember(IList <ICSharpTypeMemberDeclaration> members)
        {
            var anchor = members.LastOrDefault(member =>
                                               member.DeclaredElement is IProperty && !member.IsStatic &&
                                               member.GetAccessRights() == AccessRights.PRIVATE) ??
                         members.LastOrDefault(member =>
                                               member.DeclaredElement is IField && !member.IsStatic &&
                                               member.GetAccessRights() == AccessRights.PRIVATE);

            return(anchor);
        }
Пример #6
0
 public Model.ResponseMessage Create(Model.Account account)
 {
     accounts.Add(new Model.Account()
     {
         Id = null == accounts.LastOrDefault() ? "1" : (int.Parse(accounts.LastOrDefault().Id) + 1).ToString(), Name = account.Name
     });
     return(new Model.ResponseMessage()
     {
         Success = true, Message = "Created"
     });
 }
Пример #7
0
        private void HitungSaldoAkhir(IList <ReportKartuHutang> listOfSaldoAwal, IList <ReportKartuHutang> listOfSaldoAkhir)
        {
            var    currentSupplierId = string.Empty;
            var    isFirstRecord     = false;
            double saldo             = 0;

            foreach (var item in listOfSaldoAkhir)
            {
                if (currentSupplierId != item.supplier_id)
                {
                    if (currentSupplierId.Length > 0)
                    {
                        var oldSupplier = listOfSaldoAkhir.LastOrDefault(f => f.supplier_id == currentSupplierId);
                        oldSupplier.saldo_akhir = oldSupplier.saldo;
                    }

                    saldo             = 0;
                    currentSupplierId = item.supplier_id;
                    isFirstRecord     = true;
                }

                if (isFirstRecord)
                {
                    // copy saldo awal
                    var supplierSaldoAwal = listOfSaldoAwal.LastOrDefault(f => f.supplier_id == currentSupplierId);
                    if (supplierSaldoAwal != null)
                    {
                        item.saldo_awal = supplierSaldoAwal.saldo_akhir;
                        saldo           = item.saldo_awal;
                    }

                    isFirstRecord = false;
                }

                if (item.jenis == 1) // pembelian kredit
                {
                    saldo += item.total;
                }
                else // pembayaran hutang
                {
                    saldo -= item.total;
                }

                item.saldo = saldo;
            }

            var lastSupplier = listOfSaldoAkhir.LastOrDefault();

            if (lastSupplier != null)
            {
                lastSupplier.saldo_akhir = lastSupplier.saldo;
            }
        }
        public override void EnterXppmethod([NotNull] XP.XppmethodContext context)
        {
            Check4ClipperCC(context, context.ParamList?._Params, null, context.Type);
            CheckInitMethods(context);
            string       name;
            XppClassInfo current = null;

            if (context.ClassId == null)
            {
                current = _classes.LastOrDefault();
            }
            else
            {
                // when context contains a classname, find the right class in the list of classes
                name    = context.ClassId.GetText();
                current = FindClassInfo(name);
                if (current == null)
                {
                    context.AddError(new ParseErrorData(context, ErrorCode.ERR_XPPClassNotFound, name));
                }
                current = _classes.LastOrDefault();
            }
            current.ExternalMethods.Add(context);
            if (current != null)
            {
                // link to method
                name = context.Id.GetText();
                var decl = current.FindMethod(name);
                if (decl == null)
                {
                    decl = current.FindPropertyMethod(name);
                }
                if (decl != null)
                {
                    if (decl.IsProperty)
                    {
                        if (XSharpString.Equals(decl.AccessMethod, name))
                        {
                            decl.Entity = context;
                        }
                        if (XSharpString.Equals(decl.AssignMethod, name))
                        {
                            decl.SetEntity = context;
                        }
                    }
                    else
                    {
                        decl.Entity = context;
                    }
                    context.Info = decl;
                }
            }
        }
Пример #9
0
        public WordTableRowDef AddRow(/*int rowNo*/)
        {
            var section = _sections.LastOrDefault();

            if (section == null)
            {
                section = new WordTableSectionDef();
                _sections.Add(section);
            }

            return(section.AddRow(/*rowNo*/));
        }
Пример #10
0
 private static bool CzyOstatni(Excel.Worksheet sht, Excel.Workbook wbk)
 {
     try
     {
         LogiPomoc ostatni = logi.LastOrDefault();
         return((ostatni.KluczPliku != Nazwy.ZnajdzNazwe(wbk) && ostatni.KluczArkusza != Nazwy.ZnajdzNazwe(sht)) || logi.Count == 0);
     }
     catch (Exception e)
     {
         return(true);
     }
 }
            protected override ICSharpTypeMemberDeclaration GetAnchorMember(IList <ICSharpTypeMemberDeclaration> members)
            {
                var anchor = members.LastOrDefault(member => member.DeclaredElement is IProperty && member.IsStatic == IsStatic) ??
                             members.LastOrDefault(member => member.DeclaredElement is IField && member.IsStatic == IsStatic);

                if (anchor == null && IsStatic)
                {
                    return(members.LastOrDefault(m => m.DeclaredElement is IProperty) ??
                           members.LastOrDefault(m => m.DeclaredElement is IField));
                }

                return(anchor);
            }
            protected override ICSharpTypeMemberDeclaration GetAnchorMember(IList<ICSharpTypeMemberDeclaration> members)
            {
                var anchor = members.LastOrDefault(member =>
                       member.DeclaredElement is IProperty && member.IsStatic == IsStatic) ??
                     members.LastOrDefault(member =>
                       member.DeclaredElement is IField && member.IsStatic == IsStatic);
                if (anchor == null && IsStatic)
                {
                  return members.LastOrDefault(m => m.DeclaredElement is IProperty) ??
                 members.LastOrDefault(m => m.DeclaredElement is IField);
                }

                return anchor;
            }
Пример #13
0
        public async void GoBack()
        {
            var lastWindow = WindowTypes.LastOrDefault();

            if (lastWindow != null)
            {
                WindowTypes.Remove(lastWindow);
                lastWindow = WindowTypes.LastOrDefault();
                if (lastWindow != null)
                {
                    await NavigateTo(lastWindow);
                }
            }
        }
Пример #14
0
 public LevelsEntitiesController()
 {
     Entities = new List <LevelsEntity>();
     for (int i = 1; i <= 10; i++)
     {
         if (i % 2 == 1)
         {
             var newEntity = new LevelsEntity
             {
                 ID           = i,
                 Name         = "Name " + i,
                 Parent       = Entities.LastOrDefault(),
                 BaseEntities = Entities.Concat(new[]
                 {
                     new LevelsBaseEntity
                     {
                         ID   = i + 10,
                         Name = "Name " + (i + 10)
                     }
                 }).ToArray(),
                 DerivedAncestors = Entities.OfType <LevelsDerivedEntity>().ToArray()
             };
             Entities.Add(newEntity);
         }
         else
         {
             var newEntity = new LevelsDerivedEntity
             {
                 ID           = i,
                 Name         = "Name " + i,
                 DerivedName  = "DerivedName " + i,
                 Parent       = Entities.LastOrDefault(),
                 BaseEntities = Entities.Concat(new[]
                 {
                     new LevelsBaseEntity
                     {
                         ID   = i + 10,
                         Name = "Name " + (i + 10)
                     }
                 }).ToArray(),
                 DerivedAncestors         = Entities.OfType <LevelsDerivedEntity>().ToArray(),
                 AncestorsInDerivedEntity = Entities.ToArray()
             };
             Entities.Add(newEntity);
         }
     }
     Entities[8].Parent           = Entities[9];
     Entities[1].DerivedAncestors = new LevelsDerivedEntity[] { (LevelsDerivedEntity)Entities[3] };
 }
Пример #15
0
        /// <summary>
        /// Adds a <see cref="HttpMessageHandler"/> to the chain of handlers.
        /// </summary>
        /// <param name="handler"></param>
        /// <returns></returns>
        public HttpHandlerBuilder AddHandler(HttpMessageHandler handler)
        {
            if (handler is HttpTracerHandler)
            {
                throw new ArgumentException($"Can't add handler of type {nameof(HttpTracerHandler)}.");
            }

            if (_handlersList.Any())
            {
                ((DelegatingHandler)_handlersList.LastOrDefault()).InnerHandler = handler;
            }

            _handlersList.Add(handler);
            return(this);
        }
Пример #16
0
        /// <summary>
        /// Gets the state of <c>node</c> within the passed <c>currentPath</c>, which is the navigation breadcrumb.
        /// </summary>
        /// <param name="node">The node to get the state for</param>
        /// <param name="currentPath">The current path/breadcrumb</param>
        /// <returns>
        ///		<see cref="NodePathState" /> enumeration indicating whether the node is in the current path (<c>Selected</c> or <c>Expanded</c>)
        ///		and whether it has children (<c>Parent</c>)
        ///	</returns>
        public static NodePathState GetNodePathState(this TreeNode <MenuItem> node, IList <MenuItem> currentPath)
        {
            Guard.NotNull(currentPath, nameof(currentPath));

            var state = NodePathState.Unknown;

            if (node.HasChildren)
            {
                state = state | NodePathState.Parent;
            }

            var lastInPath = currentPath.LastOrDefault();

            if (currentPath.Count > 0)
            {
                if (node.Value.Equals(lastInPath))
                {
                    state = state | NodePathState.Selected;
                }
                else
                {
                    if (node.Depth - 1 < currentPath.Count)
                    {
                        if (currentPath[node.Depth - 1].Equals(node.Value))
                        {
                            state = state | NodePathState.Expanded;
                        }
                    }
                }
            }

            return(state);
        }
Пример #17
0
 public EventPage(long @from, IList<long> sequences, IList<IEvent> events)
 {
     Sequences = sequences;
     From = @from;
     To = Sequences.LastOrDefault();
     Streams = ToStreams(events);
 }
        public override string ProcessContext(string StringContext, IDatabaseContext databaseContext)
        {
            ControlContext(StringContext, databaseContext);
            IColumnModel columnModel = databaseContext.Column;

            if (databaseContext.Table == null)
            {
                throw new Exception("The provided column has no parent table");
            }
            IList <IColumnModel> columnList = databaseContext.Table.Columns;

            if (columnList == null || !columnList.Any())
            {
                throw new Exception("The provided column's parent table has no column associated to");
            }

            if (columnModel.IsIndexed == false)
            {
                return(string.Empty);
            }
            string TrimedStringContext = TrimContextFromContextWrapper(StringContext);
            var    indexedColumn       = columnList.LastOrDefault(currentColumn => currentColumn.IsIndexed);

            if (indexedColumn == default(IColumnModel))
            {
                return(string.Empty);
            }
            if (indexedColumn.Equals(columnModel))
            {
                return(HandleTrimedContext(TrimedStringContext, databaseContext));
            }
            return(string.Empty);
        }
        /// <summary>
        /// 获取最新未收到消息的请求
        /// </summary>
        /// <returns></returns>
        public virtual IConnection GetConnection(FrameBase frame)
        {
            IList <IConnection> connections = this.connectionDocker.BusinessCaseList.
                                              Where(o => o.Receiving).OrderByDescending(o => o.Created).ToList();

            return(connections.LastOrDefault());
        }
Пример #20
0
        private string GetNextFileAvailable(string filePath)
        {
            int    i = 0;
            bool   availabilityFound = false;
            string nextFileAvailable = string.Empty;

            IList <string> filePaths = filePath.Split('.');
            string         ext       = filePaths.LastOrDefault();

            filePaths = filePaths.Take(filePaths.Count() - 1).ToArray();
            string fileBasePath = string.Join(string.Empty, filePaths);

            do
            {
                string fileAttempt = string.Format("{0}-{1}.{2}", fileBasePath, i, ext);
                if (File.Exists(fileAttempt))
                {
                    i++;
                }
                else
                {
                    nextFileAvailable = fileAttempt;
                    availabilityFound = true;
                }
            }while (!availabilityFound);
            return(nextFileAvailable);
        }
Пример #21
0
    public T Remove()
    {
        var el = data.LastOrDefault();

        data.RemoveAt(data.Count - 1);
        return(el);
    }
Пример #22
0
 public EventPage(long @from, IList <long> sequences, IList <IEvent> events)
 {
     Sequences = sequences;
     From      = @from;
     To        = Sequences.LastOrDefault();
     Streams   = ToStreams(events);
 }
		/// <summary>
		/// Gets the state of <c>node</c> within the passed <c>currentPath</c>, which is the navigation breadcrumb.
		/// </summary>
		/// <param name="node">The node to get the state for</param>
		/// <param name="currentPath">The current path/breadcrumb</param>
		/// <returns>
		///		<see cref="NodePathState" /> enumeration indicating whether the node is in the current path (<c>Selected</c> or <c>Expanded</c>)
		///		and whether it has children (<c>Parent</c>)
		///	</returns>
		public static NodePathState GetNodePathState(this TreeNode<MenuItem> node, IList<MenuItem> currentPath)
		{
			Guard.ArgumentNotNull(() => currentPath);
			
			var state = NodePathState.Unknown;

			if (node.HasChildren)
			{
				state = state | NodePathState.Parent;
			}

			if (currentPath.Count > 0)
			{
				if (node.Value.Equals(currentPath.LastOrDefault()))
				{
					state = state | NodePathState.Selected;
				}
				else
				{
					if (node.Depth < currentPath.Count)
					{
						if (currentPath[node.Depth].Equals(node.Value))
						{
							state = state | NodePathState.Expanded;
						}
					}
				}
			}

			return state;
		}
Пример #24
0
    public T Remove()
    {
        var rem = box.LastOrDefault();

        this.box.RemoveAt(this.Count - 1);
        return(rem);
    }
Пример #25
0
    public T Remove()
    {
        var lastElement = data.LastOrDefault();

        data.RemoveAt(data.Count - 1);
        return(lastElement);
    }
Пример #26
0
        public void Backup(string filePath = null)
        {
            string backupFolderPath, backupFilePath;

            if (string.IsNullOrWhiteSpace(filePath))
            {
                IList <string> filePaths = LoadedFilePath.Split('\\');
                string         fileName  = filePaths.LastOrDefault();
                backupFolderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DgmlBackups");
                backupFilePath   = Path.Combine(backupFolderPath, fileName);
            }
            else
            {
                IList <string> filePaths = filePath.Split('\\');
                string         fileName  = filePaths.LastOrDefault();
                filePaths        = filePaths.Take(filePaths.Count() - 1).ToArray();
                backupFolderPath = string.Join("\\", filePaths);
                backupFilePath   = Path.Combine(backupFolderPath, fileName);
            }

            if (!Directory.Exists(backupFolderPath))
            {
                Directory.CreateDirectory(backupFolderPath);
            }
            backupFilePath = this.GetNextFileAvailable(backupFilePath);

            XDocument docToSave = XDocument.Parse(_xdoc.ToString().Replace("<DirectedGraph ", "<DirectedGraph xmlns=\"http://schemas.microsoft.com/vs/2009/dgml\" "));

            docToSave.Save(backupFilePath);
        }
Пример #27
0
    public T Remove()
    {
        var reminder = data.LastOrDefault();

        data.RemoveAt(data.Count - 1);
        return(reminder);
    }
Пример #28
0
        /// <summary>
        /// Adds a url to the batch for processing
        /// </summary>
        /// <param name="item">url for batch item</param>
        /// <returns>True if an appropriate pending batch operation was found</returns>
        public bool AddToBatch(SDataBatchRequestItem item)
        {
            Guard.ArgumentNotNull(item, "item");

            var uri = new SDataUri(item.Url)
            {
                CollectionPredicate = null,
                Query = null
            };

            if (uri.PathSegments.Length > 4)
            {
                uri.TrimRange(4, uri.PathSegments.Length - 4);
            }

            uri.AppendPath("$batch");
            var baseUri = uri.ToString();
            var request = _requests.LastOrDefault(x => string.Equals(x.ToString(), baseUri, StringComparison.InvariantCultureIgnoreCase));

            if (request != null)
            {
                request.Items.Add(item);
                return(true);
            }

            return(false);
        }
Пример #29
0
        private static void CheckAllHandActionsForUncalled(IList <HandAction> handActions, int index)
        {
            var lastAgrassiveAction =
                handActions.LastOrDefault(ha => ha.HandActionType == HandActionType.BET || ha.HandActionType == HandActionType.RAISE ||
                                          ha.HandActionType == HandActionType.ALL_IN_RAISE);

            if (lastAgrassiveAction == null)
            {
                return;
            }
            var ind = handActions.IndexOf(lastAgrassiveAction);

            for (var i = ind; i < handActions.Count; i++)
            {
                if (handActions[i].HandActionType == HandActionType.CALL || handActions[i].HandActionType == HandActionType.ALL_IN_CALL)
                {
                    return;
                }
            }
            var uncalledBetHandAction = new HandAction
            {
                Index          = index,
                PlayerName     = lastAgrassiveAction.PlayerName,
                HandActionType = HandActionType.UNCALLED_BET,
                Street         = lastAgrassiveAction.Street,
                Amount         = -lastAgrassiveAction.Amount
            };

            handActions.Add(uncalledBetHandAction);
        }
Пример #30
0
        public static string GetTimeLeft(EpisodeJson episodeJson, IList <Season> seasonList)
        {
            var lastSeason = seasonList.LastOrDefault();

            if (lastSeason == null)
            {
                return(empty);
            }

            var lastIndex = lastSeason.EpisodeList.Count - 1;

            while (lastIndex >= 0)
            {
                var episode = lastSeason.EpisodeList[lastIndex];

                var seasonId  = episode.Season.ID;
                var episodeId = episode.ID;
                episode = episodeJson.GetEpisode(seasonId, episodeId);

                if (episode != null && isComplete(episode))
                {
                    return(getTimeLeft(seasonId, episodeId));
                }

                lastIndex--;
            }

            return(empty);
        }
Пример #31
0
        public static bool AddOrSimplify(IList <Transform> transformList, Transform transform)
        {
            if (transform.IsNull)
            {
                return(false);
            }
            var last = transformList.LastOrDefault();

            if (transform.CanSimplify(last))
            {
                var simplified = transform.Simplify(last);
                if (simplified.IsNull)
                {
                    transformList.RemoveAt(transformList.Count - 1);
                }
                else
                {
                    transformList[transformList.Count - 1] = transform.Simplify(last);
                }
            }
            else
            {
                transformList.Add(transform);
            }
            return(true);
        }
Пример #32
0
        private async Task Up(IList <LibraryBrowserFrame> frames, bool updateSelection)
        {
            if (frames.Count <= 1)
            {
                return;
            }
            var frame = frames.LastOrDefault();

            if (frame == null)
            {
                return;
            }
            if (object.ReferenceEquals(this.Frames, frames))
            {
                await Windows.Invoke(() => frames.Remove(frame)).ConfigureAwait(false);
            }
            else
            {
                frames.Remove(frame);
            }
            if (updateSelection && object.ReferenceEquals(this.Frames, frames))
            {
                await Windows.Invoke(() => this.SelectedItem = frame.ItemsSource).ConfigureAwait(false);
            }
        }
Пример #33
0
        /// <summary>
        /// Gets the state of <c>node</c> within the passed <c>currentPath</c>, which is the navigation breadcrumb.
        /// </summary>
        /// <param name="node">The node to get the state for</param>
        /// <param name="currentPath">The current path/breadcrumb</param>
        /// <returns>
        ///		<see cref="NodePathState" /> enumeration indicating whether the node is in the current path (<c>Selected</c> or <c>Expanded</c>)
        ///		and whether it has children (<c>Parent</c>)
        ///	</returns>
        public static NodePathState GetNodePathState(this TreeNode <MenuItem> node, IList <MenuItem> currentPath)
        {
            Guard.ArgumentNotNull(() => currentPath);

            var state = NodePathState.Unknown;

            if (node.HasChildren)
            {
                state = state | NodePathState.Parent;
            }

            if (currentPath.Count > 0)
            {
                if (node.Value.Equals(currentPath.LastOrDefault()))
                {
                    state = state | NodePathState.Selected;
                }
                else
                {
                    if (node.Depth < currentPath.Count)
                    {
                        if (currentPath[node.Depth].Equals(node.Value))
                        {
                            state = state | NodePathState.Expanded;
                        }
                    }
                }
            }

            return(state);
        }
        static FunctionalTestsConfiguration()
        {
            // First just a quick test that an event can be added and removed.
            Loaded += OnLoaded;
            Loaded -= OnLoaded;

            // Now add an event that actually changes config in a verifiable way.
            // Note that OriginalConnectionFactories will be set to the DbConfiguration specified in the config file when running
            // the functional test project and set to the DbConfiguration that was set in code when running the unit tests project.
            Loaded +=
                (s, a) =>
            {
                var currentFactory = a.DependencyResolver.GetService <IDbConnectionFactory>();
                if (currentFactory != _originalConnectionFactories.LastOrDefault())
                {
                    var newList = new List <IDbConnectionFactory>(_originalConnectionFactories)
                    {
                        currentFactory
                    };
                    _originalConnectionFactories = newList;
                }
                a.AddDependencyResolver(
                    new SingletonDependencyResolver <IDbConnectionFactory>(
                        new SqlConnectionFactory(ModelHelpers.BaseConnectionString)), overrideConfigFile: true);

                var currentProviderFactory = a.DependencyResolver.GetService <IDbProviderFactoryResolver>();
                a.AddDependencyResolver(
                    new SingletonDependencyResolver <IDbProviderFactoryResolver>(
                        new FakeProviderFactoryResolver(currentProviderFactory))
                    , overrideConfigFile: true);

                a.AddDependencyResolver(new FakeProviderServicesResolver(), overrideConfigFile: true);
            };
        }
Пример #35
0
 public EventPage(long lastEncountered, IList<long> sequences, IList<IEvent> events)
 {
     Sequences = sequences;
     From = lastEncountered;
     To = Sequences.LastOrDefault();
     Streams = ToStreams(events);
 }
Пример #36
0
        /// <summary>
        /// Creates and initializes a new instance of a complex lens.
        /// </summary>
        /// <param name="surfaces">List of element surfaces, ordered from
        /// back to front.</param>
        public ComplexLens(IList<ElementSurface> surfaces)
        {
            ElementSurfaces = surfaces;

            ElementSurface frontSurface = surfaces.LastOrDefault((surface) => surface.Surface is Sphere);
            frontSphericalSurface = (Sphere)frontSurface.Surface;
            frontSurfaceSinTheta = frontSphericalSurface.GetCapElevationAngleSine(frontSurface.ApertureRadius);
            frontSurfaceApertureRadius = frontSurface.ApertureRadius;

            ElementSurface backSurface = surfaces.FirstOrDefault((surface) => surface.Surface is Sphere);
            backSphericalSurface = (Sphere)backSurface.Surface;
            backSurfaceSinTheta = backSphericalSurface.GetCapElevationAngleSine(backSurface.ApertureRadius);
            backSurfaceApertureRadius = backSurface.ApertureRadius;

            MediumRefractiveIndex = Materials.Fixed.AIR;
            frontSurface.NextRefractiveIndex = MediumRefractiveIndex;
        }
Пример #37
0
 public static void AddOrSimplify(IList<Transform> transformList, Transform transform)
 {
     var last = transformList.LastOrDefault();
     if (transform.CanSimplify(last))
     {
         var simplified = transform.Simplify(last);
         if (simplified.IsNull)
         {
             transformList.RemoveAt(transformList.Count - 1);
         }
         else
         {
             transformList[transformList.Count - 1] = transform.Simplify(last);
         }
     }
     else if (!transform.IsNull)
     {
         transformList.Add(transform);
     }
 }
Пример #38
0
 private static void Write( StringBuilder sb, MethodInfo method, IList<ParameterInfo> parameters )
 {
     sb.AppendFormat( "{0} ", method.ReturnType.Name() );
     sb.AppendFormat( "{0}{1}( ", method.Name, GetGenericParameterText( method ) );
     ParameterInfo first = parameters.FirstOrDefault();
     ParameterInfo last = parameters.LastOrDefault();
     bool addPrefix = method.IsStatic && method.DeclaringType.Name.EndsWith( "Extensions" );
     parameters.ForEach( p => sb.AppendFormat( "{0}{1} {2}{3}",
                                               p == first && addPrefix ? "this " : "",
                                               GetType( p ), p.Name, p == last ? "" : ", " ) );
     sb.AppendFormat( " );{0}", Environment.NewLine );
 }
Пример #39
0
        private void AppendEndMarker(IList<MidiEvent> eventList)
        {
            long absoluteTime = 0;

            if (eventList.Count > 0)
                absoluteTime = eventList[eventList.Count - 1].AbsoluteTime;

            if (!IsEndTrack(eventList.LastOrDefault()))
                eventList.Add(new MetaEvent(MetaEventType.EndTrack, 0, absoluteTime));
        }
 protected override ICSharpTypeMemberDeclaration GetAnchorMember(IList<ICSharpTypeMemberDeclaration> members)
 {
     return members.LastOrDefault(member =>
       member.DeclaredElement is IField && member.IsStatic == IsStatic);
 }
Пример #41
0
        /// <summary>
        /// Updates a list of candles with the most recent data from a given exchange (Called when ticker refreshes)
        /// </summary>
        /// <param name="from">The from date</param>
        /// <param name="candlesDurationInMin">The period' duration in minutes</param>
        /// <param name="existingCandles">A list of existing candles</param>
        /// <returns>True if the update was successful</returns>
        public static bool UpdateCandlesWithLiveData(DateTime from, int candlesDurationInMin, IList<OHLC> existingCandles, CurrencyPair pair)
        {
            try
            {
                var proxy = ExchangeProxyFactory.GetProxy(pair.Exchange.InternalCode);

                //We first get the transactions for the last minute
                var transactionsRes = proxy.GetTransactions(true, pair);//
                if (!transactionsRes.Success)
                {
                    return false;
                }

                var transactions = transactionsRes.Result.Transactions;
                transactions.Reverse();//Make sure they are in ASC order

                transactions = transactions.Where(t => t.Date >= from).ToList();
                // Create trade list (required to calculate OHLC)
                IList<BitcoinCharts.Models.Trade> list = (from trade in transactions
                                                          select new BitcoinCharts.Models.Trade()
                                                          {
                                                              Datetime = trade.Date,
                                                              Price = trade.Price,
                                                              Quantity = trade.Amount,
                                                              Symbol = pair.Item2
                                                          }).ToList();

                //Check if we need to create another candle
                var lastCandle = existingCandles.LastOrDefault();
                if (list.Count == 0 && lastCandle != null)
                {
                    if (lastCandle.Date.Subtract(DateTime.MinValue).TotalMinutes / candlesDurationInMin
                        != DateTime.Now.Subtract(DateTime.MinValue).TotalMinutes / candlesDurationInMin)
                    {
                        list.Add(new BitcoinCharts.Models.Trade
                                                              {
                                                                  Datetime = lastCandle.Date.AddMilliseconds(candlesDurationInMin),
                                                                  Price = lastCandle.Close,
                                                                  Quantity = 0,
                                                                  Symbol = pair.Item2
                                                              });
                    }
                }
                // Calculate trades
                IList<OHLC> recentCandles = CandlesProvider.CalculateOHLCFromTrades(list, candlesDurationInMin, TradeSource.Bitstamp);


                foreach (OHLC newCandle in recentCandles)
                {
                    var existingCandle = existingCandles.FirstOrDefault(e => e.Date == newCandle.Date);
                    if (existingCandle != null)
                    {
                        existingCandle.High = newCandle.High > existingCandle.High ? newCandle.High : existingCandle.High;
                        existingCandle.Low = newCandle.Low < existingCandle.Low ? newCandle.Low : existingCandle.Low;
                        existingCandle.Close = newCandle.Close;
                        existingCandle.TradeSource = TradeSource.Bitstamp;
                        //recentCandles = recentCandles.Skip(1).ToList();
                    }
                    else
                    {
                        existingCandles.Add(newCandle);
                    }
                }

                return recentCandles.Count() > 0;
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                MessageBox.Show(ex.ToString());
            }
            return false;
        }
Пример #42
0
        /// <summary>
        /// Creates the symbol token from matched string.
        /// </summary>
        /// <param name="match">The matched string.</param>
        /// <param name="tokens">The list of tokens.</param>
        /// <exception cref="LexerException">
        /// The specified symbol is not supported.
        /// </exception>
        private void CreateSymbol(string match, IList<IToken> tokens)
        {
            if (match == "(")
            {
                tokens.Add(new SymbolToken(Symbols.OpenBracket));
            }
            else if (match == ")")
            {
                var lastToken = tokens.LastOrDefault() as SymbolToken;
                if (lastToken != null && lastToken.Symbol == Symbols.Comma)
                    throw new LexerException(Resource.NotEnoughParams);

                tokens.Add(new SymbolToken(Symbols.CloseBracket));
            }
            else if (match == "{")
            {
                if (!(tokens.LastOrDefault() is FunctionToken))
                    tokens.Add(new FunctionToken(Functions.Vector));

                tokens.Add(new SymbolToken(Symbols.OpenBrace));
            }
            else if (match == "}")
            {
                tokens.Add(new SymbolToken(Symbols.CloseBrace));
            }
            else if (match == ",")
            {
                tokens.Add(new SymbolToken(Symbols.Comma));
            }
            else
            {
                throw new LexerException(string.Format(Resource.NotSupportedSymbol, match));
            }
        }
Пример #43
0
        public virtual SqlStatement GetSqlFunction(SqlFunctionType functionType, bool forceIgnoreCase, IList<SqlStatement> parameters)
        {
            var pLast = parameters.LastOrDefault();
            switch (functionType) //
            {
            case SqlFunctionType.IsNull:
                return GetLiteralIsNull(parameters[0]);
            case SqlFunctionType.IsNotNull:
                return GetLiteralIsNotNull(parameters[0]);
            case SqlFunctionType.EqualNullables:
                return GetEqualNullables(parameters[0], parameters[1]);
            case SqlFunctionType.Concat:
                return GetLiteralStringConcat(parameters[0], parameters[1]);
            case SqlFunctionType.Count:
                return GetLiteralCount(parameters[0]);
            case SqlFunctionType.Exists:
                return GetLiteralExists(parameters[0]);
            case SqlFunctionType.Like:
                return GetLiteralLike(parameters[0], parameters[1], forceIgnoreCase);
            // RI: changed index to 1 (from 0) for Min, Max, Avg, Sum
            case SqlFunctionType.Min:
                return GetLiteralMin(pLast);
            case SqlFunctionType.Max:
                return GetLiteralMax(pLast);
            case SqlFunctionType.Sum:
                return GetLiteralSum(pLast);
            case SqlFunctionType.Average:
                return GetLiteralAverage(pLast);

            case SqlFunctionType.StringLength:
                return GetLiteralStringLength(parameters[0]);
            case SqlFunctionType.ToUpper:
                return GetLiteralStringToUpper(parameters[0]);
            case SqlFunctionType.ToLower:
                return GetLiteralStringToLower(parameters[0]);
            case SqlFunctionType.In:
                return GetLiteralIn(parameters[0], parameters[1]);
            case SqlFunctionType.InArray:
                return GetLiteralInArray(parameters[0], parameters[1]);
            case SqlFunctionType.StringEqual:
                return GetLiteralStringEqual(parameters[0], parameters[1], forceIgnoreCase);
            case SqlFunctionType.Substring:
                if (parameters.Count > 2)
                    return GetLiteralSubString(parameters[0], parameters[1], parameters[2]);
                else
                    return GetLiteralSubString(parameters[0], parameters[1]);
            case SqlFunctionType.Trim:
            case SqlFunctionType.LTrim:
            case SqlFunctionType.RTrim:
                return GetLiteralTrim(parameters[0]);
            case SqlFunctionType.StringInsert:
                return GetLiteralStringInsert(parameters[0], parameters[1], parameters[2]);
            case SqlFunctionType.Replace:
                return GetLiteralStringReplace(parameters[0], parameters[1], parameters[2]);
            case SqlFunctionType.Remove:
                if (parameters.Count > 2)
                    return GetLiteralStringRemove(parameters[0], parameters[1], parameters[2]);
                return GetLiteralStringRemove(parameters[0], parameters[1]);
            case SqlFunctionType.IndexOf:
                if (parameters.Count == 2)
                    return GetLiteralStringIndexOf(parameters[0], parameters[1]);
                else if (parameters.Count == 3)
                    return GetLiteralStringIndexOf(parameters[0], parameters[1], parameters[2]);
                else if (parameters.Count == 4)
                    return GetLiteralStringIndexOf(parameters[0], parameters[1], parameters[2], parameters[3]);
                break;
            case SqlFunctionType.Year:
            case SqlFunctionType.Month:
            case SqlFunctionType.Day:
            case SqlFunctionType.Hour:
            case SqlFunctionType.Minute:
            case SqlFunctionType.Second:
            case SqlFunctionType.Millisecond:
            case SqlFunctionType.Date:
            case SqlFunctionType.Time:
            case SqlFunctionType.Week:
              return GetLiteralDateTimePart(parameters[0], functionType);
            case SqlFunctionType.DateDiffInMilliseconds:
                return GetLiteralDateDiff(parameters[0], parameters[1]);
            case SqlFunctionType.Abs:
                return GetLiteralMathAbs(parameters[0]);
            case SqlFunctionType.Exp:
                return GetLiteralMathExp(parameters[0]);
            case SqlFunctionType.Floor:
                return GetLiteralMathFloor(parameters[0]);
            case SqlFunctionType.Ln:
                return GetLiteralMathLn(parameters[0]);

            case SqlFunctionType.Log:
                if (parameters.Count == 1)
                    return GetLiteralMathLog(parameters[0]);
                else
                    return GetLiteralMathLog(parameters[0], parameters[1]);
            case SqlFunctionType.Pow:
                return GetLiteralMathPow(parameters[0], parameters[1]);
            case SqlFunctionType.Round:
                return GetLiteralMathRound(parameters[0]);
            case SqlFunctionType.Sign:
                return GetLiteralMathSign(parameters[0]);
            case SqlFunctionType.Sqrt:
                return GetLiteralMathSqrt(parameters[0]);
              case SqlFunctionType.AndBitwise:
                return GetLiteralAndBitwise(parameters[0], parameters[1]);
              case SqlFunctionType.OrBitwise:
                return GetLiteralOrBitwise(parameters[0], parameters[1]);
              case SqlFunctionType.XorBitwise:
                return GetLiteralExclusiveOrBitwise(parameters[0], parameters[1]);
              case SqlFunctionType.ConvertBoolToBit:
                return GetConvertBoolToBit(parameters[0]);
              case SqlFunctionType.NewGuid:
                return GetNewGuid();
            }//switch
            throw new ArgumentException(functionType.ToString());
        }
Пример #44
0
 public LevelsEntitiesController()
 {
     Entities = new List<LevelsEntity>();
     for (int i = 1; i <= 10; i++)
     {
         if (i % 2 == 1)
         {
             var newEntity = new LevelsEntity
             {
                 ID = i,
                 Name = "Name " + i,
                 Parent = Entities.LastOrDefault(),
                 BaseEntities = Entities.Concat(new[]
                     {
                         new LevelsBaseEntity
                         {
                             ID = i + 10,
                             Name = "Name " + (i + 10)
                         }
                     }).ToArray(),
                 DerivedAncestors = Entities.OfType<LevelsDerivedEntity>().ToArray()
             };
             Entities.Add(newEntity);
         }
         else
         {
             var newEntity = new LevelsDerivedEntity
             {
                 ID = i,
                 Name = "Name " + i,
                 DerivedName = "DerivedName " + i,
                 Parent = Entities.LastOrDefault(),
                 BaseEntities = Entities.Concat(new[]
                     {
                         new LevelsBaseEntity
                         {
                             ID = i + 10,
                             Name = "Name " + (i + 10)
                         }
                     }).ToArray(),
                 DerivedAncestors = Entities.OfType<LevelsDerivedEntity>().ToArray(),
                 AncestorsInDerivedEntity = Entities.ToArray()
             };
             Entities.Add(newEntity);
         }
     }
     Entities[8].Parent = Entities[9];
     Entities[1].DerivedAncestors = new LevelsDerivedEntity[] { (LevelsDerivedEntity)Entities[3] }; 
 }
Пример #45
0
 private static void CheckAllHandActionsForUncalled(IList<HandAction> handActions, int index)
 {
     var lastAgrassiveAction =
         handActions.LastOrDefault(ha => ha.HandActionType == HandActionType.BET || ha.HandActionType == HandActionType.RAISE
                                         || ha.HandActionType == HandActionType.ALL_IN_RAISE);
     if (lastAgrassiveAction == null) return;
     var ind = handActions.IndexOf(lastAgrassiveAction);
     for (var i = ind; i < handActions.Count; i++)
     {
         if (handActions[i].HandActionType == HandActionType.CALL || handActions[i].HandActionType == HandActionType.ALL_IN_CALL)
             return;
     }
     var uncalledBetHandAction = new HandAction
     {
         Index = index,
         PlayerName = lastAgrassiveAction.PlayerName,
         HandActionType = HandActionType.UNCALLED_BET,
         Street = lastAgrassiveAction.Street,
         Amount = -lastAgrassiveAction.Amount
     };
     handActions.Add(uncalledBetHandAction);
 }
Пример #46
0
        /// <summary>
        /// 详细内容
        /// 传入字节数组的list,然后返回详细文件mode的list
        /// </summary>
        /// <param name="tmpDetailedBytes"></param>
        /// <returns></returns>
        private IEnumerable<DetailedField> getDetailedData(ProductWorkingSummaryData productWorkingSummaryData,
            IList<byte[]> tmpDetailedBytes)
        {
            DateTime endTime, startTime;
            string time = timeBytes.ToHexString();
            startTime =
                DateTime.ParseExact(
                   time + tmpDetailedBytes.FirstOrDefault().SubBytes(0, 3).ToDecString()
                    , "yyyyMMddHHmmss"
                    , CultureInfo.InvariantCulture);

            endTime =
                DateTime.ParseExact(
                    time + tmpDetailedBytes.LastOrDefault().SubBytes(0, 3).ToDecString()
                    , "yyyyMMddHHmmss"
                    , CultureInfo.InvariantCulture);
            time = null;
            //半夜12点之后的数据日期加一 todo
            if (tmpDetailedBytes.FirstOrDefault()[0] == 0 && isChangeDate)
            {
                startTime = startTime.AddDays(1);
                endTime = endTime.AddDays(1);
            }
            productWorkingSummaryData.StartTime = startTime;
            productWorkingSummaryData.EndTime = endTime;
            productWorkingSummaryData.WorkingTime = (int)(endTime - startTime).TotalMilliseconds;

            double titick = 1;
            if (tmpDetailedBytes.Count() > 1)
            {
                titick = (endTime - startTime).TotalMilliseconds / (tmpDetailedBytes.Count() - 1);
            }
            ICollection<DetailedField> listDetailed = new Collection<DetailedField>();

            #region 同步方法解析 比异步步快 ,是有序的,使用时不需要排序 ,异步需要锁list所以费时,不锁会导致多线程访问list

            //var objLock = new object();
            //var result = Parallel.For(0, tmpDetailedBytes.Count(), i =>
            for (int i = 0; i < tmpDetailedBytes.Count(); i++)// var result = Parallel.For(0, tmpDetailedBytes.Count(), i =>
            {

                var detailedField = new DetailedField();
                detailedField.RecoredTime = startTime.AddMilliseconds(titick * i);

                #region 详细数据 512之后的数据

                // 0x00:S/T
                // 0x01:T
                // 0x02:S
                // 0x03:CPAP
                // 0x04:APAP
                // 0x05:PCV
                // 0x06:AutoS
                switch (productWorkingSummaryData.TherapyMode)
                {
                    //双水品512之后一样
                    case 0x00: //S/T
                    case 0x01: //T
                    case 0x02: //S
                    case 0x05: //PCV
                    case 0x06: //AutoS

                        #region 处理详细 双水品

                        //------------------------------------------------------------压力kpa 0.01 cmH2O 0.1
                        detailedField.TargetPressure = tmpDetailedBytes[i].SubBytes(3, 2).BytesToInt16(0) * 0.1f;

                        //------------------------------------------------------------当前流量.有负值
                        var tt = tmpDetailedBytes[i][5] * 256 + tmpDetailedBytes[i][6];
                        if (tt > short.MaxValue)
                        {
                            detailedField.CurrentFlow = short.MaxValue - tt; //升/分钟
                        }
                        else
                        {
                            detailedField.CurrentFlow = tt; //升/分钟
                        }
                        //tmpbytes = null;

                        //------------------------------------------------------------潮气量(0-2500)mL
                        detailedField.TidalVolume = tmpDetailedBytes[i].SubBytes(7, 2).BytesToInt16(0) * 0.1f;

                        //------------------------------------------------------------漏气量(0-99) L/min
                        //detailedField.Leak = tmpDetailedBytes[i].SubBytes(9, 1)[0];
                        detailedField.Leak = tmpDetailedBytes[i][9];

                        //------------------------------------------------------------分钟通气量(0-30)L/min
                        //detailedField.MinuteVentilation = tmpDetailedBytes[i].SubBytes(10, 1)[0];
                        detailedField.MinuteVentilation = tmpDetailedBytes[i][10];

                        //------------------------------------------------------------呼吸频率(0-60)min
                        //detailedField.RespiratoryRate = tmpDetailedBytes[i].SubBytes(11, 1)[0];
                        detailedField.RespiratoryRate = tmpDetailedBytes[i][11];

                        //------------------------------------------------------------吸呼比(1-99),1:0.1-9.9
                        //detailedField.IERatio = tmpDetailedBytes[i].SubBytes(12, 1)[0] * 0.1m;
                        detailedField.IERatio = tmpDetailedBytes[i][12] * 0.1f;

                        //------------------------------------------------------------IPAP(40-250)4-25cmH2O
                        //detailedField.IPAP = tmpDetailedBytes[i].SubBytes(13, 1)[0] * 0.1m;
                        detailedField.IPAP = tmpDetailedBytes[i][13] * 0.1f;

                        //------------------------------------------------------------EPAP(40-200)4-20cmH2O
                        //detailedField.EPAP = tmpDetailedBytes[i].SubBytes(14, 1)[0] * 0.1m;
                        detailedField.EPAP = tmpDetailedBytes[i][14] * 0.1f;

                        //呼吸事件对128求余后: 0,无;1低通气,2,呼吸暂停 4,鼾声 .主动 / 被动 :主动 >= 128,被动 < 128;
                        //呼吸事件和

                        //var tmp = tmpDetailedBytes[i].SubBytes(15, 1)[0];
                        var tmp = tmpDetailedBytes[i][15];
                        if (tmp >= 128)
                        {
                            detailedField.TriggerMode = 128;//主动
                        }
                        else
                        {
                            detailedField.TriggerMode = 127;//被动
                        }
                        var vv = tmp % 128;
                        switch (vv)
                        {
                            case 1:
                                detailedField.Events = 1;
                                break;
                            case 2:
                                detailedField.Events = 2;
                                break;
                            case 4:
                                detailedField.Events = 4;
                                break;
                            default:
                                detailedField.Events = 0;
                                break;
                        }
                        //if (vv != 0 && vv != 1 && vv != 2 && vv != 4)//其他值无效
                        //{
                        //    detailedField.Events = 0;
                        //}
                        //else
                        //{
                        //    detailedField.Events = vv;
                        //}
                        //var tmpSingleLevel = tmpDetailedBytes[i][9];
                        //if (detailedField.Events != 0)
                        //    System.Diagnostics.Debug.Print("detailedField.Events " + detailedField.Events);

                        //System.Diagnostics.Debug.Print("tmpDetailedBytes " + tmpDetailedBytes[i].ToHexString());

                        //------------------------------------------------------------血氧0-99
                        //detailedField.SpO2 = tmpDetailedBytes[i].SubBytes(16, 1)[0];
                        detailedField.SpO2 = tmpDetailedBytes[i][16];

                        //------------------------------------------------------------脉率0-255
                        //detailedField.PulseRate = tmpDetailedBytes[i].SubBytes(17, 1)[0];
                        detailedField.PulseRate = tmpDetailedBytes[i][17];

                        #endregion
                        break;
                    //单水品512之后一样
                    case 0x03: //CPAP
                    case 0x04: //APAP

                        #region 处理详细 单水平

                        //------------------------------------------------------------目标压力kpa 0.01 cmH2O 0.1
                        detailedField.TargetPressure = tmpDetailedBytes[i].SubBytes(3, 2).BytesToInt16(0) * 0.1f;

                        //------------------------------------------------------------当前压力kap
                        detailedField.CurrentPressure = tmpDetailedBytes[i].SubBytes(5, 2).BytesToInt16(0) * 0.1f;

                        //------------------------------------------------------------当前流量.有负值
                        //var tmpbytesSingleLevel = tmpDetailedBytes[i].SubBytes(7, 2);

                        //var ttSingleLevel = tmpbytesSingleLevel[0] * 256 + tmpbytesSingleLevel[1];

                        var ttSingleLevel = tmpDetailedBytes[i][7] * 256 + tmpDetailedBytes[i][8];
                        if (ttSingleLevel > short.MaxValue)
                        {
                            detailedField.CurrentFlow = short.MaxValue - ttSingleLevel; //升/分钟
                        }
                        else
                        {
                            detailedField.CurrentFlow = ttSingleLevel; //升/分钟
                        }
                        //tmpbytesSingleLevel = null;

                        //单水平呼吸事件0,无;1低通气,2,呼吸暂停 4,鼾声
                        //var tmpSingleLevel = tmpDetailedBytes[i].SubBytes(9, 1)[0];
                        var tmpSingleLevel = tmpDetailedBytes[i][9];
                        switch (tmpSingleLevel)
                        {
                            case 1:
                                detailedField.Events = 1;
                                break;
                            case 2:
                                detailedField.Events = 2;
                                break;
                            case 4:
                                detailedField.Events = 4;
                                break;
                            default:
                                detailedField.Events = 0;
                                break;
                        }
                        //if (tmpSingleLevel != 0 && tmpSingleLevel != 1 && tmpSingleLevel != 2 && tmpSingleLevel != 4)
                        //{
                        //    detailedField.Events = 0;
                        //}
                        //else
                        //{
                        //    detailedField.Events = tmpSingleLevel;
                        //    //System.Diagnostics.Debug.Print(tmpSingleLevel.ToString());
                        //}

                        //------------------------------------------------------------潮气量(0-2500)mL
                        detailedField.TidalVolume = tmpDetailedBytes[i].SubBytes(10, 2).BytesToInt16(0) * 0.1f;

                        //------------------------------------------------------------漏气量(0-99) L/min
                        //detailedField.Leak = tmpDetailedBytes[i].SubBytes(12, 1)[0];
                        detailedField.Leak = tmpDetailedBytes[i][12];

                        //------------------------------------------------------------分钟通气量(0-30)L/min
                        //detailedField.MinuteVentilation = tmpDetailedBytes[i].SubBytes(13, 1)[0];
                        detailedField.MinuteVentilation = tmpDetailedBytes[i][13];

                        //------------------------------------------------------------血氧0-99
                        //detailedField.SpO2 = tmpDetailedBytes[i].SubBytes(14, 1)[0];
                        detailedField.SpO2 = tmpDetailedBytes[i][14];

                        //------------------------------------------------------------脉率0-255
                        //detailedField.PulseRate = tmpDetailedBytes[i].SubBytes(15, 1)[0];
                        detailedField.PulseRate = tmpDetailedBytes[i][15];

                        #endregion

                        break;
                }

                #endregion

                //lock (objLock)
                //{
                listDetailed.Add(detailedField);
                //}
                //});
            }

            //objLock = null;

            #endregion 同步方法解析

            return listDetailed;
        }
Пример #47
0
        /// <summary>
        /// Creates the operation token from matched string.
        /// </summary>
        /// <param name="match">The matched string.</param>
        /// <param name="tokens">The list of tokens.</param>
        /// <exception cref="LexerException">
        /// The specified operation is not supported.
        /// </exception>
        private void CreateOperations(string match, IList<IToken> tokens)
        {
            if (match == "+=")
            {
                tokens.Add(new OperationToken(Operations.AddAssign));
            }
            else if (match == "-=" || match == "−=")
            {
                tokens.Add(new OperationToken(Operations.SubAssign));
            }
            else if (match == "*=" || match == "×=")
            {
                tokens.Add(new OperationToken(Operations.MulAssign));
            }
            else if (match == "*" || match == "×")
            {
                tokens.Add(new OperationToken(Operations.Multiplication));
            }
            else if (match == "/")
            {
                tokens.Add(new OperationToken(Operations.Division));
            }
            else if (match == "^")
            {
                tokens.Add(new OperationToken(Operations.Exponentiation));
            }
            else if (match == "!")
            {
                var lastToken = tokens.LastOrDefault();
                if (lastToken != null)
                {
                    var symbol = lastToken as SymbolToken;
                    if ((symbol != null && symbol.Symbol == Symbols.CloseBracket) || lastToken is NumberToken || lastToken is VariableToken)
                    {
                        tokens.Add(new OperationToken(Operations.Factorial));
                        return;
                    }
                }

                throw new LexerException(string.Format(Resource.NotSupportedSymbol, match));
            }
            else if (match == "%" || match == "mod")
            {
                tokens.Add(new OperationToken(Operations.Modulo));
            }
            else if (match == "&&")
            {
                tokens.Add(new OperationToken(Operations.ConditionalAnd));
            }
            else if (match == "||")
            {
                tokens.Add(new OperationToken(Operations.ConditionalOr));
            }
            else if (match == "==")
            {
                tokens.Add(new OperationToken(Operations.Equal));
            }
            else if (match == "!=")
            {
                tokens.Add(new OperationToken(Operations.NotEqual));
            }
            else if (match == "<=")
            {
                tokens.Add(new OperationToken(Operations.LessOrEqual));
            }
            else if (match == "<")
            {
                tokens.Add(new OperationToken(Operations.LessThan));
            }
            else if (match == ">=")
            {
                tokens.Add(new OperationToken(Operations.GreaterOrEqual));
            }
            else if (match == ">")
            {
                tokens.Add(new OperationToken(Operations.GreaterThan));
            }
            else if (match == "++")
            {
                tokens.Add(new OperationToken(Operations.Increment));
            }
            else if (match == "--" || match == "−−")
            {
                tokens.Add(new OperationToken(Operations.Decrement));
            }
            else if (match == "+")
            {
                var lastToken = tokens.LastOrDefault();
                if (lastToken == null)
                {
                    return;
                }
                else
                {
                    var symbolToken = lastToken as SymbolToken;
                    if (symbolToken != null && (symbolToken.Symbol == Symbols.OpenBracket ||
                                                symbolToken.Symbol == Symbols.OpenBrace))
                        return;
                }

                tokens.Add(new OperationToken(Operations.Addition));
            }
            else if (match == "-" || match == "−")
            {
                var lastToken = tokens.LastOrDefault();
                if (lastToken == null)
                {
                    tokens.Add(new OperationToken(Operations.UnaryMinus));
                }
                else
                {
                    var symbolToken = lastToken as SymbolToken;
                    if (symbolToken != null && (symbolToken.Symbol == Symbols.OpenBracket ||
                                                symbolToken.Symbol == Symbols.OpenBrace ||
                                                symbolToken.Symbol == Symbols.Comma))
                    {
                        tokens.Add(new OperationToken(Operations.UnaryMinus));
                    }
                    else
                    {
                        var operationToken = lastToken as OperationToken;
                        if (operationToken != null && (operationToken.Operation == Operations.Exponentiation ||
                                                       operationToken.Operation == Operations.Division ||
                                                       operationToken.Operation == Operations.Assign ||
                                                       operationToken.Operation == Operations.AddAssign ||
                                                       operationToken.Operation == Operations.SubAssign ||
                                                       operationToken.Operation == Operations.MulAssign ||
                                                       operationToken.Operation == Operations.DivAssign))
                        {
                            tokens.Add(new OperationToken(Operations.UnaryMinus));
                        }
                        else
                        {
                            tokens.Add(new OperationToken(Operations.Subtraction));
                        }
                    }
                }
            }
            else if (match == "/=")
            {
                tokens.Add(new OperationToken(Operations.DivAssign));
            }
            else if (match == ":=")
            {
                tokens.Add(new OperationToken(Operations.Assign));
            }
            else if (match == "not" || match == "~")
            {
                var lastToken = tokens.LastOrDefault();
                if (lastToken != null)
                {
                    var symbol = lastToken as SymbolToken;
                    if ((symbol != null && symbol.Symbol == Symbols.CloseBracket) || lastToken is NumberToken || lastToken is VariableToken)
                        throw new LexerException(string.Format(Resource.NotSupportedSymbol, match));
                }

                tokens.Add(new OperationToken(Operations.Not));
            }
            else if (match == "and" || match == "&")
            {
                tokens.Add(new OperationToken(Operations.And));
            }
            else if (match == "or" || match == "|")
            {
                tokens.Add(new OperationToken(Operations.Or));
            }
            else if (match == "xor")
            {
                tokens.Add(new OperationToken(Operations.XOr));
            }
            else if (match == "impl" || match == "->" || match == "−>" || match == "=>")
            {
                tokens.Add(new OperationToken(Operations.Implication));
            }
            else if (match == "eq" || match == "<->" || match == "<−>" || match == "<=>")
            {
                tokens.Add(new OperationToken(Operations.Equality));
            }
            else if (match == "nor")
            {
                tokens.Add(new OperationToken(Operations.NOr));
            }
            else if (match == "nand")
            {
                tokens.Add(new OperationToken(Operations.NAnd));
            }
            else
            {
                throw new LexerException(string.Format(Resource.NotSupportedSymbol, match));
            }
        }
 /// <summary>
 /// Mean the specified vectorList.
 /// </summary>
 /// <param name="vectorList">Vector list.</param>
 public static Vector4 Mean(IList<Vector4> vectorList)
 {
     var first = vectorList.FirstOrDefault();
     var last = vectorList.LastOrDefault();
     return first + (last - first) / vectorList.Count;
 }
Пример #49
0
        private CodeMemberMethod CreateCompositeKeyEqualsMethod(IList<string> columns)
        {
            if (columns.Count == 0)
                return null;

            var method = new CodeMemberMethod {
                Name = "Equals",
                ReturnType = new CodeTypeReference(typeof(bool)),
                Attributes = MemberAttributes.Public | MemberAttributes.Override,
            };

            method.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "obj"));

            // Create the if statement to compare if the obj equals another.
            var compareCode = new StringBuilder();

            var className = string.Format("{0}{1}", appPrefs.ClassNamePrefix, Formatter.FormatSingular(Table.Name));

            if (appPrefs.Language == Language.CSharp)
            {
                method.Statements.Add(new CodeSnippetStatement("\t\t\tif (obj == null) return false;"));
                method.Statements.Add(new CodeSnippetStatement(string.Format("\t\t\tvar t = obj as {0};", className)));
                method.Statements.Add(new CodeSnippetStatement("\t\t\tif (t == null) return false;"));

                compareCode.Append("\t\t\tif (");
                var lastCol = columns.LastOrDefault();
                foreach (var column in columns)
                {
                    compareCode.Append(string.Format("{0} == t.{0}", column));
                    compareCode.Append(column != lastCol ? "\n\t\t\t && " : ")");
                }
                method.Statements.Add(new CodeSnippetStatement(compareCode.ToString()));

                method.Statements.Add(new CodeSnippetStatement("\t\t\t\treturn true;"));
                method.Statements.Add(new CodeSnippetStatement(string.Empty));
                method.Statements.Add(new CodeSnippetStatement("\t\t\treturn false;"));
            } else if (appPrefs.Language == Language.VB)
            {
                method.Statements.Add(new CodeSnippetStatement("\t\t\tIf obj Is Nothing Then Return False"));
                method.Statements.Add(new CodeSnippetStatement(string.Format("\t\t\tDim t = TryCast(obj, {0})", className)));
                method.Statements.Add(new CodeSnippetStatement("\t\t\tIf t Is Nothing Then Return False"));

                compareCode.Append("\t\t\tIf ");
                var lastCol = columns.LastOrDefault();
                foreach (var column in columns)
                {
                    compareCode.Append(string.Format("{0} = t.{0}", column));
                    compareCode.Append(column != lastCol ? " AndAlso " : string.Empty);
                }
                method.Statements.Add(new CodeSnippetStatement(compareCode.ToString()));

                method.Statements.Add(new CodeSnippetStatement("\t\t\t\tReturn True"));
                method.Statements.Add(new CodeSnippetStatement("\t\t\tEnd If"));
                method.Statements.Add(new CodeSnippetStatement(string.Empty));
                method.Statements.Add(new CodeSnippetStatement("\t\t\tReturn False"));
            }
            return method;
        }