auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean canParseResource(final HttpMessage message) { try { String baseURL = getURIfromMessage(message); String contentType = message.getResponseHeader().getHeader(HttpHeader.CONTENT_TYPE); if (baseURL.endsWith(".wsdl") || contentType.equals("text/xml") || contentType.equals("application/wsdl+xml")) { String content = message.getResponseBody().toString(); if (parser.canBeWSDLparsed(content)) return true; LOG.debug("Content is not wsdl: " + content); } } catch (Exception e) { return false; } return false; }

Target:
public boolean canParseResource(final HttpMessage message) { try { String baseURL = getURIfromMessage(message); String contentType = message.getResponseHeader().getHeader(HttpHeader.CONTENT_TYPE); if (baseURL.endsWith(".wsdl") || contentType.equals("text/xml") || contentType.equals("application/wsdl+xml")) { String content = message.getResponseBody().toString(); if (parser.canBeWSDLparsed(content)) return true; if (LOG.isDebugEnabled()) { LOG.debug("Content is not wsdl: " + content); } } } catch (Exception e) { return false; } return false; }
Source:
public VertexQuery queryVertex(Graph graph, Vertex vertex, String queryString, Authorizations authorizations) { return new ElasticSearchParentChildVertexQuery( getClient(), getConfig().getIndicesToQuery(), graph, vertex, queryString, getAllPropertyDefinitions(), getConfig().getScoringStrategy(), getConfig().getNameSubstitutionStrategy(), authorizations); }

Target:
public VertexQuery queryVertex(Graph graph, Vertex vertex, String queryString, Authorizations authorizations) { return new ElasticSearchParentChildVertexQuery( getClient(), getConfig().getIndicesToQuery(), graph, vertex, queryString, getAllPropertyDefinitions(), getConfig().getScoringStrategy(), this.nameSubstitutionStrategy, authorizations); }
Source:
private static void setVlanSpeeds(VDS vds) { List<VdsNetworkInterface> interfaces = vds.getInterfaces(); List<VdsNetworkInterface> vlans = interfaces .stream() .filter(iface -> iface.getVlanId() != null) .collect(Collectors.toList()); for (VdsNetworkInterface vlanIface : vlans) { VdsNetworkInterface baseInterface = interfaces .stream() .filter(iface -> iface.getName().equals(vlanIface.getBaseInterface())) .findFirst() .get(); vlanIface.setSpeed(baseInterface.getSpeed()); } }

Target:
private static void setVlanSpeeds(VDS vds) { List<VdsNetworkInterface> interfaces = vds.getInterfaces(); List<VdsNetworkInterface> vlans = interfaces .stream() .filter(iface -> NetworkCommonUtils.isVlan(iface)) .collect(Collectors.toList()); for (VdsNetworkInterface vlanIface : vlans) { VdsNetworkInterface baseInterface = interfaces .stream() .filter(iface -> iface.getName().equals(vlanIface.getBaseInterface())) .findFirst() .get(); vlanIface.setSpeed(baseInterface.getSpeed()); } }
Source:
public void test_presentValue_onEnd() { SimpleRatesProvider prov = provider(END_DATE); CurrencyAmount computed = PRICER.presentValue(TERM_DEPOSIT, prov); double expected = (1d + RATE * TERM_DEPOSIT.expand().getYearFraction()) * dfEnd * NOTIONAL; assertEquals(computed.getCurrency(), EUR); assertEquals(computed.getAmount(), expected, TOLERANCE * NOTIONAL); }

Target:
public void test_presentValue_onEnd() { SimpleRatesProvider prov = provider(END_DATE, 1.2d, 1.0d); CurrencyAmount computed = PRICER.presentValue(TERM_DEPOSIT, prov); double expected = (1d + RATE * TERM_DEPOSIT.expand().getYearFraction()) * 1.0d * NOTIONAL; assertEquals(computed.getCurrency(), EUR); assertEquals(computed.getAmount(), expected, TOLERANCE * NOTIONAL); }
Source:
public void addQueueNames(String... queueNames) { try { addQueues(Arrays.stream(queueNames)); } catch (AmqpIOException e) { throw new AmqpIOException("Failed to add " + queueNames, e.getCause()); } super.addQueueNames(queueNames); }

Target:
public void addQueueNames(String... queueNames) { try { addQueues(Arrays.stream(queueNames)); } catch (AmqpIOException e) { throw new AmqpIOException("Failed to add " + Arrays.asList(queueNames), e.getCause()); } super.addQueueNames(queueNames); }
Source:
public String q(boolean reload, boolean browser) { return _getQA(reload, browser).get("q"); }

Target:
public String q(boolean reload, boolean browser) { return css() + _getQA(reload, browser).get("q"); }
Source:
void validatePatchRequest(JsonNode payload){ List<String> pathCheck = requestValidator.checkIfExistsOrEmpty(payload, FIELD_OPERATION, FIELD_OPERATION_PATH); if(!pathCheck.isEmpty()){ throw new ValidationException(pathCheck); } String operation = payload.findValue(FIELD_OPERATION_PATH).asText(); if(!VALID_PATHS.contains(operation)) { throw new ValidationException(Collections.singletonList(format("Operation [%s] not supported for path [%s]", FIELD_OPERATION, payload.findValue(FIELD_OPERATION_PATH).asText()))); } if (operation.equalsIgnoreCase(FIELD_NOTIFY_SETTINGS)) { validateNotifySettingsRequest(payload); } }

Target:
void validatePatchRequest(JsonNode payload){ List<String> pathCheck = requestValidator.checkIfExistsOrEmpty(payload, FIELD_OPERATION, FIELD_OPERATION_PATH); if(!pathCheck.isEmpty()){ throw new ValidationException(pathCheck); } String path = payload.findValue(FIELD_OPERATION_PATH).asText(); if(!VALID_PATHS.contains(path)) { throw new ValidationException(Collections.singletonList(format("Operation [%s] not supported for path [%s]", FIELD_OPERATION, path))); } if (path.equalsIgnoreCase(FIELD_NOTIFY_SETTINGS)) { validateNotifySettingsRequest(payload); } if (path.equalsIgnoreCase(FIELD_EMAIL_COLLECTION_MODE)) { validateEmailCollectionMode(payload); } }
Source:
public BinaryHttpUpload initiateHttpUpload(String path, long maxSize, int maxParts) throws RepositoryException { if (! hasPermission(path, Session.ACTION_SET_PROPERTY)) { throw new AccessDeniedException(String.format("No permission to add binary property at path %s", path)); } return sd.safePerformNullable(new ReadOperation<BinaryHttpUpload>("initiateHttpUpload") { @Nullable @Override public BinaryHttpUpload performNullable() throws RepositoryException { HttpBlobProvider httpBlobProvider = getHttpBlobProvider(); if (httpBlobProvider == null) { return null; } BlobHttpUpload upload = httpBlobProvider.initiateHttpUpload(maxSize, maxParts); if (upload != null) { return new BinaryHttpUpload() { @Override public String getUploadToken() { return upload.getUploadToken(); } @Override public long getMinPartSize() { return upload.getMinPartSize(); } @Override public long getMaxPartSize() { return upload.getMaxPartSize(); } @Nonnull @Override public Collection<URL> getUploadURLs() { return upload.getUploadURLs(); } }; } return null; } }); }

Target:
public HttpBinaryUpload initiateHttpUpload(String path, long maxSize, int maxParts) throws RepositoryException { if (! hasPermission(path, Session.ACTION_SET_PROPERTY)) { throw new AccessDeniedException(String.format("No permission to add binary property at path %s", path)); } return sd.safePerformNullable(new ReadOperation<HttpBinaryUpload>("initiateHttpUpload") { @Nullable @Override public HttpBinaryUpload performNullable() throws RepositoryException { HttpBlobProvider httpBlobProvider = getHttpBlobProvider(); if (httpBlobProvider == null) { return null; } HttpBlobUpload upload = httpBlobProvider.initiateHttpUpload(maxSize, maxParts); if (upload != null) { return new HttpBinaryUpload() { @Override public String getUploadToken() { return upload.getUploadToken(); } @Override public long getMinPartSize() { return upload.getMinPartSize(); } @Override public long getMaxPartSize() { return upload.getMaxPartSize(); } @Nonnull @Override public Collection<URL> getUploadURLs() { return upload.getUploadURLs(); } }; } return null; } }); }
Source:
public void init() throws Exception { initMocks(this); processor = new FulltextProcessor(fileName); file = tmpDir.newFile(fileName + ".txt"); file.deleteOnExit(); when(exchange.getIn()).thenReturn(message); when(message.getHeader(eq(FCREPO_URI))).thenReturn(BINARY_URI); try (BufferedWriter writeFile = new BufferedWriter(new FileWriter(file))) { writeFile.write(testText); } String filePath = file.getAbsolutePath().toString(); when(message.getHeader(eq(CdrBinaryPath))) .thenReturn(filePath); when(message.getHeader(eq(CdrBinarySubPath))) .thenReturn(derivativeSubPath); }

Target:
public void init() throws Exception { initMocks(this); TestHelper.setContentBase(FEDORA_BASE); derivPath = tmpDir.newFolder().getAbsolutePath(); processor = new FulltextProcessor(derivPath); when(exchange.getIn()).thenReturn(message); when(message.getHeader(eq(FCREPO_URI))).thenReturn(RESC_ID); finalDerivativeFile = new File(derivPath + "/" + derivativeFinalPath + ".txt"); finalDerivativeFile.delete(); }
Source:
private void listenOnAddress(String address) throws IOException { mServerSocket = bindToSocket(address); LogUtil.i("Listening on @" + address); while (!Thread.interrupted()) { try { LocalSocket socket = mServerSocket.accept(); Thread t = new WorkerThread(socket, mSocketHandler); t.setName( WORKER_THREAD_NAME_PREFIX + "-" + mFriendlyName + "-" + mThreadId.incrementAndGet()); t.setDaemon(true); t.start(); } catch (SocketException se) { if (!Thread.interrupted()) { LogUtil.w(se, "I/O error"); } } catch (InterruptedIOException ex) { break; } catch (IOException e) { LogUtil.w(e, "I/O error initialising connection thread"); break; } } }

Target:
private void listenOnAddress(String address) throws IOException { mServerSocket = bindToSocket(address); LogUtil.i("Listening on @" + address); while (!Thread.interrupted()) { try { LocalSocket socket = mServerSocket.accept(); Thread t = new WorkerThread(socket, mSocketHandler); t.setName( WORKER_THREAD_NAME_PREFIX + "-" + mFriendlyName + "-" + mThreadId.incrementAndGet()); t.setDaemon(true); t.start(); } catch (SocketException se) { if (Thread.interrupted()) { break; } LogUtil.w(se, "I/O error"); } catch (InterruptedIOException ex) { break; } catch (IOException e) { LogUtil.w(e, "I/O error initialising connection thread"); break; } } LogUtil.i("Server shutdown on @" + address); }
Source:
private Runnable getScheduleableAction(String actionName, Runnable runnable) { return () -> { try { runnable.run(); if (Thread.currentThread().isInterrupted()) { LOG.warn("Action: is interrupted.", actionName); doCleanUpOnTaskException(new InterruptedException()); } else { LOG.debug("Action: completed successfully.", actionName); } } catch (Exception exception) { LOG.error("Execution of action: failed.", actionName, exception); doCleanUpOnTaskException(exception); } }; }

Target:
private Runnable getScheduleableAction(String actionName, Runnable runnable) { return () -> { try { runnable.run(); if (Thread.currentThread().isInterrupted()) { LOG.warn("Action: is interrupted.", actionName); doCleanUpOnTaskException(new InterruptedException()); } else { LOG.debug("Action: completed successfully.", actionName); } } catch (Throwable throwable) { LOG.error("Execution of action: failed.", actionName, throwable); doCleanUpOnTaskException(throwable); } }; }
Source:
protected void initStreamImplementation(RuntimeHarness harness) throws IOException { log.info("Deploying stream work manager implementation"); defaultProperty(STREAM_WORK_MANAGER_STORESTATE_ENABLED_PROPERTY, STREAM_WORK_MANAGER_STORESTATE_ENABLED_DEFAULT); deployComponent(harness, "OSGI-INF/test-stream-workmanager-config.xml"); }

Target:
protected void initStreamImplementation(RuntimeHarness harness) throws Exception { defaultProperty(STREAM_WORK_MANAGER_STORESTATE_ENABLED_PROPERTY, STREAM_WORK_MANAGER_STORESTATE_ENABLED_DEFAULT); harness.deployContrib(BUNDLE_TEST_NAME, "OSGI-INF/test-stream-workmanager-config.xml"); }
Source:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.create: if (TextUtils.isEmpty(mFolder.id)) { Toast.makeText(this, R.string.folder_id_required, Toast.LENGTH_LONG) .show(); return true; } if (TextUtils.isEmpty(mFolder.path)) { Toast.makeText(this, R.string.folder_path_required, Toast.LENGTH_LONG) .show(); return true; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && mFolderUri != null) { DocumentFile dfFolder = DocumentFile.fromTreeUri(this, mFolderUri); if (dfFolder != null) { Log.v(TAG, "Creating new directory " + mFolder.path + File.separator + FOLDER_MARKER_NAME); dfFolder.createDirectory(FOLDER_MARKER_NAME); } } getApi().createFolder(mFolder); finish(); return true; case R.id.remove: showDeleteDialog(); return true; case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } }

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.create: if (TextUtils.isEmpty(mFolder.id)) { Toast.makeText(this, R.string.folder_id_required, Toast.LENGTH_LONG) .show(); return true; } if (TextUtils.isEmpty(mFolder.path)) { Toast.makeText(this, R.string.folder_path_required, Toast.LENGTH_LONG) .show(); return true; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && mFolderUri != null && mFolder.type.equals(Constants.FOLDER_TYPE_SEND_ONLY)) { DocumentFile dfFolder = DocumentFile.fromTreeUri(this, mFolderUri); if (dfFolder != null) { Log.v(TAG, "Creating new directory " + mFolder.path + File.separator + FOLDER_MARKER_NAME); dfFolder.createDirectory(FOLDER_MARKER_NAME); } } getApi().createFolder(mFolder); finish(); return true; case R.id.remove: showDeleteDialog(); return true; case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } }
Source:
private static Set<BingTile> latitudeLongitudeToSurroundingTiles(double latitude, double longitude, int zoomLevel, int radius) { int mapSize = mapSize(zoomLevel); checkCondition((radius >= 0 && radius < mapSize / TILE_PIXELS), "radius should be between 0 and map size"); int tileX = longitudeToTileX(longitude, mapSize); int tileY = longitudeToTileY(latitude, mapSize); Set<BingTile> bingTiles = new HashSet<>(); IntStream.rangeClosed(-1 * radius, radius).forEach(i -> { IntStream.rangeClosed(-1 * radius, radius).forEach(j -> { if (coordinateInsideBoundary(tileX + i, mapSize) && coordinateInsideBoundary(tileY + j, mapSize)) { bingTiles.add(BingTile.fromCoordinates(tileX + i, tileY + j, zoomLevel)); } }); }); return Collections.unmodifiableSet(bingTiles); }

Target:
private static Set<BingTile> latitudeLongitudeToSurroundingTiles(double latitude, double longitude, int zoomLevel, int radius) { long mapSize = mapSize(zoomLevel); long maxTileIndex = (mapSize / TILE_PIXELS) - 1; checkCondition(radius >= 0 && radius <= maxTileIndex, "radius should be between 0 and map size"); int tileX = longitudeToTileX(longitude, mapSize); int tileY = longitudeToTileY(latitude, mapSize); Set<BingTile> bingTiles = new HashSet<>(); for (int i = -1 * radius; i <= radius; i++) { for (int j = -1 * radius; j <= radius; j++) { if (coordinateInsideBoundary(tileX + i, maxTileIndex) && coordinateInsideBoundary(tileY + j, maxTileIndex)) { bingTiles.add(BingTile.fromCoordinates(tileX + i, tileY + j, zoomLevel)); } } } return unmodifiableSet(bingTiles); }
Source:
void onHideEmptyPane(ValueChangeEvent<Boolean> e) { prefs.hideEmptyPane(!e.getValue()); view.diffTable.setHideEmptyPane(!e.getValue()); if (!e.getValue()) { if (view.diffTable.getChangeType() == ChangeType.ADDED) { leftSide.setValue(false); leftSide.setEnabled(false); } } else { leftSide.setValue(view.diffTable.isVisibleA()); leftSide.setEnabled(true); } }

Target:
void onHideEmptyPane(ValueChangeEvent<Boolean> e) { prefs.hideEmptyPane(!e.getValue()); view.diffTable.setHideEmptyPane(prefs.hideEmptyPane()); if (prefs.hideEmptyPane()) { if (view.diffTable.getChangeType() == ChangeType.ADDED) { leftSide.setValue(false); leftSide.setEnabled(false); } } else { leftSide.setValue(view.diffTable.isVisibleA()); leftSide.setEnabled(true); } }
Source:
Single<Integer> validateImage(UploadModel.UploadItem uploadItem, boolean checkTitle) { int currentImageQuality = uploadItem.getImageQuality(); Timber.d("Current image quality is %d", currentImageQuality); if (currentImageQuality == ImageUtils.IMAGE_KEEP) { return Single.just(ImageUtils.IMAGE_OK); } Timber.d("Checking the validity of image"); String filePath = uploadItem.getMediaUri().getPath(); Single<Integer> duplicateImage = checkDuplicateImage(filePath); Single<Integer> wrongGeoLocation = checkImageGeoLocation(uploadItem.getPlace(), filePath); Single<Integer> darkImage = checkDarkImage(filePath); Single<Integer> itemTitle = checkTitle ? validateItemTitle(uploadItem) : Single.just(ImageUtils.IMAGE_OK); Single<Integer> checkFBMD = checkFBMD(filePath); Single<Integer> zipResult = Single.zip(duplicateImage, wrongGeoLocation, darkImage, itemTitle, (duplicate, wrongGeo, dark, title) -> { Timber.d("Result for duplicate: %d, geo: %d, dark: %d, title: %d", duplicate, wrongGeo, dark, title); return duplicate | wrongGeo | dark | title; }); return Single.zip(zipResult, checkFBMD, (zip, fbmd) -> { return zip | fbmd; }); }

Target:
Single<Integer> validateImage(UploadModel.UploadItem uploadItem, boolean checkTitle) { int currentImageQuality = uploadItem.getImageQuality(); Timber.d("Current image quality is %d", currentImageQuality); if (currentImageQuality == ImageUtils.IMAGE_KEEP) { return Single.just(ImageUtils.IMAGE_OK); } Timber.d("Checking the validity of image"); String filePath = uploadItem.getMediaUri().getPath(); Single<Integer> duplicateImage = checkDuplicateImage(filePath); Single<Integer> wrongGeoLocation = checkImageGeoLocation(uploadItem.getPlace(), filePath); Single<Integer> darkImage = checkDarkImage(filePath); Single<Integer> itemTitle = checkTitle ? validateItemTitle(uploadItem) : Single.just(ImageUtils.IMAGE_OK); Single<Integer> checkFBMD = checkFBMD(filePath); Single<Integer> zipResult = Single.zip(duplicateImage, wrongGeoLocation, darkImage, itemTitle, (duplicate, wrongGeo, dark, title) -> { Timber.d("Result for duplicate: %d, geo: %d, dark: %d, title: %d", duplicate, wrongGeo, dark, title); return duplicate | wrongGeo | dark | title; }); return Single.zip(zipResult, checkFBMD, (zip, fbmd) -> { Timber.d("zip:" + zip + "fbmd:" + fbmd); return zip | fbmd; }); }
Source:
public void afterSession(TestSession session) { LOGGER.entering(); totalSessionsCompleted++; if (totalSessionsCompleted <= maxSessionsAllowed) { proxyLogger.fine("Completed session #" + totalSessionsCompleted + " (" + session.toString() + ")"); } proxyLogger.fine("Total number of slots used: " + getTotalUsed() + " on node: " + getId()); LOGGER.exiting(); }

Target:
public void afterSession(TestSession session) { LOGGER.entering(); totalSessionsCompleted++; proxyLogger.fine("Completed session #" + totalSessionsCompleted + " (" + session.toString() + ")"); proxyLogger.fine("Total number of slots used: " + getTotalUsed() + " on node: " + getId()); LOGGER.exiting(); }
Source:
public void should_run_two_concurrent_builds() { String jobName = "MyJob"; String jobDslScript = String.format("job('%s') { concurrentBuild(); steps { shell('sleep 10') } }", jobName); Job seed = createSeedJobWithJobDsl(jobDslScript); seed.startBuild().waitUntilFinished(); Job job = jenkins.jobs.get(Job.class, jobName); Build firstBuild = job.scheduleBuild().waitUntilStarted(); Build secondBuild = job.scheduleBuild().waitUntilStarted(); assertTrue(firstBuild.isInProgress()); assertTrue(secondBuild.isInProgress()); }

Target:
public void should_run_two_concurrent_builds() { String jobName = "MyJob"; String jobDslScript = String.format("job('%s') { concurrentBuild(); steps { shell('sleep 10') } }", jobName); Job seed = createSeedJobWithJobDsl(jobDslScript); seed.startBuild().waitUntilFinished(); Job job = jenkins.jobs.get(Job.class, jobName); Build firstBuild = job.scheduleBuild().waitUntilStarted(); Build secondBuild = job.scheduleBuild().waitUntilStarted(); assertTrue(firstBuild.isInProgress()); assertTrue(secondBuild.isInProgress()); firstBuild.stop(); secondBuild.stop(); }
Source:
protected void doExecute() { diagramdesc = DescriptionFactory.eINSTANCE.createDiagramDescription(); diagramdesc.setName("pattern.class.diagram.default.layer"); viewpoint.getOwnedRepresentations().add(diagramdesc); layer = DescriptionFactory.eINSTANCE.createLayer(); diagramdesc.setDefaultLayer(layer); createPackageMapping(); createClassListMapping(); createClassListMapping(); createEdgeMappingInheritance(); createEdgeMappingReference(); createToolSection(); createContainerClassMapping(); createContainerPackageMapping(); createDeleteTool(); createEditTool(); createNodeCreation(); }

Target:
protected void doExecute() { DiagramDescription diagramdesc = DescriptionFactory.eINSTANCE.createDiagramDescription(); diagramdesc.setName(BASE_ID + ".default.layer"); viewpoint.getOwnedRepresentations().add(diagramdesc); Layer layer = DescriptionFactory.eINSTANCE.createLayer(); diagramdesc.setDefaultLayer(layer); ContainerMapping packageMapping = createPackageMapping(layer); ContainerMapping classMapping = createClassListMapping(layer); createClassListMapping(layer); EdgeMapping edgeMappingInheritance = createEdgeMappingInheritance(layer, classMapping); EdgeMapping edgeMappingReference = createEdgeMappingReference(layer, classMapping); ToolSection toolSection = createToolSection(layer); createContainerClassMapping(toolSection, classMapping); createContainerPackageMapping(toolSection, packageMapping); createDeleteTool(toolSection, classMapping, classMapping, edgeMappingInheritance, edgeMappingReference); createEditTool(toolSection, classMapping, classMapping, edgeMappingInheritance, edgeMappingReference); createNodeCreation(toolSection, classMapping); }
Source:
public void testExistCustomAndGraphClient() { this.contextRunner .withUserConfiguration(AADResourceServerOboConfiguration.class) .withPropertyValues(AAD_PROPERTY_PREFIX + "authorization.graph.scopes=User.read") .withPropertyValues(AAD_PROPERTY_PREFIX + "authorization.custom.scopes=User.read") .run(context -> { final InMemoryClientRegistrationRepository oboRepo = context.getBean( InMemoryClientRegistrationRepository.class); final OAuth2AuthorizedClientRepository aadOboRepo = context.getBean( AADOAuth2OboAuthorizedClientRepository.class); ClientRegistration graph = oboRepo.findByRegistrationId("graph"); ClientRegistration custom = oboRepo.findByRegistrationId("custom"); Set<String> graphScopes = graph.getScopes(); Set<String> customScopes = custom.getScopes(); assertThat(aadOboRepo).isNotNull(); assertThat(oboRepo).isExactlyInstanceOf(InMemoryClientRegistrationRepository.class); assertThat(graph).isNotNull(); assertThat(customScopes).isNotNull(); assertThat(graphScopes).hasSize(1); assertThat(customScopes).hasSize(1); }); }

Target:
public void testExistCustomAndGraphClient() { this.contextRunner .withUserConfiguration(AADResourceServerOboConfiguration.class) .withPropertyValues("azure.activedirectory.authorization.graph.scopes=<LINK_1>" + ".Read") .withPropertyValues("azure.activedirectory.authorization.custom" + ".scopes=api://52261059-e515-488e-84fd-a09a3f372814/File.Read") .run(context -> { final InMemoryClientRegistrationRepository oboRepo = context.getBean( InMemoryClientRegistrationRepository.class); final OAuth2AuthorizedClientRepository aadOboRepo = context.getBean( AADOAuth2OboAuthorizedClientRepository.class); ClientRegistration graph = oboRepo.findByRegistrationId("graph"); ClientRegistration custom = oboRepo.findByRegistrationId("custom"); Set<String> graphScopes = graph.getScopes(); Set<String> customScopes = custom.getScopes(); assertThat(aadOboRepo).isNotNull(); assertThat(oboRepo).isExactlyInstanceOf(InMemoryClientRegistrationRepository.class); assertThat(graph).isNotNull(); assertThat(customScopes).isNotNull(); assertThat(graphScopes).containsOnly("<LINK_0>"); assertThat(customScopes).containsOnly("api://52261059-e515-488e-84fd-a09a3f372814/File.Read"); }); }
Source:
public void userIsTakenToDiscussionsPostViewAfterClickOnPostSzl() { new MixedContentFooter().openWikiMainPage() .scrollToMCFooter() .getDiscussionsCard() .scrollToDiscussions() .clickDiscussionsPost(); String url = driver.getCurrentUrl(); Assertion.assertTrue(url.contains(".wikia.com/szl/d/")); }

Target:
public void userIsTakenToDiscussionsPostViewAfterClickOnPostSzl() { new MixedContentFooter().openWikiMainPage() .scrollToMCFooter() .getDiscussionsCard() .scrollToDiscussions() .clickDiscussionsPost(); Assertion.assertTrue(driver.getCurrentUrl().contains(".wikia.com/szl/d/")); }
Source:
public String getUsage(ICommandSender commandSender) { return new TextComponentTranslation("commands.bloodmagic.orb.usage").getFormattedText(); }

Target:
public String getUsage(ICommandSender commandSender) { return "commands.bloodmagic.orb.usage"; }
Source:
protected void executeCommand() { Time originalExecutionTime = getSchedule().getExecutionTime(); try { String jobId = scheduleJob(); if (jobId != null) { setSucceeded(true); getSchedule().setJobId(jobId); getSchedule().setExecutionTime(originalExecutionTime); getGlusterVolumeSnapshotScheduleDao().save(getSchedule()); } else { setSucceeded(false); } } catch (Exception ex) { setSucceeded(false); handleVdsError(AuditLogType.GLUSTER_VOLUME_SNAPSHOT_SCHEDULE_FAILED, ex.getMessage()); } }

Target:
protected void executeCommand() { Time originalExecutionTime = getSchedule().getExecutionTime(); try { String jobId = scheduleJob(); setSucceeded(true); getSchedule().setJobId(jobId); getSchedule().setExecutionTime(originalExecutionTime); getGlusterVolumeSnapshotScheduleDao().save(getSchedule()); } catch (Exception ex) { setSucceeded(false); handleVdsError(AuditLogType.GLUSTER_VOLUME_SNAPSHOT_SCHEDULE_FAILED, ex.getMessage()); } }
Source:
public void setup(OperatorContext context) { }

Target:
public void setup(OperatorContext context) { logger.debug("bufferTime tumblingWindowTime laggardsWindowTime {}, timestampKeyName {}", bufferTime, tumblingWindowTime, laggardsWindowTime, timestampKeyName); }
Source:
private PreparedStatement readSessionStatement(SessionId sessionId) throws SQLException { PreparedStatement getSessionsStatement = connection.prepareStatement("select * from " + tableName + " where " + sessionIdCol + " like ?"); getSessionsStatement.setString(1, sessionUri(sessionId).concat("%")); return getSessionsStatement; }

Target:
private PreparedStatement readSessionStatement(SessionId sessionId) throws SQLException { PreparedStatement getSessionsStatement = connection.prepareStatement(String.format("select * from %1$s where %2$s = ?", TABLE_NAME, SESSION_ID_COL)); getSessionsStatement.setMaxRows(1); getSessionsStatement.setString(1, sessionId.toString()); return getSessionsStatement; }
Source:
public SeparatedList(List<T> list, List<InternalSyntaxToken> separators) { Preconditions.checkArgument(list.size() == separators.size() + 1 || list.size() == separators.size()); this.list = list; this.separators = separators; }

Target:
public SeparatedList(List<T> list, List<InternalSyntaxToken> separators) { Preconditions.checkArgument( list.size() == separators.size() + 1 || list.size() == separators.size(), "Instanciating a SeparatedList with inconsistent number of elements (%s) and separators (%s)", list.size(), separators.size()); this.list = list; this.separators = separators; }
Source:
public static void removeCartridge(String cartridgeType) throws RestAPIException { try { if (log.isDebugEnabled()) { log.debug(String.format("Removing cartridge: [cartridge-type] %s ", cartridgeType)); } CloudControllerServiceClient cloudControllerServiceClient = getCloudControllerServiceClient(); if (cloudControllerServiceClient.getCartridge(cartridgeType) == null) { throw new RuntimeException("Cartridge not found: [cartridge-type] " + cartridgeType); } StratosManagerServiceClient smServiceClient = getStratosManagerServiceClient(); if (!smServiceClient.canCartridgeBeRemoved(cartridgeType)) { String message = "Cannot remove cartridge : [cartridge-type] " + cartridgeType + " since it is used in another cartridge group or an application"; log.error(message); throw new RestAPIException(message); } cloudControllerServiceClient.removeCartridge(cartridgeType); if (log.isInfoEnabled()) { log.info(String.format("Successfully removed cartridge: [cartridge-type] %s ", cartridgeType)); } } catch (RemoteException e) { throw new RestAPIException(e.getMessage()); } catch (CloudControllerServiceInvalidCartridgeTypeExceptionException e) { throw new RestAPIException(e.getFaultMessage().getInvalidCartridgeTypeException().getMessage()); } catch (CloudControllerServiceCartridgeNotFoundExceptionException e) { throw new RestAPIException(e.getFaultMessage().getCartridgeNotFoundException().getMessage()); } }

Target:
public static void removeCartridge(String cartridgeType) throws RestAPIException, RemoteException, CloudControllerServiceCartridgeNotFoundExceptionException, CloudControllerServiceInvalidCartridgeTypeExceptionException { if (log.isDebugEnabled()) { log.debug(String.format("Removing cartridge: [cartridge-type] %s ", cartridgeType)); } CloudControllerServiceClient cloudControllerServiceClient = getCloudControllerServiceClient(); if (cloudControllerServiceClient.getCartridge(cartridgeType) == null) { throw new RuntimeException("Cartridge not found: [cartridge-type] " + cartridgeType); } StratosManagerServiceClient smServiceClient = getStratosManagerServiceClient(); if (!smServiceClient.canCartridgeBeRemoved(cartridgeType)) { String message = "Cannot remove cartridge : [cartridge-type] " + cartridgeType + " since it is used in another cartridge group or an application"; log.error(message); throw new RestAPIException(message); } cloudControllerServiceClient.removeCartridge(cartridgeType); if (log.isInfoEnabled()) { log.info(String.format("Successfully removed cartridge: [cartridge-type] %s ", cartridgeType)); } }
Source:
List<String> getURLBackupAddress(URL url) { List<String> addressList = new ArrayList<String>(); addressList.add(url.getAddress()); String[] backups = url.getParameter(Constants.BACKUP_KEY, new String[0]); addressList.addAll(Arrays.asList(backups)); return addressList; }

Target:
List<String> getURLBackupAddress(URL url) { List<String> addressList = new ArrayList<String>(); addressList.add(url.getAddress()); addressList.addAll(url.getParameter(Constants.BACKUP_KEY, Collections.EMPTY_LIST)); return addressList; }
Source:
public static Visibility getVisibility(Class<? extends Message> stateClass) { final Descriptors.Descriptor descriptor = TypeName.of(stateClass).getDescriptor(); final EntityOption entityOption = descriptor.getOptions() .getExtension(OptionsProto.entity); final Visibility definedVisibility = entityOption.getVisibility(); final Visibility result = (definedVisibility == Visibility.VISIBILITY_UNKNOWN) ? Visibility.FULL : definedVisibility; return result; }

Target:
public static Visibility getVisibility(Class<? extends Message> stateClass) { checkNotNull(stateClass); final Descriptors.Descriptor descriptor = TypeName.of(stateClass).getDescriptor(); final EntityOption entityOption = descriptor.getOptions() .getExtension(OptionsProto.entity); final Visibility definedVisibility = entityOption.getVisibility(); final Visibility result = (definedVisibility == Visibility.VISIBILITY_UNKNOWN) ? Visibility.FULL : definedVisibility; return result; }
Source:
private DateTime lease() { DateTime lease = new DateTime(); setLease(lease); latestOwnedLease = lease; return lease; }

Target:
private DateTime lease() { DateTime lease = new DateTime().withMillisOfSecond(0); setLease(lease); latestOwnedLease = lease; return lease; }
Source:
public boolean matches(Object item) { if(item instanceof Resource) { try { InputStream in = ((Resource) item).in(); try { byte[] result = new byte[contents.length]; int len = in.read(result); if(len != contents.length) return false; if(in.read()!=-1) return false; return Arrays.equals(contents, result); } finally { in.close(); } } catch (IOException ex) { throw new IllegalStateException("Exception while reading resource contents", ex); } } return false; }

Target:
public boolean matches(Object item) { if(item instanceof Resource) { try (InputStream in = ((Resource) item).in()) { byte[] result = new byte[contents.length]; int len = in.read(result); if (len != contents.length) { return false; } if (in.read() != -1) { return false; } return Arrays.equals(contents, result); } catch (IOException ex) { throw new IllegalStateException("Exception while reading resource contents", ex); } } return false; }
Source:
public void enableBarometer() { byte[] value = { 0x01 }; BluetoothLeGattCharacteristic preEnableChar; try { preEnableChar = this.gattServices.get(PRESSURE).findCharacteristic(TiSensorTagGatt.UUID_PRE_SENSOR_ENABLE); preEnableChar.writeValue(value); } catch (KuraException e) { logger.error("Barometer enable failed", e); } }

Target:
public boolean enableBarometer() { boolean result = false; byte[] value = { 0x01 }; BluetoothLeGattCharacteristic preEnableChar; try { preEnableChar = this.gattServices.get(PRESSURE).findCharacteristic(TiSensorTagGatt.UUID_PRE_SENSOR_ENABLE); preEnableChar.writeValue(value); result = true; } catch (KuraException e) { logger.error("Barometer enable failed", e); } return result; }
Source:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: startActivity(MainActivity.newIntent(this)); finish(); return true; default: return super.onOptionsItemSelected(item); } }

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (shouldRecreateMainActivity()) { startActivity(getSupportParentActivityIntent()); } finish(); return true; default: return super.onOptionsItemSelected(item); } }
Source:
public void testSnapshotAfterEndOfPartition() throws Exception { int numInputChannels = 1; int channelId = 0; int checkpointId = 0; VerifyRecordsDataOutput<Long> output = new VerifyRecordsDataOutput<>(); LongSerializer inSerializer = LongSerializer.INSTANCE; StreamTestSingleInputGate<Long> inputGate = new StreamTestSingleInputGate<>(numInputChannels, 0, inSerializer, 1024); TestRecordDeserializer[] deserializers = createDeserializers(numInputChannels); StreamTaskNetworkInput<Long> input = new StreamTaskNetworkInput<>( new CheckpointedInputGate( inputGate.getInputGate(), new CheckpointBarrierUnaligner( TestSubtaskCheckpointCoordinator.INSTANCE, "test", new DummyCheckpointInvokable(), inputGate.getInputGate())), inSerializer, new StatusWatermarkValve(numInputChannels, output), 0, deserializers); inputGate.sendEvent( new CheckpointBarrier(checkpointId, 0L, CheckpointOptions.forCheckpointWithDefaultLocation()), channelId); inputGate.sendElement(new StreamRecord<>(42L), channelId); assertHasNextElement(input, output); assertHasNextElement(input, output); assertEquals(1, output.getNumberOfEmittedRecords()); inputGate.sendEvent(EndOfPartitionEvent.INSTANCE, channelId); input.emitNext(output); assertNull(deserializers[channelId]); CompletableFuture<Void> completableFuture = input.prepareSnapshot(ChannelStateWriter.NO_OP, checkpointId); completableFuture.join(); }

Target:
public void testSnapshotAfterEndOfPartition() throws Exception { int numInputChannels = 1; int channelId = 0; int checkpointId = 0; VerifyRecordsDataOutput<Long> output = new VerifyRecordsDataOutput<>(); LongSerializer inSerializer = LongSerializer.INSTANCE; StreamTestSingleInputGate<Long> inputGate = new StreamTestSingleInputGate<>(numInputChannels, 0, inSerializer, 1024); TestRecordDeserializer[] deserializers = createDeserializers(numInputChannels); StreamTaskNetworkInput<Long> input = new StreamTaskNetworkInput<>( new CheckpointedInputGate( inputGate.getInputGate(), new CheckpointBarrierUnaligner( TestSubtaskCheckpointCoordinator.INSTANCE, "test", new DummyCheckpointInvokable(), inputGate.getInputGate()), new SyncMailboxExecutor()), inSerializer, new StatusWatermarkValve(numInputChannels, output), 0, deserializers); inputGate.sendEvent( new CheckpointBarrier(checkpointId, 0L, CheckpointOptions.forCheckpointWithDefaultLocation()), channelId); inputGate.sendElement(new StreamRecord<>(42L), channelId); assertHasNextElement(input, output); assertHasNextElement(input, output); assertEquals(1, output.getNumberOfEmittedRecords()); inputGate.sendEvent(EndOfPartitionEvent.INSTANCE, channelId); input.emitNext(output); assertNull(deserializers[channelId]); CompletableFuture<Void> completableFuture = input.prepareSnapshot(ChannelStateWriter.NO_OP, checkpointId); completableFuture.join(); }
Source:
public Lz4Decompressor(int directBufferSize) { this.directBufferSize = directBufferSize; try { LZ4Factory lz4Factory = LZ4Factory.fastestInstance(); lz4Decompressor = lz4Factory.safeDecompressor(); } catch (Throwable t) { throw new RuntimeException("lz4-java library is not available: " + "Lz4Decompressor has not been loaded. You need to add " + "lz4-java.jar to your CLASSPATH", t); } compressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize); uncompressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize); uncompressedDirectBuf.position(directBufferSize); }

Target:
public Lz4Decompressor(int directBufferSize) { this.directBufferSize = directBufferSize; try { LZ4Factory lz4Factory = LZ4Factory.fastestInstance(); lz4Decompressor = lz4Factory.safeDecompressor(); } catch (AssertionError t) { throw new RuntimeException("lz4-java library is not available: " + "Lz4Decompressor has not been loaded. You need to add " + "lz4-java.jar to your CLASSPATH. " + t, t); } compressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize); uncompressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize); uncompressedDirectBuf.position(directBufferSize); }
Source:
public ArrayList<Event> processTurn(GlobalGameData globalGameData) { GlobalGameData.setTurn(globalGameData.getTurn() + 1); ArrayList<Event> events = new ArrayList<Event>(); ArrayList<PendingMove> pendingMoves = new ArrayList<PendingMove>(); for (int x = 0; x < GlobalGameData.galaxySizeX; x++) { for (int y = 0; y < GlobalGameData.galaxySizeY; y++) { processUnitActions(globalGameData.getSectors()[x][y], pendingMoves, x, y); } } for (PendingMove p : pendingMoves) { Unit unit = p.getUnit(); unit.setSector(globalGameData.getSectors()[p.getX()][p.getY()]); Log.wtf("Next: ", "" + p.getX() + "," + p.getY()); globalGameData.getSectors()[p.getX()][p.getY()].addShip(unit); for (Unit u : globalGameData.getSectors()[p.getX()][p.getY()].getUnits()) { if (u.getFaction() != unit.getFaction()) { events.add(processBattle(globalGameData.getSectors()[p.getX()][p.getY()])); } } Iterator<Unit> iterator = globalGameData.getSectors()[p.getX()][p.getY()].getUnits().iterator(); while(iterator.hasNext()) { Unit aUnit = iterator.next(); if (aUnit.getCurrentHP() <= 0) { Log.wtf("Battle", aUnit.getShipName()+" destroyed"); iterator.remove(); } } } return events; }

Target:
public ArrayList<Event> processTurn(GlobalGameData globalGameData) { GlobalGameData.setTurn(globalGameData.getTurn() + 1); ArrayList<Event> events = new ArrayList<Event>(); ArrayList<PendingMove> pendingMoves = new ArrayList<PendingMove>(); processUnitActions(globalGameData, pendingMoves); processPendingMoves(globalGameData, events, pendingMoves); return events; }
Source:
public GetDetailedObjectsResult call() throws Exception { final ImmutableList<DetailedS3Object> suspectBulkObjects; Predicate<DetailedS3Object> filterPredicate; if (Guard.isMapNullOrEmpty(this.filterParams)) { filterPredicate = new Predicate<DetailedS3Object>() { @Override public boolean apply(@Nullable final DetailedS3Object input) { return (input != null); }}; } else { long larger = 0L; long smaller = Long.MAX_VALUE; Date newer = new Date(0); Date older = new Date(Long.MAX_VALUE); for (final String paramChange : this.filterParams.keySet()) { final String paramNewValue = this.filterParams.get(paramChange); if ("largerthan".equalsIgnoreCase(paramChange)) { larger = Long.parseLong(paramNewValue); } else if ("smallerthan".equalsIgnoreCase(paramChange)) { smaller = Long.parseLong(paramNewValue); } else if ("newerthan".equalsIgnoreCase(paramChange)) { newer = new Date(new Date().getTime() - Utils.dateDiffToSeconds(paramNewValue) * 1000); } else if ("olderthan".equalsIgnoreCase(paramChange)) { older = new Date(new Date().getTime() - Utils.dateDiffToSeconds(paramNewValue) * 1000); } else { throw new CommandException("Unrecognized filter parameter: " + paramChange); } } final long largerthan = larger; final long smallerthan = smaller; final Date newerthan = newer; final Date olderthan = older; filterPredicate = new Predicate<DetailedS3Object>() { @Override public boolean apply(@Nullable final DetailedS3Object input) { if (input == null) { return false; } return (input.getSize() > largerthan && input.getSize() < smallerthan && input.getCreationDate().after(newerthan) && input.getCreationDate().before(olderthan) ); } }; } suspectBulkObjects = ImmutableList.copyOf( FluentIterable.from(new LazyIterable<DetailedS3Object>( new GetObjectsFullDetailsLoaderFactory(getClient(), this.bucketName, this.prefix, 100, 5, true))).filter( filterPredicate)); return new GetDetailedObjectsResult(suspectBulkObjects.iterator()); }

Target:
public GetDetailedObjectsResult call() throws Exception { final Iterable suspectBulkObjects; final Predicate<DetailedS3Object> filterPredicate = getPredicate(); suspectBulkObjects = FluentIterable.from(new LazyIterable<DetailedS3Object>( new GetObjectsFullDetailsLoaderFactory(getClient(), this.bucketName, this.prefix, 100, 5, true))) .filter(filterPredicate); return new GetDetailedObjectsResult(suspectBulkObjects); }
Source:
protected boolean canDoAction() { StorageServerConnections paramConnection = getParameters().getStorageServerConnection(); if (paramConnection.getstorage_type() == StorageType.NFS && !new NfsMountPointConstraint().isValid(paramConnection.getconnection(), null)) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_INVALID); } if (paramConnection.getstorage_type() == StorageType.POSIXFS && (StringUtils.isEmpty(paramConnection.getVfsType()))) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if (getParameters().getVdsId().equals(Guid.Empty)) { if (!InitializeVds()) { return false; } } else if (getVds() == null) { return failCanDoAction(VdcBllMessages.VDS_INVALID_SERVER_ID); } else if (getVds().getStatus() != VDSStatus.Up) { return failCanDoAction(VdcBllMessages.VDS_ADD_STORAGE_SERVER_STATUS_MUST_BE_UP); } return super.canDoAction(); }

Target:
protected boolean canDoAction() { if(super.canDoAction()) { StorageServerConnections paramConnection = getParameters().getStorageServerConnection(); if (paramConnection.getstorage_type() == StorageType.NFS && !new NfsMountPointConstraint().isValid(paramConnection.getconnection(), null)) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_INVALID); } if (paramConnection.getstorage_type() == StorageType.POSIXFS && (StringUtils.isEmpty(paramConnection.getVfsType()))) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if (getParameters().getVdsId().equals(Guid.Empty)) { if (!InitializeVds()) { return false; } } else if (getVds() == null) { return failCanDoAction(VdcBllMessages.VDS_INVALID_SERVER_ID); } else if (getVds().getStatus() != VDSStatus.Up) { return failCanDoAction(VdcBllMessages.VDS_ADD_STORAGE_SERVER_STATUS_MUST_BE_UP); } return true; } return false; }
Source:
public void printTime(String header, boolean fromStart) { long dur = logTime(fromStart); System.out.println(String.format("%s (%,6d sec; DB cache: %,6d; Docs: %,6d)", header, dur / 1000, getCacheCounts(fromStart), docs.size())); }

Target:
public void printTime(String header, boolean fromStart) { long dur = logTime(fromStart); long totalDur = logTime(true); String stotalDur = duration(totalDur); System.out.println(String.format("%s (%,6d sec; %s; DB cache: %,6d; Docs: %,6d)", header, dur/1000, stotalDur, getCacheCounts(fromStart), docs.size())); }
Source:
public <T> Flux<T> multiGet(Query query, Class<T> clazz, IndexCoordinates index) { Assert.notNull(index, "index must not be null"); Assert.notEmpty(query.getIds(), "No Id define for Query"); MultiGetRequest request = requestFactory.multiGetRequest(query, index); return Flux.from(execute(cl -> cl.multiGet(request))) .handle((result, sink) -> { Document document = DocumentAdapters.from(result); if (document != null) { T entity = getElasticsearchConverter().mapDocument(document, clazz); if (entity != null) { sink.next(entity); } } }); }

Target:
public <T> Flux<T> multiGet(Query query, Class<T> clazz, IndexCoordinates index) { Assert.notNull(index, "Index must not be null"); Assert.notNull(clazz, "Class must not be null"); Assert.notNull(query, "Query must not be null"); Assert.notEmpty(query.getIds(), "No Id define for Query"); MultiGetRequest request = requestFactory.multiGetRequest(query, index); return Flux.from(execute(client -> client.multiGet(request))) .handle((result, sink) -> { Document document = DocumentAdapters.from(result); T entity = converter.mapDocument(document, clazz); if (entity != null) { sink.next(entity); } }); }
Source:
private String removeType(String value) { if (value != null && value.startsWith("mvel: ")) { return value.substring(6); } else { return value; } }

Target:
private String removeType(String value) { if(value != null) { if(value.startsWith("mvel: ")) { return value.substring(6); } else if(value.startsWith("reflection: ")) { return value.substring(12); } else { return value; } } else { return value; } }
Source:
public static boolean isNetworkConnectionPresent(Context ctx) { ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); return isConnected; }

Target:
public static boolean isNetworkConnectionPresent(Context ctx) { ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnected(); }
Source:
public void should_pass_all_samples_when_config_has_1_percentage() throws Exception { samplerConfiguration.setPercentage(1d); boolean passed = new PercentageBasedSampler(samplerConfiguration, traceAccessor).next(null); for (int i = 0; i < 10; i++) { then(passed).isTrue(); } }

Target:
public void should_pass_all_samples_when_config_has_1_percentage() throws Exception { samplerConfiguration.setPercentage(1f); for (int i = 0; i < 10; i++) { then(new PercentageBasedSampler(samplerConfiguration, traceAccessor, stringToUuidConverter).next(null)).isTrue(); } }
Source:
protected void doStop() { try { this.active = false; this.lifecycleCondition.await(Math.min(this.stopTimeout, this.receiveTimeout), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logger.debug("Thread interrupted while stopping the endpoint"); Thread.currentThread().interrupt(); } finally { this.listening = false; } }

Target:
protected void doStop() { super.doStop(); this.active = this.listening = false; }
Source:
public SCMProbeStat stat(@NonNull String path) throws IOException { try { String depotPath = base + "/" + path; if (p4.hasFile(depotPath)) { return SCMProbeStat.fromType(SCMFile.Type.REGULAR_FILE); } } catch (Exception e) { logger.warning("Unable to check file: " + e.getMessage()); } return SCMProbeStat.fromType(SCMFile.Type.NONEXISTENT); }

Target:
public SCMProbeStat stat(@NonNull String path) throws IOException { try { String depotPath = base + "/" + path; if (p4.hasFile(depotPath)) { return SCMProbeStat.fromType(SCMFile.Type.REGULAR_FILE); } } catch (Exception e) { throw new IOException("Unable to check file: " + e.getMessage()); } return SCMProbeStat.fromType(SCMFile.Type.NONEXISTENT); }
Source:
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value present"); } return this.value; }

Target:
public T getValue() { if (!this.isInitialized) { throw new NoSuchElementException("No value initialized"); } return this.value; }
Source:
private WikipediaApp getApplication() { return (WikipediaApp) getPageActivity().getApplication(); }

Target:
private WikipediaApp getApplication() { return WikipediaApp.getInstance(); }
Source:
public String getPassword() { String user = getUsername(); String defPass = null; if( "openshift-dev".equals(user)) { defPass = "devel"; } else { defPass = "developer"; } String pass = env.containsKey(DOTCDK_AUTH_PASS) ? env.get(DOTCDK_AUTH_PASS) : defPass; return pass; }

Target:
public String getPassword() { String user = getUsername(); String defPass = null; if(DEFAULT_CDK_USER.equals(user)) { defPass = DEFAULT_CDK_PASS; } else if( DEFAULT_MINISHIFT_USER.equals(user)){ defPass = DEFAULT_MINISHIFT_PASS; } String pass = env.containsKey(DOTCDK_AUTH_PASS) ? env.get(DOTCDK_AUTH_PASS) : defPass; return pass; }