コード例 #1
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,PersonnelNumber,Name,Position,Department,LocalPhoneNumber,CityPhoneNumber,Mail,Room")] BookEntry bookEntry)
        {
            if (id != bookEntry.Id)
            {
                return(NotFound());
            }

            if (!VerifyPersonnelNumber(bookEntry))
            {
                ModelState.AddModelError(nameof(bookEntry.PersonnelNumber), "Табельный номер уже существует");
            }
            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(bookEntry);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!BookEntryExists(bookEntry.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(bookEntry));
        }
コード例 #2
0
ファイル: Book.cs プロジェクト: cococo111111/Csharp4chess
        /** Add a move to a position in the opening book. */
        private void addToBook(Position pos, Move moveToAdd)
        {
            ulong            key   = pos.zobristHash();
            bool             iskey = bookMap.ContainsKey(key);
            List <BookEntry> ent   = (iskey ? bookMap[key] : null);

            if (ent == null)
            {
                ent = new List <BookEntry>();
                bookMap.Add(pos.zobristHash(), ent);
            }
            for (int i = 0; i < ent.Count; i++)
            {
                BookEntry be = ent[i];
                if (be.move.equals(moveToAdd))
                {
                    be.count++;
                    return;
                }
            }
            BookEntry be2 = new BookEntry(moveToAdd);

            ent.Add(be2);
            numBookMoves++;
        }
コード例 #3
0
        public static PhoneBook ParsePhoneBook(
            string path, char[] splitChars)
        {
            if (!File.Exists(path))
            {
                return null;
            }

            var phonebook = new PhoneBook();

            using (TextReader reader = new StreamReader(path))
            {
                string nextLine;
                while ((nextLine = reader.ReadLine()) != null)
                {
                    string[] elements = nextLine.Split(splitChars);
                    var entry = new BookEntry
                    {
                        Name = elements[0].Trim(),
                        Town = elements[1].Trim(),
                        Phone = elements[2].Trim()
                    };

                    // Since entry is reference type the book entry is shared among all
                    // tables and the memory it takes is not trippled
                    phonebook.Names.Add(entry.Name, entry);
                    phonebook.Towns.Add(entry.Town, entry);
                    phonebook.Phones.Add(entry.Phone, entry);
                }
            }

            return phonebook;
        }
コード例 #4
0
 /// <summary>
 /// Changes id for entry by removing from db, updating id, then re-inserting
 /// </summary>
 public void ChangeBookId(BookEntry book, int Id)
 {
     Logger.Info("Changing {} ID from [{}] to [{}]", book.Title, book.Id, Id);
     RemoveBook(book);
     book.Id = Id;
     AddBook(book);
 }
コード例 #5
0
            public static BookEntry?ReadEntry([NotNull] Stream stream)
            {
                _buffer ??= new byte[DataLength];

                var bytesRead = stream.Read(_buffer, 0, DataLength);

                if (bytesRead == 0)
                {
                    return(null);
                }

                if (bytesRead != DataLength)
                {
                    throw new InvalidOperationException(
                              $@"Error reading the stream. Bytes read: {bytesRead}. Bytes required: {DataLength}.");
                }

                ReverseBufferSlotsIfNeeded();

                var offset = 0;
                var key    = BitConverter.ToUInt64(_buffer, offset);

                offset += sizeof(ulong);
                var move = BitConverter.ToUInt16(_buffer, offset);

                offset += sizeof(ushort);
                var weight = BitConverter.ToUInt16(_buffer, offset);

                offset += sizeof(ushort);
                var learn = BitConverter.ToUInt32(_buffer, offset);

                var result = new BookEntry(key, move, weight, learn);

                return(result);
            }
コード例 #6
0
    protected void cmdSubmit_Click(Object sender, EventArgs e)
    {
        // Create a new BookEntry object.
        BookEntry newEntry = new BookEntry();

        newEntry.Author    = txtName.Text;
        newEntry.Submitted = DateTime.Now;
        newEntry.Message   = txtMessage.Text;

        // Let the SaveEntry procedure create the corresponding file.
        try
        {
            SaveEntry(newEntry);
        }
        catch (Exception err)
        {
            // An error occurred. Notify the user and don't clear the
            // display.
            lblError.Text = err.Message + " File not saved.";
            return;
        }

        // Refresh the display.
        GuestBookList.DataSource = GetAllEntries();
        GuestBookList.DataBind();
        txtName.Text    = "";
        txtMessage.Text = "";
    }
コード例 #7
0
 /// <summary>
 /// Forces CollectionChanged even on ObservableCollection by moving a book (but not really)
 /// </summary>
 public void RefreshBook(BookEntry book)
 {
     App.Current.Dispatcher.Invoke(() =>
     {
         int index = BOOKS.IndexOf(book);
         BOOKS.Move(index, index);
     });
 }
コード例 #8
0
ファイル: Book.cs プロジェクト: cococo111111/Csharp4chess
        /** Return a random book move for a position, or null if out of book. */
        public Move getBookMove(Position pos)
        {
            long             t0        = SystemHelper.currentTimeMillis();
            Random           rndGen    = new Random((int)t0);
            ulong            key       = pos.zobristHash();
            bool             iskey     = bookMap.ContainsKey(key);
            List <BookEntry> bookMoves = (iskey ? bookMap[key] : null);

            if (bookMoves == null)
            {
                return(null);
            }

            MoveGen.MoveList legalMoves = new MoveGen().pseudoLegalMoves(pos);
            MoveGen.RemoveIllegal(pos, legalMoves);
            int sum = 0;

            for (int i = 0; i < bookMoves.Count; i++)
            {
                BookEntry be       = bookMoves[i];
                bool      contains = false;
                for (int mi = 0; mi < legalMoves.size; mi++)
                {
                    if (legalMoves.m[mi].equals(be.move))
                    {
                        contains = true;
                        break;
                    }
                }
                if (!contains)
                {
                    // If an illegal move was found, it means there was a hash collision.
                    return(null);
                }
                sum += getWeight(bookMoves[i].count);
            }
            if (sum <= 0)
            {
                return(null);
            }
            int rnd = rndGen.Next(sum);

            sum = 0;
            for (int i = 0; i < bookMoves.Count; i++)
            {
                sum += getWeight(bookMoves[i].count);
                if (rnd < sum)
                {
                    return(bookMoves[i].move);
                }
            }
            // Should never get here
            throw new RuntimeException();
        }
コード例 #9
0
 private void btnAckBooking_Click(object sender, RoutedEventArgs e)
 {
     if (lstBookings.SelectedItem != null)
     {
         BookEntry entry = (BookEntry)lstBookings.SelectedItem;
         if (!entry.Booked)
         {
             _stockAccounts.Book(entry.DebitAccount.Name, entry.CreditAccount.Name, entry.Ammount);
         }
     }
 }
コード例 #10
0
    private BookEntry GetEntryFromFile(FileInfo entryFile)
    {
        // Turn the file information into a Book Entry object.
        BookEntry    newEntry = new BookEntry();
        StreamReader r        = entryFile.OpenText();

        newEntry.Author    = r.ReadLine();
        newEntry.Submitted = DateTime.Parse(r.ReadLine());
        newEntry.Message   = r.ReadLine();
        r.Close();

        return(newEntry);
    }
コード例 #11
0
        public void SaveBook(Book currentBook)
        {
            var entry = new BookEntry {
                Book = currentBook, UserName = m_SettingsService.Get <string>("UserName")
            };
            var doc = m_DataBase.CreateDocument();

            doc.Update(rev =>
            {
                rev.SetUserProperties(entry.ToDictionary());
                return(true);
            });
        }
コード例 #12
0
        public void RemoveBook(int id)
        {
            Logger.Info("Removing ID [{}] from database.", id);
            var c = db.GetCollection <BookEntry>("BOOKS");

            c.Delete(x => x.Id == id);
            BookEntry m = BOOKS.FirstOrDefault(x => x.Id == id);

            if (m != null)
            {
                BOOKS.Remove(m);
            }
        }
コード例 #13
0
        public async Task <IActionResult> Create([Bind("Id,PersonnelNumber,Name,Position,Department,LocalPhoneNumber,CityPhoneNumber,Mail,Room")] BookEntry bookEntry)
        {
            if (!VerifyPersonnelNumber(bookEntry))
            {
                ModelState.AddModelError(nameof(bookEntry.PersonnelNumber), "Табельный номер уже существует");
            }
            if (ModelState.IsValid)
            {
                _context.Add(bookEntry);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(bookEntry));
        }
コード例 #14
0
        internal PolyglotOpeningBook([NotNull] Stream stream)
        {
            if (stream is null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (!stream.CanRead)
            {
                throw new ArgumentException(@"The stream cannot be read.", nameof(stream));
            }

            var capacity = 128; // Guesstimate

            if (stream.CanSeek)
            {
                var streamLength = stream.Length - stream.Position;
                var quotient     = Math.DivRem(streamLength, BookEntry.DataLength, out var remainder);

                if (remainder != 0)
                {
                    throw new ArgumentException(
                              $@"Invalid opening book stream length ({streamLength}).",
                              nameof(stream));
                }

                capacity = (int)Math.Min(quotient, int.MaxValue);
            }

            var entries = new List <BookEntry>(capacity);

            while (true)
            {
                var entry = BookEntry.ReadEntry(stream);
                if (!entry.HasValue)
                {
                    break;
                }

                entries.Add(entry.Value);
            }

            _entryMap = entries
                        .ToLookup(entry => entry.Key)
                        .ToDictionary(grouping => grouping.Key, grouping => grouping.ToArray());
        }
コード例 #15
0
    private void SaveEntry(BookEntry entry)
    {
        // Create a new file for this entry, with a file name that should
        // be statistically unique.
        Random random   = new Random();
        string fileName = guestBookName + @"\";

        fileName += DateTime.Now.Ticks.ToString() + random.Next(100).ToString();
        FileInfo     newFile = new FileInfo(fileName);
        StreamWriter w       = newFile.CreateText();

        // Write the information to the file.
        w.WriteLine(entry.Author);
        w.WriteLine(entry.Submitted.ToString());
        w.WriteLine(entry.Message);
        w.Flush();
        w.Close();
    }
コード例 #16
0
        private BookEntry TryGetBookName(string text, int startIndex, int indexOfDigit)
        {
            BookEntry bookEntry = null;

            if (startIndex >= 0 && indexOfDigit - startIndex > 1)
            {
                var endIndex            = GetBookEndIndex(text, indexOfDigit);
                var bookPotentialString = text.Substring(startIndex, endIndex - startIndex + 1);
                bookEntry = GetBookName(bookPotentialString, text[endIndex + 1] == '.');  // здесь text[endIndex + 1] не выдаст исключения, так как до этого мы работали с бОльшими индексами.
                if (bookEntry != null)
                {
                    bookEntry.StartIndex += startIndex;
                    bookEntry.EndIndex    = endIndex;
                }
            }

            return(bookEntry);
        }
コード例 #17
0
        /// <summary>
        /// Updates BOOKS entry with matching Id
        /// Raises exception if filename not in colletion
        /// </summary>
        public void UpdateBook(BookBase update)
        {
            var       col     = db.GetCollection <BookEntry>("BOOKS");
            BookEntry dbEntry = col.FindOne(x => x.Id == update.Id);

            if (dbEntry == null)
            {
                throw new IDNotFoundException($"{update.FilePath} not found in library");
            }

            BookEntry tableRow = BOOKS.First(x => x.Id == update.Id);

            dbEntry = new BookEntry(update);
            tableRow.CopyFrom(update);

            col.Update(dbEntry);

            RefreshBook(tableRow);
        }
コード例 #18
0
        public void AddBook(BookBase book)
        {
            Logger.Info("Adding {} [{}] to database.", book.Title, book.Id);
            if (BOOKS.Any(x => x.Id == book.Id))
            {
                throw new LiteException($"{book.FilePath} [{book.Id}] already exists in library");;
            }

            BookEntry entry = new BookEntry(book);

            entry.DateAdded = DateTime.Now.ToString("M/d/yyyy");

            entry.Id = book.Id != 0 ? book.Id : NextID();

            db.GetCollection <BookEntry>("BOOKS").Insert(entry);

            // ObservableCollections *must* be updated from the main/ui thread
            App.Current.Dispatcher.Invoke(() =>
            {
                BOOKS.Add(entry);
            });
        }
コード例 #19
0
ファイル: BooksController.cs プロジェクト: Grigann/PopWeb
        /// <summary>
        /// Saves a new reading session and creates a new book if necessary
        /// </summary>
        /// <param name="bookEntry">A book entry</param>
        /// <returns>A JSON representation of a timeline entry</returns>
        public JsonResult QuickSave(BookEntry bookEntry)
        {
            // Used to emulate a failure
            if (bookEntry.Writer == "FAIL") {
                throw new Exception("Une erreur");
            }

            ReadingSession readingSession;
            using (var uow = new UnitOfWork(true)) {
                var book = uow.Books.FindByTitle(bookEntry.Title) ??
                           new Book() { Title = bookEntry.Title, Writer = bookEntry.Writer };

                readingSession = new ReadingSession() {
                    Date = DateTime.ParseExact(bookEntry.EntryDate, "dd/MM/yyyy", null),
                    Note = bookEntry.Note };
                book.AddReadingSession(readingSession);

                uow.Books.SaveOrUpdate(book);
                uow.Commit();
            }

            var timelineEntry = new TimelineEntry(readingSession, this);
            return Json(timelineEntry);
        }
コード例 #20
0
        private void TT6(BinanceOrderBook obj)
        {
            var BestAsk = (List <BinanceOrderBookEntry>)obj.Asks;
            var BestBid = (List <BinanceOrderBookEntry>)obj.Bids;

            BookEntry Entry = new BookEntry(BestAsk[0].Price, BestBid[0].Price, obj.LastUpdateId);


            Logger.Info(string.Format("Spread : {0}", Entry.PriceSpread));
            Logger.Info(string.Format("MediumPrice : {0}", Entry.MediumPrice));
            Logger.Info(string.Format("Ask : {0}", Entry.Ask));
            Logger.Info(string.Format("Bid : {0}", Entry.Bid));

            if (Entry.PriceSpread > 1)
            {
                this.RemoveAllDirectionOrder(Binance.Net.Objects.OrderSide.Sell);
                this.PlaceOrder("BTCUSDT", Binance.Net.Objects.OrderSide.Buy, Binance.Net.Objects.OrderType.Limit, decimal.Round(.0022m, 4), decimal.Round(Entry.Bid, 2));
            }
            if (Entry.NegativeSpread < -1)
            {
                this.RemoveAllDirectionOrder(Binance.Net.Objects.OrderSide.Buy);
                this.PlaceOrder("BTCUSDT", Binance.Net.Objects.OrderSide.Sell, Binance.Net.Objects.OrderType.Limit, decimal.Round(.0022m, 4), decimal.Round(Entry.Ask, 2));
            }
        }
コード例 #21
0
 public void RemoveBook(BookEntry book)
 {
     Logger.Info("Removing {} [{}] from database.", book.Title, book.Id);
     db.GetCollection <BookEntry>("BOOKS").Delete(x => x.Id == book.Id);
     BOOKS.Remove(book);
 }
コード例 #22
0
 private bool VerifyPersonnelNumber(BookEntry entry)
 {
     return(VerifyPersonnelNumber(entry.PersonnelNumber, entry.Id));
 }
コード例 #23
0
ファイル: SearchListViewModel.cs プロジェクト: jstoe/BooksApp
 private void DeleteItem(BookEntry item)
 {
     InvokeOnMainThread(() => Books.Remove(item));
 }
コード例 #24
0
 public BookEntryAdapter(BookEntry src)
 {
     Price  = src.Price;
     Volume = src.Volume;
 }
コード例 #25
0
ファイル: SearchListViewModel.cs プロジェクト: jstoe/BooksApp
 private async void ShareItem(BookEntry entry)
 {
     await m_Chat.Send(JsonConvert.SerializeObject(entry));
 }
コード例 #26
0
ファイル: Book.cs プロジェクト: Chessforeva/Csharp4chess
 /** Add a move to a position in the opening book. */
 private void addToBook(Position pos, Move moveToAdd)
 {
     ulong key = pos.zobristHash();
     bool iskey = bookMap.ContainsKey(key);
     List<BookEntry> ent = (iskey ? bookMap[key] : null );
     if (ent == null) {
     ent = new List<BookEntry>();
     bookMap.Add( pos.zobristHash(), ent);
     }
     for (int i = 0; i < ent.Count; i++) {
     BookEntry be = ent[i];
     if (be.move.equals(moveToAdd)) {
         be.count++;
         return;
     }
     }
     BookEntry be2 = new BookEntry(moveToAdd);
     ent.Add(be2);
     numBookMoves++;
 }