auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<Role> getGrantedRoles(Permission permission) { List<Role> roles = Collections.emptyList(); Connection conn = null; PreparedStatement ps = null; ResultSet resultSet = null; <START> String query = "SELECT * FROM ROLE_PERMISSIONS WHERE APP_NAME = ? AND PERMISSION_STRING = ?"; <END> try { conn = getConnection(); ps = conn.prepareStatement(query); ps.setString(1, permission.getAppName()); ps.setString(2, permission.getPermissionString()); if (log.isDebugEnabled()) { log.debug("Executing query: " + query); } resultSet = ps.executeQuery(); while (resultSet.next()) { roles.add(new Role(resultSet.getString("ROLE_ID"), "")); } } catch (SQLException e) { throw new PermissionException("Unable to get roles assigned for the permission " + permission + ". [Query=" + query + "]", e); } finally { closeConnection(conn, ps, resultSet); } return roles; }</code><technical_language>need ROLE_ID change this query "SELECT ROLE_ID ROLE_PERMISSIONS APP_NAME = ? PERMISSION_STRING = ?"</technical_language>

Target:
public List<Role> getGrantedRoles(Permission permission) { List<Role> roles = new ArrayList<>(); Connection conn = null; PreparedStatement ps = null; ResultSet resultSet = null; String query = "SELECT ROLE_ID FROM ROLE_PERMISSIONS WHERE APP_NAME = ? AND PERMISSION_STRING = ?"; try { conn = getConnection(); ps = conn.prepareStatement(query); ps.setString(1, permission.getAppName()); ps.setString(2, permission.getPermissionString()); if (log.isDebugEnabled()) { log.debug("Executing query: " + query); } resultSet = ps.executeQuery(); while (resultSet.next()) { roles.add(new Role(resultSet.getString("ROLE_ID"), "")); } } catch (SQLException e) { throw new PermissionException("Unable to get roles assigned for the permission " + permission + ". [Query=" + query + "]", e); } finally { closeConnection(conn, ps, resultSet); } return roles; }
Source:
<code>public static Date parseISO8601(String dateString) throws ParseException { Date date = new Date(); <START> SimpleDateFormat sdf = new SimpleDateFormat(ISO8601_FORMAT_STRING, Locale.ENGLISH); <END> sdf.setTimeZone(TimeZone.getTimeZone("UTC")); date.setTime(sdf.parse(dateString).getTime()); return date; }</code><technical_language>Great idea! Locale.ROOT instead, though</technical_language>

Target:
public static Date parseISO8601(String dateString) throws ParseException { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(ISO8601_FORMAT_STRING, Locale.ROOT); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); date.setTime(sdf.parse(dateString).getTime()); return date; }
Source:
<code>public void checkAndCreate() { String uuid = organization.getUuid(); QualityProfileDto writtenDto = factory.checkAndCreate(dbSession, organization, new QProfileName("xoo", "P1")); dbSession.commit(); dbSession.clearCache(); assertThat(writtenDto.getOrganizationUuid()).isEqualTo(uuid); <START> assertThat(writtenDto.getKey()).isNotNull(); <END> assertThat(writtenDto.getName()).isEqualTo("P1"); assertThat(writtenDto.getLanguage()).isEqualTo("xoo"); assertThat(writtenDto.getId()).isNotNull(); QualityProfileDto readDto = db.qualityProfileDao().selectByNameAndLanguage("P1", "xoo", dbSession); assertThat(readDto.getOrganizationUuid()).isEqualTo(uuid); assertThat(readDto.getName()).isEqualTo(writtenDto.getName()); assertThat(readDto.getKey()).startsWith(writtenDto.getKey()); assertThat(readDto.getLanguage()).isEqualTo(writtenDto.getLanguage()); assertThat(readDto.getId()).isEqualTo(writtenDto.getId()); assertThat(readDto.getParentKee()).isNull(); assertThat(db.qualityProfileDao().selectAll(dbSession)).hasSize(1); }</code><technical_language>isNotEmpty()</technical_language>

Target:
public void checkAndCreate() { String uuid = organization.getUuid(); QualityProfileDto writtenDto = factory.checkAndCreate(dbSession, organization, new QProfileName("xoo", "P1")); dbSession.commit(); dbSession.clearCache(); assertThat(writtenDto.getOrganizationUuid()).isEqualTo(uuid); assertThat(writtenDto.getKey()).isNotEmpty(); assertThat(writtenDto.getName()).isEqualTo("P1"); assertThat(writtenDto.getLanguage()).isEqualTo("xoo"); assertThat(writtenDto.getId()).isNotNull(); QualityProfileDto readDto = db.qualityProfileDao().selectByNameAndLanguage("P1", "xoo", dbSession); assertEqual(writtenDto, readDto); assertThat(db.qualityProfileDao().selectAll(dbSession, organization)).hasSize(1); }
Source:
<code>public void testInsertTaskWithStartAndDue() { RowSnapshot<TaskLists> taskList = new VirtualRowSnapshot<>(new LocalTaskListsTable(mAuthority)); RowSnapshot<Tasks> task = new VirtualRowSnapshot<>(new TaskListScoped(taskList, new TasksTable(mAuthority))); DateTime start = DateTime.now(); DateTime due = start.addDuration(new Duration(1, 1, 0)); assertThat(new Seq<>( new Put<>(taskList, new EmptyRowData<TaskLists>()), new Put<>(task, new TimeData(start, due)) ), resultsIn(mClient, new Assert<>(task, new TimeData(start, due)), new AssertRelated<>( new InstanceTable(mAuthority), Instances.TASK_ID, task, <START> new InstanceData( <END> start.shiftTimeZone(TimeZone.getDefault()), due.shiftTimeZone(TimeZone.getDefault()), absent(), Instances.INSTANCE_STATUS_NEXT)) )); }</code><technical_language>Previous version checked TZ here. way, is basic I understand here. Instances table TaskColumns well, values in sync? test tables for values then</technical_language>

Target:
public void testInsertTaskWithStartAndDue() { RowSnapshot<TaskLists> taskList = new VirtualRowSnapshot<>(new LocalTaskListsTable(mAuthority)); RowSnapshot<Tasks> task = new VirtualRowSnapshot<>(new TaskListScoped(taskList, new TasksTable(mAuthority))); DateTime start = DateTime.now(); DateTime due = start.addDuration(new Duration(1, 1, 0)); assertThat(new Seq<>( new Put<>(taskList, new EmptyRowData<TaskLists>()), new Put<>(task, new TimeData(start, due)) ), resultsIn(mClient, new Assert<>(task, new TimeData(start, due)), new AssertRelated<>( new InstanceTable(mAuthority), Instances.TASK_ID, task, new Composite<Instances>( new InstanceTestData( start.shiftTimeZone(TimeZone.getDefault()), due.shiftTimeZone(TimeZone.getDefault()), absent(), 0), new CharSequenceRowData<>(Tasks.TZ, "UTC")) ))); }
Source:
<code>public static Exception extractExecutionExceptionCause(Exception e) { if (!(e instanceof ExecutionException)) { return e; } Throwable cause = e.getCause(); return cause == null ? e : (cause instanceof Exception ? (Exception) cause : new Exception(cause)); <START> } <END></code><technical_language>if (!(e instanceof ExecutionException) || e.getCause() == null) { return e; } Throwable = e.getCause(); return instanceof Exception ? (Exception) : new Exception(cause); making return statement simpler</technical_language>

Target:
public static Exception extractExecutionExceptionCause(Exception e) { Throwable cause = e.getCause(); if (!(e instanceof ExecutionException) || cause == null) { return e; } return cause instanceof Exception ? (Exception) cause : new Exception(cause); }
Source:
<code>public ToIntFunction<ConnectorSplit> getSplitBucketFunction( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorPartitioningHandle partitioningHandle) { return value -> ((HiveSplit) value).getBucketNumber() <START> .orElseThrow(() -> new IllegalStateException("Bucket number not set in split")); <END> }</code><technical_language>nit: "in a split"</technical_language>

Target:
public ToIntFunction<ConnectorSplit> getSplitBucketFunction( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorPartitioningHandle partitioningHandle) { return value -> ((HiveSplit) value).getBucketNumber() .orElseThrow(() -> new IllegalArgumentException("Bucket number not set in split")); }
Source:
<code>public void testCleanReindex() throws Exception { PID fileObjPid = makePid(); <START> FileObject fileObj =repoObjFactory.createFileObject(fileObjPid, null); <END> PID parentPid = makePid(); WorkObject work = repoObjFactory.createWorkObject(parentPid, null); work.addMember(fileObj); MvcResult result = mvc.perform(post("/edit/solr/reindex/" + parentPid.getUUID(), false)) .andExpect(status().is2xxSuccessful()) .andReturn(); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(parentPid.getUUID(), respMap.get("pid")); assertEquals("reindex", respMap.get("action")); assertFalse(respMap.containsKey("error")); }</code><technical_language>space =. helpful run a mvn package verify ready push branch out catch checkstyle issues</technical_language>

Target:
public void testCleanReindex() throws Exception { PID parentPid = makePid(); MvcResult result = mvc.perform(post("/edit/solr/reindex/" + parentPid.getUUID(), false)) .andExpect(status().is2xxSuccessful()) .andReturn(); Map<String, Object> respMap = getMapFromResponse(result); assertEquals(parentPid.getUUID(), respMap.get("pid")); assertEquals("reindex", respMap.get("action")); assertFalse(respMap.containsKey("error")); }
Source:
<code><START> public static String dryRun(Config cfg) { <END> return cfg.getStringValue(ConfigKeys.get("DRY_RUN")); }</code><technical_language>This a Boolean instead is a dry run</technical_language>

Target:
public static Boolean dryRun(Config cfg) { return cfg.getBooleanValue(ConfigKeys.get("DRY_RUN"), false); }
Source:
<code>public Response totpKeyGenExternal(@Context HttpServletRequest request) { TOTPManager totpManager = (TOTPManager) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService (TOTPManager.class); if (totpManager != null) { String username = request.getParameter("username"); TOTPDTO totpdto = null; try { totpdto = totpManager.generateTOTPKey(username); String json = createJsonPayload(totpdto.getSecretkey(), totpdto.getQRCodeURL()); return Response.ok(json, MediaType.APPLICATION_JSON_TYPE).build(); } catch (TOTPException e) { <START> log.error("TOTPKeyGenerator endpoint could not generate the key for the user : "+username,e); <END> return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error when generating the key") .type(MediaType.APPLICATION_JSON_TYPE).build(); } } else { log.error("TOTPKeyGenerator endpoint could not generate the key"); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error when generating the key") .type(MediaType.APPLICATION_JSON_TYPE).build(); } }</code><technical_language>format code</technical_language>

Target:
public Response totpKeyGenExternal(@Context HttpServletRequest request) { TOTPManager totpManager = (TOTPManager) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService (TOTPManager.class); if (totpManager != null) { String username = CharacterEncoder.getSafeText(request.getParameter("username")); TOTPDTO totpdto = null; try { totpdto = totpManager.generateTOTPKey(username); String json = createJsonPayload(totpdto.getSecretkey(), totpdto.getQRCodeURL()); return Response.ok(json, MediaType.APPLICATION_JSON_TYPE).build(); } catch (TOTPException e) { log.error("TOTPKeyGenerator endpoint could not generate the key for the user : " + username,e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error when generating the key") .type(MediaType.APPLICATION_JSON_TYPE).build(); } } else { log.error("TOTPKeyGenerator endpoint could not generate the key"); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error when generating the key") .type(MediaType.APPLICATION_JSON_TYPE).build(); } }
Source:
<code>public SystemConsumer getConsumer(String systemName, Config config, MetricsRegistry registry) { EventHubConfig eventHubConfig = new EventHubConfig(config, systemName); <START> return new EventHubSystemConsumer(eventHubConfig, new EventHubClientWrapperFactory(), getSerdesMap(eventHubConfig), <END> registry); }</code><technical_language>call EventHubClientWrapper SamzaEventHubClient? name "wrapper" slightly confusing</technical_language>

Target:
public SystemConsumer getConsumer(String systemName, Config config, MetricsRegistry registry) { EventHubConfig eventHubConfig = new EventHubConfig(config); return new EventHubSystemConsumer(eventHubConfig, systemName, new EventHubClientManagerFactory(), getInterceptorsMap(eventHubConfig, systemName), registry); }
Source:
<code>private boolean isMetadataExpired() { <START> return !(cacheDuration == null || Instant.now().isAfter(created.plus(cacheDuration))); <END> }</code><technical_language>I test isBefore. 1. cacheDuration == null, short-circuit out of conditional a true is toggled a false: implying _Not Expired_ 2. cacheDuration != null, continue next test; if isAfter (created + cacheDuration) return true is toggled a false: implying _Not Expired_ 3. cacheDuration != null, continue next test; if isNotAfter (created + cacheDuration) return false is toggled a true: implying _Expired_ misreading this test, instead java return !(cacheDuration == null || created.plus(cacheDuration).isAfter(Instant.now()));</technical_language>

Target:
private boolean isMetadataExpired() { if (getCacheDuration() == null) { return false; } if (getCacheDuration().isZero()) { return true; } return Instant.now().isAfter(created.plus(getCacheDuration())); }
Source:
<code>public void onUpdateProgress(int currentProgress, int duration, int bufferPercent) { updateProgress(currentProgress, duration, bufferPercent); if (!shouldUpdateOnProgress) return; resetNotification(); <START> if(Build.VERSION.SDK_INT >= 26 ) updateNotificationThumbnail(); <END> if (bigNotRemoteView != null) { if(cachedDuration != duration) { cachedDuration = duration; cachedDurationString = getTimeString(duration); } bigNotRemoteView.setProgressBar(R.id.notificationProgressBar, duration, currentProgress, false); bigNotRemoteView.setTextViewText(R.id.notificationTime, getTimeString(currentProgress) + " / " + cachedDurationString); } if (notRemoteView != null) { notRemoteView.setProgressBar(R.id.notificationProgressBar, duration, currentProgress, false); } updateNotification(-1); }</code><technical_language>I this line while reviewing PR want send a new PR for this single change. Please add :) suggestion if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O /*Oreo*/) updateNotificationThumbnail();</technical_language>

Target:
public void onUpdateProgress(int currentProgress, int duration, int bufferPercent) { updateProgress(currentProgress, duration, bufferPercent); if (!shouldUpdateOnProgress) return; resetNotification(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) updateNotificationThumbnail(); if (bigNotRemoteView != null) { if(cachedDuration != duration) { cachedDuration = duration; cachedDurationString = getTimeString(duration); } bigNotRemoteView.setProgressBar(R.id.notificationProgressBar, duration, currentProgress, false); bigNotRemoteView.setTextViewText(R.id.notificationTime, getTimeString(currentProgress) + " / " + cachedDurationString); } if (notRemoteView != null) { notRemoteView.setProgressBar(R.id.notificationProgressBar, duration, currentProgress, false); } updateNotification(-1); }
Source:
<code>void testTryWithResourcesConnectsThenReceivesEvent() throws InterruptedException { server.expect() .withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true") .andUpgradeToWebSocket().open() .waitFor(EVENT_WAIT_PERIOD_MS).andEmit(new WatchEvent(pod1, "DELETED")) .waitFor(EVENT_WAIT_PERIOD_MS).andEmit(outdatedEvent()).done().once(); final CountDownLatch deleteLatch = new CountDownLatch(1); final CountDownLatch closeLatch = new CountDownLatch(1); final Watcher<Pod> watcher = new Watcher<Pod>() { @Override public void eventReceived(Action action, Pod resource) { if (action != DELETED) { fail(); } deleteLatch.countDown(); } @Override public void onClose(WatcherException cause) { <START> assertEquals(410, cause.asClientException().getCode()); <END> closeLatch.countDown(); } }; try (Watch watch = client.pods().withName("pod1").withResourceVersion("1").watch(watcher)) { assertNotNull(watch); assertTrue(deleteLatch.await(10, TimeUnit.SECONDS)); assertTrue(closeLatch.await(10, TimeUnit.SECONDS)); } }</code><technical_language>suggestion assertTrue(410, cause.isHttpGone());</technical_language>

Target:
void testTryWithResourcesConnectsThenReceivesEvent() throws InterruptedException { server.expect() .withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true") .andUpgradeToWebSocket().open() .waitFor(EVENT_WAIT_PERIOD_MS).andEmit(new WatchEvent(pod1, "DELETED")) .waitFor(EVENT_WAIT_PERIOD_MS).andEmit(outdatedEvent()).done().once(); final CountDownLatch deleteLatch = new CountDownLatch(1); final CountDownLatch closeLatch = new CountDownLatch(1); final Watcher<Pod> watcher = new Watcher<Pod>() { @Override public void eventReceived(Action action, Pod resource) { if (action != DELETED) { fail(); } deleteLatch.countDown(); } @Override public void onClose(WatcherException cause) { assertTrue(cause.isHttpGone()); closeLatch.countDown(); } }; try (Watch watch = client.pods().withName("pod1").withResourceVersion("1").watch(watcher)) { assertNotNull(watch); assertTrue(deleteLatch.await(10, TimeUnit.SECONDS)); assertTrue(closeLatch.await(10, TimeUnit.SECONDS)); } }
Source:
<code>public Location findPortal(Location destination) { Location minLoc = null; double minDistance = Double.MAX_VALUE; final int blockX = destination.getBlockX(); final int blockZ = destination.getBlockZ(); for (int x = blockX - searchRadius; x < (blockX + searchRadius); x++) { for (int z = blockZ - searchRadius; z < (blockZ + searchRadius); z++) { <START> for (int y = 127; y >= 0; y--) { <END> final Block toCompare = world.getBlockAt(x, y, z); if (toCompare.getType() == Material.PORTAL && toCompare.getRelative(BlockFace.DOWN).getType() != Material.PORTAL ) { final Location location = toCompare.getLocation(); double distance = RayUtil.getRayBetween(location, destination).length(); if (distance < minDistance) { minDistance = distance; minLoc = location; } } } } } return minLoc; }</code><technical_language>I start y depending world type is in Vanilla Minecraft (127 for nether, 255 for rest)</technical_language>

Target:
public Location findPortal(Location destination) { Location minLoc = null; double minDistance = Double.MAX_VALUE; final int maxY = world.getEnvironment() == World.Environment.NETHER ? 127 : 255; final int blockX = destination.getBlockX(); final int blockZ = destination.getBlockZ(); for (int x = blockX - searchRadius; x < (blockX + searchRadius); x++) { for (int z = blockZ - searchRadius; z < (blockZ + searchRadius); z++) { for (int y = maxY; y >= 0; y--) { final Block toCompare = world.getBlockAt(x, y, z); if (toCompare.getType() == Material.PORTAL && toCompare.getRelative(BlockFace.DOWN).getType() != Material.PORTAL ) { final Location location = toCompare.getLocation(); double distance = RayUtil.getRayBetween(location, destination).length(); if (distance < minDistance) { minDistance = distance; minLoc = location; } } } } } return minLoc; }
Source:
<code>void errorOutWriteLacKey(final CompletionKey key, final int rc) { <START> LOG.info("Removing completion key: {}", key); <END> final WriteLacCompletion writeLacCompletion = (WriteLacCompletion)completionObjects.remove(key); if (null == writeLacCompletion) { return; } executor.submitOrdered(writeLacCompletion.ledgerId, new SafeRunnable() { @Override public void safeRun() { String bAddress = "null"; Channel c = channel; if (c != null) { bAddress = c.getRemoteAddress().toString(); } LOG.debug("Could not write request writeLac for ledgerId: bookie: {}", new Object[] { writeLacCompletion.ledgerId, bAddress}); writeLacCompletion.cb.writeLacComplete(rc, writeLacCompletion.ledgerId, addr, writeLacCompletion.ctx); } }); }</code><technical_language>@govind-menon remove change "debug" level</technical_language>

Target:
void errorOutWriteLacKey(final CompletionKey key, final int rc) { LOG.debug("Removing completion key: {}", key); final WriteLacCompletion writeLacCompletion = (WriteLacCompletion)completionObjects.remove(key); if (null == writeLacCompletion) { return; } executor.submitOrdered(writeLacCompletion.ledgerId, new SafeRunnable() { @Override public void safeRun() { String bAddress = "null"; Channel c = channel; if (c != null) { bAddress = c.getRemoteAddress().toString(); } LOG.debug("Could not write request writeLac for ledgerId: bookie: {}", new Object[] { writeLacCompletion.ledgerId, bAddress}); writeLacCompletion.cb.writeLacComplete(rc, writeLacCompletion.ledgerId, addr, writeLacCompletion.ctx); } }); }
Source:
<code>public ErrorsAndDMNModelAsSerialized(List<Message> messages, Definitions definitions) { <START> super(); <END> this.messages = Collections.unmodifiableList(messages); this.definitions = definitions; }</code><technical_language>need a call super()</technical_language>

Target:
public ErrorsAndDMNModelAsSerialized(List<Message> messages, Definitions definitions) { this.messages = Collections.unmodifiableList(messages); this.definitions = definitions; }
Source:
<code>protected void refreshVisuals() { Connector connector = (Connector) getNotationView(); <START> NamedStyle namedStyle = connector.getNamedStyle(NotationPackage.Literals.INT_VALUE_STYLE, "delta"); <END> if (namedStyle instanceof IntValueStyle) { refreshArrowDelta((IntValueStyle) namedStyle); } else { ((DurationLinkFigure) getFigure()).setArrowPositionDelta(0); } super.refreshVisuals(); }</code><technical_language>a convention, is typically responsibility of refreshSomething() method extract style change figure. #refreshVisuals() typically calls #refreshSomething() methods, method reads style notation, calls #setSomething() Figure Also, #refreshSomething() methods protected, subclasses adapt behavior, install listeners (Although in case, I doubt override DurationLink EditParts)</technical_language>

Target:
protected void refreshVisuals() { refreshArrowDelta(); super.refreshVisuals(); }
Source:
<code>protected BlobServiceClient buildBlobServiceClient(HttpClient httpClient, Configuration configuration, RequestRetryOptions retryOptions, AzureCloudConfig azureCloudConfig) throws MalformedURLException, InterruptedException, ExecutionException { IAuthenticationResult iAuthenticationResult = getAccessTokenByClientCredentialGrant(azureCloudConfig); <START> return new BlobServiceClientBuilder().credential(new TokenCredential() { <END> @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.just(new AccessToken(iAuthenticationResult.accessToken(), iAuthenticationResult.expiresOnDate().toInstant().atOffset(OffsetDateTime.now().getOffset()))); } }) .endpoint(azureCloudConfig.azureStorageEndpoint) .httpClient(httpClient) .retryOptions(retryOptions) .configuration(configuration) .buildClient(); }</code><technical_language>Minor: easier read if split credential construction line</technical_language>

Target:
protected BlobServiceClient buildBlobServiceClient(HttpClient httpClient, Configuration configuration, RequestRetryOptions retryOptions, AzureCloudConfig azureCloudConfig) throws MalformedURLException, InterruptedException, ExecutionException { IAuthenticationResult iAuthenticationResult = getAccessTokenByClientCredentialGrant(azureCloudConfig); TokenCredential tokenCredential = new TokenCredential() { @Override public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.just(new AccessToken(iAuthenticationResult.accessToken(), iAuthenticationResult.expiresOnDate().toInstant().atOffset(OffsetDateTime.now().getOffset()))); } }; return new BlobServiceClientBuilder().credential(tokenCredential) .endpoint(azureCloudConfig.azureStorageEndpoint) .httpClient(httpClient) .retryOptions(retryOptions) .configuration(configuration) .buildClient(); }
Source:
<code>public static void postAnswer(Topic topic, Post post) throws PermissionsDeniedException, CouldNotOpenPageException, ValidationException { openRequiredTopic(topic); postPage.getMessageField().clear(); <START> postPage.getMessageField().sendKeys(post.getPostContent()); <END> postPage.clickAnswerToTopicButton(); assertTopicPostFormValid(); topic.addPost(post); info("Answer to topic [" + topic.getTitle() + "] was left"); }</code><technical_language>re-use methods TopicPage instead? create similar ones.</technical_language>

Target:
public static void postAnswer(Topic topic, Post post) throws PermissionsDeniedException, CouldNotOpenPageException, ValidationException { openRequiredTopic(topic); postPage.fillPostBody(post.getPostContent()); postPage.clickAnswerToTopicButton(); assertTopicPostFormValid(); topic.addPost(post); info("Answer to topic [" + topic.getTitle() + "] was left"); }
Source:
<code>protected void applyValidation() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (getControls().size() == 0 || getControls().values().iterator().next().isDisposed()) { return; } Label validationIcon = null; switch (getControls().size()) { case 3: validationIcon = Label.class.cast(getControls().get( new SWTGridCell(0, 1, CustomControlSWTRenderer.this))); break; default: break; } final VDiagnostic diag = getVElement().getDiagnostic(); <START> if (validationIcon != null && !validationIcon.isDisposed() && diag != null) { <END> validationIcon.setImage(getValidationIcon(diag.getHighestSeverity())); validationIcon.setToolTipText(diag.getMessage()); } if (swtCustomControl != null) { swtCustomControl.applyValidation(); } } }); }</code><technical_language>diag null check place testing if icon is disposed? nitpicking ;)</technical_language>

Target:
protected void applyValidation() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { if (getControls().size() == 0 || getControls().values().iterator().next().isDisposed()) { return; } Label validationIcon = null; switch (getControls().size()) { case 3: validationIcon = Label.class.cast(getControls().get( new SWTGridCell(0, 1, CustomControlSWTRenderer.this))); break; default: break; } final VDiagnostic diag = getVElement().getDiagnostic(); if (diag != null && validationIcon != null && !validationIcon.isDisposed()) { validationIcon.setImage(getValidationIcon(diag.getHighestSeverity())); validationIcon.setToolTipText(diag.getMessage()); } if (swtCustomControl != null) { swtCustomControl.applyValidation(); } } }); }
Source:
<code>public Collection<Class<?>> getProvidedServiceTypes() { <START> return Collections.singletonList(DetailedServerStateImpl.class); <END> }</code><technical_language>interface</technical_language>

Target:
public Collection<Class<?>> getProvidedServiceTypes() { return Collections.singletonList(DetailedServerState.class); }
Source:
<code>public synchronized ListenableFuture identify(LDUser user) { <START> if (user == null || user.getKey() == null) { <END> Log.w(TAG, "identify called with null user or null user key!"); } ListenableFuture doneFuture = userManager.setCurrentUser(user); sendEvent(new IdentifyEvent(user)); return doneFuture; }</code><technical_language>Do want bail here, do want set current user null</technical_language>

Target:
public synchronized ListenableFuture<Void> identify(LDUser user) { if (user == null) { return Futures.immediateFailedFuture(new LaunchDarklyException("User cannot be null")); } if (user.getKey() == null) { Log.w(TAG, "identify called with null user or null user key!"); } ListenableFuture<Void> doneFuture = userManager.setCurrentUser(user); sendEvent(new IdentifyEvent(user)); return doneFuture; }
Source:
<code>private Boolean testBeaconHelper(String chromosome, int start, String allele, List<String> datasetIds) { String url = String.format("/v1/ga4gh/beacon?referenceName=%s&start=%d&allele=%s&datasetIds=%s", chromosome, start, allele, String.join(",", datasetIds)); ResponseEntity<GA4GHBeaconResponse> response = restTemplate.getForEntity( url, GA4GHBeaconResponse.class); assertEquals(HttpStatus.OK, response.getStatusCode()); <START> GA4GHBeaconResponse ga4GHBeaconResponse = response.getBody(); <END> return ga4GHBeaconResponse.isExists(); }</code><technical_language>ga4ghBeaconResponse variable for more consistent capitalization</technical_language>

Target:
private boolean testBeaconHelper(String chromosome, int start, String allele, List<String> datasetIds) { String url = String.format("/v1/ga4gh/beacon?referenceName=%s&start=%d&allele=%s&datasetIds=%s", chromosome, start, allele, String.join(",", datasetIds)); ResponseEntity<GA4GHBeaconResponse> response = restTemplate.getForEntity( url, GA4GHBeaconResponse.class); assertEquals(HttpStatus.OK, response.getStatusCode()); GA4GHBeaconResponse ga4ghBeaconResponse = response.getBody(); return ga4ghBeaconResponse.isExists(); }
Source:
<code>public EntityReference resolveRelativeEntityReference(String name, EntityType type) { EntityReference ref = relativeRefResolver.resolve(name, type); <START> LOGGER.debug("resolveRelativeEntityReference: for [" + name + "] got reference [" + ref + "]"); <END> return ref; }</code><technical_language>please logger StringBuilder call debug(String message, Object replacement1..., Throwable)</technical_language>

Target:
public EntityReference resolveRelativeEntityReference(String name, EntityType type) { EntityReference ref = relativeRefResolver.resolve(name, type); LOGGER.debug("resolveRelativeEntityReference: for '{}' got ref '{}'", name, ref); return ref; }
Source:
<code>public String getName() { <START> Preconditions.checkState( (name == null && userRole.equals(UserRole.HOST)) || (name != null && !userRole.equals(UserRole.HOST)), <END> "All user roles will have a name except the 'HOST' role (lobby watcher)"); return name; }</code><technical_language>java Preconditions.checkState((name == null) == userRole.equals(UserRole.HOST));</technical_language>

Target:
public String getName() { Preconditions.checkState( (name == null) == userRole.equals(UserRole.HOST), "All user roles will have a name except the 'HOST' role (lobby watcher)"); return name; }
Source:
<code>protected void buildProject(IProject proj) throws CoreException { IWorkspace wsp = ResourcesPlugin.getWorkspace(); final IProject curProject = proj; ISchedulingRule rule = wsp.getRuleFactory().buildRule(); Job buildJob = new Job("project build job") { @Override protected IStatus run(IProgressMonitor monitor) { try { curProject.build(IncrementalProjectBuilder.FULL_BUILD, null); } catch (CoreException e) { fail(e.getStatus().getMessage()); } catch (OperationCanceledException e) { fail(NLS.bind(Messages.getString("AbstractTest.Build_cancelled"), curProject.getName(), e.getMessage())); } catch(Exception e) { e.printStackTrace(); fail(e.getLocalizedMessage()); } return Status.OK_STATUS; } }; try { buildJob.setRule(rule); buildJob.schedule(); buildJob.join(); IStatus status = buildJob.getResult(); if (status.getCode() != IStatus.OK) { fail(NLS.bind(Messages.getString("AbstractTest.Build_failed"), curProject.getName(), status.getMessage())); } } catch (InterruptedException e) { fail(NLS.bind(Messages.getString("AbstractTest.Build_interrupted"), curProject.getName(), e.getMessage())); <START> } catch(Exception e) { <END> fail(e.getLocalizedMessage()); } IWorkspaceRunnable runnable = new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { curProject.refreshLocal(IResource.DEPTH_INFINITE, null); } }; wsp.run(runnable, wsp.getRoot(), IWorkspace.AVOID_UPDATE, null); }</code><technical_language>Specific exceptions caught here</technical_language>

Target:
protected void buildProject(IProject proj) throws CoreException { IWorkspace wsp = ResourcesPlugin.getWorkspace(); final IProject curProject = proj; ISchedulingRule rule = wsp.getRuleFactory().buildRule(); Job buildJob = new Job("project build job") { @Override protected IStatus run(IProgressMonitor monitor) { try { curProject.build( IncrementalProjectBuilder.FULL_BUILD, null); } catch (CoreException e) { fail(e.getStatus().getMessage()); } catch (OperationCanceledException e) { fail(NLS.bind(Messages.getString("AbstractTest.Build_cancelled"), curProject.getName(), e.getMessage())); } return Status.OK_STATUS; } }; buildJob.setRule(rule); buildJob.schedule(); try { buildJob.join(); } catch (InterruptedException e) { fail(NLS.bind(Messages.getString("AbstractTest.Build_interrupted"), curProject.getName(), e.getMessage())); } IStatus status = buildJob.getResult(); if (status.getCode() != IStatus.OK) { fail(NLS.bind(Messages.getString("AbstractTest.Build_failed"), curProject.getName(), status.getMessage())); } IWorkspaceRunnable runnable = new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { curProject.refreshLocal(IResource.DEPTH_INFINITE, null); } }; wsp.run(runnable, wsp.getRoot(), IWorkspace.AVOID_UPDATE, null); }
Source:
<code>private void doSearch() { final String query = searchBox.getText().trim(); if (query.length() == 0 || Gerrit.C.searchHint().equals(query)) { return; } searchBox.setFocus(false); if (query.matches("^[1-9][0-9]*$")) { final Change.Id ck = Change.Id.parse(query); Gerrit.display(Link.toChange(ck), new ChangeScreen(ck)); } else if (query.contains("owner:")) { <START> Gerrit.display(Link.toOwnerQuery(query), true ); <END> } else if (query.contains("reviewer:")) { Gerrit.display(Link.toReviewerQuery(query), true ); } else { Gerrit.display(Link.toChangeQuery(query), true); } }</code><technical_language>I intended fall else toChangeQuery case below, server perform magic of decoding query string produce a result. Reason is, in future able efficiently support "4419 (owner:bob is:closed)". This simple change jump case above, server needs consider more "owner" predicate</technical_language>

Target:
private void doSearch() { final String query = searchBox.getText().trim(); if (query.length() == 0 || Gerrit.C.searchHint().equals(query)) { return; } searchBox.setFocus(false); if (query.matches("^[1-9][0-9]*$")) { final Change.Id ck = Change.Id.parse(query); Gerrit.display(Link.toChange(ck), new ChangeScreen(ck)); } else { Gerrit.display(Link.toChangeQuery(query), true); } }
Source:
<code>public void getCashPointsByLocation_shouldNotReturnRetiredCashpointsUnlessSpecified() throws Exception { CashPoint cashPoint = service.getById(2); cashPoint.setRetired(true); cashPoint.setRetireReason("reason"); service.save(cashPoint); Location location = Context.getLocationService().getLocation(2); Context.flushSession(); List<CashPoint> cashPoints = service.getCashPointsByLocation(location,false); Assert.assertNotNull(cashPoints); Assert.assertEquals(0,cashPoints.size()); <START> for (CashPoint cashpoint : cashPoints) { <END> if(cashpoint.getId().equals(cashPoint.getId())) { Assert.fail("The retired item was incorrectly returned."); } } cashPoints = service.getCashPointsByLocation(location,false); Assert.assertNotNull(cashPoints); Assert.assertEquals(0,cashPoints.size()); }</code><technical_language>confirmed size is zero. need this for loop</technical_language>

Target:
public void getCashPointsByLocation_shouldNotReturnRetiredCashpointsUnlessSpecified() throws Exception { CashPoint cashPoint = service.getById(0); cashPoint.setRetired(true); cashPoint.setRetireReason("reason"); service.save(cashPoint); Location location = Context.getLocationService().getLocation(0); Context.flushSession(); List<CashPoint> cashPoints = service.getCashPointsByLocation(location,false); Assert.assertNotNull(cashPoints); Assert.assertEquals(2,cashPoints.size()); Assert.assertEquals(4,(int)Iterators.get(cashPoints.iterator(),0).getId()); Assert.assertEquals(5,(int)Iterators.get(cashPoints.iterator(),1).getId()); List<CashPoint> cashPoints1 = service.getCashPointsByLocation(location,true); Assert.assertNotNull(cashPoints1); Assert.assertEquals(3,cashPoints1.size()); Assert.assertEquals(0,(int)Iterators.get(cashPoints1.iterator(),0).getId()); }
Source:
<code>private int ilog(int a) { if (a <= 0) { return 0; } <START> int n = 0; <END> while (a > 0) { a >>= 1; n++; } return n; }</code><technical_language>occured good Integer a bitCount method same, probably. used? (It mention negative numbers I assume treats other number.)</technical_language>

Target:
private int ilog(int a) { if (a <= 0) { return 0; } return 32 - Integer.numberOfLeadingZeros(a); }
Source:
<code>private static Iterable<Artifact> getProducedRuntimeJars( ConfiguredTarget base, RuleContext ruleContext) { <START> JavaInfo javaInfo = JavaInfo.getJavaInfo(base); <END> if (javaInfo != null) { return javaInfo.getDirectRuntimeJars(); } else if (isProtoLibrary(ruleContext)) { if (!ruleContext.getPrerequisites("srcs", Mode.TARGET).isEmpty()) { JavaRuleOutputJarsProvider outputJarsProvider = base.getProvider(JavaRuleOutputJarsProvider.class); if (outputJarsProvider != null) { return outputJarsProvider .getOutputJars() .stream() .map(OutputJar::getClassJar) .collect(toImmutableList()); } } } return null; }</code><technical_language>issues current logic order unchanged here</technical_language>

Target:
private static Iterable<Artifact> getProducedRuntimeJars( ConfiguredTarget base, RuleContext ruleContext) { if (isProtoLibrary(ruleContext)) { if (!ruleContext.getPrerequisites("srcs", Mode.TARGET).isEmpty()) { JavaRuleOutputJarsProvider outputJarsProvider = base.getProvider(JavaRuleOutputJarsProvider.class); if (outputJarsProvider != null) { return outputJarsProvider .getOutputJars() .stream() .map(OutputJar::getClassJar) .collect(toImmutableList()); } else { JavaInfo javaInfo = JavaInfo.getJavaInfo(base); if (javaInfo != null) { return javaInfo.getDirectRuntimeJars(); } } } } else { JavaInfo javaInfo = JavaInfo.getJavaInfo(base); if (javaInfo != null) { return javaInfo.getDirectRuntimeJars(); } } return null; }
Source:
<code>public CredentialSupport getCredentialSupport(Class<?> credentialType) throws RealmUnavailableException { for (QueryConfiguration configuration : this.queryConfiguration) { for (ColumnMapper mapper : configuration.getColumnMappers()) { if (KeyMapper.class.isInstance(mapper)) { KeyMapper credentialMapper = (KeyMapper) mapper; if (credentialType.equals(credentialMapper.getCredentialType())) { <START> return CredentialSupport.FULLY_SUPPORTED; <END> } } } } return CredentialSupport.UNSUPPORTED; }</code><technical_language>some accounts credential types them</technical_language>

Target:
public CredentialSupport getCredentialSupport(Class<?> credentialType) throws RealmUnavailableException { for (QueryConfiguration configuration : this.queryConfiguration) { for (ColumnMapper mapper : configuration.getColumnMappers()) { if (KeyMapper.class.isInstance(mapper)) { KeyMapper keyMapper = (KeyMapper) mapper; if (credentialType.equals(keyMapper.getKeyType())) { return CredentialSupport.UNKNOWN; } } } } return CredentialSupport.UNSUPPORTED; }
Source:
<code>public void onLocationChanged(Location location) { User user = User.getCurrentUser(); if (user == null) return; <START> if (lastLatitude == location.getLatitude()) <END> if (lastLongitude == location.getLongitude()) return; user.setLocation( lastLatitude = location.getLatitude(), lastLongitude = location.getLongitude() ); user.saveEventually(); try { UserUpdateChannel.publish(user); } catch (JSONException e) { onLocationTrackingFailed(e); } }</code><technical_language>this simplified if (lastLatitude == location.getLatitude() && lastLongitude == location.getLongitude()) return? (&&)</technical_language>

Target:
public void onLocationChanged(Location location) { User user = User.getCurrentUser(); if (user == null) return; ParseGeoPoint last = user.getLocation(); if (last.getLatitude() == location.getLatitude() && last.getLongitude() == location.getLongitude()) return; user.setLocation(location.getLatitude(), location.getLongitude()); user.saveEventually(); try { UserUpdateChannel.publish(user); } catch (JSONException e) { onLocationTrackingFailed(e); } }
Source:
<code><START> protected final boolean credentialsRetryable(Function<Credentials, Access> getAccess) { <END> return CredentialTypes.isRetryable(getAccess); }</code><technical_language>expose CredentialType object instead of a boolean</technical_language>

Target:
protected final CredentialType credentialsRetryable(Function<Credentials, Access> getAccess) { return CredentialTypes.credentialTypeObjectOf(getAccess); }
Source:
<code>public Collection<Order> getOrder(String... orderIds) throws IOException { Collection<Order> orders = new ArrayList<>(); for (String orderId : orderIds) { CoingiGetOrderRequest request = new CoingiGetOrderRequest().setOrderId(orderId); CoingiOrder coingiOrder; try { <START> coingiOrder = getCoingiOrder(request); <END> } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } CurrencyPair currencyPair = CoingiAdapters.adaptCurrency(coingiOrder.getCurrencyPair()); Date date = new Date(coingiOrder.getTimestamp() * 1000); Order order = new LimitOrder( coingiOrder.getType() == 0 ? Order.OrderType.BID : Order.OrderType.ASK, coingiOrder.getOriginalBaseAmount(), currencyPair, coingiOrder.getId(), date, coingiOrder.getPrice()); order.setOrderStatus(CoingiAdapters.adaptOrderStatus(coingiOrder.getStatus())); orders.add(order); } return orders; }</code><technical_language>try / catch CoingiException hit applied</technical_language>

Target:
public Collection<Order> getOrder(String... orderIds) throws IOException { try { Collection<Order> orders = new ArrayList<>(); for (String orderId : orderIds) { CoingiGetOrderRequest request = new CoingiGetOrderRequest().setOrderId(orderId); CoingiOrder coingiOrder; coingiOrder = getCoingiOrder(request); CurrencyPair currencyPair = CoingiAdapters.adaptCurrency(coingiOrder.getCurrencyPair()); Date date = new Date(coingiOrder.getTimestamp() * 1000); Order order = new LimitOrder( coingiOrder.getType() == 0 ? Order.OrderType.BID : Order.OrderType.ASK, coingiOrder.getOriginalBaseAmount(), currencyPair, coingiOrder.getId(), date, coingiOrder.getPrice()); order.setOrderStatus(CoingiAdapters.adaptOrderStatus(coingiOrder.getStatus())); orders.add(order); } return orders; } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } }
Source:
<code>public QosMetrics() { readRequestCount = metricsManager.registerMeter(QosMetrics.class, "numReadRequests"); writeRequestCount = metricsManager.registerMeter(QosMetrics.class, "numWriteRequests"); <START> bytesRead = metricsManager.registerHistogram(QosMetrics.class, "bytesRead"); <END> bytesWritten = metricsManager.registerHistogram(QosMetrics.class, "bytesWritten"); }</code><technical_language>if sliding time window reservoir, need consider memory bounds overhead of require</technical_language>

Target:
public QosMetrics() { readRequestCount = metricsManager.registerMeter(QosMetrics.class, "numReadRequests"); writeRequestCount = metricsManager.registerMeter(QosMetrics.class, "numWriteRequests"); bytesRead = metricsManager.registerMeter(QosMetrics.class, "bytesRead"); bytesWritten = metricsManager.registerMeter(QosMetrics.class, "bytesWritten"); }
Source:
<code>public static Case getOpenCase() throws NoCurrentCaseException { try { Case openCase = new Case(currentCase.getCaseType(), currentCase.getCacheDirectory(), new CaseDetails(currentCase.getDisplayName(), currentCase.getNumber(), currentCase.getExaminer(), currentCase.getExaminerPhone(), currentCase.getExaminerEmail(), currentCase.getCaseNotes())); <START> return openCase; <END> } catch (NullPointerException ex) { throw new NoCurrentCaseException(); } }</code><technical_language>For this fix, making a local copy of reference in currentCase, checking local reference for null, finally returning local reference. This prevent another thread closing case, a bit risk returning null violating contract of method. Dealing possibility of current case closed while other objects a reference is a bigger problem for another story</technical_language>

Target:
public static Case getOpenCase() throws NoCurrentCaseException { Case openCase = currentCase; if (null != openCase) { return openCase; } else { throw new NoCurrentCaseException(); } }
Source:
<code>private IndexManager indexManager() { <START> graphDatabase().beginTx(); <END> return graphDatabase().index(); }</code><technical_language>hmmm, this a transaction running lifetime of IndexManager, weird behaviour if mistaken</technical_language>

Target:
private IndexManager indexManager() { return graphDatabase().index(); }
Source:
<code>public void setAttribute(String name, List<String> values) { removeAttribute(name); <START> List<String> nonNullValues = values.stream().filter(Objects::nonNull).collect(Collectors.toList()); <END> for (String value : nonNullValues) { persistAttributeValue(name, value); } }</code><technical_language>need realize this list memory .collect. obtain a stream iterator() Stream.forEach()</technical_language>

Target:
public void setAttribute(String name, List<String> values) { removeAttribute(name); for (Iterator<String> it = values.stream().filter(Objects::nonNull).iterator(); it.hasNext();) { persistAttributeValue(name, it.next()); } }
Source:
<code>void process(Content dataSource, IngestJobContext context) { this.dataSource = dataSource; this.context = context; <START> dataFound = false; <END> this.processWebCache(); this.getBookmark(); }</code><technical_language>I this dataFound field is another protected field in super class. For this story, do partial fix of adding a protected setter for super class field this new code instead of writing field</technical_language>

Target:
void process(Content dataSource, IngestJobContext context) { this.dataSource = dataSource; this.context = context; this.setFoundData(false); List<AbstractFile> webCacheFiles = null; List<AbstractFile> spartanFiles = null; try { webCacheFiles = fetchWebCacheFiles(); } catch (TskCoreException ex) { this.addErrorMessage(Bundle.ExtractEdge_process_errMsg_errGettingWebCacheFiles()); logger.log(Level.SEVERE, "Error fetching 'WebCacheV01.dat' files for Microsoft Edge", ex); } try { spartanFiles = fetchSpartanFiles(); } catch (TskCoreException ex) { this.addErrorMessage(Bundle.ExtractEdge_process_errMsg_spartanFail()); logger.log(Level.SEVERE, "Error fetching 'spartan.edb' files for Microsoft Edge", ex); } if (webCacheFiles == null && spartanFiles == null) { return; } this.setFoundData(true); if (!PlatformUtil.isWindowsOS()) { logger.log(Level.WARNING, "Microsoft Edge files found, unable to parse on Non-Windows system"); return; } final String esedumper = getPathForESEDumper(); if (esedumper == null) { this.addErrorMessage(Bundle.ExtractEdge_process_errMsg_unableFindESEViewer()); logger.log(Level.SEVERE, "Error finding ESEDatabaseViewer program"); return; } if (context.dataSourceIngestIsCancelled()) { return; } try { this.processWebCache(esedumper, webCacheFiles); } catch (IOException ex) { this.addErrorMessage(Bundle.ExtractEdge_process_errMsg_webcacheFail()); logger.log(Level.SEVERE, "Error returned from processWebCach", ex); } if (context.dataSourceIngestIsCancelled()) { return; } this.getBookmark(); }