auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void initializeRunId(){ LOG.info("Manasa: LocalApplicationRunner: getRunId() : entered "); Boolean isAppModeBatch = new ApplicationConfig(appDesc.getConfig()).getAppMode() == ApplicationConfig.ApplicationMode.BATCH; if(coordinationUtils == null || !isAppModeBatch) { return; } runIdLock = coordinationUtils.getReadWriteLock(CoordinationConstants.RUNID_LOCK_ID); runIdAccess = coordinationUtils.getDataAccess(); if(runIdAccess == null || runIdLock == null) { LOG.warn("Processor failed to create utils for run.id generation", uid); return; } try { DistributedReadWriteLock.AccessType lockAccess = runIdLock.lock(CoordinationConstants.LOCK_TIMEOUT_MS, TimeUnit.MILLISECONDS); if(lockAccess == DistributedReadWriteLock.AccessType.WRITE) { LOG.info("write lock acquired for run.id generation by Processor " + uid); runId = String.valueOf(System.currentTimeMillis()) + "-" + UUID.randomUUID().toString().substring(0, 8); LOG.info("The run id for this run is {}", runId); runIdAccess.writeData(CoordinationConstants.RUNID_PATH, runId, new LocalDistributedDataWatcher()); runIdLock.unlock(); } else if(lockAccess == DistributedReadWriteLock.AccessType.READ) { LOG.info("read lock acquired for run.id by Processor " + uid); runId = (String) runIdAccess.readData(CoordinationConstants.RUNID_PATH, new LocalDistributedDataWatcher()); runIdLock.unlock(); } else { String msg = String.format("Processor failed to get the lock for run.id", uid); throw new SamzaException(msg); } } catch (TimeoutException e) { String msg = String.format("Processor timed out waiting to acquire lock for run.id generation", uid); throw new SamzaException(msg, e); } }

Target:
private void initializeRunId() { if (!isAppModeBatch) { LOG.info("Not BATCH mode and hence not generating run id"); return; } if (!coordinationUtils.isPresent()) { LOG.warn("Coordination utils not present. Aborting run id generation. Will continue execution without a run id."); return; } try { MetadataStore metadataStore = getMetadataStore(); runIdGenerator = Optional.of(new RunIdGenerator(coordinationUtils.get(), metadataStore)); runId = runIdGenerator.flatMap(RunIdGenerator::getRunId); } catch (Exception e) { LOG.warn("Failed to generate run id. Will continue execution without a run id. Caused by {}", e); } }
Source:
public void removeListener() { if (!stereotypeList.isEmpty()) { if (comment != null) { for (Stereotype stereotype : stereotypeList) { getDiagramEventBroker().removeNotificationListener(helper.getStereotypeCompartment(comment, stereotype), this); getDiagramEventBroker().removeNotificationListener(helper.getStereotypeBraceCompartment(comment, stereotype), this); } } } }

Target:
public void removeListener() { if (!stereotypeList.isEmpty()) { if (null != comment) { for (Stereotype stereotype : stereotypeList) { getDiagramEventBroker().removeNotificationListener(helper.getStereotypeCompartment(comment, stereotype), this); getDiagramEventBroker().removeNotificationListener(helper.getStereotypeBraceCompartment(comment, stereotype), this); } } } }
Source:
void testNumberOfCellsByExperimentAccession(String experimentAccession) { cleanDatabaseTables(); populator.setScripts(new ClassPathResource("fixtures/scxa_tsne-full.sql")); populator.execute(dataSource); Map<Integer, AtlasResource<TsvStreamer>> resource = new DataFileHub(dataFilesPath.resolve("scxa")) .getSingleCellExperimentFiles(experimentAccession).tSnePlotTsvs; Map.Entry<Integer, AtlasResource<TsvStreamer>> firstFile = resource.entrySet().iterator().next(); Stream<String[]> fileContent = firstFile.getValue().get().get(); Integer fileContentLines = Math.toIntExact(fileContent.count()); Integer numberOfcells = subject.fetchCellNumberByExperimentAccession(experimentAccession); assertThat(numberOfcells) .isEqualTo(fileContentLines-1); cleanDatabaseTables(); populateDatabaseTables(); }

Target:
void testNumberOfCellsByExperimentAccession(String experimentAccession) { cleanDatabaseTables(); populator.setScripts(new ClassPathResource("fixtures/scxa_tsne-full.sql")); populator.execute(dataSource); Map<Integer, AtlasResource<TsvStreamer>> resource = new DataFileHub(dataFilesPath.resolve("scxa")) .getSingleCellExperimentFiles(experimentAccession).tSnePlotTsvs; Map.Entry<Integer, AtlasResource<TsvStreamer>> firstFile = resource.entrySet().iterator().next(); Stream<String[]> fileContent = firstFile.getValue().get().get(); Integer fileContentLines = Math.toIntExact(fileContent.count()); Integer numberOfcells = subject.fetchNumberOfCellsByExperimentAccession(experimentAccession); assertThat(numberOfcells) .isEqualTo(fileContentLines-1); cleanDatabaseTables(); populateDatabaseTables(); }
Source:
public CachingContext(ExperimentsCache cache, Experiment.BuilderFactory builderFactory, ExecutorService executorService) { this.cache = cache; this.builderFactory = builderFactory; this.executorService = executorService != null ? executorService : Executors.newSingleThreadExecutor(); this.ownsExecutorService = executorService == null; this.experimentLocks = Maps.newConcurrentMap(); this.lock = new ReentrantLock(); }

Target:
public CachingContext(ExperimentsCache cache, Experiment.BuilderFactory builderFactory, ExecutorService executorService) { this.cache = cache; this.builderFactory = builderFactory; this.executorService = executorService != null ? executorService : Executors.newSingleThreadExecutor(); this.ownsExecutorService = executorService == null; this.experimentLocks = Maps.newConcurrentMap(); this.lock = new AtomicBoolean(false); }
Source:
public void testProxyUriUnexpectedWidgetType() { ItemUIRegistry itemUIRegistry = mock(ItemUIRegistry.class); ModelRepository modelRepository = mock(ModelRepository.class); Sitemap sitemap = mock(Sitemap.class); Switch widget = mock(Switch.class); HttpServletRequest request = mock(HttpServletRequest.class); service.setModelRepository(modelRepository); service.setItemUIRegistry(itemUIRegistry); when(request.getParameter(eq("sitemap"))).thenReturn("testSitemap"); when(request.getParameter(eq("widgetId"))).thenReturn("testWidget"); when(modelRepository.getModel(eq("testSitemap"))).thenReturn(sitemap); when(itemUIRegistry.getWidget(eq(sitemap), eq("testWidget"))).thenReturn(widget); URI uri = service.uriFromRequest(request); assertNull(uri); }

Target:
public void testProxyUriUnexpectedWidgetType() { when(request.getParameter(eq("widgetId"))).thenReturn(SWITCH_WIDGET_ID); URI uri = service.uriFromRequest(request); assertNull(uri); }
Source:
public static Slice stPoint(@SqlType(StandardTypes.DOUBLE) double x, @SqlType(StandardTypes.DOUBLE) double y) { OGCGeometry geometry = getGeometry(OGCGeometry.createFromEsriGeometry(new Point(x, y), null), "ST_Point", POINT); return serialize(geometry); }

Target:
public static Slice stPoint(@SqlType(StandardTypes.DOUBLE) double x, @SqlType(StandardTypes.DOUBLE) double y) { OGCGeometry geometry = createFromEsriGeometry(new Point(x, y), null); return serialize(geometry); }
Source:
AbstractApplication loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Class<?> appClass; try { log.debug("Trying to load application as class on classpath"); appClass = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { log.debug("Loading as class on classpath failed, now trying as .groovy file"); String content = utils.getResourceAsString(app); appClass = loader.parseClass(content); } Constructor<?> constructor = appClass.getConstructor(); return (AbstractApplication) constructor.newInstance(); }

Target:
AbstractApplication loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Class<?> appClass; try { log.debug("Trying to load application as class on classpath: {}", app); appClass = loader.loadClass(app, true, false); } catch (ClassNotFoundException cnfe) { log.debug("Loading \"{}\" as class on classpath failed, now trying as .groovy source file",app); String content = utils.getResourceAsString(app); appClass = loader.parseClass(content); } Constructor<?> constructor = appClass.getConstructor(); return (AbstractApplication) constructor.newInstance(); }
Source:
public final ProtoSubject message(int index) { if (messages() == null) { failWithActual(fact(FactKey.ACTUAL.value, null)); return ignoreCheck().about(protos()) .that(Empty.getDefaultInstance()); } int size = size(messages()); if (index >= size(messages())) { failWithActual( fact(FactKey.MESSAGE_COUNT.value, size), fact(FactKey.REQUESTED_INDEX.value, index) ); return ignoreCheck().about(protos()) .that(Empty.getDefaultInstance()); } T outerObject = Iterables.get(messages(), index); Message unpacked = AnyPacker.unpack(outerObject.getMessage()); return ProtoTruth.assertThat(unpacked); }

Target:
public final ProtoSubject message(int index) { if (messages() == null) { failWithActual(fact(ACTUAL.value, null)); return ignoreCheck().about(protos()) .that(Empty.getDefaultInstance()); } int size = size(messages()); if (index >= size(messages())) { failWithActual( fact(MESSAGE_COUNT.value, size), fact(REQUESTED_INDEX.value, index) ); return ignoreCheck().about(protos()) .that(Empty.getDefaultInstance()); } T outerObject = Iterables.get(messages(), index); Message unpacked = AnyPacker.unpack(outerObject.getMessage()); return ProtoTruth.assertThat(unpacked); }
Source:
void cancelFocusAndMetering() { if (mCurrentFocusMeteringAction != null) { mCurrentFocusMeteringAction.notifyAutoFocusCompleted(false); } disableAutoCancel(); if (shouldTriggerAF()) { mCameraControl.cancelAfAeTriggerInternal(true, false); } mAfRects = new MeteringRectangle[]{}; mAeRects = new MeteringRectangle[]{}; mAwbRects = new MeteringRectangle[]{}; mCameraControl.setIsInAfAutoMode(false); mCameraControl.updateSessionConfig(); mCurrentFocusMeteringAction = null; }

Target:
void cancelFocusAndMetering() { mCameraControl.removeCaptureResultListener(mSessionListenerForFocus); if (mCurrentFocusMeteringAction != null) { mCurrentFocusMeteringAction.notifyAutoFocusCompleted(false); } disableAutoCancel(); if (shouldTriggerAF()) { mCameraControl.cancelAfAeTriggerInternal(true, false); } mAfRects = new MeteringRectangle[]{}; mAeRects = new MeteringRectangle[]{}; mAwbRects = new MeteringRectangle[]{}; mIsInAfAutoMode = false; mCameraControl.updateSessionConfig(); mCurrentFocusMeteringAction = null; }
Source:
static FileBasedSystemAccessControlRules parse(byte[] json) { ObjectMapper mapper = new ObjectMapperProvider().get() .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); Class<FileBasedSystemAccessControlRules> javaType = FileBasedSystemAccessControlRules.class; try { return mapper.readValue(json, javaType); } catch (IOException e) { throw new IllegalArgumentException(format("Invalid JSON string for %s", javaType), e); } }

Target:
private static FileBasedSystemAccessControlRules parse(byte[] json) { ObjectMapper mapper = new ObjectMapperProvider().get() .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); Class<FileBasedSystemAccessControlRules> javaType = FileBasedSystemAccessControlRules.class; try { return mapper.readValue(json, javaType); } catch (IOException e) { throw new IllegalArgumentException(format("Invalid JSON string for %s", javaType), e); } }
Source:
private void invoke(String... parameters) { CmdLineParser parser = new CmdLineParser(this); try { try { parser.parseArgument(parameters); if (inputFiles.isEmpty()) { throw new CmdLineException(parser, "asciidoctor: FAILED: input file missing"); } } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.exit(1); return; } ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile)); byte[] buf = new byte[BUFSIZ]; for (String inputFile : inputFiles) { Options options = createOptions(inputFile); renderInput(options, inputFile); FileInputStream f = new FileInputStream(new File(mapInFileToOutFileWithDir(inputFile))); int len; zip.putNextEntry(new ZipEntry(mapInFileToOutFile(inputFile))); while ((len = f.read(buf)) > 0) { zip.write(buf, 0, len); } f.close(); zip.closeEntry(); } zip.close(); } catch (java.io.IOException e) { System.err.println(e.getMessage()); System.exit(1); } }

Target:
private void invoke(String... parameters) throws IOException { CmdLineParser parser = new CmdLineParser(this); try { parser.parseArgument(parameters); if (inputFiles.isEmpty()) { throw new CmdLineException(parser, "asciidoctor: FAILED: input file missing"); } } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.exit(1); return; } ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile)); byte[] buf = new byte[BUFSIZ]; for (String inputFile : inputFiles) { File tmp = File.createTempFile("doc", ".html"); tmp.deleteOnExit(); Options options = createOptions(tmp); renderInput(options, inputFile); FileInputStream f = new FileInputStream(tmp); int len; zip.putNextEntry(new ZipEntry(mapInFileToOutFile(inputFile))); while ((len = f.read(buf)) > 0) { zip.write(buf, 0, len); } f.close(); zip.closeEntry(); } zip.close(); }
Source:
public boolean isCompatible(String otherMimeType) { return mimeType.equalsIgnoreCase(otherMimeType) || otherMimeType.startsWith(mimeType); }

Target:
public boolean isCompatible(String otherMimeType) { return mimeType.equalsIgnoreCase(otherMimeType) || (otherMimeType != null && otherMimeType.toLowerCase().startsWith(mimeType.toLowerCase())); }
Source:
protected Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type, LUNs lun, Guid storagePoolId) { if (FeatureSupported.refreshLunSupported(DbFacade.getInstance() .getStoragePoolDao() .get(storagePoolId) .getCompatibilityVersion())) { List<StorageServerConnections> list = new ArrayList<>(); list.add(getFCPConnection()); VDSReturnValue returnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.forValue(type), new StorageServerConnectionManagementVDSParameters(vdsId, storagePoolId, StorageType.FCP, list)); boolean isSuccess = returnValue.getSucceeded(); EngineFault engineFault = null; if (!isSuccess && returnValue.getVdsError() != null) { engineFault = new EngineFault(); engineFault.setError(returnValue.getVdsError().getCode()); } return new Pair<>(isSuccess, engineFault); } else { return new Pair<>(true, null); } }

Target:
protected Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type, LUNs lun, Guid storagePoolId) { if(storagePoolId == null || storagePoolId.equals(Guid.Empty)){ return new Pair<>(false, null); } if (FeatureSupported.refreshLunSupported(DbFacade.getInstance() .getStoragePoolDao() .get(storagePoolId) .getCompatibilityVersion())) { VDSReturnValue returnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.forValue(type), new StorageServerConnectionManagementVDSParameters(vdsId, storagePoolId, StorageType.FCP, Arrays.asList(getFCPConnection()))); boolean isSuccess = returnValue.getSucceeded(); EngineFault engineFault = null; if (!isSuccess && returnValue.getVdsError() != null) { engineFault = new EngineFault(); engineFault.setError(returnValue.getVdsError().getCode()); } return new Pair<>(isSuccess, engineFault); } else { return new Pair<>(true, null); } }
Source:
public void addColumn(Column<T, ?> column, Header<?> header) { Header<?> wrappedHeader = (columnResizingEnabled && header instanceof CheckboxHeader) ? new ResizeableCheckboxHeader<T>((CheckboxHeader) header, column, this) : header; super.addColumn(column, wrappedHeader); if (columnResizingEnabled) { if (emptyNoWidthColumn != null) { removeColumn(emptyNoWidthColumn); } emptyNoWidthColumn = new EmptyColumn<T>(); addColumn(emptyNoWidthColumn); } }

Target:
public void addColumn(Column<T, ?> column, Header<?> header) { super.addColumn(column, wrapHeader(header, column)); if (columnResizingEnabled) { if (emptyNoWidthColumn != null) { removeColumn(emptyNoWidthColumn); } emptyNoWidthColumn = new EmptyColumn<T>(); addColumn(emptyNoWidthColumn); } }
Source:
private void unlockImageInDb() { DiskImage diskImage = getDiskImage(); diskImage.setImageStatus(ImageStatus.OK); ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.OK); }

Target:
private void unlockImageInDb() { DiskImage diskImage = getDiskImage(); ImagesHandler.updateImageStatus(diskImage.getImageId(), ImageStatus.OK); }
Source:
public void processSoftwareCapabilities(VDS vds) { boolean softwareCapabilitiesAreMet = true; if (vds.getKvmEnabled() != null && vds.getKvmEnabled().equals(false)) { softwareCapabilitiesAreMet = false; } if (!softwareCapabilitiesAreMet && vds.getStatus() != VDSStatus.NonOperational) { vdsNonOperational(vds); vds.setStatus(VDSStatus.NonOperational); } }

Target:
public void processSoftwareCapabilities(VDS vds) { if (vds.getKvmEnabled() != null && vds.getKvmEnabled().equals(false) && vds.getStatus() != VDSStatus.NonOperational) { vdsNonOperational(vds, NonOperationalReason.KVM_NOT_RUNNING, null); vds.setStatus(VDSStatus.NonOperational); } VDSGroup vdsGroup = DbFacade.getInstance().getVdsGroupDao().get(vds.getVdsGroupId()); if (!hostCompliesWithClusterEmulationMode(vds, vdsGroup) && vds.getStatus() != VDSStatus.NonOperational) { Map<String, String> customLogValues = new HashMap<>(); customLogValues.put("hostSupportedEmulatedMachines", vds.getSupportedEmulatedMachines()); customLogValues.put("clusterEmulatedMachines", StringUtils.isEmpty(vdsGroup.getEmulatedMachine()) ? Config.<String>GetValue(ConfigValues.ClusterEmulatedMachines, vds.getVdsGroupCompatibilityVersion().getValue()) : vdsGroup.getEmulatedMachine()); vdsNonOperational(vds, NonOperationalReason.EMULATED_MACHINES_INCOMPATIBLE_WITH_CLUSTER, customLogValues); vds.setStatus(VDSStatus.NonOperational); } }
Source:
protected void setNavMenuItems() { navMenu = new NavDrawerItem[] { NavMenuItem.create(SWITCH_MODE, getResources().getString(R.string.switch_to_client), "ic_action_client_mode", false, this), NavMenuItem.create(LOGOUT, getResources().getString(R.string.logout), "ic_logout", false, this) }; }

Target:
protected void setNavMenuItems() { navMenu = new NavDrawerItem[] { NavMenuItem.create(SWITCH_MODE, getResources().getString(R.string.switch_to_client), "ic_action_client_mode", false, this), LogoutMenuItem.create(this) }; }
Source:
public final void run() { doRun(); fHasDrawnEntries = true; fDirty.decrementAndGet(); }

Target:
public final void run() { doRun(); fDirty.decrementAndGet(); }
Source:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = super.onCreateView(inflater, container, savedInstanceState); Bundle args = getArguments(); LocalFileLocation rootPath = null; checkReadStoragePermission(); try { if (http_app == null) { http_app = HttpApp.getInstance(getContext(), 8080); } } catch (IOException ioe) { Toast.makeText(getContext(), getString(R.string.error_starting_http_server), Toast.LENGTH_LONG); } if (args != null) { rootPath = args.getParcelable(ROOT_PATH); this.rootPathLocation = args.getString(ROOT_PATH_LOCATION); mediaType = args.getString(MEDIA_TYPE, Files.Media.FILES); sortMethod = args.getParcelable(SORT_METHOD); } hostManager = HostManager.getInstance(getActivity()); getEmptyView().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!atRootDirectory()) browseSources(); } }); if (savedInstanceState != null) { mediaType = savedInstanceState.getString(MEDIA_TYPE, Files.Media.FILES); sortMethod = savedInstanceState.getParcelable(SORT_METHOD); ArrayList<LocalFileLocation> list = savedInstanceState.getParcelableArrayList(PATH_CONTENTS); rootFileLocation = savedInstanceState.getParcelableArrayList(ROOT_PATH_CONTENTS); browseRootAlready = savedInstanceState.getBoolean(ROOT_VISITED); ((MediaPictureListAdapter) getAdapter()).setFilelistItems(list); } else if (rootPath != null) { loadOnVisible = rootPath; setUserVisibleHint(getUserVisibleHint() || !args.getBoolean(DELAY_LOAD, false)); } else { browseSources(); } return root; }

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = super.onCreateView(inflater, container, savedInstanceState); Bundle args = getArguments(); LocalFileLocation rootPath = null; checkReadStoragePermission(); try { if (http_app == null) { http_app = HttpApp.getInstance(getContext(), 8080); } } catch (IOException ioe) { Toast.makeText(getContext(), getString(R.string.error_starting_http_server), Toast.LENGTH_LONG).show(); } if (args != null) { rootPath = args.getParcelable(ROOT_PATH); this.rootPathLocation = args.getString(ROOT_PATH_LOCATION); mediaType = args.getString(MEDIA_TYPE, Files.Media.FILES); sortMethod = args.getParcelable(SORT_METHOD); } hostManager = HostManager.getInstance(getActivity()); getEmptyView().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!atRootDirectory()) browseSources(); } }); if (savedInstanceState != null) { mediaType = savedInstanceState.getString(MEDIA_TYPE, Files.Media.FILES); sortMethod = savedInstanceState.getParcelable(SORT_METHOD); ArrayList<LocalFileLocation> list = savedInstanceState.getParcelableArrayList(PATH_CONTENTS); rootFileLocation = savedInstanceState.getParcelableArrayList(ROOT_PATH_CONTENTS); browseRootAlready = savedInstanceState.getBoolean(ROOT_VISITED); ((MediaPictureListAdapter) getAdapter()).setFilelistItems(list); } else if (rootPath != null) { loadOnVisible = rootPath; setUserVisibleHint(getUserVisibleHint() || !args.getBoolean(DELAY_LOAD, false)); } else { browseSources(); } return root; }
Source:
private static void validateClause(Map<String, Object> clause) throws QueryException { List<String> validOperators = Arrays.asList(EQ, LT, GT, EXISTS, NOT, GTE, LTE, IN, MOD, SIZE); if (clause.size() == 1) { String operator = (String) clause.keySet().toArray()[0]; if (validOperators.contains(operator)) { Object clauseOperand = clause.get(operator); if (operator.equals(NOT)) { if (!(clauseOperand instanceof Map)) { throw new QueryException("clauseOperand not instance of Map"); } validateClause((Map) clauseOperand); } else if (operator.equals(IN)) { if (!(clauseOperand instanceof List)) { throw new QueryException("clauseOperand not instance of List"); } validateInListValues((List<Object>) clauseOperand); } else { validatePredicateValue(clauseOperand, operator); } } else { throw new QueryException(String.format(Locale.ENGLISH, "%s not a valid operator", operator)); } } else { throw new QueryException("Clause must only have one key"); } }

Target:
private static void validateClause(Map<String, Object> clause) throws QueryException { List<String> validOperators = Arrays.asList(EQ, LT, GT, EXISTS, NOT, GTE, LTE, IN, MOD, SIZE); if (clause.size() == 1) { String operator = (String) clause.keySet().toArray()[0]; if (validOperators.contains(operator)) { Object clauseOperand = clause.get(operator); if (operator.equals(NOT)) { if (!(clauseOperand instanceof Map)) { throw new QueryException(String.format(Locale.ENGLISH, "clauseOperand %s is not an instance of Map", clauseOperand)); } validateClause((Map) clauseOperand); } else if (operator.equals(IN)) { if (!(clauseOperand instanceof List)) { throw new QueryException(String.format(Locale.ENGLISH, "clauseOperand %s is not an instance of List", clauseOperand)); } validateInListValues((List<Object>) clauseOperand); } else { validatePredicateValue(clauseOperand, operator); } } else { throw new QueryException(String.format(Locale.ENGLISH, "operator %s is not a valid operator", operator)); } } else { throw new QueryException(String.format(Locale.ENGLISH, "Clause %s must only have one key", clause)); } }
Source:
public void setLastAccessTime(long lastAccessTime, TimeUnit unit) { while (true) { long read = this.lastAccessTime; if (read >= lastAccessTime) { break; } if (ACCESSTIME_UPDATER.compareAndSet(this, read, unit.convert(lastAccessTime, nativeTimeUnit()))) { break; } } }

Target:
public void setLastAccessTime(long lastAccessTime, TimeUnit unit) { long update = unit.convert(lastAccessTime, nativeTimeUnit()); while (true) { long current = this.lastAccessTime; if (current >= update) { break; } if (ACCESSTIME_UPDATER.compareAndSet(this, current, update)) { break; } }; }
Source:
private void addPreferenceChangeListener() { IEclipsePreferences pref = (IEclipsePreferences) Platform.getPreferencesService().getRootNode().node(InstanceScope.SCOPE).node(ResourcesPlugin.PI_RESOURCES); if (pref != null) { pref.addPreferenceChangeListener(this); fileWalkerConcurrencyLevel = pref.getInt(ResourcesPlugin.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL, PreferenceInitializer.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL_DEFAULT); } else { fileWalkerConcurrencyLevel = PreferenceInitializer.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL_DEFAULT; } }

Target:
private void addPreferenceChangeListener() { IPreferencesService preferencesService = Platform.getPreferencesService(); fileWalkerConcurrencyLevel = preferencesService.getInt(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL, PreferenceInitializer.PREF_NIO2_REFRESH_FILE_WALKER_CONCURRENCY_LEVEL_DEFAULT, null); }
Source:
private void updateFromSourceField() { if (sourceNameField.getText().contentEquals(currentSourceName)) { return; } setSourceName(sourceNameField.getText()); updateWidgetEnablements(); fileSystemStructureProvider.clearVisitedDirs(); selectionGroup.setFocus(); }

Target:
private void updateFromSourceField() { String sourceNameFieldText = sourceNameField.getText(); if (sourceNameFieldText.equals(currentSourceName)) { return; } setSourceName(sourceNameFieldText); updateWidgetEnablements(); fileSystemStructureProvider.clearVisitedDirs(); selectionGroup.setFocus(); }
Source:
private void broadcastCallScreeningAppChangedIntent(String componentName, boolean isDefault) { Intent intentForNewCallScreeningApp = new Intent(TelecomManager .ACTION_DEFAULT_CALL_SCREENING_APP_CHANGED); intentForNewCallScreeningApp.putExtra(TelecomManager .EXTRA_IS_DEFAULT_CALL_SCREENING_APP, isDefault); intentForNewCallScreeningApp.putExtra(TelecomManager .EXTRA_DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME, componentName); intentForNewCallScreeningApp.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); mContext.sendBroadcast(intentForNewCallScreeningApp); }

Target:
private void broadcastCallScreeningAppChangedIntent(String componentName, boolean isDefault) { if (TextUtils.isEmpty(componentName)) { return; } ComponentName broadcastComponentName = ComponentName.unflattenFromString(componentName); if (broadcastComponentName != null) { Intent intent = new Intent(TelecomManager .ACTION_DEFAULT_CALL_SCREENING_APP_CHANGED); intent.putExtra(TelecomManager .EXTRA_IS_DEFAULT_CALL_SCREENING_APP, isDefault); intent.putExtra(TelecomManager .EXTRA_DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME, componentName); intent.setPackage(broadcastComponentName.getPackageName()); mContext.sendBroadcast(intent); } }
Source:
private int checkMouseDownListener(Control c) { Listener[] listeners = c.getListeners(SWT.MouseDown); List<TypedListener> typedListeners = new ArrayList<TypedListener>(); for (Listener l : listeners) { if (l instanceof TypedListener) { TypedListener tl = (TypedListener) l; if (tl.getEventListener() .toString() .contains("org.eclipse.mylyn.internal.reviews.ui.annotations.CommentPopupDialog")) { typedListeners.add(tl); } } } assertEquals(1, typedListeners.size()); return typedListeners.size(); }

Target:
private void checkMouseDownListener(Control c) { Listener[] listeners = c.getListeners(SWT.MouseDown); List<TypedListener> typedListeners = new ArrayList<TypedListener>(); for (Listener listener : listeners) { if (listener instanceof TypedListener) { TypedListener tl = (TypedListener) listener; if (tl.getEventListener() .toString() .contains("org.eclipse.mylyn.internal.reviews.ui.annotations.CommentPopupDialog")) { typedListeners.add(tl); } } } assertEquals(1, typedListeners.size()); }
Source:
public void reduce(Iterator<Edge> edges, Collector<Triad> out) throws Exception { vertices.clear(); Edge firstEdge = edges.next(); outTriad.setFirstVertex(firstEdge.getFirstVertex()); vertices.add((Integer)firstEdge.getSecondVertex()); while(edges.hasNext()) { Integer higherVertexId = edges.next().getSecondVertex(); for(Integer lowerVertexId : vertices) { outTriad.setSecondVertex(lowerVertexId); outTriad.setThirdVertex(higherVertexId); out.collect(outTriad); } vertices.add(higherVertexId); } }

Target:
public void reduce(Iterator<Edge> edges, Collector<Triad> out) throws Exception { vertices.clear(); Edge firstEdge = edges.next(); outTriad.setFirstVertex(firstEdge.getFirstVertex()); vertices.add(firstEdge.getSecondVertex()); while(edges.hasNext()) { Integer higherVertexId = edges.next().getSecondVertex(); for(Integer lowerVertexId : vertices) { outTriad.setSecondVertex(lowerVertexId); outTriad.setThirdVertex(higherVertexId); out.collect(outTriad); } vertices.add(higherVertexId); } }
Source:
protected static Collection<Story[]> createStories(String[] interopTests) throws Exception { List<Story[]> result = new ArrayList<>(); for (String interopTestName : interopTests) { List<Story> stories = HpackJsonUtil.readStories(interopTestName); if (stories.isEmpty()) { throw new AssumptionViolatedException("No stories for: " + interopTestName); } for (Story story : stories) { result.add(new Story[] {story}); } } return result; }

Target:
protected static Collection<Story[]> createStories(String[] interopTests) throws Exception { if (interopTests.length == 0) { return Collections.singletonList(new Story[] {MISSING}); } List<Story[]> result = new ArrayList<>(); for (String interopTestName : interopTests) { List<Story> stories = HpackJsonUtil.readStories(interopTestName); for (Story story : stories) { result.add(new Story[] {story}); } } return result; }
Source:
public void dispose() { fTCPBlock.dispose(); fSerialBlock.dispose(); fConnectionStack.dispose(); fConnectionField.dispose(); }

Target:
public void dispose() { fTCPBlock.dispose(); fSerialBlock.dispose(); fConnectionStack.dispose(); fConnectionField.dispose(); super.dispose(); }
Source:
public static void assertNotEquals(String pattern, String current){ boolean isAssertPassed = true; pattern = encodeSpecialChars(pattern); current = encodeSpecialChars(current); try { Assert.assertNotEquals(pattern, current); PageObjectLogging.log( "assertNotEquals", "assertion passed<br/>pattern: " + pattern + "<br/>current: " + current, true ); } catch(AssertionError ass) { isAssertPassed = false; addVerificationFailure(ass); PageObjectLogging.log( "assertNotEquals", "assertion failed<br/>pattern: " + pattern + "<br/>current: " + current, false ); } }

Target:
public static void assertNotEquals(String pattern, String current){ boolean isAssertPassed = true; String patternEncoded = encodeSpecialChars(pattern); String currentEncoded = encodeSpecialChars(current); try { Assert.assertNotEquals(pattern, current); } catch(AssertionError err) { isAssertPassed = false; addVerificationFailure(err); PageObjectLogging.log( "assertNotEquals", "assertion failed<br/>pattern: " + patternEncoded + "<br/>current: " + currentEncoded, false ); } PageObjectLogging.log( "assertNotEquals", "assertion passed<br/>pattern: " + patternEncoded + "<br/>current: " + currentEncoded, true ); }
Source:
public void shouldAttemptMethodAndFailImmedaitelyOnException_withImmediateFailureExceptionClassThrownAndRetryEnabled() throws Throwable { final RetryableAspect retryableAspect = new RetryableAspect(); final ProceedingJoinPoint mockProceedingJoinPoint = setupSimpleProceedingJoinPointMock(); final int retryMaxAttempts = 3; final Retryable mockRetryable = setupMockRetryable(retryMaxAttempts, 2000); RetryableConfiguration.setRetryableEnabled(true); when(mockRetryable.failImmediatelyOn()).thenReturn(new Class[] { RetryAspectTestException.class }); when(mockProceedingJoinPoint.proceed()).thenThrow(new RetryAspectTestException()); RetryAspectTestException actualException = null; try { retryableAspect.attemptMethodAndRetryIfNeeded(mockProceedingJoinPoint, mockRetryable); } catch (final RetryAspectTestException e) { actualException = e; } verify(mockProceedingJoinPoint, atMost(1)).proceed(); assertNotNull(actualException); }

Target:
public void shouldAttemptMethodAndFailImmedaitelyOnException_withImmediateFailureExceptionClassThrownAndRetryEnabled() throws Throwable { final RetryableAspect retryableAspect = new RetryableAspect(); final ProceedingJoinPoint mockProceedingJoinPoint = setupSimpleProceedingJoinPointMock(); final int maxAttempts = 3; final Retryable mockRetryable = setupMockRetryable(maxAttempts, 2000); RetryableConfiguration.setRetryableEnabled(true); when(mockRetryable.failImmediatelyOn()).thenReturn(new Class[] { RetryAspectTestException.class }); when(mockProceedingJoinPoint.proceed()).thenThrow(new RetryAspectTestException()); RetryAspectTestException actualException = null; try { retryableAspect.attemptMethodAndRetryIfNeeded(mockProceedingJoinPoint, mockRetryable); } catch (final RetryAspectTestException e) { actualException = e; } verify(mockProceedingJoinPoint, atMost(1)).proceed(); assertNotNull(actualException); }
Source:
private static boolean storedInStaticFinal(MethodInvocationTree mit) { Tree tree = mit.parent(); while (!tree.is(Tree.Kind.VARIABLE, Tree.Kind.CLASS, Tree.Kind.ASSIGNMENT)) { tree = tree.parent(); } if (tree.is(Tree.Kind.CLASS)) { return false; } else if (tree.is(Tree.Kind.ASSIGNMENT)) { return isConstant(((AssignmentExpressionTree) tree).variable()); } VariableTree variableTree = (VariableTree) tree; return variableTree.symbol().isStatic() && variableTree.symbol().isFinal(); }

Target:
private static boolean storedInStaticFinal(MethodInvocationTree mit) { Tree tree = mit.parent(); while (!tree.is(Tree.Kind.VARIABLE, Tree.Kind.CLASS, Tree.Kind.ASSIGNMENT, Tree.Kind.METHOD)) { tree = tree.parent(); } if (tree.is(Tree.Kind.CLASS, Tree.Kind.METHOD)) { return false; } else { return isConstant(tree); } }
Source:
public void testEncode() { String[][] tests = new String[][]{ {"Test <code>title</code>", "Test&nbsp;&#60;code&#62;title&#60;/code&#62;"}, {"ahoj", "ahoj"}, {"<>|&\"'", "&#60;&#62;|&#38;&#34;&#39;"} }; for (String[] test : tests) { assertEquals(test[1], Util.encode(test[0])); } }

Target:
public void testEncode() { String[][] tests = new String[][]{ {"Test <code>title</code>", "Test&nbsp;&#60;code&#62;title&#60;/code&#62;"}, {"ahoj", "ahoj"}, {"<>|&\"'", "&#60;&#62;|&#38;&#34;&#39;"}, {"tab\ttab", "tab&nbsp;&nbsp;&nbsp;&nbsp;tab"}, {"multi\nline\t\nstring", "multi&lt;br/&gt;line&nbsp;&nbsp;&nbsp;&nbsp;&lt;br/&gt;string"} }; for (String[] test : tests) { assertEquals(test[1], Util.encode(test[0])); } }
Source:
public MgfFileImportMethod(File target) { this.target = target; spectra = new LinkedList<>(); patterns = new Hashtable<>(); patterns.put("PEPMASS", Pattern.compile("(?<=PEPMASS=)(\\d+\\.\\d+)")); patterns.put("CHARGE", Pattern.compile("(?<=CHARGE=)(\\d+)\\+|-")); patterns.put("TITLE", Pattern.compile("(?<=TITLE=).*")); }

Target:
public MgfFileImportMethod(File target) { this.target = target; }
Source:
public static KeyedStateBackend<Long> createKeyedStateBackend(StateBackendType backendType) throws IOException { switch (backendType) { case HEAP: rootDir = prepareDirectory(rootDirName, null); return createHeapKeyedStateBackend(rootDir); case ROCKSDB: rootDir = prepareDirectory(rootDirName, null); return createRocksDBKeyedStateBackend(rootDir); case SINGLE_KEY: try { return new SingleKeyStateBackend().createKeyedStateBackend( null, null, null, new LongSerializer(), 0, null, null, null, null, Collections.emptyList(), null ); } catch (Exception e) { throw new IOException(e); } default: throw new IllegalArgumentException("Unknown backend type: " + backendType); } }

Target:
public static KeyedStateBackend<Long> createKeyedStateBackend(StateBackendType backendType) throws IOException { switch (backendType) { case HEAP: rootDir = prepareDirectory(rootDirName, null); return createHeapKeyedStateBackend(rootDir); case ROCKSDB: rootDir = prepareDirectory(rootDirName, null); return createRocksDBKeyedStateBackend(rootDir); case BATCH_EXECUTION: return createBatchExecutionStateBackend(); default: throw new IllegalArgumentException("Unknown backend type: " + backendType); } }
Source:
private void validate() { if (_clusterName == null) { throw new HelixException("The cluster name/ID cannot be null."); } if (_cloudEnabled) { if (_cloudID == null || _cloudInfoURLList == null || _cloudInfoParserClassName == null || _cloudInfoURLList.isEmpty()) { throw new HelixException( "This Cloud Configuration is Invalid. The configuration must have all of the fields if enabled."); } } }

Target:
private void validate() { if (_cloudEnabled) { if (_cloudID == null) { throw new HelixException( "This Cloud Configuration is Invalid. The CloudID is missing from the config."); } if (_cloudProvider == null) { throw new HelixException( "This Cloud Configuration is Invalid. The Cloud Provider is missing from the config."); } else if (_cloudProvider == CloudProvider.CUSTOMIZED) { if (_cloudInfoProcessorName == null || _cloudInfoSources == null || _cloudInfoSources.size() == 0) { throw new HelixException( "This Cloud Configuration is Invalid. CUSTOMIZED provider has been chosen without defining CloudInfoProcessorName or CloudInfoSources"); } } } }
Source:
public void startModule_shouldCreateDwrModulesXmlIfNotExists() throws ParserConfigurationException { Module mod = buildModuleForMessageTest(); ModuleFactory.getStartedModulesMap().put(mod.getModuleId(), mod); ServletContext servletContext = mock(ServletContext.class); String realPath = servletContext.getRealPath(""); if (realPath == null) realPath = System.getProperty("user.dir"); File f = new File(realPath, "/WEB-INF/dwr-modules.xml"); f.delete(); WebModuleUtil.startModule(mod, servletContext, true); assertTrue(f.exists()); ModuleFactory.getStartedModulesMap().clear(); }

Target:
public void startModule_shouldCreateDwrModulesXmlIfNotExists() throws ParserConfigurationException { Module mod = buildModuleForMessageTest(); ModuleFactory.getStartedModulesMap().put(mod.getModuleId(), mod); ServletContext servletContext = mock(ServletContext.class); String realPath = servletContext.getRealPath(""); if (realPath == null) realPath = System.getProperty("user.dir"); File f = new File(Paths.get(realPath, "WEB-INF", "dwr-modules.xml").toString()); f.delete(); WebModuleUtil.startModule(mod, servletContext, true); assertTrue(f.exists()); ModuleFactory.getStartedModulesMap().clear(); }
Source:
protected boolean validateBackupDomainNotFirstInPool() { if (getStoragePool() != null) { if (getStoragePool().getStatus() == StoragePoolStatus.Uninitialized && getStorageDomain().isBackup()) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_FIRST_DOMAIN_CANNOT_BE_BACKUP); } } return true; }

Target:
protected boolean validateBackupDomainNotFirstInPool() { if (getStoragePool() != null && getStoragePool().getStatus() == StoragePoolStatus.Uninitialized && getStorageDomain().isBackup()) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_FIRST_DOMAIN_CANNOT_BE_BACKUP); } return true; }
Source:
public void verifyUnclickable(WebElement element) { try { assertTrue(element.getAttribute("class").contains("disabled")); } catch (AssertionError e) { assertNotNull(element.getAttribute("disabled")); } }

Target:
public void verifyUnclickable(WebElement element) { if (element.getTagName().equals("a")) { assertTrue(element.getAttribute("class").contains("disabled")); } else { assertNotNull(element.getAttribute("disabled")); } }
Source:
private Cache<K, V> getBaseCache() { Cache<K, V> cache = null; try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext .getThreadLocalCarbonContext(); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); CacheManager cacheManager = Caching.getCacheManagerFactory() .getCacheManager(CACHE_MANAGER_NAME); if (cacheTimeout > 0 && cacheBuilder == null) { synchronized (cacheName.intern()) { if (cacheBuilder == null) { cacheManager.removeCache(cacheName); cacheBuilder = cacheManager.<K, V>createCacheBuilder(cacheName). setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration .Duration(TimeUnit.SECONDS, cacheTimeout)). setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration .Duration(TimeUnit.SECONDS, cacheTimeout)). setStoreByValue(false); cache = cacheBuilder.build(); if(cacheListeners != null) { for (AbstractCacheListener cacheListener : cacheListeners) { this.cacheBuilder.registerCacheEntryListener(cacheListener); } } if (capacity != 0) { ((CacheImpl) cache).setCapacity(capacity); } } else { cache = cacheManager.getCache(cacheName); } } } else { cache = cacheManager.getCache(cacheName); } } finally { PrivilegedCarbonContext.endTenantFlow(); } return cache; }

Target:
private Cache<K, V> getBaseCache() { Cache<K, V> cache = null; try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext .getThreadLocalCarbonContext(); carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID); carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); CacheManager cacheManager = Caching.getCacheManagerFactory() .getCacheManager(CACHE_MANAGER_NAME); if (cacheTimeout > 0 && cacheBuilder == null) { synchronized (cacheName.intern()) { if (cacheBuilder == null) { cacheManager.removeCache(cacheName); cacheBuilder = cacheManager.<K, V>createCacheBuilder(cacheName). setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration .Duration(TimeUnit.SECONDS, cacheTimeout)). setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration .Duration(TimeUnit.SECONDS, cacheTimeout)). setStoreByValue(false); cache = cacheBuilder.build(); for (AbstractCacheListener cacheListener : cacheListeners) { this.cacheBuilder.registerCacheEntryListener(cacheListener); } if (capacity != 0) { ((CacheImpl) cache).setCapacity(capacity); } } else { cache = cacheManager.getCache(cacheName); } } } else { cache = cacheManager.getCache(cacheName); } } finally { PrivilegedCarbonContext.endTenantFlow(); } return cache; }
Source:
protected ConfigurableElement[] getConfigurableElements() { ConfigurableElement[] configurableElements = new ConfigurableElement[1]; configurableElements[0] = new ConfigurableElement() { @Override public String getName() { return "Enable CONSTRAINT-DRIVEN auth"; } @Override public void create(CLIWrapper cli) throws Exception { cli.sendLine("/subsystem=undertow/servlet-container=default:write-attribute(name=proactive-authentication, value=false)"); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine("/subsystem=undertow/servlet-container=default:remove-attribute(name=proactive-authentication)"); } }; return configurableElements; }

Target:
protected ConfigurableElement[] getConfigurableElements() { ConfigurableElement[] configurableElements = new ConfigurableElement[1]; configurableElements[0] = new ConfigurableElement() { @Override public String getName() { return "Enable CONSTRAINT-DRIVEN auth"; } @Override public void create(CLIWrapper cli) throws Exception { cli.sendLine("/subsystem=undertow/servlet-container=default:write-attribute(name=proactive-authentication, value=false)"); } @Override public void remove(CLIWrapper cli) throws Exception { cli.sendLine("/subsystem=undertow/servlet-container=default:undefine-attribute(name=proactive-authentication)"); } }; return configurableElements; }
Source:
public Consumer<WebClient.Builder> oauth2Configuration() { Hooks.onLastOperator(REQUEST_CONTEXT_OPERATOR_KEY, Operators.lift((s, sub) -> createRequestContextSubscriber(sub))); return builder -> builder.defaultRequest(defaultRequest()).filter(this); }

Target:
public Consumer<WebClient.Builder> oauth2Configuration() { return builder -> builder.defaultRequest(defaultRequest()).filter(this); }
Source:
public void applyRightFloor(final PatchSetApproval a) { final IdentifiedUser user = userFactory.create(a.getAccountId()); List<RefRight> actionRights = getAllRights(a.getCategoryId()); boolean sameRefPattern = true; List<RefRight> mostSpecific = RefControl.filterMostSpecific(actionRights); short minAllowed = 0, maxAllowed = 0; for (final RefRight r : mostSpecific) { final AccountGroup.Id grp = r.getAccountGroupId(); if (user.getEffectiveGroups().contains(grp)) { minAllowed = (short) Math.min(minAllowed, r.getMinValue()); maxAllowed = (short) Math.max(maxAllowed, r.getMaxValue()); } } if (a.getValue() < minAllowed) { a.setValue(minAllowed); dirty(a); } else if (a.getValue() > maxAllowed) { a.setValue(maxAllowed); dirty(a); } }

Target:
public void applyRightFloor(final PatchSetApproval a) { final IdentifiedUser user = userFactory.create(a.getAccountId()); List<RefRight> actionRights = getAllRights(a.getCategoryId()); List<RefRight> mostSpecific = RefControl.filterMostSpecific(actionRights); short minAllowed = 0, maxAllowed = 0; for (final RefRight r : mostSpecific) { final AccountGroup.Id grp = r.getAccountGroupId(); if (user.getEffectiveGroups().contains(grp)) { minAllowed = (short) Math.min(minAllowed, r.getMinValue()); maxAllowed = (short) Math.max(maxAllowed, r.getMaxValue()); } } if (a.getValue() < minAllowed) { a.setValue(minAllowed); dirty(a); } else if (a.getValue() > maxAllowed) { a.setValue(maxAllowed); dirty(a); } }
Source:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(PyElementTypes.EXEC_STATEMENT, ctx -> { PyExecStatement node = (PyExecStatement) ctx.syntaxNode(); PsiElement currentNode = node.getFirstChild().getNextSibling(); while (currentNode instanceof PsiWhiteSpace) { currentNode = currentNode.getNextSibling(); } if (currentNode == null || !currentNode.getText().startsWith("(")) { ctx.addIssue(node.getFirstChild(), "Do not use exec statement."); } }); }

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(PyElementTypes.EXEC_STATEMENT, ctx -> { List<PyExpression> expressions = PsiTreeUtil.getChildrenOfTypeAsList(ctx.syntaxNode(), PyExpression.class); if (expressions.size() == 1 && expressions.get(0) instanceof PyParenthesizedExpression) { return; } ctx.addIssue(ctx.syntaxNode().getFirstChild(), "Do not use exec statement."); }); }