auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void captureVarargsPart(Invocation invocation) { if (!invocation.getMethod().isVarArgs()) { return; } int indexOfVararg = invocation.getRawArguments().length - 1; for (ArgumentMatcher m : uniqueMatcherSet(indexOfVararg)) { if (m instanceof CapturesArguments) { Object rawArgument = invocation.getRawArguments()[indexOfVararg]; <START> for (int i = 0; i < getLength(rawArgument); i++) { <END> ((CapturesArguments) m).captureFrom(getArgument(rawArgument, i)); } } } }</code><technical_language>Instead of magically changing length of array, I introduce if-else for-loop, intent clearer. this implementation is a hidden connection getLength getArgument</technical_language>

Target:
private void captureVarargsPart(Invocation invocation) { if (!invocation.getMethod().isVarArgs()) { return; } int indexOfVararg = invocation.getRawArguments().length - 1; for (ArgumentMatcher m : uniqueMatcherSet(indexOfVararg)) { if (m instanceof CapturesArguments) { Object rawArgument = invocation.getRawArguments()[indexOfVararg]; if (rawArgument != null) { for (int i = 0; i < Array.getLength(rawArgument); i++) { ((CapturesArguments) m).captureFrom(Array.get(rawArgument, i)); } } else { ((CapturesArguments) m).captureFrom(null); } } } }
Source:
<code>private void manageProcessDependenciesForIndex(Template template) throws CustomResponseException, IOException { Process process = template.getProcess(); <START> if (template.getIndexAction() == IndexAction.DELETE) { <END> if (process != null) { process.getTemplates().remove(template); serviceManager.getProcessService().saveToIndex(process); } } else { if (process != null) { serviceManager.getProcessService().saveToIndex(process); } } }</code><technical_language>A template exists a process. a process template</technical_language>

Target:
private void manageProcessDependenciesForIndex(Template template) throws CustomResponseException, IOException { Process process = template.getProcess(); if (template.getIndexAction() == IndexAction.DELETE) { process.getTemplates().remove(template); serviceManager.getProcessService().saveToIndex(process); } else { serviceManager.getProcessService().saveToIndex(process); } }
Source:
<code>private void addDnsConfiguration(ReportedConfigurations result) { if (!isDefaultRouteNetwork) { return; } List<NameServer> nameServersOfNetworkAttachment = getNameServers(networkAttachment.getDnsResolverConfiguration()); List<NameServer> nameServersOfNetwork = getNameServers(network.getDnsResolverConfiguration()); List<NameServer> nameServersOfHost = <START> getNameServers(vds.getDnsResolverConfiguration()); <END> boolean engineDoesNotContainDnsConfiguration = nameServersOfNetworkAttachment == null && nameServersOfNetwork == null; List<NameServer> expectedNameServers = nameServersOfNetworkAttachment != null ? nameServersOfNetworkAttachment : nameServersOfNetwork; boolean inSync = isDhcpUsed(networkAttachment) || engineDoesNotContainDnsConfiguration || Objects.equals(nameServersOfHost, expectedNameServers); result.add(DNS_CONFIGURATION, addressesAsString(nameServersOfHost), addressesAsString(expectedNameServers), inSync); }</code><technical_language>VDS is big object, try narrow DnsResolverConfiguration</technical_language>

Target:
private void addDnsConfiguration(ReportedConfigurations result) { if (!isDefaultRouteNetwork) { return; } List<NameServer> nameServersOfNetworkAttachment = getNameServers(networkAttachment.getDnsResolverConfiguration()); List<NameServer> nameServersOfNetwork = getNameServers(network.getDnsResolverConfiguration()); List<NameServer> nameServersOfHost = getNameServers(reportedDnsResolverConfiguration); boolean engineDoesNotContainDnsConfiguration = nameServersOfNetworkAttachment == null && nameServersOfNetwork == null; List<NameServer> expectedNameServers = nameServersOfNetworkAttachment != null ? nameServersOfNetworkAttachment : nameServersOfNetwork; boolean inSync = isDhcpUsed(networkAttachment) || engineDoesNotContainDnsConfiguration || Objects.equals(nameServersOfHost, expectedNameServers); result.add(DNS_CONFIGURATION, addressesAsString(nameServersOfHost), addressesAsString(expectedNameServers), inSync); }
Source:
<code>public String getText(Object element) { String text = super.getText(element); if (element instanceof ViewpointItemImpl) { ViewpointItemImpl viewpointItem = (ViewpointItemImpl) element; if (!viewpointItem.isViewpointEnabledInSession()) { text += " (" + Messages.GraphicalRepresentationHandler_disabledViewpoint_label + ")"; } } else if (element instanceof RepresentationDescriptionItemImpl) { RepresentationDescriptionItemImpl descriptionItem = (RepresentationDescriptionItemImpl) element; text += " (" + <START> descriptionItem.getChildren().size() + " " + Messages.GraphicalRepresentationHandler_representationNumber_label <END> + ")"; } return text; }</code><technical_language>a parameterized message instead. avoids hard-coding structure of message "$NUMBER $MESSAGE", in order, possibility for a prefix</technical_language>

Target:
public String getText(Object element) { String text = super.getText(element); if (element instanceof ViewpointItemImpl) { ViewpointItemImpl viewpointItem = (ViewpointItemImpl) element; if (!viewpointItem.isViewpointEnabledInSession()) { text += " (" + Messages.GraphicalRepresentationHandler_disabledViewpoint_label + ")"; } } else if (element instanceof RepresentationDescriptionItemImpl) { RepresentationDescriptionItemImpl descriptionItem = (RepresentationDescriptionItemImpl) element; text += MessageFormat.format(Messages.GraphicalRepresentationHandler_representationNumber_label, descriptionItem.getChildren().size()); } return text; }
Source:
<code>private boolean skipDispatch(HttpServletRequest request) { if (isAsyncDispatch(request) && shouldNotFilterAsyncDispatch()) { return true; } <START> return request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE) != null && shouldNotFilterErrorDispatch(); <END> }</code><technical_language>proposed changed is technically correct, please revert this for sake of readability</technical_language>

Target:
private boolean skipDispatch(HttpServletRequest request) { if (isAsyncDispatch(request) && shouldNotFilterAsyncDispatch()) { return true; } if (request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE) != null && shouldNotFilterErrorDispatch()) { return true; } return false; }
Source:
<code>protected void addStorageDomainStatusIllegalMessage() { addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2); StorageDomainStatus status = getStorageDomainStatus(); StorageDomainSharedStatus sharedStatus = getStorageDomainSharedStatus(); <START> Object messageParameter; if (status == StorageDomainStatus.Unknown && sharedStatus != null) { messageParameter = sharedStatus; } else { messageParameter = status; } <END> addCanDoActionMessageVariable("status", messageParameter); }</code><technical_language>initialize messageParameter status, i.e: Object messageParameter = getStorageDomainStatus(); do check: if (messageParameter == Unknown && sharedStatus != null) { messageParameter = sharedStatus; } This save 'else' part. BTW, if call getStorageDomainSharedStatus() is expensive, want save validating getStorageDomainStatus() is Unknown: Object messageParameter = getStorageDomainStatus(); if (messageParameter == Unknown) { SDSharedStatus sharedStatus = getSDSharedStatus(); if (sharedStatus != null) { messageParameter = sharedStatus; } } addCanDo ..</technical_language>

Target:
protected void addStorageDomainStatusIllegalMessage() { addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2); StorageDomainStatus status = getStorageDomainStatus(); StorageDomainSharedStatus sharedStatus = getStorageDomainSharedStatus(); Object messageParameter = status; if (status == StorageDomainStatus.Unknown && sharedStatus != null) { messageParameter = sharedStatus; } addCanDoActionMessageVariable("status", messageParameter); }
Source:
<code>public static void announceForAccessibility(View view, CharSequence text) { final AccessibilityManager manager = (AccessibilityManager) view.getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); if (!manager.isEnabled()) { return; } final int eventType = AccessibilityEvent.TYPE_ANNOUNCEMENT; <START> final AccessibilityEvent event = AccessibilityEvent.obtain(eventType); <END> event.getText().add(text); event.setSource(view); event.setEnabled(view.isEnabled()); event.setClassName(view.getClass().getName()); event.setPackageName(view.getContext().getPackageName()); manager.sendAccessibilityEvent(event); }</code><technical_language>suggestion final AccessibilityEvent event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_ANNOUNCEMENT);</technical_language>

Target:
public static void announceForAccessibility(View view, CharSequence text) { final AccessibilityManager manager = (AccessibilityManager) view.getContext().getSystemService(Context.ACCESSIBILITY_SERVICE); if (!manager.isEnabled()) { return; } final AccessibilityEvent event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_ANNOUNCEMENT); event.getText().add(text); event.setSource(view); event.setEnabled(view.isEnabled()); event.setClassName(view.getClass().getName()); event.setPackageName(view.getContext().getPackageName()); manager.sendAccessibilityEvent(event); }
Source:
<code><START> public void resolveProxyCrossReferences(Resource resource) { if (!initialized) { initialize(); } adapter.resolveProxyCrossReferences(resource); } <END></code><technical_language>do nothing, trigger initialization, if initialized (in this case is cleanup do)</technical_language>

Target:
public void resolveProxyCrossReferences(Resource resource) { if (initialized) { adapter.resolveProxyCrossReferences(resource); } }
Source:
<code>protected Query newFieldQuery(Analyzer analyzer, String field, String queryText, boolean quoted) throws ParseException { if (field == null || field.length() == 0) { return super.newFieldQuery(analyzer, field, queryText, quoted); } Matcher m = PROPERTY_NAME_PATTERN.matcher(field); if (m.matches() && m.group(2) != null) { return super.newFieldQuery(analyzer, field, queryText, quoted); } String fieldPrefix = field + "_"; <START> List<Query> disjucts = new ArrayList<>(); <END> for (String fieldName : fieldNameToVisibilityMap.getFieldNames()) { if (fieldName.startsWith(fieldPrefix)) { String visibility = fieldNameToVisibilityMap.getFieldVisibility(fieldName); if (VisibilityUtils.canRead(visibility, authorizations)) { Query termQuery = super.newFieldQuery(analyzer, fieldName, queryText, quoted); disjucts.add(termQuery); } } } DisjunctionMaxQuery query = new DisjunctionMaxQuery(disjucts, 0.0f); if (query.getDisjuncts().size() == 0) { return super.newFieldQuery(analyzer, field, queryText, quoted); } return query; }</code><technical_language>Typo? disjuncts</technical_language>

Target:
protected Query newFieldQuery(Analyzer analyzer, String field, String queryText, boolean quoted) throws ParseException { if (field == null || field.length() == 0) { return super.newFieldQuery(analyzer, field, queryText, quoted); } Matcher m = PROPERTY_NAME_PATTERN.matcher(field); if (m.matches() && m.group(2) != null) { return super.newFieldQuery(analyzer, field, queryText, quoted); } String fieldPrefix = field + "_"; List<Query> disjuncts = new ArrayList<>(); for (String fieldName : fieldNameToVisibilityMap.getFieldNames()) { if (fieldName.startsWith(fieldPrefix)) { String visibility = fieldNameToVisibilityMap.getFieldVisibility(fieldName); if (VisibilityUtils.canRead(visibility, authorizations)) { Query termQuery = super.newFieldQuery(analyzer, fieldName, queryText, quoted); disjuncts.add(termQuery); } } } DisjunctionMaxQuery query = new DisjunctionMaxQuery(disjuncts, 0.0f); if (query.getDisjuncts().size() == 0) { return super.newFieldQuery(analyzer, field, queryText, quoted); } return query; }
Source:
<code>public void outject(@Observes MethodExecuted event) { <START> Type returnType = event.getControllerMethod().getMethod().getGenericReturnType(); <END> if (!returnType.equals(Void.TYPE)) { String name = extractor.nameFor(returnType); Object value = this.info.getResult(); logger.debug("outjecting {}={}", name, value); result.include(name, value); } }</code><technical_language>Demeter happy here... add event.getMethodReturnType() alike</technical_language>

Target:
public void outject(@Observes MethodExecuted event) { Type returnType = event.getMethodReturnType(); if (!returnType.equals(Void.TYPE)) { String name = extractor.nameFor(returnType); Object value = this.info.getResult(); logger.debug("outjecting {}={}", name, value); result.include(name, value); } }
Source:
<code><START> Mono<CosmosContainerResponse> read(CosmosContainerRequestOptions options, Context context) { <END> Mono<CosmosContainerResponse> responseMono = readInternal(options); return database.getClient().getTracerProvider().traceEnabledCosmosResponsePublisher(responseMono, context, this.readContainerSpanName, database.getId(), database.getClient().getServiceEndpoint()); }</code><technical_language>@simplynaveen20 Non-blocking, thoughts combing these</technical_language>

Target:
Mono<CosmosContainerResponse> read(CosmosContainerRequestOptions options, Context context) { Mono<CosmosContainerResponse> responseMono = database.getDocClientWrapper().readCollection(getLink(), ModelBridgeInternal.toRequestOptions(options)) .map(response -> ModelBridgeInternal.createCosmosContainerResponse(response)).single(); return database.getClient().getTracerProvider().traceEnabledCosmosResponsePublisher(responseMono, context, this.readContainerSpanName, database.getId(), database.getClient().getServiceEndpoint()); }
Source:
<code>public int getDocumentCount() throws DocumentStoreException { Misc.checkState(this.isOpen(), "Database is closed"); try { return get(queue.submit(new GetDocumentCountCallable())); } catch (ExecutionException e) { String message = "Failed to get document count"; logger.log(Level.SEVERE, message, e); <START> throw new DocumentStoreException(e.getCause()); <END> } }</code><technical_language>include message in exception</technical_language>

Target:
public int getDocumentCount() throws DocumentStoreException { Misc.checkState(this.isOpen(), "Database is closed"); try { return get(queue.submit(new GetDocumentCountCallable())); } catch (ExecutionException e) { String message = "Failed to get document count"; logger.log(Level.SEVERE, message, e); throw new DocumentStoreException(message, e.getCause()); } }
Source:
<code>public void uploadFromFile(String filePath, BlobHTTPHeaders headers, Metadata metadata, BlobAccessConditions accessConditions, Duration timeout) throws IOException { <START> Mono<Void> upload = this.blockBlobAsyncClient.uploadFromFile(filePath, headers, metadata, accessConditions); <END> try { if (timeout == null) { upload.block(); } else { upload.block(timeout); } } catch (UncheckedIOException e) { throw e.getCause(); } }</code><technical_language>removed Context parameter async method, removed this call. added a blockSize integer parameter method, add this call. This compile</technical_language>

Target:
public void uploadFromFile(String filePath, BlobHTTPHeaders headers, Metadata metadata, BlobAccessConditions accessConditions, Duration timeout) throws IOException { Mono<Void> upload = this.blockBlobAsyncClient.uploadFromFile(filePath, BlockBlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE, headers, metadata, accessConditions); try { if (timeout == null) { upload.block(); } else { upload.block(timeout); } } catch (UncheckedIOException e) { throw e.getCause(); } }
Source:
<code>private Iterator<CliCommand> getAllCommands() { <START> ServiceLoader<CliCommand> loader = <END> ServiceLoader.load(CliCommand.class); return loader.iterator(); }</code><technical_language>Missing final</technical_language>

Target:
private Iterator<CliCommand> getAllCommands() { final ServiceLoader<CliCommand> loader = ServiceLoader.load(CliCommand.class); return loader.iterator(); }
Source:
<code>public void setUp() { <START> mockConfiguration = mock(TestcontainersConfiguration.class); <END> underTest = new ConfigurationFileImageNameSubstitutor(mockConfiguration); }</code><technical_language>JFYI MockTestcontainersConfigurationRule :)</technical_language>

Target:
public void setUp() { underTest = new ConfigurationFileImageNameSubstitutor(TestcontainersConfiguration.getInstance()); }
Source:
<code>protected void fill(Control control, MouseEvent event, Point pt) { TimeGraphControl timeGraphControl = (TimeGraphControl) control; if ((event.stateMask & SWT.MODIFIER_MASK) != SWT.SHIFT) { ILinkEvent linkEvent = timeGraphControl.getArrow(pt); if (linkEvent != null) { fillValues(linkEvent); } } if (getTipComposite().getChildren().length == 0) { ITimeGraphEntry entry = timeGraphControl.getEntry(pt); <START> fillValues(pt, timeGraphControl, entry); <END> Iterable<IMarkerEvent> markers = getMarkers(timeGraphControl , entry, pt); for (IMarkerEvent marker : markers) { fillValues(marker); } } }</code><technical_language>entry null, return early (otherwise unnecessarily fetches markers)</technical_language>

Target:
protected void fill(Control control, MouseEvent event, Point pt) { TimeGraphControl timeGraphControl = (TimeGraphControl) control; if ((event.stateMask & SWT.MODIFIER_MASK) != SWT.SHIFT) { ILinkEvent linkEvent = timeGraphControl.getArrow(pt); if (linkEvent != null) { fillValues(linkEvent); } } if (getTipComposite().getChildren().length == 0) { ITimeGraphEntry entry = timeGraphControl.getEntry(pt); if (entry == null) { return; } fillValues(pt, timeGraphControl, entry); Iterable<IMarkerEvent> markers = getMarkers(timeGraphControl, entry, pt); for (IMarkerEvent marker : markers) { fillValues(marker); } } }
Source:
<code>public void callPublicMethodWithDateParam() { Assert.assertNull(controller.getModel().getDateValue()); <START> Date value = new Date(); <END> controller.invoke(PUBLIC_WITH_DATE_PARAM_ACTION, new Param(PARAM_NAME, value)); Assert.assertEquals(controller.getModel().getDateValue(), value); }</code><technical_language>final</technical_language>

Target:
public void callPublicMethodWithDateParam() { Assert.assertNull(controller.getModel().getDateValue()); final Date value = new Date(); controller.invoke(PUBLIC_WITH_DATE_PARAM_ACTION, new Param(PARAM_NAME, value)); Assert.assertEquals(controller.getModel().getDateValue(), value); }
Source:
<code>private void ensureCapacity(int minCapacity) { int oldCapacity = objectData.length; if (minCapacity > oldCapacity) { int newCapacity = (oldCapacity * 3) / 2 + 1; if (newCapacity < minCapacity) { newCapacity = minCapacity; } final int rem = newCapacity % arity; newCapacity += (arity - rem); <START> if (cjMaxSize > 0 && newCapacity > cjMaxSize) { <END> throw MondrianResource.instance().TotalMembersLimitExceeded.ex( newCapacity, cjMaxSize); } Util.checkCJResultLimit(newCapacity); objectData = Util.copyOf(objectData, newCapacity); } }</code><technical_language>@mkambol I checking newCapacity limit is right do. assume limit is set 1M. Suppose a list of 700K tuples need add 10 more tuples this list. Lets suppose array's capacity 700K need increase 1.5x accommodate additional 10. However, soon increase capacity of array 700K+350K=1.05M, this hit 1M limit error out. a user, I query returned 700,010 tuples is 1M limit. I right fix cap newCapacity limit error out if array filled this limit</technical_language>

Target:
private void ensureCapacity( int minCapacity ) { int oldCapacity = objectData.length; if ( minCapacity > oldCapacity ) { int newCapacity = ( oldCapacity * 3 ) / 2 + 1; if ( newCapacity < minCapacity ) { newCapacity = minCapacity; } final int rem = newCapacity % arity; newCapacity += ( arity - rem ); if ( CJ_MAX_SIZE > 0 && newCapacity > CJ_MAX_SIZE ) { throw MondrianResource.instance().TotalMembersLimitExceeded.ex( newCapacity, CJ_MAX_SIZE ); } Util.checkCJResultLimit( newCapacity ); objectData = Util.copyOf( objectData, newCapacity ); } }
Source:
<code>public Object onPullRequest(Runnable closure) throws ANTLRException { GitHubPRTriggerDslContext context = new GitHubPRTriggerDslContext(); executeInContext(closure, context); GitHubPRTrigger trigger = new GitHubPRTrigger(context.cron(), context.mode(), context.events()); trigger.setPreStatus(context.isSetPreStatus()); trigger.setCancelQueued(context.isSetCancelQueued()); <START> trigger.setSkipFirstRun(context.isSetSkipFirstRun()); <END> return trigger; }</code><technical_language>this special afair cc @lanwen</technical_language>

Target:
public Object onPullRequest(Runnable closure) throws ANTLRException { GitHubPRTriggerDslContext context = new GitHubPRTriggerDslContext(); executeInContext(closure, context); GitHubPRTrigger trigger = new GitHubPRTrigger(context.cron(), context.mode(), context.events()); trigger.setPreStatus(context.isSetPreStatus()); trigger.setCancelQueued(context.isCancelQueued()); return trigger; }
Source:
<code>public void run(TestInformation testInfo, ITestInvocationListener listener) throws DeviceNotAvailableException { mTestInfo = testInfo; mFilterHelper.addAllIncludeAnnotation(mIncludeAnnotations); mFilterHelper.addAllExcludeAnnotation(mExcludeAnnotations); try { List<Class<?>> classes = getClasses(); if (!mSkipTestClassCheck) { if (classes.isEmpty()) { throw new IllegalArgumentException("No '--class' option was specified."); } } if (mMethodName != null && classes.size() > 1) { throw new IllegalArgumentException( String.format( <START> "'--method' only supports one '--class' name. Multiple were given: '%s'", <END> classes)); } } catch (IllegalArgumentException e) { listener.testRunStarted(this.getClass().getCanonicalName(), 0); FailureDescription failureDescription = FailureDescription.create(StreamUtil.getStackTrace(e)); failureDescription.setFailureStatus(FailureStatus.TEST_FAILURE); listener.testRunFailed(failureDescription); listener.testRunEnded(0L, new HashMap<String, Metric>()); throw e; } if (mEnableHostDeviceLogs) { PrettyTestEventLogger logger = new PrettyTestEventLogger(mTestInfo.getDevices()); listener = new ResultForwarder(logger, listener); } if (mTestMethods != null) { runTestCases(listener); } else { runTestClasses(listener); } }</code><technical_language>long</technical_language>

Target:
public void run(TestInformation testInfo, ITestInvocationListener listener) throws DeviceNotAvailableException { mTestInfo = testInfo; mFilterHelper.addAllIncludeAnnotation(mIncludeAnnotations); mFilterHelper.addAllExcludeAnnotation(mExcludeAnnotations); try { List<Class<?>> classes = getClasses(); if (!mSkipTestClassCheck) { if (classes.isEmpty()) { throw new IllegalArgumentException("No '--class' option was specified."); } } if (mMethodName != null && classes.size() > 1) { throw new IllegalArgumentException( String.format( "'--method' only supports one '--class' name. Multiple were " + "given: '%s'", classes)); } } catch (IllegalArgumentException e) { listener.testRunStarted(this.getClass().getCanonicalName(), 0); FailureDescription failureDescription = FailureDescription.create(StreamUtil.getStackTrace(e)); failureDescription.setFailureStatus(FailureStatus.TEST_FAILURE); listener.testRunFailed(failureDescription); listener.testRunEnded(0L, new HashMap<String, Metric>()); throw e; } if (mEnableHostDeviceLogs) { PrettyTestEventLogger logger = new PrettyTestEventLogger(mTestInfo.getDevices()); listener = new ResultForwarder(logger, listener); } if (mTestMethods != null) { runTestCases(listener); } else { runTestClasses(listener); } }
Source:
<code>protected void initialize(Object... args) { <START> service = Framework.getLocalService(TokenAuthenticationService.class); <END> }</code><technical_language>Framework.getService</technical_language>

Target:
protected void initialize(Object... args) { service = Framework.getService(TokenAuthenticationService.class); }
Source:
<code>public String toString() { Bundle myBundle = getBundle(); if (myBundle == null) return ""; String name = myBundle.getSymbolicName(); <START> return name == null ? Long.valueOf(myBundle.getBundleId()).toString() : name; <END> }</code><technical_language>String.valueOf(myBundle.getBundleId()) more sense .valueOf.toString</technical_language>

Target:
public String toString() { Bundle myBundle = getBundle(); if (myBundle == null) return ""; String name = myBundle.getSymbolicName(); return name == null ? String.valueOf(myBundle.getBundleId()) : name; }
Source:
<code>protected void validateDemographics(CertifiedProductSearchDetails product) { super.validateDemographics(product); if(StringUtils.isEmpty(product.getReportFileLocation())) { product.getErrorMessages().add("A test result summary URL is required."); } for(CertificationResult cert : product.getCertificationResults()) { if(cert.getTestToolsUsed() != null && cert.getTestToolsUsed().size() > 0) { for(CertificationResultTestTool testTool : cert.getTestToolsUsed()) { if(StringUtils.isEmpty(testTool.getTestToolName())) { product.getErrorMessages().add("There was no test tool name found for certification " + cert.getNumber() + "."); } else { TestToolDTO tt = super.testToolDao.getByName(testTool.getTestToolName()); if(tt != null && tt.isRetired() && super.icsCode.equals("0")) { if(super.hasIcsConflict) { product.getWarningMessages().add("Test Tool '" + testTool.getTestToolName() + "' can not be used for criteria '" + cert.getNumber() + "', as it is a retired tool, and this Certified Product does not carry ICS."); } else if(tt != null) { <START> product.getErrorMessages().add("Test Tool '" + testTool.getTestToolName() + "' can not be used for criteria '" + cert.getNumber() <END> + "', as it is a retired tool, and this Certified Product does not carry ICS."); } } } } } } }</code><technical_language>This is right error message. "No test tool testTool.getTestToolName() for criteria cert.getNumber()</technical_language>

Target:
protected void validateDemographics(CertifiedProductSearchDetails product) { super.validateDemographics(product); if(StringUtils.isEmpty(product.getReportFileLocation())) { product.getErrorMessages().add("A test result summary URL is required."); } for(CertificationResult cert : product.getCertificationResults()) { if(cert.getTestToolsUsed() != null && cert.getTestToolsUsed().size() > 0) { for(CertificationResultTestTool testTool : cert.getTestToolsUsed()) { if(StringUtils.isEmpty(testTool.getTestToolName())) { product.getErrorMessages().add("There was no test tool name found for certification " + cert.getNumber() + "."); } else { TestToolDTO tt = super.testToolDao.getByName(testTool.getTestToolName()); if(tt == null){ product.getErrorMessages().add("No test tool with " + testTool.getTestToolName() + " was found for criteria " + cert.getNumber() + "."); } else if(tt.isRetired() && super.icsCode.equals("0")) { if(super.hasIcsConflict) { product.getWarningMessages().add("Test Tool '" + testTool.getTestToolName() + "' can not be used for criteria '" + cert.getNumber() + "', as it is a retired tool, and this Certified Product does not carry ICS."); } else { product.getErrorMessages().add("Test Tool '" + testTool.getTestToolName() + "' can not be used for criteria '" + cert.getNumber() + "', as it is a retired tool, and this Certified Product does not carry ICS."); } } } } } } }
Source:
<code>public int execute() throws HiveException { Table tbl = desc.toTable(context.getConf()); LOG.debug("creating table on {}", tbl.getFullyQualifiedName(), tbl.getDataLocation()); boolean dataLocationChanged = false; if (desc.getReplicationSpec().isInReplicationScope()) { Table existingTable = context.getDb().getTable(tbl.getDbName(), tbl.getTableName(), false); if (existingTable != null) { if (desc.getReplicationSpec().allowEventReplacementInto(existingTable.getParameters())) { desc.setReplaceMode(true); ReplicationSpec.copyLastReplId(existingTable.getParameters(), tbl.getParameters()); if (existingTable.getTableType().equals(TableType.MANAGED_TABLE) && tbl.getTableType().equals(TableType.EXTERNAL_TABLE) <START> && (!existingTable.getDataLocation().equals(tbl.getDataLocation()))) { <END> dataLocationChanged = true; } } else { LOG.debug("DDLTask: Create Table is skipped as table is newer than update", desc.getTableName()); return 0; } } } if (desc.getReplaceMode()) { createTableReplaceMode(tbl, dataLocationChanged); } else { createTableNonReplaceMode(tbl); } DDLUtils.addIfAbsentByName(new WriteEntity(tbl, WriteEntity.WriteType.DDL_NO_LOCK), context); return 0; }</code><technical_language>in scenario location for conversion managed external in replication flow</technical_language>

Target:
public int execute() throws HiveException { Table tbl = desc.toTable(context.getConf()); LOG.debug("creating table on {}", tbl.getFullyQualifiedName(), tbl.getDataLocation()); boolean replDataLocationChanged = false; if (desc.getReplicationSpec().isInReplicationScope()) { Table existingTable = context.getDb().getTable(tbl.getDbName(), tbl.getTableName(), false); if (existingTable != null) { if (desc.getReplicationSpec().allowEventReplacementInto(existingTable.getParameters())) { desc.setReplaceMode(true); ReplicationSpec.copyLastReplId(existingTable.getParameters(), tbl.getParameters()); if (existingTable.getTableType().equals(TableType.MANAGED_TABLE) && tbl.getTableType().equals(TableType.EXTERNAL_TABLE) && (!existingTable.getDataLocation().equals(tbl.getDataLocation()))) { replDataLocationChanged = true; } } else { LOG.debug("DDLTask: Create Table is skipped as table is newer than update", desc.getTableName()); return 0; } } } if (desc.getReplaceMode()) { createTableReplaceMode(tbl, replDataLocationChanged); } else { createTableNonReplaceMode(tbl); } DDLUtils.addIfAbsentByName(new WriteEntity(tbl, WriteEntity.WriteType.DDL_NO_LOCK), context); return 0; }
Source:
<code>boolean stateFlagsTest() { final long tagCBoxPtr = OS.GetWindowLongPtr(handle, 0); <START> if (tagCBoxPtr == 0) return false; <END> final long stateFlagsPtr = tagCBoxPtr + stateFlagsOffset; int stateFlags[] = new int[1]; OS.MoveMemory(stateFlags, stateFlagsPtr, 4); return (stateFlags[0] == 0x02006002); }</code><technical_language>safe add check in stateFlagsAdd()</technical_language>

Target:
boolean stateFlagsTest() { final long tagCBoxPtr = OS.GetWindowLongPtr(handle, 0); if (tagCBoxPtr != 0) { final long stateFlagsPtr = tagCBoxPtr + stateFlagsOffset; int stateFlags[] = new int[1]; OS.MoveMemory(stateFlags, stateFlagsPtr, 4); return (stateFlags[0] == 0x02006002); } return false; }
Source:
<code>public TaskResult execute() { TaskResult result = new TaskResult(); Map<String, String> props = new HashMap<>(); props.putAll(tester.globalProperties); props.putAll(taskProperties); Batch.builder() .setGlobalProperties(props) .setEnableLoggingConfiguration(true) .addComponents(new EnvironmentInformation("mediumTest", "1.0"), tester.pluginInstaller, tester.globalRefProvider, tester.qualityProfiles, tester.rulesLoader, tester.branchConfigurationLoader, tester.projectRefProvider, tester.activeRules, tester.serverIssues, <START> mock(ScmConfiguration.class), <END> new DefaultDebtModel(), new FakeSettingsLoader(), result) .setLogOutput(tester.logOutput) .build().execute(); return result; }</code><technical_language>surprised inject a mock for medium tests. purpose is test real components possible</technical_language>

Target:
public TaskResult execute() { TaskResult result = new TaskResult(); Map<String, String> props = new HashMap<>(); props.putAll(tester.globalProperties); props.putAll(taskProperties); Batch.builder() .setGlobalProperties(props) .setEnableLoggingConfiguration(true) .addComponents(new EnvironmentInformation("mediumTest", "1.0"), tester.pluginInstaller, tester.globalRefProvider, tester.qualityProfiles, tester.rulesLoader, tester.branchConfigurationLoader, tester.projectRefProvider, tester.activeRules, tester.serverIssues, new DefaultDebtModel(), new FakeSettingsLoader(), result) .setLogOutput(tester.logOutput) .build().execute(); return result; }
Source:
<code>static String getRelModuleOutputPath() throws NoCurrentCaseException { return Case.getCurrentCaseThrows().getModuleOutputDirectoryRelativePath() + File.separator <START> + "RecentActivity"; <END> }</code><technical_language>a cleaner build path Paths. worry File.separator. need \\NON-NLS end of this line "OpenIDE-Module-Name" bundles.properties</technical_language>

Target:
static String getRelModuleOutputPath() throws NoCurrentCaseException { return Paths.get(Case.getCurrentCaseThrows().getModuleOutputDirectoryRelativePath(), "RecentActivity").normalize().toString() ; }
Source:
<code>public void cancel(InterpreterContext context) { if (livyVersion.isCancelSupported()) { try { cancelStatement(paragraphId2StmtIdMapping.get(context.getParagraphId())); } catch (LivyException e) { <START> LOGGER.warn("Fail to cancel statement for paragraph ", <END> paragraphId2StmtIdMapping.get(context.getParagraphId()), context.getParagraphId()); } finally { paragraphId2StmtIdMapping.remove(context.getParagraphId()); } } else { LOGGER.warn("cancel is not supported for this version of livy: " + livyVersion); } }</code><technical_language>this LOGGER.error(message, e) - log actual exception too</technical_language>

Target:
public void cancel(InterpreterContext context) { if (livyVersion.isCancelSupported()) { String paraId = context.getParagraphId(); Integer stmtId = paragraphId2StmtIdMapping.get(paraId); try { if (stmtId != null) { cancelStatement(stmtId); } } catch (LivyException e) { LOGGER.error("Fail to cancel statement " + stmtId + " for paragraph " + paraId, e); } finally { paragraphId2StmtIdMapping.remove(paraId); } } else { LOGGER.warn("cancel is not supported for this version of livy: " + livyVersion); } }
Source:
<code>protected void executeCommand() { ManagedBlockStorage managedBlockStorage = cinderStorageDao.get(getParameters().getStorageDomainId()); List<String> extraParams = new ArrayList<>(); extraParams.add(getNewDisk().getId().toString()); Number sizeInGiB = SizeConverter.convert(getParameters().getDiskInfo().getSize(), SizeConverter.SizeUnit.BYTES, SizeConverter.SizeUnit.GiB); extraParams.add(Long.toString(sizeInGiB.longValue())); Map<String, Object> driverOptions = new HashMap<>(managedBlockStorage.getDriverOptions()); if (managedBlockStorage.getDriverSensitiveOptions() != null) { driverOptions.putAll(managedBlockStorage.getDriverSensitiveOptions()); } CinderlibReturnValue returnValue; try { CinderlibCommandParameters params = new CinderlibCommandParameters(JsonHelper.mapToJson(driverOptions, false), extraParams); returnValue = cinderlibExecutor.runCommand(CinderlibCommand.EXTEND_VOLUME, params); } catch (Exception e) { log.error("Failed executing volume extension", e); <START> setSucceeded(false); <END> return; } if (!returnValue.getSucceed()) { setSucceeded(false); return; } updateDisk(); setSucceeded(true); }</code><technical_language>needed</technical_language>

Target:
protected void executeCommand() { ManagedBlockStorage managedBlockStorage = cinderStorageDao.get(getParameters().getStorageDomainId()); List<String> extraParams = new ArrayList<>(); extraParams.add(getNewDisk().getId().toString()); Number sizeInGiB = SizeConverter.convert(getParameters().getDiskInfo().getSize(), SizeConverter.SizeUnit.BYTES, SizeConverter.SizeUnit.GiB); extraParams.add(Long.toString(sizeInGiB.longValue())); Map<String, Object> driverOptions = new HashMap<>(managedBlockStorage.getDriverOptions()); if (managedBlockStorage.getDriverSensitiveOptions() != null) { driverOptions.putAll(managedBlockStorage.getDriverSensitiveOptions()); } CinderlibReturnValue returnValue; try { CinderlibCommandParameters params = new CinderlibCommandParameters(JsonHelper.mapToJson(driverOptions, false), extraParams); returnValue = cinderlibExecutor.runCommand(CinderlibCommand.EXTEND_VOLUME, params); } catch (Exception e) { log.error("Failed executing volume extension", e); return; } if (!returnValue.getSucceed()) { return; } updateDisk(); setSucceeded(true); }
Source:
<code>private static CompletableFuture<List<? extends ICodeMining>> getCodeMinings(ITextViewer viewer, List<ICodeMiningProvider> providers, IProgressMonitor monitor) { List<CompletableFuture<List<? extends ICodeMining>>> com= providers.stream() .map(provider -> provider.provideCodeMinings(viewer, monitor)) .filter(c -> c != null) <START> .map(future -> future.exceptionally(CodeMiningManager::logCodeMiningProviderException)) <END> .collect(Collectors.toList()); return CompletableFuture.allOf(com.toArray(new CompletableFuture[com.size()])).thenApply( v -> com.stream().map(CompletableFuture::join).flatMap(l -> l.stream()).collect(Collectors.toList())); }</code><technical_language>map(future -> future.exceptionally(e -> { CodeMiningManager.logCodeMiningProviderException(e); return Collections.emptyList(); }) ).collect(Collectors.toList());</technical_language>

Target:
private static CompletableFuture<List<? extends ICodeMining>> getCodeMinings(ITextViewer viewer, List<ICodeMiningProvider> providers, IProgressMonitor monitor) { List<CompletableFuture<List<? extends ICodeMining>>> com= providers.stream() .map(provider -> provider.provideCodeMinings(viewer, monitor)) .filter(c -> c != null) .map(future -> future.exceptionally(e -> { logCodeMiningProviderException(e); return Collections.emptyList(); })) .collect(Collectors.toList()); return CompletableFuture.allOf(com.toArray(new CompletableFuture[com.size()])).thenApply( v -> com.stream().map(CompletableFuture::join).flatMap(l -> l.stream()).collect(Collectors.toList())); }
Source:
<code>protected void deleteBlob(final String blobIdStr, final String serviceId, FutureResult<Void> futureResult, final Callback<Void> callback, boolean attemptChunkDeletes) { try { deleteManager.submitDeleteBlobOperation(blobIdStr, serviceId, futureResult, (Void result, Exception exception) -> { if (exception == null && attemptChunkDeletes) { try { initiateChunkDeletesIfAny(blobIdStr, serviceId); } catch (RouterException e) { logger.warn( "RouterException for same reason should have been thrown by submitDeleteBlobOperation() and no callback should be triggered.", e); } } if (exception == null && !attemptChunkDeletes) { <START> routerMetrics.skippedGetBlobCount.inc(); <END> } if (callback != null) { callback.onCompletion(result, exception); } }); } catch (RouterException e) { routerMetrics.operationDequeuingRate.mark(); routerMetrics.onDeleteBlobError(e); NonBlockingRouter.completeOperation(futureResult, callback, null, e); } routerCallback.onPollReady(); }</code><technical_language>this count unreliable chunks of blobs deleted triggered attemptChunkDeletes == false</technical_language>

Target:
protected void deleteBlob(final String blobIdStr, final String serviceId, FutureResult<Void> futureResult, final Callback<Void> callback, boolean attemptChunkDeletes) { try { deleteManager.submitDeleteBlobOperation(blobIdStr, serviceId, futureResult, (Void result, Exception exception) -> { if (exception == null && attemptChunkDeletes) { try { initiateChunkDeletesIfAny(blobIdStr, serviceId); } catch (RouterException e) { logger.warn( "RouterException for same reason should have been thrown by submitDeleteBlobOperation() and no callback should be triggered.", e); } } if (callback != null) { callback.onCompletion(result, exception); } }); } catch (RouterException e) { routerMetrics.operationDequeuingRate.mark(); routerMetrics.onDeleteBlobError(e); NonBlockingRouter.completeOperation(futureResult, callback, null, e); } routerCallback.onPollReady(); }
Source:
<code><START> public synchronized SdkEnvironment getSdkEnvironment(SdkConfig sdkConfig, boolean layoutLibIncluded) { <END> if (!layoutLibIncluded) { return getSdkEnvironment(sdkConfig); } else { Pair<InstrumentationConfiguration, SdkConfig> key = Pair.create(instrumentationConfig, sdkConfig); SdkEnvironment sdkEnvironment = sdkToEnvironment.get(key); if (sdkEnvironment == null) { URL[] urls = dependencyResolver.getLocalArtifactUrls(sdkConfig.getSdkClasspathDependencies()); ClassLoader robolectricClassLoader = new InstrumentingClassLoader(instrumentationConfig, layoutLibIncluded, urls); sdkEnvironment = new SdkEnvironment(sdkConfig, robolectricClassLoader); sdkToEnvironment.put(key, sdkEnvironment); } return sdkEnvironment; } }</code><technical_language>add boolean parameter original method</technical_language>

Target:
public synchronized SdkEnvironment getSdkEnvironment(SdkConfig sdkConfig, boolean layoutLibIncluded) { Pair<InstrumentationConfiguration, SdkConfig> key = Pair.create(instrumentationConfig, sdkConfig); SdkEnvironment sdkEnvironment = sdkToEnvironment.get(key); if (sdkEnvironment == null) { URL[] urls = dependencyResolver.getLocalArtifactUrls(sdkConfig.getSdkClasspathDependencies()); ClassLoader robolectricClassLoader = new InstrumentingClassLoader(instrumentationConfig, layoutLibIncluded, urls); sdkEnvironment = new SdkEnvironment(sdkConfig, robolectricClassLoader); if (!layoutLibIncluded) { sdkToEnvironment.put(key, sdkEnvironment); } } return sdkEnvironment; }
Source:
<code>public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); restore(savedInstanceState); try { if( courseData == null ) { final Bundle bundle = getArguments(); courseData = (EnrolledCoursesResponse) bundle.getSerializable(Router.EXTRA_ENROLLMENT); courseComponentId = (String) bundle.getString(Router.EXTRA_COURSE_COMPONENT_ID); } } catch (Exception ex) { logger.error(ex); } loadData(getView()); <START> String lastAccessedId = getArguments().getString(Router.EXTRA_LAST_ACCESSED_ID); <END> if (!TextUtils.isEmpty(lastAccessedId)) { updateRowSelection(lastAccessedId); } }</code><technical_language>arguments bundle is initialized a variable previously. If remove generic exception catching block, out of scope of if condition, reused</technical_language>

Target:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); restore(savedInstanceState); final Bundle bundle = getArguments(); if( courseData == null ) { courseData = (EnrolledCoursesResponse) bundle.getSerializable(Router.EXTRA_ENROLLMENT); courseComponentId = bundle.getString(Router.EXTRA_COURSE_COMPONENT_ID); } loadData(getView()); updateRowSelection(bundle.getString(Router.EXTRA_LAST_ACCESSED_ID)); }
Source:
<code>public void performFailureSuccessIssueClosedWithComponents() throws Exception { JiraCreateIssueNotifier notifier = spy(new JiraCreateIssueNotifier(JIRA_PROJECT, "", "", "")); doReturn(site).when(notifier).getSiteForProject(Mockito.any()); Issue issue = mock(Issue.class); <START> Status status = new Status(null, null, "", JiraCreateIssueNotifier.finishedStatuses.Closed.toString() , null, null); <END> when(session.createIssue(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyList(), Mockito.anyString(), Mockito.anyLong(), Mockito.anyLong())).thenReturn(issue); when(issue.getStatus()).thenReturn(status); when(session.getIssueByKey(Mockito.anyString())).thenReturn(issue); assertEquals(0, temporaryDirectory.list().length); when(previousBuild.getResult()).thenReturn(Result.SUCCESS); when(currentBuild.getResult()).thenReturn(Result.FAILURE); assertTrue(notifier.perform(currentBuild, launcher, buildListener)); assertEquals(1, temporaryDirectory.list().length); when(previousBuild.getResult()).thenReturn(Result.FAILURE); when(currentBuild.getResult()).thenReturn(Result.SUCCESS); assertTrue(notifier.perform(currentBuild, launcher, buildListener)); assertEquals(0, temporaryDirectory.list().length); }</code><technical_language>this is reason of test failure. Status name empty in test</technical_language>

Target:
public void performFailureSuccessIssueClosedWithComponents() throws Exception { JiraCreateIssueNotifier notifier = spy(new JiraCreateIssueNotifier(JIRA_PROJECT, "", "", "")); doReturn(site).when(notifier).getSiteForProject(Mockito.any()); Issue issue = mock(Issue.class); Status status = new Status(null, null, JiraCreateIssueNotifier.finishedStatuses.Closed.toString() , null, null, null); when(session.createIssue(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyList(), Mockito.anyString(), Mockito.anyLong(), Mockito.anyLong())).thenReturn(issue); when(issue.getStatus()).thenReturn(status); when(session.getIssueByKey(Mockito.anyString())).thenReturn(issue); assertEquals(0, temporaryDirectory.list().length); when(previousBuild.getResult()).thenReturn(Result.SUCCESS); when(currentBuild.getResult()).thenReturn(Result.FAILURE); assertTrue(notifier.perform(currentBuild, launcher, buildListener)); assertEquals(1, temporaryDirectory.list().length); when(previousBuild.getResult()).thenReturn(Result.FAILURE); when(currentBuild.getResult()).thenReturn(Result.SUCCESS); assertTrue(notifier.perform(currentBuild, launcher, buildListener)); assertEquals(0, temporaryDirectory.list().length); }
Source:
<code>public static Function<Iterable<?>, String> formatterForIterable(final String pattern) { return new Function<Iterable<?>, String>() { public String apply(@Nullable Iterable<?> input) { <START> return String.format(pattern, Iterables.toArray(input, Object.class)); <END> } }; }</code><technical_language>This NPE if input is null, parameter is marked @Nullable. remove annotation, explicitly check for null (e.g. return null if input is null)</technical_language>

Target:
public static Function<Iterable<?>, String> formatterForIterable(final String pattern) { return new Function<Iterable<?>, String>() { public String apply(@Nullable Iterable<?> input) { Object[] arr = (input == null) ? null : Iterables.toArray(input, Object.class); return String.format(pattern, arr); } }; }
Source:
<code>public void start() { try { <START> this.server.start(); <END> } catch (Exception e) { LOGGER.error("Fail to start the Jetty server... please check the availability of the port."); throw Throwables.propagate(e); } }</code><technical_language>block server finishes calling server.join() ? <LINK_0> BTW: nice work Cedric, code of Kasper a lot cleaner & tested, I impressed :)</technical_language>

Target:
public void start() { try { this.server.start(); } catch (final Exception e) { LOGGER.error("Fail to start the Jetty server... please check the availability of the port."); Throwables.propagate(e); } }
Source:
<code>public Mono<byte[]> getSessionState(String sessionId) { if (isDisposed.get()) { return monoError(logger, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver.")); } if (sessionManager != null) { <START> if (validateSessionId(sessionId)) { return monoError(logger, new IllegalArgumentException(String.format( "This receiver client is tied to session %s. It can't be used for another session(%s).", receiverOptions.getSessionId(), sessionId))); <END> } return sessionManager.getSessionState(sessionId); } else { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId))); } }</code><technical_language>of validations required if remove sessionId param methods. A client is tied a single session only</technical_language>

Target:
Mono<byte[]> getSessionState(String sessionId) { if (isDisposed.get()) { return monoError(logger, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getSessionState"))); } else if (!receiverOptions.isSessionReceiver()) { return monoError(logger, new IllegalStateException("Cannot get session state on a non-session receiver.")); } if (sessionManager != null) { return sessionManager.getSessionState(sessionId); } else { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(channel -> channel.getSessionState(sessionId, getLinkName(sessionId))); } }