auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void convertStoredDefinitionWorks() { StoredWorkflowDefinition convertedOriginal = dao.convert(original); assertThat(convertedOriginal.type, is(original.getType())); assertThat(convertedOriginal.onError, is(original.getErrorState().name())); assertThat(convertedOriginal.description, is(original.getDescription())); assertThat(convertedOriginal.states.size(), is(original.getStates().size())); for (StoredWorkflowDefinition.State convertedState : convertedOriginal.states) { boolean foundMatchingState = false; for (DummyTestState originalState : original.getStates()) { if (originalState.name().equals(convertedState.id)) { assertThat(convertedState.description, is(originalState.getDescription())); WorkflowState originalFailureTransition = original.getFailureTransitions().get(originalState.name()); assertThat(convertedState.onFailure, is(originalFailureTransition != null ? originalFailureTransition.name() : null)); List<String> originalStateTransitions = original.getAllowedTransitions().get(originalState.name()); if (originalStateTransitions != null) { assertThat(convertedState.transitions, containsElementsInAnyOrder(originalStateTransitions)); } else { assertThat(convertedState.transitions.size(), is(0)); } foundMatchingState = true; <START> } <END> } assertThat("Not found match for state " + convertedState.id, foundMatchingState, is(true)); } }</code><technical_language>break;</technical_language>

Target:
public void convertStoredDefinitionWorks() { StoredWorkflowDefinition convertedOriginal = dao.convert(original); assertThat(convertedOriginal.type, is(original.getType())); assertThat(convertedOriginal.onError, is(original.getErrorState().name())); assertThat(convertedOriginal.description, is(original.getDescription())); assertThat(convertedOriginal.states.size(), is(original.getStates().size())); for (StoredWorkflowDefinition.State convertedState : convertedOriginal.states) { boolean foundMatchingState = false; for (DummyTestState originalState : original.getStates()) { if (originalState.name().equals(convertedState.id)) { assertThat(convertedState.description, is(originalState.getDescription())); WorkflowState originalFailureTransition = original.getFailureTransitions().get(originalState.name()); assertThat(convertedState.onFailure, is(originalFailureTransition != null ? originalFailureTransition.name() : null)); List<String> originalStateTransitions = original.getAllowedTransitions().get(originalState.name()); if (originalStateTransitions != null) { assertThat(convertedState.transitions, containsElementsInAnyOrder(originalStateTransitions)); } else { assertThat(convertedState.transitions.size(), is(0)); } foundMatchingState = true; break; } } assertThat("Not found match for state " + convertedState.id, foundMatchingState, is(true)); } }
Source:
<code>public EventHubProducer createProducer(EventHubProducerOptions options) { final EventHubAsyncProducer producer = client.createProducer(); <START> return new EventHubProducer(producer, options.retry().tryTimeout()); <END> }</code><technical_language>Check for null options</technical_language>

Target:
public EventHubProducer createProducer(EventHubProducerOptions options) { Objects.requireNonNull(options); final EventHubAsyncProducer producer = client.createProducer(options); final Duration tryTimeout = options.retry() != null && options.retry().tryTimeout() != null ? options.retry().tryTimeout() : defaultProducerOptions.retry().tryTimeout(); return new EventHubProducer(producer, tryTimeout); }
Source:
<code>public boolean rename(ByteArrayWrapper oldKey, ByteArrayWrapper newKey) { <START> while (true) { <END> if (!region.containsKey(oldKey)) { return false; } List<ByteArrayWrapper> keysToOperateOn = new ArrayList<>(); keysToOperateOn.add(oldKey); keysToOperateOn.add(newKey); return invoke(RenameFunction.ID, oldKey, oldKey, newKey, keysToOperateOn, new ArrayList<>(), new ArrayList<>()); } }</code><technical_language>I "while (true)" loop removed. I is a remnant of tryLock code. is I loop</technical_language>

Target:
public boolean rename(ByteArrayWrapper oldKey, ByteArrayWrapper newKey) { if (!region.containsKey(oldKey)) { return false; } List<ByteArrayWrapper> keysToOperateOn = new ArrayList<>(); keysToOperateOn.add(oldKey); keysToOperateOn.add(newKey); return invoke(RenameFunction.ID, oldKey, oldKey, newKey, keysToOperateOn, new ArrayList<>(), new ArrayList<>()); }
Source:
<code>public void write(Object datum) throws IOException { dataCount++; if (null == datum) { return; } if (null == factory) { factory = (IndexedRecordConverter<Object, ? extends IndexedRecord>) SalesforceAvroRegistry.get() .createIndexedRecordConverter(datum.getClass()); } IndexedRecord input = factory.convertToAvro(datum); OutputAction outputAction = sprops.outputAction.getValue(); <START> LOGGER.info("Prepare to record {}.", outputAction.name().toLowerCase(), dataCount); <END> switch (outputAction) { case INSERT: insert(input); break; case UPDATE: update(input); break; case UPSERT: upsert(input); break; case DELETE: delete(input); } }</code><technical_language>I suppose I18N is needed</technical_language>

Target:
public void write(Object datum) throws IOException { dataCount++; if (null == datum) { return; } if (null == factory) { factory = (IndexedRecordConverter<Object, ? extends IndexedRecord>) SalesforceAvroRegistry.get() .createIndexedRecordConverter(datum.getClass()); } IndexedRecord input = factory.convertToAvro(datum); Property<OutputAction> outputAction = sprops.outputAction; LOGGER.info(MESSAGES.getMessage("info.startMessage", sprops.outputAction.getPossibleValuesDisplayName(outputAction.getValue()).toLowerCase(), dataCount)); switch (outputAction.getValue()) { case INSERT: insert(input); break; case UPDATE: update(input); break; case UPSERT: upsert(input); break; case DELETE: delete(input); } }
Source:
<code>private boolean checkDeviceSDK() { return android.os.Build.VERSION.SDK_INT <START> >= MINIMUM_SDK_VERSION_OF_TESTING_DEVICE; <END> }</code><technical_language>do enforcing *exact* SDK version requirement, instead of "minimum"? guessing future SDK versions slightly font rendering other subtle differences break precise screenshot tests</technical_language>

Target:
private boolean checkDeviceSDK() { return android.os.Build.VERSION.SDK_INT == SDK_VERSION_OF_TESTING_DEVICE; }
Source:
<code>private String getIPv4inSubnet(String subnet) { try { final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { final NetworkInterface current = interfaces.nextElement(); if (!current.isUp() || current.isLoopback() || current.isVirtual()) { continue; } for (InterfaceAddress ifAddr : current.getInterfaceAddresses()) { InetAddress addr = ifAddr.getAddress(); if (addr.isLoopbackAddress() || (addr instanceof Inet6Address)) { continue; } String ipv4Address = addr.getHostAddress(); String subNetString = getIpv4NetAddress(ipv4Address, ifAddr.getNetworkPrefixLength()) + "/" + String.valueOf(ifAddr.getNetworkPrefixLength()); if (subNetString.equals(subnet)) { return ipv4Address; } } } } catch (SocketException ex) { LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex); <START> return null; <END> } return null; }</code><technical_language>this line is superfluous</technical_language>

Target:
private String getIPv4inSubnet(String subnet) { try { final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { final NetworkInterface current = interfaces.nextElement(); if (!current.isUp() || current.isLoopback() || current.isVirtual()) { continue; } for (InterfaceAddress ifAddr : current.getInterfaceAddresses()) { InetAddress addr = ifAddr.getAddress(); if (addr.isLoopbackAddress() || (addr instanceof Inet6Address)) { continue; } String ipv4Address = addr.getHostAddress(); String subNetString = getIpv4NetAddress(ipv4Address, ifAddr.getNetworkPrefixLength()) + "/" + String.valueOf(ifAddr.getNetworkPrefixLength()); if (subNetString.equals(subnet)) { return ipv4Address; } } } } catch (SocketException ex) { LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex); } return null; }
Source:
<code>KeyEncryptionKeyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { super(keyId, pipeline, version); <START> this.keyId = keyId; <END> }</code><technical_language>passing this superclass constructor, a superclass manage lifecycle of this variable? CryptographyAsyncClient a protected method getKeyId() get this key id</technical_language>

Target:
KeyEncryptionKeyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { super(keyId, pipeline, version); }
Source:
<code>private List<DiscoverySelector> getSelectorsFromTestCasesHeader(BundleDescriptor bd) { Bundle bundle = bd.getBundle(); Bundle host = BundleUtils.getHost(bundle) .get(); return BundleUtils.testCases(bundle) .map(testcase -> { int index = testcase.indexOf('#'); String className = (index < 0) ? testcase : testcase.substring(0, index); try { Class<?> testClass = host.loadClass(className); testClass.getDeclaredMethods(); testClass.getDeclaredFields(); if (!resolvedClasses.contains(testClass)) { checkForMixedJUnit34(bd, testClass); if (index < 0) { resolvedClasses.add(testClass); return selectClass(testClass); } return selectMethod(testClass, DiscoverySelectors.selectMethod(testcase)); } <START> } catch (ClassNotFoundException | NoClassDefFoundError cnfe) { <END> info(() -> "error: " + cnfe); StaticFailureDescriptor unresolvedClassDescriptor = new StaticFailureDescriptor(bd.getUniqueId() .append("test", testcase), testcase, cnfe); bd.addChild(unresolvedClassDescriptor); } return null; }) .filter(Objects::nonNull) .collect(toList()); }</code><technical_language>Putting NoClassDefFoundError hide stupidity in other parts of this code :-( narrow window for catching NoClassDefFoundError calls testClass.getDeclaredMethods() testClass.getDeclaredFields() I is source for need worry it</technical_language>

Target:
private List<DiscoverySelector> getSelectorsFromTestCasesHeader(BundleDescriptor bd) { Bundle bundle = bd.getBundle(); Bundle host = BundleUtils.getHost(bundle) .get(); return BundleUtils.testCases(bundle) .map(testcase -> { int index = testcase.indexOf('#'); String className = (index < 0) ? testcase : testcase.substring(0, index); Class<?> testClass = tryToResolveTestClass(host, className, bd); if (testClass != null && !resolvedClasses.contains(testClass)) { checkForMixedJUnit34(bd, testClass); if (index < 0) { resolvedClasses.add(testClass); return selectClass(testClass); } return selectMethod(testClass, DiscoverySelectors.selectMethod(testcase)); } return null; }) .filter(Objects::nonNull) .collect(toList()); }
Source:
<code>private String getCompressLobsStatements(final DbEntity entity) { if (!this.properties.shouldCompressLobs()) { return ""; } <START> final String defaultLob = " LOB (\"%s\") STORE AS SECUREFILE (COMPRESS HIGH CACHE LOGGING)"; <END> return entity.getColumns() .stream() .filter(dbColumn -> dbColumn.getDbColumnType().equals(DbColumnType.CLOB) || dbColumn.getDbColumnType().equals(DbColumnType.BLOB)) .map(dbColumn -> String.format(defaultLob, dbColumn.getName())) .collect(joining()); }</code><technical_language>talked before, if this left HIGH default MEDIUM... quick test showed appears difference in terms of size is small, I guess difference in CPU utilization negligible</technical_language>

Target:
private String getCompressLobsStatements(final DbEntity entity) { if (!this.properties.shouldCompressLobs()) { return ""; } final String defaultLob = " LOB (\"%s\") STORE AS SECUREFILE (COMPRESS MEDIUM CACHE LOGGING)"; return entity.getColumns() .stream() .filter(dbColumn -> dbColumn.getDbColumnType().equals(DbColumnType.CLOB) || dbColumn.getDbColumnType().equals(DbColumnType.BLOB)) .map(dbColumn -> String.format(defaultLob, dbColumn.getName())) .collect(joining()); }
Source:
<code>public void testIntCollectSet() { Schema schema = Schema.recordOf("test", Schema.Field.of("x", Schema.of(Schema.Type.INT))); CollectSet collectSet = new CollectSet("x", Schema.of(Schema.Type.INT)); collectSet.beginFunction(); collectSet.operateOn(StructuredRecord.builder(schema).set("x", 1).build()); collectSet.operateOn(StructuredRecord.builder(schema).set("x", 2).build()); collectSet.operateOn(StructuredRecord.builder(schema).set("x", 1).build()); Set set = collectSet.getAggregate(); <START> Assert.assertArrayEquals(new Integer[] {1, 2}, set.toArray()); <END> }</code><technical_language>comparing Sets instead of array comparison, order is guaranteed</technical_language>

Target:
public void testIntCollectSet() { Schema schema = Schema.recordOf("test", Schema.Field.of("x", Schema.of(Schema.Type.INT))); CollectSet collectSet = new CollectSet("x", Schema.of(Schema.Type.INT)); collectSet.beginFunction(); collectSet.operateOn(StructuredRecord.builder(schema).set("x", 1).build()); collectSet.operateOn(StructuredRecord.builder(schema).set("x", 2).build()); collectSet.operateOn(StructuredRecord.builder(schema).set("x", 1).build()); Set set = collectSet.getAggregate(); Set<Integer> expectedSet = ImmutableSet.of(1, 2); Assert.assertEquals(expectedSet, set); }
Source:
<code>public SchemaVersionsResponse versions(Topic topic, boolean online) { try { if (online) { List<SchemaVersion> v = rawSchemaClient.getVersions(topic.getName()); versionsCache.put(topic, v); <START> return SchemaVersionsResponse.succeeded(v); <END> } else { List<SchemaVersion> versions = versionsCache.get(topic); return SchemaVersionsResponse.succeeded(versions); } } catch (Exception e) { logger.error("Error while loading schema versions for topic {}", topic.getQualifiedName(), e); return SchemaVersionsResponse.failed(); } }</code><technical_language>v -> versions? in else branch is fully named</technical_language>

Target:
public SchemaVersionsResult versions(Topic topic, boolean online) { try { if (online) { List<SchemaVersion> versions = rawSchemaClient.getVersions(topic.getName()); versionsCache.put(topic, versions); return SchemaVersionsResult.succeeded(versions); } else { List<SchemaVersion> versions = versionsCache.get(topic); return SchemaVersionsResult.succeeded(versions); } } catch (Exception e) { logger.error("Error while loading schema versions for topic {}", topic.getQualifiedName(), e); return SchemaVersionsResult.failed(); } }
Source:
<code>private static void generateEntityStatistics() { for (EntityType entityType : EntityType.values()) { Class<? extends Entity> entityClass = entityType.getEntityClass(); if (entityClass == null) { continue; } if (Monster.class.isAssignableFrom(entityClass)) { set(ENTITY_KILLED_BY, entityType, "entityKilledBy." <START> + UPPER_UNDERSCORE.to(UPPER_CAMEL, entityType.name())); <END> } if (Creature.class.isAssignableFrom(entityClass)) { set(KILL_ENTITY, entityType, "killEntity." + UPPER_UNDERSCORE.to(UPPER_CAMEL, entityType.name())); } } }</code><technical_language>EntityType#getName()</technical_language>

Target:
private static void generateEntityStatistics() { for (EntityType entityType : EntityType.values()) { Class<? extends Entity> entityClass = entityType.getEntityClass(); if (entityClass == null) { continue; } if (Monster.class.isAssignableFrom(entityClass)) { set(ENTITY_KILLED_BY, entityType, "entityKilledBy." + entityClass.getSimpleName()); } if (Creature.class.isAssignableFrom(entityClass)) { set(KILL_ENTITY, entityType, "killEntity." + entityClass.getSimpleName()); } } }
Source:
<code>private void appendData(DecodedBlockNode[] decodedBlocks, int fixedWidthRowSize, List<Integer> variableWidthChannels, OutputBuffer outputBuffer) { if (decodedBlocks.length != channelCount) { throw new IllegalArgumentException(format("Unexpected number of decoded blocks %d. It should be %d.", decodedBlocks.length, channelCount)); } if (positionCount == 0) { return; } if (channelCount == 0) { bufferedRowCount += positionCount; return; } initializeBlockEncodingBuffers(decodedBlocks); for (int i = 0; i < channelCount; i++) { blockEncodingBuffers[i].setupDecodedBlocksAndPositions(decodedBlocks[i], positions, positionCount); } int[] serializedRowSizes = ensureCapacity(null, positionCount, SMALL, INITIALIZE, bufferAllocator); try { populateSerializedRowSizes(fixedWidthRowSize, variableWidthChannels, serializedRowSizes); int offset = 0; do { int batchSize = calculateNextBatchSize(fixedWidthRowSize, variableWidthChannels, offset, serializedRowSizes); <START> boolean lastBatchInPage = offset + batchSize >= positionCount; <END> for (int i = 0; i < channelCount; i++) { blockEncodingBuffers[i].setNextBatch(offset, batchSize); blockEncodingBuffers[i].appendDataInBatch(); } bufferedRowCount += batchSize; offset += batchSize; if (bufferFull) { flush(outputBuffer); bufferFull = false; } } while (offset < positionCount); } finally { bufferAllocator.returnArray(serializedRowSizes); for (int i = 0; i < channelCount; i++) { blockEncodingBuffers[i].noMoreBatches(); } } }</code><technical_language>this variable is used; remove</technical_language>

Target:
private void appendData(DecodedBlockNode[] decodedBlocks, int fixedWidthRowSize, List<Integer> variableWidthChannels, OutputBuffer outputBuffer) { if (decodedBlocks.length != channelCount) { throw new IllegalArgumentException(format("Unexpected number of decoded blocks %d. It should be %d.", decodedBlocks.length, channelCount)); } if (positionCount == 0) { return; } if (channelCount == 0) { bufferedRowCount += positionCount; return; } initializeBlockEncodingBuffers(decodedBlocks); for (int i = 0; i < channelCount; i++) { blockEncodingBuffers[i].setupDecodedBlocksAndPositions(decodedBlocks[i], positions, positionCount); } int[] serializedRowSizes = ensureCapacity(null, positionCount, SMALL, INITIALIZE, bufferAllocator); try { populateSerializedRowSizes(fixedWidthRowSize, variableWidthChannels, serializedRowSizes); int offset = 0; do { int batchSize = calculateNextBatchSize(fixedWidthRowSize, variableWidthChannels, offset, serializedRowSizes); for (int i = 0; i < channelCount; i++) { blockEncodingBuffers[i].setNextBatch(offset, batchSize); blockEncodingBuffers[i].appendDataInBatch(); } bufferedRowCount += batchSize; offset += batchSize; if (bufferFull) { flush(outputBuffer); bufferFull = false; } } while (offset < positionCount); } finally { bufferAllocator.returnArray(serializedRowSizes); for (int i = 0; i < channelCount; i++) { blockEncodingBuffers[i].noMoreBatches(); } } }
Source:
<code>public void addToOrderBook(Order order) { if (order instanceof BuyOrder) { if (buyOrders.containsKey(order.getStockSymbol())) { buyOrders.get(order.getStockSymbol()).add(order); } <START> else { <END> ArrayList<Order> list = new ArrayList<Order>(); list.add(order); buyOrders.put(order.getStockSymbol(), list); } } else { if (sellOrders.containsKey(order.getStockSymbol())) { sellOrders.get(order.getStockSymbol()).add(order); } else { ArrayList<Order> list = new ArrayList<Order>(); list.add(order); sellOrders.put(order.getStockSymbol(), list); } } }</code><technical_language>change variable name more descriptive</technical_language>

Target:
public void addToOrderBook(Order order) { if (order instanceof BuyOrder) { if (buyOrders.containsKey(order.getStockSymbol())) { buyOrders.get(order.getStockSymbol()).add(order); } else { ArrayList<Order> buyOrderList = new ArrayList<Order>(); buyOrderList.add(order); buyOrders.put(order.getStockSymbol(), buyOrderList); } } else { if (sellOrders.containsKey(order.getStockSymbol())) { sellOrders.get(order.getStockSymbol()).add(order); } else { ArrayList<Order> sellOrderlist = new ArrayList<Order>(); sellOrderlist.add(order); sellOrders.put(order.getStockSymbol(), sellOrderlist); } } }
Source:
<code>ReturnValueExecutableValidationContext( ConstraintValidatorManager constraintValidatorManager, ConstraintValidatorFactory constraintValidatorFactory, ValidatorScopedContext validatorScopedContext, TraversableResolver traversableResolver, HibernateConstraintValidatorInitializationContext constraintValidatorInitializationContext, T rootBean, Class<T> rootBeanClass, BeanMetaData<T> rootBeanMetaData, Executable executable, Optional<ExecutableMetaData> executableMetaData, Object executableReturnValue ) { super( constraintValidatorManager, constraintValidatorFactory, validatorScopedContext, traversableResolver, constraintValidatorInitializationContext, rootBean, rootBeanClass, rootBeanMetaData, buildDisableAlreadyValidatedBeanTracking( executableMetaData ) ); this.executable = executable; this.executableReturnValue = executableReturnValue; <START> this.executableMetaData = executableMetaData; <END> }</code><technical_language>minor try consistent order of method parameters</technical_language>

Target:
ReturnValueExecutableValidationContext( ConstraintValidatorManager constraintValidatorManager, ConstraintValidatorFactory constraintValidatorFactory, ValidatorScopedContext validatorScopedContext, TraversableResolver traversableResolver, HibernateConstraintValidatorInitializationContext constraintValidatorInitializationContext, T rootBean, Class<T> rootBeanClass, BeanMetaData<T> rootBeanMetaData, Executable executable, Optional<ExecutableMetaData> executableMetaData, Object executableReturnValue ) { super( constraintValidatorManager, constraintValidatorFactory, validatorScopedContext, traversableResolver, constraintValidatorInitializationContext, rootBean, rootBeanClass, rootBeanMetaData, buildDisableAlreadyValidatedBeanTracking( executableMetaData ) ); this.executable = executable; this.executableMetaData = executableMetaData; this.executableReturnValue = executableReturnValue; }
Source:
<code>public ReplicationWorker(final ZooKeeper zkc, final ServerConfiguration conf, StatsLogger statsLogger) throws CompatibilityException, KeeperException, InterruptedException, IOException { this.zkc = zkc; this.conf = conf; LedgerManagerFactory mFactory = LedgerManagerFactory <START> .newLedgerManagerFactory( <END> this.conf, new ZkLayoutManager(zkc, conf.getZkLedgersRootPath(), ZkUtils.getACLs(conf))); this.underreplicationManager = mFactory .newLedgerUnderreplicationManager(); try { this.bkc = BookKeeper.forConfig(new ClientConfiguration(conf)) .statsLogger(statsLogger.scope(BK_CLIENT_SCOPE)) .build(); } catch (BKException e) { throw new IOException("Failed to instantiate replication worker", e); } this.admin = new BookKeeperAdmin(bkc, statsLogger); this.ledgerChecker = new LedgerChecker(bkc); this.workerThread = new BookieThread(this, "ReplicationWorker"); this.openLedgerRereplicationGracePeriod = conf .getOpenLedgerRereplicationGracePeriod(); this.rwRereplicateBackoffMs = conf.getRwRereplicateBackoffMs(); this.pendingReplicationTimer = new Timer("PendingReplicationTimer"); this.statsLogger = statsLogger; this.rereplicateOpStats = this.statsLogger.getOpStatsLogger(REREPLICATE_OP); this.numLedgersReplicated = this.statsLogger.getCounter(NUM_FULL_OR_PARTIAL_LEDGERS_REPLICATED); this.exceptionCounters = new HashMap<String, Counter>(); }</code><technical_language>I suggest layout manager registration client, construct zk layout manager directly</technical_language>

Target:
public ReplicationWorker(final ZooKeeper zkc, final ServerConfiguration conf, StatsLogger statsLogger) throws CompatibilityException, KeeperException, InterruptedException, IOException { this.zkc = zkc; this.conf = conf; try { this.bkc = BookKeeper.forConfig(new ClientConfiguration(conf)) .statsLogger(statsLogger.scope(BK_CLIENT_SCOPE)) .build(); } catch (BKException e) { throw new IOException("Failed to instantiate replication worker", e); } LedgerManagerFactory mFactory = LedgerManagerFactory .newLedgerManagerFactory( this.conf, bkc.getRegClient().getLayoutManager()); this.underreplicationManager = mFactory .newLedgerUnderreplicationManager(); this.admin = new BookKeeperAdmin(bkc, statsLogger); this.ledgerChecker = new LedgerChecker(bkc); this.workerThread = new BookieThread(this, "ReplicationWorker"); this.openLedgerRereplicationGracePeriod = conf .getOpenLedgerRereplicationGracePeriod(); this.rwRereplicateBackoffMs = conf.getRwRereplicateBackoffMs(); this.pendingReplicationTimer = new Timer("PendingReplicationTimer"); this.statsLogger = statsLogger; this.rereplicateOpStats = this.statsLogger.getOpStatsLogger(REREPLICATE_OP); this.numLedgersReplicated = this.statsLogger.getCounter(NUM_FULL_OR_PARTIAL_LEDGERS_REPLICATED); this.exceptionCounters = new HashMap<String, Counter>(); }
Source:
<code>public void testReadAcrossReadahead() throws Throwable { <START> Path path = path("testReadAcrossReadahead"); <END> writeTestDataset(path); FileSystem fs = getFileSystem(); try (FSDataInputStream in = fs.open(path)) { final byte[] temp = new byte[5]; in.readByte(); int offset = READAHEAD - 1; in.readFully(offset, temp); assertDatasetEquals(offset, "read spanning boundary", temp, temp.length); } try (FSDataInputStream in = fs.open(path)) { final byte[] temp = new byte[5]; readAtEndAndReturn(in); assertEquals("current position", 1, (int)(in.getPos())); in.readFully(READAHEAD, temp); assertDatasetEquals(READAHEAD, "read across boundary", temp, temp.length); } }</code><technical_language>nice a describe() too</technical_language>

Target:
public void testReadAcrossReadahead() throws Throwable { describe("Sets up a read which will span the active readahead" + " and the rest of the file."); Path path = path("testReadAcrossReadahead"); writeTestDataset(path); FileSystem fs = getFileSystem(); try (FSDataInputStream in = fs.open(path)) { final byte[] temp = new byte[5]; in.readByte(); int offset = READAHEAD - 1; in.readFully(offset, temp); assertDatasetEquals(offset, "read spanning boundary", temp, temp.length); } try (FSDataInputStream in = fs.open(path)) { final byte[] temp = new byte[5]; readAtEndAndReturn(in); assertEquals("current position", 1, (int)(in.getPos())); in.readFully(READAHEAD, temp); assertDatasetEquals(READAHEAD, "read exactly on boundary", temp, temp.length); } }
Source:
<code><START> public static State createInstance(long startTime, long endTime, long lastUpdatedTime, <END> int numTrail, int numSuccess, int numFailure, int numIgnored, boolean isPaused, int rampStage, boolean isActive) { return new State() .setStartTime(startTime) .setEndTime(endTime) .setLastUpdatedTime(lastUpdatedTime) .setNumOfTrail(numTrail) .setNumOfSuccess(numSuccess) .setNumOfFailure(numFailure) .setNumOfIgnored(numIgnored) .setPaused(isPaused) .setRampStage(rampStage) .setActive(isActive); }</code><technical_language>Add final keyword? other places necessary</technical_language>

Target:
public static final State createInstance(long startTime, long endTime, long lastUpdatedTime, int numTrail, int numSuccess, int numFailure, int numIgnored, boolean isPaused, int rampStage, boolean isActive) { return new State() .setStartTime(startTime) .setEndTime(endTime) .setLastUpdatedTime(lastUpdatedTime) .setNumOfTrail(numTrail) .setNumOfSuccess(numSuccess) .setNumOfFailure(numFailure) .setNumOfIgnored(numIgnored) .setPaused(isPaused) .setRampStage(rampStage) .setActive(isActive); }
Source:
<code>protected GlusterVolume postPopulate(GlusterVolume model) { <START> model.setAccessProtocols("GLUSTER,NFS"); <END> return model; }</code><technical_language>spotted, this is confusing :)</technical_language>

Target:
protected GlusterVolume postPopulate(GlusterVolume model) { model.setVolumeType(GlusterVolumeType.DISTRIBUTE.name()); List<String> transportTypes = model.getTransportTypes().getTransportTypes(); transportTypes.clear(); transportTypes.add(TransportType.TCP.name()); List<String> accessProtocols = model.getAccessProtocols().getAccessProtocols(); accessProtocols.clear(); accessProtocols.add(AccessProtocol.GLUSTER.name()); accessProtocols.add(AccessProtocol.NFS.name()); return model; }
Source:
<code>void presentForList(int position, String listName) { this.position = position; <START> String dialogContent = dialog.getContext().getString(R.string.confirm_deletion_message," \"" + listName + "\""); <END> dialog.setContent(dialogContent); }</code><technical_language>nit: Slight formatting improvement suggestion String dialogContent = dialog.getContext().getString(R.string.confirm_deletion_message, " \"" + listName + "\"");</technical_language>

Target:
void presentForList(int position, String listName) { this.position = position; String dialogContent = dialog.getContext().getString(R.string.confirm_deletion_message, " \"" + listName + "\""); dialog.setContent(dialogContent); dialog.show(); }
Source:
<code>public Builder providerConfigurationMetadata(Map<String, Object> configurationMetadata) { <START> this.configurationMetadata = configurationMetadata; <END> return this; }</code><technical_language>In combination making configurationMetadata empty, prevent this null</technical_language>

Target:
public Builder providerConfigurationMetadata(Map<String, Object> configurationMetadata) { if (configurationMetadata != null) { this.configurationMetadata = new LinkedHashMap<>(configurationMetadata); } return this; }
Source:
<code>public ListenableFuture<?> enqueue(OrganizationSet organizationSet) { log.info("enqueue organizationSet: %s", organizationSet); shardsInProgress.putAll(organizationSet.getShardsMap()); ListenableFuture<?> listenableFuture = prioritizedFifoExecutor.submit(jobFactory.create(organizationSet)); listenableFuture.addListener( () -> { for (UUID uuid : organizationSet.getShardsMap().keySet()) { shardsInProgress.remove(uuid); <START> } <END> }, MoreExecutors.directExecutor()); Futures.addCallback( listenableFuture, new FutureCallback<Object>() { @Override public void onSuccess(Object o) { successCount.update(1); } @Override public void onFailure(Throwable throwable) { log.warn(throwable, "Error running organization job"); failureCount.update(1); } }, MoreExecutors.directExecutor()); return listenableFuture; }</code><technical_language>Instead of adding 2 levels of callback, extract for loop a function call onSuccess() onFailure() below</technical_language>

Target:
public ListenableFuture<?> enqueue(OrganizationSet organizationSet) { log.info("enqueue organizationSet: %s", organizationSet); shardsInProgress.putAll(organizationSet.getShardsMap()); deltaCountInProgress = shardsInProgress.values().stream().filter(Optional::isPresent).collect(toSet()).size(); ListenableFuture<?> listenableFuture = prioritizedFifoExecutor.submit(jobFactory.create(organizationSet)); listenableFuture.addListener( () -> { for (UUID uuid : organizationSet.getShardsMap().keySet()) { shardsInProgress.remove(uuid); deltaCountInProgress = shardsInProgress.values().stream().filter(Optional::isPresent).collect(toSet()).size(); } }, MoreExecutors.directExecutor()); Futures.addCallback( listenableFuture, new FutureCallback<Object>() { @Override public void onSuccess(Object o) { successCount.update(1); } @Override public void onFailure(Throwable throwable) { log.warn(throwable, "Error running organization job"); failureCount.update(1); } }, MoreExecutors.directExecutor()); return listenableFuture; }
Source:
<code>public static InetAddress intToInetAddress(int hostAddress) { InetAddress inetAddress; String hostName; <START> hostName = Integer.toString(0xff & hostAddress) + "." + <END> Integer.toString(0xff & (hostAddress >> 8)) + "." + Integer.toString(0xff & (hostAddress >> 16)) + "." + Integer.toString(0xff & (hostAddress >> 24)); try { inetAddress = InetAddress.getByName(hostName); } catch (UnknownHostException e) { return null; } return inetAddress; }</code><technical_language>Do need Integer.ToString? This work: hostName = "" + 0xff & hostAddress + "." + ..</technical_language>

Target:
public static InetAddress intToInetAddress(int hostAddress) { InetAddress inetAddress; String hostName; hostName = "" + (0xff & hostAddress) + "." + (0xff & (hostAddress >> 8)) + "." + (0xff & (hostAddress >> 16)) + "." + (0xff & (hostAddress >> 24)); try { inetAddress = InetAddress.getByName(hostName); } catch (UnknownHostException e) { return null; } return inetAddress; }
Source:
<code>public AttributeDetail(final AbstractBuild<?, ?> owner, final DetailFactory detailFactory, final Collection<FileAnnotation> annotations, final String defaultEncoding, final String header, final String name) { <START> super(owner, detailFactory, annotations, defaultEncoding, header, Hierarchy.PROJECT); <END> attributeName = name; }</code><technical_language>this((Run<?,?>)owner, ...) simpler safer for class evolution line</technical_language>

Target:
public AttributeDetail(final AbstractBuild<?, ?> owner, final DetailFactory detailFactory, final Collection<FileAnnotation> annotations, final String defaultEncoding, final String header, final String name) { this((Run<?, ?>) owner, detailFactory, annotations, defaultEncoding, header, name); }
Source:
<code>public void shouldUpdateChargeToCaptured_IfEpdqStatusIs9AndChargeIsHistoric() throws QueueException { charge = getCharge(true); final String payload = notificationPayloadForTransaction(payId, EPDQ_PAYMENT_REQUESTED); when(mockGatewayAccountService.getGatewayAccount(charge.getGatewayAccountId())).thenReturn(Optional.of(gatewayAccountEntity)); when(mockChargeService.findByProviderAndTransactionIdFromDbOrLedger(EPDQ.getName(), payId)).thenReturn(Optional.of(charge)); <START> ArgumentCaptor<ZonedDateTime> eventTimeStamp = ArgumentCaptor.forClass(ZonedDateTime.class); <END> notificationService.handleNotificationFor(payload); verify(mockChargeNotificationProcessor).processCaptureNotificationForExpungedCharge(gatewayAccountEntity, payId, charge, CAPTURED); }</code><technical_language>ArgumentCaptor more removed</technical_language>

Target:
public void shouldUpdateChargeToCaptured_IfEpdqStatusIs9AndChargeIsHistoric() throws QueueException { charge = getCharge(true); final String payload = notificationPayloadForTransaction(payId, EPDQ_PAYMENT_REQUESTED); when(mockGatewayAccountService.getGatewayAccount(charge.getGatewayAccountId())).thenReturn(Optional.of(gatewayAccountEntity)); when(mockChargeService.findByProviderAndTransactionIdFromDbOrLedger(EPDQ.getName(), payId)).thenReturn(Optional.of(charge)); notificationService.handleNotificationFor(payload); verify(mockChargeNotificationProcessor).processCaptureNotificationForExpungedCharge(gatewayAccountEntity, payId, charge, CAPTURED); }
Source:
<code>private void writeHeader(final LittleEndianOutputStream dos) throws IOException { dos.writeInt(MAGIC_NUMBER); dos.writeInt(getType()); dos.writeInt(version); <START> dos.writeString(indexedPath.toString()); <END> dos.writeLong(indexedFileSize); dos.writeLong(indexedFileTS); dos.writeString(indexedFileMD5); dos.writeInt(flags); dos.writeInt(properties.size()); for (final Map.Entry<String, String> prop : properties.entrySet()) { dos.writeString(prop.getKey()); dos.writeString(prop.getValue()); } }</code><technical_language>I indexedPath.toURI().toString() more roundtrip correctly for non-file paths</technical_language>

Target:
private void writeHeader(final LittleEndianOutputStream dos) throws IOException { dos.writeInt(MAGIC_NUMBER); dos.writeInt(getType()); dos.writeInt(version); dos.writeString(indexedPath.toUri().toString()); dos.writeLong(indexedFileSize); dos.writeLong(indexedFileTS); dos.writeString(indexedFileMD5); dos.writeInt(flags); dos.writeInt(properties.size()); for (final Map.Entry<String, String> prop : properties.entrySet()) { dos.writeString(prop.getKey()); dos.writeString(prop.getValue()); } }
Source:
<code>public void setup() { <START> provider = (ParanamerNameProvider) Factories.createParameterNameProvider(); <END> }</code><technical_language>casting</technical_language>

Target:
public void setup() { CacheStore<AccessibleObject, Parameter[]> cache = new DefaultCacheStore<>(); provider = new ParanamerNameProvider(cache); }
Source:
<code>public void createTopic(final String topic, final String zkUrl) { KafkaZkClient zkClient = null; try { zkClient = getZkClient(zkUrl); final AdminZkClient adminZkClient = new AdminZkClient(zkClient); adminZkClient.createTopic(topic, 1, 1, new Properties(), RackAwareMode.Safe$.MODULE$); } finally { if (zkClient != null) { zkClient.close(); <START> } <END> } }</code><technical_language>i do understand punish yourself, simpler. final KafkaZkClient zkClient = createZkClient(zkUrl) try { ... } finally { zkClient.close(); }</technical_language>

Target:
public void createTopic(final String topic, final String zkUrl) { try (KafkaZkClient zkClient = createZkClient(zkUrl)) { final AdminZkClient adminZkClient = new AdminZkClient(zkClient); adminZkClient.createTopic(topic, 1, 1, new Properties(), RackAwareMode.Safe$.MODULE$); } }
Source:
<code>public String expression(final String nodeIdentifier) { final Filter filter = this.getFilter(); return String.format("toLower(%s.`%s`) %s toLower({ `%s` }) ", nodeIdentifier, filter.getPropertyName(), <START> filter.getComparisonOperator().getValue(), filter.uniqueParameterName()); <END> }</code><technical_language>filter.getComparisonOperator().getValue() set ComparisonOperator.EQUALS is supported operator. parameter string template placeholder</technical_language>

Target:
public String expression(final String nodeIdentifier) { final Filter filter = this.getFilter(); return String.format("toLower(%s.`%s`) %s toLower({ `%s` }) ", nodeIdentifier, filter.getPropertyName(), ComparisonOperator.EQUALS.getValue(), filter.uniqueParameterName()); }
Source:
<code>public void shoultTestCustomApiKeyValidation() { <START> System.out.println("Exectute custom API key validation test for: " + this.customApiKeyParam); <END> CustomApiKeyObject customApiKeyObject = new CustomApiKeyObject(this.customApiKeyParam); Set<ConstraintViolation<CustomApiKeyObject>> violations = validator.validate(customApiKeyObject); Assert.assertEquals(violations.size(), this.violationSize); if (violationSize > 0) { Assert.assertTrue(violations.stream().anyMatch( v -> v.getMessage().equals(message))); } }</code><technical_language>a logger instead ;)</technical_language>

Target:
public void shoultTestCustomApiKeyValidation() { LOGGER.info("Exectute custom API key validation test for: " + this.customApiKeyParam); CustomApiKeyObject customApiKeyObject = new CustomApiKeyObject(this.customApiKeyParam); Set<ConstraintViolation<CustomApiKeyObject>> violations = validator.validate(customApiKeyObject); Assert.assertEquals(violations.size(), this.violationSize); if (violationSize > 0) { Assert.assertTrue(violations.stream().anyMatch( v -> v.getMessage().equals(message))); } }
Source:
<code>public synchronized <K> KeyQueryMetadata getKeyQueryMetadataForKey(final String storeName, final K key, final StreamPartitioner<? super K, ?> partitioner) { Objects.requireNonNull(storeName, "storeName can't be null"); Objects.requireNonNull(key, "key can't be null"); Objects.requireNonNull(partitioner, "partitioner can't be null"); if (!isInitialized()) { return KeyQueryMetadata.NOT_AVAILABLE; } if (globalStores.contains(storeName)) { <START> if (thisHost == UNKNOWN_HOST) { <END> return new KeyQueryMetadata(allMetadata.get(0).hostInfo(), Collections.emptySet(), -1); } return new KeyQueryMetadata(myMetadata.hostInfo(), Collections.emptySet(), -1); } final SourceTopicsInfo sourceTopicsInfo = getSourceTopicsInfo(storeName); if (sourceTopicsInfo == null) { return null; } return getKeyQueryMetadataForKey(storeName, key, partitioner, sourceTopicsInfo); }</code><technical_language>suggestion // global stores node. if host info</technical_language>

Target:
public synchronized <K> KeyQueryMetadata getKeyQueryMetadataForKey(final String storeName, final K key, final StreamPartitioner<? super K, ?> partitioner) { Objects.requireNonNull(storeName, "storeName can't be null"); Objects.requireNonNull(key, "key can't be null"); Objects.requireNonNull(partitioner, "partitioner can't be null"); if (!isInitialized()) { return KeyQueryMetadata.NOT_AVAILABLE; } if (globalStores.contains(storeName)) { if (thisHost == UNKNOWN_HOST) { return new KeyQueryMetadata(allMetadata.get(0).hostInfo(), Collections.emptySet(), -1); } return new KeyQueryMetadata(localMetadata.hostInfo(), Collections.emptySet(), -1); } final SourceTopicsInfo sourceTopicsInfo = getSourceTopicsInfo(storeName); if (sourceTopicsInfo == null) { return null; } return getKeyQueryMetadataForKey(storeName, key, partitioner, sourceTopicsInfo); }
Source:
<code>public void onLoadFinished(boolean success) { if (!success) { ToastUtil.showError(getActivity(), R.string.error_load_project); return; } <START> refreshFragment(); <END> }</code><technical_language>do instead is update adapter's item list. adapter.setItems(ProjectManager.getInstance().getCurrentProject().getSceneList()); initializeAdapter(); initializeAdapter more (would work though). why? rename scene, project is reloaded adapter's list updated (i.e. ProjectManager get's a new project SceneAdapter holds scene list). this is straightforward is absolutely need detach reattach fragment</technical_language>

Target:
public void onLoadFinished(boolean success) { if (!success) { ToastUtil.showError(getActivity(), R.string.error_load_project); return; } adapter.setItems(ProjectManager.getInstance().getCurrentProject().getSceneList()); }
Source:
<code>private boolean isCardHidden(@NonNull Card card) { int cardType = FeedRecyclerAdapter.getCardType(card); <START> for (HiddenCard hiddenCard : hiddenCards) { <END> if (hiddenCard.getType() == cardType && hiddenCard.getHashCode() == card.hashCode()) { return true; } } return false; }</code><technical_language>restricting this 100 entries ok for now. Still, I consider a data structure for lookup operations, a HashMap. idea is hashCode key card type binary-ORed value</technical_language>

Target:
private boolean isCardHidden(@NonNull Card card) { int cardType = FeedRecyclerAdapter.getCardType(card); for (HiddenCard hiddenCard : hiddenCards) { if (hiddenCard.getType() == cardType && hiddenCard.hashCode() == card.hashCode()) { return true; } } return false; }
Source:
<code><START> public static synchronized BrandingManager getInstance() { <END> if (instance == null) { instance = new BrandingManager(); } return instance; }</code><technical_language>point in synchronizing entire getInstance() (read+write), synchronizing 'write' instance</technical_language>

Target:
public static BrandingManager getInstance() { return getInstance(EngineLocalConfig.getInstance().getEtcDir()); }
Source:
<code>public void savePlayer(Player player) throws Exception { <START> try (Connection connection = connections.get()) { <END> Email email = Email.of(player.getCredentials().getUsername()); String displayName = player.getCredentials().getUsername(); putRank(connection, email, player.getPrivilegeLevel()); putPlayer(connection, email, player); putAppearance(connection, displayName, player.getAppearance()); putStats(connection, displayName, player.getSkillSet()); putInventory(connection, displayName, ITEM_BAG_ID, player.getInventory()); putInventory(connection, displayName, WORN_EQUIPMENT_ID, player.getEquipment()); putInventory(connection, displayName, BANK_ID, player.getBank()); putAttributes(connection, displayName, player.getAttributes()); } }</code><technical_language>This sequence of database queries needs wrapped in a transaction</technical_language>

Target:
public void savePlayer(Player player) throws Exception { Connection connection = null; Savepoint savepoint = null; try { connection = dataSource.getConnection(); connection.setAutoCommit(false); savepoint = connection.setSavepoint(); String email = player.getCredentials().getUsername(); String displayName = player.getCredentials().getUsername(); putRank(connection, email, player.getPrivilegeLevel()); putPlayer(connection, email, player); putAppearance(connection, displayName, player.getAppearance()); putStats(connection, displayName, player.getSkillSet()); putInventory(connection, displayName, ITEM_BAG_ID, player.getInventory()); putInventory(connection, displayName, WORN_EQUIPMENT_ID, player.getEquipment()); putInventory(connection, displayName, BANK_ID, player.getBank()); putAttributes(connection, displayName, player.getAttributes()); connection.commit(); connection.setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); connection.rollback(savepoint); } }
Source:
<code>public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { Intent intent = new Intent(HistoryActivity.this, SingleRunHistoryActivity.class); SingleRun selectedValue = (SingleRun) adapter.getItemAtPosition(position); <START> intent.putExtra("id", selectedValue.getRunID()); <END> startActivity(intent); overridePendingTransition(R.anim.in_left_anim, R.anim.out_left_anim); }</code><technical_language>hardcoded string "id"</technical_language>

Target:
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { Intent intent = new Intent(HistoryActivity.this, SingleRunHistoryActivity.class); SingleRun selectedValue = (SingleRun) adapter.getItemAtPosition(position); intent.putExtra(ID_TAG, selectedValue.getRunID()); startActivity(intent); overridePendingTransition(R.anim.in_left_anim, R.anim.out_left_anim); }
Source:
<code>public double getAOCorrectedFWHM(boolean doThrow) { switch (source.getProfileType()) { case POINT: final int IQ20 = 20, IQ70 = 70, IQ85 = 85; final int iq = (int) (imageQualityPercentile * 100); switch (strehlBand.charAt(0)) { case 'J': switch (iq) { case IQ20: return 0.08; case IQ70: return 0.13; case IQ85: return 0.15; } break; case 'H': switch (iq) { case IQ20: return 0.07; case IQ70: return 0.10; case IQ85: return 0.13; } break; case 'K': switch (iq) { case IQ20: return 0.06; case IQ70: return 0.09; case IQ85: return 0.12; } break; default: <START> throw new IllegalArgumentException("GeMS does not support band " + strehlBand); <END> } break; case GAUSSIAN: return source.getFWHM(); default: return 0.0; } if (doThrow) { throw new IllegalArgumentException("GeMS cannot be used in IQ=Any conditions"); } else { return getAOCorrectedFWHM_oldVersion(); } }</code><technical_language>band this refers to? Gems a bands select Guide Stars</technical_language>

Target:
public double getAOCorrectedFWHM(boolean doThrow) { switch (source.getProfileType()) { case POINT: final int IQ20 = 20, IQ70 = 70, IQ85 = 85; final int iq = (int) (imageQualityPercentile * 100); switch (strehlBand.charAt(0)) { case 'J': switch (iq) { case IQ20: return 0.08; case IQ70: return 0.13; case IQ85: return 0.15; } break; case 'H': switch (iq) { case IQ20: return 0.07; case IQ70: return 0.10; case IQ85: return 0.13; } break; case 'K': switch (iq) { case IQ20: return 0.06; case IQ70: return 0.09; case IQ85: return 0.12; } break; default: throw new IllegalArgumentException("Current ITC implementation for GeMS does not support band " + strehlBand); } break; case GAUSSIAN: return source.getFWHM(); default: return 0.0; } if (doThrow) { throw new IllegalArgumentException("GeMS cannot be used in IQ=Any conditions"); } else { return getAOCorrectedFWHM_oldVersion(); } }