auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setUp() throws Exception { Map<String, Integer> samplesPosition = new HashMap<>(); samplesPosition.put("sample1", 123); VARIANT_SOURCE_ENTITY.setSamplesPosition(samplesPosition); List<VariantSourceEntity> variantSourceEntities = Collections.singletonList(VARIANT_SOURCE_ENTITY); given(variantSourceEntityRepository.findByFileIdIn(eq(Collections.singletonList("fileId")), any())) .willReturn(variantSourceEntities); given(variantSourceEntityRepository.countByFileIdIn(eq(Collections.singletonList("fileId")))) <START> .willReturn(1L); <END> }</code><technical_language>Replacing 1L variantSourceEntities.size() ensure if collection size changes, mocked data sense</technical_language>

Target:
public void setUp() throws Exception { VariantSourceEntity variantSourceEntity = new VariantSourceEntity("fileId", "fileName", "studyId", "studyName", VariantStudy.StudyType.CASE, VariantSource.Aggregation.NONE, null, null, null); Map<String, Integer> samplesPosition = new HashMap<>(); samplesPosition.put("sample1", 123); variantSourceEntity.setSamplesPosition(samplesPosition); List<VariantSourceEntity> variantSourceEntities = Collections.singletonList(variantSourceEntity); given(variantSourceEntityRepository.findByFileIdIn(eq(Collections.singletonList("fileId")), any())) .willReturn(variantSourceEntities); given(variantSourceEntityRepository.countByFileIdIn(eq(Collections.singletonList("fileId")))) .willReturn(Long.valueOf(variantSourceEntities.size())); }
Source:
<code>public void onMockCreated(Object mock, MockCreationSettings settings) { this.mocks.put(mock, settings); settings.getStubbingLookUpListeners().add(new StubbingLookUpListener() { public void onStubbingLookUp(Invocation invocation, MatchableInvocation stubbingFound) { if (stubbingFound == null) { List<Invocation> matchingStubbings = new LinkedList<Invocation>(); Collection<Stubbing> stubbings = mockingDetails(invocation.getMock()).getStubbings(); for (Stubbing s : stubbings) { if (!s.wasUsed() && s.getInvocation().getMethod().getName().equals(invocation.getMethod().getName())) { <START> matchingStubbings.add(s.getInvocation()); <END> } } if (!matchingStubbings.isEmpty()) { Reporter.potentialStubbingProblemByJUnitRule(invocation, matchingStubbings); } } else { invocation.markVerified(); } } }); }</code><technical_language>Is enough compare method name</technical_language>

Target:
public void onMockCreated(Object mock, MockCreationSettings settings) { this.mocks.put(mock, settings); ((CreationSettings) settings).getStubbingLookupListeners().add(new StubbingLookupListener() { public void onStubbingLookup(Invocation invocation, MatchableInvocation stubbingFound) { if (stubbingFound == null) { List<Invocation> argMismatchStubbings = potentialArgMismatches(invocation); if (!argMismatchStubbings.isEmpty()) { Reporter.potentialStubbingProblemByJUnitRule(invocation, argMismatchStubbings); } } else { invocation.markVerified(); } } }); }
Source:
<code>private void notifyListeners(Repository repository, IndexDiffData indexDiffData) { for (IndexDiffChangedListener listener : listeners) { SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { listener.indexDiffChanged(repository, indexDiffData); } <START> @Override public void handleException(Throwable exception) { } <END> }); } }</code><technical_language>Darn, I overlooked that. worth creating package org.eclipse.egit.core.internal; public final class SafeRunnable { public static void run(Runner code) { SafeRunner.run(code); } @FunctionalInterface public interface Runner extends ISafeRunnable { @Override default void handleException(Throwable exception) { // logged SafeRunner } } } do simply SafeRunnable.run(() -> listener.indexDiffChanged(repository, indexDiffData));</technical_language>

Target:
private void notifyListeners(Repository repository, IndexDiffData indexDiffData) { for (IndexDiffChangedListener listener : listeners) { SafeRunnable.run( () -> listener.indexDiffChanged(repository, indexDiffData)); } }
Source:
<code><START> public void validateName(String name) { <END> if (name == null) { throw new IllegalArgumentException("null bucket name"); } if (name.length() < 3 || name.length() > 63) { throw new IllegalArgumentException( name + " : " + "bucket name must be at least 3 and no more than 63 characters long"); } if (name.contains("..")) { String msg = "bucket name cannot contain successive periods. For more information refer " + "<LINK_0>"; throw new IllegalArgumentException(name + " : " + msg); } if (!name.matches("^[a-z0-9][a-z0-9\\.\\-]+[a-z0-9]$")) { String msg = "bucket name does not follow Amazon S3 standards. For more information refer " + "<LINK_0>"; throw new IllegalArgumentException(name + " : " + msg); } }</code><technical_language>this static method</technical_language>

Target:
public static void validateName(String name) { if (name == null) { throw new IllegalArgumentException("null bucket name"); } if (name.length() < 3 || name.length() > 63) { throw new IllegalArgumentException( name + " : " + "bucket name must be at least 3 and no more than 63 characters long"); } if (name.contains("..")) { String msg = "bucket name cannot contain successive periods. For more information refer " + "<LINK_0>"; throw new IllegalArgumentException(name + " : " + msg); } if (!name.matches("^[a-z0-9][a-z0-9\\.\\-]+[a-z0-9]$")) { String msg = "bucket name does not follow Amazon S3 standards. For more information refer " + "<LINK_0>"; throw new IllegalArgumentException(name + " : " + msg); } }
Source:
<code>public DB getDB() { <START> return db != null ? db : mongoClient.getDB(database.getName()); <END> }</code><technical_language>I point in making db lazily created. expensive operation</technical_language>

Target:
public DB getDB() { return db; }
Source:
<code>public void run() { errorGobbler.start(); inputGobbler.start(); try { while(!stopped) { try { process.exitValue(); stop(); } catch(IllegalThreadStateException itse) } <START> } catch(NullPointerException npe) <END> }</code><technical_language>catch NPE ? do null check for null if/where needed remove NPE check. catching ignoring NPE ignore possibility of smth initialized a null</technical_language>

Target:
public void run() { errorGobbler.start(); inputGobbler.start(); try { process.waitFor(); } catch (InterruptedException e) stop(); }
Source:
<code>private DashboardInfo findProjectDefaultDashboard(ProjectState projectState) { final Project.NameKey projectName = projectState.getProject().getNameKey(); Project.NameKey parent; DashboardInfo info; Set<Project.NameKey> seen = new HashSet<Project.NameKey>(); seen.add(projectName); boolean considerLocal = true; do { info = loadProjectDefaultDashboard(projectState, considerLocal); if (info != null) { <START> replaceTokens(info, projectName.get()); <END> return info; } considerLocal = false; parent = projectState.getProject().getParent(allProjects); projectState = projectCache.get(parent); } while (projectState != null && seen.add(parent)); replaceTokens(info, projectName.get()); return info; }</code><technical_language>this method is in next change</technical_language>

Target:
private DashboardInfo findProjectDefaultDashboard(ProjectState projectState) { final Project.NameKey projectName = projectState.getProject().getNameKey(); Project.NameKey parent; DashboardInfo info; Set<Project.NameKey> seen = new HashSet<Project.NameKey>(); seen.add(projectName); boolean considerLocal = true; do { info = loadProjectDefaultDashboard(projectState, considerLocal); if (info != null) { return info; } considerLocal = false; parent = projectState.getProject().getParent(allProjects); projectState = projectCache.get(parent); } while (projectState != null && seen.add(parent)); return info; }
Source:
<code>@BeforeClass public static void beforeClass() throws Exception { pathToAppiumNodeInProperties = System.getProperty(APPIUM_PATH); for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { InetAddressValidator validator = InetAddressValidator.getInstance(); testIP = inetAddress.getHostAddress().toString(); if (validator.isValid(testIP)) { break; } testIP = null; } } <START> if (testIP != null) { <END> break; } } }</code><technical_language>I assume this in a separate private method save lines of code (break -> return) improve readability</technical_language>

Target:
@BeforeClass public static void beforeClass() throws Exception { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); if ((testIP = getLocalIP(intf)) != null) { break; } } }
Source:
<code>private boolean propagate(Map<CfgBlock, DefinedVariables> definedVariablesPerBlock) { block.predecessors().stream() .map(definedVariablesPerBlock::get) <START> .filter(Objects::nonNull) <END> .map(DefinedVariables::getOut) .forEach(predecessorOuts -> in = join(in, predecessorOuts)); Map<Symbol, VariableDefinition> newOut = new HashMap<>(in); kill.forEach(symbol -> newOut.put(symbol, VariableDefinition.DEFINED)); boolean outHasChanged = !newOut.equals(out); out = newOut; return outHasChanged; }</code><technical_language>useless</technical_language>

Target:
private boolean propagate(Map<CfgBlock, DefinedVariables> definedVariablesPerBlock) { block.predecessors().stream() .map(definedVariablesPerBlock::get) .map(DefinedVariables::getOut) .forEach(predecessorOuts -> in = join(in, predecessorOuts)); Map<Symbol, VariableDefinition> newOut = new HashMap<>(in); kill.forEach(symbol -> newOut.put(symbol, VariableDefinition.DEFINED)); boolean outHasChanged = !newOut.equals(out); out = newOut; return outHasChanged; }
Source:
<code>public void testPushSimple() throws Exception { JGitTestUtil.writeTrashFile(tdb.getRepository(), "a.bin", "1234567"); git.add().addFilepattern("a.bin").call(); RevCommit commit = git.commit().setMessage("add lfs blob").call(); git.push().call(); ObjectId id = commit.getId(); try(RevWalk walk = new RevWalk(rdb)) { RevCommit rc = walk.parseCommit(id); try (TreeWalk tw = new TreeWalk(walk.getObjectReader())) { tw.addTree(rc.getTree()); tw.setFilter(PathFilter.create("a.bin")); tw.next(); assertEquals(tw.getPathString(), "a.bin"); ObjectLoader ldr = walk.getObjectReader() .open(tw.getObjectId(0), Constants.OBJ_BLOB); try(InputStream is = ldr.openStream()) { assertEquals( "version <LINK_0>\noid sha256:8bb0cf6eb9b17d0f7d22b456f121257dc1254e1f01665370476383ea776df414\nsize 7\n", new String(IO .readWholeStream(is, (int) ldr.getSize()) .array())); } } } <START> assertEquals( <END> "[POST /lfs/objects/batch 200, PUT /lfs/objects/8bb0cf6eb9b17d0f7d22b456f121257dc1254e1f01665370476383ea776df414 200]", server.getRequests().toString()); }</code><technical_language>check content arrived</technical_language>

Target:
public void testPushSimple() throws Exception { JGitTestUtil.writeTrashFile(localDb.getRepository(), "a.bin", "1234567"); git.add().addFilepattern("a.bin").call(); RevCommit commit = git.commit().setMessage("add lfs blob").call(); git.push().call(); ObjectId id = commit.getId(); try (RevWalk walk = new RevWalk(remoteDb)) { RevCommit rc = walk.parseCommit(id); try (TreeWalk tw = new TreeWalk(walk.getObjectReader())) { tw.addTree(rc.getTree()); tw.setFilter(PathFilter.create("a.bin")); tw.next(); assertEquals(tw.getPathString(), "a.bin"); ObjectLoader ldr = walk.getObjectReader() .open(tw.getObjectId(0), Constants.OBJ_BLOB); try(InputStream is = ldr.openStream()) { assertEquals( "version <LINK_0>\noid sha256:8bb0cf6eb9b17d0f7d22b456f121257dc1254e1f01665370476383ea776df414\nsize 7\n", new String(IO .readWholeStream(is, (int) ldr.getSize()) .array())); } } } assertEquals( "[POST /lfs/objects/batch 200, PUT /lfs/objects/8bb0cf6eb9b17d0f7d22b456f121257dc1254e1f01665370476383ea776df414 200]", server.getRequests().toString()); }
Source:
<code>private void checkIfAppVersionUpgraded(Context context) { PrefManager.AppInfoPrefManager prefManager = new PrefManager.AppInfoPrefManager(context); long previousVersionCode = prefManager.getAppVersionCode(); final long curVersionCode = (long) BuildConfig.VERSION_CODE; <START> if (previousVersionCode < 0) { <END> prefManager.setAppVersionCode(curVersionCode); prefManager.setAppVersionName(BuildConfig.VERSION_NAME); } else if (previousVersionCode < curVersionCode) { final String previousVersionName = prefManager.getAppVersionName(); prefManager.setAppVersionCode(curVersionCode); prefManager.setAppVersionName(BuildConfig.VERSION_NAME); onAppUpdated(previousVersionCode, curVersionCode, previousVersionName, BuildConfig.VERSION_NAME); } }</code><technical_language>If app is opened for time, a deterministic for previousVersionCode</technical_language>

Target:
private void checkIfAppVersionUpgraded(Context context) { PrefManager.AppInfoPrefManager prefManager = new PrefManager.AppInfoPrefManager(context); long previousVersionCode = prefManager.getAppVersionCode(); final long curVersionCode = BuildConfig.VERSION_CODE; if (previousVersionCode < 0) { prefManager.setAppVersionCode(curVersionCode); prefManager.setAppVersionName(BuildConfig.VERSION_NAME); logger.debug("App opened first time, VersionCode:"+curVersionCode); } else if (previousVersionCode < curVersionCode) { final String previousVersionName = prefManager.getAppVersionName(); prefManager.setAppVersionCode(curVersionCode); prefManager.setAppVersionName(BuildConfig.VERSION_NAME); logger.debug("App updated, VersionCode:"+previousVersionCode+"->"+curVersionCode); onAppUpdated(previousVersionCode, curVersionCode, previousVersionName, BuildConfig.VERSION_NAME); } }
Source:
<code>public void setUp() throws Exception { super.setUp(); keyValueService.createTable(TABLE_CONS, AtlasDbConstants.GENERIC_TABLE_METADATA); keyValueService.createTable(TABLE_THOR, new TableMetadata(new NameMetadataDescription(), new ColumnMetadataDescription(), ConflictHandler.RETRY_ON_WRITE_WRITE, TableMetadataPersistence.CachePriority.WARM, false, 0, false, TableMetadataPersistence.SweepStrategy.THOROUGH, false, TableMetadataPersistence.LogSafety.UNSAFE) <START> .persistToBytes()); <END> }</code><technical_language>This easier: keyValueService.createTable(TABLE_THOR, TableMetadataPersistence.TableMetadata.newBuilder( TableMetadataPersistence.TableMetadata.parseFrom(AtlasDbConstants.GENERIC_TABLE_METADATA)) .setSweepStrategy(TableMetadataPersistence.SweepStrategy.THOROUGH) .build() .toByteArray());</technical_language>

Target:
public void setUp() throws Exception { super.setUp(); keyValueService.createTable(TABLE_CONS, AtlasDbConstants.GENERIC_TABLE_METADATA); keyValueService.createTable(TABLE_THOR, TableMetadataPersistence.TableMetadata.newBuilder( TableMetadataPersistence.TableMetadata.parseFrom(AtlasDbConstants.GENERIC_TABLE_METADATA)) .setSweepStrategy(TableMetadataPersistence.SweepStrategy.THOROUGH) .build() .toByteArray()); }
Source:
<code>private void OnVmAndPoolLoad() { if (getvms() != null && getpools() != null) { ArrayList<vm_pools> filteredPools = new ArrayList<vm_pools>(); for (vm_pools pool : getpools()) { boolean found = false; for (VM vm : getvms()) { if (vm.getVmPoolId() != null && vm.getVmPoolId().equals(pool.getvm_pool_id())) <START> { <END> found = true; break; } } if (!found) { filteredPools.add(pool); } } List all = Linq.Concat(getvms(), filteredPools); Linq.Sort(all, new Linq.VmAndPoolByNameComparer()); ArrayList<Model> items = new ArrayList<Model>(); for (Object item : all) { UserPortalItemModel model = new UserPortalItemModel(this); model.setEntity(item); items.add(model); updateConsoleModel(model); } setCanConnectAutomatically(canConnectAutomatically(items)); setItems(items); setvms(null); setpools(null); getSearchCompletedEvent().raise(this, EventArgs.Empty); } }</code><technical_language>a hashset runtime o(n*m)</technical_language>

Target:
public void OnVmAndPoolLoad() { if (getvms() != null && getpools() != null) { ArrayList<VmPool> filteredPools = new ArrayList<VmPool>(); for (VmPool pool : getpools()) { boolean found = false; for (VM vm : getvms()) { if (vm.getVmPoolId() != null && vm.getVmPoolId().equals(pool.getVmPoolId())) { found = true; break; } } if (!found) { filteredPools.add(pool); } } List all = Linq.Concat(getvms(), filteredPools); Linq.Sort(all, new Linq.VmAndPoolByNameComparer()); ArrayList<Model> items = new ArrayList<Model>(); for (Object item : all) { UserPortalItemModel model = new UserPortalItemModel(this); model.setEntity(item); items.add(model); updateConsoleModel(model); } setCanConnectAutomatically(canConnectAutomatically(items)); setItems(items); setvms(null); setpools(null); getSearchCompletedEvent().raise(this, EventArgs.Empty); } }
Source:
<code>public int lastIndexOf(Object o) { <START> for (int i = list.size(); i >= 0; ++i) { <END> B b = func.project(list.get(i)); if (b == null) { if (o == null) return i; } else { if (b.equals(o)) return i; } } return -1; }</code><technical_language>-i</technical_language>

Target:
public int lastIndexOf(Object o) { for (int i = list.size(); i >= 0; --i) { B b = func.project(list.get(i)); if (b == null) { if (o == null) return i; } else { if (b.equals(o)) return i; } } return -1; }
Source:
<code>public void exchangeToken() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder(CREDENTIAL, SUBJECT_TOKEN_TYPE).build(); StsRequestHandler requestHandler = StsRequestHandler.newBuilder( TOKEN_URL, stsTokenExchangeRequest, MOCK_HTTP_TRANSPORT_FACTORY.create().createRequestFactory()) .build(); StsTokenExchangeResponse response = requestHandler.exchangeToken(); <START> MockStsServiceTransport transport = MOCK_HTTP_TRANSPORT_FACTORY.transport; <END> assertThat(response.getAccessToken().getTokenValue()).isEqualTo(transport.getAccessToken()); assertThat(response.getTokenType()).isEqualTo(transport.getTokenType()); assertThat(response.getIssuedTokenType()).isEqualTo(transport.getIssuedTokenType()); assertThat(response.getExpiresIn()).isEqualTo(transport.getExpiresIn()); GenericData expectedRequestContent = new GenericData() .set("grant_type", TOKEN_EXCHANGE_GRANT_TYPE) .set("scope", CLOUD_PLATFORM_SCOPE) .set("requested_token_type", DEFAULT_REQUESTED_TOKEN_TYPE) .set("subject_token_type", stsTokenExchangeRequest.getSubjectTokenType()) .set("subject_token", stsTokenExchangeRequest.getSubjectToken()); MockLowLevelHttpRequest request = transport.getRequest(); Map<String, String> actualRequestContent = TestUtils.parseQuery(request.getContentAsString()); assertThat(actualRequestContent).isEqualTo(expectedRequestContent); }</code><technical_language>transport is mutable - run issues test data modifying transport tests</technical_language>

Target:
public void exchangeToken() throws IOException { StsTokenExchangeRequest stsTokenExchangeRequest = StsTokenExchangeRequest.newBuilder(CREDENTIAL, SUBJECT_TOKEN_TYPE).build(); StsRequestHandler requestHandler = StsRequestHandler.newBuilder( TOKEN_URL, stsTokenExchangeRequest, transport.createRequestFactory()) .build(); StsTokenExchangeResponse response = requestHandler.exchangeToken(); assertThat(response.getAccessToken().getTokenValue()).isEqualTo(transport.getAccessToken()); assertThat(response.getTokenType()).isEqualTo(transport.getTokenType()); assertThat(response.getIssuedTokenType()).isEqualTo(transport.getIssuedTokenType()); assertThat(response.getExpiresIn()).isEqualTo(transport.getExpiresIn()); GenericData expectedRequestContent = new GenericData() .set("grant_type", TOKEN_EXCHANGE_GRANT_TYPE) .set("scope", CLOUD_PLATFORM_SCOPE) .set("requested_token_type", DEFAULT_REQUESTED_TOKEN_TYPE) .set("subject_token_type", stsTokenExchangeRequest.getSubjectTokenType()) .set("subject_token", stsTokenExchangeRequest.getSubjectToken()); MockLowLevelHttpRequest request = transport.getRequest(); Map<String, String> actualRequestContent = TestUtils.parseQuery(request.getContentAsString()); assertThat(actualRequestContent).isEqualTo(expectedRequestContent); }
Source:
<code>public Optional<RequestTypeId> getRequestTypeForCreatingNewRequestsAfterComplete(@NonNull final I_C_Order order) { final I_C_DocType docType = docTypeDAO.getById(order.getC_DocType_ID()); <START> if (docType.getR_RequestType_ID() == 0) <END> { return Optional.empty(); } return Optional.of(RequestTypeId.ofRepoId(docType.getR_RequestType_ID())); }</code><technical_language>pls <= 0</technical_language>

Target:
public Optional<RequestTypeId> getRequestTypeForCreatingNewRequestsAfterComplete(@NonNull final I_C_Order order) { final I_C_DocType docType = docTypeDAO.getById(order.getC_DocType_ID()); if (docType.getR_RequestType_ID() <= 0) { return Optional.empty(); } return Optional.ofNullable(RequestTypeId.ofRepoIdOrNull(docType.getR_RequestType_ID())); }
Source:
<code>private static String addFullDetailsParam(ParamsMap params, String urlParams) { <START> if (params != null && params.size() > 0 && params.get(FULL_DETAILS_QUERY_PARAM) != null) { <END> return urlParams + FULL_DETAILS_QUERY_PARAM + "="+ params.get(FULL_DETAILS_QUERY_PARAM); } return urlParams; }</code><technical_language>check (_params.size() > 0_) removed. If params is null, params.get() fail. that, cases. If params "fullDetails", checks instead of (params.size() is removed). If params "fullDetails", checks (as in current implementation, .size() in place), replaced .size() .get()</technical_language>

Target:
private static String addFullDetailsParam(ParamsMap params, String urlParams) { if (params != null && params.get(FULL_DETAILS_QUERY_PARAM) != null) { return urlParams + FULL_DETAILS_QUERY_PARAM + "="+ params.get(FULL_DETAILS_QUERY_PARAM); } return urlParams; }
Source:
<code><START> public boolean isUseContributorAgreements() { <END> Set<Project.NameKey> seen = Sets.newHashSet(); seen.add(getProject().getNameKey()); ProjectState s = this; do { switch (s.getProject().getUseContributorAgreements()) { case TRUE: return true; case FALSE: return false; case INHERIT: default: Project.NameKey parent = s.getProject().getParent(); if (parent == null || !seen.add(parent)) { break; } s = projectCache.get(parent); } } while (s != null); return false; }</code><technical_language>This 3 methods identical getter call in switch line. sense factor out logic of computing inherited (into class) of in 4 methods: private abstract class InheritedValue { Set<Project.NameKey> = Sets.newHashSet(); abstract InheritedBoolean getValue(Project p); boolean compute() { seen.add(getProject().getNameKey()); ProjectState s = ProjectState.this; do { switch (getValue(s.getProject())) { case TRUE: return true; case FALSE: return false; case INHERIT: default: Project.NameKey parent = s.getProject().getParent(); if (parent == null || !seen.add(parent)) { break; } s = projectCache.get(parent); } } while (s != null); return false; } } public boolean isUseContributorAgreements() { return new InheritedValue() { InheritedBoolean getValue(Project p) { return p.getUseContributorAgreements(); }; }.compute(); }</technical_language>

Target:
public boolean isUseContributorAgreements() { return getInheritedBoolean(new Function<Project, InheritedBoolean>() { @Override public InheritedBoolean apply(Project input) { return input.getUseContributorAgreements(); } }); }
Source:
<code>public List<Path> getFileSegmentPaths() { <START> Set<String> skippedFilePrefix = new HashSet<>(Arrays.asList("readme")); <END> Set<String> skippedDirs = new HashSet<>(Arrays.asList("cr", "dtd", "dtds")); return discover(path, skippedFilePrefix, EMPTY_SET, EMPTY_SET, EMPTY_SET, skippedDirs); }</code><technical_language>wt10g gov2 pretty clean tuna - readme file other unwanted folders. do need filters</technical_language>

Target:
public List<Path> getFileSegmentPaths() { return discover(path, EMPTY_SET, EMPTY_SET, EMPTY_SET, EMPTY_SET, EMPTY_SET); }
Source:
<code>public void requestsAreParallel() throws Exception { final int port = new Ports().allocate(); final String uri = String.format("http://localhost:%d", port); final int count = 3; final CountDownLatch started = new CountDownLatch(count); final CountDownLatch completed = new CountDownLatch(count); final Take take = new Take() { @Override public Response act(final Request req) throws IOException { started.countDown(); try { started.await(); } catch (final InterruptedException ex) { throw new IllegalStateException(ex); } completed.countDown(); return new TkEmpty().act(req); } }; new Thread( new Runnable() { @Override public void run() { try { new FtBasic( new BkParallel( new BkBasic(take), <START> BkParallelTest.size(count) <END> ), port ).start( new Exit() { @Override public boolean ready() { return completed.getCount() == 0; } } ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ).start(); for (int idx = 0; idx < count; ++idx) { new Thread( new Runnable() { @Override public void run() { try { new JdkRequest(uri) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ).start(); } completed.await(1L, TimeUnit.MINUTES); MatcherAssert.assertThat(started.getCount(), Matchers.equalTo(0L)); MatcherAssert.assertThat(completed.getCount(), Matchers.equalTo(0L)); new Ports().release(port); }</code><technical_language>@lautarobock count</technical_language>

Target:
public void requestsAreParallel() throws Exception { final int port = new Ports().allocate(); final String uri = String.format("http://localhost:%d", port); final int count = 3; final CountDownLatch started = new CountDownLatch(count); final CountDownLatch completed = new CountDownLatch(count); final Take take = new Take() { @Override public Response act(final Request req) throws IOException { started.countDown(); try { started.await(); } catch (final InterruptedException ex) { throw new IllegalStateException(ex); } completed.countDown(); return new TkEmpty().act(req); } }; new Thread( new Runnable() { @Override public void run() { try { new FtBasic( new BkParallel( new BkBasic(take), count ), port ).start( new Exit() { @Override public boolean ready() { return completed.getCount() == 0; } } ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ).start(); for (int idx = 0; idx < count; ++idx) { new Thread( new Runnable() { @Override public void run() { try { new JdkRequest(uri) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ).start(); } completed.await(1L, TimeUnit.MINUTES); MatcherAssert.assertThat(started.getCount(), Matchers.equalTo(0L)); MatcherAssert.assertThat(completed.getCount(), Matchers.equalTo(0L)); new Ports().release(port); }
Source:
<code>public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); textViewTitle.setVisibility(View.VISIBLE); textViewTitle.setText(discussionThread.getTitle()); <START> <END> DiscussionTextUtils.linkifyTextView(textViewResponse, discussionThread.getRenderedBody()); AuthorLayoutViewHolder authorLayoutViewHolder = new AuthorLayoutViewHolder(getView().findViewById(R.id.discussion_user_profile_row)); authorLayoutViewHolder.populateViewHolder(config, discussionThread, discussionThread, System.currentTimeMillis(), new Runnable() { @Override public void run() { router.showUserProfile(getActivity(), discussionThread.getAuthor()); } }); buttonAddComment.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { createComment(); } }); buttonAddComment.setEnabled(false); editTextNewComment.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { buttonAddComment.setEnabled(s.toString().trim().length() > 0); } }); }</code><technical_language>Unneeded empty line here</technical_language>

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); textViewTitle.setVisibility(View.VISIBLE); textViewTitle.setText(discussionThread.getTitle()); DiscussionTextUtils.renderHtml(textViewResponse, discussionThread.getRenderedBody()); AuthorLayoutViewHolder authorLayoutViewHolder = new AuthorLayoutViewHolder(getView().findViewById(R.id.discussion_user_profile_row)); authorLayoutViewHolder.populateViewHolder(config, discussionThread, discussionThread, System.currentTimeMillis(), new Runnable() { @Override public void run() { router.showUserProfile(getActivity(), discussionThread.getAuthor()); } }); buttonAddComment.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { createComment(); } }); buttonAddComment.setEnabled(false); editTextNewComment.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { buttonAddComment.setEnabled(s.toString().trim().length() > 0); } }); }
Source:
<code>public String toString() { return String.format("timestamp = %d, is_integer=%s, long:%d, " + "double:value = %g", timestamp, is_integer, long_value, <START> double_value); <END> }</code><technical_language>name of class in toString representation is useful, e.g. return "MutableDataPoint(timestamp=" + timestamp + ", is_integer=" + is_integer + ...);</technical_language>

Target:
public String toString() { return String.format("MutableDataPoint(timestamp = %d, is_integer=%s, " + "long:%d, double:value = %g)", timestamp, is_integer, long_value, double_value); }
Source:
<code>protected void executeVdsBrokerCommand() { _result = getBroker().getVGInfo(getParameters().getVGID()); proceedProxyReturnValue(); String vgName = (String) _result.vgInfo.get("name"); Object[] temp = (Object[]) _result.vgInfo.get("pvlist"); Map<String, Object>[] pvList = new Map[0]; if (temp != null) { pvList = new Map[temp.length]; for (int i = 0; i < temp.length; i++) { pvList[i] = (Map<String, Object>) temp[i]; pvList[i].put("vgName", vgName); } } Version compatibilityVersion = <START> DbFacade.getInstance().getStoragePoolDao().getForVds(getParameters().getVdsId()) <END> .getCompatibilityVersion(); setReturnValue(GetDeviceListVDSCommand.parseLUNList(pvList, compatibilityVersion)); }</code><technical_language>inject this</technical_language>

Target:
protected void executeVdsBrokerCommand() { _result = getBroker().getVGInfo(getParameters().getVGID()); proceedProxyReturnValue(); String vgName = (String) _result.vgInfo.get("name"); Object[] temp = (Object[]) _result.vgInfo.get("pvlist"); Map<String, Object>[] pvList = new Map[0]; if (temp != null) { pvList = new Map[temp.length]; for (int i = 0; i < temp.length; i++) { pvList[i] = (Map<String, Object>) temp[i]; pvList[i].put("vgName", vgName); } } Version compatibilityVersion = storagePoolDao.getForVds(getParameters().getVdsId()).getCompatibilityVersion(); setReturnValue(GetDeviceListVDSCommand.parseLUNList(pvList, compatibilityVersion)); }
Source:
<code>protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable { if (!ctx.isOriginLocal()) { return invokeNextInterceptor(ctx, command); } Transaction tx; if (transactionManager.getTransaction() != null || (tx = batchContainer.getBatchTransaction()) == null) { return invokeNextInterceptor(ctx, command); } try { transactionManager.resume(tx); InvocationContext invocationContext = ctx; if (!ctx.isInTxScope()) { <START> log.warnf("Called with a non-tx invocation context: %s", ctx); <END> invocationContext = invocationContextFactory.createInvocationContext(true, -1); } return invokeNextInterceptor(invocationContext, command); } finally { if (transactionManager.getTransaction() != null && batchContainer.isSuspendTxAfterInvocation()) transactionManager.suspend(); } }</code><technical_language>if log.warnf() sense in this scenario. if makes, need create a method in Log interface</technical_language>

Target:
protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable { if (!ctx.isOriginLocal()) { return invokeNextInterceptor(ctx, command); } Transaction tx; if (transactionManager.getTransaction() != null || (tx = batchContainer.getBatchTransaction()) == null) { return invokeNextInterceptor(ctx, command); } try { transactionManager.resume(tx); InvocationContext invocationContext = ctx; if (!ctx.isInTxScope()) { log.tracef("Called with a non-tx invocation context: %s", ctx); invocationContext = invocationContextFactory.createInvocationContext(true, -1); } return invokeNextInterceptor(invocationContext, command); } finally { if (transactionManager.getTransaction() != null && batchContainer.isSuspendTxAfterInvocation()) transactionManager.suspend(); } }
Source:
<code>@Config(reportSdk = ICE_CREAM_SANDWICH) @Test public void cacheOnlyInstalledOnce() <START> throws Exception { <END> UrlConnectionDownloader.cache = null; server.enqueue(new MockResponse()); loader.load(URL, false); Object cache = UrlConnectionDownloader.cache; assertThat(cache).isNotNull(); server.enqueue(new MockResponse()); loader.load(URL, false); assertThat(UrlConnectionDownloader.cache).isSameAs(cache); }</code><technical_language>Revert. Add // prevent this</technical_language>

Target:
@Test public void cacheOnlyInstalledOnce() throws Exception { UrlConnectionDownloader.cache = null; server.enqueue(new MockResponse()); loader.load(URL, false); Object cache = UrlConnectionDownloader.cache; assertThat(cache).isNotNull(); server.enqueue(new MockResponse()); loader.load(URL, false); assertThat(UrlConnectionDownloader.cache).isSameAs(cache); }
Source:
<code>public Collection<Achievement> getAll() { <START> return ImmutableSet.copyOf(this.achievementMappings.values()); <END> }</code><technical_language>Collections.unmodifiableSet instead of a deep copy</technical_language>

Target:
public Collection<Achievement> getAll() { if (this.achievements == null) { this.achievements = ImmutableSet.copyOf(this.achievementMappings.values()); } return this.achievements; }
Source:
<code>public void define(NewController context) { NewAction action = context.createAction("update") .setDescription("Update a group.<br>" + "Requires the following permission: 'Administer System'.") .setHandler(this) .setPost(true) .setResponseExample(getClass().getResource("example-update.json")) .setSince("5.2") <START> .setChangelog(new Change("6.4", "The default group is no more editable")); <END> action.createParam(PARAM_GROUP_ID) .setDescription("Identifier of the group.") .setExampleValue("42") .setRequired(true); action.createParam(PARAM_GROUP_NAME) .setDescription(String.format("New optional name for the group. A group name cannot be larger than %d characters and must be unique. " + "Value 'anyone' and '%s' (whatever the case) is reserved and cannot be used. If value is empty or not defined, then name is not changed.", GROUP_NAME_MAX_LENGTH, SONAR_USERS_GROUP_NAME)) .setExampleValue("my-group"); action.createParam(PARAM_GROUP_DESCRIPTION) .setDescription(String.format("New optional description for the group. A group description cannot be larger than %d characters. " + "If value is not defined, then description is not changed.", DESCRIPTION_MAX_LENGTH)) .setExampleValue("Default group for new users"); }</code><technical_language>is longer editable</technical_language>

Target:
public void define(NewController context) { NewAction action = context.createAction("update") .setDescription("Update a group.<br>" + "Requires the following permission: 'Administer System'.") .setHandler(this) .setPost(true) .setResponseExample(getClass().getResource("example-update.json")) .setSince("5.2") .setChangelog(new Change("6.4", "The default group is no longer editable")); action.createParam(PARAM_GROUP_ID) .setDescription("Identifier of the group.") .setExampleValue("42") .setRequired(true); action.createParam(PARAM_GROUP_NAME) .setDescription(String.format("New optional name for the group. A group name cannot be larger than %d characters and must be unique. " + "Value 'anyone' and '%s' (whatever the case) are reserved and cannot be used. If value is empty or not defined, then name is not changed.", GROUP_NAME_MAX_LENGTH, SONAR_USERS_GROUP_NAME)) .setExampleValue("my-group"); action.createParam(PARAM_GROUP_DESCRIPTION) .setDescription(String.format("New optional description for the group. A group description cannot be larger than %d characters. " + "If value is not defined, then description is not changed.", DESCRIPTION_MAX_LENGTH)) .setExampleValue("Default group for new users"); }
Source:
<code>private void loadRaster() { Raster raster = new Raster( <START> new File("/storage/emulated/0/ArcGIS/samples/raster/Shasta.tif").getAbsolutePath()); <END> final RasterLayer rasterLayer = new RasterLayer(raster); ArcGISMap map = new ArcGISMap(Basemap.createImagery()); mMapView.setMap(map); map.getOperationalLayers().add(rasterLayer); rasterLayer.addDoneLoadingListener(new Runnable() { @Override public void run() { mMapView.setViewpointGeometryAsync(rasterLayer.getFullExtent(), 50); } }); }</code><technical_language>Avoid hard coding path, Environment.getExternalStorageDirectory() local path a string resource</technical_language>

Target:
private void loadRaster() { Raster raster = new Raster(buildRasterPath()); final RasterLayer rasterLayer = new RasterLayer(raster); ArcGISMap map = new ArcGISMap(Basemap.createImagery()); mMapView.setMap(map); map.getOperationalLayers().add(rasterLayer); rasterLayer.addDoneLoadingListener(new Runnable() { @Override public void run() { mMapView.setViewpointGeometryAsync(rasterLayer.getFullExtent(), 50); } }); }
Source:
<code>private IncrementalIndex makeIncrementalIndex(Bucket theBucket, AggregatorFactory[] aggs) { int aggsSize = 0; for (AggregatorFactory agg : aggs) { aggsSize += agg.getMaxIntermediateSize(); } <START> int bufferSize = aggsSize * config.getSchema().getTuningConfig().getRowFlushBoundary(); <END> return new IncrementalIndex( new IncrementalIndexSchema.Builder() .withMinTimestamp(theBucket.time.getMillis()) .withDimensionsSpec(config.getSchema().getDataSchema().getParser()) .withQueryGranularity(config.getSchema().getDataSchema().getGranularitySpec().getQueryGranularity()) .withMetrics(aggs) .build(), new OffheapBufferPool(bufferSize) ); }</code><technical_language>I added a hyperUnique aggregator index, requested buffer size jumped 20MB 535MB. large, is expected</technical_language>

Target:
private IncrementalIndex makeIncrementalIndex(Bucket theBucket, AggregatorFactory[] aggs) { int aggsSize = 0; for (AggregatorFactory agg : aggs) { aggsSize += agg.getMaxIntermediateSize(); } final HadoopTuningConfig tuningConfig = config.getSchema().getTuningConfig(); int bufferSize = aggsSize * tuningConfig.getRowFlushBoundary(); final IncrementalIndexSchema indexSchema = new IncrementalIndexSchema.Builder() .withMinTimestamp(theBucket.time.getMillis()) .withDimensionsSpec(config.getSchema().getDataSchema().getParser()) .withQueryGranularity(config.getSchema().getDataSchema().getGranularitySpec().getQueryGranularity()) .withMetrics(aggs) .build(); if (tuningConfig.isIngestOffheap()) { return new OffheapIncrementalIndex( indexSchema, new OffheapBufferPool(bufferSize) ); } else { return new IncrementalIndex( indexSchema, new OffheapBufferPool(bufferSize) ); } }
Source:
<code>private void init( OutputStream output, VCFHeader header, final boolean writeHeader) throws IOException { final BCFStoppableOutputStream stopOut = new BCFStoppableOutputStream(!writeHeader, output); writer = new VariantContextWriterBuilder().clearOptions() <START> .setOutputBCFStream(stopOut).build(); <END> writer.writeHeader(header); stopOut.stopped = false; setInputHeader(header); }</code><technical_language>this set FORCE_BCF option? I matter in order introduce side effects set setOption</technical_language>

Target:
private void init( OutputStream output, VCFHeader header, final boolean writeHeader) throws IOException { final BCFStoppableOutputStream stopOut = new BCFStoppableOutputStream(!writeHeader, output); writer = new VariantContextWriterBuilder().clearOptions() .setOption(Options.FORCE_BCF) .setOutputBCFStream(stopOut).build(); writer.writeHeader(header); stopOut.stopped = false; setInputHeader(header); }
Source:
<code>public boolean startDriverForWithProfile(String browser, Map<String, String> profile) throws Exception { if (OVERRIDE_ACTIVE) { return true; } boolean result = false; String browserName = browser.toLowerCase(); if ("firefox".equals(browserName)) { result = startDriver(FirefoxDriver.class.getName(), profile); } else if ("safari".equals(browserName)) { <START> result = startDriver(SafariDriver.class.getName(), profile); <END> } else if ("chrome".equals(browserName)) { String driverPath = getExecutable("chromedriver"); setPropertyValue("webdriver.chrome.driver", driverPath); result = startDriver(ChromeDriver.class.getName(), profile); } else if ("internet explorer".equals(browserName)) { String driverPath = getExecutable("IEDriverServer"); setPropertyValue("webdriver.ie.driver", driverPath); result = startDriver(InternetExplorerDriver.class.getName(), profile); } else if ("phantomjs".equals(browserName)) { String driverPath = getExecutable("phantomjs"); setPropertyValue("phantomjs.binary.path", driverPath); result = startDriver(PhantomJSDriver.class.getName(), profile); } else { throw new IllegalArgumentException("No defaults known for: " + browser); } return result; }</code><technical_language>do pass a profile for drivers, if firefox pick up? a method startFirefoxWithProfile more appropriate</technical_language>

Target:
public boolean startDriverForWithProfile(String browser, Map<String, String> profile) throws Exception { if (OVERRIDE_ACTIVE) { return true; } boolean result = false; String browserName = browser.toLowerCase(); if ("firefox".equals(browserName)) { result = startDriver(FirefoxDriver.class.getName(), profile); } else if ("safari".equals(browserName)) { result = startDriver(SafariDriver.class.getName()); } else if ("chrome".equals(browserName)) { String driverPath = getExecutable("chromedriver"); setPropertyValue("webdriver.chrome.driver", driverPath); result = startDriver(ChromeDriver.class.getName()); } else if ("internet explorer".equals(browserName)) { String driverPath = getExecutable("IEDriverServer"); setPropertyValue("webdriver.ie.driver", driverPath); result = startDriver(InternetExplorerDriver.class.getName()); } else if ("phantomjs".equals(browserName)) { String driverPath = getExecutable("phantomjs"); setPropertyValue("phantomjs.binary.path", driverPath); result = startDriver(PhantomJSDriver.class.getName()); } else { throw new IllegalArgumentException("No defaults known for: " + browser); } return result; }
Source:
<code>private int[] getStartandEndBucket(final double position) { double thumbSize = miniMapController.getMiniMap().getVisibleAmount(); double leftHalf = position - thumbSize; double rightHalf = position + thumbSize; if (leftHalf < 0) { <START> leftHalf = position - thumbSize / 2; <END> } if (rightHalf > scrollPane.getHmax()) { rightHalf = position + thumbSize / 2; } int[] buckets = new int[] { getStartBucketPosition(leftHalf), Math.min(model.getBucketCache().getNumberBuckets(), getEndBucketPosition(rightHalf) + 2) }; return buckets; }</code><technical_language>Duplicate code, replace leftHalf /= 2</technical_language>

Target:
private int[] getStartandEndBucket(final double position) { double thumbSize = miniMapController.getMiniMap().getVisibleAmount(); double leftHalf = position - thumbSize; double rightHalf = position + thumbSize; if (leftHalf < 0) { leftHalf /= 2; } if (rightHalf > scrollPane.getHmax()) { rightHalf /= 2; } int[] buckets = new int[] { getStartBucketPosition(leftHalf), Math.min(model.getBucketCache().getNumberBuckets(), getEndBucketPosition(rightHalf) + 2) }; return buckets; }
Source:
<code>public void testErrorHandlerIsCalledWhenSubmissionFails() throws Exception { final Tuple1<Boolean> clusterShutdown = new Tuple1<>(false); final TestingDispatcherGateway.Builder dispatcherBuilder = new TestingDispatcherGateway.Builder() .setSubmitFunction(jobGraph -> { throw new FlinkRuntimeException("Nope!"); }) .setClusterShutdownFunction(status -> { if (clusterShutdown.f0) { throw new FlinkRuntimeException("This should be called only once"); } clusterShutdown.f0 = true; return CompletableFuture.completedFuture(Acknowledge.get()); }); final CompletableFuture<Void> errorHandlerFuture = new CompletableFuture<>(); final TestingDispatcherGateway dispatcherGateway = dispatcherBuilder.build(); final ApplicationDispatcherBootstrap bootstrap = createApplicationDispatcherBootstrap( 3, dispatcherGateway, scheduledExecutor, errorHandlerFuture::completeExceptionally); final CompletableFuture<Acknowledge> shutdownFuture = bootstrap.getClusterShutdownFuture(); assertException(errorHandlerFuture, ApplicationExecutionException.class); assertException(shutdownFuture, ApplicationExecutionException.class); <START> assertFalse(clusterShutdown.f0); dispatcherGateway.shutDownCluster(ApplicationStatus.SUCCEEDED); assertTrue(clusterShutdown.f0); <END> }</code><technical_language>is this necessary? write test w/o fail if shutDownCluster is called</technical_language>

Target:
public void testErrorHandlerIsCalledWhenSubmissionFails() throws Exception { final TestingDispatcherGateway.Builder dispatcherBuilder = new TestingDispatcherGateway.Builder() .setSubmitFunction(jobGraph -> { throw new FlinkRuntimeException("Nope!"); }) .setClusterShutdownFunction(status -> { fail("We should not call shutdownCluster()"); return CompletableFuture.completedFuture(Acknowledge.get()); }); final CompletableFuture<Void> errorHandlerFuture = new CompletableFuture<>(); final TestingDispatcherGateway dispatcherGateway = dispatcherBuilder.build(); final ApplicationDispatcherBootstrap bootstrap = createApplicationDispatcherBootstrap( 3, dispatcherGateway, scheduledExecutor, errorHandlerFuture::completeExceptionally); final CompletableFuture<Acknowledge> shutdownFuture = bootstrap.getClusterShutdownFuture(); assertException(errorHandlerFuture, ApplicationExecutionException.class); assertException(shutdownFuture, ApplicationExecutionException.class); }
Source:
<code>public SpellResult perform(CastContext context) { if (context.getTargetEntity() == null) { return SpellResult.NO_TARGET; } targetMage = context.getController().getMage(context.getTargetEntity()); originalCostFree = targetMage.isCostFree(); originalCooldownFree = targetMage.isCooldownFree(); targetMage.setCostFree(costFree); targetMage.setCooldownFree(cooldownFree); try { <START> targetMage.getSpell(spell).cast(spellParameters); <END> } catch (NullPointerException exception) { exception.printStackTrace(); } return SpellResult.CAST; }</code><technical_language>check result if false return SpellResult.FAIL</technical_language>

Target:
public SpellResult perform(CastContext context) { if (context.getTargetEntity() == null) { return SpellResult.NO_TARGET; } Mage targetMage = context.getController().getMage(context.getTargetEntity()); boolean originalCostFree = targetMage.isCostFree(); boolean originalCooldownFree = targetMage.isCooldownFree(); targetMage.setCostFree(costFree); targetMage.setCooldownFree(cooldownFree); try { MageSpell mageSpell = targetMage.getSpell(spell); if (mageSpell == null) { return SpellResult.FAIL; } boolean casted = mageSpell.cast(spellParameters); if (!casted) { return SpellResult.FAIL; } } catch (Exception exception) { exception.printStackTrace(); } targetMage.setCostFree(originalCostFree); targetMage.setCooldownFree(originalCooldownFree); return SpellResult.CAST; }