auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String getText(IAtsWorkPackage workPackage) { String result = ""; if (workPackage != null) { if (workPackage.getActivityId() != null && workPackage.getActivityName() != null) { result = String.format("%s - %s", workPackage.getActivityId(), workPackage.getActivityName()); } } return result; }

Target:
private String getText(IAtsWorkPackage workPackage) { String result = ""; if (workPackage != null) { String activityId = Strings.isValid(workPackage.getActivityId()) ? workPackage.getActivityId() : ""; String activityName = Strings.isValid(workPackage.getActivityName()) ? workPackage.getActivityName() : ""; result = String.format("%s - %s", activityId, activityName); } return result; }
Source:
public List<StructuredViewer> getViewers() { List<StructuredViewer> viewers = new ArrayList<StructuredViewer>(); IViewPart view = super.getPartForAction(); try { Class<?> clazz = Class.forName("org.eclipse.search2.internal.ui.SearchView"); Method method = clazz.getMethod("getActivePage"); Page page = (Page) method.invoke(view); if (page.getControl() != null) { IWorkbenchSite site = page.getSite(); if (site != null) { ISelectionProvider provider = site.getSelectionProvider(); if (provider instanceof TreeViewer) { viewers.add((TreeViewer) provider); } } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } return viewers; }

Target:
public List<StructuredViewer> getViewers() { List<StructuredViewer> viewers = new ArrayList<StructuredViewer>(); updateCurrentPage(); if (page instanceof AbstractTextSearchViewPage) { try { Method getViewer = AbstractTextSearchViewPage.class.getDeclaredMethod("getViewer"); getViewer.setAccessible(true); StructuredViewer viewer = (StructuredViewer) getViewer.invoke(page); viewers.add(viewer); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } } return viewers; }
Source:
public boolean isAlwaysTrue() { return equiConditions.isEmpty() && allTrueLiteralNonEquiConditions; }

Target:
public boolean isAlwaysTrue() { return isAlwaysTrue; }
Source:
public void testFactoryFailureResultsInErrorEmission() { TestSubscriber<Object> ts = TestSubscriber.create(); final RuntimeException e = new RuntimeException(); Flowable.just(1).collect(new Callable<List<Integer>>() { @Override public List<Integer> call() throws Exception { throw e; } }, new BiConsumer<List<Integer>, Integer>() { @Override public void accept(List<Integer> list, Integer t) { list.add(t); } }).subscribe(ts); ts.assertNoValues(); ts.assertError(e); ts.assertNotComplete(); }

Target:
public void testFactoryFailureResultsInErrorEmission() { final RuntimeException e = new RuntimeException(); Flowable.just(1).collect(new Callable<List<Integer>>() { @Override public List<Integer> call() throws Exception { throw e; } }, new BiConsumer<List<Integer>, Integer>() { @Override public void accept(List<Integer> list, Integer t) { list.add(t); } }) .test() .assertNoValues() .assertError(e) .assertNotComplete(); }
Source:
private void parsePath(String path) { if (path == null || path.length() == 0 || path.charAt(0) != '/') { throw new IllegalArgumentException("URL path \"" + path + "\" on method " + method.getName() + " must start with '/'. (" + method.getName() + ")"); } String url = path; String query = null; int question = path.indexOf('?'); if (question != -1 && question < path.length() - 1) { url = path.substring(0, question); query = path.substring(question + 1); hasQueryParams = true; Matcher queryMatcher = PATH_PARAMETERS.matcher(query); if (queryMatcher.find()) { List<String> matches = new ArrayList<String>(); do { matches.add("{" + queryMatcher.group(1) + "}"); } while (queryMatcher.find()); throw new IllegalStateException("URL query string \"" + query + "\" on method " + method.getName() + " may not have replace block. Found: " + matches); } } Set<String> urlParams = parsePathParameters(path); requestUrl = url; requestUrlParamNames = urlParams; requestQuery = query; }

Target:
private void parsePath(String path) { if (path == null || path.length() == 0 || path.charAt(0) != '/') { throw new IllegalArgumentException("URL path \"" + path + "\" on method " + method.getName() + " must start with '/'. (" + method.getName() + ")"); } String url = path; String query = null; int question = path.indexOf('?'); if (question != -1 && question < path.length() - 1) { url = path.substring(0, question); query = path.substring(question + 1); hasQueryParams = true; Matcher queryParamMatcher = URL_PARAMETERS.matcher(query); if (queryParamMatcher.find()) { throw new IllegalStateException("URL query string \"" + query + "\" on method " + method.getName() + " may not have replace block."); } } Set<String> urlParams = parsePathParameters(path); requestUrl = url; requestUrlParamNames = urlParams; requestQuery = query; }
Source:
static Map<String, List<String>> findQueryParamsGroupedByName(HttpServletRequest request) { Map<String, List<String>> result = new HashMap<>(); String query = request.getQueryString(); if (StringUtils.isEmpty(query)) { return result; } for (String value : StringUtils.tokenizeToStringArray(query, "&")) { if (value.contains("=")) { String key = value.substring(0, value.indexOf("=")); value = value.substring(value.indexOf("=") + 1, value.length()); if (!result.containsKey(key)) { ArrayList<String> listOfQueryValues = new ArrayList<>(); listOfQueryValues.add(value); result.put(key, listOfQueryValues); } else { result.get(key).add(value); } } } return result; }

Target:
static Map<String, List<String>> findQueryParamsGroupedByName( HttpServletRequest request) { String query = request.getQueryString(); if (isEmpty(query)) { return emptyMap(); } return UriComponentsBuilder.fromUriString("?" + query).build().getQueryParams(); }
Source:
public void testIsQuestionAnswered() { FeedbackQuestionAttributes question; ______TS("test question is answered by user"); question = getQuestionFromDatastore("qn1InSession1InCourse1"); try { assertTrue(fqLogic.isQuestionAnsweredByUser(question, "student1InCourse1@gmail.com")); } catch (EntityDoesNotExistException e) { signalDetectionOfWrongException(e.getMessage()); } try { assertFalse(fqLogic.isQuestionAnsweredByUser(question, "studentWithNoResponses@gmail.com")); } catch (EntityDoesNotExistException e) { signalDetectionOfWrongException(e.getMessage()); } List<FeedbackResponseAttributes> responses = new ArrayList<FeedbackResponseAttributes>(); assertFalse(fqLogic.isQuestionAnsweredByUser(question, "student1InCourse1@gmail.com", responses)); responses = frLogic.getFeedbackResponsesForQuestion(question.getId()); assertTrue(fqLogic.isQuestionAnsweredByUser(question, "student2InCourse1@gmail.com", responses)); ______TS("test question is fully answered by user"); try { assertTrue(fqLogic.isQuestionFullyAnsweredByUser(question, "student1InCourse1@gmail.com")); } catch (EntityDoesNotExistException e) { signalDetectionOfWrongException(e.getMessage()); } try { assertFalse(fqLogic.isQuestionFullyAnsweredByUser(question, "studentWithNoResponses@gmail.com")); } catch (EntityDoesNotExistException e) { signalDetectionOfWrongException(e.getMessage()); } ______TS("test question is fully answered by team"); try { assertFalse(fqLogic.isQuestionFullyAnsweredByTeam(question, "Team 1.1")); } catch (EntityDoesNotExistException e) { signalDetectionOfWrongException(e.getMessage()); } }

Target:
public void testIsQuestionAnswered() throws Exception { FeedbackQuestionAttributes question; ______TS("test question is answered by user"); question = getQuestionFromDatastore("qn1InSession1InCourse1"); assertTrue(fqLogic.isQuestionAnsweredByUser(question, "student1InCourse1@gmail.com")); assertFalse(fqLogic.isQuestionAnsweredByUser(question, "studentWithNoResponses@gmail.com")); List<FeedbackResponseAttributes> responses = new ArrayList<FeedbackResponseAttributes>(); assertFalse(fqLogic.isQuestionAnsweredByUser(question, "student1InCourse1@gmail.com", responses)); responses = frLogic.getFeedbackResponsesForQuestion(question.getId()); assertTrue(fqLogic.isQuestionAnsweredByUser(question, "student2InCourse1@gmail.com", responses)); ______TS("test question is fully answered by user"); assertTrue(fqLogic.isQuestionFullyAnsweredByUser(question, "student1InCourse1@gmail.com")); assertFalse(fqLogic.isQuestionFullyAnsweredByUser(question, "studentWithNoResponses@gmail.com")); ______TS("test question is fully answered by team"); assertFalse(fqLogic.isQuestionFullyAnsweredByTeam(question, "Team 1.1")); }
Source:
public boolean evalToNullIfParamIsNull(StatementContext context, int index) throws SQLException { return false; }

Target:
public boolean evalToNullIfParamIsNull(StatementContext context, int index) throws SQLException { return index == 0; }
Source:
public static UserLayer createUserLayer(SimpleFeatureCollection fc, String uuid, String name, String desc, String source) throws FactoryException, TransformException { final SimpleFeatureType ft = fc.getSchema(); final UserLayer userLayer = new UserLayer(); userLayer.setUuid(uuid); userLayer.setLayer_name(ConversionHelper.getString(name, ft.getTypeName())); userLayer.setLayer_desc(ConversionHelper.getString(desc, "")); userLayer.setLayer_source(ConversionHelper.getString(source, "")); userLayer.setFields(parseFields(ft)); userLayer.setWkt(getWGS84ExtentAsWKT(fc)); return userLayer; }

Target:
public static UserLayer createUserLayer(SimpleFeatureCollection fc, String uuid, String name, String desc, String source) { final SimpleFeatureType ft = fc.getSchema(); final UserLayer userLayer = new UserLayer(); userLayer.setUuid(uuid); userLayer.setLayer_name(ConversionHelper.getString(name, ft.getTypeName())); userLayer.setLayer_desc(ConversionHelper.getString(desc, "")); userLayer.setLayer_source(ConversionHelper.getString(source, "")); userLayer.setFields(parseFields(ft)); userLayer.setWkt(getWGS84ExtentAsWKT(fc)); return userLayer; }
Source:
public boolean tryAdvance(Consumer<? super Map<Address, CacheEntry<K, V>>> action) { while (!iterator.hasNext()) { if (nextSegment < totalSegments) { try { if (trace) log.tracef("Cache %s Attempting to receive all replicas for segment %s with topology %s", cacheName, nextSegment, topology); segmentRequestFuture = stateReceiver.getAllReplicasForSegment(nextSegment, topology); long remainingTime = timeService.remainingTime(endTime, TimeUnit.MILLISECONDS); List<Map<Address, CacheEntry<K, V>>> segmentEntries = segmentRequestFuture.get(remainingTime, TimeUnit.MILLISECONDS); if (trace) log.tracef("Cache %s Segment %s entries received: %s", cacheName, nextSegment, segmentEntries); nextSegment++; iterator = segmentEntries.iterator(); } catch (CancellationException e) { handleException(e); return false; } catch (InterruptedException e) { handleException(e); stateReceiver.stop(); Thread.currentThread().interrupt(); throw new CacheException(e); } catch (ExecutionException | TimeoutException e) { handleException(e); Throwable cause = e.getCause(); throw new CacheException(e.getMessage(), cause != null ? cause : e); } } else { streamInProgress.compareAndSet(true, false); return false; } } action.accept(iterator.next()); return true; }

Target:
public boolean tryAdvance(Consumer<? super Map<Address, CacheEntry<K, V>>> action) { while (!iterator.hasNext()) { if (nextSegment < totalSegments) { try { if (trace) log.tracef("Cache %s attempting to receive all replicas for segment %s with topology %s", cacheName, nextSegment, topology); segmentRequestFuture = stateReceiver.getAllReplicasForSegment(nextSegment, topology); long remainingTime = timeService.remainingTime(endTime, TimeUnit.MILLISECONDS); List<Map<Address, CacheEntry<K, V>>> segmentEntries = segmentRequestFuture.get(remainingTime, TimeUnit.MILLISECONDS); if (trace) log.tracef("Cache %s segment %s entries received: %s", cacheName, nextSegment, segmentEntries); nextSegment++; iterator = segmentEntries.iterator(); } catch (CancellationException e) { handleException(e); return false; } catch (InterruptedException e) { handleException(e); Thread.currentThread().interrupt(); throw new CacheException(e); } catch (ExecutionException | TimeoutException e) { handleException(e); Throwable cause = e.getCause(); throw new CacheException(e.getMessage(), cause != null ? cause : e); } } else { streamInProgress.compareAndSet(true, false); return false; } } action.accept(iterator.next()); return true; }
Source:
public void userPrivateRole() { RealmResults<PermissionUser> permissionUsers = realm.where(PermissionUser.class).findAll(); assertEquals(1, permissionUsers.size()); PermissionUser permissionUser = permissionUsers.get(0); assertNotNull(permissionUser); Role role = permissionUser.getRole(); assertNotNull(role); assertEquals("__User:" + user.getIdentity(), role.getName()); assertTrue(role.hasMember(user.getIdentity())); }

Target:
public void userPrivateRole() { RealmResults<PermissionUser> permissionUsers = realm.where(PermissionUser.class).findAll(); assertEquals(1, permissionUsers.size()); PermissionUser permissionUser = permissionUsers.get(0); assertNotNull(permissionUser); Role role = permissionUser.getPrivateRole(); assertNotNull(role); assertEquals("__User:" + user.getIdentity(), role.getName()); assertTrue(role.hasMember(user.getIdentity())); }
Source:
private IRadio getRadioProxy(Message result) { if (!mIsMobileNetworkSupported) { riljLog("Not calling getService(): wifi-only"); return null; } if (mRadioProxy != null) { return mRadioProxy; } try { mRadioProxy = IRadio.getService(SOCKET_NAME_RIL[mPhoneId == null ? 0 : mPhoneId]); if (mRadioProxy != null) { mRadioProxy.linkToDeath(mRadioProxyDeathRecipient, mRadioProxyCookie.incrementAndGet()); mRadioProxy.setResponseFunctions(mRadioResponse, mRadioIndication); } else { riljLoge("getRadioProxy: radioProxy == null"); } } catch (RemoteException | RuntimeException e) { mRadioProxy = null; if (result != null) { AsyncResult.forMessage(result, null, CommandException.fromRilErrno(RADIO_NOT_AVAILABLE)); result.sendToTarget(); } mRilHandler.sendMessageDelayed( mRilHandler.obtainMessage(EVENT_RADIO_PROXY_DEAD, mRadioProxyCookie.get()), IRADIO_GET_SERVICE_DELAY_MILLIS); riljLoge("setResponseFunctions", e); } return mRadioProxy; }

Target:
private IRadio getRadioProxy(Message result) { if (!mIsMobileNetworkSupported) { if (RILJ_LOGV) riljLog("Not calling getService(): wifi-only"); return null; } if (mRadioProxy != null) { return mRadioProxy; } try { mRadioProxy = IRadio.getService(SOCKET_NAME_RIL[mPhoneId == null ? 0 : mPhoneId]); if (mRadioProxy != null) { mRadioProxy.linkToDeath(mRadioProxyDeathRecipient, mRadioProxyCookie.incrementAndGet()); mRadioProxy.setResponseFunctions(mRadioResponse, mRadioIndication); } else { riljLoge("getRadioProxy: radioProxy == null"); } } catch (RemoteException | RuntimeException e) { mRadioProxy = null; if (result != null) { AsyncResult.forMessage(result, null, CommandException.fromRilErrno(RADIO_NOT_AVAILABLE)); result.sendToTarget(); } mRilHandler.sendMessageDelayed( mRilHandler.obtainMessage(EVENT_RADIO_PROXY_DEAD, mRadioProxyCookie.get()), IRADIO_GET_SERVICE_DELAY_MILLIS); riljLoge("setResponseFunctions", e); } return mRadioProxy; }
Source:
Configurer(Config config) { ConditionUtility.notNull(config); this.config = config; }

Target:
Configurer(Config config) { Objects.requireNonNull(config); this.config = config; }
Source:
public void initTestAggregationFunction() { typeRegistry = new TypeRegistry(); functionManager = new FunctionManager(typeRegistry, new BlockEncodingManager(typeRegistry), new FeaturesConfig()); session = testSessionBuilder().build(); }

Target:
public final void initTestAggregationFunction() { typeRegistry = new TypeRegistry(); functionManager = new FunctionManager(typeRegistry, new BlockEncodingManager(typeRegistry), new FeaturesConfig()); }
Source:
private void applySessionToken(RxDocumentServiceRequest request) { Map<String, String> headers = request.getHeaders(); Objects.requireNonNull(headers, "RxDocumentServiceRequest::headers is required and cannot be null"); String requestConsistencyLevel = headers.get(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL); boolean sessionTokenApplicable = Strings.areEqualIgnoreCase(requestConsistencyLevel, ConsistencyLevel.SESSION.toString()) || (this.defaultConsistencyLevel == ConsistencyLevel.SESSION && (!request.isReadOnlyRequest() || request.getResourceType() != ResourceType.Document || !Strings.areEqualIgnoreCase(requestConsistencyLevel, ConsistencyLevel.EVENTUAL.toString()))); if (!Strings.isNullOrEmpty(request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN))) { if (!sessionTokenApplicable || ReplicatedResourceClientUtils.isMasterResource(request.getResourceType())) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } return; } if (!sessionTokenApplicable || ReplicatedResourceClientUtils.isMasterResource(request.getResourceType())) { return; } String sessionToken = this.sessionContainer.resolveGlobalSessionToken(request); if (!Strings.isNullOrEmpty(sessionToken)) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionToken); } }

Target:
private void applySessionToken(RxDocumentServiceRequest request) { Map<String, String> headers = request.getHeaders(); Objects.requireNonNull(headers, "RxDocumentServiceRequest::headers is required and cannot be null"); String requestConsistencyLevel = headers.get(HttpConstants.HttpHeaders.CONSISTENCY_LEVEL); boolean sessionTokenApplicable = Strings.areEqual(requestConsistencyLevel, ConsistencyLevel.SESSION.toString()) || (this.defaultConsistencyLevel == ConsistencyLevel.SESSION && (!request.isReadOnlyRequest() || request.getResourceType() != ResourceType.Document || !Strings.areEqual(requestConsistencyLevel, ConsistencyLevel.EVENTUAL.toString()))); if (!Strings.isNullOrEmpty(request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN))) { if (!sessionTokenApplicable || ReplicatedResourceClientUtils.isMasterResource(request.getResourceType())) { request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN); } return; } if (!sessionTokenApplicable || ReplicatedResourceClientUtils.isMasterResource(request.getResourceType())) { return; } String sessionToken = this.sessionContainer.resolveGlobalSessionToken(request); if (!Strings.isNullOrEmpty(sessionToken)) { headers.put(HttpConstants.HttpHeaders.SESSION_TOKEN, sessionToken); } }
Source:
public void getOrderHistoryByConcept_shouldReturnOrdersWithTheGivenConcept() throws Exception { Concept concept = Context.getConceptService().getConcept(88); Patient patient = Context.getPatientService().getPatient(2); List<Order> orders = Context.getOrderService().getOrderHistoryByConcept(patient, concept); Assert.assertEquals(3, orders.size()); for (Order order : orders) Assert.assertTrue(order.getOrderId() == 4 || order.getOrderId() == 5 || order.getOrderId() == 444); concept = Context.getConceptService().getConcept(792); orders = Context.getOrderService().getOrderHistoryByConcept(patient, concept); Assert.assertEquals(3, orders.size()); for (Order order : orders) Assert.assertTrue(order.getOrderId() == 2 || order.getOrderId() == 3 || order.getOrderId() == 222); }

Target:
public void getOrderHistoryByConcept_shouldReturnOrdersWithTheGivenConcept() throws Exception { Concept concept = Context.getConceptService().getConcept(88); Patient patient = Context.getPatientService().getPatient(2); List<Order> orders = Context.getOrderService().getOrderHistoryByConcept(patient, concept); Assert.assertEquals(3, orders.size()); Assert.assertTrue(orders.get(0).getOrderId() == 5); Assert.assertTrue(orders.get(1).getOrderId() == 4); Assert.assertTrue(orders.get(2).getOrderId() == 444); concept = Context.getConceptService().getConcept(792); orders = Context.getOrderService().getOrderHistoryByConcept(patient, concept); Assert.assertEquals(3, orders.size()); Assert.assertTrue(orders.get(0).getOrderId() == 3); Assert.assertTrue(orders.get(1).getOrderId() == 2); Assert.assertTrue(orders.get(2).getOrderId() == 222); }
Source:
public void setHeader(Widget widget) { widget.addStyleName("obrand_dialogHeaderTitleElement"); headerTitlePanel.insert(widget, 0); }

Target:
public void setHeader(Widget widget) { widget.addStyleName(style.obrand_dialogHeaderTitleElement()); headerTitlePanel.insert(widget, 0); }
Source:
public Limit(@Nonnull final Long limit, final Operator child) { super(child); this.limit = Objects.requireNonNull(limit, "limit"); Preconditions.checkArgument(limit >= 0L, "limit must be non-negative"); toEmit = this.limit; done = false; }

Target:
public Limit(@Nonnull final Long limit, final Operator child) { super(child); this.limit = Objects.requireNonNull(limit, "limit"); Preconditions.checkArgument(limit >= 0L, "limit must be non-negative"); toEmit = this.limit; }
Source:
public void testLoginValidUserAndPasswordButNotAuthorisedToSendNonPersistent() throws Exception { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616"); connectionFactory.setConfirmationWindowSize(100); connectionFactory.setBlockOnDurableSend(false); connectionFactory.setBlockOnNonDurableSend(false); Connection connection = connectionFactory.createConnection("guest", "guest"); Session session = connection.createSession(); Destination destination = session.createQueue("guest.cannot.send"); MessageProducer messageProducer = session.createProducer(destination); messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); try { AtomicReference<Exception> e = new AtomicReference<>(); CountDownLatch countDownLatch = new CountDownLatch(1); messageProducer.send(session.createTextMessage("hello"), new CompletionListener() { @Override public void onCompletion(Message message) { countDownLatch.countDown(); } @Override public void onException(Message message, Exception exception) { countDownLatch.countDown(); e.set(exception); } }); countDownLatch.await(10, TimeUnit.SECONDS); if (e.get() != null) { throw e.get(); } fail("JMSSecurityException expected as guest is not allowed to send"); } catch (JMSSecurityException activeMQSecurityException) { activeMQSecurityException.printStackTrace(); } connection.close(); }

Target:
public void testLoginValidUserAndPasswordButNotAuthorisedToSendNonPersistent() throws Exception { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://localhost:61616"); connectionFactory.setConfirmationWindowSize(100); connectionFactory.setBlockOnDurableSend(false); connectionFactory.setBlockOnNonDurableSend(false); Connection connection = connectionFactory.createConnection("guest", "guest"); Session session = connection.createSession(); Destination destination = session.createQueue("guest.cannot.send"); MessageProducer messageProducer = session.createProducer(destination); messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); try { AtomicReference<Exception> e = new AtomicReference<>(); CountDownLatch countDownLatch = new CountDownLatch(1); messageProducer.send(session.createTextMessage("hello"), new CompletionListener() { @Override public void onCompletion(Message message) { countDownLatch.countDown(); } @Override public void onException(Message message, Exception exception) { e.set(exception); countDownLatch.countDown(); } }); countDownLatch.await(10, TimeUnit.SECONDS); if (e.get() != null) { throw e.get(); } fail("JMSSecurityException expected as guest is not allowed to send"); } catch (JMSSecurityException activeMQSecurityException) { activeMQSecurityException.printStackTrace(); } connection.close(); }
Source:
private WeekActivityOverviewDto getWeekActivityOverview(UUID userAnonymizedId, LocalDate earliestPossibleDate, LocalDate date, Set<IntervalInactivityDto> missingInactivities) { Interval interval = Interval.createWeekInterval(date); assertDateNotTooEarly(earliestPossibleDate, interval.endDate); UserAnonymizedDto userAnonymized = userAnonymizedService.getUserAnonymized(userAnonymizedId); List<WeekActivityOverviewDto> weekActivityOverviews = getWeekActivityOverviews(userAnonymizedId, earliestPossibleDate, missingInactivities, userAnonymized, interval); return weekActivityOverviews.get(0); }

Target:
private WeekActivityOverviewDto getWeekActivityOverview(UUID userAnonymizedId, LocalDate earliestPossibleDate, LocalDate date, Set<IntervalInactivityDto> missingInactivities) { Interval interval = Interval.createWeekInterval(date); assertDateNotTooEarly(interval.endDate, earliestPossibleDate); UserAnonymizedDto userAnonymized = userAnonymizedService.getUserAnonymized(userAnonymizedId); List<WeekActivityOverviewDto> weekActivityOverviews = getWeekActivityOverviews(userAnonymizedId, earliestPossibleDate, missingInactivities, userAnonymized, interval); return weekActivityOverviews.get(0); }
Source:
private void addGlusterVolumeBricks(List<GlusterBrickEntity> bricksList, int replicaCount, int stripeCount, boolean force) { VDSReturnValue returnValue = Backend.getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.AddBricksToGlusterVolume, new GlusterVolumeBricksActionVDSParameters(upServer.getId(), getGlusterVolumeName(), bricksList, replicaCount, stripeCount, force)); setSucceeded(returnValue.getSucceeded()); if (getSucceeded()) { addCustomValue(GlusterConstants.NO_OF_BRICKS, String.valueOf(bricksList.size())); addGlusterVolumeBricksInDb(bricksList, replicaCount, stripeCount); logAuditMessages(bricksList); getReturnValue().setActionReturnValue(getBrickIds(bricksList)); } else { handleVdsError(AuditLogType.GLUSTER_VOLUME_ADD_BRICK_FAILED, returnValue.getVdsError().getMessage()); return; } }

Target:
private void addGlusterVolumeBricks(List<GlusterBrickEntity> bricksList, int replicaCount, int stripeCount, boolean force) { VDSReturnValue returnValue = Backend.getInstance() .getResourceManager() .RunVdsCommand(VDSCommandType.AddBricksToGlusterVolume, new GlusterVolumeBricksActionVDSParameters(upServer.getId(), getGlusterVolumeName(), bricksList, replicaCount, stripeCount, upServer.getVdsGroupCompatibilityVersion(), force)); setSucceeded(returnValue.getSucceeded()); if (getSucceeded()) { addCustomValue(GlusterConstants.NO_OF_BRICKS, String.valueOf(bricksList.size())); addGlusterVolumeBricksInDb(bricksList, replicaCount, stripeCount); logAuditMessages(bricksList); getReturnValue().setActionReturnValue(getBrickIds(bricksList)); } else { handleVdsError(AuditLogType.GLUSTER_VOLUME_ADD_BRICK_FAILED, returnValue.getVdsError().getMessage()); return; } }
Source:
AnnotatedNoRouteToHostException(NoRouteToHostException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); }

Target:
AnnotatedNoRouteToHostException(NoRouteToHostException exception, SocketAddress remoteAddress) { super(exception.getMessage() + ": " + remoteAddress); initCause(exception); }
Source:
public void removeContentFromIndexByStructureInode(final String structureInode) throws DotDataException { final String structureName = CacheLocator.getContentTypeCache().getStructureByInode(structureInode).getVelocityVarName(); final IndiciesInfo info = APILocator.getIndiciesAPI().loadIndicies(); final List<String> idxs = new ArrayList<String>(); idxs.add(info.working); idxs.add(info.live); if (info.reindex_working != null) idxs.add(info.reindex_working); if (info.reindex_live != null) idxs.add(info.reindex_live); String[] idxsArr = new String[idxs.size()]; idxsArr = idxs.toArray(idxsArr); final BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(new ESClient().getClient()) .filter(QueryBuilders.matchQuery("contenttype",structureName.toLowerCase())).source(idxsArr).get(); Logger.info(this, "Records deleted: " + response.getDeleted() + " from contentType: " + structureName); }

Target:
public void removeContentFromIndexByStructureInode(final String structureInode) throws DotDataException, DotSecurityException { final ContentType contentType = APILocator.getContentTypeAPI(APILocator.getUserAPI().getSystemUser()).find(structureInode); if(contentType==null){ throw new DotDataException("ContentType with Inode or VarName: " + structureInode + "not found"); } final String structureName = contentType.variable(); final IndiciesInfo info = APILocator.getIndiciesAPI().loadIndicies(); final List<String> idxs = new ArrayList<String>(); idxs.add(info.working); idxs.add(info.live); if (info.reindex_working != null) idxs.add(info.reindex_working); if (info.reindex_live != null) idxs.add(info.reindex_live); String[] idxsArr = new String[idxs.size()]; idxsArr = idxs.toArray(idxsArr); final BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(new ESClient().getClient()) .filter(QueryBuilders.matchQuery("contenttype",structureName.toLowerCase())).source(idxsArr).get(); Logger.info(this, "Records deleted: " + response.getDeleted() + " from contentType: " + structureName); }
Source:
public void test_equality() { String uuid = RandomStringUtils.randomAlphanumeric(35); Date date = new Date(new Random().nextLong()); assertThat(new Analysis(uuid, date)).isEqualTo(new Analysis(uuid, date)); assertThat(new Analysis(uuid, date).hashCode()).isEqualTo(new Analysis(uuid, date).hashCode()); assertThat(new Analysis(uuid, date)).isNotEqualTo(null); assertThat(new Analysis(uuid, date)).isNotEqualTo(new Analysis(uuid + "1", date)); assertThat(new Analysis(uuid, date).hashCode()).isNotEqualTo(new Analysis(uuid + "1", date).hashCode()); assertThat(new Analysis(uuid, date)).isNotEqualTo(new Analysis(uuid, new Date(date.getTime() + 1_000))); assertThat(new Analysis(uuid, date).hashCode()).isNotEqualTo(new Analysis(uuid, new Date(date.getTime() + 1_000)).hashCode()); assertThat(new Analysis(uuid, date).getUuid()).isEqualTo(uuid); assertThat(new Analysis(uuid, date).getDate()).isEqualTo(date); }

Target:
public void test_equality() { String uuid = randomAlphanumeric(35); Date date = new Date(new Random().nextLong()); Analysis underTest = new Analysis(uuid, date); assertThat(underTest).isEqualTo(underTest); assertThat(underTest.getUuid()).isEqualTo(uuid); assertThat(underTest.getDate()).isEqualTo(date); assertThat(underTest).isNotEqualTo(null); assertThat(underTest).isNotEqualTo(new Analysis(uuid + "1", date)); assertThat(underTest).isNotEqualTo(new Analysis(uuid, new Date(date.getTime() + 1_000))); }
Source:
public void justTheHeaderIfNoInput() { Tournament tournament = new Tournament(); assertEquals("Team | MP | W | D | L | P", tournament.printTable()); }

Target:
public void justTheHeaderIfNoInput() { assertEquals("Team | MP | W | D | L | P\n", tournament.printTable()); }
Source:
public void mergeLots(final Integer userId, final Integer keepLotId, final LotsSearchDto lotsSearchDto) { List<ExtendedLotDto> extendedLotDtos = this.searchLots(lotsSearchDto, null).stream() .filter(extendedLotDto -> extendedLotDto.getLotId().intValue() != keepLotId.intValue()) .collect(Collectors.toList()); extendedLotDtos.stream() .forEach(extendedLotDto -> { final Transaction transaction = new Transaction(TransactionType.DEPOSIT, TransactionStatus.CONFIRMED, userId, null, keepLotId, extendedLotDto.getActualBalance()); transaction.setSourceType(TransactionSourceType.MERGED_LOT.name()); transaction.setSourceId(extendedLotDto.getLotId()); daoFactory.getTransactionDAO().save(transaction); }); List<Integer> lotIds = extendedLotDtos.stream() .map(ExtendedLotDto::getLotId).collect(Collectors.toList()); this.closeLots(userId, lotIds); }

Target:
public void mergeLots(final Integer userId, final Integer keepLotId, final LotsSearchDto lotsSearchDto) { final List<ExtendedLotDto> extendedLotDtos = this.searchLots(lotsSearchDto, null).stream() .filter(extendedLotDto -> extendedLotDto.getLotId().intValue() != keepLotId.intValue()) .collect(Collectors.toList()); extendedLotDtos.stream() .forEach(extendedLotDto -> { final Transaction transaction = new Transaction(TransactionType.DEPOSIT, TransactionStatus.CONFIRMED, userId, null, keepLotId, extendedLotDto.getActualBalance()); transaction.setSourceType(TransactionSourceType.MERGED_LOT.name()); transaction.setSourceId(extendedLotDto.getLotId()); daoFactory.getTransactionDAO().save(transaction); }); final List<Integer> lotIds = extendedLotDtos.stream() .map(ExtendedLotDto::getLotId).collect(Collectors.toList()); this.closeLots(userId, lotIds); }
Source:
private IntegrationMimeMessage(MimeMessage source) throws MessagingException { super(source); this.source = source; if (AbstractMailReceiver.this.simpleContent) { this.content = null; } else { Object complexContent; try { complexContent = source.getContent(); } catch (IOException e) { complexContent = "Unable to extract content; see logs: " + e.getMessage(); AbstractMailReceiver.this.logger.error("Failed to extract content from " + source, e); } this.content = complexContent; } }

Target:
private IntegrationMimeMessage(MimeMessage source) throws MessagingException { super(source); this.source = source; if (AbstractMailReceiver.this.simpleContent) { this.content = null; } else { Object complexContent; try { complexContent = source.getContent(); } catch (IOException e) { throw new MessagingException("IOException while extracting content", e); } this.content = complexContent; } }
Source:
private static void handleConsoleMessage(TaskListener listener, boolean isValidCommand, String path) { boolean isValidPath = false; isValidPath = path!=null && (path.isEmpty() || path.equals("accurev")); if(isValidCommand && isValidPath) { listener.getLogger().println( String.format( "No AccuRev tool configured, using default" ) ); } }

Target:
private static void handleConsoleMessage(TaskListener listener, boolean isValidCommand, String path) { boolean isValidPath = false; isValidPath = (path != null && (path.isEmpty() || path.equals("accurev"))); if (isValidCommand && isValidPath) { listener.getLogger().println("No AccuRev tool configured, using default"); } }
Source:
public Set<String> getUncommittedChanges() { Set<String> uncommittedChanges = new HashSet<String>(); uncommittedChanges.addAll(diff.getAdded()); uncommittedChanges.addAll(diff.getChanged()); uncommittedChanges.addAll(diff.getRemoved()); uncommittedChanges.addAll(diff.getMissing()); uncommittedChanges.addAll(diff.getMissing()); uncommittedChanges.addAll(diff.getConflicting()); return uncommittedChanges; }

Target:
public Set<String> getUncommittedChanges() { Set<String> uncommittedChanges = new HashSet<String>(); uncommittedChanges.addAll(diff.getAdded()); uncommittedChanges.addAll(diff.getChanged()); uncommittedChanges.addAll(diff.getRemoved()); uncommittedChanges.addAll(diff.getMissing()); uncommittedChanges.addAll(diff.getModified()); uncommittedChanges.addAll(diff.getConflicting()); return uncommittedChanges; }
Source:
protected void done() { List<MiniTimelineResult> results = null; if (!isCancelled()) { try { results = get(); } catch (InterruptedException | ExecutionException ex) { logger.log(Level.SEVERE, "Exception while trying to get list of artifacts for Domain details for mini timeline view for domain: " + domain, ex); } catch (CancellationException ignored) { } } if (results == null) { results = new ArrayList<>(); } DiscoveryEventUtils.getDiscoveryEventBus().post(new DiscoveryEventUtils.MiniTimelineResultEvent(results)); }

Target:
protected void done() { List<MiniTimelineResult> results = new ArrayList<>(); if (!isCancelled()) { try { results.addAll(get()); DiscoveryEventUtils.getDiscoveryEventBus().post(new DiscoveryEventUtils.MiniTimelineResultEvent(results)); } catch (InterruptedException | ExecutionException ex) { logger.log(Level.SEVERE, "Exception while trying to get list of artifacts for Domain details for mini timeline view for domain: " + domain, ex); } catch (CancellationException ignored) { } } }
Source:
public boolean reserveSeatForTicket(String groupname, int seatnumber, Long ticketId) { Ticket ticket = ticketRepository.findOne(ticketId); Seat seat = seatRespository.findBySeatGroupAndSeatNumber(groupname, seatnumber); if (!seat.isTaken()) { seat.setTicket(ticket); seatRespository.saveAndFlush(seat); return true; } else { return false; } }

Target:
public boolean reserveSeatForTicket(String groupname, int seatnumber, Long ticketId) { Ticket ticket = ticketRepository.findOne(ticketId); synchronized (seatReservationLock) { Seat seat = seatRepository.findBySeatGroupAndSeatNumber(groupname, seatnumber); if (!seat.isTaken()) { seat.setTicket(ticket); seatRepository.saveAndFlush(seat); return true; } else { return false; } } }
Source:
private List<Action> handleChangesCanceled(Session session, Resource resource, ResourceStatus newStatus) { final List<Action> actions = Lists.newArrayList(); actions.add(Action.RELOAD); return actions; }

Target:
private List<Action> handleChangesCanceled(Session session, Resource resource, ResourceStatus newStatus) { return Arrays.asList(Action.RELOAD); }
Source:
private void checkTransformMethods(ASTMethodDeclaration node, Object data, String nameOfMethod) { ASTResultType resultType = node.getResultType(); if (nameOfMethod.contains("To") && resultType.isVoid()) { addViolation(data, node); } else if (hasPrefix(nameOfMethod, "to") && resultType.isVoid()) { addViolation(data, node); } }

Target:
private void checkTransformMethods(ASTMethodDeclaration node, Object data, String nameOfMethod) { ASTResultType resultType = node.getResultType(); if (resultType.isVoid() && containsWord(nameOfMethod, "To")) { addViolationWithMessage(data, node, "Linguistics Antipattern - The transform method ''{0}'' should not return void linguistically", new Object[] { nameOfMethod }); } }
Source:
public Map<String, Object> aliveness(String vhost) { URI uri = UriComponentsBuilder.fromUriString(this.baseUri).pathSegment("aliveness-test", "{vhost}") .buildAndExpand(vhost).encode().toUri(); return this.restTemplate.getForObject(uri, Map.class); }

Target:
public Map<String, Object> aliveness(String vhost) throws HttpClientErrorException { URI uri = UriComponentsBuilder.fromUriString(this.baseUri).pathSegment("aliveness-test", "{vhost}") .buildAndExpand(vhost).encode().toUri(); return this.restTemplate.getForObject(uri, Map.class); }
Source:
public SortedMap<Long, String> getPurgeFileVersionSettings() { if (purgeFileVersionSettings == null) { purgeFileVersionSettings = new TreeMap<Long, String>(); purgeFileVersionSettings.put(30L * 24L * 3600L, "DD"); purgeFileVersionSettings.put(3L * 24L * 3600L, "HH"); purgeFileVersionSettings.put(3600L, "MI"); } return purgeFileVersionSettings; }

Target:
public SortedMap<Long, TimeUnit> getPurgeFileVersionSettings() { return purgeFileVersionSettings; }
Source:
public void toLastCommitted() { long offset = offsetTracker.getLastCommittedOffset(); if (offset > 0) { log.debug(String.format("toLastCommitted: %s, found: %d", id, offset)); if (!cqTailer.moveToIndex(offset) && cqTailer.index() != offset) { toStart(); long startOffset = cqTailer.index(); if (offset < startOffset) { log.error("The last committed offset " + offset + " for tailer " + this + " points to a record that has been deleted by the retention policy." + " Records have been lost, continuing from the beginning of the partition offset: " + startOffset); } else { throw new IllegalStateException( "Unable to move to the last committed offset" + offset + " for tailer " + this); } } } else { log.debug(String.format("toLastCommitted: %s, not found, move toStart", id)); cqTailer.toStart(); } }

Target:
public void toLastCommitted() { long offset = offsetTracker.getLastCommittedOffset(); if (offset > 0) { log.debug(String.format("toLastCommitted: %s, found: %d", id, offset)); if (!cqTailer.moveToIndex(offset) && cqTailer.index() != offset) { toStart(); long startOffset = cqTailer.index(); if (offset < startOffset) { log.error("The last committed offset: " + offset + " for tailer: " + this + " points to a record that has been deleted by the retention policy." + " Records have been lost, continuing from the beginning of the partition offset: " + startOffset); } else { throw new IllegalStateException( "Unable to move to the last committed offset: " + offset + " for tailer: " + this); } } } else { log.debug(String.format("toLastCommitted: %s, not found, move toStart", id)); cqTailer.toStart(); } }
Source:
protected void resetDocks() { abstractScenarioSimulationDocksHandler.getSettingsPresenter().ifPresent(SubDockView.Presenter::reset); abstractScenarioSimulationDocksHandler.getCheatSheetPresenter().ifPresent(SubDockView.Presenter::reset); abstractScenarioSimulationDocksHandler.getTestToolsPresenter().ifPresent(SubDockView.Presenter::reset); scenarioSimulationEditorWrapper.resetAdditionalDocks(); }

Target:
protected void resetDocks() { abstractScenarioSimulationDocksHandler.resetDocks(); }
Source:
protected void attemptTransition( final ExecutionContext executionContext ) throws RetryableTransitionException, FatalTransitionException { final File jobDirectory = executionContext.getJobDirectory(); @NotNull final CleanupStrategy cleanupStrategy = executionContext.getCleanupStrategy(); if (jobDirectory != null) { log.info("Cleaning up job directory (strategy: {})", cleanupStrategy); try { this.jobSetupService.cleanupJobDirectory( jobDirectory.toPath(), cleanupStrategy ); } catch (final IOException e) { throw new RetryableTransitionException("Failed to cleanup job directory", e); } } }

Target:
protected void attemptTransition( final ExecutionContext executionContext ) throws RetryableTransitionException, FatalTransitionException { final File jobDirectory = executionContext.getJobDirectory(); final CleanupStrategy cleanupStrategy = executionContext.getCleanupStrategy(); if (jobDirectory != null) { log.info("Cleaning up job directory (strategy: {})", cleanupStrategy); try { this.jobSetupService.cleanupJobDirectory( jobDirectory.toPath(), cleanupStrategy ); } catch (final IOException e) { throw new RetryableTransitionException("Failed to cleanup job directory", e); } } }
Source:
protected void executeCommand() { getParameters().setEntityInfo(getEntityInfo()); setSucceeded(true); if (images != null && !images.isEmpty()) { List<DiskImage> imageToRemove = new ArrayList<>(); for (DiskImage image : images) { if (image.getStorageIds().get(0).equals(getParameters().getStorageDomainId())) { image.setStorageIds(Collections.singletonList(getParameters().getStorageDomainId())); image.setStoragePoolId(getParameters().getStoragePoolId()); imageToRemove.add(image); } } RemoveAllVmImagesParameters removeAllVmImagesParameters = new RemoveAllVmImagesParameters(ovfEntityData.getEntityId(), imageToRemove); removeAllVmImagesParameters.setParentCommand(getActionType()); removeAllVmImagesParameters.setEntityInfo(getParameters().getEntityInfo()); removeAllVmImagesParameters.setForceDelete(true); removeAllVmImagesParameters.setParentParameters(getParameters()); ActionReturnValue vdcRetValue = runInternalActionWithTasksContext(ActionType.RemoveAllVmImages, removeAllVmImagesParameters); if (vdcRetValue.getSucceeded()) { getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } else { getReturnValue().setFault(vdcRetValue.getFault()); setSucceeded(false); } } vmAndTemplatesGenerationsDao.deleteOvfGenerations(Collections.singletonList(ovfEntityData.getEntityId())); unregisteredOVFDataDao.removeEntity(ovfEntityData.getEntityId(), null); unregisteredDisksDao.removeUnregisteredDiskRelatedToVM(ovfEntityData.getEntityId(), null); }

Target:
protected void executeCommand() { getParameters().setEntityInfo(getEntityInfo()); setSucceeded(true); if (images != null && !images.isEmpty()) { List<DiskImage> imageToRemove = new ArrayList<>(); for (DiskImage image : images) { if (image.getStorageIds().get(0).equals(getParameters().getStorageDomainId())) { image.setStorageIds(Collections.singletonList(getParameters().getStorageDomainId())); image.setStoragePoolId(getParameters().getStoragePoolId()); imageToRemove.add(image); } } RemoveAllVmImagesParameters removeAllVmImagesParameters = new RemoveAllVmImagesParameters(ovfEntityData.getEntityId(), imageToRemove); removeAllVmImagesParameters.setParentCommand(getActionType()); removeAllVmImagesParameters.setEntityInfo(getParameters().getEntityInfo()); removeAllVmImagesParameters.setForceDelete(true); removeAllVmImagesParameters.setParentParameters(getParameters()); ActionReturnValue vdcRetValue = runInternalActionWithTasksContext(ActionType.RemoveAllVmImages, removeAllVmImagesParameters); if (vdcRetValue.getSucceeded()) { getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } else { getReturnValue().setFault(vdcRetValue.getFault()); setSucceeded(false); } } TransactionSupport.executeInNewTransaction(() -> { vmAndTemplatesGenerationsDao.deleteOvfGenerations(Collections.singletonList(ovfEntityData.getEntityId())); unregisteredOVFDataDao.removeEntity(ovfEntityData.getEntityId(), null); unregisteredDisksDao.removeUnregisteredDiskRelatedToVM(ovfEntityData.getEntityId(), null); return null; }); }
Source:
public synchronized void stateChanged(TaskStatus newStatus) { long currentUserMemory = newStatus.getMemoryReservation().toBytes(); long currentSystemMemory = newStatus.getSystemMemoryReservation().toBytes(); long currentTotalMemory = currentUserMemory + currentSystemMemory; long deltaUserMemoryInBytes = currentUserMemory - previousUserMemory; long deltaTotalMemoryInBytes = currentTotalMemory - (previousUserMemory + previousSystemMemory); previousUserMemory = currentUserMemory; previousSystemMemory = currentSystemMemory; stateMachine.updateMemoryUsage(deltaUserMemoryInBytes, deltaTotalMemoryInBytes, currentUserMemory, currentTotalMemory); if (state == PLANNED && newStatus.getState() == RUNNING) { int runningTasks = stateMachine.getCurrentRunningTasks().incrementAndGet(); stateMachine.getPeakRunningTasks().accumulateAndGet(runningTasks, Math::max); } else if (!state.isDone() && newStatus.getState().isDone()) { stateMachine.getCurrentRunningTasks().decrementAndGet(); } state = newStatus.getState(); }

Target:
public synchronized void stateChanged(TaskStatus newStatus) { long currentUserMemory = newStatus.getMemoryReservation().toBytes(); long currentSystemMemory = newStatus.getSystemMemoryReservation().toBytes(); long currentTotalMemory = currentUserMemory + currentSystemMemory; long deltaUserMemoryInBytes = currentUserMemory - previousUserMemory; long deltaTotalMemoryInBytes = currentTotalMemory - (previousUserMemory + previousSystemMemory); previousUserMemory = currentUserMemory; previousSystemMemory = currentSystemMemory; stateMachine.updateMemoryUsage(deltaUserMemoryInBytes, deltaTotalMemoryInBytes, currentUserMemory, currentTotalMemory); if (state == PLANNED && newStatus.getState() == RUNNING) { stateMachine.incrementCurrentRunningTaskCount(); } else if (state == RUNNING && newStatus.getState().isDone()) { stateMachine.decrementCurrentRunningTaskCount(); } state = newStatus.getState(); }