auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testGcjConnectionsAreCaching() throws IOException { String[] connectionEndpoints = {"127.0.0.1", "127.0.0.2"}; BigtableOptions.Builder optionsBuilder = BigtableOptions.builder() .setProjectId("fake-project") .setInstanceId("fake-instance") .setUsePlaintextNegotiation(true) .setCredentialOptions(CredentialOptions.nullCredential()) .setUseGCJClient(true) .setUseCachedDataPool(true) .setPort(fakeServer.getPort()) .setUserAgent("test"); Map<String, ClientContext> context = getGcjContext(optionsBuilder, connectionEndpoints[0]); Assert.assertEquals(context.size(), 1); Assert.assertTrue(context.containsKey(connectionEndpoints[0])); ClientContext Context_0 = context.get(connectionEndpoints[0]); context = getGcjContext(optionsBuilder, connectionEndpoints[1]); Assert.assertEquals(context.size(), 2); Assert.assertTrue(context.containsKey(connectionEndpoints[1])); Assert.assertEquals(Context_0, context.get(connectionEndpoints[0])); ClientContext Context_1 = context.get(connectionEndpoints[1]); context = getGcjContext(optionsBuilder, connectionEndpoints[1]); Assert.assertEquals(context.size(), 2); Assert.assertEquals(Context_1, context.get(connectionEndpoints[1])); Assert.assertEquals(Context_0, context.get(connectionEndpoints[0])); context = getGcjContext(optionsBuilder, connectionEndpoints[0]); Assert.assertEquals(context.size(), 2); Assert.assertEquals(Context_1, context.get(connectionEndpoints[1])); Assert.assertEquals(Context_0, context.get(connectionEndpoints[0])); }

Target:
public void testGcjConnectionsAreCaching() throws IOException { String[] connectionEndpoints = {"127.0.0.1", "localhost"}; BigtableOptions.Builder optionsBuilder = BigtableOptions.builder() .setProjectId("fake-project") .setInstanceId("fake-instance") .setUsePlaintextNegotiation(true) .setCredentialOptions(CredentialOptions.nullCredential()) .setUseGCJClient(true) .setUseCachedDataPool(true) .setPort(fakeServer.getPort()) .setUserAgent("test"); Map<String, ClientContext> context = getGcjContext(optionsBuilder, connectionEndpoints[0]); Assert.assertEquals(context.size(), 1); Assert.assertTrue(context.containsKey(connectionEndpoints[0])); ClientContext context0 = context.get(connectionEndpoints[0]); context = getGcjContext(optionsBuilder, connectionEndpoints[1]); Assert.assertEquals(context.size(), 2); Assert.assertTrue(context.containsKey(connectionEndpoints[1])); Assert.assertEquals(context0, context.get(connectionEndpoints[0])); ClientContext context1 = context.get(connectionEndpoints[1]); context = getGcjContext(optionsBuilder, connectionEndpoints[1]); Assert.assertEquals(context.size(), 2); Assert.assertEquals(context1, context.get(connectionEndpoints[1])); Assert.assertEquals(context0, context.get(connectionEndpoints[0])); context = getGcjContext(optionsBuilder, connectionEndpoints[0]); Assert.assertEquals(context.size(), 2); Assert.assertEquals(context1, context.get(connectionEndpoints[1])); Assert.assertEquals(context0, context.get(connectionEndpoints[0])); }
Source:
public void run() { Folder folder = getFolder(); logger.debug("Canceling IDLE"); if (folder != null) { folder.isOpen(); } }

Target:
public void run() { try { Folder folder = getFolder(); logger.debug("Canceling IDLE"); if (folder != null) { folder.isOpen(); } } catch (Exception ex) { logger.error("Error during resetting idle state.", ex); } }
Source:
public int execute() { try { if (work.dirCopyIteratorInitialized() || work.replPathIteratorInitialized()) { intitiateDataCopyTasks(); } else { Hive hiveDb = getHive(); Path dumpRoot = new Path(conf.getVar(HiveConf.ConfVars.REPLDIR), Base64.getEncoder().encodeToString(work.dbNameOrPattern.toLowerCase() .getBytes(StandardCharsets.UTF_8.name()))); Path currentDumpPath = new Path(dumpRoot, getNextDumpDir()); Path hiveDumpRoot = new Path(currentDumpPath, ReplUtils.REPL_HIVE_BASE_DIR); DumpMetaData dmd = new DumpMetaData(hiveDumpRoot, conf); ReplChangeManager.getInstance(conf); Path cmRoot = new Path(conf.getVar(HiveConf.ConfVars.REPLCMDIR)); Long lastReplId; if (!dumpRoot.getFileSystem(conf).exists(dumpRoot) || dumpRoot.getFileSystem(conf).listStatus(dumpRoot).length == 0) { lastReplId = bootStrapDump(hiveDumpRoot, dmd, cmRoot, hiveDb); } else { work.setEventFrom(getEventFromPreviousDumpMetadata(dumpRoot)); lastReplId = incrementalDump(hiveDumpRoot, dmd, cmRoot, hiveDb); } intitiateDataCopyTasks(); prepareReturnValues(Arrays.asList(currentDumpPath.toUri().toString(), String.valueOf(lastReplId))); } } catch (Exception e) { LOG.error("failed", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } return 0; }

Target:
public int execute() { try { if (work.tableDataCopyIteratorsInitialized()) { initiateDataCopyTasks(); } else { Hive hiveDb = getHive(); Path dumpRoot = new Path(conf.getVar(HiveConf.ConfVars.REPLDIR), Base64.getEncoder().encodeToString(work.dbNameOrPattern.toLowerCase() .getBytes(StandardCharsets.UTF_8.name()))); Path previousHiveDumpPath = getPreviousDumpMetadataPath(dumpRoot); if (shouldDump(previousHiveDumpPath)) { Path currentDumpPath = new Path(dumpRoot, getNextDumpDir()); Path hiveDumpRoot = new Path(currentDumpPath, ReplUtils.REPL_HIVE_BASE_DIR); DumpMetaData dmd = new DumpMetaData(hiveDumpRoot, conf); ReplChangeManager.getInstance(conf); Path cmRoot = new Path(conf.getVar(HiveConf.ConfVars.REPLCMDIR)); Long lastReplId; if (previousHiveDumpPath == null) { lastReplId = bootStrapDump(hiveDumpRoot, dmd, cmRoot, hiveDb); } else { work.setEventFrom(getEventFromPreviousDumpMetadata(previousHiveDumpPath)); lastReplId = incrementalDump(hiveDumpRoot, dmd, cmRoot, hiveDb); } work.setResultValues(Arrays.asList(currentDumpPath.toUri().toString(), String.valueOf(lastReplId))); work.setCurrentDumpPath(currentDumpPath); initiateDataCopyTasks(); } else { LOG.info("Previous Dump is not yet loaded"); } } } catch (Exception e) { LOG.error("failed", e); setException(e); return ErrorMsg.getErrorMsg(e.getMessage()).getErrorCode(); } return 0; }
Source:
private SiriusServerActivityDto convertActivity(Session session, ActivityDescription activityDescription) { String activityIdentifier = activityDescription.getName(); DAnalysis self = ((DAnalysisSessionImpl) session).getAnalyses().get(0); Map<String, Object> variables = new HashMap<>(); variables.put(SELF, self); IEvaluationResult result = new SiriusBackendInterpreter(session).evaluateExpression(variables, activityDescription.getLabelExpression()); String activityName = result.asString(); return new SiriusServerActivityDto(activityIdentifier, activityName); }

Target:
private SiriusServerActivityDto convertActivity(Session session, ActivityDescription activityDescription) { String activityIdentifier = activityDescription.getName(); DAnalysis self = ((DAnalysisSessionImpl) session).allAnalyses().stream().findFirst().orElse(null); Map<String, Object> variables = new HashMap<>(); variables.put(SELF, self); IEvaluationResult result = new SiriusBackendInterpreter(session).evaluateExpression(variables, activityDescription.getLabelExpression()); String activityName = result.asString(); return new SiriusServerActivityDto(activityIdentifier, activityName); }
Source:
public void setImage (Image image) { checkWidget(); if ((style & SWT.SEPARATOR) != 0) return; super.setImage (image); if (OS.GTK3) { if (!OS.GTK_IS_MENU_ITEM (handle)) { return; } if (image != null && boxHandle != 0) { ImageList imageList = parent.imageList; if (imageList == null) imageList = parent.imageList = new ImageList (); int imageIndex = imageList.indexOf (image); if (imageIndex == -1) { imageIndex = imageList.add (image); } else { imageList.put (imageIndex, image); } long pixbuf = imageList.getPixbuf (imageIndex); if (OS.SWT_PADDED_MENU_ITEMS && imageHandle != 0) { OS.gtk_image_set_from_pixbuf(imageHandle, pixbuf); } else { imageHandle = OS.gtk_image_new_from_pixbuf (pixbuf); if (imageHandle == 0) error (SWT.ERROR_NO_HANDLES); OS.gtk_container_add (boxHandle, imageHandle); OS.gtk_box_reorder_child (boxHandle, imageHandle, 0); } } } else { if (!OS.GTK_IS_IMAGE_MENU_ITEM (handle)) { return; } if (image != null) { ImageList imageList = parent.imageList; if (imageList == null) imageList = parent.imageList = new ImageList (); int imageIndex = imageList.indexOf (image); if (imageIndex == -1) { imageIndex = imageList.add (image); } else { imageList.put (imageIndex, image); } long pixbuf = imageList.getPixbuf (imageIndex); imageHandle = OS.gtk_image_new_from_pixbuf (pixbuf); if (imageHandle == 0) error (SWT.ERROR_NO_HANDLES); OS.gtk_image_menu_item_set_image (handle, imageHandle); } else { OS.gtk_image_menu_item_set_image (handle, 0); } } OS.gtk_widget_show (imageHandle); }

Target:
public void setImage (Image image) { checkWidget(); if ((style & SWT.SEPARATOR) != 0) return; super.setImage (image); if (image != null) { ImageList imageList = parent.imageList; if (imageList == null) imageList = parent.imageList = new ImageList (); int imageIndex = imageList.indexOf (image); if (imageIndex == -1) { imageIndex = imageList.add (image); } else { imageList.put (imageIndex, image); } long pixbuf = imageList.getPixbuf (imageIndex); if (OS.GTK3) { if (!OS.GTK_IS_MENU_ITEM (handle)) return; if (OS.SWT_PADDED_MENU_ITEMS && imageHandle != 0) { OS.gtk_image_set_from_pixbuf(imageHandle, pixbuf); } else { imageHandle = OS.gtk_image_new_from_pixbuf (pixbuf); if (imageHandle == 0) error (SWT.ERROR_NO_HANDLES); if (boxHandle != 0) { OS.gtk_container_add (boxHandle, imageHandle); OS.gtk_box_reorder_child (boxHandle, imageHandle, 0); } } } else { if (!OS.GTK_IS_IMAGE_MENU_ITEM (handle)) return; imageHandle = OS.gtk_image_new_from_pixbuf (pixbuf); OS.gtk_image_menu_item_set_image (handle, imageHandle); } } OS.gtk_widget_show (imageHandle); }
Source:
ResourceSupport listSearchMethods(@PathVariable String apiCategory, @PathVariable String model) { ResourceSupport root = new ResourceSupport(); DSpaceRestRepository repository = utils.getResourceRepository(apiCategory, model); boolean searchEnabled = false; for (Method method : repository.getClass().getMethods()) { SearchRestMethod ann = method.getAnnotation(SearchRestMethod.class); if (ann != null) { String name = ann.name(); if (name.isEmpty()) { name = method.getName(); } Link link = linkTo(this.getClass(), apiCategory, model).slash("search").slash(name).withRel(name); root.add(link); searchEnabled = true; } } if (!searchEnabled) { throw new RepositorySearchNotFoundException(model); } return root; }

Target:
public ResourceSupport listSearchMethods(@PathVariable String apiCategory, @PathVariable String model) { ResourceSupport root = new ResourceSupport(); DSpaceRestRepository repository = utils.getResourceRepository(apiCategory, model); List<String> searchMethods = repositoryUtils.listSearchMethods(repository); if (CollectionUtils.isEmpty(searchMethods)) { throw new RepositorySearchNotFoundException(model); } for (String name : searchMethods) { Link link = linkTo(this.getClass(), apiCategory, model).slash("search").slash(name).withRel(name); root.add(link); } return root; }
Source:
private static final String formatInterval(TimeZone zone, Interval interval) { return String.format( "(%s, %s)", DateTimeFormatter.ofPattern("HH:mm").withZone(zone.toZoneId()).format(Instant.ofEpochMilli(interval.getStart())), DateTimeFormatter.ofPattern("HH:mm").withZone(zone.toZoneId()).format(Instant.ofEpochMilli(interval.getEnd())) ); }

Target:
private static final String formatInterval(TimeZone zone, Interval interval) { final Function<Long, String> f = ms -> dateFormat(zone).format(Instant.ofEpochMilli(ms)); return String.format("(%s, %s)", f.apply(interval.getStart()), f.apply(interval.getEnd())); }
Source:
public SnomedSimpleTypeRefSetDSVExporter(final SnomedRefSetDSVExportModel exportSetting) { this.refSetId = exportSetting.getRefSetId(); this.includeDescriptionId = exportSetting.includeDescriptionId(); this.includeRelationshipId = exportSetting.includeRelationshipTargetId(); this.includeInactiveMembers = exportSetting.includeInactiveMembers(); this.exportItems = exportSetting.getExportItems(); this.locales = exportSetting.getLocales(); this.delimiter = exportSetting.getDelimiter(); this.branchPath = BranchPathUtils.createPath(exportSetting.getBranchPath()); exportPath = exportSetting.getExportPath(); lineSeparator = System.getProperty("line.separator"); groupedRelationships = Maps.newTreeMap(); groupedOnlyItems = Lists.newArrayList(); }

Target:
public SnomedSimpleTypeRefSetDSVExporter(final SnomedRefSetDSVExportModel exportSetting) { this.refSetId = exportSetting.getRefSetId(); this.includeDescriptionId = exportSetting.includeDescriptionId(); this.includeRelationshipId = exportSetting.includeRelationshipTargetId(); this.includeInactiveMembers = exportSetting.includeInactiveMembers(); this.exportItems = exportSetting.getExportItems(); this.locales = exportSetting.getLocales(); this.delimiter = exportSetting.getDelimiter(); this.branchPath = BranchPathUtils.createPath(exportSetting.getBranchPath()); exportPath = exportSetting.getExportPath(); groupedRelationships = Maps.newTreeMap(); groupedOnlyItems = Lists.newArrayList(); }
Source:
public ZkJobCoordinator(Config config, MetricsRegistry metricsRegistry) { this.config = config; ZkConfig zkConfig = new ZkConfig(config); ZkKeyBuilder keyBuilder = new ZkKeyBuilder(new ApplicationConfig(config).getAppId()); this.metrics = new ZkJobCoordinatorMetrics(metricsRegistry); this.zkUtils = new ZkUtils( keyBuilder, ZkCoordinationServiceFactory.createZkClient( zkConfig.getZkConnect(), zkConfig.getZkSessionTimeoutMs(), zkConfig.getZkConnectionTimeoutMs()), zkConfig.getZkConnectionTimeoutMs(), metrics); this.processorId = createProcessorId(config); LeaderElector leaderElector = new ZkLeaderElector(processorId, zkUtils); leaderElector.setLeaderElectorListener(new LeaderElectorListenerImpl()); this.zkController = new ZkControllerImpl(processorId, zkUtils, this, leaderElector); this.barrier = new ZkBarrierForVersionUpgrade( keyBuilder.getJobModelVersionBarrierPrefix(), zkUtils, new ZkBarrierListenerImpl()); this.debounceTimeMs = new JobConfig(config).getDebounceTimeMs(); this.reporters = MetricsReporterLoader.getMetricsReporters(new MetricsConfig(config), processorId); }

Target:
public ZkJobCoordinator(Config config, MetricsRegistry metricsRegistry) { this.config = config; ZkConfig zkConfig = new ZkConfig(config); ZkKeyBuilder keyBuilder = new ZkKeyBuilder(new ApplicationConfig(config).getGlobalAppId()); this.metrics = new ZkJobCoordinatorMetrics(metricsRegistry); this.zkUtils = new ZkUtils( keyBuilder, ZkCoordinationServiceFactory.createZkClient( zkConfig.getZkConnect(), zkConfig.getZkSessionTimeoutMs(), zkConfig.getZkConnectionTimeoutMs()), zkConfig.getZkConnectionTimeoutMs(), metrics); this.processorId = createProcessorId(config); LeaderElector leaderElector = new ZkLeaderElector(processorId, zkUtils); leaderElector.setLeaderElectorListener(new LeaderElectorListenerImpl()); this.zkController = new ZkControllerImpl(processorId, zkUtils, this, leaderElector); this.barrier = new ZkBarrierForVersionUpgrade( keyBuilder.getJobModelVersionBarrierPrefix(), zkUtils, new ZkBarrierListenerImpl()); this.debounceTimeMs = new JobConfig(config).getDebounceTimeMs(); this.reporters = MetricsReporterLoader.getMetricsReporters(new MetricsConfig(config), processorId); }
Source:
private static Collection<OAuth2Error> validateRequiredClaims(Jwt idToken){ Collection<OAuth2Error> errors = new ArrayList<>(); URL issuer = idToken.getIssuer(); if (issuer == null) { errors.add(requiredClaimError(JwtClaimNames.ISS)); } String subject = idToken.getSubject(); if (subject == null) { errors.add(requiredClaimError(JwtClaimNames.SUB)); } List<String> audience = idToken.getAudience(); if (CollectionUtils.isEmpty(audience)) { errors.add(requiredClaimError(JwtClaimNames.AUD)); } Instant expiresAt = idToken.getExpiresAt(); if (expiresAt == null) { errors.add(requiredClaimError(JwtClaimNames.EXP)); } Instant issuedAt = idToken.getIssuedAt(); if (issuedAt == null) { errors.add(requiredClaimError(JwtClaimNames.IAT)); } return errors; }

Target:
private static Map<String, Object> validateRequiredClaims(Jwt idToken){ Map<String, Object> requiredClaims = new HashMap<>(); URL issuer = idToken.getIssuer(); if (issuer == null) { requiredClaims.put(IdTokenClaimNames.ISS, issuer); } String subject = idToken.getSubject(); if (subject == null) { requiredClaims.put(IdTokenClaimNames.SUB, subject); } List<String> audience = idToken.getAudience(); if (CollectionUtils.isEmpty(audience)) { requiredClaims.put(IdTokenClaimNames.AUD, audience); } Instant expiresAt = idToken.getExpiresAt(); if (expiresAt == null) { requiredClaims.put(IdTokenClaimNames.EXP, expiresAt); } Instant issuedAt = idToken.getIssuedAt(); if (issuedAt == null) { requiredClaims.put(IdTokenClaimNames.IAT, issuedAt); } return requiredClaims; }
Source:
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath SCMSourceOwner owner, @QueryParameter String source) { return new StandardListBoxModel() .withEmptySelection() .withAll(availableCredentials(owner, source)); }

Target:
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath SCMSourceOwner owner, @QueryParameter String source) { return new StandardUsernameListBoxModel() .withEmptySelection() .withAll(availableCredentials(owner, source)); }
Source:
public void runWithEvent(Event event) { ISelection selection = selectionProvider.getSelection(); Collection<IFeatureModel> featureModels = FeatureSupport.toFeatureModels(selection); Collection<IPluginModelBase> pluginModels = PluginSupport.toPluginModels(selection); Collection<IProject> projects = new HashSet<>(); addUnderlyingResources(projects, featureModels); addUnderlyingResources(projects, pluginModels); String[] fileData = new String[projects.size()]; int i = 0; for (IProject project : projects) { fileData[i++] = project.getLocation().toOSString(); } String textData = getTextData(featureModels, pluginModels); Object[] data = { projects.toArray(new IResource[projects.size()]), textData, fileData }; Transfer[] dataTypes = { ResourceTransfer.getInstance(), TextTransfer.getInstance(), FileTransfer.getInstance() }; clipboard.setContents(data, dataTypes); }

Target:
public void runWithEvent(Event event) { IStructuredSelection selection = fStructuredViewer.getStructuredSelection(); List<IModel> models = toModels(selection); String textData = toTextData(models); IResource[] projectResources = toProjectResources(models); String[] fileData = toFileData(projectResources); Object[] data = { textData, projectResources, fileData }; Transfer[] dataTypes = { TextTransfer.getInstance(), ResourceTransfer.getInstance(), FileTransfer.getInstance() }; fClipboard.setContents(data, dataTypes); }
Source:
public static PrimaryElectorType instance() { return new PrimaryElectorType(); }

Target:
public static PrimaryElectorType instance() { return TYPE; }
Source:
public void testSyncTaskWithMultiplePartition() throws Exception { Map<Integer, List<KV>> inputPartitionData = new HashMap<>(); Map<Integer, List<Integer>> expectedOutputPartitionData = new HashMap<>(); genData(inputPartitionData, expectedOutputPartitionData); InMemorySystemDescriptor isd = new InMemorySystemDescriptor("test"); InMemoryInputDescriptor<KV> imid = isd .getInputDescriptor("input", new NoOpSerde<KV>()); InMemoryOutputDescriptor<Integer> imod = isd .getOutputDescriptor("output", new NoOpSerde<Integer>()); TestRunner .of(new LegacyTaskApplication(MyStreamTestTask.class.getName())) .addInputStream(imid, inputPartitionData) .addOutputStream(imod, 5) .run(Duration.ofSeconds(2)); StreamAssert.containsInOrder(expectedOutputPartitionData, imod, Duration.ofMillis(1000)); }

Target:
public void testSyncTaskWithMultiplePartition() throws Exception { Map<Integer, List<KV>> inputPartitionData = new HashMap<>(); Map<Integer, List<Integer>> expectedOutputPartitionData = new HashMap<>(); genData(inputPartitionData, expectedOutputPartitionData); InMemorySystemDescriptor isd = new InMemorySystemDescriptor("test"); InMemoryInputDescriptor<KV> imid = isd .getInputDescriptor("input", new NoOpSerde<KV>()); InMemoryOutputDescriptor<Integer> imod = isd .getOutputDescriptor("output", new NoOpSerde<Integer>()); TestRunner .of(MyStreamTestTask.class) .addInputStream(imid, inputPartitionData) .addOutputStream(imod, 5) .run(Duration.ofSeconds(2)); StreamAssert.containsInOrder(expectedOutputPartitionData, imod, Duration.ofMillis(1000)); }
Source:
private void checkFraPvIsZero(FraCurveNode node, LocalDate valuationDate, RatesProvider ratesProvider) { Trade trade = node.buildTrade(valuationDate, ImmutableMap.of()); FraProduct product = ((FraTrade) trade).getProduct(); CurrencyAmount currencyAmount = DiscountingFraProductPricer.DEFAULT.presentValue(product, ratesProvider); double pv = currencyAmount.getAmount(); assertThat(pv).isCloseTo(0, offset(1e-6)); }

Target:
private void checkFraPvIsZero(FraCurveNode node, LocalDate valuationDate, RatesProvider ratesProvider) { Trade trade = node.buildTrade(valuationDate, ImmutableMap.of()); CurrencyAmount currencyAmount = DiscountingFraTradePricer.DEFAULT.presentValue((FraTrade) trade, ratesProvider); double pv = currencyAmount.getAmount(); assertThat(pv).isCloseTo(0, offset(1e-6)); }
Source:
public static Map<String, Object> parseCaddisflyResponseValue(String caddisflyValue) { Map<String, Object> caddisflyResponseMap = new HashMap<String, Object>(); try { caddisflyResponseMap = JSON_OBJECT_MAPPER.readValue(caddisflyValue, Map.class); } catch (IOException e) { log.error("Failed to parse the caddisfly response"); } if (caddisflyResponseMap != null) { return caddisflyResponseMap; } else { return Collections.emptyMap(); } }

Target:
public static Map<String, Object> parseCaddisflyResponseValue(String caddisflyValue) { Map<String, Object> caddisflyResponseMap = new HashMap<>(); try { caddisflyResponseMap = JSON_OBJECT_MAPPER.readValue(caddisflyValue, Map.class); } catch (IOException e) { log.error("Failed to parse the caddisfly response"); } if (caddisflyResponseMap != null) { return caddisflyResponseMap; } else { return Collections.emptyMap(); } }
Source:
public void modified(Map<String, Object> properties) { MagicServiceConfig config = new Configuration(properties).as(MagicServiceConfig.class); List<Field> l = ConfigUtil.getAllFields(MagicServiceConfig.class); l.forEach(field -> { try { Object value = field.get(config); if (value != null) { logger.debug("MagicService config = {}", field.getName(), value); } } catch (IllegalArgumentException | IllegalAccessException ignored) { } }); }

Target:
public void modified(Map<String, Object> properties) { MagicServiceConfig config = new Configuration(properties).as(MagicServiceConfig.class); logger.debug(config.toString()); }
Source:
protected void firstListenerAdded() { if (!isDisposed()) { if (listener == null) { listener = property .adaptListener(new ISimplePropertyListener<ValueDiff<T>>() { @Override public void handleEvent( final SimplePropertyEvent<ValueDiff<T>> event) { if (!isDisposed() && !updating) { getRealm().exec(new Runnable() { @Override public void run() { if (event.type == SimplePropertyEvent.CHANGE) { notifyIfChanged(event.diff); } else if (event.type == SimplePropertyEvent.STALE && !stale) { stale = true; fireStale(); } } }); } } }); } getRealm().exec(new Runnable() { @Override public void run() { cachedValue = property.getValue(source); stale = false; if (listener != null) listener.addTo(source); } }); } }

Target:
protected void firstListenerAdded() { if (!isDisposed() && listener == null) { listener = property.adaptListener(new ISimplePropertyListener<ValueDiff<T>>() { @Override public void handleEvent(final SimplePropertyEvent<ValueDiff<T>> event) { if (!isDisposed() && !updating) { getRealm().exec(new Runnable() { @Override public void run() { if (event.type == SimplePropertyEvent.CHANGE) { notifyIfChanged(event.diff); } else if (event.type == SimplePropertyEvent.STALE && !stale) { stale = true; fireStale(); } } }); } } }); } getRealm().exec(new Runnable() { @Override public void run() { cachedValue = property.getValue(source); stale = false; if (listener != null) listener.addTo(source); } }); }
Source:
public static String getGeneralMaterialName(String fullName) { fullName = fullName.toUpperCase(); if (fullName.startsWith("STRIPPED")) { return fullName.replaceFirst("_[^_]+", ""); } else { return fullName.replaceFirst(".+?_", ""); } }

Target:
public static String getGeneralMaterialName(String fullName) { String newName = fullName.toUpperCase(); if (newName.startsWith("STRIPPED")) { return newName.replaceFirst("_[^_]+", ""); } else if (newName.matches("^(DARK|LIGHT).+")) { return newName.replaceFirst(".+?_.+?_", ""); } else if (newName.matches( "^(WHITE|ORANGE|MAGENTA|YELLOW|LIME|PINK|GRAY|CYAN|PURPLE|BLUE|BROWN|GREEN|RED|BLACK|" + "OAK|SPRUCE|BIRCH|JUNGLE|ACACIA).+")) { return newName.replaceFirst(".+?_", ""); } return fullName; }
Source:
public static int getInternalInboundHttpPort() { File synapseProperties = Paths.get(CarbonUtils.getCarbonConfigDirPath(), "synapse.properties").toFile(); Properties properties = new Properties(); try (InputStream inputStream = new FileInputStream(synapseProperties)) { properties.load(inputStream); } catch (FileNotFoundException e) { handleException("synapse.properties file not found", e); } catch (IOException e) { handleException("Error while reading synapse.properties file", e); } String internalInboundEnabledProperty = properties.getProperty(Constants.INTERNAL_HTTP_API_ENABLED); if (internalInboundEnabledProperty == null) { return -1; } boolean internalInboundEnabled = Boolean.parseBoolean(internalInboundEnabledProperty); if (!internalInboundEnabled) { return -1; } int internalInboundHttpPort = Constants.DEFAULT_INTERNAL_HTTP_API_PORT; String internalInboundPortProperty = properties.getProperty(Constants.INTERNAL_HTTP_API_PORT); if (internalInboundPortProperty != null) { try { internalInboundHttpPort = Integer.parseInt(internalInboundPortProperty); } catch (Exception ex) { handleException(Constants.INTERNAL_HTTP_API_PORT + " is not in proper format", ex); } } internalInboundHttpsPort = Constants.DEFAULT_INTERNAL_HTTPS_API_PORT; String internalInboundHttpsProperty = properties.getProperty(Constants.INTERNAL_HTTPS_API_PORT); if (internalInboundPortProperty != null) { try { internalInboundHttpsPort = Integer.parseInt(internalInboundHttpsProperty); } catch (Exception ex) { handleException(Constants.INTERNAL_HTTPS_API_PORT + " is not in proper format", ex); } } return internalInboundHttpPort; }

Target:
public static int getInternalInboundHttpPort() { return getPort(Constants.INTERNAL_HTTP_API_PORT, internalInboundHttpPortProperty, Constants.DEFAULT_INTERNAL_HTTP_API_PORT); }
Source:
public T read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException { while (bufferIterator == null || !bufferIterator.hasNext()) { Collection<? extends T> buffer = windedReader.read(); if (buffer == null) { return null; } this.bufferIterator = buffer.iterator(); } return bufferIterator.next(); }

Target:
public T read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException { while (bufferIterator == null || !bufferIterator.hasNext()) { Collection<? extends T> buffer = reader.read(); if (buffer == null) { return null; } this.bufferIterator = buffer.iterator(); } return bufferIterator.next(); }
Source:
private void prepareForSending() { try { if (partitionId != null) { attemptedPartitionIds.add(partitionId); } partitionId = getPartitionForPut(attemptedPartitionIds); chunkBlobId = new BlobId(partitionId); operationTracker = new SimpleOperationTracker(routerConfig.routerDatacenterName, partitionId, false, routerConfig.routerPutSuccessTarget, routerConfig.routerPutRequestParallelism); correlationIdToChunkPutRequest.clear(); state = ChunkState.Ready; } catch (RouterException e) { setOperationException(e); } }

Target:
private void prepareForSending() { try { if (partitionId != null) { attemptedPartitionIds.add(partitionId); } partitionId = getPartitionForPut(attemptedPartitionIds); chunkBlobId = new BlobId(partitionId); operationTracker = new SimpleOperationTracker(routerConfig.routerDatacenterName, partitionId, false, routerConfig.routerPutSuccessTarget, routerConfig.routerPutRequestParallelism); correlationIdToChunkPutRequestInfo.clear(); state = ChunkState.Ready; } catch (RouterException e) { setOperationException(e); } }
Source:
protected void runInternal() { boolean exist = recordStore.existInMemory(dataKey); recordStore.removeBackupTx(dataKey, getCallerProvenance(), transactionId); recordStore.forceUnlock(dataKey); if (!exist) { wbqCapacityCounter().decrement(transactionId, getPartitionId()); } }

Target:
protected void runInternal() { boolean exist = recordStore.existInMemory(dataKey); recordStore.removeBackupTxn(dataKey, getCallerProvenance(), transactionId); recordStore.forceUnlock(dataKey); if (!exist) { wbqCapacityCounter().decrement(transactionId); } }
Source:
public Command findCommand(String name, ClassLoader cl) { synchronized (commandCache) { if (!commandCache.containsKey(name)) { try { Command commandInstance = (Command) Class.forName(name, true, cl).newInstance(); commandCache.put(name, commandInstance); } catch (Exception ex) { throw new IllegalArgumentException("Unknown Command implementation with name '" + name + "': " + ex.getMessage()); } } else { Command cmd = commandCache.get(name); if (!cmd.getClass().getClassLoader().equals(cl)) { commandCache.remove(name); try { Command commandInstance = (Command) Class.forName(name, true, cl).newInstance(); commandCache.put(name, commandInstance); } catch (Exception ex) { throw new IllegalArgumentException("Unknown Command implementation with name '" + name + "': " + ex.getMessage()); } } } } return commandCache.get(name); }

Target:
public Command findCommand(String name, ClassLoader cl) { synchronized (commandCache) { if (!commandCache.containsKey(name)) { try { Command commandInstance = (Command) Class.forName(name, true, cl).newInstance(); commandCache.put(name, commandInstance); } catch (Exception ex) { throw new IllegalArgumentException("Unknown Command implementation with name '" + name + "': " + ex.getMessage(), ex); } } else { Command cmd = commandCache.get(name); if (!cmd.getClass().getClassLoader().equals(cl)) { commandCache.remove(name); try { Command commandInstance = (Command) Class.forName(name, true, cl).newInstance(); commandCache.put(name, commandInstance); } catch (Exception ex) { throw new IllegalArgumentException("Unknown Command implementation with name '" + name + "': " + ex.getMessage(), ex); } } } } return commandCache.get(name); }
Source:
public void setup() throws ParseException { context = new Context(); context.turnOffAuthorisationSystem(); if (commandLine.hasOption('h')) { help = true; return; } if (!commandLine.hasOption('f')) { throw new ParseException("Required parameter -f missing!"); } filename = commandLine.getOptionValue('f'); exportAllMetadata = commandLine.hasOption('a'); if (commandLine.hasOption('i')) { exportAllItems = true; } handle = commandLine.getOptionValue('i'); try { context.setCurrentUser(ePersonService.find(context, getEpersonIdentifier())); } catch (SQLException e) { handler.handleException(e); } }

Target:
public void setup() throws ParseException { if (commandLine.hasOption('h')) { help = true; return; } if (!commandLine.hasOption('f')) { throw new ParseException("Required parameter -f missing!"); } filename = commandLine.getOptionValue('f'); exportAllMetadata = commandLine.hasOption('a'); if (!commandLine.hasOption('i')) { exportAllItems = true; } handle = commandLine.getOptionValue('i'); }
Source:
public CreateBranchWizard(Repository repository, String base) { try (RevWalk rw = new RevWalk(repository)) { if (base == null) { myPage = new CreateBranchPage(repository, (Ref) null); } else if (ObjectId.isId(base)) { RevCommit commit = rw.parseCommit(ObjectId .fromString(base)); myPage = new CreateBranchPage(repository, commit); } else { if (base.startsWith(Constants.R_HEADS) || base.startsWith(Constants.R_REMOTES) || base.startsWith(Constants.R_TAGS)) { Ref currentBranch = repository.exactRef(base); myPage = new CreateBranchPage(repository, currentBranch); } else { RevCommit commit = rw.parseCommit( repository.resolve(base + "^{commit}")); myPage = new CreateBranchPage(repository, commit); } } } catch (IOException e) { myPage = new CreateBranchPage(repository, (Ref) null); } if (newBranchName != null) myPage.setBranchName(newBranchName); setWindowTitle(UIText.CreateBranchWizard_NewBranchTitle); }

Target:
public CreateBranchWizard(Repository repository, String base) { try (RevWalk rw = new RevWalk(repository)) { if (base == null) { myPage = new CreateBranchPage(repository, (Ref) null); } else if (ObjectId.isId(base)) { RevCommit commit = rw.parseCommit(ObjectId .fromString(base)); myPage = new CreateBranchPage(repository, commit); } else { if (base.startsWith(Constants.R_HEADS) || base.startsWith(Constants.R_REMOTES) || base.startsWith(Constants.R_TAGS)) { Ref currentBranch = repository.exactRef(base); myPage = new CreateBranchPage(repository, currentBranch); } else { RevCommit commit = rw.parseCommit( repository.resolve(base + "^{commit}")); myPage = new CreateBranchPage(repository, commit); } } } catch (IOException e) { myPage = new CreateBranchPage(repository, (Ref) null); } if (newBranchName != null) { myPage.setBranchName(newBranchName); } setWindowTitle(UIText.CreateBranchWizard_NewBranchTitle); }
Source:
public long takeSnapshot() throws IOException { LOG.info("Saving Ratis snapshot on the OM."); return ozoneManager.saveRatisSnapshot(); }

Target:
public long takeSnapshot() throws IOException { LOG.info("Saving Ratis snapshot on the OM."); if (ozoneManager != null) { return ozoneManager.saveRatisSnapshot(); } return 0; }
Source:
public void testSetProperties() throws Exception { DocumentModel model = session.getDocument(new PathRef("/default-domain/workspaces/test")); String nxql = String.format("SELECT * from ComplexDoc where ecm:parentId='%s'", model.getId()); String title = "test title"; String description = "test description"; String foo = "test foo"; String bar = "test bar"; HashMap<String, Serializable> complex = new HashMap<>(); complex.put("foo", foo); complex.put("bar", bar); String commandId = service.submit(new BulkCommand().withRepository(session.getRepositoryName()) .withUsername(session.getPrincipal().getName()) .withQuery(nxql) .withAction(ACTION_NAME) .withParam("dc:title", title) .withParam("dc:description", description) .withParam("cpx:complex", complex)); assertTrue("Bulk action didn't finish", service.await(Duration.ofSeconds(10))); BulkStatus status = service.getStatus(commandId); assertNotNull(status); assertEquals(COMPLETED, status.getState()); assertEquals(SIZE * 2, status.getProcessed()); txFeature.nextTransaction(); for (DocumentModel child : session.query(nxql)) { assertEquals(title, child.getTitle()); assertEquals(description, child.getPropertyValue("dc:description")); assertEquals(foo, child.getPropertyValue("cpx:complex/foo")); assertEquals(bar, child.getPropertyValue("cpx:complex/bar")); } }

Target:
public void testSetProperties() throws Exception { DocumentModel model = session.getDocument(new PathRef("/default-domain/workspaces/test")); String nxql = String.format("SELECT * from ComplexDoc where ecm:parentId='%s'", model.getId()); String title = "test title"; String description = "test description"; String foo = "test foo"; String bar = "test bar"; HashMap<String, Serializable> complex = new HashMap<>(); complex.put("foo", foo); complex.put("bar", bar); String commandId = service.submit(new BulkCommand().withRepository(session.getRepositoryName()) .withUsername(session.getPrincipal().getName()) .withQuery(nxql) .withAction(ACTION_NAME) .withParam("dc:title", title) .withParam("dc:description", description) .withParam("cpx:complex", complex)); assertTrue("Bulk action didn't finish", service.await(Duration.ofSeconds(10))); BulkStatus status = service.getStatus(commandId); assertNotNull(status); assertEquals(COMPLETED, status.getState()); assertEquals(DOC_BY_LEVEL, status.getProcessed()); txFeature.nextTransaction(); for (DocumentModel child : session.query(nxql)) { assertEquals(title, child.getTitle()); assertEquals(description, child.getPropertyValue("dc:description")); assertEquals(foo, child.getPropertyValue("cpx:complex/foo")); assertEquals(bar, child.getPropertyValue("cpx:complex/bar")); } }
Source:
private ClosableObservable<EditableConfiguration> edit(ClosableObservable<Configuration> config) { ObservableEditableConfiguration editableConfig = new ObservableEditableConfiguration( config, configServer); return editableConfig; }

Target:
private ObservableEditableConfiguration edit(ClosableObservable<Configuration> config) { return registerForClose(new ObservableEditableConfiguration(config,configServer)); }
Source:
public String generateCommonJar() throws IOException { File file = new File("/tmp/schemaSQL.jar"); if (file.exists()) { file.delete(); } FileSystem fs = FileSystem.newInstance(file.toURI(), new Configuration()); FSDataOutputStream out = fs.create(new Path(file.getAbsolutePath())); JarOutputStream jout = new JarOutputStream(out); for (Schema schema : schemas.values()) { jout.putNextEntry(new ZipEntry(schema.fqcn.replace(".", "/") + ".class")); jout.write(schema.beanClassBytes); jout.closeEntry(); } jout.close(); out.close(); return file.getAbsolutePath(); }

Target:
public String generateCommonJar() throws IOException { File file = File.createTempFile("schemaSQL", ".jar"); FileSystem fs = FileSystem.newInstance(file.toURI(), new Configuration()); FSDataOutputStream out = fs.create(new Path(file.getAbsolutePath())); JarOutputStream jout = new JarOutputStream(out); for (Schema schema : schemas.values()) { jout.putNextEntry(new ZipEntry(schema.fqcn.replace(".", "/") + ".class")); jout.write(schema.beanClassBytes); jout.closeEntry(); } jout.close(); out.close(); return file.getAbsolutePath(); }
Source:
public List<ElementT> decode( @Nullable ByteBuffer bytes, @NonNull ProtocolVersion protocolVersion) { if (bytes == null || bytes.remaining() == 0) { return new ArrayList<>(0); } else { ByteBuffer input = bytes.duplicate(); int size = input.getInt(); List<ElementT> result = new ArrayList<>(size); for (int i = 0; i < size; i++) { ElementT element; int elementSize = input.getInt(); if (elementSize < 0) { element = null; } else { ByteBuffer encodedElement = input.slice(); encodedElement.limit(elementSize); input.position(input.position() + elementSize); element = elementCodec.decode(encodedElement, protocolVersion); } result.add(element); } return result; } }

Target:
public List<ElementT> decode( @Nullable ByteBuffer bytes, @NonNull ProtocolVersion protocolVersion) { if (bytes == null || bytes.remaining() == 0) { return new ArrayList<>(0); } else { ByteBuffer input = bytes.duplicate(); int size = input.getInt(); List<ElementT> result = new ArrayList<>(size); for (int i = 0; i < size; i++) { ElementT element; int elementSize = input.getInt(); if (elementSize < 0) { element = null; } else { ByteBuffer encodedElement = input.slice(); encodedElement.limit(elementSize); element = elementCodec.decode(encodedElement, protocolVersion); input.position(input.position() + elementSize); } result.add(element); } return result; } }
Source:
public boolean canPlaceAt(GlowPlayer player, GlowBlock block, BlockFace against) { return canPlaceAt(block, against); }

Target:
public boolean canPlaceAt(GlowPlayer player, GlowBlock block, BlockFace against) { return true; }
Source:
public synchronized Headers takeHeaders() throws IOException { readTimeout.enter(); try { while (headersQueue.isEmpty() && errorCode == null) { waitForIo(); } } finally { readTimeout.exitAndThrowIfTimedOut(); } if (!headersQueue.isEmpty()) { return headersQueue.removeFirst(); } if (errorException == null) throw new StreamResetException(errorCode); throw errorException; }

Target:
public synchronized Headers takeHeaders() throws IOException { readTimeout.enter(); try { while (headersQueue.isEmpty() && errorCode == null) { waitForIo(); } } finally { readTimeout.exitAndThrowIfTimedOut(); } if (!headersQueue.isEmpty()) { return headersQueue.removeFirst(); } throw errorException != null ? errorException : new StreamResetException(errorCode); }
Source:
public void isDiscontinued_shouldReturnTrueIfTheOrderIsScheduledForTheFutureAndActivatedOnCheckDateButTheCheckDateIsAfterDateStopped() throws Exception { Order order = new Order(); order.setUrgency(Urgency.ON_SCHEDULED_DATE); Date scheduledDateInFuture = DateUtils.addMonths(new Date(), 2); order.setScheduledDate(scheduledDateInFuture); Date activationDate = DateUtils.addDays(new Date(), -2); order.setDateActivated(activationDate); Date stopDate = new Date(); OrderUtilTest.setDateStopped(order, stopDate); assertNotNull(order.getDateActivated()); assertNotNull(order.getDateStopped()); assertNull(order.getAutoExpireDate()); assertTrue(order.isDiscontinued(DateUtils.addSeconds(stopDate, 1))); }

Target:
public void isDiscontinued_shouldReturnTrueIfTheOrderIsScheduledForTheFutureAndActivatedOnCheckDateButTheCheckDateIsAfterDateStopped() throws Exception { Order order = new Order(); order.setUrgency(Urgency.ON_SCHEDULED_DATE); Date today = new Date(); Date scheduledDateInFuture = DateUtils.addMonths(today, 2); order.setScheduledDate(scheduledDateInFuture); Date activationDate = DateUtils.addDays(today, -2); order.setDateActivated(activationDate); Date stopDate = new Date(); OrderUtilTest.setDateStopped(order, stopDate); assertNotNull(order.getDateActivated()); assertNotNull(order.getDateStopped()); assertNull(order.getAutoExpireDate()); assertTrue(order.isDiscontinued(DateUtils.addSeconds(stopDate, 1))); }
Source:
public static ArrayExpressionIn any(@NonNull VariableExpression variable) { if(variable == null) { throw new IllegalArgumentException("variable is null"); } return new ArrayExpressionIn(QuantifiesType.ANY, variable); }

Target:
public static ArrayExpressionIn any(@NonNull VariableExpression variable) { if (variable == null) { throw new IllegalArgumentException("variable is null."); } return new ArrayExpressionIn(QuantifiesType.ANY, variable); }
Source:
public int hashCode() { int result = factType.hashCode(); result = 31 * result + name.hashCode(); return result; }

Target:
public int hashCode() { int result = ~~factType.hashCode(); result = 31 * result + ~~name.hashCode(); return ~~result; }
Source:
public void commitEmptyCommits() throws Exception { Git git = new Git(db); writeTrashFile("file1", "file1"); git.add().addFilepattern("file1").call(); RevCommit initial = git.commit().setMessage("initial commit").call(); RevCommit emptyFollowUp = git.commit() .setAuthor("New Author", "newauthor@example.org") .setMessage("no change").call(); assertNotEquals(initial.getId(), emptyFollowUp.getId()); assertEquals(initial.getTree().getId(), emptyFollowUp.getTree().getId()); try { git.commit().setAuthor("New Author", "newauthor@example.org") .setMessage("again no change").setAllowEmpty(false) .call(); fail("Didn't got the expected EmtpyCommitException"); } catch (EmtpyCommitException e) { } }

Target:
public void commitEmptyCommits() throws Exception { try (Git git = new Git(db)) { writeTrashFile("file1", "file1"); git.add().addFilepattern("file1").call(); RevCommit initial = git.commit().setMessage("initial commit") .call(); RevCommit emptyFollowUp = git.commit() .setAuthor("New Author", "newauthor@example.org") .setMessage("no change").call(); assertNotEquals(initial.getId(), emptyFollowUp.getId()); assertEquals(initial.getTree().getId(), emptyFollowUp.getTree().getId()); try { git.commit().setAuthor("New Author", "newauthor@example.org") .setMessage("again no change").setAllowEmpty(false) .call(); fail("Didn't get the expected EmtpyCommitException"); } catch (EmtpyCommitException e) { } } }
Source:
private void checkAndMaybeComplete() { if (operationTracker.isDone()) { if (operationTracker.hasSucceeded()) { operationException.set(null); } operationCompleted = true; } if (operationCompleted) { Exception e = operationException.get(); if (operationResult == null && e == null) { e = new RouterException("Operation failed, but exception was not set", RouterErrorCode.UnexpectedInternalError); } if (e != null) { operationResult = null; routerMetrics.onGetBlobInfoError(e); } routerMetrics.getBlobInfoOperationLatencyMs.update(time.milliseconds() - submissionTimeMs); operationCompleteCallback.completeOperation(operationFuture, operationCallback, operationResult, e); } }

Target:
private void checkAndMaybeComplete() { if (operationTracker.isDone()) { if (operationTracker.hasSucceeded()) { operationException.set(null); } operationCompleted = true; } if (operationCompleted) { Exception e = operationException.get(); if (operationResult == null && e == null) { e = new RouterException("Operation failed, but exception was not set", RouterErrorCode.UnexpectedInternalError); routerMetrics.operationFailureWithUnsetExceptionCount.inc(); } if (e != null) { operationResult = null; routerMetrics.onGetBlobInfoError(e); } routerMetrics.getBlobInfoOperationLatencyMs.update(time.milliseconds() - submissionTimeMs); operationCompleteCallback.completeOperation(operationFuture, operationCallback, operationResult, e); } }
Source:
public void canSupportGuaranteedSize() throws InterruptedException, CameraInfoUnavailableException { for (int i = 0; i <= 1; i++) { final int lensFacing = i; if (CameraUtil.hasCameraWithLensFacing(lensFacing)) { continue; } String cameraId = CameraX.getCameraFactory().cameraIdForLensFacing(lensFacing); boolean isRotateNeeded = (CameraX.getCameraInfo(cameraId).getSensorRotationDegrees( Surface.ROTATION_0) % 180) != 0; ImageAnalysis useCase = new ImageAnalysis.Builder().setTargetResolution( GUARANTEED_RESOLUTION).setTargetRotation( isRotateNeeded ? Surface.ROTATION_90 : Surface.ROTATION_0).build(); mInstrumentation.runOnMainSync(() -> { CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing( lensFacing).build(); CameraX.bindToLifecycle(mLifecycleOwner, cameraSelector, useCase); mLifecycleOwner.startAndResume(); useCase.setAnalyzer(CameraXExecutors.newHandlerExecutor(mHandler), mAnalyzer); }); assertTrue(mAnalysisResultsSemaphore.tryAcquire(5, TimeUnit.SECONDS)); synchronized (mAnalysisResultLock) { assertEquals(GUARANTEED_RESOLUTION, mAnalysisResults.iterator().next().mResolution); } } }

Target:
public void canSupportGuaranteedSize() throws InterruptedException, CameraInfoUnavailableException { for (int i = 0; i <= 1; i++) { final int lensFacing = i; if (!CameraUtil.hasCameraWithLensFacing(lensFacing)) { continue; } String cameraId = CameraX.getCameraFactory().cameraIdForLensFacing(lensFacing); boolean isRotateNeeded = (CameraX.getCameraInfo(cameraId).getSensorRotationDegrees( Surface.ROTATION_0) % 180) != 0; ImageAnalysis useCase = new ImageAnalysis.Builder().setTargetResolution( GUARANTEED_RESOLUTION).setTargetRotation( isRotateNeeded ? Surface.ROTATION_90 : Surface.ROTATION_0).build(); mInstrumentation.runOnMainSync(() -> { CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing( lensFacing).build(); CameraX.bindToLifecycle(mLifecycleOwner, cameraSelector, useCase); mLifecycleOwner.startAndResume(); useCase.setAnalyzer(CameraXExecutors.newHandlerExecutor(mHandler), mAnalyzer); }); assertTrue(mAnalysisResultsSemaphore.tryAcquire(5, TimeUnit.SECONDS)); synchronized (mAnalysisResultLock) { assertEquals(GUARANTEED_RESOLUTION, mAnalysisResults.iterator().next().mResolution); } mInstrumentation.runOnMainSync(() -> { CameraX.unbindAll(); mLifecycleOwner.pauseAndStop(); }); } }
Source:
public static boolean isPem(String data) { if (CERT_PATTERN.matcher(data).find()) { return true; } if (PUBLIC_KEY_PATTERN.matcher(data).find()) { return true; } if (PRIVATE_KEY_PATTERN.matcher(data).find()) { return true; } return false; }

Target:
public static boolean isPem(String data) { return CERT_PATTERN.matcher(data).find() || PUBLIC_KEY_PATTERN.matcher(data).find() || PRIVATE_KEY_PATTERN.matcher(data).find(); }