auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { if (inputStream == null || outputStream == null) { if (outputStream != null) { IOUtils.closeQuietly(outputStream); } return; } try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(outputStream); return; } }

Target:
public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { if (inputStream == null || outputStream == null) { if (outputStream != null) { IOUtils.closeQuietly(outputStream); } return; } try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(outputStream); } }
Source:
public synchronized void close() { try { Closer closer = Closer.create(); if (mJournalOutputStream != null) { closer.register(mJournalOutputStream); } closer.register(mGarbageCollector); closer.close(); } catch (IOException e) { LOG.warn("Failed to close UfsJournalLogWriter with error: {}.", e.getMessage()); } mClosed = true; }

Target:
public synchronized void close() throws IOException { Closer closer = Closer.create(); if (mJournalOutputStream != null) { closer.register(mJournalOutputStream); } closer.register(mGarbageCollector); closer.close(); mClosed = true; }
Source:
public void testFooPing() { // change logging level, does NOT work Logger logger = Logger.getLogger(JMXMethodExecutor.class.getName()); Level originalLevel = logger.getLevel(); logger.setLevel(Level.OFF); // Initialize weld, Foo bean is used in observer new Weld().initialize(); logger.setLevel(originalLevel); }

Target:
public void testFooPing() { // Initialize weld, Foo bean is used in observer new Weld().initialize(); }
Source:
public void searchForProcesses() throws Exception { desktopPage.searchInSearchField("process"); int numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); searchResultPage.searchInSearchField("proc"); numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); searchResultPage.searchInSearchField("möhö"); numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be no process found",0,numberOfResults); }

Target:
public void searchForProcesses() throws Exception { desktopPage.searchInSearchField("process"); int numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); searchResultPage.searchInSearchField("proc"); numberOfResults = searchResultPage.getNumberOfResults(); assertEquals("There should be two processes found",2,numberOfResults); //TODO: selenium is too fast here and counts results from previous search searchResultPage.searchInSearchField("möhö"); numberOfResults = searchResultPage.getNumberOfResults(); //assertEquals("There should be no process found",0,numberOfResults); }
Source:
public Integer getIdle() { HikariPool pool = getHikariPool(); if (Objects.nonNull(pool)) { return pool.getIdleConnections(); } return super.getIdle(); }

Target:
public Integer getIdle() { HikariPool pool = getHikariPool(); if (Objects.nonNull(pool)) { return pool.getIdleConnections(); } return null; }
Source:
public synchronized void setTailSegment(long tailSegment) { dataStore.put(Long.class, PREFIX_TAIL_SEGMENT, KEY_TAIL_SEGMENT, tailSegment); // Set the epoch in the router as well. //TODO need to figure out if we can remove this redundancy serverRouter.setServerEpoch(tailSegment); }

Target:
public void setTailSegment(long tailSegment) { dataStore.put(Long.class, PREFIX_TAIL_SEGMENT, KEY_TAIL_SEGMENT, tailSegment); }
Source:
public void release() { JdbcConnectionAccess connectionAccess = jdbcContext.getJdbcConnectionAccess(); if( !( connectionAccess instanceof JdbcConnectionAccessProvidedConnectionImpl ) ) { throw new IllegalStateException( "DdlTransactionIsolatorProvidedConnectionImpl should always use a JdbcConnectionAccessProvidedConnectionImpl" ); } JdbcConnectionAccessProvidedConnectionImpl connectionAccessProvidedConnection = (JdbcConnectionAccessProvidedConnectionImpl) connectionAccess; try { connectionAccess.releaseConnection( null ); } catch (SQLException ignore) { LOG.unableToReleaseIsolatedConnection( ignore ); } }

Target:
public void release() { JdbcConnectionAccess connectionAccess = jdbcContext.getJdbcConnectionAccess(); if( !( connectionAccess instanceof JdbcConnectionAccessProvidedConnectionImpl ) ) { throw new IllegalStateException( "DdlTransactionIsolatorProvidedConnectionImpl should always use a JdbcConnectionAccessProvidedConnectionImpl" ); } try { // While passing the connection to the releaseConnection method might be suitable for other `JdbcConnectionAccess` implementations, // it has no meaning for JdbcConnectionAccessProvidedConnectionImpl because, in this case, the connection is wrapped // and we don't have access to it upon releasing via the DdlTransactionIsolatorProvidedConnectionImpl. connectionAccess.releaseConnection( null ); } catch (SQLException ignore) { LOG.unableToReleaseIsolatedConnection( ignore ); } }
Source:
public void disconnect() { // Set the terminal control state to CLOSED. fControl.setState(TerminalState.CLOSED); }

Target:
public void disconnect() { // Set the terminal control state to CLOSED. if (fControl != null) { fControl.setState(TerminalState.CLOSED); } }
Source:
DropDownMenu updateContextMenu(DropDownMenu menuBar, List<ActionButtonDefinition<T>> actions) { return updateContextMenu(menuBar, actions, true); }

Target:
private DropDownMenu updateContextMenu(DropDownMenu menuBar, List<ActionButtonDefinition<T>> actions) { return updateContextMenu(menuBar, actions, true); }
Source:
private String author(int line) { PersonIdent author = db.getMailmap().map(blame.getSourceAuthor(line)); if (author == null) return ""; //$NON-NLS-1$ String name = showAuthorEmail ? author.getEmailAddress() : author .getName(); return name != null ? name : ""; //$NON-NLS-1$ }

Target:
private String author(int line) { PersonIdent author = blame.getSourceAuthor(line); if (author == null) return ""; //$NON-NLS-1$ String name = showAuthorEmail ? author.getEmailAddress() : author .getName(); return name != null ? name : ""; //$NON-NLS-1$ }
Source:
public void deactivate() { // retrieve the view and the element managed by the edit part View view = getView(); if (view == null) { return; } getDiagramEventBroker().removeNotificationListener(view, this); if (hostSemanticElement == null) { return; } // remove listeners to applied stereotyped for (EObject stereotypeApplication : hostSemanticElement.getStereotypeApplications()) { getDiagramEventBroker().removeNotificationListener(stereotypeApplication, this); } // remove notification on element getDiagramEventBroker().removeNotificationListener(hostSemanticElement, this); // removes the reference to the semantic element hostSemanticElement = null; }

Target:
public void deactivate() { // retrieve the view and the element managed by the edit part View view = getView(); if (view != null) { getDiagramEventBroker().removeNotificationListener(view, this); if (hostSemanticElement != null) { // remove listeners to applied stereotyped for (EObject stereotypeApplication : hostSemanticElement.getStereotypeApplications()) { getDiagramEventBroker().removeNotificationListener(stereotypeApplication, this); } // remove notification on element getDiagramEventBroker().removeNotificationListener(hostSemanticElement, this); // removes the reference to the semantic element hostSemanticElement = null; } } }
Source:
public DefaultSchedulerMessageSource(MuleContext muleContext, PeriodicScheduler scheduler, boolean disallowConcurrentExecution) { this.muleContext = muleContext; this.scheduler = scheduler; this.disallowConcurrentExecution = disallowConcurrentExecution; notificationFunctions = new LinkedList<>(); // Add message received notification notificationFunctions .add((event, component) -> createConnectorMessageNotification(this, event, component.getLocation(), MESSAGE_RECEIVED)); }

Target:
public DefaultSchedulerMessageSource(MuleContext muleContext, PeriodicScheduler scheduler, boolean disallowConcurrentExecution) { this.muleContext = muleContext; this.scheduler = scheduler; this.disallowConcurrentExecution = disallowConcurrentExecution; }
Source:
public final GHIntArrayList reverse() { final int[] buffer = this.buffer; for (int start = 0, end = size() - 1; start < end; start++, end--) { // swap the values int tmp = buffer[start]; buffer[start] = buffer[end]; buffer[end] = tmp; } return this; }

Target:
public final GHIntArrayList reverse() { final int[] buffer = this.buffer; int tmp; for (int start = 0, end = size() - 1; start < end; start++, end--) { // swap the values tmp = buffer[start]; buffer[start] = buffer[end]; buffer[end] = tmp; } return this; }
Source:
public String getAbsoluteFilePath(String relPath) { Bundle bundle = Platform.getBundle(MulticoreVisualizerUIPlugin.PLUGIN_ID); URL fileURL = bundle.getEntry(relPath); File file = null; try { file = new File(FileLocator.resolve(fileURL).toURI()); } catch (URISyntaxException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return file.getAbsolutePath(); }

Target:
private String getAbsoluteFilePath(String relPath) { Bundle bundle = Platform.getBundle(MulticoreVisualizerUIPlugin.PLUGIN_ID); URL fileURL = bundle.getEntry(relPath); File file = null; try { file = new File(FileLocator.resolve(fileURL).toURI()); } catch (URISyntaxException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return file.getAbsolutePath(); }
Source:
public boolean needsInput() { // Since SetBuildOperator is always the last operator (no next operator that needs input from it), // we handle the unfinished work in this method instead of getOutput(). The Driver always // calls it in each iteration. if (unfinishedWork != null) { boolean done = processUnfinishedWork(); channelSetBuilder.updateMemoryReservation(); if (!done) { return false; } } return !finished; }

Target:
public boolean needsInput() { // Since SetBuilderOperator doesn't produce any output, the getOutput() // method may never be called. We need to handle any unfinished work // before addInput() can be called again. return !finished && (unfinishedWork == null || processUnfinishedWork()); }
Source:
public void onStart(ITestContext iTestContext) { getLifecycle().fire(new TestSuiteStartedEvent( getSuiteUid(iTestContext), iTestContext.getSuite().getName() ).withTitle( getCurrentSuiteTitle(iTestContext) ).withLabels( AllureModelUtils.createTestFrameworkLabel("TestNG"), AllureModelUtils.createFeatureLabel(getCurrentSuiteTitle(iTestContext)) )); }

Target:
public void onStart(ITestContext iTestContext) { getLifecycle().fire(new TestSuiteStartedEvent( getSuiteUid(iTestContext), iTestContext.getSuite().getName() ).withTitle( getCurrentSuiteTitle(iTestContext) ).withLabels( AllureModelUtils.createTestFrameworkLabel("TestNG") )); }
Source:
void process(BitVector changedBits, BitVector deletedBits) { toEntityIntBags(changedBits, deletedBits); // note: processAll != process subscriptions.get(0).processAll(changed, deleted); for (int i = 0, s = subscriptions.size(); s > i; i++) { subscriptions.get(i).process(changed, deleted); } }

Target:
void process(BitVector changedBits, BitVector deletedBits) { toEntityIntBags(changedBits, deletedBits); // note: processAll != process subscriptions.get(0).processAll(changed, deleted); for (int i = 1, s = subscriptions.size(); s > i; i++) { subscriptions.get(i).process(changed, deleted); } }
Source:
void setMinMax(double min, double max) { this.min = min; this.max = max; }

Target:
private void setMinMax(double min, double max) { this.min = min; this.max = max; }
Source:
public static Win32VK fromValue(final int code) { if (code < 0 || code > 0xFF) { throw new IllegalArgumentException(String.format("No mapping for %02x", code)); } for (Win32VK vk : Win32VK.values()) { if (vk.code == code) { return vk; } } // We shall not reach here. throw new IllegalArgumentException(String.format("No mapping for %02x", code)); }

Target:
public static Win32VK fromValue(final int code) { for (Win32VK vk : Win32VK.values()) { if (vk.code == code) { return vk; } } throw new IllegalArgumentException(String.format("No mapping for %02x", code)); }
Source:
private void print() { if (canceled) { out.print("[CANCELED] "); } else if (total == IProgressMonitor.UNKNOWN) { out.print(animationFrames[animationFrameId]); animationFrame = (animationFrame + 1) % animationFrames.length; } else { out.printf("[%2d%%] ", worked / total); } out.print(task); if (subTask != null) { out.printf(" - %s", subTask); } out.print('\r'); }

Target:
private void print() { if (canceled) { out.print("[CANCELED] "); } else if (total == IProgressMonitor.UNKNOWN) { out.print(animationFrames[animationFrameId]); animationFrameId = (animationFrameId + 1) % animationFrames.length; } else { out.printf("[%2d%%] ", worked / total); } out.print(task); if (subTask != null) { out.printf(" - %s", subTask); } out.print('\r'); }
Source:
public URI createAdminUnit(URI path, Model model) { // Add types to the object being created model = populateModelTypes(path, model, Arrays.asList(Cdr.AdminUnit, PcdmModels.Object)); return createContentContainerObject(path, model); }

Target:
public URI createAdminUnit(URI path, Model model) { // Add types to the object being created model = populateModelTypes(path, model, Arrays.asList(Cdr.AdminUnit, PcdmModels.Collection)); return createContentContainerObject(path, model); }
Source:
public void setUp() throws Exception { User.disableStorage(); // don't change the app login from this test }

Target:
public void setUp() { User.disableStorage(); // don't change the app login from this test }
Source:
private boolean isEmailValid(String email) { EmailValidator emailValidator = EmailValidator.getInstance(); return emailValidator.isValid(email); }

Target:
private boolean isEmailValid(String email) { return EmailValidator.getInstance().isValid(email); }
Source:
public void evict(WrappedBytes key) { Lock lock = locks.getLock(key).writeLock(); lock.lock(); try { checkDeallocation(); long address = memoryLookup.getMemoryAddress(key); if (address != 0) { // TODO: this could be more efficient InternalCacheEntry<WrappedBytes, WrappedBytes> ice = performGet(address, key); passivator.passivate(ice); performRemove(address, key); } } finally { lock.unlock(); } }

Target:
public void evict(WrappedBytes key) { Lock lock = locks.getLock(key).writeLock(); lock.lock(); try { checkDeallocation(); long address = memoryLookup.getMemoryAddress(key); if (address != 0) { // TODO: this could be more efficient InternalCacheEntry<WrappedBytes, WrappedBytes> ice = performGet(address, key); if (ice != null) { passivator.passivate(ice); performRemove(address, key); } } } finally { lock.unlock(); } }
Source:
public Map<String, Object> getMetadata() { return this.metadata; }

Target:
public Map<String, String> getMetadata() { return this.metadata; }
Source:
protected Node[] createNodes(AbstractFile t) { Node[] node = new Node[1]; if(t.isDir()){ //TODO log an error ??? return node; } else { //replace FileNode with our own subclass of its base type or similar node[0] = new DataResultFilterNode(new FileNode(t, false), DirectoryTreeTopComponent.findInstance().getExplorerManager()); return node; } }

Target:
protected Node[] createNodes(AbstractFile t) { Node[] node = new Node[1]; //TODO replace FileNode with our own subclass of its base type or similar node[0] = new DataResultFilterNode(new FileNode(t, false), DirectoryTreeTopComponent.findInstance().getExplorerManager()); return node; }
Source:
private boolean isBrokerWithPRTSupport(final Intent intent) { if (intent == null) { throw new IllegalArgumentException("intent"); } // Only new broker with PRT support will send down the value and the version will be v2 final String brokerVersion = intent.getStringExtra(AuthenticationConstants.Broker.BROKER_VERSION); if (!StringExtensions.IsNullOrBlank(brokerVersion) && AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion)) { return true; } return false; }

Target:
private boolean isBrokerWithPRTSupport(final Intent intent) { if (intent == null) { throw new IllegalArgumentException("intent"); } // Only new broker with PRT support will send down the value and the version will be v2 final String brokerVersion = intent.getStringExtra(AuthenticationConstants.Broker.BROKER_VERSION); return AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion); }
Source:
private PyUDFExpression() { name = ""; //set default return type this is changed once pythonfunction is retrived. outputType = Type.BLOB_TYPE; }

Target:
private PyUDFExpression()
Source:
protected String createRecordName(String objectType) { StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb, Locale.US); formatter.format("ManagerTest_%s_%08d", objectType, System.currentTimeMillis()); return sb.toString(); }

Target:
protected String createRecordName(String objectType) { return String.format(Locale.US, "ManagerTest_%s_%08d", objectType, System.currentTimeMillis()); }
Source:
public Stock(String symbol, String name, double price) { super(); this.symbol = symbol; this.name = name; this.price = price; }

Target:
public Stock(String symbol, String name, double price) { //super(); this.symbol = symbol; this.name = name; this.price = price; }
Source:
Pair<IAnnotationModel, List<ContributionAnnotation>> addNewEntry( final List<ContributionAnnotation> annotations) { if (queue.size() > maxHistoryLength) { throw new IllegalStateException( "The queue already contains the allowed number of annotations."); } Pair<IAnnotationModel, List<ContributionAnnotation>> removedEntry = removeEntryIfFull(); queue.add(annotations); return removedEntry; }

Target:
Pair<IAnnotationModel, List<ContributionAnnotation>> addNewEntry( final List<ContributionAnnotation> annotations) { Pair<IAnnotationModel, List<ContributionAnnotation>> removedEntry = removeEntryIfFull(); queue.add(annotations); return removedEntry; }
Source:
public ObjectListingChunk getNextChunk() throws IOException { if (mResult.isTruncated()) { String nextMarker = mResult.getNextMarker(); mRequest.setMarker(nextMarker); ObjectListing nextResult = mClient.listObjects(mRequest); if (nextResult != null) { return new OSSObjectListingChunk(mRequest, nextResult); } } return null; }

Target:
public ObjectListingChunk getNextChunk() throws IOException { if (mResult.isTruncated()) { mRequest.setMarker(mResult.getNextMarker()); ObjectListing nextResult = mClient.listObjects(mRequest); if (nextResult != null) { return new OSSObjectListingChunk(mRequest, nextResult); } } return null; }
Source:
private void update() { // OK to ignore calls to update() if already busy updating if (busy.compareAndSet(false, true)) { try { PollingResponse response = reader.call(); if (response.hasData()) { current = response.getToAdd(); notifyConfigUpdated(this); } } catch (Exception e) { try { notifyError(e, this); } catch (Exception e2) { LOG.warn("Failed to notify error observer"); } } finally { busy.set(false); } } }

Target:
private void update() { // OK to ignore calls to update() if already busy updating if (busy.compareAndSet(false, true)) { try { PollingResponse response = reader.call(); if (response.hasData()) { current = response.getToAdd(); notifyConfigUpdated(this); } } catch (Exception e) { try { notifyError(e, this); } catch (Exception e2) { LOG.warn("Failed to notify error observer", e2); } } finally { busy.set(false); } } }
Source:
public ConnectorHandle(ConnectorLocator locator, Class<? extends StoragePluginConfig> configClass) { this.locator = locator; this.configClass = configClass; this.isIntrinsic = false; }

Target:
private ConnectorHandle(ConnectorLocator locator, Class<? extends StoragePluginConfig> configClass) { this.locator = locator; this.configClass = configClass; this.isIntrinsic = false; }
Source:
public Subscriber<Observable<? extends T>> call(final Subscriber<? super T> child) { MergeSubscriber<T> subscriber = new MergeSubscriber<T>(child, delayErrors, maxConcurrent); MergeProducer<T> producer = new MergeProducer<T>(subscriber); subscriber.producer = producer; producer.lazySet(0); // make sure subscriber.producer is visible child.add(subscriber); child.setProducer(producer); return subscriber; }

Target:
public Subscriber<Observable<? extends T>> call(final Subscriber<? super T> child) { MergeSubscriber<T> subscriber = new MergeSubscriber<T>(child, delayErrors, maxConcurrent); MergeProducer<T> producer = new MergeProducer<T>(subscriber); subscriber.producer = producer; child.add(subscriber); child.setProducer(producer); return subscriber; }
Source:
public String me() { return "" + state + ME_SEPARATOR; }

Target:
public String me() { return state + ME_SEPARATOR; }
Source:
public int findWikiIndex(String wikiCode) { int index = ArrayUtils.indexOf(getWikiCodes(), wikiCode); if (index == ArrayUtils.INDEX_NOT_FOUND) { // FIXME: Instrument this with EL to find out what is happening on places where there is a lang we can't find // In the meantime, just fall back to en. See https://bugzilla.wikimedia.org/show_bug.cgi?id=66140 return findWikiIndex(FALLBACK_WIKI_LANG_CODE); } return index; }

Target:
public int findWikiIndex(String wikiCode) { int index = getWikiCodes().indexOf(wikiCode); if (index == -1) { // FIXME: Instrument this with EL to find out what is happening on places where there is a lang we can't find // In the meantime, just fall back to en. See https://bugzilla.wikimedia.org/show_bug.cgi?id=66140 return findWikiIndex(FALLBACK_WIKI_LANG_CODE); } return index; }
Source:
public void init() { try { eventBus.registerSubscriber(this); // Must set the initial status currentStatus.compareAndSet(InstanceInfo.InstanceStatus.UNKNOWN, client.getInstanceRemoteStatus()); } catch (InvalidSubscriberException e) { LOG.error("Error registring for discovery status change events.", e); } }

Target:
public void init() { try { eventBus.registerSubscriber(this); // Must set the initial status currentStatus = client.getInstanceRemoteStatus(); } catch (InvalidSubscriberException e) { LOG.error("Error registring for discovery status change events.", e); } }
Source:
public static void insertPageProlog(StringBuilder buffer, int position) { StringBuilder pageProlog= new StringBuilder(60); pageProlog.append("<html>"); //$NON-NLS-1$ buffer.append("<head>"); //$NON-NLS-1$ appendStyleSheetWithBodyColorRules(pageProlog, FG_COLOR_RGB, BG_COLOR_RGB); buffer.append("</head>"); //$NON-NLS-1$ buffer.insert(position, pageProlog.toString()); }

Target:
public static void insertPageProlog(StringBuilder buffer, int position) { StringBuilder pageProlog= new StringBuilder(60); pageProlog.append("<html>"); //$NON-NLS-1$ pageProlog.append("<head>"); //$NON-NLS-1$ appendStyleSheetWithBodyColorRules(pageProlog, FG_COLOR_RGB, BG_COLOR_RGB); pageProlog.append("</head>"); //$NON-NLS-1$ buffer.insert(position, pageProlog.toString()); }
Source:
private void verifyCertificateChain(final List<X509Certificate> certificates) throws GeneralSecurityException, AuthenticationException { // create certificate chain, find the self signed cert first and chain all the way back // to the signer cert. Also perform certificate signing validation when chaining them back. X509Certificate issuerCert = getSelfSignedCert(certificates); final TrustAnchor trustAnchor = new TrustAnchor(issuerCert, null); PKIXParameters pkixParameters = new PKIXParameters(Collections.singleton(trustAnchor)); pkixParameters.setRevocationEnabled(false); final CertPath certPath = CertificateFactory.getInstance("X.509") .generateCertPath(certificates); final CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX"); certPathValidator.validate(certPath, pkixParameters); }

Target:
private void verifyCertificateChain(final List<X509Certificate> certificates) throws GeneralSecurityException, AuthenticationException { // create certificate chain, find the self signed cert first and chain all the way back // to the signer cert. Also perform certificate signing validation when chaining them back. final X509Certificate issuerCert = getSelfSignedCert(certificates); final TrustAnchor trustAnchor = new TrustAnchor(issuerCert, null); final PKIXParameters pkixParameters = new PKIXParameters(Collections.singleton(trustAnchor)); pkixParameters.setRevocationEnabled(false); final CertPath certPath = CertificateFactory.getInstance("X.509") .generateCertPath(certificates); final CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX"); certPathValidator.validate(certPath, pkixParameters); }
Source:
public Set<Class<?>> getClasses() { final Set<Class<?>> classes = new HashSet<>(); classes.add(HelloResource.class); classes.add(PureProxyEndPoint.class); classes.add(HelloBadResource.class); classes.add(HelloSometimesBadResource.class); return classes; }

Target:
public Set<Class<?>> getClasses() { final Set<Class<?>> classes = new HashSet<>(); classes.add(HelloResource.class); classes.add(PureProxyEndPoint.class); return classes; }
Source:
protected String gtk_rgba_to_css_string (GdkRGBA rgba) { String color = "rgba(" + (int)(rgba.red * 255) + "," + (int)(rgba.green * 255) + "," + (int)(rgba.blue * 255) + "," + (int)(rgba.alpha * 255) + ")"; return color; }

Target:
String gtk_rgba_to_css_string (GdkRGBA rgba) { /* * In GdkRGBA, values are a double between 0-1.<br> * In CSS, values are typically integers between 0-255.<br> * I.e, note, there is a slight loss of precision. * Thus setting/getting color *might* return slight differences. */ String color = "rgba(" + (int)(rgba.red * 255) + "," + (int)(rgba.green * 255) + "," + (int)(rgba.blue * 255) + "," + (int)(rgba.alpha * 255) + ")"; return color; }
Source:
private void sendCancelCommand(IntSet cancelledSegments) { Address origin = rpcManager.getAddress(); CacheRpcCommand cmd = commandsFactory.buildStateTransferCancelCommand(topologyId, cancelledSegments); try { rpcManager.sendTo(source, cmd, DeliverOrder.NONE); } catch (Exception e) { // Ignore exceptions here, the worst that can happen is that the provider will send some extra state log.debugf("Caught an exception while cancelling state transfer from node %s for segments %s", source, cancelledSegments); } }

Target:
private void sendCancelCommand(IntSet cancelledSegments) { CacheRpcCommand cmd = commandsFactory.buildStateTransferCancelCommand(topologyId, cancelledSegments); try { rpcManager.sendTo(source, cmd, DeliverOrder.NONE); } catch (Exception e) { // Ignore exceptions here, the worst that can happen is that the provider will send some extra state log.debugf("Caught an exception while cancelling state transfer from node %s for segments %s", source, cancelledSegments); } }
Source:
public void heartbeat() { // Sync the pin list before attempting to reserve space mBlockWorker.syncPinList(); reserveSpace(); }

Target:
public void heartbeat() { reserveSpace(); }
Source:
private final void decrementResponseOrExpired() { int decrementedValue = responsesAndExpirations.decrementAndGet(); if (decrementedValue == 0) { // The condition being signaled is a valid proxy for the CL being achieved // Only mark it as failed if the requested CL was achieved. if (!condition.isSignaled() & requestedCLAchieved) { replicaPlan.keyspace().metric.writeFailedIdealCL.inc(); } else { replicaPlan.keyspace().metric.idealCLWriteLatency.addNano(System.nanoTime() - queryStartNanoTime); } } }

Target:
private final void decrementResponseOrExpired() { int decrementedValue = responsesAndExpirations.decrementAndGet(); if (decrementedValue == 0) { // The condition being signaled is a valid proxy for the CL being achieved // Only mark it as failed if the requested CL was achieved. if (!condition.isSignaled() && requestedCLAchieved) { replicaPlan.keyspace().metric.writeFailedIdealCL.inc(); } else { replicaPlan.keyspace().metric.idealCLWriteLatency.addNano(System.nanoTime() - queryStartNanoTime); } } }
Source:
private IssuesRecorder enableWarningsForNewFixedOutstandingTest(final FreeStyleProject job, IssuesRecorder oldPublisher, String pattern) { if(oldPublisher != null) { job.getPublishersList().remove(oldPublisher); } IssuesRecorder publisher = new IssuesRecorder(); publisher.setTools(Collections.singletonList(new ToolConfiguration(pattern, new Eclipse()))); job.getPublishersList().add(publisher); return publisher; }

Target:
private IssuesRecorder enableWarningsForNewFixedOutstandingTest(final FreeStyleProject job, IssuesRecorder oldPublisher, String pattern) { if(oldPublisher != null) { job.getPublishersList().remove(oldPublisher); } return enableWarningsForNewFixedOutstandingTest(job, pattern); }
Source:
static private long toMillis(String seconds) { if (seconds.contains(".")) { float value = Float.parseFloat(seconds); float millis = value % 1; return SECONDS.toMillis((long) value) + (long) (millis * 1000); } else { return SECONDS.toMillis(Long.parseLong(seconds)); } }

Target:
private static long toMillis(String seconds) { if (seconds.contains(".")) { float value = Float.parseFloat(seconds); float millis = value % 1; return SECONDS.toMillis((long) value) + (long) (millis * 1000); } else { return SECONDS.toMillis(Long.parseLong(seconds)); } }
Source:
static boolean checkStartObject(JsonParser parser, boolean shouldThrow) throws IOException { try { JsonToken currentToken = parser.currentToken(); // The parser may not be at a token, yet. If that's the case advance. if (currentToken == null) currentToken = parser.nextToken(); // If we are still not at the expected token, we could be an another or an empty body. if (currentToken == JsonToken.START_OBJECT) return true; if (shouldThrow) { throw new IllegalArgumentException("Expected start object, was " + currentToken); } return false; } catch (JsonParseException e) { // likely not json if (shouldThrow) throw e; return false; } }

Target:
static boolean checkStartObject(JsonParser parser, boolean shouldThrow) throws IOException { try { JsonToken currentToken = parser.currentToken(); // The parser may not be at a token, yet. If that's the case advance. if (currentToken == null) currentToken = parser.nextToken(); // If we are still not at the expected token, we could be an another or an empty body. if (currentToken == JsonToken.START_OBJECT) return true; if (shouldThrow) { throw new IllegalArgumentException("Expected start object, was " + currentToken); } return false; } catch (Throwable e) { // likely not json if (shouldThrow) throw e; return false; } }
Source:
private String getLsRegisterOutput() throws Exception { if (lsRegisterOutput != null) { return lsRegisterOutput; } long beforeCallLsRegister = System.currentTimeMillis(); lsRegisterOutput = processExecutor.execute(LSREGISTER, DUMP); long afterCallLsRegister = System.currentTimeMillis(); System.out.println("Call to lsregister took :" + (afterCallLsRegister - beforeCallLsRegister)); //$NON-NLS-1$ return lsRegisterOutput; }

Target:
private String getLsRegisterOutput() throws Exception { if (this.lsRegisterOutput != null) { return this.lsRegisterOutput; } this.lsRegisterOutput = processExecutor.execute(LSREGISTER, DUMP); return this.lsRegisterOutput; }
Source:
public static String masterInbox(Map conf) throws IOException { String ret = masterLocalDir(conf) + FILE_SEPARATOR + "inbox"; try { FileUtils.forceMkdir(new File(ret)); } catch (IOException e) { LOG.error("Failed to create dir " + ret, e); throw e; } return ret; }

Target:
public static String masterInbox(Map conf) throws IOException { String ret = masterLocalDir(conf) + FILE_SEPARATOR + "inbox"; FileUtils.forceMkdir(new File(ret)); return ret; }
Source:
public static void main(String[] args) { LOG.info("Validating configuration."); try { Configuration.validate(); LOG.info("Configuration is valid."); } catch (IllegalStateException e) { LOG.warn("Configuration is invalid: {}", e.getMessage()); System.exit(-1); } System.exit(0); }

Target:
public static void main(String[] args) { LOG.info("Validating configuration."); try { Configuration.validate(); LOG.info("Configuration is valid."); } catch (IllegalStateException e) { LOG.error("Configuration is invalid: {}", e.getMessage()); System.exit(-1); } System.exit(0); }
Source:
public void should_return_null_when_encountering_parsing_issue() { logTester.setLevel(LoggerLevel.DEBUG); assertThat(XmlParser.parseXML(new File("src/test/files/xml/parsing-issue.xml"))).isNull(); assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Unable to parse xml file: src/test/files/xml/parsing-issue.xml"); System.out.println(logTester.logs(LoggerLevel.DEBUG)); assertThat(logTester.logs(LoggerLevel.DEBUG)).hasSize(1).allSatisfy(s -> s.startsWith("XML file parsing failed because of : org.xml.sax.SAXParseException; systemId: file: ")); }

Target:
public void should_return_null_when_encountering_parsing_issue() { logTester.setLevel(LoggerLevel.DEBUG); assertThat(XmlParser.parseXML(new File("src/test/files/xml/parsing-issue.xml"))).isNull(); assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Unable to parse xml file: src/test/files/xml/parsing-issue.xml"); assertThat(logTester.logs(LoggerLevel.DEBUG)).hasSize(1).allSatisfy(s -> s.startsWith("XML file parsing failed because of : org.xml.sax.SAXParseException; systemId: file: ")); }
Source:
public void followPeergos() throws Exception { UserContext u1 = PeergosNetworkUtils.ensureSignedUp("peergos", "testpassword", network, crypto); UserContext u2 = PeergosNetworkUtils.ensureSignedUp("w", "w", network, crypto); u2.sendFollowRequest(u1.username, SymmetricKey.random()).get(); List<FollowRequestWithCipherText> u1Requests = u1.processFollowRequests().get(); assertTrue("Receive a follow request", u1Requests.size() > 0); }

Target:
public void followPeergos() throws Exception { UserContext u1 = PeergosNetworkUtils.ensureSignedUp("peergos", "testpassword", network, crypto); UserContext u2 = PeergosNetworkUtils.ensureSignedUp("w", "w", network, crypto); List<FollowRequestWithCipherText> u1Requests = u1.processFollowRequests().get(); assertTrue("Receive a follow request", u1Requests.size() > 0); }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { requireNonNull(contextThreadLocalSupplier, "httpClientContextSupplier should not be null"); try { contextThreadLocalSupplier.addContext(getRequestHeadersMap(request), getQueryParamsMap(request)); chain.doFilter(request, response); } catch (IllegalArgumentException e) { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST); } finally { contextThreadLocalSupplier.clear(); } }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { requireNonNull(contextThreadLocalSupplier, "httpClientContextSupplier should not be null"); try { try { contextThreadLocalSupplier.addContext(getRequestHeadersMap(request), getQueryParamsMap(request)); } catch (IllegalArgumentException e) { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST); return; } chain.doFilter(request, response); } finally { contextThreadLocalSupplier.clear(); } }
Source:
public CtPath getPath() { try { return new CtElementPathBuilder().fromElement(this, getParent(CtModelImpl.CtRootPackage.class)); } catch (CtPathException e) { throw new SpoonException(); } }

Target:
public CtPath getPath() { try { return new CtElementPathBuilder().fromElement(this, getParent(CtModelImpl.CtRootPackage.class)); } catch (CtPathException e) { throw new SpoonException(e); } }
Source:
public WorkQueue.Executor getBatchQueue() { System.out.println("Job scheduled in batch Queue"); return batchExecutor; }

Target:
public WorkQueue.Executor getBatchQueue() { return batchExecutor; }
Source:
public void itDoesntWritePassword() throws Exception { // When I call JSON for user1 JsonNode node = getResponseAsJson(RequestType.GET, "/user/user1"); // Then it doesn't contain the password at all assertNull("", node.get("properties").get("password")); }

Target:
public void itDoesntWritePassword() throws Exception { // When I call JSON for user1 JsonNode node = getResponseAsJson(RequestType.GET, "/user/user1"); // Then it doesn't contain the password at all assertNull(node.get("properties").get("password")); }
Source:
private void checkSigOps() throws VerificationException { // Check there aren't too many signature verifications in the block. This is an anti-DoS measure, see the // comments for MAX_BLOCK_SIGOPS. int sigOps = 0; for (Transaction tx : transactions) { sigOps += tx.getSigOpCount(); } if (sigOps > MAX_BLOCK_SIGOPS) { throw new VerificationException("Block had too many Signature Operations"); } }

Target:
private void checkSigOps() throws VerificationException { // Check there aren't too many signature verifications in the block. This is an anti-DoS measure, see the // comments for MAX_BLOCK_SIGOPS. int sigOps = 0; for (Transaction tx : transactions) { sigOps += tx.getSigOpCount(); } if (sigOps > MAX_BLOCK_SIGOPS) throw new VerificationException("Block had too many Signature Operations"); }
Source:
public void createPartControl(Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { name = TmfViewFactory.getBaseSecId(name); } if (name != null) { /* must initialize view info before calling super */ fViewInfo.setName(name); } fPresentationProvider = new XmlPresentationProvider(name); TimeGraphViewer timeGraphViewer = getTimeGraphViewer(); timeGraphViewer.getTimeGraphControl().colorSettingsChanged(timeGraphViewer.getTimeGraphProvider().getStateTable()); super.createPartControl(parent); }

Target:
public void createPartControl(Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { name = TmfViewFactory.getBaseSecId(name); } if (name != null) { /* must initialize view info before calling super */ fViewInfo.setName(name); } fPresentationProvider = new XmlPresentationProvider(name); super.createPartControl(parent); TimeGraphViewer timeGraphViewer = getTimeGraphViewer(); timeGraphViewer.getTimeGraphControl().colorSettingsChanged(timeGraphViewer.getTimeGraphProvider().getStateTable()); }
Source:
public void retireIdentifierSource_shouldRetireAnIdentifierSourceFromTheSystem() throws Exception { IdentifierSource identifierSource = identifierSourceService.getIdentifierSource(1); Assert.assertFalse(identifierSourceService.getIdentifierSource(1).isRetired()); identifierSourceService.retireIdentifierSource(identifierSource, "testing"); Assert.assertTrue(identifierSourceService.getIdentifierSource(1).isRetired()); }

Target:
public void retireIdentifierSource_shouldRetireAnIdentifierSourceFromTheSystem() throws Exception { IdentifierSource identifierSource = identifierSourceService.getIdentifierSource(2); Assert.assertFalse(identifierSourceService.getIdentifierSource(2).isRetired()); identifierSourceService.retireIdentifierSource(identifierSource, "testing"); Assert.assertTrue(identifierSourceService.getIdentifierSource(2).isRetired()); }
Source:
private Expression simplifyExpression(Session session, Expression predicate, TypeProvider types) { Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, predicate, types); ExpressionInterpreter interpreter = ExpressionInterpreter.expressionOptimizer(predicate, metadata, session, expressionTypes); Object value = interpreter.optimize(NoOpSymbolResolver.INSTANCE); if (value instanceof Expression) { return (Expression) value; } if (value == null) { // expression evaluates to SQL null, which in Filter is equivalent to false value = false; } return literalEncoder.toExpression(value, BOOLEAN); }

Target:
private Expression simplifyExpression(Session session, Expression predicate, TypeProvider types) { // TODO reuse com.facebook.presto.sql.planner.iterative.rule.SimplifyExpressions.rewrite Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, predicate, types); ExpressionInterpreter interpreter = ExpressionInterpreter.expressionOptimizer(predicate, metadata, session, expressionTypes); Object value = interpreter.optimize(NoOpSymbolResolver.INSTANCE); if (value == null) { // Expression evaluates to SQL null, which in Filter is equivalent to false. This assumes the expression is a top-level expression (eg. not in NOT). value = false; } return literalEncoder.toExpression(value, BOOLEAN); }
Source:
public void testTypeAccessInLambdaNoClassPath() { final Launcher runLaunch = new Launcher(); runLaunch.getEnvironment().setNoClasspath(true); runLaunch.addInputResource("./src/test/resources/noclasspath/lambdas/TypeAccessInLambda.java"); runLaunch.buildModel(); assertEquals("The token 'Strings' has not been parsed as CtTypeAccess", runLaunch.getModel().getElements(new Filter<CtTypeAccess>() { @Override public boolean matches(final CtTypeAccess element) { return element.getAccessedType().getSimpleName().equals("Strings"); } }).size(), 1); }

Target:
public void testTypeAccessInLambdaNoClassPath() { final Launcher runLaunch = new Launcher(); runLaunch.getEnvironment().setNoClasspath(true); runLaunch.addInputResource("./src/test/resources/noclasspath/lambdas/TypeAccessInLambda.java"); runLaunch.buildModel(); assertEquals("The token 'Strings' has not been parsed as CtTypeAccess", 1, runLaunch.getModel().getElements(new Filter<CtTypeAccess>() { @Override public boolean matches(final CtTypeAccess element) { return element.getAccessedType().getSimpleName().equals("Strings"); } }).size()); }
Source:
public RecipientListRouter rlRouter() { RecipientListRouter router = new RecipientListRouter(); router.setChannels(Arrays.asList(new MessageChannel[] { barChannel(), bazChannel() })); router.setDefaultOutputChannel(discards()); return router; }

Target:
public RecipientListRouter rlRouter() { RecipientListRouter router = new RecipientListRouter(); router.setChannels(Arrays.asList(barChannel(), bazChannel())); router.setDefaultOutputChannel(discards()); return router; }
Source:
public String getFile(@PathVariable("id") final String id, final HttpServletRequest request) { String encodedId; try { // When forwarding, the downstream ApplicationContext will perform URL decoding. // If the job ID contains special characters (such as '+'), they will be interpreted as url-encoded and // decoded, resulting in an invalid job ID that cannot be found. // To prevent this, always perform URL encoding on the ID before forwarding. encodedId = URLEncoder.encode(id, "UTF-8"); } catch (UnsupportedEncodingException e) { log.warn("Failed to encode id: {}", id, e); encodedId = id; } final String path = "/api/v3/jobs/" + encodedId + "/" + ControllerUtils.getRemainingPath(request); return "forward:" + path; }

Target:
public String getFile( @PathVariable("id") final String id, final HttpServletRequest request ) throws UnsupportedEncodingException { // When forwarding, the downstream ApplicationContext will perform URL decoding. // If the job ID contains special characters (such as '+'), they will be interpreted as url-encoded and // decoded, resulting in an invalid job ID that cannot be found. // To prevent this, always perform URL encoding on the ID before forwarding. final String encodedId = URLEncoder.encode(id, "UTF-8"); final String path = "/api/v3/jobs/" + encodedId + "/" + ControllerUtils.getRemainingPath(request); return "forward:" + path; }
Source:
private void logFailureResponseObject(MockHttpException httpEx, String url, long callDelay) { LogLevel logLevel = restAdapter.logLevel; RestAdapter.Log log = restAdapter.log; if (logLevel.log()) { log.log(String.format("<--- MOCK %s %s (%sms)", httpEx.code, url, callDelay)); if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) { log.log(httpEx.responseBody + ""); // Hack to convert toString while supporting null. log.log("<--- END MOCK"); } } }

Target:
private void logFailureResponseObject(MockHttpException httpEx, String url, long callDelay) { LogLevel logLevel = restAdapter.logLevel; RestAdapter.Log log = restAdapter.log; if (logLevel.log()) { log.log(String.format("<--- MOCK %s %s (%sms)", httpEx.code, url, callDelay)); if (logLevel.ordinal() >= LogLevel.FULL.ordinal()) { log.log(String.valueOf(httpEx.responseBody)); log.log("<--- END MOCK"); } } }
Source:
private void lookupCoordinatorAndRetry(TransactionManager.TxnRequestHandler nextRequestHandler) { if (!nextRequestHandler.needsCoordinator()) { // For non-coordinator requests, sleep here to prevent a tight loop when no node is available time.sleep(retryBackoffMs); metadata.requestUpdate(); } transactionManager.lookupCoordinator(nextRequestHandler); transactionManager.retry(nextRequestHandler); }

Target:
private void lookupCoordinatorAndRetry(TransactionManager.TxnRequestHandler nextRequestHandler) { if (nextRequestHandler.needsCoordinator()) { transactionManager.lookupCoordinator(nextRequestHandler); } else { // For non-coordinator requests, sleep here to prevent a tight loop when no node is available time.sleep(retryBackoffMs); metadata.requestUpdate(); } transactionManager.retry(nextRequestHandler); }
Source:
public void setAcl(FileSystem hdfs, String path, AccessControlList acl) throws IOException { // convert AccessControlList into hdfsAcl List<AclEntry> aclSpecs = new ArrayList<>(); for (alluxio.security.authorization.AclEntry entry : acl.getEntries()) { AclEntry hdfsAclEntry = getHdfsAclEntry(entry); aclSpecs.add(hdfsAclEntry); } // set hdfsAcl; try { hdfs.setAcl(new Path(path), aclSpecs); } catch (UnsupportedOperationException e) { LOG.warn("Setting ACL on HDFS with acl disabled"); } }

Target:
public void setAcl(FileSystem hdfs, String path, AccessControlList acl) throws IOException { // convert AccessControlList into hdfsAcl List<AclEntry> aclSpecs = new ArrayList<>(); for (alluxio.security.authorization.AclEntry entry : acl.getEntries()) { AclEntry hdfsAclEntry = getHdfsAclEntry(entry); aclSpecs.add(hdfsAclEntry); } // set hdfsAcl; try { hdfs.setAcl(new Path(path), aclSpecs); } catch (UnsupportedOperationException e) { // noop if hdfs does not support acl } }
Source:
private int nextCorrelationId() { if (SaslClientAuthenticator.isReserved(correlation)) correlation = SaslClientAuthenticator.MAX_RESERVED_CORRELATION_ID + 1; return correlation++; }

Target:
int nextCorrelationId() { if (SaslClientAuthenticator.isReserved(correlation)) { // the numeric overflow is fine as negative values is acceptable correlation = SaslClientAuthenticator.MAX_RESERVED_CORRELATION_ID + 1; } return correlation++; }
Source:
public void teardownTest() throws InterruptedException { //give time for operations to finish firewallPolicyApi().delete(currentFirewallPolicy.id()); Thread.sleep(15000); assertNodeAvailable(currentServer); deleteServer(currentServer.id()); }

Target:
public void teardownTest() throws InterruptedException { assertNodeAvailable(currentServer); firewallPolicyApi().delete(currentFirewallPolicy.id()); assertNodeAvailable(currentServer); deleteServer(currentServer.id()); }
Source:
public boolean onPrepareOptionsMenu(Menu menu) { LibraryAdapter adapter = mCurrentAdapter; boolean isLibraryAdapter = (adapter != null && adapter.getMediaType() != MediaUtils.TYPE_FILE); menu.findItem(MENU_GO_HOME).setVisible(!isLibraryAdapter); menu.findItem(MENU_SORT).setEnabled(adapter != null); return super.onPrepareOptionsMenu(menu); }

Target:
public boolean onPrepareOptionsMenu(Menu menu) { LibraryAdapter adapter = mCurrentAdapter; menu.findItem(MENU_GO_HOME).setVisible( adapter != null && adapter.getMediaType() == MediaUtils.TYPE_FILE); menu.findItem(MENU_SORT).setEnabled(adapter != null); return super.onPrepareOptionsMenu(menu); }
Source:
private void init() { // Creating ObjectChecker must be deferred. Unit tests change // behavior of is{Windows,MacOS} in constructor of subclass. if (platformChecker == null) { setPlatformChecker(); } }

Target:
private void init() { // Creating ObjectChecker must be deferred. Unit tests change // behavior of is{Windows,MacOS} in constructor of subclass. if (platformChecker == null) setPlatformChecker(); }
Source:
private static II getLivingSubjectId(PRPAMT201306UV02LivingSubjectId id) { II oII = null; if (id != null && id.getValue() != null && id.getValue().size() > 0) { oII = id.getValue().get(0); } return oII; }

Target:
private static II getLivingSubjectId(PRPAMT201306UV02LivingSubjectId id) { II oII = null; if (id != null && id.getValue() != null && !id.getValue().isEmpty()) { oII = id.getValue().get(0); } return oII; }