auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static <T extends Item> void addRangeKeyConditionToQuerySpec(final QuerySpec querySpec, final CompoundAttributeQuery compoundAttributeQuery, final Class<T> itemClass) { final String supportingConditionValue = compoundAttributeQuery.getSupportingCondition().getValues().iterator() .next(); final Operators comparisonOperator = compoundAttributeQuery.getSupportingCondition().getComparisonOperator(); final Class<?> clazz = compoundAttributeQuery.getSupportingAttributeType(itemClass); try { final Object value = clazz.getConstructor(String.class).newInstance(supportingConditionValue); final RangeKeyCondition rangeKeyCondition = RangeKeyConditionBuilder .build(compoundAttributeQuery.getSupportingAttributeName(), value, comparisonOperator); querySpec.withRangeKeyCondition(rangeKeyCondition); } catch (final Exception e) { throw new PersistenceResourceFailureException( String.format("Could not add range key condition for query: %s on item %s.", compoundAttributeQuery, itemClass.getSimpleName()), e); } }

Target:
private static <T extends Item> void addRangeKeyConditionToQuerySpec(final QuerySpec querySpec, final CompoundAttributeQuery compoundAttributeQuery, final Class<T> itemClass) { final String supportingConditionStringValue = compoundAttributeQuery.getSupportingCondition().getValues().iterator() .next(); final Operators comparisonOperator = compoundAttributeQuery.getSupportingCondition().getComparisonOperator(); final Class<?> supportingAttributeType = compoundAttributeQuery.getSupportingAttributeType(itemClass); try { final Object supportingConditionValue = supportingAttributeType.getConstructor(String.class).newInstance(supportingConditionStringValue); final RangeKeyCondition rangeKeyCondition = RangeKeyConditionBuilder .build(compoundAttributeQuery.getSupportingAttributeName(), supportingConditionValue, comparisonOperator); querySpec.withRangeKeyCondition(rangeKeyCondition); } catch (final Exception e) { throw new PersistenceResourceFailureException( String.format("Could not add range key condition for query: %s on item %s.", compoundAttributeQuery, itemClass.getSimpleName()), e); } }
Source:
public void copy(Velocity other) { this.velocity = other.velocity; }

Target:
public void copy(Velocity other) { velocity = other.velocity.cpy(); }
Source:
protected List<Object> getChannelKeys(Message<?> message) { String mostSpecificCause = null; Object payload = message.getPayload(); if (payload instanceof Throwable) { Throwable cause = (Throwable) payload; Set<String> mapping = getChannelMappings().keySet(); Map<String, Class<?>> classesCache = new HashMap<String, Class<?>>(); while (cause != null) { for (String className : mapping) { Class<?> exceptionClass = classesCache.get(className); if (exceptionClass == null) { try { exceptionClass = ClassUtils.forName(className, getApplicationContext().getClassLoader()); classesCache.put(className, exceptionClass); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } } if (exceptionClass.isInstance(cause)) { mostSpecificCause = className; } } cause = cause.getCause(); } } return mostSpecificCause != null ? Collections.<Object>singletonList(mostSpecificCause) : null; }

Target:
protected List<Object> getChannelKeys(Message<?> message) { String mostSpecificCause = null; Object payload = message.getPayload(); if (payload instanceof Throwable) { Throwable cause = (Throwable) payload; while (cause != null) { for (Map.Entry<String, Class<?>> entry : this.classNameMappings.entrySet()) { String channelKey = entry.getKey(); Class<?> exceptionClass = entry.getValue(); if (exceptionClass.isInstance(cause)) { mostSpecificCause = channelKey; } } cause = cause.getCause(); } } return mostSpecificCause != null ? Collections.<Object>singletonList(mostSpecificCause) : null; }
Source:
public static List<StorageServerConnections> updateInitiators(List<StorageServerConnections> conns, Guid vdsId) { List<StorageServerConnections> res = new ArrayList<>(conns); for (StorageServerConnections conn : conns) { List<VdsNetworkInterface> initiators = DbFacade.getInstance().getInterfaceDao() .getIscsiInitiatorsByVdsIdAndStorageTargetId(vdsId, conn.getid()); if (initiators != null && !initiators.isEmpty()) { conn.setInitiatorName(initiators.remove(0).getName()); for (VdsNetworkInterface initiator : initiators) { StorageServerConnections newConn = StorageServerConnections.copyOf(conn); newConn.setid(Guid.newGuid().toString()); newConn.setInitiatorName(initiator.getName()); res.add(newConn); } } } return res; }

Target:
public static List<StorageServerConnections> updateInitiators(List<StorageServerConnections> conns, Guid vdsId) { List<StorageServerConnections> res = new ArrayList<>(conns); for (StorageServerConnections conn : conns) { List<VdsNetworkInterface> initiators = DbFacade.getInstance().getInterfaceDao() .getIscsiInitiatorsByHostIdAndStorageTargetId(vdsId, conn.getid()); if (!initiators.isEmpty()) { conn.setInitiatorName(initiators.remove(0).getName()); for (VdsNetworkInterface initiator : initiators) { StorageServerConnections newConn = StorageServerConnections.copyOf(conn); newConn.setid(Guid.newGuid().toString()); newConn.setInitiatorName(initiator.getName()); res.add(newConn); } } } return res; }
Source:
private void serviceCacheCleanup() { long currentTime = new Date().getTime(); long updateTime = lastCacheCleanupMillis + ( DataServiceConstants.STREAMING_CACHE_CLEANUP_INTERVAL_SECONDS * 1000 ); if ( updateTime <= currentTime ) { serviceListeners.cleanUp(); lastCacheCleanupMillis = currentTime; } }

Target:
private void serviceCacheCleanup() { long currentTime = System.currentTimeMillis(); long updateTime = lastCacheCleanupMillis + ( DataServiceConstants.STREAMING_CACHE_CLEANUP_INTERVAL_SECONDS * 1000 ); if ( updateTime <= currentTime ) { serviceListeners.cleanUp(); lastCacheCleanupMillis = currentTime; } }
Source:
public int getItemHeight(ITimeGraphEntry entry) { int itemHeight = super.getItemHeight(entry); if (isCurrentThread(entry)) { return itemHeight / 4; } return itemHeight; }

Target:
public int getItemHeight(ITimeGraphEntry entry) { int itemHeight = super.getItemHeight(entry); if (isType(entry, Type.CPU)) { return (int) (itemHeight * 0.65); } return itemHeight; }
Source:
public void initializeState(FunctionInitializationContext context) throws Exception { lastSentStored = context.getOperatorStateStore().getListState(new ListStateDescriptor<>("counter", Integer.class)); if (context.isRestored()) { Iterator<Integer> iterator = lastSentStored.get().iterator(); checkState(iterator.hasNext()); sentCount = iterator.next(); checkState(!iterator.hasNext()); } checkState(cancelAfter == null || sentCount < cancelAfter); }

Target:
public void initializeState(FunctionInitializationContext context) throws Exception { lastSentStored = context.getOperatorStateStore().getListState(new ListStateDescriptor<>("counter", Integer.class)); if (context.isRestored()) { sentCount = getOnlyElement(lastSentStored.get()); } checkState(cancelAfter == null || sentCount < cancelAfter); }
Source:
public void uninstall() throws DeviceException { ILogger lifecycleLogger = new LoggerWrapper(getLogger(), LogLevel.LIFECYCLE); final String applicationId = variant.getApplicationId(); getLogger().info("Uninstalling app: " + applicationId); final DeviceProvider deviceProvider = new ConnectedDeviceProvider(getAdbExe()); deviceProvider.init(); final List<? extends DeviceConnector> devices = deviceProvider.getDevices(); final List<DeviceConnector> onlineDevices = InstallUtils.keepOnlineDevices(devices, lifecycleLogger); for (DeviceConnector device : onlineDevices) { device.uninstallPackage(applicationId, getTimeOutInMs(), getILogger()); logUninstall(device, applicationId); } int n = onlineDevices.size(); getLogger().quiet("Uninstalled from device{}.", applicationId, n, n == 1 ? "" : "s"); }

Target:
public void uninstall() throws DeviceException { final Logger logger = getLogger(); final String applicationId = variant.getApplicationId(); logger.info("Uninstalling app: {}", applicationId); final ILogger lifecycleLogger = new LoggerWrapper(getLogger(), LogLevel.LIFECYCLE); final DeviceProvider deviceProvider = new ConnectedDeviceProvider(getAdbExe(), lifecycleLogger); deviceProvider.init(); final List<? extends DeviceConnector> devices = deviceProvider.getDevices(); for (DeviceConnector device : devices) { device.uninstallPackage(applicationId, getTimeOutInMs(), getILogger()); logger.lifecycle( "Uninstalling (from {}:{}) from device '{}' ({}).", applicationId, getProject().getName(), variant.getVariantConfiguration().getFullName(), device.getName(), device.getSerialNumber()); } int n = devices.size(); logger.quiet("Uninstalled from device{}.", applicationId, n, n == 1 ? "" : "s"); }
Source:
public boolean hasMore() { if (savedInputRow != null) { return true; } while (firehose.hasMore()) { final InputRow row = firehose.nextRow(); if (predicate.apply(row)) { savedInputRow = row; return true; } if (ignored % ignoredThreshold == 0) { ignored++; log.warn("[%s] InputRow(s) ignored as they do not satisfy the predicate", ignored); } } return false; }

Target:
public boolean hasMore() { if (savedInputRow != null) { return true; } while (firehose.hasMore()) { final InputRow row = firehose.nextRow(); if (predicate.apply(row)) { savedInputRow = row; return true; } if (ignored % IGNORE_THRESHOLD == 0) { log.warn("[%,d] InputRow(s) ignored as they do not satisfy the predicate", ignored); } ignored++; } return false; }
Source:
public static void afterClass() throws InterruptedException, TimeoutException, IOException, CommandFailedException { client.apply(new RemoveDataSource(JDBC_STORE_DATASOURCE_NAME)); client.apply(snapshotBackup.restore()); administration.restartIfRequired(); }

Target:
public static void afterClass() throws InterruptedException, TimeoutException, IOException, CommandFailedException { client.apply(snapshotBackup.restore()); administration.restartIfRequired(); }
Source:
public ContainerInfo allocateContainer(final ReplicationType type, final ReplicationFactor replicationFactor, final String owner) throws IOException { lock.lock(); try { final ContainerInfo containerInfo; containerInfo = containerStateManager .allocateContainer(pipelineManager, type, replicationFactor, owner); addContainerToDB(containerInfo); return containerInfo; } finally { lock.unlock(); } }

Target:
public ContainerInfo allocateContainer(final ReplicationType type, final ReplicationFactor replicationFactor, final String owner) throws IOException { lock.lock(); try { final ContainerInfo containerInfo = containerStateManager.allocateContainer(pipelineManager, type, replicationFactor, owner); addContainerToDB(containerInfo); return containerInfo; } finally { lock.unlock(); } }
Source:
public InputStream getEntryInputStream() { if (data == null) { throw new IllegalStateException("entry content can be accessed only once"); } ByteBufInputStream res = new ByteBufInputStream(data); data = null; return res; }

Target:
public InputStream getEntryInputStream() { Preconditions.checkNotNull(data, "entry content can be accessed only once"); ByteBufInputStream res = new ByteBufInputStream(data); data = null; return res; }
Source:
public AsyncTableFunction<RowData> getAsyncLookupFunction(String[] lookupKeys) { return null; }

Target:
public AsyncTableFunction<RowData> getAsyncLookupFunction(String[] lookupKeys) { throw new UnsupportedOperationException("Hive table doesn't support async lookup"); }
Source:
public void testTxLocalNodeFailover(){ withAllIsolationsAndConcurrencies(new IgniteClosure<Object, Void>() { @Override public Void apply(Object o) { try { txLocalNodeFailover(); } catch (Exception ignore) { ignore.printStackTrace(); assert false : "Impossible situation"; } return null; } }); }

Target:
public void testTxLocalNodeFailover() throws Exception { startGrid(getTestIgniteInstanceName(0)); runWithAllIsolations(new IgniteCallable<Void>() { @Override public Void call() throws Exception { txLocalNodeFailover(); return null; } }); stopAllGrids(); }
Source:
public static IWorkspace getWorkspace() { Job job = initWorkspaceJob; if (workspace == null && job == null) { throw new IllegalStateException(Messages.resources_workspaceClosed); } else if (job != null && Thread.currentThread() != job.getThread()) { try { while (!job.join(GET_WORKSPACE_TIMEOUT_BEFORE_WARNING, new NullProgressMonitor())) { class SeverityMultiStatus extends MultiStatus { public SeverityMultiStatus(int severity, String pluginId, String message, Throwable exception) { super(pluginId, OK, message, exception); setSeverity(severity); } } MultiStatus status = new SeverityMultiStatus(IStatus.WARNING, PI_RESOURCES, NLS.bind(Messages.resources_longWorkspaceInit, Thread.currentThread()), null); Exception exception = new Exception(); status.add(new Status(IStatus.INFO, PI_RESOURCES, String.format(Messages.resources_sampleStacktrace, new SimpleDateFormat("HH:mm:ss.SSS").format(new Date())), exception)); getPlugin().getLog().log(status); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (workspace == null) { throw new IllegalStateException(Messages.resources_workspaceClosed); } } return workspace; }

Target:
public static IWorkspace getWorkspace() { Job job = initWorkspaceJob; if (workspace == null && job == null) { throw new IllegalStateException(Messages.resources_workspaceClosed); } else if (job != null && Thread.currentThread() != job.getThread()) { try { while (!job.join(GET_WORKSPACE_TIMEOUT_BEFORE_WARNING_MILLIS, new NullProgressMonitor())) { logLongWorkspaceInitWarning(job); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (workspace == null) { throw new IllegalStateException(Messages.resources_workspaceClosed); } } return workspace; }
Source:
private boolean isNotDuplicateDocumentFilter(@NonNull final DocumentFilter filterToAdd) { return _addedFiltersNoDuplicates.add(filterToAdd.withId("1")); }

Target:
private boolean isNotDuplicateDocumentFilter(@NonNull final DocumentFilter filterToAdd) { return _addedFiltersNoDuplicates.add(filterToAdd.withId("AvoidDuplicateFiltersThatOnlyDifferInTheirId")); }
Source:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int pos) { if (holder instanceof ReadingListPageItemHolder) { ((ReadingListPageItemHolder) holder).bindItem(readingList.getPages().get(pos)); } }

Target:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int pos) { if (readingList != null && holder instanceof ReadingListPageItemHolder) { ((ReadingListPageItemHolder) holder).bindItem(readingList.getPages().get(pos)); } }
Source:
public static boolean isSymlink(@Nonnull File file) throws IOException { try { Path path = file.toPath(); BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); if (attrs.isSymbolicLink()) { return true; } else if (attrs instanceof DosFileAttributes) { return attrs.isOther(); } else { return false; } } catch (NoSuchFileException e) { return false; } }

Target:
public static boolean isSymlink(@Nonnull File file) throws IOException { try { Path path = file.toPath(); BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); if (attrs.isSymbolicLink()) { return true; } else if (attrs instanceof DosFileAttributes) { return attrs.isOther(); } else { return false; } } catch (InvalidPathException e) { throw new IOException(e); } catch (NoSuchFileException e) { return false; } }
Source:
protected Geometry unifyGeometry(Geometry geom, IOReporter report) { if (geom == null) { return geom; } EnumWindingOrderTypes windingOrder = getWindingOrder(); if (windingOrder == null || windingOrder == EnumWindingOrderTypes.noChanges) { return geom; } else { Geometry unifiedGeometry; switch (windingOrder) { case counterClockwise: unifiedGeometry = WindingOrder.unifyWindingOrder(geom, true); break; case clockwise: unifiedGeometry = WindingOrder.unifyWindingOrder(geom, false); break; default: if (report != null) { report.error(new IOMessageImpl("WindingOrder is not set", null)); } unifiedGeometry = geom; break; } return unifiedGeometry; } }

Target:
protected Geometry unifyGeometry(Geometry geom, IOReporter report) { if (geom == null) { return geom; } EnumWindingOrderTypes windingOrder = getWindingOrder(); if (windingOrder == null || windingOrder == EnumWindingOrderTypes.noChanges) { return geom; } else { Geometry unifiedGeometry; switch (windingOrder) { case counterClockwise: unifiedGeometry = WindingOrder.unifyWindingOrder(geom, true); break; case clockwise: unifiedGeometry = WindingOrder.unifyWindingOrder(geom, false); break; default: if (report != null) { report.error(new IOMessageImpl( "Parameter encountered as winding order is not known: " + windingOrder.toString(), null)); } unifiedGeometry = geom; break; } return unifiedGeometry; } }
Source:
public PanelNameTextField(String panelName, FilterPanel panel) { this.panel = panel; previousText = panelName; Platform.runLater(() -> { requestFocus(); selectAll(); }); setText(panelName); setup(); textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observableValue, String s, String s2) { if (getText().length() > PANEL_MAX_NAME_LENGTH) { setText(previousText); } previousText = getText(); } }); setPrefColumnCount(30); }

Target:
public PanelNameTextField(String panelName, FilterPanel panel) { this.panel = panel; previousText = panelName; Platform.runLater(() -> { requestFocus(); selectAll(); }); setText(panelName); setup(); textProperty().addListener(c -> { if (getText().length() > PANEL_MAX_NAME_LENGTH) { setText(previousText); } previousText = getText(); }); setPrefColumnCount(30); }
Source:
public void run() { GerritTrigger trigger = getGerritTrigger(); if (trigger == null) { return; } if (trigger.getTriggerConfigURL() == null || trigger.getTriggerConfigURL().isEmpty()) { return; } trigger.updateTriggerConfigURL(); }

Target:
public void run() { GerritTrigger trigger = getGerritTrigger(); if (trigger == null) { return; } if (StringUtils.isEmpty(trigger.getTriggerConfigURL())) { return; } trigger.updateTriggerConfigURL(); }
Source:
public void forecast(Weather weather) { this.forecast(weather, (300 + (new Random()).nextInt(600)) * 20); }

Target:
public void forecast(Weather weather) { this.forecast(weather, (300 + this.rand.nextInt(600)) * 20); }
Source:
public void inputGroupRecipient(String fileName) { WebElement groupReceiverListUploadBox = this.getGroupReceiverListUploadBox(); JavascriptExecutor js = (JavascriptExecutor) browser.driver; js.executeScript("arguments[0].style.display = 'inline'", groupReceiverListUploadBox); File file = new File("src/test/resources/data/" + fileName); WebElement uploadGroupListFile = this.uploadGroupListFile(); uploadGroupListFile.sendKeys(file.getAbsolutePath()); js.executeScript("arguments[0].style.display = 'none'", groupReceiverListUploadBox); waitForAjaxLoaderGifToDisappear(); }

Target:
public void inputGroupRecipient(String fileName) { executeScript("arguments[0].style.display = 'inline'", groupReceiverListUploadBox); File file = new File(TestProperties.TEST_EMAILS_FOLDER + File.separator + fileName); inputFieldForGroupList.sendKeys(file.getAbsolutePath()); executeScript("arguments[0].style.display = 'none'", groupReceiverListUploadBox); waitForAjaxLoaderGifToDisappear(); }
Source:
public BinaryData getBodyAsBinaryData() { final AmqpBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType(); switch (bodyType) { case DATA: return ((AmqpDataBody) amqpAnnotatedMessage.getBody()).getDataAsBinaryData().stream().findFirst().get(); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Body type not supported yet " + bodyType.toString())); default: logger.warning("Invalid body type {}.", bodyType); throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } }

Target:
public BinaryData getBodyAsBinaryData() { final AmqpBodyType bodyType = amqpAnnotatedMessage.getBody().getBodyType(); switch (bodyType) { case DATA: return ((AmqpDataBody) amqpAnnotatedMessage.getBody()).getData().stream().findFirst().get(); case SEQUENCE: case VALUE: throw logger.logExceptionAsError(new UnsupportedOperationException("Body type not supported yet " + bodyType.toString())); default: throw logger.logExceptionAsError(new IllegalStateException("Body type not valid " + bodyType.toString())); } }
Source:
public void run() { if (!isRunAllowed() || !InfinispanRoutePolicy.this.isRunAllowed()) { return; } if (isLeader() && version != null) { LOGGER.debug("Lock refresh key={} with version={}", lockKey, version); if (!cache.replaceWithVersion(lockKey, lockKey, version, (int)lifespanTimeUnit.toSeconds(lifespan))) { setLeader(false); } } if (!isLeader()) { Object result = cache.putIfAbsent(lockKey, lockValue, lifespan, lifespanTimeUnit); if (result == null) { setLeader(true); version = cache.getWithMetadata(lockKey).getVersion(); LOGGER.debug("Lock acquired key={} with version={}", lockKey, version); } else if (ObjectHelper.equal(lockValue, result) && !isLeader()) { setLeader(true); version = cache.getWithMetadata(lockKey).getVersion(); LOGGER.debug("Lock resumed key={} with version={}", lockKey, version); } else { setLeader(false); } } }

Target:
public void run() { if (!isRunAllowed() || !InfinispanRoutePolicy.this.isRunAllowed()) { return; } if (isLeader() && version != null) { LOGGER.debug("Lock refresh key={} with version={}", lockKey, version); if (!cache.replaceWithVersion(lockKey, lockValue, version, (int)lifespanTimeUnit.toSeconds(lifespan))) { setLeader(false); } } if (!isLeader()) { Object result = cache.putIfAbsent(lockKey, lockValue, lifespan, lifespanTimeUnit); if (result == null) { setLeader(true); version = cache.getWithMetadata(lockKey).getVersion(); LOGGER.debug("Lock acquired key={} with version={}", lockKey, version); } else if (ObjectHelper.equal(lockValue, result) && !isLeader()) { setLeader(true); version = cache.getWithMetadata(lockKey).getVersion(); LOGGER.debug("Lock resumed key={} with version={}", lockKey, version); } else { setLeader(false); } } }
Source:
public UrlValidation(String[] allowedSchemes) { if (allowedSchemes == null) { this.allowedSchemes.add(new String()); } else for (String scheme : allowedSchemes) { this.allowedSchemes.add(scheme.toLowerCase()); } }

Target:
public UrlValidation(String[] allowedSchemes) { if (allowedSchemes == null) { this.allowedSchemes.add(new String()); } else { for (String scheme : allowedSchemes) { this.allowedSchemes.add(scheme.toLowerCase()); } } }
Source:
public void activate() { try { Configuration configuration = configurationAdmin.getConfiguration(PID); encryptionKey = getOrGenerateEncryptionKey(configuration); } catch (IOException e) { logger.error("Cannot get configuration", e); } }

Target:
public void activate() throws NoSuchAlgorithmException, IOException { encryptionKey = getOrGenerateEncryptionKey(); }
Source:
public List<String> deleteRoleLayouts(final Role role, final Set<String> layoutIds, final LayoutAPI layoutAPI, final RoleAPI roleAPI, final SystemEventsAPI systemEventsAPI) throws DotDataException { final List<String> layoutsDeleted = new ArrayList<>(); for(final String toDeleteLayout : layoutIds) { final Layout layout = layoutAPI.findLayout(toDeleteLayout); if (null != layout && UtilMethods.isSet(layout.getId())) { if (roleAPI.hasLayoutToRole(layout, role)) { roleAPI.removeLayoutFromRole(layout, role); layoutsDeleted.add(layout.getId()); } } } systemEventsAPI.pushAsync(SystemEventType.DELETE_PORTLET_LAYOUTS, new Payload(layoutsDeleted)); return layoutsDeleted; }

Target:
public List<String> deleteRoleLayouts(final Role role, final Set<String> layoutIds, final LayoutAPI layoutAPI, final RoleAPI roleAPI, final SystemEventsAPI systemEventsAPI) throws DotDataException { final List<String> layoutsDeleted = new ArrayList<>(); for(final String toDeleteLayout : layoutIds) { final Layout layout = layoutAPI.findLayout(toDeleteLayout); if (null != layout && UtilMethods.isSet(layout.getId())) { if (roleAPI.roleHasLayout(layout, role)) { roleAPI.removeLayoutFromRole(layout, role); layoutsDeleted.add(layout.getId()); } } } systemEventsAPI.pushAsync(SystemEventType.DELETE_PORTLET_LAYOUTS, new Payload(layoutsDeleted)); return layoutsDeleted; }
Source:
public SearchMapping build() { SearchMapping mapping = new SearchMapping(); mapping .analyzerDef( "stemmer", StandardTokenizerFactory.class ) .filter( StandardFilterFactory.class ) .filter( LowerCaseFilterFactory.class ) .filter( StopFilterFactory.class ) .filter( SnowballPorterFilterFactory.class ) .param( "language", "English" ) .analyzerDef( "ngram", StandardTokenizerFactory.class ) .filter( StandardFilterFactory.class ) .filter( LowerCaseFilterFactory.class ) .filter( StopFilterFactory.class ) .filter( NGramFilterFactory.class ) .param( "minGramSize", "3" ) .param( "maxGramSize", "3" ) .analyzerDef( "htmlStrip", StandardTokenizerFactory.class ) .charFilter( HTMLStripCharFilterFactory.class ) .filter( LowerCaseFilterFactory.class ); return mapping; }

Target:
public SearchMapping build() { SearchMapping mapping = new SearchMapping(); mapping .analyzerDef( "stemmer", StandardTokenizerFactory.class ) .filter( StandardFilterFactory.class ) .filter( LowerCaseFilterFactory.class ) .filter( StopFilterFactory.class ) .filter( SnowballPorterFilterFactory.class ) .param( "language", "English" ) .analyzerDef( "ngram", StandardTokenizerFactory.class ) .filter( StandardFilterFactory.class ) .filter( LowerCaseFilterFactory.class ) .filter( StopFilterFactory.class ) .filter( NGramFilterFactory.class ) .param( "minGramSize", "3" ) .param( "maxGramSize", "3" ) .analyzerDef( "htmlStrip", StandardTokenizerFactory.class ) .charFilter( HTMLStripCharFilterFactory.class ) .param( "escapedTags", "escaped" ) .filter( LowerCaseFilterFactory.class ); return mapping; }
Source:
public void analyzeSource(File sourceFile) throws IOException { JavaProjectBuilder project = new JavaProjectBuilder(); if (sourceFile.isDirectory()) { project.addSourceTree(sourceFile); Collection<File> documentFiles = FileUtils.listFiles(sourceFile, new String[] { "adoc" }, true); for (File documentFile : documentFiles) { try (InputStream documentIn = new FileInputStream(documentFile)) { analyzeDocument(documentFile.getName(), documentIn); } } } else if (sourceFile.isFile() && sourceFile.getName().endsWith(".jar")) { try (ZipFile zipFile = new ZipFile(sourceFile)) { Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); String zipEntryName = zipEntry.getName(); if (zipEntryName.endsWith(".java")) { try (InputStream sourceIn = zipFile.getInputStream(zipEntry)) { try (Reader sourceReader = new InputStreamReader(sourceIn, Charset.forName("UTF-8"))) { project.addSource(sourceReader); } } } else if (zipEntryName.endsWith(".adoc")) { try (InputStream documentIn = zipFile.getInputStream(zipEntry)) { analyzeDocument(zipEntryName, documentIn); } } } } } else { throw new IOException( "Don't know how to parse source file \"" + sourceFile.getAbsolutePath() + "\", should be a " + "directory or a .jar file." ); } List<JavaClass> types = new ArrayList<>(); List<JavaClass> services = new ArrayList<>(); separateClasses(project, types, services); analyzeTypes(types); services.stream().filter(x -> !x.isInner()).forEach(this::analyzeService); fixUndefinedTypeUsages(); fixUndefinedServiceUsages(); parseConstraints(); }

Target:
public void analyzeSource(File sourceFile) throws IOException { JavaProjectBuilder project = new JavaProjectBuilder(); if (sourceFile.isDirectory()) { project.addSourceTree(sourceFile); Collection<File> documentFiles = FileUtils.listFiles(sourceFile, new String[] { "adoc" }, true); for (File documentFile : documentFiles) { try (InputStream documentIn = new FileInputStream(documentFile)) { analyzeDocument(documentFile.getName(), documentIn); } } } else if (sourceFile.isFile() && sourceFile.getName().endsWith(".jar")) { try (ZipFile zipFile = new ZipFile(sourceFile)) { Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); String zipEntryName = zipEntry.getName(); if (zipEntryName.endsWith(".java")) { try (InputStream sourceIn = zipFile.getInputStream(zipEntry)) { try (Reader sourceReader = new InputStreamReader(sourceIn, Charset.forName("UTF-8"))) { project.addSource(sourceReader); } } } else if (zipEntryName.endsWith(".adoc")) { try (InputStream documentIn = zipFile.getInputStream(zipEntry)) { analyzeDocument(zipEntryName, documentIn); } } } } } else { throw new IOException( "Don't know how to parse source file \"" + sourceFile.getAbsolutePath() + "\", should be a " + "directory or a .jar file." ); } List<JavaClass> types = new ArrayList<>(); List<JavaClass> services = new ArrayList<>(); separateClasses(project, types, services); analyzeTypes(types); analyzeServices(services); parseConstraints(); }
Source:
public HeaderPresenterWidget(EventBus eventBus, ViewDef view, CurrentUser user, SearchPanelPresenterWidget searchPanel, AboutPopupPresenterWidget aboutPopup, ConfigurePopupPresenterWidget configurePopup, ApplicationDynamicMessages dynamicMessages) { super(eventBus, view, user, WebAdminConfigurator.DOCUMENTATION_GUIDE_PATH, dynamicMessages.applicationDocTitle()); this.searchPanel = searchPanel; this.aboutPopup = aboutPopup; this.configurePopup = configurePopup; getView().setFeedbackLink(dynamicMessages.feedbackUrl()); }

Target:
public HeaderPresenterWidget(EventBus eventBus, ViewDef view, CurrentUser user, SearchPanelPresenterWidget searchPanel, AboutPopupPresenterWidget aboutPopup, ConfigurePopupPresenterWidget configurePopup, ApplicationDynamicMessages dynamicMessages) { super(eventBus, view, user, WebAdminConfigurator.DOCUMENTATION_GUIDE_PATH, dynamicMessages.applicationDocTitle()); this.searchPanel = searchPanel; this.aboutPopup = aboutPopup; this.configurePopup = configurePopup; final String feedbackLink = dynamicMessages.feedbackUrl(); if (feedbackLink != null && feedbackLink.length() > 0) { registerHandler(getView().getFeedbackImage().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { Window.open(feedbackLink, "_blank", null); } })); getView().getFeedbackImage().setVisible(true); } }
Source:
public void testShareSimpleFile() throws IOException { File file = new File(Constants.CACHE_DIR, filename); file.createNewFile(); embroideryFileExporter.shareEmbroideryFile(context, file); ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class); Mockito.verify(context, Mockito.times(1)).startActivity(captor.capture()); Intent chooserIntent = captor.getValue(); Intent shareIntent = chooserIntent.getParcelableExtra(Intent.EXTRA_INTENT); File dstFile = new File(Constants.CACHE_DIR, filename); Uri uriForFile = FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", dstFile); Intent compareShareIntent = new Intent(Intent.ACTION_SEND, uriForFile); compareShareIntent.setType("text/plain"); compareShareIntent.putExtra(Intent.EXTRA_STREAM, uriForFile); compareShareIntent.putExtra(Intent.EXTRA_SUBJECT, dstFile.getName()); Intent compareChooserIntent = new Intent(Intent.ACTION_CHOOSER); compareChooserIntent.putExtra(Intent.EXTRA_INTENT, compareShareIntent); compareChooserIntent.putExtra(Intent.EXTRA_TITLE, "Share embroidery file"); assertEquals(compareChooserIntent.toUri(0), chooserIntent.toUri(0)); assertEquals(compareShareIntent.toUri(0), shareIntent.toUri(0)); }

Target:
public void testShareSimpleFile() { File dstFile = new File(Constants.CACHE_DIR, filename); Uri uriForFile = FileProvider.getUriForFile(stageActivity, stageActivity.getPackageName() + ".fileProvider", dstFile); new ExportEmbroideryFileLauncher(stageActivity, dstFile).startActivity(); ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class); Mockito.verify(stageActivity, Mockito.times(1)).startActivity(captor.capture()); Intent actualChooserIntent = captor.getValue(); Intent actualShareIntent = actualChooserIntent.getParcelableExtra(Intent.EXTRA_INTENT); Intent expectedShareIntent = new Intent(Intent.ACTION_SEND, uriForFile); expectedShareIntent.setType("application/octet-stream"); expectedShareIntent.putExtra(Intent.EXTRA_STREAM, uriForFile); expectedShareIntent.putExtra(Intent.EXTRA_SUBJECT, dstFile.getName()); assertEquals(expectedShareIntent.toUri(0), actualShareIntent.toUri(0)); Intent expectedChooserIntent = new Intent(Intent.ACTION_CHOOSER); expectedChooserIntent.putExtra(Intent.EXTRA_INTENT, expectedShareIntent); expectedChooserIntent.putExtra(Intent.EXTRA_TITLE, "Share embroidery file"); assertEquals(expectedChooserIntent.toUri(0), actualChooserIntent.toUri(0)); }
Source:
public boolean doPreAddIdP(IdentityProvider identityProvider) throws IdentityProviderManagementException { log.debug("add new Identity Provider event received"); return true; }

Target:
public boolean doPreAddIdP(IdentityProvider identityProvider) throws IdentityProviderManagementException { if(log.isDebugEnabled()){ log.debug("add new Identity Provider event received"); } return true; }
Source:
public static int abandonAudioFocusRequest( @NonNull AudioManager audioManager, @NonNull AudioFocusRequestCompat focusRequest) { if (focusRequest == null) { throw new IllegalArgumentException("AudioFocusRequestCompat must not be null"); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { return audioManager.abandonAudioFocusRequest(focusRequest.getAudioFocusRequest()); } else { return audioManager.abandonAudioFocus(focusRequest.getOnAudioFocusChangeListener()); } }

Target:
public static int abandonAudioFocusRequest( @NonNull AudioManager audioManager, @NonNull AudioFocusRequestCompat focusRequest) { if (audioManager == null) { throw new IllegalArgumentException("AudioManager must not be null"); } if (focusRequest == null) { throw new IllegalArgumentException("AudioFocusRequestCompat must not be null"); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { return audioManager.abandonAudioFocusRequest(focusRequest.getAudioFocusRequest()); } else { return audioManager.abandonAudioFocus(focusRequest.getOnAudioFocusChangeListener()); } }
Source:
protected List<CompletableFuture<List<ICompletionProposal>>> buildCompletionFuturesOrJobs(int invocationOffset) { Set<IContentAssistProcessor> processors = null; try { processors= fContentAssistant.getContentAssistProcessors(getTokenContentType(invocationOffset)); } catch (BadLocationException e) { } if (processors == null) { return Collections.emptyList(); } List<CompletableFuture<List<ICompletionProposal>>> futures = new ArrayList<>(processors.size()); for (IContentAssistProcessor processor : processors) { futures.add(CompletableFuture.supplyAsync(() -> { @SuppressWarnings("unchecked") final List<ICompletionProposal>[] result= (List<ICompletionProposal>[]) new List<?>[1]; SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { ICompletionProposal[] proposals= processor.computeCompletionProposals(fViewer, invocationOffset); if (proposals == null) { result[0]= Collections.emptyList(); } result[0]= Arrays.asList(proposals); } }); if (result[0] == null) { return Collections.emptyList(); } return result[0]; })); } return futures; }

Target:
protected List<CompletableFuture<List<ICompletionProposal>>> buildCompletionFuturesOrJobs(int invocationOffset) { Set<IContentAssistProcessor> processors = null; try { processors= fContentAssistant.getContentAssistProcessors(getTokenContentType(invocationOffset)); } catch (BadLocationException e) { } if (processors == null) { return Collections.emptyList(); } List<CompletableFuture<List<ICompletionProposal>>> futures = new ArrayList<>(processors.size()); for (IContentAssistProcessor processor : processors) { futures.add(CompletableFuture.supplyAsync(() -> { AtomicReference<List<ICompletionProposal>> result= new AtomicReference<>(); SafeRunner.run(new ISafeRunnable() { @Override public void run() throws Exception { ICompletionProposal[] proposals= processor.computeCompletionProposals(fViewer, invocationOffset); if (proposals == null) { result.set(Collections.emptyList()); } result.set(Arrays.asList(proposals)); } }); List<ICompletionProposal> proposals= result.get(); if (proposals == null) { return Collections.emptyList(); } return proposals; })); } return futures; }
Source:
protected Text createFilterText(Composite parent) { filterText = new Text(parent, SWT.NONE); Dialog.applyDialogFont(filterText); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.CENTER; filterText.setLayoutData(data); filterText.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.CR) { gotoSelectedElement(); dispose(); } else if (e.keyCode == SWT.ARROW_DOWN) { delegate.getTreeViewer().getTree().setFocus(); } else if (e.character == SWT.ESC) { dispose(); } } }); filterText.setText(""); filterText.addModifyListener(e -> { AtomicBoolean firstMatchFound = new AtomicBoolean(false); TreeViewer viewer = delegate.getTreeViewer(); try { viewer.getControl().setRedraw(false); String text = filterText.getText(); if (StringUtils.isEmptyOrNull(text)) { viewer.setFilters(); } else { final SearchPattern pattern = new SearchPattern(); pattern.setPattern(text); viewer.setFilters(new ViewerFilter() { @Override public boolean select(Viewer v, Object parentElement, Object element) { boolean result = isMatch(pattern, element); if (result && element instanceof FileDiffRegion && !firstMatchFound.getAndSet(true)) { viewer.setSelection( new StructuredSelection(element)); } return result; } }); } viewer.expandAll(); } finally { viewer.getControl().setRedraw(true); } }); return filterText; }

Target:
protected Text createFilterText(Composite parent) { filterText = new Text(parent, SWT.NONE); Dialog.applyDialogFont(filterText); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.CENTER; filterText.setLayoutData(data); filterText.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.CR || e.character == '\r' || e.character == '\n') { gotoSelectedElement(); dispose(); } else if (e.keyCode == SWT.ARROW_DOWN) { delegate.getTreeViewer().getTree().setFocus(); } else if (e.character == SWT.ESC) { dispose(); } } }); filterText.setText(""); filterText.addModifyListener(e -> { TreeViewer viewer = delegate.getTreeViewer(); try { viewer.getControl().setRedraw(false); String text = filterText.getText(); if (StringUtils.isEmptyOrNull(text)) { viewer.setFilters(); } else { final SearchPattern pattern = new SearchPattern(); pattern.setPattern(text); viewer.setFilters(new ViewerFilter() { private boolean firstMatch = true; @Override public boolean select(Viewer v, Object parentElement, Object element) { boolean result = isMatch(pattern, element); if (result && element instanceof FileDiffRegion && firstMatch) { firstMatch = false; viewer.setSelection( new StructuredSelection(element)); } return result; } }); } viewer.expandAll(); } finally { viewer.getControl().setRedraw(true); } }); return filterText; }
Source:
public void setXssIgnoreUris(Set<String> xssIgnoreUris) { if (xssIgnoreUris == null) { this.xssIgnoreUris = emptySet(); } else { Set<UriPatten> xssIgnoreUriPatterns = new HashSet<>(); for (String xssUri : xssIgnoreUris) { if (xssUri == null) { throw new IllegalArgumentException("XSS ignore URI cannot be null."); } else if (xssUri.isEmpty()) { throw new IllegalArgumentException("XSS ignore URI cannot be empty."); } xssIgnoreUriPatterns.add(new UriPatten(xssUri)); } this.xssIgnoreUris = unmodifiableSet(xssIgnoreUriPatterns); } }

Target:
public void setXssIgnoreUris(Set<String> xssIgnoreUris) { if (xssIgnoreUris == null) { this.xssIgnoreUris = emptySet(); } else { Set<UriPatten> xssIgnoreUriPatterns = new HashSet<>(); for (String xssUri : xssIgnoreUris) { if (xssUri == null) { throw new IllegalArgumentException("XSS ignore URI pattern cannot be null."); } else if (xssUri.isEmpty()) { throw new IllegalArgumentException("XSS ignore URI pattern cannot be empty."); } try { xssIgnoreUriPatterns.add(new UriPatten(xssUri)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("XSS ignore URI pattern '" + xssUri + "' is invalid.", e); } } this.xssIgnoreUris = unmodifiableSet(xssIgnoreUriPatterns); } }
Source:
private static boolean hasReachedGlobalQuorum(Map<String, Integer> totalNumberInDcs, Map<String, Integer> currentNumberInDcs) { boolean hasReached = true; if (totalNumberInDcs.size() == currentNumberInDcs.size()) { for (String dcName : totalNumberInDcs.keySet()) { int totalNum = totalNumberInDcs.get(dcName); int currentNum = currentNumberInDcs.get(dcName); if (totalNum != 1 && currentNum <= totalNum / 2) { hasReached = false; break; } } } else { hasReached = false; } return hasReached; }

Target:
static boolean hasReachedGlobalQuorum(Map<String, Integer> totalNumberInDcs, Map<String, Integer> currentNumberInDcs) { boolean hasReached = true; if (totalNumberInDcs.size() == currentNumberInDcs.size()) { for (String dcName : totalNumberInDcs.keySet()) { int totalNum = totalNumberInDcs.get(dcName); int currentNum = currentNumberInDcs.getOrDefault(dcName, 0); if (currentNum <= totalNum / 2) { hasReached = false; break; } } } else { hasReached = false; } return hasReached; }
Source:
public UpsertByIdWithDurability<T> withExpiry(final Duration expiry) { Assert.notNull(persistTo, "PersistTo must not be null."); Assert.notNull(replicateTo, "ReplicateTo must not be null."); return new ExecutableUpsertByIdSupport<>(template, domainType, collection, persistTo, replicateTo, durabilityLevel, expiry); }

Target:
public UpsertByIdWithDurability<T> withExpiry(final Duration expiry) { Assert.notNull(expiry, "expiry must not be null."); return new ExecutableUpsertByIdSupport<>(template, domainType, collection, persistTo, replicateTo, durabilityLevel, expiry); }
Source:
public void removeVariable(final Variable variable) { fVariables.remove(variable); }

Target:
public void removeVariable(final Variable variable) { fVariables.remove(variable); fDirty = true; }
Source:
public void beforeTest() throws IOException { bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout)); bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout)); try { DeleteJobTemplate.deleteJobTemplate(PROJECT_ID, LOCATION, TEMPLATE_ID); } catch (GoogleJsonResponseException gjre) { } try { CreateJobTemplate.createJobTemplate(PROJECT_ID, LOCATION, TEMPLATE_ID); } catch (GoogleJsonResponseException gjre) { } bout.reset(); }

Target:
public void beforeTest() throws IOException { originalOut = System.out; bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout)); bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout)); DeleteJobTemplate.deleteJobTemplate(PROJECT_ID, LOCATION, TEMPLATE_ID); CreateJobTemplate.createJobTemplate(PROJECT_ID, LOCATION, TEMPLATE_ID); bout.reset(); }
Source:
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { ExecutionStatistics.get().begin(NAME); if (arguments.size() != 1) throw new TemplateModelException("Error, method expects one argument (" + FileModel.class.getSimpleName() + ")"); System.out.println("HHHHHHH getTagsFromFileClassificationsAndHints"); StringModel stringModelArg = (StringModel) arguments.get(0); FileModel fileModel = (FileModel) stringModelArg.getWrappedObject(); Set<String> tags = this.findTagsFromFileClassificationsAndHints(fileModel); ExecutionStatistics.get().end(NAME); return tags; }

Target:
public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { ExecutionStatistics.get().begin(NAME); if (arguments.size() != 1) throw new TemplateModelException("Error, method expects one argument (" + FileModel.class.getSimpleName() + ")"); StringModel stringModelArg = (StringModel) arguments.get(0); FileModel fileModel = (FileModel) stringModelArg.getWrappedObject(); Set<String> tags = this.findTagsFromFileClassificationsAndHints(fileModel); ExecutionStatistics.get().end(NAME); return tags; }
Source:
public void setGeoJsonLayer(AirMapGeoJsonLayer airMapGeoJsonLayer) { clearGeoJsonLayer(); try { layerOnMap = new GeoJsonLayer(getMap(), new JSONObject(airMapGeoJsonLayer.geoJson)); } catch (JSONException e) { Log.e(TAG, "Failed to add GeoJson layer", e); return; } layerOnMap.getDefaultPolygonStyle().setStrokeColor(airMapGeoJsonLayer.strokeColor); layerOnMap.getDefaultPolygonStyle().setStrokeWidth(airMapGeoJsonLayer.strokeWidth); layerOnMap.getDefaultPolygonStyle().setFillColor(airMapGeoJsonLayer.fillColor); layerOnMap.addLayerToMap(); }

Target:
public void setGeoJsonLayer(AirMapGeoJsonLayer airMapGeoJsonLayer) throws JSONException { clearGeoJsonLayer(); layerOnMap = new GeoJsonLayer(getMap(), new JSONObject(airMapGeoJsonLayer.geoJson)); GeoJsonPolygonStyle style = layerOnMap.getDefaultPolygonStyle(); style.setStrokeColor(airMapGeoJsonLayer.strokeColor); style.setStrokeWidth(airMapGeoJsonLayer.strokeWidth); style.setFillColor(airMapGeoJsonLayer.fillColor); layerOnMap.addLayerToMap(); }
Source:
static RuntimeException handleAutobatcherExceptions(Exception e) { if (e instanceof ExecutionException) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new RuntimeException(cause); } else { Thread.currentThread().interrupt(); throw new RuntimeException(e); } }

Target:
static RuntimeException handleAutobatcherExceptions(Exception e) { if (e instanceof ExecutionException) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new RuntimeException(cause); } else { Preconditions.checkArgument(e instanceof InterruptedException, "expected Interrupted exception"); Thread.currentThread().interrupt(); throw new RuntimeException(e); } }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof ITuple)) return false; final ITuple other = (ITuple) obj; if (cachedHash != other.hashCode()) return false; return internalEquals(other); }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj instanceof ITuple) { final ITuple other = (ITuple) obj; return cachedHash == other.hashCode() && internalEquals(other); } return false; }