auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void handleBinInfo(ITmfEvent event, final Long vpid, final ITmfStateSystemBuilder ss, boolean statedump) { Long baddr = event.getContent().getFieldValue(Long.class, fLayout.fieldBaddr()); Long memsz = event.getContent().getFieldValue(Long.class, fLayout.fieldMemsz()); String path = event.getContent().getFieldValue(String.class, fLayout.fieldPath()); Long hasBuildIdValue = event.getContent().getFieldValue(Long.class, fLayout.fieldHasBuildId()); Long hasDebugLinkValue = event.getContent().getFieldValue(Long.class, fLayout.fieldHasDebugLink()); Long isPicValue = event.getContent().getFieldValue(Long.class, fLayout.fieldIsPic()); if (baddr == null || memsz == null || path == null || hasBuildIdValue == null || hasDebugLinkValue == null || (statedump && isPicValue == null)) { LOGGER.warning(() -> "[UstDebugInfoStateProvider:InvalidBinInfoEvent] event=" + event.toString()); return; } boolean isPic; long ts; if (statedump) { isPic = (checkNotNull(isPicValue).longValue() != 0); Long statedumpStartTime = fLatestStatedumpStarts.get(vpid); if (statedumpStartTime == null) { ts = event.getTimestamp().getValue(); } else { ts = statedumpStartTime; } } else { isPic = true; ts = event.getTimestamp().getValue(); } boolean hasBuildId = (hasBuildIdValue != 0); boolean hasDebugLink = (hasDebugLinkValue != 0); PendingBinInfo p = new PendingBinInfo(hasBuildId, hasDebugLink, vpid, baddr, memsz, path, isPic); processPendingBinInfo(p, ts, ss); }

Target:
private void handleBinInfo(ITmfEvent event, final Long vpid, final ITmfStateSystemBuilder ss, boolean statedump) { Long baddr = event.getContent().getFieldValue(Long.class, fLayout.fieldBaddr()); Long memsz = event.getContent().getFieldValue(Long.class, fLayout.fieldMemsz()); String path = event.getContent().getFieldValue(String.class, fLayout.fieldPath()); Long hasBuildIdValue = event.getContent().getFieldValue(Long.class, fLayout.fieldHasBuildId()); Long hasDebugLinkValue = event.getContent().getFieldValue(Long.class, fLayout.fieldHasDebugLink()); Long isPicValue = event.getContent().getFieldValue(Long.class, fLayout.fieldIsPic()); if (baddr == null || memsz == null || path == null || hasBuildIdValue == null || hasDebugLinkValue == null || (statedump && isPicValue == null)) { LOGGER.warning(() -> "[UstDebugInfoStateProvider:InvalidBinInfoEvent] event=" + event.toString()); return; } boolean isPic = (statedump ? (checkNotNull(isPicValue).longValue() != 0) : true); long ts = getBinInfoTimeStamp(event, vpid, statedump); boolean hasBuildId = (hasBuildIdValue != 0); boolean hasDebugLink = (hasDebugLinkValue != 0); PendingBinInfo p = new PendingBinInfo(hasBuildId, hasDebugLink, vpid, baddr, memsz, path, isPic); processPendingBinInfo(p, ts, ss); }
Source:
public VariantContextWriterBuilder() { if (Defaults.USE_ASYNC_IO_FOR_TRIBBLE) options.add(Options.USE_ASYNC_IO); }

Target:
public VariantContextWriterBuilder() { if (Defaults.USE_ASYNC_IO_FOR_TRIBBLE) { options.add(Options.USE_ASYNC_IO); } }
Source:
private void unregisterAllInstances() { synchronized (_instanceMonitorMap) { _instanceMonitorMap.values().forEach(monitor -> monitor.unregister()); } }

Target:
private void unregisterAllInstances() { synchronized (_instanceMonitorMap) { unregisterInstances(_instanceMonitorMap.keySet()); } }
Source:
private void fetchLangLinks() { if (languageEntries == null) { new LangLinksClient().request(title.getWikiSite(), title, new LangLinksClient.Callback() { @Override public void success(@NonNull Call<MwQueryResponse<LangLinks>> call, @NonNull List<PageTitle> links) { languageEntries = links; updateLanguageEntriesSupported(languageEntries); sortLanguageEntriesByMru(languageEntries); displayLangLinks(); } @Override public void failure(@NonNull Call<MwQueryResponse<LangLinks>> call, @NonNull Throwable caught) { ViewAnimations.crossFade(langLinksProgress, langLinksError); langLinksError.setError(caught); } }); } else { displayLangLinks(); } }

Target:
private void fetchLangLinks() { if (languageEntries == null) { client.request(title.getWikiSite(), title, new LangLinksClient.Callback() { @Override public void success(@NonNull Call<MwQueryResponse<LangLinks>> call, @NonNull List<PageTitle> links) { languageEntries = links; callback.updateLanguageEntriesSupported(languageEntries); callback.sortLanguageEntriesByMru(languageEntries); displayLangLinks(); } @Override public void failure(@NonNull Call<MwQueryResponse<LangLinks>> call, @NonNull Throwable caught) { ViewAnimations.crossFade(langLinksProgress, langLinksError); langLinksError.setError(caught); } }); } else { displayLangLinks(); } }
Source:
private void createDeleteTool(ToolSection toolSection, DiagramElementMapping... mappings) { if (!globalDeleteTool) { DeleteElementDescription deleteElement = ToolFactory.eINSTANCE.createDeleteElementDescription(); deleteElement.setName(baseId + "global.delete"); deleteElement.setLabel("Delete Tool"); toolSection.getOwnedTools().add(deleteElement); for (DiagramElementMapping dem : mappings) { deleteElement.getMappings().add(dem); } } else { for (DiagramElementMapping dem : mappings) { DeleteElementDescription deleteElement = ToolFactory.eINSTANCE.createDeleteElementDescription(); deleteElement.setName("global.delete" + "." + ((ClassDiagramPattern) dem).getBaseId()); deleteElement.setLabel("Delete Tool" + " " + dem.getLabel()); toolSection.getOwnedTools().add(deleteElement); deleteElement.getMappings().add(dem); } } }

Target:
private void createDeleteTool(ToolSection toolSection, DiagramElementMapping... mappings) { if (!globalDeleteTool) { DeleteElementDescription deleteElement = ToolFactory.eINSTANCE.createDeleteElementDescription(); deleteElement.setName(baseId + "global.delete"); deleteElement.setLabel("Delete Tool"); toolSection.getOwnedTools().add(deleteElement); for (DiagramElementMapping dem : mappings) { deleteElement.getMappings().add(dem); } } else { for (DiagramElementMapping dem : mappings) { DeleteElementDescription deleteElement = ToolFactory.eINSTANCE.createDeleteElementDescription(); deleteElement.setName(baseId + ".global.delete" + "." + baseId); deleteElement.setLabel("Delete Tool" + " " + dem.getLabel()); toolSection.getOwnedTools().add(deleteElement); deleteElement.getMappings().add(dem); } } }
Source:
public static void setAliases(Map<String, String> aliases) { SimpleUnitFormat format = AbstractNetCDFUnitFormat.getNewInstance(); Unit bel = ONE.transform(new LogConverter(10)); format.alias(bel.divide(10), "dB"); for (Unit u : NonSI.getInstance().getUnits()) { if (u.getSymbol() != null && unknownSymbol(format, u.getSymbol())) { System.out.println(u.getSymbol() + " -> " + u); format.alias(u, u.getSymbol()); } } format.label(AbstractUnit.ONE, "unitless"); for (Map.Entry<String, String> entry : aliases.entrySet()) { try { format.alias(format.parse(entry.getValue()), entry.getKey()); } catch (ParserException ex) { throw new RuntimeException( "Failed to parse " + entry.getKey() + " -> " + entry.getValue(), ex); } } FORMAT = format; }

Target:
public static void setAliases(Map<String, String> aliases) { SimpleUnitFormat format = AbstractNetCDFUnitFormat.getNewInstance(); Unit bel = ONE.transform(new LogConverter(10)); format.alias(bel.divide(10), "dB"); for (Unit u : NonSI.getInstance().getUnits()) { if (u.getSymbol() != null && unknownSymbol(format, u.getSymbol())) { format.alias(u, u.getSymbol()); } } format.label(AbstractUnit.ONE, "unitless"); for (Map.Entry<String, String> entry : aliases.entrySet()) { try { format.alias(format.parse(entry.getValue()), entry.getKey()); } catch (ParserException ex) { LOGGER.log( Level.WARNING, "Failed to parse " + entry.getKey() + " -> " + entry.getValue() + ", skipped.", ex); } } FORMAT = format; }
Source:
public void persistState(String checkpointId) { if (!isTopologyStateful) { throw new RuntimeException("Could not save a non-stateful topology's state"); } if (spout instanceof IStatefulComponent) { ((IStatefulComponent) spout).preSave(checkpointId); } else { LOG.info("Trying to checkponit a non stateful component. Send empty state"); } collector.sendOutState(instanceState, checkpointId); }

Target:
public void persistState(String checkpointId) { LOG.info("Persisting state for checkpoint: " + checkpointId); if (!isTopologyStateful) { throw new RuntimeException("Could not save a non-stateful topology's state"); } if (spout instanceof IStatefulComponent) { ((IStatefulComponent) spout).preSave(checkpointId); } collector.sendOutState(instanceState, checkpointId); }
Source:
public void build_createANewRadiologyOrderSearchCriteriaInstanceWithToEffectiveStartDateIfToEffectiveStartDateIsSet() throws Exception { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date toEffectiveStartDate = format.parse("2016-05-01"); radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withToEffectiveStartDate(toEffectiveStartDate) .build(); assertTrue(radiologyOrderSearchCriteria.getToEffectiveStartDate() .equals(toEffectiveStartDate)); assertNull(radiologyOrderSearchCriteria.getPatient()); assertFalse(radiologyOrderSearchCriteria.getIncludeVoided()); assertNull(radiologyOrderSearchCriteria.getUrgency()); assertNull(radiologyOrderSearchCriteria.getFromEffectiveStartDate()); }

Target:
public void build_createANewRadiologyOrderSearchCriteriaInstanceWithToEffectiveStartDateIfToEffectiveStartDateIsSet() throws Exception { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date toEffectiveStartDate = format.parse("2016-05-01"); radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withToEffectiveStartDate(toEffectiveStartDate) .build(); assertThat(radiologyOrderSearchCriteria.getToEffectiveStartDate(), is(toEffectiveStartDate)); assertNull(radiologyOrderSearchCriteria.getPatient()); assertFalse(radiologyOrderSearchCriteria.getIncludeVoided()); assertNull(radiologyOrderSearchCriteria.getUrgency()); assertNull(radiologyOrderSearchCriteria.getFromEffectiveStartDate()); }
Source:
public String toString() { StringBuilder sb = new StringBuilder(getClass().getName()); sb.append("={id='"); sb.append(getId()); sb.append("', hostId='"); sb.append(getHostId()); sb.append("', order='"); sb.append(getOrder()); sb.append("', type='"); sb.append(getType()); sb.append("', ip='"); sb.append(getIp()); sb.append("', port='"); sb.append(getPort()); sb.append("', user='"); sb.append(getUser()); sb.append("', password='"); sb.append(getPassword() == null || getPassword().length() < 1 ? "" : "***"); sb.append("', encryptOptions='"); sb.append(getEncryptOptions()); sb.append("', options='"); sb.append(getOptions()); sb.append("'}"); return sb.toString(); }

Target:
public String toString() { return ToStringBuilder.forInstance(this) .append("id", getId()) .append("hostId", getHostId()) .append("order", getOrder()) .append("type", getType()) .append("ip", getIp()) .append("port", getPort()) .append("user", getUser()) .appendFiltered("password", getPassword()) .append("encryptOptions", getEncryptOptions()) .append("options", getOptions()) .build(); }
Source:
@Test public void customSampler() throws Exception { String path = "/foo"; SamplerFunction<HttpRequest> sampler = (HttpRuleSampler.newBuilder() .putRule(pathStartsWith(path), Sampler.NEVER_SAMPLE) .build()); httpTracing = httpTracing.toBuilder().serverSampler(sampler).build(); init(); Request request = new Request.Builder().url(url(path)).build(); try (Response response = client.newCall(request).execute()) { assertThat(response.isSuccessful()).isTrue(); } }

Target:
@Test public void customSampler() throws Exception { String path = "/foo"; SamplerFunction<HttpRequest> sampler = HttpRuleSampler.newBuilder() .putRule(pathStartsWith(path), Sampler.NEVER_SAMPLE) .build(); httpTracing = httpTracing.toBuilder().serverSampler(sampler).build(); init(); Request request = new Request.Builder().url(url(path)).build(); try (Response response = client.newCall(request).execute()) { assertThat(response.isSuccessful()).isTrue(); } }
Source:
static SharedCache build(int L1capacity, long maxCacheSizeBytes) { checkArgument(L1capacity >= 0); checkArgument(maxCacheSizeBytes >= 0, "Cache size can't be < 0, 0 meaning no cache at all"); if (0L == maxCacheSizeBytes) { return NO_CACHE; } int initialCapacityCount = 1_000_000; int concurrencyLevel = 16; CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); cacheBuilder = cacheBuilder.maximumWeight(maxCacheSizeBytes); cacheBuilder.weigher(Impl.WEIGHER); cacheBuilder.initialCapacity(initialCapacityCount); cacheBuilder.concurrencyLevel(concurrencyLevel); cacheBuilder.recordStats(); Impl.SizeTracker sizeTracker = new Impl.SizeTracker(); cacheBuilder.removalListener(sizeTracker); Cache<Key, byte[]> byteCache = cacheBuilder.build(); return new Impl(L1capacity, byteCache, sizeTracker); }

Target:
static SharedCache build(int L1capacity, long maxCacheSizeBytes) { checkArgument(L1capacity >= 0); checkArgument(maxCacheSizeBytes >= 0, "Cache size can't be < 0, 0 meaning no cache at all"); if (0L == maxCacheSizeBytes) { return NO_CACHE; } int initialCapacityCount = 1_000_000; int concurrencyLevel = 16; CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); cacheBuilder = cacheBuilder.maximumWeight(maxCacheSizeBytes); cacheBuilder.weigher(Impl.SizeTracker.WEIGHER); cacheBuilder.initialCapacity(initialCapacityCount); cacheBuilder.concurrencyLevel(concurrencyLevel); cacheBuilder.recordStats(); Impl.SizeTracker sizeTracker = new Impl.SizeTracker(); cacheBuilder.removalListener(sizeTracker); Cache<Key, byte[]> byteCache = cacheBuilder.build(); return new Impl(L1capacity, byteCache, sizeTracker); }
Source:
protected void executeCommand() { getParameters().setEntityInfo(new EntityInfo(VdcObjectType.VmTemplate, getVmTemplateId())); setSucceeded(true); if (!images.isEmpty()) { List<DiskImage> imageToRemove = new ArrayList<>(); for (DiskImage image : images) { if (image.getStorageIds().get(0).equals(getParameters().getStorageDomainId())) { image.setStorageIds(Collections.singletonList(getParameters().getStorageDomainId())); image.setStoragePoolId(getParameters().getStoragePoolId()); imageToRemove.add(image); } } RemoveAllVmImagesParameters removeAllVmImagesParameters = new RemoveAllVmImagesParameters(getVmId(), imageToRemove); removeAllVmImagesParameters.setParentCommand(getActionType()); removeAllVmImagesParameters.setEntityInfo(getParameters().getEntityInfo()); removeAllVmImagesParameters.setForceDelete(true); removeAllVmImagesParameters.setParentParameters(getParameters()); ActionReturnValue vdcRetValue = runInternalActionWithTasksContext(ActionType.RemoveAllVmImages, removeAllVmImagesParameters); if (vdcRetValue.getSucceeded()) { getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } else { getReturnValue().setFault(vdcRetValue.getFault()); setSucceeded(false); } } vmAndTemplatesGenerationsDao.deleteOvfGenerations(Collections.singletonList(ovfEntityData.getEntityId())); unregisteredOVFDataDao.removeEntity(ovfEntityData.getEntityId(), null); unregisteredDisksDao.removeUnregisteredDiskRelatedToVM(ovfEntityData.getEntityId(), null); }

Target:
protected void executeCommand() { getParameters().setEntityInfo(new EntityInfo(VdcObjectType.VmTemplate, getVmTemplateId())); setSucceeded(true); if (images != null && !images.isEmpty()) { List<DiskImage> imageToRemove = new ArrayList<>(); for (DiskImage image : images) { if (image.getStorageIds().get(0).equals(getParameters().getStorageDomainId())) { image.setStorageIds(Collections.singletonList(getParameters().getStorageDomainId())); image.setStoragePoolId(getParameters().getStoragePoolId()); imageToRemove.add(image); } } RemoveAllVmImagesParameters removeAllVmImagesParameters = new RemoveAllVmImagesParameters(getVmId(), imageToRemove); removeAllVmImagesParameters.setParentCommand(getActionType()); removeAllVmImagesParameters.setEntityInfo(getParameters().getEntityInfo()); removeAllVmImagesParameters.setForceDelete(true); removeAllVmImagesParameters.setParentParameters(getParameters()); ActionReturnValue vdcRetValue = runInternalActionWithTasksContext(ActionType.RemoveAllVmImages, removeAllVmImagesParameters); if (vdcRetValue.getSucceeded()) { getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } else { getReturnValue().setFault(vdcRetValue.getFault()); setSucceeded(false); } } vmAndTemplatesGenerationsDao.deleteOvfGenerations(Collections.singletonList(ovfEntityData.getEntityId())); unregisteredOVFDataDao.removeEntity(ovfEntityData.getEntityId(), null); unregisteredDisksDao.removeUnregisteredDiskRelatedToVM(ovfEntityData.getEntityId(), null); }
Source:
private List<Rule> getRules( FeatureCollection features, String property, Class<?> propertyType, int classNumber, boolean open, boolean normalize, String functionName) { try { final Function classify = FF.function( functionName, FF.property(property), FF.literal(classNumber), FF.literal(outputPercentages)); Classifier groups = (Classifier) classify.evaluate(features); if (groups instanceof RangedClassifier) if (open) return openRangedRules( (RangedClassifier) groups, property, propertyType, normalize); else return closedRangedRules( (RangedClassifier) groups, property, propertyType, normalize); else if (groups instanceof ExplicitClassifier) return this.explicitRules((ExplicitClassifier) groups, property, propertyType); } catch (Exception e) { if (LOGGER.isLoggable(Level.INFO)) LOGGER.log( Level.INFO, "Failed to build " + functionName + " Classification" + e.getLocalizedMessage(), e); } return null; }

Target:
private List<Rule> getRules( FeatureCollection features, String property, Class<?> propertyType, int classNumber, boolean open, boolean normalize, String functionName) { try { final Function classify; if (functionName.equals("EqualArea")) { classify = FF.function( functionName, FF.property(property), FF.literal(classNumber), FF.literal(""), FF.literal(outputPercentages)); } else { classify = FF.function( functionName, FF.property(property), FF.literal(classNumber), FF.literal(outputPercentages)); } Classifier groups = (Classifier) classify.evaluate(features); if (groups instanceof RangedClassifier) if (open) return openRangedRules( (RangedClassifier) groups, property, propertyType, normalize); else return closedRangedRules( (RangedClassifier) groups, property, propertyType, normalize); else if (groups instanceof ExplicitClassifier) return this.explicitRules((ExplicitClassifier) groups, property, propertyType); } catch (Exception e) { if (LOGGER.isLoggable(Level.INFO)) LOGGER.log( Level.INFO, "Failed to build " + functionName + " Classification" + e.getLocalizedMessage(), e); } return null; }
Source:
public SetVdsStatusVDSCommandParameters() { _status = VDSStatus.Unassigned; nonOperationalReason = NonOperationalReason.NONE; }

Target:
public SetVdsStatusVDSCommandParameters() { _status = VDSStatus.Unassigned; nonOperationalReason = NonOperationalReason.NONE; stopSpmFailureLogged = false; }
Source:
public static int size(JsonNode node) { int size = 0; if (node instanceof ArrayNode) { for (Iterator<JsonNode> elements = ((ArrayNode) node).elements(); elements.hasNext();) { size += size(elements.next()); } } else if (node instanceof ObjectNode) { for (Iterator<Map.Entry<String, JsonNode>> fields = ((ObjectNode) node).fields(); fields.hasNext();) { Map.Entry<String, JsonNode> field = fields.next(); size += field.getKey().length(); size += size(field.getValue()); } } else if (node instanceof NumericNode) { size += 4; } else { size += node.asText().length(); } return size; }

Target:
public static int size(JsonNode node) { if (node == null) { return 0; } int size = 0; if (node instanceof ArrayNode) { for (Iterator<JsonNode> elements = ((ArrayNode) node).elements(); elements.hasNext();) { size += size(elements.next()); } } else if (node instanceof ObjectNode) { for (Iterator<Map.Entry<String, JsonNode>> fields = ((ObjectNode) node).fields(); fields.hasNext();) { Map.Entry<String, JsonNode> field = fields.next(); size += field.getKey().length(); size += size(field.getValue()); } } else if (node instanceof NumericNode) { size += 4; } else { size += node.asText().length(); } return size; }
Source:
public List<ServerModule> getModules() { List<ServerModule> childModules = new ArrayList<ServerModule>(); List<TreeItem> childModuleTreeItems = this.treeItem.getItems(); for (TreeItem item : childModuleTreeItems) { childModules.add(new ServerModule(item, view)); } return childModules; }

Target:
public List<ServerModule> getModules() { List<ServerModule> childModules = new ArrayList<ServerModule>(); List<TreeItem> childModuleTreeItems = getTreeItem().getItems(); for (TreeItem item : childModuleTreeItems) { childModules.add(new ServerModule(item, view)); } return childModules; }
Source:
synchronized void setOps(final SelectionKey key, final int ops) { if (currentThread() == this) { try { key.interestOps(key.interestOps() | ops); } catch (CancelledKeyException ignored) } else if (OLD_LOCKING) { final SynchTask task = new SynchTask(); queueTask(task); try { selector.wakeup(); key.interestOps(key.interestOps() | ops); } catch (CancelledKeyException ignored) { } finally { task.done(); } } else { try { key.interestOps(key.interestOps() | ops); if (polling) selector.wakeup(); } catch (CancelledKeyException ignored) { } } }

Target:
void setOps(final SelectionKey key, final int ops) { if (currentThread() == this) { try { synchronized(key) { key.interestOps(key.interestOps() | ops); } } catch (CancelledKeyException ignored) } else if (OLD_LOCKING) { final SynchTask task = new SynchTask(); queueTask(task); try { selector.wakeup(); synchronized(key) { key.interestOps(key.interestOps() | ops); } } catch (CancelledKeyException ignored) { } finally { task.done(); } } else { try { synchronized(key) { key.interestOps(key.interestOps() | ops); } if (polling) selector.wakeup(); } catch (CancelledKeyException ignored) { } } }
Source:
public void shouldLoadMultipleJavaModules_ToolchainsXML() throws IOException { OutputValidator validator = assumeJava9Property() .setForkJvm() .activateProfile( "use-toolchains" ) .addGoal( "--toolchains" ) .addGoal( System.getProperty( "maven.toolchains.file" ) ) .execute( "verify" ) .verifyErrorFree( 1 ); validator.verifyTextInLog( "loaded class java.sql.SQLException" ) .verifyTextInLog( "loaded class javax.xml.ws.Holder" ) .verifyTextInLog( "loaded class javax.transaction.TransactionManager" ) .verifyTextInLog( "loaded class javax.transaction.InvalidTransactionException" ) .verifyTextInLog( "loaded class javax.xml.bind.JAXBException" ) .verifyTextInLog( "java.specification.version=9" ); }

Target:
public void shouldLoadMultipleJavaModules_ToolchainsXML() throws IOException { OutputValidator validator = assumeJava9Property() .setForkJvm() .activateProfile( "use-toolchains" ) .addGoal( "--toolchains" ) .addGoal( System.getProperty( "maven.toolchains.file" ) ) .execute( "verify" ) .verifyErrorFree( 1 ); validator.verifyTextInLog( "loaded class java.sql.SQLException" ) .verifyTextInLog( "loaded class javax.xml.ws.Holder" ) .verifyTextInLog( "loaded class javax.xml.bind.JAXBException" ) .verifyTextInLog( "loaded class javax.transaction.TransactionManager" ) .verifyTextInLog( "loaded class javax.transaction.InvalidTransactionException" ) .verifyTextInLog( "java.specification.version=9" ); }
Source:
public MessageChannel getInputChannel() { return this.inputChannel == null ? null : this.inputChannel; }

Target:
public MessageChannel getInputChannel() { return this.inputChannel; }
Source:
public void updateJobAndTasksStatuses(final InternalJob job, final Set<TaskId> taskIds, TaskStatus taskStatus) { executeReadWriteTransaction(new SessionWork<Void>() { @Override public Void doInTransaction(Session session) { updateTasksStatuses(taskIds, taskStatus, session); JobInfo jobInfo = job.getJobInfo(); session.getNamedQuery("updateJobAndTasksState") .setParameter("status", jobInfo.getStatus()) .setParameter("numberOfFailedTasks", jobInfo.getNumberOfFailedTasks()) .setParameter("numberOfFaultyTasks", jobInfo.getNumberOfFaultyTasks()) .setParameter("numberOfInErrorTasks", jobInfo.getNumberOfInErrorTasks()) .setParameter("inErrorTime", jobInfo.getInErrorTime()) .setParameter("lastUpdatedTime", new Date().getTime()) .setParameter("jobId", jobId(job)) .executeUpdate(); return null; } }); }

Target:
public void updateJobAndTasksStatuses(final InternalJob job, final Set<TaskId> taskIds, TaskStatus taskStatus) { executeReadWriteTransaction((SessionWork<Void>) session -> { updateTasksStatuses(taskIds, taskStatus, session); JobInfo jobInfo = job.getJobInfo(); session.getNamedQuery("updateJobAndTasksState") .setParameter("status", jobInfo.getStatus()) .setParameter("numberOfFailedTasks", jobInfo.getNumberOfFailedTasks()) .setParameter("numberOfFaultyTasks", jobInfo.getNumberOfFaultyTasks()) .setParameter("numberOfInErrorTasks", jobInfo.getNumberOfInErrorTasks()) .setParameter("inErrorTime", jobInfo.getInErrorTime()) .setParameter("lastUpdatedTime", new Date().getTime()) .setParameter("jobId", jobId(job)) .executeUpdate(); return null; }); }
Source:
private String getWeatherData(String url) { try { String httpResponse = HttpUtil.executeUrl("GET", url, 30 * 1000); logger.trace("http response: {}", httpResponse); return httpResponse; } catch (IOException e) { logger.warn("I/O Exception occurred while retrieving weather data.", e); return null; } }

Target:
private String getWeatherData(String url) { try { String httpResponse = HttpUtil.executeUrl("GET", url, 30 * 1000); logger.trace("http response: {}", httpResponse); return httpResponse; } catch (IOException e) { logger.debug("I/O Exception occurred while retrieving weather data.", e); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "I/O Exception occurred while retrieving weather data."); return null; } }
Source:
public void init() { get( "/events", (req, res) -> { try { res.type("text/event-stream; charset=UTF-8"); res.header("Connection", "keep-alive"); res.header("Cache-Control", "no-cache"); res.status(200); PrintWriter out = res.raw().getWriter(); synchronized (listeners) { listeners.add(out); } out.write(HEARTBEAT); out.flush(); while (true) { out.write(HEARTBEAT); if (out.checkError()) { break; } Thread.sleep(1000); } listeners.remove(out); return "Event Source setup successful"; } catch (Exception e) { LOGGER.error("Event Source configuration error"); } res.status(500); return "Event Source configuration error: Server error"; }); }

Target:
public void init() { get( "/events/:id", (req, res) -> { try { String sourceId = req.params(":id"); if (listeners.size() >= 5) { notifyListener(sourceId, new EventType("CLOSE")); res.status(429); return "Too many HTTP connections - cannot create new Event Source"; } res.type("text/event-stream; charset=UTF-8"); res.header("Connection", "keep-alive"); res.header("Cache-Control", "no-cache"); PrintWriter out = res.raw().getWriter(); res.status(200); listeners.put(sourceId, out); while (!out.checkError()) { out.write(HEARTBEAT); out.flush(); Thread.sleep(15000); } notifyListener(sourceId, new EventType("CLOSE")); listeners.remove(sourceId); return "Event Source connection closed"; } catch (Exception e) { LOGGER.error("Event Source configuration error"); } res.status(500); return "Event Source configuration error: Server error"; }); }
Source:
private boolean isSlyList(TagNode node) { return "data-sly-list".equals(node.getAttributes().iterator().next().getName()); }

Target:
private boolean isSlyList(TagNode node) { return node.getAttributes().stream() .anyMatch(attribute -> "data-sly-list".equals(attribute.getName())); }
Source:
public void stop() { for (Entry<CacheType,BlockCache> e : this.caches.entrySet()) { ((LruBlockCache) e.getValue()).shutdown(); } super.stop(); }

Target:
public void stop() { for (CacheType type : CacheType.values()) { LruBlockCache cache = ((LruBlockCache) this.getBlockCache(type)); if (null != cache) { cache.shutdown(); } } super.stop(); }
Source:
public void newIssue() { logger.info("Navigating to New Issue page"); if (isBrowserActive()) { runBrowserOperation(() -> { if (!driver.getCurrentUrl().equals(GitHubURL.getPathForNewIssue())) { driver.get(GitHubURL.getPathForNewIssue()); } }); } else{ resetBrowser(); newIssue(); } }

Target:
public void newIssue() { logger.info("Navigating to New Issue page"); runBrowserOperation(() -> { if (!driver.getCurrentUrl().equals(GitHubURL.getPathForNewIssue())) { driver.get(GitHubURL.getPathForNewIssue()); } }); }
Source:
public void removeFromJobs(boolean isGlobal, ITmfTrace jobTrace) { Map<ITmfTrace, Job> updateJobs = isGlobal ? fUpdateJobsGlobal : fUpdateJobsPartial; Job job = updateJobs.remove(jobTrace); if (job != null) { job.cancel(); } }

Target:
void removeFromJobs(boolean isGlobal, ITmfTrace jobTrace) { Map<ITmfTrace, Job> updateJobs = isGlobal ? fUpdateJobsGlobal : fUpdateJobsPartial; Job job = updateJobs.remove(jobTrace); if (job != null) { job.cancel(); } }
Source:
public void findAllTest() throws Exception { getClient().perform(get("/api/eperson/groups")) .andExpect(status().isForbidden()); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/eperson/groups")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$._embedded.groups", hasSize(2))) .andExpect(jsonPath("$._embedded.groups", Matchers.containsInAnyOrder( GroupMatcher.matchGroupWithName("Administrator"), GroupMatcher.matchGroupWithName("Anonymous") ))) ; }

Target:
public void findAllTest() throws Exception { getClient().perform(get("/api/eperson/groups")) .andExpect(status().isUnauthorized()); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/eperson/groups")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$._embedded.groups", hasSize(2))) .andExpect(jsonPath("$._embedded.groups", Matchers.containsInAnyOrder( GroupMatcher.matchGroupWithName("Administrator"), GroupMatcher.matchGroupWithName("Anonymous") ))) ; }
Source:
private void reEncryptMasterKey(final SmartMeteringDeviceDto smartMeteringDevice) throws ProtocolAdapterException { if (smartMeteringDevice.getMasterKey() == null || smartMeteringDevice.getMasterKey().length <= 0) { return; } final byte[] reEncryptedMasterKey = this.securityKeyService.reEncryptKey(smartMeteringDevice.getMasterKey(), SecurityKeyType.E_METER_MASTER); smartMeteringDevice.setMasterKey(reEncryptedMasterKey); }

Target:
private void reEncryptMasterKey(final SmartMeteringDeviceDto smartMeteringDevice) throws ProtocolAdapterException { if (ArrayUtils.isEmpty(smartMeteringDevice.getMasterKey())) { return; } final byte[] reEncryptedMasterKey = this.securityKeyService.reEncryptKey(smartMeteringDevice.getMasterKey(), SecurityKeyType.E_METER_MASTER); smartMeteringDevice.setMasterKey(reEncryptedMasterKey); }
Source:
boolean matchesUser(LDUser user) { JsonElement userValue = valueOf(user, attribute); if (userValue == null) { return false; } if (userValue.isJsonArray()) { JsonArray array = userValue.getAsJsonArray(); for (JsonElement jsonElement : array) { if (!jsonElement.isJsonPrimitive()) { logger.error("Invalid custom attribute value in user object: " + jsonElement); return false; } if (matchAny(jsonElement.getAsJsonPrimitive())) { return maybeNegate(true); } } return maybeNegate(false); } if (userValue.isJsonPrimitive()) { return maybeNegate(matchAny(userValue.getAsJsonPrimitive())); } logger.warn("Got unexpected user attribute type: " + userValue.getClass().getName() + " for user key: " + user.getKey() + " and attribute: " + attribute); return false; }

Target:
boolean matchesUser(LDUser user) { JsonElement userValue = valueOf(user, attribute); if (userValue == null) { return false; } if (userValue.isJsonArray()) { JsonArray array = userValue.getAsJsonArray(); for (JsonElement jsonElement : array) { if (!jsonElement.isJsonPrimitive()) { logger.error("Invalid custom attribute value in user object: " + jsonElement); return false; } if (matchAny(jsonElement.getAsJsonPrimitive())) { return maybeNegate(true); } } return maybeNegate(false); } else if (userValue.isJsonPrimitive()) { return maybeNegate(matchAny(userValue.getAsJsonPrimitive())); } logger.warn("Got unexpected user attribute type: " + userValue.getClass().getName() + " for user key: " + user.getKey() + " and attribute: " + attribute); return false; }
Source:
public ElasticsearchTableDescription( @JsonProperty("tableName") String tableName, @JsonProperty("schemaName") String schemaName, @JsonProperty("host") String host, @JsonProperty("port") int port, @JsonProperty("clusterName") String clusterName, @JsonProperty("index") String index, @JsonProperty("indexExactMatch") boolean indexExactMatch, @JsonProperty("type") String type, @JsonProperty("columns") Optional<List<ElasticsearchColumn>> columns) { checkArgument(!isNullOrEmpty(tableName), "tableName is null or is empty"); checkArgument(!isNullOrEmpty(host), "hostis null or is empty"); checkArgument(!isNullOrEmpty(clusterName), "clusterName is null or is empty"); checkArgument(!isNullOrEmpty(index), "index is null or is empty"); checkArgument(!isNullOrEmpty(type), "type is null or is empty"); this.tableName = tableName; this.schemaName = schemaName; this.host = host; this.port = port; this.clusterName = clusterName; this.index = index; this.indexExactMatch = indexExactMatch; this.type = type; this.columns = requireNonNull(columns, "columns is null"); }

Target:
public ElasticsearchTableDescription( @JsonProperty("tableName") String tableName, @JsonProperty("schemaName") String schemaName, @JsonProperty("host") String host, @JsonProperty("port") int port, @JsonProperty("clusterName") String clusterName, @JsonProperty("index") String index, @JsonProperty("indexExactMatch") boolean indexExactMatch, @JsonProperty("type") String type, @JsonProperty("columns") Optional<List<ElasticsearchColumn>> columns) { checkArgument(!isNullOrEmpty(tableName), "tableName is null or empty"); checkArgument(!isNullOrEmpty(host), "host is null or empty"); checkArgument(!isNullOrEmpty(clusterName), "clusterName is null or empty"); checkArgument(!isNullOrEmpty(index), "index is null or empty"); checkArgument(!isNullOrEmpty(type), "type is null or empty"); requireNonNull(columns, "columns is null"); this.tableName = tableName; this.schemaName = schemaName; this.host = host; this.port = port; this.clusterName = clusterName; this.index = index; this.indexExactMatch = indexExactMatch; this.type = type; this.columns = columns; }
Source:
public String probeState() { List<String> repositoryNames = Framework.getService(RepositoryService.class).getRepositoryNames(); List<String> probes = repositoryNames.stream().map(this::probeRepository).collect(Collectors.toList()); if (probes.contains(MIGRATION_STATE_RELATION)) { return MIGRATION_STATE_RELATION; } else if (probes.contains(MIGRATION_STATE_PROPERTY)) { return MIGRATION_STATE_PROPERTY; } return MIGRATION_STATE_SECURED; }

Target:
public String probeState() { List<String> repositoryNames = Framework.getService(RepositoryService.class).getRepositoryNames(); if (repositoryNames.stream().map(this::probeRepository).anyMatch(isEqual(MIGRATION_STATE_RELATION))) { return MIGRATION_STATE_RELATION; } return MIGRATION_STATE_PROPERTY; }
Source:
public void run() { try { LOG.debug(String.format("[consumer tag: %s] Starting message processing: %s", consumerTag, body)); msgHandler.onMessage(body, ackHandler); LOG.debug(String.format("[consumer tag: %s] Message has been processed: %s", consumerTag, body)); ackHandler.autoConfirm(); } catch (Exception e) { LOG.error(String.format("[consumer tag: %s] Failed to process message %s", consumerTag, body), e); ackHandler.autoReject(); } }

Target:
public void run() { try { LOG.debug(String.format("[consumer tag: %s] Starting message processing: %s", consumerTag, body)); msgHandler.onMessage(body, ackHandler); LOG.debug(String.format("[consumer tag: %s] Message has been processed: %s", consumerTag, body)); ackHandler.autoConfirm(); } catch (Exception e) { LOG.error(String.format("[consumer tag: %s] Failed to process message %s", consumerTag, body), e); ackHandler.autoRetry(); } }
Source:
public JSONArray mergeJsonArrays(JSONArray currentArray, JSONArray arrayToAdd) { String currentJsonString = currentArray.toString(); String toAddJsonString = arrayToAdd.toString(); StringBuilder sb = new StringBuilder(); if (!currentJsonString.equals("[]")) { sb.append(currentJsonString.trim()); sb.replace(currentJsonString.length() - 1, currentJsonString.length(), ","); sb.append(toAddJsonString.replaceFirst("\\[", "")); } else { sb.append(toAddJsonString); } JSONArray toReturn; try { toReturn = new JSONArray(sb.toString()); } catch (JSONException ex) { toReturn = currentArray; throw new OseeCoreException(ex); } return toReturn; }

Target:
public JSONArray mergeJsonArrays(JSONArray currentArray, JSONArray arrayToAdd) { String currentJsonString = currentArray.toString().trim(); String toAddJsonString = arrayToAdd.toString(); StringBuilder sb = new StringBuilder(); if (!currentJsonString.equals("[]")) { sb.append(currentJsonString); sb.replace(currentJsonString.length() - 1, currentJsonString.length(), ","); sb.append(toAddJsonString.replaceFirst("\\[", "")); } else { sb.append(toAddJsonString); } JSONArray toReturn; try { toReturn = new JSONArray(sb.toString()); } catch (JSONException ex) { toReturn = currentArray; throw new OseeCoreException(ex); } return toReturn; }
Source:
public static Iterable<String> readLocalFile(final String fileName) throws IOException { return Files.readAllLines(Paths.get(DOWNLOAD_BASE_NAME + fileName), Charset.defaultCharset()); }

Target:
public static Iterable<String> readLocalFile(final String fileName) throws IOException { return Files.readAllLines(Paths.get(DOWNLOAD_BASE_NAME + fileName), Charset.forName("utf-8")); }
Source:
public void testGetIsDirtySupplierWhenItIsDirty() { final GuidedDecisionTableView.Presenter presenter = mock(GuidedDecisionTableView.Presenter.class); final GuidedDecisionTable52 model = mock(GuidedDecisionTable52.class); final Set<GuidedDecisionTableView.Presenter> availableDecisionTables = asSet(presenter); final int currentHash = 456; final int originalHash = 123; doReturn(currentHash).when(this.presenter).originalHashCode(presenter); doReturn(originalHash).when(this.presenter).currentHashCode(presenter); doReturn(model).when(presenter).getModel(); doReturn(availableDecisionTables).when(this.presenter).getAvailableDecisionTables(); final boolean isDirty = this.presenter.getIsDirtySupplier().get(); assertTrue(isDirty); }

Target:
public void testGetIsDirtySupplierWhenItIsDirty() { final GuidedDecisionTableView.Presenter presenter = mock(GuidedDecisionTableView.Presenter.class); final GuidedDecisionTable52 model = mock(GuidedDecisionTable52.class); final int currentHash = 456; final int originalHash = 123; doReturn(currentHash).when(this.presenter).currentHashCode(presenter); doReturn(originalHash).when(this.presenter).originalHashCode(presenter); doReturn(model).when(presenter).getModel(); doReturn(presenter).when(this.presenter).getActiveDocument(); final boolean isDirty = this.presenter.getIsDirtySupplier().get(); assertTrue(isDirty); }
Source:
public String getReplicationId() { HashMap<String, String> dict = new HashMap<String, String>(); dict.put("source", this.sourceDb.getIdentifier()); dict.put("target", this.targetDb.getDbCore().getPublicIdentifier()); if(filter != null) { dict.put("filter", this.filter.toQueryString()); } return new String(new Hex().encode(Misc.getSha1(new ByteArrayInputStream(JSONUtils.serializeAsBytes(dict))))); }

Target:
public String getReplicationId() { HashMap<String, String> dict = new HashMap<String, String>(); dict.put("source", this.sourceDb.getIdentifier()); dict.put("target", this.targetDb.getIdentifier()); if(filter != null) { dict.put("filter", this.filter.toQueryString()); } byte[] sha1Bytes = Misc.getSha1(new ByteArrayInputStream(JSONUtils.serializeAsBytes(dict))); byte[] sha1Hex = new Hex().encode(sha1Bytes); return new String(sha1Hex); }
Source:
public static Set<String> mergeIgnored(Set<String> oldIgnoredPaths, Collection<String> changedPaths, Set<String> newIgnoredPaths) { Set<String> merged = new HashSet<String>(); for (String oldIgnoredPath : oldIgnoredPaths) { boolean changed = isAnyPrefixOf(oldIgnoredPath, changedPaths); if (!changed) { merged.add(oldIgnoredPath); } } merged.addAll(newIgnoredPaths); return merged; }

Target:
protected static Set<String> mergeIgnored(Set<String> oldIgnoredPaths, Collection<String> changedPaths, Set<String> newIgnoredPaths) { Set<String> merged = new HashSet<String>(); for (String oldIgnoredPath : oldIgnoredPaths) { boolean changed = isAnyPrefixOf(oldIgnoredPath, changedPaths); if (!changed) { merged.add(oldIgnoredPath); } } merged.addAll(newIgnoredPaths); return merged; }
Source:
protected void onResume() { super.onResume(); if (AppLockManager.getInstance().getAppLock().isPasswordLocked()) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE); } }

Target:
protected void onResume() { super.onResume(); disableScreenshotsIfLocked(this); }
Source:
protected void drawableStateChanged() { super.drawableStateChanged(); int alpha = isEnabled() ? 0xFF : (int) (0xFF * mDisabledAlpha); LayerDrawable ld = (LayerDrawable) getProgressDrawable().mutate(); Drawable progressDrawable = ld.findDrawableByLayerId(android.R.id.progress); Drawable backgroundDrawable = ld.findDrawableByLayerId(android.R.id.background); setDrawableColor(mThumb, mProgressAndThumbColor, alpha); setDrawableColor(progressDrawable, mProgressAndThumbColor, alpha); setDrawableColor(backgroundDrawable, mBackgroundColor, alpha); }

Target:
protected void drawableStateChanged() { super.drawableStateChanged(); int alpha = isEnabled() ? 0xFF : (int) (0xFF * mDisabledAlpha); mThumb.setColorFilter(mProgressAndThumbColor, PorterDuff.Mode.SRC_IN); mThumb.setAlpha(alpha); LayerDrawable ld = (LayerDrawable) getProgressDrawable(); Drawable progressDrawable = ld.findDrawableByLayerId(android.R.id.progress); Drawable backgroundDrawable = ld.findDrawableByLayerId(android.R.id.background); progressDrawable.setColorFilter(mProgressAndThumbColor, PorterDuff.Mode.SRC_IN); backgroundDrawable.setColorFilter(mBackgroundColor, PorterDuff.Mode.SRC_IN); ld.setAlpha(alpha); }
Source:
public void upgrade() throws IOException, SQLException { upgrade("liquibase-update-to-latest.xml"); }

Target:
public void upgrade() throws IOException, SQLException { upgrade("liquibase-master.xml"); }
Source:
protected <R> R readValue(@Nullable Object source, ElasticsearchPersistentProperty property, TypeInformation<R> targetType) { if (source == null) { return null; } Class<?> rawType = targetType.getType(); if (conversions.hasCustomReadTarget(source.getClass(), rawType)) { return (R) conversionService.convert(source, rawType); } else if (source instanceof List) { return readCollectionValue((List) source, property, targetType); } else if (source instanceof Map) { return readMapValue((Map<String, Object>) source, property, targetType); } else if (Enum.class.isAssignableFrom(rawType)) { return (R) Enum.valueOf((Class<Enum>) rawType, source.toString()); } return (R) readSimpleValue(source, targetType); }

Target:
protected <R> R readValue(@Nullable Object source, ElasticsearchPersistentProperty property, TypeInformation<R> targetType) { if (source == null) { return null; } Class<R> rawType = targetType.getType(); if (conversions.hasCustomReadTarget(source.getClass(), rawType)) { return rawType.cast(conversionService.convert(source, rawType)); } else if (source instanceof List) { return readCollectionValue((List) source, property, targetType); } else if (source instanceof Map) { return readMapValue((Map<String, Object>) source, property, targetType); } return (R) readSimpleValue(source, targetType); }
Source:
private ConfigKey(List<String> names) { Preconditions.checkArgument(names.size() >= 1, "Number of names must be larger than 1"); for (String key : names) { Preconditions.checkArgument(VALID_NAME.matcher(key).matches(), "Invalid name in keys"); } this.names = ImmutableList.copyOf(names); }

Target:
private ConfigKey(List<String> names) { Preconditions.checkArgument(!names.isEmpty(), "Names must not be empty"); for (String key : names) { Preconditions.checkArgument(VALID_NAME.matcher(key).matches(), "Invalid name"); } this.names = ImmutableList.copyOf(names); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.puzzle); setTitle(R.string.puzzle_view_name); User user = ; String ingredient = user.getIngredient(); ParseQuery<Puzzle> query = Puzzle.getQuery(); query.whereEqualTo("ingredient", ingredient); final Puzzle puzzle; query.findInBackground(new FindCallback<Puzzle>(){ @Override public void done(List<Puzzle> potentialPuzzles, ParseException e) { if (e == null && potentialPuzzles.size() > 0) { Random randomizer = new Random(); Puzzle puzzle = potentialPuzzles.get(randomizer.nextInt(potentialPuzzles.size())); } else { } } }); TextView question = (TextView) findViewById(R.id.question); question.setText(puzzle.getString("riddle")); correctAnswer = puzzle.getString("answer"); chk1 = (CheckBox) findViewById(R.id.chkanswer_1); chk2 = (CheckBox) findViewById(R.id.chkanswer_2); chk3 = (CheckBox) findViewById(R.id.chkanswer_3); chk4 = (CheckBox) findViewById(R.id.chkanswer_4); ArrayList<String> options = puzzle.getOptions(); options.add(correctAnswer); List<CheckBox> checkBoxes = new ArrayList<CheckBox>(Arrays.asList(chk1, chk2, chk3, chk4)); List<Integer> ordering = generateRandomOrder(); for (int i = 0; i < totalNumMultChoice; i++){ checkBoxes.get(i).setText(options.get(ordering.get(i))); } addListenerOnMainMenuButton(); addListenerOnChkAnswer_1(); addListenerOnChkAnswer_2(); addListenerOnChkAnswer_3(); addListenerOnChkAnswer_4(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.puzzle); setTitle(R.string.puzzle_view_name); String ingredient = ((User) User.getCurrentUser()).getIngredient(); ParseQuery<Puzzle> query = Puzzle.getQuery(); query.whereEqualTo("ingredient", ingredient); query.findInBackground(new FindCallback<Puzzle>(){ @Override public void done(List<Puzzle> potentialPuzzles, ParseException e) { if (e == null && potentialPuzzles.size() > 0) { Random randomizer = new Random(); Puzzle puzzle = potentialPuzzles.get(randomizer.nextInt(potentialPuzzles.size())); TextView question = (TextView) findViewById(R.id.question); question.setText(puzzle.getString("riddle")); correctAnswer = puzzle.getString("answer"); chk1 = (CheckBox) findViewById(R.id.chkanswer_1); chk2 = (CheckBox) findViewById(R.id.chkanswer_2); chk3 = (CheckBox) findViewById(R.id.chkanswer_3); chk4 = (CheckBox) findViewById(R.id.chkanswer_4); ArrayList<String> options = puzzle.getOptions(); options.add(correctAnswer); List<CheckBox> checkBoxes = new ArrayList<CheckBox>(Arrays.asList(chk1, chk2, chk3, chk4)); List<Integer> ordering = generateRandomOrder(); for (int i = 0; i < totalNumMultChoice; i++){ checkBoxes.get(i).setText(options.get(ordering.get(i))); } addListenerOnMainMenuButton(); addListenerOnChkAnswer_1(); addListenerOnChkAnswer_2(); addListenerOnChkAnswer_3(); addListenerOnChkAnswer_4(); } else { } } }); }
Source:
public int countObjects(@Nonnull String query) { try (Stream<Path> stream = Files.list(file.toPath())) { return Math.toIntExact(stream.map(Path::toFile) .filter(currentFile -> currentFile.getName().contains(query) && currentFile.isFile() && !currentFile.getName().startsWith("__")) .count()); } catch (IOException e) { throw Exceptions.createHandled().error(e).handle(); } }

Target:
public int countObjects(@Nonnull String query) { try (Stream<Path> stream = Files.list(file.toPath())) { return Math.toIntExact(stream.map(Path::toFile) .filter(currentFile -> currentFile.getName().contains(query) && currentFile.isFile() && !currentFile.getName().startsWith("__")) .count()); } catch (IOException e) { throw Exceptions.handle(e); } }