auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void nonRackAwareAllocationTest() throws JSONException, IOException { int replicaCountPerDataCenter = 2; long replicaCapacityInBytes = 100 * 1024 * 1024 * 1024L; TestUtils.TestHardwareLayout testHardwareLayout = new TestUtils.TestHardwareLayout("Alpha"); PartitionLayout partitionLayout = new PartitionLayout(testHardwareLayout.getHardwareLayout()); ClusterMapManager clusterMapManager = new ClusterMapManager(partitionLayout); List<PartitionId> allocatedPartitions; allocatedPartitions = clusterMapManager.allocatePartitions(5, replicaCountPerDataCenter, replicaCapacityInBytes, true); assertEquals(allocatedPartitions.size(), 5); assertEquals(clusterMapManager.getWritablePartitionIds().size(), 5); allocatedPartitions = clusterMapManager.allocatePartitions(1000 * 1000, replicaCountPerDataCenter, replicaCapacityInBytes, true); assertEquals(allocatedPartitions.size() + 5, clusterMapManager.getWritablePartitionIds().size()); System.out.println(freeCapacityDump(clusterMapManager, testHardwareLayout.getHardwareLayout())); allocatedPartitions = clusterMapManager.allocatePartitions(5, replicaCountPerDataCenter, replicaCapacityInBytes, true); assertEquals(allocatedPartitions.size(), 0); }

Target:
public void nonRackAwareAllocationTest() throws JSONException, IOException { int replicaCountPerDataCenter = 2; long replicaCapacityInBytes = 100 * 1024 * 1024 * 1024L; TestUtils.TestHardwareLayout testHardwareLayout = new TestUtils.TestHardwareLayout("Alpha"); PartitionLayout partitionLayout = new PartitionLayout(testHardwareLayout.getHardwareLayout()); ClusterMapManager clusterMapManager = new ClusterMapManager(partitionLayout); List<PartitionId> allocatedPartitions; try { clusterMapManager.allocatePartitions(5, replicaCountPerDataCenter, replicaCapacityInBytes, false); Assert.fail("allocatePartitions should not succeed when datacenters are missing rack info " + "and retryIfNotRackAware is false"); } catch (IllegalArgumentException e) { } allocatedPartitions = clusterMapManager.allocatePartitions(5, replicaCountPerDataCenter, replicaCapacityInBytes, true); assertEquals(allocatedPartitions.size(), 5); assertEquals(clusterMapManager.getWritablePartitionIds().size(), 5); allocatedPartitions = clusterMapManager.allocatePartitions(1000 * 1000, replicaCountPerDataCenter, replicaCapacityInBytes, true); assertEquals(allocatedPartitions.size() + 5, clusterMapManager.getWritablePartitionIds().size()); System.out.println(freeCapacityDump(clusterMapManager, testHardwareLayout.getHardwareLayout())); allocatedPartitions = clusterMapManager.allocatePartitions(5, replicaCountPerDataCenter, replicaCapacityInBytes, true); assertEquals(allocatedPartitions.size(), 0); }
Source:
public void scan(HttpMessage msg, String param, String value) { SinkDetectionStorage storage = getStorage(); List<HttpMessage> possibleSinks = storage.getPossibleSinksForValue(value); try { HttpMessage inputMsg = msg.cloneRequest(); String injectedValue = getRandomString(); this.setParameter(inputMsg, param, injectedValue); sendAndReceive(inputMsg, false); for (HttpMessage possibleSink : possibleSinks) { if (inputMsg.hashCode() != possibleSink.hashCode()) { HttpMessage possibleSink1 = possibleSink.cloneRequest(); sendAndReceive(possibleSink1, false); if (possibleSink1.getResponseBody().toString().contains(injectedValue)) { ParamSinksUtils.setSinkForSource(msg, param, possibleSink1); } } } } catch (Exception e) { log.error(e.getMessage(), e); } }

Target:
public void scan(HttpMessage msg, String param, String value) { SinkDetectionStorage storage = getStorage(); Set<HttpMessage> possibleSinks = storage.getPossibleSinksForValue(value); try { HttpMessage inputMsg = msg.cloneRequest(); String injectedValue = getRandomString(); this.setParameter(inputMsg, param, injectedValue); sendAndReceive(inputMsg, false); for (HttpMessage possibleSink : possibleSinks) { if (inputMsg.hashCode() != possibleSink.hashCode()) { HttpMessage possibleSinkClone = possibleSink.cloneRequest(); sendAndReceive(possibleSinkClone, false); if (possibleSinkClone.getResponseBody().toString().contains(injectedValue)) { ParamSinksUtils.setSinkForSource(msg, param, possibleSinkClone); } } } } catch (Exception e) { log.error(e.getMessage(), e); } }
Source:
private int getSectionOver(Vector2i mousePos) { logger.info(mousePos.toString()); mousePos.x -= radius; mousePos.y -= radius; logger.info(mousePos.toString()); double angle = Math.atan2(mousePos.y(), mousePos.y()); logger.info(angle + " ang"); angle += angle < 0 ? Math.PI * 2 : 0; return (int) Math.floor(angle * 1.5); }

Target:
private int getSectionOver(Vector2i mousePos) { mousePos.x -= radius; mousePos.y -= radius; double angle = Math.atan2(mousePos.y(), mousePos.x()); angle = angle < 0 ? angle + Math.PI * 2 : angle; double dist = Math.sqrt(mousePos.x() * mousePos.x() + mousePos.y() * mousePos.y()); if (dist < radius / 2 || dist > radius) { return -1; } return (int) Math.floor(angle / sectionAngle); }
Source:
private static Date calculateDefaultDueDate() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1);; return new Date(cal.getTimeInMillis()); }

Target:
private static DateTime calculateDefaultDueDate() { Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1); return new DateTime(cal.getTimeInMillis()); }
Source:
protected Shell getShell(ExecutionEvent event) { IWorkbenchPart part = (IWorkbenchPart) ((IEvaluationContext) event .getApplicationContext()).getRoot().getVariable("activePart"); return part.getSite().getShell(); }

Target:
protected Shell getShell(ExecutionEvent event) throws ExecutionException { return HandlerUtil.getActiveShellChecked(event); }
Source:
private void checkMasterStatus() { try { if (conf.getBoolVar(TajoConf.ConfVars.TAJO_MASTER_HA_ENABLE)) { if (!HAServiceUtil.isMasterAlive(conf.get(TajoConf.ConfVars.TAJO_MASTER_CLIENT_RPC_ADDRESS .varname), conf)) { String baseDatabase = client.getBaseDatabase(); conf.set(ConfVars.TAJO_MASTER_CLIENT_RPC_ADDRESS.varname, HAServiceUtil.getMasterClientName(conf)); client.close(); commands.clear(); client = new TajoClient(conf, baseDatabase); context.setCurrentDatabase(client.getCurrentDatabase()); initHistory(); initCommands(); } } } catch (Exception e) { } }

Target:
private void checkMasterStatus() throws IOException, ServiceException { String sessionId = client.getSessionId() != null ? client.getSessionId().getId() : null; client = TajoHAClientUtil.getTajoClient(conf, client, context); if(sessionId != null && (client.getSessionId() == null || !sessionId.equals(client.getSessionId().getId()))) { commands.clear(); initHistory(); initCommands(); } }
Source:
public void startReplicationService() throws IOException { this.replicationSink = new ReplicationSink(this.conf); this.server.getChoreService().scheduleChore( new ReplicationStatisticsChore("ReplicationSinkStatistics", server, 1000 * statsPeriodInSecond)); }

Target:
public void startReplicationService() throws IOException { this.replicationSink = new ReplicationSink(this.conf); this.server.getChoreService().scheduleChore( new ReplicationStatisticsChore("ReplicationSinkStatistics", server, (int) TimeUnit.SECONDS.toMillis(statsPeriodInSecond))); }
Source:
public void basicConsume(String queue, String address, boolean autoAck, Handler<AsyncResult<Void>> resultHandler) { forChannel(resultHandler, channel -> { channel.basicConsume(queue, new ConsumerHandler(vertx, channel, includeProperties, autoAck, ar -> { if (ar.succeeded()) { vertx.eventBus().send(address, ar.result()); } else { log.error("Exception occurred inside rabbitmq service consumer.", ar.cause()); } })); return null; }); }

Target:
public void basicConsume(String queue, String address, boolean autoAck, Handler<AsyncResult<Void>> resultHandler) { forChannel(resultHandler, channel -> { channel.basicConsume(queue, autoAck, new ConsumerHandler(vertx, channel, includeProperties, ar -> { if (ar.succeeded()) { vertx.eventBus().send(address, ar.result()); } else { log.error("Exception occurred inside rabbitmq service consumer.", ar.cause()); } })); return null; }); }
Source:
private String parseUsingGrobid(String plainText) { try { return grobidService.processCitation(plainText, GrobidService.ConsolidateCitations.WITH_METADATA); } catch (IOException e) { LOGGER.atDebug().setCause(e).log(e.getMessage()); return ""; } }

Target:
private String parseUsingGrobid(String plainText) { try { return grobidService.processCitation(plainText, GrobidService.ConsolidateCitations.WITH_METADATA); } catch (IOException e) { LOGGER.debug("Could not process citation", e); return ""; } }
Source:
private void handleEviction(long address, ILogData entry, RemovalCause cause) { log.trace("Eviction[{}]: {}", address, cause); streamLog.release(address, (LogData) entry); }

Target:
private void handleEviction(long address, ILogData entry, RemovalCause cause) { log.trace("Eviction[{}]: {}", address, cause); }
Source:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } ClassTree classTree = (ClassTree) tree; if (!hasMethodsAnnotatedWithTransactional(classTree)) { return; } Map<Symbol, String> methodsPropagationMap = collectMethodsPropagation(classTree); if (hasSameValues(methodsPropagationMap)) { return; } methodsPropagationMap .forEach((symbol, propagation) -> checkMethodInvocation((MethodTree) symbol.declaration(), propagation, methodsPropagationMap)); }

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } ClassTree classTree = (ClassTree) tree; Map<Symbol, String> methodsPropagationMap = collectMethodsPropagation(classTree); if (hasSameValues(methodsPropagationMap.values())) { return; } methodsPropagationMap .forEach((symbol, propagation) -> checkMethodInvocations((MethodTree) symbol.declaration(), propagation, methodsPropagationMap)); }
Source:
private void logFailedUpgrades() { TransactionSupport.executeInNewTransaction(() -> { for (Map.Entry<String, String> entry : failedUpgradeVms.entrySet()) { addCustomValue("VmName", entry.getKey()); addCustomValue("Message", entry.getValue()); auditLogDirector.log(this, AuditLogType.CLUSTER_CANNOT_UPDATE_VM_COMPATIBILITY_VERSION); } return null; }); }

Target:
private void logFailedUpgrades() { for (Map.Entry<String, String> entry : failedUpgradeEntities.entrySet()) { addCustomValue("VmName", entry.getKey()); addCustomValue("Message", entry.getValue()); auditLogDirector.log(this, AuditLogType.CLUSTER_CANNOT_UPDATE_VM_COMPATIBILITY_VERSION); } }
Source:
void randomEmit(T record, int targetChannelIndex) throws IOException, InterruptedException { tryFinishCurrentBufferBuilder(targetChannelIndex); randomTriggered = true; emit(record, targetChannelIndex); randomTriggered = false; if (bufferBuilder != null) { for (int index = 0; index < numberOfChannels; index++) { if (index != targetChannelIndex) { addBufferConsumer(randomTriggeredConsumer.copyAndSync(bufferBuilder), index); } } } }

Target:
void randomEmit(T record, int targetChannelIndex) throws IOException, InterruptedException { tryFinishCurrentBufferBuilder(targetChannelIndex); randomTriggered = true; emit(record, targetChannelIndex); randomTriggered = false; if (bufferBuilder != null) { for (int index = 0; index < numberOfChannels; index++) { if (index != targetChannelIndex) { addBufferConsumer(randomTriggeredConsumer.copyWithReaderPosition(bufferBuilder.getCommittedBytes()), index); } } } }
Source:
protected Object fromByteBuffer(ByteBuffer byteBuffer) { return serDes.deserialize(byteBuffer); }

Target:
protected BluefloodEnumRollup fromByteBuffer(ByteBuffer byteBuffer) { return serDes.deserialize(byteBuffer); }
Source:
public List<VdsNetworkInterface> getAllMigrationNetworkInterfacesInCluster(Guid clusterId) { return getCallsHandler().executeReadList("GetAllMigrationNetworkInterfacesInCluster", vdsNetworkInterfaceRowMapper, getCustomMapSqlParameterSource().addValue("cluster_id", clusterId)); }

Target:
public List<VdsNetworkInterface> getAllMigrationNetworkInterfacesInCluster(Guid clusterId) { MapSqlParameterSource parameterSource = getCustomMapSqlParameterSource() .addValue("cluster_id", clusterId); return readVdsNetworkInterfaces(parameterSource, "GetAllMigrationNetworkInterfacesInCluster"); }
Source:
protected void compileJavaParser(boolean leftRecursive) throws IOException { String grammarFileName = leftRecursive ? "JavaLR.g4" : "Java.g4"; String sourceName = leftRecursive ? "JavaLR.g4" : "Java.g4"; String parserName = leftRecursive ? "JavaLRParser" : "JavaParser"; String lexerName = leftRecursive ? "JavaLRLexer" : "JavaLexer"; String body = load(sourceName, null); List<String> extraOptions = new ArrayList<String>(); extraOptions.add("-Werror"); if (FORCE_ATN) { extraOptions.add("-Xforce-atn"); } if (EXPORT_ATN_GRAPHS) { extraOptions.add("-atn"); } if (DEBUG_TEMPLATES) { extraOptions.add("-XdbgST"); if (DEBUG_TEMPLATES_WAIT) { extraOptions.add("-XdbgSTWait"); } } extraOptions.add("-visitor"); String[] extraOptionsArray = extraOptions.toArray(new String[extraOptions.size()]); boolean success = rawGenerateAndBuildRecognizer(grammarFileName, body, parserName, lexerName, true, extraOptionsArray); assertTrue(success); }

Target:
protected void compileJavaParser(boolean leftRecursive) throws IOException { String grammarFileName = leftRecursive ? "JavaLR.g4" : "Java.g4"; String parserName = leftRecursive ? "JavaLRParser" : "JavaParser"; String lexerName = leftRecursive ? "JavaLRLexer" : "JavaLexer"; String body = load(grammarFileName, null); List<String> extraOptions = new ArrayList<String>(); extraOptions.add("-Werror"); if (FORCE_ATN) { extraOptions.add("-Xforce-atn"); } if (EXPORT_ATN_GRAPHS) { extraOptions.add("-atn"); } if (DEBUG_TEMPLATES) { extraOptions.add("-XdbgST"); if (DEBUG_TEMPLATES_WAIT) { extraOptions.add("-XdbgSTWait"); } } extraOptions.add("-visitor"); String[] extraOptionsArray = extraOptions.toArray(new String[extraOptions.size()]); boolean success = rawGenerateAndBuildRecognizer(grammarFileName, body, parserName, lexerName, true, extraOptionsArray); assertTrue(success); }
Source:
void setAsyncLockRemoval(final String path) throws IOException { LightWeightRequestHandler handler = new LightWeightRequestHandler( HDFSOperationType.SET_ASYNC_SUBTREE_RECOVERY_FLAG) { @Override public Object performTask() throws IOException { OngoingSubTreeOpsDataAccess<SubTreeOperation> dataAccess = (OngoingSubTreeOpsDataAccess) HdfsStorageFactory.getDataAccess(OngoingSubTreeOpsDataAccess.class); SubTreeOperation op = dataAccess.findByPath(getSubTreeLockPathPrefix(path)); if (op != null) { op.setAsyncLockRecoveryTime(System.currentTimeMillis()); List<SubTreeOperation> modified = new ArrayList<SubTreeOperation>(); modified.add(op); dataAccess.prepare(Collections.EMPTY_LIST, Collections.EMPTY_LIST, modified); } return null; } }; handler.handle(); }

Target:
void setAsyncLockRemoval(final String path) throws IOException { LightWeightRequestHandler handler = new LightWeightRequestHandler( HDFSOperationType.SET_ASYNC_SUBTREE_RECOVERY_FLAG) { @Override public Object performTask() throws IOException { OngoingSubTreeOpsDataAccess<SubTreeOperation> dataAccess = (OngoingSubTreeOpsDataAccess) HdfsStorageFactory.getDataAccess(OngoingSubTreeOpsDataAccess.class); SubTreeOperation op = dataAccess.findByPath(getSubTreeLockPathPrefix(path)); if (op != null && op.getAsyncLockRecoveryTime() == 0) { op.setAsyncLockRecoveryTime(System.currentTimeMillis()); List<SubTreeOperation> modified = new ArrayList<SubTreeOperation>(); modified.add(op); dataAccess.prepare(Collections.EMPTY_LIST, Collections.EMPTY_LIST, modified); } return null; } }; handler.handle(); }
Source:
public Response getHistogram(@QueryParam("queryId") final Long queryId, @QueryParam("fragmentId") final Long fragmentId, @Context final UriInfo uriInfo) throws DbException { if (queryId == null) { throw new WebApplicationException(Response.status(HttpURLConnection.HTTP_BAD_REQUEST).entity("queryId missing") .build()); } if (fragmentId == null) { throw new WebApplicationException(Response.status(HttpURLConnection.HTTP_BAD_REQUEST) .entity("fragmentId missing").build()); } ResponseBuilder response = Response.ok(); response.type(MediaType.TEXT_PLAIN); PipedOutputStream writerOutput = new PipedOutputStream(); PipedInputStream input; try { input = new PipedInputStream(writerOutput, MyriaConstants.DEFAULT_PIPED_INPUT_STREAM_SIZE); } catch (IOException e) { throw new DbException(e); } PipedStreamingOutput entity = new PipedStreamingOutput(input); response.entity(entity); TupleWriter writer = new CsvTupleWriter(writerOutput); try { server.startHistorgramDataStream(queryId, fragmentId, writer); } catch (IllegalArgumentException e) { throw new MyriaApiException(Status.BAD_REQUEST, e); } return response.build(); }

Target:
public Response getHistogram(@QueryParam("queryId") final Long queryId, @QueryParam("fragmentId") final Long fragmentId, @Context final UriInfo uriInfo) throws DbException { if (queryId == null) { throw new MyriaApiException(Status.BAD_REQUEST, "Query ID missing."); } if (fragmentId == null) { throw new MyriaApiException(Status.BAD_REQUEST, "Fragment ID missing."); } ResponseBuilder response = Response.ok(); response.type(MediaType.TEXT_PLAIN); PipedOutputStream writerOutput = new PipedOutputStream(); PipedInputStream input; try { input = new PipedInputStream(writerOutput, MyriaConstants.DEFAULT_PIPED_INPUT_STREAM_SIZE); } catch (IOException e) { throw new DbException(e); } PipedStreamingOutput entity = new PipedStreamingOutput(input); response.entity(entity); TupleWriter writer = new CsvTupleWriter(writerOutput); try { server.startHistogramDataStream(queryId, fragmentId, writer); } catch (IllegalArgumentException e) { throw new MyriaApiException(Status.BAD_REQUEST, e); } return response.build(); }
Source:
public int hashCode() { final HashCodeBuilder hashCodeBuilder = new HashCodeBuilder(); hashCodeBuilder.append(_filterOutcome); hashCodeBuilder.append(_from); hashCodeBuilder.append(_requirement); hashCodeBuilder.append(_to); hashCodeBuilder.append(_outputDataStream); return hashCodeBuilder.toHashCode(); }

Target:
public int hashCode() { return Objects.hash(_filterOutcome, _from, _requirement, _to, _outputDataStream); }
Source:
@Override public void connectionClosed(final RpcClientChannel rpcClientChannel) { socketHandler.rpcOnClose(new RpcSession(rpcClientChannel), -1, "Idk"); }

Target:
@Override public void connectionClosed(final RpcClientChannel rpcClientChannel) { socketHandler.rpcOnClose(new RpcSession(rpcClientChannel), -1, "for an unknown reason"); }
Source:
private static void pressShortcut(Control control, Runnable pressShortcut, KeyStroke... keys) { AtomicInteger keysPressed = new AtomicInteger(); AtomicInteger keysReleased = new AtomicInteger(); KeyListener keyListener = new KeyListener() { @Override public void keyPressed(KeyEvent e) { keysPressed.incrementAndGet(); } @Override public void keyReleased(KeyEvent e) { keysReleased.incrementAndGet(); } }; UIThreadRunnable.syncExec(new VoidResult() { @Override public void run() { control.addKeyListener(keyListener); } }); pressShortcut.run(); new SWTBot().waitUntil(new DefaultCondition() { @Override public boolean test() throws Exception { return keysPressed.get() > 0 && keysPressed.get() == keysReleased.get(); } @Override public String getFailureMessage() { return "key press " + Arrays.toString(keys) + " not detected"; } }); UIThreadRunnable.syncExec(new VoidResult() { @Override public void run() { control.removeKeyListener(keyListener); } }); }

Target:
private static void pressShortcut(Control control, Runnable pressShortcut, KeyStroke... keys) { AtomicInteger keysPressed = new AtomicInteger(); AtomicInteger keysReleased = new AtomicInteger(); KeyListener keyListener = new KeyListener() { @Override public void keyPressed(KeyEvent e) { keysPressed.incrementAndGet(); } @Override public void keyReleased(KeyEvent e) { keysReleased.incrementAndGet(); } }; UIThreadRunnable.syncExec(() -> control.addKeyListener(keyListener)); pressShortcut.run(); new SWTBot().waitUntil(new DefaultCondition() { @Override public boolean test() throws Exception { return keysPressed.get() > 0 && keysPressed.get() == keysReleased.get(); } @Override public String getFailureMessage() { return "key press " + Arrays.toString(keys) + " not detected"; } }); UIThreadRunnable.syncExec(() -> control.removeKeyListener(keyListener)); }
Source:
public void endpointsByNamespaceWithNodeName() { endpointsByNamespaceWithNodePublicIp(); kubernetesClient = newKubernetesClient(true); String forbiddenBody = "\"reason\":\"Forbidden\""; stub("/api/v1/nodes/node-name-1", 403, forbiddenBody); stub("/api/v1/nodes/node-name-2", 403, forbiddenBody); List<Endpoint> result = kubernetesClient.endpoints(); assertThat(format(result), containsInAnyOrder(ready("192.168.0.25", 5701), ready("172.17.0.5", 5702))); assertThat(formatPublic(result), containsInAnyOrder(ready("node-name-1", 31916), ready("node-name-2", 31917))); }

Target:
public void endpointsByNamespaceWithNodeName() { kubernetesClient = newKubernetesClient(true); stub(String.format("/api/v1/namespaces/%s/pods", NAMESPACE), podsListResponse()); stub(String.format("/api/v1/namespaces/%s/endpoints", NAMESPACE), endpointsListResponse()); stub(String.format("/api/v1/namespaces/%s/services/service-0", NAMESPACE), nodePortService1Response()); stub(String.format("/api/v1/namespaces/%s/services/service-1", NAMESPACE), nodePortService2Response()); String forbiddenBody = "\"reason\":\"Forbidden\""; stub("/api/v1/nodes/node-name-1", 403, forbiddenBody); stub("/api/v1/nodes/node-name-2", 403, forbiddenBody); List<Endpoint> result = kubernetesClient.endpoints(); assertThat(format(result), containsInAnyOrder(ready("192.168.0.25", 5701), ready("172.17.0.5", 5702))); assertThat(formatPublic(result), containsInAnyOrder(ready("node-name-1", 31916), ready("node-name-2", 31917))); }
Source:
private String getEditedAtText(String lastEditorEmail, Instant createdAt, Instant lastEditedAt) { if (lastEditedAt == null || lastEditedAt.equals(createdAt)) { return ""; } String lastEditor = commentGiverEmailToNameTable.get(lastEditorEmail) == null ? lastEditorEmail : commentGiverEmailToNameTable.get(lastEditorEmail); boolean isGiverAnonymous = Const.DISPLAYED_NAME_FOR_ANONYMOUS_PARTICIPANT.equals(commentGiverName); return "(last edited " + (isGiverAnonymous ? "" : "by " + SanitizationHelper.sanitizeForHtml(lastEditor) + " ") + "at " + TimeHelper.formatDateTimeForDisplay(lastEditedAt, sessionTimeZone) + ")"; }

Target:
private String getEditedAtText(String lastEditorEmail, Instant createdAt, Instant lastEditedAt) { if (lastEditedAt == null || lastEditedAt.equals(createdAt)) { return ""; } boolean isGiverAnonymous = Const.DISPLAYED_NAME_FOR_ANONYMOUS_PARTICIPANT.equals(commentGiverName); return "(last edited " + (isGiverAnonymous ? "" : "by " + SanitizationHelper.sanitizeForHtml(commentGiverEmailToNameTable.get(lastEditorEmail)) + " ") + "at " + TimeHelper.formatDateTimeForDisplay(lastEditedAt, sessionTimeZone) + ")"; }
Source:
private AuthenticationCache lookupAuthenticationCache() { AuthenticationCache authCache = GeoServerExtensions.bean(AuthenticationCache.class); if (authCache==null) { Disposer disposer = GeoServerExtensions.bean(Disposer.class); authCache = new GuavaAuthenticationCacheImpl(1000); if(disposer!=null) { disposer.register((DisposableBean)authCache); } else { LOGGER.warning("Disposer not available to register for disposal. GuavaAuthenticationCacheImpl may not be closed at application shutdown."); } } return authCache; }

Target:
AuthenticationCache lookupAuthenticationCache() { AuthenticationCache authCache = GeoServerExtensions.bean(AuthenticationCache.class); return authCache != null ? authCache : new GuavaAuthenticationCacheImpl(1000); }
Source:
private boolean statusFilter(RejisPartialCitation partialCitation){ boolean keepCitation = false; if (!partialCitation.caseStatus.equals("C")){ keepCitation = true; } return keepCitation; }

Target:
private boolean statusFilter(RejisPartialCitation partialCitation){ return !partialCitation.caseStatus.equals("C"); }
Source:
public void test(TestHarness th) { th.check(overridden(), 2); }

Target:
public void test(TestHarness th) { th.check(overridden(), 2); th.check(overridden(), 2); }
Source:
public static JavaTypeQualifiedName ofClass(Class<?> clazz) { if (clazz == null) { return null; } String name = clazz.getName(); if (name.indexOf('.') < 0) { name = '.' + name; } return ((JavaTypeQualifiedName) ofString(name)).withClassLoader(clazz.getClassLoader()); }

Target:
public static JavaTypeQualifiedName ofClass(Class<?> clazz) { if (clazz == null) { return null; } String name = clazz.getName(); if (name.indexOf('.') < 0) { name = '.' + name; } JavaTypeQualifiedName qualifiedName = (JavaTypeQualifiedName) ofString(name); if (qualifiedName != null) { qualifiedName.withClassLoader(clazz.getClassLoader()); } return qualifiedName; }
Source:
public boolean isRestricted() { throw new UnsupportedOperationException("Not supported yet."); }

Target:
public boolean isRestricted() { return true; @Override public Boolean runAsync() { return false; } @Override public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer m = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCWorld world; int x; int z; if (args.length == 1) { MCLocation l = ObjectGenerator.GetGenerator().location(args[0], m != null ? m.getWorld() : null, t); world = l.getWorld(); x = l.getBlockX(); z = l.getBlockZ(); } else if (args.length == 2) { if (args[1] instanceof CArray) { world = Static.getServer().getWorld(args[0].val()); MCLocation l = ObjectGenerator.GetGenerator().location(args[1], null, t); x = l.getBlockX(); z = l.getBlockZ(); } else { if (m == null) { throw new ConfigRuntimeException("No world specified", ExceptionType.InvalidWorldException, t); } world = m.getWorld(); x = Static.getInt32(args[0], t); z = Static.getInt32(args[1], t); } } else { world = Static.getServer().getWorld(args[0].val()); x = Static.getInt32(args[1], t); z = Static.getInt32(args[2], t); } world.unloadChunk(x, z); return new CVoid(t); } @Override public String getName() { return "unload_chunk"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } @Override public String docs() { return "void {[world], x, z | [world], locationArray} Unloads the chunk, using the specified world, or the current" + " players world if not provided."; } @Override public Version since() { return CHVersion.V3_3_1; } }
Source:
public boolean canUnload() { return false; }

Target:
public boolean canUnload() { return true; }
Source:
protected List<ExecutionErrorInfo> findErrorsToAck(EntityManager em) { List<ExecutionErrorInfo> errorsToAck = new ArrayList<>(); String findProcessErrorsQuery = "select error from ExecutionErrorInfo error " + "where error.acknowledged =:acknowledged " + "and error.processInstanceId in (select pil.id from ProcessInstanceLog pil where status in (:status))"; List<ExecutionErrorInfo> processErrorsToAck = em.createQuery(findProcessErrorsQuery) .setParameter("acknowledged", false) .setParameter("status", Arrays.asList(2, 3)) .getResultList(); errorsToAck.addAll(processErrorsToAck); String findNodeErrorsQuery = "select error from ExecutionErrorInfo error " + "where error.acknowledged =:acknowledged " + "and error.initActivityId in (select nil.nodeInstanceId from NodeInstanceLog nil where nil.processInstanceId = error.processInstanceId and nil.nodeInstanceId = error.initActivityId and nil.type = 1)"; List<ExecutionErrorInfo> nodeErrorsToAck = em.createQuery(findNodeErrorsQuery) .setParameter("acknowledged", false) .getResultList(); errorsToAck.addAll(nodeErrorsToAck); return errorsToAck; }

Target:
protected List<ExecutionErrorInfo> findErrorsToAck(EntityManager em) { List<ExecutionErrorInfo> errorsToAck = new ArrayList<>(); String findProcessErrorsQuery = "select error from ExecutionErrorInfo error " + "where error.acknowledged =:acknowledged " + "and error.processInstanceId in (select pil.id from ProcessInstanceLog pil where status in (:status))"; List<ExecutionErrorInfo> processErrorsToAck = em.createQuery(findProcessErrorsQuery) .setParameter("acknowledged", new Short("0")) .setParameter("status", Arrays.asList(ProcessInstance.STATE_COMPLETED, ProcessInstance.STATE_ABORTED)) .getResultList(); errorsToAck.addAll(processErrorsToAck); String findNodeErrorsQuery = "select error from ExecutionErrorInfo error " + "where error.acknowledged =:acknowledged " + "and error.initActivityId in (select nil.nodeInstanceId from NodeInstanceLog nil where nil.processInstanceId = error.processInstanceId and nil.nodeInstanceId = error.initActivityId and nil.type = 1)"; List<ExecutionErrorInfo> nodeErrorsToAck = em.createQuery(findNodeErrorsQuery) .setParameter("acknowledged", new Short("0")) .getResultList(); errorsToAck.addAll(nodeErrorsToAck); return errorsToAck; }
Source:
private List<Double> applyScenarios(ObservableId id, double value, ScenarioDefinition scenarioDefinition) { Optional<PerturbationMapping<?>> mapping = scenarioDefinition.getMappings().stream() .filter(m -> m.getFilter().apply(id, value)) .findFirst(); if (mapping.isPresent()) { return mapping.get().getPerturbations().stream() .map(perturbation -> (Double) perturbation.apply(value)) .collect(toImmutableList()); } else { return Collections.nCopies(scenarioDefinition.getScenarioCount(), value); } }

Target:
private Result<List<Double>> applyScenarios(ObservableId id, double value, ScenarioDefinition scenarioDefinition) { try { Optional<PerturbationMapping<?>> mapping = scenarioDefinition.getMappings().stream() .filter(m -> m.matches(id, value)) .findFirst(); if (mapping.isPresent()) { List<Double> values = mapping.get().getPerturbations().stream() .map(perturbation -> (Double) perturbation.apply(value)) .collect(toImmutableList()); return Result.success(values); } else { List<Double> values = Collections.nCopies(scenarioDefinition.getScenarioCount(), value); return Result.success(values); } } catch (RuntimeException e) { return Result.failure(e); } }
Source:
private Optional<CurrentWsResponse.Homepage> projectHomepage(DbSession dbSession, UserDto user) { Optional<ComponentDto> projectOptional = ofNullable(dbClient.componentDao().selectByUuid(dbSession, of(user.getHomepageParameter()).orElse(EMPTY)).orNull()); if (!projectOptional.isPresent() || !userSession.hasComponentPermission(USER, projectOptional.get())) { cleanUserHomepageInDb(dbSession, user); return empty(); } CurrentWsResponse.Homepage.Builder homepage = CurrentWsResponse.Homepage.newBuilder() .setType(CurrentWsResponse.HomepageType.valueOf(user.getHomepageType())) .setComponent(projectOptional.get().getKey()); setNullable(projectOptional.get().getBranch(), homepage::setBranch); return of(homepage.build()); }

Target:
private Optional<CurrentWsResponse.Homepage> projectHomepage(DbSession dbSession, UserDto user) { Optional<ComponentDto> projectOptional = ofNullable(dbClient.componentDao().selectByUuid(dbSession, of(user.getHomepageParameter()).orElse(EMPTY)).orNull()); if (shouldCleanProjectHomepage(projectOptional)) { cleanUserHomepageInDb(dbSession, user); return empty(); } CurrentWsResponse.Homepage.Builder homepage = CurrentWsResponse.Homepage.newBuilder() .setType(CurrentWsResponse.HomepageType.valueOf(user.getHomepageType())) .setComponent(projectOptional.get().getKey()); setNullable(projectOptional.get().getBranch(), homepage::setBranch); return of(homepage.build()); }
Source:
public void getAssignmentValue_multiple() throws Exception { CompilationUnitTree tree = parse("<?php $a = 1;\n$a = 2;", PHPLexicalGrammar.COMPILATION_UNIT); SymbolTable symbolTable = SymbolTableImpl.create(tree); AssignmentExpressionVisitor assignmentExpressionVisitor = new AssignmentExpressionVisitor(symbolTable); tree.accept(assignmentExpressionVisitor); IdentifierTree var = ((SymbolTableImpl) symbolTable).getSymbols("$a").get(0).declaration(); assertThat(assignmentExpressionVisitor.getAssignmentValue(var).isPresent()).isFalse(); }

Target:
public void getAssignmentValue_multiple() throws Exception { Optional<ExpressionTree> uniqueAssignedValue = UniqueAssignedValue.Of("$a").from("<?php $a = 1;\n$a = 2;"); assertThat(uniqueAssignedValue).isNotPresent(); }
Source:
protected void setUp() { edgeWeights = new HashMap<>(); nev = edgeWeights::get; dg = NetworkBuilder.directed().allowsParallelEdges(true).allowsSelfLoops(true).build(); for (double[] dg_distance : dg_distances) { dg.addNode(vertexFactoryDG.get()); } did = Indexer.create(dg.nodes(), 1); Integer[] dgArray = new Integer[edges.length]; addEdges(dg, did, dgArray); ug = NetworkBuilder.undirected().allowsParallelEdges(true).allowsSelfLoops(true).build(); for (double[] ugDistance : ug_distances) { ug.addNode(vertexFactoryUG.get()); } uid = Indexer.create(ug.nodes(), 1); Integer[] ugArray = new Integer[edges.length]; addEdges(ug, uid, ugArray); edgeArrays = new HashMap<>(); edgeArrays.put(dg, dgArray); edgeArrays.put(ug, ugArray); }

Target:
protected void setUp() { edgeWeights = new HashMap<>(); nev = edgeWeights::get; dg = NetworkBuilder.directed().allowsParallelEdges(true).allowsSelfLoops(true).build(); for (int i = 0; i < dg_distances.length; i++) { dg.addNode(vertexFactoryDG.get()); } did = Indexer.create(dg.nodes(), 1); Integer[] dgArray = new Integer[edges.length]; addEdges(dg, did, dgArray); ug = NetworkBuilder.undirected().allowsParallelEdges(true).allowsSelfLoops(true).build(); for (int i = 0; i < ug_distances.length; i++) { ug.addNode(vertexFactoryUG.get()); } uid = Indexer.create(ug.nodes(), 1); Integer[] ugArray = new Integer[edges.length]; addEdges(ug, uid, ugArray); edgeArrays = new HashMap<>(); edgeArrays.put(dg, dgArray); edgeArrays.put(ug, ugArray); }
Source:
private void parseMetadataOptions(String metadataOptions) { try { JSONObject jsonObject = new JSONObject(metadataOptions); JSONArray optionsArray = jsonObject.getJSONArray("MetadataOptions"); JSONObject options = optionsArray.getJSONObject(0); metadataType = options.getString("Type"); metadataFormat = options.getString("Format"); metadataLabel = options.getString("Label"); MetadataElement metadataElement = new MetadataElement(); metadataElement.setElements(metadataType, metadataFormat, metadataLabel); metadataElements.add(metadataElement); } catch (JSONException ex) { OseeCoreException.wrapAndThrow(ex); } }

Target:
private void parseMetadataOptions(String metadataOptions) { try { JSONObject jsonObject = new JSONObject(metadataOptions); if (!jsonObject.has("MetadataOptions")) { return; } JSONArray optionsArray = jsonObject.getJSONArray("MetadataOptions"); JSONObject options = optionsArray.getJSONObject(0); metadataType = options.getString("Type"); metadataFormat = options.getString("Format"); metadataLabel = options.getString("Label"); MetadataElement metadataElement = new MetadataElement(); metadataElement.setElements(metadataType, metadataFormat, metadataLabel); metadataElements.add(metadataElement); } catch (JSONException ex) { OseeCoreException.wrapAndThrow(ex); } }
Source:
static public void sendNotification(String userId, String message) { logger.debug("sendNotification()"); if (mMyOpenHABService != null) mMyOpenHABService.sendNotification(userId, message, null, null); }

Target:
static public void sendNotification(String userId, String message) { sendNotification(userId, message, null, null); }
Source:
protected DiskImage createImage() { final DiskImage diskImage = new DiskImage(); diskImage.setimage_group_id(Guid.NewGuid()); diskImage.setstorage_ids(new ArrayList<Guid>(Arrays.asList(new Guid()))); return diskImage; }

Target:
private DiskImage createImage() { final DiskImage diskImage = new DiskImage(); diskImage.setimage_group_id(Guid.NewGuid()); diskImage.setstorage_ids(new ArrayList<Guid>(Arrays.asList(new Guid()))); return diskImage; }
Source:
public ListBoxModel doFillTypeIdItems(@AncestorInPath Item item) { Project project = null; ListBoxModel items = new ListBoxModel().add(""); if(item instanceof Project) { project = (Project) item; final JiraProjectProperty jiraProjectProperty = (JiraProjectProperty) project.getProperty(JiraProjectProperty.class); JiraSite site = jiraProjectProperty.getSite(); JiraSession session = site.getSession(); if (session != null) { for (IssueType type : session.getIssueTypes()) { items.add("[" + site.getName() + "] " + type.getName(), String.valueOf(type.getId())); } } } return items; }

Target:
public ListBoxModel doFillTypeIdItems(@AncestorInPath Item item) { Project project = null; ListBoxModel items = new ListBoxModel().add(""); if(item instanceof Project) { project = (Project) item; final JiraProjectProperty jiraProjectProperty = (JiraProjectProperty) project.getProperty(JiraProjectProperty.class); JiraSite site = jiraProjectProperty.getSite(); if(site != null) { JiraSession session = site.getSession(); if (session != null) { for (IssueType type : session.getIssueTypes()) { items.add("[" + site.getName() + "] " + type.getName(), String.valueOf(type.getId())); } } } } return items; }
Source:
protected boolean validateForm(String jobName, String jobType, String jobRetries) { boolean valid = true; view.cleanErrorMessages(); if (jobName.isEmpty()) { view.showNameErrorMessage(); valid = false; } if (jobType.isEmpty()) { view.showEmptyTypeErrorMessage(); valid = false; } if (jobRetries.isEmpty()) { view.showRetriesErrorMessage(); valid = false; } return valid; }

Target:
protected boolean validateForm(String jobName, String jobType, String jobRetries) { boolean valid = true; view.cleanErrorMessages(); if (jobName.isEmpty()) { view.showEmptyNameErrorMessage(); valid = false; } if (jobType.isEmpty()) { view.showEmptyTypeErrorMessage(); valid = false; } if (jobRetries.isEmpty()) { view.showEmptyRetriesErrorMessage(); valid = false; } return valid; }
Source:
private void attachEventContextManagingListenersIfRequired(SessionFactoryServiceRegistry serviceRegistry) { @SuppressWarnings("unchecked") Map<Object, Object> settings = serviceRegistry.getService( ConfigurationService.class ).getSettings(); if ( !EventContextManager.isEventContextRequired( serviceRegistry ) ) { return; } EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class ); EventContextManager stateManager = serviceRegistry.getService( EventContextManager.class ); eventListenerRegistry.addDuplicationStrategy( EventContextManagingAutoFlushEventListenerDuplicationStrategy.INSTANCE ); eventListenerRegistry.getEventListenerGroup( EventType.AUTO_FLUSH ).appendListener( new EventContextManagingAutoFlushEventListener( stateManager ) ); eventListenerRegistry.addDuplicationStrategy( EventContextManagingFlushEventListenerDuplicationStrategy.INSTANCE ); eventListenerRegistry.getEventListenerGroup( EventType.FLUSH ).appendListener( new EventContextManagingFlushEventListener( stateManager ) ); if ( getIntegrator( JpaIntegrator.class, serviceRegistry ) != null ) { eventListenerRegistry.addDuplicationStrategy( EventContextManagingPersistEventListenerDuplicationStrategy.INSTANCE ); eventListenerRegistry.getEventListenerGroup( EventType.PERSIST ).appendListener( new EventContextManagingPersistEventListener( stateManager ) ); } }

Target:
private void attachEventContextManagingListenersIfRequired(SessionFactoryServiceRegistry serviceRegistry) { if ( !EventContextManager.isEventContextRequired( serviceRegistry ) ) { return; } EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class ); EventContextManager stateManager = serviceRegistry.getService( EventContextManager.class ); eventListenerRegistry.addDuplicationStrategy( EventContextManagingAutoFlushEventListenerDuplicationStrategy.INSTANCE ); eventListenerRegistry.getEventListenerGroup( EventType.AUTO_FLUSH ).appendListener( new EventContextManagingAutoFlushEventListener( stateManager ) ); eventListenerRegistry.addDuplicationStrategy( EventContextManagingFlushEventListenerDuplicationStrategy.INSTANCE ); eventListenerRegistry.getEventListenerGroup( EventType.FLUSH ).appendListener( new EventContextManagingFlushEventListener( stateManager ) ); if ( getIntegrator( JpaIntegrator.class, serviceRegistry ) != null ) { eventListenerRegistry.addDuplicationStrategy( EventContextManagingPersistEventListenerDuplicationStrategy.INSTANCE ); eventListenerRegistry.getEventListenerGroup( EventType.PERSIST ).appendListener( new EventContextManagingPersistEventListener( stateManager ) ); } }
Source:
public void testDocumentClientConnectionPolicy() throws Exception { String proxyHost = "zwus2-proxy.azure.linkedin.com"; int proxyPort = 3128; String[] schemes = {"http", "https"}; for (String scheme : schemes) { String endpoint = scheme + "://mycosmosdb.documents.azure.com/"; String proxyHostProperty = scheme + "." + "proxyHost"; String proxyPortProperty = scheme + "." + "proxyPort"; System.clearProperty(proxyHostProperty); System.clearProperty(proxyPortProperty); ConnectionPolicy policy = AzureCloudDestination.getProxyWiseConnectionPolicy(endpoint); assertNull("Expected null proxy", policy.getProxy()); System.setProperty(proxyHostProperty, proxyHost); policy = AzureCloudDestination.getProxyWiseConnectionPolicy(endpoint); assertNotNull("Expected proxy", policy.getProxy()); assertEquals("Wrong host", proxyHost, policy.getProxy().getHostName()); assertEquals("Wrong scheme", scheme, policy.getProxy().getSchemeName()); assertEquals("Expected default port", -1, policy.getProxy().getPort()); System.setProperty(proxyPortProperty, String.valueOf(proxyPort)); policy = AzureCloudDestination.getProxyWiseConnectionPolicy(endpoint); assertNotNull("Expected proxy", policy.getProxy()); assertEquals("Wrong host", proxyHost, policy.getProxy().getHostName()); assertEquals("Wrong scheme", scheme, policy.getProxy().getSchemeName()); assertEquals("Wrong port", proxyPort, policy.getProxy().getPort()); } }

Target:
public void testDocumentClientConnectionPolicy() throws Exception { String proxyHost = "azure-proxy.github.com"; int proxyPort = 3128; String[] schemes = {"http", "https"}; for (String scheme : schemes) { String endpoint = scheme + "://mycosmosdb.documents.azure.com/"; String proxyHostProperty = scheme + "." + "proxyHost"; String proxyPortProperty = scheme + "." + "proxyPort"; System.clearProperty(proxyHostProperty); System.clearProperty(proxyPortProperty); ConnectionPolicy policy = AzureCloudDestination.getProxyWiseConnectionPolicy(endpoint); assertNull("Expected null proxy", policy.getProxy()); System.setProperty(proxyHostProperty, proxyHost); policy = AzureCloudDestination.getProxyWiseConnectionPolicy(endpoint); assertNotNull("Expected proxy", policy.getProxy()); assertEquals("Wrong host", proxyHost, policy.getProxy().getHostName()); assertEquals("Expected default port", -1, policy.getProxy().getPort()); System.setProperty(proxyPortProperty, String.valueOf(proxyPort)); policy = AzureCloudDestination.getProxyWiseConnectionPolicy(endpoint); assertNotNull("Expected proxy", policy.getProxy()); assertEquals("Wrong host", proxyHost, policy.getProxy().getHostName()); assertEquals("Wrong port", proxyPort, policy.getProxy().getPort()); } }
Source:
private void assertAnnotation(int numOccurrences, String physicalTableName, String tenant, String schemaName, String logicalTableName, PTableType tableType, long ddlTimestamp) throws IOException { int foundCount = 0; int notFoundCount = 0; List<Map<String, byte[]>> entries = getEntriesForTable(TableName.valueOf(physicalTableName)); for (Map<String, byte[]> m : entries) { byte[] tenantBytes = m.get(MutationState.MutationMetadataType.TENANT_ID.toString()); byte[] schemaBytes = m.get(MutationState.MutationMetadataType.SCHEMA_NAME.toString()); byte[] logicalTableBytes = m.get(MutationState.MutationMetadataType.LOGICAL_TABLE_NAME.toString()); byte[] tableTypeBytes = m.get(MutationState.MutationMetadataType.TABLE_TYPE.toString()); byte[] timestampBytes = m.get(MutationState.MutationMetadataType.TIMESTAMP.toString()); assertNotNull(timestampBytes); long timestamp = Bytes.toLong(timestampBytes); if (Objects.equals(tenant, Bytes.toString(tenantBytes)) && Objects.equals(schemaName, Bytes.toString(schemaBytes)) && Objects.equals(logicalTableName, Bytes.toString(logicalTableBytes)) && Objects.equals(tableType.toString(), Bytes.toString(tableTypeBytes)) && Objects.equals(ddlTimestamp, timestamp) && timestamp < HConstants.LATEST_TIMESTAMP) { foundCount++; } else { notFoundCount++; } } Assert.assertEquals(numOccurrences, foundCount); Assert.assertEquals(0, notFoundCount); }

Target:
private void assertAnnotation(int numOccurrences, String physicalTableName, String tenant, String schemaName, String logicalTableName, PTableType tableType, long ddlTimestamp) throws IOException { int foundCount = 0; int notFoundCount = 0; List<Map<String, byte[]>> entries = getEntriesForTable(TableName.valueOf(physicalTableName)); for (Map<String, byte[]> m : entries) { byte[] tenantBytes = m.get(MutationState.MutationMetadataType.TENANT_ID.toString()); byte[] schemaBytes = m.get(MutationState.MutationMetadataType.SCHEMA_NAME.toString()); byte[] logicalTableBytes = m.get(MutationState.MutationMetadataType.LOGICAL_TABLE_NAME.toString()); byte[] tableTypeBytes = m.get(MutationState.MutationMetadataType.TABLE_TYPE.toString()); byte[] timestampBytes = m.get(MutationState.MutationMetadataType.TIMESTAMP.toString()); assertNotNull(timestampBytes); long timestamp = Bytes.toLong(timestampBytes); if (Objects.equals(tenant, Bytes.toString(tenantBytes)) && Objects.equals(schemaName, Bytes.toString(schemaBytes)) && Objects.equals(logicalTableName, Bytes.toString(logicalTableBytes)) && Objects.equals(tableType.toString(), Bytes.toString(tableTypeBytes)) && Objects.equals(ddlTimestamp, timestamp) && timestamp < HConstants.LATEST_TIMESTAMP) { foundCount++; } else { notFoundCount++; } } assertEquals(numOccurrences, foundCount); assertEquals(0, notFoundCount); }
Source:
public void testAlterTable() throws InterruptedException { assertUpdate("CREATE TABLE test_table (c1 bigint, c2 bigint)"); assertUpdate("INSERT INTO test_table VALUES (1, 1), (1, 2), (1, 3), (1, 4)", 4); assertUpdate("INSERT INTO test_table VALUES (11, 1), (11, 2)", 2); assertUpdate("ALTER TABLE test_table ADD COLUMN c3 bigint"); assertQueryFails("ALTER TABLE test_table DROP COLUMN c3", "Cannot drop the column which has the largest column ID in the table"); assertUpdate("INSERT INTO test_table VALUES (2, 1, 1), (2, 2, 2), (2, 3, 3), (2, 4, 4)", 4); assertUpdate("INSERT INTO test_table VALUES (22, 1, 1), (22, 2, 2), (22, 4, 4)", 3); assertUpdate("DELETE FROM test_table WHERE c1=1 and c2=1", 1); assertUpdate("DELETE FROM test_table WHERE c1=11", 2); assertUpdate("ALTER TABLE test_table DROP COLUMN c2"); assertUpdate("INSERT INTO test_table VALUES (3, 1), (3, 2), (3, 3), (3, 4)", 4); assertUpdate("DELETE FROM test_table WHERE c1=2 and c3=1", 1); assertUpdate("DELETE FROM test_table WHERE c1=22", 3); assertUpdate("DROP TABLE test_table"); }

Target:
public void testAlterTable() { assertUpdate("CREATE TABLE test_alter_table (c1 bigint, c2 bigint)"); assertUpdate("INSERT INTO test_alter_table VALUES (1, 1), (1, 2), (1, 3), (1, 4)", 4); assertUpdate("INSERT INTO test_alter_table VALUES (11, 1), (11, 2)", 2); assertUpdate("ALTER TABLE test_alter_table ADD COLUMN c3 bigint"); assertQueryFails("ALTER TABLE test_alter_table DROP COLUMN c3", "Cannot drop the column which has the largest column ID in the table"); assertUpdate("INSERT INTO test_alter_table VALUES (2, 1, 1), (2, 2, 2), (2, 3, 3), (2, 4, 4)", 4); assertUpdate("INSERT INTO test_alter_table VALUES (22, 1, 1), (22, 2, 2), (22, 4, 4)", 3); assertUpdate("DELETE FROM test_alter_table WHERE c1 = 1 and c2 = 1", 1); assertUpdate("DELETE FROM test_alter_table WHERE c1 = 11", 2); assertUpdate("ALTER TABLE test_alter_table DROP COLUMN c2"); assertUpdate("INSERT INTO test_alter_table VALUES (3, 1), (3, 2), (3, 3), (3, 4)", 4); assertUpdate("DELETE FROM test_alter_table WHERE c1 = 2 and c3 = 1", 1); assertUpdate("DELETE FROM test_alter_table WHERE c1 = 22", 3); assertUpdate("DROP TABLE test_alter_table"); }