code
stringlengths
73
34.1k
label
stringclasses
1 value
public static double daleChallScore(String strText) { strText = cleanText(strText); int intDifficultWordCount = 0; List<String> arrWords = (new WhitespaceTokenizer()).tokenize(strText); int intWordCount = arrWords.size(); for (int i = 0; i < intWordCount; ++i) { if (!...
java
public static double daleChallGrade(String strText) { //http://rfptemplates.technologyevaluation.com/dale-chall-list-of-3000-simple-words.html double score=daleChallScore(strText); if(score<5.0) { return 2.5; } else if(score<6.0) { return 5.5; } ...
java
public static double spacheScore(String strText) { //http://simple.wikipedia.org/wiki/Spache_Readability_Formula strText = cleanText(strText); int intUniqueUnfamiliarWordCount = 0; Set<String> arrWords = new HashSet<>((new WhitespaceTokenizer()).tokenize(strText)); for(String wor...
java
private static int sentenceCount(String strText) { int numberOfDots=PHPMethods.substr_count(strText, '.'); // Will be tripped up by "Mr." or "U.K.". Not a major concern at this point. if(strText.charAt(strText.length()-1)!='.') { //missing the final dot, count it too ++numberOfDots; ...
java
private static String cleanText(String strText) { strText = HTMLParser.unsafeRemoveAllTags(strText); strText = strText.toLowerCase(Locale.ENGLISH); strText = StringCleaner.unifyTerminators(strText); strText = strText.replaceAll(" [0-9]+ ", " "); // Remove "words" compri...
java
private static double averageWordsPerSentence(String strText) { int intSentenceCount = sentenceCount(strText); int intWordCount = wordCount(strText); return (intWordCount / (double)intSentenceCount); }
java
private static int totalSyllables(String strText) { int intSyllableCount = 0; List<String> arrWords = (new WhitespaceTokenizer()).tokenize(strText); int intWordCount = arrWords.size(); for (int i = 0; i < intWordCount; ++i) { intSyllableCount += syllableCount(arrWord...
java
private static double averageSyllablesPerWord(String strText) { int intSyllableCount = totalSyllables(strText); int intWordCount = wordCount(strText); return (intSyllableCount / (double)intWordCount); }
java
private static int wordsWithThreeSyllables(String strText) { int intLongWordCount = 0; List<String> arrWords = (new WhitespaceTokenizer()).tokenize(strText); int intWordCount = arrWords.size(); for (int i = 0; i < intWordCount; ++i) { if(syllableCount(arrWords.get(i)...
java
private static double percentageWordsWithThreeSyllables(String strText) { int intWordCount = wordCount(strText); int intLongWordCount = wordsWithThreeSyllables(strText); double percentage = ((intLongWordCount / (double)intWordCount) * 100.0); return percentage; }
java
public static int similarityChars(String txt1, String txt2) { int sim = similar_char(txt1, txt1.length(), txt2, txt2.length()); return sim; }
java
public static double similarityPercentage(String txt1, String txt2) { double sim = similarityChars(txt1, txt2); return sim * 200.0 / (txt1.length() + txt2.length()); }
java
public String extract(String html, CETR.Parameters parameters) { html = clearText(html); //preprocess the Document by removing irrelevant HTML tags and empty lines and break the document to its lines List<String> rows = extractRows(html); // List<Integer> selectedRowIds = selectRows(row...
java
public static byte[] serialize(Object obj) { try(ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos)) { oos.writeObject(obj); return bos.toByteArray(); } catch (IOException ex) { throw new ...
java
public static Object deserialize(byte[] arr) { try (InputStream bis = new ByteArrayInputStream(arr); ObjectInputStream ois = new ObjectInputStream(bis)) { return ois.readObject(); } catch (IOException ex) { throw new UncheckedIOException(ex); } ...
java
public static AssociativeArray copy2Unmodifiable(AssociativeArray original) { Map<Object, Object> internalData = new LinkedHashMap<>(); internalData.putAll(original.internalData); internalData = Collections.unmodifiableMap(internalData); return new AssociativeArray(internalData); }
java
public final void overwrite(Map<Object, Object> data) { internalData.clear(); internalData.putAll(data); }
java
public final void multiplyValues(double multiplier) { for(Map.Entry<Object, Object> entry : internalData.entrySet()) { Double previousValue = TypeInference.toDouble(entry.getValue()); if(previousValue==null) { continue; } internalData.put(entry.get...
java
@SuppressWarnings("unchecked") public FlatDataList toFlatDataList() { Collection<Object> values = internalData.values(); List<Object> list; if (values instanceof List<?>) { list = (List<Object>)values; } else { list = new ArrayList(values); } ...
java
public void save(String storageName) { //store the objects on storage storageEngine.saveObject("data", data); //rename the storage storageEngine.rename(storageName); //reload the data of the object data = storageEngine.loadObject("data", Data.class); //mark it ...
java
@Override public void clear() { data.yDataType = null; data.atomicNextAvailableRecordId.set(0); data.xDataTypes.clear(); data.records.clear(); }
java
@Override public boolean remove(Object o) { Integer id = indexOf((Record) o); if(id == null) { return false; } remove(id); return true; }
java
@Override public boolean retainAll(Collection<?> c) { boolean modified = false; for(Map.Entry<Integer, Record> e : entries()) { Integer rId = e.getKey(); Record r = e.getValue(); if(!c.contains(r)) { remove(rId); modified = true; ...
java
public Integer addRecord(Record r) { Integer rId = _unsafe_add(r); updateMeta(r); return rId; }
java
public Integer set(Integer rId, Record r) { _unsafe_set(rId, r); updateMeta(r); return rId; }
java
public FlatDataList getXColumn(Object column) { FlatDataList flatDataList = new FlatDataList(); for(Record r : values()) { flatDataList.add(r.getX().get(column)); } return flatDataList; }
java
public FlatDataList getYColumn() { FlatDataList flatDataList = new FlatDataList(); for(Record r : values()) { flatDataList.add(r.getY()); } return flatDataList; }
java
public void dropXColumns(Set<Object> columnSet) { columnSet.retainAll(data.xDataTypes.keySet()); //keep only those columns that are already known to the Meta data of the Dataframe if(columnSet.isEmpty()) { return; } //remove all the columns from the Meta data data.x...
java
public Dataframe getSubset(FlatDataList idsCollection) { Dataframe d = new Dataframe(configuration); for(Object id : idsCollection) { d.add(get((Integer)id)); } return d; }
java
public void recalculateMeta() { data.yDataType = null; data.xDataTypes.clear(); for(Record r : values()) { updateMeta(r); } }
java
public Iterable<Map.Entry<Integer, Record>> entries() { return () -> new Iterator<Map.Entry<Integer, Record>>() { private final Iterator<Map.Entry<Integer, Record>> it = data.records.entrySet().iterator(); /** {@inheritDoc} */ @Override public boolean hasNext() {...
java
public Iterable<Integer> index() { return () -> new Iterator<Integer>() { private final Iterator<Integer> it = data.records.keySet().iterator(); /** {@inheritDoc} */ @Override public boolean hasNext() { return it.hasNext(); } ...
java
public Iterable<Record> values() { return () -> new Iterator<Record>(){ private final Iterator<Record> it = data.records.values().iterator(); /** {@inheritDoc} */ @Override public boolean hasNext() { return it.hasNext(); } ...
java
private Integer _unsafe_add(Record r) { Integer newId = data.atomicNextAvailableRecordId.getAndIncrement(); data.records.put(newId, r); return newId; }
java
private void updateMeta(Record r) { for(Map.Entry<Object, Object> entry : r.getX().entrySet()) { Object column = entry.getKey(); Object value = entry.getValue(); if(value!=null) { data.xDataTypes.putIfAbsent(column, TypeInference.getDataType(value)); ...
java
public static AssociativeArray normalDistributionGetParams(FlatDataCollection flatDataCollection) { AssociativeArray params = new AssociativeArray(); params.put("mean", Descriptives.mean(flatDataCollection)); params.put("variance", Descriptives.variance(flatDataCollection, true)); return...
java
public static <C extends Configurable> C getConfiguration(Class<C> klass) { String defaultPropertyFile = "datumbox." + klass.getSimpleName().toLowerCase(Locale.ENGLISH) + DEFAULT_POSTFIX + ".properties"; Properties properties = new Properties(); ClassLoader cl = klass.getClassLoader();...
java
public static <C extends Configurable> C getConfiguration(Class<C> klass, Properties properties) { //Initialize configuration object C configuration; try { Constructor<C> constructor = klass.getDeclaredConstructor(); constructor.setAccessible(true); configurat...
java
public static double getPvalue(TransposeDataList transposeDataList) { Object[] keys = transposeDataList.keySet().toArray(); if(keys.length!=2) { throw new IllegalArgumentException("The collection must contain observations from 2 groups."); } Object keyX = keys[0]; ...
java
public static double calculateCorrelation(TransposeDataList transposeDataList) { Object[] keys = transposeDataList.keySet().toArray(); if(keys.length!=2) { throw new IllegalArgumentException("The collection must contain observations from 2 groups."); } Object keyX = keys[0];...
java
private static double scoreToPvalue(double score, int n) { double Zs= score*Math.sqrt(n-1.0); double Ts= score*Math.sqrt((n-Zs)/(1.0-score*score)); return ContinuousDistributions.studentsCdf(Ts, n-2); }
java
public static P create(String... texts) { P p = objectFactory.createP(); for (String text : texts) { R r = RunUtil.create(text, p); p.getContent().add(r); } return p; }
java
public Object resolveExpression(String expressionString, Object contextRoot) { if ((expressionString.startsWith("${") || expressionString.startsWith("#{")) && expressionString.endsWith("}")) { expressionString = expressionUtil.stripExpression(expressionString); } ExpressionParser par...
java
public <T> void runProcessors(final WordprocessingMLPackage document, final ProxyBuilder<T> proxyBuilder) { final Map<BigInteger, CommentWrapper> comments = CommentUtil.getComments(document); CoordinatesWalker walker = new BaseCoordinatesWalker(document) { @Override protected void onParagraph(Para...
java
public ProxyBuilder<T> withInterface(Class<?> interfaceClass, Object interfaceImpl) { this.interfacesToImplementations.put(interfaceClass, interfaceImpl); return this; }
java
public T build() throws ProxyException { if (this.root == null) { throw new IllegalArgumentException("root must not be null!"); } if (this.interfacesToImplementations.isEmpty()) { // nothing to proxy return this.root; } try { ProxyMethodHandler methodHandler = new ProxyMet...
java
public static Comments.Comment getCommentAround(R run, WordprocessingMLPackage document) { try { if (run instanceof Child) { Child child = (Child) run; ContentAccessor parent = (ContentAccessor) child.getParent(); if (parent == null) return null; CommentRangeStart possibleComment = null; ...
java
public static Comments.Comment getCommentFor(ContentAccessor object, WordprocessingMLPackage document) { try { for (Object contentObject : object.getContent()) { if (contentObject instanceof CommentRangeStart) { try { BigInteger id = ((CommentRangeStart) contentObject).getId(); CommentsPart...
java
public static String getCommentString(Comments.Comment comment) { StringBuilder builder = new StringBuilder(); for (Object commentChildObject : comment.getContent()) { if (commentChildObject instanceof P) { builder.append(new ParagraphWrapper((P) commentChildObject).getText()); } } return builder.toSt...
java
public static String getText(R run) { String result = ""; for (Object content : run.getContent()) { if (content instanceof JAXBElement) { JAXBElement element = (JAXBElement) content; if (element.getValue() instanceof Text) { Text textObj = ...
java
public static void setText(R run, String text) { run.getContent().clear(); Text textObj = factory.createText(); textObj.setSpace("preserve"); textObj.setValue(text); textObj.setSpace("preserve"); // make the text preserve spaces run.getContent().add(textObj); }
java
public static R create(String text) { R run = factory.createR(); setText(run, text); return run; }
java
public static R create(Object content){ R run = factory.createR(); run.getContent().add(content); return run; }
java
public static R create(String text, P parentParagraph) { R run = create(text); applyParagraphStyle(parentParagraph, run); return run; }
java
public DocxStamperConfiguration addCommentProcessor(Class<?> interfaceClass, ICommentProcessor commentProcessor) { this.commentProcessors.put(interfaceClass, commentProcessor); return this; }
java
public DocxStamperConfiguration exposeInterfaceToExpressionLanguage(Class<?> interfaceClass, Object implementation) { this.expressionFunctions.put(interfaceClass, implementation); return this; }
java
public <T> ITypeResolver getResolverForType(Class<T> type) { ITypeResolver resolver = typeResolversByType.get(type); if (resolver == null) { return defaultResolver; } else { return resolver; } }
java
private void addRun(R run, int index) { int startIndex = currentPosition; int endIndex = currentPosition + RunUtil.getText(run).length() - 1; runs.add(new IndexedRun(startIndex, endIndex, index, run)); currentPosition = endIndex + 1; }
java
public List<R> getRuns() { List<R> resultList = new ArrayList<>(); for (IndexedRun run : runs) { resultList.add(run.getRun()); } return resultList; }
java
public boolean isTouchedByRange(int globalStartIndex, int globalEndIndex) { return ((startIndex >= globalStartIndex) && (startIndex <= globalEndIndex)) || ((endIndex >= globalStartIndex) && (endIndex <= globalEndIndex)) || ((startIndex <= globalStartIndex) && (endIndex >= globalE...
java
public void replace(int globalStartIndex, int globalEndIndex, String replacement) { int localStartIndex = globalIndexToLocalIndex(globalStartIndex); int localEndIndex = globalIndexToLocalIndex(globalEndIndex); String text = RunUtil.getText(run); text = text.substring(0, localStartIndex);...
java
public void resolveExpressions(final WordprocessingMLPackage document, ProxyBuilder<T> proxyBuilder) { try { final T expressionContext = proxyBuilder.build(); CoordinatesWalker walker = new BaseCoordinatesWalker(document) { @Override protected void onParagraph(ParagraphCoordinates paragr...
java
@Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if (mTrackedChild == null) { if (getChildCount() > 0) { mTrackedChild = getChildInTheMiddle(); mTrackedChildPrevTop = mTrackedChild.getT...
java
public static String of(String[] headers, String[][] data) { if (headers == null) throw new NullPointerException("headers == null"); if (headers.length == 0) throw new IllegalArgumentException("Headers must not be empty."); if (data == null) throw new NullPointerException("data == null"); return new Fli...
java
public static <T> String fromIterable(Iterable<T> rows, Class<T> rowType) { if (rows == null) throw new NullPointerException("rows == null"); if (rowType == null) throw new NullPointerException("rowType == null"); Method[] declaredMethods = rowType.getDeclaredMethods(); Arrays.sort(declaredMethods, MET...
java
public String getBaseClassName() { CodeGeneratorLoggerFactory.getLogger().debug( String.format("Reading base class name from data file [%s]", fileName)); String baseClass = reader.getBaseClassName(); if (baseClass == null) { String path = new File(fileName).getAbsolut...
java
public TestPlatform platform() { CodeGeneratorLoggerFactory.getLogger().debug( String.format("Specified platform in data file [%s] : [%s] ", fileName, reader.getPlatform())); TestPlatform currentPlatform = reader.getPlatform(); if (currentPlatform == null) { String da...
java
public static void registerListener(ListenerInfo information) { if (isServiceLoaderDisabled()) { // Donot even attempt register any listeners if the user doesnt want them to be managed. return; } logger.entering(information); listenerMap.put(information.getListene...
java
public static Map<String, String> getParameters(HttpServletRequest request) { Map<String, String> parameters = new HashMap<>(); Enumeration<?> names = request.getParameterNames(); while (names.hasMoreElements()) { String key = (String) names.nextElement(); String value = ...
java
static String saveGetLocation(WebDriver driver) { logger.entering(driver); String location = "n/a"; try { if (driver != null) { location = driver.getCurrentUrl(); } } catch (Exception exception) { logger.log(Level.FINER, "Current locati...
java
public String returnArg(String key) { SeLionElement element = HtmlSeLionElementSet.getInstance().findMatch(key); if (element == null) { return key; } if (!element.isUIElement()) { return key; } return key.substring(0, key.indexOf(element.getElementC...
java
public static List<GUIObjectDetails> transformKeys(List<String> keys, TestPlatform platform) { List<GUIObjectDetails> htmlObjectDetailsList = null; // Get the HTML object list based on the platform. // Note: This part is reached only when there is a valid platform specified. So it's safe to pro...
java
public void type(String value) { getDispatcher().beforeType(this, value); RemoteWebElement element = getElement(); element.clear(); element.sendKeys(value); if (Config.getBoolConfigProperty(ConfigProperty.ENABLE_GUI_LOGGING)) { logUIActions(UIActions.ENTERED,...
java
public void type(String value, boolean isKeepExistingText) { if (isKeepExistingText) { getDispatcher().beforeType(this, value); getElement().sendKeys(value); if (Config.getBoolConfigProperty(ConfigProperty.ENABLE_GUI_LOGGING)) { logUIActions(UIAct...
java
public void clear() { getElement().clear(); if (Config.getBoolConfigProperty(ConfigProperty.ENABLE_GUI_LOGGING)) { logUIAction(UIActions.CLEARED); } }
java
public String getText() { String text = getElement().getText(); if (text.isEmpty()) { text = getValue(); } return text; }
java
public void uploadFile(String filePath) { SeLionLogger.getLogger().entering(filePath); Preconditions.checkArgument(StringUtils.isNotBlank(filePath), "Please provide a valid file path to work with."); String filePathToUse = new File(filePath).getAbsolutePath(); LocalFileDetector detector ...
java
public void check() { getDispatcher().beforeCheck(this); RemoteWebElement e = (RemoteWebElement) getElement(); while (!e.isSelected()) { e.click(); } if (Config.getBoolConfigProperty(ConfigProperty.ENABLE_GUI_LOGGING)) { logUIAction(UIActions.CHEC...
java
public void check(String locator) { getDispatcher().beforeCheck(this, locator); this.check(); validatePresenceOfAlert(); WebDriverWaitUtils.waitUntilElementIsPresent(locator); getDispatcher().afterUncheck(this, locator); }
java
public void uncheck() { getDispatcher().beforeUncheck(this); RemoteWebElement e = (RemoteWebElement) getElement(); while (e.isSelected()) { e.click(); } if (Config.getBoolConfigProperty(ConfigProperty.ENABLE_GUI_LOGGING)) { logUIAction(UIActions.U...
java
public void uncheck(String locator) { getDispatcher().beforeUncheck(this, locator); this.uncheck(); validatePresenceOfAlert(); WebDriverWaitUtils.waitUntilElementIsPresent(locator); getDispatcher().afterUncheck(this, locator); }
java
public void click() { getDispatcher().beforeClick(this); getElement().click(); if (Config.getBoolConfigProperty(ConfigProperty.ENABLE_GUI_LOGGING)) { logUIAction(UIActions.CLICKED); } getDispatcher().afterClick(this); }
java
public void click(String locator) { getDispatcher().beforeClick(this, locator); click(); validatePresenceOfAlert(); WebDriverWaitUtils.waitUntilElementIsPresent(locator); getDispatcher().afterClick(this, locator); }
java
public ManagedArtifact getArtifact(String pathInfo) { LOGGER.entering(); ManagedArtifact managedArtifact = serverRepository.getArtifact(pathInfo); LOGGER.exiting(managedArtifact); return managedArtifact; }
java
static void cleanup() { LOGGER.entering(); for (String temp : files) { new File(temp).delete(); } // Cleaning up the files list files.clear(); LOGGER.exiting(); }
java
static void checkForDownloads(List<String> artifactNames, boolean checkTimeStamp, boolean cleanup) { LOGGER.entering(); if (checkTimeStamp && (lastModifiedTime == DOWNLOAD_FILE.lastModified())) { return; } lastModifiedTime = DOWNLOAD_FILE.lastModified(); if (cleanup...
java
static String downloadFile(String artifactUrl, String checksum) { LOGGER.entering(new Object[] { artifactUrl, checksum }); Preconditions.checkArgument(StringUtils.isNotBlank(artifactUrl), "Invalid URL: Cannot be null or empty"); Preconditions.checkArgument(StringUtils.isNotBlank(checksum), "Inva...
java
public void insertCode() throws IOException, ParseException { CompilationUnit cuResult = JavaParser.parse(baseFile); if (cuResult.getImports() != null) { List<ImportDeclaration> importsFromBaseFile = cuResult.getImports(); for (ImportDeclaration eachImport : importsFromExtendedFi...
java
public boolean add(SeLionElement element) { // if already initialized, add the new elements to the front of the list. if (initialized) { CodeGeneratorLogger logger = CodeGeneratorLoggerFactory.getLogger(); // info messages are only displayed after initialization happens ...
java
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String sOpDirectory) { logger.entering(new Object[] { xmlSuites, suites, sOpDirectory }); if (ListenerManager.isCurrentMethodSkipped(this)) { logger.exiting(ListenerManager.THREAD_EXCLUSION_MSG); return; ...
java
public void setExcelFileName(String fileName) { Preconditions.checkArgument(StringUtils.endsWith(fileName, ".xls"), "Excel file name must end with '.xls'."); reportFileName = fileName; }
java
@SuppressWarnings("rawtypes") private void createExcelReport() { logger.entering(); wb = new HSSFWorkbook(); Styles.initStyles(wb); // Report Details this.createReportInfo(); // Map of sheet names - individual reports and corresponding data this.createRepor...
java
private void createReportInfo() { logger.entering(); HSSFSheet summarySheet = wb.createSheet(ReportSheetNames.TESTSUMMARYREPORT.getName()); Map<String, String> reportInfo = new LinkedHashMap<String, String>(); for (Entry<String, String> temp : ConfigSummaryData.getConfigSummary().entr...
java
private void generateSummaryData(List<ISuite> suites) { logger.entering(suites); SummarizedData tempSuite; SummarizedData tempTest; SummarizedData tempGroups; this.generateTestCaseResultData(suites); // Generating Group Summary data for (ISuite suite : suites) {...
java
private List<TestCaseResult> createResultFromMap(IResultMap resultMap) { logger.entering(resultMap); List<TestCaseResult> statusWiseResults = new ArrayList<TestCaseResult>(); for (ITestResult singleMethodResult : resultMap.getAllResults()) { TestCaseResult tcresult1 = new TestCaseRe...
java
private void showAssertInfo(IAssert<?> assertCommand, AssertionError ex, boolean failedTest) { ITestResult testResult = Reporter.getCurrentTestResult(); // Checks whether the soft assert was called in a TestNG test run or else within a Java application. String methodName = "main"; if (t...
java
@Override public RemoteWebDriver createDriver(WebDriverPlatform platform, CommandExecutor commandExecutor, URL url, Capabilities caps) { if (platform.equals(WebDriverPlatform.ANDROID)) { if (commandExecutor == null) { return new SeLionAp...
java
static void copyFileFromResources(String sourcePath, String destPath) throws IOException { LOGGER.entering(new Object[] { sourcePath, destPath }); File downloadFile = new File(destPath); if (!downloadFile.exists()) { InputStream stream = JarSpawner.class.getResourceAsStream(sourceP...
java
public String getDateText() { String value = null; value = HtmlElementUtils.locateElement(dateTextLocator).getText(); return value; }
java
public void setDate(Calendar to) { // Navigate from the current date // to the new date navigateMonth(calendar, to); // Select the day-of-month. clickDay(to.get(Calendar.DATE)); Calendar cal = calendar; cal.set(Calendar.YEAR, to.get(Calendar.YEAR)); cal....
java