auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public AcknowledgementType auditLog(LogEventRequestType request, AssertionType assertion) { <START> LOG.debug("Entering AuditRepositoryProxyWebServiceUnsecuredImpl.auditLog(...)"); <END> if (request.getAuditMessage() == null) { LOG.error("Audit Request Message is null."); synchronized (result) { return result; } } try { String url = oProxyHelper.getUrlLocalHomeCommunity(NhincConstants.AUDIT_REPO_SERVICE_NAME); if (NullChecker.isNotNullish(url)) { ServicePortDescriptor<AuditRepositoryManagerPortType> portDescriptor = new AuditRepositoryUnsecuredServicePortDescriptor(); CONNECTClient<AuditRepositoryManagerPortType> client = CONNECTCXFClientFactory.getInstance() .getCONNECTClientUnsecured(portDescriptor, url, assertion); synchronized (result) { result = (AcknowledgementType) client.invokePort(AuditRepositoryManagerPortType.class, "logEvent", request); } } } catch (Exception e) { LOG.error("Failed to call the web service (" + NhincConstants.AUDIT_REPO_SERVICE_NAME + "). An unexpected exception occurred. " + "Exception: " + e.getLocalizedMessage(), e); } LOG.debug("In AuditRepositoryProxyWebServiceUnsecuredImpl.auditLog(...) - completed called to " + "ConnectionManager to retrieve endpoint."); return result; }</code><technical_language>this (and other instances of "Entering Class.Method") changed trace level, removed in favor of a more meaningful log message</technical_language>

Target:
public AcknowledgementType auditLog(LogEventRequestType request, AssertionType assertion) { if (request.getAuditMessage() == null) { LOG.error("Audit Request Message is null."); synchronized (result) { return result; } } try { String url = oProxyHelper.getUrlLocalHomeCommunity(NhincConstants.AUDIT_REPO_SERVICE_NAME); if (NullChecker.isNotNullish(url)) { ServicePortDescriptor<AuditRepositoryManagerPortType> portDescriptor = new AuditRepositoryUnsecuredServicePortDescriptor(); CONNECTClient<AuditRepositoryManagerPortType> client = CONNECTCXFClientFactory.getInstance() .getCONNECTClientUnsecured(portDescriptor, url, assertion); synchronized (result) { result = (AcknowledgementType) client.invokePort(AuditRepositoryManagerPortType.class, invokeMethodName, request); } } } catch (Exception e) { LOG.error("Failed to call the web service (" + NhincConstants.AUDIT_REPO_SERVICE_NAME + "). An unexpected exception occurred. " + "Exception: " + e.getLocalizedMessage(), e); } LOG.debug("In AuditRepositoryProxyWebServiceUnsecuredImpl.auditLog(...) - completed called to " + "ConnectionManager to retrieve endpoint."); return result; }
Source:
<code>public void updateElement(int index) { final TableViewer tableViewer = fTableViewer; final ISegment[] segmentArray = fSegmentArray; <START> if (tableViewer != null && segmentArray != null) { tableViewer.replace(segmentArray[index], index); } <END> }</code><technical_language>TableViewer.setInput() is called, preserve selection (based index). In AbstractTableViewer.getVirtualSelection():489, update element (which calls this method here) *then* a bounds check selection index. I a bug in JFace, a workaround for clear selection changing input, sense. want preserve selected index unrelated input segment store</technical_language>

Target:
public void updateElement(int index) { final TableViewer tableViewer = fTableViewer; final ISegment[] segmentArray = fSegmentArray; if (tableViewer != null && segmentArray != null) { if (index < segmentArray.length) { tableViewer.replace(segmentArray[index], index); } } }
Source:
<code>private static Set<Type> primitiveWrappers(Set<Type> types) { <START> if (!types.stream().allMatch(Type::isPrimitive)) { <END> return types.stream().map(t -> !t.isPrimitive() ? t : ((JavaType) t).primitiveWrapperType()).collect(Collectors.toCollection(LinkedHashSet::new)); } return types; }</code><technical_language>I negate condition</technical_language>

Target:
private static Set<Type> primitiveWrappers(Set<Type> types) { if (types.stream().allMatch(Type::isPrimitive)) { return types; } return types.stream().map(t -> !t.isPrimitive() ? t : ((JavaType) t).primitiveWrapperType()).collect(Collectors.toCollection(LinkedHashSet::new)); }
Source:
<code>private static List<String> getFailedNotifications() throws MambuApiException{ <START> List<String> foundFaildNotifications = new ArrayList<>(); <END> ArrayList<JSONFilterConstraint> constraints = new ArrayList<JSONFilterConstraint>(); JSONFilterConstraint constraint = new JSONFilterConstraint(); constraint.setDataFieldType(DataFieldType.NATIVE.name()); constraint.setFilterSelection(NotificationMessageDataField.STATE.name()); constraint.setFilterElement(FilterElement.EQUALS.name()); constraint.setValue(MessageState.FAILED.name()); constraints.add(constraint); JSONFilterConstraints filterConstraints = new JSONFilterConstraints(); filterConstraints.setFilterConstraints(constraints); SearchService searchService = MambuAPIFactory.getSearchService(); List<NotificationMessage> notificationMessages = searchService.getNotificationMessages(filterConstraints, "0", "5"); for(NotificationMessage failedessage :notificationMessages){ foundFaildNotifications.add(failedessage.getEncodedKey()); } return foundFaildNotifications; }</code><technical_language>failed</technical_language>

Target:
private static List<String> getFailedNotifications() throws MambuApiException{ List<String> foundFailedNotifications = new ArrayList<>(); List<JSONFilterConstraint> constraints = new ArrayList<>(); JSONFilterConstraint constraint = new JSONFilterConstraint(); constraint.setDataFieldType(DataFieldType.NATIVE.name()); constraint.setFilterSelection(NotificationMessageDataField.STATE.name()); constraint.setFilterElement(FilterElement.EQUALS.name()); constraint.setValue(MessageState.FAILED.name()); constraints.add(constraint); JSONFilterConstraints filterConstraints = new JSONFilterConstraints(); filterConstraints.setFilterConstraints(constraints); SearchService searchService = MambuAPIFactory.getSearchService(); List<NotificationMessage> notificationMessages = searchService.getNotificationMessages(filterConstraints, "0", "5"); for(NotificationMessage failedMessage :notificationMessages){ foundFailedNotifications.add(failedMessage.getEncodedKey()); } return foundFailedNotifications; }
Source:
<code>public void whenTopicCreationFailsRemoveEventTypeFromRepositoryAnd500() throws Exception { Mockito .doNothing() .when(eventTypeRepository) .saveEventType(any(EventType.class)); Mockito .doThrow(TopicCreationException.class) .when(topicRepository) .createTopic(EVENT_TYPE_NAME); Mockito .doNothing() .when(eventTypeRepository) .removeEventType(EVENT_TYPE_NAME); final Problem expectedProblem = Problem.valueOf(Response.Status.SERVICE_UNAVAILABLE); postEventType(buildEventType()) .andExpect(status().isServiceUnavailable()) .andExpect(content().contentType("application/problem+json")) .andExpect(content().string(matchesProblem(expectedProblem))); verify(eventTypeRepository, times(1)).saveEventType(any(EventType.class)); <START> verify(topicRepository, times(1)).createTopic("team.event-name"); <END> verify(eventTypeRepository, times(1)).removeEventType("team.event-name"); }</code><technical_language>createTopic(EVENT_TYPE_NAME)</technical_language>

Target:
public void whenTopicCreationFailsRemoveEventTypeFromRepositoryAnd500() throws Exception { final EventType et = buildDefaultEventType(); Mockito.doNothing().when(eventTypeRepository).saveEventType(any(EventType.class)); Mockito.doThrow(TopicCreationException.class).when(topicRepository).createTopic(et.getName()); Mockito.doNothing().when(eventTypeRepository).removeEventType(et.getName()); final Problem expectedProblem = Problem.valueOf(Response.Status.SERVICE_UNAVAILABLE); postEventType(et).andExpect(status().isServiceUnavailable()) .andExpect(content().contentType("application/problem+json")).andExpect(content().string( matchesProblem(expectedProblem))); verify(eventTypeRepository, times(1)).saveEventType(any(EventType.class)); verify(topicRepository, times(1)).createTopic(et.getName()); verify(eventTypeRepository, times(1)).removeEventType(et.getName()); }
Source:
<code>public double mean(String colName) { double[] colArray = toDoubleArray(colName); <START> double arrayMean = StatUtils.mean(colArray); return arrayMean; <END> }</code><technical_language>return StatUtils.mean(toDoubleArray(colName)) directly</technical_language>

Target:
public double mean(String colName) { return StatUtils.mean(toDoubleArray(colName)); }
Source:
<code>public final Long getCardinalityLimit() { <START> if (cardinalityLimit == null) { return null; } return cardinalityLimit; <END> }</code><technical_language>This is redundant, return cardinalityLimit null check</technical_language>

Target:
public final Long getCardinalityLimit() { return cardinalityLimit; }
Source:
<code>public boolean mergeTypeParameters(ParameterizedTypeBinding current, ParameterizedTypeBinding newB) { TypeBinding[] curTypeArgs = current.typeArguments(); TypeBinding[] newTypeArgs = newB.typeArguments(); TypeBinding[] merged = new TypeBinding[curTypeArgs.length]; System.arraycopy(curTypeArgs, 0, merged, 0, curTypeArgs.length); boolean wasMerged = false; for (int i = 0; i < curTypeArgs.length; i++) { if (TypeBinding.equalsEquals(curTypeArgs[i], newTypeArgs[i])) continue; if(curTypeArgs[i].isCapture() || newTypeArgs[i].isCapture()) return false; if (curTypeArgs[i] instanceof InferenceVariable) { if (!(newTypeArgs[i] instanceof InferenceVariable)) { if(this.sameBounds != null && !this.sameBounds.contains(new TypeBound((InferenceVariable) curTypeArgs[i], newTypeArgs[i], ReductionResult.SAME))) { merged[i] = newTypeArgs[i]; wasMerged = true; } } else if (!curTypeArgs[i].equals(newTypeArgs[i])) { return false; } } else { if (!(newTypeArgs[i] instanceof InferenceVariable)) { if (!TypeBinding.equalsEquals(curTypeArgs[i], newTypeArgs[i])) { return false; } } else { if(this.sameBounds == null || !this.sameBounds.contains(new TypeBound((InferenceVariable) newTypeArgs[i], curTypeArgs[i], ReductionResult.SAME))) { return false; } } } } if(wasMerged) { <START> current.arguments = merged; <END> return true; } return false; }</code><technical_language>In-place modification of PTB 'current' dangerous me! hard other code locations affected this side effect</technical_language>

Target:
public ParameterizedTypeBinding mergeTypeParameters(ParameterizedTypeBinding current, ParameterizedTypeBinding newB) { TypeBinding[] curTypeArgs = current.typeArguments(); TypeBinding[] newTypeArgs = newB.typeArguments(); TypeBinding[] merged = new TypeBinding[curTypeArgs.length]; System.arraycopy(curTypeArgs, 0, merged, 0, curTypeArgs.length); boolean wasMerged = false; for (int i = 0; i < curTypeArgs.length; i++) { if (TypeBinding.equalsEquals(curTypeArgs[i], newTypeArgs[i])) continue; if(curTypeArgs[i].isCapture() || newTypeArgs[i].isCapture()) return null; if (curTypeArgs[i] instanceof InferenceVariable) { if (!(newTypeArgs[i] instanceof InferenceVariable)) { ThreeSets three = BoundSet.this.boundsPerVariable.get(curTypeArgs[i]); if(three != null && three.sameBounds != null && three.sameBounds.contains(new TypeBound((InferenceVariable) curTypeArgs[i], newTypeArgs[i], ReductionResult.SAME))) { merged[i] = newTypeArgs[i]; wasMerged = true; } } else if (!curTypeArgs[i].equals(newTypeArgs[i])) { return null; } } else { if (!(newTypeArgs[i] instanceof InferenceVariable)) { if (!TypeBinding.equalsEquals(curTypeArgs[i], newTypeArgs[i])) { return null; } } else { ThreeSets three = BoundSet.this.boundsPerVariable.get(newTypeArgs[i]); if(three == null || three.sameBounds == null || !three.sameBounds.contains(new TypeBound((InferenceVariable) newTypeArgs[i], curTypeArgs[i], ReductionResult.SAME))) { return null; } } } } if(wasMerged) { ParameterizedTypeBinding clone = (ParameterizedTypeBinding)current.clone(current.enclosingType()); clone.arguments = merged; return clone; } return null; }
Source:
<code>public boolean isEmpty() { <START> return Arrays.stream(lookupSources).allMatch(lookupSource -> lookupSource.isEmpty()); <END> }</code><technical_language>s/lookupSource -> lookupSource.isEmpty()/LookupSource::isEmpty/</technical_language>

Target:
public boolean isEmpty() { return Arrays.stream(lookupSources).allMatch(LookupSource::isEmpty); }
Source:
<code>public void testResend() throws Exception { final AtomicInteger flushCount = new AtomicInteger(); final EmbeddedChannel channel = newChannel(flushCount, true); channel.writeAndFlush(1L).addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { channel.writeAndFlush(1L); } }); channel.flushOutbound(); assertEquals(1L, channel.readOutbound()); assertEquals(1L, channel.readOutbound()); assertNull(channel.readOutbound()); <START> channel.finish(); <END> }</code><technical_language>nit: assertFalse(channel.finish);</technical_language>

Target:
public void testResend() throws Exception { final AtomicInteger flushCount = new AtomicInteger(); final EmbeddedChannel channel = newChannel(flushCount, true); channel.writeAndFlush(1L).addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { channel.writeAndFlush(1L); } }); channel.flushOutbound(); assertEquals(1L, channel.readOutbound()); assertEquals(1L, channel.readOutbound()); assertNull(channel.readOutbound()); assertFalse(channel.finish()); }
Source:
<code>public void testGetSet_shouldBeAtomic() throws ExecutionException, InterruptedException, TimeoutException { jedis.set("contestedKey", "0"); assertThat(jedis.get("contestedKey")).isEqualTo("0"); CountDownLatch latch = new CountDownLatch(1); ExecutorService pool = Executors.newFixedThreadPool(2); Callable<Integer> callable1 = () -> doABunchOfIncrs(jedis, latch); Callable<Integer> callable2 = () -> doABunchOfGetSets(jedis2, latch); Future<Integer> future1 = pool.submit(callable1); Future<Integer> future2 = pool.submit(callable2); latch.countDown(); <START> Integer getSetSum = future2.get(60, TimeUnit.SECONDS); <END> Integer incrSum = future1.get(); assertThat(getSetSum).isEqualTo(incrSum); assertThat(incrSum + getSetSum).isEqualTo(2 * ITERATION_COUNT); }</code><technical_language>hard-coding a wait limit, Geode tests GeodeAwaitility. advantage of is (and have) set a global default maximum timeout (currently 5 minutes)</technical_language>

Target:
public void testGetSet_shouldBeAtomic() throws ExecutionException, InterruptedException, TimeoutException { jedis.set("contestedKey", "0"); assertThat(jedis.get("contestedKey")).isEqualTo("0"); CountDownLatch latch = new CountDownLatch(1); ExecutorService pool = Executors.newFixedThreadPool(2); Callable<Integer> callable1 = () -> doABunchOfIncrs(jedis, latch); Callable<Integer> callable2 = () -> doABunchOfGetSets(jedis2, latch); Future<Integer> future1 = pool.submit(callable1); Future<Integer> future2 = pool.submit(callable2); latch.countDown(); GeodeAwaitility.await().untilAsserted(() -> assertThat(future2.get()).isEqualTo(future1.get())); assertThat(future1.get() + future2.get()).isEqualTo(2 * ITERATION_COUNT); }
Source:
<code><START> public void drainPermissions() { <END> State prevState = state.getAndUpdate(activeState -> { if (activeState.activePermissions > 0) { return calculateNextState(activeState.activePermissions, 0, activeState); } else { return activeState; } }); if (eventProcessor.hasConsumers()) { eventProcessor.consumeEvent(new RateLimiterOnDrainedEvent(name, Math.min(prevState.activePermissions, 0))); } }</code><technical_language>Please change state directly, approach in updateStateWithBackOff <LINK_0></technical_language>

Target:
public void drainPermissions() { AtomicRateLimiter.State prev; AtomicRateLimiter.State next; do { prev = state.get(); next = calculateNextState(prev.activePermissions, 0, prev); } while (!compareAndSet(prev, next)); if (eventProcessor.hasConsumers()) { eventProcessor.consumeEvent(new RateLimiterOnDrainedEvent(name, Math.min(prev.activePermissions, 0))); } }
Source:
<code>private void restartPoller(final long pollInterval) { LOG.debug("Restarting alarm poller (interval {}s).", pollInterval); <START> if (m_alarmPoller != null) { <END> stopPoller(); } startPoller(pollInterval); }</code><technical_language>Stopping poller check for poller null. consistent this. check in stopPoller before</technical_language>

Target:
private void restartPoller(final long pollInterval) { LOG.debug("Restarting alarm poller (interval {}s).", pollInterval); stopPoller(); startPoller(pollInterval); }
Source:
<code>public void updateFromMethodInvocation( MethodInvocationNode methodInvNode, Tree receiverTree, ExecutableElement methodElt, AnnotatedTypeFactory atf) { if (ElementUtils.isElementFromByteCode(methodElt)) { return; } String className = getEnclosingClassName(methodElt); String jaifPath = storage.getJaifPath(className); AClassWrapper clazz = storage.getAClass(className, jaifPath); String methodName = JVMNames.getJVMMethodName(methodElt); AMethodWrapper method = clazz.vivifyMethod(methodName); <START> method.setReturnType(methodElt.getReturnType()); <END> List<Node> arguments = methodInvNode.getArguments(); updateInferredExecutableParameterTypes(methodElt, atf, jaifPath, method, arguments); }</code><technical_language>setReturnType is called 3 times. time is right a call AMethodWrapper.vivifyMethod. putting call setReturnType vivifyMethod? error-prone making client remember call. argument type of vivifyMethod change (say, ExecutableElement), OK. able remove setReturnType public API of AMethodWrapper, a plus</technical_language>

Target:
public void updateFromMethodInvocation( MethodInvocationNode methodInvNode, Tree receiverTree, ExecutableElement methodElt, AnnotatedTypeFactory atf) { if (!ElementUtils.isElementFromSourceCode(methodElt)) { return; } String className = getEnclosingClassName(methodElt); String jaifPath = storage.getJaifPath(className); AClass clazz = storage.getAClass(className, jaifPath, ((MethodSymbol) methodElt).enclClass()); AMethod method = clazz.methods.getVivify(JVMNames.getJVMMethodSignature(methodElt)); method.setFieldsFromMethodElement(methodElt); List<Node> arguments = methodInvNode.getArguments(); updateInferredExecutableParameterTypes(methodElt, atf, jaifPath, method, arguments); }
Source:
<code>public void testRedirect() throws Exception { final MockHttpSession session = new MockHttpSession(); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); final FilterChain filterChain = new FilterChain() { <START> public void doFilter(ServletRequest arg0, ServletResponse arg1) throws IOException, ServletException { <END> } }; request.setSession(session); this.filter.doFilter(request, response, filterChain); assertEquals(CAS_LOGIN_URL + "?service=" + URLEncoder.encode(CAS_SERVICE_URL, "UTF-8"), response.getRedirectedUrl()); }</code><technical_language>for beauty of source code, I prefer request response instead of arg0 arg1..</technical_language>

Target:
public void testRedirect() throws Exception { final MockHttpSession session = new MockHttpSession(); final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); final FilterChain filterChain = new FilterChain() { public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { } }; request.setSession(session); this.filter.doFilter(request, response, filterChain); assertEquals(CAS_LOGIN_URL + "?service=" + URLEncoder.encode(CAS_SERVICE_URL, "UTF-8"), response.getRedirectedUrl()); }
Source:
<code>public void dispose() { super.dispose(); if (composedAdapterFactory != null) { <START> composedAdapterFactory.dispose(); <END> } }</code><technical_language>call EcoreHelper.unregisterEcore dispose, we</technical_language>

Target:
public void dispose() { super.dispose(); if (composedAdapterFactory != null) { composedAdapterFactory.dispose(); } registeredEcores.forEach(EcoreHelper::unregisterEcore); }
Source:
<code>public void sendResponseToClient(CoreEvent response, Map<String, Object> parameters, CompletableCallback<Void> callback) { <START> ((BaseEventContext) response.getContext()).success(); <END> }</code><technical_language>I this is necessary. This happen autoamtically in pipeline. Verify if case remove</technical_language>

Target:
public void sendResponseToClient(CoreEvent response, Map<String, Object> parameters, CompletableCallback<Void> callback) { }
Source:
<code>public Map<String, Boolean> getPartitionStoppableCheck(String baseUrl, List<String> partitions, Map<String, String> customPayloads) throws IOException { String url = baseUrl + PARTITION_HEALTH_STATUS; Map<String, String> payLoads = new HashMap<>(customPayloads); payLoads.put(PARTITIONS, partitions.toString()); JsonConverter jsonConverter = jsonNode -> { Map<String, Boolean> result = new HashMap<>(); jsonNode.fields().forEachRemaining( kv -> result.put(kv.getKey(), kv.getValue().get(IS_HEALTHY_FIELD).asBoolean())); return result; }; try { _semaphore.acquire(); return handleResponse(post(url, payLoads), jsonConverter); } catch (InterruptedException e) { LOG.warn("Interrupted while acquiring the semaphore", e); } finally { _semaphore.release(); } <START> return Collections.emptyMap(); <END> }</code><technical_language>method lock, right? This is instance check, parallel duplication. duplicated requests part is partition level checks. Another here, Semaphore conditional variable</technical_language>

Target:
public Map<String, Boolean> getPartitionStoppableCheck(String baseUrl, List<String> partitions, Map<String, String> customPayloads) throws IOException { String url = baseUrl + PARTITION_HEALTH_STATUS; Map<String, String> payLoads = new HashMap<>(customPayloads); payLoads.put(PARTITIONS, partitions.toString()); JsonConverter jsonConverter = jsonNode -> { Map<String, Boolean> result = new HashMap<>(); jsonNode.fields().forEachRemaining( kv -> result.put(kv.getKey(), kv.getValue().get(IS_HEALTHY_FIELD).asBoolean())); return result; }; String requestId = baseUrl + customPayloads.toString() + partitions.toString(); try { lock(requestId); if (_cachedResults.containsKey(requestId)) { return _cachedResults.get(requestId); } Map<String, Boolean> result = handleResponse(post(url, payLoads), jsonConverter); _cachedResults.put(requestId, result); return result; } catch (InterruptedException e) { LOG.error("Error while acquiring the lock", e); } finally { unlock(requestId); } return Collections.emptyMap(); }
Source:
<code>public boolean isEnabled() { IResource[] selectedResources = getSelectedResources(); return super.isEnabled() && <START> selectedResources.length == 1 && <END> selectionMapsToSingleRepository(); }</code><technical_language>I lift this restriction. Note handler definition in plugin.xml is restricted single-element selections</technical_language>

Target:
public boolean isEnabled() { IStructuredSelection selection = getSelection(); return super.isEnabled() && selection.size() == 1 && selectionMapsToSingleRepository(); }
Source:
<code>public int size() { if (size == -1) { int tempsize = 0; if ((from instanceof Integer || from instanceof Long) && (to instanceof Integer || to instanceof Long)) { final BigInteger fromNum = new BigInteger(from.toString()); final BigInteger toNum = new BigInteger(to.toString()); final BigInteger sizeNum = toNum.subtract(fromNum).add(new BigInteger("1")); tempsize = sizeNum.intValue(); if (!BigInteger.valueOf(tempsize).equals(sizeNum)) { tempsize = Integer.MAX_VALUE; } } else if (from instanceof Character && to instanceof Character) { final char fromNum = (Character) from; final char toNum = (Character) to; tempsize = toNum - fromNum + 1; } else if (((from instanceof BigDecimal || from instanceof BigInteger) && to instanceof Number) || ((to instanceof BigDecimal || to instanceof BigInteger) && from instanceof Number)) { final BigDecimal fromNum = new BigDecimal(from.toString()); final BigDecimal toNum = new BigDecimal(to.toString()); final BigInteger sizeNum = toNum.subtract(fromNum).add(new BigDecimal(1.0)).toBigInteger(); tempsize = sizeNum.intValue(); if (!BigInteger.valueOf(tempsize).equals(sizeNum)) { tempsize = Integer.MAX_VALUE; } } else { for (Iterator it = iterator(); it.hasNext(); ) { tempsize++; <START> if (tempsize < 0) { <END> break; } it.next(); } } if (tempsize < 0) { tempsize = Integer.MAX_VALUE; } size = tempsize; } return size; }</code><technical_language>synchronization serves inlining barrier, I do agree cheap in cases. If needed avoided</technical_language>

Target:
public int size() { if (size == -1) { int tempsize = 0; if ((from instanceof Integer || from instanceof Long) && (to instanceof Integer || to instanceof Long)) { final BigInteger fromNum = new BigInteger(from.toString()); final BigInteger toNum = new BigInteger(to.toString()); final BigInteger sizeNum = toNum.subtract(fromNum).add(new BigInteger("1")); tempsize = sizeNum.intValue(); if (!BigInteger.valueOf(tempsize).equals(sizeNum)) { tempsize = Integer.MAX_VALUE; } } else if (from instanceof Character && to instanceof Character) { final char fromNum = (Character) from; final char toNum = (Character) to; tempsize = toNum - fromNum + 1; } else if (((from instanceof BigDecimal || from instanceof BigInteger) && to instanceof Number) || ((to instanceof BigDecimal || to instanceof BigInteger) && from instanceof Number)) { final BigDecimal fromNum = new BigDecimal(from.toString()); final BigDecimal toNum = new BigDecimal(to.toString()); final BigInteger sizeNum = toNum.subtract(fromNum).add(new BigDecimal(1.0)).toBigInteger(); tempsize = sizeNum.intValue(); if (!BigInteger.valueOf(tempsize).equals(sizeNum)) { tempsize = Integer.MAX_VALUE; } } else { for (Iterator<Comparable> iter = new LazySteppingIterator(this, 1); iter.hasNext(); ) { tempsize++; if (tempsize < 0) { break; } iter.next(); } } if (tempsize < 0) { tempsize = Integer.MAX_VALUE; } size = tempsize; } return size; }
Source:
<code><START> public Map<Guid, VdcObjectType> getPermissionCheckSubjects() { <END> Map<Guid, VdcObjectType> map = new HashMap<Guid, VdcObjectType>(); map.put(Guid.createGuidFromString(getStoragePoolId().toString()), VdcObjectType.StoragePool); return map; }</code><technical_language>please StorageHandlingCommandBase.getPermissionCheckSubjects()</technical_language>

Target:
public Map<Guid, VdcObjectType> getPermissionCheckSubjects() { return Collections.singletonMap(getStoragePoolId() == null ? null : getStoragePoolId().getValue(), VdcObjectType.Quota); }
Source:
<code>public void transformSlope(){ final ITmfTimestampTransform slope = TimestampTransformFactory.create(10, 0); assertEquals(t1e3, slope.transform(t1e2)); assertEquals(tn100, slope.transform(new TmfNanoTimestamp(10))); assertEquals(tn100, slope.transform(slope.transform(tn1))); <START> assertEquals(tn100, slope.transform(slope.transform(tn1))); <END> assertEquals(tn100, slope.composeWith(slope).transform(tn1)); }</code><technical_language>yes, knew</technical_language>

Target:
public void transformSlope(){ final ITmfTimestampTransform slope = TimestampTransformFactory.create(10, 0); assertEquals(t1e3, slope.transform(t1e2)); assertEquals(tn100, slope.transform(new TmfNanoTimestamp(10))); assertEquals(tn100, slope.transform(slope.transform(tn1))); assertEquals(tn100, slope.composeWith(slope).transform(tn1)); }
Source:
<code>public static Function<ProductItem, String> imageId() { return new Function<ProductItem, String>() { @Override public String apply(ProductItem productItem) { checkNotNull(productItem, "productItem"); ProductItemPrice price = ProductItems.price().apply(productItem); <START> return Objects.firstNonNull(price.getId() + "", ""); <END> } }; }</code><technical_language>price.getId() + "" _always_ non-null? System.out.println((null + "") == null); // prints false</technical_language>

Target:
public static Function<ProductItem, String> imageId() { return new Function<ProductItem, String>() { @Override public String apply(ProductItem productItem) { checkNotNull(productItem, "productItem"); ProductItemPrice price = ProductItems.price().apply(productItem); return String.valueOf(checkNotNull(price, "price").getId()); } }; }
Source:
<code>public Optional<Long> calculateDelta() { if (!initialized) { return Optional.empty(); } try { long[] allThreadIds = threadMXBean.getAllThreadIds(); long[] bytes = (long[]) getThreadAllocatedBytes.invoke(threadMXBean, (Object) allThreadIds); long sum = 0; for (int i = 0; i < allThreadIds.length; i++) { long threadId = allThreadIds[i]; Long previous = previousResults.get(threadId); Long current = bytes[i]; if (previous == null || previous > current) { sum += current; } else if (previous <= current) { sum += current - previous; } this.previousResults.put(threadId, current); } <START> previousResults.keySet().retainAll(Arrays.stream(allThreadIds).boxed().collect(Collectors.toList())); <END> return Optional.of(sum); } catch (ReflectiveOperationException e) { log.error(e, "Cannot calculate delta"); } return Optional.empty(); }</code><technical_language>This operation quadratic complexity. easier build a new map iterate allThreadIds reassign previousResults new map here</technical_language>

Target:
long calculateDelta() { try { long[] allThreadIds = threadMXBean.getAllThreadIds(); long[] bytes = (long[]) getThreadAllocatedBytes.invoke(threadMXBean, (Object) allThreadIds); long sum = 0; Long2LongMap newResults = new Long2LongOpenHashMap(); newResults.defaultReturnValue(NO_DATA); for (int i = 0; i < allThreadIds.length; i++) { long threadId = allThreadIds[i]; long previous = previousResults.get(threadId); long current = bytes[i]; newResults.put(threadId, current); if (previous == NO_DATA || previous > current) { sum += current; } else { sum += current - previous; } } previousResults = newResults; return sum; } catch (ReflectiveOperationException e) { log.error(e, "Cannot calculate delta"); } return 0; }
Source:
<code>public static <T> T unwrap(Class<T> clazz) { BeanManager manager = CDI.current().getBeanManager(); Set<Bean<?>> beans = manager.getBeans(clazz); if (beans.isEmpty()) { return null; } Bean<T> bean = (Bean<T>) beans.iterator().next(); Context context = manager.getContext(bean.getScope()); T beanInstance = context.get(bean); if (beanInstance != null) { return beanInstance; } CreationalContext<T> cc = manager.createCreationalContext(bean); <START> return context.get(bean, cc); <END> }</code><technical_language>sure, a lot of work unwrap a proxy =( a if I find some simpler/cheaper solution</technical_language>

Target:
public static <T> T unwrap(Class<T> clazz) { BeanManager manager = CDI.current().getBeanManager(); Set<Bean<?>> beans = manager.getBeans(clazz); Bean<T> bean = (Bean<T>) manager.resolve(beans); if (bean == null) { return null; } Context context = manager.getContext(bean.getScope()); T beanInstance = context.get(bean); if (beanInstance != null) { return beanInstance; } CreationalContext<T> cc = manager.createCreationalContext(bean); return context.get(bean, cc); }
Source:
<code>void throwOnDuplicateCommandDispatchers() { CommandClass commandTypeToIntercept = CommandClass.from(BbRegisterCommandDispatcher.class); BbCommandDispatcher dispatcher = new BbCommandDispatcher(context.eventBus(), commandTypeToIntercept); context.withHandlers(dispatcher); <START> assertThrows(IllegalArgumentException.class, () -> context.withHandlers(dispatcher)); <END> }</code><technical_language>Instead, try register a dispatcher of a type handles command</technical_language>

Target:
void throwOnDuplicateCommandDispatchers() { CommandClass commandTypeToDispatch = CommandClass.from(BbRegisterCommandDispatcher.class); BbCommandDispatcher dispatcher = new BbCommandDispatcher(context.eventBus(), commandTypeToDispatch); context.withHandlers(dispatcher); BbDuplicateCommandDispatcher duplicateDispatcher = new BbDuplicateCommandDispatcher(context.eventBus(), commandTypeToDispatch); assertThrows(IllegalArgumentException.class, () -> context.withHandlers(duplicateDispatcher)); }
Source:
<code>public void send(Send request) throws IOException { Channel streamChannel; try { streamChannel = http2MultiplexedChannelPool.acquire().get(500, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { <START> throw new IOException("Can't acquire stream channel: ", e); <END> } ChannelPipeline p = streamChannel.pipeline(); p.addLast(new Http2StreamFrameToHttpObjectCodec(false)); p.addLast(new HttpObjectAggregator(http2MultiplexedChannelPool.getMaxContentLength())); p.addLast(new SimpleChannelInboundHandler<FullHttpResponse>() { @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { ctx.channel().attr(RESPONSE_PROMISE).getAndSet(null).setSuccess(msg.content().retainedDuplicate()); ctx.channel() .parent() .attr(Http2MultiplexedChannelPool.HTTP2_MULTIPLEXED_CHANNEL_POOL) .get() .release(ctx.channel()); } }); streamChannel.pipeline().addLast(new AmbrySendToHttp2Adaptor()); responsePromise = streamChannel.eventLoop().newPromise(); streamChannel.attr(RESPONSE_PROMISE).set(responsePromise); streamChannel.writeAndFlush(request).awaitUninterruptibly(3, TimeUnit.SECONDS); }</code><technical_language>nit: print out host port</technical_language>

Target:
public void send(Send request) throws IOException { Channel streamChannel; try { streamChannel = http2MultiplexedChannelPool.acquire() .get(http2ClientConfig.http2BlockingChannelAcquireTimeoutMs, TimeUnit.MILLISECONDS); } catch (Exception e) { throw new IOException("Can't acquire stream channel from " + getRemoteHost() + ":" + getRemotePort(), e); } ChannelPipeline p = streamChannel.pipeline(); p.addLast(new Http2StreamFrameToHttpObjectCodec(false)); p.addLast(new HttpObjectAggregator(http2ClientConfig.http2MaxContentLength)); p.addLast(new SimpleChannelInboundHandler<FullHttpResponse>() { @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { Promise<ByteBuf> promise = ctx.channel().attr(RESPONSE_PROMISE).get(); if (promise != null) { promise.setSuccess(msg.content().retainedDuplicate()); releaseStreamChannel(ctx); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Promise<ByteBuf> promise = ctx.channel().attr(RESPONSE_PROMISE).getAndSet(null); if (promise != null) { promise.setFailure(cause); releaseStreamChannel(ctx); } } private void releaseStreamChannel(ChannelHandlerContext ctx) { ctx.channel() .parent() .attr(Http2MultiplexedChannelPool.HTTP2_MULTIPLEXED_CHANNEL_POOL) .get() .release(ctx.channel()); } }); p.addLast(new AmbrySendToHttp2Adaptor()); responsePromise = streamChannel.eventLoop().newPromise(); streamChannel.attr(RESPONSE_PROMISE).set(responsePromise); streamChannel.writeAndFlush(request) .awaitUninterruptibly(http2ClientConfig.http2BlockingChannelSendTimeoutMs, TimeUnit.MILLISECONDS); }
Source:
<code>private void startDemo(Demo demo) { try { getSupportFragmentManager().beginTransaction().replace(R.id.content, demo.fragment.newInstance()).commit(); } catch (Exception e) { <START> e.printStackTrace(); <END> } ((DrawerLayout) findViewById(R.id.drawer_layout)).closeDrawer(GravityCompat.START); }</code><technical_language>remove this try/catch? sample app get in a weird state</technical_language>

Target:
private void startDemo (Demo demo){ getSupportFragmentManager() .beginTransaction() .replace(R.id.content, demo.fragmentFactory.make()) .commit(); ((DrawerLayout) findViewById(R.id.drawer_layout)).closeDrawer(GravityCompat.START); }
Source:
<code>public String getType() { <START> if (isBlank(type)) { <END> return ""; } return type; }</code><technical_language>StringUtils commons.lang3</technical_language>

Target:
public String getType() { if (StringUtils.isBlank(type)) { return ""; } return type; }
Source:
<code>private void assignPermissions(String user, File tokenFile, Logger logger) throws IOException { final String changePermissionsCommand = String.format("chmod 460 %s", tokenFile.getAbsolutePath()); <START> int result = executeAsUser.execute(System.getProperty("user.name"), changePermissionsCommand); <END> if (result != 0) { throw new IOException("Unable to modify permissions. User: " + user); } final String changeOwnershipCommand = String.format("chown %s:azkaban %s", user, tokenFile.getAbsolutePath()); result = executeAsUser.execute("root", changeOwnershipCommand); if (result != 0) { throw new IOException("Unable to set ownership. User: " + user); } }</code><technical_language>Instead of partitioning argument string, considered passing array is easier parse? Python subprocess module approach</technical_language>

Target:
private void assignPermissions(String user, File tokenFile, Logger logger) throws IOException { final List<String> changePermissionsCommand = Arrays.asList( CHMOD, TOKEN_FILE_PERMISSIONS, tokenFile.getAbsolutePath() ); int result = executeAsUser.execute(System.getProperty("user.name"), changePermissionsCommand); if (result != 0) { throw new IOException("Unable to modify permissions. User: " + user); } final List<String> changeOwnershipCommand = Arrays.asList( CHOWN, user + ":" + GROUP_NAME, tokenFile.getAbsolutePath() ); result = executeAsUser.execute("root", changeOwnershipCommand); if (result != 0) { throw new IOException("Unable to set ownership. User: " + user); } }
Source:
<code><START> private void refreshLabelAndIcon() { EditPart parent = getParent(); <END> if (parent instanceof IAbstractDiagramNodeEditPart) { IAbstractDiagramNodeEditPart parentDiagramNodeEditPart = (IAbstractDiagramNodeEditPart) parent; SiriusWrapLabel siriusWrapLabel = parentDiagramNodeEditPart.getNodeLabel(); DDiagramElement dDiagramElement = parentDiagramNodeEditPart.resolveDiagramElement(); if (siriusWrapLabel != null && dDiagramElement != null) { DiagramElementEditPartOperation.refreshFont(parentDiagramNodeEditPart, dDiagramElement, siriusWrapLabel); StyleConfiguration styleConfiguration = IStyleConfigurationRegistry.INSTANCE.getStyleConfiguration(dDiagramElement.getDiagramElementMapping(), dDiagramElement.getStyle()); Image labelIcon = new StyleConfigurationQuery(styleConfiguration).getLabelIcon(dDiagramElement, parentDiagramNodeEditPart); siriusWrapLabel.setText(dDiagramElement.getName()); siriusWrapLabel.setIcon(labelIcon); if (dDiagramElement instanceof DNode) { styleConfiguration.adaptNodeLabel((DNode) dDiagramElement, siriusWrapLabel); } } } }</code><technical_language>Lot of duplicated code here, of XXXEditPartOperation place common part</technical_language>

Target:
private void refreshLabelAndIcon() { EditPart parent = getParent(); if (parent instanceof IAbstractDiagramNodeEditPart) { IAbstractDiagramNodeEditPart parentDiagramNodeEditPart = (IAbstractDiagramNodeEditPart) parent; SiriusWrapLabel siriusWrapLabel = parentDiagramNodeEditPart.getNodeLabel(); DDiagramElement dDiagramElement = parentDiagramNodeEditPart.resolveDiagramElement(); DiagramElementEditPartOperation.refreshLabelAndIcon(parentDiagramNodeEditPart, dDiagramElement, siriusWrapLabel); } }
Source:
<code>public LocalCandidate findLocalCandidate(TransportAddress localAddress, LocalCandidate base) { for (LocalCandidate localCnd : localCandidates) { <START> if (localCnd.getTransportAddress().equals(localAddress)) <END> { if (base == null || base.equals(localCnd.getBase())) return localCnd; } } for (LocalCandidate localCnd : localCandidates) { if (localCnd.getTransportAddress().equals(localAddress)) { return localCnd; } } return null; }</code><technical_language>duplicated loop here</technical_language>

Target:
public LocalCandidate findLocalCandidate(TransportAddress localAddress, LocalCandidate base) { for (LocalCandidate localCnd : localCandidates) { if (localCnd.getTransportAddress().equals(localAddress)) { if (base == null || base.equals(localCnd.getBase())) { return localCnd; } } } for (LocalCandidate localCnd : localCandidates) { if (localCnd.getTransportAddress().equals(localAddress)) { logger.warn("Returning a candidate matching the address, " + "while no candidates match both address (" + localAddress + ") and base (" + base +"): " + localCnd + " with base " + localCnd.getBase()); return localCnd; } } return null; }
Source:
<code>public FileVisitResult visitFileFailed(final Path file, final IOException ioe) { if (ioe instanceof FileSystemLoopException) { log.warn("Detected file system cycle visiting while visiting {}. Skipping.", file); return FileVisitResult.SKIP_SUBTREE; } else if (ioe instanceof AccessDeniedException) { log.warn("Access denied for file {}. Skipping", file); return FileVisitResult.SKIP_SUBTREE; } else if (ioe instanceof NoSuchFileException) { <START> log.warn("File or directory disappeared while vising {}. Skipping", file); <END> return FileVisitResult.SKIP_SUBTREE; } else { log.error("Got unknown error while visiting {}. Terminating visitor", ioe.getMessage(), file, ioe); return FileVisitResult.TERMINATE; } }</code><technical_language>spelling mistake visiting</technical_language>

Target:
public FileVisitResult visitFileFailed(final Path file, final IOException ioe) { if (ioe instanceof FileSystemLoopException) { log.warn("Detected file system cycle visiting while visiting {}. Skipping.", file); return FileVisitResult.SKIP_SUBTREE; } else if (ioe instanceof AccessDeniedException) { log.warn("Access denied for file {}. Skipping", file); return FileVisitResult.SKIP_SUBTREE; } else if (ioe instanceof NoSuchFileException) { log.warn("File or directory disappeared while visiting {}. Skipping", file); return FileVisitResult.SKIP_SUBTREE; } else { log.error("Got unknown error while visiting {}. Terminating visitor", ioe.getMessage(), file, ioe); return FileVisitResult.TERMINATE; } }
Source:
<code>protected void onPostExecute(String result) { if (result != null) { try { JSONObject obj = new JSONObject(result); if (obj.getString("result").equals("success")) { if (startedFromAddRealm) { loginThroughAddRealm(obj); callback.onTaskComplete(result, obj); } else { this.app.setServerURL(serverURL); this.app.setLoggedInApiKey(obj.getString("api_key")); ZulipApp.get().saveServerName(realmName); <START> if (context instanceof LoginActivity) { <END> ((LoginActivity) this.context).openHome(); } else if (context instanceof DevAuthActivity) { ((DevAuthActivity) this.context).openHome(); } } return; } } catch (JSONException e) { ZLog.logException(e); } } Toast.makeText(activity, "Unknown error", Toast.LENGTH_LONG).show(); Log.wtf("login", "We shouldn't have gotten this far."); }</code><technical_language>cleaner do this interface for method openHome()</technical_language>

Target:
protected void onPostExecute(String result) { if (result != null) { try { JSONObject obj = new JSONObject(result); if (obj.getString("result").equals("success")) { if (startedFromAddRealm) { loginThroughAddRealm(obj); callback.onTaskComplete(result, obj); } else { this.app.setServerURL(serverURL); this.app.setLoggedInApiKey(obj.getString("api_key")); ZulipApp.get().saveServerName(realmName); loginInterface.openHome(); } return; } } catch (JSONException e) { ZLog.logException(e); } } Toast.makeText(activity, "Unknown error", Toast.LENGTH_LONG).show(); Log.wtf("login", "We shouldn't have gotten this far."); }
Source:
<code>static void addPromptHandlerIfAvailable(LocationHandler handler) { if (handler instanceof LocationAndPromptHandler) { <START> synchronized (promptHandlers) { <END> promptHandlers.add((LocationAndPromptHandler) handler); } } }</code><technical_language>good synchronized promptHandlers</technical_language>

Target:
static void addPromptHandlerIfAvailable(LocationHandler handler) { if (handler instanceof LocationPromptCompletionHandler) { synchronized (promptHandlers) { promptHandlers.add((LocationPromptCompletionHandler) handler); } } }
Source:
<code>private static void parseSdkStanza(ClientInfo.Builder builder, String stanza) { String[] sdkComponents = stanza.split("/"); if (sdkComponents.length == 2) { if (!sdkComponents[0].matches(DIGITS_REGEXP)) { builder.withSdkName(parseString(sdkComponents[0])); } <START> builder.withSdkVersion(parseInteger(sdkComponents[1])).build(); <END> } else if (sdkComponents.length == 1) { if (sdkComponents[0].matches(DIGITS_REGEXP)) { builder.withSdkVersion(parseInteger(sdkComponents[0])); } else { builder.withSdkName(parseString(sdkComponents[0])); } } }</code><technical_language>Stray .build()</technical_language>

Target:
private static void parseSdkStanza(ClientInfo.Builder builder, String stanza) { String[] sdkComponents = stanza.split("/"); if (sdkComponents.length == 2) { if (!sdkComponents[0].matches(DIGITS_REGEXP)) { builder.withSdkName(parseString(sdkComponents[0])); } builder.withSdkVersion(parseInteger(sdkComponents[1])); } else if (sdkComponents.length == 1) { if (sdkComponents[0].matches(DIGITS_REGEXP)) { builder.withSdkVersion(parseInteger(sdkComponents[0])); } else { builder.withSdkName(parseString(sdkComponents[0])); } } }
Source:
<code>private boolean hasSameNodes(List<Node> first, List<Node> second) { if (first.size() != second.size()) { return false; } <START> for (int i = 0; i < first.size(); i++) { <END> if (!first.get(i).toString().equals(second.get(i).toString())) { return false; } } return true; }</code><technical_language>is good for performance I guess. java for (int i = 0, size = first.size(); i < size; i++) {</technical_language>

Target:
private boolean hasSameNodes(List<Node> first, List<Node> second) { if (first.size() != second.size()) { return false; } for (int i = 0, size = first.size(); i < size; i++) { if (!first.get(i).toString().equals(second.get(i).toString())) { return false; } } return true; }
Source:
<code><START> public T ADD_ROW() { <END> sql().values.add(new ArrayList<>()); return getSelf(); }</code><technical_language>Please add @Since 3.5.2</technical_language>

Target:
public T ADD_ROW() { sql().valuesList.add(new ArrayList<>()); return getSelf(); }
Source:
<code>public UserInfo about(String username) throws ActionFailedException { <START> if(username == "[deleted]") <END> throw new ActionFailedException("There is no information associated with the username [deleted]"); JSONObject object = (JSONObject) restClient.get(String.format(ApiEndpointUtils.USER_ABOUT, username), null).getResponseObject(); JSONObject data = (JSONObject) object.get("data"); return data != null ? new UserInfo(data) : null; }</code><technical_language>add curly brackets if statement? good practice end weird bugs in future</technical_language>

Target:
public UserInfo about(String username) throws ActionFailedException { if(username.equals("[deleted]")) { throw new ActionFailedException("There is no information associated with the username [deleted]"); } JSONObject object = (JSONObject) restClient.get(String.format(ApiEndpointUtils.USER_ABOUT, username), null).getResponseObject(); JSONObject data = (JSONObject) object.get("data"); return data != null ? new UserInfo(data) : null; }
Source:
<code>public int hashCode() { return scope.hashCode() <START> ^ name.hashCode(); <END> }</code><technical_language>Bit xoring is combine hash codes. A approach is scope.hashCode() * <some prime number, e.g. 29> + name.hashCode()</technical_language>

Target:
public int hashCode() { return scope.hashCode() * (29 + name.hashCode()); }