public bool hasCorrectInput(string input) { // get initial state var current = InitialState; // loop to get next state foreach (char c in input) { if (current == null) { return(false); } if (!Alphabets.Contains(c)) { throw new ArgumentException("Character is not in alphabet list!"); } else { current = Table.GetNextStates(current, c); } } // check if the current state is final return(isFinalState(current)); }
public void ExistingBoard() { GameBoard board = new GameBoard(new char[4, 4] { { 'y', 'o', 'x', 'f' }, { 'y', 'o', 'x', 'u' }, { 'r', 'b', 'a', 'n' }, { 'v', 'e', 'd', 'd' } }); // Load the Alphabet Alphabet alphabet = Alphabets.Load("en-us"); // Load the Dictionary Dictionary dict = Dictionaries.Load("english-words"); BoardSolution sol = BoardConstructor.Solve(alphabet, dict, board); string solboard = sol.SolvedBoard.ToString(); int words = sol.SolutionWords.Count; Assert.InRange(words, 1, int.MaxValue); Assert.Equal(24, solboard.Length); Assert.Equal(4, sol.SolvedBoard.Size); Assert.Equal("en-us", sol.AlphabetId); Assert.Equal("english-words", sol.DictionaryId); }
public bool isHavingCorrectTransitions() { int counter = 0; int expectedResult = Alphabets.Count() * States.Count(); // check if all the states has all the alphabets with the correct transitions foreach (var t in Transitions) { foreach (var s in States) { if (t.CurrentState.Name == s.Name) { foreach (var a in Alphabets) { if (t.Token == a) { counter++; } } } } } if (counter != expectedResult) { return(false); } return(true); }
private void DownClick(object sender, RoutedEventArgs e) { FrameworkElement ele = sender as FrameworkElement; if (ele == null) { return; } var alp = (AlphabetItem)ele.DataContext; var index = Alphabets.IndexOf(alp); AlphabetItem tmp = null; if (ActiveAlphabet == alp) { tmp = alp; } index--; if (index > -1) { Alphabets.Remove(alp); Alphabets.Insert(index, alp); if (tmp != null) { ActiveAlphabet = alp; } } AlphabetCollectionView.Refresh(); }
/* * проверяет, что строка сожержит только буквы соответствующего алфавита * string word - строка для проверки * string alphabet - строка идетификатор алфивита, может принимать значения из перечисления Alphabets * out string errorMessage - выходной параметр, срока сообщения об ошибке */ public static bool ValidText(string word, Alphabets alphabet, out string errorMessage) { if (String.IsNullOrEmpty(word)) { errorMessage = "Текст обязательный"; return(false); } string regEx = ""; if (alphabet == Alphabets.Ru) { regEx = "^[А-Яа-я]+$"; } else if (alphabet == Alphabets.En) { regEx = "^[A-Za-z]+$"; } if (Regex.IsMatch(word, regEx)) { errorMessage = String.Empty; return(true); } errorMessage = "Слово должно состоять только из " + alphabet + " алфавита"; return(false); }
/// <summary> /// Parses one line from the text file. /// </summary> /// <param name="line"></param> /// <returns></returns> private ISequence ParseLine(string line) { string[] splitLine = line.Split(this.Delimiter); if (splitLine.Length != 2) { throw new Exception(string.Format(CultureInfo.InvariantCulture, Resource.INVALID_INPUT_FILE, line)); } IAlphabet alphabet = this.Alphabet; if (alphabet == null) { byte[] byteArray = Encoding.UTF8.GetBytes(splitLine[1]); alphabet = Alphabets.AutoDetectAlphabet(byteArray, 0, byteArray.Length, null); if (alphabet == null) { throw new Exception(string.Format(CultureInfo.InvariantCulture, Resource.InvalidSymbolInString, splitLine[1])); } } return(new Sequence(alphabet, splitLine[1]) { ID = splitLine[0] }); }
/// <summary> /// Analyze the given sequences and store a consensus into its Consensus property. /// </summary> /// <param name="referenceSequence">Reference sequence.</param> /// <param name="querySequence">Query sequence.</param> /// <returns>Consensus of sequences.</returns> protected ISequence MakeConsensus( ISequence referenceSequence, ISequence querySequence) { if (referenceSequence == null) { throw new ArgumentNullException("referenceSequence"); } if (querySequence == null) { throw new ArgumentNullException("querySequence"); } // For each pair of symbols (characters) in reference and query sequence // get the consensus symbol and append it. byte[] consensus = new byte[referenceSequence.Count]; for (int index = 0; index < referenceSequence.Count; index++) { consensus[index] = ConsensusResolver.GetConsensus( new byte[] { referenceSequence[index], querySequence[index] }); } IAlphabet alphabet = Alphabets.AutoDetectAlphabet(consensus, 0, consensus.LongLength, referenceSequence.Alphabet); return(new Sequence(alphabet, consensus, false)); }
public void LoadAlphabets() { // Load the Alphabet Alphabet alphabet = Alphabets.Load("en-us"); Assert.Equal(26, alphabet.letters.Count); }
/// <summary> /// Validates input sequences and gap penalties. /// Checks that input sequences use the same alphabet. /// Checks that each symbol in the input sequences exists in the similarity matrix. /// Checks that gap penalties are less than or equal to 0. /// Throws exception if sequences fail these checks. /// Writes warning to ApplicationLog if gap penalty or penalties are positive. /// </summary> /// <param name="inputA">First input sequence.</param> /// <param name="inputB">Second input sequence.</param> protected void ValidateAlignInput(ISequence inputA, ISequence inputB) { if (inputA == null) { throw new ArgumentNullException("inputA"); } if (inputB == null) { throw new ArgumentNullException("inputB"); } if (!Alphabets.CheckIsFromSameBase(inputA.Alphabet, inputB.Alphabet)) { throw new ArgumentException(Properties.Resource.InputAlphabetsMismatch); } if (null == this.InternalSimilarityMatrix) { throw new ArgumentException(Properties.Resource.SimilarityMatrixCannotBeNull); } if (!this.InternalSimilarityMatrix.ValidateSequence(inputA)) { throw new ArgumentException(Properties.Resource.FirstInputSequenceMismatchSimilarityMatrix); } if (!this.InternalSimilarityMatrix.ValidateSequence(inputB)) { throw new ArgumentException(Properties.Resource.SecondInputSequenceMismatchSimilarityMatrix); } }
public No29_ReturnIteratorNotCollection() { //目的: //①シーケンス(IEnumerable<T>)の初期化・作成を便利に実現し、利用者に選択肢を与える //概要: //-------------------------------------------------------------------------------------- //集合を生成するメソッドを作成する場合、コレクション(List,Dictionary)でなく //シーケンス(IEnumerable)返すメソッドをイテレータメソッドとして実装する //そうすることで、利用者が任意のタイミングでコレクション化でき、性能劣化を引き起こさない //利用時 foreach (var alph in Alphabets.Generate()) { Console.WriteLine(alph); } //作成時にチェックを入れる var sequence = Alphabets.GenerateSubSet('c', 'r'); //ここでエラーがでる //var sequence = Alphabets.GenerateSubSet('c', 'a'); foreach (var alph in sequence) { Console.WriteLine(alph); } }
/// <summary> /// Build the HTTP content for the request based on the parameters /// </summary> /// <returns>The request.</returns> public HttpContent BuildRequest(BlastRequestParameters blastParams) { if (string.IsNullOrWhiteSpace(blastParams.Database)) { throw new ArgumentException("Database must be supplied."); } if (string.IsNullOrWhiteSpace(blastParams.Program)) { throw new ArgumentException("Program must be supplied."); } if (blastParams.Sequences.Count == 0) { throw new ArgumentException("Must have at least one sequence."); } // Check that all sequences are same alphabet if (blastParams.Sequences.Count > 1) { ISequence primary = blastParams.Sequences[0]; for (int i = 1; i < blastParams.Sequences.Count; i++) { if (!Alphabets.CheckIsFromSameBase(primary.Alphabet, blastParams.Sequences[i].Alphabet)) { throw new ArgumentException("Sequences must all share the same base alphabet."); } } } var data = new List <KeyValuePair <string, string> > { this.CreateKVP("CMD", "Put") }; if (blastParams.Program == BlastProgram.Megablast) { data.Add(this.CreateKVP("PROGRAM", BlastProgram.Blastn)); data.Add(this.CreateKVP("MEGABLAST", "ON")); } else { data.Add(this.CreateKVP("PROGRAM", blastParams.Program)); } data.Add(this.CreateKVP("DATABASE", blastParams.Database)); data.AddRange(blastParams.ExtraParameters); // Add the sequences. StringBuilder sb = new StringBuilder(); foreach (var seq in blastParams.Sequences) { sb.Append(seq.ConvertToString()); } data.Add(this.CreateKVP("QUERY", sb.ToString())); return(new FormUrlEncodedContent(data)); }
public Tritemius(Alphabets.Alphabet _alphabet, int _a, int _b, int _c) { alphabet = _alphabet; A = _a; B = _b; C = _c; stringKey = false; }
/// <summary> /// Sets up fields for the assembly process. /// </summary> private void Initialize() { this.currentStep = 0; this.progressTimer = new Timer(ProgressTimerInterval); this.progressTimer.Elapsed += new ElapsedEventHandler(this.ProgressTimerElapsed); this.statusMessage = string.Format(CultureInfo.CurrentCulture, Properties.Resource.InitializingStarted, DateTime.Now); this.RaiseStatusEvent(); // Reset parameters not set by user, based on sequenceReads if (this.AllowKmerLengthEstimation) { this.kmerLength = EstimateKmerLength(this.sequenceReads); } else { if (this.kmerLength <= 0) { throw new InvalidOperationException(Properties.Resource.KmerLength); } try { if (!Alphabets.CheckIsFromSameBase(this.sequenceReads.First().Alphabet, Alphabets.DNA)) { throw new InvalidOperationException(Properties.Resource.CannotAssembleSequenceType); } } catch (Exception e) { if (e.InnerException != null && !string.IsNullOrEmpty(e.InnerException.Message)) { throw e.InnerException; } else { throw; } } } if (this.dangleThreshold == -1) { this.dangleThreshold = this.kmerLength + 1; } if (this.redundantPathLengthThreshold == -1) { // Reference for default threshold for redundant path purger: // ABySS Release Notes 1.1.2 - "Pop bubbles shorter than N bp. The default is b=3*(k + 1)." this.redundantPathLengthThreshold = 3 * (this.kmerLength + 1); } this.InitializeDefaultGraphModifiers(); this.statusMessage = string.Format(CultureInfo.CurrentCulture, Properties.Resource.InitializingEnded, DateTime.Now); this.RaiseStatusEvent(); }
public bool AddAlphabet(char alphabet) { if (!Alphabets.Contains(alphabet)) { Alphabets.Add(alphabet); return(true); } return(false); }
void TestBoardRandomizer() { string debug; GameBoard board = null; board = BoardRandomizer.GenerateRandom(4, Alphabets.Load("en-us")); Assert.Equal(4, board.Size); debug = board.ToString(); }
/// <summary> /// Parses the GenBank Origin data from the GenBank file. /// </summary> /// <param name="line">parse line</param> /// <param name="metadata">The GenBank metadata.</param> /// <param name="stream">The stream reader.</param> private void ParseOrigin(ref string line, GenBankMetadata metadata, StreamReader stream) { // The origin line can contain optional data; don't put empty string into // metadata. string lineData = GetLineData(line, DataIndent); if (!String.IsNullOrEmpty(lineData)) { metadata.Origin = lineData; } line = GoToNextLine(line, stream); IAlphabet alphabet = null; var sequenceBuilder = new StringBuilder(); while ((line != null) && line[0] == ' ') { // Using a regex is too slow. int len = line.Length; int k = 10; while (k < len) { string seqData = line.Substring(k, Math.Min(10, len - k)); sequenceBuilder.Append(seqData); k += 11; } line = GoToNextLine(line, stream); } var sequenceString = sequenceBuilder.ToString().Trim(); if (!string.IsNullOrEmpty(sequenceString)) { if (Alphabet == null) { byte[] tempData = System.Text.Encoding.ASCII.GetBytes(sequenceString.ToUpper(CultureInfo.InvariantCulture)); alphabet = Alphabets.AutoDetectAlphabet(tempData, 0, tempData.Length, alphabet); if (alphabet == null) { var message = String.Format(CultureInfo.InvariantCulture, Properties.Resource.InvalidSymbolInString, line); Trace.Report(message); throw new InvalidDataException(message); } } else { alphabet = Alphabet; } sequenceWithData = new Sequence(alphabet, sequenceString); } }
public bool RemoveAlphabet(char alphabet) { if (Alphabets.Contains(alphabet)) { RemoveInstructionsInvolvingAlphabet(alphabet); Alphabets.Remove(alphabet); return(true); } return(false); }
public override async Task OnNavigatedToAsync(INavigationParameters parameters) { if (parameters.GetNavigationMode() == NavigationMode.New) { await syncData(); } Request = parameters.GetValue <EvlRequestItemSource>(nameof(Request)); SelectedCar = Request.LostCarId != 0 ? Cars.FirstOrDefault(c => c.PrmID == Request.LostCarId) : new ExternalEntityDto(); LostLicense = !string.IsNullOrEmpty(Request.LostPlateNumber) ? _licenseHelper.ConvertToItemSource(Request.LostPlateNumber) : new LicensePlateItemSource(); SelectedAlphabet = LostLicense != null?Alphabets.FirstOrDefault(c => c.Name == LostLicense.Alphabet) : new ExternalEntityDto(); }
public IActionResult CaesarVisualization([FromBody] CaesarCipherViewModel viewModel) { CaesarCipher cipher = new CaesarCipher(viewModel.Key) { Alphabet = Alphabets.GetAlphabet((Alphabets.AlphabetType)viewModel.AlphabetType) }; cipher.Alphabet = Alphabets.GetAlphabet((Alphabets.AlphabetType)viewModel.AlphabetType); string[] results = new string[4] { "alphabet", "newalphabet", "output", "input" }; string encrypted = ""; string input = viewModel.Message; input = StringHelper.ReplaceWhitespace(input, ""); input = input.ToUpper(); int alphabetLength = cipher.Alphabet.Length; int newKey = (viewModel.Key) % alphabetLength; string cipherAlphabet = ""; for (int i = 0; i < alphabetLength; i++) { if ((i + newKey) >= alphabetLength) { cipherAlphabet += cipher.Alphabet[i + newKey - alphabetLength]; } else { cipherAlphabet += cipher.Alphabet[i + newKey]; } } results[0] = cipher.Alphabet; results[1] = cipherAlphabet; results[3] = input; try { encrypted = cipher.Encrypt(viewModel.Message); results[2] = encrypted; } catch (NullReferenceException) { } catch (Exception) { return(BadRequest(new { Result = false, Message = Text.InvalidCharacter })); } return(Json(results)); }
public Shtirlits(Alphabets.Alphabet alphabet) { StringBuilder row = new StringBuilder(); foreach (var letter in alphabet.Letters) { if(letter == '\n') { alphabetMass.Add(row.ToString()); row.Clear(); continue; } row.Append(letter); } }
/// <summary> /// Adds consensus to the alignment result. At this point, it is a very simple algorithm /// which puts an ambiguity character where the two aligned sequences do not match. /// Uses X and N for protein and DNA/RNA alignments, respectively. /// </summary> /// <param name="alignment"> /// Alignment to which to add the consensus. This is the result returned by the main Align /// or AlignSimple method, which contains the aligned sequences but not yet a consensus sequence. /// </param> private void AddSimpleConsensusToResult(PairwiseAlignedSequence alignment) { ISequence seq0 = alignment.FirstSequence; ISequence seq1 = alignment.SecondSequence; byte[] consensus = new byte[seq0.Count]; for (int i = 0; i < seq0.Count; i++) { consensus[i] = ConsensusResolver.GetConsensus( new byte[] { seq0[i], seq1[i] }); } IAlphabet consensusAlphabet = Alphabets.AutoDetectAlphabet(consensus, 0, consensus.GetLongLength(), seq0.Alphabet); alignment.Consensus = new Sequence(consensusAlphabet, consensus, false); }
/// <summary> /// Validates input sequences and gap penalties. /// Checks that input sequences use the same alphabet. /// Checks that each symbol in the input sequences exists in the similarity matrix. /// Checks that gap penalties are less than or equal to 0. /// Throws exception if sequences fail these checks. /// Writes warning to ApplicationLog if gap penalty or penalties are positive. /// </summary> /// <param name="inputA">First input sequence.</param> /// <param name="inputB">Second input sequence.</param> protected void ValidateAlignInput(ISequence inputA, ISequence inputB) { if (inputA == null) { throw new ArgumentNullException("inputA"); } if (inputB == null) { throw new ArgumentNullException("inputB"); } if (!Alphabets.CheckIsFromSameBase(inputA.Alphabet, inputB.Alphabet)) { Trace.Report(Properties.Resource.InputAlphabetsMismatch); throw new ArgumentException(Properties.Resource.InputAlphabetsMismatch); } if (null == internalSimilarityMatrix) { Trace.Report(Properties.Resource.SimilarityMatrixCannotBeNull); throw new ArgumentException(Properties.Resource.SimilarityMatrixCannotBeNull); } if (!internalSimilarityMatrix.ValidateSequence(inputA)) { Trace.Report(Properties.Resource.FirstInputSequenceMismatchSimilarityMatrix); throw new ArgumentException(Properties.Resource.FirstInputSequenceMismatchSimilarityMatrix); } if (!internalSimilarityMatrix.ValidateSequence(inputB)) { Trace.Report(Properties.Resource.SecondInputSequenceMismatchSimilarityMatrix); throw new ArgumentException(Properties.Resource.SecondInputSequenceMismatchSimilarityMatrix); } // Warning if gap penalty > 0 if (GapOpenCost > 0) { ApplicationLog.WriteLine("Gap Open Penalty {0} > 0, possible error", GapOpenCost); } if (GapExtensionCost > 0) { ApplicationLog.WriteLine("Gap Extension Penalty {0} > 0, possible error", GapExtensionCost); } }
public IActionResult VigenereVisualization([FromBody] VigenereCipherViewModel viewModel) { VigenereCipher cipher = new VigenereCipher (viewModel.Key, Alphabets.GetAlphabet((Alphabets.AlphabetType)viewModel.AlphabetType)); cipher.Alphabet = Alphabets.GetAlphabet((Alphabets.AlphabetType)viewModel.AlphabetType); string[] results = new string[4] { "alphabet", "output", "input", "key" }; string encrypted = ""; string input = viewModel.Message; input = StringHelper.ReplaceWhitespace(input, ""); input = input.ToUpper(); int alphabetLength = cipher.Alphabet.Length; results[0] = cipher.Alphabet; results[2] = input; try { encrypted = cipher.Encrypt(viewModel.Message); results[1] = encrypted; var key = new StringBuilder(); int keyIndex = 0; for (int i = 0; i < input.Length; i++) { key.Append(cipher.Key[keyIndex]); keyIndex++; if (keyIndex >= cipher.Key.Length) { keyIndex = 0; } } results[3] = key.ToString(); } catch (NullReferenceException) { } catch (Exception) { return(BadRequest(new { Result = false, Message = Text.InvalidCharacter })); } return(Json(results)); }
public void ValidateAutoDetectAlphabet() { string alphabetName = utilityObj.xmlUtil.GetTextValue( Constants.DnaDerivedSequenceNode, Constants.AlphabetNameNode); string dnaSequence = utilityObj.xmlUtil.GetTextValue( Constants.DnaDerivedSequenceNode, Constants.ExpectedDerivedSequence); byte[] dnaArray = encodingObj.GetBytes(dnaSequence); //Validating for Dna. IAlphabet dnaAplhabet = Alphabets.AutoDetectAlphabet(dnaArray, 0, 4, null); Assert.AreEqual(dnaAplhabet.Name, alphabetName); ApplicationLog.WriteLine(string.Concat( "Alphabets BVT: Validation of Auto Detect method for Dna completed successfully.")); //Validating for Rna. alphabetName = ""; alphabetName = utilityObj.xmlUtil.GetTextValue( Constants.RnaDerivedSequenceNode, Constants.AlphabetNameNode); string rnaSequence = utilityObj.xmlUtil.GetTextValue( Constants.RnaDerivedSequenceNode, Constants.ExpectedDerivedSequence); byte[] rnaArray = encodingObj.GetBytes(rnaSequence); IAlphabet rnaAplhabet = Alphabets.AutoDetectAlphabet(rnaArray, 0, 4, null); Assert.AreEqual(rnaAplhabet.Name, alphabetName); ApplicationLog.WriteLine(string.Concat( "Alphabets BVT: Validation of Auto Detect method for Rna completed successfully.")); //Validating for Protein. alphabetName = ""; alphabetName = utilityObj.xmlUtil.GetTextValue( Constants.ProteinDerivedSequenceNode, Constants.AlphabetNameNode); string proteinSequence = utilityObj.xmlUtil.GetTextValue( Constants.ProteinDerivedSequenceNode, Constants.ExpectedDerivedSequence); byte[] proteinArray = encodingObj.GetBytes(proteinSequence); IAlphabet proteinAplhabet = Alphabets.AutoDetectAlphabet(proteinArray, 0, 4, null); Assert.AreEqual(proteinAplhabet.Name, alphabetName); ApplicationLog.WriteLine(string.Concat( "Alphabets BVT: Validation of Auto Detect method for Protein completed successfully.")); }
public override async Task OnNavigatedToAsync(INavigationParameters parameters) { if (parameters.TryGetValue(nameof(InsuranceType), out InsuranceType insuranceType)) { Request.InsuranceType = insuranceType; } if (parameters.GetNavigationMode() == NavigationMode.New) { requestCancellationTokenSource?.Cancel(); requestCancellationTokenSource = new CancellationTokenSource(); using (_userDialogs.Loading(ConstantStrings.Loading, cancelText: ConstantStrings.Loading_Cancel, onCancel: requestCancellationTokenSource.Cancel)) { await syncData(); } if (parameters.TryGetValue(nameof(Request), out EvlRequestItemSource request)) { Request = request; SelectedInsurer = Insurers.FirstOrDefault(i => i.ID == Request.InsurerId); SelectedCar = Cars.FirstOrDefault(c => c.PrmID == Request.CarId); License = _licenseHelper.ConvertToItemSource(Request.PlateNumber); SelectedAlphabet = Alphabets.FirstOrDefault(a => a.Name == License.Alphabet); } } else if (parameters.GetNavigationMode() == NavigationMode.Back) { Request = parameters.GetValue <EvlRequestItemSource>(nameof(Request)); SelectedInsurer = new InsurersItemSource(); SelectedInsurer = Insurers.FirstOrDefault(i => i.ID == Request.InsurerId); //SelectedCar = Cars.FirstOrDefault(c => c.PrmID == Request.CarId); //License = _licenseHelper.ConvertToItemSource(Request.PlateNumber); //SelectedAlphabet = Alphabets.FirstOrDefault(a => a.Name == License.Alphabet); } }
public IActionResult VigenereDecrypt([FromBody] VigenereCipherViewModel viewModel) { VigenereCipher cipher = new VigenereCipher (viewModel.Key, Alphabets.GetAlphabet((Alphabets.AlphabetType)viewModel.AlphabetType)); string decrypted = ""; try { decrypted = cipher.Decrypt(viewModel.Message); } catch (Exception e) { return(BadRequest(new { Result = false, Message = e.Message })); } return(Json(decrypted)); }
public IActionResult CaesarDecrypt([FromBody] CaesarCipherViewModel viewModel) { CaesarCipher cipher = new CaesarCipher(viewModel.Key) { Alphabet = Alphabets.GetAlphabet((Alphabets.AlphabetType)viewModel.AlphabetType) }; string decrypted = ""; try { decrypted = cipher.Decrypt(viewModel.Message); } catch (Exception) { return(BadRequest(new { Result = false, Message = Text.InvalidCharacter })); } return(Json(decrypted)); }
// ConfigWatcher m_config; // const int m_letterNum = 26; // /// <summary> // /// Initializes a new instance of this class. // /// </summary> // public Letters() // { // Reset(); // } // /// <summary> // /// Reset the object's letters. // /// </summary> // public void Reset() // { // ClearCounts(); // ClearFrequencies(); // } // /// <summary> // /// Clear out the current count values // /// </summary> // private void ClearCounts() // { // m_letterCount = new int[m_letterNum]; // m_prevLetterCount = new int[m_letterNum][]; // m_nextLetterCount = new int[m_letterNum][]; // for (int i = 0; i < m_letterNum; i++) // { // m_prevLetterCount[i] = new int[m_letterNum]; // m_nextLetterCount[i] = new int[m_letterNum]; // } // } // /// <summary> // /// Clear out the current frequency values // /// </summary> // private void ClearFrequencies() // { // m_letterFrequencies = new float[m_letterNum]; // m_prevLetterFreqencies = new float[m_letterNum][]; // m_nextLetterFreqencies = new float[m_letterNum][]; // for (int i = 0; i < m_letterNum; i++) // { // m_prevLetterFreqencies[i] = new float[m_letterNum]; // m_nextLetterFreqencies[i] = new float[m_letterNum]; // } // } // /// <summary> // /// Returns the letter frequencies for the letters. // /// </summary> // /// <returns>An array of frequencies representing a-z.</returns> // public float[] GetLetterFrequencies() // { // return m_letterFrequencies; // } // /// <summary> // /// Reads in letter frequencies from an config file. // /// </summary> // public void LoadLetterFrequencies() // { // //int letter; // m_letterFrequencies = new float[m_letterNum]; // if (m_config == null) // { // m_config = new ConfigWatcher(); // m_config.Changed += new EventHandler<ConfigChangedEventArgs>(m_config_Changed); // } // LoadLettersFromConfig(); // //XmlDocument xDOM = new XmlDocument(); // //xDOM.Load(@"statistics.xml"); // //XmlNodeList nodelist = xDOM.SelectNodes("FREQUENCY/LETTERS/LETTER"); // //XmlAttribute xAttr; // //foreach (XmlNode node in nodelist) // //{ // // xAttr = (XmlAttribute)node.Attributes.GetNamedItem("name"); // // letter = (int)xAttr.Value.ToCharArray()[0] % 'A'; // // xAttr = (XmlAttribute)node.Attributes.GetNamedItem("value"); // // m_letterFrequencies[letter] = float.Parse(xAttr.Value, m_culture); // //} // // TODO: Prev/Next letter frequencies // return; // } // void m_config_Changed(object sender, ConfigChangedEventArgs e) // { // LoadLettersFromConfig(); // } // private void LoadLettersFromConfig() // { // foreach (UsefulConfigLetter letter in m_config.Config.Letters) // { // m_letterFrequencies[char.ToUpper(letter.Name[0], m_culture) % 'A'] = letter.Frequency; // } // } // /// <summary> // /// Reads in letters from some text. // /// </summary> // /// <param name="text">The text from which to read the letters from.</param> // public void ReadText(string text) // { // if (text == null) // { // throw new ArgumentNullException("text"); // } // char letter; // char previousLetter; // char nextLetter; // //Clear out the current values // ClearFrequencies(); // //Get First letter //// cLetter = char.ToUpper(TextString[0]); // previousLetter = char.MinValue; // letter = char.ToUpper(text[0], m_culture); // //Get the rest of the text // for (int i = 1 ; i < text.Length ; i++) // { // nextLetter = char.ToUpper(text[i], m_culture); // //Add to stats // AddToLetterCount(letter, previousLetter, nextLetter); // //Shuffle letters for next read // previousLetter = letter; // letter = nextLetter; // } // //This will be for the last letter // AddToLetterCount(letter, previousLetter, char.MinValue); // //Calculate the frequency percentages // //Call objStrings.CopyArray(MyLetters.FrequencyPercent, objCrypt.CalcFrequencyPercentages(MyLetters.Frequency)) // m_letterFrequencies = Statistics.CalcFrequencyPercentages(m_letterCount); // m_prevLetterFreqencies = Statistics.CalcFreqPercentages(m_prevLetterCount); // m_nextLetterFreqencies = Statistics.CalcFreqPercentages(m_nextLetterCount); // } // ///// <summary> // ///// // ///// </summary> // ///// <param name="Letter"></param> // //private void AddToLetterCount(char Letter) // //{ // // AddToLetterCount(Letter, char.MinValue, char.MinValue); // //} // /// <summary> // /// Add a letter to the letter's frequency count. // /// </summary> // /// <param name="letter">The letter to add to.</param> // /// <param name="previousLetter">Letter that comes before this letter.</param> // /// <param name="nextLetter">Letter that comes after this letter.</param> // private void AddToLetterCount(char letter, char previousLetter, char nextLetter) // { // if (char.IsLetter(letter)) // { // m_letterCount[char.ToUpper(letter, m_culture) % 'A']++; // if (char.IsLetter(previousLetter)) // { // //Add letter to previous letter spread // m_prevLetterCount[char.ToUpper(letter, m_culture) % 'A'][char.ToUpper(previousLetter, new CultureInfo("en-GB")) % 'A']++; // } // if (char.IsLetter(nextLetter)) // { // //Add letter to next letter spread // m_nextLetterCount[char.ToUpper(letter, m_culture) % 'A'][char.ToUpper(nextLetter, new CultureInfo("en-GB")) % 'A']++; // } // } // } /// <summary> /// Cleans a dirty string by making it uppercase and removing any non-letters. /// </summary> /// <param name="dirty">The dirty string to clean.</param> /// <param name="alphabet">The unicode alphabet to check the dirty letter is in.</param> /// <param name="options"></param> /// <returns>The clean string.</returns> public static char Clean(char dirty, Alphabets alphabet, CleanOptions options) { // Check to make sure the letter is in the specified alphabet if (Alphabet.GetAlphabetLetters(alphabet).Contains(dirty)) { if ((options & CleanOptions.ToUpper) == CleanOptions.ToUpper) { return(char.ToUpper(dirty)); } else { return(dirty); } } else { return('\0'); } }
public IActionResult AffineEncrypt([FromBody] AffineCipherViewModel viewModel) { AffineCipher cipher = new AffineCipher(viewModel.KeyA, viewModel.KeyB) { Alphabet = Alphabets.GetAlphabet((Alphabets.AlphabetType)viewModel.AlphabetType) }; string encrypted = ""; try { encrypted = cipher.Encrypt(viewModel.Message); } catch (Exception) { return(BadRequest(new { Result = false, Message = Text.InvalidCharacter })); } return(Json(encrypted)); }
/// <summary> /// Validate input sequences /// </summary> /// <param name="reads">The Reads</param> /// <returns>Valid reads.</returns> private IEnumerable <ISequence> ValidateReads(IEnumerable <ISequence> reads) { IAlphabet readAlphabet = Alphabets.GetAmbiguousAlphabet(reads.First().Alphabet); HashSet <byte> ambiguousSymbols = readAlphabet.GetAmbiguousSymbols(); HashSet <byte> gapSymbols; readAlphabet.TryGetGapSymbols(out gapSymbols); foreach (ISequence read in reads) { if (read.All(c => !ambiguousSymbols.Contains(c) && !gapSymbols.Contains(c))) { yield return(read); } else { continue; } } }
/// <summary> /// Validate input sequences /// </summary> /// <param name="reads">The Reads</param> /// <returns>Valid reads.</returns> private IEnumerable <ISequence> ValidateReads(IEnumerable <ISequence> reads) { IAlphabet readAlphabet = Alphabets.GetAmbiguousAlphabet(reads.First().Alphabet); HashSet <byte> ambiguousSymbols = readAlphabet.GetAmbiguousSymbols(); HashSet <byte> gapSymbols; readAlphabet.TryGetGapSymbols(out gapSymbols); foreach (ISequence read in reads) { string originalSequenceId; string pairedReadType; bool forward; string libraryName; if (Bio.Util.Helper.ValidatePairedSequenceId(read.ID, out originalSequenceId, out forward, out pairedReadType, out libraryName)) { if (!read.Alphabet.HasAmbiguity) { bool gapSymbolFound = false; for (long index = 0; index < read.Count; index++) { if (gapSymbols.Contains(read[index])) { gapSymbolFound = true; } } if (!gapSymbolFound) { // Exclude the otherinfo if any. read.ID = Bio.Util.Helper.GetReadIdExcludingOtherInfo(read.ID); yield return(read); } } else { continue; } } } }
private ISequence ParseLine(string line) { string[] splitLine = line.Split(Delimiter); string message; if (splitLine.Length != 2) { message = string.Format(CultureInfo.InvariantCulture, Resource.INVALID_INPUT_FILE, line); Trace.Report(message); throw new FileFormatException(message); } IAlphabet alphabet = Alphabet; if (alphabet == null) { byte[] byteArray = UTF8Encoding.UTF8.GetBytes(splitLine[1]); alphabet = Alphabets.AutoDetectAlphabet(byteArray, 0, byteArray.Length, null); if (alphabet == null) { message = string.Format(CultureInfo.InvariantCulture, Resource.InvalidSymbolInString, splitLine[1]); Trace.Report(message); throw new FileFormatException(message); } } Sequence sequence; sequence = new Sequence(alphabet, splitLine[1]) { ID = splitLine[0] }; return(sequence); }
public Composition() : base("Composition") { compElements = new ObservableCollection<CompositionElement>(); Mode = MatchMode.ALL; Alphabet = Alphabets.DNA; }
public XOREncryption(string gammaKey, Alphabets.Alphabet alphabet) { this.alphabet = alphabet; this.gammaKey = gammaKey; }
public RSA(Alphabets.Alphabet alphabet) { this.alphabet = alphabet; PublicKey = new int[2]; privateKey = new int[2]; }
public RecursivePatterns(string patternTypeName, string alphabet) : base(patternTypeName) { Alphabet = Alphabets.DNA; }
public ElHamal(Alphabets.Alphabet alphabet) { this.alphabet = alphabet; }
public Caesar(int key, Alphabets.Alphabet alphabet):base() { this.key = key; this.alphabet = alphabet; }
public Polinom(Alphabets.Alphabet alphabet, Mathematics.Function function) { this.alphabet = alphabet; this.function = function; }
public Tritemius(Alphabets.Alphabet _alphabet, String _key) { alphabet = _alphabet; Key = _key; stringKey = true; }