auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void validateUser(ServerConfiguration conf) throws AccessControlException { <START> if (conf.containsKey("permittedStartupUsers")) { <END> String currentUser = System.getProperty("user.name"); String[] propertyValue = conf.getPermittedStartupUsers(); for (String s : propertyValue) { if (s.equals(currentUser)) { return; } } String errorMsg = "System cannot start because current user isn't in permittedStartupUsers." + " Current user: " + currentUser + " permittedStartupUsers: " + Arrays.toString(propertyValue); LOG.error(errorMsg); throw new AccessControlException(errorMsg); } }</code><technical_language>constant defined in AbstractConfiguration</technical_language>

Target:
private void validateUser(ServerConfiguration conf) throws AccessControlException { if (conf.containsKey(PERMITTED_STARTUP_USERS)) { String currentUser = System.getProperty("user.name"); String[] propertyValue = conf.getPermittedStartupUsers(); for (String s : propertyValue) { if (s.equals(currentUser)) { return; } } String errorMsg = "System cannot start because current user isn't in permittedStartupUsers." + " Current user: " + currentUser + " permittedStartupUsers: " + Arrays.toString(propertyValue); LOG.error(errorMsg); throw new AccessControlException(errorMsg); } }
Source:
<code>public <T> void deleteAll(Class<T> type) { ClassInfo classInfo = session.metaData().classInfo(type.getName()); if (classInfo != null) { <START> String entityLabel = session.entityType(classInfo.name()); <END> if (entityLabel == null) { LOG.warn("Unable to find database label for entity " + type.getName() + " : no results will be returned. Make sure the class is registered, " + "and not abstract without @NodeEntity annotation"); } Statement request = getDeleteStatementsBasedOnType(type).delete(entityLabel); RowModelRequest query = new DefaultRowModelRequest(request.getStatement(), request.getParameters()); session.notifyListeners(new PersistenceEvent(type, Event.TYPE.PRE_DELETE)); session.doInTransaction(() -> { try (Response<RowModel> response = session.requestHandler().execute(query)) { session.context().removeType(type); if (session.eventsEnabled()) { session.notifyListeners(new PersistenceEvent(type, Event.TYPE.POST_DELETE)); } } }, Transaction.Type.READ_WRITE); } else { session.warn(type.getName() + " is not a persistable class"); } }</code><technical_language>neo4jName()here? I getName() before, is IMHO wrong</technical_language>

Target:
public <T> void deleteAll(Class<T> type) { ClassInfo classInfo = session.metaData().classInfo(type.getName()); if (classInfo != null) { String entityLabel = classInfo.neo4jName(); if (entityLabel == null) { LOG.warn("Unable to find database label for entity " + type.getName() + " : no results will be returned. Make sure the class is registered, " + "and not abstract without @NodeEntity annotation"); } Statement request = getDeleteStatementsBasedOnType(type).delete(entityLabel); RowModelRequest query = new DefaultRowModelRequest(request.getStatement(), request.getParameters()); session.notifyListeners(new PersistenceEvent(type, Event.TYPE.PRE_DELETE)); session.doInTransaction(() -> { try (Response<RowModel> response = session.requestHandler().execute(query)) { session.context().removeType(type); if (session.eventsEnabled()) { session.notifyListeners(new PersistenceEvent(type, Event.TYPE.POST_DELETE)); } } }, Transaction.Type.READ_WRITE); } else { session.warn(type.getName() + " is not a persistable class"); } }
Source:
<code>public static AffinityGroup map(org.ovirt.engine.core.common.scheduling.AffinityGroup entity, AffinityGroup template) { AffinityGroup model = template != null ? template : new AffinityGroup(); model.setId(entity.getId().toString()); model.setName(entity.getName()); model.setDescription(entity.getDescription()); model.setPositive(entity.isVmAffinityEnabled() ? entity.getVmPolarityBooleanObject() : null); model.setEnforcing(entity.isVmEnforcing()); AffinityRule hostsRule = new AffinityRule(); hostsRule.setEnabled(true); hostsRule.setEnforcing(entity.isVdsEnforcing()); hostsRule.setPositive(entity.isVdsPositive()); <START> model.setHostsRule(hostsRule); <END> AffinityRule vmsRule = new AffinityRule(); vmsRule.setEnabled(entity.isVmAffinityEnabled()); vmsRule.setEnforcing(entity.isVmEnforcing()); vmsRule.setPositive(entity.isVmPositive()); model.setVmsRule(vmsRule); Cluster cluster = new Cluster(); cluster.setId(entity.getClusterId().toString()); model.setCluster(cluster); return model; }</code><technical_language>'hostsRole' set in passed 'template' other parts of code, replacing completely. happen in this case, change in future. Instead of this consider checking first: AffinityRule hostsRule = model.getHostsRule(); if (hostsRule == null) { hostsRule = new AffinityRule(); model.setHostsRule(hostsRule); } ..</technical_language>

Target:
public static AffinityGroup map(org.ovirt.engine.core.common.scheduling.AffinityGroup entity, AffinityGroup template) { AffinityGroup model = template != null ? template : new AffinityGroup(); model.setId(entity.getId().toString()); model.setName(entity.getName()); model.setDescription(entity.getDescription()); model.setPositive(entity.isVmAffinityEnabled() ? entity.getVmPolarityBooleanObject() : null); model.setEnforcing(entity.isVmEnforcing()); AffinityRule hostsRule = model.getHostsRule(); if (hostsRule == null) { hostsRule = new AffinityRule(); model.setHostsRule(hostsRule); } hostsRule.setEnabled(true); hostsRule.setEnforcing(entity.isVdsEnforcing()); hostsRule.setPositive(entity.isVdsPositive()); AffinityRule vmsRule = model.getVmsRule(); if (vmsRule == null) { vmsRule = new AffinityRule(); model.setVmsRule(vmsRule); } vmsRule.setEnabled(entity.isVmAffinityEnabled()); vmsRule.setEnforcing(entity.isVmEnforcing()); vmsRule.setPositive(entity.isVmPositive()); Cluster cluster = new Cluster(); cluster.setId(entity.getClusterId().toString()); model.setCluster(cluster); return model; }
Source:
<code>private void readWhilePossible(ChannelStateByteBuffer buffer) throws IOException { while (haveMoreData() && buffer.isWritable()) { <START> if (pos < 0 || rem <= 0) { <END> advanceOffset(); } int bytesRead = serializer.readData(stream, buffer, rem); rem -= bytesRead; pos = addExact(pos, bytesRead); } }</code><technical_language>I guess get ride of pos field judge rem <= 0 advance offset. If avoid return tuple2 in serializer.readLength(stream)</technical_language>

Target:
private void readWhilePossible(ChannelStateByteBuffer buffer) throws IOException { while (haveMoreData() && buffer.isWritable()) { if (remainingBytes <= 0) { advanceOffset(); } int bytesRead = serializer.readData(stream, buffer, remainingBytes); remainingBytes -= bytesRead; } }
Source:
<code>public void stopServerListRefreshing() { <START> serverListUpdater.stop(); <END> }</code><technical_language>null check serverListUpdater</technical_language>

Target:
public void stopServerListRefreshing() { if (serverListUpdater != null) { serverListUpdater.stop(); } }
Source:
<code>private void setDebugPort(Server server) { if (StringUtils.isBlank(debug) || wizard.checkYes(debug)) { debug = wizard.promptForValueIfMissingWithDefault( ENABLE_DEBUGGING_DEFAULT_MESSAGE, server.getDebugPort(), "port number", "no debugging"); } <START> if(StringUtils.isNumeric(debug)){ <END> server.setDebugPort(debug); } }</code><technical_language>I fact numeric input for debug port is silently ignored, I guess do it, e.g. show information non-numeric input is invalid ask for port again</technical_language>

Target:
private void setDebugPort(Server server) { if (StringUtils.isBlank(debug) || wizard.checkYes(debug)) { while (!"no debugging".equals(debug) && !StringUtils.isNumeric(debug)) { debug = wizard.promptForValueIfMissingWithDefault( ENABLE_DEBUGGING_DEFAULT_MESSAGE, server.getDebugPort(), "port number", "no debugging"); if(!StringUtils.isNumeric(debug)){ wizard.showMessage("\nPort number must be numeric."); } else if(!"no debugging".equals(debug)){ server.setDebugPort(debug); } } } }
Source:
<code>private ContainerMapping createPackageMapping(Layer layer, ToolSection toolSection) { <START> ContainerMapping packageMapping = DescriptionFactory.eINSTANCE.createContainerMapping(); <END> packageMapping.setLabel("packageMapping"); packageMapping.setName(BASE_ID + ".package.container"); packageMapping.setStyle(StyleFactory.eINSTANCE.createFlatContainerStyleDescription()); layer.getContainerMappings().add(packageMapping); packageMapping.setSemanticCandidatesExpression("feature:eContents"); ContainerCreationDescription containerPackageMapping = ToolFactory.eINSTANCE.createContainerCreationDescription(); containerPackageMapping.setName(BASE_ID + ".package.container.creation"); containerPackageMapping.setLabel("Package"); toolSection.getOwnedTools().add(containerPackageMapping); containerPackageMapping.getContainerMappings().add(packageMapping); return packageMapping; }</code><technical_language>label consistent : mapping not, mappings. Another remark: label for presentation user in editr, package mapping Package Mapping packageMapping</technical_language>

Target:
private ContainerMapping createPackageMapping(Layer layer, ToolSection toolSection) { ContainerMapping packageMapping = DescriptionFactory.eINSTANCE.createContainerMapping(); packageMapping.setLabel("Package Mapping"); packageMapping.setName(baseId + ".package.container"); packageMapping.setStyle(StyleFactory.eINSTANCE.createFlatContainerStyleDescription()); layer.getContainerMappings().add(packageMapping); packageMapping.setSemanticCandidatesExpression("feature:eContents"); ContainerCreationDescription containerPackageMapping = ToolFactory.eINSTANCE.createContainerCreationDescription(); containerPackageMapping.setName(baseId + ".package.container.creation"); containerPackageMapping.setLabel("Package"); toolSection.getOwnedTools().add(containerPackageMapping); containerPackageMapping.getContainerMappings().add(packageMapping); return packageMapping; }
Source:
<code>private void pollStoreAvailability() { storesMutex.writeLock().lock(); try { for (StoreStatus status : storeStatuses.values()) { if (!status.availabilityChanged()) continue; cacheNotifier.notifyPersistenceAvailabilityChanged(status.availability); if (!status.availability) { unavailableException = new StoreUnavailableException(String.format("Store %s is unavailable", status.store)); managerAvailable = false; <START> return; <END> } if (!managerAvailable) { managerAvailable = true; unavailableException = null; } } } finally { storesMutex.writeLock().unlock(); } }</code><technical_language>check of stores availability, fails</technical_language>

Target:
private void pollStoreAvailability() { storesMutex.writeLock().lock(); try { boolean availabilityChanged = false; boolean failureDetected = false; for (StoreStatus status : storeStatuses.values()) { if (status.availabilityChanged()) availabilityChanged = true; if (availabilityChanged && !status.availability && !failureDetected) { failureDetected = true; unavailableException = new StoreUnavailableException(String.format("Store %s is unavailable", status.store)); cacheNotifier.notifyPersistenceAvailabilityChanged(false); } } if (!failureDetected && availabilityChanged) { unavailableException = null; cacheNotifier.notifyPersistenceAvailabilityChanged(true); } } finally { storesMutex.writeLock().unlock(); } }
Source:
<code>protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws NotEnoughArgumentsException { if (args.length < 2) { throw new NotEnoughArgumentsException(); } final String address = EssentialsXMPP.getInstance().getAddress(args[0]); if (address == null) { sender.sendMessage("§cThere are no players matching that name."); return; } final String message = getFinalArg(args, 1); final String senderName = sender.isPlayer() ? ess.getUser(sender.getPlayer()).getDisplayName() : Console.NAME; sender.sendMessage("[" + senderName + ">" + address + "] " + message); if (!EssentialsXMPP.getInstance().sendMessage(address, "[" + senderName + "] " + message)) { <START> sender.sendMessage("§cError sending message."); <END> } }</code><technical_language>ChatColor</technical_language>

Target:
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws NotEnoughArgumentsException { if (args.length < 2) { throw new NotEnoughArgumentsException(); } final String address = EssentialsXMPP.getInstance().getAddress(args[0]); if (address == null) { sender.sendMessage(ChatColor.RED + "There are no players matching that name."); return; } final String message = getFinalArg(args, 1); final String senderName = sender.isPlayer() ? ess.getUser(sender.getPlayer()).getDisplayName() : Console.NAME; sender.sendMessage("[" + senderName + ">" + address + "] " + message); if (!EssentialsXMPP.getInstance().sendMessage(address, "[" + senderName + "] " + message)) { sender.sendMessage(ChatColor.RED + "Error sending message."); } }
Source:
<code>public StrictDtlsCorrelationContextMatcher() { <START> super("relaxed correlation", KEYS); <END> }</code><technical_language>bad copy/paste :)</technical_language>

Target:
public StrictDtlsCorrelationContextMatcher() { super("strict correlation", KEYS); }
Source:
<code>protected void clipForOverlappingReads(final SAMRecord read1, final SAMRecord read2) { if (!(read1.getReadUnmappedFlag() || read2.getReadUnmappedFlag())) { <START> <END> if (read1.getReadNegativeStrandFlag() != read2.getReadNegativeStrandFlag()) { final SAMRecord pos = (read1.getReadNegativeStrandFlag()) ? read2 : read1; final SAMRecord neg = (read1.getReadNegativeStrandFlag()) ? read1 : read2; if (pos.getAlignmentStart() < neg.getAlignmentEnd()) { final int posDiff = pos.getAlignmentEnd() - neg.getAlignmentEnd(); final int negDiff = pos.getAlignmentStart() - neg.getAlignmentStart(); if (posDiff > 0) { CigarUtil.softClip3PrimeEndOfRead(pos, Math.min(pos.getReadLength(), pos.getReadLength() - posDiff + 1)); } if (negDiff > 0) { CigarUtil.softClip3PrimeEndOfRead(neg, Math.min(neg.getReadLength(), neg.getReadLength() - negDiff + 1)); } } } else { } } }</code><technical_language>in this code removed calculateNm, calculateMd reversed</technical_language>

Target:
protected void clipForOverlappingReads(final SAMRecord read1, final SAMRecord read2) { if (!(read1.getReadUnmappedFlag() || read2.getReadUnmappedFlag())) { if (read1.getReadNegativeStrandFlag() != read2.getReadNegativeStrandFlag()) { final SAMRecord pos = (read1.getReadNegativeStrandFlag()) ? read2 : read1; final SAMRecord neg = (read1.getReadNegativeStrandFlag()) ? read1 : read2; if (pos.getAlignmentStart() < neg.getAlignmentEnd()) { final int posDiff = pos.getAlignmentEnd() - neg.getAlignmentEnd(); final int negDiff = pos.getAlignmentStart() - neg.getAlignmentStart(); if (posDiff > 0) { CigarUtil.softClip3PrimeEndOfRead(pos, Math.min(pos.getReadLength(), pos.getReadLength() - posDiff + 1)); removeNmMdAndUqTags(pos); } if (negDiff > 0) { CigarUtil.softClip3PrimeEndOfRead(neg, Math.min(neg.getReadLength(), neg.getReadLength() - negDiff + 1)); removeNmMdAndUqTags(neg); } } } else { } } }
Source:
<code>@Test public void writerBooleanValue() throws Exception { JsonWriter writer = factory.newWriter(); writer.beginObject(); writer.promoteValueToName(); try { writer.value(true); fail(); } catch (IllegalStateException e) { <START> assertThat(e).hasMessage("Boolean cannot be used as a map key in JSON."); <END> } writer.value("true"); assertThat(writer.getPath()).isEqualTo("$.true"); writer.value(1); writer.endObject(); assertThat(writer.getPath()).isEqualTo("$"); assertThat(factory.json()).isEqualTo("{\"true\":1}"); }</code><technical_language>This catch block e instead of expected, prefer latter, expected a good naming convention. I a</technical_language>

Target:
@Test public void writerBooleanValue() throws Exception { JsonWriter writer = factory.newWriter(); writer.beginObject(); writer.promoteValueToName(); try { writer.value(true); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Boolean cannot be used as a map key in JSON at path $."); } writer.value("true"); assertThat(writer.getPath()).isEqualTo("$.true"); writer.value(1); writer.endObject(); assertThat(writer.getPath()).isEqualTo("$"); assertThat(factory.json()).isEqualTo("{\"true\":1}"); }
Source:
<code>public Boolean call() throws Exception { if (!settings.userDataExists()) { throw new TmcCoreException( "Unable to download model solution: missing username/password"); } String courseName = getCourseName(); Path target = exerciseDownloader.createCourseFolder( <START> Paths.get(settings.getTmcMainDirectory()), courseName); <END> return exerciseDownloader.downloadModelSolution(exercise, target); }</code><technical_language>this result in NPE if settings.getTmcMainDirectory() returns null? Checking for null time settings.getTmcMainDirectory() is called cumbersome. Do a nice of declaring interface return a non-null this check in place only</technical_language>

Target:
public Boolean call() throws Exception { if (!settings.userDataExists()) { throw new TmcCoreException( "Unable to download model solution: missing username/password"); } String courseName = getCourseName(); Path target = exerciseDownloader.createCourseFolder( settings.getTmcMainDirectory(), courseName); return exerciseDownloader.downloadModelSolution(exercise, target); }
Source:
<code>public void channelActive(ChannelHandlerContext ctx) throws Exception { MqttFixedHeader connectFixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttConnectVariableHeader connectVariableHeader = new MqttConnectVariableHeader(PROTOCOL_NAME_MQTT_3_1_1, PROTOCOL_VERSION_MQTT_3_1_1, true, true, false, 0, false, false, 20); MqttConnectPayload connectPayload = new MqttConnectPayload(clientId, null, null, userName, password); MqttConnectMessage connectMessage = new MqttConnectMessage(connectFixedHeader, connectVariableHeader, connectPayload); <START> ctx.channel().writeAndFlush(connectMessage); <END> System.out.println("Sent CONNECT"); }</code><technical_language>ctx.writeAndFlush(...);</technical_language>

Target:
public void channelActive(ChannelHandlerContext ctx) throws Exception { MqttFixedHeader connectFixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_MOST_ONCE, false, 0); MqttConnectVariableHeader connectVariableHeader = new MqttConnectVariableHeader(PROTOCOL_NAME_MQTT_3_1_1, PROTOCOL_VERSION_MQTT_3_1_1, true, true, false, 0, false, false, 20); MqttConnectPayload connectPayload = new MqttConnectPayload(clientId, null, null, userName, password); MqttConnectMessage connectMessage = new MqttConnectMessage(connectFixedHeader, connectVariableHeader, connectPayload); ctx.writeAndFlush(connectMessage); System.out.println("Sent CONNECT"); }
Source:
<code>public ActivityMetadataBuilder getBuilder(final ActivityDTO dto) { ActivityMetadataBuilder builder = null; switch (dto.getConcept()) { case CERTIFIED_PRODUCT: builder = listingBuilder; break; case DEVELOPER: builder = developerBuilder; break; case PRODUCT: builder = productBuilder; break; case VERSION: builder = versionBuilder; break; case CERTIFICATION_BODY: builder = acbBuilder; break; case TESTING_LAB: builder = atlBuilder; break; case USER: builder = userMaintenanceActivityMetadataBuilder; break; case ANNOUNCEMENT: builder = announcementActivityMetadataBuilder; break; case PENDING_CERTIFIED_PRODUCT: builder = pendingListingActivityMetadataBuilder; break; case CORRECTIVE_ACTION_PLAN: builder = correctActionPlanActivityMetadataBuilder; break; case PENDING_SURVEILLANCE: <START> builder = pendingListingActivityMetadataBuilder; <END> break; default: break; } return builder; }</code><technical_language>pendingSurveillanceActivityMetadataBuilder</technical_language>

Target:
public ActivityMetadataBuilder getBuilder(final ActivityDTO dto) { ActivityMetadataBuilder builder = null; switch (dto.getConcept()) { case CERTIFIED_PRODUCT: builder = listingBuilder; break; case DEVELOPER: builder = developerBuilder; break; case PRODUCT: builder = productBuilder; break; case VERSION: builder = versionBuilder; break; case CERTIFICATION_BODY: builder = acbBuilder; break; case TESTING_LAB: builder = atlBuilder; break; case USER: builder = userMaintenanceActivityMetadataBuilder; break; case ANNOUNCEMENT: builder = announcementActivityMetadataBuilder; break; case PENDING_CERTIFIED_PRODUCT: builder = pendingListingActivityMetadataBuilder; break; case CORRECTIVE_ACTION_PLAN: builder = correctActionPlanActivityMetadataBuilder; break; case PENDING_SURVEILLANCE: builder = pendingSurveillanceActivityMetadataBuilder; break; default: break; } return builder; }
Source:
<code>public void addDeviceToUser_addFirstDevice_userHasOneDevice() { String deviceName = "Testing"; OperatingSystem operatingSystem = OperatingSystem.ANDROID; LocalDateTime startTime = TimeUtil.utcNow(); UserDeviceDto deviceDto = new UserDeviceDto(deviceName, operatingSystem, "Unknown"); service.addDeviceToUser(richard, deviceDto); verify(userDeviceRepository, times(1)).save(any(UserDevice.class)); assertThat(deviceAnonymizedRepository.count(), equalTo(1L)); Set<UserDevice> devices = richard.getDevices(); assertThat(devices.size(), equalTo(1)); UserDevice device = devices.iterator().next(); assertDevice(device, startTime, deviceName, operatingSystem, 0); <START> assertVpnAccountCreated(device); <END> }</code><technical_language>move new asserts separate tests, tests test stay easy read</technical_language>

Target:
public void addDeviceToUser_addFirstDevice_userHasOneDevice() { String deviceName = "Testing"; OperatingSystem operatingSystem = OperatingSystem.ANDROID; LocalDateTime startTime = TimeUtil.utcNow(); UserDeviceDto deviceDto = new UserDeviceDto(deviceName, operatingSystem, SUPPORTED_APP_VERSION); service.addDeviceToUser(richard, deviceDto); verify(userDeviceRepository, times(1)).save(any(UserDevice.class)); assertThat(deviceAnonymizedRepository.count(), equalTo(1L)); Set<UserDevice> devices = richard.getDevices(); assertThat(devices.size(), equalTo(1)); UserDevice device = devices.iterator().next(); assertDevice(device, startTime, deviceName, operatingSystem, 0); assertVpnAccountCreated(device); }
Source:
<code>public void setValueArrayFromString() { Element convert = ElementFactory.make("audioconvert", null); convert.setAsString("mix-matrix", "<<(float)0.25, (float)0.45>,<(float)0.65, (float)0.85>>"); String matrix = convert.getAsString("mix-matrix"); assertTrue(matrix.contains("0.2")); assertTrue(matrix.contains("0.4")); assertTrue(matrix.contains("0.6")); assertTrue(matrix.contains("0.8")); <START> convert.dispose(); <END> }</code><technical_language>other Elements creared in @Before disposed explicitly. adjust a similar pattern</technical_language>

Target:
public void setValueArrayFromString() { if (!Gst.testVersion(1, 14)) { return; } Element convert = ElementFactory.make("audioconvert", null); convert.setAsString("mix-matrix", "<<(float)0.25, (float)0.45>,<(float)0.65, (float)0.85>>"); String matrix = convert.getAsString("mix-matrix"); assertTrue(matrix.contains("0.2")); assertTrue(matrix.contains("0.4")); assertTrue(matrix.contains("0.6")); assertTrue(matrix.contains("0.8")); convert.dispose(); }
Source:
<code>public void testChunkFillerSleep() throws Exception { router = getNonBlockingRouter(); Thread chunkFillerThread = TestUtils.getThreadByThisName("ChunkFillerThread"); Assert.assertTrue("ChunkFillerThread should have gone to WAITING state as there are no active operations", waitForThreadState(chunkFillerThread, Thread.State.WAITING)); int blobSize = chunkSize * 2; RequestAndResult requestAndResult = new RequestAndResult(blobSize); requestAndResultsList.add(requestAndResult); MockReadableStreamChannel putChannel = new MockReadableStreamChannel(blobSize); FutureResult<String> future = (FutureResult<String>) router .putBlob(requestAndResult.putBlobProperties, requestAndResult.putUserMetadata, putChannel, null); ByteBuffer src = ByteBuffer.wrap(requestAndResult.putContent); int writeSize = blobSize / 2; ByteBuffer buf = ByteBuffer.allocate(writeSize); src.get(buf.array()); putChannel.write(buf); Assert.assertTrue( "ChunkFillerThread should have gone to RUNNABLE state as there is an active operation that is not yet complete", waitForThreadState(chunkFillerThread, Thread.State.RUNNABLE)); buf.rewind(); src.get(buf.array()); putChannel.write(buf); Assert .assertTrue("ChunkFillerThread should have gone to WAITING state as the only active operation is now complete", waitForThreadState(chunkFillerThread, Thread.State.WAITING)); <START> future.await(); <END> requestAndResult.result = future; assertSuccess(); assertCloseCleanup(); }</code><technical_language>timed wait</technical_language>

Target:
public void testChunkFillerSleep() throws Exception { router = getNonBlockingRouter(); Thread chunkFillerThread = TestUtils.getThreadByThisName("ChunkFillerThread"); Assert.assertTrue("ChunkFillerThread should have gone to WAITING state as there are no active operations", waitForThreadState(chunkFillerThread, Thread.State.WAITING)); int blobSize = chunkSize * 2; RequestAndResult requestAndResult = new RequestAndResult(blobSize); requestAndResultsList.add(requestAndResult); MockReadableStreamChannel putChannel = new MockReadableStreamChannel(blobSize); FutureResult<String> future = (FutureResult<String>) router .putBlob(requestAndResult.putBlobProperties, requestAndResult.putUserMetadata, putChannel, null); ByteBuffer src = ByteBuffer.wrap(requestAndResult.putContent); int writeSize = blobSize / 2; ByteBuffer buf = ByteBuffer.allocate(writeSize); src.get(buf.array()); putChannel.write(buf); Assert.assertTrue( "ChunkFillerThread should have gone to RUNNABLE state as there is an active operation that is not yet complete", waitForThreadState(chunkFillerThread, Thread.State.RUNNABLE)); buf.rewind(); src.get(buf.array()); putChannel.write(buf); Assert .assertTrue("ChunkFillerThread should have gone to WAITING state as the only active operation is now complete", waitForThreadState(chunkFillerThread, Thread.State.WAITING)); Assert .assertTrue("Operation should not take too long to complete", future.await(MAX_WAIT_MS, TimeUnit.MILLISECONDS)); requestAndResult.result = future; assertSuccess(); assertCloseCleanup(); }
Source:
<code>public static Slice castFromIpAddressToVarchar(@SqlType(StandardTypes.IPADDRESS) Slice slice) { <START> SqlIpAddress address = new SqlIpAddress(slice.getBytes()); <END> return utf8Slice(address.toString()); }</code><technical_language>SqlXx here. SqlVarbinary SqlTimestamp, this for getObjectValue tests. want in other places</technical_language>

Target:
public static Slice castFromIpAddressToVarchar(@SqlType(StandardTypes.IPADDRESS) Slice slice) { try { return utf8Slice(InetAddresses.toAddrString(InetAddress.getByAddress(slice.getBytes()))); } catch (UnknownHostException e) { throw new PrestoException(INVALID_CAST_ARGUMENT, "Invalid IP address binary length: " + slice.length(), e); } }
Source:
<code>private void createTimeEventContextMenu() { fEventMenuManager.setRemoveAllWhenShown(true); TimeGraphControl timeGraphControl = fTimeGraphViewer.getTimeGraphControl(); final Menu timeEventMenu = fEventMenuManager.createContextMenu(timeGraphControl); timeGraphControl.addTimeEventMenuListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent event) { Menu menu = timeEventMenu; if (!isOnFlameGraphEvent(event, timeGraphControl)) { timeGraphControl.setMenu(null); } timeGraphControl.setMenu(menu); } }); timeGraphControl.addTimeGraphEntryMenuListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent event) { <START> if (!isOnFlameGraphEvent(event, timeGraphControl)) { <END> timeGraphControl.setMenu(null); } } }); fEventMenuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { fillTimeEventContextMenu(fEventMenuManager); fEventMenuManager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); } }); getSite().registerContextMenu(fEventMenuManager, fTimeGraphViewer.getSelectionProvider()); }</code><technical_language>This condition is necessary, in this method call event.data a TimeGraphEntry, isOnFlameGraphEvent is false</technical_language>

Target:
private void createTimeEventContextMenu() { fEventMenuManager.setRemoveAllWhenShown(true); TimeGraphControl timeGraphControl = fTimeGraphViewer.getTimeGraphControl(); final Menu timeEventMenu = fEventMenuManager.createContextMenu(timeGraphControl); timeGraphControl.addTimeEventMenuListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent event) { Menu menu = timeEventMenu; if (isOnNamespace(event, timeGraphControl) || !(event.data instanceof FlamegraphEvent)) { timeGraphControl.setMenu(null); event.doit = false; return; } timeGraphControl.setMenu(menu); } }); timeGraphControl.addTimeGraphEntryMenuListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent event) { if (isOnNamespace(event, timeGraphControl)) { timeGraphControl.setMenu(null); event.doit = false; } } }); fEventMenuManager.addMenuListener(new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { fillTimeEventContextMenu(fEventMenuManager); fEventMenuManager.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS)); } }); getSite().registerContextMenu(fEventMenuManager, fTimeGraphViewer.getSelectionProvider()); }
Source:
<code>private void setVmTemplateIdParameter() { Map<Boolean, VmTemplate> templateMap = getDbFacade().getVmTemplateDAO().getAllForImage(((DiskImage) disk).getImageId()); <START> if (!templateMap.values().isEmpty()) { <END> setVmTemplateId(templateMap.values().iterator().next().getId()); } }</code><technical_language>common of writing is !templateMap().isEmpty()</technical_language>

Target:
private void setVmTemplateIdParameter() { Map<Boolean, VmTemplate> templateMap = getDbFacade().getVmTemplateDAO().getAllForImage(((DiskImage) disk).getImageId()); if (!templateMap.isEmpty()) { setVmTemplateId(templateMap.values().iterator().next().getId()); } }
Source:
<code>public <S> SparqlTraversal<S,?> sparql(final String query) { final SparqlTraversalSource clone = this.clone(); clone.getStrategies().addStrategies(SparqlStrategy.instance()); clone.bytecode.addStep(GraphTraversal.Symbols.inject); <START> clone.bytecode.addStep(GraphTraversal.Symbols.constant, query); <END> final SparqlTraversal.Admin<S, S> traversal = new DefaultSparqlTraversal<>(clone); traversal.addStep(new InjectStep<S>(traversal)); return traversal.addStep(new ConstantStep<S,String>(traversal, query)); }</code><technical_language>inject(query) sufficient, no</technical_language>

Target:
public <S> SparqlTraversal<S,?> sparql(final String query) { final SparqlTraversalSource clone = this.clone(); clone.getStrategies().addStrategies(SparqlStrategy.instance()); clone.bytecode.addStep(GraphTraversal.Symbols.inject, query); final SparqlTraversal.Admin<S, S> traversal = new DefaultSparqlTraversal<>(clone); return traversal.addStep(new InjectStep<>(traversal, query)); }
Source:
<code>public void testGameRefresh() throws URISyntaxException, IOException { MockApplication.initStatics(); MockPlatform mockPlatform = new MockPlatform(); MockFiles mf = new MockFiles(); Controller mockController = new Controller(mockPlatform, mf, new Group()); <START> File source = new File( <END> "../../engine/desktop/src/test/resources/techdemo") .getCanonicalFile(); mockController.getModel().addLoadListener( new Model.ModelListener<LoadEvent>() { @Override public void modelChanged(LoadEvent event) { Model m = event.getModel(); Index.SearchResult sr; sr = m.search("_g_lang"); assertEquals("single match", 1, sr.getMatches().size()); assertTrue(sr.getMatches().get(0).getObject() instanceof VariableDef); sr = m.search("zebras"); assertEquals("no zebras here", 0, sr.getMatches() .size()); sr = m.search("_g_"); assertEquals("single match", 1, sr.getMatches().size()); assertTrue(sr.getMatches().get(0).getObject() instanceof VariableDef); } }); mockController.action(OpenGame.class, source.getPath()); mockController.getEditorGameAssets().finishLoading(); }</code><technical_language>I a PR ClassLoader instead of relative path (I tested it). Also, this test is kind of limited, I guess a limited model. in mind updating this schema is complete</technical_language>

Target:
public void testGameRefresh() throws URISyntaxException, IOException { MockApplication.initStatics(); MockPlatform mockPlatform = new MockPlatform(); MockFiles mf = new MockFiles(); Controller mockController = new Controller(mockPlatform, mf, new Group()); File source = new File( "../../engine/desktop/src/test/resources/techdemo") .getCanonicalFile(); mockController.getModel().addLoadListener( new Model.ModelListener<LoadEvent>() { @Override public void modelChanged(LoadEvent event) { Model m = event.getModel(); Index.SearchResult sr; sr = m.search("lang"); assertEquals("only one language per game", 1, sr .getMatches().size()); assertTrue(sr.getMatches().get(0).getObject() instanceof VariableDef); sr = m.search("zebras"); assertEquals("no zebras here", 0, sr.getMatches() .size()); sr = m.search("logo"); assertEquals("lots of logos", 4, sr.getMatches().size()); sr = m.search("logo2"); assertEquals("single match", 1, sr.getMatches().size()); assertTrue(sr.getMatches().get(0).getObject() instanceof Image); } }); mockController.action(OpenGame.class, source.getPath()); mockController.getEditorGameAssets().finishLoading(); }
Source:
<code>public void clear() throws IOException { for (final String label : this.labelSet()) { <START> this.remove(label); <END> } }</code><technical_language>@cvrebert This do - removes elements set labelSet() returns. iterator.remove() (or storage.apply statement above, modifies mock Github)</technical_language>

Target:
public void clear() throws IOException { for (final String label : this.labels()) { this.remove(label); } }
Source:
<code>public void initialize(InputSplit inputSplit, TaskAttemptContext context) throws IOException, InterruptedException { if (context instanceof TaskInputOutputContext<?, ?, ?, ?>) { BenchmarkCounter.initCounterFromContext((TaskInputOutputContext<?, ?, ?, ?>) context); } else { LOG.error("Can not initialize counter due to context is not a instance of TaskInputOutputContext, but is " + context.getClass().getCanonicalName()); } ParquetInputSplit parquetSplit; if (inputSplit instanceof ParquetInputSplit) { parquetSplit = (ParquetInputSplit) inputSplit; } else if (inputSplit instanceof FileSplit) { parquetSplit = ParquetInputSplit.from((FileSplit) inputSplit); } else { throw new IllegalArgumentException( "Invalid split (not a FileSplit or ParquetInputSplit): " + inputSplit); } <START> initializeInternalReader(parquetSplit, ContextUtil.getConfiguration(context)); <END> }</code><technical_language>ParquetInputSplit extends FileSplit depend FileSplit. other end receive returned getSplits returns ParquetInputSplits in implementation. In cases logic simplified</technical_language>

Target:
public void initialize(InputSplit inputSplit, TaskAttemptContext context) throws IOException, InterruptedException { if (context instanceof TaskInputOutputContext<?, ?, ?, ?>) { BenchmarkCounter.initCounterFromContext((TaskInputOutputContext<?, ?, ?, ?>) context); } else { LOG.error("Can not initialize counter due to context is not a instance of TaskInputOutputContext, but is " + context.getClass().getCanonicalName()); } initializeInternalReader(toParquetSplit(inputSplit), ContextUtil.getConfiguration(context)); }
Source:
<code>public void testPutHeaders() { PutOptions options = new PutOptions().headers(ImmutableMultimap.of(OBJECT_DELETE_AT, "123456789")); <START> assertEquals(ImmutableList.of("123456789"), options.buildRequestHeaders().get(OBJECT_DELETE_AT)); <END> }</code><technical_language>above, assertions wrong around</technical_language>

Target:
public void testPutHeaders() { PutOptions options = new PutOptions().headers(ImmutableMultimap.of(OBJECT_DELETE_AT, "123456789")); assertEquals(options.buildRequestHeaders().get(OBJECT_DELETE_AT), ImmutableList.of("123456789")); }
Source:
<code>public void run() { Location dropLocation = this.location.clone(); ItemStack item = this.itemstack.clone(); <START> if (Main.getInstance().getBooleanConfig("spawnRessourcesInChest", true)) { <END> BlockState blockState = dropLocation.getBlock().getState(); if (blockState instanceof Chest) { Chest chest = (Chest) blockState; if (canContainItem(chest.getInventory(), item)) { chest.getInventory().addItem(item); return; } else { dropLocation.setY(dropLocation.getY() + 1); } } } dropItem(dropLocation); }</code><technical_language>dash notation instead of camel-case in config before. changed</technical_language>

Target:
public void run() { Location dropLocation = this.location.clone(); ItemStack item = this.itemstack.clone(); if (Main.getInstance().getBooleanConfig("spawn-ressources-in-chest", true)) { BlockState blockState = dropLocation.getBlock().getState(); if (blockState instanceof Chest) { Chest chest = (Chest) blockState; if (canContainItem(chest.getInventory(), item)) { chest.getInventory().addItem(item); return; } else { dropLocation.setY(dropLocation.getY() + 1); } } } dropItem(dropLocation); }
Source:
<code>private Change submitThisChange(RevisionResource rsrc, IdentifiedUser caller, boolean force) throws ResourceConflictException, OrmException, IOException { ReviewDb db = dbProvider.get(); ChangeData cd = changeDataFactory.create(db, rsrc.getControl()); List<SubmitRecord> submitRecords = checkSubmitRule(cd, rsrc.getPatchSet(), force); final Timestamp timestamp = TimeUtil.nowTs(); Change change = rsrc.getChange(); ChangeUpdate update = updateFactory.create(rsrc.getControl(), timestamp); update.submit(submitRecords); db.changes().beginTransaction(change.getId()); try { BatchMetaDataUpdate batch = approve(rsrc, update, caller, timestamp); batch.write(update, new CommitBuilder()); change = submitToDatabase(db, change.getId(), timestamp); db.commit(); <START> } catch (ResourceConflictException e) { <END> throw e; } finally { db.rollback(); } indexer.index(db, change); return change; }</code><technical_language>This block effect. this effect is if a catch block for a type a superclass: } catch (SomeSpecificIOException e) { throw e; } catch (IOException e) { // Do "throw e". } here</technical_language>

Target:
private Change submitThisChange(RevisionResource rsrc, IdentifiedUser caller, boolean force) throws ResourceConflictException, OrmException, IOException { ReviewDb db = dbProvider.get(); ChangeData cd = changeDataFactory.create(db, rsrc.getControl()); List<SubmitRecord> submitRecords = checkSubmitRule(cd, rsrc.getPatchSet(), force); final Timestamp timestamp = TimeUtil.nowTs(); Change change = rsrc.getChange(); ChangeUpdate update = updateFactory.create(rsrc.getControl(), timestamp); update.submit(submitRecords); db.changes().beginTransaction(change.getId()); try { BatchMetaDataUpdate batch = approve(rsrc, update, caller, timestamp); batch.write(update, new CommitBuilder()); change = submitToDatabase(db, change.getId(), timestamp); db.commit(); } finally { db.rollback(); } indexer.index(db, change); return change; }
Source:
<code>public void testCiphersuites(boolean hasException, int serverPort) { try { ByteBuffer byteBuffer = ByteBuffer.wrap(testValue.getBytes(Charset.forName("UTF-8"))); HTTPCarbonMessage msg = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "")); msg.setProperty("PORT", serverPort); msg.setProperty("PROTOCOL", scheme); msg.setProperty("HOST", TestUtil.TEST_HOST); msg.setProperty("HTTP_METHOD", "GET"); msg.addMessageBody(byteBuffer); msg.setEndOfMsgAdded(true); CountDownLatch latch = new CountDownLatch(1); SSLConnectorListener listener = new SSLConnectorListener(latch); HttpResponseFuture responseFuture = httpClientConnector.send(msg); responseFuture.setHttpConnectorListener(listener); <START> latch.await(3, TimeUnit.SECONDS); <END> HTTPCarbonMessage response = listener.getHttpResponseMessage(); if (hasException) { assertNotNull(listener.getThrowables()); boolean hasSSLException = false; for (Throwable t : listener.getThrowables()) { if (t.getMessage() != null && t.getMessage().contains("handshake_failure")) { hasSSLException = true; break; } } assertTrue(hasSSLException); } else { assertNotNull(response); String result = new BufferedReader( new InputStreamReader(new HttpMessageDataStreamer(response).getInputStream())).lines() .collect(Collectors.joining("\n")); assertEquals(testValue, result); } } catch (Exception e) { TestUtil.handleException("Exception occurred while running testCiphersuites", e); } }</code><technical_language>5 seconds ? safe side</technical_language>

Target:
public void testCiphersuites(boolean hasException, int serverPort) { try { ByteBuffer byteBuffer = ByteBuffer.wrap(testValue.getBytes(Charset.forName("UTF-8"))); HTTPCarbonMessage msg = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "")); msg.setProperty("PORT", serverPort); msg.setProperty("PROTOCOL", scheme); msg.setProperty("HOST", TestUtil.TEST_HOST); msg.setProperty("HTTP_METHOD", "GET"); msg.addMessageBody(byteBuffer); msg.setEndOfMsgAdded(true); CountDownLatch latch = new CountDownLatch(1); SSLConnectorListener listener = new SSLConnectorListener(latch); HttpResponseFuture responseFuture = httpClientConnector.send(msg); responseFuture.setHttpConnectorListener(listener); latch.await(5, TimeUnit.SECONDS); HTTPCarbonMessage response = listener.getHttpResponseMessage(); if (hasException) { assertNotNull(listener.getThrowables()); boolean hasSSLException = false; for (Throwable throwable : listener.getThrowables()) { if (throwable.getMessage() != null && throwable.getMessage().contains("handshake_failure")) { hasSSLException = true; break; } } assertTrue(hasSSLException); } else { assertNotNull(response); String result = new BufferedReader( new InputStreamReader(new HttpMessageDataStreamer(response).getInputStream())).lines() .collect(Collectors.joining("\n")); assertEquals(testValue, result); } } catch (Exception e) { TestUtil.handleException("Exception occurred while running testCiphersuites", e); } }
Source:
<code>public void destroySession(final HttpServletRequest request) { final String logoutMessage = CommonUtils.safeGetParameter(request, this.logoutParameterName, this.safeParameters); logger.trace("Logout request:\n{}", logoutMessage); final String token = XmlUtils.getTextForElement(logoutMessage, "SessionIndex"); if (CommonUtils.isNotBlank(token)) { final HttpSession session = this.sessionMappingStorage.removeSessionByMappingId(token); if (session != null) { String sessionID = session.getId(); logger.debug("Invalidating session for token [{}]", sessionID, token); try { session.invalidate(); <START> request.logout(); <END> } catch (final ServletException e) { logger.debug("Error performing request.logout."); } catch (final IllegalStateException e) { logger.debug("Error invalidating session.", e); } } } }</code><technical_language>sense put in try/catch? if session.invalidate fails, request.logout tried</technical_language>

Target:
public void destroySession(final HttpServletRequest request) { final String logoutMessage = CommonUtils.safeGetParameter(request, this.logoutParameterName, this.safeParameters); logger.trace("Logout request:\n{}", logoutMessage); final String token = XmlUtils.getTextForElement(logoutMessage, "SessionIndex"); if (CommonUtils.isNotBlank(token)) { final HttpSession session = this.sessionMappingStorage.removeSessionByMappingId(token); if (session != null) { String sessionID = session.getId(); logger.debug("Invalidating session for token [{}]", sessionID, token); try { session.invalidate(); } catch (final IllegalStateException e) { logger.debug("Error invalidating session.", e); } try { request.logout(); } catch (final ServletException e) { logger.debug("Error performing request.logout."); } } } }
Source:
<code>protected Sheet createSheet() { Sheet sheet = super.createSheet(); Sheet.Set sheetSet = sheet.get(Sheet.PROPERTIES); if (sheetSet == null) { sheetSet = Sheet.createPropertiesSet(); sheet.put(sheetSet); } final BlackboardArtifact artifact = getArtifact(); <START> BlackboardArtifact.ARTIFACT_TYPE fromID = BlackboardArtifact.ARTIFACT_TYPE.fromID(artifact.getArtifactTypeID()); <END> if (null != fromID && fromID != TSK_CALLLOG) { return sheet; } String phoneNumber = getAttributeDisplayString(artifact, TSK_PHONE_NUMBER_FROM); if(phoneNumber == null || phoneNumber.isEmpty()) { phoneNumber = getAttributeDisplayString(artifact, TSK_PHONE_NUMBER_TO); } long duration = -1; try{ duration = getCallDuration(artifact); } catch(TskCoreException ex) { } sheetSet.put(createNode(TSK_DATETIME_START, artifact)); sheetSet.put(createNode(TSK_DIRECTION, artifact)); sheetSet.put(new NodeProperty<>(TSK_PHONE_NUMBER.getLabel(), TSK_PHONE_NUMBER.getDisplayName(), "", phoneNumber)); if(duration != -1) { sheetSet.put(new NodeProperty<>("duration", "Duration", "", Long.toString(duration))); } return sheet; }</code><technical_language>rename fromID</technical_language>

Target:
protected Sheet createSheet() { Sheet sheet = super.createSheet(); Sheet.Set sheetSet = sheet.get(Sheet.PROPERTIES); if (sheetSet == null) { sheetSet = Sheet.createPropertiesSet(); sheet.put(sheetSet); } final BlackboardArtifact artifact = getArtifact(); BlackboardArtifact.ARTIFACT_TYPE fromID = BlackboardArtifact.ARTIFACT_TYPE.fromID(artifact.getArtifactTypeID()); if (null != fromID && fromID != TSK_CALLLOG) { return sheet; } String phoneNumber = getAttributeDisplayString(artifact, TSK_PHONE_NUMBER_FROM); if(phoneNumber == null || phoneNumber.isEmpty()) { phoneNumber = getAttributeDisplayString(artifact, TSK_PHONE_NUMBER_TO); } long duration = -1; try{ duration = getCallDuration(artifact); } catch(TskCoreException ex) { logger.log(Level.WARNING, String.format("Unable to get calllog duration for artifact: %d", artifact.getArtifactID()), ex); } sheetSet.put(createNode(TSK_DATETIME_START, artifact)); sheetSet.put(createNode(TSK_DIRECTION, artifact)); sheetSet.put(new NodeProperty<>(TSK_PHONE_NUMBER.getLabel(), TSK_PHONE_NUMBER.getDisplayName(), "", phoneNumber)); if(duration != -1) { sheetSet.put(new NodeProperty<>("duration", "Duration", "", Long.toString(duration))); } return sheet; }