auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public static Collection<TypeUrl> getTypesFromPackage(final String packageName) { <END> final Collection<TypeUrl> knownTypeUrls = knownTypes.keySet(); final Collection<TypeUrl> result = Collections2.filter(knownTypeUrls, new Predicate<TypeUrl>() { @Override public boolean apply(@Nullable TypeUrl input) { if (input == null) { return false; } final boolean inPackage = input.getTypeName().startsWith(packageName); return inPackage; } }); return result; }</code><technical_language>Set</technical_language>

Target:
public static Set<TypeUrl> getTypesFromPackage(final String packageName) { final Collection<TypeUrl> knownTypeUrls = knownTypes.keySet(); final Collection<TypeUrl> resultCollection = Collections2.filter(knownTypeUrls, new Predicate<TypeUrl>() { @Override public boolean apply(@Nullable TypeUrl input) { if (input == null) { return false; } final String typeName = input.getTypeName(); final boolean inPackage = typeName.startsWith(packageName) && typeName.charAt(packageName.length()) == PACKAGE_SEPARATOR; return inPackage; } }); final Set<TypeUrl> resultSet = ImmutableSet.copyOf(resultCollection); return resultSet; }
Source:
<code>public Element unparseServiceCreationConfiguration(ServiceCreationConfiguration<TransactionManagerProvider> serviceCreationConfiguration) { try { validateParameterForTranslationToServiceConfig(serviceCreationConfiguration); Document doc = createDocumentRoot(); LookupTransactionManagerProviderConfiguration lookupTransactionManagerProviderConfiguration = (LookupTransactionManagerProviderConfiguration) serviceCreationConfiguration; Element rootElement = createRootElement(doc, lookupTransactionManagerProviderConfiguration); return rootElement; <START> } catch (SAXException | ParserConfigurationException | IOException e) { <END> throw new XmlConfigurationException(e); } }</code><technical_language>try carve out of this exceptions user errors due input setup errors? pretty ParserConfigurationException caused errors in user input</technical_language>

Target:
public Element unparseServiceCreationConfiguration(ServiceCreationConfiguration<TransactionManagerProvider> serviceCreationConfiguration) { return unparseConfig(serviceCreationConfiguration); }
Source:
<code><START> public StashCredentials getCredentials() throws StashConfigurationException { <END> String pwEnv = config.getStashPasswordEnvironmentVariable(); String pw = config.getStashPassword(); if (pwEnv != null) { pw = System.getenv(pwEnv); if (pw == null) { throw new StashConfigurationException( "Unable to retrieve password from configured environment variable " + StashPlugin.STASH_PASSWORD_ENVIRONMENT_VARIABLE); } } return new StashCredentials(config.getStashLogin(), pw); }</code><technical_language>catch exception in method? For readability, I tend prefer full name variables passwordEnv</technical_language>

Target:
public StashCredentials getCredentials() throws StashConfigurationException { String passwordEnvVariable = config.getStashPasswordEnvironmentVariable(); String password = config.getStashPassword(); if (passwordEnvVariable != null) { password = System.getenv(passwordEnvVariable); if (password == null) { throw new StashConfigurationException( "Unable to retrieve password from configured environment variable " + StashPlugin.STASH_PASSWORD_ENVIRONMENT_VARIABLE); } } return new StashCredentials(config.getStashLogin(), password); }
Source:
<code>public static int getKFromEpsilon(final double epsilon, final boolean pmf) { <START> final double eps = max(epsilon, 4.7E-5); <END> final double kdbl = pmf ? exp(log(1.854 / eps) / 0.9657) : exp(log(1.576 / eps) / 0.9726); final double krnd = round(kdbl); final double del = abs(krnd - kdbl); final int k = (int) ((del < 1E-6) ? krnd : ceil(kdbl)); return k; }</code><technical_language>explain this constant</technical_language>

Target:
public static int getKFromEpsilon(final double epsilon, final boolean pmf) { final double eps = max(epsilon, 6.395E-5); final double kdbl = pmf ? exp(log(1.854 / eps) / 0.9657) : exp(log(1.576 / eps) / 0.9726); final double krnd = round(kdbl); final double del = abs(krnd - kdbl); final int k = (int) ((del < 1E-6) ? krnd : ceil(kdbl)); return max(MIN_K, min(MAX_K, k)); }
Source:
<code>public static Win32VK fromValue(final int code) { <START> if (code < 0 || code > 0xFF) { <END> throw new IllegalArgumentException(String.format("No mapping for %02x", code)); } for (Win32VK vk : Win32VK.values()) { if (vk.code == code) { return vk; } } throw new IllegalArgumentException(String.format("No mapping for %02x", code)); }</code><technical_language>reason special case this? fall line 300 catch it</technical_language>

Target:
public static Win32VK fromValue(final int code) { for (Win32VK vk : Win32VK.values()) { if (vk.code == code) { return vk; } } throw new IllegalArgumentException(String.format("No mapping for %02x", code)); }
Source:
<code><START> public static DataSource cosmos( <END> String name, String cosmosConnectionString, String collectionName, String query, Boolean useChangeDetection, String description, DataDeletionDetectionPolicy deletionDetectionPolicy) { if (CoreUtils.isNullOrEmpty(name)) { throw new IllegalArgumentException("name cannot be null or empty"); } if (CoreUtils.isNullOrEmpty(collectionName)) { throw new IllegalArgumentException("collectionName cannot be null or empty"); } if (CoreUtils.isNullOrEmpty(cosmosConnectionString)) { throw new IllegalArgumentException("cosmosConnectionString cannot be null or empty"); } return new DataSource() .setName(name) .setType(DataSourceType.COSMOS) .setCredentials(new DataSourceCredentials() .setConnectionString(cosmosConnectionString)) .setContainer(new DataContainer() .setName(collectionName) .setQuery(query)) .setDescription(description) .setDataDeletionDetectionPolicy(deletionDetectionPolicy) .setDataChangeDetectionPolicy( useChangeDetection ? new HighWaterMarkChangeDetectionPolicy().setHighWaterMarkColumnName("_ts") : null); }</code><technical_language>nit: I feel this other related methods "cosmosDB" instead of "cosmos"</technical_language>

Target:
public static DataSource cosmos( String name, String cosmosConnectionString, String collectionName, String query, Boolean useChangeDetection, String description, DataDeletionDetectionPolicy deletionDetectionPolicy) { if (CoreUtils.isNullOrEmpty(name)) { throw new IllegalArgumentException("name cannot be null or empty"); } if (CoreUtils.isNullOrEmpty(collectionName)) { throw new IllegalArgumentException("collectionName cannot be null or empty"); } if (CoreUtils.isNullOrEmpty(cosmosConnectionString)) { throw new IllegalArgumentException("cosmosConnectionString cannot be null or empty"); } return new DataSource() .setName(name) .setType(DataSourceType.COSMOS) .setCredentials(new DataSourceCredentials() .setConnectionString(cosmosConnectionString)) .setContainer(new DataContainer() .setName(collectionName) .setQuery(query)) .setDataChangeDetectionPolicy( useChangeDetection ? new HighWaterMarkChangeDetectionPolicy().setHighWaterMarkColumnName("_ts") : null) .setDescription(description) .setDataDeletionDetectionPolicy(deletionDetectionPolicy); }
Source:
<code><START> public String getCommitStatusFromPatch(Patch patch) throws NotFoundException { <END> checkRepositoryServiceExists(); Objects.requireNonNull(patch, "patch cannot be null"); String status = null; for (RepositoryService repositoryService : repositories) { try { status = repositoryService.getCommitStatusFromPatch(patch); } catch (NotFoundException e) { if (LOG.isInfoEnabled()) LOG.info("No commit status found at RepositoryService: " + repositoryService.getClass().getName(), e); } } return status; }</code><technical_language>I is create enum a defined number of items (pending, failure, success). Returning String in cases more difficult for clients of API</technical_language>

Target:
public CommitStatus getCommitStatusFromPatch(Patch patch) throws NotFoundException { checkRepositoryServiceExists(); Objects.requireNonNull(patch, "patch cannot be null"); for (RepositoryService repositoryService : repositories) { try { return repositoryService.getCommitStatusFromPatch(patch); } catch (NotFoundException e) { if (LOG.isInfoEnabled()) LOG.info("No commit status found at RepositoryService: " + repositoryService.getClass().getName(), e); } } throw new NotFoundException("No commit status found for patch:" + patch.getURL()); }
Source:
<code>public Map<ByteArray, Boolean> hasKeys(Iterable<ByteArray> keys, boolean exact) { StoreUtils.assertValidKeys(keys); Map<ByteArray, Boolean> results = new HashMap<ByteArray, Boolean>(); try { fileModificationLock.readLock().lock(); List<KeyValueLocation> keysAndValueLocations = Lists.newArrayList(); for(ByteArray key: keys) { int chunk = fileSet.getChunkForKey(key.get()); int valueLocation = searchStrategy.indexOf(fileSet.indexFileFor(chunk), fileSet.keyToStorageFormat(key.get()), fileSet.getIndexFileSize(chunk)); if(valueLocation >= 0) { if(exact) keysAndValueLocations.add(new KeyValueLocation(chunk, key, valueLocation)); else results.put(key, true); } } <START> if(exact) { <END> Collections.sort(keysAndValueLocations); for(KeyValueLocation keyVal: keysAndValueLocations) { byte[] value = fileSet.readValue(keyVal.getKey().get(), keyVal.getChunk(), keyVal.getValueLocation()); if(value.length > 0) results.put(keyVal.getKey(), true); } } return results; } finally { fileModificationLock.readLock().unlock(); } }</code><technical_language>if 'exact' is specified, longer index-file-only read, correct? In this case, need control rate hasKeys used</technical_language>

Target:
public Map<ByteArray, Boolean> hasKeys(Iterable<ByteArray> keys, boolean exact) { StoreUtils.assertValidKeys(keys); Map<ByteArray, Boolean> results = new HashMap<ByteArray, Boolean>(); try { fileModificationLock.readLock().lock(); List<KeyValueLocation> keysAndValueLocations = Lists.newArrayList(); for(ByteArray key: keys) { int chunk = fileSet.getChunkForKey(key.get()); int valueLocation = searchStrategy.indexOf(fileSet.indexFileFor(chunk), fileSet.keyToStorageFormat(key.get()), fileSet.getIndexFileSize(chunk)); if(valueLocation >= 0) { if(exact) keysAndValueLocations.add(new KeyValueLocation(chunk, key, valueLocation)); else results.put(key, true); } } if(exact) { Collections.sort(keysAndValueLocations); for(KeyValueLocation keyVal: keysAndValueLocations) { results.put(keyVal.getKey(), fileSet.keyExists(keyVal.getKey().get(), keyVal.getChunk(), keyVal.getValueLocation())); } } return results; } finally { fileModificationLock.readLock().unlock(); } }
Source:
<code>public Observable<Boolean> buildRx() { <START> return Observable.defer(new Func0<Observable<Boolean>>() { <END> @Override public Observable<Boolean> call() { return Observable.create(new Observable.OnSubscribe<Boolean>() { @Override public void call(Subscriber<? super Boolean> subscriber) { try { startBuild(); subscriber.onNext(true); subscriber.onCompleted(); } catch (Exception e) { subscriber.onError(e); } } }); } }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); }</code><technical_language>Rx is optional, great if add a check, added this in Hawk.java moved utils well. java private static void checkRx() { if (!Utils.hasRxJavaOnClasspath()) { throw new NoClassDefFoundError("RxJava is classpath, " + "make in dependencies"); } }</technical_language>

Target:
public Observable<Boolean> buildRx() { Utils.checkRx(); return Observable.defer(new Func0<Observable<Boolean>>() { @Override public Observable<Boolean> call() { return Observable.create(new Observable.OnSubscribe<Boolean>() { @Override public void call(Subscriber<? super Boolean> subscriber) { try { startBuild(); subscriber.onNext(true); subscriber.onCompleted(); } catch (Exception e) { subscriber.onError(e); } } }); } }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); }
Source:
<code>public static void report(Saveable obj, Collection<Throwable> errors) { StringBuilder buf = new StringBuilder(); int i = 0; for (Throwable e : errors) { if (e instanceof ReportException) { report(obj, ((ReportException)e).version); } else { if (++i > 1) buf.append(", "); buf.append(e.getClass().getSimpleName()).append(": ").append(e.getMessage()); } } if (buf.length() == 0) return; Jenkins j = Jenkins.getInstance(); if (j == null) { for (Throwable t : errors) { LOGGER.log(Level.WARNING, "could not read " + obj + " (and Jenkins did not start up)", t); } return; } OldDataMonitor odm = get(j); SaveableReference ref = referTo(obj); while (true) { VersionRange vr = odm.data.get(ref); if (vr != null) { vr.extra = buf.toString(); break; <START> } else if (odm.data.put(ref, new VersionRange(null, buf.toString())) == null) { <END> break; } } }</code><technical_language>putIfAbsent? is a risk of overriding VersionRange if inserted another thread</technical_language>

Target:
public static void report(Saveable obj, Collection<Throwable> errors) { StringBuilder buf = new StringBuilder(); int i = 0; for (Throwable e : errors) { if (e instanceof ReportException) { report(obj, ((ReportException)e).version); } else { if (++i > 1) buf.append(", "); buf.append(e.getClass().getSimpleName()).append(": ").append(e.getMessage()); } } if (buf.length() == 0) return; Jenkins j = Jenkins.getInstance(); if (j == null) { for (Throwable t : errors) { LOGGER.log(Level.WARNING, "could not read " + obj + " (and Jenkins did not start up)", t); } return; } OldDataMonitor odm = get(j); SaveableReference ref = referTo(obj); while (true) { VersionRange vr = odm.data.get(ref); if (vr != null && odm.data.replace(ref, vr, new VersionRange(vr, null, buf.toString()))) { break; } else if (odm.data.putIfAbsent(ref, new VersionRange(null, null, buf.toString())) == null) { break; } } }
Source:
<code>protected final byte[] generatePremasterSecretFromPSK(byte[] psk, byte[] otherSecret) { int pskLength = psk.length; byte[] pskLengthField = new byte[2]; pskLengthField[0] = (byte) (pskLength >> 8); pskLengthField[1] = (byte) (pskLength); if(otherSecret == null) { <START> byte[] zero = ByteArrayUtils.padArray(new byte[0], (byte) 0x00, pskLength); <END> byte[] premasterSecret = ByteArrayUtils.concatenate(pskLengthField, ByteArrayUtils.concatenate(zero, ByteArrayUtils.concatenate(pskLengthField, psk))); return premasterSecret; } else { int otherSecretLength = otherSecret.length; byte[] otherSecretLengthField = new byte[2]; otherSecretLengthField[0] = (byte) (otherSecretLength >> 8); otherSecretLengthField[1] = (byte) (otherSecretLength); byte[] premasterSecret = ByteArrayUtils.concatenate(ByteArrayUtils.concatenate(otherSecretLengthField, otherSecret), ByteArrayUtils.concatenate(pskLengthField, psk)); return premasterSecret; } }</code><technical_language>whitespace</technical_language>

Target:
protected final byte[] generatePremasterSecretFromPSK(byte[] psk, byte[] otherSecret) { int pskLength = psk.length; byte[] other = otherSecret == null ? new byte[pskLength] : otherSecret; DatagramWriter writer = new DatagramWriter(); writer.write(other.length, 16); writer.writeBytes(other); writer.write(pskLength, 16); writer.writeBytes(psk); return writer.toByteArray(); }
Source:
<code>public void start() { <START> log.info("ShardOrganizationManager start, enabled: %s, started: %s", enabled, started); <END> if (!enabled || started.getAndSet(true)) { log.info("ShardOrganizationManager return"); return; } startDiscovery(); }</code><technical_language>I need this log. for next one</technical_language>

Target:
public void start() { if (!enabled || started.getAndSet(true)) { return; } startDiscovery(); }
Source:
<code>public Memoizer() { <START> this.map = new HashMap<K, V>(); <END> ReadWriteLock lock = new ReentrantReadWriteLock(); this.readLock = lock.readLock(); this.writeLock = lock.writeLock(); }</code><technical_language>LinkedHashMap? matter here? (on mobile)</technical_language>

Target:
public Memoizer() { this.map = new LinkedHashMap<K, V>(); ReadWriteLock lock = new ReentrantReadWriteLock(); this.readLock = lock.readLock(); this.writeLock = lock.writeLock(); }
Source:
<code>public CompletableFuture<TransactionId> startTransaction(PublicKeyHash owner) { <START> return CompletableFuture.completedFuture(new TransactionId(Long.toString(System.currentTimeMillis()))); <END> }</code><technical_language>Risk of duplicate transactionId. Resolution of currentTimeMillis is low</technical_language>

Target:
public CompletableFuture<TransactionId> startTransaction(PublicKeyHash owner) { return CompletableFuture.completedFuture(transactions.startTransaction(owner)); }
Source:
<code>private int checkHeaderField(String headerName, String fieldName, BitInputStream input, int sizeInBits, Predicate<Integer> validator) throws IOException { int value = input.readInt(sizeInBits); <START> if (validator.test(value)) { <END> throw new UnknownContentTypeException(headerName + "Header " + fieldName + ": " + value); } return value; }</code><technical_language>A validator return trueif is valid, needs other here. :)</technical_language>

Target:
private int checkHeaderField(String headerName, String fieldName, BitInputStream input, int sizeInBits, Predicate<Integer> validator) throws IOException { int value = input.readInt(sizeInBits); if (!validator.test(value)) { throw new UnknownContentTypeException(headerName + "Header " + fieldName + ": " + value); } return value; }
Source:
<code>public Transformer build(Site site) throws IOException { Templates templates = transformTemplateCache.get(site); if (templates == null) { TransformerFactory factory = newTransformerFactory(); Theme theme = site.getTheme(); try (ThemeUriResolver resolver = new ThemeUriResolver(theme); InputStream transformFile = theme.getStaticResource(rootPath + templateFilename)) { factory.setURIResolver(resolver); templates = factory.newTemplates(new StreamSource(transformFile)); } catch (TransformerConfigurationException e) { throw new RuntimeException(e); <START> } <END> transformTemplateCache.put(site, templates); } try { return templates.newTransformer(); } catch (TransformerConfigurationException e){ throw new RuntimeException(e); } }</code><technical_language>nice! pull content of this if block out a function returns of templates? (Then roll transformTemplateCache.get transformTemplateCache.put a lambdalicious transformTemplateCache.computeIfAbsent. :grinning:)</technical_language>

Target:
public Transformer build(Site site) { Templates templates = transformTemplateCache.computeIfAbsent(site, this::createTemplate); try { return templates.newTransformer(); } catch (TransformerConfigurationException e){ throw new RuntimeException(e); } }
Source:
<code>public void populateExpressionProperty(FactModelTree factModelTree) { <START> factModelTree.addSimpleProperty(factModelTree.getFactName() + "Expression", "expression"); <END> }</code><technical_language>@yesamer above, please replace "Expression" "expression" static global constants</technical_language>

Target:
public void populateExpressionProperty(FactModelTree factModelTree) { factModelTree.addSimpleProperty(factModelTree.getFactName() + ConstantsHolder.EXPRESSION_SUFFIX, ConstantsHolder.EXPRESSION_CLASSNAME); }
Source:
<code>private void verifySlotsUnblocked(AdsBaseObject ads, List<Map<String, Object>> slotsData) { for (Map<String, Object> slotData : slotsData) { String slotName = slotData.get("slotName").toString(); <START> ads.wait.forElementPresent(By.cssSelector("#"+slotName)); <END> ads.scrollToPosition("#"+slotName); Dimension slotSize = (Dimension) slotData.get("slotSize"); ads.verifyLineItemId(slotName, Integer.valueOf(slotData.get("lineItemId").toString())); ads.verifyIframeSize(slotName, slotData.get("src").toString(), slotSize.getWidth(), slotSize.getHeight()); } }</code><technical_language>try do some refactor here, is id selector, cssSelector string concatenation "#"</technical_language>

Target:
private void verifySlotsUnblocked(AdsBaseObject ads, List<Map<String, Object>> slotsData) { for (Map<String, Object> slotData : slotsData) { String slotName = slotData.get("slotName").toString(); String slotSelector = AdsContent.getSlotSelector(slotName); ads.wait.forElementPresent(By.cssSelector(slotSelector)); ads.scrollToPosition(slotSelector); Dimension slotSize = (Dimension) slotData.get("slotSize"); ads.verifyLineItemId(slotName, Integer.valueOf(slotData.get("lineItemId").toString())); ads.verifyIframeSize(slotName, slotData.get("src").toString(), slotSize.getWidth(), slotSize.getHeight()); } }
Source:
<code>public WorldBorder getWorldBorder() { if (this.worldBorder == null) { <START> this.worldBorder = cloneBorder((WorldBorder) this.world.worldBorder); <END> } return this.worldBorder; }</code><technical_language>-1: Instead default World's world border, do scoreboards</technical_language>

Target:
public Optional<WorldBorder> getWorldBorder() { return Optional.ofNullable(this.worldBorder); }
Source:
<code>public Network mapRow(ResultSet rs, int rowNum) throws SQLException { Network entity = super.mapRow(rs, rowNum); entity.setCluster(new NetworkCluster()); entity.getCluster().setDisplay((Boolean) rs.getObject("is_display")); entity.getCluster().setRequired(rs.getBoolean("required")); entity.getCluster().setStatus(NetworkStatus.forValue(rs.getInt("status"))); <START> entity.getCluster().setMigration((Boolean) rs.getObject("migration")); <END> return entity; }</code><technical_language>getBoolean</technical_language>

Target:
public Network mapRow(ResultSet rs, int rowNum) throws SQLException { Network entity = super.mapRow(rs, rowNum); entity.setCluster(new NetworkCluster()); entity.getCluster().setDisplay((Boolean) rs.getObject("is_display")); entity.getCluster().setRequired(rs.getBoolean("required")); entity.getCluster().setStatus(NetworkStatus.forValue(rs.getInt("status"))); entity.getCluster().setMigration(rs.getBoolean("migration")); return entity; }
Source:
<code>public Collection<String> getBoltNames() { <START> getCachedPhysicalPlan(); <END> return getBoltNames(cachedPhysicalPlan); }</code><technical_language>local variable cleaner. physicalPlan = getCachedPhysicalPlan(); getBoltNames(physicalPlan);</technical_language>

Target:
public List<String> getBoltNames() { PhysicalPlan pp = getPhysicalPlan(); return getBoltNames(pp); }
Source:
<code>public void seek(long position) throws IOException { <START> if (Math.abs(position - mPos) > MOVEMENT_LIMIT) { <END> mSequentialReadCount = 0; } else { ((FSDataInputStream) in).seek(position); } mPos = position; }</code><technical_language>If seek sequential count set 0</technical_language>

Target:
public void seek(long position) throws IOException { if (position < mPos || position - mPos > MOVEMENT_LIMIT) { mSequentialReadCount = 0; } mPos = position; }
Source:
<code>public int getItemViewType(int position) { if (mItemList.get(position) instanceof ParentObject) { return TYPE_PARENT; } else if (mItemList.get(position) instanceof ChildObject) { return TYPE_CHILD; } else { <START> return TYPE_PARENT; END> } }</code><technical_language>Null case log error throw - above</technical_language>

Target:
public int getItemViewType(int position) { if (mItemList.get(position) instanceof ParentObject) { return TYPE_PARENT; } else if (mItemList.get(position) instanceof ChildObject) { return TYPE_CHILD; } else if (mItemList.get(position) == null) { throw new IllegalStateException("Null object added"); } else { return TYPE_PARENT; } }
Source:
<code>public boolean sendToPlayers() { if (this.sentToPlayers) { return true; } <START> if (this.cube == null || !this.playerCubeMap.getWorld().getGeneratorPipeline().isLastStage(cube.getGeneratorStage())) { <END> return false; } this.dirtyBlocks.clear(); this.sentToPlayers = true; for (WatcherPlayerEntry entry : this.players.valueCollection()) { sendToPlayer(entry.player); } return true; }</code><technical_language>This pattern frequently. I state if is final state</technical_language>

Target:
public boolean sendToPlayers() { if (this.sentToPlayers) { return true; } if (this.cube == null || !this.cube.getGeneratorStage().isLastStage()) { return false; } this.dirtyBlocks.clear(); this.sentToPlayers = true; for (WatcherPlayerEntry entry : this.players.valueCollection()) { sendToPlayer(entry.player); } return true; }
Source:
<code>public ByteBuf getCommandLineBytes() { final ImapArgumentFormatter argWriter = new ImapArgumentFormatter(); final String flagListString = argWriter.buildFlagString(flags); final String unchangedSinceStr = unchangedSince == null ? "" : unchangedSince.toString(); <START> final int len = ImapClientConstants.PAD_LEN + msgNumbers.length() + unchangedSinceStr.length() + flagListString.length(); <END> final ByteBuf sb = Unpooled.buffer(len); sb.writeBytes(isUid ? UID_STORE_SP_B : STORE_SP_B); sb.writeBytes(msgNumbers.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.SPACE); if (unchangedSince != null) { sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(UNCHANGEDSINCE_SP_B); sb.writeBytes(unchangedSinceStr.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.R_PAREN); sb.writeByte(ImapClientConstants.SPACE); } if (action == FlagsAction.ADD) { sb.writeByte(ImapClientConstants.PLUS); } else if (action == FlagsAction.REMOVE) { sb.writeByte(ImapClientConstants.MINUS); } sb.writeBytes(FLAGS_B); if (isSilent) { sb.writeBytes(SILENT_B); } sb.writeByte(ImapClientConstants.SPACE); sb.writeBytes(flagListString.getBytes(StandardCharsets.US_ASCII)); sb.writeBytes(CRLF_B); return sb; }</code><technical_language>if this is approximate buffer size unchangedSinceLength max length pad include paren space</technical_language>

Target:
public ByteBuf getCommandLineBytes() { final ImapArgumentFormatter argWriter = new ImapArgumentFormatter(); final String flagListString = argWriter.buildFlagString(flags); final String unchangedSinceStr = unchangedSince == null ? "" : unchangedSince.toString(); final int len = ImapClientConstants.PAD_LEN + msgNumbers.length() + flagListString.length(); final ByteBuf sb = Unpooled.buffer(len); sb.writeBytes(isUid ? UID_STORE_SP_B : STORE_SP_B); sb.writeBytes(msgNumbers.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.SPACE); if (unchangedSince != null) { sb.writeByte(ImapClientConstants.L_PAREN); sb.writeBytes(UNCHANGEDSINCE_SP_B); sb.writeBytes(unchangedSinceStr.getBytes(StandardCharsets.US_ASCII)); sb.writeByte(ImapClientConstants.R_PAREN); sb.writeByte(ImapClientConstants.SPACE); } if (action == FlagsAction.ADD) { sb.writeByte(ImapClientConstants.PLUS); } else if (action == FlagsAction.REMOVE) { sb.writeByte(ImapClientConstants.MINUS); } sb.writeBytes(FLAGS_B); if (isSilent) { sb.writeBytes(SILENT_B); } sb.writeByte(ImapClientConstants.SPACE); sb.writeBytes(flagListString.getBytes(StandardCharsets.US_ASCII)); sb.writeBytes(CRLF_B); return sb; }
Source:
<code>public static Properties loadProperties(InputStream resource) { try ( <START> Reader is = new InputStreamReader(resource, "UTF-8"); <END> ) { Properties prop = new Properties(); prop.load(is); return prop; } catch (IOException ioe) { throw new RuntimeException(ioe); } }</code><technical_language>revert Charset.forName()</technical_language>

Target:
public static Properties loadProperties(InputStream resource) { try ( Reader is = new InputStreamReader(resource, Charset.forName("UTF-8")); ) { Properties prop = new Properties(); prop.load(is); return prop; } catch (IOException ioe) { throw new RuntimeException(ioe); } }
Source:
<code>public int hashCode() { <START> return (int) (getAddress() & 0xFFFFFFFF); <END> }</code><technical_language>is Long.hashCode(long value) method</technical_language>

Target:
public int hashCode() { return Long.hashCode(this.getAddress()); }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, Intent data) { if (intentListeners.indexOfKey(requestCode) >= 0) { IntentListener asker = intentListeners.get(requestCode); asker.onIntentResult(resultCode, data); intentListeners.remove(requestCode); } else if (requestCode == REQUEST_EXPORT_EMBROIDERY_FILE) { if (resultCode == RESULT_OK) { <START> Log.d(TAG, "Exported embroidery file"); <END> } } else { stageResourceHolder.onActivityResult(requestCode, resultCode, data); } }</code><technical_language>please remove this</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (intentListeners.indexOfKey(requestCode) >= 0) { IntentListener asker = intentListeners.get(requestCode); asker.onIntentResult(resultCode, data); intentListeners.remove(requestCode); } else { stageResourceHolder.onActivityResult(requestCode, resultCode, data); } }
Source:
<code>public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && isDeterministic(expression) && !mayReturnNullOnNonNullInput(expression) && <START> !isDynamicFilter(expression)) { <END> ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getType() == ComparisonExpressionType.EQUAL) { return !comparison.getLeft().equals(comparison.getRight()); } } return false; }; }</code><technical_language>do need here</technical_language>

Target:
public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && isDeterministic(expression) && !mayReturnNullOnNonNullInput(expression)) { ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getType() == ComparisonExpressionType.EQUAL) { return !comparison.getLeft().equals(comparison.getRight()); } } return false; }; }
Source:
<code>public static byte[] encodeOSCoreRequest(OSCoreCtx ctx) { int firstByte = 0x00; ByteArrayOutputStream bRes = new ByteArrayOutputStream(); byte[] partialIV = OSSerializer.processPartialIV(ctx.getSenderSeq()); firstByte = firstByte | (partialIV.length & 0x07); firstByte = firstByte | 0x08; <START> if(ctx.getIncludeContextId() == true) { <END> firstByte = firstByte | 0x10; } bRes.write(firstByte); try { bRes.write(partialIV); if(ctx.getIncludeContextId() == true) { bRes.write(ctx.getIdContext().length); bRes.write(ctx.getIdContext()); } bRes.write(ctx.getSenderId()); } catch (IOException e) { e.printStackTrace(); } return bRes.toByteArray(); }</code><technical_language>Please insert a space (' ') "if" "("</technical_language>

Target:
public static byte[] encodeOSCoreRequest(OSCoreCtx ctx) { int firstByte = 0x00; ByteArrayOutputStream bRes = new ByteArrayOutputStream(); byte[] partialIV = OSSerializer.processPartialIV(ctx.getSenderSeq()); firstByte = firstByte | (partialIV.length & 0x07); firstByte = firstByte | 0x08; if (ctx.getIncludeContextId()) { firstByte = firstByte | 0x10; } bRes.write(firstByte); try { bRes.write(partialIV); if (ctx.getIncludeContextId()) { bRes.write(ctx.getIdContext().length); bRes.write(ctx.getIdContext()); } bRes.write(ctx.getSenderId()); } catch (IOException e) { e.printStackTrace(); } return bRes.toByteArray(); }
Source:
<code>public boolean performFinish() { try { IProject project = selectContextPage.getProject(); final ContextType type = selectContextPage.getContextType(); String name = selectContextPage.getContextName(); IPath containerPath = selectContextPage.getPathInProject(); IQ7Folder folder = RcpttCore.create(project).getFolder(containerPath); context = folder.createContext(name, ContextTypeManager .getInstance() .getTypeById("org.eclipse.rcptt.ctx.super"), true, new NullProgressMonitor()); IQ7NamedElement copy = context .getWorkingCopy(new NullProgressMonitor()); try { SuperContext superCtx = (SuperContext) copy.getNamedElement(); superCtx.setChildType(type.getId()); <START> Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); <END> WriteAccessChecker writeAccessChecker = new WriteAccessChecker(shell); if (!writeAccessChecker.makeResourceWritable(copy)) { return false; } copy.commitWorkingCopy(true, new NullProgressMonitor()); } finally { copy.discardWorkingCopy(); } IDE.openEditor( workbench.getActiveWorkbenchWindow().getActivePage(), (IFile) context.getResource()); } catch (Exception e) { Q7UIPlugin.log(e); return false; } return true; }</code><technical_language>Wizard dialog shell, default one</technical_language>

Target:
public boolean performFinish() { try { IProject project = selectContextPage.getProject(); final ContextType type = selectContextPage.getContextType(); String name = selectContextPage.getContextName(); IPath containerPath = selectContextPage.getPathInProject(); IQ7Folder folder = RcpttCore.create(project).getFolder(containerPath); context = folder.createContext(name, ContextTypeManager .getInstance() .getTypeById("org.eclipse.rcptt.ctx.super"), true, new NullProgressMonitor()); IQ7NamedElement copy = context .getWorkingCopy(new NullProgressMonitor()); try { SuperContext superCtx = (SuperContext) copy.getNamedElement(); superCtx.setChildType(type.getId()); WriteAccessChecker writeAccessChecker = new WriteAccessChecker(getShell()); if (!writeAccessChecker.makeResourceWritable(copy)) { return false; } copy.commitWorkingCopy(true, new NullProgressMonitor()); } finally { copy.discardWorkingCopy(); } IDE.openEditor( workbench.getActiveWorkbenchWindow().getActivePage(), (IFile) context.getResource()); } catch (Exception e) { Q7UIPlugin.log(e); return false; } return true; }
Source:
<code>public HttpConnectionFilterContext filterRequest(HttpConnectionFilterContext context) { HttpURLConnection connection = context.connection.getConnection(); if(cookie == null){ cookie = getCookie(connection.getURL()); } connection.setRequestProperty("Cookie",cookie); <START> <END> return context; }</code><technical_language>Excessive newlines</technical_language>

Target:
public HttpConnectionFilterContext filterRequest(HttpConnectionFilterContext context) { HttpURLConnection connection = context.connection.getConnection(); if(shouldAttemptCookieRequest) { if (cookie == null) { cookie = getCookie(connection.getURL()); } connection.setRequestProperty("Cookie", cookie); } return context; }
Source:
<code>private boolean hasPropsBefore( int[] propertyIds, SchemaDescriptor.PropertySchemaType propertySchemaType ) { boolean found = false; for ( int propertyId : propertyIds ) { PropertyValue propertyValue = knownProperties.get( propertyId ); <START> if ( propertyValue == null || !propertyValue.hasBefore() ) <END> { if ( propertySchemaType == COMPLETE_ALL_TOKENS ) { return false; } } else { found = true; } } return found; }</code><technical_language>I suggest simplifying this a bit knownProperties.getIfAbsent( probertyId, noValue )</technical_language>

Target:
private boolean hasPropsBefore( int[] propertyIds, SchemaDescriptor.PropertySchemaType propertySchemaType ) { boolean found = false; for ( int propertyId : propertyIds ) { PropertyValue propertyValue = knownProperties.getIfAbsent( propertyId, () -> noValue ); if ( !propertyValue.hasBefore() ) { if ( propertySchemaType == COMPLETE_ALL_TOKENS ) { return false; } } else { found = true; } } return found; }
Source:
<code>public void onSubmit(final String code) { <START> dispatcher.execute(voteService.useCode(code), new RestCallbackImpl<Void>() { <END> @Override public void onError(Response response) { super.onError(response); PlaceRequest placeRequest = new PlaceRequest.Builder() .nameToken(NameTokens.ALREADY_VOTED) .build(); placeManager.revealPlace(placeRequest); } @Override public void onSuccess(Void result) { Cookies.setCookie(CookieNames.VOTE_CODE, code); PlaceRequest placeRequest = new PlaceRequest.Builder() .nameToken(NameTokens.VOTE) .build(); placeManager.revealPlace(placeRequest); } }); }</code><technical_language>resource delegates instead, right</technical_language>

Target:
public void onSubmit(final String code) { dispatcher.execute(voteService.useCode(code), new RestCallbackImpl<Void>() { @Override public void onError(Response response) { super.onError(response); if (response.getStatusCode() == SC_FORBIDDEN) { revealPlace(NameTokens.ALREADY_VOTED); } else { getView().showInvalidCodeError(); } } @Override public void onSuccess(Void result) { Cookies.setCookie(CookieNames.VOTE_CODE, code); revealPlace(NameTokens.VOTE); } }); }
Source:
<code>public static TrackingLookupSourceSupplier createPartitionedLookupSourceSupplier(List<Supplier<LookupSource>> partitions, List<Type> hashChannelTypes, boolean outer) { if (outer) { OuterPositionTracker.Factory outerPositionTrackerFactory = new OuterPositionTracker.Factory(partitions); return new TrackingLookupSourceSupplier() { @Override public LookupSource getLookupSource() { return new PartitionedLookupSource( getPartitionsLookupSources(partitions), hashChannelTypes, Optional.of(outerPositionTrackerFactory.create())); } @Override public OuterPositionIterator getOuterPositionIterator() { return outerPositionTrackerFactory.getOuterPositionIterator(); } }; } else { <START> return TrackingLookupSourceSupplier.from( <END> () -> new PartitionedLookupSource( getPartitionsLookupSources(partitions), hashChannelTypes, Optional.empty())); } }</code><technical_language>rename nonTrackingSupplier static import</technical_language>

Target:
public static Supplier<LookupSource> createPartitionedLookupSourceSupplier(List<Supplier<LookupSource>> partitions, List<Type> hashChannelTypes, boolean outer) { Optional<OuterPositionTracker.Factory> outerPositionTrackerFactory = outer ? Optional.of(new OuterPositionTracker.Factory( partitions.stream() .map(partition -> partition.get().getJoinPositionCount()) .collect(toImmutableList()))) : Optional.empty(); return () -> new PartitionedLookupSource( partitions.stream() .map(Supplier::get) .collect(toImmutableList()), hashChannelTypes, outerPositionTrackerFactory.map(OuterPositionTracker.Factory::create)); }
Source:
<code>public int getNext() { if (this == this.previous) { return this.id; } else if (this.previous == null) { System.out.printf("%s(unreached)", this.id); <START> return (Integer)null; <END> } else { Integer tmp = this.previous.getNext(); if (null != tmp) { pathNodeIds.add(tmp); } return this.id; } }</code><technical_language>Interesting... return null here</technical_language>

Target:
public Integer getNext() { if (this == this.previous) { return this.id; } else if (this.previous == null) { System.out.printf("%s(unreached)", this.id); return null; } else { Integer tmp = this.previous.getNext(); if (null != tmp) { pathNodeIds.add(tmp); } return this.id; } }
Source:
<code><START> public void unregisterDeserializer(LRAParticipantDeserializer deserializer) { <END> }</code><technical_language>great</technical_language>

Target:
public void unregisterDeserializer(LRAParticipantDeserializer deserializer) { deserializers.remove(deserializer); }
Source:
<code>public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { mUser = User.getUser(getArguments()); } else { mUser = User.getUser(savedInstanceState); } mHandler = ViewModelProviders.of(this).get(EmailProviderResponseHandler.class); mHandler.init(getFlowParams()); mHandler.getOperation().observe(this, new ResourceObserver<IdpResponse>( this, R.string.fui_progress_dialog_signing_up) { @Override protected void onSuccess(@NonNull IdpResponse response) { startSaveCredentials( mHandler.getCurrentUser(), response, mPasswordEditText.getText().toString()); } @Override protected void onFailure(@NonNull Exception e) { if (e instanceof FirebaseAuthWeakPasswordException) { mPasswordInput.setError(getResources().getQuantityString( R.plurals.fui_error_weak_password, R.integer.fui_min_password_length)); } else if (e instanceof FirebaseAuthInvalidCredentialsException) { mEmailInput.setError(getString(R.string.fui_invalid_email_address)); } else if (e instanceof FirebaseAuthAnonymousUpgradeException) { IdpResponse response = ((FirebaseAuthAnonymousUpgradeException) e).getResponse(); <START> ((AnonymousUpgradeListener) getActivity()).onMergeFailure(response); <END> } else { mEmailInput.setError(getString(R.string.fui_email_account_creation_error)); } } }); }</code><technical_language>This is fine, optionally assert cast in onActivityCreated store a listener reference casting here</technical_language>

Target:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { mUser = User.getUser(getArguments()); } else { mUser = User.getUser(savedInstanceState); } mHandler = ViewModelProviders.of(this).get(EmailProviderResponseHandler.class); mHandler.init(getFlowParams()); mHandler.getOperation().observe(this, new ResourceObserver<IdpResponse>( this, R.string.fui_progress_dialog_signing_up) { @Override protected void onSuccess(@NonNull IdpResponse response) { startSaveCredentials( mHandler.getCurrentUser(), response, mPasswordEditText.getText().toString()); } @Override protected void onFailure(@NonNull Exception e) { if (e instanceof FirebaseAuthWeakPasswordException) { mPasswordInput.setError(getResources().getQuantityString( R.plurals.fui_error_weak_password, R.integer.fui_min_password_length)); } else if (e instanceof FirebaseAuthInvalidCredentialsException) { mEmailInput.setError(getString(R.string.fui_invalid_email_address)); } else if (e instanceof FirebaseAuthAnonymousUpgradeException) { IdpResponse response = ((FirebaseAuthAnonymousUpgradeException) e).getResponse(); mListener.onMergeFailure(response); } else { mEmailInput.setError(getString(R.string.fui_email_account_creation_error)); } } }); }
Source:
<code>public void handlesTwoRequestInOneConnection() throws Exception { final String text = "Hello world!"; final Socket socket = Mockito.mock(Socket.class); Mockito.when(socket.getInputStream()).thenReturn( new ByteArrayInputStream( Joiner.on("\r\n").join( "POST / HTTP/1.1", "Host: localhost", "Content-Length: 4", "", "hi", "POST / HTTP/1.1", "Host: localhost", "Content-Length: 4", "", "hi" ).getBytes() ) ); Mockito.when(socket.getLocalAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getLocalPort()).thenReturn(0); Mockito.when(socket.getInetAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getPort()).thenReturn(0); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); Mockito.when(socket.getOutputStream()).thenReturn(baos); new BkReuse(new BkBasic(new TkGreedy(new TkText(text)))).accept(socket); final Pattern pattern = Pattern.compile( text + ".*?" + text, Pattern.DOTALL ); <START> Assert.assertTrue( <END> String.format("Actual is %s", baos.toString()), pattern.matcher(baos.toString()).find() ); }</code><technical_language>@prondzyn Hamcrest matchers for consistency. RegexMatchers [jcabi-matchers](<LINK_0></technical_language>

Target:
public void handlesTwoRequestInOneConnection() throws Exception { final String text = "Hello world!"; final Socket socket = Mockito.mock(Socket.class); Mockito.when(socket.getInputStream()).thenReturn( new ByteArrayInputStream( Joiner.on("\r\n").join( "POST / HTTP/1.1", "Host: localhost", "Content-Length: 4", "", "hi", "POST / HTTP/1.1", "Host: localhost", "Content-Length: 4", "", "hi" ).getBytes("UTF-8") ) ); Mockito.when(socket.getLocalAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getLocalPort()).thenReturn(0); Mockito.when(socket.getInetAddress()).thenReturn( InetAddress.getLocalHost() ); Mockito.when(socket.getPort()).thenReturn(0); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); Mockito.when(socket.getOutputStream()).thenReturn(baos); new BkReuse(new BkBasic(new TkGreedy(new TkText(text)))).accept(socket); MatcherAssert.assertThat( baos.toString(), RegexMatchers.containsPattern(text + ".*?" + text) ); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) <START> return true; <END> if (obj == null) return false; if (getClass() != obj.getClass()) return false; IntervalBase other = (IntervalBase) obj; if (end == null) { if (other.end != null) return false; } else if (!end.equals(other.end)) return false; if (intervalType != other.intervalType) return false; if (sessionSeed == null) { if (other.sessionSeed != null) return false; } else if (!sessionSeed.equals(other.sessionSeed)) return false; if (start == null) { if (other.start != null) return false; } else if (!start.equals(other.start)) return false; return true; }</code><technical_language>for pedantry, { } :)</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } IntervalBase other = (IntervalBase) obj; if (end == null) { if (other.end != null) { return false; } } else if (!end.equals(other.end)) { return false; } if (intervalType != other.intervalType) { return false; } if (sessionSeed == null) { if (other.sessionSeed != null) { return false; } } else if (!sessionSeed.equals(other.sessionSeed)) { return false; } if (start == null) { if (other.start != null) { return false; } } else if (!start.equals(other.start)) { return false; } return true; }
Source:
<code>protected void onBindViewHolder(ViewHolder holder, CodeSearchResult result) { Repository repo = result.getRepository(); holder.tvTitle.setText(result.getName()); holder.tvRepo.setText(repo.getOwner().getLogin() + "/" + repo.getName()); List<TextMatch> matches = result.getTextMatches(); if (matches != null && !matches.isEmpty()) { LayoutInflater inflater = LayoutInflater.from(mContext); holder.matchesContainer.removeAllViews(); for (int i = 0; i < matches.size(); i++) { TextMatch match = matches.get(i); SpannableStringBuilder builder = new SpannableStringBuilder(); builder.append(match.getFragment()); List<TextMatch.MatchItem> items = match.getMatches(); if (items != null) { for (TextMatch.MatchItem item : items) { int start = item.getStartPos(); <START> int end = item.getEdndPos(); <END> if (start >= 0 && end > start) { builder.setSpan(new StyleSpan(Typeface.BOLD), start, end, 0); } } } View row = inflater.inflate(R.layout.row_search_match, holder.matchesContainer, false); TextView tvMatch = (TextView) row.findViewById(R.id.tv_match); tvMatch.setOnClickListener(this); tvMatch.setText(builder); tvMatch.setTag(result); tvMatch.setTag(R.id.search_match_index, i); holder.matchesContainer.addView(row); } holder.matchesContainer.setVisibility(View.VISIBLE); } else { holder.matchesContainer.setVisibility(View.GONE); } }</code><technical_language>I this, fix this :)</technical_language>

Target:
protected void onBindViewHolder(ViewHolder holder, CodeSearchResult result) { Repository repo = result.getRepository(); holder.tvTitle.setText(result.getName()); holder.tvRepo.setText(repo.getOwner().getLogin() + "/" + repo.getName()); List<TextMatch> matches = result.getTextMatches(); if (matches != null && !matches.isEmpty()) { LayoutInflater inflater = LayoutInflater.from(mContext); for (int i = 0; i < matches.size(); i++) { TextMatch match = matches.get(i); SpannableStringBuilder builder = new SpannableStringBuilder(match.getFragment()); List<TextMatch.MatchItem> items = match.getMatches(); if (items != null) { for (TextMatch.MatchItem item : items) { int start = item.getStartPos(); int end = item.getEndPos(); if (start >= 0 && end > start) { builder.setSpan(new StyleSpan(Typeface.BOLD), start, end, 0); } } } View row = holder.matchesContainer.getChildAt(i); if (row == null) { row = inflater.inflate(R.layout.row_search_match, holder.matchesContainer, false); holder.matchesContainer.addView(row); } TextView tvMatch = (TextView) row.findViewById(R.id.tv_match); tvMatch.setOnClickListener(this); tvMatch.setText(builder); tvMatch.setTag(result); tvMatch.setTag(R.id.search_match_index, i); row.setVisibility(View.VISIBLE); } for (int i = matches.size(); i < holder.matchesContainer.getChildCount(); i++) { holder.matchesContainer.getChildAt(i).setVisibility(View.GONE); } holder.matchesContainer.setVisibility(View.VISIBLE); } else { holder.matchesContainer.setVisibility(View.GONE); } }