auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private boolean containsJavaSource(File dir) { File[] files = dir.listFiles(); for (File file : files) { if (file.isFile() && file.getName().lastIndexOf(".") != -1 <START> && file.getName().substring(file.getName().lastIndexOf(".")).equalsIgnoreCase(".java")) { <END> return true; } else if (file.isDirectory()) { return containsJavaSource(file); } } return false; }</code><technical_language>file.getName().endsWith(".java") work OK? I guess if case is a concern, file.getName().toLowercase().endsWith(.java)</technical_language>

Target:
private boolean containsJavaSource(File dir) { File[] files = dir.listFiles(); for (File file : files) { if (file.isFile() && file.getName().lastIndexOf(".") != -1 && file.getName().toLowerCase().endsWith(".java")) { return true; } else if (file.isDirectory()) { return containsJavaSource(file); } } return false; }
Source:
<code>public void setAssignment(MethodInvocation node) { this.findViewByIdInvocation = node; <START> this.findViewByIdDeclarationFragment = (VariableDeclarationFragment) getFirstAncestorOrNull(node, <END> VariableDeclarationFragment.class); if (this.findViewByIdDeclarationFragment != null) { this.variable = this.findViewByIdDeclarationFragment.getName(); this.findViewByIdAssignment = getAncestor(this.findViewByIdDeclarationFragment, VariableDeclarationStatement.class); this.findViewByIdExpression = this.findViewByIdDeclarationFragment.getInitializer(); } else { this.findViewByIdVariableAssignment = (Assignment) getFirstAncestorOrNull(node, Assignment.class); if (this.findViewByIdVariableAssignment != null) { this.variable = (SimpleName) this.findViewByIdVariableAssignment.getLeftHandSide(); this.findViewByIdAssignment = getAncestor(this.findViewByIdVariableAssignment, ExpressionStatement.class); this.findViewByIdExpression = this.findViewByIdVariableAssignment.getRightHandSide(); } } }</code><technical_language>getAncestor()</technical_language>

Target:
private boolean setAssignment(MethodInvocation node) { this.findViewByIdInvocation = node; ASTNode ancestor = getFirstAncestorOrNull(node, VariableDeclarationFragment.class, Assignment.class); if (ancestor instanceof VariableDeclarationFragment) { findViewByIdDeclarationFragment = (VariableDeclarationFragment) ancestor; variable = findViewByIdDeclarationFragment.getName(); findViewByIdExpr = findViewByIdDeclarationFragment.getInitializer(); } else if (ancestor instanceof Assignment) { findViewByIdVariableAssignment = (Assignment) ancestor; ASTNode leftSide = findViewByIdVariableAssignment.getLeftHandSide(); if (leftSide.getNodeType() == SIMPLE_NAME) { variable = (SimpleName) leftSide; } else { return false; } findViewByIdExpr = findViewByIdVariableAssignment.getRightHandSide(); } return true; }
Source:
<code>private void handleGo() { privateKeyBadPasswordView.setVisibility(View.INVISIBLE); attemptsRemainingTextView.setVisibility(View.GONE); final String pin = privateKeyPasswordView.getText().toString().trim(); if (wallet.isEncrypted()) { new DeriveKeyTask(backgroundHandler, application.scryptIterationsTarget()) { @Override protected void onSuccess(final KeyParameter encryptionKey, final boolean wasChanged) { if (wasChanged) application.backupWallet(); signAndSendPayment(encryptionKey, pin); } }.deriveKey(wallet, pin); setState(State.DECRYPTING); } else { <START> signAndSendPayment(null); <END> } }</code><technical_language>this needs changed based new method parameter String pin in signAndSendPayment</technical_language>

Target:
private void handleGo() { privateKeyBadPasswordView.setVisibility(View.INVISIBLE); attemptsRemainingTextView.setVisibility(View.GONE); final String pin = privateKeyPasswordView.getText().toString().trim(); if (pinRetryController.isLocked()) { return; } if (wallet.isEncrypted()) { new DeriveKeyTask(backgroundHandler, application.scryptIterationsTarget()) { @Override protected void onSuccess(final KeyParameter encryptionKey, final boolean wasChanged) { if (wasChanged) application.backupWallet(); signAndSendPayment(encryptionKey, pin); } }.deriveKey(wallet, pin); setState(State.DECRYPTING); } else { signAndSendPayment(null, pin); } }
Source:
<code>public void deserialize(ConsumerRecord<byte[], byte[]> record, Collector<RowData> collector) throws Exception { if (keyDeserialization == null && !hasMetadata) { valueDeserialization.deserialize(record.value(), collector); return; } if (keyDeserialization != null) { keyDeserialization.deserialize(record.key(), keyCollector); } outputCollector.inputRecord = record; outputCollector.physicalKeyRows = keyCollector.buffer; outputCollector.outputCollector = collector; if (record.value() != null) { valueDeserialization.deserialize(record.value(), outputCollector); } else { outputCollector.collect(null); <START> } <END> keyCollector.buffer.clear(); }</code><technical_language>add a flag, e.g. upsertMode=true enable this behavior. for normal kafka connector, tombstone messages skipped</technical_language>

Target:
public void deserialize(ConsumerRecord<byte[], byte[]> record, Collector<RowData> collector) throws Exception { if (keyDeserialization == null && !hasMetadata) { valueDeserialization.deserialize(record.value(), collector); return; } if (keyDeserialization != null) { keyDeserialization.deserialize(record.key(), keyCollector); } outputCollector.inputRecord = record; outputCollector.physicalKeyRows = keyCollector.buffer; outputCollector.outputCollector = collector; if (record.value() == null && upsertMode) { outputCollector.collect(null); } else { valueDeserialization.deserialize(record.value(), outputCollector); } keyCollector.buffer.clear(); }
Source:
<code>private IProject getSingleProject() { IProject result= null; for (IJavaElement <START> fJavaElement : <END> fJavaElements) { if (result == null) { result= fJavaElement.getJavaProject().getProject(); } else if (!result.equals(fJavaElement.getJavaProject().getProject())) { return null; } } return result; }</code><technical_language>rename javaElement</technical_language>

Target:
private IProject getSingleProject() { IProject result= null; for (IJavaElement javaElement : fJavaElements) { if (result == null) { result= javaElement.getJavaProject().getProject(); } else if (!result.equals(javaElement.getJavaProject().getProject())) { return null; } } return result; }
Source:
<code>public final Response createType(@Context final HttpServletRequest req, final String json) throws DotDataException, DotSecurityException { final InitDataObject initData = this.webResource.init(null, true, req, true, null); final User user = initData.getUser(); Response response = null; try { List<ContentType> typesToSave = new JsonContentTypeTransformer(json).asList(); <START> List<ContentType> retTypes = new ArrayList<>(); <END> for (ContentType type : typesToSave) { if (UtilMethods.isSet(type.id()) && !UUIDUtil.isUUID(type.id())) { return ExceptionMapperUtil.createResponse(null, "ContentType 'id' if set, should be a uuid"); } retTypes.add(APILocator.getContentTypeAPI(user, true).save(type)); } response = Response.ok(new ResponseEntityView(new JsonContentTypeTransformer(retTypes).mapList())).build(); } catch (DotStateException e) { response = ExceptionMapperUtil.createResponse(null, "Content-type is not valid ("+ e.getMessage() +")"); } catch (DotDataException e) { response = ExceptionMapperUtil.createResponse(null, "Content-type is not valid ("+ e.getMessage() +")"); } catch (Exception e) { response = ExceptionMapperUtil.createResponse(e, Response.Status.INTERNAL_SERVER_ERROR); } return response; }</code><technical_language>This immutable</technical_language>

Target:
public final Response createType(@Context final HttpServletRequest req, final String json) throws DotDataException, DotSecurityException { final InitDataObject initData = this.webResource.init(null, true, req, true, null); final User user = initData.getUser(); Response response = null; try { final List<ContentType> typesToSave = new JsonContentTypeTransformer(json).asList(); final List<ContentType> retTypes = new ArrayList<>(); for (ContentType type : typesToSave) { if (UtilMethods.isSet(type.id()) && !UUIDUtil.isUUID(type.id())) { return ExceptionMapperUtil.createResponse(null, "ContentType 'id' if set, should be a uuid"); } retTypes.add(APILocator.getContentTypeAPI(user, true).save(type)); } response = Response.ok(new ResponseEntityView(new JsonContentTypeTransformer(retTypes).mapList())).build(); } catch (DotStateException e) { response = ExceptionMapperUtil.createResponse(null, "Content-type is not valid ("+ e.getMessage() +")"); } catch (DotDataException e) { response = ExceptionMapperUtil.createResponse(null, "Content-type is not valid ("+ e.getMessage() +")"); } catch (Exception e) { response = ExceptionMapperUtil.createResponse(e, Response.Status.INTERNAL_SERVER_ERROR); } return response; }
Source:
<code><START> String getTagType() { <END> return tagType; }</code><technical_language>public access</technical_language>

Target:
public String getTagType() { return tagType; }
Source:
<code><START> private void validate(String accountId, Stack stack, Set<InstanceMetaData> remainingGoodInstances, Set<InstanceMetaData> remainingBadInstances, <END> Collection<InstanceMetaData> instancesToRepair) { if (!entitlementService.freeIpaHaEnabled(INTERNAL_ACTOR_CRN, accountId)) { throw new BadRequestException("The FreeIPA HA capability is disabled."); } if (instancesToRepair.isEmpty()) { throw new NotFoundException("No unhealthy instances to repair. Maybe use the force option."); } if (remainingGoodInstances.isEmpty()) { throw new BadRequestException("At least one instance must remain running with a good status during a repair."); } if (!remainingBadInstances.isEmpty()) { String errorMsg = "At least one remaining non-repaired instance has a bad status. All remaining instances must have a good status during a repair."; LOGGER.error("{}. The following instances have a bad status: [{}]", errorMsg, remainingBadInstances); throw new BadRequestException(errorMsg); } if (stack.getInstanceGroups().isEmpty()) { throw new BadRequestException("At least one instace group must be present for a repair."); } }</code><technical_language>I if log instances parameters of this method</technical_language>

Target:
private void validate(String accountId, Stack stack, Set<InstanceMetaData> remainingGoodInstances, Set<InstanceMetaData> remainingBadInstances, Collection<InstanceMetaData> instancesToRepair) { LOGGER.debug("Validating repair for account and stack ID {}. Remaining good instances [{}]. Remaining bad instances [{}]. Instances to repair [{}].", accountId, stack.getId(), remainingGoodInstances, remainingBadInstances, instancesToRepair); if (!entitlementService.freeIpaHaEnabled(INTERNAL_ACTOR_CRN, accountId)) { throw new BadRequestException("The FreeIPA HA capability is disabled."); } if (instancesToRepair.isEmpty()) { throw new NotFoundException("No unhealthy instances to repair. Maybe use the force option."); } if (remainingGoodInstances.isEmpty()) { throw new BadRequestException("At least one instance must remain running with a good status during a repair."); } if (!remainingBadInstances.isEmpty()) { String errorMsg = "At least one remaining non-repaired instance has a bad status. All remaining instances must have a good status during a repair."; LOGGER.error("{}. The following instances have a bad status: [{}]", errorMsg, remainingBadInstances); throw new BadRequestException(errorMsg); } if (stack.getInstanceGroups().isEmpty()) { throw new BadRequestException("At least one instace group must be present for a repair."); } }
Source:
<code>protected boolean canDoAction() { VmHandler.updateDisksFromDb(getVm()); Collection<DiskImage> diskImages = ImagesHandler.filterImageDisks(getVm().getDiskMap().values(), false, true); DiskImage vmDisk = LinqUtils.first(diskImages); boolean result = true; Snapshot snapshot = getSnapshotDao().get(getParameters().getDstSnapshotId()); SnapshotsValidator snapshotsValidator = new SnapshotsValidator(); VmValidator vmValidator = new VmValidator(getVm()); <START> result = result && validate(snapshotsValidator.vmNotDuringSnapshot(getVmId())) <END> && validate(snapshotsValidator.snapshotExists(snapshot)) && validate(snapshotsValidator.snapshotNotBroken(snapshot)) && validate(vmValidator.vmDown()); if (vmDisk != null) { result = result && ImagesHandler.PerformImagesChecks(getVm(), getReturnValue().getCanDoActionMessages(), getVm().getStoragePoolId(), Guid.Empty, true, true, false, false, true, false, true, true, getVm().getDiskMap().values()); } if (result && LinqUtils.foreach(diskImages, new Function<DiskImage, Guid>() { @Override public Guid eval(DiskImage disk) { return disk.getvm_snapshot_id().getValue(); } }).contains(getParameters().getDstSnapshotId())) { result = false; addCanDoActionMessage(VdcBllMessages.CANNOT_PREIEW_CURRENT_IMAGE); } if (!result) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__PREVIEW); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__SNAPSHOT); } return result; }</code><technical_language>I part of change, result is true - result&&... ? if agree, pls remove condition. Also, worth put "vmDown" check check in condition fast efficient check - if down, snapshot is currently check</technical_language>

Target:
protected boolean canDoAction() { updateVmDisksFromDb(); Collection<DiskImage> diskImages = ImagesHandler.filterImageDisks(getVm().getDiskMap().values(), false, true); DiskImage vmDisk = LinqUtils.first(diskImages); Snapshot snapshot = getSnapshotDao().get(getParameters().getDstSnapshotId()); SnapshotsValidator snapshotsValidator = new SnapshotsValidator(); VmValidator vmValidator = new VmValidator(getVm()); boolean result = validate(vmValidator.vmDown()) && validate(snapshotsValidator.vmNotDuringSnapshot(getVmId())) && validate(snapshotsValidator.snapshotExists(snapshot)) && validate(snapshotsValidator.snapshotNotBroken(snapshot)); if (vmDisk != null) { result = result && ImagesHandler.PerformImagesChecks(getVm(), getReturnValue().getCanDoActionMessages(), getVm().getStoragePoolId(), Guid.Empty, true, true, false, false, true, false, true, true, getVm().getDiskMap().values()); } if (result && LinqUtils.foreach(diskImages, new Function<DiskImage, Guid>() { @Override public Guid eval(DiskImage disk) { return disk.getvm_snapshot_id().getValue(); } }).contains(getParameters().getDstSnapshotId())) { result = false; addCanDoActionMessage(VdcBllMessages.CANNOT_PREIEW_CURRENT_IMAGE); } if (!result) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__PREVIEW); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__SNAPSHOT); } return result; }
Source:
<code>public void testCollections() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("list", "5,4,3,2,1"); config.setProperty("set", "5,4,3,2,1"); config.setProperty("sortedSet", "5,4,3,2,1"); config.setProperty("linkedList", "5,4,3,2,1"); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); ConfigWithCollections withCollections = proxy.newProxy(ConfigWithCollections.class); Assert.assertEquals(Arrays.asList(5,4,3,2,1), new ArrayList<>(withCollections.getLinkedList())); Assert.assertEquals(Arrays.asList(5,4,3,2,1), new ArrayList<>(withCollections.getList())); <START> Assert.assertEquals(Arrays.asList(5,4,3,2,1), new ArrayList<>(withCollections.getSet())); <END> Assert.assertEquals(Arrays.asList(1,2,3,4,5), new ArrayList<>(withCollections.getSortedSet())); config.setProperty("list", "6,7,8,9,10"); Assert.assertEquals(Arrays.asList(6,7,8,9,10), new ArrayList<>(withCollections.getList())); }</code><technical_language>assert order unsorted set? assume not</technical_language>

Target:
public void testCollections() { SettableConfig config = new DefaultSettableConfig(); config.setProperty("list", "5,4,3,2,1"); config.setProperty("set", "1,2,3,5,4"); config.setProperty("sortedSet", "5,4,3,2,1"); config.setProperty("linkedList", "5,4,3,2,1"); PropertyFactory factory = DefaultPropertyFactory.from(config); ConfigProxyFactory proxy = new ConfigProxyFactory(config, config.getDecoder(), factory); ConfigWithCollections withCollections = proxy.newProxy(ConfigWithCollections.class); Assert.assertEquals(Arrays.asList(5,4,3,2,1), new ArrayList<>(withCollections.getLinkedList())); Assert.assertEquals(Arrays.asList(5,4,3,2,1), new ArrayList<>(withCollections.getList())); Assert.assertEquals(Arrays.asList(1,2,3,5,4), new ArrayList<>(withCollections.getSet())); Assert.assertEquals(Arrays.asList(1,2,3,4,5), new ArrayList<>(withCollections.getSortedSet())); config.setProperty("list", "6,7,8,9,10"); Assert.assertEquals(Arrays.asList(6,7,8,9,10), new ArrayList<>(withCollections.getList())); }
Source:
<code>public void onPlayerTeleport(PlayerTeleportEvent event) { final Player player = event.getPlayer(); final TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player); final Player player = event.getPlayer(); <START> final TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player); <END> double teleportX = event.getTo().getX(); double teleportZ = event.getTo().getZ(); if(Math.abs(teleportX) >= 30000000 || Math.abs(teleportZ) >= 30000000) { event.setCancelled(true); } if (!TFM_AdminList.isSuperAdmin(player) && playerdata.isFrozen()) { TFM_Util.setFlying(player, true); event.setTo(playerdata.getFreezeLocation()); return; } TFM_AdminWorld.getInstance().validateMovement(event); }</code><technical_language>Unused variable</technical_language>

Target:
public void onPlayerTeleport(PlayerTeleportEvent event) { final Player player = event.getPlayer(); final TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player); if(Math.abs(event.getTo().getX()) >= 30000000 || Math.abs(event.getTo().getZ()) >= 30000000) { event.setCancelled(true); } if (!TFM_AdminList.isSuperAdmin(player) && playerdata.isFrozen()) { TFM_Util.setFlying(player, true); event.setTo(playerdata.getFreezeLocation()); return; } TFM_AdminWorld.getInstance().validateMovement(event); }
Source:
<code>public void initializeGrid() { int xx = FRAME_THICKNESS; for (int x = 0; x < GRID_WIDTH; x++) { int yy = FRAME_THICKNESS; for (int y = 0; y < GRID_WIDTH; y++) { Cell cell = new Cell(0); cell.setCellLocation(xx, yy); grid[x][y] = cell; <START> yy += <END> FRAME_THICKNESS + Cell.getCellWidth(); } xx += FRAME_THICKNESS + Cell.getCellWidth(); } }</code><technical_language>correct</technical_language>

Target:
public void initializeGrid() { int frameThicknessX = FRAME_THICKNESS; for (int i = 0; i < GRID_WIDTH; i++) { int frameThicknessY = FRAME_THICKNESS; for (int j = 0; j < GRID_WIDTH; j++) { Cell cell = new Cell(0); cell.setCellLocation(frameThicknessX, frameThicknessY); grid[i][j] = cell; frameThicknessY += FRAME_THICKNESS + Cell.getCellWidth(); } frameThicknessX += FRAME_THICKNESS + Cell.getCellWidth(); } }
Source:
<code>public void associateNeighborStateNotifier(P unwindingContext, BlockPos sourcePos, Block block, BlockPos notifyPos, WorldServer minecraftWorld, PlayerTracker.Type notifier) { final Player player = unwindingContext.getSpongePlayer(); <START> unwindingContext.getOwner().ifPresent(owner -> ((IMixinChunk) minecraftWorld.getChunkFromBlockCoords(notifyPos)).setBlockCreator(notifyPos, owner.getUniqueId())); <END> ((IMixinChunk) minecraftWorld.getChunkFromBlockCoords(notifyPos)).setBlockNotifier(notifyPos, player.getUniqueId()); }</code><technical_language>here.... player......... other owner for a player, is there..</technical_language>

Target:
public void associateNeighborStateNotifier(P unwindingContext, BlockPos sourcePos, Block block, BlockPos notifyPos, WorldServer minecraftWorld, PlayerTracker.Type notifier) { final Player player = unwindingContext.getSpongePlayer(); Chunk chunk = minecraftWorld.getChunkFromBlockCoords(notifyPos); ((IMixinChunk) chunk).setBlockCreator(notifyPos, player.getUniqueId()); ((IMixinChunk) chunk).setBlockNotifier(notifyPos, player.getUniqueId()); }
Source:
<code>private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { List<Message> listAmqpMessages = convertAMQPValueMessageToBrokeredMessage(amqpMessage); List<ServiceBusReceivedMessage> receivedMessageList = new ArrayList<>(); for (Message oneAmqpMessage:listAmqpMessages <START> ) { <END> ServiceBusReceivedMessage serviceBusReceivedMessage = deserializeMessage(oneAmqpMessage); receivedMessageList.add(serviceBusReceivedMessage); } return receivedMessageList; }</code><technical_language>nit: new line</technical_language>

Target:
private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { List<Message> listAmqpMessages = convertAmqpValueMessageToBrokeredMessage(amqpMessage); List<ServiceBusReceivedMessage> receivedMessageList = new ArrayList<>(); for (Message oneAmqpMessage:listAmqpMessages) { ServiceBusReceivedMessage serviceBusReceivedMessage = deserializeMessage(oneAmqpMessage); receivedMessageList.add(serviceBusReceivedMessage); } return receivedMessageList; }
Source:
<code>public void playerDamageEvent(EntityDamageEvent event) { <START> if (!(event.getEntity().getType() == EntityType.PLAYER)) <END> return; Player p = (Player) event.getEntity(); if (BetterShardsPlugin.getTransitManager().isPlayerInTransit(p.getUniqueId())) { event.setCancelled(true); } }</code><technical_language>downside is this change, line 390 is unchecked cast, checked</technical_language>

Target:
public void playerDamageEvent(EntityDamageEvent event) { if (!(event.getEntity() instanceof Player)) { return; } Player p = (Player) event.getEntity(); if (BetterShardsPlugin.getTransitManager().isPlayerInTransit(p.getUniqueId())) { event.setCancelled(true); } }
Source:
<code>public Ipx800Binding() { <START> logger.debug("Ipx800Binding created"); <END> }</code><technical_language>remove statement</technical_language>

Target:
public Ipx800Binding() { }
Source:
<code>private void sendRequest(String addUrl, String query) throws IOException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/xml;charset=" + charset); OutputStream output = null; try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { <START> log.error("Error while closing the connection"); <END> } } } InputStream response = connection.getInputStream(); if (response != null) { StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[1024]; int len; while ((len = response.read(bytes)) != -1) { sb.append(new String(bytes, 0, len)); } } }</code><technical_language>Exception swallows</technical_language>

Target:
private void sendRequest(String addUrl, String query) throws IOException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/xml;charset=" + charset); OutputStream output = null; try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { output.close(); } } InputStream response = connection.getInputStream(); if (response != null) { StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[1024]; int len; while ((len = response.read(bytes)) != -1) { sb.append(new String(bytes, 0, len)); } } }
Source:
<code>private IProxyService retrieveProxyService() { final String CORE_NET_BUNDLE = "org.eclipse.core.net"; Bundle bundle = Platform.getBundle(CORE_NET_BUNDLE); while (bundle.getState() != Bundle.ACTIVE) { try { Thread.sleep(1000); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } } ServiceReference ref = bundle.getBundleContext().getServiceReference(IProxyService.class.getName()); if (ref != null) { return (IProxyService) bundle.getBundleContext().getService(ref); } return null; }</code><technical_language>wait for a bundle active. If a dependency exists plug-in A B, B active A. If case, investigation is needed</technical_language>

Target:
private IProxyService retrieveProxyService() { final String CORE_NET_BUNDLE = "org.eclipse.core.net"; Bundle bundle = Platform.getBundle(CORE_NET_BUNDLE); ServiceReference ref = bundle.getBundleContext().getServiceReference(IProxyService.class.getName()); if (ref != null) { IProxyService proxyService = (IProxyService) bundle.getBundleContext().getService(ref); proxyService.setProxiesEnabled(true); proxyService.setSystemProxiesEnabled(false); return proxyService; } return null; }
Source:
<code>public boolean cleanupManagedDisks(VirtualMachine virtualMachine) { Map<String, URI> deleteJobs = new HashMap<String, URI>(); OSDisk osDisk = virtualMachine.properties().storageProfile().osDisk(); deleteManagedDisk(osDisk.managedDiskParameters(), deleteJobs); for (DataDisk dataDisk : virtualMachine.properties().storageProfile().dataDisks()) { deleteManagedDisk(dataDisk.managedDiskParameters(), deleteJobs); } Set<String> nonDeletedDisks = filterValues(deleteJobs, not(resourceDeleted)).keySet(); if (!nonDeletedDisks.isEmpty()) { <START> logger.warn(">> could not deleteVault disks: %s", Joiner.on(',').join(nonDeletedDisks)); <END> } return nonDeletedDisks.isEmpty(); }</code><technical_language>I delete more approriate</technical_language>

Target:
public boolean cleanupManagedDisks(VirtualMachine virtualMachine) { Map<String, URI> deleteJobs = new HashMap<String, URI>(); OSDisk osDisk = virtualMachine.properties().storageProfile().osDisk(); deleteManagedDisk(osDisk.managedDiskParameters(), deleteJobs); for (DataDisk dataDisk : virtualMachine.properties().storageProfile().dataDisks()) { deleteManagedDisk(dataDisk.managedDiskParameters(), deleteJobs); } Set<String> nonDeletedDisks = filterValues(deleteJobs, not(resourceDeleted)).keySet(); if (!nonDeletedDisks.isEmpty()) { logger.warn(">> could not delete disks: %s", Joiner.on(',').join(nonDeletedDisks)); } return nonDeletedDisks.isEmpty(); }
Source:
<code>private void executeAndCheckSplitPart(int fieldNumber) throws SQLException { int count = 0; String sCell1 = null; String sCell2 = null; ResultSet rs; <START> rs = methodWatcher.executeQuery(String.format("select split_part(e, ' ', %d), e from ", fieldNumber) + tableWatcherB); <END> count = 0; while (rs.next()) { sCell1 = rs.getString(1); sCell2 = rs.getString(2); String splitExpected; if (sCell2 != null) { String sCell2Parts[] = sCell2.split("\\s"); if (fieldNumber > sCell2Parts.length) { splitExpected = null; } else { splitExpected = sCell2Parts[fieldNumber - 1]; } } else { splitExpected = null; } Assert.assertEquals("Wrong result value", sCell1, splitExpected); count++; } Assert.assertEquals("Incorrect row count", 5, count); }</code><technical_language>please rewrite: String.format("select split_part(e, ' ', %d), e ", fieldNumber) + tableWatcherB to: String.format("select split_part(e, ' ', %d), e %s", fieldNumber, tableWatcherB)</technical_language>

Target:
private void executeAndCheckSplitPart(int fieldNumber) throws SQLException { int count = 0; String sCell1 = null; String sCell2 = null; ResultSet rs; rs = methodWatcher.executeQuery(String.format("select split_part(e, ' ', %d), e from %s", fieldNumber, tableWatcherB)); count = 0; while (rs.next()) { sCell1 = rs.getString(1); sCell2 = rs.getString(2); String splitExpected; if (sCell2 != null) { String sCell2Parts[] = sCell2.split("\\s"); if (fieldNumber > sCell2Parts.length) { splitExpected = null; } else { splitExpected = sCell2Parts[fieldNumber - 1]; } } else { splitExpected = null; } Assert.assertEquals("Wrong result value", sCell1, splitExpected); count++; } Assert.assertEquals("Incorrect row count", 5, count); }
Source:
<code>public ConceptMapMappings evaluate(CodeSystemURI uri, BranchContext context, Options search) { final String preferredDisplay = search.get(OptionKey.DISPLAY, String.class); SnomedDisplayTermType snomedDisplayTermType; <START> try { <END> snomedDisplayTermType = SnomedDisplayTermType.valueOf(preferredDisplay); } catch(Exception e) { snomedDisplayTermType = SnomedDisplayTermType.PT; } SnomedReferenceSetMembers referenceSetMembers = fetchRefsetMembers(uri, context, search, snomedDisplayTermType); return toCollectionResource(referenceSetMembers, uri, context, search, snomedDisplayTermType); }</code><technical_language>This try-catch part of SnomedDisplayTermType enum, unrecognized preferredDisplay strings either: * Fail a clear error message * fall FSN default, PT</technical_language>

Target:
public ConceptMapMappings evaluate(CodeSystemURI uri, BranchContext context, Options search) { final String preferredDisplay = search.get(OptionKey.DISPLAY, String.class); final SnomedDisplayTermType snomedDisplayTermType = SnomedDisplayTermType.getEnum(preferredDisplay); SnomedReferenceSetMembers referenceSetMembers = fetchRefsetMembers(uri, context, search, snomedDisplayTermType); return toCollectionResource(referenceSetMembers, uri, context, search, snomedDisplayTermType); }
Source:
<code>@Override public void close(boolean cancel) throws CacheException { try { closeEx(cancel); closedStreamer = true; <START> } <END> catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } }</code><technical_language>This changed write lock</technical_language>

Target:
@Override public void close(boolean cancel) throws CacheException { try { closeEx(cancel); } catch (IgniteCheckedException e) { throw CU.convertToCacheException(e); } }
Source:
<code>public void setup() throws IOException { <START> geometry = GeoFunctions.toSphericalGeography(GeoFunctions.stGeometryFromText(Slices.utf8Slice(loadPolygon("large_polygon.txt")))); <END> geometry500k = GeoFunctions.toSphericalGeography(GeoFunctions.stGeometryFromText(Slices.utf8Slice(createPolygon(9.0, 500000)))); }</code><technical_language>static import toSphericalGeography, toSphericalGeography utf8Slice</technical_language>

Target:
public void setup() throws IOException { geometry = stGeometryFromText(utf8Slice(loadPolygon("large_polygon.txt"))); geometry500k = stGeometryFromText(utf8Slice(createPolygon(500000))); geography = toSphericalGeography(geometry); geography500k = toSphericalGeography(geometry500k); }
Source:
<code>private void startPassiveScanIfNeeded() { LogManager.d(TAG, "Checking to see if we need to start a passive scan"); boolean insideAnyRegion = false; List<Region> regions = new ArrayList<>(mScanState.getMonitoringStatus().regions()); for (Region region : regions) { RegionMonitoringState state = mScanState.getMonitoringStatus().stateOf(region); if (state != null && state.getInside()) { insideAnyRegion = true; } } if (insideAnyRegion) { } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { <START> mScanHelper.startAndroidOBackgroundScan(mScanState.getBeaconParsers()); <END> } else { LogManager.d(TAG, "This is not Android O. No scanning between cycles when using ScanJob"); } }</code><technical_language>I this code change helpful. If insideAnyRegion == true (meaning beacon is visible in vicinity), is point in calling mScanHelper.startAndroidOBackgroundScan(mScanState.getBeaconParsers());. This result in callbacks quickly time visible beacon continues seen. This accomplish more extra CPU battery app is in background</technical_language>

Target:
private void startPassiveScanIfNeeded() { LogManager.d(TAG, "Checking to see if we need to start a passive scan"); boolean insideAnyRegion = false; List<Region> regions = new ArrayList<>(mScanState.getMonitoringStatus().regions()); for (Region region : regions) { RegionMonitoringState state = mScanState.getMonitoringStatus().stateOf(region); if (state != null && state.getInside()) { insideAnyRegion = true; } } if (insideAnyRegion && mScanState.getRangedRegionState().size() == 0) { LogManager.i(TAG, "We are inside a beacon region. We will not scan between cycles."); } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { mScanHelper.startAndroidOBackgroundScan(mScanState.getBeaconParsers()); } else { LogManager.d(TAG, "This is not Android O. No scanning between cycles when using ScanJob"); } } }
Source:
<code>private boolean processNextEvent(LineTcpMeasurementEvent event) { Parser parser = parserCache.get(event.getTableName()); if (null == parser) { parser = new Parser(); try { parser.processFirstEvent(engine, securityContext, event); } catch (CairoException ex) { <START> LOG.info().$(name).$(" could not create parser [name=").$(event.getTableName()).$(", ex=").$(ex.getFlyweightMessage()).$(']').$(); <END> parser.close(); return false; } LOG.info().$(name).$(" created parser [name=").$(event.getTableName()).$(']').$(); parserCache.put(Chars.toString(event.getTableName()).toString(), parser); return true; } else { parser.processEvent(event); return true; } }</code><technical_language>This in tests. catch "CairoError". writer.commit() is liable throw that. stick "message [context]" style of logging for thread name too</technical_language>

Target:
private boolean processNextEvent(LineTcpMeasurementEvent event) { Parser parser = parserCache.get(event.getTableName()); if (null == parser) { parser = new Parser(); try { parser.processFirstEvent(engine, securityContext, event); } catch (CairoException ex) { LOG.info().$("could not create parser [jobName=").$(jobName).$(" name=").$(event.getTableName()).$(", ex=").$(ex.getFlyweightMessage()).$(']').$(); parser.close(); return false; } LOG.info().$("created parser [jobName=").$(jobName).$(" name=").$(event.getTableName()).$(']').$(); parserCache.put(Chars.toString(event.getTableName()), parser); } else { parser.processEvent(event); } return true; }
Source:
<code>private int getTimeMultiplier() { int mult; switch(refitClass) { case NO_CHANGE: mult = 0; break; case CLASS_C: mult = 2; break; case CLASS_D: mult = 3; break; case CLASS_E: mult = 4; break; case CLASS_F: mult = 5; break; case CLASS_A: case CLASS_B: default: mult = 1; <START> } <END> if(customJob) { mult *= 2; } return mult; }</code><technical_language>Put a break; for good measure</technical_language>

Target:
private int getTimeMultiplier() { int mult; switch(refitClass) { case NO_CHANGE: mult = 0; break; case CLASS_C: mult = 2; break; case CLASS_D: mult = 3; break; case CLASS_E: mult = 4; break; case CLASS_F: mult = 5; break; case CLASS_A: case CLASS_B: default: mult = 1; break; } if (customJob) { mult *= 2; } return mult; }
Source:
<code>public void test_setControl() { int number = 5; TabItem[] items = new TabItem[number]; final Button setControlButton = new Button (tabFolder, SWT.None); setControlButton.setText ("test button"); <START> for (int i = 0; i < number; i++) { <END> items[i] = new TabItem(tabFolder, 0); items[i].setControl (setControlButton); assertEquals (items[i].getControl (), setControlButton); } assertEquals (items[number-1].getControl (), setControlButton); }</code><technical_language>test works for patch. a version fails patch passes afterwards. tests case widget invisible coming a tab: for (int i = 0; i < number; i++) { items[i] = new TabItem(tabFolder, 0); items[i].setControl (setControlButton); assertEquals (items[i].getControl (), setControlButton); assertTrue(setControlButton.getVisible()); } items[0].setControl (setControlButton); assertEquals (items[0].getControl (), setControlButton); assertTrue(setControlButton.getVisible());</technical_language>

Target:
public void test_setControl() { int number = 5; TabItem[] items = new TabItem[number]; final Button setControlButton = new Button (tabFolder, SWT.None); setControlButton.setText ("test button"); for (int i = 0; i < number; i++) { items[i] = new TabItem(tabFolder, 0); items[i].setControl (setControlButton); assertEquals (items[i].getControl (), setControlButton); assertTrue(setControlButton.getVisible()); } items[0].setControl (setControlButton); assertEquals (items[0].getControl (), setControlButton); assertTrue(setControlButton.getVisible()); }
Source:
<code>public boolean hasUpdates() { <START> synchronized (m_updates) { <END> if (m_updates.booleanValue()) { return true; } } return false; }</code><technical_language>simplified return m_updates</technical_language>

Target:
public boolean hasUpdates() { return m_updates.get(); }
Source:
<code>private Optional<PingableLeader> getSuspectedLeaderOverNetwork(String uuid) { PaxosResponsesWithRemote<PingableLeader, PaxosString> responses = PaxosQuorumChecker.collectUntil( <START> ImmutableList.copyOf(leaderPingExecutors.keySet()), <END> pingableLeader -> new PaxosString(pingableLeader.getUUID()), leaderPingExecutors, Duration.ofMillis(leaderPingResponseWaitMs), state -> state.responses().values().stream().map(PaxosString::get).anyMatch(uuid::equals)); for (Map.Entry<PingableLeader, PaxosString> cacheEntry : responses.responses().entrySet()) { String uuidFromRequest = cacheEntry.getValue().get(); PingableLeader service = uuidToServiceCache.putIfAbsent(uuidFromRequest, cacheEntry.getKey()); throwIfInvalidSetup(service, cacheEntry.getKey(), uuidFromRequest); if (uuid.equals(uuidFromRequest)) { return Optional.of(cacheEntry.getKey()); } } return Optional.empty(); }</code><technical_language>nit: I expecting otherPingables here, - equal</technical_language>

Target:
private Optional<PingableLeader> getSuspectedLeaderOverNetwork(String uuid) { PaxosResponsesWithRemote<PingableLeader, PaxosString> responses = PaxosQuorumChecker.collectUntil( otherPingables, pingableLeader -> new PaxosString(pingableLeader.getUUID()), leaderPingExecutors, Duration.ofMillis(leaderPingResponseWaitMs), state -> state.responses().values().stream().map(PaxosString::get).anyMatch(uuid::equals)); for (Map.Entry<PingableLeader, PaxosString> cacheEntry : responses.responses().entrySet()) { String uuidFromRequest = cacheEntry.getValue().get(); PingableLeader service = uuidToServiceCache.putIfAbsent(uuidFromRequest, cacheEntry.getKey()); throwIfInvalidSetup(service, cacheEntry.getKey(), uuidFromRequest); if (uuid.equals(uuidFromRequest)) { return Optional.of(cacheEntry.getKey()); } } return Optional.empty(); }
Source:
<code>public <T extends Enum<?>> T getEnum(final T[] all, final String section, final String subsection, final String name, final T defaultValue) { String value = getString(section, subsection, name); if (value == null) return defaultValue; <START> String n = value.replace(' ', '_'); <END> T trueState = null; T falseState = null; for (T e : all) { if (StringUtils.equalsIgnoreCase(e.name(), n)) return e; else if (StringUtils.equalsIgnoreCase(e.toString(), n)) return e; else if (StringUtils.equalsIgnoreCase(e.name(), "TRUE")) trueState = e; else if (StringUtils.equalsIgnoreCase(e.name(), "FALSE")) falseState = e; } if (trueState != null && falseState != null) { try { return StringUtils.toBoolean(n) ? trueState : falseState; } catch (IllegalArgumentException err) { } } if (subsection != null) throw new IllegalArgumentException(MessageFormat.format(JGitText .get().enumValueNotSupported3, section, name, value)); else throw new IllegalArgumentException(MessageFormat.format(JGitText .get().enumValueNotSupported2, section, name, value)); }</code><technical_language>parsing replace ' ' '_' match toString() format, output convert '_' in toString() output ' '. identity transforms</technical_language>

Target:
public <T extends Enum<?>> T getEnum(final T[] all, final String section, final String subsection, final String name, final T defaultValue) { String value = getString(section, subsection, name); if (value == null) return defaultValue; if (defaultValue instanceof FastForwardMode) { return (T) FastForwardMode.valueOf(section, subsection, name, value); } String n = value.replace(' ', '_'); T trueState = null; T falseState = null; for (T e : all) { if (StringUtils.equalsIgnoreCase(e.name(), n)) return e; else if (StringUtils.equalsIgnoreCase(e.toString(), n)) return e; else if (StringUtils.equalsIgnoreCase(e.name(), "TRUE")) trueState = e; else if (StringUtils.equalsIgnoreCase(e.name(), "FALSE")) falseState = e; } if (trueState != null && falseState != null) { try { return StringUtils.toBoolean(n) ? trueState : falseState; } catch (IllegalArgumentException err) { } } if (subsection != null) throw new IllegalArgumentException(MessageFormat.format(JGitText .get().enumValueNotSupported3, section, subsection, name, value)); else throw new IllegalArgumentException(MessageFormat.format(JGitText .get().enumValueNotSupported2, section, name, value)); }
Source:
<code>private OafRel createOafRelObject() { return OafRel.newBuilder().setSource(SOURCE_ID).setTarget(TARGET_ID) <START> .setRelType(irrelevantType).setSubRelType(irrelevantSubtype) <END> .setRelClass("irrelevantRelClass").setChild(false) .build(); }</code><technical_language>care. Proper converter is picked based columnFamily is need check relType subRelType</technical_language>

Target:
private static OafRel createOafRelObject() { return OafRel.newBuilder().setSource(SOURCE_ID).setTarget(TARGET_ID) .setRelType(RelType.resultResult).setSubRelType(SubRelType.provision) .setRelClass("irrelevantRelClass").setChild(false) .build(); }
Source:
<code>public void withdrawFromStudyRemovesDataGroups() { account.setConsentSignatureHistory(SUBPOP_GUID, ImmutableList.of(CONSENT_SIGNATURE)); <START> account.setDataGroups(new HashSet<>(TestConstants.USER_DATA_GROUPS)); <END> when(subpopulation.getDataGroupsAssignedWhileConsented()).thenReturn(TestConstants.USER_DATA_GROUPS); when(subpopService.getSubpopulation(study.getStudyIdentifier(), SUBPOP_GUID)).thenReturn(subpopulation); when(accountDao.getAccount(any())).thenReturn(account); consentService.withdrawFromStudy(study, PARTICIPANT, WITHDRAWAL, WITHDREW_ON); assertTrue(account.getDataGroups().isEmpty()); verify(subpopulation).getDataGroupsAssignedWhileConsented(); verify(subpopulation, never()).getSubstudyIdsAssignedOnConsent(); }</code><technical_language>Add additional data groups, subpopulation removed</technical_language>

Target:
public void withdrawFromStudyRemovesDataGroups() { account.setConsentSignatureHistory(SUBPOP_GUID, ImmutableList.of(CONSENT_SIGNATURE)); Set<String> dataGroups = new HashSet<>(TestConstants.USER_DATA_GROUPS); dataGroups.add("remainingDataGroup1"); dataGroups.add("remainingDataGroup2"); account.setDataGroups(dataGroups); when(subpopulation.getDataGroupsAssignedWhileConsented()).thenReturn(TestConstants.USER_DATA_GROUPS); when(subpopService.getSubpopulation(study.getStudyIdentifier(), SUBPOP_GUID)).thenReturn(subpopulation); when(accountDao.getAccount(any())).thenReturn(account); consentService.withdrawFromStudy(study, PARTICIPANT, WITHDRAWAL, WITHDREW_ON); assertEquals(ImmutableSet.of("remainingDataGroup1", "remainingDataGroup2"), account.getDataGroups()); verify(subpopulation).getDataGroupsAssignedWhileConsented(); verify(subpopulation, never()).getSubstudyIdsAssignedOnConsent(); }
Source:
<code>public CompletableFuture<KubernetesWorkerNode> requestResource(TaskExecutorProcessSpec taskExecutorProcessSpec) { final KubernetesTaskManagerParameters parameters = createKubernetesTaskManagerParameters(taskExecutorProcessSpec); final KubernetesPod taskManagerPod = KubernetesTaskManagerFactory.buildTaskManagerKubernetesPod(parameters); final String podName = taskManagerPod.getName(); final CompletableFuture<KubernetesWorkerNode> requestResourceFuture = new CompletableFuture<>(); requestResourceFutures.put(podName, requestResourceFuture); log.info("Creating new TaskManager pod with name and resource <{},{}>.", podName, parameters.getTaskManagerMemoryMB(), parameters.getTaskManagerCPU()); final CompletableFuture<Void> createPodFuture = podCreationCoolDown.thenCompose((ignore) -> kubeClient .map(client -> client.createTaskManagerPod(taskManagerPod)) <START> .orElse(CompletableFuture.completedFuture(null))); <END> FutureUtils.assertNoException( createPodFuture.handleAsync((ignore, exception) -> { if (exception != null) { log.warn("Could not create pod {}, exception: {}", podName, exception); tryResetPodCreationCoolDown(); CompletableFuture<KubernetesWorkerNode> future = requestResourceFutures.remove(taskManagerPod.getName()); if (future != null) { future.completeExceptionally(exception); } } else { log.info("Pod is created.", podName); } return null; }, getMainThreadExecutor())); return requestResourceFuture; }</code><technical_language>expecting client non-empty, I fail explicitly for empty case. for other occurrences</technical_language>

Target:
public CompletableFuture<KubernetesWorkerNode> requestResource(TaskExecutorProcessSpec taskExecutorProcessSpec) { final KubernetesTaskManagerParameters parameters = createKubernetesTaskManagerParameters(taskExecutorProcessSpec); final KubernetesPod taskManagerPod = KubernetesTaskManagerFactory.buildTaskManagerKubernetesPod(parameters); final String podName = taskManagerPod.getName(); final CompletableFuture<KubernetesWorkerNode> requestResourceFuture = new CompletableFuture<>(); requestResourceFutures.put(podName, requestResourceFuture); log.info("Creating new TaskManager pod with name and resource <{},{}>.", podName, parameters.getTaskManagerMemoryMB(), parameters.getTaskManagerCPU()); final CompletableFuture<Void> createPodFuture = podCreationCoolDown.thenCompose((ignore) -> getKubeClient().createTaskManagerPod(taskManagerPod)); FutureUtils.assertNoException( createPodFuture.handleAsync((ignore, exception) -> { if (exception != null) { log.warn("Could not create pod {}, exception: {}", podName, exception); tryResetPodCreationCoolDown(); CompletableFuture<KubernetesWorkerNode> future = requestResourceFutures.remove(taskManagerPod.getName()); if (future != null) { future.completeExceptionally(exception); } } else { log.info("Pod is created.", podName); } return null; }, getMainThreadExecutor())); return requestResourceFuture; }
Source:
<code>private void resolveIdentityInsertDelayable() { canIdentityInsertBeDelayed = true; if ( getEntityMetamodel().getIdentifierProperty().isIdentifierAssignedByInsert() ) { for ( NonIdentifierAttribute attribute : getEntityMetamodel().getProperties() ) { final Type attributeType = attribute.getType(); if ( attributeType.isAssociationType() ) { if ( attributeType.isEntityType() ) { Class<?> entityClass = attributeType.getReturnedClass(); if ( getMappedClass().equals( entityClass ) ) { canIdentityInsertBeDelayed = false; <START> } <END> } else if ( attributeType.isCollectionType() ) { final CollectionType collection = (CollectionType) attributeType; final CollectionPersister collectionPersister = getFactory().getMetamodel().collectionPersister( collection.getRole() ); if ( collectionPersister.isInverse() ) { final EntityPersister entityPersister = collectionPersister.getOwnerEntityPersister(); if ( collectionPersister.getOwnerEntityPersister().equals( this ) ) { final QueryableCollection queryableCollection = (QueryableCollection) collectionPersister; final IdentifierGenerator identifierGenerator = queryableCollection.getElementPersister().getIdentifierGenerator(); if ( ( identifierGenerator instanceof ForeignGenerator ) || ( identifierGenerator instanceof SequenceStyleGenerator ) ) { canIdentityInsertBeDelayed = false; } } } } } } } }</code><technical_language>Is this a problem attribute is a reference entity persisted? association embeddable refers entity persisted? check work for case. if association is a reference a entity of class? Could/should delay insert in this case? I suppose require persister track attributes (or sub-attributes) of class, checked if refer entity persisted. this improvement fixed later</technical_language>

Target:
private void resolveIdentityInsertDelayable() { canIdentityInsertBeDelayed = true; if ( getEntityMetamodel().getIdentifierProperty().isIdentifierAssignedByInsert() ) { for ( NonIdentifierAttribute attribute : getEntityMetamodel().getProperties() ) { if ( isTypeSelfReferencing( attribute.getType() ) ) { canIdentityInsertBeDelayed = false; } } } }