auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private <T extends Item> void mergeBroadcasts( Application application, T chosen, Iterable<T> notChosen, Set<Annotation> activeAnnotations ) { List<T> all = ImmutableList.<T>builder().add(chosen).addAll(notChosen).build(); List<T> notChosenOrdered = application.getConfiguration() .getReadPrecedenceOrdering() .onResultOf(Sourceds.toPublisher()) .sortedCopy(notChosen); List<T> first = application.getConfiguration() .getReadPrecedenceOrdering() .onResultOf(Sourceds.toPublisher()) .leastOf( all.stream() .filter(HAS_BROADCASTS::apply) .collect(Collectors.toList()), 1 ); <START> if (activeAnnotations.contains(Annotation.ALL_BROADCASTS)) { <END> chosen.setBroadcasts( all.stream() .map(T::getBroadcasts) .flatMap(Collection::stream) .collect(MoreCollectors.toImmutableSet()) ); return; } if (!first.isEmpty()) { Publisher sourceForBroadcasts = Iterables.getOnlyElement(first).getSource(); chosen.setBroadcasts( all.stream() .filter(item -> activeAnnotations.contains(Annotation.ALL_MERGED_BROADCASTS) || item.getSource().equals(sourceForBroadcasts) ) .map(T::getBroadcasts) .flatMap(Collection::stream) .collect(MoreCollectors.toImmutableSet()) ); } if (chosen.getBroadcasts() != null && !chosen.getBroadcasts().isEmpty()) { for (Broadcast chosenBroadcast : chosen.getBroadcasts()) { matchAndMerge(chosenBroadcast, notChosenOrdered); } } }</code><technical_language>I suggest putting this if statement computing (line 613) previous computations redundant if this is true</technical_language>

Target:
private <T extends Item> void mergeBroadcasts( Application application, T chosen, Iterable<T> notChosen, Set<Annotation> activeAnnotations ) { List<T> all = ImmutableList.<T>builder().add(chosen).addAll(notChosen).build(); if (activeAnnotations.contains(Annotation.ALL_BROADCASTS)) { chosen.setBroadcasts( all.stream() .map(T::getBroadcasts) .flatMap(Collection::stream) .collect(MoreCollectors.toImmutableSet()) ); return; } List<T> notChosenOrdered = application.getConfiguration() .getReadPrecedenceOrdering() .onResultOf(Sourceds.toPublisher()) .sortedCopy(notChosen); List<T> first = application.getConfiguration() .getReadPrecedenceOrdering() .onResultOf(Sourceds.toPublisher()) .leastOf( all.stream() .filter(HAS_BROADCASTS::apply) .collect(Collectors.toList()), 1 ); if (!first.isEmpty()) { Publisher sourceForBroadcasts = Iterables.getOnlyElement(first).getSource(); chosen.setBroadcasts( all.stream() .filter(item -> activeAnnotations.contains(Annotation.ALL_MERGED_BROADCASTS) || item.getSource().equals(sourceForBroadcasts) ) .map(T::getBroadcasts) .flatMap(Collection::stream) .collect(MoreCollectors.toImmutableSet()) ); } if (chosen.getBroadcasts() != null && !chosen.getBroadcasts().isEmpty()) { for (Broadcast chosenBroadcast : chosen.getBroadcasts()) { matchAndMerge(chosenBroadcast, notChosenOrdered); } } }
Source:
<code><START> protected void reduceToMinimalMerge() throws MergeException { <END> final Collection<CodeReviewCommit> heads; try { heads = new MergeSorter(rw, alreadyAccepted, CAN_MERGE).sort(toMerge); } catch (IOException e) { throw new MergeException("Branch head sorting failed", e); } toMerge.clear(); toMerge.addAll(heads); Collections.sort(toMerge, new Comparator<CodeReviewCommit>() { public int compare(final CodeReviewCommit a, final CodeReviewCommit b) { return a.originalOrder - b.originalOrder; } }); }</code><technical_language>subclasses allowed override this method</technical_language>

Target:
protected final void reduceToMinimalMerge() throws MergeException { final Collection<CodeReviewCommit> heads; try { heads = new MergeSorter(rw, alreadyAccepted, CAN_MERGE).sort(toMerge); } catch (IOException e) { throw new MergeException("Branch head sorting failed", e); } toMerge.clear(); toMerge.addAll(heads); Collections.sort(toMerge, new Comparator<CodeReviewCommit>() { public int compare(final CodeReviewCommit a, final CodeReviewCommit b) { return a.originalOrder - b.originalOrder; } }); }
Source:
<code>public Response listPhrasesForPage(@HeaderParam("Authorization") String authorization, @PathParam("package") String packageCode, @PathParam("pageName") String pageName) { logger.info(String.format("Listing phrases w/ authorization %s", authorization)); AuthorizationRecord.checkAdminAccess(authorizationService.getAuthorizationRecord(null, authorization), clock.currentDateTime()); logger.info(String.format("Listing phrases, admin validated. Listing phrases for %s-%s", packageCode, pageName)); Optional<GodToolsTranslation> translationOptional = draftTranslation.retrieve(BASE_LANGUAGE_CODE, packageCode, false); if(!translationOptional.isPresent()) { translationOptional = publishedTranslation.retrieve(BASE_LANGUAGE_CODE, packageCode, false); if(!translationOptional.isPresent()) { logger.warn("Something weird... no published English translation for: " + packageCode); <START> return Response.status(Response.Status.BAD_REQUEST).build(); <END> } } Optional<PageStructure> pageOptional = translationOptional.get().getPage(pageName); if(!pageOptional.isPresent()) { logger.warn(String.format("Listing phrases, Page %s not found English translation for %s", pageName, packageCode)); return Response.status(Response.Status.NOT_FOUND).build(); } List<TranslationElement> translationElements = translationElementService.selectByTranslationIdPageStructureId(translationOptional.get().getTranslation().getId(), pageOptional.get().getId()); return Response .ok(translationElements) .build(); }</code><technical_language>a NOT_FOUND more helpful</technical_language>

Target:
public Response listPhrasesForPage(@HeaderParam("Authorization") String authorization, @PathParam("package") String packageCode, @PathParam("pageName") String pageName) { logger.info(String.format("Listing phrases w/ authorization %s", authorization)); AuthorizationRecord.checkAdminAccess(authorizationService.getAuthorizationRecord(null, authorization), clock.currentDateTime()); logger.info(String.format("Listing phrases, admin validated. Listing phrases for %s-%s", packageCode, pageName)); Optional<GodToolsTranslation> translationOptional = getGodToolsTranslationOptional(packageCode); Optional<PageStructure> pageOptional = translationOptional.get().getPage(pageName); if(!pageOptional.isPresent()) { logger.warn(String.format("Listing phrases, Page %s not found English translation for %s", pageName, packageCode)); return Response.status(Response.Status.NOT_FOUND).build(); } List<TranslationElement> translationElements = translationElementService.selectByTranslationIdPageStructureId(translationOptional.get().getTranslation().getId(), pageOptional.get().getId()); return Response .ok(translationElements) .build(); }
Source:
<code>void initListBoxEditors() { vncKeyboardLayoutEditor = new ListModelListBoxEditor<String>(new AbstractRenderer<String>() { final String globalLayout = (String) AsyncDataProvider.getConfigValuePreConverted(ConfigurationValues.VncKeyboardLayout); @Override public String render(String object) { if (object == null) { return messages.globalVncKeyboardLayoutCaption(globalLayout); } else { return object; } }; }); <START> } <END></code><technical_language>please reuse code in AbstractVmPopupWidget somehow. I guess change here/there forget other one</technical_language>

Target:
void initListBoxEditors() { vncKeyboardLayoutEditor = new ListModelListBoxEditor<String>(new VncKeyMapRenderer(messages)); }
Source:
<code>private Path getTestingModulemapVFSOverlayLocationFromSymlinkTreeRoot( Path headerSymlinkTreeRoot) { <START> return headerSymlinkTreeRoot.resolve("testing.yaml"); <END> }</code><technical_language>consistent naming of objc-module-overlay.yaml name this testing-overlay.yaml</technical_language>

Target:
private Path getTestingModulemapVFSOverlayLocationFromSymlinkTreeRoot( Path headerSymlinkTreeRoot) { return headerSymlinkTreeRoot.resolve("testing-overlay.yaml"); }
Source:
<code>public void doTestFailAsEncodingNotSupportedBase64() throws Exception { exception.expect(PipeRunException.class); exception.expectMessage("Pipe [FilePipe under test] msgId [null] Error while executing file action(s): (UnsupportedEncodingException) /"); <START> Parameter p = new Parameter(); p.setSessionKey("key"); p.setName("p1"); p.setValue("15"); p.setType("int"); p.configure(); <END> session1.put("key", p); PipeForward fw = new PipeForward(); fw.setName("test"); pipe.registerForward(fw); pipe.addParameter(p); pipe.setCharset("/"); pipe.setDirectory(sourceFolderPath); pipe.setOutputType("base64"); pipe.setActions("read"); pipe.setFileName("1.txt"); pipe.setFileSource("filesystem"); pipe.setActions("create"); pipe.configure(); pipe.doPipe(var, session1); }</code><technical_language>Please put setters other for readability</technical_language>

Target:
public void doTestFailAsEncodingNotSupportedBase64() throws Exception { exception.expect(PipeRunException.class); exception.expectMessage("Pipe [FilePipe under test] msgId [null] Error while executing file action(s): (UnsupportedEncodingException) /"); Parameter p = new Parameter(); p.setSessionKey("key"); p.setName("p1"); p.setValue("15"); p.setType("int"); p.configure(); session1.put("key", p); PipeForward fw = new PipeForward(); fw.setName("test"); pipe.registerForward(fw); pipe.addParameter(p); pipe.setCharset("/"); pipe.setDirectory(sourceFolderPath); pipe.setOutputType("base64"); pipe.setActions("read"); pipe.setFileName("1.txt"); pipe.setFileSource("filesystem"); pipe.setActions("create"); pipe.configure(); doPipe(pipe, var, session1); fail("this will fail"); }
Source:
<code>public static void delete(File file) throws IOException { for (int n = 0; n < 10; n++) { try { Files.delete(file.toPath()); } catch (DirectoryNotEmptyException dnee) { Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); continue; } catch (AccessDeniedException ade) { Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); continue; } catch (NoSuchFileException nse) { return; } <START> return; <END> } throw new IOException("Could not delete: " + file.toPath()); }</code><technical_language>[minor] Move this Files.delete, for clarity</technical_language>

Target:
public static void delete(File file) throws IOException { for (int n = 0; n < 10; n++) { try { Files.delete(file.toPath()); if (Files.exists(file.toPath())) { Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS); continue; } return; } catch (DirectoryNotEmptyException dnee) { Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); continue; } catch (AccessDeniedException ade) { Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); continue; } catch (NoSuchFileException nse) { return; } } throw new IOException("Could not delete: " + file.toPath()); }
Source:
<code>public void resignLeadership() { if (isLeader.get()) { boolean status = leaseBlobManager.releaseLease(leaseId.get()); <START> if (status) { <END> isLeader.set(false); leaseId = null; renewLeaseSF.cancel(true); livenessSF.cancel(true); } } else { LOG.info("Can't release the lease because it is not the leader and does not hold an active lease."); } }</code><technical_language>if status is false? I set isLeader state false, irrespective of release successful not</technical_language>

Target:
public void resignLeadership() { if (isLeader.get()) { leaseBlobManager.releaseLease(leaseId.get()); isLeader.set(false); LOG.info("Resigning leadership with lease ID {}", leaseId.get()); leaseId.getAndSet(null); } else { LOG.info("Can't release the lease because it is not the leader and does not hold an active lease."); } }
Source:
<code>public String getOrCreateToken(String userId, String workspaceId) { lock.writeLock().lock(); try { final Map<String, String> wsRow = tokens.row(workspaceId); String token = wsRow.get(userId); if (token == null) { <START> final PrivateKey privateKey = signatureKeyManager.getKeyPair().getPrivate(); <END> final User user = userManager.getById(userId); final Map<String, Object> header = new HashMap<>(2); header.put("kind", MACHINE_TOKEN_KIND); final Map<String, Object> claims = new HashMap<>(2); claims.put(Claims.ID, UUID.randomUUID().toString()); claims.put(Constants.USER_ID_CLAIM, userId); claims.put(Constants.USER_NAME_CLAIM, user.getName()); claims.put(Constants.WORKSPACE_ID_CLAIM, workspaceId); token = Jwts.builder() .setClaims(claims) .setHeader(header) .signWith(RS512, privateKey) .compact(); tokens.put(workspaceId, userId, token); } return token; } catch (NotFoundException | ServerException ex) { throw new IllegalStateException( format( "Failed to generate machine token for user '%s' and workspace '%s' cause: '%s'", userId, workspaceId, ex.getMessage()), ex); } finally { lock.writeLock().unlock(); } }</code><technical_language>move new code a separate method</technical_language>

Target:
public String getOrCreateToken(String userId, String workspaceId) { lock.writeLock().lock(); try { final Map<String, String> wsRow = tokens.row(workspaceId); String token = wsRow.get(userId); if (token == null) { token = createToken(userId, workspaceId); } return token; } catch (NotFoundException | ServerException ex) { throw new IllegalStateException( format( "Failed to generate machine token for user '%s' and workspace '%s'. Cause: '%s'", userId, workspaceId, ex.getMessage()), ex); } finally { lock.writeLock().unlock(); } }
Source:
<code>public void roleNotSetTest() { loginPage.open(); loginPage.login("test-user@localhost", "password"); doAIA(); <START> assertRedirectSuccess(); END> }</code><technical_language>In event client is initiate AIA, is permitted do error page displayed redirecting app</technical_language>

Target:
public void roleNotSetTest() { loginPage.open(); loginPage.login("test-user@localhost", "password"); doAIA(); errorPage.assertCurrent(); }
Source:
<code>protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource, ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) { super.initializeExtraSubystemsAndModel(extensionRegistry, rootResource, rootRegistration, capabilityRegistry); Map<String, Class> capabilities = new HashMap<>(); capabilities.put(WELD_CAPABILITY_NAME, WeldCapability.class); <START> capabilities.put("org.wildfly.microprofile.config", Void.class); <END> registerServiceCapabilities(capabilityRegistry, capabilities); }</code><technical_language>Please org.wildfly.extension.microprofile.opentracing.SubsystemDefinition#MICROPROFILE_CONFIG_CAPABILITY_NAME instead public</technical_language>

Target:
protected void initializeExtraSubystemsAndModel(ExtensionRegistry extensionRegistry, Resource rootResource, ManagementResourceRegistration rootRegistration, RuntimeCapabilityRegistry capabilityRegistry) { super.initializeExtraSubystemsAndModel(extensionRegistry, rootResource, rootRegistration, capabilityRegistry); Map<String, Class> capabilities = new HashMap<>(); capabilities.put(WELD_CAPABILITY_NAME, WeldCapability.class); registerServiceCapabilities(capabilityRegistry, capabilities); }
Source:
<code>public DocumentModelList run(DocumentModelList documents) { DocumentModelList result = new DocumentModelListImpl(); for (DocumentModel documentModel : documents) { try { result.add(moveContent(documentModel, false)); <START> } catch (Exception e) { <END> log.error("Unable to move document: to cold storage", documentModel.getId(), e); } } if (save) { session.saveDocuments(result.toArray(new DocumentModel[0])); } return result; }</code><technical_language>catching Exception here? Do forget <LINK_0> :)</technical_language>

Target:
public DocumentModelList run(DocumentModelList documents) { DocumentModelList result = new DocumentModelListImpl(); for (DocumentModel documentModel : documents) { try { result.add(run(documentModel)); } catch (NuxeoException e) { log.error("Unable to move document: to cold storage", documentModel.getId(), e); } } return result; }
Source:
<code>void dialogChanged() { IResource container = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(getProject())); if(getProject().length() == 0) { updateStatus(Messages.MavenPomWizardPage_error_folder); return; } if(container == null || (container.getType() & IResource.FOLDER | IResource.PROJECT) == 0) { updateStatus(Messages.MavenPomWizardPage_error_folder2); return; } if(!container.isAccessible()) { updateStatus(Messages.MavenPomWizardPage_error_folder_write); return; } <START> String message = validateInput(pomComponent.getGroupId(), false); <END> if(message != null) { updateStatus(message); return; } message = validateInput(pomComponent.getArtifactId(), true); if(message != null) { updateStatus(message); return; } if(pomComponent.getVersion().length() == 0) { updateStatus(Messages.MavenPomWizardPage_error_version); return; } if(pomComponent.getPackaging().length() == 0) { updateStatus(Messages.MavenPomWizardPage_error_pack); return; } if(container instanceof IProject && projectConversionEnabler != null) { IStatus status = projectConversionEnabler.canBeConverted((IProject) container); if(status.getSeverity() == IStatus.ERROR) { updateStatus(status.getMessage()); return; } } updateStatus(null); }</code><technical_language>simpler: message = validateGroupIdInput(pomComponent.getGroupId());</technical_language>

Target:
void dialogChanged() { IResource container = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(getProject())); if(getProject().length() == 0) { updateStatus(Messages.MavenPomWizardPage_error_folder); return; } if(container == null || (container.getType() & IResource.FOLDER | IResource.PROJECT) == 0) { updateStatus(Messages.MavenPomWizardPage_error_folder2); return; } if(!container.isAccessible()) { updateStatus(Messages.MavenPomWizardPage_error_folder_write); return; } String message = validateGroupIdInput(pomComponent.getGroupId()); if(message != null) { updateStatus(message); return; } message = validateArtifactIdInput(pomComponent.getArtifactId()); if(message != null) { updateStatus(message); return; } if(pomComponent.getVersion().length() == 0) { updateStatus(Messages.MavenPomWizardPage_error_version); return; } if(pomComponent.getPackaging().length() == 0) { updateStatus(Messages.MavenPomWizardPage_error_pack); return; } if(container instanceof IProject && projectConversionEnabler != null) { IStatus status = projectConversionEnabler.canBeConverted((IProject) container); if(status.getSeverity() == IStatus.ERROR) { updateStatus(status.getMessage()); return; } } updateStatus(null); }
Source:
<code>public static void renameTempPartitionFile(File workDir, int partId) throws IgniteCheckedException { File defragmentedPartTmpFile = defragmentedPartTmpFile(workDir, partId); File defragmentedPartFile = defragmentedPartFile(workDir, partId); <START> assert !defragmentedPartFile.exists() : defragmentedPartFile; <END> try { Files.move(defragmentedPartTmpFile.toPath(), defragmentedPartFile.toPath(), ATOMIC_MOVE); } catch (IOException e) { handleIoException(e); } }</code><technical_language>a race if a user deletes this file manually - handle cases regular IO exceptions assertions</technical_language>

Target:
public static void renameTempPartitionFile(File workDir, int partId) throws IgniteException { File defragmentedPartTmpFile = defragmentedPartTmpFile(workDir, partId); File defragmentedPartFile = defragmentedPartFile(workDir, partId); assert !defragmentedPartFile.exists() : defragmentedPartFile; try { Files.move(defragmentedPartTmpFile.toPath(), defragmentedPartFile.toPath(), ATOMIC_MOVE); } catch (IOException e) { throw new IgniteException(e); } }
Source:
<code><START> public void streaming(InputStream stream) <END></code><technical_language>this endpoint needs consume stream in order test properly</technical_language>

Target:
public String streaming(InputStream stream) { try { byte[] bytes = ByteStreams.toByteArray(stream); return new String(bytes, StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { <START> parameterTypeCheck(args[0], ntp1); <END> parameterTypeCheck(args[1], ntp2); if (nodeCompare(FunctionHelper.getLocalNodeId(args[0], tp), FunctionHelper.getLocalNodeId(args[1], tp))) { XDMConstants.setTrue(result); } else { XDMConstants.setFalse(result); } }</code><technical_language>I code cleaner short if function call if statements following: if (args[0].getTag() != ValueTag.NODE_TREE_TAG) { throw new SystemException(ErrorCode.FORG0006); }</technical_language>

Target:
protected void evaluate(TaggedValuePointable[] args, IPointable result) throws SystemException { if (args[0].getTag() != ValueTag.NODE_TREE_TAG) { throw new SystemException(ErrorCode.FORG0006); } if (args[1].getTag() != ValueTag.NODE_TREE_TAG) { throw new SystemException(ErrorCode.FORG0006); } if (nodeCompare(FunctionHelper.getLocalNodeId(args[0], tp), FunctionHelper.getLocalNodeId(args[1], tp))) { XDMConstants.setTrue(result); } else { XDMConstants.setFalse(result); } }
Source:
<code>public String getAlign() { <START> if (mAlign.startsWith(ATTR_ALIGN)) { <END> return mAlign.substring(ATTR_ALIGN.length(), mAlign.length()); } return mAlign; }</code><technical_language>Do need null check mAlign here</technical_language>

Target:
public String getAlign() { if (!TextUtils.isEmpty(mAlign) && mAlign.startsWith(ATTR_ALIGN)) { return mAlign.substring(ATTR_ALIGN.length(), mAlign.length()); } return mAlign; }
Source:
<code>public LocalDateTime getDate() { <START> if (viewModel.getDate() == null) { <END> LocalDateTime date = (LocalDateTime) getArguments().getSerializable(DateTimeWidgetUtils.DATE); viewModel.setDate(date); } return viewModel.getDate(); }</code><technical_language>I viewmodel's responsibility return null, this check moved call viewModel.getDate();</technical_language>

Target:
public LocalDateTime getDate() { return getDay() == 0 ? viewModel.getLocalDateTime() : getOriginalDate(); }
Source:
<code>private static void setTheEnvironmentVariablesAddthePlatformTxt(IContributedEnvironment contribEnv, ICConfigurationDescription confDesc, IPath platformFile) throws IOException { DataInputStream dataInputStream = new DataInputStream(new FileInputStream(platformFile.toOSString())); BufferedReader br = new BufferedReader(new InputStreamReader(dataInputStream)); String strLine; IEnvironmentVariable var = null; while ((strLine = br.readLine()) != null) { String RealData[] = strLine.split("#"); if (RealData.length > 0) { String Var[] = RealData[0].split("=", 2); if (Var.length == 2) { String Value = MakeEnvironmentString(Var[1].replace("\"{build.path}/syscalls_sam3.c.o\"", "\"{build.path}/arduino/syscalls_sam3.c.o\"")); <START> Value = MakeEnvironmentString(Var[1].replace("\"{build.path}/syscalls_mtk.c.o\"", <END> "\"{build.path}/arduino/syscalls_mtk.c.o\"")); var = new EnvironmentVariable(MakeKeyString(Var[0]), Value); contribEnv.addVariable(var, confDesc); } } } dataInputStream.close(); }</code><technical_language>This is a concern overwrites of due longer work</technical_language>

Target:
private static void setTheEnvironmentVariablesAddthePlatformTxt(IContributedEnvironment contribEnv, ICConfigurationDescription confDesc, IPath platformFile) throws IOException { DataInputStream dataInputStream = new DataInputStream(new FileInputStream(platformFile.toOSString())); BufferedReader br = new BufferedReader(new InputStreamReader(dataInputStream)); String strLine; IEnvironmentVariable var = null; while ((strLine = br.readLine()) != null) { String RealData[] = strLine.split("#"); if (RealData.length > 0) { String Var[] = RealData[0].split("=", 2); if (Var.length == 2) { String value = Var[1]; if (value.contains(BUILD_PATH_SYSCALLS_SAM3)) { value = MakeEnvironmentString(value.replace(BUILD_PATH_SYSCALLS_SAM3, BUILD_PATH_ARDUINO_SYSCALLS_SAM3)); } else if (value.contains(BUILD_PATH_SYSCALLS_MTK)) { value = MakeEnvironmentString(value.replace(BUILD_PATH_SYSCALLS_MTK, BUILD_PATH_ARDUINO_SYSCALLS_MTK)); } var = new EnvironmentVariable(MakeKeyString(Var[0]), value); contribEnv.addVariable(var, confDesc); } } } dataInputStream.close(); }
Source:
<code>public void testBlockFlooder() throws Exception { final EventType eventType = NakadiTestUtils.createEventType(); blacklist(eventType.getName(), BlacklistService.Type.CONSUMER_ET); try { Assert.assertNotNull(CURATOR.checkExists() .forPath("/nakadi/blacklist/consumers/event_types/" + eventType.getName())); } finally { <START> whitelist(eventType.getName(), BlacklistService.Type.CONSUMER_ET); <END> } }</code><technical_language>waste time whitelisting it</technical_language>

Target:
public void testBlockFlooder() throws Exception { final EventType eventType = NakadiTestUtils.createEventType(); blacklist(eventType.getName(), BlacklistService.Type.CONSUMER_ET); Assert.assertNotNull(CURATOR.checkExists() .forPath("/nakadi/blacklist/consumers/event_types/" + eventType.getName())); }
Source:
<code>public void testValidateStatusUpForActivation() { validator = setValidatorForActivation(VDSStatus.Up); ValidationResult result = validator.validateStatusForActivation(); <START> assertEquals(result.getMessage(), VdcBllMessages.VDS_ALREADY_UP); <END> }</code><technical_language>please for negative tests convention: assertThat(validator.validateStatusForActivation(), failsWith( VdcBllMessages.VDS_ALREADY_UP));</technical_language>

Target:
public void testValidateStatusUpForActivation() { validator = mockHostForActivation(VDSStatus.Up); assertThat(validator.validateStatusForActivation(), failsWith( VdcBllMessages.VDS_ALREADY_UP)); }
Source:
<code>private void physicalClose() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Closing cached Channel: " + this.target); } if (this.target == null) { return; } try { <START> this.target.close(); <END> } catch (AlreadyClosedException e) { if (logger.isTraceEnabled()) { logger.trace(this.target + " is already closed"); } } }</code><technical_language>I understand isOpen issue, removed this.target = null;</technical_language>

Target:
private void physicalClose() throws Exception { if (logger.isDebugEnabled()) { logger.debug("Closing cached Channel: " + this.target); } if (this.target == null) { return; } try { this.target.close(); } catch (AlreadyClosedException e) { if (logger.isTraceEnabled()) { logger.trace(this.target + " is already closed"); } } finally { this.target = null; } }
Source:
<code>private void loadOutputChannel(ChannelTypeUID channelTypeUID, String acceptedItemType) { <START> if (channelTypeUID != null && acceptedItemType != null) { <END> currentChannel = channelTypeUID.getId(); List<Channel> channelList = new LinkedList<Channel>(this.getThing().getChannels()); boolean channelIsAlreadyLoaded = false; boolean channelListChanged = false; if (!channelList.isEmpty()) { Iterator<Channel> channelInter = channelList.iterator(); while (channelInter.hasNext()) { Channel eshChannel = channelInter.next(); if (DsChannelTypeProvider.isOutputChannel(eshChannel.getUID().getId())) { if (!eshChannel.getUID().getId().equals(currentChannel) && !(device.isShade() && eshChannel.getUID().getId().equals(DsChannelTypeProvider.SHADE))) { channelInter.remove(); channelListChanged = true; } else { if (!eshChannel.getUID().getId().equals(DsChannelTypeProvider.SHADE)) { channelIsAlreadyLoaded = true; } } } } } if (!channelIsAlreadyLoaded && currentChannel != null) { Channel channel = ChannelBuilder .create(new ChannelUID(this.getThing().getUID(), channelTypeUID.getId()), acceptedItemType) .withType(channelTypeUID).build(); channelList.add(channel); channelListChanged = true; } if (channelListChanged) { ThingBuilder thingBuilder = editThing(); thingBuilder.withChannels(channelList); updateThing(thingBuilder.build()); logger.debug("load channel: with item: {}", channelTypeUID.getAsString(), acceptedItemType); } } }</code><technical_language>a return if this is true. This is do indent method</technical_language>

Target:
private void loadOutputChannel(ChannelTypeUID channelTypeUID, String acceptedItemType) { if (channelTypeUID == null || acceptedItemType == null) { return; } currentChannel = channelTypeUID.getId(); List<Channel> channelList = new LinkedList<Channel>(this.getThing().getChannels()); boolean channelIsAlreadyLoaded = false; boolean channelListChanged = false; if (!channelList.isEmpty()) { Iterator<Channel> channelInter = channelList.iterator(); while (channelInter.hasNext()) { Channel eshChannel = channelInter.next(); if (DsChannelTypeProvider.isOutputChannel(eshChannel.getUID().getId())) { if (!eshChannel.getUID().getId().equals(currentChannel) && !(device.isShade() && eshChannel.getUID().getId().equals(DsChannelTypeProvider.SHADE))) { channelInter.remove(); channelListChanged = true; } else { if (!eshChannel.getUID().getId().equals(DsChannelTypeProvider.SHADE)) { channelIsAlreadyLoaded = true; } } } } } if (!channelIsAlreadyLoaded && currentChannel != null) { Channel channel = ChannelBuilder .create(new ChannelUID(this.getThing().getUID(), channelTypeUID.getId()), acceptedItemType) .withType(channelTypeUID).build(); channelList.add(channel); channelListChanged = true; } if (channelListChanged) { ThingBuilder thingBuilder = editThing(); thingBuilder.withChannels(channelList); updateThing(thingBuilder.build()); logger.debug("load channel: with item: {}", channelTypeUID.getAsString(), acceptedItemType); } }
Source:
<code>public void shouldDeleteNetworkToPublicRouterNoDeleted() throws OpenStackException, InfrastructureException { String response = "{\"ports\": [ {\"status\": \"ACTIVE\",\"name\": \"\", \"admin_state_up\": true, " + "\"network_id\": \"ID\", \"tenant_id\": \"08bed031f6c54c9d9b35b42aa06b51c0\"," + "\"device_owner\": \"compute:None\", \"binding:capabilities\": {\"port_filter\": true}, " + "\"fixed_ips\": [ {\"subnet_id\": \"ID\", \"ip_address\": \"172.31.0.3\"}]," + "\"id\": \"07fd27d2-9ce1-48f3-be83-c7d2b7041a1a\", \"security_groups\": [], \"device_id\":" + " \"dhcpfa3e6aae-2140-5176-877a-2f67684a3165-6a609412-3f04-485c-b269-b1a9b9ecb6bf\"" + "}]}"; when(openStackUtil.listPorts(any(PaasManagerUser.class), anyString())).thenReturn(response); NetworkInstance net = new NetworkInstance("router", "vdc", "region"); SubNetworkInstance subNet = new SubNetworkInstance("dd", "vdc", "region", "ID"); subNet.setIdSubNet("ID"); net.addSubNet(subNet); when(openStackUtil.deleteInterfaceToPublicRouter(any(PaasManagerUser.class), any(NetworkInstance.class), anyString())).thenReturn(response); openStackNetworkImpl.deleteNetworkToPublicRouter(claudiaData, net, REGION); <START> <END> }</code><technical_language>add verify assert</technical_language>

Target:
public void shouldDeleteNetworkToPublicRouterNoDeleted() throws OpenStackException, InfrastructureException { String response = "{\"ports\": [ {\"status\": \"ACTIVE\",\"name\": \"\", \"admin_state_up\": true, " + "\"network_id\": \"ID\", \"tenant_id\": \"08bed031f6c54c9d9b35b42aa06b51c0\"," + "\"device_owner\": \"compute:None\", \"binding:capabilities\": {\"port_filter\": true}, " + "\"fixed_ips\": [ {\"subnet_id\": \"ID\", \"ip_address\": \"172.31.0.3\"}]," + "\"id\": \"07fd27d2-9ce1-48f3-be83-c7d2b7041a1a\", \"security_groups\": [], \"device_id\":" + " \"dhcpfa3e6aae-2140-5176-877a-2f67684a3165-6a609412-3f04-485c-b269-b1a9b9ecb6bf\"" + "}]}"; when(openStackUtil.listPorts(any(PaasManagerUser.class), anyString())).thenReturn(response); NetworkInstance net = new NetworkInstance("router", "vdc", "region"); SubNetworkInstance subNet = new SubNetworkInstance("dd", "vdc", "region", "ID"); subNet.setIdSubNet("ID"); net.addSubNet(subNet); when(openStackUtil.deleteInterfaceToPublicRouter(any(PaasManagerUser.class), any(NetworkInstance.class), anyString())).thenReturn(response); openStackNetworkImpl.deleteNetworkToPublicRouter(claudiaData, net, REGION); verify(openStackUtil, never()).deleteInterfaceToPublicRouter(any(PaasManagerUser.class), any(NetworkInstance.class), anyString()); }
Source:
<code>public void testJvmPauseMonitorExceedInfoThreshold() throws InterruptedException { final Long sleepTime = 100L; final Long infoTH = -1L; ServerConfig serverConfig = new ServerConfig(); QuorumPeerConfig quorumPeerConfig = new QuorumPeerConfig(); Properties zkProp = new Properties(); zkProp.setProperty("dataDir", new File("myDataDir").getAbsolutePath()); zkProp.setProperty("jvm.pause.monitor", "true"); zkProp.setProperty("jvm.pause.sleep.time.ms", sleepTime.toString()); zkProp.setProperty("jvm.pause.info-threshold.ms", infoTH.toString()); try { quorumPeerConfig.parseProperties(zkProp); } catch (IOException | QuorumPeerConfig.ConfigException e) { Assert.fail("Exception while reading config for JvmPauseMonitor"); } serverConfig.readFrom(quorumPeerConfig); JvmPauseMonitor pauseMonitor = new JvmPauseMonitor(serverConfig); <START> pauseMonitor.serviceStart(); <END> Assert.assertEquals(sleepTime, Long.valueOf(pauseMonitor.sleepTimeMs)); Assert.assertEquals(infoTH, Long.valueOf(pauseMonitor.infoThresholdMs)); Thread.sleep(1000); Assert.assertNotEquals(0L, pauseMonitor.getNumGcInfoThresholdExceeded()); Assert.assertEquals(0L, pauseMonitor.getNumGcWarnThresholdExceeded()); }</code><technical_language>stop it</technical_language>

Target:
public void testJvmPauseMonitorExceedInfoThreshold() throws InterruptedException { QuorumPeerConfig qpConfig = mock(QuorumPeerConfig.class); when(qpConfig.getJvmPauseSleepTimeMs()).thenReturn(sleepTime); when(qpConfig.getJvmPauseInfoThresholdMs()).thenReturn(infoTH); pauseMonitor = new JvmPauseMonitor(qpConfig); pauseMonitor.serviceStart(); Assert.assertEquals(sleepTime, Long.valueOf(pauseMonitor.sleepTimeMs)); Assert.assertEquals(infoTH, Long.valueOf(pauseMonitor.infoThresholdMs)); while(pauseMonitor.getNumGcInfoThresholdExceeded() == 0) { Thread.sleep(200); } }
Source:
<code>public static long fromIEEE754Binary32(@SqlType(StandardTypes.VARBINARY) Slice slice) { ByteBuffer buffer = ByteBuffer.wrap(slice.getBytes()); return (long) buffer.getInt(); <START> } <END></code><technical_language>able slice.getInt(0) here</technical_language>

Target:
public static long fromIEEE754Binary32(@SqlType(StandardTypes.VARBINARY) Slice slice) { checkCondition(slice.length() == Integer.BYTES, INVALID_FUNCTION_ARGUMENT, "Input floating-point value must be exactly 4 bytes long"); return Integer.reverseBytes(slice.getInt(0)); }
Source:
<code>private void waitUntilProcessEnds(Long timeoutInSeconds) { boolean finished; try { boolean processWroteDuringWait; do { long beforeWaiting = System.currentTimeMillis(); finished = process.waitFor(timeoutInSeconds, TimeUnit.SECONDS); processWroteDuringWait = beforeWaiting < outputIdleSince.get(); if (processWroteDuringWait && !finished) { logger.debug("Extending the timeout, as the process wrote more lines (it's still active)"); } } while (processWroteDuringWait && !finished); } catch (InterruptedException e) { throw new ItemStreamException(e); } if (!finished) { String timeoutReachedMessage = "VEP has been idle for more than the timeout (" + timeoutInSeconds <START> + " seconds). Killed the process."; <END> logger.error(timeoutReachedMessage); process.destroy(); throw new ItemStreamException(timeoutReachedMessage); } }</code><technical_language>process killed</technical_language>

Target:
private void waitUntilProcessEnds(Long timeoutInSeconds) { boolean finished; try { boolean processWroteDuringWait; do { long beforeWaiting = System.currentTimeMillis(); finished = process.waitFor(timeoutInSeconds, TimeUnit.SECONDS); processWroteDuringWait = beforeWaiting < outputIdleSince.get(); if (processWroteDuringWait && !finished) { logger.debug("Extending the timeout, as the process wrote more lines (it's still active)"); } } while (processWroteDuringWait && !finished); } catch (InterruptedException e) { throw new ItemStreamException(e); } if (!finished) { process.destroy(); String timeoutReachedMessage = "VEP has been idle for more than the timeout (" + timeoutInSeconds + " seconds). The process has been killed."; logger.error(timeoutReachedMessage); throw new ItemStreamException(timeoutReachedMessage); } }
Source:
<code>public Response createPolicy(@Context UriInfo info, @PathParam("tenant") String tenant, @PathParam("subject") String subject, String policy) { String id; try { <START> LOGGER.debug("Creating policy for tenant [" + tenant + "] and subject [" + subject + "]"); <END> id = factory.create(Xml.toXml(policy)).getId().toString(); } catch (Exception e) { LOGGER.error("Cannot parse policy: " + e.getMessage()); return Response.status(400).build(); } dao.createPolicy(new Policy(id, tenant, subject, policy)); return Response.created(info.getAbsolutePathBuilder().path("/policy/" + id).build()).build(); }</code><technical_language><LINK_0></technical_language>

Target:
public Response createPolicy(@Context UriInfo info, @PathParam("tenant") String tenant, @PathParam("subject") String subject, String policy) { String id; try { LOGGER.debug("Creating policy for tenant and subject [{}]", tenant, subject); id = factory.create(Xml.toXml(policy)).getId().toString(); } catch (Exception e) { LOGGER.error("Cannot parse policy: " + e.getMessage()); return Response.status(400).build(); } dao.createPolicy(new Policy(id, tenant, subject, policy)); return Response.created(info.getAbsolutePathBuilder().path("/policy/" + id).build()).build(); }
Source:
<code>public void createEphemeral(String path, Object data, List<ACL> acl) { throw new UnsupportedOperationException( "Create ephemeral nodes using " + SharedZkClient.class.getSimpleName() + " is not supported."); <START> } <END></code><technical_language>Call method ZkClient reduce maintenance effort</technical_language>

Target:
public void createEphemeral(String path, Object data, List<ACL> acl) { throw new UnsupportedOperationException( "Creating ephemeral nodes using " + SharedZkClient.class.getSimpleName() + " is not supported."); }
Source:
<code>public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) { <START> String address = hostAddress.getHostAddress(); <END> try { return mService.requestRouteToHostAddress(networkType, address); } catch (RemoteException e) { return false; } }</code><technical_language>getAddress get a byte array instead - prevents confusion other end string is a host name ip addr</technical_language>

Target:
public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) { byte[] address = hostAddress.getAddress(); try { return mService.requestRouteToHostAddress(networkType, address); } catch (RemoteException e) { return false; } }
Source:
<code>public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { <START> this(poolConfig, uri, timeout, timeout); <END> }</code><technical_language>is clear passing SSL context constructor. *(even of test pass in environment, odd me..)</technical_language>

Target:
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { this(poolConfig, uri, timeout, timeout, sslSocketFactory, sslParameters, hostnameVerifier); }
Source:
<code>private static String loadDefaultLicenseInfoHeaderText(){ try { <START> String defaultLicenseInfoHeader = IOUtils.toString(LicenseInfoHandler.class.getResourceAsStream(DEFAULT_LICENSE_INFO_HEADER_FILE), "UTF-8"); <END> defaultLicenseInfoHeader = defaultLicenseInfoHeader.replaceAll("(?m)^#.*\\n", ""); return defaultLicenseInfoHeader; } catch (IOException e) { LOGGER.error("Could not read default license info header text from file."); return ""; } }</code><technical_language>changed CommonUtils.loadResource() requested. I is important do so</technical_language>

Target:
private static String loadDefaultLicenseInfoHeaderText(){ String defaultLicenseInfoHeader = new String( CommonUtils.loadResource(LicenseInfoHandler.class, DEFAULT_LICENSE_INFO_HEADER_FILE).orElse(new byte[0]) ); defaultLicenseInfoHeader = defaultLicenseInfoHeader.replaceAll("(?m)^#.*\\n", ""); return defaultLicenseInfoHeader; }
Source:
<code>final int createServerSocketChannel(InetAddress bindAddress, int initialPort, boolean bindAny) { int portCount = networkConfig.getPortCount(); boolean portAutoIncrement = networkConfig.isPortAutoIncrement(); logger.finest("inet reuseAddress:" + networkConfig.isReuseAddress()); if (initialPort == 0) { initialPort = networkConfig.getPort() ; } if (initialPort == 0) { logger.info("No explicit port is given, system will pick up an ephemeral port."); } int portTrialCount = initialPort > 0 && portAutoIncrement ? portCount : 1; try { return tryOpenServerSocketChannel(bindAddress, initialPort, portTrialCount, bindAny); } catch (IOException e) { String message = "Cannot bind to a given address: " + bindAddress + ". Hazelcast cannot start. "; if (networkConfig.isPortAutoIncrement()) { <START> message += "Config-port: " + networkConfig.getPort() + ", latest-port: " + (initialPort + portTrialCount); <END> } else { message += "Port [" + initialPort + "] is already in use and auto-increment is disabled."; } throw new HazelcastException(message, e); } }</code><technical_language>this initialPort + portTrialCount - 1</technical_language>

Target:
final int createServerSocketChannel(InetAddress bindAddress, int initialPort, boolean bindAny) { int portCount = networkConfig.getPortCount(); boolean portAutoIncrement = networkConfig.isPortAutoIncrement(); logger.finest("inet reuseAddress:" + networkConfig.isReuseAddress()); if (initialPort == 0) { initialPort = networkConfig.getPort() ; } if (initialPort == 0) { logger.info("No explicit port is given, system will pick up an ephemeral port."); } int portTrialCount = initialPort > 0 && portAutoIncrement ? portCount : 1; try { return tryOpenServerSocketChannel(bindAddress, initialPort, portTrialCount, bindAny); } catch (IOException e) { String message = "Cannot bind to a given address: " + bindAddress + ". Hazelcast cannot start. "; if (networkConfig.isPortAutoIncrement()) { message += "Config-port: " + networkConfig.getPort() + ", latest-port: " + (initialPort + portTrialCount - 1); } else { message += "Port [" + initialPort + "] is already in use and auto-increment is disabled."; } throw new HazelcastException(message, e); } }
Source:
<code>public long save(Run run) throws IOException { updateWatchers(run); long id; if (run.getId() == AbstractRun.UNSAVED_ID) { currentSession().save(run); try { <START> String name = namingScheme.generateNameFor(run); <END> run.setName(name); DbUtils.validateNameOrThrow(run, namingScheme); Number newId = (long) currentSession().save(run); if (newId.longValue() != run.getId()) { log.error("Expected Run ID doesn't match returned value from database insert: rolling back..."); currentSession().delete(run); throw new IOException("Something bad happened. Expected Run ID doesn't match returned value from DB insert"); } else { id = run.getId(); } } catch (MisoNamingException e) { throw new IOException("Cannot save Run - issue with generating name"); } } else { currentSession().update(run); id = run.getId(); } return id; }</code><technical_language>Name generation validation moved service layer</technical_language>

Target:
public long save(Run run) throws IOException { updateWatchers(run); long id; if (run.getId() == AbstractRun.UNSAVED_ID) { currentSession().save(run); } else { currentSession().update(run); } id = run.getId(); return id; }
Source:
<code>private static <E> View<E> load(Configuration conf) { Class<E> type; try { type = (Class<E>)conf.getClass(KITE_TYPE, GenericData.Record.class); } catch (RuntimeException e) { if (e.getCause() instanceof ClassNotFoundException) { throw new TypeNotFoundException(String.format( "The Java class %s for the entity type could not be found", conf.get(KITE_TYPE)), e.getCause()); } else { throw e; } } String inputUri = conf.get(KITE_INPUT_URI); <START> DefaultConfiguration.set(conf); <END> return Datasets.<E, View<E>>load(inputUri, type); }</code><technical_language>OutputFormat, I this done soon in a method is called setup job. createRecordReader a good place for this in InputFormat. want avoid setting default configuration in job client process</technical_language>

Target:
private static <E> View<E> load(Configuration conf) { Class<E> type; try { type = (Class<E>)conf.getClass(KITE_TYPE, GenericData.Record.class); } catch (RuntimeException e) { if (e.getCause() instanceof ClassNotFoundException) { throw new TypeNotFoundException(String.format( "The Java class %s for the entity type could not be found", conf.get(KITE_TYPE)), e.getCause()); } else { throw e; } } String inputUri = conf.get(KITE_INPUT_URI); return Datasets.<E, View<E>>load(inputUri, type); }
Source:
<code>private boolean checkCertificate(X509Certificate cert, AuditLogType alertExpirationEventType, AuditLogType alertAboutToExpireEventType, AuditLogType warnAboutToExpireEventType, VDS host) { Date expirationDate = cert.getNotAfter(); Date certWarnTime = getExpirationDate(expirationDate, ConfigValues.CertExpirationWarnPeriodInDays); Date certAlertTime = getExpirationDate(expirationDate, ConfigValues.CertExpirationAlertPeriodInDays); Date now = new Date(); AuditLogType eventType = null; if (now.compareTo(expirationDate) > 0) { eventType = alertExpirationEventType; } else if (now.compareTo(certAlertTime) > 0) { eventType = alertAboutToExpireEventType; } else if (now.compareTo(certWarnTime) > 0) { eventType = warnAboutToExpireEventType; } if (eventType != null) { AuditLogableBase event = Injector.injectMembers(new AuditLogableBase()); event.addCustomValue("ExpirationDate", new SimpleDateFormat("yyyy-MM-dd").format(expirationDate)); <START> if (host != null) { <END> event.setVds(host); } auditLogDirector.log(event, eventType); return false; } return true; }</code><technical_language>Please rebase top of latest master, this is related changes in <LINK_0> if (host != null) { event.setVdsName(host.getName()); }</technical_language>

Target:
private boolean checkCertificate(X509Certificate cert, AuditLogType alertExpirationEventType, AuditLogType alertAboutToExpireEventType, AuditLogType warnAboutToExpireEventType, VDS host) { Date expirationDate = cert.getNotAfter(); Date certWarnTime = getExpirationDate(expirationDate, ConfigValues.CertExpirationWarnPeriodInDays); Date certAlertTime = getExpirationDate(expirationDate, ConfigValues.CertExpirationAlertPeriodInDays); Date now = new Date(); AuditLogType eventType = null; if (now.compareTo(expirationDate) > 0) { eventType = alertExpirationEventType; } else if (now.compareTo(certAlertTime) > 0) { eventType = alertAboutToExpireEventType; } else if (now.compareTo(certWarnTime) > 0) { eventType = warnAboutToExpireEventType; } if (eventType != null) { AuditLogableBase event = new AuditLogableBase(); event.addCustomValue("ExpirationDate", new SimpleDateFormat("yyyy-MM-dd").format(expirationDate)); if (host != null) { event.setVds(host); } auditLogDirector.log(event, eventType); return false; } return true; }