auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void shift(int n) { int rownum = getRowNum() + n; String msg = "Row[rownum="+getRowNum()+"] contains cell(s) included in a multi-cell array formula. " + "You cannot change part of an array."; for(Cell c : this){ ((XSSFCell)c).updateCellReferencesForShifting(msg); } setRowNum(rownum); }

Target:
protected void shift(int n) { int rownum = getRowNum() + n; String msg = "Row[rownum="+getRowNum()+"] contains cell(s) included in a multi-cell array formula. " + "You cannot change part of an array."; for(Cell c : this){ ((XSSFCell)c).updateCellReferencesForShifting(msg); } setRowNum(rownum); }
Source:
public void init() { Assert.notNull(serverUriResolver, "serverUriResolver must be configured."); IdSiteController controller = new LogoutIdSiteController(); controller.setServerUriResolver(serverUriResolver); controller.setCallbackUri(idSiteResultUri); controller.setIdSiteOrganizationResolver(idSiteOrganizationResolver); controller.setAlreadyLoggedInUri(nextUri); //this will not really have any affect on logout but we need to set it otherwise controller#init() will throw controller.init(); this.idSiteController = controller; }

Target:
public void init() { Assert.notNull(serverUriResolver, "serverUriResolver must be configured."); IdSiteController controller = new LogoutIdSiteController(); controller.setServerUriResolver(serverUriResolver); controller.setCallbackUri(idSiteResultUri); controller.setIdSiteOrganizationResolver(idSiteOrganizationResolver); controller.setAlreadyLoggedInUri(nextUri); //this will not really have any affect on logout but we need to set it otherwise controller#init() will throw controller.init(); this.idSiteController = controller; super.init(); }
Source:
public Account removeGroup(String hrefOrName) { GroupMembership groupMembership = null; for (GroupMembership aGroupMembership : getGroupMemberships()) { if (aGroupMembership.getGroup().getName().equalsIgnoreCase(hrefOrName) || aGroupMembership.getGroup().getHref().equalsIgnoreCase(hrefOrName)) { groupMembership = aGroupMembership; break; } } if (groupMembership != null){ groupMembership.delete(); } else { throw new IllegalStateException("This account does not belong to the specified group."); } return this; }

Target:
public Account removeGroup(String hrefOrName) { GroupMembership groupMembership = null; for (GroupMembership aGroupMembership : getGroupMemberships()) { if (aGroupMembership.getGroup().getName().equals(hrefOrName) || aGroupMembership.getGroup().getHref().equals(hrefOrName)) { groupMembership = aGroupMembership; break; } } if (groupMembership != null){ groupMembership.delete(); } else { throw new IllegalStateException("This account does not belong to the specified group."); } return this; }
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(); 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; }

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 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 if(gadgetsLoaded) { 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; }

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 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(); } else { return orderIsDeterministic; } }

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() { ClientConfig cc = new ClientConfig(m_username, m_password); cc.setProcedureCallTimeout(10 * 60 * 1000); // 10 min return cc; }

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()); } scheduleTaskFor(m_pbd.getNonce(), ()->deleteOldSegments(), MIN_DELAY); }

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 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. cleanupStaleBuffers(); }

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:
public void updateCatalog(Table table, long genId) { m_es.execute(new Runnable() { public void run() { if (genId != m_previousGenId) { 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; } } }); }

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:
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); headerBuf.putLong(crc.getValue()); headerBuf.putInt(size); headerBuf.putInt(flag); headerBuf.order(ByteOrder.BIG_ENDIAN); }

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())); } catch (Exception e) { // No-op } }

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:
@Override 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")); }

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:
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); } return startsWithObject.compare(session, leftValue); }

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:
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 }

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:
private synchronized 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); }

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:
private synchronized void ackImpl(long uso, Exception ackCallStack) { 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; } } }

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(); if ("".equals(stmtDeps)) { // 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); } }

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(); if ("".equals(funcDeps)) { // 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); } }

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:
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); m_isForReplica = true; m_ackRequestedFromSender = false; }

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:
public void close() throws InterruptedException, NoConnectionsException { while (m_processedCount.get() != m_totalRowCount.get()) { m_client.drain(); Thread.yield(); } m_reinsertExecutor.shutdown(); m_reinsertExecutor.awaitTermination(365, TimeUnit.DAYS); // Don't close the client because it may be shared with other loaders }

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. m_username="adminUser"; 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); }

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:
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); m_taskQueue.setQueueDepthTracker(new QueueDepthTracker(m_partitionId)); JOINLOG.info("P" + m_partitionId + " received initiation"); }

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); m_taskQueue.setQueueDepthTracker(new QueueDepthTracker(m_partitionId)); m_taskQueue.offer(this); JOINLOG.info("P" + m_partitionId + " received initiation"); }

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:
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); // add this config to the set of tests to run builder.addServerConfig(config); return builder; }

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 void shutdown(ShutdownInput shutDownInput) { if (isDebugEnabled()) { debug(null, "shard ID: " + (m_shardId.trim().isEmpty()? "unknown" : 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()); } }

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:
public final void convertToHeapBuffer() { if (m_buffer.isDirect()) { // Either this was allocated by the stored procedure as a direct buffer cached // from the EE. If the second, we need to make a copy so the EE can reuse the // buffer fir the next stored procedure. ByteBuffer heapBuffer = ByteBuffer.allocate(m_buffer.limit()); m_buffer.position(0); heapBuffer.put(m_buffer); heapBuffer.position(heapBuffer.limit()); } }

Target:
public final void convertToHeapBuffer() { if (m_buffer.isDirect()) { // Either this was allocated by the stored procedure as a direct buffer or this // is cached from the EE. If the second, we need to make a copy so the EE can // reuse the buffer for the next stored procedure. ByteBuffer heapBuffer = ByteBuffer.allocate(m_buffer.limit()); m_buffer.position(0); heapBuffer.put(m_buffer); m_buffer = heapBuffer; } }
Source:
private void updatePartitioning(VoltTable vt) { List<Integer> ketSet = new ArrayList<Integer>(); while (vt.advanceRow()) { //check for mock unit test if (vt.getColumnCount() == 2) { Integer key = (int)(vt.getLong("PARTITION_KEY")); ketSet.add(key); } } m_partitionKeys.set(ImmutableSet.copyOf(ketSet)); }

Target:
private void updatePartitioning(VoltTable vt) { List<Integer> keySet = new ArrayList<Integer>(); while (vt.advanceRow()) { //check for mock unit test if (vt.getColumnCount() == 2) { Integer key = (int)(vt.getLong("PARTITION_KEY")); keySet.add(key); } } m_partitionKeys.set(ImmutableSet.copyOf(keySet)); }
Source:
public void clientCallback(ClientResponse clientResponse) throws Exception { if (clientResponse.getStatus() == ClientResponse.SUCCESS) { synchronized (Distributer.this) { VoltTable results[] = clientResponse.getResults(); if (results != null && results.length > 0) { updatePartitioning(results[0]); } } } m_partitionUpdateStatus.set(clientResponse); if (m_latch != null) { m_latch.countDown(); } }

Target:
public void clientCallback(ClientResponse clientResponse) throws Exception { if (clientResponse.getStatus() == ClientResponse.SUCCESS) { VoltTable results[] = clientResponse.getResults(); if (results != null && results.length > 0) { updatePartitioning(results[0]); } } m_partitionUpdateStatus.set(clientResponse); if (m_latch != null) { m_latch.countDown(); } }
Source:
void doCommonSPICompleteActions() { // Mark the transaction state as DONE m_txnState.setDone(); // Set the truncation handle here instead of when processing the // messages in the SpScheduler to avoid any races of transaction // completing on the Site and receiving the messages in the Scheduler // for MPs. // // We have to use the spHandle from the first fragment, not from the // current message because it may be out of order if we do so. If we use // the spHandle from the current completion message, it may be advancing // the truncation handle before previous SPs are finished. if (m_txnDoneNotification != null) { m_txnDoneNotification.transactionDone(m_txnState.m_spHandle); } // Flush us out of the head of the TransactionTaskQueue. Null check so we're reusable // for live rejoin replay if (m_queue != null) { m_queue.flush(getTxnId()); } }

Target:
void doCommonSPICompleteActions() { // Mark the transaction state as DONE m_txnState.setDone(); // Flush us out of the head of the TransactionTaskQueue. Null check so we're reusable // for live rejoin replay if (m_queue != null) { m_queue.flush(getTxnId()); } }
Source:
private PBDSegment peekFirstSegment() { Map.Entry<Long, PBDSegment> entry = m_segments.firstEntry(); return (entry!=null) ? entry.getValue() : null; }

Target:
private PBDSegment peekFirstSegment() { Map.Entry<Long, PBDSegment> entry = m_segments.firstEntry(); // entry may be null in ctor and while we are manipulating m_segments in addSegment, for example return (entry==null) ? null : entry.getValue(); }
Source:
public static byte[] fileToBytes(File path) throws IOException { byte[] bytes = null; try { bytes = Files.readAllBytes(path.toPath()); } catch (IOException ioe) { throw new IOException("File " + path.getAbsolutePath() + " is empty"); } return bytes; }

Target:
public static byte[] fileToBytes(File path) throws IOException { return Files.readAllBytes(path.toPath()); }
Source:
public void offerSp(InitiateResponseMessage msg, boolean isLeader, long handle) { // System.out.println(String.format("Leader %s, truncation handle %d, replica truncation handle %d", // Boolean.toString(isLeader), handle, m_lastSpTruncationHandle)); long truncationHandle = m_lastSpTruncationHandle; if (isLeader) { truncationHandle = handle; } if (msg.getSpHandle() >= truncationHandle || truncationHandle == Long.MIN_VALUE) { m_mailbox.send(msg.getInitiatorHSId(), msg); } else { m_shortCircuitReadSp.add(new Item(msg)); } releaseShortCircuitRead(truncationHandle, IS_SP); }

Target:
public void offerSp(InitiateResponseMessage msg, boolean isLeader, long handle) { // System.out.println(String.format("Leader %s, truncation handle %d, replica truncation handle %d", // Boolean.toString(isLeader), handle, m_lastSpTruncationHandle)); long truncationHandle = m_lastSpTruncationHandle; if (isLeader) { truncationHandle = handle; } if (msg.getSpHandle() >= truncationHandle) { m_mailbox.send(msg.getInitiatorHSId(), msg); } else { m_shortCircuitReadSp.add(new Item(msg)); } releaseShortCircuitRead(truncationHandle, IS_SP); }
Source:
private void checkProcStatistics(Client client) throws NoConnectionsException, IOException, ProcCallException { VoltTable vt; vt = client.callProcedure("@Statistics", "PROCEDUREPROFILE", 1).getResults()[0]; System.out.println(vt.toString()); }

Target:
private void checkProcStatistics(Client client) throws NoConnectionsException, IOException, ProcCallException { VoltTable vt; vt = client.callProcedure("@Statistics", "PROCEDUREPROFILE", 1).getResults()[0]; //System.out.println(vt.toString()); }
Source:
public void shutdown() throws InterruptedException { for (VoltNetwork vn : m_networks) { vn.shutdown(); } // end "Reverse DNS lookups" thread before shutdown ReverseDNSCache.m_es.shutdown(); }

Target:
public void shutdown() throws InterruptedException { for (VoltNetwork vn : m_networks) { vn.shutdown(); } }
Source:
public static byte[] compressJSONString(String data) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length()); GZIPOutputStream gzip = new GZIPOutputStream(bos); gzip.write(data.getBytes(StandardCharsets.UTF_8)); gzip.close(); byte[] compressed = bos.toByteArray(); bos.close(); return compressed; }

Target:
public static byte[] compressJSONString(String data) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length()); try (GZIPOutputStream gzip = new GZIPOutputStream(bos)) { gzip.write(data.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw e; } return bos.toByteArray(); }
Source:
void expandConditions() { expandConditions(whereExpressions, false); for (HsqlArrayList whereExpression : whereExpressions) { if (whereExpression.size() > whereExpressionElementsUpperBound) { // If the query's where clause is composed of 240+ predicate expressions, when parsing these // expressions, due to mutual recursion, thread stack can grow to it's maximum capacity, // resulting in stack overflow error. The optimal solution to avoid this is to convert the // mutual recursion into tail-recursion or iterative approach. Though the change needed // are at multiple places like generating unique id for the expression during construction // of volt XML elements and converting the expression tree for the plan to json-string. // So at present guard against query whose where clause has more than 232 predicates. String msg = "Limit of predicate expressions in \"where\" clause exceeded the maximum limit of " + whereExpressionElementsUpperBound + " predicates, predicates detected: " + whereExpression.size() + ". Reduce the number of predicates in the \"where\" clause to " + whereExpressionElementsUpperBound; throw new HsqlException(msg, "", ErrorCode.X_47002); } } expandConditions(joinExpressions, false); }

Target:
void expandConditions() { expandConditions(whereExpressions, false); expandConditions(joinExpressions, false); }
Source:
public void shutdown(ShutdownInput shutDownInput) { if (shutDownInput.getShutdownReason().equals(ShutdownReason.TERMINATE)) { //The shard may be split or merged. checkpoint one last time commitCheckPoint(shutDownInput.getCheckpointer()); } }

Target:
public void shutdown(ShutdownInput shutDownInput) { if (ShutdownReason.TERMINATE.equals(shutDownInput.getShutdownReason())) { //The shard may be split or merged. checkpoint one last time commitCheckPoint(shutDownInput.getCheckpointer()); } }
Source:
public HTTPClientInterface() { final ClientResponseImpl r = new ClientResponseImpl(ClientResponse.CONNECTION_TIMEOUT, new VoltTable[0], "Request Timeout"); m_timeoutResponse = r.toJSONString(); m_closeAllExecutor = CoreUtils.getSingleThreadExecutor("HttpClientInterface-closeAll"); // STEBUG remove m_servicePrincipal = getAuthSystem().getServicePrincipal(); m_spnegoEnabled = m_servicePrincipal != null && !m_servicePrincipal.isEmpty(); }

Target:
public HTTPClientInterface() { final ClientResponseImpl r = new ClientResponseImpl(ClientResponse.CONNECTION_TIMEOUT, new VoltTable[0], "Request Timeout"); m_timeoutResponse = r.toJSONString(); m_servicePrincipal = getAuthSystem().getServicePrincipal(); m_spnegoEnabled = m_servicePrincipal != null && !m_servicePrincipal.isEmpty(); }
Source:
public void goOnline() { ReadOnlyStoreStatusValidation validation = validateReadOnlyStoreStatusBeforeGoingOnline(); if (validation.readyToGoOnline) { createOnlineServices(); startOnlineServices(); getMetadataStore().setOfflineState(false); } if (validation.e != null) { throw new VoldemortException("Problem while going online!", validation.e); } }

Target:
public void goOnline() { ReadOnlyStoreStatusValidation validation = validateReadOnlyStoreStatusBeforeGoingOnline(); if (validation.readyToGoOnline) { getMetadataStore().setOfflineState(false); createOnlineServices(); startOnlineServices(); } if (validation.e != null) { throw new VoldemortException("Problem while going online!", validation.e); } }
Source:
public static String writeSingleClientConfigAvro(Properties props) { // FIXME: This sucks. We shouldn't be manually manipulating json... String avroConfig = new String(); Boolean firstProp = true; for(String key: props.stringPropertyNames()) { if(firstProp) { firstProp = false; } else { avroConfig = avroConfig + ",\n"; } avroConfig = avroConfig + "\t\t\"" + key + "\": \"" + props.getProperty(key) + "\""; } if(avroConfig.isEmpty()) { return "{}"; } else { return "{\n" + avroConfig + "\n\t}"; } }

Target:
public static String writeSingleClientConfigAvro(Properties props) { // TODO: Use a dedicated json lib. We shouldn't be manually manipulating json... String avroConfig = ""; Boolean firstProp = true; for(String key: props.stringPropertyNames()) { if(firstProp) { firstProp = false; } else { avroConfig = avroConfig + ",\n"; } avroConfig = avroConfig + "\t\t\"" + key + "\": \"" + props.getProperty(key) + "\""; } if(avroConfig.isEmpty()) { return "{}"; } else { return "{\n" + avroConfig + "\n\t}"; } }
Source:
void createTableDuplicateName() { // Arrange String tableName = testResourceNamer.randomName("test", 20); TableProperties tableProperties = new TableProperties().setTableName(tableName); createTable(tableName); String requestId = testResourceNamer.randomUuid(); // Act & Assert StepVerifier.create(azureTable.getTables().createWithResponseAsync(tableProperties, requestId, ResponseFormat.RETURN_CONTENT, null, Context.NONE)) .expectError(com.azure.data.tables.implementation.models.TableServiceErrorException.class) .verify(); }

Target:
void createTableDuplicateName() { // Arrange String tableName = testResourceNamer.randomName("test", 20); TableProperties tableProperties = new TableProperties().setTableName(tableName); createTable(tableName); String requestId = testResourceNamer.randomUuid(); // Act & Assert StepVerifier.create(azureTable.getTables().createWithResponseAsync(tableProperties, requestId, ResponseFormat.RETURN_CONTENT, null, Context.NONE)) .expectError(TableServiceErrorException.class) .verify(); }
Source:
public List<TokenCredential> getCredentials() { return tokenCredentials; }

Target:
public List<TokenCredential> getCredentials() { return super.getCredentials(); }
Source:
private Mono<AmqpSendLink> getSendLink() { return connectionProcessor .flatMap(connection -> { String linkName = entityName; if (!CoreUtils.isNullOrEmpty(viaEntityName)) { linkName = "VIA-".concat(viaEntityName); return connection.createSendLink(linkName, viaEntityName, retryOptions, entityName); } else { return connection.createSendLink(linkName, entityName, retryOptions, null); } }) .doOnNext(next -> linkName.compareAndSet(null, next.getLinkName())); }

Target:
private Mono<AmqpSendLink> getSendLink() { return connectionProcessor .flatMap(connection -> { if (!CoreUtils.isNullOrEmpty(viaEntityName)) { return connection.createSendLink("VIA-".concat(viaEntityName), viaEntityName, retryOptions, entityName); } else { return connection.createSendLink(entityName, entityName, retryOptions, null); } }) .doOnNext(next -> linkName.compareAndSet(null, next.getLinkName())); }
Source:
public void createTable() { TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder() .connectionString("connectionString") .buildAsyncClient(); tableServiceAsyncClient.createTable("OfficeSupplies").subscribe( Void -> {}, error -> logger.error("There was an error creating the table. Error: " + error), () -> logger.info("Table creation successful.")); }

Target:
public void createTable() { TableServiceAsyncClient tableServiceAsyncClient = new TableServiceClientBuilder() .connectionString("connectionString") .buildAsyncClient(); tableServiceAsyncClient.createTable("OfficeSupplies").subscribe( Void -> { }, error -> System.err.println("There was an error creating the table. Error: " + error), () -> System.out.println("Table creation successful.")); }
Source:
private void performRecoveredIndexDropActions() { indexesToDropAfterCompletedRecovery.values().forEach( index -> { try { index.drop(); } catch ( Exception e ) { // This is OK to get during recovery because the underlying index can be in any unknown state // while we're recovering. Let's just move on to closing it instead. try { index.close(); } catch ( IOException closeException ) { // This is OK for the same reason as above e.addSuppressed( closeException ); } } } ); indexesToDropAfterCompletedRecovery.clear(); }

Target:
private void performRecoveredIndexDropActions() { indexesToDropAfterCompletedRecovery.values().forEach( index -> { try { index.drop(); } catch ( Exception e ) { // This is OK to get during recovery because the underlying index can be in any unknown state // while we're recovering. Let's just move on to closing it instead. try { index.close(); } catch ( IOException closeException ) { // This is OK for the same reason as above } } } ); indexesToDropAfterCompletedRecovery.clear(); }
Source:
void shouldFailWithNonExistentProviderName( IndexCreator creator ) throws KernelException { // given SchemaWrite schemaWrite = schemaWriteInNewTransaction(); // when try { schemaWrite.indexCreate( forLabel( 0, 0 ), "something-completely-different" ); fail( "Should have failed" ); } catch ( IllegalArgumentException e ) { // then good } }

Target:
void shouldFailWithNonExistentProviderName( IndexCreator creator ) throws KernelException { // given SchemaWrite schemaWrite = schemaWriteInNewTransaction(); // when try { creator.create( schemaWrite, forLabel( 0, 0 ), "something-completely-different" ); fail( "Should have failed" ); } catch ( IllegalArgumentException e ) { // then good } }
Source:
private TemporalValue attachTimeZone( TemporalValue temporal, ZoneId zoneIdToAttach ) { if ( temporal.isSupported( ChronoField.MONTH_OF_YEAR ) ) { // turn local date time into date time return datetime( ZonedDateTime.of( temporal.getDatePart(), temporal.getLocalTimePart(), zoneIdToAttach ) ); } else { // turn local time into time if ( zoneIdToAttach instanceof ZoneOffset ) { return time( OffsetTime.of( temporal.getLocalTimePart(), (ZoneOffset) zoneIdToAttach ) ); } else { throw new UnsupportedTemporalUnitException( "Should only attach offsets to local times, not zone ids." ); } } }

Target:
private TemporalValue attachTimeZone( TemporalValue temporal, ZoneId zoneIdToAttach ) { if ( temporal.isSupported( ChronoField.MONTH_OF_YEAR ) ) { // turn local date time into date time return datetime( ZonedDateTime.of( temporal.getDatePart(), temporal.getLocalTimePart(), zoneIdToAttach ) ); } else { // turn local time into time if ( zoneIdToAttach instanceof ZoneOffset ) { return time( OffsetTime.of( temporal.getLocalTimePart(), (ZoneOffset) zoneIdToAttach ) ); } else { throw new IllegalStateException( "Should only attach offsets to local times, not zone ids." ); } } }
Source:
public static TimeValue parse( CharSequence text, Supplier<ZoneId> defaultZone, CSVHeaderInformation fieldsFromHeader ) { if ( fieldsFromHeader != null ) { if ( !(fieldsFromHeader instanceof TimeCSVHeaderInformation) ) { throw new TemporalParseException( "Wrong header information type: " + fieldsFromHeader ); } // Override defaultZone defaultZone = ((TimeCSVHeaderInformation) fieldsFromHeader).zoneSupplier( defaultZone ); } return parse( TimeValue.class, PATTERN, TimeValue::parse, text, defaultZone ); }

Target:
public static TimeValue parse( CharSequence text, Supplier<ZoneId> defaultZone, CSVHeaderInformation fieldsFromHeader ) { if ( fieldsFromHeader != null ) { if ( !(fieldsFromHeader instanceof TimeCSVHeaderInformation) ) { throw new IllegalStateException( "Wrong header information type: " + fieldsFromHeader ); } // Override defaultZone defaultZone = ((TimeCSVHeaderInformation) fieldsFromHeader).zoneSupplier( defaultZone ); } return parse( TimeValue.class, PATTERN, TimeValue::parse, text, defaultZone ); }
Source:
public static PointValue parse( CharSequence text, AnyValue[] fieldsFromHeader ) { AnyValue[] fieldsFromData = parseIntoArray( text ); if ( fieldsFromHeader != null ) { //It is given that fieldsFromData.length == fieldsFromHeader.length because parseIntoArray produces fixed length arrays // Merge InputFields: Data fields override header fields for ( int i = 0; i < fieldsFromData.length; i++ ) { if ( fieldsFromData[i] == null ) { fieldsFromData[i] = fieldsFromHeader[i]; } } } return fromInputFields( fieldsFromData ); }

Target:
public static PointValue parse( CharSequence text, AnyValue[] fieldsFromHeader ) { AnyValue[] fieldsFromData = parseIntoArray( text ); if ( fieldsFromHeader != null ) { // If fieldsFromHeader comes from parseIntoArray it is given that fieldsFromData.length == fieldsFromHeader.length // because parseIntoArray produces fixed length arrays assert fieldsFromData.length == fieldsFromHeader.length; // Merge InputFields: Data fields override header fields for ( int i = 0; i < fieldsFromData.length; i++ ) { if ( fieldsFromData[i] == null ) { fieldsFromData[i] = fieldsFromHeader[i]; } } } return fromInputFields( fieldsFromData ); }
Source:
public void shouldGetErrorWhenUsingCreateUniqueWhenCypherVersionIs3_3() { // expect exception thrown.expect( QueryExecutionException.class ); thrown.expectMessage( "CREATE UNIQUE is no longer supported. You can achieve the same result using MERGE"); // when Result result = db().execute( "CYPHER 3.3 MATCH (b) WITH b LIMIT 1 CREATE UNIQUE (b)-[:REL]->()" ); }

Target:
public void shouldGetErrorWhenUsingCreateUniqueWhenCypherVersionIs3_3() { // expect exception thrown.expect( QueryExecutionException.class ); thrown.expectMessage( "CREATE UNIQUE is no longer supported. You can achieve the same result using MERGE"); // when db().execute( "CYPHER 3.3 MATCH (b) WITH b LIMIT 1 CREATE UNIQUE (b)-[:REL]->()" ); }
Source:
public Iterator<T> iterator() { if ( count == -1 ) { // This should never happen in generated code but is here to simplify debugging if used incorrectly throw new IllegalStateException( "sort() needs to be called before requesting an iterator" ); } return new Iterator<T>() { private int cursor = count; @Override public boolean hasNext() { return cursor > 0; } @Override @SuppressWarnings( "unchecked" ) public T next() { if ( !hasNext() ) { throw new NoSuchElementException(); } --cursor; return (T) array[cursor]; } }; }

Target:
public Iterator<T> iterator() { if ( count == -1 ) { // This should never happen in generated code but is here to simplify debugging if used incorrectly throw new IllegalStateException( "sort() needs to be called before requesting an iterator" ); } return new Iterator<T>() { private int cursor = count; @Override public boolean hasNext() { return cursor > 0; } @Override @SuppressWarnings( "unchecked" ) public T next() { if ( !hasNext() ) { throw new NoSuchElementException(); } int offset = --cursor; return (T) array[offset]; } }; }
Source:
private static TemporalType find( int temporalType ) { if ( temporalType < TYPES.length ) { return TYPES[temporalType]; } else { // Kernel code requires no exceptions in deeper PropertyChain processing of corrupt/invalid data return TEMPORAL_INVALID; } }

Target:
private static TemporalType find( int temporalType ) { if ( temporalType < TYPES.length && temporalType >= 0 ) { return TYPES[temporalType]; } else { // Kernel code requires no exceptions in deeper PropertyChain processing of corrupt/invalid data return TEMPORAL_INVALID; } }
Source:
public void releaseCursor( Cursor cursor ) { if ( cursorsInUse > 0 ) { if ( TRACK_CURSORS ) { cursorsOpenCloseCalls.remove( cursor ); } cursorsInUse--; } }

Target:
public void releaseCursor( Cursor cursor ) { //System.out.println("REL "+ cursor + "@" + System.identityHashCode( cursor )); cursorsOpenCloseCalls.remove( cursor ); // TODO: Test this }
Source:
void single( long reference, Read read ) { if ( getId() != NO_ID ) { reset(); } if ( pageCursor == null ) { pageCursor = read.nodePage( reference ); } this.next = reference; //This marks the cursor as a "single cursor" this.highMark = NO_ID; this.read = read; this.hasChanges = HasChanges.MAYBE; this.addedNodes = emptySet(); this.single = true; }

Target:
void single( long reference, Read read ) { if ( getId() != NO_ID ) { reset(); } if ( pageCursor == null ) { pageCursor = read.nodePage( reference ); } this.next = reference; //This marks the cursor as a "single cursor" this.highMark = NO_ID; this.read = read; this.hasChanges = HasChanges.MAYBE; this.addedNodes = emptySet(); }
Source:
private void placeCursorAtActualKey( PageCursor cursor, int pos, Type type ) { // Set cursor to correct place in offset array int keyPosOffset = keyPosOffset( pos, type ); cursor.setOffset( keyPosOffset ); // Read actual offset to key int keyOffset = readKeyOffset( cursor ); // Verify offset is reasonable if ( keyOffset > pageSize ) { cursor.setCursorException( "Tried to read key on offset " + keyOffset + ". Page size is " + pageSize ); } // Set cursor to actual offset cursor.setOffset( keyOffset ); }

Target:
private void placeCursorAtActualKey( PageCursor cursor, int pos, Type type ) { // Set cursor to correct place in offset array int keyPosOffset = keyPosOffset( pos, type ); cursor.setOffset( keyPosOffset ); // Read actual offset to key int keyOffset = readKeyOffset( cursor ); // Verify offset is reasonable if ( keyOffset > pageSize || keyOffset < 0 ) { cursor.setCursorException( "Tried to read key on offset " + keyOffset + ". Page size is " + pageSize ); } // Set cursor to actual offset cursor.setOffset( keyOffset ); }