auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public IQ handleIQ(IQ iq, CallContext ctx) throws Exception { try { String fromBareJid = StringUtils.parseBareAddress(iq.getFrom()); if (allowedJid != null && !allowedJid.equals(fromBareJid)) { return IQ.createErrorResponse( iq, new XMPPError(XMPPError.Condition.not_allowed)); } else if (allowedJid == null) { logger.warn("Requests are not secured by JID filter!"); } if (iq instanceof DialIq) { DialIq dialIq = (DialIq) iq; String from = dialIq.getSource(); String to = dialIq.getDestination(); ctx.setDestination(to); String roomName = dialIq.getHeader(ROOM_NAME_HEADER); ctx.setRoomName(roomName); String roomPassword = dialIq.getHeader(ROOM_PASSWORD_HEADER); ctx.setRoomPassword(roomPassword); if (roomName == null) throw new RuntimeException("No JvbRoomName header found"); logger.info( "Got dial request " + from + " -> " + to + " room: " + roomName); String callResource = ctx.getCallResource(); if("transcribe:".equals(to)) { transcriptionGateway.createOutgoingCall(ctx); } else { sipGateway.createOutgoingCall(ctx); } callResource = "xmpp:" + callResource; return RefIq.createResult(iq, callResource); } else if (iq instanceof HangUp) { HangUp hangUp = (HangUp) iq; String callResource = hangUp.getTo(); SipGatewaySession session = sipGateway.getSession(callResource); if (session == null) throw new RuntimeException( "No sipGateway for call: " + callResource); session.hangUp(); return IQ.createResultIQ(iq); } else { return null; } } catch (Exception e) { logger.error(e, e); throw e; } }

Target:
public IQ handleIQ(IQ iq, CallContext ctx) throws Exception { try { String fromBareJid = StringUtils.parseBareAddress(iq.getFrom()); if (allowedJid != null && !allowedJid.equals(fromBareJid)) { return IQ.createErrorResponse( iq, new XMPPError(XMPPError.Condition.not_allowed)); } else if (allowedJid == null) { logger.warn("Requests are not secured by JID filter!"); } if (iq instanceof DialIq) { DialIq dialIq = (DialIq) iq; String from = dialIq.getSource(); String to = dialIq.getDestination(); ctx.setDestination(to); String roomName = dialIq.getHeader(ROOM_NAME_HEADER); ctx.setRoomName(roomName); String roomPassword = dialIq.getHeader(ROOM_PASSWORD_HEADER); ctx.setRoomPassword(roomPassword); if (roomName == null) throw new RuntimeException("No JvbRoomName header found"); logger.info( "Got dial request " + from + " -> " + to + " room: " + roomName); String callResource = ctx.getCallResource(); if(TRANSCRIPTION_DIAL_IQ_DESTINATION.equals(to)) { transcriptionGateway.createOutgoingCall(ctx); } else { sipGateway.createOutgoingCall(ctx); } callResource = "xmpp:" + callResource; return RefIq.createResult(iq, callResource); } else if (iq instanceof HangUp) { HangUp hangUp = (HangUp) iq; String callResource = hangUp.getTo(); SipGatewaySession session = sipGateway.getSession(callResource); if (session == null) throw new RuntimeException( "No sipGateway for call: " + callResource); session.hangUp(); return IQ.createResultIQ(iq); } else { return null; } } catch (Exception e) { logger.error(e, e); throw e; } }
Source:
public void handleRequest(HttpServerExchange exchange) throws Exception { boolean componentsStarted = countdown.tryAwait(COMPONENT_STARTUP_TIMEOUT, TimeUnit.MILLISECONDS); if (componentsStarted) { wrappedHandler.handleRequest(exchange); } else { exchange.setStatusCode(StatusCodes.NOT_FOUND); exchange.endExchange(); } }

Target:
public void handleRequest(HttpServerExchange exchange) throws Exception { if (started.get()) { wrappedHandler.handleRequest(exchange); } else { Connectors.executeRootHandler(startupFailedHandler, exchange); } }
Source:
private static String extractLicenseName(ExtractedLicenseInfo extractedLicenseInfo) { return !isNullEmptyOrWhitespace(extractedLicenseInfo.getName()) ? extractedLicenseInfo.getName() : extractedLicenseInfo.getLicenseId().replaceAll("LicenseRef-", ""); }

Target:
private static String extractLicenseName(ExtractedLicenseInfo extractedLicenseInfo) { return !isNullEmptyOrWhitespace(extractedLicenseInfo.getName()) ? extractedLicenseInfo.getName() : extractedLicenseInfo.getLicenseId().replaceAll(LICENSE_REF_PREFIX, ""); }
Source:
public void fill(Control control, MouseEvent event, Point pt) { if (getChartViewer().getWindowDuration() != 0) { Chart chart = getChart(); IAxisSet axisSet = chart.getAxisSet(); IAxis xAxis = axisSet.getXAxis(0); double xCoordinate = xAxis.getDataCoordinate(pt.x); ISeries[] series = getChart().getSeriesSet().getSeries(); if ((xCoordinate < 0) || (series.length == 0)) { return; } double[] xS = series[0].getXSeries(); if (xS == null) { return; } int index = Arrays.binarySearch(xS, xCoordinate); index = index >= 0 ? index : -index - 1; int maxLen = 0; for (ISeries serie : series) { if (isValid(index, serie)) { maxLen = Math.max(maxLen, serie.getId().length()); } } TmfCommonXAxisChartViewer viewer = null; ITmfChartTimeProvider timeProvider = getChartViewer(); if(timeProvider instanceof TmfCommonXAxisChartViewer) { viewer = (TmfCommonXAxisChartViewer) timeProvider; } ITmfTimestamp time = TmfTimestamp.fromNanos((long) xCoordinate + getChartViewer().getTimeOffset()); addItem(null, Messages.TmfCommonXLineChartTooltipProvider_time, time.toString(), time.toNanos()); for (ISeries serie : series) { double[] yS = serie.getYSeries(); if (isValid(index, serie)) { String key = serie.getId(); if (viewer != null && Activator.getDefault().getPreferenceStore().getBoolean(ITmfUIPreferences.USE_BROWSER_TOOLTIPS)) { IYAppearance appearance = viewer.getSeriesAppearance(key); key = " <span style=\"color:" + appearance.getColor() + "\">" + key + "</span>"; } addItem(null, key, String.format("%12.2f", yS[index]), null); } } } }

Target:
public void fill(Control control, MouseEvent event, Point pt) { if (getChartViewer().getWindowDuration() != 0) { Chart chart = getChart(); IAxisSet axisSet = chart.getAxisSet(); IAxis xAxis = axisSet.getXAxis(0); double xCoordinate = xAxis.getDataCoordinate(pt.x); ISeries[] series = getChart().getSeriesSet().getSeries(); if ((xCoordinate < 0) || (series.length == 0)) { return; } double[] xS = series[0].getXSeries(); if (xS == null) { return; } int index = Arrays.binarySearch(xS, xCoordinate); index = index >= 0 ? index : -index - 1; int maxLen = 0; for (ISeries serie : series) { if (isValid(index, serie)) { maxLen = Math.max(maxLen, serie.getId().length()); } } TmfCommonXAxisChartViewer viewer = null; ITmfChartTimeProvider timeProvider = getChartViewer(); if (timeProvider instanceof TmfCommonXAxisChartViewer) { viewer = (TmfCommonXAxisChartViewer) timeProvider; } ITmfTimestamp time = TmfTimestamp.fromNanos((long) xCoordinate + getChartViewer().getTimeOffset()); addItem(null, Messages.TmfCommonXLineChartTooltipProvider_time, time.toString(), time.toNanos()); for (ISeries serie : series) { double[] yS = serie.getYSeries(); if (isValid(index, serie)) { String key = serie.getId(); if (key != null && viewer != null && Activator.getDefault().getPreferenceStore().getBoolean(ITmfUIPreferences.USE_BROWSER_TOOLTIPS)) { IYAppearance appearance = viewer.getSeriesAppearance(key); key = String.format(HTML_COLOR_TOOLTIP, appearance.getColor(), key); } addItem(null, key, String.format("%12.2f", yS[index]), null); } } } }
Source:
public boolean doesMatchUserAttribute(NamingEnumeration<SearchResult> answer, Map<String, String> ldap_user_attribute_map) { boolean matches = false; StringBuffer logString = new StringBuffer(); try { if (answer.hasMore()) { SearchResult s = answer.next(); logString.append(s.getName() + "---- Users current university LDAP attributes: "); Attributes attrs = s.getAttributes(); for (String attributeName : ldap_user_attribute_map.keySet()) { String expectedValue = ldap_user_attribute_map.get(attributeName); logString.append(attrs.get(attributeName) + " ----"); if (attrs.get(attributeName) != null && attrs.get(attributeName).contains(expectedValue)) { matches = true; break; } } } } catch (Exception e) { System.out.println("\nUnexpected exception when iterating over user attributes"); System.out.println(e.toString()); e.printStackTrace(); } if(!matches){ log.error("No matching LDAP attributes in active directory " + logString.toString()); } return matches; }

Target:
public boolean doesMatchUserAttribute(NamingEnumeration<SearchResult> answer, Map<String, String> ldap_user_attribute_map) { boolean matches = false; StringBuffer logString = new StringBuffer(); try { if (answer.hasMore()) { SearchResult s = answer.next(); logString.append(s.getName() + "---- Users current university LDAP attributes: "); Attributes attrs = s.getAttributes(); for (String attributeName : ldap_user_attribute_map.keySet()) { String expectedValue = ldap_user_attribute_map.get(attributeName); logString.append(attrs.get(attributeName) + " ----"); if (attrs.get(attributeName) != null && attrs.get(attributeName).contains(expectedValue)) { matches = true; break; } } } } catch (Exception e) { LOG.error("Unexpected exception when iterating over user attributes", e); } if(!matches){ LOG.error("No matching LDAP attributes in active directory " + logString.toString()); } return matches; }
Source:
private boolean upgradeNineTen(SQLiteDatabase db) { db.beginTransaction(); try { if (multipleInstalledAppRecords()) { throw new MigrationException(true); } SqlStorage<FormRecordV1> oldStorage = new SqlStorage<>( FormRecord.STORAGE_KEY, FormRecordV1.class, new ConcreteAndroidDbHelper(c, db)); String appId = getInstalledAppRecord().getApplicationId(); Vector<FormRecord> upgradedRecords = new Vector<>(); for (FormRecordV1 oldRecord : oldStorage) { FormRecord newRecord = new FormRecord( oldRecord.getInstanceURIString(), oldRecord.getStatus(), oldRecord.getFormNamespace(), oldRecord.getAesKey(), oldRecord.getInstanceID(), oldRecord.lastModified(), appId); newRecord.setID(oldRecord.getID()); upgradedRecords.add(newRecord); } db.execSQL(DatabaseAppOpenHelper.addColumnToTable( FormRecord.STORAGE_KEY, FormRecord.META_APP_ID, "TEXT")); SqlStorage<FormRecord> newStorage = new SqlStorage<>( FormRecord.STORAGE_KEY, FormRecord.class, new ConcreteAndroidDbHelper(c, db)); for (FormRecord r : upgradedRecords) { newStorage.write(r); } db.setTransactionSuccessful(); return true; } finally { db.endTransaction(); } }

Target:
private boolean upgradeNineTen(SQLiteDatabase db) { CommCareApplication._().setCustomServiceBindTimeout(60 * 5 * 1000); db.beginTransaction(); try { if (multipleInstalledAppRecords()) { deleteExistingFormRecordsAndWarnUser(c, db); addAppIdColumnToTable(db); db.setTransactionSuccessful(); return true; } SqlStorage<FormRecordV1> oldStorage = new SqlStorage<>( FormRecord.STORAGE_KEY, FormRecordV1.class, new ConcreteAndroidDbHelper(c, db)); String appId = getInstalledAppRecord().getApplicationId(); Vector<FormRecord> upgradedRecords = new Vector<>(); for (FormRecordV1 oldRecord : oldStorage) { FormRecord newRecord = new FormRecord( oldRecord.getInstanceURIString(), oldRecord.getStatus(), oldRecord.getFormNamespace(), oldRecord.getAesKey(), oldRecord.getInstanceID(), oldRecord.lastModified(), appId); newRecord.setID(oldRecord.getID()); upgradedRecords.add(newRecord); } addAppIdColumnToTable(db); SqlStorage<FormRecord> newStorage = new SqlStorage<>( FormRecord.STORAGE_KEY, FormRecord.class, new ConcreteAndroidDbHelper(c, db)); for (FormRecord r : upgradedRecords) { newStorage.write(r); } db.setTransactionSuccessful(); return true; } finally { db.endTransaction(); } }
Source:
public void testLaunchAppPackageParametersWithConfigPackage() throws Exception { ApexCli.LaunchCommandLineInfo commandLineInfo = getLaunchCommandLineInfo(new String[]{"-exactMatch", "-conf", configFile.getAbsolutePath(), appFile.getAbsolutePath(), "MyFirstApplication"}); commandLineInfo.args = new String[1]; commandLineInfo.args[0] = "MyFirstApplication"; String[] args = cli.getLaunchAppPackageArgs(ap, cp, commandLineInfo, null); commandLineInfo = getLaunchCommandLineInfo(args); StringBuilder sb = new StringBuilder(); for (String f : ap.getClassPath()) { if (sb.length() != 0) { sb.append(","); } sb.append(ap.tempDirectory()).append(File.separatorChar).append(f); } for (String f : cp.getClassPath()) { if (sb.length() != 0) { sb.append(","); } sb.append(cp.tempDirectory()).append(File.separatorChar).append(f); } Assert.assertEquals(sb.toString(), commandLineInfo.libjars); sb.setLength(0); for (String f : cp.getFiles()) { if (sb.length() != 0) { sb.append(","); } sb.append(cp.tempDirectory()).append(File.separatorChar).append(f); } Assert.assertEquals(sb.toString(), commandLineInfo.files); }

Target:
public void testLaunchAppPackageParametersWithConfigPackage() throws Exception { ApexCli.LaunchCommandLineInfo commandLineInfo = ApexCli .getLaunchCommandLineInfo(new String[]{"-exactMatch", "-conf", configFile.getAbsolutePath(), appFile.getAbsolutePath(), "MyFirstApplication"}); commandLineInfo.args = new String[] {"MyFirstApplication"}; String[] args = cli.getLaunchAppPackageArgs(ap, cp, commandLineInfo, null); commandLineInfo = ApexCli.getLaunchCommandLineInfo(args); StringBuilder sb = new StringBuilder(); for (String f : ap.getClassPath()) { if (sb.length() != 0) { sb.append(","); } sb.append(ap.tempDirectory()).append(File.separatorChar).append(f); } for (String f : cp.getClassPath()) { if (sb.length() != 0) { sb.append(","); } sb.append(cp.tempDirectory()).append(File.separatorChar).append(f); } Assert.assertEquals(sb.toString(), commandLineInfo.libjars); sb.setLength(0); for (String f : cp.getFiles()) { if (sb.length() != 0) { sb.append(","); } sb.append(cp.tempDirectory()).append(File.separatorChar).append(f); } Assert.assertEquals(sb.toString(), commandLineInfo.files); }
Source:
public static List<String> splitStatements(String expression) { StringTokenizer tokenizer = new StringTokenizer(expression, SQL_SPECIAL_CHARS + BEELINE_SPECIAL_CHARS, true); List<String> statements = new ArrayList<>(); String statement = ""; while (tokenizer.hasMoreElements()) { String token = (String) tokenizer.nextElement(); switch (token) { case ";": if (isValidStatement(statement)) { statements.add(statement.trim()); } statement = ""; break; case "-": statement += token; if (START_OF_COMMENT_PATTERN.matcher(statement).matches()) { statement += readUntilEndOfLine(tokenizer); } break; case "\"": case "'": statement += readQuoted(tokenizer, token); break; case "!": if (statement.trim().isEmpty()) { statement += token; statement += readUntilEndOfLine(tokenizer); if (isValidStatement(statement)) { statements.add(statement.trim()); } statement = ""; break; } default: statement += token; } } if (isValidStatement(statement)) { statements.add(statement); } return statements; }

Target:
public static List<String> splitStatements(String expression) { StringTokenizer tokenizer = new StringTokenizer(expression, SQL_SPECIAL_CHARS + BEELINE_SPECIAL_CHARS, true); List<String> statements = new ArrayList<>(); String statement = ""; while (tokenizer.hasMoreElements()) { String token = (String) tokenizer.nextElement(); switch (token) { case ";": if (isValidStatement(statement)) { statements.add(statement.trim()); } statement = ""; break; case "-": statement += token; if (START_OF_COMMENT_PATTERN.matcher(statement).matches()) { statement += readUntilEndOfLine(tokenizer); } break; case "\"": case "'": statement += readQuoted(tokenizer, token); break; case "!": if (statement.trim().isEmpty()) { statement += token; statement += readUntilEndOfLine(tokenizer); if (isValidStatement(statement)) { statements.add(statement.trim()); } statement = ""; break; } default: statement += token; } } if (isValidStatement(statement)) { statements.add(statement.trim()); } return statements; }
Source:
public synchronized Map<RecipientId, Long> remove(long timestamp) { Map<RecipientId, Long> receipts = cache.remove(timestamp); Log.i(TAG, this+""); Log.i(TAG, String.format(Locale.US, "Checking early receipts (%d): %d", timestamp, receipts == null ? 0 : receipts.size())); return receipts != null ? receipts : Collections.emptyMap(); }

Target:
public synchronized Map<RecipientId, Long> remove(long timestamp) { Map<RecipientId, Long> receipts = cache.remove(timestamp); return receipts != null ? Collections.unmodifiableMap(receipts) : Collections.emptyMap(); }
Source:
private void computeNextStartPosition(List<CellTsPairInfo> results, boolean scannedSingleRow) { if (results.size() < sqlRowLimit) { if (scannedSingleRow) { byte[] nextRow = RangeRequests.getNextStartRowUnlessTerminal(false, startRowInclusive); if (nextRow == null) { reachedEnd = true; } else { startRowInclusive = nextRow; startColInclusive = PtBytes.EMPTY_BYTE_ARRAY; startTsInclusive = null; cellTsPairsAlreadyExaminedInCurrentRow = 0L; } } else { reachedEnd = true; } } else { CellTsPairInfo lastResult = Iterables.getLast(results); Preconditions.checkState(lastResult.ts != Long.MAX_VALUE); startRowInclusive = lastResult.rowName; startColInclusive = lastResult.colName; startTsInclusive = lastResult.ts + 1; } }

Target:
private CellTsPairToken computeNextStartPosition(List<CellTsPairInfo> results, boolean scannedSingleRow) { if (results.size() < sqlRowLimit) { if (scannedSingleRow) { byte[] nextRow = RangeRequests.getNextStartRowUnlessTerminal(false, token.startRowInclusive()); if (nextRow == null) { return CellTsPairToken.end(); } else { cellTsPairsAlreadyExaminedInCurrentRow = 0L; return CellTsPairToken.startRow(nextRow); } } else { return CellTsPairToken.end(); } } else { CellTsPairInfo lastResult = Iterables.getLast(results); return CellTsPairToken.continueRow(lastResult); } }
Source:
private void setUser(String userKey) { new Thread(() -> { UserProfile cachedProfile = Caches.UserProfileCache.getInstance().get(userKey); if (cachedProfile == null) { try { Caches.UserProfileCache.getInstance().put( userKey, JsonUserProfileDecoder.decodeUserProfile( Json.createReader(MapillaryURL.APIv3.getUser(userKey).openStream()).readObject() ) ); } catch (IOException var4) { Logging.log(Logging.LEVEL_WARN, "Error when downloading user profile for user key '" + userKey + "'!", var4); } } this.user = Caches.UserProfileCache.getInstance().get(userKey); }, "userProfileDownload_" + userKey).start(); }

Target:
private void setUser(String userKey) { if (userKey != null) { MainApplication.worker.submit(() -> { UserProfile cachedProfile = Caches.UserProfileCache.getInstance().get(userKey); if (cachedProfile == null) { try { Caches.UserProfileCache.getInstance().put( userKey, JsonUserProfileDecoder.decodeUserProfile( Json.createReader(MapillaryURL.APIv3.getUser(userKey).openStream()).readObject() ) ); } catch (IOException var4) { Logging.log(Logging.LEVEL_WARN, "Error when downloading user profile for user key '" + userKey + "'!", var4); } } this.user = Caches.UserProfileCache.getInstance().get(userKey); }, "userProfileDownload_" + userKey); } else { this.user = null; } }
Source:
public void onAdd(SolApplication solApplication) { mapDrawer = solApplication.getGame().getMapDrawer(); mapDrawer.setToggled(true); UiVerticalListLayout verticalListLayout = new UiVerticalListLayout(); cancelButton = new UiTextButton() .setDisplayName("Cancel") .setTriggerKey(solApplication.getOptions().getKeyClose()) .setOnReleaseAction(uiElement -> { mapDrawer.setToggled(false); SolApplication.changeScreen(solApplication.getGame().getScreens().mainGameScreen); }); UiHeadlessButton alternateCancelKeyButton = new UiHeadlessButton() .setTriggerKey(solApplication.getOptions().getKeyMap()) .setOnReleaseAction(uiElement -> { cancelButton.maybeFlashPressed(solApplication.getOptions().getKeyClose()); }); zoomOutButton = new UiTextButton() .setDisplayName("Zoom out") .setOnReleaseAction(uiElement -> { mapDrawer.changeZoom(false); }) .setTriggerKey(solApplication.getOptions().getKeyZoomOut()); zoomInButton = new UiTextButton() .setDisplayName("Zoom in") .setOnReleaseAction(uiElement -> { mapDrawer.changeZoom(true); }) .setTriggerKey(solApplication.getOptions().getKeyZoomIn()); verticalListLayout.addElement(cancelButton); verticalListLayout.addElement(zoomInButton); verticalListLayout.addElement(zoomOutButton); verticalListLayout.addElement(alternateCancelKeyButton); rootUiElement = new UiRelativeLayout().addElement(verticalListLayout, UI_POSITION_RIGHT, -UiTextButton.DEFAULT_BUTTON_WIDTH / 2, 0); SolApplication.getInputManager().changeScreen(this); }

Target:
public void onAdd(SolApplication solApplication) { mapDrawer = solApplication.getGame().getMapDrawer(); mapDrawer.setToggled(true); UiVerticalListLayout verticalListLayout = new UiVerticalListLayout(); cancelButton = new UiTextButton() .setDisplayName("Cancel") .setTriggerKey(solApplication.getOptions().getKeyClose()) .setOnReleaseAction(uiElement -> { mapDrawer.setToggled(false); SolApplication.changeScreen(solApplication.getGame().getScreens().mainGameScreen); }); UiHeadlessButton alternateCancelKeyButton = new UiHeadlessButton() .setTriggerKey(solApplication.getOptions().getKeyMap()) .setOnReleaseAction(uiElement -> cancelButton.maybeFlashPressed(solApplication.getOptions().getKeyClose())); zoomOutButton = new UiTextButton() .setDisplayName("Zoom out") .setOnReleaseAction(uiElement -> mapDrawer.changeZoom(false)) .setTriggerKey(solApplication.getOptions().getKeyZoomOut()); zoomInButton = new UiTextButton() .setDisplayName("Zoom in") .setOnReleaseAction(uiElement -> mapDrawer.changeZoom(true)) .setTriggerKey(solApplication.getOptions().getKeyZoomIn()); verticalListLayout.addElement(cancelButton); verticalListLayout.addElement(zoomInButton); verticalListLayout.addElement(zoomOutButton); verticalListLayout.addElement(alternateCancelKeyButton); rootUiElement = new UiRelativeLayout().addElement(verticalListLayout, UI_POSITION_RIGHT, -UiTextButton.DEFAULT_BUTTON_WIDTH / 2, 0); SolApplication.getInputManager().changeScreen(this); }
Source:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { logger.debug("update() method is called!"); if (config != null) { String refreshIntervalString = (String) config.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } String newPort = (String) config.get("port"); if (StringUtils.isNotBlank(newPort) && !newPort.equals(port)) { port = newPort; setProperlyConfigured(true); } } }

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { logger.trace("update() method is called!"); if (config != null) { String refreshIntervalString = (String) config.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } String newPort = (String) config.get("port"); if (StringUtils.isNotBlank(newPort) && !newPort.equals(port)) { port = newPort; setProperlyConfigured(true); } } }
Source:
TabletGoalState getGoalState(TabletLocationState tls, MergeInfo mergeInfo) { KeyExtent extent = tls.extent; TabletGoalState state = getSystemGoalState(tls); if (state == TabletGoalState.HOSTED) { if (tls.current != null && serversToShutdown.contains(tls.current)) { return TabletGoalState.SUSPENDED; } if (mergeInfo.getExtent() != null) { final boolean overlaps = mergeInfo.overlaps(extent); if (overlaps && log.isDebugEnabled()) { log.debug("mergeInfo overlaps: {}", extent, overlaps); } else if (log.isTraceEnabled()) { log.trace("mergeInfo overlaps: {}", extent, overlaps); } if (overlaps) { switch (mergeInfo.getState()) { case NONE: case COMPLETE: break; case STARTED: case SPLITTING: return TabletGoalState.HOSTED; case WAITING_FOR_CHOPPED: if (tls.getState(tserverSet.getCurrentServers()).equals(TabletState.HOSTED)) { if (tls.chopped) return TabletGoalState.UNASSIGNED; } else { if (tls.chopped && tls.walogs.isEmpty()) return TabletGoalState.UNASSIGNED; } return TabletGoalState.HOSTED; case WAITING_FOR_OFFLINE: case MERGING: return TabletGoalState.UNASSIGNED; } } } state = getTableGoalState(extent); if (state == TabletGoalState.HOSTED) { TServerInstance dest = migrations.get(extent); if (dest != null && tls.current != null && !dest.equals(tls.current)) { return TabletGoalState.UNASSIGNED; } } } return state; }

Target:
TabletGoalState getGoalState(TabletLocationState tls, MergeInfo mergeInfo) { KeyExtent extent = tls.extent; TabletGoalState state = getSystemGoalState(tls); if (state == TabletGoalState.HOSTED) { if (tls.current != null && serversToShutdown.contains(tls.current)) { return TabletGoalState.SUSPENDED; } if (mergeInfo.getExtent() != null) { final boolean overlaps = mergeInfo.overlaps(extent); if (overlaps) { log.debug("mergeInfo overlaps: true", extent); switch (mergeInfo.getState()) { case NONE: case COMPLETE: break; case STARTED: case SPLITTING: return TabletGoalState.HOSTED; case WAITING_FOR_CHOPPED: if (tls.getState(tserverSet.getCurrentServers()).equals(TabletState.HOSTED)) { if (tls.chopped) return TabletGoalState.UNASSIGNED; } else { if (tls.chopped && tls.walogs.isEmpty()) return TabletGoalState.UNASSIGNED; } return TabletGoalState.HOSTED; case WAITING_FOR_OFFLINE: case MERGING: return TabletGoalState.UNASSIGNED; } } else { log.trace("mergeInfo overlaps: false", extent); } } state = getTableGoalState(extent); if (state == TabletGoalState.HOSTED) { TServerInstance dest = migrations.get(extent); if (dest != null && tls.current != null && !dest.equals(tls.current)) { return TabletGoalState.UNASSIGNED; } } } return state; }
Source:
private void updateTimezoneForCourse(CourseAttributes course) { List<FeedbackSessionAttributes> sessions = logic.getFeedbackSessionsForCourse(course.getId()); String timeZone = sessions.isEmpty() ? Const.DEFAULT_TIMEZONE : getTimeZoneId(sessions.get(0).getTimeZone()); if (isPreview) { System.out.println("Course " + course.getId() + " to be set to " + timeZone + "."); return; } try { course.setTimeZone(timeZone); logic.updateCourse(course); System.out.println("Course + " + course.getId() + " timezone successfully set to " + timeZone + "."); } catch (InvalidParametersException | EntityDoesNotExistException e) { System.out.println("Failed to set timezone for course + " + course.getId() + "."); e.printStackTrace(); } }

Target:
private void updateTimezoneForCourse(CourseAttributes course) { List<FeedbackSessionAttributes> sessions = logic.getFeedbackSessionsForCourse(course.getId()); String timeZone = sessions.isEmpty() ? Const.DEFAULT_TIMEZONE : getTimeZoneId(sessions.get(0).getTimeZone()); if (isPreview) { System.out.println("Course " + course.getId() + " timezone to be set to " + timeZone + "."); return; } try { course.setTimeZone(timeZone); logic.updateCourse(course); System.out.println("Course " + course.getId() + " timezone successfully set to " + timeZone + "."); } catch (InvalidParametersException | EntityDoesNotExistException e) { System.out.println("Failed to set timezone for course " + course.getId() + "."); e.printStackTrace(); } }
Source:
public BayesNetHmmModelDAODynamoDB(final AmazonDynamoDB dynamoDBClient, final String tableName){ this.dynamoDBClient = dynamoDBClient; this.tableName = tableName; mapper.registerModule(new GuavaModule()); mapper.registerModule(new GuavaExtrasModule()); mapper.registerModule(new JodaModule()); }

Target:
public BayesNetHmmModelDAODynamoDB(final AmazonDynamoDB dynamoDBClient, final String tableName){ this.dynamoDBClient = dynamoDBClient; this.tableName = tableName; }
Source:
private void checkVdsSwapThreshold(VdsStatistics stat) { final double THRESHOLD = 0.98; Integer minAvailableThreshold = Config.getValue(ConfigValues.LogPhysicalMemoryThresholdInMB); Integer maxUsedPercentageThreshold = Config.getValue(ConfigValues.LogMaxPhysicalMemoryUsedThresholdInPercentage); if (stat.getswap_total() == null || stat.getswap_free() == null || stat.getswap_total() == 0) { return; } Long swapUsedPercent = (stat.getswap_total() - stat.getswap_free()) / stat.getswap_total(); Long allowedMinAvailableThreshold = Math.round(minAvailableThreshold.doubleValue() * THRESHOLD); AuditLogType valueToLog = stat.getswap_free() < allowedMinAvailableThreshold ? AuditLogType.VDS_LOW_SWAP : AuditLogType.VDS_HIGH_SWAP_USE; if (stat.getswap_free() < allowedMinAvailableThreshold || swapUsedPercent > maxUsedPercentageThreshold) { AuditLogableBase logable = new AuditLogableBase(stat.getId()); logable.addCustomValue("HostName", _vds.getName()); logable.addCustomValue("UsedSwap", swapUsedPercent.toString()); logable.addCustomValue("AvailableSwapMemory", stat.getswap_free().toString()); logable.addCustomValue("Threshold", stat.getswap_free() < allowedMinAvailableThreshold ? allowedMinAvailableThreshold.toString() : maxUsedPercentageThreshold.toString()); auditLog(logable, valueToLog); } }

Target:
private void checkVdsSwapThreshold(VdsStatistics stat) { final double THRESHOLD = 0.98; Integer minAvailableThreshold = Config.getValue(ConfigValues.LogPhysicalMemoryThresholdInMB); Integer maxUsedPercentageThreshold = Config.getValue(ConfigValues.LogMaxPhysicalMemoryUsedThresholdInPercentage); if (stat.getswap_total() == null || stat.getswap_free() == null || stat.getswap_total() == 0) { return; } Long swapUsedPercent = (stat.getswap_total() - stat.getswap_free()) / stat.getswap_total(); Long allowedMinAvailableThreshold = Math.round(minAvailableThreshold.doubleValue() * THRESHOLD); AuditLogType valueToLog = stat.getswap_free() < allowedMinAvailableThreshold ? AuditLogType.VDS_LOW_SWAP : AuditLogType.VDS_HIGH_SWAP_USE; if (stat.getswap_free() < allowedMinAvailableThreshold || swapUsedPercent > maxUsedPercentageThreshold) { AuditLogableBase logable = new AuditLogableBase(stat.getId()); logable.addCustomValue("HostName", _vds.getName()); logable.addCustomValue("UsedSwap", swapUsedPercent.toString()); logable.addCustomValue("AvailableSwapMemory", stat.getswap_free().toString()); logable.addCustomValue("Threshold", stat.getswap_free() < allowedMinAvailableThreshold ? minAvailableThreshold.toString() : maxUsedPercentageThreshold.toString()); auditLog(logable, valueToLog); } }
Source:
protected void processTuple(Object tuple) { GenericRecord record = null; try { record = getGenericRecord(tuple); } catch (Exception e) { LOG.error("Exception in parsing record"); errorCnt++; } if (record != null) { output.emit(record); recordCnt++; } else { errorCnt++; } }

Target:
protected void processTuple(Object tuple) { GenericRecord record = null; try { record = getGenericRecord(tuple); } catch (Exception e) { LOG.error("Exception in parsing record"); errorCount++; } if (record != null) { output.emit(record); recordCount++; } else if (errorPort.isConnected()) { errorPort.emit(tuple); errorCount++; } }
Source:
static Object standardize(String column, @Nullable Object value, boolean isSingleValue) { if (value == null) { return null; } if (value instanceof Collection) { return standardizeCollection(column, (Collection) value, isSingleValue); } if (value instanceof Map) { return standardizeCollection(column, ((Map) value).values(), isSingleValue); } if (value instanceof Object[]) { Object[] values = (Object[]) value; int numValues = values.length; if (numValues == 0) { return null; } if (numValues == 1) { return standardize(column, values[0], isSingleValue); } List<Object> standardizedValues = new ArrayList<>(numValues); for (Object singleValue : values) { Object standardizedValue = standardize(column, singleValue, true); if (standardizedValue != null) { standardizedValues.add(standardizedValue); } } int numStandardizedValues = standardizedValues.size(); if (numStandardizedValues == 0) { return null; } if (numStandardizedValues == 1 || isSingleValue) { return standardizedValues.get(0); } return standardizedValues.toArray(); } return value; }

Target:
static Object standardize(String column, @Nullable Object value, boolean isSingleValue) { if (value == null) { return null; } if (value instanceof Collection) { return standardizeCollection(column, (Collection) value, isSingleValue); } if (value instanceof Map) { return standardizeCollection(column, ((Map) value).values(), isSingleValue); } if (value instanceof Object[]) { Object[] values = (Object[]) value; int numValues = values.length; if (numValues == 0) { return null; } if (numValues == 1) { return standardize(column, values[0], isSingleValue); } List<Object> standardizedValues = new ArrayList<>(numValues); for (Object singleValue : values) { Object standardizedValue = standardize(column, singleValue, true); if (standardizedValue != null) { standardizedValues.add(standardizedValue); } } int numStandardizedValues = standardizedValues.size(); if (numStandardizedValues == 0) { return null; } if (numStandardizedValues == 1) { return standardizedValues.get(0); } Preconditions.checkState(!isSingleValue, "Cannot read single-value from Object[]: %s for column: %s", Arrays.toString(values), column); return standardizedValues.toArray(); } return value; }
Source:
public String doSomething(String message) { message = prefix + ": " + message; Level level = Level.INFO; if ("DEBUG".equals(outputMode)) { log.debug(message); level = Level.DEBUG; } else if ("INFO".equals(outputMode)) { log.info(message); level = Level.INFO; } else if ("WARN".equals(outputMode)) { log.warn(message); level = Level.WARN; } else if ("ERROR".equals(outputMode)) { log.error(message); level = Level.ERROR; } raiseEvent(message, level); return "LogServiceCalled with: " + message; }

Target:
public String doSomething(String message) { message = prefix + ": " + message; Level level = Level.INFO; if ("DEBUG".equals(outputMode)) { LOGGER.debug(message); level = Level.DEBUG; } else if ("INFO".equals(outputMode)) { LOGGER.info(message); level = Level.INFO; } else if ("WARN".equals(outputMode)) { LOGGER.warn(message); level = Level.WARN; } else if ("ERROR".equals(outputMode)) { LOGGER.error(message); level = Level.ERROR; } raiseEvent(message, level); return "LogServiceCalled with: " + message; }
Source:
protected TupleBatch fetchNextReady() throws DbException { if (child.eos()) { return resultBuffer.popAny(); } if (tb == null) { tb = child.nextReady(); row = 0; } while (tb != null) { while (row < tb.numTuples()) { if (curGroupKey == null) { curGroupKey = new Tuple(groupSchema); for (int gKey = 0; gKey < gFields.length; ++gKey) { TupleUtils.copyValue(tb, gFields[gKey], row, curGroupKey, gKey); } } else if (!TupleUtils.tupleEquals(tb, gFields, row, curGroupKey, gRange, 0)) { addToResult(); for (int gKey = 0; gKey < gFields.length; ++gKey) { TupleUtils.copyValue(tb, gFields[gKey], row, curGroupKey, gKey); } aggregatorStates = AggUtils.allocateAggStates(aggregators); if (resultBuffer.hasFilledTB()) { return resultBuffer.popFilled(); } } for (int agg = 0; agg < aggregators.length; ++agg) { aggregators[agg].addRow(tb, row, aggregatorStates[agg]); } row++; } tb = child.nextReady(); row = 0; } if (child.eos()) { addToResult(); return resultBuffer.popAny(); } return null; }

Target:
protected TupleBatch fetchNextReady() throws DbException { if (child.eos()) { return null; } if (tb == null) { tb = child.nextReady(); row = 0; } while (tb != null) { while (row < tb.numTuples()) { if (curGroupKey == null) { curGroupKey = new Tuple(groupSchema); for (int gKey = 0; gKey < gFields.length; ++gKey) { TupleUtils.copyValue(tb, gFields[gKey], row, curGroupKey, gKey); } } else if (!TupleUtils.tupleEquals(tb, gFields, row, curGroupKey, gRange, 0)) { addToResult(); for (int gKey = 0; gKey < gFields.length; ++gKey) { TupleUtils.copyValue(tb, gFields[gKey], row, curGroupKey, gKey); } aggregatorStates = AggUtils.allocateAggStates(aggregators); if (resultBuffer.hasFilledTB()) { return resultBuffer.popFilled(); } } for (int agg = 0; agg < aggregators.length; ++agg) { aggregators[agg].addRow(tb, row, aggregatorStates[agg]); } row++; } tb = child.nextReady(); row = 0; } if (child.eos()) { addToResult(); return resultBuffer.popAny(); } return null; }
Source:
public Entity getWikibaseItemById(final String id) throws IOException, WikibaseException { if (null == id || 0 == id.trim().length()) return null; StringBuilder actualId = new StringBuilder(id.trim()); if ('q' != Character.toLowerCase(actualId.charAt(0))) { if (Pattern.matches("\\d+", actualId)) { actualId.insert(0, 'Q'); } else { throw new WikibaseException(id + " is not a valid Wikibase id"); } } final StringBuilder url = new StringBuilder(query); url.append("action=wbgetentities"); url.append("&ids=").append(actualId); url.append("&format=xml"); final String text = fetch(url.toString(), "getWikibaseItem"); System.out.println(text); return WikibaseEntityFactory.getWikibaseItem(text); }

Target:
public Entity getWikibaseItemById(final String id) throws IOException, WikibaseException { if (null == id || 0 == id.trim().length()) return null; StringBuilder actualId = new StringBuilder(id.trim()); if ('q' != Character.toLowerCase(actualId.charAt(0))) { if (Pattern.matches("\\d+", actualId)) { actualId.insert(0, 'Q'); } else { throw new WikibaseException(id + " is not a valid Wikibase id"); } } final StringBuilder url = new StringBuilder(query); url.append("action=wbgetentities"); url.append("&ids=").append(actualId); url.append("&format=xml"); final String text = fetch(url.toString(), "getWikibaseItem"); return WikibaseEntityFactory.getWikibaseItem(text); }
Source:
public List<SMREntry> previous() { ILogData data = streamView.previous(); while (Address.isAddress(streamView.getCurrentGlobalPosition()) && data != null) { if (data.getType() == DataType.DATA && data.getPayload(runtime) instanceof ISMRConsumable) { return ((ISMRConsumable) data.getPayload(runtime)) .getSMRUpdates(streamView.getId()); } data = streamView.previous(); } return new ArrayList<>(); }

Target:
public List<SMREntry> previous() { ILogData data = streamView.previous(); while (Address.isAddress(streamView.getCurrentGlobalPosition()) && data != null) { if (data.getType() == DataType.DATA && data.getPayload(runtime) instanceof ISMRConsumable) { return ((ISMRConsumable) data.getPayload(runtime)) .getSMRUpdates(streamView.getId()); } data = streamView.previous(); } return Collections.emptyList(); }
Source:
public void shouldNotContinueWithConfigSaveIfRequestIsNotFresh() { when(goConfigService.isUserAdmin(currentUser)).thenReturn(true); when(goConfigService.isGroupAdministrator(currentUser.getUsername())).thenReturn(false); SCM updatedScm = new SCM("id", new PluginConfiguration("plugin-id", "1"), new Configuration(new ConfigurationProperty(new ConfigurationKey("key1"),new ConfigurationValue("value1")))); updatedScm.setName("material"); when(entityHashingService.md5ForEntity(cruiseConfig.getSCMs().find("id"), "material")).thenReturn("another-md5"); UpdateSCMConfigCommand command = new UpdateSCMConfigCommand(updatedScm, pluggableScmService, goConfigService, currentUser, result, "md5", entityHashingService); assertThat(command.canContinue(cruiseConfig), is(false)); }

Target:
public void shouldNotContinueWithConfigSaveIfRequestIsNotFresh() { when(goConfigService.isUserAdmin(currentUser)).thenReturn(true); when(goConfigService.isGroupAdministrator(currentUser.getUsername())).thenReturn(false); SCM updatedScm = new SCM("id", new PluginConfiguration("plugin-id", "1"), new Configuration(new ConfigurationProperty(new ConfigurationKey("key1"),new ConfigurationValue("value1")))); updatedScm.setName("material"); when(entityHashingService.md5ForEntity(cruiseConfig.getSCMs().find("id"), "material")).thenReturn("another-md5"); UpdateSCMConfigCommand command = new UpdateSCMConfigCommand(updatedScm, pluggableScmService, goConfigService, currentUser, result, "md5", entityHashingService); assertThat(command.canContinue(cruiseConfig), is(false)); assertThat(result.toString(), containsString("STALE_RESOURCE_CONFIG")); assertThat(result.toString(), containsString(updatedScm.getName())); }
Source:
public File run() throws IOException { Properties props = loadBaseProperties(); setAdditionalProperties(props); log.debug("Sonar configuration: {}", props.toString()); sonarEnbeddedRunner.addProperties(props); sonarEnbeddedRunner.execute(); return new File(OUTPUT_DIR, OUTPUT_FILE); }

Target:
public File run() throws IOException { Properties props = loadBaseProperties(); setAdditionalProperties(props); log.info("Sonar configuration: {}", props.toString()); sonarEnbeddedRunner.addProperties(props); sonarEnbeddedRunner.execute(); return new File(OUTPUT_DIR, OUTPUT_FILE); }
Source:
public void registerAttributes(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadWriteAttribute(MAP_GROUPS_TO_ROLES, null, new ReloadRequiredWriteAttributeHandler(MAP_GROUPS_TO_ROLES){ @Override protected boolean requiresRuntime(OperationContext context) { return context.getRunningMode() == RunningMode.NORMAL && !context.isBooting(); } }); }

Target:
public void registerAttributes(ManagementResourceRegistration resourceRegistration) { resourceRegistration.registerReadWriteAttribute(MAP_GROUPS_TO_ROLES, null, new ReloadRequiredWriteAttributeHandler(MAP_GROUPS_TO_ROLES){ @Override protected boolean requiresRuntime(OperationContext context) { return context.getRunningMode() == RunningMode.ADMIN_ONLY && !context.isBooting(); } }); }
Source:
public void whenOverridingCookie_thenItIsUpdated() { driver.navigate().to(navUrl); Cookie lpCookie = driver.manage().getCookieNamed("lp_120073"); driver.manage().deleteCookie(lpCookie); lpCookie = new Cookie("lp_120073", "foo"); driver.manage().addCookie(lpCookie); assertThat(lpCookie.getValue(), equalTo("foo")); }

Target:
public void whenOverridingCookie_thenItIsUpdated() { driver.navigate().to(navUrl); Cookie lpCookie = driver.manage().getCookieNamed("lp_120073"); driver.manage().deleteCookie(lpCookie); Cookie newLpCookie = new Cookie("lp_120073", "foo"); driver.manage().addCookie(newLpCookie); Cookie overriddenCookie = driver.manage().getCookieNamed("lp_120073"); assertThat(overriddenCookie.getValue(), equalTo("foo")); }
Source:
public Optional<? extends Blob> findByPath(String tenantId, String path) { if (Strings.isEmpty(path)) { return Optional.empty(); } String cacheKey = tenantId + "-" + ensureRelativePath(path); return Optional.ofNullable(blobByPathCache.get(cacheKey, ignored -> fetchByPath(tenantId, path))); }

Target:
public Optional<? extends Blob> findByPath(String tenantId, String path) { if (Strings.isEmpty(path)) { return Optional.empty(); } return Optional.ofNullable(blobByPathCache.get(determinePathCacheKey(tenantId, path), ignored -> fetchByPath(tenantId, path))); }
Source:
public void deleteAsync() { ListenableFuture<Void> future = executor.submit(new Callable<Void>() { @Override public Void call() throws IOException { try { deleteNow(); return null; } catch (Throwable t) { if (executor.isShutdown()) { LOG.debug("Error deleting "+file+" (but executor shutdown)", t); return null; } else { LOG.error("Error deleting "+file, t); throw Exceptions.propagate(t); } } }}); addPostExecListener(future); }

Target:
private void deleteAsync() { ListenableFuture<Void> future = executor.submit(new Callable<Void>() { @Override public Void call() throws IOException { try { deleteNow(); return null; } catch (Throwable t) { if (executor.isShutdown()) { LOG.debug("Error deleting "+file+" (but executor shutdown)", t); return null; } else { LOG.error("Error deleting "+file, t); throw Exceptions.propagate(t); } } }}); addPostExecListener(future); }
Source:
private Constraint serviceConflict(ConstraintFactory factory) { return factory.fromUniquePair(MrProcessAssignment.class, equal(MrProcessAssignment::getMachine), equal(MrProcessAssignment::getService) ).penalize(MrConstraints.SERVICE_CONFLICT, HardSoftLongScore.ofHard(1L)); }

Target:
private Constraint serviceConflict(ConstraintFactory factory) { return factory.fromUniquePair(MrProcessAssignment.class, equal(MrProcessAssignment::getMachine), equal(MrProcessAssignment::getService) ).penalize(MrConstraints.SERVICE_CONFLICT, HardSoftLongScore.ONE_HARD); }
Source:
public void findLowestCommonAncestor() { assertNull(PathUtils.findLowestCommonAncestor(null)); assertNull(PathUtils.findLowestCommonAncestor(Collections.EMPTY_LIST)); ArrayList<AlluxioURI> paths = new ArrayList<>(); paths.add(new AlluxioURI("/")); assertTrue("/".equals(PathUtils.findLowestCommonAncestor(paths).getPath())); paths.clear(); paths.add(new AlluxioURI("/a")); assertTrue("/a".equals(PathUtils.findLowestCommonAncestor(paths).getPath())); paths.add(new AlluxioURI("/a/b")); assertTrue("/a".equals(PathUtils.findLowestCommonAncestor(paths).getPath())); paths.clear(); paths.add(new AlluxioURI("/a/c")); paths.add(new AlluxioURI("/a/d/")); assertTrue("/a".equals(PathUtils.findLowestCommonAncestor(paths).getPath())); paths.add(new AlluxioURI("/b/a/")); assertTrue("/".equals(PathUtils.findLowestCommonAncestor(paths).getPath())); paths.clear(); paths.add(new AlluxioURI("/a/b/c")); paths.add(new AlluxioURI("/a/b/d")); paths.add(new AlluxioURI("/a/b/e")); assertTrue("/a/b".equals(PathUtils.findLowestCommonAncestor(paths).getPath())); paths.clear(); String prefix = "/a/b/c"; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { for (int k = 0; k < 10; k++) { paths.add(new AlluxioURI(String.format("%s/%d/%d/%d", prefix, i, j, k))); } } } assertTrue(prefix.equals(PathUtils.findLowestCommonAncestor(paths).getPath())); }

Target:
public void findLowestCommonAncestor() { assertNull(PathUtils.findLowestCommonAncestor(null)); assertNull(PathUtils.findLowestCommonAncestor(Collections.EMPTY_LIST)); ArrayList<AlluxioURI> paths = new ArrayList<>(); paths.add(new AlluxioURI("/")); assertEquals("/", PathUtils.findLowestCommonAncestor(paths).getPath()); paths.clear(); paths.add(new AlluxioURI("/a")); assertEquals("/a", PathUtils.findLowestCommonAncestor(paths).getPath()); paths.add(new AlluxioURI("/a/b")); assertEquals("/a", PathUtils.findLowestCommonAncestor(paths).getPath()); paths.clear(); paths.add(new AlluxioURI("/a/c")); paths.add(new AlluxioURI("/a/d/")); assertEquals("/a", PathUtils.findLowestCommonAncestor(paths).getPath()); paths.add(new AlluxioURI("/b/a/")); assertEquals("/", PathUtils.findLowestCommonAncestor(paths).getPath()); paths.clear(); paths.add(new AlluxioURI("/a/b/c")); paths.add(new AlluxioURI("/a/b/d")); paths.add(new AlluxioURI("/a/b/e")); assertEquals("/a/b", PathUtils.findLowestCommonAncestor(paths).getPath()); paths.clear(); String prefix = "/a/b/c"; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { for (int k = 0; k < 10; k++) { paths.add(new AlluxioURI(String.format("%s/%d/%d/%d", prefix, i, j, k))); } } } assertEquals(prefix, PathUtils.findLowestCommonAncestor(paths).getPath()); }
Source:
public void start() { synchronized (_lock) { if (_state != State.NOT_YET_STARTED) { throw new IllegalStateException(_poolName + " is " + _state); } _state = State.RUNNING; long timeOut = Math.min(_idleTimeout, _waitTimeout); if (timeOut > 0) { long freq = Math.min(timeOut / 10, 1000); _objectTimeoutFuture = _timeoutExecutor.scheduleAtFixedRate(new Runnable() { @Override public void run() { timeoutWaiters(); timeoutObjects(); } }, freq, freq, TimeUnit.MILLISECONDS); } } for(int i = 0; i < _minSize; i++) { if(shouldCreate()) { create(); } } }

Target:
public void start() { synchronized (_lock) { if (_state != State.NOT_YET_STARTED) { throw new IllegalStateException(_poolName + " is " + _state); } _state = State.RUNNING; if (_idleTimeout > 0) { long freq = Math.min(_idleTimeout / 10, 1000); _objectTimeoutFuture = _timeoutExecutor.scheduleAtFixedRate(new Runnable() { @Override public void run() { timeoutObjects(); } }, freq, freq, TimeUnit.MILLISECONDS); } } for(int i = 0; i < _minSize; i++) { if(shouldCreate()) { create(); } } }