auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public DoubleDictionary(DictionaryPage dictionaryPage) throws IOException { super(dictionaryPage.getEncoding()); content = new double[dictionaryPage.getDictionarySize()]; DoublePlainValuesReader doubleReader = new DoublePlainValuesReader(); final ByteBufferInputStream in = ByteBufferInputStream.wrap(ByteBuffer.wrap(dictionaryPage.getSlice().getBytes())); doubleReader.initFromPage(dictionaryPage.getDictionarySize(), in); for (int i = 0; i < content.length; i++) { content[i] = doubleReader.readDouble(); } }

Target:
public DoubleDictionary(DictionaryPage dictionaryPage) throws IOException { super(dictionaryPage.getEncoding()); content = new double[dictionaryPage.getDictionarySize()]; DoublePlainValuesReader doubleReader = new DoublePlainValuesReader(); ByteBuffer byteBuffer = ByteBuffer.wrap(dictionaryPage.getSlice().getBytes()); ByteBufferInputStream inputStream = ByteBufferInputStream.wrap(ImmutableList.of(byteBuffer)); doubleReader.initFromPage(dictionaryPage.getDictionarySize(), inputStream); for (int i = 0; i < content.length; i++) { content[i] = doubleReader.readDouble(); } }
Source:
protected File fileFromKey(byte[] key) { File file = new File(attachmentsDir, new String(new Hex().encode(key))); return file; }

Target:
private File fileFromKey(byte[] key) { File file = new File(attachmentsDir, keyToString(key)); return file; }
Source:
public boolean next(List<Cell> list) throws IOException { if (failure.get() != null) { timer.cancel(); throw failure.get(); } Entry entry; try { entry = queue.take(); int toRelease = entry.cells.size(); final boolean more = entry.more; List<TxnView> txns = waitFor(entry.txns); compactionState.mutate(entry.cells, txns, list, purgeConfig); if (!more) { timer.cancel(); context.close(); } permits.release(toRelease); return more; } catch (Exception e) { timer.cancel(); throw new IOException(e); } }

Target:
public boolean next(List<Cell> list) throws IOException { if (failure.get() != null) { timer.cancel(); throw failure.get(); } Entry entry; try { entry = queue.take(); int toRelease = entry.cells.size(); final boolean more = entry.more; List<TxnView> txns = waitFor(entry.txns); compactionState.mutate(entry.cells, txns, list, purgeConfig); if (!more) { timer.cancel(); context.close(); } permits.release(toRelease); return more; } catch (Throwable t) { timer.cancel(); stop = true; permits.release(queue.size()); queue.clear(); throw new IOException(t); } }
Source:
private Metacard buildMetacard() { MetacardType metacardType = new MetacardTypeImpl("", new HashSet<>(ATTRIBUTE_DESCRIPTOR_LIST)); Metacard metacard = new MetacardImpl(metacardType); for (Attribute a : metacardDataMap.values()) { metacard.setAttribute(a); } return metacard; }

Target:
private Metacard buildMetacard() { MetacardType metacardType = new MetacardTypeImpl("", ATTRIBUTE_DESCRIPTORS); Metacard metacard = new MetacardImpl(metacardType); for (Attribute attribute : ATTRIBUTES) { metacard.setAttribute(attribute); } return metacard; }
Source:
public void testCreateTabixIndexFromVCF( final File inputVCF, final Interval queryInterval) throws IOException { final File tmpVCF = new File(IOUtil.createTempDir("testCreateTabixIndexFromVCF", null), inputVCF.getName()); Files.copy(inputVCF, tmpVCF); final TabixIndex tabixIndexGz = IndexFactory.createTabixIndex(tmpVCF, new VCFCodec(), null); tabixIndexGz.writeBasedOnFeatureFile(tmpVCF); try(final VCFFileReader originalReader = new VCFFileReader(inputVCF,false); final VCFFileReader tmpReader = new VCFFileReader(tmpVCF, new File(tmpVCF.getAbsolutePath()+ ".tbi"),true)) { Iterator<VariantContext> originalIt = originalReader.iterator(); Iterator<VariantContext> tmpIt = tmpReader.query(queryInterval.getContig(), queryInterval.getStart(), queryInterval.getEnd()); while(originalIt.hasNext()) { Assert.assertTrue(tmpIt.hasNext(), "variants missing from gzip query"); VariantContext vcTmp = tmpIt.next(); VariantContext vcOrig = originalIt.next(); Assert.assertEquals(vcOrig.getContig(), vcTmp.getContig()); Assert.assertEquals(vcOrig.getStart(), vcTmp.getStart()); Assert.assertEquals(vcOrig.getEnd(), vcTmp.getEnd()); } } }

Target:
public void testCreateTabixIndexFromVCF( final File inputVCF, final Interval queryInterval) throws IOException { final File tempDir = IOUtil.createTempDir("testCreateTabixIndexFromVCF", null); tempDir.deleteOnExit(); final File tmpVCF = new File(tempDir, inputVCF.getName()); Files.copy(inputVCF, tmpVCF); tmpVCF.deleteOnExit(); final TabixIndex tabixIndexGz = IndexFactory.createTabixIndex(tmpVCF, new VCFCodec(), null); tabixIndexGz.writeBasedOnFeatureFile(tmpVCF); final File tmpIndex = Tribble.tabixIndexFile(tmpVCF); tmpIndex.deleteOnExit(); try (final VCFFileReader originalReader = new VCFFileReader(inputVCF,false); final VCFFileReader tmpReader = new VCFFileReader(tmpVCF, tmpIndex,true)) { Iterator<VariantContext> originalIt = originalReader.iterator(); Iterator<VariantContext> tmpIt = tmpReader.query(queryInterval.getContig(), queryInterval.getStart(), queryInterval.getEnd()); while (originalIt.hasNext()) { Assert.assertTrue(tmpIt.hasNext(), "variants missing from gzip query"); VariantContext vcTmp = tmpIt.next(); VariantContext vcOrig = originalIt.next(); Assert.assertEquals(vcOrig.getContig(), vcTmp.getContig()); Assert.assertEquals(vcOrig.getStart(), vcTmp.getStart()); Assert.assertEquals(vcOrig.getEnd(), vcTmp.getEnd()); } } }
Source:
public void spec210_blackbox_mustBePreparedToReceiveAnOnErrorSignalWithPrecedingRequestCall() throws Throwable { blackboxSubscriberTest(new BlackboxTestStageTestRun() { @Override @SuppressWarnings("ThrowableResultOfMethodCallIgnored") public void run(BlackboxTestStage stage) throws Throwable { stage.sub().onError(new Throwable("Test Exception: Boom!")); stage.subProxy().expectError(Throwable.class); } }); }

Target:
public void spec210_blackbox_mustBePreparedToReceiveAnOnErrorSignalWithPrecedingRequestCall() throws Throwable { blackboxSubscriberTest(new BlackboxTestStageTestRun() { @Override @SuppressWarnings("ThrowableResultOfMethodCallIgnored") public void run(BlackboxTestStage stage) throws Throwable { stage.sub().onError(new TestException()); stage.subProxy().expectError(Throwable.class); } }); }
Source:
private void performSlaRelatedLogging(DatastreamRecordMetadata metadata, long eventsSourceTimestamp, long sourceToDestinationLatencyMs) { if (_warnLogLatencyEnabled && (sourceToDestinationLatencyMs > _warnLogLatencyThresholdMs)) { _logger.warn("Source to destination latency ms is higher than ms, Source Timestamp: {}, Metadata: {}", sourceToDestinationLatencyMs, _warnLogLatencyThresholdMs, eventsSourceTimestamp, metadata.toString()); } if (_numEventsOutsideAltSlaLogEnabled) { if (sourceToDestinationLatencyMs > _availabilityThresholdAlternateSlaMs) { TopicPartition topicPartition = new TopicPartition(metadata.getTopic(), metadata.getPartition()); int numEvents = _trackEventsOutsideAltSlaMap.getOrDefault(topicPartition, 0); _trackEventsOutsideAltSlaMap.put(topicPartition, numEvents + 1); } long timeSinceLastLog = System.currentTimeMillis() - _lastEventsOutsideAltSlaLogTimeMs; if (timeSinceLastLog >= _numEventsOutsideAltSlaFrequencyMs) { _trackEventsOutsideAltSlaMap.forEach((topicPartition, numEvents) -> _logger.warn("{} had event(s) with latency greater than alternate SLA of ms in the last ms", topicPartition, numEvents, _availabilityThresholdAlternateSlaMs, timeSinceLastLog)); _trackEventsOutsideAltSlaMap.clear(); _lastEventsOutsideAltSlaLogTimeMs = System.currentTimeMillis(); } } }

Target:
private void performSlaRelatedLogging(DatastreamRecordMetadata metadata, long eventsSourceTimestamp, long sourceToDestinationLatencyMs) { if (_warnLogLatencyEnabled && (sourceToDestinationLatencyMs > _warnLogLatencyThresholdMs)) { _logger.warn("Source to destination latency ms is higher than ms, Source Timestamp: {}, Metadata: {}", sourceToDestinationLatencyMs, _warnLogLatencyThresholdMs, eventsSourceTimestamp, metadata); } if (_numEventsOutsideAltSlaLogEnabled) { if (sourceToDestinationLatencyMs > _availabilityThresholdAlternateSlaMs) { TopicPartition topicPartition = new TopicPartition(metadata.getTopic(), metadata.getPartition()); int numEvents = _trackEventsOutsideAltSlaMap.getOrDefault(topicPartition, 0); _trackEventsOutsideAltSlaMap.put(topicPartition, numEvents + 1); } long timeSinceLastLog = System.currentTimeMillis() - _lastEventsOutsideAltSlaLogTimeMs; if (timeSinceLastLog >= _numEventsOutsideAltSlaFrequencyMs) { _trackEventsOutsideAltSlaMap.forEach((topicPartition, numEvents) -> _logger.warn("{} had event(s) with latency greater than alternate SLA of ms in the last ms", topicPartition, numEvents, _availabilityThresholdAlternateSlaMs, timeSinceLastLog)); _trackEventsOutsideAltSlaMap.clear(); _lastEventsOutsideAltSlaLogTimeMs = System.currentTimeMillis(); } } }
Source:
public void find(String packageName, final Class<?> parentType) { this.parentType = parentType; packageName = packageName.replace('.', '/'); final Enumeration<URL> urls; try { urls = loader.getResources(packageName); } catch (IOException ioe) { log.warn("Could not read package: " + packageName, ioe); return; } while (urls.hasMoreElements()) { try { String urlPath = urls.nextElement().getFile(); try { URI uri = new URI(urlPath); urlPath = uri.getPath(); } catch (URISyntaxException e) { log.warn("Cannot convert to URI the " + urlPath + " URL"); } if (urlPath.indexOf('!') > 0) { urlPath = urlPath.substring(0, urlPath.indexOf('!')); } if (jarPath != null && !jarPath.equals(urlPath)) { continue; } final File file = new File(urlPath); if ( file.isDirectory() ) { scanDir(file, packageName); } else { scanJar(file, packageName); } } catch (IOException ioe) { log.warn("could not read entries", ioe); } } }

Target:
public void find(String packageName, final Class<?> parentType) { this.parentType = parentType; packageName = packageName.replace('.', '/'); final Enumeration<URL> urls; try { urls = loader.getResources(packageName); } catch (IOException ioe) { log.warn("Could not read package: " + packageName, ioe); return; } while (urls.hasMoreElements()) { try { String urlPath = urls.nextElement().getFile(); try { URI uri = new URI(urlPath); urlPath = uri.getPath(); } catch (URISyntaxException e) { log.warn("Cannot convert to URI the " + urlPath + " URL"); } if (urlPath.indexOf('!') > 0) { urlPath = urlPath.substring(0, urlPath.indexOf('!')); } if (jarPath != null && !jarPath.equals(urlPath)) { continue; } log.debug("Looking for classes in location: " + urlPath); final File file = new File(urlPath); if ( file.isDirectory() ) { scanDir(file, packageName); } else { scanJar(file, packageName); } } catch (IOException ioe) { log.warn("could not read entries", ioe); } } }
Source:
private static <T> InputStream pageToStream(Page<T> page, ObjectMapper mapper) { PipedInputStream in = new PipedInputStream(); new Thread(() -> { try (PipedOutputStream out = new PipedOutputStream(in)) { while (page.hasNext()) { mapper.writeValue(out, page.next()); } } catch (IOException e) { throw new IllegalStateException("Unable to convert page to input stream.", e); } }).start(); return in; }

Target:
private static <T> InputStream pageToStream(Page<T> page, ObjectMapper mapper) throws IOException { final PipedOutputStream outs = new PipedOutputStream(); final PipedInputStream ins = new PipedInputStream() { @Override public void close() throws IOException { outs.close(); super.close(); } }; outs.connect(ins); mapper.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET); PageToStreamThreadPool.getInstance().submit(() -> { try (Page<T> closeablePage = page; PipedOutputStream out = outs; SequenceWriter sequenceWriter = mapper.writer().writeValuesAsArray(out)) { for (T element : closeablePage) { sequenceWriter.write(element); sequenceWriter.flush(); } } catch (IOException e) { throw new IllegalStateException("Unable to convert page to input stream.", e); } }); return ins; }
Source:
public void inspectRuntimeShape(final RuntimeShapeInspector inspector) { inspector.visit("keyselector", keySelector); inspector.visit("valueselectors", valueSelectors.toArray()); }

Target:
public void inspectRuntimeShape(final RuntimeShapeInspector inspector) { inspector.visit("keySelector", keySelector); inspector.visit("valueSelectors", valueSelectors); }
Source:
public void cleanShutdown() { log.info("CleanShutdown: Starting Cleanup."); shutdownServer = true; activeServer.close(); replicationDiscoveryService.shutdown(); clusterManagerAdapter.shutdown(); }

Target:
public void cleanShutdown() { log.info("CleanShutdown: Starting Cleanup."); shutdownServer = true; activeServer.close(); if (replicationDiscoveryService != null) { replicationDiscoveryService.shutdown(); } }
Source:
public void testWithFilledArrays() { final KeySet keySetOriginal = new KeySet(); final byte[] authenticationKey = { 1, 64, 127 }; keySetOriginal.setAuthenticationKey(authenticationKey); final byte[] encryptionKey = { 127, 63, 0 }; keySetOriginal.setEncryptionKey(encryptionKey); final com.alliander.osgp.domain.core.valueobjects.smartmetering.KeySet keySetMapped = this.mapperFactory .getMapperFacade().map(keySetOriginal, com.alliander.osgp.domain.core.valueobjects.smartmetering.KeySet.class); assertNotNull(keySetMapped); assertEquals(1, keySetMapped.getAuthenticationKey()[0]); assertEquals(64, keySetMapped.getAuthenticationKey()[1]); assertEquals(127, keySetMapped.getAuthenticationKey()[2]); assertEquals(127, keySetMapped.getEncryptionKey()[0]); assertEquals(63, keySetMapped.getEncryptionKey()[1]); assertEquals(0, keySetMapped.getEncryptionKey()[2]); }

Target:
public void testWithFilledArrays() { final KeySet keySetOriginal = new KeySet(); final byte[] authenticationKey = BYTE_ARRAY; keySetOriginal.setAuthenticationKey(authenticationKey); final byte[] encryptionKey = BYTE_ARRAY; keySetOriginal.setEncryptionKey(encryptionKey); final com.alliander.osgp.domain.core.valueobjects.smartmetering.KeySet keySetMapped = this.configurationMapper .map(keySetOriginal, com.alliander.osgp.domain.core.valueobjects.smartmetering.KeySet.class); assertNotNull(keySetMapped); this.checkMappingFilledArray(keySetMapped.getAuthenticationKey()); this.checkMappingFilledArray(keySetMapped.getEncryptionKey()); }
Source:
protected void addPages() { try { List<AbstractAirdEditorCustomPage> newOrderedPages = pageRegistry.getPagesOrdered(this, session, pages.stream().filter(AbstractAirdEditorCustomPage.class::isInstance).map(AbstractAirdEditorCustomPage.class::cast).collect(Collectors.toList())); updatePages(newOrderedPages); } catch (PartInitException e) { ErrorDialog.openError(getSite().getShell(), MessageFormat.format(Messages.UI_SessionEditor_page_loading_error_message, new Object[0]), e.getMessage(), e.getStatus()); } }

Target:
protected void addPages() { updatePages(); }
Source:
public Optional<OutputStream> tryCreateOutputStream() { try { if (outputStreamSupplier == null) { return Optional.empty(); } return Optional.ofNullable(outputStreamSupplier.apply(this)); } catch (Exception e) { throw handleErrorInCallback(e, "outputStreamSupplier"); } }

Target:
public Optional<OutputStream> tryCreateOutputStream() { try { if (!canCreateOutputStream()) { return Optional.empty(); } return Optional.ofNullable(outputStreamSupplier.apply(this)); } catch (Exception e) { throw handleErrorInCallback(e, "outputStreamSupplier"); } }
Source:
private void updateStoragePoolFormatType() { final StoragePool storagePool = getStoragePool(); final Guid spId = storagePool.getId(); final Version spVersion = storagePool.getcompatibility_version(); final Version oldSpVersion = _oldStoragePool.getcompatibility_version(); if (oldSpVersion.equals(spVersion)) { return; } StorageType spType = storagePool.getStorageType(); final StorageFormatType targetFormat = VersionStorageFormatUtil.getPreferredForVersion(spVersion, spType); storagePool.setStoragePoolFormatType(targetFormat); TransactionSupport.executeInScope(TransactionScopeOption.RequiresNew, new TransactionMethod<Object>() { @Override public Object runInTransaction() { getStoragePoolDAO().updatePartial(storagePool); updateMemberDomainsFormat(targetFormat); return null; } }); if (_oldStoragePool.getStatus() == StoragePoolStatus.Up) { try { runVdsCommand(VDSCommandType.UpgradeStoragePool, new UpgradeStoragePoolVDSCommandParameters(spId, targetFormat)); } catch (VdcBLLException e) { log.warnFormat("Upgrade procees of Storage Pool {0} has encountered a problem due to following reason: {1}", spId, e.getMessage()); AuditLogDirector.log(this, AuditLogType.UPGRADE_STORAGE_POOL_ENCOUNTERED_PROBLEMS); } } }

Target:
private void updateStoragePoolFormatType() { final StoragePool storagePool = getStoragePool(); final Guid spId = storagePool.getId(); final Version spVersion = storagePool.getcompatibility_version(); final Version oldSpVersion = _oldStoragePool.getcompatibility_version(); if (oldSpVersion.equals(spVersion)) { return; } final StorageFormatType targetFormat = VersionStorageFormatUtil.getPreferredForVersion(spVersion, getMasterDomain() == null ? null : getMasterDomain().getStorageType()); storagePool.setStoragePoolFormatType(targetFormat); TransactionSupport.executeInScope(TransactionScopeOption.RequiresNew, new TransactionMethod<Object>() { @Override public Object runInTransaction() { getStoragePoolDAO().updatePartial(storagePool); updateMemberDomainsFormat(targetFormat); return null; } }); if (_oldStoragePool.getStatus() == StoragePoolStatus.Up) { try { runVdsCommand(VDSCommandType.UpgradeStoragePool, new UpgradeStoragePoolVDSCommandParameters(spId, targetFormat)); } catch (VdcBLLException e) { log.warnFormat("Upgrade procees of Storage Pool {0} has encountered a problem due to following reason: {1}", spId, e.getMessage()); AuditLogDirector.log(this, AuditLogType.UPGRADE_STORAGE_POOL_ENCOUNTERED_PROBLEMS); } } }
Source:
public void verifyFirstResult(String query) { verifyFirstResultName(query); verifyDescription(); verifyUrl(query); }

Target:
public void verifyFirstResult(String query) { Assertion.assertStringContains(firstResult.getText(), query.replaceAll("_", " ")); for (WebElement elem:descriptions) { Assertion.assertTrue(!elem.getText().isEmpty()); } Assertion.assertEquals(titles.size(), urls.size()); }
Source:
public String getParams() { return "cell c or object value, string projectName (optional), string columnName (optional)"; }

Target:
public String getParams() { return "cell or value, string projectName (optional), string columnName (optional)"; }
Source:
static final Predicate<IMatchEngine.Factory> isMatchEngineFactoryActivable(final IComparisonScope scope) { return new Predicate<IMatchEngine.Factory>() { public boolean apply(IMatchEngine.Factory d) { return d.isMatchEngineFactoryFor(scope); } }; }

Target:
private static Predicate<IMatchEngine.Factory> isMatchEngineFactoryActivable(final IComparisonScope scope) { return new Predicate<IMatchEngine.Factory>() { public boolean apply(IMatchEngine.Factory factory) { return factory.isMatchEngineFactoryFor(scope); } }; }
Source:
private static List<ExceptionInfo> getThrowed(DetailAST methodAst) { final List<ExceptionInfo> returnValue = new ArrayList<>(); final DetailAST blockAst = methodAst.findFirstToken(TokenTypes.SLIST); if (blockAst != null) { final List<DetailAST> throwLiterals = findTokensInAstByType(blockAst, TokenTypes.LITERAL_THROW); for (DetailAST throwAst : throwLiterals) { if (!isInIgnoreBlock(blockAst, throwAst)) { final DetailAST newAst = throwAst.getFirstChild().getFirstChild(); if (newAst.getType() == TokenTypes.LITERAL_NEW) { DetailAST child = newAst.getFirstChild(); final FullIdent ident = FullIdent.createFullIdent(child); while (child.getType() == TokenTypes.DOT) { child = child.getFirstChild(); } final ExceptionInfo exceptionInfo = new ExceptionInfo(child, new ClassInfo(new Token(ident))); returnValue.add(exceptionInfo); } } } } return returnValue; }

Target:
private static List<ExceptionInfo> getThrowed(DetailAST methodAst) { final List<ExceptionInfo> returnValue = new ArrayList<>(); final DetailAST blockAst = methodAst.findFirstToken(TokenTypes.SLIST); if (blockAst != null) { final List<DetailAST> throwLiterals = findTokensInAstByType(blockAst, TokenTypes.LITERAL_THROW); for (DetailAST throwAst : throwLiterals) { if (!isInIgnoreBlock(blockAst, throwAst)) { final DetailAST newAst = throwAst.getFirstChild().getFirstChild(); if (newAst.getType() == TokenTypes.LITERAL_NEW) { final DetailAST child = newAst.getFirstChild(); returnValue.add(getExceptionInfo(child)); } } } } return returnValue; }
Source:
protected void parseTickerFromJsonObject(int requestId, JSONObject jsonObject, Ticker ticker, CheckerInfo checkerInfo) throws Exception { String pairId = checkerInfo.getCurrencyPairId(); String currencyCode = checkerInfo.getCurrencyCounterLowerCase() + "btc"; final JSONObject tickerJsonObject = jsonObject.getJSONObject("data"); final JSONObject buyObject = tickerJsonObject.getJSONObject("compra"); final JSONObject sellObject = tickerJsonObject.getJSONObject("venta"); ticker.ask = buyObject.getDouble(currencyCode); ticker.bid = sellObject.getDouble(currencyCode); ticker.last = ticker.ask; }

Target:
protected void parseTickerFromJsonObject(int requestId, JSONObject jsonObject, Ticker ticker, CheckerInfo checkerInfo) throws Exception { String currencyCode = checkerInfo.getCurrencyCounterLowerCase() + checkerInfo.getCurrencyBaseLowerCase(); final JSONObject tickerJsonObject = jsonObject.getJSONObject("data"); final JSONObject buyObject = tickerJsonObject.getJSONObject("compra"); final JSONObject sellObject = tickerJsonObject.getJSONObject("venta"); ticker.ask = buyObject.getDouble(currencyCode); ticker.bid = sellObject.getDouble(currencyCode); ticker.last = ticker.ask; }
Source:
public static final ByteSizeStrings java() { ByteSizeStrings strings = new ByteSizeStrings(); strings.setBytesPerMetricUnit(1024); strings.setPrecision(0); strings.setMaxLen(6); strings.setSuffixBytes(""); strings.setSuffixKilo("k"); strings.setSuffixMega("m"); strings.setSuffixGiga("g"); return strings; }

Target:
public static final ByteSizeStrings java() { return JAVA; }
Source:
public HostLocation getHostLocation() { String dataCenter = "Unknown"; String rack = "Unknown"; String physicalHost = "Unknown"; try { Config config = ConfigFactory.parseFile(file); if (config.hasPath("dataCenter")) { dataCenter = config.getString("dataCenter"); } if (config.hasPath("rack")) { rack = config.getString("rack"); } if (config.hasPath("physicalHost")) { physicalHost = config.getString("physicalHost"); } } catch (Exception e) { log.warn("error getting host location from {}: {}", file.getName(), e); } return new HostLocation(dataCenter, rack, physicalHost); }

Target:
public HostLocation getHostLocation() { String dataCenter = "Unknown"; String rack = "Unknown"; String physicalHost = "Unknown"; try { Config config = ConfigFactory.parseFile(file); if (config.hasPath("dataCenter")) { dataCenter = config.getString("dataCenter"); } if (config.hasPath("rack")) { rack = config.getString("rack"); } if (config.hasPath("physicalHost")) { physicalHost = config.getString("physicalHost"); } } catch (Exception e) { log.warn("error getting host location from {}: ", file.getName(), e); } return new HostLocation(dataCenter, rack, physicalHost); }
Source:
public boolean doTruncate(StorageBroker sb, TileBreeder breeder) throws StorageException, GeoWebCacheException { Iterator<TileLayer> iterator = breeder.getLayers().iterator(); TileLayer toTruncate; boolean truncated = false; while (iterator.hasNext()) { toTruncate = iterator.next(); truncated = sb.delete(toTruncate.getName()); if (!truncated) { try { breeder.findTileLayer(toTruncate.getName()); } catch (GeoWebCacheException e) { throw new IllegalArgumentException( "Could not find layer " + toTruncate.getName()); } } else { log.info("Truncate All Job: Finished deleting layer " + toTruncate.getName()); if (getTrucatedLayers().length() > 0) getTrucatedLayers().append(","); getTrucatedLayers().append(toTruncate.getName()); } } return true; }

Target:
public boolean doTruncate(StorageBroker sb, TileBreeder breeder) throws StorageException, GeoWebCacheException { Iterator<TileLayer> iterator = breeder.getLayers().iterator(); TileLayer toTruncate; Iterator<String> gridSetIterator; String gridSetId = ""; boolean truncated = false; while (iterator.hasNext()) { toTruncate = iterator.next(); gridSetIterator = toTruncate.getGridSubsets().iterator(); while (gridSetIterator.hasNext()) { gridSetId = gridSetIterator.next(); truncated = sb.deleteByGridSetId(toTruncate.getName(), gridSetId); log.info("Layer: " + toTruncate.getName() + ",Truncated Gridset :" + gridSetId); } if (truncated) { if (getTrucatedLayers().length() > 0) trucatedLayers.append(","); getTrucatedLayers().append(toTruncate.getName()); } } return true; }
Source:
private boolean initializeOpenVRLibrary() throws Exception { if (initialized) return true; System.out.println("Adding OpenVR search path: " + OSValidator.getLibPath()); NativeLibrary.addSearchPath("openvr_api", OSValidator.getLibPath()); if (jopenvr.JOpenVRLibrary.VR_IsHmdPresent() == 1) { System.out.println("VR Headset detected."); } else { System.out.println("VR Headset not detected."); return false; } return true; }

Target:
private boolean initializeOpenVRLibrary() { if (initialized) { return true; } logger.info("Adding OpenVR search path: " + NativeHelper.getOpenVRLibPath()); NativeLibrary.addSearchPath("openvr_api", NativeHelper.getOpenVRLibPath()); if (jopenvr.JOpenVRLibrary.VR_IsHmdPresent() != 1) { logger.info("VR Headset not detected."); return false; } logger.info("VR Headset detected."); return true; }
Source:
public ChainBuilder add(final ByteBuffer payload) { List<Element> newList = new ArrayList<Element>(); newList.addAll(this.elements); newList.add(new Element() { @Override public ByteBuffer getPayload() { return payload.duplicate(); } }); return new ChainBuilder(newList); }

Target:
public ChainBuilder add(final ByteBuffer payload) { List<ByteBuffer> newList = new ArrayList<ByteBuffer>(); newList.addAll(this.buffers); newList.add(payload); return new ChainBuilder(newList); }
Source:
protected boolean updateGalleryElements(Controller controller, final Array<SceneButton> elements, final Vector2 viewport, final I18N i18n, final Skin skin) { if (this.needsUpdate) { this.needsUpdate = false; elements.clear(); Map<String, Scene> map = controller.getModel().getScenes(); for (Entry<String, Scene> entry : map.entrySet()) { final SceneButton sceneWidget = new SceneButton(viewport, i18n, entry.getValue(), skin); sceneWidget.setUserObject(entry.getKey()); elements.add(sceneWidget); } return true; } return false; }

Target:
protected boolean updateGalleryElements(Controller controller, final Array<SceneButton> elements, final Vector2 viewport, final I18N i18n, final Skin skin) { if (this.needsUpdate) { this.needsUpdate = false; elements.clear(); Map<String, Scene> map = controller.getModel().getScenes(); for (Entry<String, Scene> entry : map.entrySet()) { final SceneButton sceneWidget = new SceneButton(viewport, i18n, entry.getKey(), entry.getValue(), skin); elements.add(sceneWidget); } return true; } return false; }
Source:
private static Predicate<ViolationEntity> applicationIdIsEqual(String applicationId) { return v -> applicationId.equals(v.getApplication().getName()); }

Target:
private static Predicate<ViolationEntity> applicationIdIsEqual(String applicationId) { return v -> applicationId.equals( Optional.ofNullable( v.getApplication()). map(ApplicationEntity::getName). orElse(null)); }
Source:
public static SequencerReference to(SequencerDto dto) { SequencerReference to = new SequencerReferenceImpl(); to.setId(dto.getId()); to.setDateCommissioned(extractDateOrNull(dto.getDateCommissioned())); to.setDateDecommissioned(extractDateOrNull(dto.getDateDecommissioned())); to.setIpAddress(dto.getIp()); to.setName(dto.getName()); to.setSerialNumber(dto.getSerialNumber()); to.setPlatform(to(dto.getPlatform())); to.setSerialNumber(dto.getSerialNumber()); return to; }

Target:
public static SequencerReference to(SequencerDto dto) { SequencerReference to = new SequencerReferenceImpl(); to.setId(dto.getId()); to.setDateCommissioned(extractDateOrNull(dto.getDateCommissioned())); to.setDateDecommissioned(extractDateOrNull(dto.getDateDecommissioned())); to.setIpAddress(dto.getIp()); to.setName(dto.getName()); to.setPlatform(to(dto.getPlatform())); to.setSerialNumber(dto.getSerialNumber()); return to; }
Source:
public void testEventMessageToJobData( Serializer serializer, Function<Class, String> expectedSerializedClassType, Predicate<Object> revisionMatcher ) { QuartzEventScheduler.DirectEventJobDataBinder testSubject = new QuartzEventScheduler.DirectEventJobDataBinder(serializer); JobDataMap result = testSubject.toJobData(testEventMessage); assertEquals(testEventMessage.getIdentifier(), result.get(MESSAGE_ID)); assertEquals(testEventMessage.getTimestamp().toEpochMilli(), result.get(MESSAGE_TIMESTAMP)); String expectedPayloadType = expectedSerializedClassType.apply(testEventMessage.getPayloadType()); assertEquals(expectedPayloadType, result.get(MESSAGE_TYPE)); Object resultRevision = result.get(MESSAGE_REVISION); assertTrue(revisionMatcher.test(resultRevision)); assertNotNull(result.get(SERIALIZED_MESSAGE_PAYLOAD)); assertNotNull(result.get(MESSAGE_METADATA)); verify(serializer).serialize(TEST_EVENT_PAYLOAD, byte[].class); verify(serializer).serialize(testMetaData, byte[].class); }

Target:
void testEventMessageToJobData( Serializer serializer, Function<Class, String> expectedSerializedClassType, Predicate<Object> revisionMatcher ) { QuartzEventScheduler.DirectEventJobDataBinder testSubject = new QuartzEventScheduler.DirectEventJobDataBinder(serializer); JobDataMap result = testSubject.toJobData(testEventMessage); assertEquals(testEventMessage.getIdentifier(), result.get(MESSAGE_ID)); assertEquals(testEventMessage.getTimestamp().toEpochMilli(), result.get(MESSAGE_TIMESTAMP)); String expectedPayloadType = expectedSerializedClassType.apply(testEventMessage.getPayloadType()); assertEquals(expectedPayloadType, result.get(MESSAGE_TYPE)); Object resultRevision = result.get(MESSAGE_REVISION); assertTrue(revisionMatcher.test(resultRevision)); assertNotNull(result.get(SERIALIZED_MESSAGE_PAYLOAD)); assertNotNull(result.get(MESSAGE_METADATA)); verify(serializer).serialize(TEST_EVENT_PAYLOAD, byte[].class); verify(serializer).serialize(testMetaData, byte[].class); }
Source:
public PartialTableCache() { cache = new ConcurrentHashMap<>(); epochEntries = new TreeSet<>(); executorService = Executors.newSingleThreadExecutor(); }

Target:
public PartialTableCache() { cache = new ConcurrentHashMap<>(); epochEntries = new TreeSet<>(); ThreadFactory build = new ThreadFactoryBuilder().setDaemon(true) .setNameFormat("PartialTableCache Cleanup Thread - %d").build(); executorService = Executors.newSingleThreadExecutor(build); }
Source:
public void onRefresh() { super.onRefresh(); if (mFile != null) { mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId()); listDirectory(mFile); ((FileDisplayActivity)mContainerActivity).startSyncFolderOperation(mFile); Log_OC.d(TAG, "Parent etag= |" + mFile.getEtag() + "|"); } }

Target:
public void onRefresh() { super.onRefresh(); if (mFile != null) { mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId()); listDirectory(mFile); ((FileDisplayActivity)mContainerActivity).startSyncFolderOperation(mFile); } }
Source:
public void bindTo(MeterRegistry registry) { startingCounter = Counter.builder(workspaceMetric("starting_attempts.total")) .description("The count of workspaces start attempts") .register(registry); startingDebugCounter = Counter.builder(workspaceMetric("starting_attempts.total")) .tags(withStandardTags("debug")) .description("The count of workspaces start attempts in debug mode") .register(registry); eventService.subscribe( event -> { if (event.getPrevStatus() == WorkspaceStatus.STOPPED && event.getStatus() == WorkspaceStatus.STARTING) { startingCounter.increment(); if (event.getOptions() != null && event.getOptions() .containsKey(DEBUG_WORKSPACE_START)) { startingDebugCounter.increment(); } } }, WorkspaceStatusEvent.class); }

Target:
public void bindTo(MeterRegistry registry) { startingCounter = Counter.builder(workspaceMetric("starting_attempts.total")) .tags(withStandardTags("debug", "false")) .description("The count of workspaces start attempts") .register(registry); startingDebugCounter = Counter.builder(workspaceMetric("starting_attempts.total")) .tags(withStandardTags("debug", "true")) .description("The count of workspaces start attempts in debug mode") .register(registry); eventService.subscribe( event -> { if (event.getPrevStatus() == WorkspaceStatus.STOPPED && event.getStatus() == WorkspaceStatus.STARTING) { if (event.getOptions() != null && Boolean.parseBoolean( event.getOptions().getOrDefault(DEBUG_WORKSPACE_START, FALSE.toString()))) { startingDebugCounter.increment(); } else { startingCounter.increment(); } } }, WorkspaceStatusEvent.class); }
Source:
private void loadPluginSections(Config rc) { pluginConfigs = Maps.newHashMap(); Set<String> pluginSubsections = rc.getSubsections(PLUGIN); for (String plugin : pluginSubsections) { LinkedListMultimap<String, String> pluginConfig = LinkedListMultimap.create(); pluginConfigs.put(plugin, pluginConfig); for (String name : rc.getNames(PLUGIN, plugin)) { pluginConfig.putAll(name, Arrays.asList(rc.getStringList(PLUGIN, plugin, name))); } } }

Target:
private void loadPluginSections(Config rc) { pluginConfigs = Maps.newHashMap(); for (String plugin : rc.getSubsections(PLUGIN)) { LinkedListMultimap<String, String> pluginConfig = LinkedListMultimap.create(); pluginConfigs.put(plugin, pluginConfig); for (String name : rc.getNames(PLUGIN, plugin)) { pluginConfig.putAll(name, Arrays.asList(rc.getStringList(PLUGIN, plugin, name))); } } }
Source:
public void buildProjNoCmdLineArgumentsTest() { FreeStyleJob job = msBuildJob("/msbuild_plugin/projProject/", "project.proj", null); Build b = job.scheduleBuild(); b.shouldSucceed(); assertThat(b.getConsole(), Matchers.containsString("Build succeeded.")); assertThat(b.getConsole(), Matchers.not(Matchers.containsString("Done building project \"project.proj\"."))); }

Target:
public void buildProjNoCmdLineArgumentsTest() { FreeStyleJob job = msBuildJob("/msbuild_plugin/projProject/", "project.proj", null); Build b = job.scheduleBuild(); b.shouldSucceed(); assertThat(b.getConsole(), containsString("Build succeeded.")); assertThat(b.getConsole(), not(containsString("Done building project \"project.proj\"."))); }
Source:
public void publish(Object message, Map<String, String> dynamicProperties) { try { if (session == null) { throw new ConnectionUnavailableException("Connection was not available when trying to publish a message via the adapter: " + eventAdapterConfiguration.getName() + ", for tenant ID: " + tenantId + " as the session was null. \n Message: \n" + message); } else if (!session.isOpen()) { throw new ConnectionUnavailableException("Connection was not available when trying to publish a message via the adapter: " + eventAdapterConfiguration.getName() + ", for tenant ID: " + tenantId + " as the session was not open. Session ID:" + session.getId() + " \n Message: \n" + message); } else { executorService.execute(new WebSocketSender(message.toString())); } } catch (RejectedExecutionException e) { EventAdapterUtil.logAndDrop(eventAdapterConfiguration.getName(), message, "Job queue is full", e, log, tenantId); } }

Target:
public void publish(Object message, Map<String, String> dynamicProperties) { try { if (session == null) { throw new ConnectionUnavailableException("Session was not available when trying to publish via adapter: " + eventAdapterConfiguration.getName() + ", tenant ID: " + tenantId + "\n Event: \n" + message); } else if (!session.isOpen()) { throw new ConnectionUnavailableException("Session was not open when trying to publish via adapter: " + eventAdapterConfiguration.getName() + ", for tenant ID: " + tenantId + ". Session ID: " + session.getId() + " \n Event: \n" + message); } else { executorService.execute(new WebSocketSender(message.toString())); } } catch (RejectedExecutionException e) { EventAdapterUtil.logAndDrop(eventAdapterConfiguration.getName(), message, "Job queue is full", e, log, tenantId); } }
Source:
public Container apply(HttpResponse from) { String bytesUsed = from.getFirstHeaderOrNull(CONTAINER_BYTES_USED); String objectCount = from.getFirstHeaderOrNull(CONTAINER_OBJECT_COUNT); Container c = Container.builder() .name(name) .bytesUsed(bytesUsed==null?0:Long.parseLong(bytesUsed)) .objectCount(objectCount==null?0:Long.parseLong(objectCount)) .anybodyRead(CONTAINER_ACL_ANYBODY_READ.equals(from.getFirstHeaderOrNull(CONTAINER_READ))) .metadata(EntriesWithoutMetaPrefix.INSTANCE.apply(from.getHeaders())).build(); return c; }

Target:
public Container apply(HttpResponse from) { String bytesUsed = from.getFirstHeaderOrNull(CONTAINER_BYTES_USED); String objectCount = from.getFirstHeaderOrNull(CONTAINER_OBJECT_COUNT); Container c = Container.builder() .name(name) .bytesUsed(bytesUsed != null ? Long.valueOf(bytesUsed) : null) .objectCount(objectCount != null ? Long.valueOf(objectCount) : null) .anybodyRead(CONTAINER_ACL_ANYBODY_READ.equals(from.getFirstHeaderOrNull(CONTAINER_READ))) .metadata(EntriesWithoutMetaPrefix.INSTANCE.apply(from.getHeaders())).build(); return c; }
Source:
public static int getSkyBlendColour(World world, BlockPos center) { if (center.getX() == skyX && center.getZ() == skyZ && skyInit) { return skyRGBMultiplier; } skyInit = true; GameSettings settings = Minecraft.getMinecraft().gameSettings; int[] ranges = ForgeModContainer.blendRanges; int distance = 0; if (settings.fancyGraphics && settings.renderDistanceChunks >= 0 && settings.renderDistanceChunks < ranges.length) { distance = ranges[settings.renderDistanceChunks]; } int r = 0; int g = 0; int b = 0; int divider = 0; for (int x = -distance; x <= distance; ++x) { for (int z = -distance; z <= distance; ++z) { BlockPos pos = center.add(x, 0, z); Biome biome = world.getBiome(pos); int colour = biome.getSkyColorByTemp(biome.getFloatTemperature(pos)); r += (colour & 0xFF0000) >> 16; g += (colour & 0x00FF00) >> 8; b += colour & 0x0000FF; divider++; } } int multiplier = (r / divider & 255) << 16 | (g / divider & 255) << 8 | b / divider & 255; skyX = center.getX(); skyZ = center.getY(); skyRGBMultiplier = multiplier; return skyRGBMultiplier; }

Target:
public static int getSkyBlendColour(World world, BlockPos center) { if (center.getX() == skyX && center.getZ() == skyZ && skyInit) { return skyRGBMultiplier; } skyInit = true; GameSettings settings = Minecraft.getMinecraft().gameSettings; int[] ranges = ForgeModContainer.blendRanges; int distance = 0; if (settings.fancyGraphics && settings.renderDistanceChunks >= 0 && settings.renderDistanceChunks < ranges.length) { distance = ranges[settings.renderDistanceChunks]; } int r = 0; int g = 0; int b = 0; int divider = 0; for (int x = -distance; x <= distance; ++x) { for (int z = -distance; z <= distance; ++z) { BlockPos pos = center.add(x, 0, z); Biome biome = world.getBiomeGenForCoords(pos); int colour = biome.getSkyColorByTemp(biome.getFloatTemperature(pos)); r += (colour & 0xFF0000) >> 16; g += (colour & 0x00FF00) >> 8; b += colour & 0x0000FF; divider++; } } int multiplier = (r / divider & 255) << 16 | (g / divider & 255) << 8 | b / divider & 255; skyX = center.getX(); skyZ = center.getY(); skyRGBMultiplier = multiplier; return skyRGBMultiplier; }
Source:
public boolean completed() { return produceFuture.completed(); }

Target:
boolean completed() { return produceFuture.completed(); }
Source:
private TranslationResult buildTranslationResult(List<TermConceptMapGroupElementTarget> theTargets) { TranslationResult retVal = new TranslationResult(); if (theTargets.isEmpty()) { retVal.setResult(new BooleanType(false)); retVal.setMessage(new StringType("No matches found!")); } else { retVal.setResult(new BooleanType(true)); retVal.setMessage(new StringType("Matches found!")); TranslationMatch translationMatch; Set<TermConceptMapGroupElementTarget> targetsToReturn = new HashSet<>(); for (TermConceptMapGroupElementTarget target : theTargets) { if (targetsToReturn.add(target)) { translationMatch = new TranslationMatch(); translationMatch.setEquivalence(new CodeType(target.getEquivalence().toCode())); translationMatch.setConcept( new Coding() .setCode(target.getCode()) .setSystem(target.getSystem()) .setVersion(target.getSystemVersion()) .setDisplay(target.getDisplay()) .setUserSelected(false) ); translationMatch.setSource(new UriType(target.getConceptMapUrl())); retVal.addMatch(translationMatch); } } } return retVal; }

Target:
private TranslationResult buildTranslationResult(List<TermConceptMapGroupElementTarget> theTargets) { TranslationResult retVal = new TranslationResult(); String msg; if (theTargets.isEmpty()) { retVal.setResult(new BooleanType(false)); msg = getContext().getLocalizer().getMessage( FhirResourceDaoConceptMapDstu3.class, "noMatchesFound"); retVal.setMessage(new StringType(msg)); } else { retVal.setResult(new BooleanType(true)); msg = getContext().getLocalizer().getMessage( FhirResourceDaoConceptMapDstu3.class, "matchesFound"); retVal.setMessage(new StringType(msg)); TranslationMatch translationMatch; Set<TermConceptMapGroupElementTarget> targetsToReturn = new HashSet<>(); for (TermConceptMapGroupElementTarget target : theTargets) { if (targetsToReturn.add(target)) { translationMatch = new TranslationMatch(); translationMatch.setEquivalence(new CodeType(target.getEquivalence().toCode())); translationMatch.setConcept( new Coding() .setCode(target.getCode()) .setSystem(target.getSystem()) .setVersion(target.getSystemVersion()) .setDisplay(target.getDisplay()) ); translationMatch.setSource(new UriType(target.getConceptMapUrl())); retVal.addMatch(translationMatch); } } } return retVal; }
Source:
private void runJob(long transactionId, boolean tableSupportsDeltaDelete, OptionalInt bucketNumber, long tableId, Map<UUID, Optional<UUID>> shardUuidsMap) throws IOException { log.info("Start compacting shards %s for table: %s", shardUuidsMap, tableId); TableMetadata metadata = getTableMetadata(tableId); List<ShardInfo> newShards = performCompaction(transactionId, tableSupportsDeltaDelete, bucketNumber, shardUuidsMap, metadata); log.info("Compacted shards %s into %s for table: %s", shardUuidsMap, newShards.stream().map(ShardInfo::getShardUuid).collect(toList()), tableId); if (tableSupportsDeltaDelete) { shardManager.replaceShardUuids(transactionId, tableId, metadata.getColumns(), shardUuidsMap, newShards, OptionalLong.empty(), tableSupportsDeltaDelete); } else { shardManager.replaceShardUuids(transactionId, tableId, metadata.getColumns(), shardUuidsMap.keySet(), newShards, OptionalLong.empty()); } }

Target:
private void runJob(long transactionId, boolean tableSupportsDeltaDelete, OptionalInt bucketNumber, long tableId, Map<UUID, Optional<UUID>> shardUuidsMap) throws IOException { TableMetadata metadata = getTableMetadata(tableId); List<ShardInfo> newShards = performCompaction(transactionId, tableSupportsDeltaDelete, bucketNumber, shardUuidsMap, metadata); log.info("Compacted shards %s into %s for table: %s", shardUuidsMap, newShards.stream().map(ShardInfo::getShardUuid).collect(toList()), tableId); if (tableSupportsDeltaDelete) { shardManager.replaceShardUuids(transactionId, tableId, metadata.getColumns(), shardUuidsMap, newShards, OptionalLong.empty(), true); } else { shardManager.replaceShardUuids(transactionId, tableId, metadata.getColumns(), shardUuidsMap.keySet(), newShards, OptionalLong.empty()); } }
Source:
private void showExportSuccessDialog(final String path, final Uri streamUri) { new AlertDialog.Builder(getContext()) .setNeutralButton(android.R.string.ok, (dialog, which) -> dialog.dismiss()) .setTitle(R.string.export_success_title) .setMessage(getContext().getString(R.string.export_success_sum, path)) .setPositiveButton(R.string.send_label, (dialog, which) -> { Intent sendIntent = new Intent(Intent.ACTION_SEND) .putExtra(Intent.EXTRA_SUBJECT, getString(R.string.opml_export_label)) .putExtra(Intent.EXTRA_STREAM, streamUri) .setType("text/plain") .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { List<ResolveInfo> resInfoList = getContext().getPackageManager().queryIntentActivities( sendIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resInfoList) { String packageName = resolveInfo.activityInfo.packageName; getContext().grantUriPermission( packageName, streamUri, Intent.FLAG_GRANT_READ_URI_PERMISSION); } } getContext().startActivity(Intent.createChooser(sendIntent, getString(R.string.send_label))); }) .create() .show(); }

Target:
private void showExportSuccessDialog(final String path, final Uri streamUri) { final AlertDialog.Builder alert = new AlertDialog.Builder(getContext()); alert.setNeutralButton(android.R.string.ok, (dialog, which) -> dialog.dismiss()); alert.setTitle(R.string.export_success_title); alert.setMessage(getString(R.string.export_success_sum, path)); alert.setPositiveButton(R.string.send_label, (dialog, which) -> { Intent sendIntent = new Intent(Intent.ACTION_SEND) .putExtra(Intent.EXTRA_SUBJECT, getString(R.string.opml_export_label)) .putExtra(Intent.EXTRA_STREAM, streamUri) .setType("text/plain") .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { List<ResolveInfo> resInfoList = getContext().getPackageManager() .queryIntentActivities(sendIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resInfoList) { String packageName = resolveInfo.activityInfo.packageName; getContext().grantUriPermission(packageName, streamUri, Intent.FLAG_GRANT_READ_URI_PERMISSION); } } startActivity(Intent.createChooser(sendIntent, getString(R.string.send_label))); }); alert.create().show(); }
Source:
static void checkLength(String stringToValidate, String jobParametersName) throws JobParametersInvalidException { if(stringToValidate.length()>=250){ throw new JobParametersInvalidException( String.format("%s in %s can't exceed 250 characters", stringToValidate, jobParametersName)); } }

Target:
static void checkLength(String stringToValidate, String jobParametersName) throws JobParametersInvalidException { if (stringToValidate.length() >= 250) { throw new JobParametersInvalidException( String.format("%s in %s can't exceed 250 characters", stringToValidate, jobParametersName)); } if (stringToValidate.trim().length() == 0) { throw new JobParametersInvalidException( String.format("%s in %s must be specified", stringToValidate, jobParametersName)); } }
Source:
private List<ChannelTypeDTO> convertToChannelTypeDTOs(List<ChannelType> channelTypes, Locale locale) { List<ChannelTypeDTO> channelTypeDTOs = new ArrayList<>(); for (ChannelType channelType : channelTypes) { channelTypeDTOs.add(convertToChannelTypeDTO(channelType, locale)); } return channelTypeDTOs; }

Target:
private List<ChannelTypeDTO> convertToChannelTypeDTOs(List<ChannelType> channelTypes, Locale locale) { List<ChannelTypeDTO> channelTypeDTOs = new ArrayList<>(channelTypes.size()); for (ChannelType channelType : channelTypes) { channelTypeDTOs.add(convertToChannelTypeDTO(channelType, locale)); } return channelTypeDTOs; }
Source:
public void setIsSender(boolean isSender) { final int color; if (isSender) { color = ContextCompat.getColor(itemView.getContext(), R.color.material_green_300); mLeftArrow.setVisibility(View.GONE); mRightArrow.setVisibility(View.VISIBLE); mMessageContainer.setGravity(Gravity.END); } else { color = ContextCompat.getColor(itemView.getContext(), R.color.material_gray_300); mLeftArrow.setVisibility(View.VISIBLE); mRightArrow.setVisibility(View.GONE); mMessageContainer.setGravity(Gravity.START); } ((GradientDrawable) mMessage.getBackground()).setColor(color); ((RotateDrawable) mLeftArrow.getBackground()).getDrawable() .setColorFilter(color, PorterDuff.Mode.SRC); ((RotateDrawable) mRightArrow.getBackground()).getDrawable() .setColorFilter(color, PorterDuff.Mode.SRC); }

Target:
public void setIsSender(boolean isSender) { final int color; if (isSender) { color = mGreen300; mLeftArrow.setVisibility(View.GONE); mRightArrow.setVisibility(View.VISIBLE); mMessageContainer.setGravity(Gravity.END); } else { color = mGray300; mLeftArrow.setVisibility(View.VISIBLE); mRightArrow.setVisibility(View.GONE); mMessageContainer.setGravity(Gravity.START); } ((GradientDrawable) mMessage.getBackground()).setColor(color); ((RotateDrawable) mLeftArrow.getBackground()).getDrawable() .setColorFilter(color, PorterDuff.Mode.SRC); ((RotateDrawable) mRightArrow.getBackground()).getDrawable() .setColorFilter(color, PorterDuff.Mode.SRC); }