auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Response cloneVmFromSnapshot(VmStatic staticVm, Snapshots snapshots, ArrayList<DiskImage> diskInfoList) { <START> Guid sourceSnapshotId = Guid.createGuidFromString(snapshots.getSnapshots().get(0).getId()); <END> AddVmFromSnapshotParameters params = new AddVmFromSnapshotParameters(staticVm, diskInfoList, sourceSnapshotId); return performCreation(VdcActionType.AddVmFromSnapshot, params, new QueryIdResolver(VdcQueryType.GetVmByVmId, GetVmByVmIdParameters.class)); }</code><technical_language>remember: asGuid() instead</technical_language>

Target:
private Response cloneVmFromSnapshot(VmStatic staticVm, Snapshots snapshots, ArrayList<DiskImage> diskInfoList) { Guid sourceSnapshotId = asGuid(snapshots.getSnapshots().get(0).getId()); AddVmFromSnapshotParameters params = new AddVmFromSnapshotParameters(staticVm, diskInfoList, sourceSnapshotId); return performCreation(VdcActionType.AddVmFromSnapshot, params, new QueryIdResolver(VdcQueryType.GetVmByVmId, GetVmByVmIdParameters.class)); }
Source:
<code>@Test public void normalGet() throws Exception { Request request = new RequestBuilderHelper() .setMethod("GET") <START> .setPath("foo/bar/") END> .build(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getHeaders()).isEmpty(); assertThat(request.getUrl()).isEqualTo(URL + "foo/bar/"); assertThat(request.getBody()).isNull(); assertThat(request.getBodyParameters()).isNull(); }</code><technical_language>path starts '/'. If start '/', path. (You're accidentally '/' a separator authority path. '/' is a part of path.)</technical_language>

Target:
@Test public void normalGet() throws Exception { Request request = new Helper() .setMethod("GET") .setUrl("<LINK_1>") .setPath("/foo/bar/") .build(); assertThat(request.getMethod()).isEqualTo("GET"); assertThat(request.getHeaders()).isEmpty(); assertThat(request.getUrl()).isEqualTo("<LINK_0>"); assertThat(request.getBody()).isNull(); assertThat(request.getBodyParameters()).isEmpty(); }
Source:
<code>private synchronized BridgeHandler getDssBridgeHandler() { if (this.dssBridgeHandler == null) { Bridge bridge = getBridge(); if (bridge == null) { logger.debug("Bride cannot be found"); return null; } ThingHandler handler = bridge.getHandler(); if (handler instanceof BridgeHandler) { dssBridgeHandler = (BridgeHandler) handler; if (device == null) { <START> dssBridgeHandler.registerDeviceStatusListener(this); <END> } } else { return null; } } else if (device == null) { dssBridgeHandler.registerDeviceStatusListener(this); } return dssBridgeHandler; }</code><technical_language>Again: is a get method registering handlers</technical_language>

Target:
private synchronized BridgeHandler getDssBridgeHandler() { if (this.dssBridgeHandler == null) { Bridge bridge = getBridge(); if (bridge == null) { logger.debug("Bride cannot be found"); return null; } ThingHandler handler = bridge.getHandler(); if (handler instanceof BridgeHandler) { dssBridgeHandler = (BridgeHandler) handler; } else { return null; } } return dssBridgeHandler; }
Source:
<code>public String getAgentStatusReport(String pluginId, JobIdentifier jobIdentifier, String elasticAgentId) { final ElasticAgentPluginInfo pluginInfo = elasticAgentMetadataStore.getPluginInfo(pluginId); if (pluginInfo.getCapabilities().supportsAgentStatusReport()) { <START> ClusterProfile clusterProfile = jobInstanceSqlMapDao.loadPlan(jobIdentifier.getId()).getClusterProfile(); <END> return elasticAgentPluginRegistry.getAgentStatusReport(pluginId, jobIdentifier, elasticAgentId, clusterProfile.getConfigurationAsMap(true)); } throw new UnsupportedOperationException("Plugin does not support agent status report."); }</code><technical_language>is a possibility of ClusterProfile null job plan deleted soon job finishes. Calling clusterProfile.getConfigurationAsMap(true) null result in NullPointerException. Please verify :)</technical_language>

Target:
public String getAgentStatusReport(String pluginId, JobIdentifier jobIdentifier, String elasticAgentId) throws Exception { final ElasticAgentPluginInfo pluginInfo = elasticAgentMetadataStore.getPluginInfo(pluginId); if (pluginInfo.getCapabilities().supportsAgentStatusReport()) { JobPlan jobPlan = jobInstanceSqlMapDao.loadPlan(jobIdentifier.getId()); if (jobPlan != null) { ClusterProfile clusterProfile = jobPlan.getClusterProfile(); Map<String, String> clusterProfileConfigurations = (clusterProfile == null) ? Collections.emptyMap() : clusterProfile.getConfigurationAsMap(true); return elasticAgentPluginRegistry.getAgentStatusReport(pluginId, jobIdentifier, elasticAgentId, clusterProfileConfigurations); } throw new Exception(format("Could not fetch agent status report for agent %s as either the job running on the agent has been completed or the agent has been terminated.", elasticAgentId)); } throw new UnsupportedOperationException("Plugin does not support agent status report."); }
Source:
<code>public AsyncReader(TransactionImpl tx) { this.tx = tx; <START> getsQueue = new PriorityQueue<>(); <END> executorService = Executors.newSingleThreadExecutor(); }</code><technical_language>create a LinkedBlockingQueue</technical_language>

Target:
public AsyncReader(TransactionImpl tx) { this.tx = tx; asyncGetsQueue = new LinkedBlockingQueue<>(); executorService = Executors.newSingleThreadExecutor(); }
Source:
<code>public void handleMessage(final Message msg) { Stats stats = mStats.get(); <START> if (stats != null) { <END> synchronized (StatsHandler.class) { switch (msg.what) { case CACHE_HIT : stats.performCacheHit(); break; case CACHE_MISS : stats.performCacheMiss(); break; case BITMAP_DECODE_FINISHED : stats.performBitmapDecoded(msg.arg1); break; case BITMAP_TRANSFORMED_FINISHED : stats.performBitmapTransformed(msg.arg1); break; case REQUESTED_COMPLETED : break; default : Handler mainHandler = new Handler(Looper.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { throw new AssertionError("Unhandled stats message." + msg.what); } }); } } } }</code><technical_language>nit: I prefer if (stats == null) return do logic avoid indentation</technical_language>

Target:
@Override public void handleMessage(final Message msg) { Stats stats = statsRef.get(); if (stats == null) { return; } synchronized (StatsHandler.class) { switch (msg.what) { case CACHE_HIT : stats.performCacheHit(); break; case CACHE_MISS : stats.performCacheMiss(); break; case BITMAP_DECODE_FINISHED : stats.performBitmapDecoded(msg.arg1); break; case BITMAP_TRANSFORMED_FINISHED : stats.performBitmapTransformed(msg.arg1); break; case REQUESTED_COMPLETED : break; default : Handler mainHandler = new Handler(Looper.getMainLooper()); mainHandler.post(new Runnable() { @Override public void run() { throw new AssertionError("Unhandled stats message." + msg.what); } }); } } }
Source:
<code>public IntArrayList(int initialCapacity) { if (initialCapacity < 0) { <START> throw new IllegalArgumentException("Initial initialCapacity (" + initialCapacity + ") is negative"); <END> } else { array = new int[initialCapacity]; } }</code><technical_language>Initial capacity is negative: %d? Initial initialCapacity is repetitive</technical_language>

Target:
public IntArrayList(int initialCapacity) { if (initialCapacity < 0) { throw new IllegalArgumentException(String.format("Initial capacity '%s' is negative", initialCapacity)); } array = new int[initialCapacity]; }
Source:
<code>private boolean hasBeenInitialized(Symbol symbol) { VariableTree source = (VariableTree) getSemanticModel().getTree(symbol); <START> return source.initializer() != null; <END> }</code><technical_language>discussed, this test initializer is NewClassTree get reference object elsewhere</technical_language>

Target:
private boolean hasBeenInitialized(Symbol symbol) { ExpressionTree initializer = ((VariableTree) getSemanticModel().getTree(symbol)).initializer(); return initializer != null && initializer.is(Kind.NEW_CLASS); }
Source:
<code>public boolean hasNext() { if (recordCounter >= records.size()) { try { nextContainer(); <START> if (records.isEmpty()) <END> return false; } catch (Exception e) { throw new RuntimeEOFException(e); } } nextRecord = records.get(recordCounter++); return true; }</code><technical_language>nextContainer set container null clear records need change this if (container == null || records.isEmpty()) nextContainer call records.clear() null container is returned</technical_language>

Target:
public boolean hasNext() { if (container != null && container.isEOF()) return false ; if (container == null || recordCounter >= records.size()) { try { nextContainer(); if (records.isEmpty()) return false; } catch (Exception e) { throw new RuntimeEOFException(e); } } nextRecord = records.get(recordCounter++); return true; }
Source:
<code><START> @Override public void remove() { <END> throw new UnsupportedOperationException(); }</code><technical_language>override annotation a separate line (not of convention in this codebase)</technical_language>

Target:
public void remove() { throw new UnsupportedOperationException(); }
Source:
<code>private long executeSqlCountComputingResourcesForAccount(long accountId, String sqlCountComputingResourcesAllocatedToAccount) { <START> TransactionLegacy tx = TransactionLegacy.currentTxn() <END> try { PreparedStatement pstmt = tx.prepareAutoCloseStatement(sqlCountComputingResourcesAllocatedToAccount); pstmt.setLong(1, accountId); ResultSet rs = pstmt.executeQuery(); if (!rs.next()) { return 0L; } return rs.getLong("total"); } catch (SQLException e) { throw new CloudRuntimeException(e); } }</code><technical_language>@DaanHoogland missed ";" end of line 269</technical_language>

Target:
private long executeSqlCountComputingResourcesForAccount(long accountId, String sqlCountComputingResourcesAllocatedToAccount) { TransactionLegacy tx = TransactionLegacy.currentTxn(); try { PreparedStatement pstmt = tx.prepareAutoCloseStatement(sqlCountComputingResourcesAllocatedToAccount); pstmt.setLong(1, accountId); ResultSet rs = pstmt.executeQuery(); if (!rs.next()) { return 0L; } return rs.getLong("total"); } catch (SQLException e) { throw new CloudRuntimeException(e); } }
Source:
<code>public static void setup() throws Exception { Path cnfPath = FileSystems.getDefault().getPath("target/test-classes/hbase-site.xml"); Path cnf2Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site2.xml"); Path cnf3Path = FileSystems.getDefault().getPath("target/test-classes/hbase-site3.xml"); String absoluteDataPath = TEST_UTIL.getDataTestDir().toString(); String dataBasePath = System.getProperty(HBaseCommonTestingUtility.BASE_TEST_DIRECTORY_KEY, HBaseCommonTestingUtility.DEFAULT_BASE_TEST_DIRECTORY); String dataPath = absoluteDataPath.substring(absoluteDataPath.indexOf(dataBasePath)); newCnfPath = Paths.get(dataPath + "/hbase-site.xml"); newCnf2Path = Paths.get(dataPath + "/hbase-site2.xml"); newCnf3Path = Paths.get(dataPath + "/hbase-site3.xml"); Files.createDirectories(Paths.get(dataPath)); Files.copy(cnfPath, newCnfPath); Files.copy(cnf2Path, newCnf2Path); <START> Files.copy(cnf3Path, newCnf3Path); <END> TEST_UTIL.getConfiguration().addResource(TEST_UTIL.getDataTestDir("hbase-site.xml")); StartMiniClusterOption option = StartMiniClusterOption.builder().numMasters(2).build(); TEST_UTIL.startMiniCluster(option); TEST_UTIL.getMiniHBaseCluster().getRegionServer(0).getConfiguration(). addResource(TEST_UTIL.getDataTestDir("hbase-site.xml")); }</code><technical_language>Duped code. of sharing</technical_language>

Target:
public static void setup() throws Exception { setUpConfigurationFiles(TEST_UTIL); StartMiniClusterOption option = StartMiniClusterOption.builder().numMasters(2).build(); TEST_UTIL.startMiniCluster(option); addResourceToRegionServerConfiguration(TEST_UTIL); }
Source:
<code>public StudyRepository(Path pathToRepository, GitHandler gitHandler, ImportFormatPreferences importFormatPreferences, FileUpdateMonitor fileUpdateMonitor, SavePreferences savePreferences, BibEntryTypesManager bibEntryTypesManager) throws IOException, ParseException, GitAPIException { this.repositoryPath = pathToRepository; this.gitHandler = gitHandler; try { gitHandler.updateLocalRepository(); } catch (GitAPIException e) { <START> LOGGER.info("Updating repository from remote failed"); <END> } this.importFormatPreferences = importFormatPreferences; this.fileUpdateMonitor = fileUpdateMonitor; this.studyDefinitionBib = Path.of(repositoryPath.toString(), STUDY_DEFINITION_FILE_NAME); this.savePreferences = savePreferences; this.bibEntryTypesManager = bibEntryTypesManager; if (Files.notExists(repositoryPath)) { throw new IOException("The given repository does not exists."); } else if (Files.notExists(studyDefinitionBib)) { throw new IOException("The study definition file does not exist in the given repository."); } study = parseStudyFile(); this.setUpRepositoryStructure(); }</code><technical_language>suggestion LOGGER.error("Updating repository remote failed",e);</technical_language>

Target:
public StudyRepository(Path pathToRepository, GitHandler gitHandler, ImportFormatPreferences importFormatPreferences, FileUpdateMonitor fileUpdateMonitor, SavePreferences savePreferences, BibEntryTypesManager bibEntryTypesManager) throws IOException, ParseException, GitAPIException { this.repositoryPath = pathToRepository; this.gitHandler = gitHandler; try { gitHandler.updateLocalRepository(); } catch (GitAPIException e) { LOGGER.error("Updating repository from remote failed"); } this.importFormatPreferences = importFormatPreferences; this.fileUpdateMonitor = fileUpdateMonitor; this.studyDefinitionBib = Path.of(repositoryPath.toString(), STUDY_DEFINITION_FILE_NAME); this.savePreferences = savePreferences; this.bibEntryTypesManager = bibEntryTypesManager; if (Files.notExists(repositoryPath)) { throw new IOException("The given repository does not exists."); } else if (Files.notExists(studyDefinitionBib)) { throw new IOException("The study definition file does not exist in the given repository."); } study = parseStudyFile(); this.setUpRepositoryStructure(); }
Source:
<code>public void setPreProcessor(DataSetPreProcessor preProcessor) { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>This strike reasonable. add a field for call set :D</technical_language>

Target:
public void setPreProcessor(DataSetPreProcessor preProcessor) { this.preProcessor = preProcessor; }
Source:
<code>public void testUpdateServer() { assertDataCenterAvailable(dataCenter); Server updated = api.serverApi().updateServer( Server.Request.updatingBuilder() .id(testServer.id()) .dataCenterId(testServer.dataCenterId()) .name("apache-node") .ram(1024 * 2) .cores(2) .build()); <START> assertRequestCompleted(updated); <END> assertRequestCompleted(updated); assertNodeAvailable(ServerRef.create(dataCenter.id(), testServer.id())); assertDataCenterAvailable(dataCenter); assertNodeRunning(ServerRef.create(dataCenter.id(), testServer.id())); Server server = serverApi().getServer(dataCenter.id(), testServer.id()); assertEquals(server.properties().name(), "apache-node"); }</code><technical_language>Duplicated</technical_language>

Target:
public void testUpdateServer() { assertDataCenterAvailable(dataCenter); Server updated = api.serverApi().updateServer( Server.Request.updatingBuilder() .id(testServer.id()) .dataCenterId(testServer.dataCenterId()) .name("apache-node") .ram(1024 * 2) .cores(2) .build()); assertRequestCompleted(updated); assertNodeAvailable(ServerRef.create(dataCenter.id(), testServer.id())); assertDataCenterAvailable(dataCenter); assertNodeRunning(ServerRef.create(dataCenter.id(), testServer.id())); Server server = serverApi().getServer(dataCenter.id(), testServer.id()); assertEquals(server.properties().name(), "apache-node"); }
Source:
<code>public static @Nullable List<Long> extractSelectedItems(Map<String, Object> parameters) { Object selectedItemObject = parameters.get(SELECTED_ITEMS_KEY); if (selectedItemObject instanceof List<?>) { List<Long> selectedItems = new ArrayList<>(); List<?> selectedItemList = (List<?>) selectedItemObject; <START> if (!selectedItemList.isEmpty()) { if (selectedItemList.get(0) instanceof Long) { selectedItems = (List<Long>) selectedItemList; } else if (selectedItemList.get(0) instanceof Integer) { for (Integer time : (List<Integer>) selectedItemList) { selectedItems.add(time.longValue()); } } else { return null; } } <END> return selectedItems; } return null; }</code><technical_language>if (!selectedItemList.isEmpty()) { selectedItems = selectedItemList.stream().filter(o -> o instanceof Integer || o instanceof Long).map(o -> (Long) o).collect(Collectors.toList()); if (selectedItems.isEmpty()) { return null; } }</technical_language>

Target:
public static @Nullable List<Long> extractSelectedItems(Map<String, Object> parameters) { Object selectedItemObject = parameters.get(SELECTED_ITEMS_KEY); if (selectedItemObject instanceof List<?>) { return transformToLongList((List<?>) selectedItemObject); } return null; }
Source:
<code>public void findOneTest() throws Exception { context.turnOffAuthorisationSystem(); Community community = CommunityBuilder.createCommunity(context).withName("My community").build(); ResourcePolicy resourcePolicy = ResourcePolicyBuilder.createResourcePolicy(context).withDspaceObject(community) <START> .withAction(Constants.READ).withPolicyType(ResourcePolicy.TYPE_CUSTOM).withUser(admin).build(); <END> context.restoreAuthSystemState(); String authToken = getAuthToken(admin.getEmail(), password); getClient(authToken).perform(get("/api/authz/resourcepolicies/" + resourcePolicy.getID())) .andExpect(status().isOk()).andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", is( ResoucePolicyMatcher.matchResourcePolicy(resourcePolicy) ))) .andExpect(jsonPath("$._links.self.href", Matchers .containsString("/api/authz/resourcepolicies/" + resourcePolicy.getID()))); }</code><technical_language>I suggest create a resource policy for item related a normal eperson other admin</technical_language>

Target:
public void findOneTest() throws Exception { context.turnOffAuthorisationSystem(); EPerson eperson1 = EPersonBuilder.createEPerson(context) .withEmail("eperson1@mail.com") .withPassword("qwerty01") .build(); Community community = CommunityBuilder.createCommunity(context).withName("My community").build(); ResourcePolicy resourcePolicy = ResourcePolicyBuilder.createResourcePolicy(context) .withDspaceObject(community) .withAction(Constants.READ) .withUser(eperson1) .build(); context.restoreAuthSystemState(); String authToken = getAuthToken(eperson1.getEmail(), "qwerty01"); getClient(authToken).perform(get("/api/authz/resourcepolicies/" + resourcePolicy.getID())) .andExpect(status().isOk()).andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", is( ResoucePolicyMatcher.matchResourcePolicy(resourcePolicy) ))) .andExpect(jsonPath("$._links.self.href", Matchers .containsString("/api/authz/resourcepolicies/" + resourcePolicy.getID()))); }
Source:
<code>private void beginCommitAsync(CommitData cd, AsyncCommitObserver commitCallback, RowColumn primary) { if (updates.size() == 0) { deleteWeakRow(); commitCallback.committed(); return; } for (Map<Column, Bytes> cols : updates.values()) { stats.incrementEntriesSet(cols.size()); } Bytes primRow = null; Column primCol = null; if (primary != null) { primRow = primary.getRow(); primCol = primary.getColumn(); if (notification != null && !primary.equals(notification.getRowColumn())) { throw new IllegalArgumentException("Primary must be notification"); } } else if (notification != null) { primRow = notification.getRow(); primCol = notification.getColumn(); } else { outer: for (Entry<Bytes, Map<Column, Bytes>> entry : updates.entrySet()) { for (Entry<Column, Bytes> entry2 : entry.getValue().entrySet()) { if (!isReadLock(entry2.getValue())) { primRow = entry.getKey(); primCol = entry2.getKey(); break outer; } } } if (primRow == null) { deleteWeakRow(); commitCallback.committed(); return; } } cd.prow = primRow; Map<Column, Bytes> colSet = updates.get(cd.prow); cd.pcol = primCol; cd.pval = colSet.remove(primCol); if (colSet.size() == 0) { updates.remove(cd.prow); } cd.commitObserver = commitCallback; final ConditionalMutation pcm = prewrite(cd.prow, cd.pcol, cd.pval, cd.prow, cd.pcol, isTriggerRow(cd.prow)); CompletableFuture<Iterator<Result>> cfuture = cd.acw.apply(Collections.singletonList(pcm)); addCallback(cfuture, cd, (cd2, result) -> postLockPrimary(cd2, pcm, <START> Iterators.getOnlyElement((Iterator<Result>) result))); <END> }</code><technical_language>this type cast (Iterator<Result>) dropped adding type param addCallback</technical_language>

Target:
private void beginCommitAsync(CommitData cd, AsyncCommitObserver commitCallback, RowColumn primary) { if (updates.size() == 0) { deleteWeakRow(); commitCallback.committed(); return; } for (Map<Column, Bytes> cols : updates.values()) { stats.incrementEntriesSet(cols.size()); } Bytes primRow = null; Column primCol = null; if (primary != null) { primRow = primary.getRow(); primCol = primary.getColumn(); if (notification != null && !primary.equals(notification.getRowColumn())) { throw new IllegalArgumentException("Primary must be notification"); } } else if (notification != null) { primRow = notification.getRow(); primCol = notification.getColumn(); } else { outer: for (Entry<Bytes, Map<Column, Bytes>> entry : updates.entrySet()) { for (Entry<Column, Bytes> entry2 : entry.getValue().entrySet()) { if (!isReadLock(entry2.getValue())) { primRow = entry.getKey(); primCol = entry2.getKey(); break outer; } } } if (primRow == null) { deleteWeakRow(); commitCallback.committed(); return; } } cd.prow = primRow; Map<Column, Bytes> colSet = updates.get(cd.prow); cd.pcol = primCol; cd.pval = colSet.remove(primCol); if (colSet.size() == 0) { updates.remove(cd.prow); } cd.commitObserver = commitCallback; final ConditionalMutation pcm = prewrite(cd.prow, cd.pcol, cd.pval, cd.prow, cd.pcol, isTriggerRow(cd.prow)); CompletableFuture<Iterator<Result>> cfuture = cd.acw.apply(Collections.singletonList(pcm)); addCallback(cfuture, cd, result -> postLockPrimary(cd, pcm, Iterators.getOnlyElement(result))); }
Source:
<code>public void testHandlePermissionRequestResultForRequestAfterSaveCopyClickedPermissionGranted() { presenter.handlePermissionRequestResults(PERMISSION_EXTERNAL_STORAGE_SAVE_COPY, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, new int[] {PackageManager.PERMISSION_GRANTED}); <START> verify(presenter).saveCopyClicked(); <END> }</code><technical_language>@spy - I now. Please mockito verify presenter called internal function. check presenter right collaborating classes, in this case verify presenter calls interactor.saveCopy _not_ call navigator.askForPermission() again. mock/spy class test</technical_language>

Target:
public void testHandlePermissionRequestResultForRequestAfterSaveCopyClickedPermissionGranted() { presenter.handlePermissionRequestResults(PERMISSION_EXTERNAL_STORAGE_SAVE_COPY, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, new int[] {PackageManager.PERMISSION_GRANTED}); verify(interactor).saveCopy(any(SaveImageAsync.SaveImageCallback.class), eq(SAVE_IMAGE_DEFAULT)); }
Source:
<code>public void started() { log.info("Started the REST Web Service module"); <START> new SwaggerSpecificationCreator("host/openmrs/ws/rest").BuildJSON(); <END> }</code><technical_language>intentionally hard code above</technical_language>

Target:
public void started() { log.info("Started the REST Web Service module"); }
Source:
<code>public static void assertNotZipSlipVulnerable(String fileName) throws IOException { <START> if (fileName.startsWith(ZIP_SLIP_EXPRESSION)) throw new IOException("Vulnerable File Name"); <END> }</code><technical_language>Is this a sufficient check? if I pass ./../../something.important</technical_language>

Target:
public static void assertNotZipSlipVulnerable(String fileName) throws IOException { File destinationfile = new File(fileName); String canonicalDestinationFile = destinationfile.getCanonicalPath(); if (canonicalDestinationFile.startsWith(ZIP_SLIP_EXPRESSION)) { throw new IOException("Vulnerable File Name"); } }
Source:
<code>public KieContainerResource createContainer(String id, String containerId, KieContainerResource container) { ServerTemplate serverTemplate = this.templateStorage.load(id); if (serverTemplate == null) { throw new KieServerControllerException("KieServerInstance not found with id: " + id); } ContainerSpec containerSpec = serverTemplate.getContainerSpec(containerId); if (containerSpec != null) { throw new KieServerControllerException("KieContainer already exists with id: " + id); } <START> containerSpec = new ContainerSpec(); <END> containerSpec.setStatus(KieContainerStatus.STOPPED); containerSpec.setId(container.getContainerId()); containerSpec.setReleasedId(container.getReleaseId()); containerSpec.setServerTemplateKey(serverTemplate); containerSpec.setContainerName(container.getContainerId()); if (container.getScanner() != null) { RuleConfig ruleConfig = new RuleConfig(); ruleConfig.setPollInterval(container.getScanner().getPollInterval()); ruleConfig.setScannerStatus(container.getScanner().getStatus()); containerSpec.addConfig(Capability.RULE, ruleConfig); } serverTemplate.addContainerSpec(containerSpec); this.templateStorage.update(serverTemplate); container.setStatus(KieContainerStatus.STOPPED); return container; }</code><technical_language>empty constructor</technical_language>

Target:
public KieContainerResource createContainer(String id, String containerId, KieContainerResource container) { ServerTemplate serverTemplate = this.templateStorage.load(id); if (serverTemplate == null) { throw new KieServerControllerException("KieServerInstance not found with id: " + id); } ContainerSpec containerSpec = serverTemplate.getContainerSpec(containerId); if (containerSpec != null) { throw new KieServerControllerException("KieContainer already exists with id: " + id); } containerSpec = new ContainerSpec(container.getContainerId(), container.getContainerId(), serverTemplate, container.getReleaseId(), KieContainerStatus.STOPPED, new HashMap<Capability, ContainerConfig>()); if (container.getScanner() != null) { RuleConfig ruleConfig = new RuleConfig(); ruleConfig.setPollInterval(container.getScanner().getPollInterval()); ruleConfig.setScannerStatus(container.getScanner().getStatus()); containerSpec.addConfig(Capability.RULE, ruleConfig); } serverTemplate.addContainerSpec(containerSpec); this.templateStorage.update(serverTemplate); container.setStatus(KieContainerStatus.STOPPED); return container; }
Source:
<code>private static void validateGroupDuplicationInGroup(List<String> groups, List<String> parentGroups) throws RestAPIException { List<String> checkList = new ArrayList<String>(); for (String group : groups) { if (!checkList.contains(group)) { checkList.add(group); } else { if (log.isDebugEnabled()) { log.debug("duplicate group defined: " + group); } <START> throw new RestAPIException("Invalid Service Group definition, duplicate groups defined: " + <END> group); } if (parentGroups.contains(group)) { if (log.isDebugEnabled()) { log.debug("cyclic group behaviour identified [group-name]: " + group); } throw new RestAPIException("Invalid Service Group definition, cyclic group behaviour identified: " + group); } } }</code><technical_language>I changed term "service group" "cartridge group". case letters sentence</technical_language>

Target:
private static void validateGroupDuplicationInGroup(List<String> groups, List<String> parentGroups) throws InvalidCartridgeGroupDefinitionException { List<String> checkList = new ArrayList<String>(); for (String group : groups) { if (!checkList.contains(group)) { checkList.add(group); } else { if (log.isDebugEnabled()) { log.debug("duplicate group defined: " + group); } throw new InvalidCartridgeGroupDefinitionException("Invalid cartridge group definition, " + "duplicate groups defined: " + group); } if (parentGroups.contains(group)) { if (log.isDebugEnabled()) { log.debug("cyclic group behaviour identified [group-name]: " + group); } throw new InvalidCartridgeGroupDefinitionException("Invalid cartridge group definition, " + "cyclic group behaviour identified: " + group); } } }
Source:
<code>public CsvSchema csvSchema() { CsvMapper csvMapper = new CsvMapper(); csvMapper.disable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY); CsvSchema entrySchema = csvMapper.schemaFor(Entry.class); CsvSchema.Builder schemaBuilder = entrySchema.rebuild(); <START> for (String value : getRegister().getFields()) { <END> schemaBuilder.addColumn(value, CsvSchema.ColumnType.STRING); } return schemaBuilder.build(); }</code><technical_language>this method is repeated in 3 4 separate places. is time remove this duplication somehow</technical_language>

Target:
public CsvSchema csvSchema() { return Record.csvSchema(getRegister().getFields()); }
Source:
<code>public void invite(final String friend) throws IOException { final RestResponse response = this.request .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .rel("/page/links/link[@rel='invite']/@href") .method(Request.POST) .body().formParam("name", friend).back() .fetch() .as(RestResponse.class); if (response.status() == HttpURLConnection.HTTP_MOVED_PERM && response.cookie(RtFriends.COOKIE_RS_FLASH).getValue() .startsWith("incorrect+alias") ) { throw new Friends.UnknownAliasException( response.cookie(RtFriends.COOKIE_RS_FLASH).getValue() ); } <START> if (response.status() != HttpURLConnection.HTTP_SEE_OTHER) { <END> throw new IOException( String.format( "HTTP response status is not equal to %d", HttpURLConnection.HTTP_SEE_OTHER ) ); } Logger.info(this, "friend '%s' invited", friend); }</code><technical_language>@dmzaytsev test this condition well</technical_language>

Target:
public void invite(final String friend) throws IOException { final RestResponse response = this.request .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .rel("/page/links/link[@rel='invite']/@href") .method(Request.POST) .body().formParam("name", friend).back() .fetch() .as(RestResponse.class); if (response.status() == HttpURLConnection.HTTP_MOVED_PERM && response.cookie(RtFriends.COOKIE_RS_FLASH).getValue() .startsWith("incorrect+alias") ) { throw new Friends.UnknownAliasException( response.cookie(RtFriends.COOKIE_RS_FLASH).getValue() ); } response.assertStatus(HttpURLConnection.HTTP_SEE_OTHER); Logger.info(this, "friend '%s' invited", friend); }
Source:
<code>public ResultScanner adapt( final com.google.cloud.bigtable.grpc.scanner.ResultScanner<Row> bigtableResultScanner) { return new AbstractClientScanner() { @Override public Result next() throws IOException { Row row = bigtableResultScanner.next(); if (row == null) { return null; } return rowAdapter.adaptResponse(row); } @Override public void close() { try { bigtableResultScanner.close(); } catch (IOException ioe) { throw Throwables.propagate(ioe); } } <START> public boolean renewLease() { <END> return false; } }; }</code><technical_language>Add doc Add @Override</technical_language>

Target:
public ResultScanner adapt( final com.google.cloud.bigtable.grpc.scanner.ResultScanner<Row> bigtableResultScanner) { return new AbstractClientScanner() { @Override public Result next() throws IOException { Row row = bigtableResultScanner.next(); if (row == null) { return null; } return rowAdapter.adaptResponse(row); } @Override public void close() { try { bigtableResultScanner.close(); } catch (IOException ioe) { throw Throwables.propagate(ioe); } } public boolean renewLease() { throw new UnsupportedOperationException("renewLease"); } }; }
Source:
<code><START> public String getCSSName() { <END> return mCSSName; }</code><technical_language>this final, specific intention is _not_ allow derived classes override this behavior</technical_language>

Target:
public final String getCSSName() { return mCSSName; }
Source:
<code>public void testScenarios() throws IOException { String testResourcesPath = getClass().getClassLoader().getResource(".").getPath(); <START> System.out.println(testResourcesPath); <END> TestScenariosFinder testScenariosFinder = new TestScenariosFinder(testResourcesPath); List<TestScenario> testScenarios = testScenariosFinder.getScenarios(); TestScenarioRunner caseRunner = new TestScenarioRunner(9080); int successfulScenarios = 0; int failedScenarios = 0; for (TestScenario testScenario: testScenarios) { if (testScenario.enabledTests() == 0) { continue; } int successfulTestCases = 0; try { successfulTestCases = caseRunner.run(testScenario); } catch (Throwable throwable) { throwable.printStackTrace(); System.out.print("Exception while running test scenario: " + testScenario); } if (successfulTestCases == testScenario.enabledTests()) { System.out.println("\nScenario success: " + testScenario + "\n"); System.out.println("Number of successful test cases: " + successfulTestCases); successfulScenarios++; } else { System.out.println("\nScenario failed: " + testScenario + "\n"); System.out.println("Number of failed test cases: " + (testScenario.enabledTests() - successfulTestCases)); failedScenarios++; } } System.out.println("\n\nScenarios results:\nSuccessful: " + successfulScenarios + ", Failed: " + failedScenarios + "\n\n"); if (failedScenarios > 0) { Assert.fail(); } }</code><technical_language>Left over</technical_language>

Target:
public void testScenarios() throws IOException { String testResourcesPath = getClass().getClassLoader().getResource(".").getPath(); TestScenariosFinder testScenariosFinder = new TestScenariosFinder(testResourcesPath); List<TestScenario> testScenarios = testScenariosFinder.getScenarios(); TestScenarioRunner caseRunner = new TestScenarioRunner(9080); int successfulScenarios = 0; int failedScenarios = 0; for (TestScenario testScenario: testScenarios) { if (testScenario.enabledTests() == 0) { continue; } int successfulTestCases = 0; try { successfulTestCases = caseRunner.run(testScenario); } catch (Throwable throwable) { throwable.printStackTrace(); System.out.print("Exception while running test scenario: " + testScenario); } if (successfulTestCases == testScenario.enabledTests()) { System.out.println("\nScenario success: " + testScenario + "\n"); System.out.println("Number of successful test cases: " + successfulTestCases); successfulScenarios++; } else { System.out.println("\nScenario failed: " + testScenario + "\n"); System.out.println("Number of failed test cases: " + (testScenario.enabledTests() - successfulTestCases)); failedScenarios++; } } System.out.println("\n\nScenarios results:\nSuccessful: " + successfulScenarios + ", Failed: " + failedScenarios + "\n\n"); if (failedScenarios > 0) { Assert.fail(); } }
Source:
<code>public void disable() throws IOException { <START> throw new IllegalStateException("does not support disable/enable"); <END> }</code><technical_language>IOException supported here</technical_language>

Target:
public void disable() throws IOException { throw new IOException("does not support disable/enable"); }
Source:
<code>public synchronized void sendQueuedEvents(KeenProject project, KeenCallback callback) { if (!isActive) { handleLibraryInactive(callback); return; } if (project == null && defaultProject == null) { handleFailure(null, new IllegalStateException("No project specified, but no default project found")); return; } if (!isNetworkConnected()) { KeenLogging.log("Not sending events because there is no network connection. " + "Events will be retried next time `sendQueuedEvents` is called."); <START> return; <END> } KeenProject useProject = (project == null ? defaultProject : project); try { String projectId = useProject.getProjectId(); Map<String, List<Object>> eventHandles = eventStore.getHandles(projectId); Map<String, List<Map<String, Object>>> events = buildEventMap(eventHandles); String response = publishAll(useProject, events); if (response != null) { try { handleAddEventsResponse(eventHandles, response); } catch (Exception e) { KeenLogging.log("Error handling response to batch publish: " + e.getMessage()); } } handleSuccess(callback); } catch (Exception e) { handleFailure(callback, e); } }</code><technical_language>need a handleFailure here. return calling success failure, is a violation of callback contract</technical_language>

Target:
public synchronized void sendQueuedEvents(KeenProject project, KeenCallback callback) { if (!isActive) { handleLibraryInactive(callback); return; } if (project == null && defaultProject == null) { handleFailure(null, new IllegalStateException("No project specified, but no default project found")); return; } if (!isNetworkConnected()) { KeenLogging.log("Not sending events because there is no network connection. " + "Events will be retried next time `sendQueuedEvents` is called."); handleFailure(callback, new Exception("Network not connected.")); return; } KeenProject useProject = (project == null ? defaultProject : project); try { String projectId = useProject.getProjectId(); Map<String, List<Object>> eventHandles = eventStore.getHandles(projectId); Map<String, List<Map<String, Object>>> events = buildEventMap(eventHandles); String response = publishAll(useProject, events); if (response != null) { try { handleAddEventsResponse(eventHandles, response); } catch (Exception e) { KeenLogging.log("Error handling response to batch publish: " + e.getMessage()); } } handleSuccess(callback); } catch (Exception e) { handleFailure(callback, e); } }
Source:
<code>private boolean isRemoveCommandAvailable(List<DiskImage> disks) { if (disks.stream().anyMatch(d -> d.getImageStatus() == ImageStatus.LOCKED || <START> (d.isOvfStore() && d.getImageStatus() != ImageStatus.ILLEGAL))) <END> { return false; } return true; }</code><technical_language>This change for DiskListModel</technical_language>

Target:
private boolean isRemoveCommandAvailable(List<DiskImage> disks) { return disks.stream().noneMatch(d -> d.getImageStatus() == ImageStatus.LOCKED || (d.isOvfStore() && d.getImageStatus() != ImageStatus.ILLEGAL))); }
Source:
<code>private EnvVars getEnvVars() throws IOException, InterruptedException { <START> return new EnvVars(build.getEnvironment(listener)).overrideAll(dockerEnv.env()); <END> }</code><technical_language>sense cache result</technical_language>

Target:
private EnvVars getEnvVars() throws IOException, InterruptedException { if (envVars == null) { envVars = new EnvVars(build.getEnvironment(listener)).overrideAll(dockerEnv.env()); } return envVars; }
Source:
<code>public String toString() { return Objects.toStringHelper(this).add("date", date).add("state", state).add("entityId", entityId) <START> .add("appId", applicationId).add("entitlementContext", user).toString(); <END> }</code><technical_language>add("user", user) instead</technical_language>

Target:
public String toString() { return Objects.toStringHelper(this) .add("date", date) .add("state", state) .add("entityId", entityId) .add("appId", applicationId) .add("user", user) .toString(); }
Source:
<code><START> public static int get(final String key) {if(!map.containsKey(key)) android.util.Log.e("AssignmentString", key); <END> return map.containsKey(key) ? map.get(key) : R.string.na; }</code><technical_language>Hm, formatting this line. Do want debug output</technical_language>

Target:
public static int get(final String key) { return map.containsKey(key) ? map.get(key) : R.string.na; }
Source:
<code>public void close() { PrivilegedAction<Void> closeAction = () -> { this.executor.shutdown(); return null; }; <START> if (System.getSecurityManager() == null) { <END> closeAction.run(); } else { AccessController.doPrivileged(closeAction); } }</code><technical_language>leverage org.wildfly.security.manager.WildFlySecurityManager method here</technical_language>

Target:
public void close() { WildFlySecurityManager.doUnchecked((PrivilegedAction<Void>) () -> { this.executor.shutdown(); return null; }); }
Source:
<code>public Observable<Address> createAddress(final Address address) { <START> if (customerService.getCustomerToken() == null) { <END> throw new IllegalStateException("customer must be logged in"); } if (address == null) { throw new NullPointerException("address cannot be null"); } return retrofitService .createAddress(customerService.getCustomerToken().getCustomerId(), new AddressWrapper(address)) .doOnNext(new RetrofitSuccessHttpStatusCodeHandler<>()) .compose(new UnwrapRetrofitBodyTransformer<AddressWrapper, Address>()) .onErrorResumeNext(new BuyClientExceptionHandler<Address>()) .observeOn(callbackScheduler); }</code><technical_language>extract this local variable: CustomerToken customerToken = customerService.getCustomerToken() in createAddress avoid race condition</technical_language>

Target:
public Observable<Address> createAddress(final Address address) { CustomerToken customerToken = customerService.getCustomerToken(); if (customerToken == null) { throw new IllegalStateException("customer must be logged in"); } if (address == null) { throw new NullPointerException("address cannot be null"); } return retrofitService .createAddress(customerToken.getCustomerId(), new AddressWrapper(address)) .doOnNext(new RetrofitSuccessHttpStatusCodeHandler<>()) .compose(new UnwrapRetrofitBodyTransformer<AddressWrapper, Address>()) .onErrorResumeNext(new BuyClientExceptionHandler<Address>()) .observeOn(callbackScheduler); }
Source:
<code>public void setBuffers(@Nonnull ChromatographyInfo[] rtBuffer, @Nonnull float[] intensityBuffer, int newSize) { if (rtBuffer.length != intensityBuffer.length) { throw new IllegalArgumentException( "The length of the rt and intensity arrays must be equal"); } for (int pos = 1; pos < newSize; pos++) { if (rtBuffer[pos - 1].compareTo(rtBuffer[pos]) >= 0) <START> throw (new MSDKRuntimeException( <END> "The RT array is not properly sorted. It should be sorted from lowest to highest.")); } this.rtBuffer = rtBuffer; this.intensityBuffer = intensityBuffer; this.size = newSize; }</code><technical_language>I agree. Also, comparison > >=. (Alternatively, previous comparison change operator < )</technical_language>

Target:
public void setBuffers(@Nonnull ChromatographyInfo[] rtBuffer, @Nonnull float[] intensityBuffer, int newSize) { if (rtBuffer.length != intensityBuffer.length) { throw new IllegalArgumentException( "The length of the rt and intensity arrays must be equal"); } for (int pos = 1; pos < newSize; pos++) { if (rtBuffer[pos - 1].compareTo(rtBuffer[pos]) > 0) throw (new MSDKRuntimeException( "The RT array is not properly sorted. It should be sorted from lowest to highest.")); } this.rtBuffer = rtBuffer; this.intensityBuffer = intensityBuffer; this.size = newSize; }
Source:
<code>public Optional<Argument> find(String name, StatementContext ctx) { if (name.startsWith(prefix)) { String propertyName = name.substring(prefix.length()); for (PropertyDescriptor descriptor : info.getPropertyDescriptors()) { if (propertyName.equals(descriptor.getName())) { Method getter = descriptor.getReadMethod(); if (getter == null) { throw new UnableToCreateStatementException(String.format("No getter method found for " + "bean property [%s] on [%s]", propertyName, bean), ctx); } try { Type propertyType = getter.getGenericReturnType(); Object propertyValue = getter.invoke(bean); <START> Argument argument = ctx.findArgumentFor(propertyType, propertyValue) <END> .orElseThrow(() -> new UnableToCreateStatementException( String.format("No argument factory registered for type [%s] for bean property [%s] on [%s]", propertyType, propertyName, bean), ctx)); return Optional.of(argument); } catch (IllegalAccessException e) { throw new UnableToCreateStatementException(String.format("Access exception invoking getter for " + "bean property [%s] on [%s]", propertyName, bean), e, ctx); } catch (InvocationTargetException e) { throw new UnableToCreateStatementException(String.format("Invocation target exception invoking " + "getter for bean property [%s] on [%s]", propertyName, bean), e, ctx); } } } } return Optional.empty(); }</code><technical_language>I explicit check argument is present is extracting optional present Optional. java Optional<Argument> argument = ctx.findArgumentFor(propertyType, propertyValue); if (!argument.isPresent()) { throw new UnableToCreateStatementException( String.format("No argument factory registered for type [%s] for bean property [%s] [%s]", propertyType, propertyName, bean), ctx); } return argument;</technical_language>

Target:
public Optional<Argument> find(String name, StatementContext ctx) { if (name.startsWith(prefix)) { String propertyName = name.substring(prefix.length()); for (PropertyDescriptor descriptor : info.getPropertyDescriptors()) { if (propertyName.equals(descriptor.getName())) { Method getter = descriptor.getReadMethod(); if (getter == null) { throw new UnableToCreateStatementException(String.format("No getter method found for " + "bean property [%s] on [%s]", propertyName, bean), ctx); } try { Type propertyType = getter.getGenericReturnType(); Object propertyValue = getter.invoke(bean); Optional<Argument> argument = ctx.findArgumentFor(propertyType, propertyValue); if (!argument.isPresent()) { throw new UnableToCreateStatementException( String.format("No argument factory registered for type [%s] for bean property [%s] on [%s]", propertyType, propertyName, bean), ctx); } return argument; } catch (IllegalAccessException e) { throw new UnableToCreateStatementException(String.format("Access exception invoking getter for " + "bean property [%s] on [%s]", propertyName, bean), e, ctx); } catch (InvocationTargetException e) { throw new UnableToCreateStatementException(String.format("Invocation target exception invoking " + "getter for bean property [%s] on [%s]", propertyName, bean), e, ctx); } } } } return Optional.empty(); }
Source:
<code>public void insertLocator(Locator locator) throws IOException { Session session = DatastaxIO.getSession(); long shard = (long) Util.getShard(locator.toString()); BoundStatement bs = putValue.bind(shard, locator.toString(), ""); Timer.Context timer = Instrumentation.getWriteTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); try { <START> session.execute(bs); <END> } finally { timer.stop(); } }</code><technical_language>BoundStatement part part of timer execution</technical_language>

Target:
public void insertLocator(Locator locator) throws IOException { Session session = DatastaxIO.getSession(); long shard = (long) Util.getShard(locator.toString()); Timer.Context timer = Instrumentation.getWriteTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); try { BoundStatement bs = putValue.bind(shard, locator.toString(), ""); session.execute(bs); } finally { timer.stop(); } }
Source:
<code>public void setActiveEditor(IEditorPart editor) { ActionRegistry registry = editor.getAdapter(ActionRegistry.class); <START> IActionBars bars = getActionBars(); for (String id : globalActionKeys) { <END> setGlobalActionHandler(registry, bars, id); } super.setActiveEditor(editor); }</code><technical_language>setGlobalActionHandler method</technical_language>

Target:
public void setActiveEditor(IEditorPart editor) { setGlobalActionHandler(editor.getAdapter(ActionRegistry.class)); super.setActiveEditor(editor); }
Source:
<code>protected void handleResult(ImportKeyResult result) { String intentAction = getIntent().getAction(); if (ACTION_IMPORT_KEY_FROM_KEYSERVER_AND_RETURN_RESULT.equals(intentAction) || ACTION_IMPORT_KEY_FROM_FILE_AND_RETURN.equals(intentAction)) { Intent intent = new Intent(); intent.putExtra(ImportKeyResult.EXTRA_RESULT, result); setResult(RESULT_OK, intent); finish(); return; } if (result.isOkNew() || result.isOkUpdated()) { <START> Preferences prefs = Preferences.getPreferences(this); <END> prefs.setFirstTime(false); Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); return; } result.createNotify(ImportKeysActivity.this) .show((ViewGroup) findViewById(R.id.import_snackbar)); }</code><technical_language>extract method please</technical_language>

Target:
protected void handleResult(ImportKeyResult result) { String intentAction = getIntent().getAction(); if (ACTION_IMPORT_KEY_FROM_KEYSERVER_AND_RETURN_RESULT.equals(intentAction) || ACTION_IMPORT_KEY_FROM_FILE_AND_RETURN.equals(intentAction)) { Intent intent = new Intent(); intent.putExtra(ImportKeyResult.EXTRA_RESULT, result); setResult(RESULT_OK, intent); finish(); } else if (result.isOkNew() || result.isOkUpdated()) { Preferences.getPreferences(this).setFirstTime(false); Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } else { result.createNotify(ImportKeysActivity.this) .show((ViewGroup) findViewById(R.id.import_snackbar)); } }