auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ApiAuthenticationResult authenticate(HttpServletRequest httpServletRequest) { Assert.notNull(httpServletRequest, "httpRequest argument cannot be null."); Assert.isInstanceOf(javax.servlet.http.HttpServletRequest.class, httpServletRequest, "The specified httpRequest argument must be an instance of " + HTTP_SERVLET_REQUEST_FQCN); com.stormpath.sdk.impl.http.ServletHttpRequest stmpHttpRequest = new com.stormpath.sdk.impl.http.ServletHttpRequest(httpServletRequest); START return (ApiAuthenticationResult) Applications.apiRequestAuthenticator(application).authenticate(stmpHttpRequest); END } `ApiAuthenticationResult` casting redundant

Target:
public ApiAuthenticationResult authenticate(HttpServletRequest httpServletRequest) { Assert.notNull(httpServletRequest, "httpRequest argument cannot be null."); Assert.isInstanceOf(javax.servlet.http.HttpServletRequest.class, httpServletRequest, "The specified httpRequest argument must be an instance of " + HTTP_SERVLET_REQUEST_FQCN); com.stormpath.sdk.impl.http.ServletHttpRequest stmpHttpRequest = new com.stormpath.sdk.impl.http.ServletHttpRequest(httpServletRequest); return Applications.apiRequestAuthenticator(application).authenticate(stmpHttpRequest); }
Source:
public void setWebDialogEnabled(boolean isEnabled) { isWebDialogEnabled = isEnabled; START addConfig("webDialogEnabled", isWebDialogEnabled ? "true" : "false"); END } Please remove this line

Target:
public void setWebDialogEnabled(boolean isEnabled) { isWebDialogEnabled = isEnabled; }
Source:
public static void init() { IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); ITEMS.register(modEventBus); for (SlimeBlock.SlimeType type : SlimeBlock.SlimeType.values()) { System.out.println(type); START System.out.println(type.toString()); END } } Leftover debug?

Target:
public static void init() { IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); ITEMS.register(modEventBus); }
Source:
public void handleServerSafe(NetHandlerPlayServer netHandler) { START if(netHandler.player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem() instanceof ItemSlimeBoots) END netHandler.player.fallDistance = 0; } Your indentation is way off, we use 2 space indentation. We also always use curly brackets for single if statements

Target:
public void handleServerSafe(NetHandlerPlayServer netHandler) { if(netHandler.player.getItemStackFromSlot(EntityEquipmentSlot.FEET).getItem() instanceof ItemSlimeBoots) { netHandler.player.fallDistance = 0; } }
Source:
public List<BakedQuad> getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { START if(side == null) return quads; END return ImmutableList.of(); } Really mezz, no braces? You're better than that ;P

Target:
public List<BakedQuad> getQuads(@Nullable IBlockState state, @Nullable EnumFacing side, long rand) { if(side == null) { return quads; } return ImmutableList.of(); }
Source:
public void update() { if(isClientWorld()) { return; } // are we fully formed? if(!isActive()) { // check for furnace once per second if(tick == 0) { checkMultiblockStructure(); } } else { // we have a lot less to do than a smeltery since the inside is unreachable and we have no liquids // basically just heating and fuel consumption // we heat items every tick, as otherwise we are quite slow compared to a vanilla furnace if(tick % 4 == 0) { heatItems(); START interactWithEntitiesInside(); END } if(needsFuel) { consumeFuel(); } // we don't check the inside for obstructions since it should not be possible unless the outside was modified } tick = (tick + 1) % 20; } The smeltery only runs this every 20 ticks, or `tick == 0`

Target:
public void update() { if(isClientWorld()) { return; } // are we fully formed? if(!isActive()) { // check for furnace once per second if(tick == 0) { checkMultiblockStructure(); } } else { // we have a lot less to do than a smeltery since the inside is unreachable and we have no liquids // basically just heating and fuel consumption // we heat items every tick, as otherwise we are quite slow compared to a vanilla furnace if(tick % 4 == 0) { heatItems(); } if(tick == 0) { interactWithEntitiesInside(); } if(needsFuel) { consumeFuel(); } // we don't check the inside for obstructions since it should not be possible unless the outside was modified } tick = (tick + 1) % 20; }
Source:
public GuiContainer createGui(InventoryPlayer inventoryplayer, World world, BlockPos pos) { START return new GuiTinkerTank((ContainerTinkerTank) createContainer(inventoryplayer, world, pos), this); END } Unneeded cast

Target:
public GuiContainer createGui(InventoryPlayer inventoryplayer, World world, BlockPos pos) { return new GuiTinkerTank(createContainer(inventoryplayer, world, pos), this); }
Source:
public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { // use the glowball for the pickblock, as it is more useful than the technical block START if(gadgetsLoaded) { END return new ItemStack(TinkerGadgets.throwball, 1, ItemThrowball.ThrowballType.GLOW.ordinal()); } // if unavailable, just return nothing, Minecraft will just not do anything on pick block return null; } I'd reduce this to a simple `if(TinkerGadgets.throwball != null)`. That way there is no hard dependency on the pulse.

Target:
public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) { // only use the glowball for pickblock if it was loaded (which happens when gadgets is loaded) if(TinkerGadgets.throwball != null) { return new ItemStack(TinkerGadgets.throwball, 1, ItemThrowball.ThrowballType.GLOW.ordinal()); } // if unavailable, just return nothing, Minecraft will just not do anything on pick block return null; }
Source:
public void setUp() throws Exception { TestPersistentBinaryDeque.setupTestDir(); m_pbd = PersistentBinaryDeque.builder(TestPersistentBinaryDeque.TEST_NONCE, TestPersistentBinaryDeque.TEST_DIR, s_logger) .compression(true) .initialExtraHeader(null, TestPersistentBinaryDeque.SERIALIZER).build(); START m_pbd.setRetentionPolicy(BinaryDeque.RetentionPolicyType.TIME_MS, new Long(s_retainMillis)); END m_pbd.startRetentionPolicyEnforcement(); } Minor: Usually better to use `Long.valueOf` instead of `new Long`

Target:
public void setUp() throws Exception { TestPersistentBinaryDeque.setupTestDir(); m_pbd = PersistentBinaryDeque.builder(TestPersistentBinaryDeque.TEST_NONCE, TestPersistentBinaryDeque.TEST_DIR, s_logger) .compression(true) .initialExtraHeader(null, TestPersistentBinaryDeque.SERIALIZER).build(); m_pbd.setRetentionPolicy(BinaryDeque.RetentionPolicyType.TIME_MS, Long.valueOf(s_retainMillis)); m_pbd.startRetentionPolicyEnforcement(); }
Source:
public static Object extractPartitioningValue(RelDistribution dist) { RexNode partitioningNode = dist.getPartitionEqualValue(); if (partitioningNode instanceof RexLiteral) { RexLiteral literal = (RexLiteral) partitioningNode; Comparable value = literal.getValue(); if (value instanceof Number) { return ((Number) value).longValue(); } else { try { START RexLiteral.stringValue(literal); END } catch(Exception ex) { } } } return null; } missing return?

Target:
public static Object extractPartitioningValue(RelDistribution dist) { RexNode partitioningNode = dist.getPartitionEqualValue(); if (partitioningNode instanceof RexLiteral) { RexLiteral literal = (RexLiteral) partitioningNode; Comparable value = literal.getValue(); if (value instanceof Number) { return ((Number) value).longValue(); } else { try { return RexLiteral.stringValue(literal); } catch(Exception ex) { } } } return null; }
Source:
START public synchronized void resume() { END m_isPaused = false; } This doesn't need to be synchronized, right?

Target:
public void resume() { m_isPaused = false; }
Source:
public boolean isOrderDeterministic(boolean orderIsDeterministic) { CompiledPlan plan = getBestCostPlan(); // If the plan is null, there is an error in the query, // so we can return anything. if (plan != null) { return orderIsDeterministic && plan.isOrderDeterministic(); START } else { END return orderIsDeterministic; } } BTW this style is considered an unnecessary else and is actually a possible compiler error/warning in eclipse and I think other java compilers

Target:
public boolean isOrderDeterministic(boolean orderIsDeterministic) { CompiledPlan plan = getBestCostPlan(); // If the plan is null, there is an error in the query, // so we can return anything. if (plan != null) { return orderIsDeterministic && plan.isOrderDeterministic(); } return orderIsDeterministic; }
Source:
protected ClientConfig createClientConfig() { START ClientConfig cc = new ClientConfig(m_username, m_password); END cc.setProcedureCallTimeout(10 * 60 * 1000); // 10 min return cc; } I think it would be cleaner to add a `createClientConfig(Stirng username, String password)` method and then just have this current one call that one with empty strings.

Target:
protected ClientConfig createClientConfig() { return createClientConfig("", ""); }
Source:
public void newSegmentAdded() { if (!m_pbd.isCursorOpen(CURSOR_NAME)) { // not started yet return; } if (m_pbd.getUsageSpecificLog().isDebugEnabled()) { m_pbd.getUsageSpecificLog().debug("Processing newSegmentAdded for PBD " + m_pbd.getNonce()); } START scheduleTaskFor(m_pbd.getNonce(), ()->deleteOldSegments(), MIN_DELAY); END } You can do `this::deleteOldSegments` for the callable

Target:
public void newSegmentAdded() { if (!m_pbd.isCursorOpen(CURSOR_NAME)) { // not started yet return; } if (m_pbd.getUsageSpecificLog().isDebugEnabled()) { m_pbd.getUsageSpecificLog().debug("Processing newSegmentAdded for PBD " + m_pbd.getNonce()); } scheduleTaskFor(m_pbd.getNonce(), this::deleteOldSegments, MIN_DELAY); }
Source:
public ValidationError(String msg) { START super("ValidationError: " + msg); END } It might be better to override toString rather than append ValidationError because now you will get `org.voltdb.exception.ValidationError: ValidationError: MESSAGE` when toString is called or the stack trace is printed

Target:
public ValidationError(String msg) { super(msg); }
Source:
public void put(TraceEventType eventType, TraceEventWrapper beginWrapper, long beginTime, String eventId) { if (TraceEventType.DURATION_BEGIN.equals(eventType)) { START m_durationEvents.addLast(new Pair<TraceEventWrapper, Long>(beginWrapper, beginTime)); END return; } if (TraceEventType.ASYNC_BEGIN.equals(eventType)) { m_asyncEvents.put(eventId, new Pair<TraceEventWrapper, Long>(beginWrapper, beginTime)); return; } return; } Use `Pair.of(beginWrapper, beginTime)`

Target:
public void put(TraceEventType eventType, TraceEventWrapper beginWrapper, long beginTime, String eventId) { if (TraceEventType.DURATION_BEGIN.equals(eventType)) { m_durationEvents.addLast(Pair.of(beginWrapper, beginTime)); return; } if (TraceEventType.ASYNC_BEGIN.equals(eventType)) { m_asyncEvents.put(eventId, Pair.of(beginWrapper, beginTime)); return; } return; }
Source:
private void fillNextCycle(int numUpdates, boolean expect) { for (int ii = 0; ii < numUpdates; ii++) { START Random m_random = new Random(); END int maxStreamSuffix = m_expectedValues.lastKey() + 1; int targetSuffix; do { targetSuffix = m_random.nextInt(maxStreamSuffix); } while (!m_expectedValues.containsKey(targetSuffix)); changeCursor(targetSuffix, getRandomPartitionId(), Math.abs(m_random.nextLong()), expect); } } Why is this creating a new random instance for each iteration in the loop? Also shouldn't be using the `m_` prefix

Target:
private void fillNextCycle(int numUpdates, boolean expect) { for (int ii = 0; ii < numUpdates; ii++) { int maxStreamSuffix = m_expectedValues.lastKey() + 1; int targetSuffix; do { targetSuffix = m_random.nextInt(maxStreamSuffix); } while (!m_expectedValues.containsKey(targetSuffix)); changeCursor(targetSuffix, getRandomPartitionId(), Math.abs(m_random.nextLong()), expect); } }
Source:
START public static RelBuilderFactory proto(final Context context) { END return new RelBuilderFactory() { public RelBuilder create(RelOptCluster cluster, RelOptSchema schema) { return new VoltPRelBuilder(context, cluster, schema); } }; } As suggested by IntelliJ: ```suggestion public static RelBuilderFactory proto(final Context context) { return (cluster, schema) -> new VoltPRelBuilder(context, cluster, schema); } ```

Target:
public static RelBuilderFactory proto(final Context context) { return (cluster, schema) -> new VoltPRelBuilder(context, cluster, schema); }
Source:
public AggregateExpression(ExpressionType type) { super(type); m_userAggregateId = "-1"; START m_name = "notUDAF"; END } empty string is better, if that works.

Target:
public AggregateExpression(ExpressionType type) { super(type); m_userAggregateId = -1; m_name = ""; }
Source:
public boolean isUserDefined() { START if (m_userAggregateId != null) { END return FunctionForVoltDB.isUserDefinedFunctionId(Integer.parseInt(m_userAggregateId)); } else { return false; } } Is this correct? It's never set to null.

Target:
public boolean isUserDefined() { return FunctionForVoltDB.isUserDefinedFunctionId(m_userAggregateId); }
Source:
public synchronized void startPolling(CatalogContext catalogContext) { m_startPolling = true; CatalogMap<Connector> connectors = CatalogUtil.getConnectors(catalogContext); if(!CatalogUtil.hasEnabledConnectors(connectors)) { exportLog.info("System is not using any export functionality or connectors configured are disabled."); return; } ExportDataProcessor processor = m_processor.get(); Preconditions.checkState(processor != null, "guest processor is not set"); processor.startPolling(); // Notify export datasources to check the *generation* of export buffers, // delete buffers older than current generation number or generation number // from snapshot. START cleanupStaleBuffers(); END } BUG? Should'nt this be done BEFORE startting the processor polling?

Target:
public synchronized void startPolling(CatalogContext catalogContext) { m_startPolling = true; CatalogMap<Connector> connectors = CatalogUtil.getConnectors(catalogContext); if(!CatalogUtil.hasEnabledConnectors(connectors)) { exportLog.info("System is not using any export functionality or connectors configured are disabled."); return; } ExportDataProcessor processor = m_processor.get(); Preconditions.checkState(processor != null, "guest processor is not set"); // Notify export datasources to check the *generation* of export buffers, // delete buffers older than current generation number or generation number // from snapshot. cleanupStaleBuffers(); processor.startPolling(); }
Source:
START private static RelNode toIndexJoin(VoltPhysicalJoin join, RelNode outerScan, RelNode innerChild, String indexName) { END return new VoltPhysicalNestLoopIndexJoin( join.getCluster(), join.getTraitSet(), outerScan, innerChild, join.getCondition(), join.getVariablesSet(), join.getJoinType(), join.isSemiJoinDone(), ImmutableList.copyOf(join.getSystemFieldList()), join.getSplitCount(), indexName); } Join type check should be consolidated probably in the logical phase

Target:
private static RelNode toIndexJoin(VoltPhysicalJoin join, RelNode outerScan, RelNode innerChild, String indexName) { return new VoltPhysicalNestLoopIndexJoin( join.getCluster(), join.getTraitSet(), outerScan, innerChild, join.getCondition(), join.getVariablesSet(), join.getJoinType(), join.isSemiJoinDone(), ImmutableList.copyOf(join.getSystemFieldList()), indexName); }
Source:
private int containsFunctionByIds(Set<Integer> functionIds) { START if (this instanceof AbstractValueExpression) { END return -1; } List<AbstractExpression> functionsList = findAllFunctionSubexpressions(); for (AbstractExpression funcExpr : functionsList) { assert (funcExpr instanceof FunctionExpression); if (functionIds.contains(((FunctionExpression) funcExpr).getFunctionId())) { return ((FunctionExpression) funcExpr).getFunctionId(); } } return -1; } Do you need this here? When? Or should it belong to `findAllFunctionsSubexpressions()`?

Target:
private int containsFunctionByIds(Set<Integer> functionIds) { List<AbstractExpression> functionsList = findAllFunctionSubexpressions(); for (AbstractExpression funcExpr : functionsList) { assert (funcExpr instanceof FunctionExpression); if (functionIds.contains(((FunctionExpression) funcExpr).getFunctionId())) { return ((FunctionExpression) funcExpr).getFunctionId(); } } return -1; }
Source:
public void updateCatalog(Table table, long genId) { m_es.execute(new Runnable() { public void run() { START if (genId != m_previousGenId) { END assert (genId > m_previousGenId); // This serializer is used to write stream schema to pbd StreamTableSchemaSerializer ds = new StreamTableSchemaSerializer(table, table.getTypeName(), genId); try { m_committedBuffers.updateSchema(ds); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to write PBD export header.", true, e); } m_previousGenId = genId; } } }); } I would check the equality first and add a runable if needed to avoid unneeded runs.

Target:
public void updateCatalog(Table table, long genId) { // Skip unneeded catalog update if (m_previousGenId >= genId) { return; } m_es.execute(new Runnable() { public void run() { if (m_previousGenId < genId) { // This serializer is used to write stream schema to pbd StreamTableSchemaSerializer ds = new StreamTableSchemaSerializer(table, table.getTypeName(), genId); try { m_committedBuffers.updateSchema(ds); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to write PBD export header.", true, e); } m_previousGenId = genId; } } }); }
Source:
static void resetDir() throws IOException { START File f = new File("/tmp/" + System.getProperty("user.name")); END VoltFile.recursivelyDelete(f); f.mkdirs(); } This directory should probably be defined in a common place so if we want to move it to another location it is a single update

Target:
public static void resetDir() throws IOException { File f = new File("/tmp/" + System.getProperty("user.name")); VoltFile.recursivelyDelete(f); f.mkdirs(); }
Source:
void reset() { m_syncedSinceLastEdit = false; if (m_segmentHeaderBuf != null) { m_segmentHeaderBuf.discard(); m_segmentHeaderBuf = null; } if (m_entryHeaderBuf != null) { m_entryHeaderBuf.discard(); m_entryHeaderBuf = null; } m_crc.reset(); START m_crc.reset(); END } Duplicated line (probably global replace)

Target:
void reset() { m_syncedSinceLastEdit = false; if (m_segmentHeaderBuf != null) { m_segmentHeaderBuf.discard(); m_segmentHeaderBuf = null; } if (m_entryHeaderBuf != null) { m_entryHeaderBuf.discard(); m_entryHeaderBuf = null; } }
Source:
public static void writeEntryHeader(CRC32 crc, ByteBuffer headerBuf, ByteBuffer destBuf, int size, int flag) { crc.update(size); crc.update(flag); crc.update(destBuf); headerBuf.clear(); headerBuf.order(ByteOrder.LITTLE_ENDIAN); START headerBuf.putLong(crc.getValue()); END headerBuf.putInt(size); headerBuf.putInt(flag); headerBuf.order(ByteOrder.BIG_ENDIAN); } Not sure if it matters but the value returned by getValue is really an unsigned int so you could store an int here and save 4bytes if that matters at all

Target:
public static void writeEntryHeader(CRC32 crc, ByteBuffer headerBuf, ByteBuffer destBuf, int size, int flag) { crc.update(size); crc.update(flag); crc.update(destBuf); // the checksum here is really an unsigned int, store integer to save 4 bytes headerBuf.putInt((int)crc.getValue()); headerBuf.putInt(size); headerBuf.putInt(flag); }
Source:
public static void setFinal(File file, boolean isFinal) { try { UserDefinedFileAttributeView view = getFileAttributeView(file); view.write(IS_FINAL_ATTRIBUTE, Charset.defaultCharset().encode(new Boolean(isFinal).toString())); START } catch (Exception e) { END // No-op } } I would prefer if not all exceptions were swallowed but instead maybe just IOExceptions and it still might be nice to log those at debug in case somebody ever wonders why this isn't working.

Target:
public static void setFinal(File file, boolean isFinal) { try { UserDefinedFileAttributeView view = getFileAttributeView(file); if (view != null) { view.write(IS_FINAL_ATTRIBUTE, Charset.defaultCharset().encode(new Boolean(isFinal).toString())); } } catch (IOException e) { // No-op } }
Source:
START @Override void addHostData(VoltTableRow row) throws IOException { END assert(row.getString("TABLE").equals(getTableName())); checkSiteConsistency(row); // throws if inconsistent // this cast should be safe; site_ids are ints but get // promoted to long in the VoltTable.row.getLong return m_hostsWithThisTable.add((int) row.getLong("CURRENT_HOST_ID")); } Why are you putting the annotation on the same line as the method name. Normally all annotations are on their own line

Target:
void addHostData(VoltTableRow row) throws IOException { assert(row.getString("TABLE").equals(getTableName())); checkSiteConsistency(row); // throws if inconsistent // this cast should be safe; site_ids are ints but get // promoted to long in the VoltTable.row.getLong return m_hostsWithThisTable.add((int) row.getLong("CURRENT_HOST_ID")); }
Source:
START VoltPSetOpsRule(RelOptRuleOperand operand, MatchType matchType) { END super(operand, "VoltPSetOpsRule_" + matchType.name()); m_matchType = matchType; } The constructor can be private.

Target:
private VoltPSetOpsRule(RelOptRuleOperand operand, MatchType matchType) { super(operand, "VoltPSetOpsRule_" + matchType.name()); m_matchType = matchType; }
Source:
public NonDdlBatch setInferPartitioning(boolean value) { value = m_batchToDecorate.getTaskCount() == 1 && value; START if (m_inferPartitioning ^ value) { END m_inferPartitioning = value; updateStatementPartitioning(); } return this; } let's just use `m_inferPartitioning != value`.

Target:
public NonDdlBatch setInferPartitioning(boolean value) { value = m_batchToDecorate.getTaskCount() == 1 && value; if (m_inferPartitioning != value) { m_inferPartitioning = value; updateStatementPartitioning(); } return this; }
Source:
JoinType(int val) { assert (this.ordinal() == val) : "Enum element " + this.name() + " in position " + this.ordinal() + " instead of position " + val; START m_val = val; END } if m_val has to equal ordinal why bother storing it you could just use ordinal everywhere.

Target:
JoinType(int val) { assert (this.ordinal() == val) : "Enum element " + this.name() + " in position " + this.ordinal() + " instead of position " + val; }
Source:
public VoltDBLLimit( RelOptCluster cluster, RelTraitSet traitSet, RelNode input, RexNode offset, RexNode limit) { super(cluster, traitSet, input); START assert VoltDBLRel.VOLTDB_LOGICAL.equals(getConvention()); END m_offset = offset; m_limit = limit; } Should we be consistent with the assert assert VoltDBLRel.VOLTDB_LOGICAL.equals(getConvention()); vs assert traitSet.contains(VoltDBLRel.VOLTDB_LOGICAL);

Target:
public VoltDBLLimit( RelOptCluster cluster, RelTraitSet traitSet, RelNode input, RexNode offset, RexNode limit) { super(cluster, traitSet, input); assert traitSet.contains(VoltDBLRel.VOLTDB_LOGICAL); m_offset = offset; m_limit = limit; }
Source:
protected CompiledPlan compileAdHocCalcitePlan(String sql, boolean inferPartitioning, boolean forcedSP, DeterminismMode detMode) { CompiledPlan cp = null; try { cp = m_aide.compileAdHocPlan(PlannerType.CALCITE, sql, inferPartitioning, forcedSP, detMode); assertNotNull(cp); } catch (Exception ex) { START fail(ex.getMessage()); END } return cp; } Why not just let the exception bubble up and fail the test by having the test throw an exception. That way the entire stack trace is captured by junit.

Target:
protected CompiledPlan compileAdHocCalcitePlan(String sql, boolean inferPartitioning, boolean forcedSP, DeterminismMode detMode) { CompiledPlan cp = m_aide.compileAdHocPlan(PlannerType.CALCITE, sql, inferPartitioning, forcedSP, detMode); assertNotNull(cp); return cp; }
Source:
protected RelNode visitChild(RelNode parent, int i, RelNode child) { START child.accept(this); END parent.getCluster().setMetadataProvider(metadataProvider); return parent; } And also here: refer to L55 of calcite/core/src/main/java/org/apache/calcite/rel/RelShuttleImpl.java. The `accept` method does not change anything on `this` instance; it returns a modified copy of `child`, which you then discarded.

Target:
protected RelNode visitChild(RelNode parent, int i, RelNode child) { parent = super.visitChild(parent, i, child); parent.getCluster().setMetadataProvider(metadataProvider); return parent; }
Source:
START public CatalogMap(Catalog catalog, CatalogType parent, String name, Class<T> cls, int depth) { END m_catalog = catalog; m_parent = parent; m_name = name; m_cls = cls; m_depth = depth; if (depth <= 3) { m_cachedPath = getPath(); } } Revert this

Target:
CatalogMap(Catalog catalog, CatalogType parent, String name, Class<T> cls, int depth) { m_catalog = catalog; m_parent = parent; m_name = name; m_cls = cls; m_depth = depth; if (depth <= 3) { m_cachedPath = getPath(); } }
Source:
protected void writeTestFileName(String name, boolean append) throws FileNotFoundException { File outFileName = new File(m_testNamesFile); if ( ! outFileName.exists() ) { append = false; } START PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(outFileName, append))); END ps.print(name); ps.close(); } [Java-8 try-with-resource](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html): try(PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(outFileName, append)))) { ps.print(name); }

Target:
protected void writeTestFileName(String name, boolean append) throws FileNotFoundException { File outFileName = new File(m_testNamesFile); if ( ! outFileName.exists() ) { append = false; } try (PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(outFileName, append)))) { ps.print(name); } }
Source:
public Object getValue(Session session) { if (opType != OpTypes.STARTS_WITH) { return super.getValue(session); } Object leftValue = nodes[LEFT].getValue(session); Object rightValue = nodes[RIGHT].getValue(session); if (startsWithObject.isVariable) { START synchronized (startsWithObject) { END startsWithObject.setPattern(session, rightValue); return startsWithObject.compare(session, leftValue); } } return startsWithObject.compare(session, leftValue); } Is this necessary? When would multiple threads with same `ExpressionStartsWith` object instance be?

Target:
public Object getValue(Session session) { if (opType != OpTypes.STARTS_WITH) { return super.getValue(session); } Object leftValue = nodes[LEFT].getValue(session); Object rightValue = nodes[RIGHT].getValue(session); if (startsWithObject.isVariable) { startsWithObject.setPattern(session, rightValue); } return startsWithObject.compare(session, leftValue); }
Source:
public Object getValue(Session session) { if (opType != OpTypes.STARTS_WITH) { return super.getValue(session); } Object leftValue = nodes[LEFT].getValue(session); Object rightValue = nodes[RIGHT].getValue(session); if (startsWithObject.isVariable) { startsWithObject.setPattern(session, rightValue); START return startsWithObject.compare(session, leftValue); END } return startsWithObject.compare(session, leftValue); } This return statement can be deleted, right?

Target:
public Object getValue(Session session) { if (opType != OpTypes.STARTS_WITH) { return super.getValue(session); } Object leftValue = nodes[LEFT].getValue(session); Object rightValue = nodes[RIGHT].getValue(session); if (startsWithObject.isVariable) { startsWithObject.setPattern(session, rightValue); } return startsWithObject.compare(session, leftValue); }
Source:
String getPathOfBatchDir(String prefix) { assert(m_batched); String hostId = ""; if(m_uniquenames) { hostId = "-("+VoltDB.instance().getHostMessenger().getHostId()+")"; } START return m_outDir.getPath() + File.separator + prefix + m_nonce + "-" + m_dateformat.get().format(start) + hostId; END } This is changing the batch directory name. This shouldn't be changed. Only the filenames need to be changed.

Target:
String getPathOfBatchDir(String prefix) { assert(m_batched); return m_outDir.getPath() + File.separator + prefix + m_nonce + "-" + m_dateformat.get().format(start); }
Source:
void resolveColumnIndexesUsingSchema(NodeSchema inputSchema) { // get all the TVEs in the output columns int difftor = 0; for (SchemaColumn col : m_outputSchema) { col.setDifferentiator(difftor); ++difftor; Collection<TupleValueExpression> allTves = ExpressionUtil.getTupleValueExpressions(col.getExpression()); // and update their indexes against the table schema for (TupleValueExpression tve : allTves) { tve.setColumnIndexUsingSchema(inputSchema); START assert (tve.getColumnIndex() >= 0 || tve.getColumnIndex() < inputSchema.size()); END } } // DON'T RE-SORT HERE } Is is possible for the column index to be negative? How can that be? Should this be an && and not a ||?

Target:
void resolveColumnIndexesUsingSchema(NodeSchema inputSchema) { // get all the TVEs in the output columns int difftor = 0; for (SchemaColumn col : m_outputSchema) { col.setDifferentiator(difftor); ++difftor; Collection<TupleValueExpression> allTves = ExpressionUtil.getTupleValueExpressions(col.getExpression()); // and update their indexes against the table schema for (TupleValueExpression tve : allTves) { tve.setColumnIndexUsingSchema(inputSchema); assert (tve.getColumnIndex() >= 0 && tve.getColumnIndex() < inputSchema.size()); } } // DON'T RE-SORT HERE }
Source:
public VoltNIOWriteStream writeStream() { START assert(m_writeStream != null && m_writeStream instanceof VoltNIOWriteStream); END return (VoltNIOWriteStream) m_writeStream; } If m_writeStream is defined as VoltNIOWriteStream, then the assertion and cast here is not needed.

Target:
public VoltNIOWriteStream writeStream() { assert(m_writeStream != null); return m_writeStream; }
Source:
START private synchronized void buildListener(AdvertisedDataSource ads) { END //Dont construct if we are shutdown if (m_shutdown) return; final ExportDecoderBase edb = m_client.constructExportDecoder(ads); detectDecoder(m_client, edb); Pair<ExportDecoderBase, AdvertisedDataSource> pair = Pair.of(edb, ads); m_decoders.add(pair); final ListenableFuture<BBContainer> fut = m_source.poll(); addBlockListener(m_source, fut, edb); } It doesn't have to be `synchronized`, ExportRunner already grabs `GuestProcessor.this` lock before it calls `buildListener()`

Target:
private void buildListener(AdvertisedDataSource ads) { //Dont construct if we are shutdown if (m_shutdown) return; final ExportDecoderBase edb = m_client.constructExportDecoder(ads); detectDecoder(m_client, edb); Pair<ExportDecoderBase, AdvertisedDataSource> pair = Pair.of(edb, ads); m_decoders.add(pair); final ListenableFuture<BBContainer> fut = m_source.poll(); addBlockListener(m_source, fut, edb); }
Source:
public void notifyOfCatalogUpdate() { try { clearSessions(); if (httpClientInterface != null) { httpClientInterface.notifyOfCatalogUpdate(); } } catch (Exception ex) { START m_log.error("Failed to update HTTP interface after catalog update", ex); END } } Is this error handling enough? What are the risks of getting here?

Target:
public void notifyOfCatalogUpdate() { try { clearSessions(); } catch (Exception ex) { m_log.error("Failed to update HTTP interface after catalog update", ex); } }
Source:
public ListenableFuture<?> sync(final boolean nofsync) { START return m_es.submit(new Runnable() { END @Override public void run() { new SyncRunnable(nofsync).run(); } }); } Can be simplified to `return m_es.submit(new SyncRunnable(nofsync));`

Target:
public ListenableFuture<?> sync(final boolean nofsync) { return m_es.submit(new SyncRunnable(nofsync)); }
Source:
START private synchronized void ackImpl(long uso, Exception ackCallStack) { END if (uso == Long.MIN_VALUE && m_onDrain != null) { //If we are not continueing generation set drained flag. if (!m_isInContinueingGeneration) m_drained = true; m_drainTraceForDebug = new Exception("Acking USO " + uso, ackCallStack); m_onDrain.run(); return; } //Process the ack if any and add blocks to the delete list or move the released USO pointer if (uso > 0) { try { releaseExportBytes(uso); } catch (IOException e) { VoltDB.crashLocalVoltDB("Error attempting to release export bytes", true, e); return; } } } Is it necessary to synchronize this?

Target:
private synchronized void ackImpl(long uso, Exception ackCallStack) { if (uso == Long.MIN_VALUE && m_onDrain != null) { m_drained = true; m_drainTraceForDebug = new Exception("Acking USO " + uso, ackCallStack); m_onDrain.run(); return; } //Process the ack if any and add blocks to the delete list or move the released USO pointer if (uso > 0) { try { releaseExportBytes(uso); } catch (IOException e) { VoltDB.crashLocalVoltDB("Error attempting to release export bytes", true, e); return; } } }
Source:
private static void addStatementDependence(Function function, Statement catalogStmt) { String stmtDeps = catalogStmt.getFunctiondependees(); START if ("".equals(stmtDeps)) { END // We will add this function. So make sure it has an // initial comma. stmtDeps = ","; } String functionName = function.getTypeName(); if ( ! stmtDeps.contains("," + functionName + ",")) { stmtDeps += functionName + ","; catalogStmt.setFunctiondependees(stmtDeps); } } I would prefer `stmtDeps.isEmpty()`

Target:
private static void addStatementDependence(Function function, Statement catalogStmt) { String stmtDeps = catalogStmt.getFunctiondependees(); if (stmtDeps.isEmpty()) { // We will add this function. So make sure it has an // initial comma. stmtDeps = ","; } String functionName = function.getTypeName(); if ( ! stmtDeps.contains("," + functionName + ",")) { stmtDeps += functionName + ","; catalogStmt.setFunctiondependees(stmtDeps); } }
Source:
private static void addFunctionDependence(Function function, Procedure procedure, Statement catalogStmt) { String funcDeps = function.getStmtdependers(); START if ("".equals(funcDeps)) { END // We will add this procedure:statement pair. So make sure we have // an initial comma. funcDeps = ","; } String statementName = procedure.getTypeName() + ":" + catalogStmt.getTypeName(); if ( ! funcDeps.contains("," + statementName + ",")) { funcDeps = funcDeps + statementName + ","; function.setStmtdependers(funcDeps); } } I would prefer `funcDeps.isEmpty()`

Target:
private static void addFunctionDependence(Function function, Procedure procedure, Statement catalogStmt) { String funcDeps = function.getStmtdependers(); if (funcDeps.isEmpty()) { // We will add this procedure:statement pair. So make sure we have // an initial comma. Note that an empty set must be represented // by an empty string. We represent the set {pp:ss, qq:tt}, // where "pp" and "qq" are procedures and "ss" and "tt" are // statements in their procedures respectively, with // the string ",pp:ss,qq:tt,". If we search for "pp:ss" we will // never find "ppp:sss" by accident. // // Do to this, when we add something to string we start with a single // comma, and then add "qq:tt," at the end. funcDeps = ","; } String statementName = procedure.getTypeName() + ":" + catalogStmt.getTypeName(); if ( ! funcDeps.contains("," + statementName + ",")) { funcDeps = funcDeps + statementName + ","; function.setStmtdependers(funcDeps); } }
Source:
START public static void saveDefinedFunctions() { END for (String name : FunctionDescriptor.defined_functions) { FunctionDescriptor fd = FunctionDescriptor.by_LC_name.get(name); FunctionDescriptor.by_LC_name.remove(name); m_savedFunctionDfns.put(name, fd); } FunctionDescriptor.defined_functions.clear(); } This method seems equivalent to `deleteOldFunctions`?

Target:
public static void saveDefinedFunctions() { for (String name : FunctionDescriptor.defined_functions) { FunctionDescriptor fd = FunctionDescriptor.by_LC_name.get(name); assert(fd != null); FunctionDescriptor.by_LC_name.remove(name); m_savedFunctionDfns.put(name, fd); } FunctionDescriptor.defined_functions.clear(); }
Source:
public synchronized void onClusterStateChange(VersionedOperationMode mode) { START m_clusterMode = mode.getMode(); END switch (m_clusterMode) { case PAUSED: importLog.info("Cluster is paused shutting down all importers."); close(); importLog.info("Cluster is paused all importers shutdown."); break; case RUNNING: importLog.info("Cluster is resumed STARTING all importers."); resume(); importLog.info("Cluster is resumed STARTED all importers."); break; default: break; } } You dont need to keep this keeping copy of cluster mode somewhere inside is not good.

Target:
public synchronized void onClusterStateChange(VersionedOperationMode mode) { switch (mode.getMode()) { case PAUSED: importLog.info("Cluster is paused shutting down all importers."); close(); importLog.info("Cluster is paused all importers shutdown."); break; case RUNNING: importLog.info("Cluster is resumed STARTING all importers."); resume(); importLog.info("Cluster is resumed STARTED all importers."); break; default: break; } }
Source:
public CompleteTransactionMessage(long initiatorHSId, long coordinatorHSId, long txnId, boolean isReadOnly, int hash, boolean isRollback, boolean requiresAck, boolean isRestart, boolean isForReplay) { super(initiatorHSId, coordinatorHSId, txnId, 0, isReadOnly, isForReplay); m_hash = hash; setBit(ISROLLBACK, isRollback); setBit(REQUIRESACK, requiresAck); setBit(ISRESTART, isRestart); START m_isForReplica = true; END m_ackRequestedFromSender = false; } Why change the default value?

Target:
public CompleteTransactionMessage(long initiatorHSId, long coordinatorHSId, long txnId, boolean isReadOnly, int hash, boolean isRollback, boolean requiresAck, boolean isRestart, boolean isForReplay) { super(initiatorHSId, coordinatorHSId, txnId, 0, isReadOnly, isForReplay); m_hash = hash; setBit(ISROLLBACK, isRollback); setBit(REQUIRESACK, requiresAck); setBit(ISRESTART, isRestart); }
Source:
private CompleteTransactionMessage makeCompleteTxnMsg(boolean readOnly, boolean isRollback, boolean isRestart) { CompleteTransactionMessage msg = new CompleteTransactionMessage(0l, 0l, m_mpiTxnEgo.getTxnId(), readOnly, 0, isRollback, false, isRestart, false); START msg.setForReplica(false); END return msg; } If by default it's false, then you can remove it.

Target:
private CompleteTransactionMessage makeCompleteTxnMsg(boolean readOnly, boolean isRollback, boolean isRestart) { CompleteTransactionMessage msg = new CompleteTransactionMessage(0l, 0l, m_mpiTxnEgo.getTxnId(), readOnly, 0, isRollback, false, isRestart, false); return msg; }
Source:
public void close() throws InterruptedException, NoConnectionsException { while (m_processedCount.get() != m_totalRowCount.get()) { m_client.drain(); Thread.yield(); } START m_reinsertExecutor.shutdown(); END m_reinsertExecutor.awaitTermination(365, TimeUnit.DAYS); // Don't close the client because it may be shared with other loaders } only shutdown if its present.

Target:
public void close() throws InterruptedException, NoConnectionsException { while (m_processedCount.get() != m_totalRowCount.get()) { m_client.drain(); Thread.yield(); } if (m_reinsertExecutor != null) { m_reinsertExecutor.shutdown(); m_reinsertExecutor.awaitTermination(365, TimeUnit.DAYS); } // Don't close the client because it may be shared with other loaders }
Source:
public void testIndividualProcTimeout() throws IOException, ProcCallException, InterruptedException { // If the authentication information is // incorrect, shutdown will not succeed. // So, we need to set this in any case. // Feel free to reset it later on. START m_username="adminUser"; END m_password="password"; if (isValgrind() || isDebug()) { // Disable the memcheck/debug for this test, it takes too long return; } Client client; m_username = "adminUser"; m_password = "password"; client = getClient(); checkIndividualProcTimeout(client, true); m_username = "userWithAllProc"; m_password = "password"; client = getClient(); checkIndividualProcTimeout(client, false); } In this case, these member variables seem to be set to the same values immediately below... delete lines 440-441?

Target:
public void testIndividualProcTimeout() throws IOException, ProcCallException, InterruptedException { // If the authentication information is // incorrect, shutdown will not succeed. // So, we need to set this in any case. // Feel free to reset it later on. m_username="adminUser"; m_password="password"; if (isValgrind() || isDebug()) { // Disable the memcheck/debug for this test, it takes too long return; } Client client; client = getClient(); checkIndividualProcTimeout(client, true); m_username = "userWithAllProc"; m_password = "password"; client = getClient(); checkIndividualProcTimeout(client, false); }
Source:
protected void addCorrelationParameterValueExpression(AbstractExpression expr, List<AbstractExpression> pves) { START int paramIdx = AbstractParsedStmt.NEXT_PARAMETER_ID.getAndIncrement(); END m_parameterIdxList.add(paramIdx); ParameterValueExpression pve = new ParameterValueExpression(paramIdx, expr); pves.add(pve); } Hmm... parameter IDs should all be adjacent for the same statement, right? If there were concurrent planners that might not be the case and havoc could result. I think `NEXT_PARAMETER_ID` should be a normal (non-static) member of some object that is not shared by more than one thread. `QueryPlanner` seems to fit this description?

Target:
protected void addCorrelationParameterValueExpression(AbstractExpression expr, List<AbstractExpression> pves) { int paramIdx = AbstractParsedStmt.NEXT_PARAMETER_ID++; m_parameterIdxList.add(paramIdx); ParameterValueExpression pve = new ParameterValueExpression(paramIdx, expr); pves.add(pve); }
Source:
private void doInitiation(RejoinMessage message) { m_coordinatorHsId = message.m_sourceHSId; registerSnapshotMonitor(message.getSnapshotNonce()); long sinkHSId = m_dataSink.initialize(message.getSnapshotSourceCount(), message.getSnapshotBufferPool()); // respond to the coordinator with the sink HSID RejoinMessage msg = new RejoinMessage(m_mailbox.getHSId(), -1, sinkHSId); m_mailbox.send(m_coordinatorHsId, msg); m_taskQueue.offer(this); START m_taskQueue.setQueueDepthTracker(new QueueDepthTracker(m_partitionId)); END JOINLOG.info("P" + m_partitionId + " received initiation"); } Do we have to do this for RejoinProducer too?

Target:
private void doInitiation(RejoinMessage message) { m_coordinatorHsId = message.m_sourceHSId; registerSnapshotMonitor(message.getSnapshotNonce()); long sinkHSId = m_dataSink.initialize(message.getSnapshotSourceCount(), message.getSnapshotBufferPool()); // respond to the coordinator with the sink HSID RejoinMessage msg = new RejoinMessage(m_mailbox.getHSId(), -1, sinkHSId); m_mailbox.send(m_coordinatorHsId, msg); m_taskQueue.offer(this); JOINLOG.info("P" + m_partitionId + " received initiation"); }
Source:
private void doInitiation(RejoinMessage message) { m_coordinatorHsId = message.m_sourceHSId; registerSnapshotMonitor(message.getSnapshotNonce()); long sinkHSId = m_dataSink.initialize(message.getSnapshotSourceCount(), message.getSnapshotBufferPool()); // respond to the coordinator with the sink HSID RejoinMessage msg = new RejoinMessage(m_mailbox.getHSId(), -1, sinkHSId); m_mailbox.send(m_coordinatorHsId, msg); START m_taskQueue.setQueueDepthTracker(new QueueDepthTracker(m_partitionId)); END m_taskQueue.offer(this); JOINLOG.info("P" + m_partitionId + " received initiation"); } The `m_taskQueue` should already been initialized with a tracker by `BaseInitiator` at this point. If you are adding this because of some unit test failures, that might be because the unit tests construct `ElasticJoinProducer` without a real `BaseInitiator`. In that case, the proper place to set the tracker is in the unit tests. Maybe you can follow the starvation tracker initialization pattern because it is also used in the `SiteTaskerQueue`.

Target:
private void doInitiation(RejoinMessage message) { m_coordinatorHsId = message.m_sourceHSId; registerSnapshotMonitor(message.getSnapshotNonce()); long sinkHSId = m_dataSink.initialize(message.getSnapshotSourceCount(), message.getSnapshotBufferPool()); // respond to the coordinator with the sink HSID RejoinMessage msg = new RejoinMessage(m_mailbox.getHSId(), -1, sinkHSId); m_mailbox.send(m_coordinatorHsId, msg); m_taskQueue.offer(this); JOINLOG.info("P" + m_partitionId + " received initiation"); }
Source:
public String getVoltDBRootPath(PathsType.Voltdbroot path) { if (isRunningWithOldVerbs()) { return path.getPath(); } START try { END return m_nodeSettings.getVoltDBRoot().getCanonicalPath(); } catch (IOException e) { throw new SettingsException("failed to canonicalize voltdbroot"); } } Can include the path for which it failed to canonicalize. Something like ```Java File root = m_nodeSettings.getVoltDBRoot(); String path = voltdbRoot.getPath(); try { return root.getCanonicalPath(); } catch (IOException e) { throw new SettingsException("failed to canonicalize voltdbroot " + path + ". Reason: " + e.getMessage()); } ``` Similar recommendation for all other paths below - command log, snapshot, dr/export overflow and so forth.

Target:
public String getVoltDBRootPath(PathsType.Voltdbroot path) { if (isRunningWithOldVerbs()) { return path.getPath(); } return getVoltDBRootPath(); }
Source:
static public Test suite() throws IOException { // the suite made here will all be using the tests from this class MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestEmptySchema.class); // build up a project builder for the workload VoltProjectBuilder project = getBuilderForTest(); boolean success; LocalCluster config = new LocalCluster(true, "decimal-default.jar", 2, 3, 0, BackendTarget.NATIVE_EE_JNI); success = config.compile(project); assertTrue(success); START END // add this config to the set of tests to run builder.addServerConfig(config); return builder; } @zeemanhe @vittvolt Great suggestion!

Target:
static public Test suite() throws IOException { // the suite made here will all be using the tests from this class MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestEmptySchema.class); // build up a project builder for the workload VoltProjectBuilder project = getBuilderForTest(); boolean success; LocalCluster config = new LocalCluster("decimal-default.jar", 2, 1, 0, BackendTarget.NATIVE_EE_JNI); success = config.compile(project); assertTrue(success); // add this config to the set of tests to run builder.addServerConfig(config); return builder; }
Source:
public boolean equals(Object o) { START if (!(o instanceof ImportConfiguration)) { END return false; } ImportConfiguration other = (ImportConfiguration) o; return m_moduleProps.equals(other.m_moduleProps) && m_formatterBuilder.equals(other.m_formatterBuilder); } add if (o == this) return true;

Target:
public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof ImportConfiguration)) { return false; } ImportConfiguration other = (ImportConfiguration) o; return m_moduleProps.equals(other.m_moduleProps) && m_formatterBuilder.equals(other.m_formatterBuilder); }
Source:
public void shutdown(ShutdownInput shutDownInput) { if (isDebugEnabled()) { START debug(null, "shard ID: " + (m_shardId.trim().isEmpty()? "unknown" : m_shardId) END + ", shutdown reason: " + shutDownInput.getShutdownReason().name()); } if (ShutdownReason.TERMINATE.equals(shutDownInput.getShutdownReason())) { //The shard may be split or merged. checkpoint one last time commitCheckPoint(shutDownInput.getCheckpointer()); } } Not blocker: please put a space before the ?

Target:
public void shutdown(ShutdownInput shutDownInput) { if (isDebugEnabled()) { debug(null, "shard ID: " + m_shardId + ", shutdown reason: " + shutDownInput.getShutdownReason().name()); } if (ShutdownReason.TERMINATE.equals(shutDownInput.getShutdownReason())) { //The shard may be split or merged. checkpoint one last time commitCheckPoint(shutDownInput.getCheckpointer()); } }
Source:
void close() { try { m_reader.close(); START } catch (IOException e) { } END } Why not throw IOException and let caller handle and log etc.

Target:
public void close() { try { m_reader.close(); } catch (IOException e) { } }
Source:
START public static int get(String token) { END int type = reservedKeys.get(token, -1); if (type == -1) { return commandSet.get(token, -1); } return type; } This looks like it can go back to having package visibility now.

Target:
static int get(String token) { int type = reservedKeys.get(token, -1); if (type == -1) { return commandSet.get(token, -1); } return type; }