auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void acceptRecord(final GcBiasCollectorArgs args) { final SAMRecord rec = args.getRec(); if (rec.getReadBases().length == 0) { <START> log.warn("Omitting read " + rec.getReadName() + " with '*' in SEQ field."); <END> return; } if (!rec.getReadUnmappedFlag()) { if (referenceIndex != rec.getReferenceIndex() || gc == null) { final ReferenceSequence ref = args.getRef(); refBases = ref.getBases(); StringUtil.toUpperCase(refBases); final int refLength = refBases.length; final int lastWindowStart = refLength - scanWindowSize; gc = GcBiasUtils.calculateAllGcs(refBases, lastWindowStart, scanWindowSize); referenceIndex = rec.getReferenceIndex(); } addReadToGcData(rec, this.gcData, ""); if (IS_NON_DUPLICATES && !rec.getDuplicateReadFlag()) { addReadToGcData(rec, this.gcDataNonDups, NON_DUPS_PREFIX); } } else { updTotalClusters(rec, this.gcData); if (IS_NON_DUPLICATES && !rec.getDuplicateReadFlag()) { updTotalClusters(rec, this.gcDataNonDups); } } }</code><technical_language>this get quickly if reads SEQ bases...limit 100 warnings please</technical_language>

Target:
public void acceptRecord(final GcBiasCollectorArgs args) { final SAMRecord rec = args.getRec(); if (logCounter < 100 && rec.getReadBases().length == 0) { log.warn("Omitting read " + rec.getReadName() + " with '*' in SEQ field."); if (++logCounter == 100) { log.warn("There are more than 100 reads with '*' in SEQ field in file."); } return; } if (!rec.getReadUnmappedFlag()) { if (referenceIndex != rec.getReferenceIndex() || gc == null) { final ReferenceSequence ref = args.getRef(); refBases = ref.getBases(); StringUtil.toUpperCase(refBases); final int refLength = refBases.length; final int lastWindowStart = refLength - scanWindowSize; gc = GcBiasUtils.calculateAllGcs(refBases, lastWindowStart, scanWindowSize); referenceIndex = rec.getReferenceIndex(); } addReadToGcData(rec, this.gcData); if (ignoreDuplicates && !rec.getDuplicateReadFlag()) { addReadToGcData(rec, this.gcDataNonDups); } } else { updateTotalClusters(rec, this.gcData); if (ignoreDuplicates && !rec.getDuplicateReadFlag()) { updateTotalClusters(rec, this.gcDataNonDups); } } }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_browser_current_category: <START> PageTitle title = Utils.getPageTitle(String.format("Category:%s", categoryName)); <END> Utils.handleWebUrl(this, Uri.parse(title.getCanonicalUri())); return true; default: return super.onOptionsItemSelected(item); } }</code><technical_language>I CATEGORY_PREFIX variable CategoryClient hard coding prefix</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_browser_current_category: PageTitle title = Utils.getPageTitle(CATEGORY_PREFIX + categoryName); Utils.handleWebUrl(this, Uri.parse(title.getCanonicalUri())); return true; default: return super.onOptionsItemSelected(item); } }
Source:
<code>public void testDownloadLog() throws Exception { String testLogName = "strongbox-test.log"; Files.createFile(Paths.get(propertiesBooter.getLogsDirectory(), testLogName)) .toFile() .deleteOnExit(); String url = getContextBaseUrl() + "/log/" + testLogName; mockMvc.header(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN_VALUE) .when() .get(url) .peek() .then() <START> .statusCode(HttpStatus.OK.value()); END> }</code><technical_language>check content size is 0</technical_language>

Target:
public void testDownloadLog() throws Exception { String testLogName = "strongbox-test.log"; Path file = Paths.get(propertiesBooter.getLogsDirectory(), testLogName); Files.createFile(file) .toFile() .deleteOnExit(); List<String> lines = Arrays.asList("Strongbox", "is", "awesome!"); Files.write(file, lines, StandardCharsets.UTF_8); assertThat(file.toFile().length()).isGreaterThan(0); String url = getContextBaseUrl() + "/download/" + testLogName; ResponseBodyExtractionOptions body = mockMvc.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM_VALUE) .when() .get(url) .peek() .then() .statusCode(HttpStatus.OK.value()) .extract() .body(); assertThat(body.asByteArray().length).isEqualTo(file.toFile().length()); }
Source:
<code>public int unsynchronizedGetExclusiveBuffersUsed() { <START> return Math.max(0, initialCredit - bufferManager.getNumberOfAvailableExclusiveBuffers()); <END> }</code><technical_language>I unsynchronized prefix for this method getNumberOfAvailableFloatingBuffers well</technical_language>

Target:
public int unsynchronizedGetExclusiveBuffersUsed() { return Math.max(0, initialCredit - bufferManager.unsynchronizedGetExclusiveBuffersUsed()); }
Source:
<code>private boolean upgradeEightNine(SQLiteDatabase db) { db.beginTransaction(); try { if (multipleInstalledAppRecords()) { <START> throw new MigrationException(true); <END> } SqlStorage<FormRecordV1> oldStorage = new SqlStorage<>( FormRecord.STORAGE_KEY, FormRecordV1.class, new ConcreteAndroidDbHelper(c, db)); String appId = getInstalledAppRecord().getApplicationId(); Vector<FormRecord> upgradedRecords = new Vector<>(); for (FormRecordV1 oldRecord : oldStorage) { FormRecord newRecord = new FormRecord( oldRecord.getInstanceURIString(), oldRecord.getStatus(), oldRecord.getFormNamespace(), oldRecord.getAesKey(), oldRecord.getInstanceID(), oldRecord.lastModified(), appId); newRecord.setID(oldRecord.getID()); upgradedRecords.add(newRecord); } db.execSQL(DatabaseAppOpenHelper.addColumnToTable( FormRecord.STORAGE_KEY, FormRecord.META_APP_ID, "TEXT")); SqlStorage<FormRecord> newStorage = new SqlStorage<>( FormRecord.STORAGE_KEY, FormRecord.class, new ConcreteAndroidDbHelper(c, db)); for (FormRecord r : upgradedRecords) { newStorage.write(r); } db.setTransactionSuccessful(); return true; } finally { db.endTransaction(); } }</code><technical_language>is end result of this exception raised? CC crash is user told uninstall apps try again? I alright failure mode (for power users) fail silently migration warn user login need re-install fix a bug</technical_language>

Target:
private boolean upgradeEightNine(SQLiteDatabase db) { return FixtureSerializationMigration.migrateFixtureDbBytes(db, c); }
Source:
<code>public FileSystem newFileSystem(URI uri, Map<String, ?> config) throws IOException { String accountName = extractAccountName(uri); if (this.openFileSystems.containsKey(accountName)) { <START> throw new FileSystemAlreadyExistsException(); <END> } AzureFileSystem afs = new AzureFileSystem(this, accountName, config); this.openFileSystems.put(accountName, afs); return afs; }</code><technical_language>add existing FileSystem name exception</technical_language>

Target:
public FileSystem newFileSystem(URI uri, Map<String, ?> config) throws IOException { String accountName = extractAccountName(uri); if (this.openFileSystems.containsKey(accountName)) { throw Utility.logError(this.logger, new FileSystemAlreadyExistsException("Name: " + accountName)); } AzureFileSystem afs = new AzureFileSystem(this, accountName, config); this.openFileSystems.put(accountName, afs); return afs; }
Source:
<code>public EtcdNettyClient(final EtcdNettyConfig config, final EtcdSecurityContext securityContext, final URI... uris) { this(config, securityContext, new HashedWheelTimer(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "etcd4j-timer-thread"); <START> t.setDaemon(false); <END> return t; } }), uris); }</code><technical_language>setDaemon(true)</technical_language>

Target:
public EtcdNettyClient(final EtcdNettyConfig config, final EtcdSecurityContext securityContext, final URI... uris) { logger.info("Setting up Etcd4j Netty client"); this.lastWorkingUriIndex = 0; this.config = config.clone(); this.securityContext = securityContext.clone(); this.uris = uris; this.timer = config.getTimer(); this.eventLoopGroup = config.getEventLoopGroup(); this.bootstrap = new Bootstrap() .group(eventLoopGroup) .channel(config.getSocketChannelClass()) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (securityContext.hasNettySsl()) { p.addLast(securityContext.nettySslContext().newHandler(ch.alloc())); } else if (securityContext.hasSsl()) { p.addLast(new SslHandler(securityContext.sslContext().createSSLEngine())); } p.addLast("codec", new HttpClientCodec()); if(securityContext.hasCredentials()) { p.addLast("auth", new HttpBasicAuthHandler()); } p.addLast("chunkedWriter", new ChunkedWriteHandler()); p.addLast("aggregate", new HttpObjectAggregator(config.getMaxFrameSize())); } }); }
Source:
<code>private static void initializePortraits() { if (parseDirectory) { parseDirectory = false; try { portraitDirectory = new DirectoryItems(Configuration.portraitImagesDir(), "", ImageFileFactory.getInstance()); } catch (Exception e) { <START> MegaMek.getLogger().error("Could not parse the portraits directory!"); e.printStackTrace(); <END> } } }</code><technical_language>suggestion MegaMek.getLogger().error("Could parse portraits directory!", e);</technical_language>

Target:
private static void initializePortraits() { if (parseDirectory) { parseDirectory = false; try { portraitDirectory = new DirectoryItems(Configuration.portraitImagesDir(), "", ImageFileFactory.getInstance()); } catch (Exception e) { MegaMek.getLogger().error("Could not parse the portraits directory!", e); } } }
Source:
<code>private String getQualifiedNetworksServiceClassName() { String className = mPhone.getContext().getResources().getString( com.android.internal.R.string.config_qualified_networks_service_class); PersistableBundle b = mCarrierConfigManager.getConfigForSubId(mPhone.getSubId()); if (b != null) { String carrierConfigPackageName = b.getString(CarrierConfigManager .KEY_CARRIER_QUALIFIED_NETWORKS_SERVICE_CLASS_OVERRIDE_STRING); if (!TextUtils.isEmpty(carrierConfigPackageName)) { if (DBG) log("Found carrier config override " + carrierConfigPackageName); className = carrierConfigPackageName; } } <START> List<ResolveInfo> resolveInfo = mPhone.getContext().getPackageManager().queryIntentServices( new Intent(QualifiedNetworksService.QUALIFIED_NETWORKS_SERVICE_INTERFACE), PackageManager.MATCH_SYSTEM_ONLY); if (resolveInfo != null) { for (ResolveInfo info : resolveInfo) { if (info.serviceInfo == null) continue; if ((info.serviceInfo.name).contains(className)) { className = info.serviceInfo.name; break; } } } <END> return className; }</code><technical_language>remove this part? I config resource overlay (for device) carrier config (for specific carrier)</technical_language>

Target:
private String getQualifiedNetworksServiceClassName() { String className = mPhone.getContext().getResources().getString( com.android.internal.R.string.config_qualified_networks_service_class); PersistableBundle b = mCarrierConfigManager.getConfigForSubId(mPhone.getSubId()); if (b != null) { String carrierConfigClassName = b.getString(CarrierConfigManager .KEY_CARRIER_QUALIFIED_NETWORKS_SERVICE_CLASS_OVERRIDE_STRING); if (!TextUtils.isEmpty(carrierConfigClassName)) { if (DBG) log("Found carrier config override " + carrierConfigClassName); className = carrierConfigClassName; } } return className; }
Source:
<code>public BlockPiston(boolean sticky) { this.sticky = sticky; <START> if (!sticky) { <END> setDrops(new ItemStack(Material.PISTON_BASE)); } else { setDrops(new ItemStack(Material.PISTON_STICKY_BASE)); } }</code><technical_language>Flip if statement, please</technical_language>

Target:
public BlockPiston(boolean sticky) { this.sticky = sticky; if (sticky) { setDrops(new ItemStack(Material.PISTON_STICKY_BASE)); } else { setDrops(new ItemStack(Material.PISTON_BASE)); } }
Source:
<code>public void toggleStars(final ToggleStarRequest req, final AsyncCallback<VoidResult> callback) { run(callback, new Action<VoidResult>() { public VoidResult run(final ReviewDb db) throws OrmException { final Account.Id me = getAccountId(); final Set<Change.Id> existing = currentUser.get().getStarredChanges(); List<StarredChange> add = new ArrayList<StarredChange>(); List<StarredChange.Key> remove = new ArrayList<StarredChange.Key>(); if (req.getAddSet() != null) { for (final Change.Id id : req.getAddSet()) { if (!existing.contains(id)) { StarredChange.Key key = new StarredChange.Key(me, id); add.add(new StarredChange(key)); starredChangesCache.evict(key); } } } if (req.getRemoveSet() != null) { for (final Change.Id id : req.getRemoveSet()) { StarredChange.Key key = new StarredChange.Key(me, id); remove.add(key); <START> starredChangesCache.evict(key); <END> } } db.starredChanges().insert(add); db.starredChanges().deleteKeys(remove); return VoidResult.INSTANCE; } }); }</code><technical_language>evict caches database updated successfully. concurrent reader loaded cache record eviction ad database update load stale data</technical_language>

Target:
public void toggleStars(final ToggleStarRequest req, final AsyncCallback<VoidResult> callback) { run(callback, new Action<VoidResult>() { public VoidResult run(final ReviewDb db) throws OrmException { final Account.Id me = getAccountId(); final Set<Change.Id> existing = currentUser.get().getStarredChanges(); List<StarredChange> add = new ArrayList<StarredChange>(); List<StarredChange.Key> remove = new ArrayList<StarredChange.Key>(); if (req.getAddSet() != null) { for (final Change.Id id : req.getAddSet()) { if (!existing.contains(id)) { StarredChange.Key key = new StarredChange.Key(me, id); add.add(new StarredChange(key)); } } } if (req.getRemoveSet() != null) { for (final Change.Id id : req.getRemoveSet()) { StarredChange.Key key = new StarredChange.Key(me, id); remove.add(key); } } db.starredChanges().insert(add); db.starredChanges().deleteKeys(remove); for (StarredChange sc : add) { starredChangesCache.evict(new StarredChange.Key(sc.getAccountId(), sc .getChangeId())); } for (StarredChange.Key key : remove) { starredChangesCache.evict(key); } return VoidResult.INSTANCE; } }); }
Source:
<code>private void writeResponse() { String result = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + 0 + "\r\n" + "Connection: close\r\n\r\n"; try { os.write(result.getBytes()); os.flush(); } catch (IOException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>Please logger instead of e.printStackTrace()</technical_language>

Target:
private void writeResponse() { String result = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + 0 + "\r\n" + "Connection: close\r\n\r\n"; try { os.write(result.getBytes()); os.flush(); } catch (IOException e) { logger.error(e.getMessage()); } }
Source:
<code><START> private String getErrorString(final String errorMessage, <END> final List<String> issues) { if((issues == null) || issues.isEmpty()) { return null; } StringBuilder builder = new StringBuilder(); builder.append(errorMessage); for (String issue : issues) { builder.append(" "); builder.append(issue); } return builder.toString(); }</code><technical_language>StaticUtils.collectionToString for this</technical_language>

Target:
private String getErrorString(final String errorMessage, final List<String> issues) { if ((issues == null) || issues.isEmpty()) { return null; } StringBuilder errorStringBuilder = new StringBuilder(errorMessage); errorStringBuilder.append(" "); errorStringBuilder.append(StaticUtils.collectionToString(issues, " ")); return errorStringBuilder.toString(); }
Source:
<code>public SavedRequest getRequest(HttpServletRequest request, HttpServletResponse response) { Cookie savedRequestCookie = WebUtils.getCookie(request, cookieName); <START> return savedRequestCookie != null ? new SimpleSavedRequest(savedRequestCookie.getValue()) : null; <END> }</code><technical_language>This DefaultSavedRequest instead of SimpleSavedRequest</technical_language>

Target:
public SavedRequest getRequest(HttpServletRequest request, HttpServletResponse response) { Cookie savedRequestCookie = WebUtils.getCookie(request, COOKIE_NAME); if (savedRequestCookie != null) { String originalURI = decodeCookie(savedRequestCookie.getValue()); UriComponents uriComponents = UriComponentsBuilder.fromUriString(originalURI).build(); DefaultSavedRequest.Builder builder = new DefaultSavedRequest.Builder(); int port = uriComponents.getPort(); if (port == -1) { if ("https".equalsIgnoreCase(uriComponents.getScheme())) { port = 443; } else { port = 80; } } return builder.setScheme(uriComponents.getScheme()) .setServerName(uriComponents.getHost()) .setRequestURI(uriComponents.getPath()) .setQueryString(uriComponents.getQuery()) .setServerPort(port) .build(); } return null; }
Source:
<code>private CoverageUnit getMethodCoverageUnit(CoverageUnit fromFile, CoverageItem fromItem) { for (CoverageUnit unit : fromFile.getCoverageUnits()) { if (unit.getName().equals(fromItem.getParent().getName())) { if (!forMethodNumbers || (forMethodNumbers && unit.getOrderNumber().equals( fromItem.getParent().getOrderNumber()))) { return unit; <START> } <END> } } return null; }</code><technical_language>Is a simplify this if statement of put in a method clear</technical_language>

Target:
private CoverageUnit getMethodCoverageUnit(CoverageUnit fromFile, CoverageItem fromItem) { CoverageUnit ret = null; for (CoverageUnit unit : fromFile.getCoverageUnits()) { if (methodsMatched(unit, fromFile, forceCompareMethodNumbers)) { ret = unit; break; } } return ret; }
Source:
<code>public T obtain() throws E, TimeoutException { <START> while (true) { <END> try { if (!semaphore.tryAcquire(1, obtainClientTimeoutMs, TimeUnit.MILLISECONDS)) { throw new TimeoutException("Failed to obtain client."); } break; } catch (InterruptedException e) { LOG.warn("Wait interrupted. Ignoring and retrying."); } } T client = elements.poll(); if (client != null) { return client; } return create(); }</code><technical_language>Do need while loop here</technical_language>

Target:
public T obtain() throws E, TimeoutException, InterruptedException { semaphore.acquire(); return getOrCreate(); }
Source:
<code>public double pastCompositionFactor() { double compositionFactor = 1.0d; LocalDate currentFixing = firstFixing; LocalDate currentPublication = index.calculatePublicationFromFixing(currentFixing); while ((!currentFixing.isAfter(lastFixingNonCutoff)) && env.getValuationDate().isAfter(currentPublication)) { LocalDate effectiveDate = index.calculateEffectiveFromFixing(currentFixing); LocalDate maturityDate = index.calculateMaturityFromEffective(effectiveDate); double accrualFactor = index.getDayCount().yearFraction(effectiveDate, maturityDate); compositionFactor *= 1.0d + accrualFactor * checkedFixing(currentFixing, indexFixingDateSeries, index); currentFixing = fixingCalendar.next(currentFixing); currentPublication = index.calculatePublicationFromFixing(currentFixing); } if (currentFixing.equals(lastFixingNonCutoff) && env.getValuationDate().isAfter(currentPublication)) { double rate = checkedFixing(currentFixing, indexFixingDateSeries, index); for (int i = 0; i < cutoffOffset - 1; i++) { compositionFactor *= 1.0d + accrualFactorCutoff[i] * rate; } <START> currentFixing = fixingCalendar.next(currentFixing); <END> } nextFixing = currentFixing; return compositionFactor; }</code><technical_language>Contents of this if statement tested env.getValuationDate().isAfter(currentPublication) false</technical_language>

Target:
private double pastCompositionFactor() { double compositionFactor = 1.0d; LocalDate currentFixing = firstFixing; LocalDate currentPublication = index.calculatePublicationFromFixing(currentFixing); while ((currentFixing.isBefore(lastFixingNonCutoff)) && env.getValuationDate().isAfter(currentPublication)) { LocalDate effectiveDate = index.calculateEffectiveFromFixing(currentFixing); LocalDate maturityDate = index.calculateMaturityFromEffective(effectiveDate); double accrualFactor = index.getDayCount().yearFraction(effectiveDate, maturityDate); compositionFactor *= 1.0d + accrualFactor * checkedFixing(currentFixing, indexFixingDateSeries, index); currentFixing = fixingCalendar.next(currentFixing); currentPublication = index.calculatePublicationFromFixing(currentFixing); } if (currentFixing.equals(lastFixingNonCutoff) && env.getValuationDate().isAfter(currentPublication)) { double rate = checkedFixing(currentFixing, indexFixingDateSeries, index); LocalDate effectiveDate = index.calculateEffectiveFromFixing(currentFixing); LocalDate maturityDate = index.calculateMaturityFromEffective(effectiveDate); double accrualFactor = index.getDayCount().yearFraction(effectiveDate, maturityDate); compositionFactor *= 1.0d + accrualFactor * rate; for (int i = 0; i < cutoffOffset - 1; i++) { compositionFactor *= 1.0d + accrualFactorCutoff[i] * rate; } currentFixing = fixingCalendar.next(currentFixing); } nextFixing = currentFixing; return compositionFactor; }
Source:
<code>public HeaderWriterServerLogoutHandler(ServerHttpHeadersWriter headersWriter) { <START> Assert.notNull(headersWriter, "ServerHttpHeadersWriter must not be null"); <END> this.headersWriter = headersWriter; }</code><technical_language>Curious if consistent [servlet version](<LINK_0> is headersWriter null</technical_language>

Target:
public HeaderWriterServerLogoutHandler(ServerHttpHeadersWriter headersWriter) { Assert.notNull(headersWriter, "headersWriter cannot be null"); this.headersWriter = headersWriter; }
Source:
<code>public void testReadProtocolWithBrokenState() { client.connect(); try { client.getOne(); <START> } catch (JedisConnectionException ignored) { <END> } try { client.getOne(); fail("Should throw exception"); } catch (JedisConnectionException exc) { assertEquals("Trying to read from a broken connection", exc.getMessage()); } }</code><technical_language>Add a fail this</technical_language>

Target:
public void testReadProtocolWithBrokenState() { client.connect(); try { client.getOne(); fail("Should have thrown an exception as there is nothing to read"); } catch (JedisConnectionException ignored) { assertEquals("Unexpected end of stream.", ignored.getMessage()); } try { client.getOne(); fail("Should have failed due to reading from a broken connection"); } catch (JedisConnectionException exc) { assertEquals("Trying to read from a broken connection", exc.getMessage()); } }
Source:
<code>static EquatableValueSet of(Type type, Object first, Object... rest) { <START> LinkedHashSet<ValueEntry> set = new LinkedHashSet<>(rest.length + 1); <END> set.add(ValueEntry.create(type, first)); for (Object value : rest) { set.add(ValueEntry.create(type, value)); } return new EquatableValueSet(type, true, set); }</code><technical_language>declaration HashSet</technical_language>

Target:
static EquatableValueSet of(Type type, Object first, Object... rest) { HashSet<ValueEntry> set = new LinkedHashSet<>(rest.length + 1); set.add(ValueEntry.create(type, first)); for (Object value : rest) { set.add(ValueEntry.create(type, value)); } return new EquatableValueSet(type, true, set); }
Source:
<code>public boolean saveValue(final String variableKey, final char[] variableValue) { try { final SecretKeyFactory factory = SecretKeyFactory.getInstance( SECRETS_STORE_SECRET_KEY_FACTORY_TYPE); final SecretKey generatedSecret = factory.generateSecret(new PBEKeySpec(encrypt(variableValue).toCharArray())); final KeyStore keyStore = getSecretsStore(); final PasswordProtection keyStorePP = new PasswordProtection(loadStorePassword()); <START> keyStore.setEntry(variableKey, new KeyStore.SecretKeyEntry(generatedSecret), keyStorePP); <END> saveSecretsStore(keyStore); } catch (Exception e) { Logger.warn(this.getClass(), "Unable to save secret from " + SECRETS_STORE_FILE + ": " + e); throw new DotRuntimeException(e); } return true; }</code><technical_language>need .toLowerCase()?, I thought keys saved lowercase in keystore</technical_language>

Target:
public boolean saveValue(final String variableKey, final char[] variableValue) { try { final SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRETS_STORE_SECRET_KEY_FACTORY_TYPE); final KeyStore keyStore = getSecretsStore(); final char encryptedVal = encrypt(variableValue).toCharArray(); final SecretKey generatedSecret = factory.generateSecret(new PBEKeySpec(encryptedVal)); final PasswordProtection keyStorePP = new PasswordProtection(loadStorePassword()); keyStore.setEntry(variableKey, new KeyStore.SecretKeyEntry(generatedSecret), keyStorePP); saveSecretsStore(keyStore); putInCache(variableKey, encryptedVal); } catch (Exception e) { Logger.warn(this.getClass(), "Unable to save secret from " + SECRETS_STORE_FILE + ": " + e); throw new DotRuntimeException(e); } return true; }
Source:
<code><START> public RealmEventStreamTask<DocumentT> watch(final BsonValue... ids) { <END> return new RealmEventStreamTaskImpl<>(getNamespace().getFullName(), new RealmEventStreamTaskImpl.Executor<DocumentT>() { @Override public EventStream<DocumentT> run() throws IOException { return osMongoCollection.watch(ids); } }); }</code><technical_language>codec registry allow automatic argument conversion in Functions.callFunction. allow collapsing this method</technical_language>

Target:
public RealmEventStreamTask<DocumentT> watch(final BsonValue... ids) { return new RealmEventStreamTaskImpl<>(getNamespace().getFullName(), new RealmEventStreamTaskImpl.Executor<DocumentT>() { @Override public EventStream<DocumentT> run() throws IOException { return osMongoCollection.watch(Arrays.asList(ids)); } }); }
Source:
<code>protected abstract void isMasterRunning() throws ServiceException; private Object makeStubNoRetries() throws IOException, ServiceException { ServerName sn = registry.getActiveMaster(); if (sn == null) { <START> String msg = "ZooKeeper available but no active master location found"; <END> LOG.info(msg); throw new MasterNotRunningException(msg); } if (isDeadServer(sn)) { throw new MasterNotRunningException(sn + " is dead."); } String key = getStubKey(getServiceName(), sn.getHostname(), sn.getPort(), hostnamesCanChange); connectionLock.putIfAbsent(key, key); Object stub = null; synchronized (connectionLock.get(key)) { stub = stubs.get(key); if (stub == null) { BlockingRpcChannel channel = rpcClient.createBlockingRpcChannel(sn, user, rpcTimeout); stub = makeStub(channel); isMasterRunning(); stubs.put(key, stub); } } return stub; }</code><technical_language>Is this correct exception text emit</technical_language>

Target:
protected abstract void isMasterRunning() throws ServiceException; private Object makeStubNoRetries() throws IOException, ServiceException { ServerName sn = registry.getActiveMaster(); if (sn == null) { String msg = "No active master location found"; LOG.info(msg); throw new MasterNotRunningException(msg); } if (isDeadServer(sn)) { throw new MasterNotRunningException(sn + " is dead."); } String key = getStubKey(getServiceName(), sn.getHostname(), sn.getPort(), hostnamesCanChange); connectionLock.putIfAbsent(key, key); Object stub = null; synchronized (connectionLock.get(key)) { stub = stubs.get(key); if (stub == null) { BlockingRpcChannel channel = rpcClient.createBlockingRpcChannel(sn, user, rpcTimeout); stub = makeStub(channel); isMasterRunning(); stubs.put(key, stub); } } return stub; }
Source:
<code>public RouteServerExposer( @Nullable @Named("che.infra.openshift.route.labels") String labelsProperty) { this.labels = labelsProperty != null <START> ? Splitter.on(",").withKeyValueSeparator("=").split(labelsProperty) <END> : new HashMap<>(); }</code><technical_language>Collections.emptyMap</technical_language>

Target:
public RouteServerExposer( @Nullable @Named("che.infra.openshift.route.labels") String labelsProperty) { this.labels = labelsProperty != null ? Splitter.on(",").withKeyValueSeparator("=").split(labelsProperty) : emptyMap(); }
Source:
<code>public static void sendPullRequestBuildStatusEvent(final PullRequestMergeCommitCreatedEventArgs gitCodePushedEventArgs, final GitStatusState buildState, final String buildDescription, final String targetUrl, final String jobFullPath) { try { final TeamGitStatus status = new TeamGitStatus(); status.state = buildState; status.description = buildDescription; status.targetUrl = targetUrl; status.context = new GitStatusContext(" ", StringUtils.stripEnd(jobFullPath, "/")); final URI collectionUri = gitCodePushedEventArgs.collectionUri; final TeamRestClient client = new TeamRestClient(collectionUri); client.addPullRequestStatus(gitCodePushedEventArgs, status); } catch (MalformedURLException e) { <START> e.printStackTrace(); <END> } catch (IOException e) { e.printStackTrace(); } return; }</code><technical_language>errors logger (<LINK_0> easy find filter</technical_language>

Target:
public static void sendPullRequestBuildStatusEvent(final PullRequestMergeCommitCreatedEventArgs gitCodePushedEventArgs, final GitStatusState buildState, final String buildDescription, final String targetUrl, final String jobFullPath) { try { final TeamGitStatus status = new TeamGitStatus(); status.state = buildState; status.description = buildDescription; status.targetUrl = targetUrl; status.context = new GitStatusContext(" ", StringUtils.stripEnd(jobFullPath, "/")); final URI collectionUri = gitCodePushedEventArgs.collectionUri; final TeamRestClient client = new TeamRestClient(collectionUri); client.addPullRequestStatus(gitCodePushedEventArgs, status); } catch (MalformedURLException e) { log.warning("ERROR: sendPullRequestBuildStatusEvent fails due to MalformedURLException: " + e.getMessage()); } catch (IOException e) { log.warning("ERROR: sendPullRequestBuildStatusEvent fails due to IOException: " + e.getMessage()); } return; }
Source:
<code>public void canDeserializeClientConfig() throws IOException { PrivilegesConfiguration configuration = deserialize(getConfigFile(CLIENT_PRIVILEGES_CONFIG)); assertThat(configuration).isInstanceOf(ClientPrivilegesConfiguration.class); <START> assertThat(configuration.id()).isEqualTo(CLIENT_ID); <END> Privileges privileges = configuration.privileges(); assertThat(privileges.hasPrivilege(CLIENT_NAMESPACE_1)).isTrue(); assertThat(privileges.hasPrivilege(CLIENT_NAMESPACE_2)).isTrue(); }</code><technical_language>construct equivalent ClientPrivilegesConfiguration compare</technical_language>

Target:
public void canDeserializeClientConfig() throws IOException { PrivilegesConfiguration deserializedConfiguration = deserialize(getConfigFile(CLIENT_PRIVILEGES_CONFIG)); ClientPrivilegesConfiguration expectedConfiguration = ImmutableClientPrivilegesConfiguration.builder() .clientId(CLIENT_ID) .addNamespaces(CLIENT_NAMESPACE_1, CLIENT_NAMESPACE_2) .build(); assertThat(deserializedConfiguration).isEqualTo(expectedConfiguration); }
Source:
<code>default Option<Double> average() { if (isEmpty()) { return Option.none(); } else { final T head; final java.util.stream.Stream<T> elements; if (isTraversableAgain()) { head = head(); elements = toJavaStream(); } else { final Iterator<T> iterator = iterator(); head = iterator.next(); elements = Iterator.of(head).concat(iterator).toJavaStream(); } if (head instanceof Number) { final java.util.stream.Stream<Number> numbers = (java.util.stream.Stream<Number>) elements; final double avg; if (head instanceof Integer || head instanceof Long || head instanceof Byte || head instanceof BigInteger || head instanceof Short) { avg = numbers.mapToLong(Number::longValue).average().getAsDouble(); } else { avg = numbers.mapToDouble(Number::doubleValue).average().getAsDouble(); } return Option.some(avg); } else { <START> throw new UnsupportedOperationException("not numeric"); <END> } } }</code><technical_language>is check for this condition (assert precondition) inverting predicate if(!(head instanceof Number)) throw new UnsupportedOperationException) Then, remove else altogether reduce complexity indentation</technical_language>

Target:
default Option<Double> average() { try { final double[] sum = TraversableModule.neumaierSum(this, t -> ((Number) t).doubleValue()); final double count = sum[1]; return (count == 0) ? Option.none() : Option.some(sum[0] / count); } catch(ClassCastException x) { throw new UnsupportedOperationException("not numeric", x); } }
Source:
<code>public void showNotificationPane(Node graphic, String text, Action action) { hideNotificationPane(); <START> Platform.runLater(() -> { <END> notificationPane.setGraphic(graphic); notificationPane.setText(text); notificationPane.getActions().clear(); notificationPane.getActions().add(action); notificationPane.show(); notificationPaneTimer.restart(); if (notificationPaneTimer.isPaused()) { notificationPaneTimer.resume(); } }); }</code><technical_language>this line previous is this: java void showNotificationPanel(...) { Platform.runLater(() -> { // hide }); Platform.runLater(() -> { // show }); } show block is guaranteed follow hide block in a sequential environment, if showNotificationPanel is called threads concurrently, show hide blocks interleave. permutation hideN precedes showN is possible: hide1 show1 hide2 show2 // normal hide2 show2 hide1 show1 // hide1 hide2 show1 show2 // unexpected happen hide2 hide1 show1 show2 // this staring for a while I _think_ is incorrect behaviour right now, in future. :grimacing: safe side ensure hiding, showing is done atomic action. Another issue is if multiple concurrent calls, order is undefined appear. buffer notification requests somehow... for another issue</technical_language>

Target:
public void showNotificationPane(Node graphic, String text, Action action) { Platform.runLater(() -> { hideNotificationPane(); notificationPane.setGraphic(graphic); notificationPane.setText(text); notificationPane.getActions().clear(); notificationPane.getActions().add(action); notificationPane.show(); notificationPaneTimer.restart(); if (notificationPaneTimer.isPaused()) { notificationPaneTimer.resume(); } }); }
Source:
<code>protected Map<String, Object> toMap() { ObjectMapper mapper = new ObjectMapper(); <START> mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); <END> try { String json = mapper.writeValueAsString(this); final MapType type = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class); return mapper.readValue(json, type); } catch (Exception e) { throw new RuntimeException("Failed to convert " + this.getClass().getName() + " to map.", e); } }</code><technical_language>create new mappers frequently. Is supposed typical pattern for Jackson? creating kind of cost? re-used</technical_language>

Target:
protected Map<String, Object> toMap() { try { String json = MAPPER.writeValueAsString(this); final MapType type = MAPPER.getTypeFactory().constructMapType(Map.class, String.class, Object.class); return MAPPER.readValue(json, type); } catch (Exception e) { throw new RuntimeException("Failed to convert " + this.getClass().getName() + " to map.", e); } }
Source:
<code>private static String[] decodeParams(HttpPostCommand command, int expectedParamCount) throws UnsupportedEncodingException { final byte[] data = command.getData(); final String[] encoded = bytesToString(data).split("&"); final String[] decoded = new String[encoded.length]; if (encoded.length < expectedParamCount) { <START> return null; <END> } for (int i = 0; i < expectedParamCount; i++) { decoded[i] = URLDecoder.decode(encoded[i], "UTF-8"); } return decoded; }</code><technical_language>I decided handle error returning null, throwing exception. disadvantage of this approach is if forget handle anywhere, get NullPointerException</technical_language>

Target:
String[] decodeParams(HttpPostCommand command, int expectedParamCount) throws UnsupportedEncodingException { byte[] data = command.getData(); if (data == null) { throw new HttpBadRequestException( "This endpoint expects at least " + expectedParamCount + " parameters"); } String[] encoded = bytesToString(data).split("&", expectedParamCount); String[] decoded = new String[encoded.length]; if (encoded.length < expectedParamCount) { throw new HttpBadRequestException( "This endpoint expects at least " + expectedParamCount + " parameters"); } for (int i = 0; i < expectedParamCount; i++) { decoded[i] = URLDecoder.decode(encoded[i], "UTF-8"); } return decoded; }
Source:
<code>public void afterReceive(boolean messageReceived, MessageSource<?> source) { if (this.logger.isTraceEnabled()) { <START> this.logger.trace("Poll resulted in message: " + messageReceived); <END> } this.factory.clearThreadKey(); if (!this.fair && !messageReceived) { configureSource(source); } }</code><technical_language>Feels is missed else..</technical_language>

Target:
public void afterReceive(boolean messageReceived, MessageSource<?> source) { if (this.logger.isTraceEnabled()) { this.logger.trace("Poll produced " + (messageReceived ? "a" : "no") + " message"); } this.factory.clearThreadKey(); if (!this.fair && !messageReceived) { configureSource(source); } }
Source:
<code>public void setup() { observable = Observable.never(); <START> subscriber = new Subscriber<Object>() { <END> @Override public void onCompleted() { onCompleteCalled = true; } @Override public void onError(Throwable e) { } @Override public void onNext(Object o) { } }; onCompleteCalled = false; }</code><technical_language>I suggest a mock Subscriber here. test verify onCompleted() is called. want test behaviour for onNext() onError()</technical_language>

Target:
public void setup() { MockitoAnnotations.initMocks(this); }
Source:
<code>public static Map<Cell, byte[]> deserializeCellVals(final TableMetadata metadata, JsonNode node) { Iterable<Iterable<Entry<Cell, byte[]>>> cellVals; <START> cellVals = new JsonNodeIterable<>(node, subNode -> deserializeCellVal(metadata, subNode)); <END> ImmutableMap.Builder<Cell, byte[]> builder = ImmutableMap.builder(); for (Iterable<Entry<Cell, byte[]>> entries : cellVals) { for (Entry<Cell, byte[]> entry : entries) { builder.put(entry); } } return builder.build(); }</code><technical_language>nit: this is a slightly nasty line length issue</technical_language>

Target:
public static Map<Cell, byte[]> deserializeCellVals(final TableMetadata metadata, JsonNode node) { Iterable<Iterable<Entry<Cell, byte[]>>> cellVals = new JsonNodeIterable<>(node, subNode -> deserializeCellVal(metadata, subNode)); ImmutableMap.Builder<Cell, byte[]> builder = ImmutableMap.builder(); for (Iterable<Entry<Cell, byte[]>> entries : cellVals) { for (Entry<Cell, byte[]> entry : entries) { builder.put(entry); } } return builder.build(); }
Source:
<code>void nonEnabledHealthReport() { HealthDescriptor descriptor = new HealthDescriptor("2", "1", Priority.NORMAL); HealthSeriesBuilder builder = new HealthSeriesBuilder(descriptor); StaticAnalysisRun run = createSimpleBuildResult(3); List<Integer> computeResult = builder.computeSeries(run); assertThat(computeResult).hasSize(1); <START> assertThat(computeResult).startsWith(3); <END> }</code><technical_language>containsExactly oder isEqualTo verwenden</technical_language>

Target:
void nonEnabledHealthReport() { HealthSeriesBuilder builder = createBuilder("2", "1", Priority.NORMAL); StaticAnalysisRun run = createSimpleBuildResult(3); List<Integer> computeResult = builder.computeSeries(run); assertThat(computeResult).containsExactly(3); }
Source:
<code>public BackendInternal getBackend() { <START> return super.getBackend(); <END> }</code><technical_language>super</technical_language>

Target:
public BackendInternal getBackend() { return Backend.getInstance(); }
Source:
<code><START> private ByteBuffer deepCopyBuffer(ByteBuf byteBuf) { <END> ByteBuffer buffer = byteBuf.nioBuffer(); int offset = buffer.position(); int size = buffer.remaining(); byte[] duplicate = new byte[size]; for (int i = 0; i < size; i++) { duplicate[i] = buffer.get(i + offset); } return ByteBuffer.wrap(duplicate); }</code><technical_language>this static</technical_language>

Target:
private static ByteBuffer deepCopyBuffer(ByteBuf byteBuf) { ByteBuffer buffer = ByteBuffer.allocate(byteBuf.readableBytes()); byteBuf.readBytes(buffer); buffer.rewind(); return buffer; }
Source:
<code>ListBookiesCmd() { super(CMD_LISTBOOKIES); opts.addOption("rw", "readwrite", false, "Print readwrite bookies"); opts.addOption("ro", "readonly", false, "Print readonly bookies"); <START> } <END></code><technical_language>I is a good idea remove option directly. I suggest marking this deprecated remove this in 4.8</technical_language>

Target:
ListBookiesCmd() { super(CMD_LISTBOOKIES); opts.addOption("rw", "readwrite", false, "Print readwrite bookies"); opts.addOption("ro", "readonly", false, "Print readonly bookies"); opts.addOption("h", "hostnames", false, "Also print hostname of the bookie"); }
Source:
<code>public KuduTableHandle getTableHandle(ConnectorSession session, SchemaTableName schemaTableName) { try { KuduTable table = clientSession.openTable(schemaTableName); return new KuduTableHandle(connectorId, schemaTableName, table); } <START> catch (Exception e) { <END> return null; } }</code><technical_language>this narrowed some kudu related exception</technical_language>

Target:
public KuduTableHandle getTableHandle(ConnectorSession session, SchemaTableName schemaTableName) { try { KuduTable table = clientSession.openTable(schemaTableName); return new KuduTableHandle(connectorId, schemaTableName, table); } catch (NotFoundException e) { return null; } }
Source:
<code>public boolean deployAllAPIsAtGatewayStartup (Set<String> assignedGatewayLabels) { if (gatewayArtifactSynchronizerProperties.isRetrieveFromStorageEnabled()) { if (artifactRetriever != null) { try { for (Iterator<String> it = assignedGatewayLabels.iterator(); it.hasNext();) { String label = it.next(); List<String> gatewayRuntimeArtifacts = ServiceReferenceHolder .getInstance().getArtifactRetriever().retrieveAllArtifacts(label); for (String APIruntimeArtifact :gatewayRuntimeArtifacts){ GatewayAPIDTO gatewayAPIDTO = null; try { gatewayAPIDTO = new Gson().fromJson(APIruntimeArtifact, GatewayAPIDTO.class); log.info("Deploying synapse artifacts of " + gatewayAPIDTO.getName()); apiGatewayAdmin.deployAPI(gatewayAPIDTO); } catch (AxisFault axisFault) { log.error("Error in deploying" + gatewayAPIDTO.getName()+ " to the Gateway "); continue; } } } return true; } catch (ArtifactSynchronizerException e ) { log.error("Error deploying APIs to the Gateway " + e ); } } else { log.error("Artifact retriever not found"); <START> } <END> } return false; }</code><technical_language>while(it.hasnext())</technical_language>

Target:
public boolean deployAllAPIsAtGatewayStartup (Set<String> assignedGatewayLabels) { if (gatewayArtifactSynchronizerProperties.isRetrieveFromStorageEnabled()) { if (artifactRetriever != null) { try { Iterator<String> it = assignedGatewayLabels.iterator(); while (it.hasNext()) { String label = it.next(); List<String> gatewayRuntimeArtifacts = ServiceReferenceHolder .getInstance().getArtifactRetriever().retrieveAllArtifacts(label); for (String APIruntimeArtifact :gatewayRuntimeArtifacts){ GatewayAPIDTO gatewayAPIDTO = null; try { if (APIruntimeArtifact != null) { gatewayAPIDTO = new Gson().fromJson(APIruntimeArtifact, GatewayAPIDTO.class); log.info("Deploying synapse artifacts of " + gatewayAPIDTO.getName()); apiGatewayAdmin.deployAPI(gatewayAPIDTO); } } catch (AxisFault axisFault) { log.error("Error in deploying" + gatewayAPIDTO.getName()+ " to the Gateway "); continue; } } } return true; } catch (ArtifactSynchronizerException e ) { log.error("Error deploying APIs to the Gateway " + e ); } } else { log.error("Artifact retriever not found"); } } return false; }
Source:
<code>private Cursor getNicknameCursor(String nickname) { Uri queryUriForNickname = ContactsContract.Data.CONTENT_URI; <START> final String[] PROJECTION_NICKNAME = <END> new String[] { ContactsContract.Data.CONTACT_ID, ContactsContract.CommonDataKinds.Nickname.NAME }; return getContext().getContentResolver().query(queryUriForNickname, PROJECTION_NICKNAME, ContactsContract.CommonDataKinds.Nickname.NAME + " LIKE ? AND " + Data.MIMETYPE + " = ?", new String[] { nickname, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE }, null); }</code><technical_language>a static field</technical_language>

Target:
private Cursor getNicknameCursor(String nickname) { nickname = "%" + nickname + "%"; Uri queryUriForNickname = ContactsContract.Data.CONTENT_URI; return getContext().getContentResolver().query(queryUriForNickname, PROJECTION_NICKNAME, ContactsContract.CommonDataKinds.Nickname.NAME + " LIKE ? AND " + Data.MIMETYPE + " = ?", new String[] { nickname, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE }, null); }
Source:
<code>public long getLastCacheUpdateTime(String cacheType, String cacheKey) { try { if (cacheType == null || cacheKey == null || Constants.EMPTY_STRING.equals(cacheType) || Constants.EMPTY_STRING.equals(cacheKey)) { return 0; } final String soupName = cacheType + cacheKey; if (!doesCacheExist(soupName)) { return 0; } final String smartSql = "SELECT {" + soupName + ":" + String.format(CACHE_TIME_KEY, cacheKey) + "} FROM {" + soupName + "}"; QuerySpec querySpec = QuerySpec.buildSmartQuerySpec(smartSql, 10); int count = smartStore.countQuery(querySpec); if (count == 0) { return 0; } querySpec = QuerySpec.buildSmartQuerySpec(smartSql, count); final JSONArray results = smartStore.query(querySpec, 0); if (results != null && results.length() > 0) { final JSONArray array = results.optJSONArray(0); if (array != null && array.length() > 0) { final String res = array.optString(0); <START> if (res != null && !Constants.EMPTY_STRING.equals(res)) { <END> return Long.parseLong(res); } } } } catch (IllegalStateException e) { Log.e(TAG, "IllegalStateException occurred while attempting to read last cached time", e); } catch (JSONException e) { Log.e(TAG, "JSONException occurred while attempting to read last cached time", e); } catch (SmartStoreException e) { Log.e(TAG, "SmartStoreException occurred while attempting to read last cached time", e); } return 0; }</code><technical_language>index field a long returned one</technical_language>

Target:
public long getLastCacheUpdateTime(String cacheType, String cacheKey) { try { if (cacheType == null || cacheKey == null || Constants.EMPTY_STRING.equals(cacheType) || Constants.EMPTY_STRING.equals(cacheKey)) { return 0; } final String soupName = cacheType + cacheKey; if (!doesCacheExist(soupName)) { return 0; } final String smartSql = "SELECT {" + soupName + ":" + String.format(CACHE_TIME_KEY, cacheKey) + "} FROM {" + soupName + "}"; final QuerySpec querySpec = QuerySpec.buildSmartQuerySpec(smartSql, 1); final JSONArray results = smartStore.query(querySpec, 0); if (results != null && results.length() > 0) { final JSONArray array = results.optJSONArray(0); if (array != null && array.length() > 0) { return array.optLong(0); } } } catch (IllegalStateException e) { Log.e(TAG, "IllegalStateException occurred while attempting to read last cached time", e); } catch (JSONException e) { Log.e(TAG, "JSONException occurred while attempting to read last cached time", e); } catch (SmartStoreException e) { Log.e(TAG, "SmartStoreException occurred while attempting to read last cached time", e); } return 0; }
Source:
<code>private static Iterable<String> append( final Response res, final int length) throws IOException { <START> return new RsWithHeader( <END> res, String.format("Content-Length:%s", length) ).head(); }</code><technical_language>RsWithHeader(res, "Content-Length", length),</technical_language>

Target:
private static Iterable<String> append( final Response res, final int length) throws IOException { return new RsWithHeader( res, "Content-Length", Integer.toString(length) ).head(); }