auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldHaveTheSessionTimeout() throws Exception { final Cluster cluster = TestClientFactory.open(); final Client client = cluster.connect(name.getMethodName()); final ResultSet results1 = client.submit("x = [1,2,3,4,5,6,7,8,9]"); final AtomicInteger counter = new AtomicInteger(0); results1.stream().map(i -> i.get(Integer.class) * 2).forEach(i -> assertEquals(counter.incrementAndGet() * 2, Integer.parseInt(i.toString()))); final ResultSet results2 = client.submit("x[0]+1"); assertEquals(2, results2.all().get().get(0).getInt()); Thread.sleep(3500); try { client.submit("x[1]+2").all().get(); fail("Session should be dead"); } catch (Exception ex) { final Throwable cause = ex.getCause(); assertThat(cause, instanceOf(ResponseException.class)); assertEquals(ResponseStatusCode.SERVER_ERROR_SCRIPT_EVALUATION, ((ResponseException) cause).getResponseStatusCode()); assertEquals(2, client.submit("1+1").all().join().get(0).getInt()); } finally { cluster.close(); } <START> this.stopServer(); <END> assertEquals(2, recordingAppender.getMessages().stream() .filter(msg -> msg.contains("Session shouldHaveTheSessionTimeout closed")).count()); }</code><technical_language>a reason stopServer() get this test pass</technical_language>

Target:
public void shouldHaveTheSessionTimeout() throws Exception { final Cluster cluster = TestClientFactory.open(); final Client client = cluster.connect(name.getMethodName()); final ResultSet results1 = client.submit("x = [1,2,3,4,5,6,7,8,9]"); final AtomicInteger counter = new AtomicInteger(0); results1.stream().map(i -> i.get(Integer.class) * 2).forEach(i -> assertEquals(counter.incrementAndGet() * 2, Integer.parseInt(i.toString()))); final ResultSet results2 = client.submit("x[0]+1"); assertEquals(2, results2.all().get().get(0).getInt()); Thread.sleep(3500); try { client.submit("x[1]+2").all().get(); fail("Session should be dead"); } catch (Exception ex) { final Throwable cause = ex.getCause(); assertThat(cause, instanceOf(ResponseException.class)); assertEquals(ResponseStatusCode.SERVER_ERROR_SCRIPT_EVALUATION, ((ResponseException) cause).getResponseStatusCode()); assertEquals(2, client.submit("1+1").all().join().get(0).getInt()); } finally { cluster.close(); } assertEquals(2, recordingAppender.getMessages().stream() .filter(msg -> msg.contains("Session shouldHaveTheSessionTimeout closed")).count()); }
Source:
<code>public void start() { startMetrics(); systemAdmins.start(); <START> zkUtils.validateZkVersion(); <END> leaderElector.tryBecomeLeader(); zkUtils.subscribeToJobModelVersionChange(new ZkJobModelVersionChangeHandler(zkUtils)); }</code><technical_language>this happen key validation (e.g. in constructor here)</technical_language>

Target:
public void start() { ZkKeyBuilder keyBuilder = zkUtils.getKeyBuilder(); zkUtils.validateZkVersion(); zkUtils.validatePaths(new String[]{keyBuilder.getProcessorsPath(), keyBuilder.getJobModelVersionPath(), keyBuilder .getJobModelPathPrefix()}); startMetrics(); systemAdmins.start(); leaderElector.tryBecomeLeader(); zkUtils.subscribeToJobModelVersionChange(new ZkJobModelVersionChangeHandler(zkUtils)); }
Source:
<code>public BlobClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint); URL url; try { <START> url = new URL(endpoint); <END> this.endpoint = new URL(url.getProtocol() + "://" + url.getAuthority()); String path = url.getPath(); if (path != null && !path.isEmpty() && !path.equals("/")) { path = path.replaceAll("^/", "").replaceAll("/$", ""); String[] segments = path.split("/", 2); if (segments.length != 2) { throw new IllegalArgumentException("Endpoint should contain 0 or at least 2 path segments"); } else { this.containerName = segments[0]; this.blobName = segments[1]; } } } catch (MalformedURLException ex) { throw new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."); } SASTokenCredential credential = SASTokenCredential.fromQuery(url.getQuery()); if (credential != null) { this.sasTokenCredential = credential; } return this; }</code><technical_language>This type of URL parsing a lot in Storage SDKs, promote this functionality a utility class in commons? Potentially move this Azure Core if fit</technical_language>

Target:
public BlobClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint); URL url; try { url = new URL(endpoint); BlobURLParts parts = URLParser.parse(url); this.endpoint = parts.scheme() + "://" + parts.host(); if (parts.containerName() != null) { this.containerName = parts.containerName(); } if (parts.blobName() != null) { this.blobName = parts.blobName(); } if (parts.snapshot() != null) { this.snapshot = parts.snapshot(); } } catch (MalformedURLException | UnknownHostException ex) { throw new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed."); } SASTokenCredential credential = SASTokenCredential.fromQuery(url.getQuery()); if (credential != null) { this.credential(credential); } return this; }
Source:
<code>public void setDateCreated(Date dateCreated) { if(dateCreated == null) { this.dateCreated = null; return; } <START> this.dateCreated = (Date) dateCreated.clone(); <END> }</code><technical_language>Hii @PermissionError, a [this](<LINK_0> article, clone() method in setters possess some security risks :)</technical_language>

Target:
public void setDateCreated(Date dateCreated) { if(dateCreated == null) { this.dateCreated = null; return; } this.dateCreated = new Date(dateCreated.getTime()); }
Source:
<code>public void testOptionWithinObjectIfMissing_shouldBeNone() throws SQLException { final SomethingWithOption result = dbRule.getSharedHandle() .registerRowMapper(ConstructorMapper.factory(SomethingWithOption.class)) .createQuery("select id, name from something where id = 2") .mapTo(SomethingWithOption.class) .findOnly(); assertThat(result.getName()).isInstanceOf(Option.class); <START> assertThat(result.getName().getOrNull()).isNull(); <END> }</code><technical_language>disappointed:</technical_language>

Target:
public void testOptionWithinObjectIfMissing_shouldBeNone() throws SQLException { final SomethingWithOption result = dbRule.getSharedHandle() .registerRowMapper(ConstructorMapper.factory(SomethingWithOption.class)) .createQuery("select id, name from something where id = 2") .mapTo(SomethingWithOption.class) .findOnly(); assertThat(result.getName()).isInstanceOf(Option.class); assertThat(result).isEqualTo(new SomethingWithOption(2, Option.none())); }
Source:
<code>protected void setResult(T... newUserSelection) { if (newUserSelection == null) { <START> result = Collections.emptyList(); <END> } else { result = Arrays.asList(newUserSelection); } }</code><technical_language>Simply set result null</technical_language>

Target:
protected void setResult(T... newUserSelection) { if (newUserSelection == null) { result = null; } else { result = Arrays.asList(newUserSelection); } }
Source:
<code>public static Optional<RuntimeException> fromMultipleRuntimeExceptions(List<RuntimeException> exceptions) { switch (exceptions.size()) { case 0: return Optional.empty(); case 1: <START> return Optional.of(exceptions.get(0)); <END> default: CacheConfigurationException exception = log.multipleConfigurationValidationErrors(); exceptions.forEach(e -> exception.addSuppressed(e)); return Optional.of(exception); } }</code><technical_language>wrap this single exception in CacheConfigurationException</technical_language>

Target:
public static Optional<RuntimeException> fromMultipleRuntimeExceptions(List<RuntimeException> exceptions) { switch (exceptions.size()) { case 0: return Optional.empty(); case 1: { RuntimeException e = exceptions.get(0); return e instanceof CacheConfigurationException ? Optional.of(e) : Optional.of(new CacheConfigurationException(e)); } default: { CacheConfigurationException exception = log.multipleConfigurationValidationErrors(); exceptions.forEach(e -> exception.addSuppressed(e)); return Optional.of(exception); } } }
Source:
<code>public void sendMessagePipelining_withNegativeReply() throws Exception { Message message = getDefaultMessage(); MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING"); server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); server.expect("DATA"); server.output("250 OK"); server.output("421 4.7.0 Temporary system problem"); <START> server.output("354 End data with <CR><LF>.<CR><LF>"); <END> server.expect("[message data]"); server.expect("."); server.output("250 OK: queued as 12345"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); transport.sendMessage(message); server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }</code><technical_language>more test case for a reply != 354 nice</technical_language>

Target:
public void sendMessagePipelining_withNegativeReply() throws Exception { Message message = getDefaultMessage(); MockSmtpServer server = createServerAndSetupForPlainAuthentication("PIPELINING"); server.expect("MAIL FROM:<user@localhost>"); server.expect("RCPT TO:<user2@localhost>"); server.expect("DATA"); server.output("250 OK"); server.output("550 remote mail to <user2@localhost> not allowed"); server.output("354 End data with <CR><LF>.<CR><LF>"); server.expect("."); server.output("554 no valid recipients"); server.expect("QUIT"); server.output("221 BYE"); server.closeConnection(); SmtpTransport transport = startServerAndCreateSmtpTransport(server); try { transport.sendMessage(message); fail("Expected exception"); } catch (NegativeSmtpReplyException e) { assertEquals(550, e.getReplyCode()); assertEquals("remote mail to <user2@localhost> not allowed", e.getReplyText()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); }
Source:
<code>public void refresh() throws IOException { <START> if (!featureToggleService.isFeatureEnabled(FEATURE_NAME)) { <END> return; } final long selector = System.currentTimeMillis() - DELAY_MILLIS; synchronized (this) { final Iterator<ListenerInfo> it = toAdd.iterator(); while (it.hasNext()) { final ListenerInfo first = it.next(); if (first.addedAt.getTime() >= selector) { break; } listeners.computeIfAbsent(first.connectionInfo, info -> new ArrayList<>()).add(first.callback); it.remove(); } } final Map<ConnectionInfo, ConnectionState> currentConnections = readAllConnectionStates(); final Set<ConnectionInfo> keys = new HashSet<>(listeners.keySet()); final AtomicInteger closedCount = new AtomicInteger(); for (final ConnectionInfo key : keys) { if (CLOSED_STATES.contains(currentConnections.getOrDefault(key, ConnectionState.TCP_CLOSE))) { LOG.info("Notifying about connection close via crutch: " + key); listeners.remove(key).forEach(callable -> { if (callable.getAsBoolean()) { closedCount.incrementAndGet(); } }); } } if (closedCount.get() > 0) { meterClosed.mark(closedCount.get()); } }</code><technical_language>I decided constants in FeatureToggleService class</technical_language>

Target:
public void refresh() throws IOException { if (!featureToggleService.isFeatureEnabled(FeatureToggleService.Feature.CONNECTION_CLOSE_CRUTCH)) { return; } synchronized (toAdd) { toAdd.forEach((conn, toAddListeners) -> { listeners.computeIfAbsent(conn, c -> new ArrayList<>()).addAll(toAddListeners); }); toAdd.clear(); } final Map<ConnectionInfo, ConnectionState> currentConnections = readAllConnectionStates(); final long closedCount = new HashSet<>(listeners.keySet()).stream() .filter(key -> CLOSED_STATES.contains(currentConnections.getOrDefault(key, ConnectionState.TCP_CLOSE))) .mapToLong(key -> { LOG.info("Notifying about connection close via crutch: " + key); return listeners.remove(key).stream().filter(BooleanSupplier::getAsBoolean).count(); }).sum(); if (closedCount > 0) { meterClosed.mark(closedCount); } }
Source:
<code>public Observable<File> save() { return Observable.create(new Observable.OnSubscribe<File>() { @Override public void call(Subscriber<? super File> subscriber) { File folder = app.getExternalFilesDir(null); if (folder == null) { subscriber.onError(new IOException("External storage is not mounted.")); return; } String fileName = LOG_FILE_FORMAT.format(new Date()); File output = new File(folder, fileName); BufferedSink sink = null; try { sink = Okio.buffer(Okio.sink(output)); List<Entry> entries = bufferedLogs(); for (Entry entry : entries) { sink.writeUtf8(entry.prettyPrint()).writeByte('\n'); } } catch (IOException e) { subscriber.onError(e); } finally { if (sink != null) { try { sink.close(); } catch (IOException e) { subscriber.onError(e); } } } subscriber.onNext(output); <START> subscriber.onCompleted(); <END> } }); }</code><technical_language>This needs in try, violating contract</technical_language>

Target:
public Observable<File> save() { return Observable.create(new Observable.OnSubscribe<File>() { @Override public void call(Subscriber<? super File> subscriber) { File folder = app.getExternalFilesDir(null); if (folder == null) { subscriber.onError(new IOException("External storage is not mounted.")); return; } String fileName = LOG_FILE_FORMAT.get().format(new Date()); File output = new File(folder, fileName); BufferedSink sink = null; try { sink = Okio.buffer(Okio.sink(output)); List<Entry> entries = bufferedLogs(); for (Entry entry : entries) { sink.writeUtf8(entry.prettyPrint()).writeByte('\n'); } subscriber.onNext(output); subscriber.onCompleted(); } catch (IOException e) { subscriber.onError(e); } finally { if (sink != null) { try { sink.close(); } catch (IOException e) { subscriber.onError(e); } } } } }); }
Source:
<code>public void loginHintWithExistingUser() { <START> getCleanup(bc.consumerRealmName()).addCleanup( <END> new UserCreator( adminClient.realm(bc.consumerRealmName()), UserBuilder.create() .username(bc.getUserLogin()) .password(bc.getUserPassword()) .email(bc.getUserEmail()) .enabled(true) .build() ) ); driver.navigate().to(getAccountUrl(bc.consumerRealmName())); waitForPageToLoad(); driver.navigate().to(driver.getCurrentUrl() + "&login_hint=" + USER_EMAIL + "&kc_idp_hint=" + IDP_OIDC_ALIAS); waitForPageToLoad(); loginPage.login(bc.getUserPassword()); updateAccountInformationPage.assertCurrent(); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); idpConfirmLinkPage.assertCurrent(); idpConfirmLinkPage.clickLinkAccount(); loginPage.login(bc.getUserPassword()); accountPage.isCurrent(); }</code><technical_language>feel free try-with-resources form instead of adding cleanup</technical_language>

Target:
public void loginHintWithExistingUser() { try (Creator<UserResource> c = Creator.create(adminClient.realm(bc.consumerRealmName()), UserBuilder.create() .username(bc.getUserLogin()) .password(bc.getUserPassword()) .email(bc.getUserEmail()) .enabled(true) .build() )) { driver.navigate().to(getAccountUrl(bc.consumerRealmName())); waitForPageToLoad(); driver.navigate().to(driver.getCurrentUrl() + "&login_hint=" + USER_EMAIL + "&kc_idp_hint=" + IDP_OIDC_ALIAS); waitForPageToLoad(); loginPage.login(bc.getUserPassword()); updateAccountInformationPage.assertCurrent(); updateAccountInformationPage.updateAccountInformation(bc.getUserLogin(), bc.getUserEmail(), "Firstname", "Lastname"); idpConfirmLinkPage.assertCurrent(); idpConfirmLinkPage.clickLinkAccount(); loginPage.login(bc.getUserPassword()); accountPage.isCurrent(); } }
Source:
<code><START> public byte[] decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { <END> return withContext(context -> client.decrypt(algorithm, cipherText, null, null, null, context)).block(); }</code><technical_language>byte[] [](start = 11, length = 6) DecryptResult</technical_language>

Target:
public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return decrypt(algorithm, cipherText, null, null, null, Context.NONE); }
Source:
<code>private static NetworkFilter fetchVnicProfileNetworkFilter(VmNic vmNic) { <START> VnicProfile vnicProfile = DbFacade.getInstance().getVnicProfileDao().get(vmNic.getVnicProfileId()); <END> final Guid networkFilterId = vnicProfile.getNetworkFilterId(); return DbFacade.getInstance().getNetworkFilterDao().getNetworkFilterById(networkFilterId); }</code><technical_language>if 'vnicProfileId' is null? Done</technical_language>

Target:
private static NetworkFilter fetchVnicProfileNetworkFilter(VmNic vmNic) { if (vmNic.getVnicProfileId() != null) { VnicProfile vnicProfile = DbFacade.getInstance().getVnicProfileDao().get(vmNic.getVnicProfileId()); if (vnicProfile != null) { final Guid networkFilterId = vnicProfile.getNetworkFilterId(); return networkFilterId == null ? null : DbFacade.getInstance().getNetworkFilterDao().getNetworkFilterById(networkFilterId); } } return null; }
Source:
<code>public Map<String, GuestId> getGuestIdMap(Iterable<String> guestIds, Owner owner) { if (guestIds == null || owner == null) { return Collections.<String, GuestId>emptyMap(); } String hql = "SELECT gid FROM GuestId gid " + "WHERE gid.consumer.owner = :owner AND gid.guestIdLower IN (:guest_ids)" + "ORDER BY gid.updated DESC"; TypedQuery<GuestId> query = this.getEntityManager().createQuery(hql, GuestId.class); Map<String, GuestId> output = new HashMap<String, GuestId>(); for (List<String> block : this.partition(guestIds)) { <START> List<String> sanitized = new ArrayList<String>(block); <END> for (String guestId : block) { if (guestId != null && !guestId.isEmpty() && !output.containsKey(guestId)) { sanitized.add(guestId.toLowerCase()); output.put(guestId, null); } } List<GuestId> guests = query .setParameter("owner", owner) .setParameter("guest_ids", sanitized) .getResultList(); if (guests != null) { for (GuestId fetched : guests) { GuestId existing = output.get(fetched.getGuestId()); if (existing == null || this.safeDateAfter(fetched.getUpdated(), existing.getUpdated())) { output.put(fetched.getGuestId(), fetched); } } } } return output; }</code><technical_language>Whoops... a mistake here. needs block.size(), block. As-is, double block size potentially exceed param limit here</technical_language>

Target:
public Map<String, GuestId> getGuestIdMap(Iterable<String> guestIds, Owner owner) { if (guestIds == null || owner == null) { return Collections.<String, GuestId>emptyMap(); } String hql = "SELECT gid FROM GuestId gid " + "WHERE gid.consumer.owner = :owner AND gid.guestIdLower IN (:guest_ids)" + "ORDER BY gid.updated DESC"; TypedQuery<GuestId> query = this.getEntityManager().createQuery(hql, GuestId.class); Map<String, GuestId> output = new HashMap<String, GuestId>(); for (List<String> block : this.partition(guestIds)) { List<String> sanitized = new ArrayList<String>(block.size()); for (String guestId : block) { if (guestId != null && !guestId.isEmpty() && !output.containsKey(guestId)) { sanitized.add(guestId.toLowerCase()); output.put(guestId, null); } } List<GuestId> guests = query .setParameter("owner", owner) .setParameter("guest_ids", sanitized) .getResultList(); if (guests != null) { for (GuestId fetched : guests) { GuestId existing = output.get(fetched.getGuestId()); if (existing == null || this.safeDateAfter(fetched.getUpdated(), existing.getUpdated())) { output.put(fetched.getGuestId(), fetched); } } } } return output; }
Source:
<code>public void accept(final Socket socket) throws IOException { socket.setSoTimeout(BkBasic.TIMEOUT); final InputStream input = socket.getInputStream(); try { while (true) { final Request request = new RqLive(input); this.print( BkBasic.addSocketHeaders( request, socket ), new BufferedOutputStream(socket.getOutputStream()) ); if (input.available() <= 0) { break; } } <START> } catch (final SocketTimeoutException exc) { <END> } finally { input.close(); } }</code><technical_language>@exper0 empty</technical_language>

Target:
public void accept(final Socket socket) throws IOException { socket.setSoTimeout(Tv.THOUSAND); final InputStream input = socket.getInputStream(); final OutputStream output = socket.getOutputStream(); final BufferedOutputStream buffered = new BufferedOutputStream(output); try { while (true) { final Request request = new RqLive(input); this.print( BkBasic.addSocketHeaders( request, socket ), buffered ); if (input.available() <= 0) { break; } } } catch (final SocketTimeoutException exc) { } finally { input.close(); output.close(); } }
Source:
<code>public void adsAdTypeAsyncSuccessWithAd() { <START> Page page = new Page("project43", "SyntheticTests/AdType/Async/Success"); <END> MobileAdsBaseObject ads = new MobileAdsBaseObject(driver, page.getUrl()); ads.scrollToFooter(); ads.waitForSlot(AdsContent.MOBILE_BOTTOM_LB); ads.verifyImgAdLoadedInSlot(AdsContent.MOBILE_BOTTOM_LB, DFP_IMAGE_URL); }</code><technical_language>![MINOR](<LINK_1> 'Severity: MINOR') Define a constant instead of duplicating this literal "project43" 6 times. [![rule](<LINK_0>](http://sonar-s4/coding_rules#rule_key=squid%3AS1192)</technical_language>

Target:
public void adsAdTypeAsyncSuccessWithAd() { Page page = new Page("project43", "SyntheticTests/AdType/Async/Success"); MobileAdsBaseObject ads = new MobileAdsBaseObject(driver, page.getUrl()); ads.scrollToRecirculationPrefooter(); ads.waitForSlot(AdsContent.MOBILE_BOTTOM_LB); ads.verifyImgAdLoadedInSlot(AdsContent.MOBILE_BOTTOM_LB, DFP_IMAGE_URL); }
Source:
<code>public final ChannelPipeline addAfter(String baseName, String name, ChannelHandler handler) { final AbstractChannelHandlerContext ctx; checkMultiplicity(handler); if (name == null) { name = generateName(handler); } AbstractChannelHandlerContext newCtx = newContext(name, handler); EventExecutor executor = executor(); <START> boolean inEventLoop = executor().inEventLoop(); <END> synchronized (handlers) { int i = findCtxIdx(context -> context.name().equals(baseName)); if (i == -1) { throw new NoSuchElementException(baseName); } if (context(name) != null) { throw new IllegalArgumentException("Duplicate handler name: " + name); } ctx = handlers.get(i); handlers.add(i + 1, newCtx); if (!inEventLoop) { try { executor.execute(() -> addAfter0(ctx, newCtx)); return this; } catch (Throwable cause) { handlers.remove(newCtx); throw cause; } } } addAfter0(ctx, newCtx); return this; }</code><technical_language>executor() -> executor</technical_language>

Target:
public final ChannelPipeline addAfter(String baseName, String name, ChannelHandler handler) { final AbstractChannelHandlerContext ctx; checkMultiplicity(handler); if (name == null) { name = generateName(handler); } AbstractChannelHandlerContext newCtx = newContext(name, handler); EventExecutor executor = executor(); boolean inEventLoop = executor.inEventLoop(); synchronized (handlers) { int i = findCtxIdx(context -> context.name().equals(baseName)); if (i == -1) { throw new NoSuchElementException(baseName); } if (context(name) != null) { throw new IllegalArgumentException("Duplicate handler name: " + name); } ctx = handlers.get(i); handlers.add(i + 1, newCtx); if (!inEventLoop) { try { executor.execute(() -> addAfter0(ctx, newCtx)); return this; } catch (Throwable cause) { handlers.remove(i + 1); throw cause; } } } addAfter0(ctx, newCtx); return this; }
Source:
<code><START> public void analyze_appActivitySameAppWithinConflictIntervalButNotContinuous_activityRecordNotMergedButNoNewGoalConflictMessageCreated() <END> { ZonedDateTime now = now(); DayActivity existingDayActivity = mockExistingActivity(gamblingGoal, now.minusMinutes(10), now.minusMinutes(5), "Lotto App"); service.analyze(userAnonId, createSingleAppActivity("Lotto App", now.minusMinutes(4), now.minusMinutes(2))); verifyNoGoalConflictMessagesCreated(); List<Activity> activities = existingDayActivity.getActivities(); assertThat(activities.size(), equalTo(2)); assertThat(activities.get(1).getApp(), equalTo(Optional.of("Lotto App"))); assertThat(activities.get(1).getDurationMinutes(), equalTo(2)); }</code><technical_language>Please change Continuous Contiguous</technical_language>

Target:
public void analyze_appActivitySameAppWithinConflictIntervalButNotContinuous_activityRecordNotMergedButNoNewGoalConflictMessageCreated() { ZonedDateTime now = now(); ZonedDateTime existingActivityEndTime = now.minusMinutes(5); DayActivity existingDayActivity = mockExistingActivity(gamblingGoal, now.minusMinutes(10), now.minusMinutes(5), "Lotto App"); service.analyze(userAnonId, createSingleAppActivity("Lotto App", existingActivityEndTime.plusSeconds(1), now.minusMinutes(2))); verifyNoGoalConflictMessagesCreated(); List<Activity> activities = existingDayActivity.getActivities(); assertThat(activities.size(), equalTo(2)); assertThat(activities.get(1).getApp(), equalTo(Optional.of("Lotto App"))); assertThat(activities.get(1).getDurationMinutes(), equalTo(2)); }
Source:
<code>public boolean tryLock(int timeoutMs) { if (!isInUse.compareAndSet(false, true)) { return false; } final String path; try { path = createAndGetLockPath(); } catch (InterruptedException e) { log.log( java.util.logging.Level.WARNING, "InterruptedException while trying to get lock path " + absoluteLockPath, e); return false; } catch (KeeperException e) { log.log( java.util.logging.Level.WARNING, "KeeperException while trying to get lock path " + absoluteLockPath, e); return false; } try { absoluteLockPath = zk.create( <START> path.toString(), <END> null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); log.log( java.util.logging.Level.INFO, "Created lock node with path: " + absoluteLockPath); final boolean wait = true; return attemptToLock(timeoutMs, wait); } catch (InterruptedException e) { log.log( java.util.logging.Level.INFO, "InterruptedException while trying to create lock " + absoluteLockPath, e); return false; } catch (KeeperException e) { log.log( java.util.logging.Level.INFO, "KeeperException while trying to create lock " + absoluteLockPath, e); return false; } }</code><technical_language>path a String</technical_language>

Target:
public boolean tryLock(int timeoutMs) { if (!isInUse.compareAndSet(false, true)) { return false; } final String path; try { path = createAndGetLockPath(); } catch (InterruptedException e) { log.log( java.util.logging.Level.WARNING, "InterruptedException while trying to get lock path " + absoluteLockPath, e); return false; } catch (KeeperException e) { log.log( java.util.logging.Level.WARNING, "KeeperException while trying to get lock path " + absoluteLockPath, e); return false; } try { absoluteLockPath = zk.create( path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); log.log( java.util.logging.Level.INFO, "Created lock node with path: " + absoluteLockPath); final boolean wait = true; return attemptToLock(timeoutMs, wait); } catch (InterruptedException e) { log.log( java.util.logging.Level.INFO, "InterruptedException while trying to create lock " + absoluteLockPath, e); return false; } catch (KeeperException e) { log.log( java.util.logging.Level.INFO, "KeeperException while trying to create lock " + absoluteLockPath, e); return false; } }
Source:
<code>public static String getActionStatus(OozieClient oozieClient, String workflowId, String actionName) throws OozieClientException { List<WorkflowAction> wfAction = oozieClient.getJobInfo(workflowId).getActions(); for (WorkflowAction wf : wfAction) { if (wf.getName().contains(actionName)) { <START> if (wf.getExternalStatus() != null) { <END> return wf.getExternalStatus(); } } } return ""; }</code><technical_language>please 'and' operator in if condition combine if statements for readability</technical_language>

Target:
public static String getActionStatus(OozieClient oozieClient, String workflowId, String actionName) throws OozieClientException { List<WorkflowAction> wfAction = oozieClient.getJobInfo(workflowId).getActions(); for (WorkflowAction wf : wfAction) { if ((wf.getName().contains(actionName)) && (wf.getExternalStatus() != null)) { return wf.getExternalStatus(); } } return ""; }
Source:
<code>private void addAdaptiveExercisesFromStub(Course returnedFromServer, Course courseStub) { <START> Set<Exercise> set = new HashSet<>(returnedFromServer.getExercises()); <END> set.addAll(courseStub.getExercises()); returnedFromServer.setExercises(new ArrayList<>(set)); }</code><technical_language>set is a unhelpful name</technical_language>

Target:
private void addAdaptiveExercisesFromStub(Course returnedFromServer, Course courseStub) { Set<Exercise> exercises = new HashSet<>(returnedFromServer.getExercises()); exercises.addAll(courseStub.getExercises()); returnedFromServer.setExercises(new ArrayList<>(exercises)); }
Source:
<code>public Control onMessage(byte[] data, WebSocketSession session) { try { BinaryDecoder decoder = decoders.get(session.getConnection()); if (decoder == null) { decoder = new BinaryDecoder(); decoders.put(session.getConnection(), decoder); } try { return onMessage(decoder.decode(data), session); } catch (IOException e) { log.error("Invalid message"); return Control.malformedRequest("Invalid message"); } <START> } catch (Exception e) { <END> log.info("onMessage(data={}, session={}", data, session); log.error("Unexpected exception: " + e.getMessage(), e); return Control.error(e.getMessage()); } }</code><technical_language>re-throw in this case? is, catching RuntimeException is right, this method throws Exception swallowing a lot more</technical_language>

Target:
public Control onMessage(byte[] data, WebSocketSession session) throws Exception { try { BinaryDecoder decoder = decoders.get(session.getConnection()); if (decoder == null) { decoder = new BinaryDecoder(); decoders.put(session.getConnection(), decoder); } try { return onMessage(decoder.decode(data), session); } catch (IOException e) { log.error("Invalid message"); return Control.malformedRequest("Invalid message"); } } catch (RuntimeException e) { log.info("onMessage(data={}, session={}", data, session); log.error("Unexpected exception: " + e.getMessage(), e); return Control.error(e.getMessage()); } catch (Exception e) { log.info("onMessage(data={}, session={}", data, session); log.error("Unexpected exception: " + e.getMessage(), e); throw(e); } }
Source:
<code>public void testUpdateUserMetadataWithoutTokens() { io.dockstore.openapi.client.ApiClient adminWebClient = getOpenAPIWebClient(ADMIN_USERNAME, testingPostgres); io.dockstore.openapi.client.ApiClient userWebClient = getOpenAPIWebClient(USER_2_USERNAME, testingPostgres); io.dockstore.openapi.client.api.UsersApi adminApi = new io.dockstore.openapi.client.api.UsersApi(adminWebClient); io.dockstore.openapi.client.api.UsersApi userApi = new io.dockstore.openapi.client.api.UsersApi(userWebClient); io.dockstore.openapi.client.model.User admin = adminApi.getUser(); io.dockstore.openapi.client.model.Profile userProfile = userApi.getUser().getUserProfiles().get("github.com"); <START> testingPostgres.runUpdateStatement("DELETE FROM token"); <END> assertNull(userProfile.getEmail()); assertNull(userProfile.getAvatarURL()); assertNull(userProfile.getLocation()); userApi.updateUserMetadata(); userProfile = userApi.getUser().getUserProfiles().get("github.com"); assertNull(userProfile.getEmail()); assertNull(userProfile.getAvatarURL()); assertNull(userProfile.getLocation()); }</code><technical_language>If delete Dockstore token, authenticated endpoints fail; get UserResource.updateUserMetadata. testing method is called all, useful in this scenario. Note: if debugging this method get invoked contradict previous statement, token is cached, delete token, calls work for a bit. deterministic rely it. This is a long-winded of delete GitHub and/or Google tokens, Dockstore tokens</technical_language>

Target:
public void testUpdateUserMetadataWithoutTokens() { io.dockstore.openapi.client.ApiClient adminWebClient = getOpenAPIWebClient(ADMIN_USERNAME, testingPostgres); io.dockstore.openapi.client.ApiClient userWebClient = getOpenAPIWebClient(USER_2_USERNAME, testingPostgres); io.dockstore.openapi.client.api.UsersApi adminApi = new io.dockstore.openapi.client.api.UsersApi(adminWebClient); io.dockstore.openapi.client.api.UsersApi userApi = new io.dockstore.openapi.client.api.UsersApi(userWebClient); io.dockstore.openapi.client.model.User admin = adminApi.getUser(); io.dockstore.openapi.client.model.Profile userProfile = userApi.getUser().getUserProfiles().get("github.com"); testingPostgres.runUpdateStatement("DELETE FROM token WHERE tokensource <> 'dockstore'"); assertNull(userProfile.getEmail()); assertNull(userProfile.getAvatarURL()); assertNull(userProfile.getLocation()); userApi.updateUserMetadata(); userProfile = userApi.getUser().getUserProfiles().get("github.com"); assertNull(userProfile.getEmail()); assertNull(userProfile.getAvatarURL()); assertNull(userProfile.getLocation()); }
Source:
<code>public void deleteLocalDocument(final String docId) throws DocumentNotFoundException { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkArgument(!Strings.isNullOrEmpty(docId), "Input document id can not be empty"); try { queue.submit(new SQLQueueCallable<Object>() { @Override public Object call(SQLDatabase db) throws Exception { String[] whereArgs = {docId}; int rowsDeleted = db.delete("localdocs", "docid=? ", whereArgs); if (rowsDeleted == 0) { throw new DocumentNotFoundException("No local document with doc id: " + docId); } return null; } }).get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { <START> throw new DocumentNotFoundException(String.format("Did not find document with id: %s",docId),e); <END> } }</code><technical_language>s/Did not/Could not/</technical_language>

Target:
public void deleteLocalDocument(final String docId) throws DocumentNotFoundException { Preconditions.checkState(this.isOpen(), "Database is closed"); Preconditions.checkArgument(!Strings.isNullOrEmpty(docId), "Input document id can not be empty"); try { queue.submit(new SQLQueueCallable<Object>() { @Override public Object call(SQLDatabase db) throws Exception { String[] whereArgs = {docId}; int rowsDeleted = db.delete("localdocs", "docid=? ", whereArgs); if (rowsDeleted == 0) { throw new DocumentNotFoundException(docId, (String) null); } return null; } }).get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new DocumentNotFoundException(docId,null,e); } }
Source:
<code>private static void invokeWithTimeoutWithNewExecutor(ITestNGMethod tm, Object instance, Object[] parameterValues, ITestResult testResult, IHookable hookable) throws InterruptedException, ThreadExecutionException { IExecutor exec = ThreadUtil.createExecutor(1, tm.getMethodName()); InvokeMethodRunnable imr = new InvokeMethodRunnable(tm, instance, parameterValues, hookable, testResult); IFutureResult future = exec.submitRunnable(imr); exec.shutdown(); long realTimeOut = MethodHelper.calculateTimeOut(tm); boolean finished = exec.awaitTermination(realTimeOut); if (!finished) { exec.stopNow(); ThreadTimeoutException exception = new ThreadTimeoutException("Method " + tm.getQualifiedName() + "()" + " didn't finish within the time-out " + realTimeOut); <START> testResult.setThrowable(exception); <END> testResult.setStatus(ITestResult.FAILURE); } else { Utils.log("Invoker " + Thread.currentThread().hashCode(), 3, "Method " + tm.getMethodName() + " completed within the time-out " + tm.getTimeOut()); future.get(); testResult.setStatus(ITestResult.SUCCESS); } }</code><technical_language>Ok, thanks for explanations. I understand getStackTraces returns empty array. I is broken in ThreadFactoryImpl add new threads in list. check</technical_language>

Target:
private static void invokeWithTimeoutWithNewExecutor(ITestNGMethod tm, Object instance, Object[] parameterValues, ITestResult testResult, IHookable hookable) throws InterruptedException, ThreadExecutionException { IExecutor exec = ThreadUtil.createExecutor(1, tm.getMethodName()); InvokeMethodRunnable imr = new InvokeMethodRunnable(tm, instance, parameterValues, hookable, testResult); IFutureResult future = exec.submitRunnable(imr); exec.shutdown(); long realTimeOut = MethodHelper.calculateTimeOut(tm); boolean finished = exec.awaitTermination(realTimeOut); if (!finished) { exec.stopNow(); ThreadTimeoutException exception = new ThreadTimeoutException("Method " + tm.getQualifiedName() + "()" + " didn't finish within the time-out " + realTimeOut); StackTraceElement[][] stacktraces = exec.getStackTraces(); if (stacktraces.length > 0) { exception.setStackTrace(stacktraces[0]); } testResult.setThrowable(exception); testResult.setStatus(ITestResult.FAILURE); } else { Utils.log("Invoker " + Thread.currentThread().hashCode(), 3, "Method " + tm.getMethodName() + " completed within the time-out " + tm.getTimeOut()); future.get(); testResult.setStatus(ITestResult.SUCCESS); } }
Source:
<code>private Position attemptMasterRecovery() throws Exception { HeartbeatRowMap recoveredHeartbeat = null; MysqlPositionStore positionStore = this.context.getPositionStore(); RecoveryInfo recoveryInfo = positionStore.getRecoveryInfo(config); if ( recoveryInfo != null ) { Recovery masterRecovery = new Recovery( config.replicationMysql, config.databaseName, this.context.getReplicationConnectionPool(), this.context.getCaseSensitivity(), recoveryInfo ); recoveredHeartbeat = masterRecovery.recover(); if (recoveredHeartbeat != null) { MysqlSchemaStore oldServerSchemaStore = new MysqlSchemaStore( <START> context, <END> recoveryInfo.serverID, recoveryInfo.position, config.filter, false ); oldServerSchemaStore.clone(context.getServerID(), recoveredHeartbeat.getPosition()); return recoveredHeartbeat.getNextPosition(); } } return null; }</code><technical_language>Please long argument lists passing context -- components more reusable maxwell a library. I a pain, reasoning</technical_language>

Target:
private Position attemptMasterRecovery() throws Exception { HeartbeatRowMap recoveredHeartbeat = null; MysqlPositionStore positionStore = this.context.getPositionStore(); RecoveryInfo recoveryInfo = positionStore.getRecoveryInfo(config); if ( recoveryInfo != null ) { Recovery masterRecovery = new Recovery( config.replicationMysql, config.databaseName, this.context.getReplicationConnectionPool(), this.context.getCaseSensitivity(), recoveryInfo ); recoveredHeartbeat = masterRecovery.recover(); if (recoveredHeartbeat != null) { MysqlSchemaStore oldServerSchemaStore = new MysqlSchemaStore( context.getMaxwellConnectionPool(), context.getReplicationConnectionPool(), context.getSchemaConnectionPool(), recoveryInfo.serverID, recoveryInfo.position, context.getCaseSensitivity(), config.filter, config.schemaChainMaxLength, false ); oldServerSchemaStore.clone(context.getServerID(), recoveredHeartbeat.getPosition()); return recoveredHeartbeat.getNextPosition(); } } return null; }
Source:
<code>public void close() <START> throws Exception { <END> consumer.close(); }</code><technical_language>Exception thrown consumer.close(), removed</technical_language>

Target:
public void close() { consumer.close(); }
Source:
<code>Server pick() { ImmutableList<Server> currNodes = nodes; <START> int index = roundRobinIndex.getAndIncrement(); <END> if (currNodes.size() == 0) { return null; } index %= currNodes.size(); return currNodes.get(index); }</code><technical_language>produce negative results index overflows, suggested replace a method wraps currNodes.size() explicitly, of compareAndSet(), for sanity</technical_language>

Target:
Server pick() { ImmutableList<Server> currNodes = nodes; if (currNodes.size() == 0) { return null; } return currNodes.get(getIndex(currNodes)); }
Source:
<code>private String sign(final Long timestamp) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException { String stringToSign = timestamp + "\n" + dingtalkConfiguration.getSecret(); Mac mac = Mac.getInstance("HmacSHA256"); <START> mac.init(new SecretKeySpec(dingtalkConfiguration.getSecret().getBytes(StandardCharsets.UTF_8.name()), "HmacSHA256")); byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8.name())); <END> return URLEncoder.encode(new String(Base64.getEncoder().encode(signData)), StandardCharsets.UTF_8.name()); }</code><technical_language>"StandardCharsets.UTF_8". "name()" is unnecessary for "getBytes"</technical_language>

Target:
private String sign(final Long timestamp) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException { String stringToSign = timestamp + "\n" + dingtalkConfiguration.getSecret(); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(dingtalkConfiguration.getSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256")); byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8)); return URLEncoder.encode(new String(Base64.getEncoder().encode(signData)), StandardCharsets.UTF_8.name()); }
Source:
<code>public CommandResponse run(ZooKeeperServer zkServer, Map<String, String> kwargs) { CommandResponse response = initializeResponse(); <START> if (zkServer instanceof LeaderZooKeeperServer) { <END> Leader leader = ((LeaderZooKeeperServer) zkServer).getLeader(); response.put("synced_observers", leader.getObservingLearners().size()); response.put("observers", leader.getObservingLearnersInfo()); } else if (zkServer instanceof FollowerZooKeeperServer) { Follower follower = ((FollowerZooKeeperServer) zkServer).getFollower(); Integer syncedObservers = follower.getSyncedObserverSize(); if (syncedObservers != null) { response.put("synced_observers", syncedObservers); response.put("observers", follower.getSyncedObserversInfo()); } } else { response.put("synced_observers", 0); response.put("observers", null); } return response; }</code><technical_language>here. file is full of instanceof do in a separate change</technical_language>

Target:
public CommandResponse run(ZooKeeperServer zkServer, Map<String, String> kwargs) { CommandResponse response = initializeResponse(); if (zkServer instanceof LeaderZooKeeperServer) { Leader leader = ((LeaderZooKeeperServer) zkServer).getLeader(); response.put("synced_observers", leader.getObservingLearners().size()); response.put("observers", leader.getObservingLearnersInfo()); return response; } else if (zkServer instanceof FollowerZooKeeperServer) { Follower follower = ((FollowerZooKeeperServer) zkServer).getFollower(); Integer syncedObservers = follower.getSyncedObserverSize(); if (syncedObservers != null) { response.put("synced_observers", syncedObservers); response.put("observers", follower.getSyncedObserversInfo()); return response; } } response.put("synced_observers", 0); response.put("observers", Collections.emptySet()); return response; }
Source:
<code>public void executeCommand(UICommand command) { super.executeCommand(command); <START> if (command == getImportImagesCommand()) { <END> importImages(); } else if (command.getName().equals("Cancel")) { cancel(); } }</code><technical_language>== (as opposed equals) is OK here</technical_language>

Target:
public void executeCommand(UICommand command) { super.executeCommand(command); if (getImportImagesCommand().equals(command)) { importImages(); } else if (command.getName().equals("Cancel")) { cancel(); } }
Source:
<code>public static String tissuePiece(long count) { <START> return pluralize(count, "tissue piece", "tissue peices"); <END> }</code><technical_language>peices -> pieces</technical_language>

Target:
public static String tissuePiece(long count) { return pluralize(count, "tissue piece", "tissue pieces"); }
Source:
<code>public Court GetCourtById(Long courtId){ <START> Court court = courtDAO.getByCourtId(courtId); <END> return court; }</code><technical_language>Another redundant variable</technical_language>

Target:
public Court GetCourtById(Long courtId){ return courtDAO.getByCourtId(courtId); }
Source:
<code>private void validate(final String certInput, final String keyInput, final String password, final String chainInput) { Certificate cert; PrivateKey key; List<Certificate> chain = null; try { cert = parseCertificate(certInput); <START> key = parsePrivateKey(keyInput); <END> if (chainInput != null) { chain = CertificateHelper.parseChain(chainInput); } } catch (final IOException | CertificateException e) { throw new IllegalArgumentException("Parsing certificate/key failed: " + e.getMessage(), e); } validateCert(cert, chainInput != null ? true : false); validateKeys(cert.getPublicKey(), key); if (chainInput != null) { validateChain(chain, cert); } }</code><technical_language>Please consider consolidating declaration of cert key variables try block, as, pulling lines 298-303 try block</technical_language>

Target:
private void validate(final String certInput, final String keyInput, final String password, final String chainInput) { try { List<Certificate> chain = null; final Certificate cert = parseCertificate(certInput); final PrivateKey key = parsePrivateKey(keyInput); if (chainInput != null) { chain = CertificateHelper.parseChain(chainInput); } validateCert(cert); validateKeys(cert.getPublicKey(), key); if (chainInput != null) { validateChain(chain, cert); } } catch (final IOException | CertificateException e) { throw new IllegalStateException("Parsing certificate/key failed: " + e.getMessage(), e); } }
Source:
<code>public void processRightData(final MistDataEvent event) { final long timestamp = event.getTimestamp(); if (recentRightTimestamp > timestamp) { throw new RuntimeException("The upstream events should be ordered by timestamp."); } else if (recentRightWatermark.getTimestamp() > timestamp){ throw new RuntimeException("The watermark should guarantee that " + "all events having less timestamp than it are arrived already."); } recentRightTimestamp = timestamp; rightUpstreamQueue.add(event); <START> final long leftWatermarkTimestamp = recentLeftWatermark.getTimestamp(); <END> final long rightWatermarkTimestamp = recentRightWatermark.getTimestamp(); final long minimumWatermark = getMinimumWatermark(leftWatermarkTimestamp, rightWatermarkTimestamp); drainUntilTimestamp(minimumWatermark); emitWatermarkUntilTimestamp(leftWatermarkTimestamp, rightWatermarkTimestamp, minimumWatermark); }</code><technical_language>lines 185-191 167-171</technical_language>

Target:
public void processRightData(final MistDataEvent event) { final long timestamp = event.getTimestamp(); if (recentRightTimestamp > timestamp) { throw new RuntimeException("The upstream events should be ordered by timestamp."); } else if (recentRightWatermark.getTimestamp() > timestamp){ throw new RuntimeException("The watermark should guarantee that " + "all events having less timestamp than it are arrived already."); } recentRightTimestamp = timestamp; rightUpstreamQueue.add(event); drainUntilMinimumWatermark(); }
Source:
<code><START> void verifyGroovyResourceClasspathExecution() { <END> try { val resource = new ClassPathResource("ScriptingUtilsTestGroovyScript.groovy"); val result = ScriptingUtils.executeGroovyScript(resource, "process", String.class, "casuser"); assertEquals("casuser", result); } catch (final Exception e) { throw new AssertionError(e.getMessage(), e); } }</code><technical_language>() throws Exception</technical_language>

Target:
public void verifyGroovyResourceClasspathExecution() { val resource = new ClassPathResource("ScriptingUtilsTestGroovyScript.groovy"); val result = ScriptingUtils.executeGroovyScript(resource, "process", String.class, "casuser"); assertEquals("casuser", result); }
Source:
<code>private void writeMetadata() { csvAppender("# METADATA:"); for (String m : metadata) { csvAppender(m); } for (String a : attributeMetadata) { csvAppender(a); } csvAppender(fNEW_LINE); <START> <END> }</code><technical_language>Empty line</technical_language>

Target:
private void writeMetadata() { csvAppender("# METADATA:"); for (String m : metadata) { csvAppender(m); } for (String a : attributeMetadata) { csvAppender(a); } csvAppender(NEW_LINE); }
Source:
<code>public int getItemCount() { if (isPlaying) { <START> return Math.max(tactCount, MINIMUM_TACT_COUNT) + PLUS_BUTTON_ON_END + 1; <END> } return Math.max(tactCount, MINIMUM_TACT_COUNT) + PLUS_BUTTON_ON_END; }</code><technical_language>.. constant EMPTY_VIEW_COUNT_ON_END instead of PLUS_BUTTON_ON_END + 1</technical_language>

Target:
public int getItemCount() { if (isPlaying) { return Math.max(tactCount, MINIMUM_TACT_COUNT) + EMPTY_VIEW_COUNT_ON_END; } return Math.max(tactCount, MINIMUM_TACT_COUNT) + PLUS_BUTTON_ON_END; }