auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void dumpMetrics(FileDescriptor fd) { Log.i(TAG, "dumpMetrics"); BluetoothProto.BluetoothLog metrics = new BluetoothProto.BluetoothLog(); metrics.setNumBondedDevices(getBondedDevices().length); for (ProfileService profile : mProfiles) { profile.dumpProto(metrics); } byte[] nativeMetricsBytes = dumpMetricsNative(); Log.i(TAG, "dumpMetrics, native metrics size is " + nativeMetricsBytes.length); try { metrics.mergeFrom(nativeMetricsBytes); } catch (InvalidProtocolBufferMicroException ex) { Log.w(TAG, "dumpMetrics, problem parsing metrics protobuf: " + ex.getMessage()); return; } byte[] metricsBytes = Base64.encode(metrics.toByteArray(), Base64.DEFAULT); Log.i(TAG, "dumpMetrics, combined metrics size is " + metricsBytes.length); try (FileOutputStream protoOut = new FileOutputStream(fd)) { protoOut.write(metricsBytes); } catch (IOException e) { errorLog("dumpMetrics, Unable to write combined protobuf to file descriptor."); } }

Target:
private void dumpMetrics(FileDescriptor fd) { BluetoothProto.BluetoothLog metrics = new BluetoothProto.BluetoothLog(); metrics.setNumBondedDevices(getBondedDevices().length); for (ProfileService profile : mProfiles) { profile.dumpProto(metrics); } byte[] nativeMetricsBytes = dumpMetricsNative(); debugLog("dumpMetrics: native metrics size is " + nativeMetricsBytes.length); try { metrics.mergeFrom(nativeMetricsBytes); } catch (InvalidProtocolBufferMicroException ex) { Log.w(TAG, "dumpMetrics: problem parsing metrics protobuf, " + ex.getMessage()); return; } byte[] metricsBytes = Base64.encode(metrics.toByteArray(), Base64.DEFAULT); debugLog("dumpMetrics: combined metrics size is " + metricsBytes.length); try (FileOutputStream protoOut = new FileOutputStream(fd)) { protoOut.write(metricsBytes); } catch (IOException e) { errorLog("dumpMetrics: error writing combined protobuf to fd, " + e.getMessage()); } }
Source:
private WallabagServiceEndpoint getServiceEndpoint() { if(serviceEndpoint == null) { if(this.wallabagMajorVersion == -1) { this.wallabagMajorVersion = guessWallabagVersion(); } switch (this.wallabagMajorVersion) { case 2: serviceEndpoint = new WallabagServiceEndpointV2(endpoint, username, password, client); break; default: Log.w(TAG, "Falling back to V1 endpoint; wallabagMajorVersion=" + this.wallabagMajorVersion); case 1: serviceEndpoint = new WallabagServiceEndpointV1(endpoint, username, password, client); break; } } return serviceEndpoint; }

Target:
private WallabagServiceEndpoint getServiceEndpoint() { if(serviceEndpoint == null) { switch(getWallabagVersion()) { case 1: serviceEndpoint = new WallabagServiceEndpointV1(endpoint, username, password, client); break; default: Log.w(TAG, "Falling back to V2 endpoint; wallabagVersion=" + this.wallabagVersion); case 2: serviceEndpoint = new WallabagServiceEndpointV2(endpoint, username, password, client); break; } } return serviceEndpoint; }
Source:
public void shouldParseAcceptScriptWithOptions() throws Exception { String script = "# tcp.client.accept-then-close\n" + "accept option transport \"localhost:8000\"\n" + "accept tcp://localhost:7788\n" + "accepted\n" + "connected\n" + "close\n" + "closed\n"; ScriptParserImpl parser = new ScriptParserImpl(); AstScriptNode actual = parser.parseWithStrategy(script, SCRIPT); }

Target:
public void shouldParseAcceptScriptWithOptions() throws Exception { String script = "# tcp.client.accept-then-close\n" + "accept http://localhost:7788\n" + " option transport tcp://localhost:8000\n" + "accepted\n" + "connected\n" + "close\n" + "closed\n"; ScriptParserImpl parser = new ScriptParserImpl(); AstScriptNode actual = parser.parseWithStrategy(script, SCRIPT); AstLocation location = new AstLocationLiteral(URI.create("http://localhost:7788")); AstLocation transport = new AstLocationLiteral(URI.create("tcp://localhost:8000")); AstScriptNode expected = new AstScriptNodeBuilder() .addAcceptStream() .setLocation(location) .setTransport(transport) .done() .addAcceptedStream() .addConnectedEvent().done() .addCloseCommand().done() .addClosedEvent().done() .done() .done(); assertEquals(expected, actual); }
Source:
public void testIterateThroughDocumentVectorComputeBM25() throws Exception { Directory dir = FSDirectory.open(tempDir1); IndexReader reader = DirectoryReader.open(dir); IndexSearcher searcher = new IndexSearcher(reader); searcher.setSimilarity(new BM25Similarity()); int numDocs = reader.numDocs(); for (int i=0; i<numDocs; i++) { String docid = reader.document(i).getField("docid").stringValue(); System.out.println(reader.document(i)); System.out.println(i+ ": " + docid); Terms terms = reader.getTermVector(i, "text"); TermsEnum te = terms.iterator(); while (te.next() != null) { String term = new Term("text", te.term()).bytes().utf8ToString(); String stemmed = AnalyzerUtils.tokenize(new EnglishAnalyzer(), term).get(0); long tf = te.totalTermFreq(); Query filterQuery = new TermQuery(new Term("docid", docid)); Query termQuery = new TermQuery(new Term("text", term)); BooleanQuery.Builder builder = new BooleanQuery.Builder(); builder.add(filterQuery, BooleanClause.Occur.MUST); builder.add(termQuery, BooleanClause.Occur.MUST); Query finalQuery = builder.build(); TopDocs rs = searcher.search(finalQuery, 1); System.out.println(stemmed + " " + tf + " " + rs.getMaxScore()); } } }

Target:
public void testIterateThroughDocumentVectorComputeBM25() throws Exception { Directory dir = FSDirectory.open(tempDir1); IndexReader reader = DirectoryReader.open(dir); IndexSearcher searcher = new IndexSearcher(reader); searcher.setSimilarity(new BM25Similarity()); int numDocs = reader.numDocs(); for (int i=0; i<numDocs; i++) { String docid = reader.document(i).getField("docid").stringValue(); System.out.println(reader.document(i)); System.out.println(i+ ": " + docid); Terms terms = reader.getTermVector(i, "text"); TermsEnum te = terms.iterator(); while (te.next() != null) { String term = new Term("text", te.term()).bytes().utf8ToString(); long tf = te.totalTermFreq(); Query filterQuery = new TermQuery(new Term("docid", docid)); Query termQuery = new TermQuery(new Term("text", term)); BooleanQuery.Builder builder = new BooleanQuery.Builder(); builder.add(filterQuery, BooleanClause.Occur.MUST); builder.add(termQuery, BooleanClause.Occur.MUST); Query finalQuery = builder.build(); TopDocs rs = searcher.search(finalQuery, 1); System.out.println(term + " " + tf + " " + rs.getMaxScore()); } } }
Source:
private void createConfigurationForCluster(String clusterId) throws LoadBalancerExtensionException { log.info("Creating configuration for cluster"); GCEClusterConfigurationHolder gceClusterConfigurationHolder = clusterToLoadBalancerConfigurationMap.get(clusterId); gceOperations.createHealthCheck(gceClusterConfigurationHolder.getHealthCheckName()); gceOperations.createTargetPool(gceClusterConfigurationHolder.getTargetPoolName(), gceClusterConfigurationHolder.getHealthCheckName()); gceOperations.addInstancesToTargetPool(gceClusterConfigurationHolder.getMemberList(), gceClusterConfigurationHolder.getTargetPoolName()); List<Integer> ipList = gceClusterConfigurationHolder.getIpList(); String portRange; if (ipList.isEmpty()) { log.warn("Ip list is null"); portRange = "1-65535"; } else if (ipList.size() == 1) { portRange = Integer.toString(ipList.get(0)) + "-" + Integer.toString(ipList.get(0)); } else { Collections.sort(ipList); portRange = Integer.toString(ipList.get(0)) + "-" + Integer.toString(ipList.get(ipList.size() - 1)); } if (log.isDebugEnabled()) { log.debug("Port range set as: " + portRange); } gceOperations.createForwardingRule(gceClusterConfigurationHolder.getForwardingRuleName(), gceClusterConfigurationHolder.getTargetPoolName(), PROTOCOL, portRange); log.info("Created configuration for cluster"); }

Target:
private void createConfigurationForCluster(String clusterId) throws LoadBalancerExtensionException { log.info("Creating configuration for cluster " + clusterId + "..."); GCEClusterConfigurationHolder gceClusterConfigurationHolder = clusterToLoadBalancerConfigurationMap.get(clusterId); List<Integer> ipList = gceClusterConfigurationHolder.getIpList(); String portRange; if (ipList.isEmpty()) { log.warn("Ip list is null"); portRange = Constants.DEFAULT_PORT_RANGE; } else if (ipList.size() == 1) { portRange = Integer.toString(ipList.get(0)) + "-" + Integer.toString(ipList.get(0)); } else { Collections.sort(ipList); portRange = Integer.toString(ipList.get(0)) + "-" + Integer.toString(ipList.get(ipList.size() - 1)); } if (log.isDebugEnabled()) { log.debug("Port range set as: " + portRange); } Map healthCheckMap = gceClusterConfigurationHolder.getHealthCheckMap(); Iterator iterator = healthCheckMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry portMapNamePair = (Map.Entry) iterator.next(); gceOperations.createHealthCheck((Integer) portMapNamePair.getKey(), (String) portMapNamePair.getValue()); } gceOperations.createTargetPool(gceClusterConfigurationHolder.getTargetPoolName(), gceClusterConfigurationHolder.getHealthCheckNames()); gceOperations.addInstancesToTargetPool(gceClusterConfigurationHolder.getMemberList(), gceClusterConfigurationHolder.getTargetPoolName()); gceOperations.createForwardingRule(gceClusterConfigurationHolder.getForwardingRuleName(), gceClusterConfigurationHolder.getTargetPoolName(), Constants.PROTOCOL, portRange); log.info("Created configuration for cluster" + clusterId); }
Source:
public void run(IProgressMonitor m) throws CoreException { if (m == null) { m = new NullProgressMonitor(); } m.beginTask(CoreText.ConnectProviderOperation_connecting, 100 * projects.size()); try { for (Iterator iterator = projects.keySet().iterator(); iterator.hasNext();) { IProject project = (IProject) iterator.next(); m.setTaskName(NLS.bind( CoreText.ConnectProviderOperation_ConnectingProject, project.getName())); Activator.trace("Locating repository for " + project); Collection<RepositoryMapping> repos = new RepositoryFinder( project).find(new SubProgressMonitor(m, 40)); Iterator<RepositoryMapping> mi = repos.iterator(); RepositoryMapping actualMapping = mi.hasNext() ? mi.next() : null; if (actualMapping != null) { GitProjectData projectData = new GitProjectData(project); try { projectData.setRepositoryMappings(Arrays.asList(actualMapping)); projectData.store(); } catch (CoreException ce) { GitProjectData.delete(project); throw ce; } catch (RuntimeException ce) { GitProjectData.delete(project); throw ce; } RepositoryProvider .map(project, GitProvider.class.getName()); projectData = GitProjectData.get(project); project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(m, 50)); m.worked(10); } else { Activator .trace("Attempted to share project without repository ignored :" + project); m.worked(60); } } } finally { m.done(); } }

Target:
public void run(IProgressMonitor m) throws CoreException { if (m == null) { m = new NullProgressMonitor(); } m.beginTask(CoreText.ConnectProviderOperation_connecting, 100 * projects.size()); try { for (Iterator iterator = projects.keySet().iterator(); iterator.hasNext();) { IProject project = (IProject) iterator.next(); m.setTaskName(NLS.bind( CoreText.ConnectProviderOperation_ConnectingProject, project.getName())); Activator.trace("Locating repository for " + project); Collection<RepositoryMapping> repos = new RepositoryFinder( project).find(new SubProgressMonitor(m, 40)); File suggestedRepo = projects.get(project); RepositoryMapping actualMapping= findActualRepository(repos, suggestedRepo); if (actualMapping != null) { GitProjectData projectData = new GitProjectData(project); try { projectData.setRepositoryMappings(Arrays.asList(actualMapping)); projectData.store(); } catch (CoreException ce) { GitProjectData.delete(project); throw ce; } catch (RuntimeException ce) { GitProjectData.delete(project); throw ce; } RepositoryProvider .map(project, GitProvider.class.getName()); projectData = GitProjectData.get(project); project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(m, 50)); m.worked(10); } else { Activator .trace("Attempted to share project without repository ignored :" + project); m.worked(60); } } } finally { m.done(); } }
Source:
public void setup() { context.turnOffAuthorisationSystem(); configurationService.setProperty("webui.user.assumelogin", true); context.restoreAuthSystemState(); }

Target:
public void setup() { configurationService.setProperty("webui.user.assumelogin", true); }
Source:
protected ContentSecurityPolicy addOrAppend(String key, String value) { if (m_directives.containsKey(key)) { String existingSource = m_directives.get(key); if ((existingSource != null || value != null) && !StringUtility.containsString(existingSource, value)) { m_directives.put(key, StringUtility.join(SOURCE_SEPARATOR, existingSource, value)); } } else { m_directives.put(key, value); } return this; }

Target:
protected ContentSecurityPolicy addOrAppend(String key, String value) { if (value == null) { return this; } if (m_directives.containsKey(key)) { String existingSource = m_directives.get(key); if (!StringUtility.containsString(existingSource, value)) { m_directives.put(key, StringUtility.join(SOURCE_SEPARATOR, existingSource, value)); } } else { m_directives.put(key, value); } return this; }
Source:
public AppendBlobClientBuilder credential(SharedKeyCredential credential) { this.sharedKeyCredential = credential; return this; }

Target:
public AppendBlobClientBuilder credential(SharedKeyCredential credential) { this.sharedKeyCredential = credential; this.tokenCredential = null; this.sasTokenCredential = null; return this; }
Source:
public boolean canRefresh(DRepresentation representation) { return isSupported(representation) && hasRelatedViewpointEnabled(representation); }

Target:
public boolean canRefresh(DRepresentation representation) { return isSupported(representation) && hasRequiredViewpointsEnabled(representation); }
Source:
public static Set<String> authorityListToSet( Collection<? extends GrantedAuthority> userAuthorities) { if (userAuthorities == null) { return Collections.emptySet(); } Set<String> set = new HashSet<>(userAuthorities.size()); for (GrantedAuthority authority : userAuthorities) { set.add(authority.getAuthority()); } return set; }

Target:
public static Set<String> authorityListToSet( Collection<? extends GrantedAuthority> userAuthorities) { Assert.notNull(userAuthorities, "userAuthorities cannot be null"); Set<String> set = new HashSet<>(userAuthorities.size()); for (GrantedAuthority authority : userAuthorities) { set.add(authority.getAuthority()); } return set; }
Source:
protected Control createDialogArea(Composite parent) { Composite main = new Composite(parent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).applyTo(main); main.setLayout(new GridLayout(1, false)); TableViewer projectsViewer = new TableViewer(main, SWT.BORDER | SWT.V_SCROLL); GridDataFactory.fillDefaults().grab(true, true) .applyTo(projectsViewer.getControl()); projectsViewer.setLabelProvider( WorkbenchLabelProvider.getDecoratingWorkbenchLabelProvider()); projectsViewer.setContentProvider(ArrayContentProvider.getInstance()); projectsViewer.setInput(groupsToDelete); setTitle(UIText.RepositoriesView_RepoGroup_Delete_Title); setMessage(UIText.RepositoriesView_RepoGroup_Delete_Confirm); return main; }

Target:
protected Control createDialogArea(Composite parent) { Composite main = new Composite(parent, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).applyTo(main); main.setLayout(new GridLayout(1, false)); TreeViewer groupsViewer = new TreeViewer(main, SWT.BORDER | SWT.V_SCROLL); GridDataFactory.fillDefaults().grab(true, true) .applyTo(groupsViewer.getControl()); groupsViewer.setLabelProvider( WorkbenchLabelProvider.getDecoratingWorkbenchLabelProvider()); groupsViewer.setContentProvider( new DeleteRepositoryGroupTreeContentProvider()); groupsViewer.setInput(groupsToDelete); setTitle(UIText.RepositoriesView_RepoGroup_Delete_Title); setMessage(UIText.RepositoriesView_RepoGroup_Delete_Confirm); return main; }
Source:
public void setUp() throws Exception { super.setUp(); gitDir = new File(project.getProject() .getLocationURI().getPath(), Constants.DOT_GIT); testRepository = new TestRepository(gitDir); testRepository.connect(project.getProject()); testRepository.commit("initial commit"); }

Target:
public void setUp() throws Exception { super.setUp(); gitDir = new File(project.getProject() .getLocationURI().getPath(), Constants.DOT_GIT); testRepository = new TestRepository(gitDir); testRepository.connect(project.getProject()); }
Source:
private Map<NodeId, Double> calculateFactors(WorkloadExecutionStatus status, Map<NodeId, WorkloadConfiguration> configurations) { Map<NodeId, Double> result = new HashMap<NodeId, Double>(); Map<NodeId, Double> scores = new HashMap<NodeId, Double>(); int nodesCount = status.getNodes().size(); double scoreSum = 0; for (NodeId nodeId: status.getNodes()) { double totalSamplesRate = (status.getTotalSamples() == 0) ? (1d / nodesCount) : (double) status.getSamples(nodeId) / status.getTotalSamples(); double ownSamplesRate = (configurations.get(nodeId) == null || configurations.get(nodeId).getSamples() == 0) ? 1d : (double) status.getSamples(nodeId) / configurations.get(nodeId).getSamples(); double score = totalSamplesRate + ownSamplesRate * 10; scores.put(nodeId, score); scoreSum += score; } for (NodeId nodeId: status.getNodes()) { result.put(nodeId, scores.get(nodeId) / scoreSum); } return result; }

Target:
private Map<NodeId, Double> calculateFactors(WorkloadExecutionStatus status, Map<NodeId, WorkloadConfiguration> configurations) { Map<NodeId, Double> result = new HashMap<NodeId, Double>(); Map<NodeId, Double> scores = new HashMap<NodeId, Double>(); int nodesCount = status.getNodes().size(); double scoreSum = 0; for (NodeId nodeId: status.getNodes()) { double totalSamplesRate = (status.getTotalSamples() == 0) ? (1d / nodesCount) : (double) status.getSamples(nodeId) / status.getTotalSamples(); double score = totalSamplesRate; scores.put(nodeId, score); scoreSum += score; } for (NodeId nodeId: status.getNodes()) { result.put(nodeId, scores.get(nodeId) / scoreSum); } return result; }
Source:
protected void configure() { DynamicMap.mapOf(binder(), CONFIG_KIND); DynamicMap.mapOf(binder(), CAPABILITY_KIND); DynamicMap.mapOf(binder(), CapabilityDefinition.class); child(CONFIG_KIND, "capabilities").to(CapabilitiesCollection.class); }

Target:
protected void configure() { DynamicMap.mapOf(binder(), CONFIG_KIND); DynamicMap.mapOf(binder(), CAPABILITY_KIND); child(CONFIG_KIND, "capabilities").to(CapabilitiesCollection.class); }
Source:
public void stop(final BundleContext context) throws Exception { SelectionRepositoryStateCache.INSTANCE.dispose(); if (focusListener != null) { if (PlatformUI.isWorkbenchRunning()) { PlatformUI.getWorkbench().removeWindowListener(focusListener); } focusListener = null; } if (GitTraceLocation.REPOSITORYCHANGESCANNER.isActive()) { GitTraceLocation.getTrace().trace( GitTraceLocation.REPOSITORYCHANGESCANNER.getLocation(), "Trying to cancel " + rcs.getName() + " job"); } getPreferenceStore().removePropertyChangeListener(rcs); rcs.setReschedule(false); rcs.cancel(); refreshJob.cancel(); if (GitTraceLocation.REPOSITORYCHANGESCANNER.isActive()) { GitTraceLocation.getTrace().trace( GitTraceLocation.REPOSITORYCHANGESCANNER.getLocation(), "Jobs terminated"); } if (resourceManager != null) { resourceManager.dispose(); resourceManager = null; } super.stop(context); plugin = null; }

Target:
public void stop(final BundleContext context) throws Exception { SelectionRepositoryStateCache.INSTANCE.dispose(); if (focusListener != null) { if (PlatformUI.isWorkbenchRunning()) { PlatformUI.getWorkbench().removeWindowListener(focusListener); } focusListener = null; } if (GitTraceLocation.REPOSITORYCHANGESCANNER.isActive()) { GitTraceLocation.getTrace().trace( GitTraceLocation.REPOSITORYCHANGESCANNER.getLocation(), "Trying to cancel " + rcs.getName() + " job"); } if (rcs != null) { getPreferenceStore().removePropertyChangeListener(rcs); rcs.setReschedule(false); rcs.cancel(); } refreshJob.cancel(); if (GitTraceLocation.REPOSITORYCHANGESCANNER.isActive()) { GitTraceLocation.getTrace().trace( GitTraceLocation.REPOSITORYCHANGESCANNER.getLocation(), "Jobs terminated"); } if (resourceManager != null) { resourceManager.dispose(); resourceManager = null; } super.stop(context); plugin = null; }
Source:
public Node<View<?>, Edge> getParent(final double x, final double y) { return CaseManagementBuilderControlHelper.getParent((CaseManagementCanvasHandler) canvasHandler, x, y); }

Target:
public Node<View<?>, Edge> getParent(final double x, final double y) { final Optional<Node<View<?>, Edge>> parent = canvasHandler.getElementAt(x, y); return parent.orElse(null); }
Source:
public void addWall(Coordinate coordinate) { if (!wallParts.add(coordinate)) throw new IllegalArgumentException("There's already a wall at this coordinate"); if (playerStartingPositions.contains(coordinate)) throw new IllegalArgumentException("a startingpos cannot contain a wall"); this.squares.remove(coordinate); }

Target:
public void addWall(Coordinate coordinate) { if (playerStartingPositions.contains(coordinate)) throw new IllegalArgumentException("a startingpos cannot contain a wall"); if (!wallParts.add(coordinate)) throw new IllegalArgumentException("There's already a wall at this coordinate"); this.squares.remove(coordinate); }
Source:
protected Object convert(Object in, Object cached) { Object o; try { o = outputClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { logger.error("Failed to create new instance of output POJO", e); return null; } for (Map.Entry<PojoUtils.Getter, PojoUtils.Setter> entry : fieldMap.entrySet()) { entry.getValue().set(o, entry.getKey().get(in)); } if (cached == null) { return null; } ArrayList<Object> includeObjects = (ArrayList<Object>)cached; int idx = 0; for (PojoUtils.Setter includeSetter : includeSetters) { try { includeSetter.set(o, includeObjects.get(idx++)); } catch (RuntimeException e) { logger.error("Failed to set the property. Continuing with default.", e); } } return o; }

Target:
protected Object convert(Object in, Object cached) { Object o; try { o = outputClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { logger.error("Failed to create new instance of output POJO", e); errorTupleCount++; error.emit(in); return null; } try { for (Map.Entry<PojoUtils.Getter, PojoUtils.Setter> entry : fieldMap.entrySet()) { entry.getValue().set(o, entry.getKey().get(in)); } } catch (RuntimeException e) { logger.error("Failed to set the property. Continuing with default.", e); errorTupleCount++; error.emit(in); return null; } if (cached == null) { return o; } ArrayList<Object> includeObjects = (ArrayList<Object>)cached; for (int i = 0; i < includeSetters.size(); i++) { try { includeSetters.get(i).set(o, includeObjects.get(i)); } catch (RuntimeException e) { logger.error("Failed to set the property. Continuing with default.", e); errorTupleCount++; error.emit(in); return null; } } return o; }
Source:
public boolean addPlayer(ProxiedPlayer player) { Preconditions.checkNotNull( player, "player" ); if ( !players.contains( player ) ) { players.add( player ); } if ( player.isConnected() && visible ) { return sendPacket( player, addPacket() ); } return false; }

Target:
public void addPlayer(ProxiedPlayer player) { Preconditions.checkNotNull( player, "player" ); Preconditions.checkArgument( canBeAdded( player ), player.getName() + " cannot be added to BossBar ( make sure to use canBeAdded to avoid such errors )" ); if ( !canBeAdded( player ) ) { return; } players.add( player ); if ( player.isConnected() && visible ) { sendPacket( player, addPacket() ); } }
Source:
public void updateNode(final OnmsNode node, String rescanExisting) { updateLocation(node); final OnmsNode dbNode = m_nodeDao.getHierarchy(node.getId()); String prevLocation = dbNode.getLocation().getLocationName(); String currentLocation = node.getLocation().getLocationName(); node.setCategories(dbNode.getCategories()); final EventAccumulator accumulator = new EventAccumulator(m_eventForwarder); dbNode.mergeNode(node, accumulator, false); updateNodeHostname(dbNode); m_nodeDao.update(dbNode); m_nodeDao.flush(); if(!prevLocation.equals(currentLocation)) { accumulator.sendNow(EventUtils.createNodeLocationChangedEvent("Provisiond", dbNode.getId(), dbNode.getLabel(), prevLocation, currentLocation)); } accumulator.flush(); final EntityVisitor eventAccumlator = new UpdateEventVisitor(m_eventForwarder, rescanExisting); dbNode.visit(eventAccumlator); }

Target:
public void updateNode(final OnmsNode node, String rescanExisting) { updateLocation(node); final OnmsNode dbNode = m_nodeDao.getHierarchy(node.getId()); String prevLocation = dbNode.getLocation().getLocationName(); String currentLocation = node.getLocation().getLocationName(); node.setCategories(dbNode.getCategories()); final EventAccumulator accumulator = new EventAccumulator(m_eventForwarder); dbNode.mergeNode(node, accumulator, false); updateNodeHostname(dbNode); m_nodeDao.update(dbNode); m_nodeDao.flush(); if(!prevLocation.equals(currentLocation)) { accumulator.sendNow(EventUtils.createNodeLocationChangedEvent(PROVISIOND, dbNode.getId(), dbNode.getLabel(), prevLocation, currentLocation)); } accumulator.flush(); final EntityVisitor eventAccumlator = new UpdateEventVisitor(m_eventForwarder, rescanExisting); dbNode.visit(eventAccumlator); }
Source:
private void discoverEntities(final StatementPattern pattern, final List<StatementPattern> unmatched) { final Var subj = pattern.getSubjectVar(); final String subjStr = subj.getName(); final RyaURI predURI = getPredURI(pattern); if(new URIImpl(predURI.getData()).equals(RDF.TYPE)) { final Var obj = pattern.getObjectVar(); final RyaURI objURI = new RyaURI(obj.getValue().stringValue()); try { final Optional<Type> optType = typeStorage.get(objURI); if(optType.isPresent()) { final Type type = optType.get(); typeMap.put(type, pattern); subjectTypeMap.put(subjStr, type); for(final StatementPattern propertyPattern : unmatched) { final RyaURI property = getPredURI(propertyPattern); final Var typeSubVar = getTypeSubject(type); final Var patternSubVar = propertyPattern.getSubjectVar(); if (type.getPropertyNames().contains(property) && typeSubVar.equals(patternSubVar)) { typeMap.put(type, propertyPattern); } } } } catch (final TypeStorageException e) { e.printStackTrace(); } } else { if(subjectTypeMap.containsKey(subjStr)) { final Type type = subjectTypeMap.get(subjStr); if(type.getPropertyNames().contains(predURI)) { typeMap.put(type, pattern); } else { unmatched.add(pattern); } } else { unmatched.add(pattern); } } }

Target:
private void discoverEntities(final StatementPattern pattern, final List<StatementPattern> unmatched) { final Var subj = pattern.getSubjectVar(); final String subjStr = subj.getName(); final RyaURI predURI = getPredURI(pattern); if(new URIImpl(predURI.getData()).equals(RDF.TYPE)) { final Var obj = pattern.getObjectVar(); final RyaURI objURI = new RyaURI(obj.getValue().stringValue()); try { final Optional<Type> optType = typeStorage.get(objURI); if(optType.isPresent()) { final Type type = optType.get(); typeMap.put(type, pattern); subjectTypeMap.put(subjStr, type); for(final StatementPattern propertyPattern : unmatched) { final RyaURI property = getPredURI(propertyPattern); final Var typeSubVar = getTypeSubject(type); final Var patternSubVar = propertyPattern.getSubjectVar(); if (type.getPropertyNames().contains(property) && typeSubVar.equals(patternSubVar)) { typeMap.put(type, propertyPattern); } } } } catch (final TypeStorageException e) { e.printStackTrace(); } } else { if(subjectTypeMap.containsKey(subjStr)) { final Type type = subjectTypeMap.get(subjStr); if(type.getPropertyNames().contains(predURI)) { if(!typeMap.containsKey(type)) { typeMap.put(type, pattern); } } else { unmatched.add(pattern); } } else { unmatched.add(pattern); } } }
Source:
public String toString() { String prefix = service.getClass().getCanonicalName() + "#" + method.getName() + "("; return Stream .of(method.getParameters()) .map(Parameter::getType) .map(Class::getSimpleName) .collect(joining(", ", prefix, ")")); }

Target:
public String toString() { String classAndMethod = service.getClass().getCanonicalName() + "#" + method.getName(); String args = Stream.of(method.getParameters()) .map(Parameter::getType) .map(Class::getSimpleName) .collect(Collectors.joining(", ", "(", ")")); return classAndMethod + args; }
Source:
public void onNext(T t) { if (index++ % skip == 0) { U b; try { b = ObjectHelper.requireNonNull(bufferSupplier.call(), "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); } catch (Throwable e) { buffers.clear(); s.dispose(); actual.onError(e); return; } buffers.offer(b); } Iterator<U> it = buffers.iterator(); while (it.hasNext()) { U b = it.next(); b.add(t); if (count <= b.size()) { it.remove(); actual.onNext(b); } } }

Target:
public void onNext(T t) { if (index++ % skip == 0) { U b; try { b = ObjectHelper.requireNonNull(bufferSupplier.call(), "The bufferSupplier returned a null collection. Null values are generally not allowed in 2.x operators and sources."); } catch (Throwable e) { buffers.clear(); s.dispose(); actual.onError(e); return; } buffers.offer(b); } Iterator<U> it = buffers.iterator(); while (it.hasNext()) { U b = it.next(); b.add(t); if (count <= b.size()) { it.remove(); actual.onNext(b); } } }
Source:
private static int getTsValue(ByteBuffer pcapPacketHeader, int blockLength, int option) { int count = 0; int optionCode; int optionValue; int optionLength; int optionBufferLength = blockLength - PcapFileValues.INTERFACE_DESCRIPTION_SIZE * 2 - 4; if (optionBufferLength == 0) { return 6; } pcapPacketHeader.position(16); while (count < optionBufferLength) { optionCode = ConversionHelper.unsignedShortToInt(pcapPacketHeader.getShort()); if (optionCode < 2 || optionCode > 14) { return 0; } count = count + 2; optionLength = ConversionHelper.unsignedShortToInt(pcapPacketHeader.getShort()); count += 2; if (optionLength <= 4) { optionValue = pcapPacketHeader.getInt(); if (optionCode == option) { return optionValue; } count += 4; } else { for (int i = 0; i <= optionLength; i++) { pcapPacketHeader.get(); } count += optionLength + 1; } } if (option == PcapFileValues.PCAPNG_IFTSRESOL_CODE) { return 6; } return 0; }

Target:
private static int getTsValue(ByteBuffer pcapPacketHeader, int blockLength, int option) { int count = 0; int optionCode; int optionValue; int optionLength; int optionBufferLength = blockLength - PcapFileValues.INTERFACE_DESCRIPTION_SIZE * 2 - 4; if (optionBufferLength == 0) { return 6; } pcapPacketHeader.position(16); while (count < optionBufferLength) { optionCode = ConversionHelper.unsignedShortToInt(pcapPacketHeader.getShort()); if (optionCode < 2 || optionCode > 14) { break; } count = count + 2; optionLength = ConversionHelper.unsignedShortToInt(pcapPacketHeader.getShort()); count += 2; if (optionLength <= 4) { optionValue = pcapPacketHeader.getInt(); if (optionCode == option) { return optionValue; } count += 4; } else { for (int i = 0; i <= optionLength; i++) { pcapPacketHeader.get(); } count += optionLength + 1; } } if (option == PcapFileValues.PCAPNG_IFTSRESOL_CODE) { return 6; } return 0; }
Source:
protected Symbol visitLikePredicate(LikePredicate node, ExpressionAnalysisContext context) { if (node.getEscape() != null) { throw new UnsupportedOperationException("ESCAPE is not supported."); } Symbol expression = node.getValue().accept(this, context); Symbol pattern = node.getPattern().accept(this, context); Symbol ignoreCase = Literal.of(node.getIgnoreCase() ? "true" : "false"); return allocateFunction( LikeOperator.NAME, ImmutableList.of(expression, pattern, ignoreCase), context); }

Target:
protected Symbol visitLikePredicate(LikePredicate node, ExpressionAnalysisContext context) { if (node.getEscape() != null) { throw new UnsupportedOperationException("ESCAPE is not supported."); } Symbol expression = node.getValue().accept(this, context); Symbol pattern = node.getPattern().accept(this, context); Symbol ignoreCase = Literal.of(node.getIgnoreCase()); return allocateFunction( LikeOperator.NAME, ImmutableList.of(expression, pattern, ignoreCase), context); }
Source:
private void addMacPool(final DataCenterModel dcModel) { SharedMacPoolModel macPoolModel = new NewSharedMacPoolModel(this) { @Override protected void postSave(Guid macPoolId) { super.postSave(macPoolId); ArrayList<MacPool> macPools = new ArrayList<MacPool>(dcModel.getMacPoolListModel().getItems()); macPools.add(1, getEntity()); dcModel.getMacPoolListModel().setItems(macPools); dcModel.getMacPoolListModel().setSelectedItem(getEntity()); } }; setConfirmWindow(macPoolModel); }

Target:
private void addMacPool(final DataCenterModel dcModel) { SharedMacPoolModel macPoolModel = new NewSharedMacPoolModel(this) { @Override protected void onActionSucceeded(Guid macPoolId) { MacPool macPool = getEntity(); macPool.setId(macPoolId); dcModel.getMacPoolListModel().getItems().add(macPool); dcModel.getMacPoolListModel().setSelectedItem(macPool); DataCenterListModel.this.setConfirmWindow(null); } }; macPoolModel.setEntity(new MacPool()); setConfirmWindow(macPoolModel); }
Source:
public void attach(ServoController controller, Integer pin, Double pos, Double speed) throws Exception { if (controller == null) { log.error("{}.attach(null)", getName()); return; } if (controllers.contains(controller.getName())) { log.info("{}.attach({}) controller already attached", getName(), controller.getName()); return; } if (pin != null) { setPin(pin); } if (pos != null) { targetPos = pos; lastPos = targetPos; } if (speed != null) { setSpeed(speed); } controllers.add(controller.getName()); controller.attach(this); }

Target:
public void attach(ServoController controller, Integer pin, Double pos, Double speed) throws Exception { attach(controller, pin, pos, speed, null); }
Source:
private void trackSessionIfNeeded(final Session session) { boolean notifyForRelease = configuration.shouldNotifyForReleaseStage(getReleaseStage()); if (notifyForRelease && (configuration.shouldAutoCaptureSessions() || !session.isAutoCaptured()) && session.isTracked().compareAndSet(false, true)) { try { final String endpoint = configuration.getSessionEndpoint(); Async.run(new Runnable() { @Override public void run() { flushStoredSessions(); SessionTrackingPayload payload = new SessionTrackingPayload(session, client.appData); try { configuration.getDelivery().deliver(payload, configuration); } catch (NetworkException exception) { Logger.info("Failed to post session payload"); sessionStore.write(session); } catch (BadResponseException exception) { Logger.warn("Invalid session tracking payload", exception); } } }); } catch (RejectedExecutionException exception) { sessionStore.write(session); } } }

Target:
private void trackSessionIfNeeded(final Session session) { boolean notifyForRelease = configuration.shouldNotifyForReleaseStage(getReleaseStage()); if (notifyForRelease && (configuration.shouldAutoCaptureSessions() || !session.isAutoCaptured()) && session.isTracked().compareAndSet(false, true)) { try { final String endpoint = configuration.getSessionEndpoint(); Async.run(new Runnable() { @Override public void run() { flushStoredSessions(); SessionTrackingPayload payload = new SessionTrackingPayload(session, client.appData); try { configuration.getDelivery().deliver(payload, configuration); } catch (DeliveryFailureException exception) { Logger.warn("Storing session payload for future delivery", exception); sessionStore.write(session); } catch (Exception exception) { Logger.warn("Dropping invalid session tracking payload", exception); } } }); } catch (RejectedExecutionException exception) { sessionStore.write(session); } } }
Source:
public void setTTL(K key, long ttl, TimeUnit timeunit) { if (getNodeEngine().getClusterService().getClusterVersion().isLessThan(Versions.V3_11)) { throw new UnsupportedOperationException("setTTL method is available when cluster version is 3.11 or higher"); } checkNotNull(key); setTTLInternal(key, ttl, timeunit); }

Target:
public void setTTL(K key, long ttl, TimeUnit timeunit) { checkNotNull(key); checkNotNull(timeunit); setTTLInternal(key, ttl, timeunit); }
Source:
protected void buildTagList(File directory, boolean interactive) { this.tagList = new TreeSet<>(); ArrayList<String> argv = new ArrayList<>(); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); argv.add(RepoCommand); argv.add("tags"); Executor executor = new Executor(argv, directory, RuntimeEnvironment.getInstance().getInteractiveCommandTimeout()); MercurialTagParser parser = new MercurialTagParser(); int status = executor.exec(true, parser); if (status != 0) { LOGGER.log(Level.WARNING, "Failed to get tags for: \"{0}\" Exit code: {1}", new Object[]{directory.getAbsolutePath(), String.valueOf(status)}); } else { this.tagList = parser.getEntries(); } }

Target:
protected void buildTagList(File directory, boolean interactive) { this.tagList = new TreeSet<>(); ArrayList<String> argv = new ArrayList<>(); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); argv.add(RepoCommand); argv.add("tags"); Executor executor = new Executor(argv, directory, interactive ? RuntimeEnvironment.getInstance().getInteractiveCommandTimeout() : RuntimeEnvironment.getInstance().getCommandTimeout()); MercurialTagParser parser = new MercurialTagParser(); int status = executor.exec(true, parser); if (status != 0) { LOGGER.log(Level.WARNING, "Failed to get tags for: \"{0}\" Exit code: {1}", new Object[]{directory.getAbsolutePath(), String.valueOf(status)}); } else { this.tagList = parser.getEntries(); } }
Source:
public void canHandleIntermediateEmptyPage() { List<Integer> pagedList = new PagedList<Integer>(new Page<Integer>() { @Override public String nextPageLink() { return "A"; } @Override public List<Integer> items() { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); return list; } }) { private final ClientLogger logger = new ClientLogger(PagedList.class); @Override public Page<Integer> nextPage(String nextPageLink) { if (nextPageLink == "A") { return new Page<Integer>() { @Override public String nextPageLink() { return "B"; } @Override public List<Integer> items() { return new ArrayList<>(); } }; } else if (nextPageLink == "B") { return new Page<Integer>() { @Override public String nextPageLink() { return "C"; } @Override public List<Integer> items() { List<Integer> list = new ArrayList<>(); list.add(3); list.add(4); return list; } }; } else if (nextPageLink == "C") { return new Page<Integer>() { @Override public String nextPageLink() { return null; } @Override public List<Integer> items() { List<Integer> list = new ArrayList<>(); list.add(5); list.add(6); return list; } }; } logger.logAndThrow(new RuntimeException("nextPage should not be called after a page with next link as null")); return null; } }; ListIterator<Integer> itr = pagedList.listIterator(); int c = 1; while (itr.hasNext()) { Assert.assertEquals(c, (int) itr.next()); c++; } Assert.assertEquals(7, c); }

Target:
public void canHandleIntermediateEmptyPage() { List<Integer> pagedList = new PagedList<Integer>(new Page<Integer>() { @Override public String nextPageLink() { return "A"; } @Override public List<Integer> items() { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); return list; } }) { @Override public Page<Integer> nextPage(String nextPageLink) { if (nextPageLink == "A") { return new Page<Integer>() { @Override public String nextPageLink() { return "B"; } @Override public List<Integer> items() { return new ArrayList<>(); } }; } else if (nextPageLink == "B") { return new Page<Integer>() { @Override public String nextPageLink() { return "C"; } @Override public List<Integer> items() { List<Integer> list = new ArrayList<>(); list.add(3); list.add(4); return list; } }; } else if (nextPageLink == "C") { return new Page<Integer>() { @Override public String nextPageLink() { return null; } @Override public List<Integer> items() { List<Integer> list = new ArrayList<>(); list.add(5); list.add(6); return list; } }; } throw new RuntimeException("nextPage should not be called after a page with next link as null"); } }; ListIterator<Integer> itr = pagedList.listIterator(); int c = 1; while (itr.hasNext()) { Assert.assertEquals(c, (int) itr.next()); c++; } Assert.assertEquals(7, c); }
Source:
public RMStateDTO getInitialState(@HeaderParam("sessionid") String sessionId, @HeaderParam("clientCounter") @DefaultValue("-1") String clientCounter) throws NotConnectedException { checkAccess(sessionId); long counter = Integer.valueOf(clientCounter); return RMStateCaching.getRMInitialState(counter); }

Target:
public RMStateDelta getInitialState(@HeaderParam("sessionid") String sessionId, @HeaderParam("clientCounter") @DefaultValue("-1") String clientCounter) throws NotConnectedException { checkAccess(sessionId); long counter = Integer.valueOf(clientCounter); return RMStateCaching.getRMInitialState(counter); }
Source:
public void fillToolBar(IToolBarManager toolBarManager) { toolBarManager.add(new Separator()); toolBarManager.add(new Action(Messages.AbstractReviewTaskEditorPage_Show_Review_Navigator, ReviewsImages.REVIEW) { @Override public void run() { try { PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getActivePage() .showView(ReviewsUiConstants.REVIEW_EXPLORER_ID); } catch (PartInitException e) { StatusHandler.log(new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, e.getMessage(), e)); } } }); super.fillToolBar(toolBarManager); }

Target:
public void fillToolBar(IToolBarManager toolBarManager) { toolBarManager.add(new Separator()); toolBarManager.add(new Action(Messages.AbstractReviewTaskEditorPage_Show_Review_Navigator, ReviewsImages.REVIEW) { @Override public void run() { WorkbenchUtil.showViewInActiveWindow(ReviewsUiConstants.REVIEW_EXPLORER_ID); } }); super.fillToolBar(toolBarManager); }
Source:
public void non_whitespace_tokens() { FileInput parsed = parse("if foo:\n pass"); IfStatement ifStmt = (IfStatement) parsed.statements().statements().get(0); List<Token> collect = new ArrayList<>(ifStmt.children().stream().map(t -> t.is(Kind.TOKEN) ? (Token) t : t.firstToken()).collect(Collectors.toList())); collect.add(parsed.lastToken()); assertThat(TreeUtils.tokens(parsed)).containsExactly(collect.toArray(new Token[0])); List<Token> nonWhitespaceTokens = TreeUtils.nonWhitespaceTokens(ifStmt); nonWhitespaceTokens.forEach(t -> { assertThat(t.type()).isNotIn(PythonTokenType.NEWLINE, PythonTokenType.INDENT, PythonTokenType.DEDENT); }); assertThat(nonWhitespaceTokens).hasSize(4); }

Target:
public void non_whitespace_tokens() { FileInput parsed = parse("if foo:\n pass"); IfStatement ifStmt = (IfStatement) parsed.statements().statements().get(0); List<Token> nonWhitespaceTokens = TreeUtils.nonWhitespaceTokens(ifStmt); nonWhitespaceTokens.forEach(t -> assertThat(t.type()).isNotIn(PythonTokenType.NEWLINE, PythonTokenType.INDENT, PythonTokenType.DEDENT)); assertThat(nonWhitespaceTokens).hasSize(4); assertThat(nonWhitespaceTokens.stream().map(Token::value)).containsExactly("if", "foo", ":", "pass"); }
Source:
public void test() { GetSpecificConfigurationObjectRequestData reqData = makeRequestDatareqData(); Object obj = commonMapper.map(reqData, GetSpecificConfigurationObjectRequestDataDto.class); assertTrue(obj != null && obj instanceof GetSpecificConfigurationObjectRequestDataDto); }

Target:
public void test() { SpecificConfigurationObjectRequestData reqData1 = makeRequestData(); Object obj = commonMapper.map(reqData1, SpecificConfigurationObjectRequestDataDto.class); assertTrue(obj != null && obj instanceof SpecificConfigurationObjectRequestDataDto); Object reqData2 = commonMapper.map(obj, SpecificConfigurationObjectRequestData.class); assertTrue(reqData2 != null && reqData2 instanceof SpecificConfigurationObjectRequestData); assertTrue(reqData1.equals(reqData2)); }
Source:
public static Bundle getBundleByMap(Map<String, Object> row){ Bundle b = new Bundle(); b.setId(row.get("id").toString()); b.setName(row.get("name").toString()); b.setPublishDate((Date)row.get("publish_date")); b.setExpireDate((Date)row.get("expire_date")); b.setOwner(UtilMethods.isSet(row.get("owner"))?row.get("owner").toString():""); b.setForcePush(UtilMethods.isSet(row.get("force_push")) && DbConnectionFactory .isDBTrue(row.get("force_push").toString())); b.setFilterKey(UtilMethods.isSet(row.get("filter_key")) ? row.get("filter_key").toString() : ""); return b; }

Target:
public static Bundle getBundleByMap(Map<String, Object> row){ final Bundle bundle = new Bundle(); bundle.setId(row.get("id").toString()); bundle.setName(row.get("name").toString()); bundle.setPublishDate((Date)row.get("publish_date")); bundle.setExpireDate((Date)row.get("expire_date")); bundle.setOwner(UtilMethods.isSet(row.get("owner"))?row.get("owner").toString():""); bundle.setForcePush(UtilMethods.isSet(row.get("force_push")) && DbConnectionFactory .isDBTrue(row.get("force_push").toString())); bundle.setFilterKey(UtilMethods.isSet(row.get("filter_key")) ? row.get("filter_key").toString() : ""); return bundle; }
Source:
public AddTruststoreAuthentication build() { if (truststorePath != null && truststorePassword == null) { throw new IllegalArgumentException("truststorePassword is manadatory when defining also truststore"); } return new AddTruststoreAuthentication(this); }

Target:
public AddTruststoreAuthentication build() { if (truststorePassword == null) { throw new IllegalArgumentException("truststorePassword is manadatory when defining the truststore"); } return new AddTruststoreAuthentication(this); }
Source:
public BuildingBlockObject registerBuilding(final String name, Block.Properties props, Item.Properties itemProps) { BlockItemObject<Block> blockObj = register(name, props, itemProps); return new BuildingBlockObject(blockObj, register(name + "_slab", () -> new SlabBlock(props), itemProps), register(name + "_stairs", () -> new StairsBlock(() -> blockObj.get().getDefaultState(), props), itemProps), register(name + "_wall", () -> new WallBlock(props), itemProps) ); }

Target:
public BuildingBlockObject registerBuilding(final String name, Block.Properties props, Item.Properties itemProps) { BlockItemObject<Block> blockObj = register(name, props, itemProps); return new BuildingBlockObject(blockObj, register(name + "_slab", () -> new SlabBlock(props), itemProps), register(name + "_stairs", () -> new StairsBlock(() -> blockObj.get().getDefaultState(), props), itemProps) ); }