auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void mergeAndStore(MavenArtifact artifact, Metadata mergeMetadata) throws IOException, XmlPullParserException, NoSuchAlgorithmException, ProviderImplementationException { RepositoryPath repositoryPath = artifact.getPath(); Repository repository = repositoryPath.getRepository(); ArtifactCoordinates coordinates = RepositoryFiles.readCoordinates(repositoryPath); <START> LayoutProvider layoutProvider = getLayoutProvider(repository, layoutProviderRegistry); <END> if (!layoutProvider.containsArtifact(repository, coordinates)) { throw new IOException("Artifact " + artifact.toString() + " does not exist in repository " + repository + " !"); } RepositoryPath artifactBasePath = repositoryPath.getParent().getParent(); logger.debug("Artifact merge metadata triggered for " + artifact.toString() + "(" + artifactBasePath + "). " + repository.getType()); try { Metadata metadata = readMetadata(artifact); mergeAndStore(artifactBasePath, metadata, mergeMetadata); } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); throw new IOException("Artifact " + artifact.toString() + " doesn't contain any metadata," + " therefore we can't merge the metadata!"); } }</code><technical_language>![INFO](<LINK_0> 'Severity: INFO') null pointer dereference in org.carlspring.strongbox.storage.metadata.MavenMetadataManager.mergeAndStore(MavenArtifact, Metadata) due return of called method [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public void mergeAndStore(MavenArtifact artifact, Metadata mergeMetadata) throws IOException, XmlPullParserException, NoSuchAlgorithmException, ProviderImplementationException { RepositoryPath repositoryPath = artifact.getPath(); Repository repository = repositoryPath.getRepository(); LayoutProvider layoutProvider = getLayoutProvider(repository, layoutProviderRegistry); if (!layoutProvider.containsPath(repositoryPath)) { throw new IOException("Artifact " + artifact.toString() + " does not exist in repository " + repository + " !"); } RepositoryPath artifactBasePath = repositoryPath.getParent().getParent(); logger.debug("Artifact merge metadata triggered for " + artifact.toString() + "(" + artifactBasePath + "). " + repository.getType()); try { Metadata metadata = readMetadata(artifact); mergeAndStore(artifactBasePath, metadata, mergeMetadata); } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); throw new IOException("Artifact " + artifact.toString() + " doesn't contain any metadata," + " therefore we can't merge the metadata!"); } }
Source:
<code>public void testGrabChecksumFromDockerHub() { final ApiClient webClient = getWebClient(USER_2_USERNAME, testingPostgres); ContainersApi toolApi = new ContainersApi(webClient); ContainertagsApi toolTagsApi = new ContainertagsApi(webClient); DockstoreTool tool = createManualDockerHubTool(); tool.setDefaultDockerfilePath("/Dockerfile"); tool.setDefaultCwlPath("/Docstore.cwl"); tool = toolApi.registerManual(tool); tool = addDockerHubTag(tool, toolTagsApi, toolApi); List<Tag> tags = toolApi.getContainer(tool.getId(), null).getWorkflowVersions(); for (Tag tag: tags) { <START> assertNotNull(tag.getImages().get(0).getChecksums().get(0).getType()); <END> assertNotNull(tag.getImages().get(0).getChecksums().get(0).getChecksum()); } String imageID = tags.get(0).getImages().get(0).getImageID(); final long count = testingPostgres.runSelectStatement("select count(*) from image", long.class); testingPostgres.runUpdateStatement("update image set image_id = 'dummyid'"); assertEquals("dummyid", toolApi.getContainer(tool.getId(), null).getWorkflowVersions().get(0).getImages().get(0).getImageID()); toolApi.refresh(tool.getId()); final long count2 = testingPostgres.runSelectStatement("select count(*) from image", long.class); assertEquals(imageID, toolApi.getContainer(tool.getId(), null).getWorkflowVersions().get(0).getImages().get(0).getImageID()); assertEquals(count, count2); }</code><technical_language>paranoid here, is checksum retrieval code is failing returning empty strings</technical_language>

Target:
public void testGrabChecksumFromDockerHub() { final ApiClient webClient = getWebClient(USER_2_USERNAME, testingPostgres); ContainersApi toolApi = new ContainersApi(webClient); ContainertagsApi toolTagsApi = new ContainertagsApi(webClient); DockstoreTool tool = createManualDockerHubTool(); tool.setDefaultDockerfilePath("/Dockerfile"); tool.setDefaultCwlPath("/Docstore.cwl"); tool = toolApi.registerManual(tool); tool = addDockerHubTag(tool, toolTagsApi, toolApi); List<Tag> tags = toolApi.getContainer(tool.getId(), null).getWorkflowVersions(); for (Tag tag: tags) { String hashType = tag.getImages().get(0).getChecksums().get(0).getType(); String checksum = tag.getImages().get(0).getChecksums().get(0).getChecksum(); assertNotNull(hashType); assertFalse(hashType.isEmpty()); assertNotNull(checksum); assertFalse(checksum.isEmpty()); } String imageID = tags.get(0).getImages().get(0).getImageID(); final long count = testingPostgres.runSelectStatement("select count(*) from image", long.class); testingPostgres.runUpdateStatement("update image set image_id = 'dummyid'"); assertEquals("dummyid", toolApi.getContainer(tool.getId(), null).getWorkflowVersions().get(0).getImages().get(0).getImageID()); toolApi.refresh(tool.getId()); final long count2 = testingPostgres.runSelectStatement("select count(*) from image", long.class); assertEquals(imageID, toolApi.getContainer(tool.getId(), null).getWorkflowVersions().get(0).getImages().get(0).getImageID()); assertEquals(count, count2); }
Source:
<code>public DataSegment uploadDataSegment( DataSegment segment, final int binaryVersion, final long size, final File compressedSegmentData, final File descriptorFile, final Map<String, String> azurePaths ) throws StorageException, IOException, URISyntaxException { azureStorage.uploadBlob(compressedSegmentData, config.getContainer(), azurePaths.get("index"), true); <START> azureStorage.uploadBlob(descriptorFile, config.getContainer(), azurePaths.get("descriptor"), true); <END> final DataSegment outSegment = segment .withSize(size) .withLoadSpec(this.makeLoadSpec(new URI(azurePaths.get("index")))) .withBinaryVersion(binaryVersion); log.info("Deleting file [%s]", compressedSegmentData); compressedSegmentData.delete(); log.info("Deleting file [%s]", descriptorFile); descriptorFile.delete(); return outSegment; }</code><technical_language>uploadBlob() replaceExisting parameter this is true. Is this intentional</technical_language>

Target:
public DataSegment uploadDataSegment( DataSegment segment, final int binaryVersion, final long size, final File compressedSegmentData, final File descriptorFile, final Map<String, String> azurePaths ) throws StorageException, IOException, URISyntaxException { azureStorage.uploadBlob(compressedSegmentData, config.getContainer(), azurePaths.get("index")); azureStorage.uploadBlob(descriptorFile, config.getContainer(), azurePaths.get("descriptor")); final DataSegment outSegment = segment .withSize(size) .withLoadSpec(this.makeLoadSpec(new URI(azurePaths.get("index")))) .withBinaryVersion(binaryVersion); log.info("Deleting file [%s]", compressedSegmentData); compressedSegmentData.delete(); log.info("Deleting file [%s]", descriptorFile); descriptorFile.delete(); return outSegment; }
Source:
<code>public Object evaluate(DeferredObject[] arguments) throws HiveException { result.clear(); UserAgent browser = null; Device device = null; OS os = null; try { <START> if (arguments.length > 0 && argumentOIs.length > 0 <END> && argumentOIs[0] != null && arguments[0] != null) { Client c; String pattern = ((StringObjectInspector) argumentOIs[0]) .getPrimitiveJavaObject(arguments[0].get()); c = cachingParser.parse(pattern); if (c != null) { browser = c.userAgent; device = c.device; os = c.os; } } } catch (Exception e) { LOG.error(e.getMessage(),e); } if (browser != null) { result.put("browser_family", replaceNA(browser.family)); result.put("browser_major", replaceNA(browser.major)); } else { result.put("browser_family", NA); result.put("browser_major", NA); } if (device != null) { result.put("device_family", replaceNA(device.family)); } else { result.put("device_family", NA); } if (os != null) { result.put("os_family", replaceNA(os.family)); result.put("os_major", replaceNA(os.major)); result.put("os_minor", replaceNA(os.minor)); } else { result.put("os_family", NA); result.put("os_major", NA); result.put("os_minor", NA); } return result; }</code><technical_language>"> 0" "== 1" instead</technical_language>

Target:
public Object evaluate(DeferredObject[] arguments) throws HiveException { result.clear(); UserAgent browser = null; Device device = null; OS os = null; try { if (arguments.length > 0 && argumentOI != null && arguments[0] != null) { Client c; String pattern = ((StringObjectInspector) argumentOI) .getPrimitiveJavaObject(arguments[0].get()); c = cachingParser.parse(pattern); if (c != null) { browser = c.userAgent; device = c.device; os = c.os; } } } catch (Exception e) { Log.error(e.getMessage(), e); } if (browser != null) { result.put("browser_family", replaceNA(browser.family)); result.put("browser_major", replaceNA(browser.major)); } else { result.put("browser_family", NA); result.put("browser_major", NA); } if (device != null) { result.put("device_family", replaceNA(device.family)); } else { result.put("device_family", NA); } if (os != null) { result.put("os_family", replaceNA(os.family)); result.put("os_major", replaceNA(os.major)); result.put("os_minor", replaceNA(os.minor)); } else { result.put("os_family", NA); result.put("os_major", NA); result.put("os_minor", NA); } return result; }
Source:
<code>private static boolean shouldFetchLogFileInformation() { if (rootFileAppender != null && isErrorLevelEnable() && rootFileAppender.getImmediateFlush()) { return true; } <START> logger <END> .debug("can't retrieve log file information as there is no single fileAppender with immediateFlust set to true and log level set to ERROR or greater"); return false; }</code><technical_language>I this checked static initialization. Note error is raised in a container, is limit logging. In case this is done static initialization, I change log level debug info is time logging</technical_language>

Target:
private static boolean shouldFetchLogFileInformation() { if (fileAppender != null && isErrorLevelEnable() && fileAppender.getImmediateFlush()) { return true; } logger.warn( "Log information is unavailable. To enable log information log4j/logging should be configured with single FileAppender that has immediateFlush set to true and log level set to ERROR or greater."); return false; }
Source:
<code>private void assertObisCode( final com.alliander.osgp.adapter.ws.schema.smartmetering.common.ObisCodeValues actualObisCode, final ObisCodeValues sourceObisCode) throws AssertionError { <START> assertEquals(sourceObisCode.getA(), actualObisCode.getA()); <END> assertEquals(sourceObisCode.getB(), actualObisCode.getB()); assertEquals(sourceObisCode.getC(), actualObisCode.getC()); assertEquals(sourceObisCode.getD(), actualObisCode.getD()); assertEquals(sourceObisCode.getE(), actualObisCode.getE()); assertEquals(sourceObisCode.getF(), actualObisCode.getF()); }</code><technical_language>Please add messages asserts. This for asserts in this class</technical_language>

Target:
private void assertObisCode( final com.alliander.osgp.adapter.ws.schema.smartmetering.common.ObisCodeValues actualObisCode, final ObisCodeValues sourceObisCode) throws AssertionError { assertEquals(MAPPED_FIELD_VALUE_MESSAGE, sourceObisCode.getA(), actualObisCode.getA()); assertEquals(MAPPED_FIELD_VALUE_MESSAGE, sourceObisCode.getB(), actualObisCode.getB()); assertEquals(MAPPED_FIELD_VALUE_MESSAGE, sourceObisCode.getC(), actualObisCode.getC()); assertEquals(MAPPED_FIELD_VALUE_MESSAGE, sourceObisCode.getD(), actualObisCode.getD()); assertEquals(MAPPED_FIELD_VALUE_MESSAGE, sourceObisCode.getE(), actualObisCode.getE()); assertEquals(MAPPED_FIELD_VALUE_MESSAGE, sourceObisCode.getF(), actualObisCode.getF()); }
Source:
<code>public String describe() { return "RabbitIndexWriter\n" + "\t" + RabbitMQConstants.SERVER_HOST + " : Host of RabbitMQ server\n" + "\t" + RabbitMQConstants.SERVER_PORT + " : Port of RabbitMQ server\n" + "\t" + RabbitMQConstants.SERVER_VIRTUAL_HOST + " : Virtualhost name\n" + "\t" + RabbitMQConstants.SERVER_USERNAME + " : Username for authentication\n" + "\t" + RabbitMQConstants.SERVER_PASSWORD + " : Password for authentication\n" + "\t" + RabbitMQConstants.COMMIT_SIZE + " : Buffer size when sending to RabbitMQ (default 250)\n"; <START> } <END></code><technical_language>For consistency StringBuilder pattern here</technical_language>

Target:
public String describe() { StringBuilder sb = new StringBuilder("RabbitIndexWriter\n"); sb.append("\t").append(RabbitMQConstants.SERVER_HOST) .append(" : Host of RabbitMQ server\n"); sb.append("\t").append(RabbitMQConstants.SERVER_PORT) .append(" : Port of RabbitMQ server\n"); sb.append("\t").append(RabbitMQConstants.SERVER_VIRTUAL_HOST) .append(" : Virtualhost name\n"); sb.append("\t").append(RabbitMQConstants.SERVER_USERNAME) .append(" : Username for authentication\n"); sb.append("\t").append(RabbitMQConstants.SERVER_PASSWORD) .append(" : Password for authentication\n"); sb.append("\t").append(RabbitMQConstants.COMMIT_SIZE) .append(" : Buffer size when sending to RabbitMQ (default 250)\n"); return sb.toString(); }
Source:
<code>public static String constructServiceUrl(final HttpServletRequest request, final HttpServletResponse response, final String service, final String serverNames, final String artifactParameterName, final boolean encode) { final Set<String> serviceParameterSet = new HashSet<String>(4); for (final Protocol protocol : Protocol.values()) { serviceParameterSet.add(protocol.getServiceParameterName()); } <START> final String serviceParameterNames = serviceParameterSet.toString() <END> .replaceAll("\\[|\\]", "") .replaceAll("\\s", ""); return constructServiceUrl(request, response, service, serverNames, serviceParameterNames , artifactParameterName, encode); }</code><technical_language>For compatibility, is passing CAS protocol service param enough? (I'm assuming happened previously?) some issues in this service url construction reduce chances of wrong :-)</technical_language>

Target:
public static String constructServiceUrl(final HttpServletRequest request, final HttpServletResponse response, final String service, final String serverNames, final String artifactParameterName, final boolean encode) { return constructServiceUrl(request, response, service, serverNames, SERVICE_PARAMETER_NAMES , artifactParameterName, encode); }
Source:
<code>public UsageRecordList getUsageRecords(UsageRecordList.Type type) { <START> return this.getUsageRecords(new HashMap<String, String>(), type); <END> }</code><technical_language>Collections.emptyMap() avoid declaring a new instance time</technical_language>

Target:
public UsageRecordList getUsageRecords(UsageRecordList.Type type) { return this.getUsageRecords(Collections.<String, String>emptyMap(), type); }
Source:
<code>public void openWith(String editor) { select(); new ContextMenu("Open With", "Other...").select(); <START> ; <END> new WaitUntil(new ShellWithTextIsAvailable("Editor Selection")); new DefaultTreeItem(editor).select(); new OkButton().click(); new WaitWhile(new ShellWithTextIsAvailable("Editor Selection")); }</code><technical_language>remove semicolon</technical_language>

Target:
public void openWith(String editor) { select(); new ContextMenu("Open With", "Other...").select(); Shell shell = new DefaultShell("Editor Selection"); new DefaultTreeItem(editor).select(); new OkButton().click(); new WaitWhile(new ShellIsAvailable(shell)); }
Source:
<code>public byte[] encode(LifecycleMessage message) { byte[] encodedMsg = Util.marshall(message); <START> ByteBuffer buffer = ByteBuffer.allocate(1 + encodedMsg.length); <END> buffer.put(EhcacheEntityMessage.Type.LIFECYCLE_OP.getOpCode()); buffer.put(encodedMsg); return buffer.array(); }</code><technical_language>Please replace 1 a constant indicating is</technical_language>

Target:
public byte[] encode(LifecycleMessage message) { byte[] encodedMsg = Util.marshall(message); ByteBuffer buffer = ByteBuffer.allocate(OPCODE_SIZE + encodedMsg.length); buffer.put(message.getOpCode()); buffer.put(encodedMsg); return buffer.array(); }
Source:
<code>private void nextPos() { <START> for (currentPos = pos.down(); currentPos.getY() >= CubicChunksChecker.worldMin; currentPos = currentPos.down()) { <END> if (canBreak()) { updateLength(); return; } else if (!world.isAirBlock(currentPos) && world.getBlockState(currentPos).getBlock() != BCFactoryBlocks.tube) { break; } } currentPos = null; updateLength(); }</code><technical_language>Assuming start position is world, !world.isOutsideBuildHeight()</technical_language>

Target:
private void nextPos() { for (currentPos = pos.down(); !world.isOutsideBuildHeight(currentPos); currentPos = currentPos.down()) { if (canBreak()) { updateLength(); return; } else if (!world.isAirBlock(currentPos) && world.getBlockState(currentPos).getBlock() != BCFactoryBlocks.tube) { break; } } currentPos = null; updateLength(); }
Source:
<code>public void onResume() { super.onResume(); Log_OC.e(TAG, "onResume"); <START> loadAndShowTextPreview(); <END> }</code><technical_language>Please, reload text in onResume(). Do in onCreateView() onActivityCreated(); onPause() onResume() called other windows partially hide fragment (such menu showing apps open file of ownCloud) stays visible</technical_language>

Target:
public void onResume() { super.onResume(); Log_OC.e(TAG, "onResume"); }
Source:
<code>public void releaseAllServices() { List<String> unreleasedServicesToReport = failOnUnreleasedService ? new ArrayList<String>() : null; for ( ServiceWrapper<?> wrapper : cachedServices.values() ) { <START> boolean stoppedProperly = wrapper.ensureStopped(); <END> if ( !stoppedProperly ) { log.serviceProviderNotReleased( wrapper.serviceClass ); if ( unreleasedServicesToReport != null ) { unreleasedServicesToReport.add( wrapper.serviceClass.getName() ); } } } allServicesReleased = true; if ( failOnUnreleasedService && !unreleasedServicesToReport.isEmpty() ) { throw new AssertionFailure( "The following services have been used but not released: " + unreleasedServicesToReport ); } }</code><technical_language>wrapper needs synchronized here, original method inlining now. Failing do expose a service instance increment usage counter this stop operation for a legitimate usage, throw exception (or log warning). extremely shutting anyway.. in theory if e.g. a service is needed perform a clean teardown. fix that</technical_language>

Target:
public synchronized void releaseAllServices() { for ( ServiceWrapper<?> wrapper : cachedServices.values() ) { wrapper.stopVirtual(); } List<String> unreleasedServicesToReport = failOnUnreleasedService ? new ArrayList<String>() : null; for ( ServiceWrapper<?> wrapper : cachedServices.values() ) { if ( wrapper.status != ServiceStatus.STOPPED ) { log.serviceProviderNotReleased( wrapper.serviceClass ); wrapper.stopReal(); if ( unreleasedServicesToReport != null ) { unreleasedServicesToReport.add( wrapper.serviceClass.getName() ); } } } cachedServices.clear(); allServicesReleased = true; if ( failOnUnreleasedService && !unreleasedServicesToReport.isEmpty() ) { throw new AssertionFailure( "The following services have been used but not released: " + unreleasedServicesToReport ); } }
Source:
<code>public void validate(Object target, Errors errors) { log.debug("{}.validate...", this.getClass().getName()); if (target == null) { return; } Person person = (Person) target; <START> if (person.getVoided()) { <END> ValidationUtils.rejectIfEmptyOrWhitespace(errors, "voidReason", "error.null"); } else if (!validatePersonHasAtLeastOneNonVoidedName(person)) { errors.rejectValue("names", "Person.shouldHaveAtleastOneNonVoidedName"); } validatePersonNames(person, errors); validatePersonAddresses(person, errors); validateBirthDate(errors, person.getBirthdate()); validateDeathDate(errors, person.getDeathDate(), person.getBirthdate()); validateDeathCause(person, errors); ValidateUtil.validateFieldLengths(errors, Person.class, "gender", "personVoidReason"); }</code><technical_language>Is this refactoring new functionality</technical_language>

Target:
public void validate(Object target, Errors errors) { log.debug("{}.validate...", this.getClass().getName()); if (target == null) { return; } Person person = (Person) target; validatePersonNames(person, errors); if (!person.getVoided() && !validatePersonHasAtLeastOneNonVoidedName(person)) { errors.rejectValue("names", "Person.shouldHaveAtleastOneNonVoidedName"); } validatePersonAddresses(person, errors); validateBirthDate(errors, person.getBirthdate()); validateDeathDate(errors, person.getDeathDate(), person.getBirthdate()); if (person.getVoided()) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "voidReason", "error.null"); } validateDeathCause(person, errors); ValidateUtil.validateFieldLengths(errors, Person.class, "gender", "personVoidReason"); }
Source:
<code>public Vector3 toCameraFrame(int pixelX, int pixelY) { <START> double centeredX = pixelX - viewport.getWidth() / 2.0d; <END> double centeredY = viewport.getHeight() / 2.0d - pixelY; return getCameraToScreenTransform().invert().apply(new Vector3(centeredX, centeredY, 0)); }</code><technical_language>final</technical_language>

Target:
public Vector3 toCameraFrame(int pixelX, int pixelY) { final double centeredX = pixelX - viewport.getWidth() / 2.0d; final double centeredY = viewport.getHeight() / 2.0d - pixelY; return getCameraToScreenTransform().invert().apply(new Vector3(centeredX, centeredY, 0)); }
Source:
<code>static <T> Task<T> whenServiceUp(final Entity target, final TaskAdaptable<T> task, String name) { return Tasks.<T>builder().name(name).dynamic(true).body(new Callable<T>() { @Override public T call() { try { while (true) { if (!Entities.isManaged(target)) { Tasks.markInessential(); throw new IllegalStateException("Target "+target+" is no longer managed"); } <START> if (target.getAttribute(Attributes.SERVICE_UP)) { <END> Tasks.resetBlockingDetails(); TaskTags.markInessential(task); DynamicTasks.queue(task); try { return task.asTask().getUnchecked(); } catch (Exception e) { if (Entities.isManaged(target)) { throw Exceptions.propagate(e); } else { Tasks.markInessential(); throw new IllegalStateException("Target "+target+" is no longer managed", e); } } } else { Tasks.setBlockingDetails("Waiting on "+target+" to be ready"); } Time.sleep(Duration.ONE_SECOND); } } finally { Tasks.resetBlockingDetails(); } } }).build(); }</code><technical_language>NPE if SERVICE_UP attribute is null. Do if (Boolean.TRUE.equals(target.getAttribute(Attributes.SERVICE_UP))) {</technical_language>

Target:
static <T> Task<T> whenServiceUp(final Entity target, final TaskAdaptable<T> task, String name) { return Tasks.<T>builder().name(name).dynamic(true).body(new Callable<T>() { @Override public T call() { try { while (true) { if (!Entities.isManaged(target)) { Tasks.markInessential(); throw new IllegalStateException("Target "+target+" is no longer managed"); } if (Boolean.TRUE.equals(target.getAttribute(Attributes.SERVICE_UP))) { Tasks.resetBlockingDetails(); TaskTags.markInessential(task); DynamicTasks.queue(task); try { return task.asTask().getUnchecked(); } catch (Exception e) { if (Entities.isManaged(target)) { throw Exceptions.propagate(e); } else { Tasks.markInessential(); throw new IllegalStateException("Target "+target+" is no longer managed", e); } } } else { Tasks.setBlockingDetails("Waiting on "+target+" to be ready"); } Time.sleep(Duration.ONE_SECOND); } } finally { Tasks.resetBlockingDetails(); } } }).build(); }
Source:
<code>private void setEncodeApiResponse(final boolean encodeApiResponse) { <START> ApiServer.encodeApiResponse = encodeApiResponse; <END> }</code><technical_language>is this for? a strange do</technical_language>

Target:
private static void setEncodeApiResponse(final boolean encodeApiResponse) { ApiServer.encodeApiResponse = encodeApiResponse; }
Source:
<code>public StramClient(Configuration conf, LogicalPlan dag) throws Exception { this.conf = conf; this.dag = dag; <START> dag.visitDAG(); <END> dag.validate(); yarnClient.init(conf); }</code><technical_language>useful allow visitor access dag properties set</technical_language>

Target:
public StramClient(Configuration conf, LogicalPlan dag) throws Exception { this.conf = conf; this.dag = dag; dag.validate(); yarnClient.init(conf); }
Source:
<code>public void saveSettings() { super.saveSettings(); if (mSite.isJetpackConnected()) { saveJetpackSettings(); updateJetpackProtectSettings(); } try { <START> final JSONObject jsonParams = serializeDotComParamsToJSONObject(); <END> WordPress.getRestClientUtils().setGeneralSiteSettings( mSite.getSiteId(), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { AppLog.d(AppLog.T.API, "Site Settings saved remotely"); notifySavedOnUiThread(null); mRemoteSettings.copyFrom(mSettings); if (response != null) { JSONObject updated = response.optJSONObject("updated"); if (updated == null) return; HashMap<String, Object> properties = new HashMap<>(); Iterator<String> keys = updated.keys(); while (keys.hasNext()) { String currentKey = keys.next(); Object currentValue = updated.opt(currentKey); if (currentValue != null) { properties.put(SAVED_ITEM_PREFIX + currentKey, currentValue); } } AnalyticsUtils.trackWithSiteDetails( AnalyticsTracker.Stat.SITE_SETTINGS_SAVED_REMOTELY, mSite, properties); } } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { AppLog.w(AppLog.T.API, "Error POSTing site settings changes: " + error); notifySavedOnUiThread(error); } }, jsonParams); } catch (JSONException exception) { AppLog.w(AppLog.T.API, "Error serializing settings changes: " + exception); notifySavedOnUiThread(exception); } }</code><technical_language>do isEmpty check this? if (jsonParams.length() == 0) return;</technical_language>

Target:
public void saveSettings() { super.saveSettings(); if (mSite.isJetpackConnected()) { saveJetpackSettings(); updateJetpackProtectSettings(); } try { final JSONObject jsonParams = serializeDotComParamsToJSONObject(); if (jsonParams.length() <= 0) { return; } WordPress.getRestClientUtils().setGeneralSiteSettings( mSite.getSiteId(), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { AppLog.d(AppLog.T.API, "Site Settings saved remotely"); notifySavedOnUiThread(null); mRemoteSettings.copyFrom(mSettings); if (response != null) { JSONObject updated = response.optJSONObject("updated"); if (updated == null) return; HashMap<String, Object> properties = new HashMap<>(); Iterator<String> keys = updated.keys(); while (keys.hasNext()) { String currentKey = keys.next(); Object currentValue = updated.opt(currentKey); if (currentValue != null) { properties.put(SAVED_ITEM_PREFIX + currentKey, currentValue); } } AnalyticsUtils.trackWithSiteDetails( AnalyticsTracker.Stat.SITE_SETTINGS_SAVED_REMOTELY, mSite, properties); } } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { AppLog.w(AppLog.T.API, "Error POSTing site settings changes: " + error); notifySavedOnUiThread(error); } }, jsonParams); } catch (JSONException exception) { AppLog.w(AppLog.T.API, "Error serializing settings changes: " + exception); notifySavedOnUiThread(exception); } }
Source:
<code>public static void _destroyKernel() { if (kernel != null) { try { kernel.destroy(); } catch (Exception e) { } <START> kernel.destroy(); <END> } kernel = null; }</code><technical_language>Destroy kernel twice? (See line 58.)</technical_language>

Target:
public static void _destroyKernel() { if (kernel != null) { kernel.destroy(); } kernel = null; }
Source:
<code>public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { SCM scm = build.getProject().getScm(); if (!(scm instanceof TeamFoundationServerScm)) { <START> listener.getLogger().println("No label for non TFS project"); <END> return false; } FilePath workspace = build.getWorkspace(); TeamFoundationServerScm tfsScm = (TeamFoundationServerScm) scm; boolean buildSucess = Result.SUCCESS.equals(build.getResult()); String whenCreateLabel = getTime(); if ("always".equals(whenCreateLabel) || ("success".equals(whenCreateLabel) && buildSucess)) { final Launcher localLauncher = launcher != null ? launcher : new Launcher.LocalLauncher(listener); final TfTool tool = new TfTool(tfsScm.getDescriptor().getTfExecutable(), localLauncher, listener, workspace); Server server = new Server(tool, tfsScm.getServerUrl(build), tfsScm.getUserName(), tfsScm.getUserPassword()); Computer computer = Computer.currentComputer(); String normalizedLabelName = computeDynamicValue(build, getLabelName()); String tfsWorkspace = tfsScm.getWorkspaceName(build, computer); try { logger.info(String.format("Create label '%s' on workspace '%s'", normalizedLabelName, tfsWorkspace)); LabelCommand labelCommand = new LabelCommand(server, normalizedLabelName, tfsWorkspace, tfsScm.getLocalPath()); server.execute(labelCommand.getArguments()); } catch (Exception e) { return false; } finally { server.close(); } } return true; }</code><technical_language>like: "Labels supported for projects TFS SCM" ...or "To create a label in TFS, Jenkins job TFS SCM."</technical_language>

Target:
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { SCM scm = build.getProject().getScm(); if (!(scm instanceof TeamFoundationServerScm)) { listener.getLogger().println("Labels are only supported for projects using TFS SCM"); return false; } FilePath workspace = build.getWorkspace(); TeamFoundationServerScm tfsScm = (TeamFoundationServerScm) scm; boolean buildSucess = Result.SUCCESS.equals(build.getResult()); String whenCreateLabel = getWhenToLabel(); if ("always".equals(whenCreateLabel) || ("success".equals(whenCreateLabel) && buildSucess)) { final Launcher localLauncher = launcher != null ? launcher : new Launcher.LocalLauncher(listener); final TfTool tool = new TfTool(tfsScm.getDescriptor().getTfExecutable(), localLauncher, listener, workspace); Server server = new Server(tool, tfsScm.getServerUrl(build), tfsScm.getUserName(), tfsScm.getUserPassword()); Computer computer = Computer.currentComputer(); String normalizedLabelName = computeDynamicValue(build, getLabelName()); String tfsWorkspace = tfsScm.getWorkspaceName(build, computer); try { logger.info(String.format("Create label '%s' on workspace '%s'", normalizedLabelName, tfsWorkspace)); LabelCommand labelCommand = new LabelCommand(server, normalizedLabelName, tfsWorkspace, tfsScm.getLocalPath()); server.execute(labelCommand.getArguments()); } catch (Exception e) { return false; } finally { server.close(); } } return true; }
Source:
<code><START> Optional<BbUserUnassigned> on(BbUserDeleted event) { <END> List<UserId> assignees = getState().getAssigneeList(); UserId user = event.getId(); if (!assignees.contains(user)) { return empty(); } return Optional.of(userUnassigned(user)); }</code><technical_language>BbUserUnassigned is a user, while speak of a Project aggregate. this is BbAssigneeRemoved</technical_language>

Target:
Optional<BbAssigneeRemoved> on(BbUserDeleted event) { List<UserId> assignees = getState().getAssigneeList(); UserId user = event.getId(); if (!assignees.contains(user)) { return empty(); } return Optional.of(userUnassigned(user)); }
Source:
<code>void closeSocket() { try { <START> if (sock != null && !sock.isClosed()) { <END> sock.close(); } } catch (IOException e) { LOG.warn("Ignoring error closing connection to leader", e); } }</code><technical_language>curious: checking 'isClosed' ? call 'close' multiple times</technical_language>

Target:
void closeSocket() { try { if (sock != null) { sock.close(); } } catch (IOException e) { LOG.warn("Ignoring error closing connection to leader", e); } }
Source:
<code>public static Pair<String, Map<String, Object>> vertexStatement(ActivityObject activityObject) { Pair<String, Map<String, Object>> mergeVertexRequest = helper.mergeVertexRequest(activityObject); <START> HashMap<String, Object> props = new HashMap<>(); <END> props.put("props", mergeVertexRequest.getValue1()); mergeVertexRequest = mergeVertexRequest.setAt1(props); return mergeVertexRequest; }</code><technical_language>Map<> LHS</technical_language>

Target:
public static Pair<String, Map<String, Object>> vertexStatement(ActivityObject activityObject) { Pair<String, Map<String, Object>> mergeVertexRequest = helper.mergeVertexRequest(activityObject); Map<String, Object> props = new HashMap<>(); props.put("props", mergeVertexRequest.getValue1()); mergeVertexRequest = mergeVertexRequest.setAt1(props); return mergeVertexRequest; }
Source:
<code>public String getTurnDescription( Translation tr ) { <START> if (rawName || !name.isEmpty()) <END> return getName(); return tr.tr("finish"); }</code><technical_language>additional check is in other instructions, is needed</technical_language>

Target:
public String getTurnDescription( Translation tr ) { if (rawName) return getName(); return tr.tr("finish"); }
Source:
<code>private void doSetUserName() { if (!canEditUserName()) { return; } String newName = userNameTxt.getText(); if ("".equals(newName)) { newName = null; } if (newName != null && !newName.matches(Account.USER_NAME_PATTERN)) { invalidUserName(); return; } <START> if (!Window.confirm("Setting the username is permanent. Are you sure?")) { <END> return; } enableUI(false); final String newUserName = newName; Util.ACCOUNT_SEC.changeUserName(newUserName, new GerritCallback<VoidResult>() { public void onSuccess(final VoidResult result) { Gerrit.getUserAccount().setUserName(newUserName); userNameLbl.setText(newUserName); userNameLbl.setVisible(true); userNameTxt.setVisible(false); setUserName.setVisible(false); } @Override public void onFailure(final Throwable caught) { enableUI(true); if (InvalidUserNameException.MESSAGE.equals(caught.getMessage())) { invalidUserName(); } else { super.onFailure(caught); } } }); }</code><technical_language>ConfgirmationDialog class</technical_language>

Target:
private void doSetUserName() { if (!canEditUserName()) { return; } String newName = userNameTxt.getText(); if ("".equals(newName)) { newName = null; } if (newName != null && !newName.matches(Account.USER_NAME_PATTERN)) { invalidUserName(); return; } enableUI(false); final String newUserName = newName; Util.ACCOUNT_SEC.changeUserName(newUserName, new GerritCallback<VoidResult>() { public void onSuccess(final VoidResult result) { Gerrit.getUserAccount().setUserName(newUserName); userNameLbl.setText(newUserName); userNameLbl.setVisible(true); userNameTxt.setVisible(false); setUserName.setVisible(false); } @Override public void onFailure(final Throwable caught) { enableUI(true); if (InvalidUserNameException.MESSAGE.equals(caught.getMessage())) { invalidUserName(); } else { super.onFailure(caught); } } }); }
Source:
<code>private TableView createTemporarySessionView(String tempViewName, String querySQL, List<Column> columnTemplateList, boolean allowRecursiveQueryDetection, boolean addViewToSession) { Schema schema = getSchemaWithDefault(); int id = database.allocateObjectId(); TableView view = new TableView(schema, id, tempViewName, querySQL, parameters, columnTemplateList.toArray(new Column[0]), session, <START> allowRecursiveQueryDetection , false); <END> if (!view.isRecursiveQueryDetected() && allowRecursiveQueryDetection) { view = new TableView(schema, id, tempViewName, querySQL, parameters, columnTemplateList.toArray(new Column[0]), session, false , false); } view.setTableExpression(true); view.setTemporary(true); if(addViewToSession){ session.addLocalTempTable(view); } view.setOnCommitDrop(true); return view; }</code><technical_language>remove /* recursive */ commnent now, I put in for boolean params passing a literal, more obvious param is for</technical_language>

Target:
private TableView createTemporarySessionView(String tempViewName, String querySQL, List<Column> columnTemplateList, boolean allowRecursiveQueryDetection, boolean addViewToSession) { Schema schema = getSchemaWithDefault(); int id = database.allocateObjectId(); TableView view = new TableView(schema, id, tempViewName, querySQL, parameters, columnTemplateList.toArray(new Column[0]), session, allowRecursiveQueryDetection, false); if (!view.isRecursiveQueryDetected() && allowRecursiveQueryDetection) { view = new TableView(schema, id, tempViewName, querySQL, parameters, columnTemplateList.toArray(new Column[0]), session, false , false); } view.setTableExpression(true); view.setTemporary(true); view.setHidden(true); if(addViewToSession){ session.addLocalTempTable(view); } view.setOnCommitDrop(false); return view; }
Source:
<code>public TimestampTracker(Environment env, TransactorID tid, long updatePeriodMs) { Preconditions.checkNotNull(env, "environment cannot null"); Preconditions.checkNotNull(tid, "tid cannot null"); Preconditions.checkArgument(updatePeriodMs > 0, "update period must be positive"); this.env = env; this.tid = tid; status = TrackerStatus.IDLE; TimerTask tt = new TimerTask() { @Override <START> public void run() { <END> synchronized(status) { if (status == TrackerStatus.CLOSED) { return; } else if (status == TrackerStatus.BUSY) { updateZkNode(getOldestActiveTimestamp()); } else if (status == TrackerStatus.IDLE) { closeZkNode(); } else { throw new IllegalStateException("Unknown status"); } } } }; timer = new Timer("TimestampTracker timer", true); timer.schedule(tt, updatePeriodMs, updatePeriodMs); }</code><technical_language>Do java timer exception is thrown? I worried info dropped floor. Wondering if run method catch exception log it</technical_language>

Target:
public TimestampTracker(Environment env, TransactorID tid, long updatePeriodMs) { Preconditions.checkNotNull(env, "environment cannot null"); Preconditions.checkNotNull(tid, "tid cannot null"); Preconditions.checkArgument(updatePeriodMs > 0, "update period must be positive"); this.env = env; this.tid = tid; status = TrackerStatus.IDLE; TimerTask tt = new TimerTask() { @Override public void run() { try { boolean update = false; long ts = 0; synchronized(TimestampTracker.this) { if (status == TrackerStatus.CLOSED) { return; } else if (status == TrackerStatus.BUSY) { update = true; ts = getOldestActiveTimestamp(); } else if (status == TrackerStatus.IDLE) { closeZkNode(); } else { log.error("Unknown status encountered in Zookeeper update thread"); return; } } if (update) { updateZkNode(ts); } } catch (Exception e) { log.error("Exception occurred in Zookeeper update thread", e); } } }; timer = new Timer("TimestampTracker timer", true); timer.schedule(tt, updatePeriodMs, updatePeriodMs); }
Source:
<code>public static final TestEnvironment getTestEnvironment() { if (!OpenNMSSeleniumTestCase.isDockerEnabled()) { return new NullTestEnvironment(); } try { final TestEnvironmentBuilder builder = TestEnvironment.builder().all(); builder.withOpenNMSEnvironment() .addFile(TelemetryIT.class.getResource("/telemetryd-configuration.xml"), "etc/telemetryd-configuration.xml") <START> .addFile(TelemetryIT.class.getResource("/telemetryd-adapters/junos-telemetry-interface.groovy"), <END> "etc/telemetryd-adapters/junos-telemetry-interface.groovy"); OpenNMSSeleniumTestCase.configureTestEnvironment(builder); m_testEnvironment = builder.build(); return m_testEnvironment; } catch (final Throwable t) { throw new RuntimeException(t); } }</code><technical_language>able existing Groovy script instead of re-bundling here</technical_language>

Target:
public static final TestEnvironment getTestEnvironment() { if (!OpenNMSSeleniumTestCase.isDockerEnabled()) { return new NullTestEnvironment(); } try { final TestEnvironmentBuilder builder = TestEnvironment.builder().all(); builder.withOpenNMSEnvironment() .addFile(TelemetryIT.class.getResource("/telemetryd-configuration.xml"), "etc/telemetryd-configuration.xml"); OpenNMSSeleniumTestCase.configureTestEnvironment(builder); m_testEnvironment = builder.build(); return m_testEnvironment; } catch (final Throwable t) { throw new RuntimeException(t); } }
Source:
<code>public IStatus validate(Object in) { <START> String value = (String) in; <END> if(allowEmpty && StringUtils.isBlank(value)) { return ValidationStatus.ok(); } if (!UrlUtils.isValid(value)) { return ValidationStatus.error(invalidURLMessage); } return ValidationStatus.ok(); }</code><technical_language>is a org.apache.commons.validator.routines.UrlValidator provided commons-validator</technical_language>

Target:
public IStatus validate(Object in) { String value = (String) in; if(allowEmpty && StringUtils.isBlank(value)) { return ValidationStatus.ok(); } if (!validator.isValid(value)) { return ValidationStatus.error(invalidURLMessage); } return ValidationStatus.ok(); }
Source:
<code>private static DataInfoBasedApprover buildApprover(String skipDeletedByInference, String trustLevelThreshold, String inferenceProvenanceBlacklist) { <START> Float trustLevelThresholdFloat = null; if (StringUtils.isNotBlank(trustLevelThreshold) && !UNDEFINED_NONEMPTY_VALUE.equals(trustLevelThreshold)) { trustLevelThresholdFloat = Float.valueOf(trustLevelThreshold); } <END> return new DataInfoBasedApprover(inferenceProvenanceBlacklist, Boolean.valueOf(skipDeletedByInference), trustLevelThresholdFloat); }</code><technical_language>Slightly more compact implementation java Optional.ofNullable(trustLevelThreshold) .filter(x -> StringUtils.isNotBlank(x) && !UNDEFINED_NONEMPTY_VALUE.equals(x)) .map(Float::parseFloat) .orElse(null);</technical_language>

Target:
private static DataInfoBasedApprover buildApprover(String skipDeletedByInference, String trustLevelThreshold, String inferenceProvenanceBlacklist) { Float trustLevelThresholdFloat = Optional.ofNullable(trustLevelThreshold) .filter(x -> StringUtils.isNotBlank(x) && !UNDEFINED_NONEMPTY_VALUE.equals(x)).map(Float::parseFloat) .orElse(null); return new DataInfoBasedApprover(inferenceProvenanceBlacklist, Boolean.parseBoolean(skipDeletedByInference), trustLevelThresholdFloat); }
Source:
<code>private void assignOrphans() { Iterator<Replica> it = _orphaned.iterator(); while (it.hasNext()) { Replica replica = it.next(); boolean added = false; Node preferred = _preferredAssignment.get(replica); <START> if (preferred.capacity > preferred.currentlyAssigned && preferred.canAdd(replica)) { <END> preferred.currentlyAssigned ++; preferred.preferred.add(replica); preferred.newReplicas.add(replica); added = true; } else { int startIndex = computeRandomStartIndex(replica); for (int index = startIndex; index < startIndex + _liveNodesList.size(); index++) { Node receiver = _liveNodesList.get(index % _liveNodesList.size()); if (receiver.capacity > receiver.currentlyAssigned && receiver.canAdd(replica)) { receiver.currentlyAssigned = receiver.currentlyAssigned + 1; receiver.nonPreferred.add(replica); receiver.newReplicas.add(replica); added = true; break; } } } if (!added) { added = assignOrphanByMakingRoom(replica); } if (added) { it.remove(); } } if (_orphaned.size() > 0 && logger.isInfoEnabled()) { logger.info("could not assign nodes to partitions: " + _orphaned); } }</code><technical_language>refactor this a method, this is basically code below</technical_language>

Target:
private void assignOrphans() { Iterator<Replica> it = _orphaned.iterator(); while (it.hasNext()) { Replica replica = it.next(); Node preferred = _preferredAssignment.get(replica); boolean added = tryAddReplica(preferred, replica, true); if (!added) { int startIndex = computeRandomStartIndex(replica); for (int index = startIndex; index < startIndex + _liveNodesList.size(); index++) { Node receiver = _liveNodesList.get(index % _liveNodesList.size()); added = tryAddReplica(receiver, replica, false); if (added) { break; } } } if (!added) { added = assignOrphanByMakingRoom(replica); } if (added) { it.remove(); } } if (_orphaned.size() > 0 && logger.isInfoEnabled()) { logger.info("could not assign nodes to partitions: " + _orphaned); } }
Source:
<code>protected void processMetadata(Class<?> targetType, Method method, MethodMetadata metadata) { String httpMethod = metadata.template().method(); if (httpMethod == null) { throw new SafeNullPointerException( "An HTTP method is required", SafeArg.of("class", targetType.getSimpleName()), SafeArg.of("method", method.getName())); } try { HttpMethod.valueOf(httpMethod.toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException e) { throw new SafeIllegalArgumentException( "Unsupported HTTP method", SafeArg.of("class", targetType.getSimpleName()), SafeArg.of("method", method.getName()), <START> SafeArg.of("method", httpMethod)); <END> } metadata.template().header(ENDPOINT_NAME_HEADER, method.getName()); }</code><technical_language>suggestion SafeArg.of("httpMethod", httpMethod));</technical_language>

Target:
protected void processMetadata(Class<?> targetType, Method method, MethodMetadata metadata) { String httpMethod = metadata.template().method(); if (httpMethod == null) { throw new SafeNullPointerException( "An HTTP method is required", SafeArg.of("class", targetType.getSimpleName()), SafeArg.of("method", method.getName())); } try { HttpMethod.valueOf(httpMethod.toUpperCase(Locale.ENGLISH)); } catch (IllegalArgumentException e) { throw new SafeIllegalArgumentException( "Unsupported HTTP method", SafeArg.of("class", targetType.getSimpleName()), SafeArg.of("method", method.getName()), SafeArg.of("httpMethod", httpMethod)); } metadata.template().header(ENDPOINT_NAME_HEADER, method.getName()); }
Source:
<code>public static Address extractAddress(@Nullable final Form<?> form, final String suffix) { if (form != null) { <START> final CountryCode country = countryOrUndefined(form.field("country" + suffix).value()); <END> return AddressBuilder.of(country) .title(form.field("title" + suffix).value()) .firstName(form.field("firstName" + suffix).value()) .lastName(form.field("lastName" + suffix).value()) .streetName(form.field("streetName" + suffix).value()) .additionalStreetInfo(form.field("additionalStreetInfo" + suffix).value()) .city(form.field("city" + suffix).value()) .postalCode(form.field("postalCode" + suffix).value()) .region(form.field("region" + suffix).value()) .phone(form.field("phone" + suffix).value()) .email(form.field("email" + suffix).value()) .build(); } else { return Address.of(CountryCode.UNDEFINED); } }</code><technical_language>is repetitive, this better? java final Function<String, String> fieldExtractor = fieldName -> form.field(fieldName + suffix).value(); return AddressBuilder.of(country) .title(fieldExtractor.apply("title")) .firstName(fieldExtractor.apply("firstName)) //etc. .build();</technical_language>

Target:
public static Address extractAddress(@Nullable final Form<?> form, final String suffix) { if (form != null) { final Function<String, String> formExtractor = formFieldExtractor(form, suffix); final CountryCode country = countryOrUndefined(formExtractor.apply("country")); return AddressBuilder.of(country) .title(formExtractor.apply("title")) .firstName(formExtractor.apply("firstName")) .lastName(formExtractor.apply("lastName")) .streetName(formExtractor.apply("streetName")) .additionalStreetInfo(formExtractor.apply("additionalStreetInfo")) .city(formExtractor.apply("city")) .postalCode(formExtractor.apply("postalCode")) .region(formExtractor.apply("region")) .phone(formExtractor.apply("phone")) .email(formExtractor.apply("email")) .build(); } else { return Address.of(CountryCode.UNDEFINED); } }
Source:
<code>public void beforeTextChanged(CharSequence s, int start, int count, int after) { int lastCharacterLocation = start + count - 1; <START> if (s.length() > lastCharacterLocation && lastCharacterLocation >= 0) { <END> if (after < count) { if (after > 0) { mLastOperation = Operation.REPLACE; } else { mLastOperation = Operation.DELETE; } mOffset = start; mModifiedText = s.subSequence(start + after, start + count); } } }</code><technical_language>If s is null, get a NPE. chance of this @Override</technical_language>

Target:
public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (s == null) { return; } int lastCharacterLocation = start + count - 1; if (s.length() > lastCharacterLocation && lastCharacterLocation >= 0) { if (after < count) { if (after > 0) { mLastOperation = Operation.REPLACE; } else { mLastOperation = Operation.DELETE; } mOffset = start; mModifiedText = s.subSequence(start + after, start + count); } } }