auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static INDArray squeeze(INDArray input, int dimension) { if (dimension < 0){ dimension += input.rank(); } long[] shape = input.shape(); if (shape[dimension] != 1){ throw new ND4JIllegalStateException("Can squeeze only dimensions of size 1."); } long[] newShape = new long[shape.length - 1]; for(int i=0; i < dimension; i++){ newShape[i] = shape[i]; } for(int i = dimension + 1; i < shape.length; i++){ newShape[i - 1] = shape[i]; } return input.reshape(newShape); }

Target:
public static INDArray squeeze(INDArray input, int dimension) { if (dimension < 0){ dimension += input.rank(); } long[] shape = input.shape(); Preconditions.checkState(shape[dimension] == 1, String.format("Squeeze: Only dimension of size 1 can be squeezed. " + "Attempted to squeeze dimension %d of array with shape %s (size %d).", dimension, ArrayUtils.toString(shape), shape[dimension])); long[] newShape = ArrayUtil.removeIndex(shape, dimension); return input.reshape(newShape); }
Source:
public void process(KeyFilter filter, final CacheLoaderTask task, Executor executor, final boolean fetchValue, final boolean fetchMetadata) { filter = PersistenceUtil.notNull(filter); Set<Object> keysToLoad = new HashSet<Object>(entries.size()); synchronized (entries) { for (Object k : entries.keySet()) { if (filter.shouldLoadKey(k)) keysToLoad.add(k); } } ExecutorAllCompletionService eacs = new ExecutorAllCompletionService(executor); final TaskContextImpl taskContext = new TaskContextImpl(); int taskCount = 0; for (final Object key : keysToLoad) { if (taskContext.isStopped()) break; eacs.submit(new Callable<Void>() { @Override public Void call() throws Exception { try { final MarshalledEntry marshalledEntry = _load(key, fetchValue, fetchMetadata); if (marshalledEntry != null) { task.processEntry(marshalledEntry, taskContext); } return null; } catch (Exception e) { log.errorExecutingParallelStoreTask(e); throw e; } } }); } eacs.waitUntilAllCompleted(); if (eacs.isExceptionThrown()) { throw new CacheLoaderException("Execution exception!"); } }

Target:
public void process(KeyFilter filter, final CacheLoaderTask task, Executor executor, final boolean fetchValue, final boolean fetchMetadata) { filter = PersistenceUtil.notNull(filter); Set<Object> keysToLoad = new HashSet<Object>(entries.size()); synchronized (entries) { for (Object k : entries.keySet()) { if (filter.shouldLoadKey(k)) keysToLoad.add(k); } } ExecutorAllCompletionService eacs = new ExecutorAllCompletionService(executor); final TaskContextImpl taskContext = new TaskContextImpl(); int taskCount = 0; for (final Object key : keysToLoad) { if (taskContext.isStopped()) break; eacs.submit(new Callable<Void>() { @Override public Void call() throws Exception { try { final MarshalledEntry marshalledEntry = _load(key, fetchValue, fetchMetadata); if (marshalledEntry != null) { task.processEntry(marshalledEntry, taskContext); } return null; } catch (Exception e) { log.errorExecutingParallelStoreTask(e); throw e; } } }); } eacs.waitUntilAllCompleted(); if (eacs.isExceptionThrown()) { throw new CacheLoaderException("Execution exception!", eacs.getFirstException()); } }
Source:
protected void executeCommand() { createPdf = new CreatePdf(); String userId = getParameters().getUserId(); GlusterVolumeProfileInfo profileInfo = getParameters().getProfileInfo(); String filePath = ""; filePath = "/home/" + getGlusterVolumeDao().getById(profileInfo.getVolumeId()).getName(); try { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(filePath)); document.open(); createPdf.addMetaData(document, createMetaData(getGlusterVolumeDao().getById(profileInfo.getVolumeId()).getName(), userId)); addContent(document, profileInfo); document.close(); } catch (Exception e) { setSucceeded(false); setActionReturnValue(e.toString()); } }

Target:
protected void executeCommand() { try { createVolumeProfileDoc(); setSucceeded(true); } catch (DocumentException | IOException e) { e.printStackTrace(); } }
Source:
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { return findAnnotation(context.getElement(), EnabledForJreRange.class) .map(enabledForJreRange -> { JRE min = enabledForJreRange.min(); JRE max = enabledForJreRange.max(); Preconditions.condition(max.compareTo(min) >= 0, "@EnabledForJreRange.min must be lower or the same version as @EnabledForJreRange.max"); if (isCurrentVersionWithinRange(min, max)) { return ENABLED_ON_CURRENT_JRE; } else { return DISABLED_ON_CURRENT_JRE; } }).orElse(ENABLED_BY_DEFAULT); }

Target:
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) { return findAnnotation(context.getElement(), EnabledForJreRange.class) .map(enabledForJreRange -> { JRE min = enabledForJreRange.min(); JRE max = enabledForJreRange.max(); Preconditions.condition(max.compareTo(min) >= 0, "@EnabledForJreRange.min must be lower or the same version as @EnabledForJreRange.max"); if (isCurrentVersionWithinRange(min, max)) { return ENABLED_ON_CURRENT_JRE; } return DISABLED_ON_CURRENT_JRE; }).orElse(ENABLED_BY_DEFAULT); }
Source:
void testBlocking() throws Exception { final PageAccessSynchronizer sync = new PageAccessSynchronizer(Duration.ofSeconds(5)); final Duration hold = Duration.ofSeconds(1); final Instant t1locks[] = new Instant[1]; final Instant t2locks[] = new Instant[1]; class T1 extends Thread { @Override public void run() { sync.lockPage(1); t1locks[0] = Instant.now(); try { Thread.sleep(hold.toMillis()); } catch (InterruptedException e) { throw new RuntimeException(e); } sync.unlockAllPages(); } } class T2 extends Thread { @Override public void run() { sync.lockPage(1); t2locks[0] = Instant.now(); sync.unlockAllPages(); } } T1 t1 = new T1(); t1.setName("t1"); T2 t2 = new T2(); t2.setName("t2"); t1.start(); Thread.sleep(100); t2.start(); t1.join(); t2.join(); assertTrue(!t2locks[0].isBefore(t1locks[0].plus(hold))); }

Target:
void testBlocking() throws Exception { final PageAccessSynchronizer sync = new PageAccessSynchronizer(Duration.ofSeconds(5)); final Duration hold = Duration.ofSeconds(1); final Instant t1locks[] = new Instant[1]; final Instant t2locks[] = new Instant[1]; class T1 extends Thread { @Override public void run() { sync.lockPage(1); t1locks[0] = Instant.now(); try { Thread.sleep(hold.toMillis()); } catch (InterruptedException e) { throw new RuntimeException(e); } sync.unlockAllPages(); } } class T2 extends Thread { @Override public void run() { sync.lockPage(1); t2locks[0] = Instant.now(); sync.unlockAllPages(); } } T1 t1 = new T1(); t1.setName("t1"); T2 t2 = new T2(); t2.setName("t2"); t1.start(); TimeUnit.MILLISECONDS.sleep(100); t2.start(); t1.join(); t2.join(); assertTrue(!t2locks[0].isBefore(t1locks[0].plus(hold))); }
Source:
public void testColdReplayNoBackpressure() { ObservableCache<Integer> source = (ObservableCache<Integer>)new ObservableCache<Integer>(Observable.range(0, 1000), 16); assertFalse("Source is connected!", source.isConnected()); TestObserver<Integer> to = new TestObserver<Integer>(); source.subscribe(to); assertTrue("Source is not connected!", source.isConnected()); assertFalse("Subscribers retained!", source.hasObservers()); to.assertNoErrors(); to.assertTerminated(); List<Integer> onNextEvents = to.values(); assertEquals(1000, onNextEvents.size()); for (int i = 0; i < 1000; i++) { assertEquals((Integer)i, onNextEvents.get(i)); } }

Target:
public void testColdReplayNoBackpressure() { ObservableCache<Integer> source = new ObservableCache<Integer>(Observable.range(0, 1000), 16); assertFalse("Source is connected!", source.isConnected()); TestObserver<Integer> to = new TestObserver<Integer>(); source.subscribe(to); assertTrue("Source is not connected!", source.isConnected()); assertFalse("Subscribers retained!", source.hasObservers()); to.assertNoErrors(); to.assertTerminated(); List<Integer> onNextEvents = to.values(); assertEquals(1000, onNextEvents.size()); for (int i = 0; i < 1000; i++) { assertEquals((Integer)i, onNextEvents.get(i)); } }
Source:
protected ObserveResponse doObserve(ServerIdentity identity, ObserveRequest request) { return ObserveResponse.internalServerError("not implemented"); }

Target:
protected ObserveResponse doObserve(ServerIdentity identity, ObserveRequest request) { ReadResponse readResponse = this.read(identity, new ReadRequest(request.getPath().toString())); return new ObserveResponse(readResponse.getCode(), readResponse.getContent(), null, null, readResponse.getErrorMessage()); }
Source:
public void handleDefaultDeviceResponse(final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleDefaultDeviceResponse for MessageType: {}", messageType); ResponseMessageResultType result = deviceResult; OsgpException osgpException = exception; if (deviceResult == ResponseMessageResultType.NOT_OK && exception == null) { LOGGER.error("Incorrect response received, exception should not be null when result is not ok"); osgpException = new TechnicalException(ComponentType.DOMAIN_CORE, "An unknown error occurred"); } if (deviceResult == ResponseMessageResultType.OK && exception != null) { LOGGER.error("Incorrect response received, result should be set to not ok when exception is not null"); result = ResponseMessageResultType.NOT_OK; } this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(result).withOsgpException(osgpException) .build()); }

Target:
public void handleDefaultDeviceResponse(final String deviceIdentification, final String organisationIdentification, final String correlationUid, final String messageType, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleDefaultDeviceResponse for MessageType: {}", messageType); ResponseMessageResultType result = deviceResult; OsgpException osgpException = exception; if (deviceResult == ResponseMessageResultType.NOT_OK && exception == null) { LOGGER.error("Incorrect response received, exception should not be null when result is not ok"); osgpException = new TechnicalException(ComponentType.DOMAIN_CORE, "An unknown error occurred"); } if (deviceResult == ResponseMessageResultType.OK && exception != null) { LOGGER.error("Incorrect response received, result should be set to not ok when exception is not null"); result = ResponseMessageResultType.NOT_OK; } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(correlationUid).withOrganisationIdentification(organisationIdentification) .withDeviceIdentification(deviceIdentification).withResult(result).withOsgpException(osgpException) .build(); this.webServiceResponseMessageSender.send(responseMessage); }
Source:
static Set<ImmutableDruidDataSource> getDataSources(InventoryView serverInventoryView) { return serverInventoryView.getInventory().stream() .flatMap(server -> server.getDataSources().stream()) .map(DruidDataSource::toImmutableDruidDataSource) .collect( () -> new TreeSet<>(Comparator.comparing(ImmutableDruidDataSource::getName)), TreeSet::add, TreeSet::addAll ); }

Target:
static SortedSet<ImmutableDruidDataSource> getDataSources(InventoryView serverInventoryView) { return serverInventoryView.getInventory() .stream() .flatMap(server -> server.getDataSources().stream()) .map(DruidDataSource::toImmutableDruidDataSource) .collect( () -> new TreeSet<>(comparingByName()), TreeSet::add, TreeSet::addAll ); }
Source:
private void doScheduleSnapshot(Class<?> aggregateType, String aggregateIdentifier) { if (CurrentUnitOfWork.isStarted()) { Set<AggregateTypeId> scheduledSnapshotMap = CurrentUnitOfWork.get() .root() .getOrComputeResource(SCHEDULED_SNAPSHOT_SET, key -> new HashSet<>()); if (!scheduledSnapshotMap.add(new AggregateTypeId(aggregateType, aggregateIdentifier))) { return; } } executor.execute(new SilentTask(() -> transactionManager .executeInTransaction(createSnapshotterTask(aggregateType, aggregateIdentifier)))); }

Target:
private void doScheduleSnapshot(Class<?> aggregateType, String aggregateIdentifier) { AggregateTypeId typeAndId = new AggregateTypeId(aggregateType, aggregateIdentifier); if (CurrentUnitOfWork.isStarted()) { Set<AggregateTypeId> scheduledSnapshotMap = CurrentUnitOfWork.get() .root() .getOrComputeResource(SCHEDULED_SNAPSHOT_SET, key -> new HashSet<>()); if (!scheduledSnapshotMap.add(typeAndId)) { return; } } if (snapshotsInProgress.add(typeAndId)) { try { executor.execute( silently(() -> transactionManager.executeInTransaction(createSnapshotterTask(aggregateType, aggregateIdentifier))) .andFinally(() -> snapshotsInProgress.remove(typeAndId))); } catch (Exception e) { snapshotsInProgress.remove(typeAndId); throw e; } } }
Source:
public WorkerResource( Worker worker, WorkerCuratorCoordinator curatorCoordinator, TaskRunner taskRunner ) throws Exception { this.enabledWorker = worker; this.disabledWorker = new Worker( worker.getHost(), worker.getIp(), worker.getCapacity(), DISABLED_VERSION, enabledWorker.getLastCompletedTaskTime() ) { @Override @JsonProperty public String getHost() { return enabledWorker.getHost(); } @Override @JsonProperty public String getIp() { return enabledWorker.getIp(); } @Override @JsonProperty public int getCapacity() { return enabledWorker.getCapacity(); } @Override @JsonProperty public String getVersion() { return DISABLED_VERSION; } @Override @JsonProperty public DateTime getLastCompletedTaskTime() { return enabledWorker.getLastCompletedTaskTime(); } }; this.curatorCoordinator = curatorCoordinator; this.taskRunner = taskRunner; }

Target:
public WorkerResource( Worker worker, WorkerCuratorCoordinator curatorCoordinator, TaskRunner taskRunner ) throws Exception { this.enabledWorker = worker; this.curatorCoordinator = curatorCoordinator; this.taskRunner = taskRunner; }
Source:
private void updateSpmPriority() { if (spmPriorityValue == null) { setSpmPriority(null); } else if (spmPriorityValue == spmLowPriorityValue) { setSpmPriority(ConstantsManager.getInstance().getConstants().lowTitle()); } else if (spmPriorityValue.equals(spmDefaultPriorityValue)) { setSpmPriority(ConstantsManager.getInstance().getConstants().mediumTitle()); } else if (spmPriorityValue == spmHighPriorityValue) { setSpmPriority(ConstantsManager.getInstance().getConstants().highTitle()); } else if (spmPriorityValue == spmNeverPriorityValue) { setSpmPriority(ConstantsManager.getInstance().getConstants().neverTitle()); } else { setSpmPriority(ConstantsManager.getInstance().getMessages().customSpmPriority(spmPriorityValue)); } }

Target:
private void updateSpmPriority() { Constants constants = ConstantsManager.getInstance().getConstants(); if (spmPriorityValue == null) { setSpmPriority(null); } else if (spmPriorityValue == spmLowPriorityValue) { setSpmPriority(constants.lowTitle()); } else if (spmPriorityValue.equals(spmDefaultPriorityValue)) { setSpmPriority(constants.mediumTitle()); } else if (spmPriorityValue == spmHighPriorityValue) { setSpmPriority(constants.highTitle()); } else if (spmPriorityValue == spmNeverPriorityValue) { setSpmPriority(constants.neverTitle()); } else { setSpmPriority(ConstantsManager.getInstance().getMessages().customSpmPriority(spmPriorityValue)); } }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.dayId == null) ? 0 : this.dayId.hashCode()); result = prime * result + ((this.dayProfileActionList == null) ? 0 : this.dayProfileActionList.hashCode()); return result; }

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.dayId.hashCode(); result = prime * result + this.dayProfileActionList.hashCode(); return result; }
Source:
void leaveGroup(InetAddress group, NetworkInterface netInterface, InetAddress source) throws IOException { final NativeInetAddress g = NativeInetAddress.newInstance(group); final NativeInetAddress i = NativeInetAddress.newInstance( deriveInetAddress(netInterface, group instanceof Inet6Address) ); if (source != null) { final NativeInetAddress s = NativeInetAddress.newInstance(source); leaveSsmGroup(intValue(), g.address(), i.address(), g.scopeId(), s.address()); } else { leaveGroup(intValue(), g.address(), i.address(), g.scopeId()); } }

Target:
void leaveGroup(InetAddress group, NetworkInterface netInterface, InetAddress source) throws IOException { final NativeInetAddress g = NativeInetAddress.newInstance(group); final boolean isIpv6 = group instanceof Inet6Address; final NativeInetAddress i = NativeInetAddress.newInstance(deriveInetAddress(netInterface, isIpv6)); if (source != null) { final NativeInetAddress s = NativeInetAddress.newInstance(source); leaveSsmGroup(intValue(), g.address(), i.address(), g.scopeId(), s.address()); } else { leaveGroup(intValue(), g.address(), i.address(), g.scopeId()); } }
Source:
public void rollbackTo(Savepoint savepoint, boolean trimToSize) { int index = savepoint == null ? 0 : savepoint.logIndex; while (undoLog.size() > index) { UndoLogRecord entry = undoLog.getLast(); entry.undo(this); undoLog.removeLast(trimToSize); } if (transaction != null) { long savepointId = savepoint == null ? 0 : savepoint.transactionSavepoint; HashMap<String, MVTable> tableMap = database.getMvStore().getTables(); Iterator<Change> it = transaction.getChanges(savepointId); while (it.hasNext()) { Change c = it.next(); MVTable t = tableMap.get(c.mapName); if (t != null) { long key = ((ValueLong) c.key).getLong(); ValueArray value = (ValueArray) c.value; short op; Row row; if (value == null) { op = UndoLogRecord.INSERT; row = t.getRow(this, key); } else { op = UndoLogRecord.DELETE; row = createRow(value.getList(), Row.MEMORY_CALCULATE); } row.setKey(key); UndoLogRecord log = new UndoLogRecord(t, op, row); log.undo(this); } } } if (savepoints != null) { String[] names = savepoints.keySet().toArray(new String[0]); for (String name : names) { Savepoint sp = savepoints.get(name); int savepointIndex = sp.logIndex; if (savepointIndex > index) { savepoints.remove(name); } } } }

Target:
public void rollbackTo(Savepoint savepoint, boolean trimToSize) { int index = savepoint == null ? 0 : savepoint.logIndex; while (undoLog.size() > index) { UndoLogRecord entry = undoLog.getLast(); entry.undo(this); undoLog.removeLast(trimToSize); } if (transaction != null) { long savepointId = savepoint == null ? 0 : savepoint.transactionSavepoint; HashMap<String, MVTable> tableMap = database.getMvStore().getTables(); Iterator<Change> it = transaction.getChanges(savepointId); while (it.hasNext()) { Change c = it.next(); MVTable t = tableMap.get(c.mapName); if (t != null) { long key = ((ValueLong) c.key).getLong(); ValueArray value = (ValueArray) c.value; short op; Row row; if (value == null) { op = UndoLogRecord.INSERT; row = t.getRow(this, key); } else { op = UndoLogRecord.DELETE; row = createRow(value.getList(), Row.MEMORY_CALCULATE); } row.setKey(key); UndoLogRecord log = new UndoLogRecord(t, op, row); log.undo(this); } } } if (savepoints != null) { String[] names = savepoints.keySet().toArray(new String[savepoints.size()]); for (String name : names) { Savepoint sp = savepoints.get(name); int savepointIndex = sp.logIndex; if (savepointIndex > index) { savepoints.remove(name); } } } }
Source:
public void startScreencast(final JsonRpcPeer peer, JSONObject params) { final StartScreencastRequest request = mObjectMapper.convertValue( params, StartScreencastRequest.class); mScreencastDispatcher.startScreencast(peer, request); }

Target:
public void startScreencast(final JsonRpcPeer peer, JSONObject params) { final StartScreencastRequest request = mObjectMapper.convertValue( params, StartScreencastRequest.class); if (mScreencastDispatcher == null) { mScreencastDispatcher = new ScreencastDispatcher(); mScreencastDispatcher.startScreencast(peer, request); } }
Source:
public Identity decode(final byte[] bytes) throws IOException { final byte[] raw = Base64.decodeBase64(bytes); return this.origin.decode(raw); }

Target:
public Identity decode(final byte[] bytes) throws IOException { return this.origin.decode(bytes); }
Source:
public static boolean isCronExpressionValid(String cronExpression, DateTimeZone timezone) { if (!CronExpression.isValidExpression(cronExpression)) { return false; } else { CronExpression cronExecutionTime = parseCronExpression(cronExpression, timezone); if (cronExecutionTime == null || cronExecutionTime.getNextValidTimeAfter(new Date()) == null) { return false; } return true; } }

Target:
public static boolean isCronExpressionValid(String cronExpression, DateTimeZone timezone) { if (!CronExpression.isValidExpression(cronExpression)) { return false; } CronExpression cronExecutionTime = parseCronExpression(cronExpression, timezone); if (cronExecutionTime == null || cronExecutionTime.getNextValidTimeAfter(new Date()) == null) { return false; } return true; }
Source:
public DeclarationScope(DeclarationScope parentScope) { this.fParentScope = parentScope; }

Target:
public DeclarationScope(DeclarationScope parentScope) { fParentScope = parentScope; }
Source:
static Stream<Map<String, String>> provider() { Map<String, String> sampleMap = new HashMap<>(); sampleMap.put("header", "value"); sampleMap.put("test", "3"); return Stream.of( sampleMap, Collections.singletonMap("header", String.valueOf(Integer.MAX_VALUE)), Collections.emptyMap()); }

Target:
static Stream<Map<String, String>> provider() { Map<String, String> sampleMap = new HashMap<>(); sampleMap.put("header", "value"); sampleMap.put("test", "3"); return Stream.of( sampleMap, Collections.singletonMap("header", String.valueOf(Integer.MAX_VALUE)), Collections.emptyMap(), Collections.singletonMap("", ""), Collections.singletonMap("header", ""), Collections.singletonMap("", "value")); }
Source:
public void testUndefinedRegion() { final KeystoneStorageEndpointModule moduleToTest = new KeystoneStorageEndpointModule(); Supplier<URI> resultingSupplier = moduleToTest.provideStorageUrl(mockFactory, apiVersion, "region-that-dne"); Assert.assertNotNull(resultingSupplier); URI resultingUri = resultingSupplier.get(); Assert.assertNull(resultingUri); }

Target:
public void testUndefinedRegion() { final KeystoneStorageEndpointModule moduleToTest = new KeystoneStorageEndpointModule(); Supplier<URI> resultingSupplier = moduleToTest.provideStorageUrl(mockFactory, apiVersion, "region-that-dne"); assertNotNull(resultingSupplier); URI resultingUri = resultingSupplier.get(); assertNull(resultingUri); }
Source:
private Object doResumableUpload() throws IOException, InterruptedException { String uploadId = startResumableUpload(); InsertChunkResponseObserver responseObserver; long writeOffset = 0; Hasher objectHasher = Hashing.crc32c().newHasher(); do { ByteString chunkData = ByteString.EMPTY; responseObserver = new InsertChunkResponseObserver(uploadId, chunkData, writeOffset, objectHasher); stub.insertObject(responseObserver); responseObserver.done.await(); writeOffset += responseObserver.bytesWritten(); } while (!responseObserver.isFinished()); if (responseObserver.hasError()) { logger.atSevere().withCause(responseObserver.getError()).log("Error:"); throw new IOException("Insert failed", responseObserver.getError()); } return responseObserver.getResponse(); }

Target:
private Object doResumableUpload() throws IOException, InterruptedException { String uploadId = startResumableUpload(); InsertChunkResponseObserver responseObserver; long writeOffset = 0; Hasher objectHasher = Hashing.crc32c().newHasher(); do { ByteString chunkData = ByteString.EMPTY; responseObserver = new InsertChunkResponseObserver(uploadId, chunkData, writeOffset, objectHasher); stub.insertObject(responseObserver); responseObserver.done.await(); writeOffset += responseObserver.bytesWritten(); } while (!responseObserver.isFinished()); if (responseObserver.hasError()) { throw new IOException("Insert failed", responseObserver.getError()); } return responseObserver.getResponse(); }
Source:
public Map getParameterValues() { if (bndrunFilesMap != null) { return bndrunFilesMap; } IWorkspaceRoot root = ResourcesPlugin.getWorkspace() .getRoot(); synchronized (root) { if (bndrunFilesMap == null) { bndrunFilesMap = Arrays.stream(root.getProjects()) .filter(IProject::isOpen) .map(this::findBndrunFiles) .flatMap(Collection::stream) .map(IResource::getFullPath) .collect(toMap(IPath::toPortableString, IPath::toPortableString)); ResourcesPlugin.getWorkspace() .addResourceChangeListener(listener); } } return bndrunFilesMap; }

Target:
public Map getParameterValues() { return bndrunFilesMap.get(); }
Source:
protected Extent getExtent() { if (extent == null) { extent = Request.request().getEditSession(); } return extent; }

Target:
protected Extent getExtent() { if (request == null || !request.isValid()) { request = Request.request(); } return request.getEditSession(); }
Source:
private void loadToplist(String country) { if (disposable != null) { disposable.dispose(); } gridView.setVisibility(View.GONE); txtvError.setVisibility(View.GONE); butRetry.setVisibility(View.GONE); txtvEmpty.setVisibility(View.GONE); progressBar.setVisibility(View.VISIBLE); if (country.equals(ItunesTopListLoader.DISCOVER_HIDE_FAKE_COUNTRY_CODE)) { gridView.setVisibility(View.GONE); txtvError.setVisibility(View.VISIBLE); txtvError.setText(String.format(getResources().getString(R.string.discover_will_be_hidden), getResources().getString(R.string.discover_hide))); butRetry.setVisibility(View.GONE); txtvEmpty.setVisibility(View.GONE); progressBar.setVisibility(View.GONE); } else { ItunesTopListLoader loader = new ItunesTopListLoader(getContext()); disposable = loader.loadToplist(country, 25).subscribe( podcasts -> { progressBar.setVisibility(View.GONE); topList = podcasts; updateData(topList); }, error -> { Log.e(TAG, Log.getStackTraceString(error)); progressBar.setVisibility(View.GONE); txtvError.setText(error.toString()); txtvError.setVisibility(View.VISIBLE); butRetry.setOnClickListener(v -> loadToplist(country)); butRetry.setVisibility(View.VISIBLE); }); } }

Target:
private void loadToplist(String country) { if (disposable != null) { disposable.dispose(); } gridView.setVisibility(View.GONE); txtvError.setVisibility(View.GONE); butRetry.setVisibility(View.GONE); txtvEmpty.setVisibility(View.GONE); progressBar.setVisibility(View.VISIBLE); if (country.equals(ItunesTopListLoader.DISCOVER_HIDE_FAKE_COUNTRY_CODE)) { gridView.setVisibility(View.GONE); txtvError.setVisibility(View.VISIBLE); txtvError.setText(getResources().getString(R.string.discover_is_hidden)); butRetry.setVisibility(View.GONE); txtvEmpty.setVisibility(View.GONE); progressBar.setVisibility(View.GONE); } else { ItunesTopListLoader loader = new ItunesTopListLoader(getContext()); disposable = loader.loadToplist(country, 25).subscribe( podcasts -> { progressBar.setVisibility(View.GONE); topList = podcasts; updateData(topList); }, error -> { Log.e(TAG, Log.getStackTraceString(error)); progressBar.setVisibility(View.GONE); txtvError.setText(error.getMessage()); txtvError.setVisibility(View.VISIBLE); butRetry.setOnClickListener(v -> loadToplist(country)); butRetry.setVisibility(View.VISIBLE); }); } }
Source:
private static MethodTree usedInOneMethodOnly(Symbol privateFieldSymbol, TypeSymbol classSymbol) { Set<MethodTree> methods = new HashSet<>(); for (IdentifierTree usageIdentifier : privateFieldSymbol.usages()) { Tree containingClassOrMethod = containingClassOrMethod(usageIdentifier); if (containingClassOrMethod.is(Kind.CLASS) || !((MethodTree) containingClassOrMethod).symbol().owner().equals(classSymbol) || (methods.size() == 1 && !methods.contains(containingClassOrMethod))) { return null; } else { methods.add((MethodTree)containingClassOrMethod); } } return methods.iterator().next(); }

Target:
private static MethodTree usedInOneMethodOnly(Symbol privateFieldSymbol, TypeSymbol classSymbol) { MethodTree method = null; for (IdentifierTree usageIdentifier : privateFieldSymbol.usages()) { Tree containingClassOrMethod = containingClassOrMethod(usageIdentifier); if (containingClassOrMethod.is(Kind.CLASS) || !((MethodTree) containingClassOrMethod).symbol().owner().equals(classSymbol) || (method != null && !method.equals(containingClassOrMethod))) { return null; } else { method = (MethodTree)containingClassOrMethod; } } return method; }
Source:
public void passesValidationForClasspathSchema() throws Exception { final Environment env = new Environment.Mock().withFile( "test-classpath-schema.xml", new StringBuilder() .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") .append("<foo xmlns=\"<LINK_0>\" ") .append("xmlns:xsi=\"") .append("<LINK_1>") .append("\" ") .append("xsi:schemaLocation=\"") .append("<LINK_0> ") .append("test-classpath-schema.xsd") .append("\">") .append("<bar>333</bar>") .append("<baz>444</baz>") .append("</foo>").toString() ); final Validator validator = new XmlValidator(); validator.validate(env); }

Target:
public void passesValidationForClasspathSchema() throws Exception { final Environment env = new Environment.Mock().withFile( "test-classpath-schema.xml", new StringBuilder() .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") .append("<foo xmlns=\"<LINK_0>\" ") .append("xmlns:xsi=\"") .append("<LINK_1>") .append("\" ") .append("xsi:schemaLocation=\"") .append("<LINK_0> ") .append("test-classpath-schema.xsd") .append("\">") .append("<bar>333</bar>") .append("<baz>444</baz>") .append("</foo>").toString() ); new XmlValidator().validate(env); }
Source:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); parseConfiguration(config.decode); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { for (Schema.Field field : inputSchema.getFields()) { if (decodeMap.containsKey(field.getName())) { if (!field.getSchema().getType().equals(Schema.Type.BYTES) && !field.getSchema().getType().equals(Schema.Type.STRING)) { throw new IllegalArgumentException( String.format("Field %s is of type %s in Input Schema, currently only String and Bytes can be decoded", field.getName(), field.getSchema().getType())); } } } } try { Schema outputSchema = Schema.parseJson(config.schema); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); } catch (IOException e) { throw new IllegalArgumentException("Format of schema specified is invalid. Please check the format."); } }

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); parseConfiguration(config.decode); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { for (Schema.Field field : inputSchema.getFields()) { if (decodeMap.containsKey(field.getName())) { if (!field.getSchema().getType().equals(Schema.Type.BYTES) && !field.getSchema().getType().equals(Schema.Type.STRING)) { throw new IllegalArgumentException( String.format("Input field %s should be of type bytes or string. It is currently of type %s", field.getName(), field.getSchema().getType().toString())); } } } } try { Schema outputSchema = Schema.parseJson(config.schema); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); } catch (IOException e) { throw new IllegalArgumentException("Format of schema specified is invalid. Please check the format."); } }
Source:
protected void done() { if (!isCancelled() && this.owningTask != null) { this.owningTask.cancel(); } super.done(); }

Target:
protected void done() { if (!isCancelled() && this.owningTask != null) { this.owningTask.cancel(); } }
Source:
public void shutdown() { initialized = false; }

Target:
public void shutdown() { JOpenVRLibrary.VR_ShutdownInternal(); vrSystem = null; vrCompositor = null; vrOverlay = null; vrSettings = null; vrState = null; initialized = false; }
Source:
public ImmutableList<TransferSegment> createStateList(Layout layout, long trimMark) { return layout.getSegments() .stream() .filter(segment -> segment.getEnd() != NON_ADDRESS && segment.getEnd() >= trimMark) .map(segment -> { long segmentStart = Math.max(segment.getStart(), trimMark); long segmentEnd = segment.getEnd() - 1L; if (segmentContainsServer(segment, getServer())) { TransferSegmentStatus restored = TransferSegmentStatus .builder() .segmentState(RESTORED) .totalTransferred(segmentEnd - segmentStart + 1L) .build(); return TransferSegment .builder() .startAddress(segmentStart) .endAddress(segmentEnd) .status(restored) .build(); } else { TransferSegmentStatus notTransferred = TransferSegmentStatus .builder() .segmentState(NOT_TRANSFERRED) .totalTransferred(0L) .build(); return TransferSegment .builder() .startAddress(segmentStart) .endAddress(segmentEnd) .status(notTransferred) .build(); } }) .collect(ImmutableList.toImmutableList()); }

Target:
public ImmutableList<TransferSegment> createStateList(Layout layout, long trimMark) { return layout.getSegments() .stream() .filter(segment -> segment.getEnd() != NON_ADDRESS && segment.getEnd() > trimMark) .map(segment -> { long segmentStart = Math.max(segment.getStart(), trimMark); long segmentEnd = segment.getEnd() - 1L; if (segmentContainsServer(segment, getServer())) { TransferSegmentStatus restored = TransferSegmentStatus .builder() .segmentState(RESTORED) .totalTransferred(segmentEnd - segmentStart + 1L) .build(); return TransferSegment .builder() .startAddress(segmentStart) .endAddress(segmentEnd) .status(restored) .build(); } else { TransferSegmentStatus notTransferred = TransferSegmentStatus .builder() .segmentState(NOT_TRANSFERRED) .totalTransferred(0L) .build(); return TransferSegment .builder() .startAddress(segmentStart) .endAddress(segmentEnd) .status(notTransferred) .build(); } }) .collect(ImmutableList.toImmutableList()); }
Source:
protected static String parseString(final String unformattedString, final Matcher m, final MonitoredService svc) { Pattern p = subPatterns.get(m.group(1)); if (p != null) { } else { LOG.error("invalid substitution pattern found: {}", m.group(1)); return null; } Matcher n = p.matcher(unformattedString); String formattedString; if (n.matches()) { StringBuilder sb = new StringBuilder(); sb.append(n.group(1)); switch (m.group(1)) { case "ipAddr": case "ipAddress": sb.append(svc.getIpAddr()); break; case "nodeId": sb.append(svc.getNodeId()); break; case "nodeLabel": sb.append(svc.getNodeLabel()); break; case "foreignId": sb.append(nodeDao.get().get(svc.getNodeId()).getForeignId()); break; case "foreignSource": sb.append(nodeDao.get().get(svc.getNodeId()).getForeignSource()); break; default: LOG.debug("attempting to add node asset property {}", m.group(1)); OnmsNode node = nodeDao.get().get(svc.getNodeId()); if (node != null) { BeanWrapper wrapper = new BeanWrapperImpl(node.getAssetRecord()); Object obj = wrapper.getPropertyValue(m.group(1)); if (obj != null) { sb.append(obj.toString()); } } } sb.append(n.group(2)); formattedString = sb.toString(); } else { throw new IllegalStateException("Engineering mistake: the regular expression seems to be wrong."); } Matcher o = substitutionPattern.matcher(formattedString); if (o.matches()) { return parseString(formattedString, o, svc); } return formattedString; }

Target:
protected static String parseString(final String unformattedString, final Matcher m, final MonitoredService svc) { Pattern p = subPatterns.get(m.group(1)); if (p != null) { } else { LOG.error("invalid substitution pattern found: {}", m.group(1)); return null; } Matcher n = p.matcher(unformattedString); String formattedString; if (n.matches()) { StringBuilder sb = new StringBuilder(); sb.append(n.group(1)); switch (m.group(1)) { case "ipAddr": case "ipAddress": sb.append(svc.getIpAddr()); break; case "nodeId": sb.append(svc.getNodeId()); break; case "nodeLabel": sb.append(svc.getNodeLabel()); break; case "foreignId": sb.append(nodeDao.get().get(svc.getNodeId()).getForeignId()); break; case "foreignSource": sb.append(nodeDao.get().get(svc.getNodeId()).getForeignSource()); break; default: LOG.debug("attempting to add node asset property {}", m.group(1)); OnmsNode node = nodeDao.get().get(svc.getNodeId()); if (node != null) { BeanWrapper wrapper = new BeanWrapperImpl(node.getAssetRecord()); Object obj = wrapper.getPropertyValue(m.group(1)); if (obj != null) { sb.append(obj.toString()); } } } sb.append(n.group(2)); formattedString = sb.toString(); } else { throw new IllegalStateException( String.format("Engineering mistake: we should never end up here, the regular expression seems to have a problem: %s", substitutionPattern.toString())); } Matcher o = substitutionPattern.matcher(formattedString); if (o.matches()) { return parseString(formattedString, o, svc); } return formattedString; }
Source:
public ArtifactArchiver(String artifacts, String excludes, boolean latestOnly) { this(artifacts, excludes, latestOnly, false, false, true); }

Target:
public ArtifactArchiver(String artifacts, String excludes, boolean latestOnly) { this(artifacts, excludes, latestOnly, false, false); }
Source:
private static int indexOfEOS(byte[] data, int fromIndex, int encodingByte) { int terminationPos = indexOf(data, fromIndex, (byte) 0); if(encodingByte == ID3_TEXT_ENCODING_ISO_8859_1 || encodingByte == ID3_TEXT_ENCODING_UTF_8) { return terminationPos; } while(terminationPos < data.length - 1) { if(data[terminationPos + 1] == (byte) 0) { return terminationPos + 1; } terminationPos = indexOf(data, terminationPos + 1, (byte) 0); } return data.length; }

Target:
private static int indexOfEOS(byte[] data, int fromIndex, int encodingByte) { int terminationPos = indexOf(data, fromIndex, (byte) 0); if(encodingByte == ID3_TEXT_ENCODING_ISO_8859_1 || encodingByte == ID3_TEXT_ENCODING_UTF_8) { return terminationPos; } while(terminationPos < data.length - 1) { if(data[terminationPos + 1] == (byte) 0) { return terminationPos; } terminationPos = indexOf(data, terminationPos + 1, (byte) 0); } return data.length; }
Source:
private void InitializeHelpers() { try { for (String helperName : EnumCompat.GetNames(StorageType.class)) { java.lang.Class actionType = null; try { actionType = java.lang.Class.forName(String.format("%1$s.%2$s%3$s", "org.ovirt.engine.core.bll.storage", helperName, "StorageHelper")); } catch (ClassNotFoundException cnfe) { } if (actionType != null) { java.lang.reflect.Constructor<?> info = actionType.getConstructors()[0]; Object tempVar = info.newInstance(null); IStorageHelper currentHelper = (IStorageHelper) ((tempVar instanceof IStorageHelper) ? tempVar : null); if (currentHelper != null) { _helpers.put(StorageType.valueOf(helperName), currentHelper); } } } } catch (Exception ex) { throw new ApplicationException("JTODO missing exception", ex); } }

Target:
private void InitializeHelpers() { try { for (String helperName : EnumCompat.GetNames(StorageType.class)) { java.lang.Class<?> actionType = null; try { actionType = java.lang.Class.forName(String.format("%1$s.%2$s%3$s", "org.ovirt.engine.core.bll.storage", helperName, "StorageHelper")); } catch (ClassNotFoundException cnfe) { } if (actionType != null) { java.lang.reflect.Constructor info = actionType.getConstructors()[0]; Object tempVar = info.newInstance(null); IStorageHelper currentHelper = (IStorageHelper) ((tempVar instanceof IStorageHelper) ? tempVar : null); if (currentHelper != null) { _helpers.put(StorageType.valueOf(helperName), currentHelper); } } } } catch (Exception ex) { throw new ApplicationException("JTODO missing exception", ex); } }
Source:
public void close() { clusterMembership.unregisterProcessor(); }

Target:
public void close() { if (!closed && processorId != null) { closed = true; clusterMembership.unregisterProcessor(processorId); } }
Source:
public int updateExperiment(String expID, HashMap<String, String> annotations) throws SQLException, IOException { for (Entry<String, String> e : annotations.entrySet()) { String key = e.getKey(); String value = e.getValue(); e.setValue(validateAnnotation(key, value)); } String query = "UPDATE Annotated_With SET Value = ?" + " WHERE (Label ~~* ?) AND (ExpID ~~* ?)"; int rs = 0; ArrayList<String> keys = new ArrayList<>(); try (PreparedStatement stmt = conn.prepareStatement(query);) { conn.setAutoCommit(false); for (Entry<String, String> e : annotations.entrySet()) { String key = e.getKey(); String value = e.getValue(); keys.add(key); stmt.setString(1, value); stmt.setString(2, key); stmt.setString(3, expID); stmt.addBatch(); } int arr[] = stmt.executeBatch(); for (int i = 0; i < arr.length; i++) { if (arr[i] == 0) { String label = keys.get(i); String value = annotations.get(label); arr[i] = annotateExperiment(expID, label, value); } rs += arr[i]; } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.setAutoCommit(true); } return rs; }

Target:
public int updateExperiment(String expID, HashMap<String, String> annotations) throws SQLException, IOException { for (Entry<String, String> e : annotations.entrySet()) { String key = e.getKey(); String value = e.getValue(); e.setValue(validateAnnotation(key, value)); } String query = "UPDATE Annotated_With SET Value = ?" + " WHERE (Label ~~* ?) AND (ExpID ~~* ?)"; int rs = 0; ArrayList<String> keys = new ArrayList<>(); try (PreparedStatement stmt = conn.prepareStatement(query);) { conn.setAutoCommit(false); for (Entry<String, String> e : annotations.entrySet()) { String key = e.getKey(); String value = e.getValue(); keys.add(key); stmt.setString(1, value); stmt.setString(2, key); stmt.setString(3, expID); stmt.addBatch(); } int arr[] = stmt.executeBatch(); for (int i = 0; i < arr.length; i++) { if (arr[i] == 0) { String label = keys.get(i); String value = annotations.get(label); arr[i] = annotateExperiment(expID, label, value); } rs += arr[i]; } conn.commit(); } catch (SQLException | IOException e) { conn.rollback(); throw e; } finally { conn.setAutoCommit(true); } return rs; }
Source:
public WebSocketClientHandshaker08 setForceCloseTimeoutMillis(long forceCloseTimeoutMillis) { this.forceCloseTimeoutMillis = forceCloseTimeoutMillis; return this; }

Target:
public WebSocketClientHandshaker08 setForceCloseTimeoutMillis(long forceCloseTimeoutMillis) { super.setForceCloseTimeoutMillis(forceCloseTimeoutMillis); return this; }
Source:
public void forEachTuple(final ModelConsumer consumer, EntityKeyMetadata... entityKeyMetadatas) { for ( EntityKeyMetadata entityKeyMetadata : entityKeyMetadatas ) { KeyScanCursor<byte[]> cursor = null; String pattern = entityKeyMetadata.getTable() + ":*"; do { if ( cursor != null ) { cursor = connection.scan( cursor, ScanArgs.Builder.matches( pattern ) ); } else { cursor = connection.scan( ScanArgs.Builder.matches( pattern ) ); } for ( byte[] key : cursor.getKeys() ) { String type = connection.type( key ); EntityStorageStrategy entityStorageStrategy; if ( "hash".equalsIgnoreCase( type ) ) { entityStorageStrategy = entityStorageStrategies.get( EntityStorageType.HASH ); } else { entityStorageStrategy = entityStorageStrategies.get( EntityStorageType.JSON ); } Entity document = entityStorageStrategy.getEntity( key ); consumer.consume( new Tuple( new RedisTupleSnapshot( document.getProperties() ) ) ); } } while ( !cursor.isFinished() ); } }

Target:
public void forEachTuple(final ModelConsumer consumer, EntityKeyMetadata... entityKeyMetadatas) { for ( EntityKeyMetadata entityKeyMetadata : entityKeyMetadatas ) { KeyScanCursor<byte[]> cursor = null; String prefix = entityKeyMetadata.getTable() + ":"; byte[] prefixBytes = toBytes( prefix ); ScanArgs scanArgs = ScanArgs.Builder.matches( prefix + "*" ); do { if ( cursor != null ) { cursor = connection.scan( cursor, scanArgs ); } else { cursor = connection.scan( scanArgs ); } for ( byte[] key : cursor.getKeys() ) { String type = connection.type( key ); Entity document = entityStorageStrategy.getEntity( key ); addKeyValuesFromKeyName( entityKeyMetadata, prefixBytes, key, document ); consumer.consume( new Tuple( new RedisTupleSnapshot( document.getProperties() ) ) ); } } while ( !cursor.isFinished() ); } }
Source:
@Override public Iterator<E> iterator() { lock.lock(); try { return queue.iterator(); } finally { lock.unlock(); } }

Target:
@Override public Iterator<E> iterator() { return queue.iterator(); }
Source:
private void writeDiskDriver(VmDevice device, Disk disk, DiskVmElement dve) { writer.writeStartElement("driver"); writer.writeAttributeString("name", "qemu"); if (FeatureSupported.passDiscardSupported(vm.getCompatibilityVersion()) && dve.isPassDiscard()) { writer.writeAttributeString("discard", "unmap"); } if (device.getSpecParams().containsKey("pinToIoThread")) { writer.writeAttributeString("iothread", device.getSpecParams().get("pinToIoThread").toString()); } switch (disk.getDiskStorageType()) { case IMAGE: DiskImage diskImage = (DiskImage) disk; String diskType = this.vmInfoBuildUtils.getDiskType(this.vm, diskImage); writer.writeAttributeString("io", "file".equals(diskType) ? "native" : "threads"); writer.writeAttributeString("type", diskImage.getVolumeFormat() == VolumeFormat.COW ? "qcow2" : "raw"); writer.writeAttributeString("error_policy", disk.getPropagateErrors() == PropagateErrors.On ? "enospace" : "stop"); break; case LUN: writer.writeAttributeString("io", "native"); writer.writeAttributeString("type", "raw"); writer.writeAttributeString("error_policy", disk.getPropagateErrors() == PropagateErrors.On ? "enospace" : "stop"); break; case CINDER: writer.writeAttributeString("type", "raw"); writer.writeAttributeString("error_policy", "stop"); writer.writeAttributeString("io", "threads"); break; } if (device.getSnapshotId() != null) { writer.writeAttributeString("cache", "writethrough"); } else { switch (dve.getDiskInterface()) { case VirtIO: default: writer.writeAttributeString("cache", "none"); } } writer.writeEndElement(); }

Target:
private void writeDiskDriver(VmDevice device, Disk disk, DiskVmElement dve) { writer.writeStartElement("driver"); writer.writeAttributeString("name", "qemu"); if (FeatureSupported.passDiscardSupported(vm.getCompatibilityVersion()) && dve.isPassDiscard()) { writer.writeAttributeString("discard", "unmap"); } if (device.getSpecParams().containsKey("pinToIoThread")) { writer.writeAttributeString("iothread", device.getSpecParams().get("pinToIoThread").toString()); } switch (disk.getDiskStorageType()) { case IMAGE: DiskImage diskImage = (DiskImage) disk; String diskType = this.vmInfoBuildUtils.getDiskType(this.vm, diskImage); writer.writeAttributeString("io", "file".equals(diskType) ? "threads" : "native"); writer.writeAttributeString("type", diskImage.getVolumeFormat() == VolumeFormat.COW ? "qcow2" : "raw"); writer.writeAttributeString("error_policy", disk.getPropagateErrors() == PropagateErrors.On ? "enospace" : "stop"); break; case LUN: writer.writeAttributeString("io", "native"); writer.writeAttributeString("type", "raw"); writer.writeAttributeString("error_policy", disk.getPropagateErrors() == PropagateErrors.On ? "enospace" : "stop"); break; case CINDER: writer.writeAttributeString("type", "raw"); writer.writeAttributeString("error_policy", "stop"); writer.writeAttributeString("io", "threads"); break; } if (device.getSnapshotId() != null) { writer.writeAttributeString("cache", "writethrough"); } else { switch (dve.getDiskInterface()) { case VirtIO: default: writer.writeAttributeString("cache", "none"); } } writer.writeEndElement(); }
Source:
public void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertContains(someInfo(), null, new int[] {0, 2, 4}, someIndex())) .withMessage(actualIsNull()); }

Target:
public void should_fail_if_actual_is_null() { int[][] actual = null; int[] expectedElement = new int[] {0, 2, 4}; AssertionError assertionError = expectAssertionError(() -> arrays.assertContains(someInfo(), actual, expectedElement, someIndex())); then(assertionError).hasMessage(shouldNotBeNull().create()); }