src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
SmoothLm extends BaseLanguageModel implements NgramLanguageModel { @Override public LmVocabulary getVocabulary() { return vocabulary; } private SmoothLm(
DataInputStream dis,
float logBase,
float unigramWeight,
float unknownBackoffPenalty,
boolean useStupidBackoff,
float stupidBacko... | @Test public void testVocabulary() throws IOException { SmoothLm lm = getTinyLm(); LmVocabulary vocab = lm.getVocabulary(); Assert.assertTrue(vocab.contains("Ahmet")); int i1 = vocab.indexOf("Ahmet"); Assert.assertTrue(vocab.contains("elma")); int i2 = vocab.indexOf("elma"); Assert.assertTrue(i1 != i2); Assert.assertEq... |
SmoothLm extends BaseLanguageModel implements NgramLanguageModel { public String explain(int... wordIndexes) { return explain(new Explanation(), wordIndexes).sb.toString(); } private SmoothLm(
DataInputStream dis,
float logBase,
float unigramWeight,
float unknownBackoffPenalty,
boolean us... | @Test public void testExplain() throws IOException { SmoothLm lm = getTinyLm(); LmVocabulary vocabulary = lm.getVocabulary(); int[] is = {vocabulary.indexOf("<s>")}; System.out.println(lm.explain(is)); int[] is2 = vocabulary.toIndexes("<s>", "kedi"); System.out.println(lm.explain(is2)); int[] is3 = vocabulary.toIndexes... |
NerDataSet { public static NerDataSet load(Path path, AnnotationStyle style) throws IOException { switch (style) { case BRACKET: return loadBracketStyle(path); case ENAMEX: return loadEnamexStyle(path); case OPEN_NLP: return loadOpenNlpStyle(path); } throw new IOException(String.format("Cannot load data from %s with st... | @Test public void testOpenNlpStyle() throws IOException { Path p = TestUtil.tempFileWithData( "<Start:ABC> Foo Bar <End> ivir zivir <Start:DEF> haha <End> . "); NerDataSet set = NerDataSet.load(p, AnnotationStyle.OPEN_NLP); System.out.println("types= " + set.types); Assert.assertTrue(TestUtil.containsAll(set.types, "AB... |
TurkishTokenizer { public static Builder builder() { return new Builder(); } private TurkishTokenizer(long acceptedTypeBits); static Builder builder(); boolean isTypeAccepted(Token.Type i); boolean isTypeIgnored(Token.Type i); List<Token> tokenize(File file); List<Token> tokenize(String input); List<Token> tokenize(Re... | @Test public void testInstances() { TurkishTokenizer t = TurkishTokenizer.DEFAULT; matchToken(t, "a b \t c \n \r", "a", "b", "c"); t = TurkishTokenizer.ALL; matchToken(t, " a b\t\n\rc", " ", "a", " ", "b", "\t", "\n", "\r", "c"); t = TurkishTokenizer.builder().ignoreAll().acceptTypes(Type.Number).build(); matchToken(t,... |
TurkishTokenizer { public List<Token> tokenize(File file) throws IOException { return getAllTokens(lexerInstance(CharStreams.fromPath(file.toPath()))); } private TurkishTokenizer(long acceptedTypeBits); static Builder builder(); boolean isTypeAccepted(Token.Type i); boolean isTypeIgnored(Token.Type i); List<Token> tok... | @Test public void testTokenBoundaries() { TurkishTokenizer t = TurkishTokenizer.ALL; List<Token> tokens = t.tokenize("bir av. geldi."); Token t0 = tokens.get(0); Assert.assertEquals("bir", t0.getText()); Assert.assertEquals(0, t0.getStart()); Assert.assertEquals(2, t0.getEnd()); Token t1 = tokens.get(1); Assert.assertE... |
Span { public String getSubstring(String input) { return input.substring(start, end); } Span(int start, int end); int length(); int middleValue(); Span copy(int offset); String getSubstring(String input); boolean inSpan(int i); final int start; final int end; } | @Test public void substringTest() { Assert.assertEquals("", new Span(0, 0).getSubstring("hello")); Assert.assertEquals("h", new Span(0, 1).getSubstring("hello")); Assert.assertEquals("ello", new Span(1, 5).getSubstring("hello")); } |
Span { public int length() { return end - start; } Span(int start, int end); int length(); int middleValue(); Span copy(int offset); String getSubstring(String input); boolean inSpan(int i); final int start; final int end; } | @Test public void lengthTest() { Assert.assertEquals(0, new Span(0, 0).length()); Assert.assertEquals(1, new Span(0, 1).length()); Assert.assertEquals(4, new Span(1, 5).length()); } |
TurkishSentenceExtractor extends PerceptronSegmenter { public List<String> fromParagraph(String paragraph) { List<Span> spans = extractToSpans(paragraph); List<String> sentences = new ArrayList<>(spans.size()); for (Span span : spans) { String sentence = span.getSubstring(paragraph).trim(); if (sentence.length() > 0) {... | @Test public void singletonAccessShouldNotThrowException() throws IOException { TurkishSentenceExtractor.DEFAULT.fromParagraph("hello"); }
@Test public void shouldExtractSentences1() throws IOException { String test = "Merhaba Dünya.| Nasılsın?"; List<String> expected = getSentences(test); Assert.assertEquals(expected,... |
TurkishSentenceExtractor extends PerceptronSegmenter { public static Builder builder() { return new Builder(); } private TurkishSentenceExtractor(FloatValueMap<String> weights); private TurkishSentenceExtractor(FloatValueMap<String> weights,
boolean doNotSplitInDoubleQuotes); static Builder builder(); List<Stri... | @Test public void testDoubleQuotes() throws IOException { TurkishSentenceExtractor e = TurkishSentenceExtractor .builder() .doNotSplitInDoubleQuotes() .useDefaultModel().build(); Assert.assertEquals( "\"Merhaba! Bugün hava çok güzel. Ne dersin?\" dedi tavşan.|Havucu kemirirken.", markBoundariesParagraph( e, "\"Merhaba!... |
TurkishDictionaryLoader { public static RootLexicon loadDefaultDictionaries() throws IOException { return loadFromResources(DEFAULT_DICTIONARY_RESOURCES); } static RootLexicon loadDefaultDictionaries(); static RootLexicon loadFromResources(String... resourcePaths); static RootLexicon loadFromResources(Collection<Strin... | @Test @Ignore("Not a unit test") public void saveFullAttributes() throws IOException { RootLexicon items = TurkishDictionaryLoader.loadDefaultDictionaries(); PrintWriter p = new PrintWriter(new File("dictionary-all-attributes.txt"), "utf-8"); for (DictionaryItem item : items) { p.println(item.toString()); } } |
TurkishNumbers { public static String convertToString(long input) { if (input == 0) { return "sıfır"; } if (input < MIN_NUMBER || input > MAX_NUMBER) { throw new IllegalArgumentException("number is out of bounds:" + input); } String result = ""; long girisPos = Math.abs(input); int sayac = 0; while (girisPos > 0) { int... | @Test public void cardinalTest() { Assert.assertEquals("sıfır", TurkishNumbers.convertToString(0)); Assert.assertEquals("bin", TurkishNumbers.convertToString(1000)); Assert.assertEquals("bir", TurkishNumbers.convertToString(1)); Assert.assertEquals("on bir", TurkishNumbers.convertToString(11)); Assert.assertEquals("yüz... |
TurkishNumbers { public static String convertNumberToString(String input) { if (input.startsWith("+")) { input = input.substring(1); } List<String> sb = new ArrayList<>(); int i; for (i = 0; i < input.length(); i++) { if (input.charAt(i) == '0') { sb.add("sıfır"); } else { break; } } String rest = input.substring(i); i... | @Test public void cardinalTest2() { Assert.assertEquals("sıfır", TurkishNumbers.convertNumberToString("0")); Assert.assertEquals("sıfır sıfır", TurkishNumbers.convertNumberToString("00")); Assert.assertEquals("sıfır sıfır sıfır", TurkishNumbers.convertNumberToString("000")); Assert.assertEquals("sıfır sıfır sıfır bir",... |
TurkishNumbers { public static String convertOrdinalNumberString(String input) { String numberPart = input; if (input.endsWith(".")) { numberPart = Strings.subStringUntilFirst(input, "."); } long number = Long.parseLong(numberPart); String text = convertToString(number); String[] words = text.trim().split("[ ]+"); Stri... | @Test public void ordinalTest() { Assert.assertEquals("sıfırıncı", TurkishNumbers.convertOrdinalNumberString("0.")); } |
TurkishNumbers { public static List<String> separateNumbers(String s) { return Regexps.allMatches(NUMBER_SEPARATION, s); } static Map<String, String> getOrdinalMap(); static String convertToString(long input); static String convertNumberToString(String input); static long singleWordNumberValue(String word); static Lis... | @Test public void separateNumbersTest() { Assert.assertEquals(Lists.newArrayList("H", "12", "A", "5") , TurkishNumbers.separateNumbers("H12A5")); Assert.assertEquals(Lists.newArrayList("F", "16", "'ya") , TurkishNumbers.separateNumbers("F16'ya")); } |
TurkishNumbers { public static List<String> seperateConnectedNumbers(List<String> inputSequence) { List<String> output = new ArrayList<>(inputSequence.size()); for (String s : inputSequence) { if (stringToNumber.containsKey(s)) { output.add(valueOf(stringToNumber.get(s))); continue; } output.addAll(seperateConnectedNum... | @Test public void separateConnectedNumbersTest() { Assert.assertEquals(Lists.newArrayList("on") , TurkishNumbers.seperateConnectedNumbers("on")); Assert.assertEquals(Lists.newArrayList("on", "iki", "bin", "altı", "yüz") , TurkishNumbers.seperateConnectedNumbers("onikibinaltıyüz")); Assert.assertEquals(Lists.newArrayLis... |
TurkishNumbers { public static long convertToNumber(String... words) { return textToNumber.convert(words); } static Map<String, String> getOrdinalMap(); static String convertToString(long input); static String convertNumberToString(String input); static long singleWordNumberValue(String word); static List<String> repl... | @Test public void testTextToNumber1() { Assert.assertEquals(11, TurkishNumbers.convertToNumber("on bir")); Assert.assertEquals(111, TurkishNumbers.convertToNumber("yüz on bir")); Assert.assertEquals(101, TurkishNumbers.convertToNumber("yüz bir")); Assert.assertEquals(1000_000, TurkishNumbers.convertToNumber("bir milyon... |
TurkishNumbers { public static int romanToDecimal(String s) { if (s == null || s.isEmpty() || !romanNumeralPattern.matcher(s).matches()) { return -1; } final Matcher matcher = Pattern.compile("M|CM|D|CD|C|XC|L|XL|X|IX|V|IV|I").matcher(s); final int[] decimalValues = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1... | @Test public void romanNumberTest() { Assert.assertEquals(-1, TurkishNumbers.romanToDecimal("foo")); Assert.assertEquals(-1, TurkishNumbers.romanToDecimal("IIIIIII")); Assert.assertEquals(1987, TurkishNumbers.romanToDecimal("MCMLXXXVII")); } |
SingleAnalysis { public PrimaryPos getPos() { return getGroup(groupCount() - 1).getPos(); } SingleAnalysis(
DictionaryItem item,
List<MorphemeData> morphemeDataList,
int[] groupBoundaries); static SingleAnalysis unknown(String input); static SingleAnalysis dummy(String input, DictionaryItem item); Str... | @Test public void getPosTest() { RuleBasedAnalyzer analyzer = getAnalyzer("görmek"); List<SingleAnalysis> analyses = analyzer.analyze("görmek"); Assert.assertEquals(1, analyses.size()); SingleAnalysis analysis = analyses.get(0); Assert.assertEquals(analysis.getDictionaryItem(), analyzer.getLexicon().getItemById("görmek... |
SingleAnalysis { public List<String> getStems() { List<String> stems = Lists.newArrayListWithCapacity(2); stems.add(getStem()); String previousStem = getGroup(0).surfaceForm(); if (groupBoundaries.length > 1) { for (int i = 1; i < groupBoundaries.length; i++) { MorphemeGroup ig = getGroup(i); MorphemeData suffixData = ... | @Test public void getStemsTest() { RuleBasedAnalyzer analyzer = getAnalyzer("kitap"); SingleAnalysis analysis = analyzer.analyze("kitap").get(0); Assert.assertEquals(toList("kitap"), analysis.getStems()); analysis = analyzer.analyze("kitaplı").get(0); Assert.assertEquals(toList("kitap", "kitaplı"), analysis.getStems())... |
SingleAnalysis { public List<String> getLemmas() { List<String> lemmas = Lists.newArrayListWithCapacity(2); lemmas.add(item.root); String previousStem = getGroup(0).surfaceForm(); if (!previousStem.equals(item.root)) { if (previousStem.endsWith("ğ")) { previousStem = previousStem.substring(0, previousStem.length() - 1)... | @Test public void getLemmasTest() { RuleBasedAnalyzer analyzer = getAnalyzer("kitap"); SingleAnalysis analysis = analyzer.analyze("kitap").get(0); Assert.assertEquals(toList("kitap"), analysis.getLemmas()); analysis = analyzer.analyze("kitaplı").get(0); Assert.assertEquals(toList("kitap", "kitaplı"), analysis.getLemmas... |
SingleAnalysis { public String formatLong() { return AnalysisFormatters.DEFAULT.format(this); } SingleAnalysis(
DictionaryItem item,
List<MorphemeData> morphemeDataList,
int[] groupBoundaries); static SingleAnalysis unknown(String input); static SingleAnalysis dummy(String input, DictionaryItem item);... | @Test public void getLemmasAfterZeroMorphemeTest_Issue_175() { RuleBasedAnalyzer analyzer = getAnalyzer("gün"); List<SingleAnalysis> analyses = analyzer.analyze("günlüğüm"); boolean found = false; for (SingleAnalysis analysis : analyses) { if (analysis.formatLong().contains("Ness→Noun+A3sg|Zero→Verb")) { found = true; ... |
WordAnalysisSurfaceFormatter { public String format(SingleAnalysis analysis, String apostrophe) { DictionaryItem item = analysis.getDictionaryItem(); String ending = analysis.getEnding(); if (apostrophe != null || apostropheRequired(analysis)) { if (apostrophe == null) { apostrophe = "'"; } return ending.length() > 0 ?... | @Test public void formatNonProperNoun() { TurkishMorphology morphology = TurkishMorphology.builder() .disableCache() .setLexicon("elma", "kitap", "demek", "evet") .build(); String[] inputs = {"elmamadaki", "elma", "kitalarımdan", "kitabımızsa", "diyebileceğimiz", "dedi", "evet"}; WordAnalysisSurfaceFormatter formatter ... |
WordAnalysisSurfaceFormatter { public String formatToCase(SingleAnalysis analysis, CaseType type, String apostrophe) { String formatted = format(analysis, apostrophe); Locale locale = analysis.getDictionaryItem().hasAttribute(RootAttribute.LocaleEn) ? Locale.ENGLISH : Turkish.LOCALE; switch (type) { case DEFAULT_CASE: ... | @Test public void formatToCase() { TurkishMorphology morphology = TurkishMorphology.builder() .disableCache() .setLexicon("kış", "şiir", "Aydın", "Google [Pr:gugıl]") .build(); String[] inputs = {"aydında", "googledan", "Google", "şiirde", "kışçığa", "kış"}; String[] expectedDefaultCase = {"Aydın'da", "Google'dan", "Go... |
TurkishSpellChecker { public List<String> suggestForWord(String word, NgramLanguageModel lm) { List<String> unRanked = getUnrankedSuggestions(word); return rankWithUnigramProbability(unRanked, lm); } TurkishSpellChecker(TurkishMorphology morphology); TurkishSpellChecker(TurkishMorphology morphology, CharacterGraph gra... | @Test public void suggestVerb1() { TurkishMorphology morphology = TurkishMorphology.builder().setLexicon("okumak").build(); List<String> endings = Lists.newArrayList("dum"); StemEndingGraph graph = new StemEndingGraph(morphology, endings); TurkishSpellChecker spellChecker = new TurkishSpellChecker(morphology, graph.ste... |
WordAnalysisSurfaceFormatter { public CaseType guessCase(String input) { boolean firstLetterUpperCase = false; int lowerCaseCount = 0; int upperCaseCount = 0; int letterCount = 0; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (!Character.isAlphabetic(c)) { continue; } if (i == 0) { firstLetter... | @Test public void guessCaseTest() { String[] inputs = {"abc", "Abc", "ABC", "Abc'de", "ABC'DE", "ABC.", "ABC'de", "a", "12", "A", "A1"}; WordAnalysisSurfaceFormatter.CaseType[] expected = { LOWER_CASE, TITLE_CASE, UPPER_CASE, TITLE_CASE, UPPER_CASE, UPPER_CASE, UPPER_CASE_ROOT_LOWER_CASE_ENDING, LOWER_CASE, DEFAULT_CAS... |
RuleBasedDisambiguator { public ResultSentence disambiguate(String sentence) { List<WordAnalysis> ambiguous = analyzer.analyzeSentence(sentence); ResultSentence s = new ResultSentence(sentence, ambiguous); s.makeDecisions(rules); return s; } RuleBasedDisambiguator(TurkishMorphology analyzer, Rules rules); ResultSentenc... | @Test public void test() throws IOException { String input = "4 Neden önemli?"; TurkishMorphology analyzer = TurkishMorphology.createWithDefaults(); RuleBasedDisambiguator disambiguator = new RuleBasedDisambiguator(analyzer, Rules.fromResources()); ResultSentence resultSentence = disambiguator.disambiguate(input); Syst... |
WebDocument { public static WebDocument fromText(String meta, List<String> pageData) { String url = Regexps.firstMatch(urlPattern, meta, 2); String id = url.replaceAll("http: String source = Regexps.firstMatch(sourcePattern, meta, 2); String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2); String labels = get... | @Test public void testTitleWithDoubleQuotes() { String meta = "<doc id=\"http: String content = "Fernandao yeni yıldan şampiyonluk bekliyor\n" + "30.12.2016 Cuma 17:04 (Güncellendi: 30.12.2016 Cuma 17:09)\n" + "Fernandao yeni yıldan şampiyonluk bekliyor\n" + "</doc>"; WebDocument d = WebDocument.fromText(meta, Splitter... |
CorpusDb { public CorpusDocument loadDocumentByKey(int key) { String sql = "SELECT ID, DOC_ID, SOURCE_ID, SOURCE_DATE, PROCESS_DATE, CONTENT FROM DOCUMENT_TABLE " + "WHERE ID = " + key; return getDocument(sql); } CorpusDb(Path dbRoot); private CorpusDb(JdbcConnectionPool connectionPool); void addAll(List<CorpusDocumen... | @Test public void saveLoadDocument() throws IOException, SQLException { Path tempDir = Files.createTempDirectory("foo"); CorpusDb storage = new CorpusDb(tempDir); Map<Integer, CorpusDocument> docMap = saveDocuments(storage); for (Integer key : docMap.keySet()) { CorpusDocument expected = docMap.get(key); CorpusDocument... |
CorpusDb { public List<SentenceSearchResult> search(String text) { try (Connection connection = connectionPool.getConnection()) { String sql = "SELECT T.* FROM FT_SEARCH_DATA('" + text + "', 0, 0) FT, SENTENCE_TABLE T " + "WHERE FT.TABLE='SENTENCE_TABLE' AND T.ID=FT.KEYS[0];"; Statement stat = connection.createStatemen... | @Test public void search() throws IOException, SQLException { Path tempDir = Files.createTempDirectory("foo"); CorpusDb storage = new CorpusDb(tempDir); Map<Integer, CorpusDocument> docMap = saveDocuments(storage); for (Integer key : docMap.keySet()) { CorpusDocument doc = docMap.get(key); List<String> paragraphs = Spl... |
SimpleTextWriter implements AutoCloseable { public SimpleTextWriter write(String s) throws IOException { try { if (s == null || s.length() == 0) { return this; } writer.write(s); return this; } finally { if (!keepOpen) { close(); } } } private SimpleTextWriter(
BufferedWriter writer,
OutputStream os,
... | @Test public void WriteStringTest() throws IOException { new SimpleTextWriter(tmpFile).write("Hello World!"); Assert.assertEquals(new SimpleTextReader(tmpFile).asString(), "Hello World!"); new SimpleTextWriter(tmpFile).write(null); Assert.assertEquals(new SimpleTextReader(tmpFile).asString(), ""); new SimpleTextWriter(... |
SimpleTextWriter implements AutoCloseable { public SimpleTextWriter writeLines(Collection<String> lines) throws IOException { try { IOs.writeLines(lines, writer); return this; } finally { if (!keepOpen) { close(); } } } private SimpleTextWriter(
BufferedWriter writer,
OutputStream os,
String encoding... | @Test public void WriteMultiLineStringTest() throws IOException { List<String> strs = new ArrayList<>(Arrays.asList("Merhaba", "Dunya", "")); new SimpleTextWriter(tmpFile).writeLines(strs); List<String> read = new SimpleTextReader(tmpFile).asStringList(); for (int i = 0; i < read.size(); i++) { Assert.assertEquals(read... |
KeyValueReader { public Map<String, String> loadFromFile(File file) throws IOException { return loadFromFile(new SimpleTextReader. Builder(file) .trim() .ignoreIfStartsWith(ignorePrefix) .ignoreWhiteSpaceLines() .build()); } KeyValueReader(String seperator); KeyValueReader(String seperator, String ignorePrefix); Map<S... | @Test public void testReader() throws IOException { Map<String, String> map = new KeyValueReader(":") .loadFromFile(new File(key_value_colon_separator.getFile())); Assert.assertEquals(map.size(), 4); Assert.assertTrue(TestUtil.containsAllKeys(map, "1", "2", "3", "4")); Assert.assertTrue(TestUtil.containsAllValues(map, ... |
Strings { public static boolean isNullOrEmpty(String str) { return str == null || str.length() == 0; } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... strings); static boolean allNullOrEmpty(String... strings); static String leftTrim(St... | @Test public void isEmptyTest() { assertTrue(isNullOrEmpty(null)); assertTrue(isNullOrEmpty("")); assertFalse(isNullOrEmpty("\n")); assertFalse(isNullOrEmpty("\t")); assertFalse(isNullOrEmpty(" ")); assertFalse(isNullOrEmpty("a")); assertFalse(isNullOrEmpty("as")); } |
Strings { public static boolean hasText(String s) { return s != null && s.length() > 0 && s.trim().length() > 0; } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... strings); static boolean allNullOrEmpty(String... strings); static String... | @Test public void hasTextTest() { assertFalse(hasText(null)); assertTrue(hasText("a")); assertTrue(hasText("abc")); assertFalse(hasText("")); assertFalse(hasText(null)); assertFalse(hasText(" ")); assertFalse(hasText("\t")); assertFalse(hasText("\n")); assertFalse(hasText(" \t")); } |
Strings { public static boolean allHasText(String... strings) { checkVarargString(strings); for (String s : strings) { if (!hasText(s)) { return false; } } return true; } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... strings); static ... | @Test public void testIfAllHasText() { assertTrue(allHasText("fg", "a", "hyh")); assertFalse(allHasText("fg", null, "hyh")); assertFalse(allHasText("fg", " ", "hyh")); }
@Test(expected = IllegalArgumentException.class) public void testIfAllHasTextExceptionIAE() { allHasText(); } |
Strings { public static boolean allNullOrEmpty(String... strings) { checkVarargString(strings); for (String s : strings) { if (!isNullOrEmpty(s)) { return false; } } return true; } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... strings... | @Test public void testAllEmpty() { assertTrue(allNullOrEmpty("", "", null)); assertFalse(allNullOrEmpty("", null, "hyh")); assertFalse(allNullOrEmpty(" ", "", "")); }
@Test(expected = IllegalArgumentException.class) public void testAllEmptyExceptionIAE() { allNullOrEmpty(); } |
Strings { public static String leftTrim(String s) { if (s == null) { return null; } if (s.length() == 0) { return EMPTY_STRING; } int j = 0; for (int i = 0; i < s.length(); i++) { if (Character.isWhitespace(s.charAt(i))) { j++; } else { break; } } return s.substring(j); } private Strings(); static boolean isNullOrEmpt... | @Test public void leftTrimTest() { assertNull(leftTrim(null)); assertEquals(leftTrim(""), ""); assertEquals(leftTrim(" \t "), ""); assertEquals(leftTrim(" 123"), "123"); assertEquals(leftTrim("\t123"), "123"); assertEquals(leftTrim("\n123"), "123"); assertEquals(leftTrim("123"), "123"); assertEquals(leftTrim(" \n 123")... |
Strings { public static String rightTrim(String str) { if (str == null) { return null; } if (str.length() == 0) { return EMPTY_STRING; } int j = str.length(); for (int i = str.length() - 1; i >= 0; --i) { if (Character.isWhitespace(str.charAt(i))) { j--; } else { break; } } return str.substring(0, j); } private String... | @Test public void rightTrimTest() { assertNull(rightTrim(null)); assertEquals(rightTrim(""), ""); assertEquals(rightTrim(" \t"), ""); assertEquals(rightTrim("aaa "), "aaa"); assertEquals(rightTrim("aaa \t "), "aaa"); assertEquals(rightTrim("aaa\n "), "aaa"); assertEquals(rightTrim("aaa"), "aaa"); assertEquals(rightTrim... |
Strings { public static String repeat(char c, int count) { if (count < 1) { return EMPTY_STRING; } char[] chars = new char[count]; Arrays.fill(chars, c); return new String(chars); } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... string... | @Test public void repeatTest() { assertEquals(repeat('c', -1), ""); assertEquals(repeat('c', 3), "ccc"); assertEquals(repeat('c', 1), "c"); assertEquals(repeat('c', 0), ""); assertNull(repeat(null, 1)); assertEquals(repeat("ab", -1), ""); assertEquals(repeat("ab", 3), "ababab"); assertEquals(repeat("ab", 1), "ab"); ass... |
Strings { public static String reverse(String str) { if (str == null) { return null; } if (str.length() == 0) { return EMPTY_STRING; } return new StringBuilder(str).reverse().toString(); } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String...... | @Test public void reverseTest() { assertNull(reverse(null), null); assertEquals(reverse(""), ""); assertEquals(reverse("a"), "a"); assertEquals(reverse("ab"), "ba"); assertEquals(reverse("ab cd "), " dc ba"); } |
CharacterGraphDecoder { public List<String> getSuggestions(String input) { return new Decoder().decode(input).getKeyList(); } CharacterGraphDecoder(float maxPenalty); CharacterGraphDecoder(); CharacterGraphDecoder(CharacterGraph graph); CharacterGraphDecoder(float maxPenalty, Map<Character, String> nearKeyMap); Char... | @Test public void stemEndingTest1() { TurkishMorphology morphology = TurkishMorphology.builder() .setLexicon("bakmak", "gelmek").build(); List<String> endings = Lists.newArrayList("acak", "ecek"); StemEndingGraph graph = new StemEndingGraph(morphology, endings); CharacterGraphDecoder spellChecker = new CharacterGraphDe... |
Strings { public static String insertFromLeft(String str, int interval, String stringToInsert) { if (interval < 0) { throw new IllegalArgumentException("interval value cannot be negative."); } if (str == null || interval == 0 || interval >= str.length() || isNullOrEmpty(stringToInsert)) { return str; } StringBuilder b ... | @Test public void insertFromLeftTest() { final String s = "0123456789"; assertEquals(insertFromLeft(s, 0, "-"), "0123456789"); assertEquals(insertFromLeft(s, 1, "-"), "0-1-2-3-4-5-6-7-8-9"); assertEquals(insertFromLeft("ahmet", 1, " "), "a h m e t"); assertEquals(insertFromLeft(s, 2, "-"), "01-23-45-67-89"); assertEqua... |
Strings { public static String insertFromRight(String str, int interval, String stringToInsert) { if (interval < 0) { throw new IllegalArgumentException("interval value cannot be negative."); } if (str == null || interval == 0 || interval >= str.length() || isNullOrEmpty(stringToInsert)) { return str; } StringBuilder b... | @Test public void insertFromRightTest() { final String s = "0123456789"; assertEquals(insertFromRight(s, 0, "-"), "0123456789"); assertEquals(insertFromRight(s, 1, "-"), "0-1-2-3-4-5-6-7-8-9"); assertEquals(insertFromRight(s, 2, "-"), "01-23-45-67-89"); assertEquals(insertFromRight(s, 3, "-"), "0-123-456-789"); assertE... |
Strings { public static String rightPad(String str, int size) { return rightPad(str, size, ' '); } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... strings); static boolean allNullOrEmpty(String... strings); static String leftTrim(String... | @Test public void testRightPad_StringInt() { assertEquals(null, rightPad(null, 5)); assertEquals(" ", rightPad("", 5)); assertEquals("abc ", rightPad("abc", 5)); assertEquals("abc", rightPad("abc", 2)); assertEquals("abc", rightPad("abc", -1)); }
@Test public void testRightPad_StringIntChar() { assertEquals(null, right... |
Strings { public static String leftPad(String str, int size) { return leftPad(str, size, " "); } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... strings); static boolean allNullOrEmpty(String... strings); static String leftTrim(String s... | @Test public void testLeftPad_StringInt() { assertEquals(null, leftPad(null, 5)); assertEquals(" ", leftPad("", 5)); assertEquals(" abc", leftPad("abc", 5)); assertEquals("abc", leftPad("abc", 2)); }
@Test public void testLeftPad_StringIntChar() { assertEquals(null, leftPad(null, 5, ' ')); assertEquals(" ", leftPad("",... |
CharacterGraphDecoder { public List<ScoredItem<String>> getSuggestionsWithScores(String input) { Decoder decoder = new Decoder(); return getMatches(input, decoder); } CharacterGraphDecoder(float maxPenalty); CharacterGraphDecoder(); CharacterGraphDecoder(CharacterGraph graph); CharacterGraphDecoder(float maxPenalty,... | @Test public void stemEndingTest2() { TurkishMorphology morphology = TurkishMorphology.builder() .setLexicon("üzmek", "yüz", "güz").build(); List<String> endings = Lists.newArrayList("düm"); StemEndingGraph graph = new StemEndingGraph(morphology, endings); CharacterGraphDecoder spellChecker = new CharacterGraphDecoder(... |
Strings { public static String whiteSpacesToSingleSpace(String str) { if (str == null) { return null; } if (str.isEmpty()) { return str; } return MULTI_SPACE.matcher(WHITE_SPACE_EXCEPT_SPACE.matcher(str).replaceAll(" ")) .replaceAll(" "); } private Strings(); static boolean isNullOrEmpty(String str); static boolean ha... | @Test public void testWhiteSpacesToSingleSpace() { assertEquals(whiteSpacesToSingleSpace(null), null); assertEquals(whiteSpacesToSingleSpace(""), ""); assertEquals(whiteSpacesToSingleSpace("asd"), "asd"); assertEquals(whiteSpacesToSingleSpace("a a"), "a a"); assertEquals(whiteSpacesToSingleSpace(" "), " "); assertEqual... |
Strings { public static String eliminateWhiteSpaces(String str) { if (str == null) { return null; } if (str.isEmpty()) { return str; } return WHITE_SPACE.matcher(str).replaceAll(""); } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(String s); static boolean allHasText(String... str... | @Test public void testEliminateWhiteSpaces() { assertEquals(eliminateWhiteSpaces(null), null); assertEquals(eliminateWhiteSpaces(""), ""); assertEquals(eliminateWhiteSpaces("asd"), "asd"); assertEquals(eliminateWhiteSpaces("a "), "a"); assertEquals(eliminateWhiteSpaces("a a "), "aa"); assertEquals(eliminateWhiteSpaces(... |
Strings { public static String subStringAfterFirst(String str, String s) { if (isNullOrEmpty(str) || isNullOrEmpty(s)) { return str; } final int pos = str.indexOf(s); if (pos < 0) { return str; } else { return str.substring(pos + s.length()); } } private Strings(); static boolean isNullOrEmpty(String str); static bool... | @Test public void testSubstringAfterFirst() { assertEquals(subStringAfterFirst("hello", "el"), "lo"); assertEquals(subStringAfterFirst("hellohello", "el"), "lohello"); assertEquals(subStringAfterFirst("hello", "hello"), ""); assertEquals(subStringAfterFirst("hello", ""), "hello"); assertEquals(subStringAfterFirst("hell... |
Strings { public static String subStringAfterLast(String str, String s) { if (isNullOrEmpty(str) || isNullOrEmpty(s)) { return str; } final int pos = str.lastIndexOf(s); if (pos < 0) { return str; } else { return str.substring(pos + s.length()); } } private Strings(); static boolean isNullOrEmpty(String str); static b... | @Test public void testSubstringAfterLast() { assertEquals(subStringAfterLast("hello\\world", "\\"), "world"); assertEquals(subStringAfterLast("hello", "el"), "lo"); assertEquals(subStringAfterLast("hellohello", "el"), "lo"); assertEquals(subStringAfterLast("hello", "hello"), ""); assertEquals(subStringAfterLast("hello"... |
Strings { public static String subStringUntilFirst(String str, String s) { if (isNullOrEmpty(str) || isNullOrEmpty(s)) { return str; } final int pos = str.indexOf(s); if (pos < 0) { return str; } else { return str.substring(0, pos); } } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasTex... | @Test public void testSubstringUntilFirst() { assertEquals(subStringUntilFirst("hello", "el"), "h"); assertEquals(subStringUntilFirst("hellohello", "el"), "h"); assertEquals(subStringUntilFirst("hello", "hello"), ""); assertEquals(subStringUntilFirst("hello", ""), "hello"); assertEquals(subStringUntilFirst("hello", nul... |
Strings { public static String subStringUntilLast(String str, String s) { if (isNullOrEmpty(str) || isNullOrEmpty(s)) { return str; } final int pos = str.lastIndexOf(s); if (pos < 0) { return str; } return str.substring(0, pos); } private Strings(); static boolean isNullOrEmpty(String str); static boolean hasText(Stri... | @Test public void testSubstringUntilLast() { assertEquals(subStringUntilLast("hello", "el"), "h"); assertEquals(subStringUntilLast("hellohello", "el"), "helloh"); assertEquals(subStringUntilLast("hello", "hello"), ""); assertEquals(subStringUntilLast("hello", ""), "hello"); assertEquals(subStringUntilLast("hello", null... |
Strings { public static String[] separateGrams(String word, int gramSize) { if (gramSize < 1) { throw new IllegalArgumentException("Gram size cannot be smaller than 1"); } if (gramSize > word.length()) { return EMPTY_STRING_ARRAY; } String[] grams = new String[word.length() - gramSize + 1]; for (int i = 0; i <= word.le... | @Test public void testGrams() { assertArrayEquals(separateGrams("hello", 1), new String[]{"h", "e", "l", "l", "o"}); assertArrayEquals(separateGrams("hello", 2), new String[]{"he", "el", "ll", "lo"}); assertArrayEquals(separateGrams("hello", 3), new String[]{"hel", "ell", "llo"}); assertArrayEquals(separateGrams("hello... |
Bytes { public static byte[] toByteArray(int... uints) { byte[] bytez = new byte[uints.length]; for (int i = 0; i < uints.length; i++) { if (uints[i] > 255 || uints[i] < 0) { throw new IllegalArgumentException( "Cannot convert to byte. Number should be between 0 and (255) 0xff. " + "Number:" + uints[i]); } bytez[i] = (... | @Test public void testtoByteArray() { Assert.assertArrayEquals(Bytes.toByteArray(0x7e, 0xac, 0x8a, 0x93), ba); }
@Test(expected = IllegalArgumentException.class) public void testtoByteArrayNegativeException() { Assert.assertArrayEquals(Bytes.toByteArray(-1, 0xac, 0x8a, 0x93), ba); }
@Test(expected = IllegalArgumentExce... |
Bytes { public static int toInt(byte[] pb, boolean bigEndian) { switch (pb.length) { case 1: return pb[0] & 0xff; case 2: if (bigEndian) { return (pb[0] << 8 & 0xff00) | (pb[1] & 0xff); } else { return (pb[1] << 8 & 0xff00) | (pb[0] & 0xff); } case 3: if (bigEndian) { return (pb[0] << 16 & 0xff0000) | (pb[1] << 8 & 0xf... | @Test public void testToInt() { assertEquals(Bytes.toInt(ba, true), bigEndianInt); assertEquals(Bytes.toInt(ba, false), littleEndianInt); assertEquals(Bytes.toInt((byte) 0x7e, (byte) 0xac, (byte) 0x8a, (byte) 0x93, true), bigEndianInt); assertEquals(Bytes.toInt((byte) 0x7e, (byte) 0xac, (byte) 0x8a, (byte) 0x93, false)... |
Bytes { public static int normalize(int i, int bitCount) { int max = 0xffffffff >>> (32 - bitCount); if (i > max) { throw new IllegalArgumentException("The integer cannot fit to bit boundaries."); } if (i > (max >>> 1)) { return i - (max + 1); } else { return i; } } static byte[] toByteArray(int... uints); static int ... | @Test public void testNormalize() { assertEquals(Bytes.normalize(0xff, 8), -1); assertEquals(Bytes.normalize(0x8000, 16), Short.MIN_VALUE); } |
Bytes { public static int[] toIntArray(byte[] ba, int amount, boolean bigEndian) { final int size = determineSize(amount, ba.length, 4); int[] result = new int[size / 4]; int i = 0; for (int j = 0; j < size; j += 4) { if (bigEndian) { result[i++] = toInt(ba[j], ba[j + 1], ba[j + 2], ba[j + 3], true); } else { result[i+... | @Test public void testToIntArray() { int[] intArrBig = {0x7eac8a93, 0x66AABBCC}; int[] intArrLittle = {0x938aac7e, 0xCCBBAA66,}; byte[] barr = {0x7e, (byte) 0xac, (byte) 0x8a, (byte) 0x93, 0x66, (byte) 0xAA, (byte) 0xBB, (byte) 0xCC}; Assert.assertArrayEquals(Bytes.toIntArray(barr, barr.length, true), intArrBig); Asser... |
Bytes { public static short[] toShortArray(byte[] ba, int amount, boolean bigEndian) { final int size = determineSize(amount, ba.length, 2); short[] result = new short[size / 2]; int i = 0; for (int j = 0; j < size; j += 2) { if (bigEndian) { result[i++] = (short) (ba[j] << 8 & 0xff00 | ba[j + 1] & 0xff); } else { resu... | @Test public void testToShort() { byte[] barr = {0x7e, (byte) 0xac, (byte) 0x8a, (byte) 0x93}; short[] sarrBe = {0x7eac, (short) 0x8a93}; short[] sarrLe = {(short) 0xac7e, (short) 0x938a}; Assert.assertArrayEquals(Bytes.toShortArray(barr, barr.length, true), sarrBe); Assert.assertArrayEquals(Bytes.toShortArray(barr, ba... |
Bytes { public static String toHex(byte b) { return String.format("%x", b); } static byte[] toByteArray(int... uints); static int toInt(byte[] pb, boolean bigEndian); static int normalize(int i, int bitCount); static void normalize(int iarr[], int bitCount); static byte[] toByteArray(int i, int size, boolean isBigEndi... | @Test public void toHextTest() { assertEquals(toHex((byte) 0), "0"); assertEquals(toHex((byte) 1), "1"); assertEquals(toHex((byte) 15), "f"); assertEquals(toHex((byte) 127), "7f"); assertEquals(toHex((byte) 0xcc), "cc"); assertEquals(toHex(new byte[]{(byte) 0x01}), "1"); assertEquals(toHex(new byte[]{(byte) 0xcc}), "cc... |
Bytes { public static String toHexWithZeros(byte b) { if (b == 0) { return "00"; } String s = toHex(b); if (s.length() == 1) { return "0" + s; } else { return s; } } static byte[] toByteArray(int... uints); static int toInt(byte[] pb, boolean bigEndian); static int normalize(int i, int bitCount); static void normalize... | @Test public void toHexWithZerostWithZerosTest() { assertEquals(toHexWithZeros((byte) 0), "00"); assertEquals(toHexWithZeros((byte) 1), "01"); assertEquals(toHexWithZeros((byte) 15), "0f"); assertEquals(toHexWithZeros((byte) 127), "7f"); assertEquals(toHexWithZeros((byte) 0xcc), "cc"); assertEquals(toHexWithZeros(new b... |
Bytes { public static void hexDump(OutputStream os, byte[] bytes, int columns) throws IOException { Dumper.hexDump(new ByteArrayInputStream(bytes, 0, bytes.length), os, columns, bytes.length); } static byte[] toByteArray(int... uints); static int toInt(byte[] pb, boolean bigEndian); static int normalize(int i, int bit... | @Test @Ignore(value = "Not a test") public void dump() throws IOException { Bytes.hexDump(new byte[]{0x01}, 20); } |
SimpleTextReader implements AutoCloseable { public String asString() throws IOException { String res = IOs.readAsString(getReader()); if (trim) { return res.trim(); } else { return res; } } SimpleTextReader(InputStream is, Template template); SimpleTextReader(File file); SimpleTextReader(File file, String encoding); ... | @Test public void testUtf8() throws IOException { String content = new SimpleTextReader(utf8_tr_with_bom.getFile(), "utf-8").asString(); assertEquals(content, "\u015fey"); }
@Test public void asStringTest() throws IOException { String a = new SimpleTextReader(multi_line_text_file.getFile()).asString(); System.out.print... |
SimpleTextReader implements AutoCloseable { public List<String> asStringList() throws IOException { return IOs.readAsStringList(getReader(), trim, filters.toArray(new Filter[0])); } SimpleTextReader(InputStream is, Template template); SimpleTextReader(File file); SimpleTextReader(File file, String encoding); SimpleT... | @Test public void multilineTest() throws IOException { List<String> list = new SimpleTextReader(multi_line_text_file.getFile()).asStringList(); assertEquals(list.size(), 17); assertEquals(list.get(1), "uno"); assertEquals(list.get(2), " dos"); }
@Test public void multilineConstarintTest() throws IOException { List<Stri... |
SimpleTextReader implements AutoCloseable { public IterableLineReader getIterableReader() throws IOException { return new IterableLineReader(getReader(), trim, filters); } SimpleTextReader(InputStream is, Template template); SimpleTextReader(File file); SimpleTextReader(File file, String encoding); SimpleTextReader(... | @Test public void iterableTest() throws IOException { int i = 0; for (String s : new SimpleTextReader(multi_line_text_file.getFile()).getIterableReader()) { if (i == 1) { assertEquals(s.trim(), "uno"); } if (i == 2) { assertEquals(s.trim(), "dos"); } if (i == 3) { assertEquals(s.trim(), "tres"); } i++; } assertEquals(i... |
Hash implements Comparable<Hash> { @Override public int compareTo(Hash o) { if (bytes.length != o.bytes.length) { return bytes.length - o.bytes.length; } BigInteger a = new BigInteger(1, bytes); BigInteger b = new BigInteger(1, o.bytes); return a.compareTo(b); } Hash(byte[] bytes); byte[] getBytes(); String getBytesAsS... | @Test public void testCompareTo() { Hash a = Hash.fromString("000000"); Hash b = Hash.fromString("000123"); assertTrue(a.compareTo(b) < 0); assertTrue(b.compareTo(a) > 0); } |
ECKeyStore { public void changePassword(char[] password) throws KeyStoreException { try { for (String alias : Collections.list(ks.aliases())) { Entry entry = ks.getEntry(alias, new PasswordProtection(this.password)); ks.setEntry(alias, entry, new PasswordProtection(password)); } Arrays.fill(this.password, '0'); this.pa... | @Test public void changePassword() throws KeyStoreException { ECKeyStore ks = new ECKeyStore(); PrivateKey k1 = PrivateKey.fresh(NetworkType.TESTNET); String alias1 = ks.addKey(k1); ks.changePassword("test".toCharArray()); PrivateKey k2 = ks.getKey(ECKeyStore.getUniqueID(k1)); assertTrue(ks.containsKey(alias1)); assert... |
MemoryMetricsCollector extends SystemMetricsCollector<MemoryMetrics> { @Override @ThreadSafe(enableChecks = false) public synchronized boolean getSnapshot(MemoryMetrics snapshot) { checkNotNull(snapshot, "Null value passed to getSnapshot!"); if (!mIsEnabled) { return false; } snapshot.sequenceNumber = mCounter.incremen... | @Test public void testBrokenFile() throws Exception { MemoryMetricsCollectorWithProcFile collector = new MemoryMetricsCollectorWithProcFile() .setPath(createFile("I am a weird android manufacturer")); MemoryMetrics snapshot = new MemoryMetrics(); collector.getSnapshot(snapshot); assertThat(collector.getSnapshot(snapsho... |
WakeLockMetrics extends SystemMetrics<WakeLockMetrics> { @Override public WakeLockMetrics set(WakeLockMetrics b) { heldTimeMs = b.heldTimeMs; acquiredCount = b.acquiredCount; if (b.isAttributionEnabled && isAttributionEnabled) { tagTimeMs.clear(); tagTimeMs.putAll(b.tagTimeMs); } return this; } WakeLockMetrics(); Wake... | @Test public void testSetWithoutAttribution() { WakeLockMetrics metrics = new WakeLockMetrics(); metrics.heldTimeMs = 10l; metrics.acquiredCount = 31; WakeLockMetrics alternate = new WakeLockMetrics(); alternate.set(metrics); assertThat(alternate).isEqualTo(metrics); }
@Test public void testSetWithAttribution() { WakeL... |
WakeLockMetrics extends SystemMetrics<WakeLockMetrics> { @Override public WakeLockMetrics sum(@Nullable WakeLockMetrics b, @Nullable WakeLockMetrics output) { if (output == null) { output = new WakeLockMetrics(isAttributionEnabled); } if (b == null) { output.set(this); } else { output.heldTimeMs = heldTimeMs + b.heldTi... | @Test public void testSumWithAttribution() { WakeLockMetrics metricsA = new WakeLockMetrics(true); metricsA.heldTimeMs = 20l; metricsA.acquiredCount = 4; metricsA.tagTimeMs.put("TestWakeLock1", 10l); metricsA.tagTimeMs.put("TestWakeLock3", 10l); WakeLockMetrics metricsB = new WakeLockMetrics(true); metricsB.heldTimeMs ... |
WakeLockMetrics extends SystemMetrics<WakeLockMetrics> { @Override public WakeLockMetrics diff(@Nullable WakeLockMetrics b, @Nullable WakeLockMetrics output) { if (output == null) { output = new WakeLockMetrics(isAttributionEnabled); } if (b == null) { output.set(this); } else { output.heldTimeMs = heldTimeMs - b.heldT... | @Test public void testDiffWithAttribution() { WakeLockMetrics metricsA = new WakeLockMetrics(true); metricsA.heldTimeMs = 25l; metricsA.acquiredCount = 100; metricsA.tagTimeMs.put("TestWakeLock1", 15l); metricsA.tagTimeMs.put("TestWakeLock2", 10l); WakeLockMetrics metricsB = new WakeLockMetrics(true); metricsB.heldTime... |
WakeLockMetrics extends SystemMetrics<WakeLockMetrics> { public @Nullable JSONObject attributionToJSONObject() throws JSONException { if (!isAttributionEnabled) { return null; } JSONObject attribution = new JSONObject(); for (int i = 0, size = tagTimeMs.size(); i < size; i++) { long currentTagTimeMs = tagTimeMs.valueAt... | @Test public void testAttributionToJSONObject() throws JSONException { WakeLockMetrics metrics = new WakeLockMetrics(); metrics.isAttributionEnabled = true; metrics.acquiredCount = 2; metrics.heldTimeMs = 400; metrics.tagTimeMs.put("Test", 100l); JSONObject attribution = metrics.attributionToJSONObject(); assertThat(at... |
CompositeMetricsSerializer extends SystemMetricsSerializer<CompositeMetrics> { public <T extends SystemMetrics<T>> CompositeMetricsSerializer addMetricsSerializer( Class<T> metricsClass, SystemMetricsSerializer<T> serializer) { Class<? extends SystemMetrics<?>> existingClass = mDeserializerClasses.get(serializer.getTag... | @Test(expected = RuntimeException.class) public void testMetricsWithTheSameTag() { CompositeMetricsSerializer serializer = new CompositeMetricsSerializer(); serializer.addMetricsSerializer(A.class, new ASerializer()); serializer.addMetricsSerializer(B.class, new BSerializer()); } |
SystemMetricsSerializer { public abstract void serializeContents(T metrics, DataOutput output) throws IOException; final void serialize(T metrics, DataOutput output); final boolean deserialize(T metrics, DataInput input); abstract long getTag(); abstract void serializeContents(T metrics, DataOutput output); abstract b... | @Test public void testSerializeContents() throws Exception { T instance = createInitializedInstance(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); getSerializer().serializeContents(instance, new DataOutputStream(baos)); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); T output = c... |
SystemMetricsSerializer { public final boolean deserialize(T metrics, DataInput input) throws IOException { if (input.readShort() != MAGIC || input.readShort() != VERSION || input.readLong() != getTag()) { return false; } return deserializeContents(metrics, input); } final void serialize(T metrics, DataOutput output);... | @Test public void testRandomContents() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream daos = new DataOutputStream(baos); daos.writeChars("Random test string that doesn't make any sense"); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(baos.toByteArray()... |
CompositeMetricsReporter implements SystemMetricsReporter<CompositeMetrics> { public void reportTo(CompositeMetrics metrics, SystemMetricsReporter.Event event) { for (int i = 0; i < mMetricsReporterMap.size(); i++) { Class<? extends SystemMetrics> metricsClass = mMetricsReporterMap.keyAt(i); if (metrics.isValid(metrics... | @Test public void testInvalidMetricsSkipped() { TimeMetrics timeMetrics = new TimeMetrics(); timeMetrics.realtimeMs = 100; timeMetrics.uptimeMs = 10; CompositeMetrics metrics = new CompositeMetrics().putMetric(TimeMetrics.class, timeMetrics); metrics.setIsValid(TimeMetrics.class, false); mReporter.reportTo(metrics, mEv... |
SensorMetricsCollector extends SystemMetricsCollector<SensorMetrics> { @Override public synchronized boolean getSnapshot(SensorMetrics snapshot) { Utilities.checkNotNull(snapshot, "Null value passed to getSnapshot!"); if (!mEnabled) { return false; } long currentTimeMs = SystemClock.elapsedRealtime(); snapshot.set(mCum... | @Test public void test_blank() { collector.getSnapshot(metrics); assertThat(metrics.total.activeTimeMs).isEqualTo(0); assertThat(metrics.total.powerMah).isEqualTo(0); assertThat(metrics.total.wakeUpTimeMs).isEqualTo(0); } |
CameraMetricsReporter implements SystemMetricsReporter<CameraMetrics> { @Override public void reportTo(CameraMetrics metrics, SystemMetricsReporter.Event event) { if (metrics.cameraOpenTimeMs != 0) { event.add(CAMERA_OPEN_TIME_MS, metrics.cameraOpenTimeMs); } if (metrics.cameraPreviewTimeMs != 0) { event.add(CAMERA_PRE... | @Test public void testZeroLogging() { CameraMetrics zeroMetrics = new CameraMetrics(); ReporterEvent event = new ReporterEvent(); mCameraMetricsReporter.reportTo(zeroMetrics, event); assertThat(event.eventMap.isEmpty()).isTrue(); }
@Test public void testNonZeroLogging() { CameraMetrics metrics1 = new CameraMetrics(); m... |
CpuFrequencyMetricsReporter implements SystemMetricsReporter<CpuFrequencyMetrics> { @Override public void reportTo(CpuFrequencyMetrics metrics, SystemMetricsReporter.Event event) { JSONObject output = metrics.toJSONObject(); if (output != null && output.length() != 0) { event.add(CPU_TIME_IN_STATE_S, output.toString())... | @Test public void testZeroLogging() { mReporter.reportTo(mMetrics, mEvent); assertThat(mEvent.eventMap.isEmpty()).isTrue(); } |
QTagUidNetworkBytesCollector extends NetworkBytesCollector { @Override public boolean getTotalBytes(long[] bytes) { try { if (mProcFileReader == null) { mProcFileReader = new ProcFileReader(getPath()); } mProcFileReader.reset(); if (!mProcFileReader.isValid() || !mProcFileReader.hasNext()) { return false; } Arrays.fill... | @Test public void testEmpty() throws Exception { QTagUidNetworkBytesCollector collector = new TestableCollector().setQTagUidStatsFile(createFile("")); boolean result = collector.getTotalBytes(mBytes); assertThat(result).isFalse(); }
@Test public void testBlank() throws Exception { QTagUidNetworkBytesCollector collector... |
TrafficStatsNetworkBytesCollector extends NetworkBytesCollector { @Override public synchronized boolean getTotalBytes(long[] bytes) { if (!mIsValid) { return false; } updateTotalBytes(); System.arraycopy(mTotalBytes, 0, bytes, 0, bytes.length); return true; } TrafficStatsNetworkBytesCollector(Context context); @Overrid... | @Test public void testEmpty() throws Exception { TrafficStatsNetworkBytesCollector collector = new TrafficStatsNetworkBytesCollector(RuntimeEnvironment.application); collector.getTotalBytes(mBytes); assertThat(mBytes).isEqualTo(new long[8]); }
@Test public void testInitialValues() throws Exception { ShadowTrafficStats.... |
MonotonicRadioMonitor { public int onRadioActivate(long transferStartMs, long transferEndMs) { long transferStartS = TimeUnit.MILLISECONDS.toSeconds(transferStartMs); long transferEndS = TimeUnit.MILLISECONDS.toSeconds(transferEndMs); long expectedNextIdleAndTotals; long newNextIdleAndTotals; boolean casSucceeded = fal... | @Test public void testSingleRadioActive() throws Exception { MonotonicRadioMonitor radioMonitor = new MonotonicRadioMonitor(WAKEUP_INTERVAL_S); int radioActiveS = radioMonitor.onRadioActivate(0L, 3000L); assertThat(radioActiveS, is(0)); assertThat(getRadioActiveS(radioMonitor), is(3 + WAKEUP_INTERVAL_S)); assertThat(ra... |
DiskMetricsCollector extends SystemMetricsCollector<DiskMetrics> { @Override @ThreadSafe(enableChecks = false) public synchronized boolean getSnapshot(DiskMetrics snapshot) { checkNotNull(snapshot, "Null value passed to getSnapshot!"); if (!mIsEnabled) { return false; } try { ProcFileReader ioReader = mProcIoFileReader... | @Test public void testBrokenFile() throws Exception { DiskMetricsCollectorWithProcFile collector = new DiskMetricsCollectorWithProcFile() .setPath(createFile("I am a weird android"), createFile("manufacturer")); DiskMetrics snapshot = new DiskMetrics(); assertThat(collector.getSnapshot(snapshot)).isFalse(); }
@Test pub... |
CompositeMetricsCollector extends SystemMetricsCollector<CompositeMetrics> { @Override @ThreadSafe(enableChecks = false) public boolean getSnapshot(CompositeMetrics snapshot) { checkNotNull(snapshot, "Null value passed to getSnapshot!"); boolean result = false; SimpleArrayMap<Class<? extends SystemMetrics>, SystemMetri... | @Test public void testNullSnapshot() { mExpectedException.expect(IllegalArgumentException.class); mCollector.getSnapshot(null); }
@Test public void allSnapshotsSucceed() throws Exception { mACollector.succeeds = true; mACollector.currentValue = 100; mBCollector.succeeds = true; mBCollector.currentValue = 120; assertTha... |
MemoryMetrics extends SystemMetrics<MemoryMetrics> { public MemoryMetrics sum(@Nullable MemoryMetrics b, @Nullable MemoryMetrics output) { if (output == null) { output = new MemoryMetrics(); } if (b == null) { output.set(this); } else { MemoryMetrics latest = sequenceNumber > b.sequenceNumber ? this : b; output.sequenc... | @Override @Test public void testSum() throws Exception { MemoryMetrics a = createMemoryMetrics(1); MemoryMetrics b = createMemoryMetrics(2); MemoryMetrics sum = new MemoryMetrics(); MemoryMetricsCollector collector = new MemoryMetricsCollector(); collector.enable(); collector.getSnapshot(a); collector.getSnapshot(b); s... |
AppWakeupMetricsCollector extends SystemMetricsCollector<AppWakeupMetrics> { @Override @ThreadSafe(enableChecks = false) public synchronized boolean getSnapshot(AppWakeupMetrics snapshot) { checkNotNull(snapshot, "Null value passed to getSnapshot!"); snapshot.appWakeups.clear(); for (int i = 0; i < mMetrics.appWakeups.... | @Test public void testGetSnapshot() { ShadowSystemClock.setElapsedRealtime(1); mAppWakeupMetricsCollector.recordWakeupStart(AppWakeupMetrics.WakeupReason.ALARM, "key1"); ShadowSystemClock.setElapsedRealtime(2); mAppWakeupMetricsCollector.recordWakeupStart( AppWakeupMetrics.WakeupReason.JOB_SCHEDULER, "key2"); ShadowSys... |
AppWakeupMetrics extends SystemMetrics<AppWakeupMetrics> { @Override public AppWakeupMetrics sum(@Nullable AppWakeupMetrics b, @Nullable AppWakeupMetrics output) { if (output == null) { output = new AppWakeupMetrics(); } if (b == null) { output.set(this); } else { output.appWakeups.clear(); for (int i = 0; i < appWakeu... | @Test @Override public void testSum() throws Exception { AppWakeupMetrics a = getAppWakeupMetrics(4, 0); AppWakeupMetrics b = getAppWakeupMetrics(7, 10); AppWakeupMetrics output = new AppWakeupMetrics(); a.sum(b, output); assertThat(output.appWakeups.size()).isEqualTo(7); verifyKeyAndReason(output.appWakeups); verifyWa... |
AppWakeupMetrics extends SystemMetrics<AppWakeupMetrics> { @Override public AppWakeupMetrics diff(@Nullable AppWakeupMetrics b, @Nullable AppWakeupMetrics output) { if (output == null) { output = new AppWakeupMetrics(); } if (b == null) { output.set(this); } else { output.appWakeups.clear(); for (int i = 0; i < appWake... | @Test @Override public void testDiff() throws Exception { AppWakeupMetrics a = getAppWakeupMetrics(7, 5); AppWakeupMetrics b = getAppWakeupMetrics(4, 10); AppWakeupMetrics output = new AppWakeupMetrics(); b.diff(a, output); assertThat(output.appWakeups.size()).isEqualTo(4); verifyKeyAndReason(output.appWakeups); verify... |
AppWakeupMetrics extends SystemMetrics<AppWakeupMetrics> { public JSONArray toJSON() throws JSONException { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < appWakeups.size(); i++) { JSONObject obj = new JSONObject(); AppWakeupMetrics.WakeupDetails details = appWakeups.valueAt(i); obj.put("key", appWakeups.ke... | @Test public void testWakeupAttribution() throws JSONException { AppWakeupMetrics metrics = new AppWakeupMetrics(); metrics.appWakeups.put( "wakeup", new AppWakeupMetrics.WakeupDetails(AppWakeupMetrics.WakeupReason.ALARM, 1L, 100L)); JSONArray json = metrics.toJSON(); assertThat(json.length()).isEqualTo(1); JSONObject ... |
DeviceBatteryMetricsCollector extends SystemMetricsCollector<DeviceBatteryMetrics> { @Override @ThreadSafe(enableChecks = false) public boolean getSnapshot(DeviceBatteryMetrics snapshot) { checkNotNull(snapshot, "Null value passed to getSnapshot!"); snapshot.batteryLevelPct = getBatteryLevel(getBatteryIntent()); long n... | @Test public void testInitialSnapshot() { ShadowSystemClock.setElapsedRealtime(5000); when(mContext.registerReceiver( Matchers.isNull(BroadcastReceiver.class), Matchers.any(IntentFilter.class))) .thenReturn(createBatteryIntent(BatteryManager.BATTERY_STATUS_CHARGING, 20, 100)); DeviceBatteryMetrics metrics = new DeviceB... |
SystemMetricsCollector { public abstract boolean getSnapshot(T snapshot); abstract boolean getSnapshot(T snapshot); abstract T createMetrics(); } | @Test public void testNullSnapshot() throws Exception { mExpectedException.expect(IllegalArgumentException.class); T instance = getClazz().newInstance(); instance.getSnapshot(null); } |
MemoryMetrics extends SystemMetrics<MemoryMetrics> { @Override public MemoryMetrics diff(@Nullable MemoryMetrics b, @Nullable MemoryMetrics output) { if (output == null) { output = new MemoryMetrics(); } if (b == null) { output.set(this); } else { MemoryMetrics latest = sequenceNumber >= b.sequenceNumber ? this : b; ou... | @Override @Test public void testDiff() throws Exception { MemoryMetrics a = createMemoryMetrics(1); MemoryMetrics b = createMemoryMetrics(2); MemoryMetrics sum = new MemoryMetrics(); MemoryMetricsCollector collector = new MemoryMetricsCollector(); collector.enable(); collector.getSnapshot(a); collector.getSnapshot(b); ... |
SystemMetrics implements Serializable { public abstract T set(T b); abstract T sum(@Nullable T b, @Nullable T output); abstract T diff(@Nullable T b, @Nullable T output); abstract T set(T b); T sum(@Nullable T b); T diff(@Nullable T b); } | @Test public void testSet() throws Exception { T a = createInitializedInstance(); T empty = createInstance(); empty.set(a); assertThat(empty).isEqualTo(a); } |
SystemMetrics implements Serializable { public abstract T sum(@Nullable T b, @Nullable T output); abstract T sum(@Nullable T b, @Nullable T output); abstract T diff(@Nullable T b, @Nullable T output); abstract T set(T b); T sum(@Nullable T b); T diff(@Nullable T b); } | @Test public void testSum() throws Exception { T a = createInitializedInstance(); int increment = 1; for (Field field : getClazz().getFields()) { if (MetricsUtil.isNumericField(field)) { field.set(a, 2 * increment); increment += 1; } } T b = createInitializedInstance(); T sum = createInstance(); a.sum(b, sum); incremen... |
SystemMetrics implements Serializable { public abstract T diff(@Nullable T b, @Nullable T output); abstract T sum(@Nullable T b, @Nullable T output); abstract T diff(@Nullable T b, @Nullable T output); abstract T set(T b); T sum(@Nullable T b); T diff(@Nullable T b); } | @Test public void testDiff() throws Exception { T a = createInitializedInstance(); T b = createInitializedInstance(); T diff = createInitializedInstance(); int index = 1; for (Field field : getClazz().getFields()) { if (MetricsUtil.isNumericField(field)) { field.set(a, 2 * index); index += 1; } } a.diff(b, diff); int i... |
ProcFileReader { public ProcFileReader reset() { mIsValid = true; if (mFile != null) { try { mFile.seek(0); } catch (IOException ioe) { close(); } } if (mFile == null) { try { mFile = new RandomAccessFile(mPath, "r"); } catch (IOException ioe) { mIsValid = false; close(); } } if (mIsValid) { mPosition = -1; mBufferSize... | @Test public void testReset() throws Exception { String contents = "notanumber"; String testPath = createFile(contents); ProcFileReader reader = new ProcFileReader(testPath).start(); assertThat(reader.readWord(CharBuffer.allocate(20)).toString()).isEqualTo(contents); assertThat(reader.hasReachedEOF()).isTrue(); reader.... |
StatefulSystemMetricsCollector { @Nullable public R getLatestDiffAndReset() { if (getLatestDiff() == null) { return null; } R temp = mPrev; mPrev = mCurr; mCurr = temp; return mDiff; } StatefulSystemMetricsCollector(S collector); StatefulSystemMetricsCollector(S collector, R curr, R prev, R diff); S getCollector(); @N... | @Test public void testGetLatestDiffAndReset() throws Exception { DummyMetricCollector collector = new DummyMetricCollector(); collector.currentValue = 10; StatefulSystemMetricsCollector<DummyMetric, DummyMetricCollector> statefulCollector = new StatefulSystemMetricsCollector<>(collector); assertThat(statefulCollector.g... |
StatefulSystemMetricsCollector { @Nullable public R getLatestDiff() { mIsValid &= mCollector.getSnapshot(this.mCurr); if (!mIsValid) { return null; } mCurr.diff(mPrev, mDiff); return mDiff; } StatefulSystemMetricsCollector(S collector); StatefulSystemMetricsCollector(S collector, R curr, R prev, R diff); S getCollecto... | @Test public void testCustomBaseSnapshot() throws Exception { DummyMetric metric = new DummyMetric(); metric.value = 0; DummyMetricCollector collector = new DummyMetricCollector(); collector.currentValue = 10; StatefulSystemMetricsCollector<DummyMetric, DummyMetricCollector> withCustomInitialSnapshot = new StatefulSyst... |
HealthStatsMetrics extends SystemMetrics<HealthStatsMetrics> { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HealthStatsMetrics that = (HealthStatsMetrics) o; if (dataType != null ? !dataType.equals(that.dataType) : that.dataType != nu... | @Test public void testEquals() { HealthStatsMetrics metricsA = new HealthStatsMetrics(); HealthStatsMetrics metricsB = new HealthStatsMetrics(); assertThat(metricsA).isEqualTo(metricsB); } |
SensorMetrics extends SystemMetrics<SensorMetrics> { @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SensorMetrics that = (SensorMetrics) o; return isAttributionEnabled == that.isAttributionEnabled && total.equals(that.total) && ... | @Test public void testEquals() { assertThat(new SensorMetrics()).isEqualTo(new SensorMetrics()); assertThat(createAttributedMetrics()).isEqualTo(createAttributedMetrics()); } |
HealthStatsMetrics extends SystemMetrics<HealthStatsMetrics> { @Override public HealthStatsMetrics set(HealthStatsMetrics b) { dataType = b.dataType; measurement.clear(); for (int i = 0; i < b.measurement.size(); i++) { measurement.append(b.measurement.keyAt(i), b.measurement.valueAt(i)); } timer.clear(); for (int i = ... | @Test public void testSetUninitialized() { HealthStatsMetrics initialized = createTestMetrics(); HealthStatsMetrics uninitialized = new HealthStatsMetrics(); uninitialized.set(initialized); assertThat(uninitialized).isEqualTo(initialized); }
@Test public void testSetInitialized() throws Exception { HealthStatsMetrics i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.