auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Map<String, Object> updateSection(ParameterParser params, SessionState state) { String message; String errorMessage = null; Map<String, Object> results = new HashMap<String, Object>(); try { String addSectionHTML = params.getString("addSectionHTML"); int locationId = params.getInt("locationId"); String cleanAddSectionHTML = getFormattedText().processFormattedText(addSectionHTML, new StringBuilder(), true, true); cleanAddSectionHTML = cleanAddSectionHTML.replaceAll("'", "&apos;"); CitationCollectionOrder.SectionType sectionType = CitationCollectionOrder.SectionType.valueOf(params.getString("sectionType")); CitationCollection collection = getCitationCollection(state, false); CitationCollectionOrder citationCollectionOrder = new CitationCollectionOrder(collection.getId(), locationId, sectionType, cleanAddSectionHTML); errorMessage = getCitationValidator().getUpdateSectionErrorMessage(citationCollectionOrder, collection); if (errorMessage==null){ getCitationService().updateSection(citationCollectionOrder); message = rb.getString("resource.updated"); logger.info("Reading list successfully updated."); } else { message = errorMessage; logger.warn("Invalid citation list in updateSection(). " + errorMessage); } } catch (Exception e){ message = e.getMessage(); logger.warn("Exception in updateSection() " + e); } if(errorMessage==null && message != null && ! message.trim().equals("")) { results.put("message", message); } else { results.put("Error: ", new String[]{errorMessage}); } return results; }

Target:
protected Map<String, Object> updateSection(ParameterParser params, SessionState state) { String message; String errorMessage = null; Map<String, Object> results = new HashMap<String, Object>(); try { String addSectionHTML = params.getString("addSectionHTML"); int locationId = params.getInt("locationId"); String cleanAddSectionHTML = getFormattedText().processFormattedText(addSectionHTML, new StringBuilder(), true, true); cleanAddSectionHTML = cleanAddSectionHTML.replaceAll("'", "&apos;"); CitationCollectionOrder.SectionType sectionType = CitationCollectionOrder.SectionType.valueOf(params.getString("sectionType")); CitationCollection collection = getCitationCollection(state, false); CitationCollectionOrder citationCollectionOrder = new CitationCollectionOrder(collection.getId(), locationId, sectionType, cleanAddSectionHTML); errorMessage = getCitationValidator().getUpdateSectionErrorMessage(citationCollectionOrder, collection); if (errorMessage==null){ getCitationService().updateSection(citationCollectionOrder); message = rb.getString("resource.updated"); logger.debug("Reading list with collection id: " + collection.getId() + " successfully updated. Section updated at location:" + locationId) ; } else { message = errorMessage; logger.warn("Invalid citation list with collection id: " + collection.getId() + " in updateSection(). " + errorMessage); } } catch (Exception e){ message = e.getMessage(); logger.warn("Exception in updateSection() " + e); } if(errorMessage==null && message != null && ! message.trim().equals("")) { results.put("message", message); } else { results.put("Error: ", new String[]{errorMessage}); } return results; }
Source:
protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { try { if (dataSink != null) { tupleWriter.open(dataSink.getOutputStream()); } tupleWriter.writeColumnHeaders(getChild().getSchema().getColumnNames()); } catch (IOException e) { throw new DbException(e); } }

Target:
protected void init(final ImmutableMap<String, Object> execEnvVars) throws DbException { try { tupleWriter.open(dataSink.getOutputStream()); tupleWriter.writeColumnHeaders(getChild().getSchema().getColumnNames()); } catch (IOException e) { throw new DbException(e); } }
Source:
private synchronized void load() { try { Map.Entry<ManagerSpec, Map<ResourceGroupIdTemplate, ResourceGroupSpec>> specsFromDb = buildSpecsFromDb(); ManagerSpec managerSpec = specsFromDb.getKey(); Map<ResourceGroupIdTemplate, ResourceGroupSpec> resourceGroupSpecs = specsFromDb.getValue(); Set<ResourceGroupIdTemplate> changedSpecs = new HashSet<>(); Set<ResourceGroupIdTemplate> deletedSpecs = Sets.difference(this.resourceGroupSpecs.keySet(), resourceGroupSpecs.keySet()); for (Map.Entry<ResourceGroupIdTemplate, ResourceGroupSpec> entry : resourceGroupSpecs.entrySet()) { if (!entry.getValue().sameConfig(this.resourceGroupSpecs.get(entry.getKey()))) { changedSpecs.add(entry.getKey()); } } this.resourceGroupSpecs = resourceGroupSpecs; this.cpuQuotaPeriod.set(managerSpec.getCpuQuotaPeriod()); this.rootGroups.set(managerSpec.getRootGroups()); this.selectors.set(buildSelectors(managerSpec)); configureChangedGroups(changedSpecs); disableDeletedGroups(deletedSpecs); } catch (Exception ex) { log.error("Error loading resource groups: %s", ex); } }

Target:
private synchronized void load() { Map.Entry<ManagerSpec, Map<ResourceGroupIdTemplate, ResourceGroupSpec>> specsFromDb = buildSpecsFromDb(); ManagerSpec managerSpec = specsFromDb.getKey(); Map<ResourceGroupIdTemplate, ResourceGroupSpec> resourceGroupSpecs = specsFromDb.getValue(); Set<ResourceGroupIdTemplate> changedSpecs = new HashSet<>(); Set<ResourceGroupIdTemplate> deletedSpecs = Sets.difference(this.resourceGroupSpecs.keySet(), resourceGroupSpecs.keySet()); for (Map.Entry<ResourceGroupIdTemplate, ResourceGroupSpec> entry : resourceGroupSpecs.entrySet()) { if (!entry.getValue().sameConfig(this.resourceGroupSpecs.get(entry.getKey()))) { changedSpecs.add(entry.getKey()); } } this.resourceGroupSpecs = resourceGroupSpecs; this.cpuQuotaPeriod.set(managerSpec.getCpuQuotaPeriod()); this.rootGroups.set(managerSpec.getRootGroups()); this.selectors.set(buildSelectors(managerSpec)); configureChangedGroups(changedSpecs); disableDeletedGroups(deletedSpecs); }
Source:
public void testPartialIterating() throws Exception { FileSystemSecurityRealm securityRealm = new FileSystemSecurityRealm(getRootPath(), 1); ModifiableRealmIdentity identity1 = securityRealm.getRealmIdentityForUpdate("firstUser", null, null); identity1.create(); ModifiableRealmIdentity identity2 = securityRealm.getRealmIdentityForUpdate("secondUser", null, null); identity2.create(); Iterator<ModifiableRealmIdentity> iterator = securityRealm.getRealmIdentityIterator(); Assert.assertTrue(iterator.hasNext()); Assert.assertTrue(iterator.next().exists()); Assert.assertTrue(iterator instanceof Closeable); ((Closeable) iterator).close(); getRootPath(); }

Target:
public void testPartialIterating() throws Exception { FileSystemSecurityRealm securityRealm = createRealmWithTwoIdentities(); Iterator<ModifiableRealmIdentity> iterator = securityRealm.getRealmIdentityIterator(); Assert.assertTrue(iterator.hasNext()); Assert.assertTrue(iterator.next().exists()); Assert.assertTrue(iterator instanceof Closeable); ((Closeable) iterator).close(); getRootPath(); }
Source:
protected void onInitUI() { super.onInitUI(); final Change.Id changeId = patchKey.getParentKey().getParentKey(); final String path = patchKey.get(); String fileName = path; final int last = fileName.lastIndexOf('/'); if (last >= 0) { fileName = fileName.substring(last + 1); } setWindowTitle(PatchUtil.M.patchWindowTitle(changeId.get(), fileName)); setPageTitle(PatchUtil.M.patchPageTitle(changeId.get(), path)); historyTable = new HistoryTable(this); historyPanel = new DisclosurePanel(PatchUtil.C.patchHistoryTitle()); historyPanel.setContent(historyTable); historyPanel.setOpen(false); historyPanel.setVisible(false); add(historyPanel); noDifference = new Label(PatchUtil.C.noDifference()); noDifference.setStyleName("gerrit-PatchNoDifference"); noDifference.setVisible(false); contentTable = createContentTable(); contentTable.fileList = fileList; final FlowPanel fp = new FlowPanel(); fp.setStyleName("gerrit-SideBySideScreen-SideBySideTable"); fp.add(noDifference); fp.add(contentTable); add(fp); FlexTable dp = new FlexTable(); dp.setStyleName("gerrit-SideBySideScreen-LinkTable"); dp.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_LEFT); dp.getFlexCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT); if (fileList != null) { previousPatchLink = fileList.getPreviousPatchLink(patchIndex, getPatchType()); nextPatchLink = fileList.getNextPatchLink(patchIndex, getPatchType()); } dp.setWidget(0, 0, previousPatchLink); dp.setWidget(0, 1, nextPatchLink); add(dp); }

Target:
protected void onInitUI() { super.onInitUI(); final Change.Id changeId = patchKey.getParentKey().getParentKey(); final String path = patchKey.get(); String fileName = path; final int last = fileName.lastIndexOf('/'); if (last >= 0) { fileName = fileName.substring(last + 1); } setWindowTitle(PatchUtil.M.patchWindowTitle(changeId.get(), fileName)); setPageTitle(PatchUtil.M.patchPageTitle(changeId.get(), path)); historyTable = new HistoryTable(this); historyPanel = new DisclosurePanel(PatchUtil.C.patchHistoryTitle()); historyPanel.setContent(historyTable); historyPanel.setOpen(false); historyPanel.setVisible(false); add(historyPanel); noDifference = new Label(PatchUtil.C.noDifference()); noDifference.setStyleName("gerrit-PatchNoDifference"); noDifference.setVisible(false); contentTable = createContentTable(); contentTable.fileList = fileList; final FlowPanel fp = new FlowPanel(); fp.setStyleName("gerrit-SideBySideScreen-SideBySideTable"); fp.add(noDifference); fp.add(contentTable); add(fp); linkTable = new FlexTable(); linkTable.setStyleName("gerrit-SideBySideScreen-LinkTable"); linkTable.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_LEFT); linkTable.getFlexCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT); if (fileList != null) { previousPatchLink = fileList.getPreviousPatchLink(patchIndex, getPatchScreenType()); nextPatchLink = fileList.getNextPatchLink(patchIndex, getPatchScreenType()); } linkTable.setWidget(0, 0, previousPatchLink); linkTable.setWidget(0, 1, nextPatchLink); add(linkTable); }
Source:
private DataFetcher<String> getNameDataFetcher() { return environment -> Optional.of(environment.getSource()) .filter(Viewpoint.class::isInstance) .map(Viewpoint.class::cast) .map(viewpoint -> { return Optional.ofNullable(viewpoint.getLabel()).orElse(viewpoint.getName()); }) .orElse(null); }

Target:
private DataFetcher<String> getNameDataFetcher() { return environment -> Optional.of(environment.getSource()) .filter(Viewpoint.class::isInstance) .map(Viewpoint.class::cast) .map(IdentifiedElementQuery::new) .map(IdentifiedElementQuery::getLabel) .orElse(null); }
Source:
public static Collection<Object[]> ipAddressParams() { return Arrays.asList(new Object[][] { { new HashSet<String>(), true }, { null, true }, { new HashSet<>(Collections.singletonList("abc")), true }, { new HashSet<>(Arrays.asList("abc", "xyz")), true }, { new HashSet<>(Collections.singletonList("abc-_sc")), true }, { new HashSet<>(Collections.singletonList("")), false }, { new HashSet<>(Collections.singletonList(" ")), false }, { new HashSet<>(Collections.singletonList("abc*")), false }, { new HashSet<>(Arrays.asList("aaa", "abc*")), false } }); }

Target:
public static Collection<Object[]> ipAddressParams() { return Arrays.asList(new Object[][] { { Collections.emptySet(), true }, { null, true }, { Collections.singleton("abc"), true }, { new HashSet<>(Arrays.asList("abc", "xyz")), true }, { Collections.singleton("abc-_sc"), true }, { Collections.singleton(""), false }, { Collections.singleton(" "), false }, { Collections.singleton("abc*"), false }, { new HashSet<>(Arrays.asList("aaa", "abc*")), false } }); }
Source:
public void getAllConceptStateConversion_shouldTestGetAllConceptStateConversion() { List<ConceptStateConversion> conceptStateConversions = pws.getAllConceptStateConversions(); int len = conceptStateConversions.size(); assertEquals(len, 1); }

Target:
public void getAllConceptStateConversion_shouldTestGetAllConceptStateConversion() { List<ConceptStateConversion> conceptStateConversions = pws.getAllConceptStateConversions(); assertEquals(conceptStateConversions.size(), 1); }
Source:
public String getMessage() { return "Annotation " + Jack.getUserFriendlyFormatter().getName(typeDef) + "should be annotated with @Retention(RetentionPolicy.SOURCE)"; }

Target:
public String getMessage() { return "Annotation @" + Jack.getUserFriendlyFormatter().getName(typeDef) + "should be annotated with @Retention(RetentionPolicy.SOURCE)"; }
Source:
public void startProcess() throws IOException { ProcessBuilder builder = new ProcessBuilder(buildCommand()); builder.redirectErrorStream(true); Process process = builder.start(); InputStream out = process.getInputStream(); OutputStream in = process.getOutputStream(); int SIZE = resolution.width * resolution.height * 3; int CHUNK_SIZE = SIZE / 20; int cursor = 0; byte[] chunk = new byte[CHUNK_SIZE]; ByteBuffer buffer = ByteBuffer.allocate(SIZE); while (isAlive(process)) { int no = out.available(); if (no >= chunk.length) { int n = out.read(chunk, 0, chunk.length); cursor += n; if (cursor < SIZE) { buffer.put(chunk, 0, n); } else { byte[] bgr = buffer.array(); image.setData(Raster.createRaster(image.getSampleModel(), new DataBufferByte(bgr, bgr.length), new Point())); buffer.clear(); cursor = 0; } } } }

Target:
public void startProcess() throws IOException { ProcessBuilder builder = new ProcessBuilder(buildCommand()); builder.redirectErrorStream(true); process = builder.start(); }
Source:
public void testCache() throws Exception { assertTrue(atsVersionCache.cache(teamWf, atsVersionCache.getVersion(teamWf)).getHumanReadableId().equals("WSXZA")); }

Target:
public void testCache() throws Exception { IAtsVersion testVersion = atsVersionCache.cache(teamWf, atsVersionCache.getVersion(teamWf)); String hrid = testVersion.getHumanReadableId(); assertEquals("WSXZA", hrid); }
Source:
public void setDerivedProvidedProducts(Collection<Product> derivedProvidedProducts) { this.derivedProvidedProductDtos = null; if (derivedProvidedProducts != null) { this.derivedProvidedProducts = new HashSet<>(derivedProvidedProducts); } }

Target:
public void setDerivedProvidedProducts(Collection<Product> derivedProvidedProducts) { this.derivedProvidedProductDtos = null; if (derivedProvidedProducts != null) { this.derivedProvidedProducts = new HashSet<>(derivedProvidedProducts); } else { this.derivedProvidedProducts = new HashSet<>(); } }
Source:
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { try { if("true".equals(System.getProperty(PROP_TRUST_STORE_UPDATE_REQUIRED))) { setupTrustManager(); } trustManager.checkServerTrusted(x509Certificates, s); } catch (NoSuchAlgorithmException e) { throw new CertificateException("Certificate validation failed due to " + e.getCause()); } catch (KeyStoreException e) { throw new CertificateException("Certificate validation failed due to " + e.getCause()); } catch (Exception e) { throw new CertificateException("Certificate validation failed due to " + e.getCause()); } }

Target:
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { try { if("true".equals(System.getProperty(PROP_TRUST_STORE_UPDATE_REQUIRED))) { setupTrustManager(); } trustManager.checkServerTrusted(x509Certificates, s); } catch (NoSuchAlgorithmException | KeyStoreException e) { throw new CertificateException("Certificate validation failed due to " + e.getCause(), e); } catch (Exception e) { throw new CertificateException("Certificate validation failed due to " + e.getCause(), e); } }
Source:
public Gson create() { List<TypeAdapterFactory> factories = new ArrayList<TypeAdapterFactory>(this.factories.size() + this.hierarchyFactories.size() + 3); factories.addAll(this.factories); Collections.reverse(factories); List<TypeAdapterFactory> hierarchyFactories = new ArrayList<TypeAdapterFactory>(this.hierarchyFactories.size()); hierarchyFactories.addAll(this.hierarchyFactories); Collections.reverse(hierarchyFactories); factories.addAll(hierarchyFactories); addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories); return new Gson(excluder, fieldNamingPolicy, instanceCreators, serializeNulls, complexMapKeySerialization, generateNonExecutableJson, escapeHtmlChars, prettyPrinting, lenient, serializeSpecialFloatingPointValues, longSerializationPolicy, factories); }

Target:
public Gson create() { List<TypeAdapterFactory> factories = new ArrayList<TypeAdapterFactory>(this.factories.size() + this.hierarchyFactories.size() + 3); factories.addAll(this.factories); Collections.reverse(factories); List<TypeAdapterFactory> hierarchyFactories = new ArrayList<TypeAdapterFactory>(this.hierarchyFactories); Collections.reverse(hierarchyFactories); factories.addAll(hierarchyFactories); addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories); return new Gson(excluder, fieldNamingPolicy, instanceCreators, serializeNulls, complexMapKeySerialization, generateNonExecutableJson, escapeHtmlChars, prettyPrinting, lenient, serializeSpecialFloatingPointValues, longSerializationPolicy, factories); }
Source:
public void process(String vreName, boolean isAssertion, Triple triple) { Entity entity = database.findOrCreateEntity(vreName, triple.getSubject()); if (isAssertion) { entity.addToCollection(database.findOrCreateCollection(vreName, triple.getObject())); entity.removeFromCollection(database.getDefaultCollection(vreName)); } else { entity.removeFromCollection(database.findOrCreateCollection(vreName, triple.getObject())); } }

Target:
public void process(String vreName, boolean isAssertion, Triple triple) { Entity entity = database.findOrCreateEntity(vreName, triple.getSubject()); if (isAssertion) { if (entity.isInKnownCollection()) { rdfImportSession.getErrorReporter().multipleRdfTypes(triple); } else { entity.addToCollection(database.findOrCreateCollection(vreName, triple.getObject())); } entity.removeFromCollection(database.getDefaultCollection(vreName)); } else { entity.removeFromCollection(database.findOrCreateCollection(vreName, triple.getObject())); } }
Source:
public InMemoryReactiveClientRegistrationRepository(ClientRegistration... registrations) { this.clientIdToClientRegistration = toUnmodifiableMapByRegistrationId(Stream.of(checkEmptyRegistrations(registrations, Assert::notEmpty))); }

Target:
public InMemoryReactiveClientRegistrationRepository(ClientRegistration... registrations) { this.delegate = new InMemoryClientRegistrationRepository(registrations); }
Source:
public void copyWalPart(WalPosition startPosition, WalPosition endPosition, long oldWalKey) { try { DataInputStream in = bfs.getInputStream(oldWalKey, WAL_FILE_PREFIX + endPosition.fileId); int length = (int)(startPosition.fileId == endPosition.fileId ? endPosition.offset - startPosition.offset : endPosition.offset); int offset = (int)(startPosition.fileId == endPosition.fileId ? startPosition.offset : 0); logger.info("length = offset = start offset = end offset = File = {}", length, offset, startPosition, endPosition); byte[] buffer = new byte[length]; IOUtils.skip(in, offset); int readBytes = IOUtils.read(in, buffer, 0, length); append(buffer, readBytes); in.close(); flushWal(); walSize = writer.getSize(); logger.info("wal size so far = {}", walSize); } catch (IOException e) { DTThrowable.wrapIfChecked(e); } }

Target:
private void copyWalPart(WalPosition startPosition, WalPosition endPosition, long oldWalKey) { try { if (bfs.exists(oldWalKey, WAL_FILE_PREFIX + endPosition.fileId)) { DataInputStream in = bfs.getInputStream(oldWalKey, WAL_FILE_PREFIX + endPosition.fileId); int length = (int)(startPosition.fileId == endPosition.fileId ? endPosition.offset - startPosition.offset : endPosition.offset); int offset = (int)(startPosition.fileId == endPosition.fileId ? startPosition.offset : 0); logger.info("length = offset = start offset = end offset = File = {}", length, offset, startPosition, endPosition); if (copyBuffer == null) { copyBuffer = new byte[BUFFER_SIZE]; } IOUtils.skip(in, offset); while (length > 0) { int readBytes = IOUtils.read(in, copyBuffer, 0, length < BUFFER_SIZE ? length : BUFFER_SIZE); append(copyBuffer, readBytes); length -= readBytes; } in.close(); flushWal(); if (writer != null) { walSize = writer.getSize(); } logger.debug("wal size so far = {}", walSize); } } catch (IOException e) { throw Throwables.propagate(e); } }
Source:
public double getCpuLoad() { if (this.collectedCpuStats.isEmpty()) { return -1; } final CpuStats oldestCpuStats = this.collectedCpuStats.pollLast(); final CpuStats newestCpuStats = getCpuStats(); this.collectedCpuStats.push(newestCpuStats); return calcCpuLoad(oldestCpuStats, newestCpuStats); }

Target:
public double getCpuLoad() { if (this.collectedCpuStats.isEmpty()) { return -1; } final CpuStats newestCpuStats = getCpuStats(); if (newestCpuStats == null) { return -1; } final CpuStats oldestCpuStats = this.collectedCpuStats.pollLast(); this.collectedCpuStats.push(newestCpuStats); return calcCpuLoad(oldestCpuStats, newestCpuStats); }
Source:
protected static String loadFileTextFromJar(final File jarFile, String path, String fileName) { try (ZipFile zip = new ZipFile(jarFile)) { for (Enumeration e = zip.entries(); e.hasMoreElements(); ) { ZipEntry entry = (ZipEntry) e.nextElement(); if (entry.getName().startsWith(path) && entry.getName().endsWith(fileName)) { return zipEntryToString(zip, entry); } } } catch (ZipException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } catch (NullPointerException e) { log.error(e.getMessage()); } return null; }

Target:
protected static String loadFileTextFromJar(final File jarFile, String path, String fileName) { if (jarFile != null && fileName != null && !fileName.isEmpty()) { try (ZipFile zip = new ZipFile(jarFile)) { for (Enumeration e = zip.entries(); e.hasMoreElements(); ) { ZipEntry entry = (ZipEntry) e.nextElement(); if (entry.getName().startsWith(path) && entry.getName().endsWith(fileName)) { return zipEntryToString(zip, entry); } } } catch (ZipException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } } return null; }
Source:
public void setUserProperties(final JSONObject userProperties, final boolean replace) { if (replace || this.userProperties == null) { this.userProperties = userProperties; return; } if (userProperties == null) { return; } final JSONObject currentUserProperties = this.userProperties; runOnLogThread(new Runnable() { @Override public void run() { final JSONObject copy; try { copy = new JSONObject(userProperties.toString()); } catch (JSONException e) { Log.e(TAG, e.toString()); return; } Iterator<?> keys = copy.keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { currentUserProperties.put(key, copy.get(key)); } catch (JSONException e) { Log.e(TAG, e.toString()); } } } }); }

Target:
public void setUserProperties(final JSONObject userProperties, final boolean replace) { runOnLogThread(new Runnable() { @Override public void run() { AmplitudeClient instance = AmplitudeClient.this; if (userProperties == null) { if (replace) { instance.userProperties = null; } return; } JSONObject copy; try { copy = new JSONObject(userProperties.toString()); } catch (JSONException e) { Log.e(TAG, e.toString()); return; } JSONObject currentUserProperties = instance.userProperties; if (replace || currentUserProperties == null) { instance.userProperties = copy; return; } Iterator<?> keys = copy.keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { currentUserProperties.put(key, copy.get(key)); } catch (JSONException e) { Log.e(TAG, e.toString()); } } } }); }
Source:
public void onInstancesChange(Set<String> enabledInstances, List<String> changedInstances) { _enabledInstances = enabledInstances; Set<String> segmentsToUpdate = new HashSet<>(); Map<String, List<String>> instanceToSegmentsMap = _instanceToSegmentsMap; for (String instance : changedInstances) { List<String> segments = instanceToSegmentsMap.get(instance); if (segments != null) { segmentsToUpdate.addAll(segments); } } if (segmentsToUpdate.isEmpty()) { return; } Map<String, List<String>> segmentToOnlineInstancesMap = _segmentToOnlineInstancesMap; Map<String, List<String>> segmentToOfflineInstancesMap = _segmentToOfflineInstancesMap; Map<String, List<String>> segmentToEnabledInstancesMap = _segmentToEnabledInstancesMap; Set<String> currentUnavailableSegments = _unavailableSegments; Set<String> newUnavailableSegments = new HashSet<>(); for (Map.Entry<String, List<String>> entry : segmentToEnabledInstancesMap.entrySet()) { String segment = entry.getKey(); if (segmentsToUpdate.contains(segment)) { List<String> enabledInstancesForSegment = calculateEnabledInstancesForSegment(segment, segmentToOnlineInstancesMap.get(segment), segmentToOfflineInstancesMap, enabledInstances, newUnavailableSegments); entry.setValue(enabledInstancesForSegment); } else { if (currentUnavailableSegments.contains(segment)) { newUnavailableSegments.add(segment); } } } _unavailableSegments = newUnavailableSegments; }

Target:
public void onInstancesChange(Set<String> enabledInstances, List<String> changedInstances) { _enabledInstances = enabledInstances; Set<String> segmentsToUpdate = new HashSet<>(); for (String instance : changedInstances) { List<String> segments = _instanceToSegmentsMap.get(instance); if (segments != null) { segmentsToUpdate.addAll(segments); } } if (segmentsToUpdate.isEmpty()) { return; } Map<String, List<String>> segmentToEnabledInstancesMap = _segmentToEnabledInstancesMap; Set<String> currentUnavailableSegments = _unavailableSegments; Set<String> newUnavailableSegments = new HashSet<>(); for (Map.Entry<String, List<String>> entry : segmentToEnabledInstancesMap.entrySet()) { String segment = entry.getKey(); if (segmentsToUpdate.contains(segment)) { List<String> enabledInstancesForSegment = calculateEnabledInstancesForSegment(segment, _segmentToOnlineInstancesMap.get(segment), newUnavailableSegments); entry.setValue(enabledInstancesForSegment); } else { if (currentUnavailableSegments.contains(segment)) { newUnavailableSegments.add(segment); } } } _unavailableSegments = newUnavailableSegments; }
Source:
public void setColor(RGB rgb) { PreferenceConverter.setValue(fOverlayStore, this.colorKey, rgb); }

Target:
public void setColor(RGB rgb) { this.previousColor= PreferenceConverter.getColor(fOverlayStore, this.colorKey); PreferenceConverter.setValue(fOverlayStore, this.colorKey, rgb); }
Source:
void fromCommandDispatch() { BlackBoxBoundedContext .with(new TaskAggregateRepository()) .receivesCommand(createTask()) .verifiesThat(acked(1).withoutErrorsOrRejections()) .verifiesThat(emitted(1)) .close(); }

Target:
void fromCommandDispatch() { BlackBoxBoundedContext .with(new TaskAggregateRepository()) .receivesCommand(createTask()) .verifiesThat(acked(once()).withoutErrorsOrRejections()) .verifiesThat(emitted(once())) .close(); }
Source:
public void testPartialUpdate() throws Exception { Statistics statsNode0 = getStatistics(0); withTxSession(false, sessionFactories[0], s -> { Street street = new Street("hard"); s.persist(street); }); assertEquals(1, statsNode0.getSecondLevelCachePutCount()); assertEquals(0, statsNode0.getSecondLevelCacheMissCount()); assertEquals(0, statsNode0.getSecondLevelCacheHitCount()); Statistics statsNode1 = getStatistics(1); withSession(sessionFactories[1].withOptions(), s -> { final Street street = s.load(Street.class, 1); assertEquals("hard", street.getName()); }); assertEquals(0, statsNode1.getSecondLevelCachePutCount()); assertEquals(0, statsNode1.getSecondLevelCacheMissCount()); assertEquals(1, statsNode1.getSecondLevelCacheHitCount()); statsNode0 = getStatistics(0); final boolean updated = doUpdate(); if (updated) { withSession(sessionFactories[0].withOptions(), s -> { final Street street = s.load(Street.class, 1); assertEquals("hardstrasse", street.getName()); }); withSession(sessionFactories[1].withOptions(), s -> { final Street street = s.load(Street.class, 1); assertEquals("hardstrasse", street.getName()); }); } }

Target:
public void testPartialUpdate() throws Exception { Statistics statsNode0 = getStatistics(localFactory); withTxSession(localFactory, s -> { Customer customer = new Customer(); customer.setName("JBoss"); s.persist(customer); }); assertEquals(1, statsNode0.getSecondLevelCachePutCount()); assertEquals(0, statsNode0.getSecondLevelCacheMissCount()); assertEquals(0, statsNode0.getSecondLevelCacheHitCount()); waitForRemotePut(); Statistics statsNode1 = getStatistics(remoteFactory); withSession(remoteFactory.withOptions(), s -> { Customer customer = s.load(Customer.class, 1); assertEquals("JBoss", customer.getName()); }); assertEquals(0, statsNode1.getSecondLevelCachePutCount()); assertEquals(0, statsNode1.getSecondLevelCacheMissCount()); assertEquals(1, statsNode1.getSecondLevelCacheHitCount()); final boolean updated = doUpdate(); if (updated) { withSession(localFactory.withOptions(), s -> { Customer customer = s.load(Customer.class, 1); assertEquals("JBoss, a division of Red Hat", customer.getName()); }); withSession(remoteFactory.withOptions(), s -> { Customer customer = s.load(Customer.class, 1); assertEquals("JBoss, a division of Red Hat", customer.getName()); }); } }
Source:
public final <R> Single<R> cast(final Class<R> klass) { return lift(new OperatorCast<T, R>(klass)); }

Target:
public final <R> Single<R> cast(final Class<R> klass) { return map(new SingleOperatorCast<T, R>(klass)); }
Source:
public void open(GenericInputSplit split) throws IOException { this.partitionNumber = split.getSplitNumber(); if (serializableIter != null) it = serializableIter; else it = this.steam.iterator(); }

Target:
public void open(GenericInputSplit split) throws IOException { super.open(split); if (serializableIter != null) { it = serializableIter; } else { it = this.dataSet.iterator(); } }
Source:
public void fetchEndOffsetsShouldRethrowInterruptedExceptionAsStreamsException() throws Exception { final Admin adminClient = EasyMock.createMock(AdminClient.class); final ListOffsetsResult result = EasyMock.createNiceMock(ListOffsetsResult.class); final KafkaFuture<Map<TopicPartition, ListOffsetsResultInfo>> allFuture = EasyMock.createMock(KafkaFuture.class); EasyMock.expect(adminClient.listOffsets(EasyMock.anyObject())).andStubReturn(result); EasyMock.expect(result.all()).andStubReturn(allFuture); EasyMock.expect(allFuture.get(60000L, TimeUnit.MILLISECONDS)).andThrow(new InterruptedException()); replay(adminClient, result, allFuture); assertThrows(StreamsException.class, () -> fetchEndOffsets(emptyList(), adminClient, 60_000L)); verify(adminClient); }

Target:
public void fetchEndOffsetsShouldRethrowInterruptedExceptionAsStreamsException() throws Exception { final Admin adminClient = EasyMock.createMock(AdminClient.class); final ListOffsetsResult result = EasyMock.createNiceMock(ListOffsetsResult.class); final KafkaFuture<Map<TopicPartition, ListOffsetsResultInfo>> allFuture = EasyMock.createMock(KafkaFuture.class); EasyMock.expect(adminClient.listOffsets(EasyMock.anyObject())).andStubReturn(result); EasyMock.expect(result.all()).andStubReturn(allFuture); EasyMock.expect(allFuture.get()).andThrow(new InterruptedException()); replay(adminClient, result, allFuture); assertThrows(StreamsException.class, () -> fetchEndOffsets(emptyList(), adminClient)); verify(adminClient); }
Source:
public Map<String, List<String>> getHeaders() { return headers; }

Target:
public MultivaluedMap<String, String> getHeaders() { final MultivaluedHashMap<String, String> toReturn = new MultivaluedHashMap<String, String>(); toReturn.putAll(headers); return toReturn; }
Source:
private void testNotifyVisibilityChange(boolean isStandalone) { final WorkbenchMenuBarPresenter presenter = getMenuBarPresenter(isStandalone); presenter.onPerspectiveVisibilityChange(new PerspectiveVisibiltiyChangeEvent("perspectiveId", false)); verify(presenter, times(1)).onPerspectiveVisibilityChange(any()); }

Target:
private void testNotifyVisibilityChange(boolean isStandalone) { final WorkbenchMenuBarPresenter presenter = getMenuBarPresenter(isStandalone); presenter.onPerspectiveVisibilityChange(new PerspectiveVisibiltiyChangeEvent("perspectiveId", false)); verify(presenter).onPerspectiveVisibilityChange(any()); }
Source:
private static String getTestingAlias(GoImportSpec testingImportSpec) { String alias = GoConstants.TESTING_PATH; if (testingImportSpec != null) { alias = !testingImportSpec.isDot() ? StringUtil.notNullize(testingImportSpec.getAlias(), GoConstants.TESTING_PATH) : ""; } return alias; }

Target:
private static String getTestingAlias(GoImportSpec testingImportSpec) { return testingImportSpec == null ? GoConstants.TESTING_PATH : !testingImportSpec.isDot() ? StringUtil.notNullize(testingImportSpec.getAlias(), GoConstants.TESTING_PATH) : ""; }
Source:
public void localFailTest() { initialize(); ot = new SimpleOperationTracker(datanodes.get(0).getDatacenterName(), mockPartition, false, 2, 3); assertFalse(ot.hasSucceeded()); Iterator<ReplicaId> itr = ot.getReplicaIterator(); ReplicaId nextReplica; while (itr.hasNext()) { nextReplica = itr.next(); assertNotNull(nextReplica); sendReplica(nextReplica); itr.remove(); } for (int i = 0; i < 2; i++) { ot.onResponse(inflightReplicas.poll(), new Exception()); } assertFalse(ot.hasSucceeded()); assertTrue(ot.isDone()); ot.onResponse(inflightReplicas.poll(), null); assertFalse(ot.hasSucceeded()); assertTrue(ot.isDone()); }

Target:
public void localFailTest() { initialize(); ot = new SimpleOperationTracker(localDcName, mockPartition, false, 2, 3); assertFalse(ot.hasSucceeded()); Iterator<ReplicaId> itr = ot.getReplicaIterator(); ReplicaId nextReplica; while (itr.hasNext()) { nextReplica = itr.next(); assertNotNull(nextReplica); sendReplica(nextReplica); itr.remove(); } for (int i = 0; i < 2; i++) { ot.onResponse(inflightReplicas.poll(), new Exception()); } assertFalse(ot.hasSucceeded()); assertTrue(ot.isDone()); ot.onResponse(inflightReplicas.poll(), null); assertFalse(ot.hasSucceeded()); assertTrue(ot.isDone()); }
Source:
public void transition(RMNodeImpl rmNode, RMNodeEvent event) { Integer timeout = null; if (RMNodeDecommissioningEvent.class.isInstance(event)) { RMNodeDecommissioningEvent e = ((RMNodeDecommissioningEvent) event); timeout = e.getDecommissioningTimeout(); } if (rmNode.getState() == NodeState.DECOMMISSIONING) { if (!Objects.equals(rmNode.getDecommissioningTimeout(), timeout)) { LOG.info("Update " + rmNode.getNodeID() + " DecommissioningTimeout to be " + timeout); rmNode.decommissioningTimeout = timeout; } else { LOG.info(rmNode.getNodeID() + " is already DECOMMISSIONING"); } return; } LOG.info("Put Node " + rmNode.nodeId + " in DECOMMISSIONING."); rmNode.updateMetricsForGracefulDecommission(initState, finalState); rmNode.decommissioningTimeout = timeout; rmNode.context.getDispatcher().getEventHandler().handle( new NodesListManagerEvent( NodesListManagerEventType.NODE_USABLE, rmNode)); if (rmNode.originalTotalCapability == null){ rmNode.originalTotalCapability = Resources.clone(rmNode.totalCapability); LOG.info("Preserve original total capability: " + rmNode.originalTotalCapability); } }

Target:
public void transition(RMNodeImpl rmNode, RMNodeEvent event) { Integer timeout = null; if (RMNodeDecommissioningEvent.class.isInstance(event)) { RMNodeDecommissioningEvent e = ((RMNodeDecommissioningEvent) event); timeout = e.getDecommissioningTimeout(); } if (rmNode.getState() == NodeState.DECOMMISSIONING) { if (!Objects.equals(rmNode.getDecommissioningTimeout(), timeout)) { LOG.info("Update " + rmNode.getNodeID() + " DecommissioningTimeout to be " + timeout); rmNode.decommissioningTimeout = timeout; } else { LOG.info(rmNode.getNodeID() + " is already DECOMMISSIONING"); } return; } LOG.info("Put Node " + rmNode.nodeId + " in DECOMMISSIONING."); rmNode.updateMetricsForGracefulDecommission(initState, finalState); rmNode.decommissioningTimeout = timeout; rmNode.context.getDispatcher().getEventHandler().handle( new NodesListManagerEvent( NodesListManagerEventType.NODE_DECOMMISSIONING, rmNode)); if (rmNode.originalTotalCapability == null){ rmNode.originalTotalCapability = Resources.clone(rmNode.totalCapability); LOG.info("Preserve original total capability: " + rmNode.originalTotalCapability); } }
Source:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_login, container, false); initViewFields(mRootView); mPasswordInput.setHint(Html.fromHtml(getString(R.string.login_password_hint) + getString(R.string.req_star))); mUsernameInput.setHint(Html.fromHtml(getString(R.string.login_username_hint) + getString(R.string.req_star))); initListeners(); if (mLastCorrectURL.equals(ApplicationConstants.EMPTY_STRING)) { mUrl.setText(OpenMRS.getInstance().getServerUrl()); mLastCorrectURL = OpenMRS.getInstance().getServerUrl(); } else { mUrl.setText(mLastCorrectURL); } hideURLDialog(); FontsUtil.setFont(this.getActivity().findViewById(android.R.id.content)); return mRootView; }

Target:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mRootView = inflater.inflate(R.layout.fragment_login, container, false); initViewFields(mRootView); initListeners(); if (mLastCorrectURL.equals(ApplicationConstants.EMPTY_STRING)) { mUrl.setText(OpenMRS.getInstance().getServerUrl()); mLastCorrectURL = OpenMRS.getInstance().getServerUrl(); } else { mUrl.setText(mLastCorrectURL); } hideURLDialog(); FontsUtil.setFont(this.getActivity().findViewById(android.R.id.content)); return mRootView; }
Source:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(DbFacade.getInstance() .getGlusterVolumeDao() .getById(getParameters().getVolumeId())); }

Target:
protected void executeQueryCommand() { getQueryReturnValue().setReturnValue(getGlusterVolumeDao().getById(getParameters().getVolumeId())); }
Source:
public static Block sequenceTimestampYearToMonth( ConnectorSession session, @SqlType(StandardTypes.TIMESTAMP) long start, @SqlType(StandardTypes.TIMESTAMP) long end, @SqlType(StandardTypes.INTERVAL_YEAR_TO_MONTH) long step) { checkCondition(step != 0, INVALID_FUNCTION_ARGUMENT, "interval must not be zero"); checkCondition(step > 0 ? end >= start : end <= start, INVALID_FUNCTION_ARGUMENT, "sequence end value should be greater than or equal to start value if step is greater than zero otherwise end should be less than start"); int length = toIntExact(diffTimestamp(session, MONTH, start, end) / step + 1); checkCondition(length <= MAX_LENGTH, INVALID_FUNCTION_ARGUMENT, "sequence should be no greater than " + MAX_LENGTH); BlockBuilder blockBuilder = BIGINT.createBlockBuilder(new BlockBuilderStatus(), length); int value = 0; for (int i = 0; i < length; ++i) { BIGINT.writeLong(blockBuilder, DateTimeOperators.timestampPlusIntervalYearToMonth(session, start, value)); value += step; } return blockBuilder.build(); }

Target:
public static Block sequenceTimestampYearToMonth( ConnectorSession session, @SqlType(StandardTypes.TIMESTAMP) long start, @SqlType(StandardTypes.TIMESTAMP) long end, @SqlType(StandardTypes.INTERVAL_YEAR_TO_MONTH) long step) { checkCondition(step != 0, INVALID_FUNCTION_ARGUMENT, "interval must not be zero"); checkCondition(step > 0 ? end >= start : end <= start, INVALID_FUNCTION_ARGUMENT, "sequence end value should be greater than or equal to start value if step is greater than zero otherwise end should be less than start"); int length = toIntExact(diffTimestamp(session, MONTH, start, end) / step + 1); checkCondition(length <= MAX_RESULT_ENTRIES, INVALID_FUNCTION_ARGUMENT, "result of sequence function must not have more than 10000 entries"); BlockBuilder blockBuilder = BIGINT.createBlockBuilder(new BlockBuilderStatus(), length); int value = 0; for (int i = 0; i < length; ++i) { BIGINT.writeLong(blockBuilder, DateTimeOperators.timestampPlusIntervalYearToMonth(session, start, value)); value += step; } return blockBuilder.build(); }
Source:
protected void createFieldEditors() { NpmHomeFieldEditor bowerHomeEditor = new NpmHomeFieldEditor(NpmPreferenceHolder.PREF_NPM_LOCATION, Messages.NpmPreferencePage_NpmLocationLabel, getFieldEditorParent()); addField(bowerHomeEditor); }

Target:
protected void createFieldEditors() { NpmHomeFieldEditor npmHomeEditor = new NpmHomeFieldEditor(NpmPreferenceHolder.PREF_NPM_LOCATION, Messages.NpmPreferencePage_NpmLocationLabel, getFieldEditorParent()); addField(npmHomeEditor); }
Source:
private void continueChain(final OperationChain opChain) { synchronized (opChain.testFutures) { OperationType nextOp = opChain.operations.poll(); if (nextOp == null) { opChain.latch.countDown(); return; } GetOptions options = GetOptions.None; switch (nextOp) { case PUT: startPutBlob(opChain); break; case GET_INFO_DELETED_SUCCESS: options = GetOptions.Include_Deleted_Blobs; case GET_INFO: case GET_INFO_DELETED: startGetBlobInfo(options, nextOp.afterDelete && options.equals(GetOptions.None), opChain); break; case GET_DELETED_SUCCESS: options = GetOptions.Include_Deleted_Blobs; case GET: case GET_DELETED: startGetBlob(options, nextOp.afterDelete && options.equals(GetOptions.None), opChain); break; case DELETE: startDeleteBlob(opChain); break; case AWAIT_CREATION: startAwaitCreation(opChain); break; case AWAIT_DELETION: startAwaitDeletion(opChain); break; default: throw new IllegalArgumentException("Unknown op: " + nextOp); } } }

Target:
private void continueChain(final OperationChain opChain) { synchronized (opChain.testFutures) { OperationType nextOp = opChain.operations.poll(); if (nextOp == null) { opChain.latch.countDown(); return; } GetOption options = GetOption.None; switch (nextOp) { case PUT: startPutBlob(opChain); break; case GET_INFO_DELETED_SUCCESS: options = GetOption.Include_Deleted_Blobs; case GET_INFO: case GET_INFO_DELETED: startGetBlobInfo(options, nextOp.checkDeleted, opChain); break; case GET_DELETED_SUCCESS: options = GetOption.Include_Deleted_Blobs; case GET: case GET_DELETED: startGetBlob(options, nextOp.checkDeleted, opChain); break; case DELETE: startDeleteBlob(opChain); break; case AWAIT_CREATION: startAwaitCreation(opChain); break; case AWAIT_DELETION: startAwaitDeletion(opChain); break; default: throw new IllegalArgumentException("Unknown op: " + nextOp); } } }
Source:
private void setupServices() { graphLoadService = new GraphLoadService(); graphLoadService.setOnFailed(e -> new ExceptionDialog(fileOpenPane.getParent(), graphLoadService.getException(), "Error loading graph files!")); graphLoadService.setOnRunning(e -> progressDialog.show()); graphLoadService.setOnSucceeded(e -> { graphProperty.setValue(graphLoadService.getValue()); done.setValue(!done.getValue()); progressDialog.close(); }); newickLoadService = new NewickLoadService(); newickLoadService.setOnFailed(e -> new ExceptionDialog(fileOpenPane.getParent(), newickLoadService.getException(), "Error loading newick file!")); newickLoadService.setOnSucceeded(e -> treeProperty.setValue(newickLoadService.getValue())); gffLoadService = new GFFLoadService(); gffLoadService.setOnFailed(e -> new ExceptionDialog(fileOpenPane.getParent(), gffLoadService.getException(), "Error loading annotations file!")); gffLoadService.graphProperty().bind(graphProperty); }

Target:
private void setupServices() { graphLoadService = new GraphLoadService(); graphLoadService.setOnFailed(e -> { progressDialog.close(); new ExceptionDialog(fileOpenPane.getParent(), graphLoadService.getException(), "Error loading graph files!"); }); graphLoadService.setOnRunning(e -> progressDialog.show()); graphLoadService.setOnSucceeded(e -> { progressDialog.close(); graphProperty.setValue(graphLoadService.getValue()); }); newickLoadService = new NewickLoadService(); newickLoadService.setOnFailed(e -> new ExceptionDialog(fileOpenPane.getParent(), newickLoadService.getException(), "Error loading newick file!")); newickLoadService.setOnSucceeded(e -> treeProperty.setValue(newickLoadService.getValue())); }
Source:
public World getWorld() { World world = this.world != null ? this.world.get() : null; if (world == null) { world = DimensionManager.getWorld(getDimId()); this.world = new WeakReference<World>(world); } return world; }

Target:
public World getWorld() { World world = this.world != null ? this.world.get() : null; if (world == null) { world = FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(getDimId()); this.world = new WeakReference<World>(world); } return world; }
Source:
public ITmfTrace getTrace() throws RuntimeException { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (trace.getResource().equals(getResource())) { return trace; } } return null; }

Target:
public ITmfTrace getTrace() { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (trace.getResource().equals(getResource())) { return trace; } } return null; }
Source:
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { if (!(args[0] instanceof CString)) { throw new CREFormatException(this.getName() + " expects a string as first argument, but type " + args[0].typeof() + " was found.", t); } Static.AssertNonCNull(t, args); String teststring = args[0].nval(); String keyword = args[1].nval(); boolean ret = teststring.startsWith(keyword); return CBoolean.get(ret); }

Target:
public Construct exec(Target t, Environment env, Construct... args) throws CancelCommandException, ConfigRuntimeException { Static.AssertNonCNull(t, args); String teststring = args[0].nval(); String keyword = args[1].nval(); boolean ret = teststring.startsWith(keyword); return CBoolean.get(ret); }
Source:
public void testPolicies() { String name = UUID.randomUUID().toString(); Policy policy = new Policy("/", name, "^foo.", null, 0, Collections.<String, Object>singletonMap("message-ttl", 1000)); this.template.addPolicy(policy); List<Policy> list = this.template.policies(); assertTrue(list.size() > 0); Policy out = null; for (Policy policyOut : list) { if (policyOut.getName().equals(name)) { out = policyOut; break; } } assertNotNull(out); list = this.template.policies("/"); assertTrue(list.size() > 0); out = null; for (Policy policyOut : list) { if (policyOut.getName().equals(name)) { out = policyOut; break; } } assertNotNull(out); this.template.removePolicy("/", name); list = this.template.policies(); out = null; for (Policy policyOut : list) { if (policyOut.getName().equals(name)) { out = policyOut; break; } } }

Target:
public void testPolicies() { String name = UUID.randomUUID().toString(); Policy policy = new Policy("/", name, "^foo.", null, 0, Collections.<String, Object>singletonMap("message-ttl", 1000)); this.template.addPolicy(policy); List<Policy> list = this.template.policies(); assertTrue(list.size() > 0); Policy out = null; for (Policy policyOut : list) { if (policyOut.getName().equals(name)) { out = policyOut; break; } } assertNotNull(out); list = this.template.policies("/"); assertTrue(list.size() > 0); out = null; for (Policy policyOut : list) { if (policyOut.getName().equals(name)) { out = policyOut; break; } } assertNotNull(out); this.template.removePolicy("/", name); list = this.template.policies(); out = null; for (Policy policyOut : list) { if (policyOut.getName().equals(name)) { out = policyOut; break; } } assertNull(out); }
Source:
public String buildSql(List<HiveColumnHandle> columns, TupleDomain<HiveColumnHandle> tupleDomain) { StringBuilder sql = new StringBuilder(); sql.append("SELECT "); if (columns.isEmpty()) { sql.append("' '"); } else { String columnNames = columns.stream() .map(column -> String.format("s._%d", column.getHiveColumnIndex() + 1)) .collect(joining(", ")); sql.append(columnNames); } sql.append(" FROM "); sql.append(DATA_SOURCE); List<String> clauses = toConjuncts(columns, tupleDomain); if (!clauses.isEmpty()) { sql.append(" WHERE ") .append(Joiner.on(" AND ").join(clauses)); } return sql.toString(); }

Target:
String buildSql(List<HiveColumnHandle> columns, TupleDomain<HiveColumnHandle> tupleDomain) { StringBuilder sql = new StringBuilder("SELECT "); if (columns.isEmpty()) { sql.append("' '"); } else { String columnNames = columns.stream() .map(column -> format("s._%d", column.getHiveColumnIndex() + 1)) .collect(joining(", ")); sql.append(columnNames); } sql.append(" FROM "); sql.append(DATA_SOURCE); List<String> clauses = toConjuncts(columns, tupleDomain); if (!clauses.isEmpty()) { sql.append(" WHERE ") .append(Joiner.on(" AND ").join(clauses)); } return sql.toString(); }