code
stringlengths
73
34.1k
label
stringclasses
1 value
public Record predict(String text) { TrainingParameters trainingParameters = (TrainingParameters) knowledgeBase.getTrainingParameters(); Dataframe testDataset = new Dataframe(knowledgeBase.getConfiguration()); testDataset.add( new Record( new AssociativeArray...
java
public ClassificationMetrics validate(Dataframe testDataset) { logger.info("validate()"); predict(testDataset); ClassificationMetrics vm = new ClassificationMetrics(testDataset); return vm; }
java
public ClassificationMetrics validate(Map<Object, URI> datasets) { TrainingParameters trainingParameters = (TrainingParameters) knowledgeBase.getTrainingParameters(); //build the testDataset Dataframe testDataset = Dataframe.Builder.parseTextFiles( datasets, Abst...
java
protected final String createKnowledgeBaseName(String storageName, String separator) { return storageName + separator + getClass().getSimpleName(); }
java
public static <T> Set<Set<T>> combinations(Set<T> elements, int subsetSize) { return combinationsStream(elements, subsetSize).collect(Collectors.toSet()); }
java
public static <T> Stream<Set<T>> combinationsStream(Set<T> elements, int subsetSize) { if (subsetSize == 0) { return Stream.of(new HashSet<>()); } else if (subsetSize <= elements.size()) { Set<T> remainingElements = elements; Iterator<T> it = remainingElement...
java
public static <T> Iterator<T[]> combinationsIterator(final T[] elements, final int subsetSize) { return new Iterator<T[]>() { /** * The index on the combination array. */ private int r = 0; /** * The index on the elements array. ...
java
public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) { return StreamSupport.<T>stream(spliterator, parallel); }
java
public static <T> Stream<T> stream(Stream<T> stream, boolean parallel) { if(parallel) { return stream.parallel(); } else { return stream.sequential(); } }
java
public static Method findMethod(Object obj, String methodName, Object... params) { Class<?>[] classArray = new Class<?>[params.length]; for (int i = 0; i < params.length; i++) { classArray[i] = params[i].getClass(); } try { //look on all the public, protected, def...
java
@Override public Map<String, Double> extract(final String text) { Map<Integer, String> ID2word = new HashMap<>(); //ID=>Kwd Map<Integer, Double> ID2occurrences = new HashMap<>(); //ID=>counts/scores Map<Integer, Integer> position2ID = new LinkedHashMap<>(); //word position=>ID maintain the o...
java
public static FlatDataCollection weightedSampling(AssociativeArray weightedTable, int n, boolean withReplacement) { FlatDataList sampledIds = new FlatDataList(); double sumOfFrequencies = Descriptives.sum(weightedTable.toFlatDataCollection()); int populationN = weightedTable.size(); ...
java
public static double xbarVariance(double variance, int sampleN, int populationN) { if(populationN<=0 || sampleN<=0 || sampleN>populationN) { throw new IllegalArgumentException("All the parameters must be positive and sampleN smaller than populationN."); } double xbarVariance...
java
public static double xbarStd(double std, int sampleN) { return Math.sqrt(xbarVariance(std*std, sampleN, Integer.MAX_VALUE)); }
java
public static double xbarStd(double std, int sampleN, int populationN) { return Math.sqrt(xbarVariance(std*std, sampleN, populationN)); }
java
public static double pbarVariance(double pbar, int sampleN, int populationN) { if(populationN<=0 || sampleN<=0 || sampleN>populationN) { throw new IllegalArgumentException("All the parameters must be positive and sampleN smaller than populationN."); } double f = (double)sampleN/popul...
java
public static double pbarStd(double pbar, int sampleN) { return Math.sqrt(pbarVariance(pbar, sampleN, Integer.MAX_VALUE)); }
java
public static double pbarStd(double pbar, int sampleN, int populationN) { return Math.sqrt(pbarVariance(pbar, sampleN, populationN)); }
java
public static int minimumSampleSizeForMaximumXbarStd(double maximumXbarStd, double populationStd, int populationN) { if(populationN<=0) { throw new IllegalArgumentException("The populationN parameter must be positive."); } double minimumSampleN = 1.0/(Math.pow(maximumXbarStd...
java
public static int minimumSampleSizeForGivenDandMaximumRisk(double d, double aLevel, double populationStd) { return minimumSampleSizeForGivenDandMaximumRisk(d, aLevel, populationStd, Integer.MAX_VALUE); }
java
public static int minimumSampleSizeForGivenDandMaximumRisk(double d, double aLevel, double populationStd, int populationN) { if(populationN<=0 || aLevel<=0 || d<=0) { throw new IllegalArgumentException("All the parameters must be positive."); } double a = 1.0 - aLevel/2.0; ...
java
public static double shinglerSimilarity(String text1, String text2, int w) { preprocessDocument(text1); preprocessDocument(text2); NgramsExtractor.Parameters parameters = new NgramsExtractor.Parameters(); parameters.setMaxCombinations(w); parameters.setMaxDistanceBetweenKwds(0);...
java
private void bigMapInitializer(StorageEngine storageEngine) { //get all the fields from all the inherited classes for(Field field : ReflectionMethods.getAllFields(new LinkedList<>(), this.getClass())){ //if the field is annotated with BigMap if (field.isAnnotationPresent(BigMap.c...
java
private void initializeBigMapField(StorageEngine storageEngine, Field field) { field.setAccessible(true); try { BigMap a = field.getAnnotation(BigMap.class); field.set(this, storageEngine.getBigMap(field.getName(), a.keyClass(), a.valueClass(), a.mapType(), a.storageHint(), a.co...
java
public Trainable put(String key, Trainable value) { return bundle.put(key, value); }
java
public void setParallelized(boolean parallelized) { for(Trainable t : bundle.values()) { if (t !=null && t instanceof Parallelizable) { ((Parallelizable)t).setParallelized(parallelized); } } }
java
public static <T extends Trainable, TP extends Parameterizable> T create(TP trainingParameters, Configuration configuration) { try { Class<T> aClass = (Class<T>) trainingParameters.getClass().getEnclosingClass(); Constructor<T> constructor = aClass.getDeclaredConstructor(trainingParamete...
java
public static <T extends Trainable> T load(Class<T> aClass, String storageName, Configuration configuration) { try { Constructor<T> constructor = aClass.getDeclaredConstructor(String.class, Configuration.class); constructor.setAccessible(true); return constructor.newInstance(...
java
public static double combination(int n, int k) { if(n<k) { throw new IllegalArgumentException("The n can't be smaller than k."); } double combinations=1.0; double lowerBound = n-k; for(int i=n;i>lowerBound;i--) { combinations *= i/(i-lowerBound); }...
java
private StorageType getStorageTypeFromName(String name) { for(Map.Entry<StorageType, DB> entry : storageRegistry.entrySet()) { DB storage = entry.getValue(); if(isOpenStorage(storage) && storage.exists(name)) { return entry.getKey(); } } ...
java
private void closeStorageRegistry() { for(DB storage : storageRegistry.values()) { if(isOpenStorage(storage)) { storage.close(); } } storageRegistry.clear(); }
java
private boolean blockedStorageClose(StorageType storageType) { DB storage = storageRegistry.get(storageType); if(isOpenStorage(storage)) { storage.commit(); //find the underlying engine Engine e = storage.getEngine(); while (EngineWrapper.class.isAssignab...
java
@Override public List<String> tokenize(String text) { List<String> tokens = new ArrayList<>(Arrays.asList(text.split("[\\p{Z}\\p{C}]+"))); return tokens; }
java
public static Map.Entry<Object, Object> maxMin(DataTable2D payoffMatrix) { if(payoffMatrix.isValid()==false) { throw new IllegalArgumentException("The payoff matrix does not have a rectangular format."); } AssociativeArray minPayoffs = new AssociativeArray(); for(Map...
java
public static Map.Entry<Object, Object> maxMax(DataTable2D payoffMatrix) { if(payoffMatrix.isValid()==false) { throw new IllegalArgumentException("The payoff matrix does not have a rectangular format."); } Double maxMaxPayoff = Double.NEGATIVE_INFINITY; Object maxMax...
java
public static Map.Entry<Object, Object> savage(DataTable2D payoffMatrix) { if(payoffMatrix.isValid()==false) { throw new IllegalArgumentException("The payoff matrix does not have a rectangular format."); } //Deep clone the payoffMatrix to avoid modifying its original values ...
java
public static Map.Entry<Object, Object> laplace(DataTable2D payoffMatrix) { if(payoffMatrix.isValid()==false) { throw new IllegalArgumentException("The payoff matrix does not have a rectangular format."); } //http://orms.pef.czu.cz/text/game-theory/DecisionTheory.html ...
java
public static Map.Entry<Object, Object> hurwiczAlpha(DataTable2D payoffMatrix, double alpha) { if(payoffMatrix.isValid()==false) { throw new IllegalArgumentException("The payoff matrix does not have a rectangular format."); } AssociativeArray minPayoffs = new AssociativeArra...
java
public static Map.Entry<Object, Object> maximumLikelihood(DataTable2D payoffMatrix, AssociativeArray eventProbabilities) { if(payoffMatrix.isValid()==false) { throw new IllegalArgumentException("The payoff matrix does not have a rectangular format."); } Map.Entry<Object, Obj...
java
public static Map.Entry<Object, Object> bayes(DataTable2D payoffMatrix, AssociativeArray eventProbabilities) { if(payoffMatrix.isValid()==false) { throw new IllegalArgumentException("The payoff matrix does not have a rectangular format."); } AssociativeArray expectedPayoffs ...
java
private static DataTable2D bivariateMatrix(Dataframe dataSet, BivariateType type) { DataTable2D bivariateMatrix = new DataTable2D(); //extract values of first variable Map<Object, TypeInference.DataType> columnTypes = dataSet.getXDataTypes(); Object[] allVariables = columnTypes....
java
public static <K> void updateWeights(double l1, double l2, double learningRate, Map<K, Double> weights, Map<K, Double> newWeights) { L2Regularizer.updateWeights(l2, learningRate, weights, newWeights); L1Regularizer.updateWeights(l1, learningRate, weights, newWeights); }
java
public static <K> double estimatePenalty(double l1, double l2, Map<K, Double> weights) { double penalty = 0.0; penalty += L2Regularizer.estimatePenalty(l2, weights); penalty += L1Regularizer.estimatePenalty(l1, weights); return penalty; }
java
public static int substr_count(final String string, final String substring) { if(substring.length()==1) { return substr_count(string, substring.charAt(0)); } int count = 0; int idx = 0; while ((idx = string.indexOf(substring, idx)) != -1) { ++idx;...
java
public static int substr_count(final String string, final char character) { int count = 0; int n = string.length(); for(int i=0;i<n;i++) { if(string.charAt(i)==character) { ++count; } } return count; }
java
public static String preg_replace(String regex, String replacement, String subject) { Pattern p = Pattern.compile(regex); return preg_replace(p, replacement, subject); }
java
public static String preg_replace(Pattern pattern, String replacement, String subject) { Matcher m = pattern.matcher(subject); StringBuffer sb = new StringBuffer(subject.length()); while(m.find()){ m.appendReplacement(sb, replacement); } m.appendTail(sb); ret...
java
public static int preg_match(String regex, String subject) { Pattern p = Pattern.compile(regex); return preg_match(p, subject); }
java
public static int preg_match(Pattern pattern, String subject) { int matches=0; Matcher m = pattern.matcher(subject); while(m.find()){ ++matches; } return matches; }
java
public static double round(double d, int i) { double multiplier = Math.pow(10, i); return Math.round(d*multiplier)/multiplier; }
java
public static double log(double d, double base) { if(base==1.0 || base<=0.0) { throw new IllegalArgumentException("Invalid base for logarithm."); } return Math.log(d)/Math.log(base); }
java
public static <K,V> Map<V,K> array_flip(Map<K,V> map) { Map<V,K> flipped = new HashMap<>(); for(Map.Entry<K,V> entry : map.entrySet()) { flipped.put(entry.getValue(), entry.getKey()); } return flipped; }
java
public static <T> void shuffle(T[] array, Random rnd) { //Implementing Fisher-Yates shuffle T tmp; for (int i = array.length - 1; i > 0; --i) { int index = rnd.nextInt(i + 1); tmp = array[index]; array[index] = array[i]; array[i] = tmp...
java
public static <T extends Comparable<T>> Integer[] asort(T[] array) { return _asort(array, false); }
java
public static <T extends Comparable<T>> Integer[] arsort(T[] array) { return _asort(array, true); }
java
public static <T> void arrangeByIndex(T[] array, Integer[] indexes) { if(array.length != indexes.length) { throw new IllegalArgumentException("The length of the two arrays must match."); } //sort the array based on the indexes for(int i=0;i<array.length;i++) { ...
java
public static double[] array_clone(double[] a) { if(a == null) { return a; } return Arrays.copyOf(a, a.length); }
java
public static double[][] array_clone(double[][] a) { if(a == null) { return a; } double[][] copy = new double[a.length][]; for(int i=0;i<a.length;i++) { copy[i] = Arrays.copyOf(a[i], a[i].length); } return copy; }
java
public static AssociativeArray sum(DataTable2D classifierClassProbabilityMatrix) { AssociativeArray combinedClassProbabilities = new AssociativeArray(); for(Map.Entry<Object, AssociativeArray> entry : classifierClassProbabilityMatrix.entrySet()) { //Object classifier = entry.getKey...
java
public static AssociativeArray median(DataTable2D classifierClassProbabilityMatrix) { AssociativeArray combinedClassProbabilities = new AssociativeArray(); //extract all the classes first for(Map.Entry<Object, AssociativeArray> entry : classifierClassProbabilityMatrix.entrySet()) { ...
java
public static AssociativeArray majorityVote(DataTable2D classifierClassProbabilityMatrix) { AssociativeArray combinedClassProbabilities = new AssociativeArray(); //extract all the classes first for(Map.Entry<Object, AssociativeArray> entry : classifierClassProbabilityMatrix.entrySet())...
java
public AssociativeArray2D getWordProbabilitiesPerTopic() { AssociativeArray2D ptw = new AssociativeArray2D(); ModelParameters modelParameters = knowledgeBase.getModelParameters(); TrainingParameters trainingParameters = knowledgeBase.getTrainingParameters(); //initializ...
java
private <K> void increase(Map<K, Integer> map, K key) { map.put(key, map.getOrDefault(key, 0)+1); }
java
private <K> void decrease(Map<K, Integer> map, K key) { map.put(key, map.getOrDefault(key, 0)-1); }
java
protected <T extends Serializable> Map<String, Object> preSerializer(T serializableObject) { Map<String, Object> objReferences = new HashMap<>(); for(Field field : ReflectionMethods.getAllFields(new LinkedList<>(), serializableObject.getClass())) { if (field.isAnnotationPresent(BigMap.class...
java
protected <T extends Serializable> void postSerializer(T serializableObject, Map<String, Object> objReferences) { for(Field field : ReflectionMethods.getAllFields(new LinkedList<>(), serializableObject.getClass())) { String fieldName = field.getName(); Object ref = objReferences.remove(...
java
protected <T extends Serializable> void postDeserializer(T serializableObject) { Method method = null; for(Field field : ReflectionMethods.getAllFields(new LinkedList<>(), serializableObject.getClass())) { if (field.isAnnotationPresent(BigMap.class)) { //look only for BigMaps ...
java
public static boolean isActive(Enum obj) { Enum value = ACTIVE_SWITCHES.get((Class)obj.getClass()); return value != null && value == obj; }
java
public boolean isValid() { int totalNumberOfColumns = 0; Set<Object> columns = new HashSet<>(); for(Map.Entry<Object, AssociativeArray> entry : internalData.entrySet()) { AssociativeArray row = entry.getValue(); if(columns.isEmpty()) { //this is executed o...
java
protected Object getSelectedClassFromClassScores(AssociativeArray predictionScores) { Map.Entry<Object, Object> maxEntry = MapMethods.selectMaxKeyValue(predictionScores); return maxEntry.getKey(); }
java
public static FlatDataCollection randomSampling(FlatDataList idList, int n, boolean randomizeRecords) { FlatDataList sampledIds = new FlatDataList(); int populationN = idList.size(); Object[] keys = idList.toArray(); if(randomizeRecords) { PHPMethods.<Object...
java
private CL getFromClusterMap(int clusterId, Map<Integer, CL> clusterMap) { CL c = clusterMap.get(clusterId); if(c.getFeatureIds() == null) { c.setFeatureIds(knowledgeBase.getModelParameters().getFeatureIds()); //fetch the featureIds from model parameters object } return c; ...
java
protected String getDirectory() { //get the default filepath of the permanet storage file String directory = storageConfiguration.getDirectory(); if(directory == null || directory.isEmpty()) { directory = System.getProperty("java.io.tmpdir"); //write them to the tmp directory ...
java
protected Path getRootPath(String storageName) { return Paths.get(getDirectory() + File.separator + storageName); }
java
protected boolean deleteIfExistsRecursively(Path path) throws IOException { try { return Files.deleteIfExists(path); } catch (DirectoryNotEmptyException ex) { //do recursive delete Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Overr...
java
protected boolean deleteDirectory(Path path, boolean cleanParent) throws IOException { boolean pathExists = deleteIfExistsRecursively(path); if(pathExists && cleanParent) { cleanEmptyParentDirectory(path.getParent()); return true; } return false; }
java
private void cleanEmptyParentDirectory(Path path) throws IOException { Path normPath = path.normalize(); if(normPath.equals(Paths.get(getDirectory()).normalize()) || normPath.equals(Paths.get(System.getProperty("java.io.tmpdir")).normalize())) { //stop if we reach the output or temporary directory ...
java
protected boolean moveDirectory(Path src, Path target) throws IOException { if(Files.exists(src)) { createDirectoryIfNotExists(target.getParent()); deleteDirectory(target, false); Files.move(src, target); cleanEmptyParentDirectory(src.getParent()); ret...
java
protected boolean createDirectoryIfNotExists(Path path) throws IOException { if(!Files.exists(path)) { Files.createDirectories(path); return true; } else { return false; } }
java
public static double simpleMovingAverage(FlatDataList flatDataList, int N) { double SMA=0; int counter=0; for(int i=flatDataList.size()-1;i>=0;--i) { double Yti = flatDataList.getDouble(i); if(counter>=N) { break; } SMA+=Yti; //pos...
java
public static double weightedMovingAverage(FlatDataList flatDataList, int N) { double WMA=0; double denominator=0.0; int counter=0; for(int i=flatDataList.size()-1;i>=0;--i) { double Yti = flatDataList.getDouble(i); if(counter>=N) { b...
java
public static double simpleExponentialSmoothing(FlatDataList flatDataList, double a) { double EMA=0; int count=0; for(int i=flatDataList.size()-1;i>=0;--i) { double Yti = flatDataList.getDouble(i); EMA+=a*Math.pow(1-a,count)*Yti; ++count; } r...
java
public static Double largest(Iterator<Double> elements, int k) { Iterator<Double> oppositeElements = new Iterator<Double>() { /** {@inheritDoc} */ @Override public boolean hasNext() { return elements.hasNext(); } /** {@inhe...
java
public static double nBar(TransposeDataList clusterIdList) { int populationM = clusterIdList.size(); double nBar = 0.0; for(Map.Entry<Object, FlatDataList> entry : clusterIdList.entrySet()) { nBar += (double)entry.getValue().size()/populationM; } return nBar...
java
public static TransposeDataCollection randomSampling(TransposeDataList clusterIdList, int sampleM) { TransposeDataCollection sampledIds = new TransposeDataCollection(); Object[] selectedClusters = clusterIdList.keySet().toArray(); PHPMethods.<Object>shuffle(selectedClusters); ...
java
public static String tokenizeSmileys(String text) { for(Map.Entry<String, String> smiley : SMILEYS_MAPPING.entrySet()) { text = text.replaceAll(smiley.getKey(), smiley.getValue()); } return text; }
java
public static String unifyTerminators(String text) { text = text.replaceAll("[\",:;()\\-]+", " "); // Replace commas, hyphens, quotes etc (count them as spaces) text = text.replaceAll("[\\.!?]", "."); // Unify terminators text = text.replaceAll("\\.[\\. ]+", "."); // Check for duplicated termina...
java
public static String removeAccents(String text) { text = Normalizer.normalize(text, Normalizer.Form.NFD); text = text.replaceAll("[\\p{InCombiningDiacriticalMarks}]", ""); return text; }
java
public static String clear(String text) { text = StringCleaner.tokenizeURLs(text); text = StringCleaner.tokenizeSmileys(text); text = StringCleaner.removeAccents(text); text = StringCleaner.removeSymbols(text); text = StringCleaner.removeExtraSpaces(text); return...
java
public static double getScoreValue(DataTable2D dataTable) { AssociativeArray result = getScore(dataTable); double score = result.getDouble("score"); return score; }
java
public static LPResult solve(double[] linearObjectiveFunction, List<LPSolver.LPConstraint> linearConstraintsList, boolean nonNegative, boolean maximize) { int m = linearConstraintsList.size(); List<LinearConstraint> constraints = new ArrayList<>(m); for(LPSolver.LPConstraint constraint : linear...
java
public final Object get2d(Object key1, Object key2) { AssociativeArray tmp = internalData.get(key1); if(tmp == null) { return null; } return tmp.internalData.get(key2); }
java
public final Object put2d(Object key1, Object key2, Object value) { AssociativeArray tmp = internalData.get(key1); if(tmp == null) { internalData.put(key1, new AssociativeArray()); } return internalData.get(key1).internalData.put(key2, value); }
java
public static String joinURL(Map<URLParts, String> urlParts) { try { URI uri = new URI(urlParts.get(URLParts.PROTOCOL), urlParts.get(URLParts.AUTHORITY), urlParts.get(URLParts.PATH), urlParts.get(URLParts.QUERY), urlParts.get(URLParts.REF)); return uri.toString(); } catc...
java
public static Map<DomainParts, String> splitDomain(String domain) { Map<DomainParts, String> domainParts = null; String[] dottedParts = domain.trim().toLowerCase(Locale.ENGLISH).split("\\."); if(dottedParts.length==2) { domainParts = new HashMap<>(); dom...
java
public static double fleschKincaidReadingEase(String strText) { strText = cleanText(strText); return PHPMethods.round((206.835 - (1.015 * averageWordsPerSentence(strText)) - (84.6 * averageSyllablesPerWord(strText))), 1); }
java
public static double fleschKincaidGradeLevel(String strText) { strText = cleanText(strText); return PHPMethods.round(((0.39 * averageWordsPerSentence(strText)) + (11.8 * averageSyllablesPerWord(strText)) - 15.59), 1); }
java
public static double gunningFogScore(String strText) { strText = cleanText(strText); return PHPMethods.round(((averageWordsPerSentence(strText) + percentageWordsWithThreeSyllables(strText)) * 0.4), 1); }
java
public static double colemanLiauIndex(String strText) { strText = cleanText(strText); int intWordCount = wordCount(strText); return PHPMethods.round( ( (5.89 * (letterCount(strText) / (double)intWordCount)) - (0.3 * (sentenceCount(strText) / (double)intWordCount)) - 15.8 ), 1); }
java
public static double smogIndex(String strText) { strText = cleanText(strText); return PHPMethods.round(1.043 * Math.sqrt((wordsWithThreeSyllables(strText) * (30.0 / sentenceCount(strText))) + 3.1291), 1); }
java