auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Set<Long> visit(ExpressionTree tree, Object... data) { Verify.that(data.length >= 1); Verify.that(data[0] instanceof Store); Store store = (Store) data[0]; AtomicOperation atomic = (AtomicOperation) data[0]; Expression expression = ((Expression) tree.root()); String key = expression.raw().key(); Operator operator = (Operator) expression.raw().operator(); if(key.equals(Constants.JSON_RESERVED_IDENTIFIER_NAME)) { Set<Long> ids; if(operator == Operator.EQUALS) { ids = Sets.newTreeSet(); expression.raw().values().forEach( value -> ids.add(((Number) value).longValue())); } else if(operator == Operator.NOT_EQUALS) { ids = store.getAllRecords(); expression.raw().values().forEach( value -> ids.remove(((Number) value).longValue())); } else { throw new IllegalArgumentException( "Cannot query on record id using " + expression.raw().operator()); } return ids; } else { ArrayBuilder<TObject> values = ArrayBuilder.builder(); expression.values().forEach( value -> values.add(Convert.javaToThrift(value.value()))); Set<Long> results; if(LinkNavigation.isNavigationScheme(key)) { TObject[] builtValues = values.build(); results = Sets.newHashSet(); Set<Long> records = store.getAllRecords(); key = expression.key().toString(); for (long record : records) { Map<Long, Set<TObject>> result = Operations <START> .navigateKeyRecordAtomic(key, record, Time.NONE, <END> atomic); for (Map.Entry<Long, Set<TObject>> entry : result .entrySet()) { for (TObject value : entry.getValue()) { if(value.is(operator, builtValues)) { results.add(record); break; } } } } } else { results = expression.timestamp() == TimestampSymbol.PRESENT ? store.find(key, operator, values.build()) : store.find(expression.raw().timestamp(), key, operator, values.build()); } return results; } }</code><technical_language>timestamp is passed in expression Time.NONE? @javierlores</technical_language>

Target:
public Set<Long> visit(ExpressionTree tree, Object... data) { Verify.that(data.length >= 1); Verify.that(data[0] instanceof Store); Store store = (Store) data[0]; Expression expression = ((Expression) tree.root()); String key = expression.raw().key(); Operator operator = (Operator) expression.raw().operator(); if(key.equals(Constants.JSON_RESERVED_IDENTIFIER_NAME)) { Set<Long> ids; if(operator == Operator.EQUALS) { ids = Sets.newTreeSet(); expression.raw().values().forEach( value -> ids.add(((Number) value).longValue())); } else if(operator == Operator.NOT_EQUALS) { ids = store.getAllRecords(); expression.raw().values().forEach( value -> ids.remove(((Number) value).longValue())); } else { throw new IllegalArgumentException( "Cannot query on record id using " + expression.raw().operator()); } return ids; } else { ArrayBuilder<TObject> values = ArrayBuilder.builder(); expression.values().forEach( value -> values.add(Convert.javaToThrift(value.value()))); Set<Long> results = expression .timestamp() == TimestampSymbol.PRESENT ? store.find(key, operator, values.build()) : store.find(expression.raw().timestamp(), key, operator, values.build()); return results; } }
Source:
<code>public UnimportedModuleNotificationPanel(@NotNull final Project project, @NotNull final VirtualFile subproject) { <START> setText("This folder was not recognized as a Gradle project. Most likely it was not added to settings.gradle."); <END> createActionLabel("Add Now...", new Runnable() { @Override public void run() { myIsImporting.set(true); try { AndroidImportModuleAction.importGradleSubprojectAsModule(subproject, project); } catch (IOException e) { throw Throwables.propagate(e); } finally { myIsImporting.set(false); } } }); }</code><technical_language>"This folder belong a Gradle project. is registered in settings.gradle"</technical_language>

Target:
public UnimportedModuleNotificationPanel(@NotNull final Project project, @NotNull final VirtualFile subproject) { setText("This folder does not belong to a Gradle project. Make sure it is registered in settings.gradle."); createActionLabel("Add Now...", new Runnable() { @Override public void run() { myIsImporting.set(true); try { AndroidImportModuleAction.importGradleSubprojectAsModule(subproject, project); } catch (IOException e) { throw Throwables.propagate(e); } finally { myIsImporting.set(false); } } }); }
Source:
<code>public void should_create_build_with_given_name() { String jobName = "MyJob"; String buildName = "MyBuild"; String jobDslScript = String.format("job('%s') { wrappers { buildName('%s') } }", jobName, buildName); Job seed = createSeedJobWithJobDsl(jobDslScript); seed.startBuild().waitUntilFinished(); Job job = jenkins.jobs.get(Job.class, jobName); Build build = job.startBuild().waitUntilFinished(); build.open(); <START> WebElement displayNameElement = build.find(by.xpath(" END> assertTrue(displayNameElement.getText().contains(buildName)); }</code><technical_language>part of Build base class</technical_language>

Target:
public void should_create_build_with_given_name() { String jobName = "MyJob"; String buildName = "MyBuild"; String jobDslScript = String.format("job('%s') { wrappers { buildName('%s') } }", jobName, buildName); Job seed = createSeedJobWithJobDsl(jobDslScript); seed.startBuild().waitUntilFinished(); Job job = jenkins.jobs.get(Job.class, jobName); Build build = job.startBuild().waitUntilFinished(); build.open(); assertThat(build.getDisplayName(), containsString(buildName)); }
Source:
<code>public Status status() { Cache<String, Status> statusCache = candlepinCache.getStatusCache(); <START> Status cached = statusCache.get("status"); <END> if (cached != null) { return cached; } boolean good = true; try { rulesCurator.getUpdatedFromDB(); } catch (Exception e) { log.error("Error checking database connection", e); good = false; } Status status = new Status(good, version, release, standalone, jsProvider.getRulesVersion(), jsProvider.getRulesSource()); statusCache.put("status", status); return status; }</code><technical_language>This a constant instead of "status". If dynamically monitoring db pool queue state in future, items of this call need evict entry</technical_language>

Target:
public Status status() { Cache<String, Status> statusCache = candlepinCache.getStatusCache(); Status cached = statusCache.get(CandlepinCache.STATUS_KEY); if (cached != null) { return cached; } boolean good = true; try { rulesCurator.getUpdatedFromDB(); } catch (Exception e) { log.error("Error checking database connection", e); good = false; } Status status = new Status(good, version, release, standalone, jsProvider.getRulesVersion(), jsProvider.getRulesSource()); statusCache.put(CandlepinCache.STATUS_KEY, status); return status; }
Source:
<code>public List<TargetTypeBuildScope> getBuildTargetScopes(@NotNull CompileScope baseScope, @NotNull CompilerFilter filter, @NotNull Project project, boolean forceBuild) { if (!hasErlangModules(baseScope) || ErlangCompilerSettings.getInstance(project).isUseRebarCompilerEnabled()) { <START> return Collections.emptyList(); <END> } TargetTypeBuildScope targetsScope = CmdlineProtoUtil.createTargetsScope(TARGET_TYPE_ID, Collections.singletonList(project.getName()), forceBuild); return Collections.singletonList(targetsScope); }</code><technical_language>Please, ContainerUtil instead of Collections possible</technical_language>

Target:
public List<TargetTypeBuildScope> getBuildTargetScopes(@NotNull CompileScope baseScope, @NotNull CompilerFilter filter, @NotNull Project project, boolean forceBuild) { if (ErlangCompilerSettings.getInstance(project).isUseRebarCompilerEnabled() || !hasErlangModules(baseScope)) { return ContainerUtil.emptyList(); } return Collections.singletonList(CmdlineProtoUtil.createTargetsScope(ErlangModuleBuildOrderTargetType.TYPE_ID, Collections.singletonList(project.getName()), forceBuild)); }
Source:
<code><START> public void clearAllConnections() <END> { _address.clear(); }</code><technical_language>I synchronized too</technical_language>

Target:
public synchronized void clearAllConnections() { _address.clear(); }
Source:
<code>public void facebookRequest(HashMap<String, String> params) { final Intent intent = new Intent(this, MainActivity.class); FacebookLoginRequest facebookLoginRequest = new FacebookLoginRequest(this, params, new Response.Listener<Session>() { @Override public void onResponse(Session session) { storeSessionAndStartMainActivity(intent, session); } }, new Response.Listener<APIError>() { @Override public void onResponse(APIError apiError) { viewBlocker.setVisibility(View.GONE); <START> Log.e("Error response", "In the landing page activity for the login request"); <END> } }); mloginNetworkManager.getRequestQueue().add(facebookLoginRequest); }</code><technical_language>remove this</technical_language>

Target:
public void facebookRequest(HashMap<String, String> params) { final Intent intent = new Intent(this, MainActivity.class); FacebookLoginRequest facebookLoginRequest = new FacebookLoginRequest(this, params, new Response.Listener<Session>() { @Override public void onResponse(Session session) { storeSessionAndStartMainActivity(intent, session); } }, new Response.Listener<APIError>() { @Override public void onResponse(APIError apiError) { viewBlocker.setVisibility(View.GONE); } }); mloginNetworkManager.getRequestQueue().add(facebookLoginRequest); }
Source:
<code>public void updateShortcut(ShortcutDTO shortcutDTO) { final String baseName = shortcutDTO.getInfo().getName(); final File shortcutDirectory = new File(this.shortcutDirectory); final File iconFile = new File(shortcutDirectory, baseName + ".icon"); final File iconBackup = new File(shortcutDirectory, baseName + ".icon_backup"); final URI shortcutIcon = shortcutDTO.getIcon(); if (shortcutIcon != null) { final boolean keepIcon = shortcutIcon.getPath().equals(iconFile.getPath()); if (keepIcon) { try { Files.move(iconFile.toPath(), iconBackup.toPath()); shortcutDTO = new ShortcutDTO.Builder(shortcutDTO).withIcon(iconBackup.toURI()).build(); } catch (IOException e) { <START> LOGGER.error("Could not backup icon."); <END> } } } final File miniatureFile = new File(shortcutDirectory, baseName + ".miniature"); final File miniatureBackup = new File(shortcutDirectory, baseName + ".miniature_backup"); final URI shortcutMiniature = shortcutDTO.getMiniature(); if (shortcutMiniature != null) { final boolean keepMiniature = shortcutMiniature.getPath().equals(miniatureFile.getPath()); if (keepMiniature) { try { Files.move(miniatureFile.toPath(), miniatureBackup.toPath()); shortcutDTO = new ShortcutDTO.Builder(shortcutDTO).withMiniature(miniatureBackup.toURI()).build(); } catch (IOException e) { LOGGER.error("Could not backup miniature."); } } } deleteShortcut(shortcutDTO); createShortcut(shortcutDTO); if (iconBackup.exists()) { iconBackup.delete(); } if (miniatureBackup.exists()) { miniatureBackup.delete(); } }</code><technical_language>add exception LOGGER.error</technical_language>

Target:
public void updateShortcut(ShortcutDTO shortcutDTO) { final String baseName = shortcutDTO.getInfo().getName(); final File shortcutDirectory = new File(this.shortcutDirectory); final File iconFile = new File(shortcutDirectory, baseName + ".icon"); final File iconBackup = new File(shortcutDirectory, baseName + ".icon_backup"); final URI shortcutIcon = shortcutDTO.getIcon(); if (shortcutIcon != null) { final boolean keepIcon = shortcutIcon.getPath().equals(iconFile.getPath()); if (keepIcon) { try { Files.move(iconFile.toPath(), iconBackup.toPath()); shortcutDTO = new ShortcutDTO.Builder(shortcutDTO).withIcon(iconBackup.toURI()).build(); } catch (IOException e) { LOGGER.error("Could not backup icon.", e); } } } final File miniatureFile = new File(shortcutDirectory, baseName + ".miniature"); final File miniatureBackup = new File(shortcutDirectory, baseName + ".miniature_backup"); final URI shortcutMiniature = shortcutDTO.getMiniature(); if (shortcutMiniature != null) { final boolean keepMiniature = shortcutMiniature.getPath().equals(miniatureFile.getPath()); if (keepMiniature) { try { Files.move(miniatureFile.toPath(), miniatureBackup.toPath()); shortcutDTO = new ShortcutDTO.Builder(shortcutDTO).withMiniature(miniatureBackup.toURI()).build(); } catch (IOException e) { LOGGER.error("Could not backup miniature.", e); } } } deleteShortcut(shortcutDTO); createShortcut(shortcutDTO); if (iconBackup.exists()) { iconBackup.delete(); } if (miniatureBackup.exists()) { miniatureBackup.delete(); } }
Source:
<code>public void testCreateEphemeralWithMismatchedSession() throws Exception { final String className = TestHelper.getTestClassName(); final String methodName = TestHelper.getTestMethodName(); final String clusterName = className + "_" + methodName; TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, "localhost", "TestDB", 1, 10, 5, 3, "MasterSlave", true); final long originalSessionId = _zkClient.getSessionId(); final String originalHexSessionId = _zkClient.getHexSessionId(); final String path = "/" + methodName; Assert.assertFalse(_zkClient.exists(path)); ZkTestHelper.expireSession(_zkClient); Assert.assertTrue(TestHelper.verify(() -> { try { <START> return _zkClient.getSessionId() > originalSessionId; <END> } catch (HelixException ex) { return false; } }, 1000L)); try { _zkClient.createEphemeral(path, "Hello Helix", originalHexSessionId); Assert.fail("Ephemeral node should not be created by the expired session."); } catch (ZkSessionMismatchedException expected) { } Assert.assertFalse(_zkClient.exists(path)); }</code><technical_language>Nit, != ok. Zookeeper guarantee >. version change it</technical_language>

Target:
public void testCreateEphemeralWithMismatchedSession() throws Exception { final String className = TestHelper.getTestClassName(); final String methodName = TestHelper.getTestMethodName(); final String clusterName = className + "_" + methodName; TestHelper.setupCluster(clusterName, ZK_ADDR, 12918, "localhost", "TestDB", 1, 10, 5, 3, "MasterSlave", true); final long originalSessionId = _zkClient.getSessionId(); final String originalHexSessionId = ZKUtil.toHexSessionId(originalSessionId); final String path = "/" + methodName; Assert.assertFalse(_zkClient.exists(path)); ZkTestHelper.expireSession(_zkClient); Assert.assertTrue(TestHelper.verify(() -> { try { return _zkClient.getSessionId() != originalSessionId; } catch (HelixException ex) { return false; } }, 1000L)); try { _zkClient.createEphemeral(path, "Hello Helix", originalHexSessionId); Assert.fail("Ephemeral node should not be created by the expired session."); } catch (ZkSessionMismatchedException expected) { } catch (Exception unexpected) { Assert.fail("Should not have thrown exception: " + unexpected); } Assert.assertFalse(_zkClient.exists(path)); }
Source:
<code>private String createURI(final boolean usePassword) { StringBuilder sb = new StringBuilder(); appendRootUri(sb, usePassword); if (sb.charAt(sb.length() - 1) != '/') { sb.append('/'); } sb.append(shareName); <START> if (!(getPath() == null || getPath().equals("/"))) { <END> if (!getPath().startsWith("/")) { sb.append('/'); } sb.append(getPath()); } return sb.toString(); }</code><technical_language>assign getPath()</technical_language>

Target:
private String createURI(final boolean usePassword) { StringBuilder sb = new StringBuilder(); appendRootUri(sb, usePassword); if (sb.charAt(sb.length() - 1) != '/') { sb.append('/'); } sb.append(shareName); String path = getPath(); if (!(path == null || path.equals("/"))) { if (!path.startsWith("/")) { sb.append('/'); } sb.append(path); } return sb.toString(); }
Source:
<code>public InputSource resolveEntity(String systemId, String publicId) throws IOException, SAXException { InputSource result; <START> if (Parser.HTTPS_TESTNG_DTD_URL.equals(publicId)) { <END> m_validate = true; InputStream is = getClass().getClassLoader().getResourceAsStream(Parser.TESTNG_DTD); if (null == is) { is = Thread.currentThread().getContextClassLoader().getResourceAsStream(Parser.TESTNG_DTD); if (null == is) { System.out.println( "WARNING: couldn't find in classpath " + publicId + "\n" + "Fetching it from the Web site."); result = super.resolveEntity(systemId, publicId); } else { result = new InputSource(is); } } else { result = new InputSource(is); } } else { result = super.resolveEntity(systemId, publicId); } return result; }</code><technical_language>I 100% do recommend disabling this logic for depricated URL. users update TestNG update xml vulnerable XXE a MITM</technical_language>

Target:
public InputSource resolveEntity(String systemId, String publicId) throws IOException, SAXException { if (Parser.isUnRecognizedPublicId(publicId)) { boolean isHttps = publicId != null && publicId.trim().toLowerCase().startsWith("https"); if (isHttps || RuntimeBehavior.useHttpUrlForDtd()) { return super.resolveEntity(systemId, publicId); } else { String msg = "TestNG by default disables loading DTD from unsecure Urls. " + "If you need to explicitly load the DTD from a http url, please do so " + "by using the JVM argument [-D" + RuntimeBehavior.TESTNG_USE_UNSECURE_URL + "=true]"; throw new TestNGException(msg); } } m_validate = true; InputStream is = loadDtdUsingClassLoader(); if (is != null) { return new InputSource(is); } System.out.println( "WARNING: couldn't find in classpath " + publicId + "\n" + "Fetching it from " + Parser.HTTPS_TESTNG_DTD_URL); return super.resolveEntity(systemId, Parser.HTTPS_TESTNG_DTD_URL); }
Source:
<code>private static void validateConfig(Map<String, Task> config) { if (config.isEmpty()) { return; } if (config.size() > 1 || !(config.containsKey("rollback") || config.containsKey("cleanup"))) { throw new GradleException("Step configuration can only have one setting either 'rollback' or 'cleanup'. " + "Please refer to the documentation."); } String key = config.keySet().iterator().next(); <START> if (!(config.get(key) instanceof Task)) { <END> throw new GradleException("Step configuration '" + key + "' must refer to a Gradle task but it is: '" + config.get(key) + "'. Please refer to the documentation."); } }</code><technical_language>This code instead entrySet</technical_language>

Target:
private static void validateConfig(Map<String, Task> config) { if (config.isEmpty()) { return; } if (config.size() > 1 || !(config.containsKey("rollback") || config.containsKey("cleanup"))) { throw new GradleException("Step configuration can only have one setting either 'rollback' or 'cleanup'. " + "Please refer to the documentation."); } Map.Entry<String, Task> entry = config.entrySet().iterator().next(); if (!(entry.getValue() instanceof Task)) { throw new GradleException("Step configuration '" + entry.getKey() + "' must refer to a Gradle task but it is: '" + entry.getValue() + "'. Please refer to the documentation."); } }
Source:
<code>@Test public void connectWithKey() { configureDefaultSSHSlaveLauncher().keyCredentials("test", sshd.getPrivateKeyString()); <START> elasticSleep(1000); <END> slave.save(); verify(); }</code><technical_language>a valid error scenario in underlying SUT</technical_language>

Target:
@Test public void connectWithKey() { configureDefaultSSHSlaveLauncher() .keyCredentials("test", sshd.getPrivateKeyString()); slave.save(); verify(); }
Source:
<code>AzureBlobDataAccessor(BlobServiceClient blobServiceClient, BlobBatchClient blobBatchClient, String clusterName, AzureMetrics azureMetrics) { this.blobLayoutStrategy = new AzureBlobLayoutStrategy(clusterName); try { this.storageClient = <START> Utils.getObj(AzureCloudConfig.DEFAULT_AZURE_STORAGE_CLIENT_CLASS, blobServiceClient, blobBatchClient, <END> blobLayoutStrategy); } catch (ReflectiveOperationException roEx) { throw new IllegalArgumentException("Unable to instantiate storage client: " + roEx.getMessage(), roEx); } this.azureMetrics = azureMetrics; this.purgeBatchSize = AzureCloudConfig.DEFAULT_PURGE_BATCH_SIZE; requestTimeout = null; uploadTimeout = null; batchTimeout = null; }</code><technical_language>kind of unconventional instantiate impl's instead of factories, strongly opposed it</technical_language>

Target:
AzureBlobDataAccessor(BlobServiceClient blobServiceClient, BlobBatchClient blobBatchClient, String clusterName, AzureMetrics azureMetrics) { this.blobLayoutStrategy = new AzureBlobLayoutStrategy(clusterName); try { this.storageClient = Utils.getObj(AzureCloudConfig.DEFAULT_AZURE_STORAGE_CLIENT_CLASS, blobServiceClient, blobBatchClient, azureMetrics, blobLayoutStrategy); } catch (ReflectiveOperationException roEx) { throw new IllegalArgumentException("Unable to instantiate storage client: " + roEx.getMessage(), roEx); } this.azureMetrics = azureMetrics; this.purgeBatchSize = AzureCloudConfig.DEFAULT_PURGE_BATCH_SIZE; requestTimeout = null; uploadTimeout = null; batchTimeout = null; }
Source:
<code>public URI adminUrl() { ServerConnector adminConnector = null; for (Connector connector : jettyServer.getConnectors()) { if (ADMIN_SERVER_CONNECTOR_NAME.equals(connector.getName())) adminConnector = (ServerConnector) connector; } if (adminConnector == null) { List<String> adminListeners = config.getList(WorkerConfig.ADMIN_LISTENERS_CONFIG); if (adminListeners == null) { return advertisedUrl(); } else if (adminListeners.isEmpty()) { return null; } else { log.error("No admin connector found for listeners {}", adminListeners); return null; } } UriBuilder builder = UriBuilder.fromUri(jettyServer.getURI()); builder.port(adminConnector.getLocalPort()); <START> log.info("Admin URI: {}", builder.build()); <END> return builder.build(); }</code><technical_language>Do want log this time this getter method is called</technical_language>

Target:
public URI adminUrl() { ServerConnector adminConnector = null; for (Connector connector : jettyServer.getConnectors()) { if (ADMIN_SERVER_CONNECTOR_NAME.equals(connector.getName())) adminConnector = (ServerConnector) connector; } if (adminConnector == null) { List<String> adminListeners = config.getList(WorkerConfig.ADMIN_LISTENERS_CONFIG); if (adminListeners == null) { return advertisedUrl(); } else if (adminListeners.isEmpty()) { return null; } else { log.error("No admin connector found for listeners {}", adminListeners); return null; } } UriBuilder builder = UriBuilder.fromUri(jettyServer.getURI()); builder.port(adminConnector.getLocalPort()); return builder.build(); }
Source:
<code>public Void visitSpecialForm(SpecialFormExpression specialForm, AtomicBoolean result) { switch (specialForm.getForm()) { case IN: case IF: case SWITCH: case WHEN: case NULL_IF: case DEREFERENCE: result.set(true); } <START> return super.visitSpecialForm(specialForm, result); <END> }</code><technical_language>avoid super</technical_language>

Target:
public Void visitSpecialForm(SpecialFormExpression specialForm, AtomicBoolean result) { switch (specialForm.getForm()) { case IN: case IF: case SWITCH: case WHEN: case NULL_IF: case DEREFERENCE: result.set(true); } specialForm.getArguments().forEach(argument -> argument.accept(this, result)); return null; }
Source:
<code>public void parseAssociatedNames(Job<?, ?> job, Collection<GitHubRepositoryName> result) { SCMTriggerItem item = SCMTriggerItems.asSCMTriggerItem(job); if (item != null) { for (SCM scm : item.getSCMs()) { <START> addRepositories(scm, buildEnv(job), result); <END> } } }</code><technical_language>extract result of buildEnv(job) out of loop. Rarely matters, though</technical_language>

Target:
public void parseAssociatedNames(Job<?, ?> job, Collection<GitHubRepositoryName> result) { SCMTriggerItem item = SCMTriggerItems.asSCMTriggerItem(job); EnvVars envVars = buildEnv(job); if (item != null) { for (SCM scm : item.getSCMs()) { addRepositories(scm, envVars, result); } } }
Source:
<code>public Object getPropertyValue(Object id) { if (sfName.equals(id)) { return getName(); } if (sfPath.equals(id)) { return getPath().toString(); } if (sfLocation.equals(id)) { return getLocation().toString(); } if (sfExperimentType.equals(id)) { if (getTraceType() != null) { IConfigurationElement ce = sfTraceTypeAttributes.get(getTraceType()); <START> return (ce != null) ? (getCategory(ce) + " : " + ce.getAttribute(TmfTraceType.NAME_ATTR)) : ""; END> } } return null; }</code><technical_language>need spaces? ':' new String() get rid of nls stuff</technical_language>

Target:
public Object getPropertyValue(Object id) { if (sfName.equals(id)) { return getName(); } if (sfPath.equals(id)) { return getPath().toString(); } if (sfLocation.equals(id)) { return getLocation().toString(); } if (sfExperimentType.equals(id)) { if (getTraceType() != null) { IConfigurationElement ce = sfTraceTypeAttributes.get(getTraceType()); return (ce != null) ? (getCategory(ce) + ':' + ce.getAttribute(TmfTraceType.NAME_ATTR)) : new String(); } } return null; }
Source:
<code>public boolean isFieldPresent(String fieldName) { for (int i = 0; i < inputs.length; i++) { DCInput field = inputs[i]; <START> String fullName = field.getElement() + "." + <END> field.getQualifier(); if (fullName.equals(fieldName)) { return true; } } return false; }</code><technical_language>add field. getSchema() fullName? some users custom schema's element+qualifier combinations overlap dc-schema (e.g. atmire.date.issued)</technical_language>

Target:
public boolean isFieldPresent(String fieldName) { for (int i = 0; i < inputs.length; i++) { DCInput field = inputs[i]; String fullName = field.getFieldName(); if (fullName.equals(fieldName)) { return true; } } return false; }
Source:
<code>public void handleMessage(Message msg) { AsyncResult ar; if (mDestroyed.get()) { Rlog.e(LOG_TAG, "Received message " + msg + "[" + msg.what + "] while being destroyed. Ignoring."); return; } loge("IsimUiccRecords: handleMessage " + msg + "[" + msg.what + "] "); try { switch (msg.what) { case EVENT_APP_READY: onReady(); break; case <START> IccRecords.EVENT_REFRESH: <END> broadcastRefresh(); super.handleMessage(msg); break; case EVENT_ISIM_AUTHENTICATE_DONE: ar = (AsyncResult)msg.obj; log("EVENT_ISIM_AUTHENTICATE_DONE"); if (ar.exception != null) { log("Exception ISIM AKA: " + ar.exception); } else { try { auth_rsp = (String)ar.result; log("ISIM AKA: auth_rsp = " + auth_rsp); } catch (Exception e) { log("Failed to parse ISIM AKA contents: " + e); } } synchronized (mLock) { mLock.notifyAll(); } break; default: super.handleMessage(msg); } } catch (RuntimeException exc) { Rlog.w(LOG_TAG, "Exception parsing SIM record", exc); } }</code><technical_language>Is this needed</technical_language>

Target:
public void handleMessage(Message msg) { AsyncResult ar; if (mDestroyed.get()) { Rlog.e(LOG_TAG, "Received message " + msg + "[" + msg.what + "] while being destroyed. Ignoring."); return; } loge("IsimUiccRecords: handleMessage " + msg + "[" + msg.what + "] "); try { switch (msg.what) { case EVENT_APP_READY: onReady(); break; case EVENT_REFRESH: broadcastRefresh(); super.handleMessage(msg); break; case EVENT_ISIM_AUTHENTICATE_DONE: ar = (AsyncResult)msg.obj; log("EVENT_ISIM_AUTHENTICATE_DONE"); if (ar.exception != null) { log("Exception ISIM AKA: " + ar.exception); } else { try { auth_rsp = (String)ar.result; log("ISIM AKA: auth_rsp = " + auth_rsp); } catch (Exception e) { log("Failed to parse ISIM AKA contents: " + e); } } synchronized (mLock) { mLock.notifyAll(); } break; default: super.handleMessage(msg); } } catch (RuntimeException exc) { Rlog.w(LOG_TAG, "Exception parsing SIM record", exc); } }
Source:
<code>public static String customizedView(String clusterName, String customizedStateName) { <START> return String.format("/%s/EXTERNALVIEW/%s", clusterName, customizedStateName); <END> }</code><technical_language>"EXTERNALVIEW"</technical_language>

Target:
public static String customizedView(String clusterName, String customizedStateName) { return String.format("/%s/CUSTOMIZEDVIEW/%s", clusterName, customizedStateName); }
Source:
<code>public void anRtuIec61850Device(final Map<String, String> settings) throws Throwable { ScenarioContext.Current().put(Keys.KEY_DEVICE_IDENTIFICATION, Defaults.DEFAULT_DEVICE_IDENTIFICATION); final Map<String, String> rtuSettings = SettingsHelper.addAsDefaults(settings, RTU_DEFAULT_SETTINGS); rtuSettings.put(Keys.KEY_NETWORKADDRESS, this.iec61850MockServerConfig.iec61850MockNetworkAddress()); <START> rtuSettings.put(Keys.KEY_NETWORKADDRESS, this.iec61850MockServerConfig.iec61850MockNetworkAddress()); <END> this.rtuDeviceSteps.anRtuDevice(rtuSettings); createIec61850Device(rtuSettings); }</code><technical_language>Duplicate line of code</technical_language>

Target:
public void anRtuIec61850Device(final Map<String, String> settings) throws Throwable { ScenarioContext.Current().put(Keys.KEY_DEVICE_IDENTIFICATION, Defaults.DEFAULT_DEVICE_IDENTIFICATION); final Map<String, String> rtuSettings = SettingsHelper.addAsDefaults(settings, RTU_DEFAULT_SETTINGS); rtuSettings.put(Keys.KEY_NETWORKADDRESS, this.iec61850MockServerConfig.iec61850MockNetworkAddress()); this.rtuDeviceSteps.anRtuDevice(rtuSettings); this.createIec61850Device(rtuSettings); }
Source:
<code>@Override @Nullable public <T extends Serializable> T read(@NotNull String key) throws IgniteCheckedException { <START> if (keysToSkip.contains(key)) <END> return null; lock.readLock().lock(); try { return (T)bridge.read(key); } finally { lock.readLock().unlock(); } }</code><technical_language>do disallow read operation? need is skip keys unmarshalled node startup</technical_language>

Target:
@Override @Nullable public <T extends Serializable> T read(@NotNull String key) throws IgniteCheckedException { lock.readLock().lock(); try { return (T)bridge.read(key); } finally { lock.readLock().unlock(); } }
Source:
<code>public void testCreateNewLog() throws Exception { ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); conf.setLedgerDirNames(ledgerDirs); LedgerDirsManager ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())); String logFileName = Long.toHexString(1) + ".log"; File dir = ledgerDirsManager.pickRandomWritableDir(); LOG.info("Picked this directory: " + dir); File newLogFile = new File(dir, logFileName); newLogFile.createNewFile(); EntryLogger el = new EntryLogger(conf, ledgerDirsManager); el.createNewLog(0L); <START> LOG.info("This is the current log id: " + el.getPreviousAllocatedEntryLogId()); <END> assertTrue("Wrong log id", el.getPreviousAllocatedEntryLogId() > 1); }</code><technical_language>nit: {}</technical_language>

Target:
public void testCreateNewLog() throws Exception { ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); conf.setLedgerDirNames(ledgerDirs); LedgerDirsManager ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())); String logFileName = Long.toHexString(1) + ".log"; File dir = ledgerDirsManager.pickRandomWritableDir(); LOG.info("Picked this directory: {}", dir); File newLogFile = new File(dir, logFileName); newLogFile.createNewFile(); EntryLogger el = new EntryLogger(conf, ledgerDirsManager); EntryLogManagerForSingleEntryLog entryLogManager = (EntryLogManagerForSingleEntryLog) el.getEntryLogManager(); entryLogManager.createNewLog(0L); LOG.info("This is the current log id: {}", entryLogManager.getCurrentLogId()); assertTrue("Wrong log id", entryLogManager.getCurrentLogId() > 1); }
Source:
<code>public GarageDoorData getGarageData() throws InvalidLoginException, IOException { logger.debug("Retreiveing door data"); String url = String.format( "%s/api/v4/userdevicedetails/get?appId=%s&SecurityToken=%s", <START> WEBSITE, appId, getSecurityToken()); <END> JsonNode data = request("GET", url, null, null, true); return new GarageDoorData(data); }</code><technical_language>appId SecurityToken values URL-encoded (or URL parameters potentially illegal characters in this source file)? I default app ID / + in them, for example. appId accidentally working present</technical_language>

Target:
public GarageDoorData getGarageData() throws InvalidLoginException, IOException { logger.debug("Retreiveing door data"); String url = String.format( "%s/api/v4/userdevicedetails/get?appId=%s&SecurityToken=%s", WEBSITE, enc(appId), enc(getSecurityToken())); JsonNode data = request("GET", url, null, null, true); return new GarageDoorData(data); }
Source:
<code>public synchronized ByteBuf getSavedEncodeBuffer() { if (temporaryBuffer == null) { temporaryBuffer = PooledByteBufAllocator.DEFAULT.buffer(getEstimateSavedEncode()); saveEncoding(temporaryBuffer); } <START> return temporaryBuffer.retain(); <END> }</code><technical_language>I naming Netty I is a good idea communicate is relased usage not, error prone write example: <LINK_0></technical_language>

Target:
public synchronized ByteBuf getSavedEncodeBuffer() { if (temporaryBuffer == null) { temporaryBuffer = PooledByteBufAllocator.DEFAULT.buffer(getEstimateSavedEncode()); saveEncoding(temporaryBuffer); } return temporaryBuffer.retain(1); }
Source:
<code><START> public int read(ByteBuffer dst) throws IOException { <END> if (this.writeMode.get()) { throw new IOException("Buffer is still in write mode!"); } if (!this.hasRemaining()) { return -1; } if (!dst.hasRemaining()) { return 0; } final int oldIndex = index; for(; index < limit; index++) { if(!dst.hasRemaining()) { break; } dst.put(this.internalMemorySegment.get(index)); } return index-oldIndex; }</code><technical_language>Please check if this method is all, if not, please remove it. situations in contents is copied a byte buffer</technical_language>

Target:
public int read(ByteBuffer dst) throws IOException { if (!this.hasRemaining()) { return -1; } int numBytes = dst.remaining(); final int remaining = this.remaining(); if (numBytes == 0) { return 0; } if(numBytes > remaining) { numBytes = remaining; } internalMemorySegment.get(position(), dst, numBytes); index += numBytes; return numBytes; }
Source:
<code>private RuntimeException prettifyFailure(MockFeatures<?> mockFeatures, Exception generationFailed) { if (Modifier.isPrivate(mockFeatures.mockedType.getModifiers())) { throw new MockitoException(join( "Mockito cannot mock this class: " + mockFeatures.mockedType + ".", "Most likely it is a private class that is not visible by Mockito", "" ), generationFailed); } throw new MockitoException(join( "Mockito cannot mock this class: " + mockFeatures.mockedType, "", <START> "Mockito can only mock visible & non-final classes.", <END> "If you're not sure why you're getting this error, please report to the mailing list.", "", Platform.isJava8BelowUpdate45() ? "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n" : "", Platform.describe(), "", "Underlying exception : " + generationFailed), generationFailed ); }</code><technical_language>replace 'visible' 'non-private'? Users 'visible' is :)</technical_language>

Target:
private RuntimeException prettifyFailure(MockFeatures<?> mockFeatures, Exception generationFailed) { if (Modifier.isPrivate(mockFeatures.mockedType.getModifiers())) { throw new MockitoException(join( "Mockito cannot mock this class: " + mockFeatures.mockedType + ".", "Most likely it is a private class that is not visible by Mockito", "" ), generationFailed); } throw new MockitoException(join( "Mockito cannot mock this class: " + mockFeatures.mockedType, "", "Mockito can only non-private & non-final classes.", "If you're not sure why you're getting this error, please report to the mailing list.", "", Platform.isJava8BelowUpdate45() ? "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n" : "", Platform.describe(), "", "Underlying exception : " + generationFailed ), generationFailed); }
Source:
<code>public String timeStamp() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); <START> XMLGregorianCalendar now = calendarUtil.buildXMLGregorianCalendarDateTime(new GregorianCalendar()); <END> return dateFormat.format(now.toGregorianCalendar().getTime()); }</code><technical_language>GregorianCalendar (what's advantage of making XMLGregorianCalendar)</technical_language>

Target:
public String timeStamp() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return dateFormat.format(new GregorianCalendar().getTime()); }
Source:
<code>private void updateVms() { for (VmStatic vm : vmsLockedForUpdate) { <START> vm.setVmInit(vmInitDao.get(vm.getId())); <END> VmManagementParametersBase updateParams = new VmManagementParametersBase(vm); updateParams.setLockProperties(LockProperties.create(LockProperties.Scope.None)); updateParams.setClusterLevelChangeFromVersion(oldCluster.getCompatibilityVersion()); updateParams.setCompensationEnabled(true); ActionReturnValue result = runInternalAction( ActionType.UpdateVm, updateParams, cloneContextWithNoCleanupCompensation()); if (!result.getSucceeded()) { List<String> params = new ArrayList<>(); params.add("$action Update"); params.add("$type VM"); params.add(parseErrorMessage(result.getValidationMessages())); List<String> messages = backend.getErrorsTranslator().translateErrorText(params); failedUpgradeEntities.put(vm.getName(), getFailedMessage(messages)); } } }</code><technical_language>right place. This function is supposed small concise call UpdateVm correct locking</technical_language>

Target:
private void updateVms() { for (VmStatic vm : vmsLockedForUpdate) { VmManagementParametersBase updateParams = new VmManagementParametersBase(vm); updateParams.setLockProperties(LockProperties.create(LockProperties.Scope.None)); updateParams.setClusterLevelChangeFromVersion(oldCluster.getCompatibilityVersion()); updateParams.setCompensationEnabled(true); ActionReturnValue result = runInternalAction( ActionType.UpdateVm, updateParams, cloneContextWithNoCleanupCompensation()); if (!result.getSucceeded()) { List<String> params = new ArrayList<>(); params.add("$action Update"); params.add("$type VM"); params.add(parseErrorMessage(result.getValidationMessages())); List<String> messages = backend.getErrorsTranslator().translateErrorText(params); failedUpgradeEntities.put(vm.getName(), getFailedMessage(messages)); } } }
Source:
<code>private FileWriter getNextWriter() throws IOException { currentFileWriter.close(); File scriptOutputFile_renameFrom = new File(path + File.separator + baseName); <START> File scriptOutputFile_renameTo = new File(path + File.separator + baseName.substring(0, baseName.indexOf("-")) + ".btrace." + (counter++)); <END> if (scriptOutputFile_renameTo.exists()) { scriptOutputFile_renameTo.delete(); } scriptOutputFile_renameFrom.renameTo(scriptOutputFile_renameTo); scriptOutputFile_renameFrom = new File(path + File.separator + baseName); if (counter > settings.getFileRollMaxRolls()) { counter = 1; } return new FileWriter(scriptOutputFile_renameFrom); }</code><technical_language>Is splitting '-' in baseName intentional? baseName '-' this code fail</technical_language>

Target:
private FileWriter getNextWriter() throws IOException { currentFileWriter.close(); File scriptOutputFile_renameFrom = new File(path + File.separator + baseName); File scriptOutputFile_renameTo = new File(path + File.separator + baseName + "." + (counter++)); if (scriptOutputFile_renameTo.exists()) { scriptOutputFile_renameTo.delete(); } scriptOutputFile_renameFrom.renameTo(scriptOutputFile_renameTo); scriptOutputFile_renameFrom = new File(path + File.separator + baseName); if (counter > settings.getFileRollMaxRolls()) { counter = 1; } return new FileWriter(scriptOutputFile_renameFrom); }
Source:
<code>public void testShadowedTests() { TestSuite suite = new TestSuite(OverrideTestCase.class); suite.run(fResult); assertEquals(1, fResult.runCount()); <START> assertNotNull(fResult); <END> }</code><technical_language>Useless. This line executed if fResult is null a NullPointerException thrown line before</technical_language>

Target:
public void testShadowedTests() { TestSuite suite = new TestSuite(OverrideTestCase.class); suite.run(fResult); assertEquals(1, fResult.runCount()); }
Source:
<code>private InetSocketAddress startServer() throws TTransportException { Preconditions.checkState( curatorFramework != null && curatorFramework.getState() == CuratorFrameworkState.STARTED); if (env.getConfiguration().containsKey(FluoConfigurationImpl.ORACLE_PORT_PROP)) { port = env.getConfiguration().getInt(FluoConfigurationImpl.ORACLE_PORT_PROP); Preconditions.checkArgument(port >= 1 && port <= 65535, FluoConfigurationImpl.ORACLE_PORT_PROP + " must be valid port (1-65535)"); } else { port = PortUtils.getRandomFreePort(); } InetSocketAddress addr = new InetSocketAddress(port); TNonblockingServerSocket socket = new TNonblockingServerSocket(addr); THsHaServer.Args serverArgs = new THsHaServer.Args(socket); TProcessor processor = new OracleService.Processor<OracleService.Iface>(this); serverArgs.processor(processor); serverArgs.maxReadBufferBytes = ORACLE_MAX_READ_BUFFER_BYTES; serverArgs.inputProtocolFactory(new TCompactProtocol.Factory()); serverArgs.outputProtocolFactory(new TCompactProtocol.Factory()); server = new THsHaServer(serverArgs); <START> Runnable st = () -> server.serve(); <END> serverThread = new Thread(st); serverThread.setDaemon(true); serverThread.start(); return addr; }</code><technical_language>st inlined</technical_language>

Target:
private InetSocketAddress startServer() throws TTransportException { Preconditions.checkState( curatorFramework != null && curatorFramework.getState() == CuratorFrameworkState.STARTED); if (env.getConfiguration().containsKey(FluoConfigurationImpl.ORACLE_PORT_PROP)) { port = env.getConfiguration().getInt(FluoConfigurationImpl.ORACLE_PORT_PROP); Preconditions.checkArgument(port >= 1 && port <= 65535, FluoConfigurationImpl.ORACLE_PORT_PROP + " must be valid port (1-65535)"); } else { port = PortUtils.getRandomFreePort(); } InetSocketAddress addr = new InetSocketAddress(port); TNonblockingServerSocket socket = new TNonblockingServerSocket(addr); THsHaServer.Args serverArgs = new THsHaServer.Args(socket); TProcessor processor = new OracleService.Processor<OracleService.Iface>(this); serverArgs.processor(processor); serverArgs.maxReadBufferBytes = ORACLE_MAX_READ_BUFFER_BYTES; serverArgs.inputProtocolFactory(new TCompactProtocol.Factory()); serverArgs.outputProtocolFactory(new TCompactProtocol.Factory()); server = new THsHaServer(serverArgs); serverThread = new Thread(server::serve); serverThread.setDaemon(true); serverThread.start(); return addr; }
Source:
<code>private void forgetInvocations(int segment, ForgetInvocationsCommand fic) { if (fic != null) { DistributionInfo info = dm.getCacheTopology().getDistributionForSegment(segment); rpcManager.invokeRemotelyAsync(info.writeOwners(), fic, forgetRpcOptions); if (info.isWriteOwner()) { fic.init(dataContainer); fic.setOrigin(rpcManager.getAddress()); if (trace) { log.tracef("Invoking %s", fic); } fic.invoke(); if (trace) { Set<Object> keys = new HashSet<>(Arrays.asList(fic.keys())); log.tracef("Invalidation completed: " + StreamSupport.stream(dataContainer.spliterator(), false) <START> .filter(ice -> keys.contains(ice.getKey())).collect(Collectors.toList())); <END> } } } }</code><technical_language>Minor, [1] instead avoid List [1] <LINK_0></technical_language>

Target:
private void forgetInvocations(int segment, ForgetInvocationsCommand fic) { if (fic != null) { DistributionInfo info = dm.getCacheTopology().getDistributionForSegment(segment); rpcManager.invokeRemotelyAsync(info.writeOwners(), fic, forgetRpcOptions); if (info.isWriteOwner()) { fic.init(dataContainer); fic.setOrigin(rpcManager.getAddress()); if (trace) { log.tracef("Invoking %s", fic); } fic.invoke(); if (trace) { Set<Object> keys = new HashSet<>(Arrays.asList(fic.keys())); log.tracef("Invalidation completed: " + StreamSupport.stream(dataContainer.spliterator(), false) .filter(ice -> keys.contains(ice.getKey())).map(String::valueOf).collect(Collectors.joining())); } } } }
Source:
<code>List<MediaWikiDumpFile> findDailyDumpsOnline() { <START> List<String> dumpFileDates = findDumpDatesOnline("other/incr/"); <END> List<MediaWikiDumpFile> result = new ArrayList<MediaWikiDumpFile>(); for (String dateStamp : dumpFileDates) { result.add(new WmfOnlineDailyDumpFile(dateStamp, this.projectName, this.webResourceFetcher, this.dumpfileDirectoryManager)); } return result; }</code><technical_language>I suggest defining this string a constant is in another class (WmfOnlineDailyDumpFile)</technical_language>

Target:
List<MediaWikiDumpFile> findDailyDumpsOnline() { List<String> dumpFileDates = findDumpDatesOnline(WmfDumpFile.DAILY_WEB_DIRECTORY); List<MediaWikiDumpFile> result = new ArrayList<MediaWikiDumpFile>(); for (String dateStamp : dumpFileDates) { result.add(new WmfOnlineDailyDumpFile(dateStamp, this.projectName, this.webResourceFetcher, this.dumpfileDirectoryManager)); } return result; }
Source:
<code>private static TimeGraphEntryModel getValueEntry(List<@NonNull TimeGraphEntryModel> treeModel, String name) { Long parentID = <START> -2L; <END> for (TimeGraphEntryModel entryModel : treeModel) { if (entryModel.getName().equals(name)) { parentID = entryModel.getId(); } if (entryModel.getParentId() == parentID && parentID != null) { return entryModel; } } return null; }</code><technical_language>nan</technical_language>

Target:
private static TimeGraphEntryModel getValueEntry(List<@NonNull TimeGraphEntryModel> treeModel, String name) { Long parentID = null; for (TimeGraphEntryModel entryModel : treeModel) { if (entryModel.getName().equals(name)) { parentID = entryModel.getId(); } if (entryModel.getParentId() == parentID && parentID != null) { return entryModel; } } return null; }
Source:
<code>public void testprocessTokenResponseNegative() throws IOException { final AuthenticationRequest request = createAuthenticationRequest(TEST_AUTHORITY, "resource", "client", "redirect", "loginhint", null, null, null); final Oauth2 oauth2 = createOAuthInstance(request, new WebRequestHandler()); final String jsonResponse = "{invalid"; final HttpURLConnection mockedConnection = mock(HttpURLConnection.class); HttpUrlConnectionFactory.mockedConnection = mockedConnection; Util.prepareMockedUrlConnection(mockedConnection); when(mockedConnection.getOutputStream()).thenReturn(mock(OutputStream.class)); when(mockedConnection.getInputStream()).thenReturn( Util.createInputStream(jsonResponse)); when(mockedConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); try { <START> oauth2.refreshToken("fakeRefresToken"); <END> fail("must throw exception"); } catch (final AuthenticationException e) { assertNotNull(e); assertEquals(e.getCode(), ADALError.SERVER_INVALID_JSON_RESPONSE); assertNotNull(e.getCause()); assertTrue(e.getCause() instanceof JSONException); } }</code><technical_language>typo</technical_language>

Target:
public void testprocessTokenResponseNegative() throws IOException { final AuthenticationRequest request = createAuthenticationRequest(TEST_AUTHORITY, "resource", "client", "redirect", "loginhint", null, null, null); final Oauth2 oauth2 = createOAuthInstance(request, new WebRequestHandler()); final String jsonResponse = "{invalid"; final HttpURLConnection mockedConnection = mock(HttpURLConnection.class); HttpUrlConnectionFactory.mockedConnection = mockedConnection; Util.prepareMockedUrlConnection(mockedConnection); when(mockedConnection.getOutputStream()).thenReturn(mock(OutputStream.class)); when(mockedConnection.getInputStream()).thenReturn( Util.createInputStream(jsonResponse)); when(mockedConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); try { oauth2.refreshToken("fakeRefreshToken"); fail("must throw exception"); } catch (final AuthenticationException e) { assertNotNull(e); assertEquals(e.getCode(), ADALError.SERVER_INVALID_JSON_RESPONSE); assertNotNull(e.getCause()); assertTrue(e.getCause() instanceof JSONException); } }