auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public synchronized void get() { <END> for (Workload workload : jobs.keySet()) { get(workload); } }</code><technical_language>synchronization is needed member variable "jobs" is modified concurrently. In case want synchronization "jobs" is accessed (both read modified) (for ex - complete() ). good add a @GuardedBy("this") annotation for "jobs"</technical_language>

Target:
public void get() { for (Workload workload : jobs.keySet()) { get(workload); } }
Source:
<code>private void initFingerprints() { if (fingerprints == null) { <START> synchronized (this) { <END> if (fingerprints == null) { fingerprints = new LinkedHashSet<List<StackTraceElement>>(); for (String sample : this.samples) { try { this.parser.parse("__dummy", sample, ParsingContext.partial_stream); } catch (Exception exception) { if (this.exceptionClass.isAssignableFrom(exception.getClass())) { computeFingerprint((E) exception); } else if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new RuntimeException(exception); } } } } } } }</code><technical_language>Double-checking overkill here... in worst case hit this race condition, collection type is a Set anyways</technical_language>

Target:
private void initFingerprints() { if (fingerprints.isEmpty()) { for (String sample : this.samples) { try { this.parser.parse("__dummy", sample, ParsingContext.partial_stream); } catch (Exception exception) { if (this.exceptionClass.isAssignableFrom(exception.getClass())) { computeFingerprint((E) exception); } else if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new RuntimeException(exception); } } } } }
Source:
<code>public CompletableFuture<Event> process(CoreEvent event, EventProcessor router) throws MuleException { logger.info("Handling odata enabled request."); HttpRequestAttributes attributes = CoreEventUtils.getHttpRequestAttributes(event); <START> OdataContext oDataContext = getOdataContext(router.getRamlHandler().getRamlV1()); <END> oDataContext.setMethod(attributes.getMethod()); String path = attributes.getRelativePath(); if (path.contains(ODATA_SVC_URI_PREFIX)) { return ODataRouterService.processODataRequest(attributes, router, oDataContext,event); } else { return router.processEvent(event); } }</code><technical_language>getRamlV1 return path raml, this method return raml content instead. Is right for case</technical_language>

Target:
public CompletableFuture<Event> process(CoreEvent event, EventProcessor router) throws MuleException { logger.info("Handling odata enabled request."); HttpRequestAttributes attributes = CoreEventUtils.getHttpRequestAttributes(event); OdataContext oDataContext = getOdataContext(router.getRamlHandler().getRootRamlLocationForV2()); oDataContext.setMethod(attributes.getMethod()); String path = attributes.getRelativePath(); if (path.contains(ODATA_SVC_URI_PREFIX)) { return ODataRouterService.processODataRequest(attributes, router, oDataContext,event); } else { return router.processEvent(event); } }
Source:
<code>public void onComplete() { s = SubscriptionHelper.CANCELLED; <START> SingleSource<? extends T> c = other; <END> other = null; c.subscribe(this); }</code><technical_language>named s. conflicting subscription s. I guess ss more appropriate</technical_language>

Target:
public void onComplete() { s = SubscriptionHelper.CANCELLED; SingleSource<? extends T> ss = other; other = null; ss.subscribe(this); }
Source:
<code><START> public synchronized void deletePerPartitionCustomizedState(String customizedStateName, String resourceName, <END> String partitionName) { PropertyKey.Builder keyBuilder = _helixDataAccessor.keyBuilder(); PropertyKey propertyKey = keyBuilder.customizedState(_instanceName, customizedStateName, resourceName); CustomizedState existingState = getCustomizedState(customizedStateName, resourceName); _helixDataAccessor.updateProperty(propertyKey, new DataUpdater<ZNRecord>() { @Override public ZNRecord update(ZNRecord current) { current.getMapFields().remove(partitionName); return current; } }, existingState); }</code><technical_language>need synchronized keyword place? ZK takes care of concurrent control, right</technical_language>

Target:
public void deletePerPartitionCustomizedState(String customizedStateName, String resourceName, String partitionName) { PropertyKey.Builder keyBuilder = _helixDataAccessor.keyBuilder(); PropertyKey propertyKey = keyBuilder.customizedState(_instanceName, customizedStateName, resourceName); CustomizedState existingState = getCustomizedState(customizedStateName, resourceName); _helixDataAccessor.updateProperty(propertyKey, new DataUpdater<ZNRecord>() { @Override public ZNRecord update(ZNRecord current) { current.getMapFields().remove(partitionName); return current; } }, existingState); }
Source:
<code>public boolean isNextAllowed() { if (isMovingToForward) { return false; } QuestionNode currentQuestionNode = getCurrentNode(); if (currentQuestionNode == null) { return true; } QuestionDB currentQuestionDB = getCurrentQuestion(); ValueDB currentValueDB = currentQuestionDB.getValueBySession(); if (currentValueDB == null) { Log.d(TAG, "isNextAllowed()->You must answer first"); return false; } OptionDB currentOptionDB = currentValueDB == null ? null : currentValueDB.getOptionDB(); boolean isAllowed = findNext(currentOptionDB) != null; <START> if (!isAllowed && !hasNext(null) && !hasNext(currentValueDB.getOptionDB())) { <END> return true; } Log.d(TAG, String.format("isNextAllowed()->%b", isAllowed)); return isAllowed; }</code><technical_language>@manuelplazaspalacio I change this method of NavigationController for this modifying a existed method apps scenarios is changing a behavior. I change caller (onSwipeLeft) for this method create new condition if is question</technical_language>

Target:
public boolean isNextAllowed() { if (isMovingToForward) { return false; } QuestionNode currentQuestionNode = getCurrentNode(); if (currentQuestionNode == null) { return true; } QuestionDB currentQuestionDB = getCurrentQuestion(); ValueDB currentValueDB = currentQuestionDB.getValueBySession(); if (currentValueDB == null) { Log.d(TAG, "isNextAllowed()->You must answer first"); return false; } OptionDB currentOptionDB = currentValueDB == null ? null : currentValueDB.getOptionDB(); boolean isAllowed = findNext(currentOptionDB) != null; Log.d(TAG, String.format("isNextAllowed()->%b", isAllowed)); return isAllowed; }
Source:
<code>public char[] reqPassword(Resource<?> resource) { if (console == null) { return null; } <START> return console.readPassword("Enter passphrase for %s:", resource.toString()); <END> }</code><technical_language>String a parameter class, in users customize message user sees. add a max number of retries a parameter</technical_language>

Target:
public char[] reqPassword(Resource<?> resource) { numTries++; if (console == null) { return null; } return console.readPassword(promptFormat, resource.toString()); }
Source:
<code>public boolean matches(String theLeftString, String theRightString) { try { return myStringEncoder.encode(theLeftString).equals(myStringEncoder.encode(theRightString)); } catch (EncoderException e) { <START> ourLog.error("Failed to match strings '" + theLeftString + "' and '" + theRightString + "' using encoder " + myStringEncoder.getClass().getName(), e); <END> } return false; }</code><technical_language>nitpick: I do Log formatting instead of string concatenation</technical_language>

Target:
public boolean matches(String theLeftString, String theRightString) { try { return myStringEncoder.encode(theLeftString).equals(myStringEncoder.encode(theRightString)); } catch (EncoderException e) { ourLog.error("Failed to match strings '{}' and '{}' using encoder {}", theLeftString, theRightString, myStringEncoder.getClass().getName(), e); } return false; }
Source:
<code><START> public void increaseEventProcessors(final int delta) { <END> synchronized (eventProcessors) { final int currNum = eventProcessors.size(); final int increaseNum = Math.min(delta, eventProcessorUpperBound - currNum); if (increaseNum != 0) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Increase event processors from {0} to {1}", new Object[]{currNum, currNum + increaseNum}); } addNewThreadsToSet(increaseNum); } } }</code><technical_language>delta < 0</technical_language>

Target:
public void increaseEventProcessors(final int delta) { if (delta < 0) { throw new RuntimeException("The delta value should be greater than zero, but " + delta); } synchronized (eventProcessors) { final int currNum = eventProcessors.size(); final int increaseNum = Math.min(delta, eventProcessorUpperBound - currNum); if (increaseNum != 0) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Increase event processors from {0} to {1}", new Object[]{currNum, currNum + increaseNum}); } addNewThreadsToSet(increaseNum); } } }
Source:
<code>public void call(Subscriber<? super T> observer) { <START> responseSubject.onBackpressureBuffer().subscribe(observer); <END> }</code><technical_language>I onBackpressureBuffer is needed unbounded ReplaySubject already</technical_language>

Target:
public void call(Subscriber<? super T> observer) { responseSubject.unsafeSubscribe(observer); }
Source:
<code>public void skip(int n) { <START> if (indexInStream + n > numberOfValues || n < 0) { <END> String errorMessage = String.format( "Cannot skip this many elements. Current index: %d. Skip %d. Total number of elements: %d", indexInStream, n, numberOfValues); throw new ParquetDecodingException(errorMessage); } indexInStream += n; }</code><technical_language>big deal 'n < 0 || indexInStream + n > numberOfValues' is 'indexInStream + n > numberOfValues || n < 0)'</technical_language>

Target:
public void skip(int n) { if (n < 0 || indexInStream + n > valuesCount) { String errorMessage = String.format( "Cannot skip this many elements. Current index: %d. Skip %d. Total number of elements: %d", indexInStream, n, valuesCount); throw new ParquetDecodingException(errorMessage); } indexInStream += n; }
Source:
<code><START> public StringBuilder getBuffer() <END> { return this.buffer; }</code><technical_language>This is API breakage</technical_language>

Target:
public StringBuffer getBuffer() { return this.buffer; }
Source:
<code>protected void onInit() throws ServletException { <START> LogoutController c = new LogoutController(getConfig()); <END> c.setLogoutInvalidateHttpSession(getConfig().isLogoutInvalidateHttpSession()) .setLogoutNextUri(getConfig().getLogoutControllerConfig().getNextUri()); setController(c); super.onInit(); }</code><technical_language>In general @lhazlewood idea of passing configuration objects around. Configuration get data initializing things. Passing config object a runtime issue if object get some some point is present is invalid. want break boot time runtime. I agree Les passing configuration objects discouraged. unnecessary coupling</technical_language>

Target:
protected void onInit() throws ServletException { LogoutController c = new LogoutController(getConfig().getLogoutControllerConfig(), getConfig().getProducesMediaTypes()); c.setLogoutInvalidateHttpSession(getConfig().isLogoutInvalidateHttpSession()) .setLogoutNextUri(getConfig().getLogoutControllerConfig().getNextUri()); setController(c); super.onInit(); }
Source:
<code>public ArticleCard(String webUrl) throws CardBuilderException { <START> this.cardType = CardType.ARTICLE; <END> webUrl(webUrl); MetaTagModel metaTagModel = MetaTagExtractor.getMetaTags(this.webUrl); article(new ArticleBuilder(metaTagModel).build()); }</code><technical_language>shouldnt this call super() metatagmodel exists in AbstractCard</technical_language>

Target:
public ArticleCard(String webUrl) throws CardBuilderException { super(webUrl); this.cardType = CardType.ARTICLE; article(new ArticleBuilder(this.getMetaTagModel()).build()); }
Source:
<code>public JingleS5BTransport build() { <START> StringUtils.requireNotNullOrEmpty(streamId, "sid MUST be neither null, nor empty."); <END> return new JingleS5BTransport(candidates, infos, streamId, dstAddr, mode); }</code><technical_language>verification is performed late possible, means in constructor. in build() method</technical_language>

Target:
public JingleS5BTransport build() { return new JingleS5BTransport(candidates, infos, streamId, dstAddr, mode); }
Source:
<code>public String formatWithConflicts(String message, List<String> conflictingPaths) { StringBuilder sb = new StringBuilder(); String[] lines = message.split("\n"); int firstFooterLine = ChangeIdUtil.findFirstFooterLine(lines); <START> for (int i = 0; i < firstFooterLine; i++) { <END> sb.append(lines[i]).append("\n"); } if (firstFooterLine == lines.length && message.length() != 0) sb.append("\n"); addConflictsMessage(conflictingPaths, sb); if (firstFooterLine < lines.length) sb.append("\n"); for (int i = firstFooterLine; i < lines.length; i++) { sb.append(lines[i]).append("\n"); } return sb.toString(); }</code><technical_language>style nit: braces</technical_language>

Target:
public String formatWithConflicts(String message, List<String> conflictingPaths) { StringBuilder sb = new StringBuilder(); String[] lines = message.split("\n"); int firstFooterLine = ChangeIdUtil.indexOfFirstFooterLine(lines); for (int i = 0; i < firstFooterLine; i++) sb.append(lines[i]).append('\n'); if (firstFooterLine == lines.length && message.length() != 0) sb.append('\n'); addConflictsMessage(conflictingPaths, sb); if (firstFooterLine < lines.length) sb.append('\n'); for (int i = firstFooterLine; i < lines.length; i++) sb.append(lines[i]).append('\n'); return sb.toString(); }
Source:
<code>public void update(Storable storable) { <START> if (queryExecutor.update(storable) == 0) { <END> log.warn("Update storable '{}' returned 0 rows, possible concurrent update"); throw new ConcurrentUpdateException("Row could not be updated, possible concurrent update"); } }</code><technical_language>I relation updating 0 rows concurrent update? ConcurrentUpdateException thrown in queryExecutor.update(storable) method instead</technical_language>

Target:
public void update(Storable storable) { if (queryExecutor.update(storable) == 0) { log.warn("Update storable '{}' returned 0 rows, possible concurrent update or invalid primary key"); throw new ConcurrentUpdateException("Row could not be updated, possible concurrent update or invalid primary key"); } }
Source:
<code><START> public FactoryDto createFactoryFromJson(String jsonFileLocation) { <END> if (jsonFileLocation != null) { final String factoryJsonContent = urlFetcher.fetch(jsonFileLocation); if (!Strings.isNullOrEmpty(factoryJsonContent)) { return DtoFactory.getInstance().createDtoFromJson(factoryJsonContent, FactoryDto.class); } } return null; }</code><technical_language>If method is designed return optional result is java.util.Optional more clear. So, please consider Optional</technical_language>

Target:
public Optional<FactoryDto> createFactoryFromJson(String jsonFileLocation) { if (jsonFileLocation != null) { final String factoryJsonContent = urlFetcher.fetch(jsonFileLocation); if (!Strings.isNullOrEmpty(factoryJsonContent)) { return Optional.of( DtoFactory.getInstance().createDtoFromJson(factoryJsonContent, FactoryDto.class)); } } return Optional.empty(); }
Source:
<code>public Map<SubscriptionCursor, Boolean> commitCursors(final String streamId, final String subscriptionId, final List<SubscriptionCursor> cursors) throws NakadiException, InvalidCursorException { validateStreamId(cursors, streamId, subscriptionId); LOG.debug("[COMMIT_CURSORS] stream IDs validation finished"); final Iterator<EventTypePartition> distinctPartitions = cursors.stream() .map(c -> new EventTypePartition(c.getEventType(), c.getPartition())) <START> .distinct() <END> .iterator(); final HashMap<EventTypePartition, Iterator<Boolean>> partitionCommits = new HashMap<>(); while (distinctPartitions.hasNext()) { final EventTypePartition etPartition = distinctPartitions.next(); final List<SubscriptionCursor> partitionCursors = cursors.stream() .filter(etPartition::ownsCursor) .collect(Collectors.toList()); final Iterator<Boolean> commitResultIterator = processPartitionCursors(subscriptionId, partitionCursors, etPartition).iterator(); partitionCommits.put(etPartition, commitResultIterator); LOG.debug("[COMMIT_CURSORS] committed cursor(s) for partition {}", partitionCursors.size(), etPartition); } return cursors.stream() .collect(Collectors.toMap( Function.identity(), cursor -> { final EventTypePartition etPartition = new EventTypePartition(cursor.getEventType(), cursor.getPartition()); return partitionCommits.get(etPartition).next(); } )); }</code><technical_language>This strange provide comparator for instead a separate class hold values. I EventTypePartition class is in CursorsService, do good class</technical_language>

Target:
public List<CursorCommitResult> commitCursors(final String streamId, final String subscriptionId, final List<SubscriptionCursor> cursors) throws ServiceUnavailableException, InvalidCursorException, InvalidStreamIdException, NoSuchEventTypeException, InternalNakadiException { validateStreamId(cursors, streamId, subscriptionId); LOG.debug("[COMMIT_CURSORS] stream IDs validation finished"); final Map<EventTypePartition, List<SubscriptionCursor>> cursorsByPartition = cursors.stream() .collect(Collectors.groupingBy( cursor -> new EventTypePartition(cursor.getEventType(), cursor.getPartition()))); final HashMap<EventTypePartition, Iterator<Boolean>> partitionCommits = new HashMap<>(); for (final EventTypePartition etPartition : cursorsByPartition.keySet()) { final Iterator<Boolean> commitResultIterator = processPartitionCursors(subscriptionId, cursorsByPartition.get(etPartition), etPartition).iterator(); partitionCommits.put(etPartition, commitResultIterator); LOG.debug("[COMMIT_CURSORS] committed cursor(s) for partition {}", cursorsByPartition.get(etPartition).size(), etPartition); } return cursors.stream() .map(cursor -> { final EventTypePartition etPartition = new EventTypePartition(cursor.getEventType(), cursor.getPartition()); final Boolean committed = partitionCommits.get(etPartition).next(); return new CursorCommitResult(cursor, committed); }) .collect(Collectors.toList()); }
Source:
<code>public static Archive<?> createTestArchive() { <START> return ClassPath.builder().add(ShrinkWrap.create(BeanArchive.class, Utils.getDeploymentNameAsHash(WeldInstanceTest.class)) <END> .addPackage(ParallelNotificationModeTest.class.getPackage())).build(); }</code><technical_language>noticed minor - referencing another test in Utils.getDeploymentNameAsHash</technical_language>

Target:
public static Archive<?> createTestArchive() { return ClassPath.builder().add(ShrinkWrap.create(BeanArchive.class, Utils.getDeploymentNameAsHash(ParallelNotificationModeTest.class)) .addPackage(ParallelNotificationModeTest.class.getPackage())).build(); }
Source:
<code>public WebResponse getResponse(final Ds3Request request) throws IOException, SignatureException { assertThat(request.getVerb(), is(this.verb)); assertThat(request.getPath(), is(this.path)); if (this.queryParams != null) { this.assertMapsEqual(this.queryParams, request.getQueryParams()); } if(this.requestHeaders != null){ assertThat(this.requestHeaders.size(), is(request.getHeaders().size())); assertTrue(Iterables.elementsEqual(this.requestHeaders.keySet(), request.getHeaders().keySet())); <START> for (String key : this.requestHeaders.keySet()){ <END> assertThat(this.requestHeaders.get(key), is(notNullValue())); assertThat(request.getHeaders().get(key), is(notNullValue())); assertTrue(Iterables.elementsEqual(this.requestHeaders.get(key), request.getHeaders().get(key))); } } if (this.requestContent != null) { final InputStream stream = request.getStream(); assertThat(stream, is(notNullValue())); assertThat(IOUtils.toString(stream), is(this.requestContent)); } return new MockedWebResponse(this.responseContent, this.statusCode, this.headers); }</code><technical_language>key final in front of type declaration</technical_language>

Target:
public WebResponse getResponse(final Ds3Request request) throws IOException, SignatureException { assertThat(request.getVerb(), is(this.verb)); assertThat(request.getPath(), is(this.path)); if (this.queryParams != null) { this.assertMapsEqual(this.queryParams, request.getQueryParams()); } if(this.requestHeaders != null){ assertThat(this.requestHeaders.size(), is(request.getHeaders().size())); assertTrue(Iterables.elementsEqual(this.requestHeaders.keySet(), request.getHeaders().keySet())); for (final String key : this.requestHeaders.keySet()){ assertThat(this.requestHeaders.get(key), is(notNullValue())); assertThat(request.getHeaders().get(key), is(notNullValue())); assertTrue(Iterables.elementsEqual(this.requestHeaders.get(key), request.getHeaders().get(key))); } } if (this.requestContent != null) { final InputStream stream = request.getStream(); assertThat(stream, is(notNullValue())); assertThat(IOUtils.toString(stream), is(this.requestContent)); } return new MockedWebResponse(this.responseContent, this.statusCode, this.headers); }
Source:
<code>public Object getPayload(CorfuRuntime runtime) { Object value = payload.get(); if (value == null) { synchronized (this.payload) { value = this.payload.get(); if (value == null) { if (data == null) { this.payload.set(null); } else { try { ByteBuf copyBuf = Unpooled.wrappedBuffer(data); final Object actualValue = <START> Serializers.CORFU.deserialize(copyBuf, runtime); <END> if (actualValue instanceof LogEntry) { ((LogEntry) actualValue).setGlobalAddress(getGlobalAddress()); ((LogEntry) actualValue).setRuntime(runtime); } value = actualValue == null ? this.payload : actualValue; this.payload.set(value); copyBuf.release(); lastKnownSize = data.length; data = null; } catch (Throwable throwable) { log.error("Exception caught at address {}, {}, {}", getGlobalAddress(), getStreams(), getType()); throw throwable; } } } } } return value; }</code><technical_language>Limit scope of try/catch deserialize line</technical_language>

Target:
public Object getPayload(CorfuRuntime runtime) { Object value = payload.get(); if (value == null) { synchronized (this.payload) { value = this.payload.get(); if (value == null) { if (data == null) { this.payload.set(null); } else { ByteBuf copyBuf = Unpooled.wrappedBuffer(data); final Object actualValue; try { actualValue = Serializers.CORFU.deserialize(copyBuf, runtime); } catch (Throwable throwable) { log.error("Exception caught at address {}, {}, {}", getGlobalAddress(), getStreams(), getType()); copyBuf.release(); data = null; throw throwable; } if (actualValue instanceof LogEntry) { ((LogEntry) actualValue).setGlobalAddress(getGlobalAddress()); ((LogEntry) actualValue).setRuntime(runtime); } value = actualValue == null ? this.payload : actualValue; this.payload.set(value); copyBuf.release(); lastKnownSize = data.length; data = null; } } } } return value; }
Source:
<code>public void addMetric(final IMetric<?> metric) { <START> if (metric != null && getMetricFromName(metric.getName()) == null) { <END> _logger.debug(String.format("Adding %s metric in Metric Manager", metric.getName())); _metrics.add(metric); metric.updateMetricManager(this); } else { _logger.error("Failed to add metric"); } }</code><technical_language>sense separate this out cases? 1) Argument metric is null -> throw IllegalArgumentException 2) getMetricFromName(metric.getName()) == null</technical_language>

Target:
public void addMetric(final IMetric<?> metric) { if(metric == null) throw new IllegalArgumentException("Cannot add a null metric"); if (getMetricFromName(metric.getName()) == null) { logger.debug(String.format("Adding %s metric in Metric Manager", metric.getName())); metrics.add(metric); metric.updateMetricManager(this); } else { logger.error("Failed to add metric"); } }
Source:
<code>public void testHandle() throws Exception { Callback[] callbackList = new Callback[1]; SAMLCallback samlCallback = new SAMLCallback(); callbackList[0] = samlCallback; final Message message = mock(Message.class); AssertionType assertionType = mock(AssertionType.class); HOKSAMLAssertionBuilder builder = mock(HOKSAMLAssertionBuilder.class); <START> PropertyAccessor accessor = mock(PropertyAccessor.class); <END> CXFSAMLCallbackHandler callbackHandler = new CXFSAMLCallbackHandler(builder) { @Override protected Message getCurrentMessage() { return message; } }; when(message.get("assertion")).thenReturn(assertionType); when(message.get(Message.INBOUND_MESSAGE)).thenReturn(false); when(message.get(NhincConstants.WS_SOAP_TARGET_HOME_COMMUNITY_ID)).thenReturn("1.1"); when(message.get(NhincConstants.TARGET_API_LEVEL)).thenReturn("G0"); when(message.get(NhincConstants.ACTION_PROP)).thenReturn("Soap Action"); when(builder.build(any(CallbackProperties.class))).thenReturn(assertionElement); callbackHandler.handle(callbackList); assertEquals(samlCallback.getSamlVersion(), org.opensaml.saml.common.SAMLVersion.VERSION_20); assertEquals(samlCallback.getAssertionElement().getTextContent(), ASSERTION); }</code><technical_language>remove accessor variable if use</technical_language>

Target:
public void testHandle() throws Exception { Callback[] callbackList = new Callback[1]; SAMLCallback samlCallback = new SAMLCallback(); callbackList[0] = samlCallback; final Message message = mock(Message.class); AssertionType assertionType = mock(AssertionType.class); HOKSAMLAssertionBuilder builder = mock(HOKSAMLAssertionBuilder.class); CXFSAMLCallbackHandler callbackHandler = new CXFSAMLCallbackHandler(builder) { @Override protected Message getCurrentMessage() { return message; } }; when(message.get("assertion")).thenReturn(assertionType); when(message.get(Message.INBOUND_MESSAGE)).thenReturn(false); when(message.get(NhincConstants.WS_SOAP_TARGET_HOME_COMMUNITY_ID)).thenReturn("1.1"); when(message.get(NhincConstants.TARGET_API_LEVEL)).thenReturn("G0"); when(message.get(NhincConstants.ACTION_PROP)).thenReturn("Soap Action"); when(builder.build(any(CallbackProperties.class))).thenReturn(assertionElement); callbackHandler.handle(callbackList); assertEquals(samlCallback.getSamlVersion(), org.opensaml.saml.common.SAMLVersion.VERSION_20); assertEquals(samlCallback.getAssertionElement().getTextContent(), ASSERTION); }
Source:
<code>protected Metric constructMetric(String metricField, Class<?> cls, EntityDictionary entityDictionary) { Meta metaData = entityDictionary.getAttributeOrRelationAnnotation(cls, Meta.class, metricField); Class<?> fieldType = entityDictionary.getType(cls, metricField); return isBaseMetric(metricField, cls) ? new EntityMetric( metricField, metaData == null || metaData.longName().isEmpty() ? metricField : metaData.longName(), metaData == null || metaData.description().isEmpty() ? metricField : metaData.description(), fieldType, extractDefaultAggregation(metricField, cls), extractNonDefaultAggregations(metricField, cls) ) : new EntityMetric( metricField, metaData == null || metaData.longName().isEmpty() ? metricField : metaData.longName(), metaData == null || metaData.description().isEmpty() ? metricField : metaData.description(), fieldType, extractDefaultAggregation(metricField, cls), extractNonDefaultAggregations(metricField, cls), <START> getExpandedMetricExpression(metricField, cls, new HashSet<>()) <END> ); }</code><technical_language>metric constructor generate this itself</technical_language>

Target:
protected Metric constructMetric(String metricField, Class<?> cls, EntityDictionary entityDictionary) { Meta metaData = entityDictionary.getAttributeOrRelationAnnotation(cls, Meta.class, metricField); Class<?> fieldType = entityDictionary.getType(cls, metricField); List<Class<? extends Aggregation>> aggregations = Arrays.stream( entityDictionary.getAttributeOrRelationAnnotation( cls, MetricAggregation.class, metricField ).aggregations() ) .collect( Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList ) ); return new AggregatedMetric( metricField, metaData, fieldType, aggregations ); }
Source:
<code>public void testDaemonShouldWaitForBuildSuccess() throws TimeoutException, InterruptedException { DaemonBuild daemonBuild = EmbeddedMaven .forProject(pathToJarSamplePom) .setGoals("package") .useAsDaemon() .withWaitUntilOutputLineMathes(".*BUILD SUCCESS.*") .build(); int timeout = 0; while (daemonBuild.isAlive() && timeout <= 20) { <START> Thread.sleep(500); <END> } Assertions.assertThat(timeout) .as("The build should have finish (not to be alive) within 10 seconds") .isLessThanOrEqualTo(10); Assertions.assertThat(daemonBuild.getBuiltProject()).isNotNull(); verifyJarSampleSimpleBuild(daemonBuild.getBuiltProject()); verifyJarSampleContainsOnlyOneJar(daemonBuild.getBuiltProject()); }</code><technical_language>awaitility</technical_language>

Target:
public void testDaemonShouldWaitForBuildSuccess() throws TimeoutException, InterruptedException { final DaemonBuild daemonBuild = EmbeddedMaven .forProject(pathToJarSamplePom) .setGoals("package") .useAsDaemon() .withWaitUntilOutputLineMathes(".*BUILD SUCCESS.*") .build(); Awaitility.await("Wait till thread is not be alive").atMost(20, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return !daemonBuild.isAlive(); } }); Assertions.assertThat(daemonBuild.getBuiltProject()).isNotNull(); verifyJarSampleSimpleBuild(daemonBuild.getBuiltProject()); verifyJarSampleContainsOnlyOneJar(daemonBuild.getBuiltProject()); }
Source:
<code>public HttpClient build(String name) { final BasicHttpParams params = createHttpParams(name); final InstrumentedClientConnManager manager = createConnectionManager(registry, name); final InstrumentedHttpClient client = new InstrumentedHttpClient(metricRegistry, manager, params, name); <START> client.setCredentialsProvider(credentialsProvider); <END> setStrategiesForClient(client); return client; }</code><technical_language>please move this setStrategiesForClient set credentials provider if credentialsProvider is null? While is currently default behaviour of Apache HttpClient, change in future want get NPEs of a sudden. :wink:</technical_language>

Target:
public HttpClient build(String name) { final BasicHttpParams params = createHttpParams(name); final InstrumentedClientConnManager manager = createConnectionManager(registry, name); final InstrumentedHttpClient client = new InstrumentedHttpClient(metricRegistry, manager, params, name); setStrategiesForClient(client); return client; }
Source:
<code>public void cluster_state_dump() throws Exception { put(0, "pets", "pet1", "Cubitus"); Properties properties = new Properties(); properties.setProperty(ConnectionPropertyNames.CONNECTION_TIMEOUT, "5000"); properties.setProperty(ConnectionPropertyNames.CONNECTION_NAME, "diagnostic"); properties.setProperty(PROP_REQUEST_TIMEOUT, "5000"); properties.setProperty(PROP_REQUEST_TIMEOUTMESSAGE, "5000"); URI uri = URI.create("diagnostic://" + voltron.getConnectionURI().getAuthority()); try (Connection connection = ConnectionFactory.connect(uri, properties)) { EntityRef<Diagnostics, Object, Void> ref = connection.getEntityRef(Diagnostics.class, 1, "root"); Diagnostics diagnostics = ref.fetchEntity(null); String dump = diagnostics.getClusterState(); <START> try (Stream<String> lines = Files.lines(Paths.get(getClass().getResource("/sate-dump-partial.txt").toURI()))) { <END> lines.forEach(line -> { assertThat(dump, dump, containsString(line)); }); } } }</code><technical_language>no: lines in order some lines in real dump skip. I some important lines</technical_language>

Target:
public void cluster_state_dump() throws Exception { put(0, "pets", "pet1", "Cubitus"); Properties properties = new Properties(); properties.setProperty(ConnectionPropertyNames.CONNECTION_TIMEOUT, "5000"); properties.setProperty(ConnectionPropertyNames.CONNECTION_NAME, "diagnostic"); properties.setProperty(PROP_REQUEST_TIMEOUT, "5000"); properties.setProperty(PROP_REQUEST_TIMEOUTMESSAGE, "5000"); URI uri = URI.create("diagnostic://" + voltron.getConnectionURI().getAuthority()); try (Connection connection = ConnectionFactory.connect(uri, properties)) { EntityRef<Diagnostics, Object, Void> ref = connection.getEntityRef(Diagnostics.class, 1, "root"); Diagnostics diagnostics = ref.fetchEntity(null); String dump = diagnostics.getClusterState(); System.out.println(dump); try (Stream<String> lines = Files.lines(Paths.get(getClass().getResource("/sate-dump-partial.txt").toURI()))) { lines.forEach(line -> { assertThat(dump, dump, containsString(line)); }); } } }
Source:
<code>private synchronized Subject getSubject(String ipAddress) { Subject subject = cachedGuestSubjectMap.get(ipAddress); if (subject == null) { GuestAuthenticationToken token = new GuestAuthenticationToken(ipAddress); LOGGER.debug("Getting new Guest user token for {}", ipAddress); try { subject = securityManager.getSubject(token); cachedGuestSubjectMap.put(ipAddress, subject); <START> } catch (SecurityServiceException sse) { <END> LOGGER.info("Unable to request subject for guest user.", sse); } } else { LOGGER.debug("Using cached Guest user token for {}", ipAddress); } return subject; }</code><technical_language>Do need a ticket for this track someway</technical_language>

Target:
private synchronized Subject getSubject(String ipAddress) { Subject subject = guestSubjectCache.getIfPresent(ipAddress); if (subject == null) { GuestAuthenticationToken token = new GuestAuthenticationToken(ipAddress); LOGGER.debug("Getting new Guest user token for {}", ipAddress); try { subject = securityManager.getSubject(token); guestSubjectCache.put(ipAddress, subject); } catch (SecurityServiceException sse) { LOGGER.info("Unable to request subject for guest user.", sse); } } else { LOGGER.debug("Using cached Guest user token for {}", ipAddress); } return subject; }
Source:
<code>public void failure(RetrofitError retrofitError) { if (isCancelled || getContext() == null) { return; } finishLoading(); Log.e(APIHelpers.LOG_TAG, "ERROR: " + retrofitError.getUrl()); Log.e(APIHelpers.LOG_TAG, "ERROR: " + retrofitError.getMessage()); if (onFailure(retrofitError)) { return; } if (errorDelegate == null) { Log.d(APIHelpers.LOG_TAG, "WARNING: No ErrorDelegate Provided "); return; } CanvasError canvasError; switch (retrofitError.getKind()) { case CONVERSION: canvasError = CanvasError.createError("Conversion Error", "An exception was thrown while (de)serializing a body"); <START> errorDelegate.generalError(retrofitError, canvasError, getContext()); <END> break; case HTTP: handleHTTPError(retrofitError); break; case NETWORK: statusDelegate.onNoNetwork(); errorDelegate.noNetworkError(retrofitError, getContext()); break; case UNEXPECTED: canvasError = CanvasError.createError("Unexpected Error", "An internal error occurred while attempting to execute a request."); errorDelegate.generalError(retrofitError, canvasError, getContext()); break; } }</code><technical_language>this switch statement need a default</technical_language>

Target:
public void failure(RetrofitError retrofitError) { if (isCancelled || getContext() == null) { return; } finishLoading(); Log.e(APIHelpers.LOG_TAG, "ERROR: " + retrofitError.getUrl()); Log.e(APIHelpers.LOG_TAG, "ERROR: " + retrofitError.getMessage()); if (onFailure(retrofitError)) { return; } if (errorDelegate == null) { Log.d(APIHelpers.LOG_TAG, "WARNING: No ErrorDelegate Provided "); return; } CanvasError canvasError; switch (retrofitError.getKind()) { case CONVERSION: canvasError = CanvasError.createError("Conversion Error", "An exception was thrown while (de)serializing a body"); errorDelegate.generalError(retrofitError, canvasError, getContext()); break; case HTTP: handleHTTPError(retrofitError); break; case NETWORK: statusDelegate.onNoNetwork(); errorDelegate.noNetworkError(retrofitError, getContext()); break; case UNEXPECTED: canvasError = CanvasError.createError("Unexpected Error", "An internal error occurred while attempting to execute a request."); errorDelegate.generalError(retrofitError, canvasError, getContext()); break; default: canvasError = CanvasError.createError("Unexpected Error", "An unexpected error occurred."); errorDelegate.generalError(retrofitError, canvasError, getContext()); break; } }
Source:
<code>private ExtensionsManager() { for (File directory : EngineLocalConfig.getInstance().getExtensionsDirectories()) { <START> loadDirectory(directory); <END> } }</code><technical_language>time funciton^ perform loop here</technical_language>

Target:
private ExtensionsManager() { for (File directory : EngineLocalConfig.getInstance().getExtensionsDirectories()) { if (!directory.exists()) { log.warn(String.format("The directory '%1$s' cotaning configuration files does not exist.", directory.getAbsolutePath())); } else { File[] files = directory.listFiles(); if (files != null) { sort(files); for (File file : files) { if (file.getName().endsWith(".properties")) { load(file); } } } } } }
Source:
<code>public void testUpgradingv1Tov2() throws IOException { final ClassLoader classLoader = this.getClass().getClassLoader(); try (final InputStream v1InputStream = classLoader.getResource("loadv1.schematic").openStream(); final InputStream v2InputStream = classLoader.getResource("loadv2.schematic").openStream()) { <START> final DataContainer v1Container = DataFormats.NBT.readFrom(new GZIPInputStream(v1InputStream)); <END> final Schematic v1Schem = DataTranslators.SCHEMATIC.translate(v1Container); final DataContainer v2Container = DataFormats.NBT.readFrom(new GZIPInputStream(v2InputStream)); final Schematic v2Schem = DataTranslators.SCHEMATIC.translate(v2Container); assertEquals(v1Schem, v2Schem); } }</code><technical_language>~~that's better, GZIPInputStream is closed~~ whoops, gabi is right. Actually, need try resources all. @clienthax update PR</technical_language>

Target:
public void testUpgradingv1Tov2() throws IOException { final ClassLoader classLoader = this.getClass().getClassLoader(); try (final InputStream v1InputStream = classLoader.getResource("loadv1.schematic").openStream(); final InputStream v2InputStream = classLoader.getResource("loadv2.schematic").openStream(); final GZIPInputStream v1GzipInputStream = new GZIPInputStream(v1InputStream); final GZIPInputStream v2GzipInputStream = new GZIPInputStream(v2InputStream)){ final DataContainer v1Container = DataFormats.NBT.readFrom(v1GzipInputStream); final Schematic v1Schem = DataTranslators.SCHEMATIC.translate(v1Container); final DataContainer v2Container = DataFormats.NBT.readFrom(v2GzipInputStream); final Schematic v2Schem = DataTranslators.SCHEMATIC.translate(v2Container); assertEquals(v1Schem, v2Schem); } }
Source:
<code><START> public void insertToRealm_CyclicType() { <END> CyclicType oneCyclicType = new CyclicType(); oneCyclicType.setName("One"); CyclicType anotherCyclicType = new CyclicType(); anotherCyclicType.setName("Two"); oneCyclicType.setObject(anotherCyclicType); anotherCyclicType.setObject(oneCyclicType); realm.beginTransaction(); realm.insert(oneCyclicType); realm.commitTransaction(); CyclicType realmObject = realm.where(CyclicType.class).findFirst(); assertEquals("One", realmObject.getName()); assertEquals("Two", realmObject.getObject().getName()); assertEquals(2, realm.where(CyclicType.class).count()); }</code><technical_language>test missing for insertOrUpdate</technical_language>

Target:
public void insertToRealm_CyclicType() { CyclicType oneCyclicType = new CyclicType(); oneCyclicType.setName("One"); CyclicType anotherCyclicType = new CyclicType(); anotherCyclicType.setName("Two"); oneCyclicType.setObject(anotherCyclicType); anotherCyclicType.setObject(oneCyclicType); realm.beginTransaction(); realm.insert(Arrays.asList(oneCyclicType, anotherCyclicType)); realm.commitTransaction(); RealmResults<CyclicType> realmObjects = realm.where(CyclicType.class).findAllSorted(CyclicType.FIELD_NAME); assertNotNull(realmObjects); assertEquals(2, realmObjects.size()); assertEquals("One", realmObjects.get(0).getName()); assertEquals("Two", realmObjects.get(0).getObject().getName()); }
Source:
<code>public void publishDiagnostics(PublishDiagnosticsParams diagnostics) { <START> String v = diagnostics.getDiagnostics().get(0).getMessage(); <END> this.observer.notify(v); if(v.equals("VALID")) { System.out.println("String is VALID"); } else if (v.equals("INVALID")) { System.out.println("String is INVALID"); } }</code><technical_language>more meaningful variable names please ;-)</technical_language>

Target:
public void publishDiagnostics(PublishDiagnosticsParams diagnostics) { observer.diagnostic(diagnostics.getDiagnostics()); Runnable completionTask = () -> { CompletionParams completionParams = new CompletionParams(); Position position = new Position(); position.setLine(0); position.setCharacter(cursor); completionParams.setPosition(position); try { Either<List<CompletionItem>, CompletionList> completion = serverProxy.getTextDocumentService().completion(completionParams).get(); observer.completion(completion); } catch (Exception e) { e.printStackTrace(); } }; Runnable syntaxHighlightingTask = () -> { DocumentColorParams colorParams = new DocumentColorParams(); try { List<ColorInformation> colors = serverProxy.getTextDocumentService().documentColor(colorParams).get(); } catch (Exception e) { e.printStackTrace(); } }; threadPoolExecutor.execute(syntaxHighlightingTask); }
Source:
<code>public void normalClearFromDataStore() { accessor.invoke(() -> feed(false)); <START> dataStore1.invoke(() -> verifyRegionSize(false, NUM_ENTRIES)); dataStore2.invoke(() -> verifyRegionSize(false, NUM_ENTRIES)); dataStore3.invoke(() -> verifyRegionSize(false, NUM_ENTRIES)); dataStore1.invoke(() -> getRegion(false).clear()); dataStore1.invoke(() -> verifyRegionSize(false, 0)); dataStore2.invoke(() -> verifyRegionSize(false, 0)); dataStore3.invoke(() -> verifyRegionSize(false, 0)); <END> }</code><technical_language>verifications of region size data stores called multiple times in multiple tests. extracted helper methods reduce code duplication</technical_language>

Target:
public void normalClearFromDataStore() { accessor.invoke(() -> feed(false)); verifyServerRegionSize(NUM_ENTRIES); dataStore1.invoke(() -> getRegion(false).clear()); verifyServerRegionSize(0); verifyCacheListenerTriggerCount(dataStore1); }
Source:
<code>public void initializeZipkinKafkaCollector() { if (zookeeper == null) { <START> return; <END> } if (spanPublisher == null) { throw new IllegalStateException("Span publisher is null!"); } log.infof("Initializing Zipkin kafka collector"); KafkaCollector kafkaCollector = KafkaCollector.builder() .zookeeper(this.zookeeper) .storage(new JMSZipkinStorage(spanPublisher)) .build(); kafkaCollector.start(); }</code><technical_language>this reported error</technical_language>

Target:
public void initializeZipkinKafkaCollector() { if (PropertyUtil.getKafkaZookeeper() == null) { return; } if (spanPublisher == null) { throw new IllegalStateException("Span publisher is null!"); } log.infof("Initializing Zipkin kafka collector"); KafkaCollector kafkaCollector = KafkaCollector.builder() .zookeeper(PropertyUtil.getKafkaZookeeper()) .storage(new APMZipkinSpanStorage(spanPublisher)) .build(); kafkaCollector.start(); }
Source:
<code>public Document decodeFromStream(final DataInputStream dais) { try { final int size = dais.readInt(); final int[] words = new int[size]; for (int i = 0; i < size; i++) { final int word = dais.readInt(); words[i] = word; } <START> return new Document(words, numTopics); <END> } catch (final IOException e) { throw new RuntimeException(e); } }</code><technical_language>question: deserialize, assignments topicCounts, initialize random variables. this imply loss of learned parameters? @gyeongin Do a clue</technical_language>

Target:
public Document decodeFromStream(final DataInputStream dais) { try { final int numWords = dais.readInt(); final int[] words = new int[numWords]; final int[] assignments = new int[numWords]; final int[] topicCounts = new int[numTopics]; for (int wordIdx = 0; wordIdx < numWords; wordIdx++) { words[wordIdx] = dais.readInt(); } for (int wordIdx = 0; wordIdx < numWords; wordIdx++) { assignments[wordIdx] = dais.readInt(); } for (int topicIdx = 0; topicIdx < numTopics; topicIdx++) { topicCounts[topicIdx] = dais.readInt(); } return new Document(words, assignments, topicCounts, numTopics); } catch (final IOException e) { throw new RuntimeException(e); } }
Source:
<code><START> public Iterable<String> getKeysToRemove() { <END> return KEYS_TO_REMOVE; }</code><technical_language>this protected (and in @Overriden)</technical_language>

Target:
protected Iterable<String> getKeysToRemove() { return KEYS_TO_REMOVE; }
Source:
<code>protected boolean repeatUntil(RepeatCompletion repeat) { repeatTime = 0; repeatTimer.start(); StopWatch loopTimer = new StopWatch(); loopTimer.start(); boolean result = false; try { try { result = repeat.isFinished(); } catch (RuntimeException e) { logger.warn("Error while checking we can stop repeating before starting loop", e); } for (repeatCount = 0; !result && repeatCount < repeatMaxCount; repeatCount++) { int nextInterval = getNextInterval(loopTimer); waitMilliseconds(nextInterval); loopTimer.start(); try { <START> repeat.repeat(); <END> result = repeat.isFinished(); } catch (RuntimeException e) { logger.warn("Error while checking whether we can stop repeating, loop count of {}", repeatCount, repeatMaxCount, e); } } } finally { repeatTime = repeatTimer.getTime(); repeatTimer.reset(); } return result; }</code><technical_language>moving this line break compatibility in situations 'repeat' throws exception for another reason (e.g. unable connect host)</technical_language>

Target:
protected boolean repeatUntil(RepeatCompletion repeat) { repeatTime = 0; repeatTimer.start(); StopWatch loopTimer = new StopWatch(); loopTimer.start(); boolean result = false; try { try { result = repeat.isFinished(); } catch (RuntimeException e) { logger.warn("Error while checking we can stop repeating before starting loop", e); } for (repeatCount = 0; !result && repeatCount < repeatMaxCount; repeatCount++) { int nextInterval = getNextInterval(loopTimer); waitMilliseconds(nextInterval); loopTimer.start(); repeat.repeat(); try { result = repeat.isFinished(); } catch (RuntimeException e) { logger.warn("Error while checking whether we can stop repeating, loop count of {}", repeatCount, repeatMaxCount, e); } } } finally { repeatTime = repeatTimer.getTime(); repeatTimer.reset(); } return result; }
Source:
<code>public void unregisterModuleMusic() { Json musicJson = Assets.getJson(currentlyRegisteredModule + ":musicConfig"); MusicConfig musicConfig = MusicConfig.load(currentlyRegisteredModule, musicJson.getJsonValue()); Map<String, List<String>> musicMap = musicConfig.getMusicMap(); int gameMusicSize = musicMap.get(GAME_MUSIC_SET).size(); <START> int menuMusicSize = musicMap.get(MENU_MUSIC_SET).size(); <END> for (int i = 1; i <= gameMusicSize; i++) { this.musicMap.get(GAME_MUSIC_SET).remove(this.musicMap.get(GAME_MUSIC_SET).size() - 1); } }</code><technical_language>do need this for</technical_language>

Target:
public void unregisterModuleMusic() { musicMap.get(GAME_MUSIC_SET).clear(); registerMusic(GAME_MUSIC_SET, "engine:cimmerianDawn"); registerMusic(GAME_MUSIC_SET, "engine:intoTheDark"); registerMusic(GAME_MUSIC_SET, "engine:spaceTheatre"); }
Source:
<code>private static String getPrefix() { StackTraceElement[] elems = Thread.currentThread().getStackTrace(); <START> StackTraceElement elem = elems[BASE_DEPTH]; END> if (elem.getClassName().startsWith("kotlin.io.")) { elem = elems[BASE_DEPTH + 2]; } else if (elem.getClassName().startsWith("java.lang.Throwable")) { elem = elems[BASE_DEPTH + 4]; } return "[" + elem.getClassName() + ":" + elem.getMethodName() + ":" + elem.getLineNumber() + "]: "; }</code><technical_language>This is ASKING for index out of bounds. protect in here</technical_language>

Target:
private static String getPrefix() { StackTraceElement[] elems = Thread.currentThread().getStackTrace(); StackTraceElement elem = elems[Math.min(BASE_DEPTH, elems.length - 1)]; if (elem.getClassName().startsWith("kotlin.io.")) { elem = elems[Math.min(BASE_DEPTH + 2, elems.length - 1)]; } else if (elem.getClassName().startsWith("java.lang.Throwable")) { elem = elems[Math.min(BASE_DEPTH + 4, elems.length - 1)]; } return "[" + elem.getClassName() + ":" + elem.getMethodName() + ":" + elem.getLineNumber() + "]: "; }