auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void preInit(FMLPreInitializationEvent evt) { RegistryHelper.useOtherModConfigFor(MODID, BCCore.MODID); BCSiliconConfig.preInit(); BCSiliconItems.preInit(); BCSiliconBlocks.preInit(); // Reload after all of the definitions have been created. BCSiliconConfig.reloadConfig(EnumRestartRequirement.GAME); NetworkRegistry.INSTANCE.registerGuiHandler(INSTANCE, BCSiliconProxy.getProxy()); BCSiliconProxy.getProxy().fmlPreInit(); }

Target:
public void preInit(FMLPreInitializationEvent evt) { RegistryHelper.useOtherModConfigFor(MODID, BCCore.MODID); BCSiliconConfig.preInit(); BCSiliconItems.preInit(); BCSiliconBlocks.preInit(); NetworkRegistry.INSTANCE.registerGuiHandler(INSTANCE, BCSiliconProxy.getProxy()); BCSiliconProxy.getProxy().fmlPreInit(); }
Source:
protected void buildVmVideoCards() { createInfo.add(VdsProperties.display, vm.getdisplay_type().toString()); // vnc,qxl createInfo.add(VdsProperties.num_of_monitors, (new Integer(vm.getnum_of_monitors())).toString()); }

Target:
protected void buildVmVideoCards() { createInfo.add(VdsProperties.display, vm.getdisplay_type().toString()); // vnc,qxl createInfo.add(VdsProperties.num_of_monitors, String.valueOf(vm.getnum_of_monitors())); }
Source:
public void testWrongPortConnection() throws Exception { BlockingChannel channel = new SSLBlockingChannel(hostName, sslPort + 1, new MetricRegistry(), 10000, 10000, 10000, 2000, sslSocketFactory, clientSSLConfig); try { // send request channel.connect(); fail("should have thrown!"); } catch (IOException e) { assertTrue(e.getMessage().contains("Connection refused")); } }

Target:
public void testWrongPortConnection() throws Exception { BlockingChannel channel = new SSLBlockingChannel(hostName, sslPort + 1, new MetricRegistry(), 10000, 10000, 10000, 2000, sslSocketFactory, clientSSLConfig); try { // send request channel.connect(); fail("should have thrown!"); } catch (IOException e) { } }
Source:
public void closeTest() { // request is keep-alive by default. HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.Close.toString()); EmbeddedChannel channel = createEmbeddedChannel(); channel.writeInbound(request); // drain the channel of content. while (channel.readOutbound() != null) { ; } assertFalse("Channel should be closed", channel.isOpen()); }

Target:
public void closeTest() { // request is keep-alive by default. HttpRequest request = createRequestWithHeaders(HttpMethod.GET, TestingUri.Close.toString()); EmbeddedChannel channel = createEmbeddedChannel(); channel.writeInbound(request); // drain the channel of content. while (channel.readOutbound() != null) { } assertFalse("Channel should be closed", channel.isOpen()); }
Source:
public void info(String message) { System.out.println(message); info.add(message); }

Target:
public void info(String message) { info.add(message); }
Source:
public boolean equals( VirtualValue other ) { if ( other == null || !(other instanceof MapValue) ) { return false; } MapValue that = (MapValue) other; return size() == that.size() && Arrays.equals( keys, that.keys ) && Arrays.equals( values, that.values ); }

Target:
public boolean equals( VirtualValue other ) { if ( other == null || other.getClass() != MapValue.class ) { return false; } MapValue that = (MapValue) other; return map.equals( that.map ); }
Source:
private void setFixedLengthStreamingMode(HttpURLConnection connection, long length) { try { // Not caching method as invocation is literally sending > 2GB, which means reflection isn't a limiter! HttpURLConnection.class.getMethod("setFixedLengthStreamingMode", long.class).invoke(connection, length); } catch (Exception e) { throw new IllegalArgumentException("Cannot transfer 2 GB or larger chunks due to JDK 1.6 limitations." + " Use chunked encoding or multi-part upload, if possible, or use a different http driver." + " For more information: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6755625"); } }

Target:
private static void setFixedLengthStreamingMode(HttpURLConnection connection, long length) { try { // Not caching method as invocation is literally sending > 2GB, which means reflection isn't a limiter! HttpURLConnection.class.getMethod("setFixedLengthStreamingMode", long.class).invoke(connection, length); } catch (Exception e) { throw new IllegalArgumentException("Cannot transfer 2 GB or larger chunks due to JDK 1.6 limitations." + " Use chunked encoding or multi-part upload, if possible, or use a different http driver." + " For more information: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6755625"); } }
Source:
String getErrorMessage(ClientResponse clientResponse) { String response = clientResponse.getEntity(String.class); try { // Try to see if the server responded with an error message from the API ApiError error = getJsonParser().readValue(response, ApiError.class); return error.getMessage(); } catch (IOException e) { // If not, inform the user of the underlying response (e.g. if server threw NPE or whatever) int statusCode = clientResponse.getStatus(); ClientResponse.Status status = clientResponse.getClientResponseStatus(); String responseText = clientResponse.getEntity(String.class); return "Server returned "+status+"("+statusCode+"); "+responseText; } }

Target:
protected String getErrorMessage(ClientResponse clientResponse) { String response = clientResponse.getEntity(String.class); try { // Try to see if the server responded with an error message from the API ApiError error = getJsonParser().readValue(response, ApiError.class); return error.getMessage(); } catch (IOException e) { // If not, inform the user of the underlying response (e.g. if server threw NPE or whatever) int statusCode = clientResponse.getStatus(); ClientResponse.Status status = clientResponse.getClientResponseStatus(); String responseText = clientResponse.getEntity(String.class); return "Server returned "+status+"("+statusCode+"); "+responseText; } }
Source:
public void onSaveClick() { editView.setSaveState(true); WikidataDescriptionEditDataClient client = new WikidataDescriptionEditDataClient(); client.submitDescription(pageTitle, editView.getDescription(), new WikidataDescriptionEditDataClient.Callback() { @Override public void success() { editView.setSaveState(false); L.i("WD description edit successful"); // TODO: go to success fragment } @Override public void failure(@NonNull Throwable caught) { editView.setSaveState(false); L.e("WD description edit failed: ", caught); // TODO: go to failure fragment } }); }

Target:
public void onSaveClick() { editView.setSaveState(true); if (client == null) { client = new WikidataDescriptionEditDataClient(); } client.request(pageTitle, editView.getDescription(), new WikidataDescriptionEditDataClient.Callback() { @Override public void success() { editView.setSaveState(false); L.i("WD description edit successful"); // TODO: go to success fragment } @Override public void failure(@NonNull Throwable caught) { editView.setSaveState(false); L.e("WD description edit failed: ", caught); // TODO: go to failure fragment } }); }
Source:
public void fillContextMenu(final IMenuManager menu) { super.fillContextMenu(menu); final ISelection selection = getContext().getSelection(); if (selection.isEmpty()) { return; } // Wait the end of the loading of the representations file try { Job.getJobManager().join(AbstractRepresentationsFileJob.FAMILY, new NullProgressMonitor()); } catch (InterruptedException e) { throw new RuntimeException(e); } // Differents behavior between win and linux : windows will not // display contextual menu if busy cursor while dialog is shown. // Fill the context menu contextMenuFiller.fillContextMenu(menu, selection); }

Target:
public void fillContextMenu(final IMenuManager menu) { super.fillContextMenu(menu); final ISelection selection = getContext().getSelection(); if (selection.isEmpty()) { return; } // Wait the end of the loading of the representations file try { Job.getJobManager().join(AbstractRepresentationsFileJob.FAMILY, new NullProgressMonitor()); } catch (InterruptedException e) { // Do nothing } // Differents behavior between win and linux : windows will not // display contextual menu if busy cursor while dialog is shown. // Fill the context menu contextMenuFiller.fillContextMenu(menu, selection); }
Source:
public void dispose() { // run super. super.dispose(); // remove ourselves as a selection and registry listener getSite().getPage().removePostSelectionListener(this); RegistryFactory.getRegistry().removeListener(this); SaveablesList saveables = (SaveablesList) getSite().getService(ISaveablesLifecycleListener.class); if (saveables != null) { saveables.removeModelLifecycleListener(saveablesTracker); } currentPart = null; currentSelection = null; pinPropertySheetAction = null; }

Target:
public void dispose() { // run super. super.dispose(); // remove ourselves as a selection and registry listener getSite().getPage().removePostSelectionListener(this); RegistryFactory.getRegistry().removeListener(this); ISaveablesLifecycleListener saveables = getSite().getService(ISaveablesLifecycleListener.class); if (saveables instanceof SaveablesList) { ((SaveablesList) saveables).removeModelLifecycleListener(saveablesTracker); } currentPart = null; currentSelection = null; pinPropertySheetAction = null; }
Source:
public List<String> getExtensions() { return extensions == null ? DEFAULT_EXTS : extensions; }

Target:
public List<String> getExtensions() { return extensions; }
Source:
public Weld addExtensions(Class<? extends Extension>... extensionClasses) { Object[] constructorParams = new Object[] {}; for (Class<? extends Extension> extensionClass : extensionClasses) { try { Extension extension = SecurityActions.newInstance(extensionClass); addExtension(extension); } catch (Exception ex) { CommonLogger.LOG.unableToInstantiate(extensionClass, constructorParams, ex); } } return this; }

Target:
public Weld addExtensions(Class<? extends Extension>... extensionClasses) { for (Class<? extends Extension> extensionClass : extensionClasses) { try { Extension extension = SecurityActions.newInstance(extensionClass); addExtension(extension); } catch (Exception ex) { CommonLogger.LOG.unableToInstantiate(extensionClass, new Object[] {}, ex); } } return this; }
Source:
public static ToolTipString fromString(String text) { Objects.requireNonNull(text, "fromString cannot take null"); //$NON-NLS-1$ return new ToolTipString(text, toHtmlString(text)); }

Target:
public static ToolTipString fromString(String text) { return new ToolTipString(text, toHtmlString(text)); }
Source:
public String getDescription() { return "Transform files representing a structured table under an Alluxio directory." + "\n\n" + "Files are coalesced and converted to parquet format." + "\n\n" + "Definition is in format like 'write(hive).option(hive.num.files, 100)'," + "currently, the only modification you can do to the example definition is " + "the number of files in the option." }

Target:
public String getDescription() { return "Transform files representing a structured table under an Alluxio directory." + "\n\n" + "Files are coalesced and converted to parquet format." + "\n\n" + "Definition is in format like 'write(hive).option(hive.num.files, 100)'," + "currently, the only modification you can do to the example definition is " + "the number of files in the option."; }
Source:
private Iterable<Ref> getSortedRefs() throws Exception { List<Ref> all = db.getRefDatabase().getRefsByPrefix(ALL); if (all instanceof RefMap || (all instanceof SortedMap && ((SortedMap) all).comparator() == null)) { return all; } return RefComparator.sort(all); }

Target:
private Iterable<Ref> getSortedRefs() throws Exception { List<Ref> all = db.getRefDatabase().getRefsByPrefix(ALL); // TODO(jrn) check if we can reintroduce fast-path by e.g. implementing // SortedList return RefComparator.sort(all); }
Source:
private IllegalReferenceCountException handleIllegalReferenceCountException(IllegalReferenceCountException e) { String accessRecord = leak.toString(); if (StringUtil.isNullOrEmpty(accessRecord)) { // means leak has been closed and there is no accessRecord. return e; } return new TrackedIllegalReferenceCountException(e.getMessage(), accessRecord); }

Target:
private IllegalReferenceCountException handleIllegalReferenceCountException(IllegalReferenceCountException e) { String accessRecord = leak.toString(); if (StringUtil.isNullOrEmpty(accessRecord)) { // means leak has been closed and there is no accessRecord. return e; } return new TrackedIllegalReferenceCountException(accessRecord, e); }
Source:
public boolean remove(Connection connection) { boolean removed = connectionPool.remove(connection); if (getHttpExchanges().isEmpty()) { tryRemoveIdleDestination(); } else { // We need to execute queued requests // even if this connection was removed. // We may create a connection that is not // needed, but it will eventually idle timeout. if (removed) process(true); } return connectionPool.remove(connection); }

Target:
public boolean remove(Connection connection) { boolean removed = connectionPool.remove(connection); if (getHttpExchanges().isEmpty()) { tryRemoveIdleDestination(); } else if (removed) { // Process queued requests that may be waiting. // We may create a connection that is not // needed, but it will eventually idle timeout. process(true); } return removed; }
Source:
public boolean setValue(T newValue) { if (!validator.validate(newValue)) { LOGGER.warn("The passed value is invalid.", newValue); return false; } PropertyChangeEvent event = new PropertyChangeEvent(this, id.toString(), this.value, newValue); this.value = newValue; dispatchChangedEvent(event); return true; }

Target:
public boolean setValue(T newValue) { if (!validate(newValue)) { return false; } PropertyChangeEvent event = new PropertyChangeEvent(this, id.toString(), this.value, newValue); this.value = newValue; dispatchChangedEvent(event); return true; }
Source:
public AbstractMetric(String metricName, String metricType, T initialValue, MetricReportManager manager) { name = metricName; type = metricType; value = initialValue; metricManager = manager; }

Target:
protected AbstractMetric(String metricName, String metricType, T initialValue, MetricReportManager manager) { name = metricName; type = metricType; value = initialValue; metricManager = manager; }
Source:
public synchronized void commit() throws CommitException { SyncCommitObserver sco = null; try { sco = new SyncCommitObserver(); commitAsync(sco); sco.waitForCommit(); } finally { updates.clear(); weakNotification = null; observedColumns.clear(); columnsRead.clear(); } }

Target:
public synchronized void commit() throws CommitException { SyncCommitObserver sco = null; try { sco = new SyncCommitObserver(); commitAsync(sco); sco.waitForCommit(); } finally { updates.clear(); weakNotification = null; columnsRead.clear(); } }
Source:
public void setEnabled(boolean enabled) { this.active = enabled; System.out.println("active state change: " + active); updateButtonState(); }

Target:
public void setEnabled(boolean enabled) { this.active = enabled; updateButtonState(); }
Source:
default void beforeDataProviderExecution(IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { throw new UnsupportedOperationException("Method is not implemented"); }

Target:
default void beforeDataProviderExecution(IDataProviderMethod dataProviderMethod, ITestNGMethod method, ITestContext iTestContext) { // not implemented }
Source:
private void maybeScheduleCheckpoint() { switch (state()) { case RESTORING: this.checkpoint = checkpointableOffsets(); break; case RUNNING: if (!eosEnabled) { this.checkpoint = checkpointableOffsets(); } break; case SUSPENDED: this.checkpoint = checkpointableOffsets(); break; case CREATED: case CLOSED: throw new IllegalStateException("Illegal state " + state() + " while scheduling checkpoint for active task " + id); default: throw new IllegalStateException("Unknown state " + state() + " while scheduling checkpoint for active task " + id); } }

Target:
private void maybeScheduleCheckpoint() { switch (state()) { case RESTORING: case SUSPENDED: this.checkpoint = checkpointableOffsets(); break; case RUNNING: if (!eosEnabled) { this.checkpoint = checkpointableOffsets(); } break; case CREATED: case CLOSED: throw new IllegalStateException("Illegal state " + state() + " while scheduling checkpoint for active task " + id); default: throw new IllegalStateException("Unknown state " + state() + " while scheduling checkpoint for active task " + id); } }
Source:
public void t1() { testCaseExecutionOrder.add(new Object() {}.getClass().getEnclosingMethod().getName()); }

Target:
public void t1() { }
Source:
public void testValidateDataStreamsNoConflicts() { Metadata metadata = createIndices(5, 10, "foo-datastream").metadata; try { validateDataStreams(metadata.getIndicesLookup(), (DataStreamMetadata) metadata.customs().get(DataStreamMetadata.TYPE)); } catch (Exception e) { fail("did not expect exception when validating a system without indices that would conflict with future backing indices: " + e.getMessage()); } }

Target:
public void testValidateDataStreamsNoConflicts() { Metadata metadata = createIndices(5, 10, "foo-datastream").metadata; // don't expect any exception when validating a system without indices that would conflict with future backing indices validateDataStreams(metadata.getIndicesLookup(), (DataStreamMetadata) metadata.customs().get(DataStreamMetadata.TYPE)); }
Source:
public void onConnectionClosedForUser(QBRTCSession qbrtcSession, Integer integer) { setStatusForOpponent(integer, getString(R.string.closed)); stopTimer(); }

Target:
public void onConnectionClosedForUser(QBRTCSession qbrtcSession, Integer integer) { setStatusForOpponent(integer, getString(R.string.closed)); }
Source:
public JettyServer run(WebApplicationContext baseContext, boolean directlyUseAsWebAppRoot, Function<Function<Integer, JettyServer>, JettyServer> serverStarter, boolean exitOnError) { try { configureLogger(); configureSentry(baseContext); JettyServer jettyServer = createJettyServer(baseContext, directlyUseAsWebAppRoot, serverStarter, v->v.addLifeCycleListener(new JettyLifeCycleListener(baseContext))); jettyServer.start(); logStartupInfo(baseContext); return jettyServer; } catch (Exception e) { return logErrorAndExit(e, exitOnError); } }

Target:
public JettyServer run(WebApplicationContext baseContext, boolean directlyUseAsWebAppRoot, Function<Function<Integer, JettyServer>, JettyServer> serverStarter, boolean exitOnError) { try { configureLogger(); configureSentry(baseContext); JettyServer jettyServer = createJettyServer(baseContext, directlyUseAsWebAppRoot, serverStarter); jettyServer.start(); logStartupInfo(baseContext); return jettyServer; } catch (Exception e) { return logErrorAndExit(e, exitOnError); } }
Source:
public int hashCode() { return name.hashCode(); }

Target:
public int hashCode() { return ~~name.hashCode(); }
Source:
protected boolean copyObject(String src, String dst) { try { LOG.info("Copying to {}", src, dst); mClient.copyObject(mBucketNameInternal, src, mBucketNameInternal, dst); return true; } catch (CosClientException e) { LOG.error("Failed to rename file to {}", src, dst, e); return false; } }

Target:
protected boolean copyObject(String src, String dst) { try { LOG.debug("Copying to {}", src, dst); mClient.copyObject(mBucketNameInternal, src, mBucketNameInternal, dst); return true; } catch (CosClientException e) { LOG.error("Failed to rename file to {}", src, dst, e); return false; } }
Source:
private JsonParser getParser(String data) throws IOException { // If the first character is { or [, assume this is // JSON data and use a JsonParser. Otherwise assume // YAML and use a YAMLParser. Character firstChar = data.charAt(0); if (firstChar == '{' || firstChar == '[') { return this.jsonFactory.createParser(data); } else { return this.yamlFactory.createParser(data); } }

Target:
private JsonParser getParser(String data) throws IOException { // If the first character is { or [, assume this is // JSON data and use a JsonParser. Otherwise assume // YAML and use a YAMLParser. char firstChar = data.charAt(0); if (firstChar == '{' || firstChar == '[') { return this.jsonFactory.createParser(data); } else { return this.yamlFactory.createParser(data); } }
Source:
public boolean equals(Object object) { if (object == null || object.getClass() != getClass()) { return false; } if (object == this) { return true; } MacroId rhs = (MacroId) object; return new EqualsBuilder() .append(getId(), rhs.getId()) .append(getSyntax(), rhs.getSyntax()) .isEquals(); }

Target:
public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof MacroId)) { return false; } MacroId rhs = (MacroId) object; return new EqualsBuilder() .append(getId(), rhs.getId()) .append(getSyntax(), rhs.getSyntax()) .isEquals(); }
Source:
private String getFriendsPath( SourcePathResolver sourcePathResolver, ImmutableList<SourcePath> friendPathsSourcePaths) { // https://youtrack.jetbrains.com/issue/KT-29933 ImmutableSortedSet<String> absoluteFriendPaths = ImmutableSortedSet.copyOf( friendPathsSourcePaths .stream() .map(path -> sourcePathResolver.getAbsolutePath(path).toString()) .collect(Collectors.toSet())); return "-Xfriend-paths=" + absoluteFriendPaths.stream().reduce("", (path1, path2) -> path1 + "," + path2); }

Target:
private String getFriendsPath( SourcePathResolver sourcePathResolver, ImmutableList<SourcePath> friendPathsSourcePaths) { if (friendPathsSourcePaths.isEmpty()) { return ""; } // https://youtrack.jetbrains.com/issue/KT-29933 ImmutableSortedSet<String> absoluteFriendPaths = ImmutableSortedSet.copyOf( friendPathsSourcePaths .stream() .map(path -> sourcePathResolver.getAbsolutePath(path).toString()) .collect(Collectors.toSet())); return "-Xfriend-paths=" + absoluteFriendPaths.stream().reduce("", (path1, path2) -> path1 + "," + path2); }
Source:
private Handler getHandler() { if (mHandler == null) { // Use current main looper mHandler = new Handler(mContext.getMainLooper()); } return mHandler; }

Target:
private synchronized Handler getHandler() { if (mHandler == null) { // Use current main looper mHandler = new Handler(mContext.getMainLooper()); } return mHandler; }
Source:
public ArticlePageObject clickGetInfoLink() { switchToIFrame(); waitForElementByElement(getInfoLink); //Opens new tab to Template namespace getInfoLink.click(); switchOutOfIFrame(); return new ArticlePageObject(driver); }

Target:
public ArticlePageObject clickGetInfoLink() { switchToIFrame(); try { waitForElementByElement(getInfoLink); //Opens new tab to Template namespace getInfoLink.click(); return new ArticlePageObject(driver); } finally { switchOutOfIFrame(); } }
Source:
@Test public void decorateSimpleRabbitListenerContainerFactory_appends_as_first_when_absent() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setAdviceChain(new CacheInterceptor()); assertThat(rabbitTracing.decorateSimpleRabbitListenerContainerFactory(factory).getAdviceChain()) .hasSize(2) .matches(adviceArray -> asList(adviceArray).get(0) instanceof TracingRabbitListenerAdvice); }

Target:
@Test public void decorateSimpleRabbitListenerContainerFactory_appends_as_first_when_absent() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setAdviceChain(new CacheInterceptor()); // the order of advices is important for the downstream interceptor to see the tracing context assertThat(rabbitTracing.decorateSimpleRabbitListenerContainerFactory(factory).getAdviceChain()) .hasSize(2) .matches(adviceArray -> adviceArray[0] instanceof TracingRabbitListenerAdvice); }
Source:
private static DataSource createC3P0DataSource(String name, Map<Object, Object> properties) { ComboPooledDataSource ds = new ComboPooledDataSource(false); ds.setDataSourceName(name); ds.setIdentityToken(name); new BeanMap(ds).putAll(properties); C3P0Registry.reregister(ds); try { checkDataSource(ds, name); } catch (SQLException e) { throw new RuntimeException("Failed check data source", e); } return ds; }

Target:
private static DataSource createC3P0DataSource(String name, Map<Object, Object> properties) { ComboPooledDataSource ds = new ComboPooledDataSource(false); ds.setDataSourceName(name); ds.setIdentityToken(name); new BeanMap(ds).putAll(properties); C3P0Registry.reregister(ds); checkDataSource(ds, name); return ds; }
Source:
private void scheduleRefresh(Duration delay) { // already stopped? avoids rejection exception if (executor.isShutdown()) { return; } executor.schedule((Runnable) this::refresh, delay.toMillis(), TimeUnit.MILLISECONDS); }

Target:
private void scheduleRefresh(Duration delay) { // already stopped? avoids rejection exception if (executor.isShutdown()) { return; } executor.schedule(this::refresh, delay.toMillis(), TimeUnit.MILLISECONDS); }
Source:
public static CDIProvider getCDIProvider() { if (configuredProvider != null) { return configuredProvider; } else { // Discover providers and cache if (discoveredProviders == null) { synchronized (lock) { if (discoveredProviders == null) { findAllProviders(); } } } configuredProvider = discoveredProviders.stream() .filter(c -> c.getCDI() != null) .findAny().orElseThrow(() -> new IllegalStateException("Unable to access CDI")); return configuredProvider; } }

Target:
private static CDIProvider getCDIProvider() { if (configuredProvider != null) { return configuredProvider; } else { // Discover providers and cache if (discoveredProviders == null) { synchronized (lock) { if (discoveredProviders == null) { findAllProviders(); } } } configuredProvider = discoveredProviders.stream() .filter(c -> c.getCDI() != null) .findAny().orElseThrow(() -> new IllegalStateException("Unable to access CDI")); return configuredProvider; } }
Source:
public static boolean customImageExists(String storage, String key) { final AzureBlobClient azureBlob = ContextBuilder.newBuilder("azureblob") .credentials(storage, key) .buildApi(AzureBlobClient.class); try { return azureBlob.containerExists("system"); } catch (Exception e) { e.printStackTrace(); return false; } finally { Closeables2.closeQuietly(azureBlob); } }

Target:
public static boolean customImageExists(String storage, String key) { final AzureBlobClient azureBlob = ContextBuilder.newBuilder("azureblob") .credentials(storage, key) .buildApi(AzureBlobClient.class); try { return azureBlob.containerExists("system"); } finally { Closeables2.closeQuietly(azureBlob); } }
Source:
public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && DeterminismEvaluator.isDeterministic(expression) && !NullabilityAnalyzer.mayReturnNullOnNonNullInput(expression) && !isDynamicFilter(expression)) { ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getType() == ComparisonExpressionType.EQUAL) { // We should only consider equalities that have distinct left and right components return !comparison.getLeft().equals(comparison.getRight()); } } return false; }; }

Target:
public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && isDeterministic(expression) && !mayReturnNullOnNonNullInput(expression) && !isDynamicFilter(expression)) { ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getType() == ComparisonExpressionType.EQUAL) { // We should only consider equalities that have distinct left and right components return !comparison.getLeft().equals(comparison.getRight()); } } return false; }; }
Source:
public void startMasters() throws Exception { mMaster = LocalAlluxioMaster.create(mWorkDirectory, true); mMaster.start(); CommonUtils.PROCESS_TYPE.set(CommonUtils.ProcessType.CLIENT); }

Target:
public void startMasters() throws Exception { mMaster = LocalAlluxioMaster.create(mWorkDirectory, true); mMaster.start(); }
Source:
public Set<VmDeviceGeneralType> getDeviceTypesWithProperties(Version version) { if (!FeatureSupported.deviceCustomProperties(version)) { return Collections.emptySet(); } Set<VmDeviceGeneralType> types; EnumMap<VmDeviceGeneralType, Map<String, Pattern>> map = deviceProperties.get(version); if (map.isEmpty()) { // no device type has any properities types = Collections.emptySet(); } else { // prevent client to modify types = Collections.unmodifiableSet(map.keySet()); } return types; }

Target:
public Set<VmDeviceGeneralType> getDeviceTypesWithProperties(Version version) { if (!FeatureSupported.deviceCustomProperties(version)) { return Collections.emptySet(); } EnumMap<VmDeviceGeneralType, Map<String, Pattern>> map = deviceProperties.get(version); if (map.isEmpty()) { // no device type has any properties return Collections.emptySet(); } else { // prevent client to modify return Collections.unmodifiableSet(map.keySet()); } }
Source:
public PapyrusStereotypedElementItemProviderDecorator(ComposeableAdapterFactory adapterFactory) { super(adapterFactory); labelProviderService = new LabelProviderServiceImpl(); try { labelProviderService.startService(); } catch (ServiceException ex) { Activator.getDefault().getLog().log( new Status(IStatus.WARNING, Activator.PLUGIN_ID, "Unable to start Papyrus Label Provider Service", ex)); //$NON-NLS-1$ } }

Target:
public PapyrusStereotypedElementItemProviderDecorator(ComposeableAdapterFactory adapterFactory) { super(adapterFactory); }
Source:
public static void setupDefaultTestCluster() throws Exception { config = DrillConfig.create(cloneDefaultTestConfigProperties()); classpathScan = ClassPathScanner.fromPrescan(config); openClient(); // turns on the verbose errors in tests // sever side stacktraces are added to the message before sending back to the client test("ALTER SESSION SET `exec.errors.verbose` = true"); emptyDirCreating(); }

Target:
public static void setupDefaultTestCluster() throws Exception { config = DrillConfig.create(cloneDefaultTestConfigProperties()); classpathScan = ClassPathScanner.fromPrescan(config); openClient(); // turns on the verbose errors in tests // sever side stacktraces are added to the message before sending back to the client test("ALTER SESSION SET `exec.errors.verbose` = true"); }
Source:
private static String parseAnnotationFieldTypeName(final Supplier<Class<?>> theTypeSupplier, final String errorMessage) { try { theTypeSupplier.get(); throw new RuntimeException(errorMessage); } catch (MirroredTypeException mte) { return mte.getTypeMirror().toString(); } }

Target:
private static String parseAnnotationFieldTypeName(final Supplier<Class<?>> theTypeSupplier, final String errorMessage) { try { theTypeSupplier.get(); } catch (MirroredTypeException mte) { return mte.getTypeMirror().toString(); } // Failed to parse the field type name throw new RuntimeException(errorMessage); }
Source:
protected void configure() { bind(EventDao.class).to(EventDaoInMemory.class).asEagerSingleton(); bind(Bootstrap.class); }

Target:
protected void configure() { bind(EventDao.class).to(EventDaoInMemory.class).asEagerSingleton(); }
Source:
public ExampleEndpointsProvider() { // Put custom code here to get endpoints // In our case they will be hardcoded try { JHttpEndpoint httpEndpoint = new JHttpEndpoint(new URI("https://jagger.griddynamics.net:443")); endpoints.add(httpEndpoint); } catch (URISyntaxException e) { throw new IllegalStateException(e); } }

Target:
public ExampleEndpointsProvider() { // Put custom code here to get endpoints // In our case they will be hardcoded JHttpEndpoint httpEndpoint = new JHttpEndpoint(URI.create("https://jagger.griddynamics.net:443")); endpoints.add(httpEndpoint); }
Source:
public boolean isEnabled() { final boolean res = super.isEnabled() || isDirty(); return res; }

Target:
public boolean isEnabled() { return super.isEnabled() || isDirty(); }
Source:
private void updateSslVerifyUser(boolean value) { StoredConfig userConfig = GlobalConfigCache.getInstance() .getUserConfig(); try { userConfig.load(); updateSslVerify(userConfig, value); } catch (IOException | ConfigInvalidException e) { // Log it, but otherwise ignore here. LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid, userConfig, e)); } }

Target:
private void updateSslVerifyUser(boolean value) { StoredConfig userConfig = null; try { userConfig = GlobalConfigCache.getInstance().getUserConfig(); updateSslVerify(userConfig, value); } catch (IOException | ConfigInvalidException e) { // Log it, but otherwise ignore here. LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid, userConfig, e)); } }
Source:
private void addAll(QuantileDigest digest, long... values) { requireNonNull(values, "values is null"); for (long value : values) { digest.add(value); } }

Target:
private static void addAll(QuantileDigest digest, long... values) { requireNonNull(values, "values is null"); for (long value : values) { digest.add(value); } }
Source:
protected Object encodeCommand(Command command) { initDevicePassword(command, LaipacProtocolDecoder.DEFAULT_DEVICE_PASSWORD); switch (command.getType()) { case Command.TYPE_CUSTOM: return formatCommand(command, "{%s}", Command.KEY_DATA); case Command.TYPE_POSITION_SINGLE: return formatCommand(command, "AVREQ,{%s},1", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_REBOOT_DEVICE: return formatCommand(command, "AVRESET,{%s},{%s}", Command.KEY_UNIQUE_ID, Command.KEY_DEVICE_PASSWORD); default: break; } return null; }

Target:
protected Object encodeCommand(Command command) { initDevicePassword(command, LaipacProtocolDecoder.DEFAULT_DEVICE_PASSWORD); switch (command.getType()) { case Command.TYPE_CUSTOM: return formatCommand(command, "{%s}", Command.KEY_DATA); case Command.TYPE_POSITION_SINGLE: return formatCommand(command, "AVREQ,{%s},1", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_REBOOT_DEVICE: return formatCommand(command, "AVRESET,{%s},{%s}", Command.KEY_UNIQUE_ID, Command.KEY_DEVICE_PASSWORD); default: return null; } }
Source:
public MetaMasterSync(Address masterAddress, MetaMasterMasterClient masterClient) throws IOException { // TODO(lu) should avoid throw exception in Java constructor to avoid half-baked class instances mMasterAddress = masterAddress; mMasterClient = masterClient; mHeartbeatTimeoutMs = (int) Configuration.getMs(PropertyKey.MASTER_HEARTBEAT_TIMEOUT_MS); mLastSuccessfulHeartbeatMs = System.currentTimeMillis() - mHeartbeatTimeoutMs; }

Target:
public MetaMasterSync(Address masterAddress, MetaMasterMasterClient masterClient) { mMasterAddress = masterAddress; mMasterClient = masterClient; mHeartbeatTimeoutMs = (int) Configuration.getMs(PropertyKey.MASTER_HEARTBEAT_TIMEOUT_MS); mLastSuccessfulHeartbeatMs = System.currentTimeMillis() - mHeartbeatTimeoutMs; }
Source:
public List<SqlIdentifier> getProjectionFields(MetadataType metadataLevel, OptionManager options) { List<SqlIdentifier> columnList = new ArrayList<>(); columnList.add(new SqlIdentifier(options.getString(ExecConstants.IMPLICIT_FQN_COLUMN_LABEL), SqlParserPos.ZERO)); columnList.add(new SqlIdentifier(options.getString(ExecConstants.IMPLICIT_LAST_MODIFIED_TIME_COLUMN_LABEL), SqlParserPos.ZERO)); return columnList; }

Target:
public List<SqlIdentifier> getProjectionFields(MetadataType metadataLevel, OptionManager options) { return Arrays.asList( new SqlIdentifier(options.getString(ExecConstants.IMPLICIT_FQN_COLUMN_LABEL), SqlParserPos.ZERO), new SqlIdentifier(options.getString(ExecConstants.IMPLICIT_LAST_MODIFIED_TIME_COLUMN_LABEL), SqlParserPos.ZERO)); }
Source:
protected void executeCommand() { //disconnect the connection from vdsm boolean isStorageDisconnectSucceeded = disconnectStorage(); if(isStorageDisconnectSucceeded) { String connectionId = getConnection().getid(); if(StringUtils.isNotEmpty(connectionId)) { //remove the connection record from db getDbFacade().getStorageServerConnectionDao().remove(connectionId); setSucceeded(true); } } }

Target:
protected void executeCommand() { //disconnect the connection from vdsm boolean isStorageDisconnectSucceeded = disconnectStorage(); if(isStorageDisconnectSucceeded) { String connectionId = getConnection().getid(); if(StringUtils.isNotEmpty(connectionId)) { //remove the connection record from db getDbFacade().getStorageServerConnectionDao().remove(connectionId); } setSucceeded(true); } }
Source:
public static String getWarningMessages(String filename){ String warningMessage = ""; if (getErrorMessage(filename).length() == 0 && filename.length() > 0) { if (!filename.matches("[A-Za-z][A-Za-z0-9_]*")) { // check to make sure if filename has no spaces String errorMessage = MESSAGES.whitespaceProjectNameError(); filename = filename.replaceAll("( )+", " ").replace(" ","_"); warningMessage = errorMessage + ". \n '" + filename + "' will be used if continued."; } } return warningMessage; }

Target:
public static String getWarningMessages(String filename) { String warningMessage = ""; if (getErrorMessage(filename).length() == 0 && filename.trim().length() > 0) { if (!filename.matches("[A-Za-z][A-Za-z0-9_]*")) { // check to make sure if filename has no spaces String errorMessage = MESSAGES.whitespaceProjectNameError(); filename = filename.trim().replaceAll("( )+", " ").replace(" ","_"); warningMessage = errorMessage + ". \n '" + filename + "' will be used if continued."; } } return warningMessage; }
Source:
private IRadioButton<T> findFirstButtonInFieldTree(IFormField f) { if (f instanceof IRadioButton) { return (IRadioButton<T>) f; //TODO: mnick } else if (f instanceof ICompositeField) { for (IFormField sub : ((ICompositeField) f).getFields()) { IRadioButton<T> b = findFirstButtonInFieldTree(sub); if (b != null) { return b; } } } return null; }

Target:
private IRadioButton<T> findFirstButtonInFieldTree(IFormField f) { if (f instanceof IRadioButton) { return (IRadioButton) f; } else if (f instanceof ICompositeField) { for (IFormField sub : ((ICompositeField) f).getFields()) { IRadioButton<T> b = findFirstButtonInFieldTree(sub); if (b != null) { return b; } } } return null; }
Source:
public void testGenerateXpathSuppressionOptionEmptyConfig() throws Exception { final String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE suppressions PUBLIC\n" + " \"-//Puppy Crawl//DTD Suppressions Xpath Experimental 1.2//EN\"\n" + " \"http://checkstyle.sourceforge.net/dtds/" + "suppressions_1_2_xpath_experimental.dtd\">\n" + "<suppressions>\n" + "</suppressions>\n"; exit.checkAssertionAfterwards(() -> { assertEquals("Unexpected output log", expected, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); Main.main("-c", getPath("InputMainConfig-empty.xml"), "--generate-xpath-suppression", getPath("InputMainComplexityOverflow.java")); }

Target:
public void testGenerateXpathSuppressionOptionEmptyConfig() throws Exception { final String expected = ""; exit.checkAssertionAfterwards(() -> { assertEquals("Unexpected output log", expected, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); Main.main("-c", getPath("InputMainConfig-empty.xml"), "--generate-xpath-suppression", getPath("InputMainComplexityOverflow.java")); }
Source:
public LocalCluster(String jarFileName, int siteCount, int hostCount, int kfactor, int clusterId, BackendTarget target, FailureState failureState, boolean debug, boolean isRejoinTest, Map<String, String> env) { // NOTE: isRejoinTest is unused this(null, null, jarFileName, siteCount, hostCount, kfactor, clusterId, target, failureState, debug, env); }

Target:
public LocalCluster(String jarFileName, int siteCount, int hostCount, int kfactor, int clusterId, BackendTarget target, FailureState failureState, boolean debug, boolean isRejoinTest, Map<String, String> env) { this(null, null, jarFileName, siteCount, hostCount, kfactor, clusterId, target, failureState, debug, isRejoinTest, env); }
Source:
public void flush() throws IOException { entryLogManager.flushCurrentLogs(); entryLogManager.flushRotatedLogs(); }

Target:
public void flush() throws IOException { entryLogManager.flush(); }
Source:
public String getModeName() { String header = getHeader(); return header.substring(0, header.indexOf('"') - 1); }

Target:
private String getModeName() { String header = getHeader(); return header.substring(0, header.indexOf('"') - 1); }
Source:
private List<RequestInfo> pollForRequests() { // these are ids that were successfully put for an operation that eventually failed idsToDelete.clear(); putManager.getIdsToDelete(idsToDelete); // this is a best effort to delete ids for cleanup purposes (these may fail and we will // not do anything about it at this time). for (String blobId : idsToDelete) { // possibly add a batch api going forward. deleteManager .submitDeleteBlobOperation(operationIdGenerator.incrementAndGet(), blobId, new FutureResult<Void>(), null); } List<RequestInfo> requests = new ArrayList<RequestInfo>(); putManager.poll(requests); getManager.poll(requests); deleteManager.poll(requests); return requests; }

Target:
private List<RequestInfo> pollForRequests() { // these are ids that were successfully put for an operation that eventually failed idsToDelete.clear(); putManager.getIdsToDelete(idsToDelete); // this is a best effort to delete ids for cleanup purposes (these may fail and we will // not do anything about it at this time). for (String blobId : idsToDelete) { // possibly add a batch api going forward. deleteManager.submitDeleteBlobOperation(blobId, new FutureResult<Void>(), null); } List<RequestInfo> requests = new ArrayList<RequestInfo>(); putManager.poll(requests); getManager.poll(requests); deleteManager.poll(requests); return requests; }
Source:
private Set<GlusterServerInfo> fetchServers(VDS upServer, List<VDS> existingServers) { Set<GlusterServerInfo> fetchedServers = null; while (fetchedServers == null && existingServers.size() > 0) { fetchedServers = fetchServers(upServer); if (fetchedServers == null) { logServerMessage(upServer, AuditLogType.GLUSTER_SERVERS_LIST_FAILED); // Couldn't fetch servers from the up server. Mark it as non-operational setNonOperational(upServer); existingServers.remove(upServer); upServer = getNewUpServer(existingServers, upServer); } } return fetchedServers; }

Target:
private Set<GlusterServerInfo> fetchServers(VDS upServer, List<VDS> existingServers) { Set<GlusterServerInfo> fetchedServers = null; while (fetchedServers == null && !existingServers.isEmpty()) { fetchedServers = fetchServers(upServer); if (fetchedServers == null) { logServerMessage(upServer, AuditLogType.GLUSTER_SERVERS_LIST_FAILED); // Couldn't fetch servers from the up server. Mark it as non-operational setNonOperational(upServer); existingServers.remove(upServer); upServer = getNewUpServer(existingServers, upServer); } } return fetchedServers; }
Source:
public void download(String url, String downloadPath) { InputStream in = null; try { in = new URL(url).openStream(); FileUtils.writeByteArrayToFile(new File(downloadPath), IOUtils.toByteArray(in)); System.out.println(IOUtils.toString(in)); } catch (IOException e) { log.error(e); } finally { IOUtils.closeQuietly(in); } }

Target:
public boolean download(String url, String downloadPath) { InputStream in = null; try { in = new URL(url).openStream(); FileUtils.writeByteArrayToFile(new File(downloadPath), IOUtils.toByteArray(in)); return true; } catch (IOException e) { log.error(e); return false; } finally { IOUtils.closeQuietly(in); } }
Source:
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file, DataContext dataContext) { if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) return; if (editor.getSettings().isVariableInplaceRenameEnabled()) { final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor); if (templateState != null && !templateState.isFinished()) return; } performAction(new GoIntroduceOperation(project, editor, file)); }

Target:
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file, DataContext dataContext) { if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) return; performAction(new GoIntroduceOperation(project, editor, file)); }
Source:
EWAHCompressedBitmap getBitmap() { // Fast path to immediately return the expanded result. Object r = bitmapContainer; if (r instanceof EWAHCompressedBitmap) return (EWAHCompressedBitmap) r; // Expand the bitmap and cache the result. XorCompressedBitmap xb = (XorCompressedBitmap) r; EWAHCompressedBitmap out = xb.bitmap; while (true) { r = xb.xorBitmap.bitmapContainer; if (r instanceof EWAHCompressedBitmap) { bitmapContainer = out = out.xor((EWAHCompressedBitmap) r); return out; } xb = (XorCompressedBitmap) r; out = out.xor(xb.bitmap); } }

Target:
EWAHCompressedBitmap getBitmap() { // Fast path to immediately return the expanded result. Object r = bitmapContainer; if (r instanceof EWAHCompressedBitmap) return (EWAHCompressedBitmap) r; // Expand the bitmap and cache the result. XorCompressedBitmap xb = (XorCompressedBitmap) r; EWAHCompressedBitmap out = xb.bitmap; for (;;) { r = xb.xorBitmap.bitmapContainer; if (r instanceof EWAHCompressedBitmap) { out = out.xor((EWAHCompressedBitmap) r); bitmapContainer = out; return out; } xb = (XorCompressedBitmap) r; out = out.xor(xb.bitmap); } }
Source:
public void handleInvocation(EJBClientInvocationContext context) throws Exception { log.info("In the client interceptor handleInvocation : " + this.getClass().getName() + " " + context.getViewClass() + " " + context.getLocator()); context.getContextData().put("ClientInterceptorInvoked", this.getClass().getName() + " " + context.getViewClass() + " " + context.getLocator()); // Must make this call context.sendRequest(); }

Target:
public void handleInvocation(EJBClientInvocationContext context) throws Exception { log.debug("In the client interceptor handleInvocation : " + this.getClass().getName() + " " + context.getViewClass() + " " + context.getLocator()); // Must make this call context.sendRequest(); }
Source:
public void testGetNameFromPath() { String path1 = "/group1"; String path2 = "/group1/group2/group3"; String emptyPath = ""; String nullPath = null; String rootPath = "/"; assertEquals(HDF5Utils.getNameFromPath(path1), "group1"); assertEquals(HDF5Utils.getNameFromPath(path2), "group3"); assertEquals(HDF5Utils.getNameFromPath(emptyPath), ""); assertNull(HDF5Utils.getNameFromPath(nullPath)); assertEquals(HDF5Utils.getNameFromPath(rootPath), ""); }

Target:
public void testGetNameFromPath() { String path1 = "/group1"; assertEquals(HDF5Utils.getNameFromPath(path1), "group1"); }
Source:
public void onEntityDestroyed(EntityRef entity) { if (!entity.isPersistent()) { return; // ignore } entityDeltas.remove(entity.getId()); destroyedEntities.add(entity.getId()); }

Target:
public void onEntityDestroyed(EntityRef entity) { if (entity.isPersistent()) { entityDeltas.remove(entity.getId()); destroyedEntities.add(entity.getId()); } }
Source:
public void testPutAsync() throws Exception { // put Future<String> f = c.putAsync("k", "v"); testFuture(f, null); testK("v"); f = c.putAsync("k", "v2"); testFuture(f, "v"); assertEquals("v2", c.get("k")); }

Target:
public void testPutAsync() throws Exception { // put Future<String> f = c.putAsync("k", "v"); testFuture(f, null); testK("v"); f = c.putAsync("k", "v2"); testFuture(f, "v"); testK("v2"); }
Source:
public void setProjectName(String projectName) { fProjectName = projectName; // If remote directory field is empty if(fLocationText.getText().equals(EMPTY_STRING)) { fRemoteDirSelected = false; } // If remote directory was not selected yet if (fRemoteDirSelected == false) { fLocationText.setText(getDefaultPathDisplayString()); } }

Target:
public void setProjectName(String projectName) { fProjectName = projectName; // If remote directory field is empty if(fLocationText.getText().equals(EMPTY_STRING)) { fRemoteDirSelected = false; } // If remote directory was not selected yet if (!fRemoteDirSelected) { fLocationText.setText(getDefaultPathDisplayString()); } }
Source:
public IllustratedSelectItem(Object value, String label, String image) { super(value, label); this.image = image; }

Target:
IllustratedSelectItem(Object value, String label, String image) { super(value, label); this.image = image; }