auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean onSingleTapConfirmed(MotionEvent event) { final BindableRecyclerView recyclerView = getRecyclerView(); if (recyclerView == null) { return false; } View childView = getChildAt(event); if (childView == null) { return false; } final int position = recyclerView.getChildAdapterPosition(childView); View childAt = getChildOfAt(childView, (int) event.getX(), (int) event.getY()); if (childAt != null && ViewCompat.hasOnClickListeners(childAt)) { childAt.playSoundEffect(SoundEffectConstants.CLICK); return true; } if (position == RecyclerView.NO_POSITION) { return true; } if (recyclerView.getItemsSource() == null) { return true; } childView.playSoundEffect(SoundEffectConstants.CLICK); final Object object = recyclerView.getItemsSource().get(position); if (mRecyclerViewClickListener.canExecute(childView, object)) { mRecyclerViewClickListener.execute(childView, object); return true; } if (mRecyclerViewClickListener.canExecute(object)) { mRecyclerViewClickListener.execute(object); return true; } return false; }

Target:
public boolean onSingleTapConfirmed(MotionEvent event) { final BindableRecyclerView recyclerView = getRecyclerView(); if (recyclerView == null) { return false; } View childView = getChildAt(event); if (childView == null) { return false; } final int position = recyclerView.getChildAdapterPosition(childView); View childAt = getChildOfAt(childView, (int) event.getX(), (int) event.getY()); if (childAt != null && ViewCompat.hasOnClickListeners(childAt)) { return true; } if (position == RecyclerView.NO_POSITION) { return true; } if (recyclerView.getItemsSource() == null) { return true; } final Object object = recyclerView.getItemsSource().get(position); if (mRecyclerViewClickListener.canExecute(childView, object)) { mRecyclerViewClickListener.execute(childView, object); return true; } if (mRecyclerViewClickListener.canExecute(object)) { mRecyclerViewClickListener.execute(object); return true; } return false; }
Source:
protected void executeQueryCommand() { Map<String, Object> response = findDirectoryUserById(); if (!response.containsKey("result")) { getQueryReturnValue().setSucceeded(false); } else { Collection<DirectoryUser> users = DirectoryUtils.mapPrincipalRecordsToDirectoryUsers( getParameters().getDomain(), (List<ExtMap>) response.get("result")); if (!users.isEmpty()) { getQueryReturnValue().setReturnValue(new ArrayList<>(users).get(0)); } } }

Target:
protected void executeQueryCommand() { Map<String, Object> response = findDirectoryUserById(); if (!response.containsKey("result")) { getQueryReturnValue().setSucceeded(false); } else { Collection<DirectoryUser> users = DirectoryUtils.mapPrincipalRecordsToDirectoryUsers( getParameters().getDomain(), (List<ExtMap>) response.get("result")); if (!users.isEmpty()) { getQueryReturnValue().setReturnValue(users.iterator().next()); } } }
Source:
public GetSearchResultsResponse getSearchResults(JsonRpcPeer peer, JSONObject params) { final GetSearchResultsRequest request = mObjectMapper.convertValue( params, GetSearchResultsRequest.class); final List<Integer> results = mSearchResults.get(request.searchId).subList(request.fromIndex, request.toIndex); final GetSearchResultsResponse response = new GetSearchResultsResponse(); response.nodeIds = results; return response; }

Target:
public GetSearchResultsResponse getSearchResults(JsonRpcPeer peer, JSONObject params) { final GetSearchResultsRequest request = mObjectMapper.convertValue( params, GetSearchResultsRequest.class); final List<Integer> results = mSearchResults.get(request.searchId); if (results == null) { LogUtil.w("\"" + request.searchId + "\" is not a valid reference to a search result"); return null; } final List<Integer> resultsRange = results.subList(request.fromIndex, request.toIndex); final GetSearchResultsResponse response = new GetSearchResultsResponse(); response.nodeIds = resultsRange; return response; }
Source:
public static Collection<NumberArrayFactory> data() throws IOException { fixture = prepareDirectoryAndPageCache( IntArrayTest.class ); PageCache pageCache = fixture.pageCache; File dir = fixture.directory; NumberArrayFactory autoWithPageCacheFallback = autoWithPageCacheFallback( pageCache, dir ); NumberArrayFactory pageCacheArrayFactory = new PageCachedNumberArrayFactory( pageCache, dir ); return Arrays.asList( HEAP, OFF_HEAP, autoWithPageCacheFallback, pageCacheArrayFactory ); }

Target:
public static Collection<NumberArrayFactory> data() throws IOException { fixture = prepareDirectoryAndPageCache( IntArrayTest.class ); PageCache pageCache = fixture.pageCache; File dir = fixture.directory; NumberArrayFactory autoWithPageCacheFallback = auto( pageCache, dir ); NumberArrayFactory pageCacheArrayFactory = new PageCachedNumberArrayFactory( pageCache, dir ); return Arrays.asList( HEAP, OFF_HEAP, autoWithPageCacheFallback, pageCacheArrayFactory ); }
Source:
protected synchronized void updateBytes(long bytes) { if (parentMemoryContext != null) { parentMemoryContext.updateBytes(bytes); } long oldLocalUsedBytes = this.usedBytes; usedBytes += bytes; if (notificationListener != null) { notificationListener.memoryUsageUpdated(oldLocalUsedBytes, usedBytes); } }

Target:
synchronized ListenableFuture<?> updateBytes(long bytes) { ListenableFuture<?> future = NOT_BLOCKED; if (parentMemoryContext != null) { future = parentMemoryContext.updateBytes(bytes); usedBytes += bytes; return future; } if (reservationHandler != null) { future = reservationHandler.reserveMemory(bytes); } usedBytes += bytes; if (guaranteedMemory.isPresent() && usedBytes < guaranteedMemory.getAsLong()) { future = NOT_BLOCKED; } return future; }
Source:
private static boolean createLockFile(byte[] lockValue, FileObject lockObject, String fullPath) throws FileSystemException { lockObject.createFile(); OutputStream stream = lockObject.getContent().getOutputStream(); try { stream.write(lockValue); stream.flush(); stream.close(); } catch (IOException e) { lockObject.delete(); log.error("Couldn't create the lock file before processing the file " + maskURLPassword(fullPath), e); return false; } finally { lockObject.close(); } return true; }

Target:
private static boolean createLockFile(byte[] lockValue, FileObject lockObject, String fullPath) throws FileSystemException { lockObject.createFile(); OutputStream stream = lockObject.getContent().getOutputStream(); try { stream.write(lockValue); stream.flush(); } catch (IOException e) { lockObject.delete(); log.error("Couldn't create the lock file before processing the file " + maskURLPassword(fullPath), e); return false; } finally { try { stream.close(); } catch (IOException e) { log.debug("Error closing stream", e); } lockObject.close(); } return true; }
Source:
private DashboardSetupStatus initDashboard(final String hostAddress, final int port) { final boolean isValidHostAddr = !hostAddress.equals(AsyncDolphinLauncher.INVALID_HOST_ADDRESS); if (!isValidHostAddr) { LOG.log(Level.INFO, "Dashboard is not in use"); return DashboardSetupStatus.getFailedStatus(); } else { final String dashboardURL = "http://" + hostAddress + ":" + port + "/"; try { final PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor()); connectionManager.setMaxTotal(Integer.MAX_VALUE); final CloseableHttpAsyncClient reusableHttpClient = HttpAsyncClients.custom().setConnectionManager(connectionManager).build(); reusableHttpClient.start(); runMetricsSenderThread(); return DashboardSetupStatus.getSucceededSatus(dashboardURL, reusableHttpClient); } catch (IOReactorException e) { LOG.log(Level.WARNING, "Dashboard: Fail on initializing IOReactor.", e); return DashboardSetupStatus.getFailedStatus(); } } }

Target:
private DashboardSetupStatus initDashboard(final String hostAddress, final int port) { final boolean invalidHostAddr = hostAddress.equals(AsyncDolphinLauncher.INVALID_HOST_ADDRESS); if (invalidHostAddr) { LOG.log(Level.INFO, "Dashboard is not in use"); return DashboardSetupStatus.getFailed(); } else { final String dashboardURL = "http://" + hostAddress + ":" + port + "/"; try { final PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor()); connectionManager.setMaxTotal(Integer.MAX_VALUE); final CloseableHttpAsyncClient reusableHttpClient = HttpAsyncClients.custom().setConnectionManager(connectionManager).build(); reusableHttpClient.start(); runMetricsSenderThread(); return DashboardSetupStatus.getSuccessful(dashboardURL, reusableHttpClient); } catch (IOReactorException e) { LOG.log(Level.WARNING, "Dashboard: Fail on initializing IOReactor.", e); return DashboardSetupStatus.getFailed(); } } }
Source:
static String isProcedureValidForScope(TaskScope scope, Procedure procedure, boolean restrictProcedureByScope) { if (scope != TaskScope.PARTITIONS && procedure.getSinglepartition() && procedure.getPartitionparameter() == -1) { return String.format( "Procedure %s is a directed procedure and must be run on PARTITIONS. Cannot be scheduled on %s.", procedure.getTypeName(), scope.name().toLowerCase()); } if (!restrictProcedureByScope) { return null; } switch (scope) { case DATABASE: if (procedure.getSinglepartition()) { return String.format( "Procedrue %s is a single partition procedure. Cannot be scheduled on the database", procedure.getTypeName()); } break; case HOSTS: if (procedure.getTransactional()) { return String.format("Procedure %s is a transactional procedure. Cannot be scheduled on a host.", procedure.getTypeName()); } break; case PARTITIONS: if (!procedure.getSinglepartition()) { return String.format("Procedure %s is not a partitioned procedure. Cannot be scheduled on a partition.", procedure.getTypeName()); } if (procedure.getPartitionparameter() != -1) { return String.format( "Procedure %s must be a directed procedure which is not partitioned on a table. " + "Cannot be scheduled on a partition.", procedure.getTypeName()); } break; default: throw new IllegalArgumentException("Unknown scope: " + scope); } return null; }

Target:
static String isProcedureValidForScope(TaskScope scope, Procedure procedure, boolean restrictProcedureByScope) { if (scope != TaskScope.PARTITIONS && procedure.getSinglepartition() && procedure.getPartitionparameter() == -1) { return String.format("Procedure %s is a directed procedure and must be run on PARTITIONS only.", procedure.getTypeName()); } if (!restrictProcedureByScope) { return null; } switch (scope) { case DATABASE: if (procedure.getSinglepartition()) { return String.format( "Procedure %s is a single partition procedure, which cannot be scheduled on the database", procedure.getTypeName()); } break; case HOSTS: if (procedure.getTransactional()) { return String.format("Procedure %s is a transactional procedure, which cannot be scheduled on a host.", procedure.getTypeName()); } break; case PARTITIONS: if (!procedure.getSinglepartition() && procedure.getPartitionparameter() != -1) { return String.format( "Procedure %s must be a directed procedure, which cannot be scheduled on a partition.", procedure.getTypeName()); } break; default: throw new IllegalArgumentException("Unknown scope: " + scope); } return null; }
Source:
public MemoryConfigurationBuilder storageType(StorageType storageType) { StorageType config = storageType == StorageType.OBJECT ? StorageType.HEAP : storageType; if (config == StorageType.BINARY) { encoding().mediaType(MediaType.APPLICATION_PROTOSTREAM_TYPE); } attributes.attribute(MemoryConfiguration.STORAGE).set(config); memoryStorageConfigurationBuilder.storageType(config); return this; }

Target:
public MemoryConfigurationBuilder storageType(StorageType storageType) { memoryStorageConfigurationBuilder.storageType(storageType); return this; }
Source:
public void setTransform(Transform transform) { if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); if (transform != null && transform.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); if (data.cairo == 0 && transform == null) return; initCairo(); long cairo = data.cairo; double[] identity = identity(); identity[4] += ctm_dx; identity[5] += ctm_dy; if (transform != null) { Cairo.cairo_matrix_multiply(identity, transform.handle, identity); } Cairo.cairo_set_matrix(cairo, identity); data.state &= ~DRAW_OFFSET; }

Target:
public void setTransform(Transform transform) { if (handle == 0) SWT.error(SWT.ERROR_GRAPHIC_DISPOSED); if (transform != null && transform.isDisposed()) SWT.error(SWT.ERROR_INVALID_ARGUMENT); if (data.cairo == 0 && transform == null) return; initCairo(); long cairo = data.cairo; if (GTK.GTK_VERSION >= OS.VERSION (3, 14, 0)) { if (hasTransform) { Cairo.cairo_restore(cairo); hasTransform = false; } if (transform != null) { double[] identity = identity(); Cairo.cairo_matrix_multiply(identity, transform.handle, identity); Cairo.cairo_save(cairo); hasTransform = true; Cairo.cairo_transform(cairo, identity); } } else { double[] identity = identity(); if (transform != null) { Cairo.cairo_matrix_multiply(identity, transform.handle, identity); } Cairo.cairo_set_matrix(cairo, identity); } data.state &= ~DRAW_OFFSET; }
Source:
private void handleExceptionalPaths(Symbol symbol) { TryStatement pop = enclosingTry.pop(); TryStatement tryStatement; if(!enclosedByCatch.peek()) { tryStatement = pop; } else { tryStatement = enclosingTry.peek(); } enclosingTry.push(pop); if(pop != outerTry) { currentBlock = createBlock(currentBlock); currentBlock.exceptions.add(exitBlocks.peek()); } if (symbol.isMethodSymbol()) { List<Type> thrownTypes = ((Symbol.MethodSymbol) symbol).thrownTypes(); if (!thrownTypes.isEmpty()) { thrownTypes.forEach(thrownType -> { for (Type caughtType : tryStatement.catches.keySet()) { if (thrownType.isSubtypeOf(caughtType) || caughtType.isSubtypeOf(thrownType)) { currentBlock.exceptions.add(tryStatement.catches.get(caughtType)); break; } } }); } } currentBlock.exceptions.addAll(tryStatement.runtimeCatches); }

Target:
private void handleExceptionalPaths(Symbol symbol) { TryStatement pop = enclosingTry.pop(); TryStatement tryStatement; if (enclosedByCatch.peek()) { tryStatement = enclosingTry.peek(); } else { tryStatement = pop; } enclosingTry.push(pop); if(pop != outerTry) { currentBlock = createBlock(currentBlock); currentBlock.exceptions.add(exitBlocks.peek()); } if (symbol.isMethodSymbol()) { List<Type> thrownTypes = ((Symbol.MethodSymbol) symbol).thrownTypes(); thrownTypes.forEach(thrownType -> { for (Type caughtType : tryStatement.catches.keySet()) { if (thrownType.isSubtypeOf(caughtType) || caughtType.isSubtypeOf(thrownType)) { currentBlock.exceptions.add(tryStatement.catches.get(caughtType)); break; } } }); } currentBlock.exceptions.addAll(tryStatement.runtimeCatches); }
Source:
public ByteBuffer subscriptionUserData(final Set<String> topics) { final Set<TaskId> activeTasks; final Set<TaskId> standbyTasks = taskManager.cachedTasksIds(); if (rebalanceProtocol == RebalanceProtocol.EAGER) { activeTasks = taskManager.previousRunningTaskIds(); standbyTasks.removeAll(activeTasks); } else if (rebalanceProtocol == RebalanceProtocol.COOPERATIVE) { activeTasks = Collections.emptySet(); standbyTasks.removeAll(taskManager.activeTaskIds()); } else { throw new IllegalStateException("Streams partition assignor has no known rebalance protocol"); } final SubscriptionInfo data = new SubscriptionInfo( usedSubscriptionMetadataVersion, taskManager.processId(), activeTasks, standbyTasks, userEndPoint); taskManager.updateSubscriptionsFromMetadata(topics); taskManager.setRebalanceInProgress(true); return data.encode(); }

Target:
public ByteBuffer subscriptionUserData(final Set<String> topics) { final Set<TaskId> standbyTasks = taskManager.cachedTasksIds(); final Set<TaskId> activeTasks = prepareForSubscription(taskManager, topics, standbyTasks, rebalanceProtocol); return new SubscriptionInfo( usedSubscriptionMetadataVersion, taskManager.processId(), activeTasks, standbyTasks, userEndPoint) .encode(); }
Source:
public PutMessageFormatInputStream(StoreKey key, ByteBuffer blobEncryptionKey, BlobProperties blobProperties, ByteBuffer userMetadata, InputStream blobStream, long streamSize) throws MessageFormatException { this(key, blobEncryptionKey, blobProperties, userMetadata, blobStream, streamSize, BlobType.DataBlob); }

Target:
public PutMessageFormatInputStream(StoreKey key, ByteBuffer blobEncryptionKey, BlobProperties blobProperties, ByteBuffer userMetadata, InputStream blobStream, long streamSize) throws MessageFormatException { this(key, blobEncryptionKey, blobProperties, userMetadata, blobStream, streamSize, BlobType.DataBlob, (short) 0); }
Source:
private static boolean equalIncludingGenerics(ClassNode orig, ClassNode copy) { if (orig==copy) return true; if (orig.isGenericsPlaceHolder()!=copy.isGenericsPlaceHolder()) return false; if (!orig.equals(copy)) return false; GenericsType[] gt1 = orig.getGenericsTypes(); GenericsType[] gt2 = copy.getGenericsTypes(); if (gt1==gt2) return true; if (gt1 == null || gt2 == null) return false; if (gt1.length!=gt2.length) return false; for (int i=0; i<gt1.length; i++) { if (!equalIncludingGenerics(gt1[i],gt2[i])) return false; } return true; }

Target:
private static boolean equalIncludingGenerics(ClassNode orig, ClassNode copy) { if (orig==copy) return true; if (orig.isGenericsPlaceHolder()!=copy.isGenericsPlaceHolder()) return false; if (!orig.equals(copy)) return false; GenericsType[] gt1 = orig.getGenericsTypes(); GenericsType[] gt2 = copy.getGenericsTypes(); if ((gt1==null) ^ (gt2==null)) return false; if (gt1==gt2) return true; if (gt1.length!=gt2.length) return false; for (int i=0; i<gt1.length; i++) { if (!equalIncludingGenerics(gt1[i],gt2[i])) return false; } return true; }
Source:
Duration getPollDuration() { return Duration.ofSeconds(1); }

Target:
Duration getPollDuration() { return DEFAULT_POLL_DURATION; }
Source:
protected Parser getSyntaxParser(Syntax syntax) throws MacroExecutionException { try { return this.componentManager.getInstance(Parser.class, syntax.toIdString()); } catch (ComponentLookupException e) { throw new MacroExecutionException(String.format("Cannot find Parser for syntax [%s]", syntax.toIdString()), e); } }

Target:
protected Parser getSyntaxParser(Syntax syntax) throws MacroExecutionException { try { return this.componentManager.getInstance(Parser.class, syntax.toIdString()); } catch (ComponentLookupException e) { throw new MacroExecutionException(String.format("Cannot find Parser for syntax [%s]" + , syntax.toIdString()), e); } }
Source:
public void onCreate() { super.onCreate(); SwrveConfig config = new SwrveConfig(); try { config.useEuStack(); config.setStack(SwrveConfigBase.SwrveStack.US); config.setAppIdPrefix(2132); config.setUseHttpsForEventsUrl(true); config.setEventsUrl(new URL("<LINK_1>")); config.setContentUrl(new URL("<LINK_0>")); config.setUseHttpsForEventsUrl(false); config.setStack(SwrveConfigBase.SwrveStack.US); } catch (MalformedURLException e) { e.printStackTrace(); } try { SwrveSDK.createInstance(this, 2132, "AYgy6V2uk6f3d46ShfJ", config); } catch (IllegalArgumentException exp) { Log.e(LOG_TAG, "Could not initialize the Swrve SDK", exp); } }

Target:
public void onCreate() { super.onCreate(); try { SwrveSDK.createInstance(this, YOUR_APP_ID, YOUR_API_KEY); } catch (IllegalArgumentException exp) { Log.e(LOG_TAG, "Could not initialize the Swrve SDK", exp); } }
Source:
public boolean offer( E e, long timeout, TimeUnit unit ) throws InterruptedException { checkNotNull(e); long nanos = unit.toNanos(timeout); boolean added = false; putLock.lockInterruptibly(); try { while (currentSize.get() >= capacity) { if (nanos <= 0) { return false; } nanos = notFull.awaitNanos(nanos); } delegate.add(e); elementAdded(e); added = true; } finally { putLock.unlock(); } if (added) { signalNotEmpty(); } return added; }

Target:
public boolean offer( E e, long timeout, TimeUnit unit ) throws InterruptedException { checkNotNull(e); checkSize(e); long nanos = unit.toNanos(timeout); boolean added = false; putLock.lockInterruptibly(); try { while (currentSize.get() + getBytesSize(e) > capacity) { if (nanos <= 0) { return false; } nanos = notFull.awaitNanos(nanos); } delegate.add(e); elementAdded(e); added = true; } finally { putLock.unlock(); } if (added) { signalNotEmpty(); } return added; }
Source:
private static void getColumnNames(DatabaseMetaData meta, Set<String> names) throws SQLException { try { ResultSet columns = meta.getColumns(meta.getConnection().getCatalog(), null, "%", "%"); try { while (columns.next()) { String name = columns.getString("TABLE_NAME"); if (!isBlank(name)) { names.add(name); names.add(columns.getString("COLUMN_NAME")); } } } finally { columns.close(); } logger.debug(Joiner.on(',').join(names)); } catch (Throwable t) { logger.error("Failed to retrieve the column name", t); } }

Target:
private static void getColumnNames(DatabaseMetaData meta, Set<String> names) throws SQLException { try { ResultSet columns = meta.getColumns(meta.getConnection().getCatalog(), null, "%", "%"); try { while (columns.next()) { String name = columns.getString("TABLE_NAME"); if (!isBlank(name)) { names.add(name); names.add(columns.getString("COLUMN_NAME")); } } } finally { columns.close(); } logger.debug(Joiner.on(',').join(names)); } catch (Exception e) { logger.error("Failed to retrieve the column name", e); } }
Source:
void close() { try { LOG.info("Starting to close KafkaProducer."); producer.close(); LOG.info("Successfully closed KafkaProducer."); } catch (Exception e) { LOG.error("An error occurred while closing KafkaProducer!", e); } }

Target:
private void close() { try { LOG.debug("Starting to close KafkaProducer."); producer.close(); LOG.debug("Successfully closed KafkaProducer."); } catch (RuntimeException e) { LOG.error("An error occurred while closing KafkaProducer.", e); } }
Source:
protected void onActiveFilterAdded(ActiveFilterItem activeFilterItem) { if (activeFilterItem.getKey().equals(constants.State()) && activeFilterItem.getValue() instanceof List) { final List<String> values = (List<String>) activeFilterItem.getValue(); values.forEach(v -> view.checkSelectFilter(constants.State(), String.valueOf(v))); } if (activeFilterItem.getKey().equals(COLUMN_ERROR_COUNT) && activeFilterItem.getValue() instanceof List) { final List<String> values = (List<String>) activeFilterItem.getValue(); values.forEach(v -> view.checkSelectFilter(constants.Errors(), (String.valueOf(v).equals("0") || String.valueOf(v) == "0") ? "true" : "false")); } }

Target:
protected void onActiveFilterAdded(ActiveFilterItem activeFilterItem) { if (activeFilterItem.getKey().equals(constants.State()) && activeFilterItem.getValue() instanceof List) { final List<String> values = (List<String>) activeFilterItem.getValue(); values.forEach(v -> view.checkSelectFilter(constants.State(), v)); } if (activeFilterItem.getKey().equals(COLUMN_ERROR_COUNT) && activeFilterItem.getValue() instanceof List) { final List<String> values = (List<String>) activeFilterItem.getValue(); values.forEach(v -> view.checkSelectFilter(constants.Errors(), v)); } }
Source:
public Optional<IOException> handle(Response response) { if (response.isSuccessful() || response.code() == 101) { return Optional.empty(); } try { String body = response.body() != null && response.body().byteStream() != null ? toString(response.body().byteStream()) : "<empty>"; return Optional.of(new IOException(String.format("Error %s. " + "(Failed to parse response body as SerializableError.) Body:%n%s", response.code(), body))); } catch (IOException e) { return Optional.of(new IOException("Failed to read response body", e)); } }

Target:
public Optional<IOException> handle(Response response) { if (response.isSuccessful() || response.code() == MoreHttpCodes.SWITCHING_PROTOCOLS) { return Optional.empty(); } try { String body = response.body() != null && response.body().byteStream() != null ? toString(response.body().byteStream()) : "<empty>"; return Optional.of(new IOException(String.format("Error %s. " + "(Failed to parse response body as SerializableError.) Body:%n%s", response.code(), body))); } catch (IOException e) { return Optional.of(new IOException("Failed to read response body", e)); } }
Source:
public Blueprint() { this(null, null, null); }

Target:
private Blueprint() { this(null, null, null); }
Source:
public void addMtuEditor() { FlowPanel panel = mtuSelectorEditor.asRadioGroup().getPanel(MtuSelector.customMtu); if (panel != null) { panel.add(mtuEditor); } }

Target:
public void addMtuEditor() { FlowPanel panel = mtuSelectorEditor.asRadioGroup().getPanel(MtuSelector.customMtu); panel.add(mtuEditor); }
Source:
public static Set<RuntimePath> parseRuntimeFile(InputStream is, boolean includeMissing) { final Set<RuntimePath> runtimePaths = new HashSet<RuntimePath>(); try { Properties servers = new Properties(); servers.load(is); Enumeration<Object> elements = servers.elements(); while (elements.hasMoreElements()) { String str = (String) elements.nextElement(); StringTokenizer lineTokenizer = new StringTokenizer(str,LINE_DELIMITER); while (lineTokenizer.hasMoreTokens()) { String lineToken = lineTokenizer.nextToken(); StringTokenizer tokenizer = new StringTokenizer( lineToken, IN_LINE_DELIMITER); if (tokenizer.countTokens() == 2) { String location = tokenizer.nextToken(); boolean scan = Boolean.parseBoolean(tokenizer.nextToken()); File locationFile = new File(location); if (locationFile.isDirectory() || (includeMissing && !locationFile.exists())) { RuntimePath tempLocation = new RuntimePath(location); tempLocation.setScanOnEveryStartup(scan); runtimePaths.add(tempLocation); } else { RuntimeCoreActivator.pluginLog().logWarning("Runtime location \"" + location + "\" does not exist or not a directory"); } } } } } catch (IOException e) { RuntimeCoreActivator.pluginLog().logError(e); } return runtimePaths; }

Target:
public static Set<RuntimePath> parseRuntimeFile(InputStream is, boolean includeMissing) { final Set<RuntimePath> runtimePaths = new HashSet<RuntimePath>(); try { Properties servers = new Properties(); servers.load(is); Enumeration<Object> elements = servers.elements(); while (elements.hasMoreElements()) { String str = (String) elements.nextElement(); StringTokenizer lineTokenizer = new StringTokenizer(str,LINE_DELIMITER); while (lineTokenizer.hasMoreTokens()) { String lineToken = lineTokenizer.nextToken(); StringTokenizer tokenizer = new StringTokenizer( lineToken, IN_LINE_DELIMITER); if (tokenizer.countTokens() == 2) { String location = tokenizer.nextToken(); boolean scan = Boolean.parseBoolean(tokenizer.nextToken()); File locationFile = new File(location); if (locationFile.isDirectory() || (includeMissing && !locationFile.exists())) { RuntimePath tempLocation = new RuntimePath(location); tempLocation.setScanOnEveryStartup(scan); runtimePaths.add(tempLocation); } else { RuntimeCoreActivator.pluginLog().logWarning("Runtime location \"" + location + "\" does not exist or is not a directory"); } } } } } catch (IOException e) { RuntimeCoreActivator.pluginLog().logError(e); } return runtimePaths; }
Source:
private void updateRepoRemoveList(Menu remove) { remove.getItems().clear(); Set<String> currentlyUsedRepos = ui.getCurrentlyUsedRepos(); Set<String> removableRepos = ui.logic.getStoredRepos(); removableRepos.removeAll(currentlyUsedRepos); for (String repoId : removableRepos) { MenuItem removeItem = new MenuItem(repoId); removeItem.setOnAction(e1 -> onRepoRemove(repoId)); remove.getItems().add(removeItem); } for (String usedRepoId : currentlyUsedRepos) { MenuItem disabledRemoveItem = new MenuItem(usedRepoId + " (in use; non-removable)"); disabledRemoveItem.setDisable(true); remove.getItems().add(disabledRemoveItem); } }

Target:
private void updateRepoRemoveList(Menu remove) { remove.getItems().clear(); Set<String> currentlyUsedRepos = ui.getCurrentlyUsedRepos(); Set<String> removableRepos = ui.logic.getStoredRepos(); removableRepos.removeAll(currentlyUsedRepos); for (String repoId : removableRepos) { MenuItem removeItem = new MenuItem(repoId); removeItem.setOnAction(e1 -> onRepoRemove(repoId)); remove.getItems().add(removeItem); } remove.getItems().add(new SeparatorMenuItem()); MenuItem nonRemovableMsg = new MenuItem("[Non-Removable - In Use]"); nonRemovableMsg.setDisable(true); remove.getItems().add(nonRemovableMsg); for (String usedRepoId : currentlyUsedRepos) { MenuItem disabledRemoveItem = new MenuItem(usedRepoId); disabledRemoveItem.setDisable(true); remove.getItems().add(disabledRemoveItem); } }
Source:
public void afterTestSuite(ProjectRunner testScenarioRunner, ProjectRunContext runContext, TestSuiteRunner testRunner) { if (testScenarioRunner != projectRunner) { return; } finishCount.incrementAndGet(); Platform.runLater(new Runnable() { @Override public void run() { progressBar.setValue(finishCount.get()); System.out.println("setting coutn to " + String.valueOf(finishCount.get())); } }); if (project.getRunType() == TestSuiteRunType.SEQUENTIAL) { testRunner.getTestSuite().removeTestSuiteRunListener(runLogListener); } }

Target:
public void afterTestSuite(ProjectRunner testScenarioRunner, ProjectRunContext runContext, TestSuiteRunner testRunner) { if (testScenarioRunner != projectRunner) { return; } finishCount.incrementAndGet(); Platform.runLater(new Runnable() { @Override public void run() { progressBar.setValue(finishCount.get()); } }); if (project.getRunType() == TestSuiteRunType.SEQUENTIAL) { testRunner.getTestSuite().removeTestSuiteRunListener(runLogListener); } }
Source:
public LogReplicationRuntimeState processEvent(LogReplicationRuntimeEvent event) throws IllegalTransitionException { switch (event.getType()) { case ON_CONNECTION_DOWN: String endpointDown = event.getEndpoint(); fsm.updateDisconnectedEndpoints(endpointDown); if (fsm.getRemoteLeader().isPresent() && fsm.getRemoteLeader().get().equals(endpointDown)) { log.warn("Connection to remote leader endpoint={} is down. Attempt to reconnect.", endpointDown); fsm.resetRemoteLeaderEndpoint(); return fsm.getConnectedEndpoints().size() == 0 ? fsm.getStates().get(LogReplicationRuntimeStateType.WAITING_FOR_CONNECTIVITY) : fsm.getStates().get(LogReplicationRuntimeStateType.VERIFYING_REMOTE_LEADER); } log.debug("Connection lost to non-leader node {}", endpointDown); return null; case REMOTE_LEADER_LOSS: if (fsm.getRemoteLeader().isPresent() && fsm.getRemoteLeader().get().equals(event.getEndpoint())) { fsm.resetRemoteLeaderEndpoint(); return fsm.getStates().get(LogReplicationRuntimeStateType.VERIFYING_REMOTE_LEADER); } return null; case ON_CONNECTION_UP: fsm.updateConnectedEndpoints(event.getEndpoint()); return null; case NEGOTIATION_COMPLETE: return fsm.getStates().get(LogReplicationRuntimeStateType.REPLICATING); case LOCAL_LEADER_LOSS: return fsm.getStates().get(LogReplicationRuntimeStateType.STOPPED); default: { log.warn("Unexpected communication event when in init state.", event.getType()); throw new IllegalTransitionException(event.getType(), getType()); } } }

Target:
public LogReplicationRuntimeState processEvent(LogReplicationRuntimeEvent event) throws IllegalTransitionException { switch (event.getType()) { case ON_CONNECTION_DOWN: String endpointDown = event.getEndpoint(); fsm.updateDisconnectedEndpoints(endpointDown); if (fsm.getRemoteLeader().isPresent() && fsm.getRemoteLeader().get().equals(endpointDown)) { log.warn("Connection to remote leader endpoint={} is down. Attempt to reconnect.", endpointDown); fsm.resetRemoteLeaderEndpoint(); return fsm.getConnectedEndpoints().isEmpty() ? fsm.getStates().get(LogReplicationRuntimeStateType.WAITING_FOR_CONNECTIVITY) : fsm.getStates().get(LogReplicationRuntimeStateType.VERIFYING_REMOTE_LEADER); } log.debug("Connection lost to non-leader node {}", endpointDown); return null; case REMOTE_LEADER_LOSS: if (fsm.getRemoteLeader().isPresent() && fsm.getRemoteLeader().get().equals(event.getEndpoint())) { fsm.resetRemoteLeaderEndpoint(); return fsm.getConnectedEndpoints().isEmpty() ? fsm.getStates().get(LogReplicationRuntimeStateType.WAITING_FOR_CONNECTIVITY) : fsm.getStates().get(LogReplicationRuntimeStateType.VERIFYING_REMOTE_LEADER); } return null; case ON_CONNECTION_UP: fsm.updateConnectedEndpoints(event.getEndpoint()); return null; case NEGOTIATION_COMPLETE: return fsm.getStates().get(LogReplicationRuntimeStateType.REPLICATING); case LOCAL_LEADER_LOSS: return fsm.getStates().get(LogReplicationRuntimeStateType.STOPPED); default: { log.warn("Unexpected communication event when in init state.", event.getType()); throw new IllegalTransitionException(event.getType(), getType()); } } }
Source:
public void run() { if (log.isDebugEnabled()) { log.debug("Starting a new BAPI worker thread to process the incoming request"); } ByteArrayInputStream bais = new ByteArrayInputStream(this.xmlContent.getBytes()); MessageContext msgContext = null; try { msgContext = endpoint.createMessageContext(); msgContext.setIncomingTransportName(SAPConstants.SAP_BAPI_PROTOCOL_NAME); if (log.isDebugEnabled()) { log.debug("Creating SOAP envelope from the BAPI function call"); } SOAPEnvelope envelope = TransportUtils.createSOAPMessage(msgContext, bais, SAPConstants.SAP_CONTENT_TYPE); msgContext.setEnvelope(envelope); AxisEngine.receive(msgContext); } catch (Exception e) { log.error("Error while processing the BAPI call through the Axis engine", e); } finally { try { bais.close(); } catch (IOException e) { log.error("Error while closing the stream", e); } } }

Target:
public void run() { if (log.isDebugEnabled()) { log.debug("Starting a new BAPI worker thread to process the incoming request"); } try (ByteArrayInputStream bais = new ByteArrayInputStream(this.xmlContent.getBytes())){ MessageContext msgContext = endpoint.createMessageContext(); msgContext.setIncomingTransportName(SAPConstants.SAP_BAPI_PROTOCOL_NAME); if (log.isDebugEnabled()) { log.debug("Creating SOAP envelope from the BAPI function call"); } SOAPEnvelope envelope = TransportUtils.createSOAPMessage(msgContext, bais, SAPConstants.SAP_CONTENT_TYPE); msgContext.setEnvelope(envelope); AxisEngine.receive(msgContext); } catch (Exception e) { log.error("Error while processing the BAPI call through the Axis engine", e); } }
Source:
public void objectWithPropDep() { ObjectSchema actual = (ObjectSchema) SchemaLoader.load(get("objectWithPropDep")); assertEquals(1, actual.getPropertyDependencies().get("isIndividual").size()); actual = (ObjectSchema) loadAsV201909(get("objectWithPropDep_V201909")); assertEquals(1, actual.getPropertyDependencies().get("isIndividual").size()); }

Target:
public void objectWithPropDep() { ObjectSchema actual = (ObjectSchema) SchemaLoader.load(get("objectWithPropDep")); assertEquals(1, actual.getPropertyDependencies().get("isIndividual").size()); }
Source:
public Locale getLoggingLocale() { return LOGGING_LOCALE.get(); }

Target:
public static Locale getLoggingLocale() { return LOGGING_LOCALE.get(); }
Source:
void generatePipelinedRegions() { final Set<Set<SchedulingExecutionVertex>> rawRegions = PipelinedRegionComputeUtil.computePipelinedRegions(this); for (Set<SchedulingExecutionVertex> rawRegion : rawRegions) { final Set<TestingSchedulingExecutionVertex> vertices = rawRegion.stream() .map(vertex -> schedulingExecutionVertices.get(vertex.getId())) .collect(Collectors.toSet()); final TestingSchedulingPipelinedRegion region = new TestingSchedulingPipelinedRegion(vertices); for (TestingSchedulingExecutionVertex vertex : vertices) { vertexRegions.put(vertex.getId(), region); } } }

Target:
private void generatePipelinedRegions() { vertexRegions = new HashMap<>(); final Set<Set<SchedulingExecutionVertex>> rawRegions = PipelinedRegionComputeUtil.computePipelinedRegions(this); for (Set<SchedulingExecutionVertex> rawRegion : rawRegions) { final Set<TestingSchedulingExecutionVertex> vertices = rawRegion.stream() .map(vertex -> schedulingExecutionVertices.get(vertex.getId())) .collect(Collectors.toSet()); final TestingSchedulingPipelinedRegion region = new TestingSchedulingPipelinedRegion(vertices); for (TestingSchedulingExecutionVertex vertex : vertices) { vertexRegions.put(vertex.getId(), region); } } }
Source:
public static ExtensionsManager getInstance() { if (instance == null) { synchronized (EngineExtensionsManager.class) { if (instance == null) { instance = new ExtensionsManager( EngineLocalConfig.getInstance().getProperties()); instance.getGlobalContext().put(Base.GlobalContextKeys.APPLICATION_NAME, Base.ApplicationNames.OVIRT_ENGINE); List<String> extensionNames = new ArrayList<>(); for (File directory : EngineLocalConfig.getInstance().getExtensionsDirectories()) { if (!directory.exists()) { log.warn(String.format("The directory '%1$s' cotaning configuration files does not exist.", directory.getAbsolutePath())); } else { File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { extensionNames.add(instance.load(file)); } } } } } for (String extensionName : extensionNames) { if (EngineLocalConfig.getInstance().getBoolean(ENGINE_EXTENSION_ENABLED + extensionName, true)) { instance.activate(extensionName); } } } } } return instance; }

Target:
public static ExtensionsManager getInstance() { if (instance == null) { synchronized (EngineExtensionsManager.class) { if (instance == null) { instance = new ExtensionsManager(); instance.getGlobalContext().put(Base.GlobalContextKeys.APPLICATION_NAME, Base.ApplicationNames.OVIRT_ENGINE); for (File directory : EngineLocalConfig.getInstance().getExtensionsDirectories()) { if (!directory.exists()) { log.warn(String.format("The directory '%1$s' cotaning configuration files does not exist.", directory.getAbsolutePath())); } else { File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { instance.load(file); } } } } } for (ExtensionProxy extension : instance.getExtensions()) { if (EngineLocalConfig.getInstance().getBoolean(ENGINE_EXTENSION_ENABLED + extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME), true)) { instance.activate(extension.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME)); } } } } } return instance; }
Source:
protected void executeVmCommand() { if (getVm().isAutoStartup() && shouldAddLease(getVm().getStaticData())) { if (FeatureSupported.isVmLeasesSupported(getEffectiveCompatibilityVersion())) { if (validateLeaseStorageDomain(getVm().getLeaseStorageDomainId())) { if (!addVmLease(getVm().getLeaseStorageDomainId(), getVm().getId())) { getVm().setLeaseStorageDomainId(null); } } else { getVm().setLeaseStorageDomainId(null); auditLogDirector.log(this, AuditLogType.CANNOT_IMPORT_VM_WITH_LEASE_STORAGE_DOMAIN); } } else { getVm().setLeaseStorageDomainId(null); auditLogDirector.log(this, AuditLogType.CANNOT_IMPORT_VM_WITH_LEASE_COMPAT_VERSION); } } else { getVm().setLeaseStorageDomainId(null); } super.executeVmCommand(); if(getReturnValue().getVdsmTaskIdList().isEmpty()){ auditLogDirector.log(this, AuditLogType.IMPORTEXPORT_STARTING_IMPORT_VM); } }

Target:
protected void executeVmCommand() { if (getVm().isAutoStartup() && shouldAddLease(getVm().getStaticData())) { if (FeatureSupported.isVmLeasesSupported(getEffectiveCompatibilityVersion())) { if (validateLeaseStorageDomain(getVm().getLeaseStorageDomainId())) { if (!addVmLease(getVm().getLeaseStorageDomainId(), getVm().getId())) { getVm().setLeaseStorageDomainId(null); } } else { getVm().setLeaseStorageDomainId(null); auditLogDirector.log(this, AuditLogType.CANNOT_IMPORT_VM_WITH_LEASE_STORAGE_DOMAIN); } } else { getVm().setLeaseStorageDomainId(null); auditLogDirector.log(this, AuditLogType.CANNOT_IMPORT_VM_WITH_LEASE_COMPAT_VERSION); } } else { getVm().setLeaseStorageDomainId(null); } super.executeVmCommand(); }
Source:
public boolean tryLock() { Lock localLock = RedisLockRegistry.this.localRegistry.obtain(lockKey); try { if (!localLock.tryLock()) { return false; } boolean obtainedLock = this.obtainLock(); if (!obtainedLock) { localLock.unlock(); if (this.reLock <= 0) { removeThreadLocal(); } } return obtainedLock; } catch (Exception e) { localLock.unlock(); throw new RuntimeException(e); } }

Target:
public boolean tryLock() { Lock localLock = RedisLockRegistry.this.localRegistry.obtain(lockKey); try { if (!localLock.tryLock()) { return false; } boolean obtainedLock = this.obtainLock(); if (!obtainedLock) { localLock.unlock(); } return obtainedLock; } catch (Exception e) { localLock.unlock(); throw new RuntimeException(e); } }
Source:
public void preBegin() { for (EntityRef entityRef : entityManager.getEntitiesWith(ModuleConfigComponent.class)) { ModuleConfigComponent moduleConfig = entityRef.getComponent(ModuleConfigComponent.class); String moduleName = moduleConfig.moduleName; Map<String, String> properties; if (propertiesPerModule.containsKey(moduleName)) { logger.error("Encountered more than one Module Config for module - "+moduleName+", this is not recommended, " + "as the property values visible are not going to be well defined."); properties = propertiesPerModule.get(moduleName); } else { properties = new HashMap<>(); propertiesPerModule.put(moduleName, properties); } properties.putAll(moduleConfig.properties); } }

Target:
public void preBegin() { for (Prefab prefab : prefabManager.listPrefabs(ModuleConfigComponent.class)) { ModuleConfigComponent moduleConfig = prefab.getComponent(ModuleConfigComponent.class); String moduleName = moduleConfig.moduleName; Map<String, String> properties; if (propertiesPerModule.containsKey(moduleName)) { logger.error("Encountered more than one Module Config for module - "+moduleName+", this is not recommended, " + "as the property values visible are not going to be well defined."); properties = propertiesPerModule.get(moduleName); } else { properties = new HashMap<>(); propertiesPerModule.put(moduleName, properties); } properties.putAll(moduleConfig.properties); } }
Source:
public void testCreateSmbFileObjectWithBackSlash1() throws IOException { System.setProperty("file.separator", "\\"); SmbShare smbShare = new SmbShare("smb://myshare/shared/"); SmbSession smbSession = new SmbSession(smbShare); SmbFile smbFile = smbSession.createSmbFileObject("smb://myshare\\blubba\\"); assertEquals("smb://myshare/shared/smb://myshare/blubba/", smbFile.getCanonicalPath()); }

Target:
public void testCreateSmbFileObjectWithBackSlash1() throws IOException { System.setProperty("file.separator", "\\"); SmbConfig config = new SmbConfig(); config.setHost("myshare"); config.setPort(445); config.setShareAndDir("shared/"); SmbShare smbShare = new SmbShare(config); SmbSession smbSession = new SmbSession(smbShare); SmbFile smbFile = smbSession.createSmbFileObject("smb://myshare\\blubba\\"); assertEquals("smb://myshare/blubba/", smbFile.getPath()); smbSession.close(); }
Source:
private void processCheckpoint(StreamAddressSpace streamAddressSpace, Function<ILogData, Boolean> filter, NavigableSet<Long> queue) { SortedSet<Long> checkpointAddresses = new TreeSet<>(Collections.reverseOrder()); streamAddressSpace.getAddressMap().forEach(checkpointAddresses::add); Iterable<List<Long>> batches = Iterables.partition(checkpointAddresses, runtime.getParameters().getCheckpointReadBatchSize()); boolean checkpointResolved = false; for (List<Long> batch : batches) { if (checkpointResolved) { break; } try { List<ILogData> entries = readAll(batch); for (ILogData data : entries) { filter.apply(data); } } catch (TrimmedException te) { checkpointResolved = processCheckpointBatchByEntry(batch, filter, queue); } } List<Long> checkpointEntries = selectCheckpoint(getCurrentContext()); queue.addAll(checkpointEntries); }

Target:
private void processCheckpoint(StreamAddressSpace streamAddressSpace, Function<ILogData, Boolean> filter, NavigableSet<Long> queue) { SortedSet<Long> checkpointAddresses = new TreeSet<>(Collections.reverseOrder()); streamAddressSpace.getAddressMap().forEach(checkpointAddresses::add); Iterable<List<Long>> batches = Iterables.partition(checkpointAddresses, runtime.getParameters().getCheckpointReadBatchSize()); boolean checkpointResolved = false; for (List<Long> batch : batches) { if (checkpointResolved) { break; } try { List<ILogData> entries = readAll(batch); for (ILogData data : entries) { filter.apply(data); } } catch (TrimmedException te) { checkpointResolved = processCheckpointBatchByEntry(batch, filter, queue); } } List<Long> checkpointEntries = resolveCheckpoint(getCurrentContext()); queue.addAll(checkpointEntries); }
Source:
static Iterator<Double> rangeClosedBy(double from, double toInclusive, double step) { if (Double.isNaN(from)) { throw new IllegalArgumentException("from is NaN"); } else if (Double.isNaN(toInclusive)) { throw new IllegalArgumentException("toInclusive is NaN"); } else if (Double.isNaN(step)) { throw new IllegalArgumentException("step is NaN"); } else if (step == 0) { throw new IllegalArgumentException("step cannot be 0"); } else if (from == toInclusive) { return of(from); } else if (Math.signum(step) == Math.signum(from - toInclusive)) { return empty(); } else { if (step > 0) { return new AbstractIterator<Double>() { final double end = Math.nextUp(toInclusive); double i = from; @Override public boolean hasNext() { return i < end; } @Override public Double getNext() { final double next = i; i = Math.max(i + step, Math.nextUp(i)); return next; } }; } else { return new AbstractIterator<Double>() { final double end = Math.nextDown(toInclusive); double i = from; @Override public boolean hasNext() { return i > end; } @Override public Double getNext() { final double previous = i; i = Math.min(i + step, Math.nextDown(i)); return previous; } }; } } }

Target:
static Iterator<Double> rangeClosedBy(double from, double toInclusive, double step) { if (Double.isNaN(from)) { throw new IllegalArgumentException("from is NaN"); } else if (Double.isNaN(toInclusive)) { throw new IllegalArgumentException("toInclusive is NaN"); } else if (Double.isNaN(step)) { throw new IllegalArgumentException("step is NaN"); } else if (step == 0) { throw new IllegalArgumentException("step cannot be 0"); } else if (from == toInclusive) { return of(from); } else if (step * (from - toInclusive) > 0) { return empty(); } else { return new AbstractIterator<Double>() { double prev = Double.NaN; double curr = from; boolean hasNext = true; @Override public boolean hasNext() { return hasNext; } @Override public Double getNext() { final double next = curr; if ((step > 0 && curr + step > toInclusive) || (step < 0 && curr + step < toInclusive)) { hasNext = false; } else { prev = curr; curr += step; if (curr == prev) { hasNext = false; } } return next; } }; } }