auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void add(final Subscription s) { if (s == null) { throw new IllegalArgumentException("Added Subscription cannot be null."); } Subscription unsubscribe = null; synchronized (this) { if (unsubscribed) { unsubscribe = s; } else { if (subscriptions == null) { subscriptions = new HashSet<Subscription>(4); } subscriptions.add(s); } } if (unsubscribe != null) { unsubscribe.unsubscribe(); } }

Target:
public void add(final Subscription s) { if (s.isUnsubscribed()) { return; } Subscription unsubscribe = null; synchronized (this) { if (unsubscribed) { unsubscribe = s; } else { if (subscriptions == null) { subscriptions = new HashSet<Subscription>(4); } subscriptions.add(s); } } if (unsubscribe != null) { unsubscribe.unsubscribe(); } }
Source:
public ResourceIterableClosableIterable(ResourceIterable<Node> resourceIterable) { this.iterator = resourceIterable.iterator(); }

Target:
public ResourceIterableClosableIterable(ResourceIterable<Node> resourceIterable) { this.resourceIterable = resourceIterable; this.requestedIterators = new ArrayList<ResourceIterator>(); }
Source:
public static List<List<String>> getGroupReceiverList(BlobKey blobKey) throws IOException { Assumption.assertNotNull(blobKey); List<List<String>> listOfList = new LinkedList<>(); int offset = 0; int size = (int) getFileSize(blobKey); while (size > 0) { int bytesToRead = Math.min(size, MAX_READING_LENGTH); try (InputStream blobStream = new BlobstoreInputStream(blobKey, offset)) { byte[] array = new byte[bytesToRead]; blobStream.read(array); offset += MAX_READING_LENGTH; size -= MAX_READING_LENGTH; String readString = new String(array); List<String> newList = Arrays.asList(readString.split(",")); if (listOfList.isEmpty()) { listOfList.add(newList); } else { List<String> lastAddedList = listOfList.get(listOfList.size() - 1); String lastStringOfLastAddedList = lastAddedList.get(lastAddedList.size() - 1); String firstStringOfNewList = newList.get(0); if (lastStringOfLastAddedList.contains("@") && firstStringOfNewList.contains("@")) { listOfList.add(newList); } else { listOfList.get(listOfList.size() - 1) .set(lastAddedList.size() - 1, lastStringOfLastAddedList + firstStringOfNewList); listOfList.add(newList.subList(1, newList.size() - 1)); } } } } return listOfList; }

Target:
public static List<List<String>> getGroupReceiverList(BlobKey blobKey) throws IOException { Assumption.assertNotNull(blobKey); List<List<String>> listOfList = new LinkedList<>(); int offset = 0; int size = (int) getFileSize(blobKey); while (size > 0) { byte[] array = new byte[Math.min(size, MAX_READING_LENGTH)];; try (InputStream blobStream = new BlobstoreInputStream(blobKey, offset)) { blobStream.read(array); } offset += MAX_READING_LENGTH; size -= MAX_READING_LENGTH; String readString = new String(array); List<String> newList = Arrays.asList(readString.split(",")); if (listOfList.isEmpty()) { listOfList.add(newList); } else { List<String> lastAddedList = listOfList.get(listOfList.size() - 1); String lastStringOfLastAddedList = lastAddedList.get(lastAddedList.size() - 1); String firstStringOfNewList = newList.get(0); if (lastStringOfLastAddedList.contains("@") && firstStringOfNewList.contains("@")) { listOfList.add(newList); } else { listOfList.get(listOfList.size() - 1) .set(lastAddedList.size() - 1, lastStringOfLastAddedList + firstStringOfNewList); listOfList.add(newList.subList(1, newList.size() - 1)); } } } return listOfList; }
Source:
public void stop(boolean force) { OpenShiftServerBehaviour behavior = getBehavior(); IServer server = behavior.getServer(); IDeploymentConfig dc = OpenShiftServerUtils.getDeploymentConfig(server); boolean debugMode = OpenShiftLaunchController.DEBUG_MODE.equals(server.getMode()); behavior.setServerStopping(); try { if(dc == null) { OpenShiftDebugUtils.get().terminateRemoteDebugger(behavior.getServer()); } else if(debugMode) { DebuggingContext debugContext = OpenShiftDebugUtils.get().getDebuggingContext(dc); OpenShiftLaunchController.stopDebugging(server, dc, debugContext, new NullProgressMonitor()); } behavior.setServerStopped(); } catch(CoreException ce) { OpenShiftCoreActivator.getDefault().getLog().log( new Status(IStatus.ERROR, OpenShiftCoreActivator.PLUGIN_ID, "Error shutting down server", ce)); getBehavior().setServerStarted(); } }

Target:
public void stop(boolean force) { OpenShiftServerBehaviour behavior = getBehavior(); behavior.setServerStopping(); try { if(OpenShiftDebugUtils.DEBUG_MODE.equals(getServer().getMode())) { OpenShiftDebugUtils.get().stopDebugging(getServer(), new NullProgressMonitor()); } behavior.setServerStopped(); } catch(CoreException ce) { OpenShiftCoreActivator.getDefault().getLog().log( new Status(IStatus.ERROR, OpenShiftCoreActivator.PLUGIN_ID, "Error shutting down server", ce)); getBehavior().setServerStarted(); } }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { try { WizardUtils.openWizardDialog(new NewApplicationWizard(), HandlerUtil.getActiveShell(event)); new RefreshResourceHandler().execute(event); } catch (ConnectionNotFoundException e) { return new Status(Status.ERROR, OpenShiftUIActivator.PLUGIN_ID, "Unable to find the connection", e); } return Status.OK_STATUS; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { try { WizardUtils.openWizardDialog(new NewApplicationWizard(), HandlerUtil.getActiveShell(event)); } catch (ConnectionNotFoundException e) { return new Status(Status.ERROR, OpenShiftUIActivator.PLUGIN_ID, "Unable to find the connection", e); } return Status.OK_STATUS; }
Source:
public ProgramState checkPreStatement(CheckerContext context, Tree syntaxNode) { if (context.getState().stackIsEmpty()) { return context.getState(); } if (syntaxNode.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree methodInvocation = (MethodInvocationTree) syntaxNode; Tree methodSelect = methodInvocation.methodSelect(); if (methodSelect.is(Tree.Kind.MEMBER_SELECT)) { SymbolicValue dereferencedSV = context.getState().peekValue(methodInvocation.arguments().size()); return checkConstraint(context, methodSelect, dereferencedSV); } } if(syntaxNode.is(Tree.Kind.ARRAY_ACCESS_EXPRESSION)) { Tree toCheck = ((ArrayAccessExpressionTree) syntaxNode).expression(); SymbolicValue currentVal = context.getState().peekValue(1); return checkConstraint(context, toCheck, currentVal); } if (syntaxNode.is(Tree.Kind.MEMBER_SELECT)) { return checkMemberSelect(context, (MemberSelectExpressionTree) syntaxNode, context.getState().peekValue()); } return context.getState(); }

Target:
public ProgramState checkPreStatement(CheckerContext context, Tree syntaxNode) { if (context.getState().peekValue() == null) { return context.getState(); } if (syntaxNode.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree methodInvocation = (MethodInvocationTree) syntaxNode; Tree methodSelect = methodInvocation.methodSelect(); if (methodSelect.is(Tree.Kind.MEMBER_SELECT)) { SymbolicValue dereferencedSV = context.getState().peekValue(methodInvocation.arguments().size()); return checkConstraint(context, methodSelect, dereferencedSV); } } if(syntaxNode.is(Tree.Kind.ARRAY_ACCESS_EXPRESSION)) { Tree toCheck = ((ArrayAccessExpressionTree) syntaxNode).expression(); SymbolicValue currentVal = context.getState().peekValue(1); return checkConstraint(context, toCheck, currentVal); } if (syntaxNode.is(Tree.Kind.MEMBER_SELECT)) { return checkMemberSelect(context, (MemberSelectExpressionTree) syntaxNode, context.getState().peekValue()); } return context.getState(); }
Source:
public String get(final String property) { Assert.hasText(property, "property should contain text."); final String secretName = getKeyVaultSecretName(property); if (this.secretKeys == null || secretKeys.size() == 0) { refreshPropertyNames(); } if (this.propertyNames.contains(secretName)) { final KeyVaultSecret secret = this.keyVaultClient.getSecret(secretName); return secret == null ? null : secret.getValue(); } else { return null; } }

Target:
public String get(final String property) { Assert.hasText(property, "property should contain text."); final String secretName = getKeyVaultSecretName(property); if (this.secretKeys == null || secretKeys.size() == 0) { refreshPropertyNames(); } if (this.propertyNames.contains(secretName)) { final KeyVaultSecret secret = this.secretClient.getSecret(secretName); return secret == null ? null : secret.getValue(); } else { return null; } }
Source:
public void onDestroyView() { serverUrlPreference = null; usernamePreference = null; passwordPreference = null; selectedGoogleAccountPreference = null; listPopupWindow = null; super.onDestroyView(); }

Target:
public void onDestroyView() { listPopupWindow = null; super.onDestroyView(); }
Source:
public void dispose() { super.dispose(); fCriticalPathModule.dispose(); }

Target:
public void dispose() { fCriticalPathModule.dispose(); super.dispose(); }
Source:
public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; if (errorMessageText != null && !errorMessageText.isDisposed()) { errorMessageText.setText(errorMessage == null ? " \n " : errorMessage); boolean hasError = errorMessage != null && !(StringConverter.removeWhiteSpaces(errorMessage)).isEmpty(); errorMessageText.setEnabled(hasError); errorMessageText.setVisible(hasError); errorMessageText.getParent().update(); Control button = getButton(IDialogConstants.OK_ID); if (button != null) { button.setEnabled(errorMessage == null); } } }

Target:
public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; if (errorMessageText != null && !errorMessageText.isDisposed()) { errorMessageText.setText(errorMessage == null ? " \n " : errorMessage); boolean hasError = errorMessage != null && (StringConverter.removeWhiteSpaces(errorMessage)).length() > 0; errorMessageText.setEnabled(hasError); errorMessageText.setVisible(hasError); errorMessageText.getParent().update(); Control button = getButton(IDialogConstants.OK_ID); if (button != null) { button.setEnabled(errorMessage == null); } } }
Source:
public void setId(long id) { System.out.println(id); this.id = id; }

Target:
public void setId(long id) { this.id = id; }
Source:
public InterestChannelImpl(final SourcedEurekaRegistry<InstanceInfo> registry, final MessageConnection transport, final InterestChannelMetrics metrics) { super(STATES.Idle, transport, registry); this.metrics = metrics; this.metrics.incrementStateCounter(STATES.Idle); this.notificationMultiplexer = new InterestNotificationMultiplexer(registry); this.channelSubscriptionMonitor = new ChannelSubscriptionMonitor(metrics); subscribeToTransportInput(new Action1<Object>() { @Override public void call(Object message) { if (message instanceof SnapshotRegistration) { switch (state.get()) { case Idle: sendSnapshot(((SnapshotRegistration) message).getInterests()); state.set(STATES.Closed); metrics.stateTransition(STATES.Idle, STATES.Open); break; case Open: sendErrorOnTransport(SNAPSHOT_REQUEST_NOT_ALLOWED); break; case Closed: sendErrorOnTransport(CHANNEL_CLOSED_EXCEPTION); break; } } else if (message instanceof InterestRegistration) { Interest<InstanceInfo> interest = ((InterestRegistration) message).toComposite(); switch (state.get()) { case Idle: case Open: change(interest); break; case Closed: sendErrorOnTransport(CHANNEL_CLOSED_EXCEPTION); break; } } else if (message instanceof UnregisterInterestSet) { switch (state.get()) { case Idle: case Open: change(Interests.forNone()); break; case Closed: sendErrorOnTransport(CHANNEL_CLOSED_EXCEPTION); break; } } else { sendErrorOnTransport(new EurekaProtocolError("Unexpected message " + message)); } } }); }

Target:
public InterestChannelImpl(final SourcedEurekaRegistry<InstanceInfo> registry, final MessageConnection transport, final InterestChannelMetrics metrics) { super(STATES.Idle, transport, registry); this.metrics = metrics; this.metrics.incrementStateCounter(STATES.Idle); this.notificationMultiplexer = new InterestNotificationMultiplexer(registry); this.channelSubscriptionMonitor = new ChannelSubscriptionMonitor(metrics); subscribeToTransportInput(new Action1<Object>() { @Override public void call(Object message) { if (message instanceof SnapshotRegistration) { switch (state.get()) { case Idle: state.set(STATES.Open); metrics.stateTransition(STATES.Idle, STATES.Open); sendSnapshot(((SnapshotRegistration) message).getInterests()); state.set(STATES.Closed); metrics.stateTransition(STATES.Idle, STATES.Closed); break; case Open: sendErrorOnTransport(SNAPSHOT_REQUEST_NOT_ALLOWED); break; case Closed: sendErrorOnTransport(CHANNEL_CLOSED_EXCEPTION); break; } } else if (message instanceof InterestRegistration) { Interest<InstanceInfo> interest = ((InterestRegistration) message).toComposite(); switch (state.get()) { case Idle: case Open: change(interest); break; case Closed: sendErrorOnTransport(CHANNEL_CLOSED_EXCEPTION); break; } } else if (message instanceof UnregisterInterestSet) { switch (state.get()) { case Idle: case Open: change(Interests.forNone()); break; case Closed: sendErrorOnTransport(CHANNEL_CLOSED_EXCEPTION); break; } } else { sendErrorOnTransport(new EurekaProtocolError("Unexpected message " + message)); } } }); }
Source:
public static Query setQuery(Parameters param) throws Exception { Query query = new Query(param.getQuery()); if (!param.getPlace().isEmpty()) { PlaceApi googleFindPlace; googleFindPlace = new PlaceApi(param.getPlace()); GeoLocation geoLocation; geoLocation = new GeoLocation(googleFindPlace.getLocation().lat, googleFindPlace.getLocation().lng); query.setGeoCode(geoLocation, googleFindPlace.getRadius(), Query.KILOMETERS); } return query; }

Target:
public static Query setQuery(Parameters param) throws IOException { Query query = new Query(param.getQuery()); if (!param.getPlace().isEmpty()) { PlaceApi googleFindPlace; googleFindPlace = new PlaceApi(param.getPlace()); GeoLocation geoLocation; geoLocation = new GeoLocation(googleFindPlace.getLocation().lat, googleFindPlace.getLocation().lng); query.setGeoCode(geoLocation, googleFindPlace.getRadius(), Query.KILOMETERS); } return query; }
Source:
public PointList getPolygonPoints() { if (getFigure() instanceof IRoundedRectangleFigure) { IRoundedRectangleFigure packageFigure = ((IRoundedRectangleFigure) ((IFigure) getFigure())); Rectangle packageHeader = packageFigure.getPackageHeader().getCopy(); packageFigure.translateToAbsolute(packageHeader); if (!packageHeader.isEmpty()) { PointList points = new PointList(5); Rectangle anchorableRectangle = getBox(); points.addPoint(anchorableRectangle.x, anchorableRectangle.y); points.addPoint(anchorableRectangle.x + packageHeader.width, anchorableRectangle.y); points.addPoint(anchorableRectangle.x + packageHeader.width, anchorableRectangle.y + packageHeader.height); points.addPoint(anchorableRectangle.x + anchorableRectangle.width, anchorableRectangle.y + packageHeader.height); points.addPoint(anchorableRectangle.x + anchorableRectangle.width, anchorableRectangle.y + anchorableRectangle.height); points.addPoint(anchorableRectangle.x, anchorableRectangle.y + anchorableRectangle.height); points.addPoint(anchorableRectangle.x, anchorableRectangle.y); return points; } else { return super.getPolygonPoints(); } } else { return super.getPolygonPoints(); } }

Target:
public PointList getPolygonPoints() { PointList points = null; if (getFigure() instanceof IRoundedRectangleFigure) { IRoundedRectangleFigure packageFigure = ((IRoundedRectangleFigure) ((IFigure) getFigure())); Rectangle packageHeader = packageFigure.getPackageHeader().getCopy(); packageFigure.translateToAbsolute(packageHeader); if (!packageHeader.isEmpty()) { points = new PointList(5); Rectangle anchorableRectangle = getBox(); points.addPoint(anchorableRectangle.x, anchorableRectangle.y); points.addPoint(anchorableRectangle.x + packageHeader.width, anchorableRectangle.y); points.addPoint(anchorableRectangle.x + packageHeader.width, anchorableRectangle.y + packageHeader.height); points.addPoint(anchorableRectangle.x + anchorableRectangle.width, anchorableRectangle.y + packageHeader.height); points.addPoint(anchorableRectangle.x + anchorableRectangle.width, anchorableRectangle.y + anchorableRectangle.height); points.addPoint(anchorableRectangle.x, anchorableRectangle.y + anchorableRectangle.height); points.addPoint(anchorableRectangle.x, anchorableRectangle.y); } } return null != points ? points : super.getPolygonPoints(); }
Source:
public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) { return false; } final TagValueWildcardFilter otherTagValueFilter = (TagValueWildcardFilter) o; final boolean result = Objects.equal(has_postfix, otherTagValueFilter.has_postfix) && Objects.equal(has_prefix, otherTagValueFilter.has_prefix) && Objects.equal(matches_all, otherTagValueFilter.matchesAll()); if (!result) { return false; } if (components != null && otherTagValueFilter.components() == null || components == null && otherTagValueFilter.components() != null) { return false; } if (components != null) { List<String> listComponents = Arrays.asList(components); List<String> otherComponents = Arrays.asList(otherTagValueFilter.components()); if (!Comparators.ListComparison.equalLists(listComponents, otherComponents)) { return false; } } return true; }

Target:
public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) { return false; } return true; }
Source:
public Map<String, ArtifactReadable> getCoverageUnits(long branchUuid, String artifactUuid) { IOseeBranch branch = TokenFactory.createBranch(branchUuid, ""); ArtifactReadable coveragePackage = getQuery().fromBranch(branchUuid).andGuid(artifactUuid).getResults().getOneOrNull(); List<ArtifactReadable> descendants = coveragePackage.getDescendants(); return getChildrenRecurse(descendants, branch); }

Target:
public Map<String, ArtifactReadable> getCoverageUnits(long branchUuid, String artifactUuid) { ArtifactReadable coveragePackage = getQuery().fromBranch(branchUuid).andGuid(artifactUuid).getResults().getOneOrNull(); List<ArtifactReadable> descendants = coveragePackage.getDescendants(); return getChildrenRecurse(descendants); }
Source:
public ArrayInterface addString(String value) { return addObject(value); }

Target:
public Array addString(String value) { return addObject(value); }
Source:
public TrackerBuilder sessionCheckInterval(long sessionCheckInterval) { this.sessionCheckInterval = sessionCheckInterval; return this; }

Target:
public TrackerBuilder sessionCheckInterval(long sessionCheckInterval) { return this; }
Source:
private void setMtuSelectorsChangeability(boolean isChangeable, String prohibitionReason) { if (!isChangeable) { getMtuSelector().setChangeProhibitionReason(prohibitionReason); getMtu().setChangeProhibitionReason(prohibitionReason); } getMtuSelector().setIsChangable(isChangeable); getMtu().setIsChangable(isChangeable); }

Target:
private void setMtuSelectorsChangeability(boolean isChangeable, String prohibitionReason) { if (!isChangeable) { getMtuSelector().setChangeProhibitionReason(prohibitionReason); getMtu().setChangeProhibitionReason(prohibitionReason); } getMtuSelector().setIsChangable(isChangeable); getMtu().setIsChangable(isChangeable && isCustomMtu()); }
Source:
public void setAttributeMappings( List<String> attributeMappingsList) { LOGGER.trace("Setting attribute mappings to: {}", attributeMappingsList); if (attributeMappingsList != null) { mappingEntries.clear(); attributeMappingsList .stream() .filter(StringUtils::isNotEmpty) .map( string -> { try { return JsonFactory.create().readValue(string, Map.class); } catch (JsonException e) { LOGGER.debug("Failed to parse attribute mapping json '{}'", string, e); } return null; }) .filter(Objects::nonNull) .filter(map -> map.get(ATTRIBUTE_NAME) instanceof String) .filter(map -> map.get(FEATURE_NAME) instanceof String) .filter(map -> map.get(TEMPLATE) instanceof String) .forEach( map -> addAttributeMapping( (String) map.get(ATTRIBUTE_NAME), (String) map.get(FEATURE_NAME), (String) map.get(TEMPLATE))); } }

Target:
public void setAttributeMappings( List<String> attributeMappingsList) { LOGGER.trace("Setting attribute mappings to: {}", attributeMappingsList); if (attributeMappingsList != null) { mappingEntries.clear(); attributeMappingsList .stream() .filter(StringUtils::isNotEmpty) .map(this::jsonToMap) .filter(this::validAttributeMapping) .forEach( map -> addAttributeMapping( (String) map.get(ATTRIBUTE_NAME), (String) map.get(FEATURE_NAME), (String) map.get(TEMPLATE))); } }
Source:
public void createPartControl(final Composite parent) { fParentComposite = parent; if (this instanceof ITmfTimeAligned) { contributeAlignViewsActionToToolbar(); fParentComposite.addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { fParentComposite.removePaintListener(this); fTimeAlignmentSynchronizer.handleViewCreated(TmfView.this); fControlListener = new ControlAdapter() { @Override public void controlResized(ControlEvent event) { fTimeAlignmentSynchronizer.handleViewResized(TmfView.this); } }; fParentComposite.addControlListener(fControlListener); } }); getSite().getPage().addPartListener(new IPartListener() { @Override public void partOpened(IWorkbenchPart part) { } @Override public void partDeactivated(IWorkbenchPart part) { } @Override public void partClosed(IWorkbenchPart part) { if (part == TmfView.this && fControlListener != null && !fParentComposite.isDisposed()) { fParentComposite.removeControlListener(fControlListener); fControlListener = null; } } @Override public void partBroughtToTop(IWorkbenchPart part) { } @Override public void partActivated(IWorkbenchPart part) { } }); } }

Target:
public void createPartControl(final Composite parent) { fParentComposite = parent; if (this instanceof ITmfTimeAligned) { contributeAlignViewsActionToToolbar(); fParentComposite.addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { fParentComposite.removePaintListener(this); TIME_ALIGNMENT_SYNCHRONIZER.handleViewCreated(TmfView.this); fControlListener = new ControlAdapter() { @Override public void controlResized(ControlEvent event) { TIME_ALIGNMENT_SYNCHRONIZER.handleViewResized(TmfView.this); } }; fParentComposite.addControlListener(fControlListener); } }); getSite().getPage().addPartListener(new IPartListener() { @Override public void partOpened(IWorkbenchPart part) { } @Override public void partDeactivated(IWorkbenchPart part) { } @Override public void partClosed(IWorkbenchPart part) { if (part == TmfView.this && fControlListener != null && !fParentComposite.isDisposed()) { fParentComposite.removeControlListener(fControlListener); fControlListener = null; getSite().getPage().removePartListener(this); } } @Override public void partBroughtToTop(IWorkbenchPart part) { } @Override public void partActivated(IWorkbenchPart part) { } }); } }
Source:
public void shouldLogWhenTopicLeaderNotAvailableAndThrowException() { final String topicLeaderNotAvailable = "LeaderNotAvailableTopic"; mockAdminClient.addTopic( false, topicLeaderNotAvailable, Collections.singletonList(new TopicPartitionInfo(0, broker1, cluster, Collections.emptyList())), null); final InternalTopicConfig internalTopicConfig = new RepartitionTopicConfig(topicLeaderNotAvailable, Collections.emptyMap()); internalTopicConfig.setNumberOfPartitions(1); final Map<String, InternalTopicConfig> topicConfigMap = new HashMap<>(); topicConfigMap.put(topicLeaderNotAvailable, internalTopicConfig); LogCaptureAppender.setClassLoggerToDebug(InternalTopicManager.class); try (final LogCaptureAppender appender = LogCaptureAppender.createAndRegister(InternalTopicManager.class)) { final StreamsException exception = assertThrows( StreamsException.class, () -> internalTopicManager.makeReady(topicConfigMap)); final String expectedMessage = "Could not create topics after 1 retries. This can happen if the Kafka cluster is temporary not available"; assertTrue(exception.getMessage().contains(expectedMessage)); final String logLeaderNotAvailable = "The leader of Topic " + topicLeaderNotAvailable + " is not available"; assertThat(appender.getMessages(), hasItem(containsString(logLeaderNotAvailable))); final String logCreateTopic = "Going to create topic " + topicLeaderNotAvailable; final String logTopicExistsException = "TopicExistsException"; assertThat(appender.getMessages(), not(hasItem(containsString(logCreateTopic)))); assertThat(appender.getMessages(), not(hasItem(containsString(logTopicExistsException)))); } }

Target:
public void shouldLogWhenTopicLeaderNotAvailableAndThrowException() { mockAdminClient.addTopic( false, MockAdminClient.LEADER_NOT_AVAILABLE_TOPIC, Collections.singletonList(new TopicPartitionInfo(0, broker1, cluster, Collections.emptyList())), null); final InternalTopicConfig internalTopicConfig = new RepartitionTopicConfig(MockAdminClient.LEADER_NOT_AVAILABLE_TOPIC, Collections.emptyMap()); internalTopicConfig.setNumberOfPartitions(1); final Map<String, InternalTopicConfig> topicConfigMap = new HashMap<>(); topicConfigMap.put(MockAdminClient.LEADER_NOT_AVAILABLE_TOPIC, internalTopicConfig); LogCaptureAppender.setClassLoggerToDebug(InternalTopicManager.class); try (final LogCaptureAppender appender = LogCaptureAppender.createAndRegister(InternalTopicManager.class)) { final StreamsException exception = assertThrows( StreamsException.class, () -> internalTopicManager.makeReady(topicConfigMap)); } }
Source:
public static String getDifferenceInYears(@NonNull String yearStr) { Context context = WikipediaApp.getInstance().getApplicationContext(); int year = Integer.parseInt(yearStr); int currentYear = Calendar.getInstance().get(Calendar.YEAR); switch (currentYear - year) { case 0: return context.getString(R.string.this_year); case 1: return context.getString(R.string.last_year); default: return String.format(context.getString(R.string.diff_in_years_text), String.valueOf(currentYear - year)); } }

Target:
public static String getDifferenceInYears(@NonNull String yearStr) { Context context = WikipediaApp.getInstance().getApplicationContext(); int diffInYears = Calendar.getInstance().get(Calendar.YEAR) - Integer.parseInt(yearStr); if (diffInYears == 0) { return context.getString(R.string.this_year); } else { return getQuantityString(context, R.plurals.diff_years, diffInYears, diffInYears); } }
Source:
private static double alpha(final double meanBias, final double biasVariance) { return meanBias * meanBias / biasVariance; }

Target:
public static double alpha(final double meanBias, final double biasVariance) { return meanBias * meanBias / biasVariance; }
Source:
private TaskProgressCallback getProgressCallback() { return this.progressCallback == null ? null : this.progressCallback.get(); }

Target:
private TaskProgressCallback getProgressCallback() { return progressCallback == null ? null : progressCallback.get(); }
Source:
private void resolveAnnotations(BlockScope scope, Annotation[] annotations, Binding currentBinding) { int length = annotations == null ? 0 : annotations.length; if (length == 0) return; boolean old = scope.insideTypeAnnotation; scope.insideTypeAnnotation = true; currentBinding.getAnnotationTagBits(); scope.insideTypeAnnotation = old; ElementImpl element = (ElementImpl) _factory.newElement(currentBinding); AnnotationBinding annotationBindings = element.getPackedAnnotationBindings(); for (AnnotationBinding binding : annotationBindings) { if (binding == null) continue; ReferenceBinding annotationType = binding.getAnnotationType(); if (Annotation.isAnnotationTargetAllowed(scope, annotationType, currentBinding)) { TypeElement anno = (TypeElement)_factory.newElement(annotationType); _annoToElement.put(anno, element); } } }

Target:
private void resolveAnnotations(BlockScope scope, Annotation[] annotations, Binding currentBinding) { int length = annotations == null ? 0 : annotations.length; if (length == 0) return; boolean old = scope.insideTypeAnnotation; scope.insideTypeAnnotation = true; currentBinding.getAnnotationTagBits(); scope.insideTypeAnnotation = old; ElementImpl element = (ElementImpl) _factory.newElement(currentBinding); AnnotationBinding annotationBindings = element.getPackedAnnotationBindings(); for (AnnotationBinding binding : annotationBindings) { ReferenceBinding annotationType = binding.getAnnotationType(); if (binding != null && Annotation.isAnnotationTargetAllowed(scope, annotationType, currentBinding) ) { TypeElement anno = (TypeElement)_factory.newElement(annotationType); _annoToElement.put(anno, element); } } }
Source:
public void testDeleteAuthorRelationshipCopyToBothItems() throws Exception { initPublicationAuthor(); getClient(adminAuthToken).perform( delete("/api/core/relationships/" + relationship.getID() + "?copyVirtualMetadata=all")) .andExpect(status().isNoContent()); leftItem = itemService.find(context, leftItem.getID()); List<MetadataValue> authorList = itemService.getMetadata(leftItem, "dc", "contributor", "author", Item.ANY); assertThat(authorList.size(), equalTo(1)); assertThat(authorList.get(0).getValue(), equalTo("familyName, firstName")); assertThat(authorList.get(0).getMetadataField().getMetadataSchema().getName(), equalTo("dc")); assertThat(authorList.get(0).getMetadataField().getElement(), equalTo("contributor")); assertThat(authorList.get(0).getMetadataField().getQualifier(), equalTo("author")); assertNull(authorList.get(0).getAuthority()); List<MetadataValue> relationshipMetadataList = itemService .getMetadata(leftItem, "relation", "isAuthorOfPublication", null, Item.ANY); assertThat(relationshipMetadataList.size(), equalTo(0)); }

Target:
public void testDeleteAuthorRelationshipCopyToBothItems() throws Exception { initPublicationAuthor(); getClient(adminAuthToken).perform( delete("/api/core/relationships/" + relationship.getID() + "?copyVirtualMetadata=all")) .andExpect(status().isNoContent()); leftItem = itemService.find(context, leftItem.getID()); List<MetadataValue> authorList = itemService.getMetadata(leftItem, "dc", "contributor", "author", Item.ANY); assertThat(authorList.size(), equalTo(1)); assertThat(authorList.get(0).getValue(), equalTo("familyName, firstName")); assertThat(authorList.get(0).getMetadataField().getMetadataSchema().getName(), equalTo("dc")); assertThat(authorList.get(0).getMetadataField().getElement(), equalTo("contributor")); assertThat(authorList.get(0).getMetadataField().getQualifier(), equalTo("author")); assertNull(authorList.get(0).getAuthority()); List<MetadataValue> relationshipMetadataList = itemService .getMetadata(leftItem, "relation", "isAuthorOfPublication", null, Item.ANY); assertThat(relationshipMetadataList.size(), equalTo(0)); relationshipMetadataList = itemService .getMetadata(rightItem, "relation", "isPublicationOfAuthor", null, Item.ANY); assertThat(relationshipMetadataList.size(), equalTo(0)); }
Source:
int blockPlayerWin() { int equalCount = 0; int emptyI = 0, emptyJ = 0; int winCombinationsNumber = fieldSize * 2 + 2; for (int k = 0; k < winCombinationsNumber; k++) { equalCount = 0; for (int i = 0; i < fieldSize; i++) for (int j = 0; j < fieldSize; j++) { if (fieldArray[i][j] == playerMark && (getWinCombination(k, i, j) == 1)) equalCount++; if ((fieldArray[i][j] == 0) && (getWinCombination(k, i, j) == 1)) { emptyI = i; emptyJ = j; } if ((fieldArray[i][j] == aIMark) && (getWinCombination(k, i, j) == 1)) { j = fieldSize; i = fieldSize; equalCount = 0; } } if (equalCount == (fieldSize - 1)) { return (emptyI * fieldSize + emptyJ); } } return NOTHING_TO_PREVENT; }

Target:
int blockPlayerWin() { int equalCount = 0; int emptyI = 0, emptyJ = 0; int winCombinationsNumber = fieldSize * 2 + 2; for (int k = 0; k < winCombinationsNumber; k++) { equalCount = 0; for (int i = 0; i < fieldSize; i++) for (int j = 0; j < fieldSize; j++) { if (fieldArray[i][j] == playerMark && (getWinCombination(k, i, j) == 1)) { equalCount++; } if ((fieldArray[i][j] == 0) && (getWinCombination(k, i, j) == 1)) { emptyI = i; emptyJ = j; } if ((fieldArray[i][j] == aIMark) && (getWinCombination(k, i, j) == 1)) { j = fieldSize; i = fieldSize; equalCount = 0; } } if (equalCount == (fieldSize - 1)) { return (emptyI * fieldSize + emptyJ); } } return NOTHING_TO_PREVENT; }
Source:
public String getColumnText(@Nullable Object element, int columnIndex) { if (columnIndex == 0 && element instanceof TmfTreeViewerEntry) { return String.valueOf(((TmfTreeViewerEntry) element).getName()); } else if (element instanceof TmfGenericTreeEntry) { SegmentStoreStatisticsModel model = ((TmfGenericTreeEntry<@NonNull SegmentStoreStatisticsModel>) element).getModel(); if (model.getNbElements() == 0) { return ""; } if (columnIndex == 1) { return toFormattedString(model.getMin()); } else if (columnIndex == 2) { return String.valueOf(toFormattedString(model.getMax())); } else if (columnIndex == 3) { return String.valueOf(toFormattedString(model.getMean())); } else if (columnIndex == 4) { return String.valueOf(toFormattedString(model.getStdDev())); } else if (columnIndex == 5) { return String.valueOf(model.getNbElements()); } else if (columnIndex == 6) { return String.valueOf(toFormattedString(model.getTotal())); } } return ""; }

Target:
public String getColumnText(@Nullable Object element, int columnIndex) { if (columnIndex == 0 && element instanceof TmfTreeViewerEntry) { return String.valueOf(((TmfTreeViewerEntry) element).getName()); } else if (element instanceof TmfGenericTreeEntry) { SegmentStoreStatisticsModel model = ((TmfGenericTreeEntry<@NonNull SegmentStoreStatisticsModel>) element).getModel(); if (model.getNbElements() == 0) { return ""; } if (columnIndex == 1) { return toFormattedString(model.getMin()); } else if (columnIndex == 2) { return String.valueOf(toFormattedString(model.getMax())); } else if (columnIndex == 3) { return String.valueOf(toFormattedString(model.getMean())); } else if (columnIndex == 4) { return String.valueOf(toFormattedString(model.getStdDev())); } else if (columnIndex == 5) { return String.valueOf(model.getNbElements()); } else if (columnIndex == 6) { return String.valueOf(toFormattedString(model.getTotal())); } } if (element instanceof SegmentStoreStatisticsEntry) { IStatistics<ISegment> statistics = ((SegmentStoreStatisticsEntry) element).getEntry(); if (statistics.getNbElements() > 0) { if (columnIndex == 1) { return toFormattedString(statistics.getMin()); } else if (columnIndex == 2) { return String.valueOf(toFormattedString(statistics.getMax())); } else if (columnIndex == 3) { return String.valueOf(toFormattedString(statistics.getMean())); } else if (columnIndex == 4) { return String.valueOf(toFormattedString(statistics.getStdDev())); } else if (columnIndex == 5) { return String.valueOf(statistics.getNbElements()); } else if (columnIndex == 6) { return String.valueOf(toFormattedString(statistics.getTotal())); } } } return ""; }
Source:
public static int clearItemInOffHand(final Player p, final ItemStack item) { if (hasMainHandSupport == null || hasMainHandSupport) { try { int removedAmount = 0; if (p.getInventory().getItemInOffHand().getType().equals(item.getType())) { removedAmount = p.getInventory().getItemInOffHand().getAmount(); p.getInventory().setItemInOffHand(null); } hasMainHandSupport = true; return removedAmount; } catch (final Throwable e) { hasMainHandSupport = false; return 0; } } return 0; }

Target:
public static int clearItemInOffHand(final Player p, final ItemStack item) { if (hasMainHandSupport == null || hasMainHandSupport) { try { int removedAmount = 0; if (p.getInventory().getItemInOffHand().getType().equals(item.getType())) { removedAmount = p.getInventory().getItemInOffHand().getAmount(); p.getInventory().setItemInOffHand(null); } hasMainHandSupport = true; return removedAmount; } catch (final Throwable e) { hasMainHandSupport = false; } } return 0; }
Source:
protected void ExecuteVmCommand() { AddCustomValue("InterfaceType", (VmInterfaceType.forValue(getParameters().getInterface().getType()).getInterfaceTranslation()).toString()); this.setVmName(DbFacade.getInstance().getVmStaticDAO().get(getParameters().getVmId()).getvm_name()); if (StringUtils.isEmpty(getMacAddress())) { getParameters().getInterface().setMacAddress(MacPoolManager.getInstance().allocateNewMac()); } getParameters().getInterface().setSpeed( VmInterfaceType.forValue( getParameters().getInterface().getType()).getSpeed()); getParameters().getInterface().setId(Guid.NewGuid()); getParameters().getInterface().setVmId(getParameters().getVmId()); DbFacade dbFacade = DbFacade.getInstance(); dbFacade .getVmNetworkInterfaceDAO() .save(getParameters().getInterface()); dbFacade .getVmNetworkStatisticsDAO() .save(getParameters().getInterface().getStatistics()); VmDevice vmDevice = VmDeviceUtils.addNetworkInterfaceDevice( new VmDeviceId(getParameters().getInterface().getId(), getParameters().getVmId()), getParameters().getInterface().isActive()); boolean succeded = true; VmDynamic vmDynamic = getVm().getDynamicData(); if (getParameters().getInterface().isActive() && HotPlugUnplugVmNicCommand.isHotPlugNicAllowedForVmStatus(vmDynamic.getstatus())) { succeded = hotPlugNic(vmDevice, vmDynamic); if (!succeded) { getReturnValue().getExecuteFailedMessages().add("Failed hot-plugging nic to VM"); } } setSucceeded(succeded); }

Target:
protected void ExecuteVmCommand() { AddCustomValue("InterfaceType", (VmInterfaceType.forValue(getParameters().getInterface().getType()).getInterfaceTranslation()).toString()); this.setVmName(DbFacade.getInstance().getVmStaticDAO().get(getParameters().getVmId()).getvm_name()); if (StringUtils.isEmpty(getMacAddress())) { getParameters().getInterface().setMacAddress(MacPoolManager.getInstance().allocateNewMac()); } getParameters().getInterface().setSpeed( VmInterfaceType.forValue( getParameters().getInterface().getType()).getSpeed()); getParameters().getInterface().setId(Guid.NewGuid()); getParameters().getInterface().setVmId(getParameters().getVmId()); DbFacade dbFacade = DbFacade.getInstance(); dbFacade .getVmNetworkInterfaceDAO() .save(getParameters().getInterface()); dbFacade .getVmNetworkStatisticsDAO() .save(getParameters().getInterface().getStatistics()); VmDevice vmDevice = VmDeviceUtils.addNetworkInterfaceDevice( new VmDeviceId(getParameters().getInterface().getId(), getParameters().getVmId()), getParameters().getInterface().isActive()); boolean succeded = true; VmDynamic vmDynamic = getVm().getDynamicData(); if (getParameters().getInterface().isActive() && VmHandler.isHotPlugNicAllowedForVmStatus(vmDynamic.getstatus())) { succeded = hotPlugNic(vmDevice, vmDynamic); if (!succeded) { getReturnValue().getExecuteFailedMessages().add("Failed hot-plugging nic to VM"); } } setSucceeded(succeded); }
Source:
public static APIRevisionListDTO fromListAPIRevisiontoDTO(List<APIRevision> apiRevisionList) throws APIManagementException { APIRevisionListDTO apiRevisionListDTO = new APIRevisionListDTO(); List<APIRevisionDTO> apiRevisionDTOS = new ArrayList<>(); int count = 0; for (APIRevision apiRevision: apiRevisionList) { count++; apiRevisionDTOS.add(fromAPIRevisiontoDTO(apiRevision)); } apiRevisionListDTO.setCount(count); apiRevisionListDTO.setList(apiRevisionDTOS); return apiRevisionListDTO; }

Target:
public static APIRevisionListDTO fromListAPIRevisiontoDTO(List<APIRevision> apiRevisionList) throws APIManagementException { APIRevisionListDTO apiRevisionListDTO = new APIRevisionListDTO(); List<APIRevisionDTO> apiRevisionDTOS = new ArrayList<>(); for (APIRevision apiRevision: apiRevisionList) { apiRevisionDTOS.add(fromAPIRevisiontoDTO(apiRevision)); } apiRevisionListDTO.setCount(apiRevisionList.size()); apiRevisionListDTO.setList(apiRevisionDTOS); return apiRevisionListDTO; }
Source:
public void shouldPassWhenBuildingSettlementInMainStageOnlyAfterDiceThrown() throws GameException, PlayException { hex_0_0.getEdges().getTopRight().setBuilding(new Building<EdgeBuiltType>(EdgeBuiltType.ROAD, gameUser1)); gameUser1.setResources(new Resources(1, 1, 1, 1, 0)); game.setStage(GameStage.MAIN); game.setDiceThrown(false); allowUserToThrowDice(gameUser1); when(gameDao.getGameByGameId(1)).thenReturn(game); when(gameDao.getGameByGameId(1)).thenReturn(game); HashMap<String, String> params = new HashMap<String, String>(); params.put("nodeId", "3"); try { playService.processAction(GameUserActionCode.BUILD_SETTLEMENT, gameUser1.getUser(), "1", params); fail("Exception should be thrown should be thrown"); } catch (PlayException e) { assertEquals(PlayServiceImpl.ERROR_CODE_ERROR, e.getErrorCode()); } catch (Exception e) { fail("No other exceptions should be thrown"); } playService.processAction(GameUserActionCode.THROW_DICE, gameUser1.getUser(), "1"); playService.processAction(GameUserActionCode.BUILD_SETTLEMENT, gameUser1.getUser(), "1", params); assertNotNull(game); assertNotNull(hex_0_0); assertNotNull(hex_0_0.getNodes().getTopRight()); assertNotNull(hex_0_0.getNodes().getTopRight().getBuilding()); assertEquals(hex_0_0.getNodes().getTopRight().getBuilding().getBuilt(), NodeBuiltType.SETTLEMENT); assertEquals(hex_0_0.getNodes().getTopRight().getBuilding().getBuildingOwner(), gameUser1); }

Target:
public void shouldPassWhenBuildingSettlementInMainStageOnlyAfterDiceThrown() throws GameException, PlayException { hex_0_0.getEdges().getTopRight().setBuilding(new Building<EdgeBuiltType>(EdgeBuiltType.ROAD, gameUser1)); gameUser1.setResources(new Resources(1, 1, 1, 1, 0)); game.setStage(GameStage.MAIN); game.setDiceThrown(false); allowUserToThrowDice(gameUser1); when(gameDao.getGameByGameId(1)).thenReturn(game); Map<String, String> params = new HashMap<String, String>(); params.put("nodeId", "3"); try { playService.processAction(GameUserActionCode.BUILD_SETTLEMENT, gameUser1.getUser(), "1", params); fail("Exception should be thrown should be thrown"); } catch (PlayException e) { assertEquals(PlayServiceImpl.ERROR_CODE_ERROR, e.getErrorCode()); } catch (Exception e) { fail("No other exceptions should be thrown"); } playService.processAction(GameUserActionCode.THROW_DICE, gameUser1.getUser(), "1"); playService.processAction(GameUserActionCode.BUILD_SETTLEMENT, gameUser1.getUser(), "1", params); assertNotNull(game); assertNotNull(hex_0_0); assertNotNull(hex_0_0.getNodes().getTopRight()); assertNotNull(hex_0_0.getNodes().getTopRight().getBuilding()); assertEquals(hex_0_0.getNodes().getTopRight().getBuilding().getBuilt(), NodeBuiltType.SETTLEMENT); assertEquals(hex_0_0.getNodes().getTopRight().getBuilding().getBuildingOwner(), gameUser1); }
Source:
public void testRetrieveAllUsers() throws Exception { String response = RestAssuredMockMvc.given() .contentType("application/json") .when() .get("/users/all") .peek() .then() .statusCode(200) .extract() .asString(); List<User> users = objectMapper.readValue(response, objectMapper.getTypeFactory().constructCollectionType(List.class, User.class)); assertNotNull(users); assertFalse(users.isEmpty()); users.forEach(user -> logger.debug("Retrieved " + user)); System.out.println(users); }

Target:
public void testRetrieveAllUsers() throws Exception { String response = given().contentType("application/json") .when() .get("/users/all") .peek() .then() .statusCode(200) .extract() .asString(); List<User> users = objectMapper.readValue(response, objectMapper.getTypeFactory().constructCollectionType(List.class, User.class)); assertNotNull(users); assertFalse(users.isEmpty()); users.forEach(user -> logger.debug("Retrieved " + user)); }
Source:
public boolean canConfigure(IProject project, Set<IPath> ignoredDirectories, IProgressMonitor monitor) { return project.getFile(PlatformConstants.FILE_XML_CONFIG).exists() || project.getFolder(PlatformConstants.DIR_WWW).getFile(PlatformConstants.FILE_XML_CONFIG).exists(); }

Target:
public boolean canConfigure(IProject project, Set<IPath> ignoredDirectories, IProgressMonitor monitor) { return shouldBeAnEclipseProject(project, monitor); }
Source:
public static void cleanupSsoSession( SsoContext ssoContext, SsoSession ssoSession, Set<String> associateClientIds) { try { ssoContext.removeSsoSession(ssoSession.getAccessToken()); HttpSession existingSession = ssoSession.getHttpSession(); if (existingSession == null) { log.debug("No existing Session found for token: {}, cannot invalidate session", ssoSession.getAccessToken()); } else { log.debug("Existing Session found for token: {}, invalidating session", ssoSession.getAccessToken()); existingSession.invalidate(); } invokeAuthnLogout(ssoContext, ssoSession); SsoUtils.notifyClientsOfLogoutEvent(ssoContext, associateClientIds, ssoSession.getAccessToken()); } catch (IllegalStateException ex) { log.debug("Unable to cleanup SsoSession: {}", ex.getMessage()); } catch (Exception ex) { log.error("Unable to cleanup SsoSession: {}", ex.getMessage()); log.debug("Exception", ex); } }

Target:
public static void cleanupSsoSession( SsoContext ssoContext, SsoSession ssoSession, Set<String> associateClientIds) { try { ssoContext.removeSsoSession(ssoSession.getAccessToken()); HttpSession existingSession = ssoSession.getHttpSession(); if (existingSession == null) { log.debug("No existing Session found for token: {}, cannot invalidate session", ssoSession.getAccessToken()); } else { log.debug("Existing Session found for token: {}, invalidating session", ssoSession.getAccessToken()); try { existingSession.invalidate(); } catch (IllegalStateException ex) { log.debug("Unable to cleanup SsoSession: {}", ex.getMessage()); } } invokeAuthnLogout(ssoContext, ssoSession); SsoUtils.notifyClientsOfLogoutEvent(ssoContext, associateClientIds, ssoSession.getAccessToken()); } catch (Exception ex) { log.error("Unable to cleanup SsoSession: {}", ex.getMessage()); log.debug("Exception", ex); } }
Source:
private boolean isCountry(SimpleFeature feature) { return feature .getAttribute(GeoCodingConstants.GEOMETRY_TYPE) .equals(GeoCodingConstants.COUNTRY_TAG); }

Target:
private boolean isCountry(SimpleFeature feature) { return GeoCodingConstants.COUNTRY_TAG.equals( feature.getAttribute(GeoCodingConstants.GEOMETRY_TYPE)); }
Source:
public boolean addFile(File file, URI uri) throws Exception { if (uri == null) uri = file.getCanonicalFile().toURI(); Domain manifest = Domain.domain(file); String mime = BUNDLE_MIME_TYPE; boolean hasIdentity = false; if (manifest != null) hasIdentity = addManifest(manifest); else mime = JAR_MIME_TYPE; String sha256 = SHA256.digest(file) .asHex(); addContentCapability(uri, sha256, file.length(), mime); return hasIdentity; }

Target:
public boolean addFile(File file, URI uri) throws Exception { if (uri == null) uri = file.toURI(); Domain manifest = Domain.domain(file); String mime = BUNDLE_MIME_TYPE; boolean hasIdentity = false; if (manifest != null) hasIdentity = addManifest(manifest); else mime = JAR_MIME_TYPE; String sha256 = SHA256.digest(file) .asHex(); addContentCapability(uri, sha256, file.length(), mime); return hasIdentity; }