code
stringlengths
73
34.1k
label
stringclasses
1 value
protected void setup(Mapper.Context context) { Configuration conf = context.getConfiguration(); extractor = new CooccurrenceExtractor(conf); // Set up the IteratorFactory properties Properties props = new Properties(); for (String property : ITERATOR_FACTORY_PROPERTIE...
java
public DependencyPath next() { if (next == null) throw new NoSuchElementException("No further paths to return"); DependencyPath p = next; advance(); return p; }
java
public long getPrimitive(int index) { if (index < 0 || index >= maxLength) { throw new ArrayIndexOutOfBoundsException("invalid index: " + index); } int pos = Arrays.binarySearch(indices, index); long value = (pos >= 0) ? values[pos] : 0; return value; }
java
public long[] toPrimitiveArray(long[] array) { for (int i = 0, j = 0; i < array.length; ++i) { int index = -1; if (j < indices.length && (index = indices[j]) == i) { array[i] = values[j]; j++; } else array[i] = 0; } return array; }
java
private Function getFunction(int exponent, int dimensions) { // Base case: we keep the same ordering. Create this function on the // fly to save space, since the base case should rarely get called. if (exponent == 0) { int[] func = new int[dimensions]; for (int i = 0; i ...
java
public V put(K key, V value) { V old = super.put(key, value); if (size() > bound) { remove(firstKey()); } return old; }
java
private void updateTimeRange(long timestamp) { // update the timestamp ranges if (timestamp < startTime) { startTime = timestamp; } if (timestamp > endTime) { endTime = timestamp; } }
java
public String getDimensionDescription(int dimension) { if (dimension < 0 || dimension >= basisMapping.numDimensions()) throw new IllegalArgumentException( "Invalid dimension: " + dimension); return basisMapping.getDimensionDescription(dimension); }
java
private boolean acceptWord(String word) { return !word.equals(EMPTY_STRING) && (semanticFilter.isEmpty() || semanticFilter.contains(word)); }
java
private void removeHtmlComments(StringBuilder article) { int htmlCommentStart = article.indexOf("<!--"); // Repeatedly loop while <!-- --> html comment markup still exists in // the document while (htmlCommentStart >= 0) { // Find the matching closing --> if it exists. Some ...
java
private int getTokenCount(String article) { Pattern notWhiteSpace = Pattern.compile("\\S+"); Matcher matcher = notWhiteSpace.matcher(article); int tokens = 0; while (matcher.find()) tokens++; return tokens; }
java
private long getIndex(T x, T y) { int i = elementIndices.index(x); int j = elementIndices.index(y); long index = (((long)i) << 32) | j; return index; }
java
public int getCount(T x, T y) { // REMINDER: check for indexing? return counts.get(getIndex(x, y)); }
java
public void reset() { data.rewind(); // Read off the rows, columns, and non-zero elements data.getInt(); data.getInt(); data.getInt(); // Reset the counters. curCol = 0; entry = 0; try { advance(); } catch (IOException ioe) { ...
java
public static void save(Object o, File file) { try { FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream outStream = new ObjectOutputStream(new BufferedOutputStream(fos)); outStream.writeObject(o); outStream.close(); } ca...
java
public static void save(Object o, OutputStream stream) { try { ObjectOutputStream outStream = (stream instanceof ObjectOutputStream) ? (ObjectOutputStream)stream : new ObjectOutputStream(stream); outStream.writeObject(o); }...
java
@SuppressWarnings("unchecked") public static <T> T load(InputStream stream) { try { ObjectInputStream inStream = (stream instanceof ObjectInputStream) ? (ObjectInputStream)stream : new ObjectInputStream(stream); T object = (T) inStream.read...
java
public static <T> Iterator<T> join(Collection<Iterable<T>> iterables) { Queue<Iterator<T>> iters = new ArrayDeque<Iterator<T>>(iterables.size()); for (Iterable<T> i : iterables) iters.add(i.iterator()); return new CombinedIterator<T>(iters); }
java
private void advance() { if (current == null || !current.hasNext()) { do { current = iters.poll(); } while (current != null && !current.hasNext()); } }
java
public synchronized T next() { if (current == null) { throw new NoSuchElementException(); } T t = current.next(); // Once an element has been drawn from the iterator, the current // iterator should be used for any subsequent remove call. if (toRemoveFrom != current) toRemoveF...
java
public DoubleVector buildVector(BufferedReader document, DoubleVector documentVector) { // Tokenize and determine what words exist in the document, along with // the requested meta information, such as a term frequency. Map<String, Integer> termCounts = new HashMap<...
java
@Override public Graph<Edge> readUndirectedFromWeighted( File f, Indexer<String> vertexIndexer, double minWeight) throws IOException { BufferedReader br = new BufferedReader(new FileReader(f)); Graph<Edge> g = new SparseUndirectedGraph(); int lineNo = 0; for (String...
java
private static void clusterIteration(Matrix matrix, int numClusters, KMeansSeed seedType, CriterionFunction criterion) { DoubleVector[] centers = seedType.chooseSeeds(numClusters, matrix); ...
java
protected static Set<String> loadValidTermSet(String validTermsFileName) throws IOException { Set<String> validTerms = new HashSet<String>(); BufferedReader br = new BufferedReader( new FileReader(validTermsFileName)); for (String line = null; (line = br.readLine()...
java
private void retainOnly(int columns) { LOGGER.info("Sorting the columns by entropy and computing the top " + columns + " columns to retain"); int words = termToIndex.numDimensions(); MultiMap<Double,Integer> entropyToIndex = new BoundedSortedMultiMap<Doubl...
java
private void processWordsInNP(ArrayList<Pair<String>> wordsInPhrase) { if( wordsInPhrase.size() > 1 ) { // this is from Grefenstette's pseudo code for (int i = 0; i < wordsInPhrase.size()-1; i++) { if (inStartSet(wordsInPhrase.get(i).x) ) { for (int j = i+1; j < wordsInPhrase.size(); j++ ) { ...
java
protected Double computeAssociation(SemanticSpace sspace, String word1, String word2) { Vector v1 = sspace.getVector(word1); Vector v2 = sspace.getVector(word2); if (v1 == null || v2 == null) return null; // Find the ranks of ...
java
protected double computeScore(double[] humanScores, double[] compScores) { double average = 0; for (double score : compScores) average += score; return average / compScores.length; }
java
public static void bitreverse(DoubleVector data, int i0, int stride) { int n = data.length(); for (int i = 0,j = 0; i < n - 1; i++) { int k = n / 2; if (i < j) { double tmp = data.get(i0+stride*i); data.set(i0+stride*i, data.get(i0+stride*j)); ...
java
protected int getIndexFromMap(int[] maskMap, int index) { if (index < 0 || index >= maskMap.length) throw new IndexOutOfBoundsException( "The given index is beyond the bounds of the matrix"); int newIndex = maskMap[index]; if (newIndex < 0 || maskMap =...
java
static String toPattern(String pos1, String rel, String pos2) { return pos1 + ":" + rel + ":" + pos2; }
java
private int computePk1Measure(double[] objectiveScores, double pk1Threshold) { LOGGER.fine("Computing the PK1 measure"); // Compute the average of the objective scores. double average = 0; for (int k = 0; k < objectiveScores.length; ++k) ave...
java
private int computePk2Measure(double[] objectiveScores) { LOGGER.fine("Computing the PK2 measure"); // Compute each Pk2 score and the average score. double average = 0; for (int k = objectiveScores.length - 1; k > 0; --k) { objectiveScores[k] /= objectiveScores[k-1]; ...
java
private double extractScore(String clutoOutput) throws IOException { double score = 0; BufferedReader reader = new BufferedReader(new StringReader(clutoOutput)); String line = null; while ((line = reader.readLine()) != null) { if (line.contains("[I2=")) { ...
java
protected ArgOptions setupOptions() { ArgOptions options = new ArgOptions(); options.addOption('c', "corpusDir", "the directory of the corpus", true, "DIR", "Required"); options.addOption('a', "analogyFile", "the file containing list of word p...
java
public static synchronized DependencyExtractor getExtractor(String name) { DependencyExtractor e = nameToExtractor.get(name); if (e == null) throw new IllegalArgumentException("No extactor with name " + name); return e; }
java
public double count(T obj) { double count = counts.get(obj); count++; counts.put(obj, count); sum++; return count; }
java
public Iterator<Map.Entry<T,Double>> iterator() { return Collections.unmodifiableSet( TDecorators.wrap(counts).entrySet()).iterator(); }
java
private static double distanceSum(double[] distances) { double sum = 0; for (double distance : distances) sum += Math.pow(distance, 2); return sum; }
java
private boolean advance(int tokens) { while (buffer.size() < tokens && tokenizer.hasNext()) buffer.add(tokenizer.next()); return buffer.size() >= tokens; }
java
public static void initializeIndex(String indexDir, String dataDir) { File indexDir_f = new File(indexDir); File dataDir_f = new File(dataDir); long start = new Date().getTime(); try { int numIndexed = index(indexDir_f, dataDir_f); long end = new Date().getTime()...
java
private static int index(File indexDir, File dataDir) throws IOException { if (!dataDir.exists() || !dataDir.isDirectory()) { throw new IOException(dataDir + " does not exist or is not a directory"); } IndexWriter writer = new IndexWriter(indexDir, ...
java
private static HashSet<String> searchDirectoryForPattern(File dir,String A, String B) throws Exception { File[] files = dir.listFiles(); HashSet<String> pattern_set = new HashSet<String>(); for (int i = 0; i < files.length; i++) { File f = files[i]; if...
java
private static void indexDirectory(IndexWriter writer, File dir) throws IOException { File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.isDirectory()) { indexDirectory(writer, f); } else...
java
private static void indexFile(IndexWriter writer, File f) throws IOException { if (f.isHidden() || !f.exists() || !f.canRead()) { System.err.println("Could not write "+f.getName()); return; } System.err.println("Indexing " + f.getCanonicalPath()); Document doc = new Document()...
java
public static float countPhraseFrequencies(String indexDir, String A, String B) { File indexDir_f = new File(indexDir); if (!indexDir_f.exists() || !indexDir_f.isDirectory()) { System.err.println("Search failed: index directory does not exist"); } else { try { ...
java
private static float searchPhrase(File indexDir, String A, String B) throws Exception { Directory fsDir = FSDirectory.getDirectory(indexDir); IndexSearcher searcher = new IndexSearcher(fsDir); long start = new Date().getTime(); QueryParser parser = new QueryParser("contents",ne...
java
private static String combinatorialPatternMaker(String[] str, int str_size, int c) { String comb_pattern = ""; int curr_comb = 1; for (int i = 0; i < str_size; i++) { if ((c & curr_comb) != 0) { comb_pattern += str[i] + "\\s"; } else { comb...
java
private static int countWildcardPhraseFrequencies(File dir, String pattern) throws Exception { File[] files = dir.listFiles(); int total = 0; for (int i = 0; i < files.length; i++) { File f = files[i]; if (f.isDirectory()) { total += cou...
java
private static int getIndexOfPair(String value, Map<Integer, String> row_data) { for(Integer i : row_data.keySet()) { if(row_data.get(i).equals(value)) { return i.intValue(); } } return -1; }
java
public Matrix computeSVD(Matrix sparse_matrix, int dimensions) { try { File rawTermDocMatrix = File.createTempFile("lra-term-document-matrix", ".dat"); MatrixIO.writeMatrix(sparse_matrix, rawTermDocMatrix, MatrixIO.Format.SVDLIBC_SPARSE_T...
java
public void evaluateAnalogies(Matrix projection, String inputFileName, String outputFileName) { try { Scanner sc = new Scanner(new File(inputFileName)); PrintStream out = new PrintStream(new FileOutputStream(outputFileName)); while (sc.hasNext()) { ...
java
public void evaluateAnalogies(Matrix projection) { try { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String analogy = sc.next(); if (!isAnalogyFormat(analogy,true)) { System.err.println("\"" + ana...
java
private void loadOffsetsFromFormat(File file, SSpaceFormat format) throws IOException { this.format = format; spaceName = file.getName(); // NOTE: Use a LinkedHashMap here because this will ensure that the // words are returned in the same row-order as the matrix. This ...
java
private <E extends WeightedEdge> SparseDoubleVector getVertexWeightVector( WeightedGraph<E> g, int vertex) { if (keepWeightVectors) { SparseDoubleVector weightVec = vertexToWeightVector.get(vertex); if (weightVec == null) { synchronized(this) { ...
java
private void process(Iterator<String> tokens) { // NOTE: this method is intentionally private to ensure that the // IteratorFactory.tokenize() tokenization scheme is enforced on the // input data long numTokens = 0; while (tokens.hasNext()) { String token = tokens.nex...
java
public void setCurrent(String value) { current.replace(0, current.length(), value); cursor = 0; limit = current.length(); limit_backward = 0; bra = cursor; ket = limit; }
java
private TernaryVector getTermIndexVector(String term) { TernaryVector iv = termToIndexVector.get(term); if (iv == null) { // lock in case multiple threads attempt to add it at once synchronized(this) { // recheck in case another thread added it while we were waiti...
java
private void processSpace() throws IOException { LOGGER.info("generating reflective vectors"); compressedDocumentsWriter.close(); int numDocuments = documentCounter.get(); termToIndexVector.clear(); indexToTerm = new String[termToIndex.size()]; for (Map.Entry<String,Integ...
java
private void processIntDocument(IntegerVector docVector, int[] document) { // Make one pass through the document to build the document vector. for (int termIndex : document) { IntegerVector reflectiveVector = termToReflectiveSemantics.get(indexToTerm[termIndex]); ...
java
public static Iterator<MatrixEntry> getMatrixFileIterator( File matrixFile, Format fileFormat) throws IOException { switch(fileFormat) { case DENSE_TEXT: return new DenseTextFileIterator(matrixFile); case SVDLIBC_SPARSE_BINARY: return new Sv...
java
private int getDimension(PathSignature path) { Integer index = pathToIndex.get(path); if (index == null && !readOnly) { synchronized(this) { // recheck to see if the term was added while blocking index = pathToIndex.get(path); // if anoth...
java
public BufferedReader open(String fileName) throws IOException { Path filePath = new Path(fileName); if (!hadoopFs.exists(filePath)) { throw new IOException(fileName + " does not exist in HDFS"); } BufferedReader br = new BufferedReader(new InputStreamReader( ...
java
static Matrix[] svdlibc(File matrix, int dimensions, Format format) { try { String formatString = ""; // output the correct formatting flags based on the matrix type switch (format) { case SVDLIBC_DENSE_BINARY: formatString = " -r db "...
java
static Matrix[] matlabSVDS(File matrix, int dimensions) { try { // create the matlab file for executing File uOutput = File.createTempFile("matlab-svds-U",".dat"); File sOutput = File.createTempFile("matlab-svds-S",".dat"); File vOutput = File.createTempFile("matl...
java
private static Set<Language> getApplicableLanguages(PMDConfiguration configuration, RuleSets ruleSets) { Set<Language> languages = new HashSet<>(); LanguageVersionDiscoverer discoverer = configuration.getLanguageVersionDiscoverer(); for (Rule rule : ruleSets.getAllRules()) { Languag...
java
public ReviewResult parseResults() throws IOException { ReviewResult result = new ReviewResult(); ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(new FileReader(resultFile)); JsonNode issues = rootNode.path("issues"); Iterator<JsonNode> issuesIterato...
java
static Severity getSeverity(String severityName) { switch (severityName) { case "BLOCKER": case "CRITICAL": case "MAJOR": return Severity.ERROR; case "MINOR": return Severity.WARNING; case "INFO": return Severity.INFO; default: ...
java
private Map<String, Component> getComponents(JsonNode componentsNode) { Iterator<JsonNode> it = componentsNode.iterator(); Map<String, Component> components = Maps.newHashMap(); while(it.hasNext()){ JsonNode componentNode = it.next(); JsonNode pathNode = componentNode.pa...
java
private String getIssueFilePath(String issueComponent, Map<String, Component> components) { Component comp = components.get(issueComponent); String file = comp.path; if (!Strings.isNullOrEmpty(comp.moduleKey)) { String theKey = comp.moduleKey; while (!theKey.isEmpty()) { ...
java
public String reviewFile(String filePath) { log.info("Reviewing file: " + filePath); // use this format to make sure that ' ' are parsed properly String[] args = new String[] {NODE_JS, tsScript, TS_LINT_OUTPUT_KEY, TS_LINT_OUTPUT_VALUE, TS_LINT_CONFI...
java
public File run() throws IOException { Map<String, String> props = loadBaseProperties(); setAdditionalProperties(props); sonarEmbeddedScanner.addGlobalProperties(props); log.info("Sonar configuration: {}", props.toString()); sonarEmbeddedScanner.start(); sonarEmbeddedS...
java
public Collection<BitfinexWallet> getWallets() throws BitfinexClientException { throwExceptionIfUnauthenticated(); synchronized (walletTable) { return Collections.unmodifiableCollection(walletTable.values()); } }
java
public boolean removeOrderbookCallback(final BitfinexOrderBookSymbol symbol, final BiConsumer<BitfinexOrderBookSymbol, BitfinexOrderBookEntry> callback) throws BitfinexClientException { return channelCallbacks.removeCallback(symbol, callback); }
java
private boolean checkTickerFreshness() { final QuoteManager quoteManager = bitfinexApiBroker.getQuoteManager(); final Map<BitfinexStreamSymbol, Long> heartbeatValues = quoteManager.getLastTickerActivity(); return checkTickerFreshness(heartbeatValues); }
java
private void sendHeartbeatIfNeeded() { final long nextHeartbeat = lastHeartbeatSupplier.get() + HEARTBEAT; if(nextHeartbeat < System.currentTimeMillis()) { logger.debug("Send heartbeat"); bitfinexApiBroker.sendCommand(new PingCommand()); } }
java
private void executeReconnect() throws InterruptedException { // Close connection websocketEndpoint.close(); // Store the reconnect time to prevent to much // reconnects in a short timeframe. Otherwise the // rate limit will apply and the reconnects are not successfully logger.info("Wait for next reconnect...
java
public void recordNewEvent() { // Remove old events from record final double thresholdTime = System.currentTimeMillis() - (timeslotInMilliseconds * 2.0); events.removeIf(e -> e < thresholdTime); // Record new event events.add(System.currentTimeMillis()); }
java
public boolean waitForNewTimeslot() throws InterruptedException { boolean hasWaited = false; while(true) { final long numberOfEventsInTimeSlot = getNumberOfEventsInTimeslot(); if(numberOfEventsInTimeSlot > numberOfEvents) { hasWaited = true; Thread.sleep(timeslotInMilliseconds / 10); } el...
java
public long getNumberOfEventsInTimeslot() { final double thresholdTime = System.currentTimeMillis() - (timeslotInMilliseconds); return events.stream() .filter(e -> e >= thresholdTime) .count(); }
java
public static BitfinexCandlestickSymbol fromBitfinexString(final String symbol) { if(! symbol.startsWith("trade:")) { throw new IllegalArgumentException("Unable to parse: " + symbol); } final String[] splitString = symbol.split(":"); if(splitString.length != 3) { throw new IllegalArgumentException(...
java
public Closeable onConnectionStateChange(final Consumer<BitfinexConnectionStateEnum> listener) { connectionStateConsumers.offer(listener); return () -> connectionStateConsumers.remove(listener); }
java
public Closeable onSubscribeChannelEvent(final Consumer<BitfinexStreamSymbol> listener) { subscribeChannelConsumers.offer(listener); return () -> subscribeChannelConsumers.remove(listener); }
java
public Closeable onUnsubscribeChannelEvent(final Consumer<BitfinexStreamSymbol> listener) { unsubscribeChannelConsumers.offer(listener); return () -> unsubscribeChannelConsumers.remove(listener); }
java
public Closeable onMyOrderNotification(final BiConsumer<BitfinexAccountSymbol, BitfinexSubmittedOrder> listener) { newOrderConsumers.offer(listener); return () -> newOrderConsumers.remove(listener); }
java
public Closeable onMySubmittedOrderEvent(final BiConsumer<BitfinexAccountSymbol, Collection<BitfinexSubmittedOrder>> listener) { submittedOrderConsumers.offer(listener); return () -> submittedOrderConsumers.remove(listener); }
java
public Closeable onMyPositionEvent(final BiConsumer<BitfinexAccountSymbol, Collection<BitfinexPosition>> listener) { positionConsumers.offer(listener); return () -> positionConsumers.remove(listener); }
java
public Closeable onMyWalletEvent(final BiConsumer<BitfinexAccountSymbol,Collection<BitfinexWallet>> listener) { walletConsumers.offer(listener); return () -> walletConsumers.remove(listener); }
java
public Closeable onCandlesticksEvent(final BiConsumer<BitfinexCandlestickSymbol, Collection<BitfinexCandle>> listener) { candlesConsumers.offer(listener); return () -> candlesConsumers.remove(listener); }
java
public Closeable onOrderbookEvent(final BiConsumer<BitfinexOrderBookSymbol, Collection<BitfinexOrderBookEntry>> listener) { orderbookEntryConsumers.offer(listener); return () -> orderbookEntryConsumers.remove(listener); }
java
public Closeable onRawOrderbookEvent(final BiConsumer<BitfinexOrderBookSymbol, Collection<BitfinexOrderBookEntry>> listener) { rawOrderbookEntryConsumers.offer(listener); return () -> rawOrderbookEntryConsumers.remove(listener); }
java
public Closeable onTickEvent(final BiConsumer<BitfinexTickerSymbol, BitfinexTick> listener) { tickConsumers.offer(listener); return () -> tickConsumers.remove(listener); }
java
public Closeable onAuthenticationSuccessEvent(final Consumer<BitfinexAccountSymbol> listener) { authSuccessConsumers.offer(listener); return () -> authSuccessConsumers.remove(listener); }
java
public Closeable onAuthenticationFailedEvent(final Consumer<BitfinexAccountSymbol> listener) { authFailedConsumers.offer(listener); return () -> authFailedConsumers.remove(listener); }
java
public static BitfinexWebsocketClient newPooledClient(final BitfinexWebsocketConfiguration config, final int channelsPerConnection) { if (channelsPerConnection < 10 || channelsPerConnection > 250) { throw new IllegalArgumentException("channelsPerConnection must be in range (10, 250)"); ...
java
public void setOrderFlags(final int flags) { orderFlags = Arrays. stream(BitfinexOrderFlag.values()) .filter(f -> ((f.getFlag() & flags) == f.getFlag())) .collect(Collectors.toSet()); }
java
public int getCombinedFlags() { return orderFlags .stream() .map(BitfinexOrderFlag::getFlag) .reduce((f1, f2) -> f1 | f2) .orElse(0); }
java
public static BitfinexOrderBookSymbol rawOrderBook(final BitfinexCurrencyPair currencyPair) { return new BitfinexOrderBookSymbol(currencyPair, BitfinexOrderBookSymbol.Precision.R0, null, null); }
java
public static BitfinexOrderBookSymbol rawOrderBook(final String currency, final String profitCurrency) { final String currencyNonNull = Objects.requireNonNull(currency).toUpperCase(); final String profitCurrencyNonNull = Objects.requireNonNull(profitCurrency).toUpperCase(); return rawOr...
java
public static BitfinexOrderBookSymbol orderBook(final BitfinexCurrencyPair currencyPair, final BitfinexOrderBookSymbol.Precision precision, final BitfinexOrderBookSymbol.Frequency frequency, final int pricePoints) { if (precision == BitfinexOrderBookSymbol.Precision.R0) { throw ne...
java