auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void createColumns() { if (!fColumnsCreated) { SegmentStoreTableDataProvider provider = fDataProvider; if (provider != null) { TmfModelResponse<List<SegmentStoreTableColumnDataModel>> providerColumns = provider.fetchTree(new TimeQueryFilter(0, 0, 2), null); List<SegmentStoreTableColumnDataModel> model = providerColumns.getModel(); if (model != null && !model.isEmpty()) { int columnIndex = 0; for (SegmentStoreTableColumnDataModel columnData : model) { fColumnIdToLineIndex.put(columnData.getId(), columnIndex); createColumn(columnData.getId(), columnData.getName(), new SegmentStoreTableColumnLabelProvider() { @Override public String getTextForLine(SegmentStoreTableLine input) { Integer index = fColumnIdToLineIndex.get(columnData.getId()); if (index != null && index < input.getLine().size()) { String text = input.getLine().get(index); if (index == 0 || index == 1) { return NonNullUtils.nullToEmptyString(TmfTimestampFormat.getDefaulTimeFormat().format(Long.parseLong(text))); } else if (index == 2) { return NonNullUtils.nullToEmptyString(FORMATTER.format(Long.parseLong(text))); } return input.getLine().get(index); } return ""; } }, null); columnIndex++; } setColumnOrder(model.size()); } fColumnsCreated = true; } } }

Target:
private void createColumns() { if (!fColumnsCreated) { SegmentStoreTableDataProvider provider = fDataProvider; if (provider != null) { TmfModelResponse<List<SegmentStoreTableColumnDataModel>> providerColumns = provider.fetchTree(new TimeQueryFilter(0, 0, 2), null); List<SegmentStoreTableColumnDataModel> model = providerColumns.getModel(); if (model != null && !model.isEmpty()) { int columnIndex = 0; for (SegmentStoreTableColumnDataModel columnData : model) { fColumnIdToLineIndex.put(columnData.getId(), columnIndex); createColumn(columnData.getId(), columnData.getName(), new SegmentStoreTableColumnLabelProvider() { @Override public String getTextForLine(SegmentStoreTableLine input) { Integer index = fColumnIdToLineIndex.get(columnData.getId()); if (index != null && index < input.getLine().size()) { switch (index) { case 0: return NonNullUtils.nullToEmptyString(TmfTimestampFormat.getDefaulTimeFormat().format(input.getStartTime())); case 1: return NonNullUtils.nullToEmptyString(TmfTimestampFormat.getDefaulTimeFormat().format(input.getEndTime())); case 2: return NonNullUtils.nullToEmptyString(FORMATTER.format(input.getEndTime() - input.getStartTime())); default: return input.getLine().get(index); } } return ""; } }, null); columnIndex++; } setColumnOrder(model.size()); } fColumnsCreated = true; } } }
Source:
protected void executeVmCommand() { Guid createdSnapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE); getParameters().setSnapshotType(determineSnapshotType()); getParameters().setInitialVmStatus(getVm().getStatus()); getSnapshotDao().updateId(createdSnapshotId, newActiveSnapshotId); setActionReturnValue(createdSnapshotId); MemoryImageBuilder memoryImageBuilder = createMemoryImageBuilder(); addSnapshotToDB(createdSnapshotId, memoryImageBuilder); createSnapshotsForDisks(); memoryImageBuilder.build(); if (getTaskIdList().isEmpty()) { getParameters().setTaskGroupSuccess(true); incrementVmGeneration(); } if (!prepareForMemorySnapshot) { freeLock(); } setSucceeded(true); }

Target:
protected void executeVmCommand() { Guid createdSnapshotId = getSnapshotDao().getId(getVmId(), SnapshotType.ACTIVE); getParameters().setSnapshotType(determineSnapshotType()); getParameters().setInitialVmStatus(getVm().getStatus()); getSnapshotDao().updateId(createdSnapshotId, newActiveSnapshotId); setActionReturnValue(createdSnapshotId); MemoryImageBuilder memoryImageBuilder = createMemoryImageBuilder(); addSnapshotToDB(createdSnapshotId, memoryImageBuilder); createSnapshotsForDisks(); memoryImageBuilder.build(); getParameters().setTaskGroupSuccess(false); if (getTaskIdList().isEmpty()) { incrementVmGeneration(); } if (!prepareForMemorySnapshot) { freeLock(); } setSucceeded(true); }
Source:
private RootModule createRootModule() { final RootModule rootModule; try { final Properties props = createOverridingProperties(); final MultiThreadModeConfiguration multiThreadModeConfiguration = MultiThreadModeConfiguration.singleThreadMode(); final MultiThreadModuleResolver moduleResolver = new MultiThreadModuleResolver( multiThreadModeConfiguration); final Configuration config = ConfigurationLoader.loadConfiguration( configLocation, new PropertiesExpander(props), moduleResolver, !executeIgnoredModules); final ClassLoader moduleClassLoader = Checker.class.getClassLoader(); final ModuleFactory factory = new PackageObjectFactory( Checker.class.getPackage().getName() + ".", moduleClassLoader); rootModule = (RootModule) factory.createModule(config.getName()); rootModule.setModuleClassLoader(moduleClassLoader); if (rootModule instanceof Checker) { final ClassLoader loader = new AntClassLoader(getProject(), classpath); ((Checker) rootModule).setClassLoader(loader); } rootModule.configure(config); } catch (final CheckstyleException ex) { throw new BuildException(String.format(Locale.ROOT, "Unable to create Root Module: " + "configLocation {%s}, classpath {%s}.", configLocation, classpath), ex); } return rootModule; }

Target:
private RootModule createRootModule() { final RootModule rootModule; try { final Properties props = createOverridingProperties(); final ThreadModeSettings threadModeSettings = ThreadModeSettings.SINGLE_THREAD_MODE_INSTANCE; final Configuration configuration = ConfigurationLoader.loadConfiguration( config, new PropertiesExpander(props), !executeIgnoredModules, threadModeSettings); final ClassLoader moduleClassLoader = Checker.class.getClassLoader(); final ModuleFactory factory = new PackageObjectFactory( Checker.class.getPackage().getName() + ".", moduleClassLoader); rootModule = (RootModule) factory.createModule(configuration.getName()); rootModule.setModuleClassLoader(moduleClassLoader); if (rootModule instanceof Checker) { final ClassLoader loader = new AntClassLoader(getProject(), classpath); ((Checker) rootModule).setClassLoader(loader); } rootModule.configure(configuration); } catch (final CheckstyleException ex) { throw new BuildException(String.format(Locale.ROOT, "Unable to create Root Module: " + "config {%s}, classpath {%s}.", config, classpath), ex); } return rootModule; }
Source:
public void initialize( Input input ) throws IOException { log.info( "Import starting" ); startTime = currentTimeMillis(); inputCache = new InputCache( fileSystem, storeDir, recordFormats, toIntExact( mebiBytes( 1 ) ) ); this.input = CachedInput.cacheAsNecessary( input, inputCache ); numberArrayFactory = auto( neoStore.getPageCache(), storeDir, config.allowCacheAllocationOnHeap() ); badCollector = input.badCollector(); idMapper = input.idMapper( numberArrayFactory ); nodeRelationshipCache = new NodeRelationshipCache( numberArrayFactory, config.denseNodeThreshold() ); Estimates inputEstimates = input.calculateEstimates( neoStore.getPropertyStore().newValueEncodedSizeCalculator() ); sanityCheckEstimatesWithRecordFormat( inputEstimates ); dependencies.satisfyDependencies( inputEstimates, idMapper, neoStore, nodeRelationshipCache ); if ( neoStore.determineDoubleRelationshipRecordUnits( inputEstimates ) ) { System.out.println( "Will use double record units for all relationships" ); } executionMonitor.initialize( dependencies ); }

Target:
public void initialize( Input input ) throws IOException { log.info( "Import starting" ); startTime = currentTimeMillis(); inputCache = new InputCache( fileSystem, storeDir, recordFormats, toIntExact( mebiBytes( 1 ) ) ); this.input = CachedInput.cacheAsNecessary( input, inputCache ); numberArrayFactory = auto( neoStore.getPageCache(), storeDir, config.allowCacheAllocationOnHeap() ); badCollector = input.badCollector(); idMapper = input.idMapper( numberArrayFactory ); nodeRelationshipCache = new NodeRelationshipCache( numberArrayFactory, config.denseNodeThreshold() ); Estimates inputEstimates = input.calculateEstimates( neoStore.getPropertyStore().newValueEncodedSizeCalculator() ); sanityCheckEstimatesWithRecordFormat( inputEstimates ); dependencies.satisfyDependencies( inputEstimates, idMapper, neoStore, nodeRelationshipCache ); if ( neoStore.determineDoubleRelationshipRecordUnits( inputEstimates ) ) { monitor.doubleRelationshipRecordUnitsEnabled(); } executionMonitor.initialize( dependencies ); }
Source:
public void resourceChanged(IResourceChangeEvent event) { IResourceDelta resourceDelta = event.getDelta(); if (resourceDelta != null) { IResourceDelta[] affectedChildren = resourceDelta.getAffectedChildren(); for (IResourceDelta affectedChildResourceDelta : affectedChildren) { IResource resource = affectedChildResourceDelta.getResource(); int kind = affectedChildResourceDelta.getKind(); if (resource instanceof IProject && (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED)) { PlatformUI.getWorkbench().getDisplay() .asyncExec(() -> Display.getDefault().timerExec(200, switchTopControlRunnable)); return; } } } }

Target:
public void resourceChanged(IResourceChangeEvent event) { IResourceDelta resourceDelta = event.getDelta(); if (resourceDelta != null) { IResourceDelta[] affectedChildren = resourceDelta.getAffectedChildren(); for (IResourceDelta affectedChildResourceDelta : affectedChildren) { IResource resource = affectedChildResourceDelta.getResource(); int kind = affectedChildResourceDelta.getKind(); if (resource instanceof IProject && (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED)) { PlatformUI.getWorkbench().getDisplay() .asyncExec(() -> PlatformUI.getWorkbench().getDisplay().timerExec(200, switchTopControlRunnable)); return; } } } }
Source:
protected void initMaxPings() { Integer maxPingsParam = getInitParameter("maxPings", Integer.class); setMaxPings((maxPingsParam == null) ? DEFAULT_MAX_PINGS : maxPingsParam); if (isDebug()) { LOGGER.debug("maxPings: {}", getMaxPings()); } }

Target:
protected void initMaxPings() { Integer maxPingsParam = getInitParameter("maxPings", Integer.class); setMaxPings(Optional.ofNullable(getInitParameter("maxPings", Integer.class)).orElse(DEFAULT_MAX_PINGS)); if (isDebug()) { LOGGER.debug("maxPings: {}", getMaxPings()); } }
Source:
public void doesntLinkUnrelatedSpansWhenMissingRootSpan() { List<DependencyLinkSpan> trace = asList( new DependencyLinkSpan(new TraceId(0L, 1L), 3L, 1L, Kind.SERVER, "service1", null), new DependencyLinkSpan(new TraceId(0L, 1L), 3L, 2L, Kind.SERVER, "service2", null) ); assertThat(new DependencyLinker() .putTrace(trace.iterator()).link()) .isEmpty(); }

Target:
public void doesntLinkUnrelatedSpansWhenMissingRootSpan() { long missingParentId = 1; List<DependencyLinkSpan> trace = asList( new DependencyLinkSpan(new TraceId(0L, 1L), missingParentId, 2L, Kind.SERVER, "service1", null), new DependencyLinkSpan(new TraceId(0L, 1L), missingParentId, 3L, Kind.SERVER, "service2", null) ); assertThat(new DependencyLinker() .putTrace(trace.iterator()).link()) .isEmpty(); }
Source:
protected byte[] runHttpMethod(HttpMethodType httpMethod, String contentType, String body, HttpURLConnection connection) { byte[] result = null; try { connection.setRequestProperty("Content-Type", contentType); connection.setDoInput(true); connection.setDoOutput(httpMethod != HttpMethodType.GET); connection.setRequestMethod(httpMethod.toString()); if (body != null) { byte[] bytes = body.getBytes(StandardCharsets.UTF_8); connection.setRequestProperty(String.valueOf(bytes.length), "Content-Length"); try (OutputStream outputStream = connection.getOutputStream()) { outputStream.write(bytes); } } result = getResponse(connection); } catch (SSLException e) { throw new EngineException(EngineError.PROVIDER_SSL_FAILURE, e.getMessage()); } catch (IOException e) { handleException(e); } finally { if (connection != null) { connection.disconnect(); } } return result; }

Target:
protected byte[] runHttpMethod(HttpMethodType httpMethod, String contentType, String body, HttpURLConnection connection) { byte[] result = null; try { connection.setRequestProperty("Content-Type", contentType); connection.setDoInput(true); connection.setDoOutput(httpMethod != HttpMethodType.GET); connection.setRequestMethod(httpMethod.toString()); if (body != null) { byte[] bytes = body.getBytes(StandardCharsets.UTF_8); connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); try (OutputStream outputStream = connection.getOutputStream()) { outputStream.write(bytes); } } result = getResponse(connection); } catch (SSLException e) { throw new EngineException(EngineError.PROVIDER_SSL_FAILURE, e.getMessage()); } catch (IOException e) { handleException(e); } finally { if (connection != null) { connection.disconnect(); } } return result; }
Source:
private static String getString(String suffix) { return Constant.messages.getString(String.format("fuzz.payloads.generator.json.%1$2s", suffix)); }

Target:
private static String getString(String suffix) { return Constant.messages.getString("fuzz.payloads.generator.json." + suffix); }
Source:
public FilteringArtifactClassLoader(ClassLoader parent, ArtifactClassLoader artifactClassLoader, ClassLoaderFilter filter, List<ExportedService> exportedServices) { super(parent); checkArgument(artifactClassLoader != null, "ArtifactClassLoader cannot be null"); checkArgument(filter != null, "Filter cannot be null"); checkArgument(exportedServices != null, "exportedServiceProviders cannot be null"); this.artifactClassLoader = artifactClassLoader; this.filter = filter; this.exportedServices = exportedServices; verboseLogging = LOGGER.isDebugEnabled() || isVerboseLoggingEnabled(); }

Target:
public FilteringArtifactClassLoader(ClassLoader parent, ArtifactClassLoader artifactClassLoader, ClassLoaderFilter filter, List<ExportedService> exportedServices) { super(parent); checkArgument(artifactClassLoader != null, "ArtifactClassLoader cannot be null"); checkArgument(filter != null, "Filter cannot be null"); checkArgument(exportedServices != null, "exportedServiceProviders cannot be null"); this.artifactClassLoader = artifactClassLoader; this.filter = filter; this.exportedServices = exportedServices; verboseLogging = valueOf(getProperty(MULE_LOG_VERBOSE_CLASSLOADING)); }
Source:
SignatureAlgorithm(String value, String description, String familyName, String jcaName, boolean jdkStandard, int digestLength, int minKeyLength) { this(value, description,familyName, jcaName, jdkStandard, digestLength, minKeyLength, null); }

Target:
SignatureAlgorithm(String value, String description, String familyName, String jcaName, boolean jdkStandard, int digestLength, int minKeyLength) { this(value, description,familyName, jcaName, jdkStandard, digestLength, minKeyLength, jcaName); }
Source:
public static OlapAnnotation getOlapAnnotationByName( final String name, List<OlapAnnotation> annotations) { OlapAnnotation foundAnnotation = null; for( OlapAnnotation annotation : annotations ) { if ( name.equals( annotation.getName() ) ) { foundAnnotation = annotation; } } return foundAnnotation; }

Target:
public static OlapAnnotation getOlapAnnotationByName( final String name, List<OlapAnnotation> annotations) { OlapAnnotation foundAnnotation = null; for( OlapAnnotation annotation : annotations ) { if ( name.equals( annotation.getName() ) ) { foundAnnotation = annotation; break; } } return foundAnnotation; }
Source:
public void load(File file) { try(InputStream in = Files.newInputStream(file.toPath())) { PropertiesConfiguration config = newPropertiesConfiguration(); new FileHandler(config).load(cleanUp(in)); ((CompositeConfiguration) internalConfig).addConfiguration(config); } catch (ConfigurationException | IOException e) { throw new IllegalArgumentException(e); } }

Target:
public void load(File file) { try (InputStream in = Files.newInputStream(file.toPath())) { PropertiesConfiguration config = new PropertiesConfiguration(); config.getLayout().load(config, checkProps(in)); ((CompositeConfiguration) internalConfig).addConfiguration(config); } catch (ConfigurationException | IOException e) { throw new IllegalArgumentException(e); } }
Source:
protected ObjectNode executePost(HttpPost httpPost) { Preconditions.checkNotNull(httpPost); ObjectNode result = null; CloseableHttpResponse response = null; String entityString = null; try { response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine() != null && response.getStatusLine().getStatusCode() >= 200 && entity != null) { entityString = EntityUtils.toString(entity); result = mapper.readValue(entityString, ObjectNode.class); } } catch (IOException e) { LOGGER.error("IO error:\n{}\n{}\n{}", httpPost.toString(), response, e.getMessage()); } finally { try { response.close(); } catch (IOException e) } return result; }

Target:
protected ObjectNode executePost(HttpPost httpPost) { Preconditions.checkNotNull(httpPost); ObjectNode result = null; CloseableHttpResponse response = null; String entityString = null; try { response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine() != null && response.getStatusLine().getStatusCode() >= HttpStatus.SC_OK && entity != null) { entityString = EntityUtils.toString(entity); result = mapper.readValue(entityString, ObjectNode.class); } } catch (IOException e) { LOGGER.error("IO error:\n{}\n{}\n{}", httpPost.toString(), response, e.getMessage()); } finally { try { response.close(); } catch (IOException e) } return result; }
Source:
public UdpServerListeningEvent(UnicastReceivingChannelAdapter adapter, int port) { super(adapter); Assert.notNull(adapter, "'adapter' cannot be null"); this.port = port; }

Target:
public UdpServerListeningEvent(UnicastReceivingChannelAdapter adapter, int port) { super(adapter); this.port = port; }
Source:
public void removeMessageHandler(final Class<? extends Message> messageType, final MessageHandler handler) { if (messageType == null) { throw new IllegalArgumentException("Cannot remove handler for null message type"); } if (handler == null) { throw new IllegalArgumentException("Cannot remove null handler"); } synchronized (messageHandlers) { List<MessageHandler> handlers = messageHandlers.get(messageType); if (handlers == null || !handlers.contains(handler)) { LOGGER.log(Level.WARNING, "{0} is not registered as a handler", handler); return; } handlers.remove(handler); if (handlers.isEmpty()) { messageHandlers.remove(messageType); } } }

Target:
public void removeMessageHandler(final Class<? extends Message> messageType, final MessageHandler handler) { if (messageType == null) { throw new IllegalArgumentException("Cannot remove handler for null message type"); } if (handler == null) { throw new IllegalArgumentException("Cannot remove null handler"); } LOGGER.log(Level.FINEST, "Removing message handler {0} for message type: {1}", new Object[] {handler, messageType}); synchronized (messageHandlers) { List<MessageHandler> handlers = messageHandlers.get(messageType); if (handlers == null || !handlers.contains(handler)) { LOGGER.log(Level.WARNING, "{0} is not registered as a handler", handler); return; } handlers.remove(handler); if (handlers.isEmpty()) { messageHandlers.remove(messageType); } } }
Source:
protected void executeVmCommand() { AddCustomValue("InterfaceType", (VmInterfaceType.forValue(getInterface().getType()).getDescription()).toString()); boolean succeeded = false; try { getInterface().setSpeed(VmInterfaceType.forValue(getInterface().getType()).getSpeed()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(oldIface); getVmNetworkInterfaceDao().update(getInterface()); if (macAddressChanged) { MacPoolManager.getInstance().freeMac(oldIface.getMacAddress()); } getCompensationContext().stateChanged(); return null; } }); succeeded = updateHost(); } finally { setSucceeded(succeeded); if (!succeeded && macAddressChanged) { MacPoolManager.getInstance().addMac(oldIface.getMacAddress()); MacPoolManager.getInstance().freeMac(getInterface().getMacAddress()); } } }

Target:
protected void executeVmCommand() { AddCustomValue("InterfaceType", (VmInterfaceType.forValue(getInterface().getType()).getDescription()).toString()); boolean succeeded = false; boolean macAddedToPool = false; try { if (macShouldBeChanged) { macAddedToPool = addMacToPool(getMacAddress()); } getInterface().setSpeed(VmInterfaceType.forValue(getInterface().getType()).getSpeed()); TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(oldIface); getVmNetworkInterfaceDao().update(getInterface()); getCompensationContext().stateChanged(); return null; } }); succeeded = updateHost(); } finally { setSucceeded(succeeded); if (macAddedToPool) { if (succeeded) { MacPoolManager.getInstance().freeMac(oldIface.getMacAddress()); } else { MacPoolManager.getInstance().freeMac(getMacAddress()); } } } }
Source:
public void validate(Element element, AnnotationElements validatedElements, IsValid valid) { validatorHelper.enclosingElementHasEnhancedComponentAnnotation(element, validatedElements, valid); ExecutableElement executableElement = (ExecutableElement) element; validatorHelper.hasTraceAnnotationAndReturnValue(executableElement, validatedElements, valid); validatorHelper.hasWakeLockPermission(element, androidManifest, valid); validatorHelper.isNotPrivate(element, valid); validatorHelper.isNotFinal(element, valid); }

Target:
public void validate(Element element, AnnotationElements validatedElements, IsValid valid) { validatorHelper.enclosingElementHasEnhancedComponentAnnotation(element, validatedElements, valid); ExecutableElement executableElement = (ExecutableElement) element; validatorHelper.doesNotHaveTraceAnnotationAndReturnValue(executableElement, validatedElements, valid); validatorHelper.doesNotUseFlagsWithPartialWakeLock(element, validatedElements, valid); validatorHelper.hasWakeLockPermission(element, androidManifest, valid); validatorHelper.isNotPrivate(element, valid); validatorHelper.isNotFinal(element, valid); }
Source:
public static String redactUrl(String path) { URL url; try { url = new URL(path); } catch (MalformedURLException e) { return path; } if (url.getUserInfo() != null) { return url.toString().replace(url.getUserInfo(), REDACTED_USER_INFO); } else { return url.toString(); } }

Target:
public static String redactUrl(String path) { URL url; try { url = new URL(path); } catch (MalformedURLException e) { return path; } if (url.getUserInfo() != null) { return url.toString().replace(url.getUserInfo(), REDACTED_USER_INFO); } else { return path; } }
Source:
public void testListNullElement() { Dog dog1 = new Dog(); dog1.setName("Dog 1"); Dog dog2 = new Dog(); dog2.setName("Dog 2"); ArrayList<Dog> list = new ArrayList<Dog>(); list.addAll(Arrays.asList(dog1, null, dog2)); realm.beginTransaction(); try { realm.insert(list); } catch (NullPointerException ignore) { } finally { realm.cancelTransaction(); } }

Target:
public void testListNullElement() { Dog dog1 = new Dog(); dog1.setName("Dog 1"); Dog dog2 = new Dog(); dog2.setName("Dog 2"); ArrayList<Dog> list = new ArrayList<Dog>(); list.addAll(Arrays.asList(dog1, null, dog2)); realm.beginTransaction(); try { realm.insert(list); fail("Should trigger IllegalArgumentException"); } catch (NullPointerException ignore) { } finally { realm.cancelTransaction(); } }
Source:
public static ConnectionDetails newForNode(final Node node, final ConnectionDetails connectionDetails) { final Builder connectionBuilder; if (node.getEndpoint() == null || node.getEndpoint().equals("FAILED_TO_DETERMINE_DATAPATH_IP_ADDRESS")) { LOG.trace("Running against an old version of the DS3 API, reusing existing endpoint configuration"); connectionBuilder = builder(connectionDetails.getEndpoint(), connectionDetails.getCredentials()); } else { LOG.trace("Creating new Connection Details for endpoint: " + node.getEndpoint()); connectionBuilder = builder(node.getEndpoint() + ":" + getPort(node, connectionDetails), connectionDetails.getCredentials()); } connectionBuilder.withRedirectRetries(connectionDetails.getRetries()) .withHttps(connectionDetails.isHttps()) .withCertificateVerification(connectionDetails.isCertificateVerification()) .withBufferSize(connectionDetails.getBufferSize()) .withProxy(connectionDetails.getProxy()); return connectionBuilder.build(); }

Target:
public static ConnectionDetails newForNode(final Node node, final ConnectionDetails connectionDetails) { final Builder connectionBuilder; if (node.getEndpoint() == null || node.getEndpoint().equals("FAILED_TO_DETERMINE_DATAPATH_IP_ADDRESS")) { LOG.trace("Running against an old version of the DS3 API, reusing existing endpoint configuration"); connectionBuilder = builder(connectionDetails.getEndpoint(), connectionDetails.getCredentials()); } else { LOG.trace("Creating new Connection Details for endpoint: " + node.getEndpoint()); connectionBuilder = builder(buildAuthority(node, connectionDetails), connectionDetails.getCredentials()); } connectionBuilder.withRedirectRetries(connectionDetails.getRetries()) .withHttps(connectionDetails.isHttps()) .withCertificateVerification(connectionDetails.isCertificateVerification()) .withBufferSize(connectionDetails.getBufferSize()) .withProxy(connectionDetails.getProxy()); return connectionBuilder.build(); }
Source:
public static String simplePrint(GraphQLSchemaElement schemaElement) { if (schemaElement instanceof GraphQLType) { return simplePrint((GraphQLType) schemaElement); } if (schemaElement instanceof GraphQLNamedSchemaElement) { return ((GraphQLNamedSchemaElement) schemaElement).getName(); } return "null"; }

Target:
public static String simplePrint(GraphQLSchemaElement schemaElement) { if (schemaElement instanceof GraphQLType) { return simplePrint((GraphQLType) schemaElement); } if (schemaElement instanceof GraphQLNamedSchemaElement) { return ((GraphQLNamedSchemaElement) schemaElement).getName(); } return assertShouldNeverHappen("unexpected schema element: " + schemaElement); }
Source:
public ICompletionProposal[] getCompletionProposals() { Parser parser = Parser.getDefault(); TargetNode rootNode = parser.getRootNode(); if (rootNode == null) return new ICompletionProposal[] {}; UnitNode node = rootNode.getEnclosingUnit(offset); if (acKey.equalsIgnoreCase(ITargetConstants.UNIT_ID_ATTR)) { if (node != null) { LocationNode location = node.getParent(); if (location.getRepositoryLocation() == null) { return getErrorCompletion(); } RepositoryCache cache = RepositoryCache.getDefault(); if (!cache.isUpToDate(location.getRepositoryLocation())) { UpdateJob job = new UpdateJob(location); job.setUser(true); job.schedule(); return getInformativeProposal(); } List<UnitNode> units = cache.getUnitsByPrefix(location.getRepositoryLocation(), prefix); return convertToProposals(units); } } if (acKey.equalsIgnoreCase(ITargetConstants.UNIT_VERSION_ATTR)) { if (node != null) { LocationNode location = node.getParent(); if (location.getRepositoryLocation() == null) { return getErrorCompletion(); } RepositoryCache cache = RepositoryCache.getDefault(); if (!cache.isUpToDate(location.getRepositoryLocation())) { UpdateJob job = new UpdateJob(location); job.setUser(true); job.schedule(); return getInformativeProposal(); } List<UnitNode> byPrefix = cache.getUnitsByPrefix(location.getRepositoryLocation(), node.getId()); List<String> versions = byPrefix.get(0).getAvailableVersions(); return convertToVersionProposals(versions); } } return new ICompletionProposal[] {}; }

Target:
public ICompletionProposal[] getCompletionProposals() { Parser parser = Parser.getDefault(); TargetNode rootNode = parser.getRootNode(); if (rootNode == null) return new ICompletionProposal[] {}; UnitNode node = rootNode.getEnclosingUnit(offset); if (acKey.equalsIgnoreCase(ITargetConstants.UNIT_ID_ATTR)) { if (node != null) { LocationNode location = node.getParent(); String repoLocation = location.getRepositoryLocation(); if (repoLocation == null) { return getErrorCompletion(); } RepositoryCache cache = RepositoryCache.getDefault(); if (!cache.isUpToDate(repoLocation)) { scheduleUpdateJob(location); return getInformativeProposal(); } List<UnitNode> units = cache.getUnitsByPrefix(repoLocation, prefix); return convertToProposals(units); } } if (acKey.equalsIgnoreCase(ITargetConstants.UNIT_VERSION_ATTR)) { if (node != null) { LocationNode location = node.getParent(); String repoLocation = location.getRepositoryLocation(); if (repoLocation == null) { return getErrorCompletion(); } RepositoryCache cache = RepositoryCache.getDefault(); if (!cache.isUpToDate(repoLocation)) { scheduleUpdateJob(location); return getInformativeProposal(); } List<UnitNode> byPrefix = cache.getUnitsByPrefix(repoLocation, node.getId()); List<String> versions = byPrefix.get(0).getAvailableVersions(); return convertToVersionProposals(versions); } } return new ICompletionProposal[] {}; }
Source:
private String getCurrentValueFromViewer(MergeViewerSide side) { final boolean isLeft = (MergeViewerSide.LEFT == side) != getCompareConfiguration().isMirrored(); final GetContentRunnable runnable = new GetContentRunnable(isLeft); Display.getDefault().syncExec(runnable); return (String)runnable.getResult(); }

Target:
private String getCurrentValueFromViewer(MergeViewerSide side) { boolean isLeft = MergeViewerSide.LEFT == side; if (getCompareConfiguration().isMirrored()) { isLeft = MergeViewerSide.RIGHT == side; } final GetContentRunnable runnable = new GetContentRunnable(isLeft); Display.getDefault().syncExec(runnable); return (String)runnable.getResult(); }
Source:
public Object execute() throws Exception { JaasRealm realm = (JaasRealm) session.get(JAAS_REALM); if (realm == null) { System.err.println("No JAAS Realm has been selected"); return null; } if (!(realm instanceof Config)) { System.err.println("Selected JAAS Realm was not added via jaas:add-realm, only those are supported!"); return null; } if (!checkIfClassExists(loginModule)) { System.err.println("Module class '" + loginModule + "' is unknown!"); return null; } Module module = createModuleFromCmdParameters(loginModule, propertiesList); List<Module> modulesList = new ArrayList<>(Arrays.asList(((Config) realm).getModules())); modulesList.add(module); Module[] newModules = modulesList.toArray(new Module[]{}); ((Config) realm).setModules(newModules); return null; }

Target:
public Object execute() throws Exception { JaasRealm realm = (JaasRealm) session.get(JAAS_REALM); if (realm == null) { System.err.println("No JAAS Realm has been selected"); throw new IllegalStateException("No JAAS Realm has been selected"); } if (!(realm instanceof Config)) { System.err.println("Selected JAAS Realm was not added via jaas:add-realm, only those are supported!"); throw new IllegalStateException("Selected JAAS Realm was not added via jaas:add-realm, only those are supported!"); } if (!checkIfClassExists(loginModule)) { System.err.println("Module class '" + loginModule + "' is unknown!"); throw new IllegalArgumentException("Module class '" + loginModule + "' is unknown!"); } Module module = createModuleFromCmdParameters(loginModule, propertiesList); List<Module> modulesList = new ArrayList<>(Arrays.asList(((Config) realm).getModules())); modulesList.add(module); Module[] newModules = modulesList.toArray(new Module[]{}); ((Config) realm).setModules(newModules); return null; }
Source:
protected void onHandleIntent(Intent intent) { mContext = getApplicationContext(); if (intent != null) { final String action = intent.getAction(); if (ACTION_SYNC.equals(action)) { final int param1 = intent.getIntExtra(SYNC_PERIOD, 1); acquireSerialDevice(); handleActionSync(param1, getApplicationContext(), mSerialDevice); } } }

Target:
protected void onHandleIntent(Intent intent) { if (intent != null) { final String action = intent.getAction(); if (ACTION_SYNC.equals(action)) { final int param1 = intent.getIntExtra(SYNC_PERIOD, 1); UsbSerialDriver driver = acquireSerialDevice(); if (driver != null) { handleActionSync(param1, getApplicationContext(), driver); } } } }
Source:
public void testResourceHandlerClearedByJVM() { if (System.getProperty("java.version").startsWith("1.7")) { return; } createDanglingObjectHandler(); long poolSize = poolOfString.poolSize(); while (poolOfString.poolSize() == poolSize) { System.gc(); } Assert.assertEquals(poolSize + 1, poolOfString.poolSize()); }

Target:
public void testResourceHandlerClearedByJVM() throws InterruptedException { if (System.getProperty("java.version").startsWith("1.7")) { return; } String leakedString = createDanglingObjectHandler(); for (int i = 0; i < 6000 && poolOfString.leakedObjectsCount() == 0; i++) { System.gc(); byte[] garbage = new byte[10_000_000]; Thread.sleep(10); } Assert.assertEquals(leakedString, 1, poolOfString.leakedObjectsCount()); }
Source:
public boolean supports(AuthenticationToken token) { if (!(token instanceof BaseAuthenticationToken)) { LOGGER.debug( "The supplied authentication token is not an instance of BaseAuthenticationToken. Sending back not supported."); return false; } BaseAuthenticationToken authToken = (BaseAuthenticationToken) token; Object credentials = authToken.getCredentials(); if (credentials == null || authToken.getType() != AuthenticationTokenType.USERNAME) { LOGGER.debug( "The supplied authentication token has null/empty credentials. Sending back no supported."); return false; } LOGGER.debug( "Token is supported by {}.", token.getClass(), UsernamePasswordRealm.class.getName()); return true; }

Target:
public boolean supports(AuthenticationToken token) { if (!(token instanceof BaseAuthenticationToken)) { LOGGER.debug( "The supplied authentication token is not an instance of BaseAuthenticationToken. Sending back not supported."); return false; } BaseAuthenticationToken authToken = (BaseAuthenticationToken) token; Object credentials = authToken.getCredentials(); if (credentials == null || authToken.getType() != AuthenticationTokenType.USERNAME) { LOGGER.debug( "The supplied authentication token has null/empty credentials. Sending back not supported."); return false; } if (credentials instanceof String) { LOGGER.debug( "Token is supported by {}.", token.getClass(), UsernamePasswordRealm.class.getName()); return true; } return false; }
Source:
public SwaggerParseResult readLocation(String url, List<AuthorizationValue> auth, ParseOptions options) { SwaggerParseResult result = new SwaggerParseResult(); try { result = readWithInfo(url,auth); if (result.getOpenAPI() != null) { String version = result.getOpenAPI().getOpenapi(); if (auth == null) { auth = new ArrayList<>(); } if (version != null && version.startsWith("3.0")) { if (options != null) { if (options.isResolve()) { result.setOpenAPI(new OpenAPIResolver(result.getOpenAPI(), auth, null).resolve()); } if (options.isResolveFully()) { result.setOpenAPI(new OpenAPIResolver(result.getOpenAPI(), auth, null).resolve()); new ResolverFully().resolveFully(result.getOpenAPI()); } } } } } catch (Exception e) { result.setMessages(Arrays.asList(e.getMessage())); } return result; }

Target:
public SwaggerParseResult readLocation(String url, List<AuthorizationValue> auth, ParseOptions options) { SwaggerParseResult result = new SwaggerParseResult(); try { result = readWithInfo(url,auth); if (result.getOpenAPI() != null) { String version = result.getOpenAPI().getOpenapi(); if (auth == null) { auth = new ArrayList<>(); } if (version != null && version.startsWith("3.0")) { if (options != null) { OpenAPIResolver resolver = new OpenAPIResolver(result.getOpenAPI(), auth, null); if (options.isResolve()) { result.setOpenAPI(resolver.resolve()); } if (options.isResolveFully()) { result.setOpenAPI(resolver.resolve()); new ResolverFully().resolveFully(result.getOpenAPI()); } } } } } catch (Exception e) { result.setMessages(Arrays.asList(e.getMessage())); } return result; }
Source:
public void check(final IProgressMonitor monitor) { if (null != monitor) { monitor.subTask("Validate dependencies for element types."); } final Collection<String> requiredPlugins = new HashSet<>(); NEEDED_REQUIRED_PLUGINS.stream().forEach(needRequiredPlugin -> requiredPlugins.add(needRequiredPlugin)); final Collection<String> existingRequiredPlugins = new HashSet<>(); ProjectManagementService.getPluginDependencies(project).stream().forEach(dependency -> existingRequiredPlugins.add(dependency.getName())); requiredPlugins.removeIf(requiredPlugin -> existingRequiredPlugins.contains(requiredPlugin)); if (!requiredPlugins.isEmpty()) { final IFile manifestFile = ProjectManagementService.getManifestFile(project); requiredPlugins.stream().forEach(requiredPlugin -> { MarkersService.createMarker(manifestFile, ElementTypesPluginValidationConstants.ELEMENTTYPES_PLUGIN_VALIDATION_TYPE, "The plug-in '" + requiredPlugin + "' must be defined as required plug-in.", IMarker.SEVERITY_WARNING); }); } if (null != monitor) { monitor.worked(1); } }

Target:
public void check(final IProgressMonitor monitor) { if (null != monitor) { monitor.subTask("Validate dependencies for element types."); } final Collection<String> requiredPlugins = new HashSet<>(); NEEDED_REQUIRED_PLUGINS.stream().forEach(needRequiredPlugin -> requiredPlugins.add(needRequiredPlugin)); final Collection<String> existingRequiredPlugins = new HashSet<>(); final List<BundleSpecification> dependencies = ProjectManagementService.getPluginDependencies(project); if (null != dependencies && !dependencies.isEmpty()) { dependencies.stream().forEach(dependency -> existingRequiredPlugins.add(dependency.getName())); requiredPlugins.removeIf(requiredPlugin -> existingRequiredPlugins.contains(requiredPlugin)); } if (!requiredPlugins.isEmpty()) { final IFile manifestFile = ProjectManagementService.getManifestFile(project); requiredPlugins.stream().forEach(requiredPlugin -> { MarkersService.createMarker(manifestFile, ElementTypesPluginValidationConstants.ELEMENTTYPES_PLUGIN_VALIDATION_TYPE, "The plug-in '" + requiredPlugin + "' must be defined as required plug-in.", IMarker.SEVERITY_WARNING); }); } if (null != monitor) { monitor.worked(1); } }
Source:
void registerCapability(RegistrationParams params) { params.getRegistrations().forEach(reg -> { if ("workspace/didChangeWorkspaceFolders".equals(reg.getMethod())) { Assert.isNotNull(serverCapabilities, "Dynamic capability registration failed! Server not yet initialized?"); if (supportsWorkspaceFolders(serverCapabilities)) { LanguageServerPlugin.logWarning( "Dynamic registration of 'workspace/didChangeWorkspaceFolders' ignored. It was already enabled before", null); } else { onUnregistration(reg, () -> enableWorkspaceFolders(serverCapabilities, false)); enableWorkspaceFolders(serverCapabilities, true); } } else if ("workspace/executeCommand".equals(reg.getMethod())) { Gson gson = new Gson(); ExecuteCommandOptions executeCommandOptions = gson.fromJson((JsonObject) reg.getRegisterOptions(), ExecuteCommandOptions.class); List<String> newCommands = executeCommandOptions.getCommands(); if (!newCommands.isEmpty()) { onUnregistration(reg, () -> unregisterCommands(newCommands)); registerCommands(newCommands); } } }); }

Target:
void registerCapability(RegistrationParams params) { params.getRegistrations().forEach(reg -> { if ("workspace/didChangeWorkspaceFolders".equals(reg.getMethod())) { Assert.isNotNull(serverCapabilities, "Dynamic capability registration failed! Server not yet initialized?"); if (initiallySupportsWorkspaceFolders) { return; } else if (supportsWorkspaceFolders(serverCapabilities)) { LanguageServerPlugin.logWarning( "Dynamic registration of 'workspace/didChangeWorkspaceFolders' ignored. It was already enabled before", null); } else { addRegistration(reg, () -> setWorkspaceFoldersEnablement(false)); setWorkspaceFoldersEnablement(true); } } else if ("workspace/executeCommand".equals(reg.getMethod())) { Gson gson = new Gson(); ExecuteCommandOptions executeCommandOptions = gson.fromJson((JsonObject) reg.getRegisterOptions(), ExecuteCommandOptions.class); List<String> newCommands = executeCommandOptions.getCommands(); if (!newCommands.isEmpty()) { addRegistration(reg, () -> unregisterCommands(newCommands)); registerCommands(newCommands); } } }); }
Source:
private String storeSensorPrefix(final String threadId, final String taskId, final String storeName) { return taskSensorPrefix(threadId, taskId) + SENSOR_PREFIX_DELIMITER + "store" + SENSOR_PREFIX_DELIMITER + storeName; }

Target:
private String storeSensorPrefix(final String threadId, final String taskId, final String storeName) { return taskSensorPrefix(threadId, taskId) + SENSOR_PREFIX_DELIMITER + SENSOR_STORE_LABEL + SENSOR_PREFIX_DELIMITER + storeName; }
Source:
public static Guid getGuidValue(NGuid id) { if (id == null) { return null; } return id.getValue(); }

Target:
public static Guid getGuidValue(NGuid id) { return id == null ? null : id.getValue(); }
Source:
private void storeInDB(String serviceName, String type, String user, Object token) throws CredentialStoreException { try { Connection connection = getConnection(); try { String application = findApplicationName(); if(StringUtil.isEmpty(user)){ user = serviceName+application; } PreparedStatement ps = connection.prepareStatement("INSERT INTO "+getTableName()+" VALUES (?, ?, ?, ?, ?)"); try { byte[] apptoken = serialize(token); ps.setString(1, application); ps.setString(2, serviceName); ps.setObject(3, type); ps.setObject(4, user); ps.setObject(5, apptoken); ps.executeUpdate(); } finally { ps.close(); } } finally { connection.close(); } } catch (SQLException e) { logger.log(Level.SEVERE, "setAppToken : ", e); throw new CredentialStoreException(e, "DBTokenStore.java : setAppToken caused a SQLException"); } }

Target:
private void storeInDB(String serviceName, String type, String user, Object token) throws CredentialStoreException { try { Connection connection = getConnection(); try { String application = findApplicationName(); if(StringUtil.isEmpty(user)){ user = ""; } PreparedStatement ps = connection.prepareStatement("INSERT INTO "+getTableName()+" VALUES (?, ?, ?, ?, ?)"); try { byte[] apptoken = serialize(token); ps.setString(1, application); ps.setString(2, serviceName); ps.setObject(3, type); ps.setObject(4, user); ps.setObject(5, apptoken); ps.executeUpdate(); } finally { ps.close(); } } finally { connection.close(); } } catch (SQLException e) { logger.log(Level.SEVERE, "setAppToken : ", e); throw new CredentialStoreException(e, "DBTokenStore.java : setAppToken caused a SQLException"); } }
Source:
public void setUp() throws InitializationError { initMocks(this); mRunner = spy(new LongevityClassRunner(SampleTest.class)); }

Target:
public void setUp() { initMocks(this); }
Source:
public EnvVars getEnvironment() throws IOException, InterruptedException { if (cachedEnvironment != null) { return cachedEnvironment; } cachedEnvironment = EnvVars.getRemote(getChannel()); return cachedEnvironment; }

Target:
public EnvVars getEnvironment() throws IOException, InterruptedException { EnvVars cachedEnvironment = this.cachedEnvironment; if (cachedEnvironment != null) { return cachedEnvironment; } cachedEnvironment = EnvVars.getRemote(getChannel()); this.cachedEnvironment = cachedEnvironment; return cachedEnvironment; }
Source:
public void testRule() throws Exception { String[] command = Stream.concat(Arrays.stream(this.getCommandArgs()), Arrays.stream(this.getDefaultArgs())) .toArray(String[]::new); addAllExpectedMsgs(); Tailor.main(command); List<String> actualOutput = new ArrayList<>(); String[] msgs = outContent.toString(Charset.defaultCharset().name()).split(NEWLINE_REGEX); String summary = msgs[msgs.length - 1]; msgs = Arrays.copyOfRange(msgs, 4, msgs.length - 2); for (String msg : msgs) { if (msg.isEmpty() || msg.contains("**********")) { continue; } String truncatedMsg = msg.substring(msg.indexOf(TEST_INPUT_DIR) + TEST_INPUT_DIR.length()); actualOutput.add(truncatedMsg); } assertThat(summary, containsString(expectedMessages.size() + " violation")); assertArrayEquals(outContent.toString(Charset.defaultCharset().name()), this.expectedMessages.toArray(), actualOutput.toArray()); }

Target:
public void testRule() throws ReflectiveOperationException, UnsupportedEncodingException { String[] command = Stream.concat(Arrays.stream(this.getCommandArgs()), Arrays.stream(this.getDefaultArgs())) .toArray(String[]::new); addAllExpectedMsgs(); Tailor.main(command); List<String> actualOutput = new ArrayList<>(); String[] msgs = outContent.toString(Charset.defaultCharset().name()).split(NEWLINE_REGEX); String summary = msgs[msgs.length - 1]; msgs = Arrays.copyOfRange(msgs, 4, msgs.length - 2); for (String msg : msgs) { if (msg.isEmpty() || msg.contains("**********")) { continue; } String truncatedMsg = msg.substring(msg.indexOf(TEST_INPUT_DIR) + TEST_INPUT_DIR.length()); actualOutput.add(truncatedMsg); } assertThat(summary, containsString(expectedMessages.size() + " violation")); assertArrayEquals(outContent.toString(Charset.defaultCharset().name()), this.expectedMessages.toArray(), actualOutput.toArray()); }
Source:
public WebElement getEditInstructorLink(int instrNum) { String id = "instrEditLink" + instrNum; return browser.driver.findElement(By.id(id)); }

Target:
public WebElement getEditInstructorLink(int instrNum) { return browser.driver.findElement(By.id("instrEditLink" + instrNum)); }
Source:
public int writeCharacteristic(BluetoothGattCharacteristic characteristic, int offset, byte[] value) { if (offset != 0) { return BluetoothGatt.GATT_INVALID_OFFSET; } if (value.length != 2) { return BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH; } ByteBuffer byteBuffer = ByteBuffer.wrap(value); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); final int newMeasurementIntervalValue = byteBuffer.getShort(); if (!isValidMeasurementIntervalValue(Integer.toString(newMeasurementIntervalValue))) { return BluetoothGatt.GATT_FAILURE; } getActivity().runOnUiThread(new Runnable() { @Override public void run() { mMeasurementIntervalCharacteristic.setValue(newMeasurementIntervalValue, MEASUREMENT_INTERVAL_FORMAT, 0); resetTimer(newMeasurementIntervalValue); } }); return BluetoothGatt.GATT_SUCCESS; }

Target:
public int writeCharacteristic(BluetoothGattCharacteristic characteristic, int offset, byte[] value) { if (offset != 0) { return BluetoothGatt.GATT_INVALID_OFFSET; } if (value.length != 2) { return BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH; } ByteBuffer byteBuffer = ByteBuffer.wrap(value); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); final int newMeasurementIntervalValue = byteBuffer.getShort(); if (!isValidMeasurementIntervalValue(newMeasurementIntervalValue)) { return BluetoothGatt.GATT_FAILURE; } getActivity().runOnUiThread(new Runnable() { @Override public void run() { mMeasurementIntervalCharacteristic.setValue(newMeasurementIntervalValue, MEASUREMENT_INTERVAL_FORMAT, 0); if (mMeasurementIntervalCCCDescriptor.getValue() == BluetoothGattDescriptor.ENABLE_INDICATION_VALUE) { resetTimer(newMeasurementIntervalValue); mTextViewNotifications.setText(R.string.notificationsEnabled); } } }); return BluetoothGatt.GATT_SUCCESS; }