protected BaseAction(Alphabet alphabet, string operandOne, string operandTwo, string flag) { Alphabet = alphabet; OperandOne = operandOne; OperandTwo = operandTwo; Flag = flag; }
private void CreateTerrain() { var parent = (GameObject) Instantiate(new GameObject("Terrain")); parent.transform.position = new Vector3(0, 0, 0); for (int x = 1; x <= tileAmount.x; x++) { for (int y = 1; y <= tileAmount.y; y++) { var terrainData = new TerrainData(); alphabet = (Alphabet) x; string name = alphabet + "-" + y; terrainData.size = new Vector3(width/16f, height, lenght/16f); terrainData.baseMapResolution = baseTextureReolution; terrainData.heightmapResolution = heightmapResoltion; terrainData.alphamapResolution = controlTextureResolution; terrainData.SetDetailResolution(detailResolution, detailResolutionPerPatch); terrainData.name = name; GameObject terrain = Terrain.CreateTerrainGameObject(terrainData); terrain.name = name; terrain.transform.parent = parent.transform; terrain.transform.position = new Vector3(lenght*(x - 1), 0, width*(y - 1)); AssetDatabase.CreateAsset(terrainData, "Assets/" + path + name + ".asset"); } } }
public static BaseAction Create(string name, Alphabet alphabet, string operandOne, string operandTwo, string flag) { switch (name) { case "Append": return new Append(alphabet, operandOne, operandTwo, flag); case "DeleteFirstLetter": return new DeleteFirstLetter(alphabet, operandOne, operandTwo, flag); case "DeleteFirstVowel": return new DeleteFirstVowel(alphabet, operandOne, operandTwo, flag); case "DeleteLastLetter": return new DeleteLastLetter(alphabet, operandOne, operandTwo, flag); case "DeleteLastVowel": return new DeleteLastVowel(alphabet, operandOne, operandTwo, flag); case "DoubleLastLetter": return new DoubleLastLetter(alphabet, operandOne, operandTwo, flag); case "Replace": return new Replace(alphabet, operandOne, operandTwo, flag); case "LexicalToSurface": return new LexicalToSurface(alphabet, operandOne, operandTwo, flag); default: throw new ArgumentException("What the hack is that action:" + name); } }
public Trie(Alphabet alphabet) { _charToIndex = alphabet._charToIndex; _indexToChar = alphabet._indexToChar; R = alphabet.R; root = new TrieNode(); }
public void SetUp() { alpha = DnaAlphabet.Instance(); symbols = new SymbolArray(alpha, "actgactg"); this.indexer = new IndexerDirect(2); accessor = new AccessorLinear(indexer, 4, symbols); }
public static BaseAction Create(string name, Alphabet alphabet, string operandOne, string operandTwo, string flag) { switch (name) { case "Append": return new Append(alphabet, operandOne, operandTwo, flag); case "Prepend": return new Prepend(alphabet, operandOne, operandTwo, flag); case "DeleteSurface": return new DeleteSurface(alphabet, operandOne, operandTwo, flag); case "DeleteFirstLetter": return new DeleteFirstLetter(alphabet, operandOne, operandTwo, flag); case "DeleteFirstVowel": return new DeleteFirstVowel(alphabet, operandOne, operandTwo, flag); case "DeleteLastLetter": return new DeleteLastLetter(alphabet, operandOne, operandTwo, flag); case "DeleteLastVowel": return new DeleteLastVowel(alphabet, operandOne, operandTwo, flag); case "DoubleLastLetter": return new DoubleLastLetter(alphabet, operandOne, operandTwo, flag); case "Replace": return new Replace(alphabet, operandOne, operandTwo, flag); case "LexicalToSurface": return new LexicalToSurface(alphabet, operandOne, operandTwo, flag); default: throw new ArgumentException($"Invalid action type: {name}"); } }
public void SetUp() { alpha = DnaAlphabet.Instance(); symbols = new SymbolArray(alpha, "tatgacgt"); this.indexer = new IndexerDirect(2); accessor = new AccessorTransparent(indexer, 4, symbols); }
/// <summary> /// Encrypts a string using a password to generate an alphabet character array. /// </summary> /// <param name="text"></param> /// <param name="password"></param> /// <returns></returns> public string Encrypt(string text, string password) { var alphabet = new Alphabet().GenerateAlphabetFromPassword(password); var manager = new EncryptionManager(); return manager.Encrypt(text, alphabet); }
public void SetUp() { alpha = DnaAlphabet.Instance(); symbols = new SymbolArray(alpha, "actgactg"); indexer = new IndexerDirect(2); indexerReverse = new IndexerReverse(2,symbols.Length); accessor = new AccessorCircular(this.indexer, 4, symbols); }
/// <summary> /// Initializes a new instance of the <see cref="Checker"/> class. /// </summary> /// <param name="alphabet"> /// The alphabet. /// </param> public Checker(Alphabet alphabet) { this.alphabet = new ChainsAlphabet(); foreach (IBaseObject baseObject in alphabet) { this.alphabet.Add(baseObject); } }
/// <summary> /// The elements in db. /// </summary> /// <param name="alphabet"> /// The alphabet. /// </param> /// <param name="notationId"> /// The notation id. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> public bool ElementsInDb(Alphabet alphabet, int notationId) { var elements = from IBaseObject element in alphabet select element.ToString(); int existingElementsCount = db.Element.Count(e => elements.Contains(e.Value) && e.NotationId == notationId); return alphabet.Cardinality == existingElementsCount; }
public void SetUp() { alphabet = new TestAlphabetClass(); alphabet2 = new TestAlphabetClass(); sym1 = new Symbol('a', "Ade", "Adenine"); sym2 = new Symbol('u', "Ura", "Uracil"); sym3 = new SymbolMeta('-', "GAP", "Gap"); }
bool ShowLine(Alphabet alphabet, Letter letter) { if (currentLine.DrawNextChar (alphabet, letter, transform)) { currentLineIndex++; if (currentLineIndex >= linesInCard.Length) { persistState = true; return false; } currentLine = linesInCard [currentLineIndex]; } return true; }
/// <summary> /// Constructs a <see cref="QUT.Bio.BioPatML.Symbols.SymbolArray">SymbolArray</see> /// based on the given character sequence. /// <para></para> /// The characters are converted to symbols according to the specified /// alphabet. Unknown characters will be converted to the default symbol if /// one is defined. /// </summary> /// <param name="alphabet"> The alphabet used to convert letters to symbols. </param> /// <param name="characters"> charSequence A character sequence with alphabet letters. </param> public SymbolArray (Alphabet alphabet, IEnumerable<char> characters) { Symbols = new Symbol[characters.Count()]; int i = 0; foreach (char ch in characters) Symbols[i++] = alphabet[ch]; SymAlphabet = alphabet; }
public bool DrawNextChar(Alphabet alphabet, Letter letter, Transform cutSceneParent) { char currentLetter = text[currentLetterPos]; Sprite s = alphabet.GetLetter(currentLetter); Letter newLetter = Instantiate (letter) as Letter; newLetter.transform.parent = cutSceneParent; newLetter.GetComponent<SpriteRenderer>().sprite = s; newLetter.transform.position = new Vector3(startPoint.x, startPoint.y, -1); startPoint.x += 1; currentLetterPos++; if(currentLetterPos >= text.Length) { return true; } return false; }
/// <summary> /// The check recovery available. /// </summary> /// <param name="chain"> /// Source sequence. /// </param> /// <param name="length"> /// Length of L-gram. /// </param> /// <returns> /// true if chain is recoverable form L-grams. /// </returns> private bool CheckRecoveryAvailable(AbstractChain chain, int length) { var iterator = new IteratorStart(chain, length, 1); var alphabet = new Alphabet(); while (iterator.Next()) { if (alphabet.Contains(iterator.Current())) { return false; } alphabet.Add(iterator.Current()); } return true; }
public bool DrawLine(Alphabet alphabet, Letter letter) { if (startFullyShown && !persistState) { ShowFullLine(alphabet, letter); } float timeSinceLast = Time.timeSinceLevelLoad - lastDrawTime; if (persistState) { if(timeSinceLast >= persistTime) { return true; } return false; } if(timeSinceLast >= timeDelay) { lastDrawTime = Time.timeSinceLevelLoad; ShowLine (alphabet, letter); } return false; }
/// <summary> /// The common ParseOne method called for parsing SNPs /// NOTE: The snpReader.MoveNext must have already been called and /// the ISnpReader.Current have the first SnpItem to parse into the sequence /// </summary> /// <param name="snpReader">The ISnpReader to read a Snp chromosome sequence from</param> /// <param name="isReadOnly"> /// Flag to indicate whether the resulting sequence should be in readonly mode or not. /// If this flag is set to true then the resulting sequence's isReadOnly property /// will be set to true, otherwise it will be set to false. /// </param> /// <returns>Returns a SparseSequence containing Snp items from the first contiguous /// chromosome number read from the snp reader.</returns> protected ISequence ParseOne(ISnpReader snpReader, bool isReadOnly) { // Check input arguments if (snpReader == null) { throw new ArgumentNullException("snpReader", "SNP Reader to read SNP sequences from cannot be null"); } if (snpReader.Current == null) { return new SparseSequence(Alphabet) { ID = "Empty" } } ; int sequenceChromosome = snpReader.Current.Chromosome; SparseSequence sequence = new SparseSequence(Alphabet); sequence.ID = ("Chr" + sequenceChromosome); do { SnpItem snp = snpReader.Current; // increase the size of the sparse sequence if (sequence.Count <= snp.Position) { sequence.Count = snp.Position + 1; } sequence[snp.Position] = ParseAlleleOne ? Alphabet.LookupBySymbol(snp.AlleleOne) : Alphabet.LookupBySymbol(snp.AlleleTwo); } while (snpReader.MoveNext() && snpReader.Current.Chromosome == sequenceChromosome); sequence.IsReadOnly = isReadOnly; return(sequence); } #endregion Protected Methods of SnpParser }
private void rebuildTranspositionCleanPassword() { string value = TranspositionPass.ToUpperInvariant(); // remove characters not part of alphabet List <char> cleanPassword = new List <char>(); foreach (char c in value) { if (Alphabet.Contains(c)) { cleanPassword.Add(c); } } // copy and sort characters char[] keyChars = cleanPassword.ToArray(); Array.Sort(keyChars); // determine column order int[] newColumnOrder = new int[keyChars.Length]; for (int i = 0; i < keyChars.Length; i++) { int column = Array.IndexOf(keyChars, cleanPassword[i]); newColumnOrder[i] = column; keyChars[column] = (char)0; // make sure the same character won't be found again } this.KeyColumnOrder = newColumnOrder; // build nice looking string for output (note: column numbers start with 0 in array, but 1 in string) StringBuilder keyWord = new StringBuilder(); if (newColumnOrder.Length >= 1) { keyWord.Append((newColumnOrder[0] + 1)); for (int i = 1; i < newColumnOrder.Length; i++) { keyWord.Append("-" + (newColumnOrder[i] + 1)); } } this.CleanTranspositionPass = keyWord.ToString(); }
protected override void CheckConstraints() { base.CheckConstraints(); foreach (var t in Transforms) { for (int i = 0; i < t.Value.Length; i++) { if (t.Key.q >= StatesCount) throw new StateException(t.Key.q, this); else if (t.Value[i].qNext >= StatesCount) throw new StateException(t.Value[i].qNext, this); else if (t.Key.ci.HasValue && !Alphabet.Contains(t.Key.ci.Value)) throw new AlphabetException(t.Key.ci.Value, this); else if (t.Key.cw.HasValue && !WorkAlphabet.Contains(t.Key.cw.Value)) throw new AlphabetException(t.Key.cw.Value, this); else if (t.Value[i].cw2 != null && t.Value[i].cw2 != "" && !WorkAlphabet.Contains(t.Value[i].cw2[0])) throw new AlphabetException(t.Value[i].cw2[0], this); } } for (int i = 0; i < AcceptedStates.Length; i++) if (AcceptedStates[i] >= StatesCount) throw new StateException(AcceptedStates[i], this); }
/// <summary> /// Generates hashtable with all possible combinations as keys /// and characteristics list as values. /// </summary> /// <param name="alphabet"> /// Alphabet for generated sequences. /// </param> /// <param name="length"> /// Length of generated sequences. /// </param> /// <param name="characteristic"> /// Calculated characteristics. /// </param> /// <returns> /// The <see cref="ChainPicksWithCharacteristics"/>. /// </returns> public ChainPicksWithCharacteristics Generate(Alphabet alphabet, int length, List<LinkedCharacteristic> characteristic) { var hashTable = new Hashtable(); // По всем возможным цепочкам (Для оптимизации скорости генерируется цепочки с одинаковой первой буквой) for (int i = 0; i < Math.Pow(alphabet.Cardinality, length - 1); i++) { Chain chain = GenerateChain(alphabet, i, length); List<double> characteristics = CalculateCharacteristics(chain, characteristic); try { hashTable.Add(ArrayExtensions.ToStringWithoutDelimiter(chain.Building), characteristics); } catch (Exception) { } } return new ChainPicksWithCharacteristics(hashTable, characteristic); }
protected override void BeginProcessing() { if (null == Encoding) { Encoding = Encoding.UTF8; } if (null == Alphabet) { return; } if (NoPadding.IsPresent) { Encoder = new BitEncoder(Alphabet.ToCharArray()); } else { Encoder = new BitEncoder(Alphabet.ToCharArray(), PaddingCharacter); } }
private IEnumerable <IndividualSet> GeneratePoputation(int size) { var random = new Random(); var population = new HashSet <IndividualSet>(size, new IndividualSetsComparer()); IndividualSet individualSet; Individual individual; while (population.Count != size) { individualSet = new IndividualSet(IndividualSetMembersCount); while (individualSet.Count != IndividualSetMembersCount) { individual = new Individual(new string(Alphabet.ToCharArray().OrderBy(s => (random.Next(2) % 2) == 0).ToArray()), Alphabet.Length); individualSet.Add(individual); } population.Add(individualSet); } return(population); }
public void AddAlphabet_DuplicateTwice_CountIs3() { Alphabet a = new Alphabet('a'); Dictionary <double, Alphabet> list = new Dictionary <double, Alphabet>(); IAlphabetMachine machine = new AlphabetMachine(); Assert.Empty(machine.List); machine.AddAlphabet(a); machine.AddAlphabet(a); machine.AddAlphabet(a); Assert.NotEmpty(machine.List); Assert.Equal(3, machine.List[a.Position].Count); }
/// <summary> /// Replaces the sequence item present in the specified index in this sequence /// with a sequence item which is represented by specified character. /// </summary> /// <param name="index">Index at which the sequence item has to be replaced.</param> /// <param name="character">Character which represent a sequence item.</param> public void Replace(int index, char character) { if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException(Properties.Resource.ParameterNameIndex); } ISequenceItem seqItem = Alphabet.LookupBySymbol(character); if (seqItem == null) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Properties.Resource.InvalidSymbol, character)); } Replace(index, seqItem); }
/// <summary> /// Detects the alphabet of a string /// </summary> /// <param name="text">The string to check</param> /// <returns>Alphabet Enum</returns> public static Alphabet GetAlphabet(string text) { if (String.IsNullOrWhiteSpace(text)) { return(Alphabet.None); } Alphabet alphabet = Alphabet.None; foreach (Char c in text) { alphabet |= GetAlphabet(c); if ((alphabet & (alphabet - 1)) != 0) { return(Alphabet.Mixed); } } return(alphabet); }
/// <summary> /// Получает указанный алфавита. /// </summary> /// <param name="Language">Алфавит.</param> /// <returns></returns> public static List <Char> GetAlphabet(Alphabet Alphabet) { switch (Alphabet) { case Alphabet.Latin: return(new List <Char>() { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }); case Alphabet.Cyrillic: return(new List <Char>() { 'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я' }); default: throw new Exception("Данный алфавит отсутствует"); } }
private void textBox_TextChanged(object sender, TextChangedEventArgs e) { checkTextBox(textBox); if (textBox.Text.Length == 1) { if (textBox.Text.Intersect(Cezar.ALPHABET_EN).Any()) { language = Alphabet.English; } if (textBox.Text.Intersect(Cezar.ALPHABET_RU).Any()) { language = Alphabet.Russian; } } else { checkLanguage(textBox); } }
public List <BigInteger> HashMessage(string msg) { var castmsg = DevideIntoBlocks(msg.ToUpper()).ToList(); List <BigInteger> messages = new List <BigInteger>(); foreach (var element in castmsg) { BigInteger ret = 0; for (int i = element.Length - 1, x = 0; i >= 0; i--, x++) { var c = element[x]; int value; Alphabet.TryGetValue(c, out value); ret += value * PowBigInteger(26, i); } messages.Add(PowBigInteger(ret, 3) % n); } return(messages); }
private static void DecodeFile(string inputFile, Alphabet alphabet, string outputFile) { var codedText = File.ReadAllText(inputFile); var decodedText = new StringBuilder(""); for (int i = 0; i < codedText.Length; i++) { var codedSymbol = codedText[i].ToString(); while (!alphabet.toDict().ContainsValue(codedSymbol)) { codedSymbol += codedText[++i]; } var character = alphabet.toDict().First(c => alphabet.GetCodeFor(c.Key) == codedSymbol).Key; decodedText.Append(character); File.WriteAllText(outputFile, decodedText.ToString()); } }
private void OnStartup(object sender, StartupEventArgs e) { Stopwatch.Normal("|App.OnStartup|Startup cost", () => { Log.Info("|App.OnStartup|Begin Wox startup ----------------------------------------------------"); RegisterDispatcherUnhandledException(); ImageLoader.Initialize(); Alphabet.Initialize(); _settingsVM = new SettingWindowViewModel(); _settings = _settingsVM.Settings; PluginManager.LoadPlugins(_settings.PluginSettings); _mainVM = new MainViewModel(_settings); var window = new MainWindow(_settings, _mainVM); API = new PublicAPIInstance(_settingsVM, _mainVM); PluginManager.InitializePlugins(API); Current.MainWindow = window; Current.MainWindow.Title = Constant.Wox; // happlebao todo temp fix for instance code logic // load plugin before change language, because plugin language also needs be changed InternationalizationManager.Instance.Settings = _settings; InternationalizationManager.Instance.ChangeLanguage(_settings.Language); // main windows needs initialized before theme change because of blur settigns ThemeManager.Instance.Settings = _settings; ThemeManager.Instance.ChangeTheme(_settings.Theme); Http.Proxy = _settings.Proxy; RegisterExitEvents(); AutoStartup(); AutoUpdates(); _mainVM.MainWindowVisibility = _settings.HideOnStartup ? Visibility.Hidden : Visibility.Visible; Log.Info("|App.OnStartup|End Wox startup ---------------------------------------------------- "); }); }
public ITask CreateDecodeDjmainHdd() { return(Build("Extract DJMAIN HDD", task => { var files = GetInputFiles(task); if (!files.Any()) { task.Message = "No input files."; return false; } ParallelProgress(task, files, file => { var options = new DjmainDecodeOptions { DisableAudio = !EnableExportingSounds }; using (var stream = OpenRead(task, file)) { long offset = 0; var chunks = _djmainChunkStreamReader.Read(stream); foreach (var chunk in chunks) { var chunkPath = $"{Alphabet.EncodeNumeric(chunk.Id, 4)}"; var decoded = _djmainDecoder.Decode(chunk, options); ExportKeysoundedChart(task, file, chunkPath, $"{Alphabet.EncodeNumeric(chunk.Id, 4)}", decoded.Charts, decoded.Samples); if (EnableExportingRaw) { foreach (var(key, value) in decoded.RawCharts) { using (var rawChartStream = OpenWriteMulti(task, file, _ => Path.Combine(chunkPath, $"{Alphabet.EncodeNumeric(key, 2)}.cs5"))) { _djmainChartEventStreamWriter.Write(rawChartStream, value); rawChartStream.Flush(); } } }
private void FrequencyBtn_Click(object sender, EventArgs e) { analysisDgv.Rows.Clear(); KeyValuePair <char, float>[] analyzeRes = frequencyAnalyzer.Analyze(textTb.Text); foreach (KeyValuePair <char, float> keyFrequency in analyzeRes) { analysisDgv.Rows.Add(keyFrequency.Key, keyFrequency.Value); } analysisDgv.Sort(analysisDgv.Columns[1], System.ComponentModel.ListSortDirection.Descending); hackedDgv.Rows.Clear(); KeyValuePair <char, float>[] encryptRes = frequencyAnalyzer.Analyze(textToDecodeTb.Text); foreach (KeyValuePair <char, float> keyFrequency in encryptRes) { hackedDgv.Rows.Add(keyFrequency.Key, keyFrequency.Value); } hackedDgv.Sort(hackedDgv.Columns[1], System.ComponentModel.ListSortDirection.Descending); // create dictionary = analysis char value - hacked char value Dictionary <char, char> replaceDictionary = frequencyAnalyzer.SetRelationOnFrequency(analyzeRes, encryptRes); // replace letter in text System.Text.StringBuilder sb = new System.Text.StringBuilder(Alphabet.TextAdapter(textToDecodeTb.Text)); for (int i = 0; i < sb.Length; ++i) { try { sb[i] = replaceDictionary[sb[i]]; } catch (KeyNotFoundException ex) { continue; } catch (Exception ex) { Service.DialogService.ErrorMessage(ex.Message); } } decryptedTextTb.Text = sb.ToString(); }
/// <summary> /// Replaces the sequence item present in the specified position in this sequence with the specified sequence item. /// </summary> /// <param name="position">Position at which the sequence item has to be replaced.</param> /// <param name="item">Sequence item to be placed at the specified position.</param> private void Replace(long position, byte item) { if (position < 0 || position >= Count) { throw new ArgumentOutOfRangeException( Properties.Resource.ParameterNamePosition, Properties.Resource.ParameterMustLessThanCount); } if (item == 0) { if (sparseSeqItems.ContainsKey(position)) { Statistics.Remove((char)sparseSeqItems[position]); sparseSeqItems.Remove(position); } } else { if (!Alphabet.ValidateSequence(new[] { item }, 0, 1)) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Properties.Resource.InvalidSymbol, item)); } if (sparseSeqItems.ContainsKey(position)) { Statistics.Remove((char)sparseSeqItems[position]); sparseSeqItems[position] = item; } else { sparseSeqItems.Add(position, item); } Statistics.Add((char)item); } }
public ITask CreateExtract2dx() { return(Build("Extract 2DX", task => { var files = GetInputFiles(task); if (!files.Any()) { task.Message = "No input files."; return false; } ParallelProgress(task, files, file => { using (var stream = OpenRead(task, file)) { var decrypted = _encryptedBeatmaniaPcAudioStreamReader.Decrypt(stream, stream.Length); var sounds = _beatmaniaPcAudioStreamReader.Read(new MemoryStream(decrypted), decrypted.Length); var index = 1; if (EnableExportingSounds) { foreach (var sound in sounds) { var decoded = _beatmaniaPcAudioDecoder.Decode(sound); var outSound = _audioDsp.ApplyEffects(decoded); using (var outStream = OpenWriteMulti(task, file, i => $"{Alphabet.EncodeAlphanumeric(index, 4)}.wav")) { var encoded = _riffPcm16SoundEncoder.Encode(outSound); _riffStreamWriter.Write(outStream, encoded); } index++; } } } }); return true; })); }
public void WriteString() { if (MyString == null) { return; } ClearCanvas(); Position = Position0; foreach (char symbol in MyString) { if (Alphabet.ContainsKey(symbol)) { WriteSymbol(Alphabet[symbol]); } else { WriteSymbol(SpecialSymbol); } Position = new Point(Position.X + (int)(WidthSymbol * SizeX), Position.Y); } }
protected virtual string TransformLetter(char letter, Operations operation) { if (Alphabet.HasLetter(letter)) { char lowerCaseLetter = Char.ToLower(letter); char shiftedLetter = operation == Operations.Encode ? EncodeLetter(lowerCaseLetter) : DecodeLetter(lowerCaseLetter); if (Alphabet.IsUpper(letter)) { return(Char.ToUpper(shiftedLetter).ToString()); } else { return(shiftedLetter.ToString()); } } else { return(letter.ToString()); } }
private void comboBoxAlphabet_SelectionChanged(object sender, SelectionChangedEventArgs e) { switch (comboBoxAlphabet.SelectedIndex) { case 0: alphabet = Alphabet.Latin; if (comboBoxCypher != null) { comboBoxCypher_SelectionChanged(null, null); } break; case 1: alphabet = Alphabet.Ukrainian; if (comboBoxCypher != null) { comboBoxCypher_SelectionChanged(null, null); } break; } }
public static Match <char> RandomMatch(Alphabet alphabet) { Match <char> newMatch = new Match <char>(alphabet); Random random = new Random(); foreach (char symbol in newMatch.symbols) { while (newMatch[symbol] == default(char)) { int randomPos = random.Next(alphabet.AlphabetSize); var randomChar = alphabet.GetChar(randomPos, true); if (!newMatch.repalaceSymbols.Contains(randomChar)) { newMatch[symbol] = randomChar; } } } return(newMatch); }
public void ValueTest() { /*** ARRANGE ***/ Alphabet alphabet = CreateDefaultAlphabet(); Cell target = new Cell(alphabet); int expected = 3; // arbitrary int actual; /*** ACT ***/ target.Value = expected; /*** ASSERT ***/ actual = target.Value; Assert.AreEqual(expected, actual); // value setting successful alphabet.Remove(expected); // cell can be no other value foreach (int value in alphabet) { Assert.IsFalse(target.CanBe(value)); } }
public Affine(int a, int b, Alphabet alphabet = null) { Alphabet = alphabet == null ? new Alphabet() : alphabet; A = a; B = b; if (Common.Math.GCD(A, Alphabet.Length) != 1) { throw new ArgumentException("a must be relatively prime to the length of the alphabet.", nameof(a)); } StringBuilder mappedAlphabet = new StringBuilder(); for (int i = 0; i < Alphabet.Length; ++i) { var mappedCharIndex = Common.Math.PositiveMod((A * i) + B, Alphabet.Length); mappedAlphabet.Append(Alphabet[mappedCharIndex]); } MappedAlphabet = new Alphabet(mappedAlphabet.ToString()); }
/// <summary> /// /// </summary> private Alphabet GenerationAlphabet() { Alphabet Alphabet = (elem_RU.Checked) ? Alphabet.Cyrillic : Alphabet.Latin; List <Char> Chars = Caesar.GetAlphabet(Alphabet); elem_alphabet.Text = Chars.Select(i => i.ToString()).Aggregate((result, item) => result + " " + item) + "\n"; for (int i = (Chars.Count - (int)elem_key.Value); i < Chars.Count; i++) { elem_alphabet.Text += Chars[i].ToString() + " "; } for (int i = 0; i < (Chars.Count - (int)elem_key.Value); i++) { elem_alphabet.Text += Chars[i].ToString() + " "; } elem_alphabet.Text = elem_alphabet.Text.Remove(elem_alphabet.Text.Length - 1, 1); return(Alphabet); }
public void SearchEngineSolutionsInitializatedCorrectly() { TaskFormat task = new TaskFormat(); task.Convolutions.Add(Cryptography.Encryption("zzzzzz")); SearchEngineSolutions searchEngineSolutions = new SearchEngineSolutions(task); AnswerFormat answerFormat = searchEngineSolutions.FindSolution(); Assert.AreEqual(answerFormat.Solution.Length, 0); task.NumberOfWordsThatNeedToBeIterated = 100; task.Convolutions.Add( Cryptography.Encryption(Alphabet.GetSymbol(99).ToString(CultureInfo.InvariantCulture))); searchEngineSolutions = new SearchEngineSolutions(task); answerFormat = searchEngineSolutions.FindSolution(); Assert.AreEqual(answerFormat.Solution.Length, 1); Assert.Throws <InitializationOfSearchEngineSolutionsWasFailedException>( () => searchEngineSolutions = new SearchEngineSolutions(null)); }
/// <summary> /// Replaces the sequence item present in the specified index in this sequence with the specified sequence item. /// </summary> /// <param name="index">Index at which the sequence item has to be replaced.</param> /// <param name="item">Sequence item to be placed at the specified position.</param> public void Replace(int index, ISequenceItem item) { if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException( Properties.Resource.ParameterNameIndex, Properties.Resource.ParameterMustLessThanCount); } // if item is null throw exception. if (item == null) { throw new ArgumentNullException(Properties.Resource.ParameterNameItem); } // Get the item from alphabet. ISequenceItem seqItem = Alphabet.LookupBySymbol(item.Symbol); if (seqItem == null) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Properties.Resource.InvalidSymbol, item.Symbol)); } // Get internal index. index = GetInternalIndex(index); // If the index is present in updated items, just update the item no need to change the updated type. if (_updatedItems.ContainsKey(index)) { _updatedItems[index].SequenceItem = item; } else { _updatedItems.Add(index, new UpdatedSequenceItem(item, UpdateType.Replaced)); } }
public static BaseAction Create(string name, Alphabet alphabet, string operandOne, string operandTwo, string flag) { switch (name) { case "Append": return(new Append(alphabet, operandOne, operandTwo, flag)); case "Prepend": return(new Prepend(alphabet, operandOne, operandTwo, flag)); case "DeleteSurface": return(new DeleteSurface(alphabet, operandOne, operandTwo, flag)); case "DeleteFirstLetter": return(new DeleteFirstLetter(alphabet, operandOne, operandTwo, flag)); case "DeleteFirstVowel": return(new DeleteFirstVowel(alphabet, operandOne, operandTwo, flag)); case "DeleteLastLetter": return(new DeleteLastLetter(alphabet, operandOne, operandTwo, flag)); case "DeleteLastVowel": return(new DeleteLastVowel(alphabet, operandOne, operandTwo, flag)); case "DoubleLastLetter": return(new DoubleLastLetter(alphabet, operandOne, operandTwo, flag)); case "Replace": return(new Replace(alphabet, operandOne, operandTwo, flag)); case "LexicalToSurface": return(new LexicalToSurface(alphabet, operandOne, operandTwo, flag)); default: throw new ArgumentException($"Invalid action type: {name}"); } }
// CONSTRUCOTORS public ApplicationViewModel() { random = new System.Random(); algorithms = new Algorithms(); alphabet = new Alphabet(string.Concat(latinLatters, ukrainianLatters, symbols, numbers)); text = null; encryptedText = null; decryptedText = null; p = null; q = null; e = null; d = null; alice = null; bob = null; hashA = null; hashB = null; digitalSignatureA = null; digitalSignatureB = null; #region Commands loadText = null; encryptText = new RelayCommand(EncryptTextMethod, CanEncodeText); saveEncryptedText = null; decryptText = new RelayCommand(DecryptTextMethod, CanDecodeText); saveDecryptedText = null; generatePQ = new RelayCommand(GeneratePQMethod); confirmPQ = new RelayCommand(ConfirmPQMethod, CanConfirmPQ); generateE = new RelayCommand(GenerateEMethod, CanGenerateE); confirmE = new RelayCommand(ConfirmEMethod, CanConfirmE); sendEN = new RelayCommand(SendENMethod, CanSendEN); #endregion }
/// <summary> /// Decodes a sequence of bytes from the specified byte array into the specified character array. /// </summary> /// <param name="bytes">The byte array containing the sequence of bytes to decode.</param> /// <param name="byteIndex">The zero-based index of the first byte to decode.</param> /// <param name="byteCount">The number of bytes to decode.</param> /// <param name="chars">The character array to contain the resulting set of characters.</param> /// <param name="charIndex">The zero-based index at which to start writing the resulting set of characters.</param> /// <returns>The actual number of characters written into chars.</returns> /// <exception cref="System.ArgumentNullException">bytes is null.-or- chars is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException">byteIndex or byteCount or charIndex is less than zero.-or- byteindex and /// byteCount do not denote a valid range in bytes.-or- charIndex is not a valid index in chars.</exception> /// <exception cref="System.ArgumentException">chars does not have enough capacity from charIndex to the end of the array /// to accommodate the resulting characters.</exception> public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (chars == null) { throw new ArgumentNullException("chars"); } if (byteIndex < 0 || (byteIndex >= bytes.Length && byteCount > 0)) { throw new ArgumentOutOfRangeException("bytes"); } if (byteCount < 0 || byteIndex + byteCount > bytes.Length) { throw new ArgumentOutOfRangeException("byteCount"); } if (charIndex < 0 || (charIndex >= chars.Length && byteCount > 0)) { throw new ArgumentOutOfRangeException("charIndex"); } if (charIndex + byteCount > chars.Length) { throw new ArgumentException("Resulting chars array does not have enough capacity from charIndex to the end of the array to accommodate the resulting characters.", "chars"); } var builder = new StringBuilder(byteCount); char[] alphabetArray = Alphabet.ToCharArray(); for (int i = 0; i < byteCount; i++) { chars[i + charIndex] = alphabetArray[bytes[byteIndex + i]]; } return(byteCount); }
public Cezar(string _keyWord, byte _key, Alphabet _language) { keyWord = _keyWord; key = _key; language = _language; CheckKeyWord(); if (language == Alphabet.English) { FillOrderedAlphabet(ALPHABET_EN); alphabetToString(); FillAlphabet(ALPHABET_EN); } if (language == Alphabet.Russian) { FillOrderedAlphabet(ALPHABET_RU); alphabetToString(); FillAlphabet(ALPHABET_RU); } }
/// <summary> /// Checks if alphabet is appropriate for dna sequence, /// e.g. contains only nucleotide elements. /// </summary> /// <param name="alphabet"> /// Alphabet to check. /// </param> public static void CheckDnaAlphabet(Alphabet alphabet) { if (alphabet.Cardinality > 4) { throw new Exception("DNA alphabet cardinality must be 4 or less"); } var completeAlphabet = new Alphabet { new ValueString("A"), new ValueString("C"), new ValueString("T"), new ValueString("G") }; for (int i = 0; i < alphabet.Cardinality; i++) { if (!completeAlphabet.Contains(alphabet[i])) { throw new Exception("Alphabet contains at least 1 wrong element: " + alphabet[i]); } } }
private void UpdateUIHaffman() { var alphabet = new Alphabet(rtbIncoming.Text); var result = ""; var tree = new HaffmanTree<char>(alphabet.ToKeyValuePairs()); var count = 0; alphabet.SortByFrequency(reverse: true); foreach (var ch in alphabet.Chars) { var charCode = tree.GetCharCode(ch); count += charCode.Length * alphabet.GetFrequency(ch); result += $"{ch}\t{alphabet.GetFrequency(ch)}\t{alphabet.GetRelativeFrequency(ch):0.000000}\t\t{charCode}\r\n"; } tbAlphabet.Text = result; lCharCount.Text = alphabet.CharCount.ToString(); lBitCount.Text = alphabet.GetBitCount(_encoding).ToString(); lBitPerChar.Text = alphabet.GetBitPerChar(_encoding).ToString("0.###"); lEntropy.Text = alphabet.Entropy.ToString("0.###"); lZippedCount.Text = $"Количество бит сжатого текста: {count}"; lEntropy.BorderSides = ToolStripStatusLabelBorderSides.Right; }
/// <summary> /// Initializes a new instance of the Sudoku.Common.Puzzle class /// with the specified dimensions and alphabet. /// <param name="width">The width of the puzzle.</param> /// <param name="height">The height of the puzzle.</param> /// <param name="boxWidth">The width of any box in the puzzle.</param> /// <param name="boxHeight">The height of any box in the puzzle.</param> /// <param name="alphabet">The puzzle alphabet that contains all possible values.</param> public Puzzle(int width, int height, int boxWidth, int boxHeight, Alphabet alphabet) { _Width = width; _Height = height; _BoxHeight = boxHeight; _BoxWidth = boxWidth; _Alphabet = alphabet; this.SolveCount = 0; // Has to be first _Cells = new List<Cell>(); int cellCount = width * height; for (int i = 0; i < cellCount; i++) this.Cells.Add(new Cell(alphabet, this)); _Columns = new List<Column>(); for (int i = 0; i < width; i++) this.Columns.Add(new Column(i, this)); _Boxes = new List<Box>(); int boxCount = (width / boxWidth) * (height / boxHeight); for (int i = 0; i < boxCount; i++) this.Boxes.Add(new Box(i, this)); }
public DeleteLastLetter(Alphabet alphabet, string operandOne, string operandTwo, string flag) : base(alphabet, operandOne, operandTwo, flag) { }
public Append(Alphabet alphabet, string operandOne, string operandTwo, string flag) : base(alphabet, operandOne, operandTwo, flag) { }
public void Initialization() { firstAlphabet = new Alphabet(); secondAlphabet = new Alphabet(); }
public InternetServiceProfile(int ServiceProfileID, InternetServiceType type, InternetConnectionProfile profile) { this.pDelFlag = POPDeleteFlage.unknown; this.alphabet = Alphabet.unknown; this.pCmd = POPCommand.unknown; this.profileID = ServiceProfileID; this.srvType = type; this.conId = profile.profileID; user = passwd = tcpPort = address = hcContent = hcContLen = hcUsrAgent = hcProp = hcRedir = hcAuth = smFrom = smRcpt = smCC = smSubj = smHdr = smAuth = pNumber = pLength = tcpMR = tcpOT = secOpt = ""; }
public void set_remap(Alphabet ascii_alphabet, Alphabet binary_alphabet) { modshogunPINVOKE.StreamingStringByteFeatures_set_remap__SWIG_0(swigCPtr, Alphabet.getCPtr(ascii_alphabet), Alphabet.getCPtr(binary_alphabet)); if (modshogunPINVOKE.SWIGPendingException.Pending) throw modshogunPINVOKE.SWIGPendingException.Retrieve(); }
public void use_alphabet(Alphabet alpha) { modshogunPINVOKE.StreamingStringByteFeatures_use_alphabet__SWIG_1(swigCPtr, Alphabet.getCPtr(alpha)); if (modshogunPINVOKE.SWIGPendingException.Pending) throw modshogunPINVOKE.SWIGPendingException.Retrieve(); }
static void Main(string[] argv) { modshogun.init_shogun_with_defaults(); int num = 10; int order = 7; int gap = 0; bool reverse = false; string[] POS = new string[141]; for (int i = 0; i < 60; i++) { POS[i] = repeat("ACGT", 10); } for (int i = 61; i < 82; i++) { POS[i] = repeat("TTGT", 10); } for (int i = 83; i < 141; i++) { POS[i] = repeat("ACGT", 10); } string[] NEG = new string[141]; for (int i = 0; i < 60; i++) { NEG[i] = repeat("ACGT", 10); } for (int i = 61; i < 82; i++) { NEG[i] = repeat("TTGT", 10); } for (int i = 83; i < 141; i++) { NEG[i] = repeat("ACGT", 10); } string[] POSNEG = new string[282]; for (int i = 0; i < 141; i++) { POSNEG[i] = POS[i]; POSNEG[i + 141] = NEG[i]; } for(int i = 0; i < 10; i++) { Alphabet alpha = new Alphabet(DNA); StringCharFeatures traindat = new StringCharFeatures(alpha); traindat.set_features(POSNEG); StringWordFeatures trainudat = new StringWordFeatures(traindat.get_alphabet()); trainudat.obtain_from_char(traindat, order-1, order, gap, reverse); SortWordString pre = new SortWordString(); pre.init(trainudat); trainudat.add_preprocessor(pre); trainudat.apply_preprocessor(); CommWordStringKernel spec = new CommWordStringKernel(10, false); spec.set_normalizer(new IdentityKernelNormalizer()); spec.init(trainudat, trainudat); DoubleMatrix K = spec.get_kernel_matrix(); } modshogun.exit_shogun(); }