auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Map<Cell, Value> get(TableReference tableRef, Map<Cell, Long> timestampByCell) { try (CloseableTrace trace = startLocalTrace("get({}, cells)", LoggingArgs.tableRefValue(tableRef), timestampByCell.size())) { return delegate().get(tableRef, timestampByCell); } }

Target:
public Map<Cell, Value> get(TableReference tableRef, Map<Cell, Long> timestampByCell) { try (CloseableTrace trace = startLocalTrace("get({}, cells)", LoggingArgs.safeTableOrPlaceholder(tableRef), timestampByCell.size())) { return delegate().get(tableRef, timestampByCell); } }
Source:
private List<CourseEditSectionRow> createSectionRows(int instructorIndex, List<String> sectionNames, List<String> feedbackNames) { firstBlankSectionRowIndex = sectionNames.size(); List<CourseEditSectionRow> rows = new ArrayList<CourseEditSectionRow>(); Map<Integer, String> specialSectionNames = new TreeMap<Integer, String>(); Map<Integer, String> nonSpecialSectionNames = new TreeMap<Integer, String>(); int sectionIndex = -1; for (String sectionName : sectionNames) { sectionIndex++; if (isSectionSpecial(sectionName)) { specialSectionNames.put(sectionIndex, sectionName); } else { nonSpecialSectionNames.put(sectionIndex, sectionName); } } int panelIndex = -1; for (Map.Entry<Integer, String> sectionNameEntry : specialSectionNames.entrySet()) { panelIndex++; sectionIndex = sectionNameEntry.getKey(); String sectionName = sectionNameEntry.getValue(); CourseEditSectionRow sectionRow = new CourseEditSectionRow(sectionName, sectionNames, sectionIndex, panelIndex, instructor, instructorIndex, feedbackNames); rows.add(sectionRow); } for (Map.Entry<Integer, String> sectionNameEntry : nonSpecialSectionNames.entrySet()) { panelIndex++; if (firstBlankSectionRowIndex == sectionNames.size()) { firstBlankSectionRowIndex = panelIndex; } sectionIndex = sectionNameEntry.getKey(); String sectionName = sectionNameEntry.getValue(); CourseEditSectionRow sectionRow = new CourseEditSectionRow(sectionName, sectionNames, sectionIndex, panelIndex, instructor, instructorIndex, feedbackNames); rows.add(sectionRow); } return rows; }

Target:
private List<CourseEditSectionRow> createSectionRows( int instructorIndex, List<String> sectionNames, List<String> feedbackNames) { firstBlankSectionRowIndex = sectionNames.size(); Map<Integer, String> specialSectionNames = new TreeMap<Integer, String>(); Map<Integer, String> nonSpecialSectionNames = new TreeMap<Integer, String>(); distinguishSpecialAndNonSpecialSections(sectionNames, specialSectionNames, nonSpecialSectionNames); List<CourseEditSectionRow> rows = createSpecialAndNonSpecialSectionRowsInOrder(instructorIndex, sectionNames, feedbackNames, specialSectionNames, nonSpecialSectionNames); return rows; }
Source:
public static <K,V> ConflictManager<K,V> get(AdvancedCache<K, V> cache) { AuthorizationManager authzManager = cache.getAuthorizationManager(); if (authzManager != null) { authzManager.checkPermission(AuthorizationPermission.ALL_READ); authzManager.checkPermission(AuthorizationPermission.ALL_WRITE); } return Objects.requireNonNull(cache, "Cache cannot be null") .getAdvancedCache() .getComponentRegistry() .getComponent(ConflictManager.class); }

Target:
public static <K,V> ConflictManager<K,V> get(AdvancedCache<K, V> cache) { AuthorizationManager authzManager = cache.getAuthorizationManager(); if (authzManager != null) { authzManager.checkPermission(AuthorizationPermission.ALL_READ); authzManager.checkPermission(AuthorizationPermission.ALL_WRITE); } return cache .getComponentRegistry() .getComponent(InternalConflictManager.class); }
Source:
public void testRequiredSerializedNameNonNull() { SerializedNameModel expected = new SerializedNameModel(); expected.bar = "hello world"; SerializedNameModel result = unmarshal(SerializedNameModel.class, "{ \"foo\": \"hello world\" }"); assertThat(result, is(expected)); }

Target:
public void testRequiredSerializedNameNonNull() { SerializedNameModel expected = new SerializedNameModel(); expected.bar = "hello world"; SerializedNameModel result = unmarshal(gson, SerializedNameModel.class, marshal(gson, expected)); assertThat(result, is(expected)); }
Source:
public synchronized RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException { String user = uri.getUser(); final String pass = uri.getPass(); String host = uri.getHost(); int port = uri.getPort(); try { if (config == null) config = OpenSshConfig.get(fs); final OpenSshConfig.Host hc = config.lookup(host); host = hc.getHostName(); if (port <= 0) port = hc.getPort(); if (user == null) user = hc.getUser(); final Session session = createSession(hc, user, host, port, fs); if (pass != null) session.setPassword(pass); final String strictHostKeyCheckingPolicy = hc .getStrictHostKeyChecking(); if (strictHostKeyCheckingPolicy != null) session.setConfig("StrictHostKeyChecking", strictHostKeyCheckingPolicy); final String pauth = hc.getPreferredAuthentications(); if (pauth != null) session.setConfig("PreferredAuthentications", pauth); if (credentialsProvider != null && (!hc.isBatchMode() || !credentialsProvider .isInteractive())) { session.setUserInfo(new CredentialsProviderUserInfo(session, credentialsProvider)); } configure(hc, session); if (!session.isConnected()) session.connect(tms); return new JschSession(session, uri); } catch (final JSchException je) { final Throwable c = je.getCause(); if (c instanceof UnknownHostException) throw new TransportException(uri, JGitText.get().unknownHost); if (c instanceof ConnectException) throw new TransportException(uri, c.getMessage()); throw new TransportException(uri, je.getMessage(), je); } }

Target:
public synchronized RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException { String user = uri.getUser(); final String pass = uri.getPass(); String host = uri.getHost(); int port = uri.getPort(); try { if (config == null) config = OpenSshConfig.get(fs); final OpenSshConfig.Host hc = config.lookup(host); host = hc.getHostName(); if (port <= 0) port = hc.getPort(); if (user == null) user = hc.getUser(); final Session session = createSession(hc, user, host, port, fs); if (pass != null) session.setPassword(pass); final String strictHostKeyCheckingPolicy = hc .getStrictHostKeyChecking(); if (strictHostKeyCheckingPolicy != null) session.setConfig("StrictHostKeyChecking", strictHostKeyCheckingPolicy); final String pauth = hc.getPreferredAuthentications(); if (pauth != null) session.setConfig("PreferredAuthentications", pauth); if (credentialsProvider != null && (!hc.isBatchMode() || !credentialsProvider.isInteractive())) { session.setUserInfo(new CredentialsProviderUserInfo(session, credentialsProvider)); } configure(hc, session); if (!session.isConnected()) session.connect(tms); return new JschSession(session, uri); } catch (JSchException je) { final Throwable c = je.getCause(); if (c instanceof UnknownHostException) throw new TransportException(uri, JGitText.get().unknownHost); if (c instanceof ConnectException) throw new TransportException(uri, c.getMessage()); throw new TransportException(uri, je.getMessage(), je); } }
Source:
public void returnProgramStateWhenObjectIsDefined() throws Exception { state = state.pushToStack(new SymbolicValueWithConstraint(Constraint.ANY_VALUE)); assertThat(dotMemberPoint.execute(state).isPresent()).isTrue(); state = state.pushToStack(new SymbolicValueWithConstraint(Constraint.ANY_VALUE)).pushToStack(new SymbolicValueWithConstraint(Constraint.ZERO)); assertThat(bracketMemberPoint.execute(state).isPresent()).isTrue(); }

Target:
public void returnProgramStateWhenObjectIsDefined() throws Exception { state = state.pushToStack(ANY_VALUE); Optional<ProgramState> stateAfterDot = dotMemberPoint.execute(state); assertThat(dotMemberPoint.execute(state).isPresent()).isTrue(); stateAfterDot.ifPresent(s -> assertThat(s.getConstraint(s.peekStack()).isStricterOrEqualTo(Constraint.NOT_NULLY)).isTrue()); state = state.pushToStack(ANY_VALUE).pushToStack(ZERO); Optional<ProgramState> stateAfterBracket = bracketMemberPoint.execute(state); assertThat(stateAfterBracket.isPresent()).isTrue(); stateAfterBracket.ifPresent(s -> assertThat(s.getConstraint(s.peekStack()).isStricterOrEqualTo(Constraint.NOT_NULLY)).isTrue()); }
Source:
public void testAddExistingContainer() throws Exception { Run run = (Run) getSession().get(Run.class, 5002L); assertTrue(run.getSequencerPartitionContainers().isEmpty()); RunPage page = RunPage.getForEdit(getDriver(), getBaseUrl(), 5002L); RunPage page2 = page.addContainer("EXISTING", "Illumina", false); assertNotNull(page2); Run addedRun = (Run) getSession().get(Run.class, 5002L); assertEquals(1, addedRun.getSequencerPartitionContainers().size()); assertEquals("EXISTING", addedRun.getSequencerPartitionContainers().get(0).getIdentificationBarcode()); }

Target:
public void testAddExistingContainer() throws Exception { Run run = (Run) getSession().get(Run.class, 5002L); assertTrue(run.getSequencerPartitionContainers().isEmpty()); RunPage page = RunPage.getForEdit(getDriver(), getBaseUrl(), 5002L); RunPage page2 = page.addContainer("EXISTING", "Illumina", false); assertTrue(page2.getTable("list_container").doesColumnContain(Columns.SERIAL_NUMBER, "EXISTING")); Run addedRun = (Run) getSession().get(Run.class, 5002L); assertEquals(1, addedRun.getSequencerPartitionContainers().size()); assertEquals("EXISTING", addedRun.getSequencerPartitionContainers().get(0).getIdentificationBarcode()); }
Source:
public Object wrap(final ProceedingJoinPoint point) throws Throwable { final Method method = MethodSignature.class .cast(point.getSignature()) .getMethod(); final RetryOnFailure rof = method.getAnnotation(RetryOnFailure.class); int attempt = 0; final long begin = System.nanoTime(); while (true) { final long start = System.nanoTime(); try { return point.proceed(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw ex; } catch (Throwable ex) { ++attempt; if (rof.verbose()) { Logger.warn( JoinPointUtils.targetize(point), "#%s(): attempt #%d of %d failed in %[nano]s (%[nano]s waiting already) with %[exception]s", method.getName(), attempt, rof.attempts(), System.nanoTime() - start, System.nanoTime() - begin, ex ); } else { Logger.warn( JoinPointUtils.targetize(point), "#%s(): attempt #%d/%d failed with %[type]s in %[nano]s (%[nano]s in total): %s", method.getName(), attempt, rof.attempts(), ex, System.nanoTime() - start, System.nanoTime() - begin, Repeater.message(ex) ); } if (attempt >= rof.attempts()) { throw ex; } if (rof.delay() > 0) { delay(rof, attempt); } } } }

Target:
public Object wrap(final ProceedingJoinPoint point) throws Throwable { final Method method = MethodSignature.class .cast(point.getSignature()) .getMethod(); final RetryOnFailure rof = method.getAnnotation(RetryOnFailure.class); int attempt = 0; final long begin = System.nanoTime(); while (true) { final long start = System.nanoTime(); try { return point.proceed(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw ex; } catch (Throwable ex) { ++attempt; if (rof.verbose()) { Logger.warn( JoinPointUtils.targetize(point), "#%s(): attempt #%d of %d failed in %[nano]s (%[nano]s waiting already) with %[exception]s", method.getName(), attempt, rof.attempts(), System.nanoTime() - start, System.nanoTime() - begin, ex ); } else { Logger.warn( JoinPointUtils.targetize(point), "#%s(): attempt #%d/%d failed with %[type]s in %[nano]s (%[nano]s in total): %s", method.getName(), attempt, rof.attempts(), ex, System.nanoTime() - start, System.nanoTime() - begin, Repeater.message(ex) ); } if (attempt >= rof.attempts()) { throw ex; } if (rof.delay() > 0) { this.delay(rof, attempt); } } } }
Source:
private void convertOrg(File file, CisConversionResult result) throws Exception { try (FileInputStream inputStream = new FileInputStream(file)) { Workbook workbook = new Workbook(inputStream); LOGGER.debug("Aangetroffen locale: " + workbook.getSettings().getLocale() + " en region: " + workbook.getSettings().getRegion()); workbook.getSettings().setLocale(Locale.GERMAN); workbook.getSettings().setRegion(CountryCode.GERMANY); LOGGER.debug("Overschreven met locale: " + workbook.getSettings().getLocale() + " en region: " + workbook.getSettings().getRegion()); Style style = workbook.getDefaultStyle(); LOGGER.debug("Default font: " + style.getFont()); workbook.save(result.getPdfResultFile().getAbsolutePath(), SaveFormat.PDF); result.setNumberOfPages(getNumberOfPages(result.getPdfResultFile())); } }

Target:
private void convertOrg(File file, CisConversionResult result) throws Exception { try (FileInputStream inputStream = new FileInputStream(file)) { Workbook workbook = new Workbook(inputStream); Style style = workbook.getDefaultStyle(); LOGGER.debug("Default font: " + style.getFont()); workbook.save(result.getPdfResultFile().getAbsolutePath(), SaveFormat.PDF); result.setNumberOfPages(getNumberOfPages(result.getPdfResultFile())); } }
Source:
public PagedList<models.ebean.Alert> createAlertQuery(final AlertQuery query) { ExpressionList<models.ebean.Alert> ebeanExpressionList = Ebean.find(models.ebean.Alert.class).where(); if (query.getCluster().isPresent()) { ebeanExpressionList = ebeanExpressionList.eq("cluster", query.getCluster().get()); } if (query.getContext().isPresent()) { ebeanExpressionList = ebeanExpressionList.eq("context", query.getContext().get().toString()); } if (query.getService().isPresent()) { ebeanExpressionList = ebeanExpressionList.eq("service", query.getService().get()); } final Query<models.ebean.Alert> ebeanQuery = ebeanExpressionList.query(); int pageOffset = 0; if (query.getOffset().isPresent()) { pageOffset = query.getOffset().get() / query.getLimit(); } return ebeanQuery.findPagedList(pageOffset, query.getLimit()); }

Target:
public PagedList<models.ebean.Alert> createAlertQuery(final AlertQuery query) { ExpressionList<models.ebean.Alert> ebeanExpressionList = Ebean.find(models.ebean.Alert.class).where(); if (query.getCluster().isPresent()) { ebeanExpressionList = ebeanExpressionList.eq("cluster", query.getCluster().get()); } if (query.getContext().isPresent()) { ebeanExpressionList = ebeanExpressionList.eq("context", query.getContext().get().toString()); } if (query.getService().isPresent()) { ebeanExpressionList = ebeanExpressionList.eq("service", query.getService().get()); } if (query.getContains().isPresent()) { final Junction<models.ebean.Alert> junction = ebeanExpressionList.disjunction(); ebeanExpressionList = junction.contains("name", query.getContains().get()); if (!query.getCluster().isPresent()) { ebeanExpressionList = junction.contains("cluster", query.getContains().get()); } if (!query.getService().isPresent()) { ebeanExpressionList = junction.contains("service", query.getContains().get()); } ebeanExpressionList = junction.contains("metric", query.getContains().get()); ebeanExpressionList = junction.contains("statistic", query.getContains().get()); ebeanExpressionList = junction.contains("operator", query.getContains().get()); ebeanExpressionList = ebeanExpressionList.endJunction(); } final Query<models.ebean.Alert> ebeanQuery = ebeanExpressionList.query(); int pageOffset = 0; if (query.getOffset().isPresent()) { pageOffset = query.getOffset().get() / query.getLimit(); } return ebeanQuery.findPagedList(pageOffset, query.getLimit()); }
Source:
public void add(E newInterval) { super.add(newInterval); fListeners.stream().forEach(l -> l.elementAdded(this, newInterval)); }

Target:
public void add(E newInterval) { super.add(newInterval); }
Source:
public PypiWheelArtifactCoordinates(String distribution, String version, String build, String languageImplementationVersion, String abi, String platform) { if (distribution == "" || version == "" || languageImplementationVersion == "" || abi == "" || platform == "") { throw new IllegalArgumentException("The distribution, version, language_implementation_version_tag, abi_tag, and platform_tag are mandatory fields."); } if (build != "" && !Character.isDigit(build.charAt(0))) { throw new IllegalArgumentException("Illegal build tag!"); } setId(distribution); setVersion(version); setBuild(build); setLanguageImplementationVersion(languageImplementationVersion); setAbi(abi); setPlatform(platform); }

Target:
public PypiWheelArtifactCoordinates(String distribution, String version, String build, String languageImplementationVersion, String abi, String platform) { if (StringUtils.isBlank(distribution) || StringUtils.isBlank(version) || StringUtils.isBlank(languageImplementationVersion) || StringUtils.isBlank(abi) || StringUtils.isBlank(platform)) { throw new IllegalArgumentException("The distribution, version, languageImplementationVersion, abi, and platform fields are mandatory."); } if (!StringUtils.isBlank(build) && !Character.isDigit(build.charAt(0))) { throw new IllegalArgumentException("Illegal build tag!"); } setId(distribution); setVersion(version); setBuild(build); setLanguageImplementationVersion(languageImplementationVersion); setAbi(abi); setPlatform(platform); }
Source:
private Sequence<T> deserializeResults( final byte[] cachedResult, CacheStrategy strategy, String resultSetId ) { if (cachedResult == null) { return null; } final Function<Object, T> pullFromCacheFunction = strategy.pullFromResultLevelCache(); final TypeReference<Object> cacheObjectClazz = strategy.getCacheObjectClazz(); byte[] prunedCacheData = Arrays.copyOfRange( cachedResult, Integer.BYTES + resultSetId.length(), cachedResult.length ); Sequence<T> cachedSequence = Sequences.simple(() -> { try { if (cachedResult.length == 0) { return Iterators.emptyIterator(); } return objectMapper.readValues( objectMapper.getFactory().createParser(prunedCacheData), cacheObjectClazz ); } catch (IOException e) { throw new RuntimeException(e); } }); return Sequences.map(cachedSequence, pullFromCacheFunction); }

Target:
private Sequence<T> deserializeResults( final byte[] cachedResult, CacheStrategy strategy, String resultSetId ) { if (cachedResult == null) { log.error("Cached result set is null"); } final Function<Object, T> pullFromCacheFunction = strategy.pullFromCache(true); final TypeReference<Object> cacheObjectClazz = strategy.getCacheObjectClazz(); Sequence<T> cachedSequence = Sequences.simple(() -> { try { int resultOffset = Integer.BYTES + resultSetId.length(); return objectMapper.readValues( objectMapper.getFactory().createParser( cachedResult, resultOffset, cachedResult.length - resultOffset ), cacheObjectClazz ); } catch (IOException e) { throw new RE(e, "Failed to retrieve results from cache for query ID [%s]", query.getId()); } }); return Sequences.map(cachedSequence, pullFromCacheFunction); }
Source:
public void networkNameTakenBySameNetwork() throws Exception { Network otherNetwork = new Network(); otherNetwork.setName(DEFAULT_NETWORK_NAME); otherNetwork.setId(new Guid(DEFAULT_GUID)); networkNameAvailableTest(ValidationResult.VALID, Collections.singletonList(otherNetwork)); }

Target:
public void networkNameTakenBySameNetwork() throws Exception { networkNameAvailableTest(ValidationResult.VALID, getSingletonNamedNetworkList(DEFAULT_NETWORK_NAME, DEFAULT_GUID)); }
Source:
public static NameMetadataDescription create(List<NameComponentDescription> components, boolean hasFirstComponentHash) { if (hasFirstComponentHash) { return NameMetadataDescription.create(components, 1); } else { return NameMetadataDescription.create(components, 0); } }

Target:
public static NameMetadataDescription create(List<NameComponentDescription> components, boolean hasFirstComponentHash) { return NameMetadataDescription.create(components, hasFirstComponentHash ? 1 : 0); }
Source:
public void headersDoIncludeUserAgent() throws Exception { URI uri = new URI("<LINK_0>"); EmbeddedChannel ch = new EmbeddedChannel(new HttpDownloadHandler(null)); ByteArrayOutputStream out = Mockito.spy(new ByteArrayOutputStream()); DownloadCommand cmd = new DownloadCommand(uri, true, "abcdef", new ByteArrayOutputStream()); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(cmd, writePromise); HttpRequest request = ch.readOutbound(); assertThat(request.headers().get(HttpHeaderNames.USER_AGENT)).isEqualTo("Bazel/development version"); }

Target:
public void headersDoIncludeUserAgent() throws Exception { URI uri = new URI("<LINK_0>"); EmbeddedChannel ch = new EmbeddedChannel(new HttpDownloadHandler( null)); DownloadCommand cmd = new DownloadCommand(uri, true, "abcdef", new ByteArrayOutputStream()); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(cmd, writePromise); HttpRequest request = ch.readOutbound(); assertThat(request.headers().get(HttpHeaderNames.USER_AGENT)).isEqualTo("bazel/HEAD"); }
Source:
public void onFire(int seconds, CallbackInfo ci, int i) { if (((IMixinWorld) world).isFake() || !ShouldFire.IGNITE_ENTITY_EVENT) { return; } if (!this.isBurning()) { try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { if (this.originalLava != null) { frame.addContext(EventContextKeys.DAMAGE_TYPE, DamageTypes.MAGMA); frame.pushCause(this.originalLava); } if (this.originalInFire != null) { frame.addContext(EventContextKeys.DAMAGE_TYPE, DamageTypes.FIRE); frame.pushCause(this.originalInFire); } if (this.originalLightning != null) { frame.addContext(EventContextKeys.DAMAGE_TYPE, DamageTypes.FIRE); frame.pushCause(this.originalLightning); } frame.pushCause(this.getLocation().getExtent()); IgniteEntityEvent event = SpongeEventFactory. createIgniteEntityEvent(frame.getCurrentCause(), i, i, this); if (SpongeImpl.postEvent(event)) { ci.cancel(); } } } }

Target:
private void onFire(int seconds, CallbackInfo ci, int i) { if (((IMixinWorld) world).isFake() || !ShouldFire.IGNITE_ENTITY_EVENT) { return; } if (this.fire < 1) { try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this.getLocation().getExtent()); IgniteEntityEvent event = SpongeEventFactory. createIgniteEntityEvent(frame.getCurrentCause(), i, i, this); if (SpongeImpl.postEvent(event)) { ci.cancel(); } } } }
Source:
public OffsetDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException { return (OffsetDateTime) rs.getObject(columnName); }

Target:
public OffsetDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException { return rs.getObject(columnName, OffsetDateTime.class); }
Source:
public ByteBuffer getBlob(ByteRange range) throws RouterException { try { if (range == null) { return getBlob(); } ByteRange resolvedRange = range.toResolvedByteRange(blob.array().length); return ByteBuffer.wrap(blob.array(), (int) resolvedRange.getStartOffset(), (int) resolvedRange.getRangeSize()); } catch (IllegalArgumentException e) { throw new RouterException("Invalid range for blob", e, RouterErrorCode.RangeNotSatisfiable); } }

Target:
public ByteBuffer getBlob(ByteRange range) throws RouterException { ByteBuffer buf; if (range == null) { buf = getBlob(); } else { ByteRange resolvedRange; try { resolvedRange = range.toResolvedByteRange(blob.array().length); } catch (IllegalArgumentException e) { throw new RouterException("Invalid range for blob", e, RouterErrorCode.RangeNotSatisfiable); } buf = ByteBuffer.wrap(blob.array(), (int) resolvedRange.getStartOffset(), (int) resolvedRange.getRangeSize()); } return buf; }
Source:
public boolean isVariadic() { for(Parameter p : getParameters()){ if(p.isVarArgs()) return true; } return false; }

Target:
public boolean isVariadic() { return getVarArgIndex() > -1; }
Source:
public StorageManagementClient buildClient() { if (host == null) { this.host = "<LINK_0>"; } if (apiVersion == null) { this.apiVersion = "2019-06-01"; } if (environment == null) { this.environment = AzureEnvironment.AZURE; } if (pipeline == null) { this.pipeline = new HttpPipelineBuilder() .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) .build(); } StorageManagementClient client = new StorageManagementClient(pipeline, environment, host, apiVersion, subscriptionId); return client; }

Target:
public StorageManagementClient buildClient() { if (endpoint == null) { this.endpoint = "<LINK_0>"; } if (environment == null) { this.environment = AzureEnvironment.AZURE; } if (pipeline == null) { this.pipeline = new HttpPipelineBuilder() .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()) .build(); } StorageManagementClient client = new StorageManagementClient(pipeline, environment, subscriptionId, endpoint); return client; }
Source:
private void stop() { if (brokers.length > 1) { try { deleteAllTopicsAndWait(60_000L); } catch (final InterruptedException e) { log.warn("Couldn't delete all topics before stopping brokers", e); } } for (final KafkaEmbedded broker : brokers) { broker.stopAsync(); } for (final KafkaEmbedded broker : brokers) { broker.awaitStoppedAndPurge(); } zookeeper.shutdown(); }

Target:
private void stop() { if (brokers.length > 1) { final Set<String> topics = getAllTopicsInCluster(); if (!topics.isEmpty()) { try (final Admin adminClient = brokers[0].createAdminClient()) { adminClient.deleteTopics(topics).all().get(); } catch (final InterruptedException e) { log.warn("Got interrupted while deleting topics in preparation for stopping embedded brokers", e); throw new RuntimeException(e); } catch (final ExecutionException | RuntimeException e) { log.warn("Couldn't delete all topics before stopping brokers", e); } } } for (final KafkaEmbedded broker : brokers) { broker.stopAsync(); } for (final KafkaEmbedded broker : brokers) { broker.awaitStoppedAndPurge(); } zookeeper.shutdown(); }
Source:
private void stage(final IStructuredSelection selection) { awaitStageJob(); stageJob = new Job(UIText.StagingView_Staging) { public IStatus run(IProgressMonitor monitor) { asyncLockUI(); try { Git git = new Git(currentRepository); AddCommand add = null; RmCommand rm = null; Iterator iterator = selection.iterator(); while (iterator.hasNext()) { StagingEntry entry = (StagingEntry) iterator.next(); switch (entry.getState()) { case ADDED: case CHANGED: case REMOVED: break; case CONFLICTING: case MODIFIED: case PARTIALLY_MODIFIED: case UNTRACKED: if (add == null) add = git.add(); add.addFilepattern(entry.getPath()); break; case MISSING: if (rm == null) rm = git.rm(); rm.addFilepattern(entry.getPath()); break; } } if (add != null) try { add.call(); } catch (NoFilepatternException e1) { } catch (Exception e2) { Activator.error(e2.getMessage(), e2); } if (rm != null) try { rm.call(); } catch (NoFilepatternException e) { } catch (Exception e2) { Activator.error(e2.getMessage(), e2); } } finally { asyncUnlockUI(); } return Status.OK_STATUS; } }; stageJob.setUser(true); stageJob.schedule(); }

Target:
private void stage(final IStructuredSelection selection) { awaitStageJob(); stageJob = new Job(UIText.StagingView_Staging) { public IStatus run(IProgressMonitor monitor) { asyncLockUI(); try { Git git = new Git(currentRepository); RmCommand rm = null; Iterator iterator = selection.iterator(); List<String> addPaths = new ArrayList<String>(); while (iterator.hasNext()) { Object element = iterator.next(); if (element instanceof StagingEntry) { StagingEntry entry = (StagingEntry) element; switch (entry.getState()) { case ADDED: case CHANGED: case REMOVED: break; case CONFLICTING: case MODIFIED: case PARTIALLY_MODIFIED: case UNTRACKED: addPaths.add(entry.getPath()); break; case MISSING: if (rm == null) rm = git.rm(); rm.addFilepattern(entry.getPath()); break; } } else { IResource resource = AdapterUtils.adapt(element, IResource.class); if (resource != null) { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); if (mapping != null && mapping.getRepository() == currentRepository) { String path = mapping.getRepoRelativePath(resource); if ("".equals(path)) addPaths.add("."); else addPaths.add(path); } } } } if (!addPaths.isEmpty()) try { AddCommand add = git.add(); for (String addPath : addPaths) add.addFilepattern(addPath); add.call(); } catch (NoFilepatternException e1) { } catch (Exception e2) { Activator.error(e2.getMessage(), e2); } if (rm != null) try { rm.call(); } catch (NoFilepatternException e) { } catch (Exception e2) { Activator.error(e2.getMessage(), e2); } } finally { asyncUnlockUI(); } return Status.OK_STATUS; } }; stageJob.setUser(true); stageJob.schedule(); }
Source:
public JavaType conditionalExpressionType(JavaType trueType, JavaType falseType) { if (trueType == falseType) { return trueType; } if (isNullAndPrimitive(trueType, falseType)) { return falseType.isPrimitive() ? falseType.primitiveWrapperType() : falseType; } if (isNullAndPrimitive(falseType, trueType)) { return trueType.isPrimitive() ? trueType.primitiveWrapperType() : trueType; } JavaType secondOperand = getPrimitive(trueType); JavaType thirdOperand = getPrimitive(falseType); if (secondOperand != null && thirdOperand != null && isNumericalConditionalExpression(secondOperand, thirdOperand)) { if ((secondOperand.tag < thirdOperand.tag || secondOperand.isTagged(JavaType.INT)) && !thirdOperand.isTagged(JavaType.INT)) { return thirdOperand; } else { return secondOperand; } } return (JavaType) leastUpperBound(Lists.<Type>newArrayList(trueType, falseType)); }

Target:
public JavaType conditionalExpressionType(JavaType trueType, JavaType falseType) { if (trueType == falseType) { return trueType; } if (trueType.isTagged(JavaType.BOT)) { return falseType.isPrimitive() ? falseType.primitiveWrapperType() : falseType; } if (falseType.isTagged(JavaType.BOT)) { return trueType.isPrimitive() ? trueType.primitiveWrapperType() : trueType; } JavaType secondOperand = getPrimitive(trueType); JavaType thirdOperand = getPrimitive(falseType); if (secondOperand != null && thirdOperand != null && isNumericalConditionalExpression(secondOperand, thirdOperand)) { if ((secondOperand.tag < thirdOperand.tag || secondOperand.isTagged(JavaType.INT)) && !thirdOperand.isTagged(JavaType.INT)) { return thirdOperand; } else { return secondOperand; } } return (JavaType) leastUpperBound(Lists.<Type>newArrayList(trueType, falseType)); }
Source:
public Object getValue(Object adaptable, String name, Type type, AnnotatedElement annotatedElement, DisposalCallbackRegistry disposalCallbackRegistry) { Integer maxLevel = annotatedElement.getAnnotation(ParentResourceValueMapValue.class).maxLevel(); if (adaptable instanceof Resource) { return getInheritedProperty((Resource)adaptable, name, type, maxLevel); } else if (adaptable instanceof SlingHttpServletRequest) { Resource adaptableResource = ((SlingHttpServletRequest) adaptable).getResource(); return getInheritedProperty(adaptableResource, name, type, maxLevel); } return null; }

Target:
public Object getValue(Object adaptable, String name, Type type, AnnotatedElement annotatedElement, DisposalCallbackRegistry disposalCallbackRegistry) { if (!annotatedElement.isAnnotationPresent(ParentResourceValueMapValue.class)) { return null; } Integer maxLevel = annotatedElement.getAnnotation(ParentResourceValueMapValue.class).maxLevel(); if (adaptable instanceof Resource) { return getInheritedProperty((Resource)adaptable, name, type, maxLevel); } else if (adaptable instanceof SlingHttpServletRequest) { Resource adaptableResource = ((SlingHttpServletRequest) adaptable).getResource(); return getInheritedProperty(adaptableResource, name, type, maxLevel); } return null; }
Source:
protected void executeCommand() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(getVmPool()); setPoolBeingDestroyed(); setPrestartedToZero(); getCompensationContext().stateChanged(); return null; } }); setCommandShouldBeLogged(false); if (stopVms()) { onStopVmsSucceeded(); } else { setSucceeded(true); } }

Target:
protected void executeCommand() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getCompensationContext().snapshotEntity(getVmPool()); setPoolBeingDestroyed(); setPrestartedToZero(); getCompensationContext().stateChanged(); return null; } }); setCommandShouldBeLogged(false); log(); stopVms(); if (allVmsDown) { getParameters().setTaskGroupSuccess(true); endAction(); } else { setSucceeded(true); } }
Source:
private Date convertDate(Date inDate, String tZone) { if (inDate == null) { return null; } DateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); format.setTimeZone(TimeZone.getTimeZone(schedule.getTimeZone())); String formattedStartDate = format.format(schedule.getStartDate()); return new Date(formattedStartDate); }

Target:
private Date convertDate(Date inDate, String tZone) { if (inDate == null) { return null; } DateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); String formattedStartDate = format.format(inDate); format.setTimeZone(TimeZone.getTimeZone(tZone)); try { return format.parse(formattedStartDate); } catch (Exception ex) { log.error("Error while converting the date to engine time zone"); return null; } }
Source:
public void provision(EnvironmentImpl environment, OpenShiftEnvironment osEnv, RuntimeIdentity runtimeIdentity) throws InfrastructureException { if (pvcEnable) { osEnv.getPersistentVolumeClaims() .put(runtimeIdentity.getWorkspaceId(), new PersistentVolumeClaimBuilder() .withNewMetadata() .withName(runtimeIdentity.getWorkspaceId()) .endMetadata() .withNewSpec() .withAccessModes(pvcAccessMode) .withNewResources() .withRequests(ImmutableMap.of("storage", new Quantity(pvcQuantity))) .endResources() .endSpec() .build()); final String devMachineName = Utils.getDevMachineName(environment); for (Pod pod : osEnv.getPods().values()) { for (Container container : pod.getSpec().getContainers()) { final String machineName = pod.getMetadata().getName() + "/" + container.getName(); if (devMachineName != null && devMachineName.equals(machineName)) { final String workspaceId = runtimeIdentity.getWorkspaceId(); final VolumeMount volumeMount = new VolumeMountBuilder().withMountPath(projectFolderPath) .withName(workspaceId) .build(); container.getVolumeMounts().add(volumeMount); final PersistentVolumeClaimVolumeSource pvcs = new PersistentVolumeClaimVolumeSourceBuilder() .withClaimName(workspaceId) .build(); final Volume volume = new VolumeBuilder().withPersistentVolumeClaim(pvcs) .withName(workspaceId) .build(); pod.getSpec().getVolumes().add(volume); return; } } } } }

Target:
public void provision(EnvironmentImpl environment, OpenShiftEnvironment osEnv, RuntimeIdentity runtimeIdentity) throws InfrastructureException { if (pvcEnable) { osEnv.getPersistentVolumeClaims() .put(pvcName, new PersistentVolumeClaimBuilder() .withNewMetadata() .withName(pvcName) .endMetadata() .withNewSpec() .withAccessModes(pvcAccessMode) .withNewResources() .withRequests(ImmutableMap.of("storage", new Quantity(pvcQuantity))) .endResources() .endSpec() .build()); final String devMachineName = Utils.getDevMachineName(environment); for (Pod pod : osEnv.getPods().values()) { for (Container container : pod.getSpec().getContainers()) { final String machineName = pod.getMetadata().getName() + "/" + container.getName(); if (devMachineName != null && devMachineName.equals(machineName)) { final VolumeMount volumeMount = new VolumeMountBuilder() .withMountPath(projectFolderPath) .withName(pvcName) .build(); container.getVolumeMounts().add(volumeMount); final PersistentVolumeClaimVolumeSource pvcs = new PersistentVolumeClaimVolumeSourceBuilder() .withClaimName(pvcName) .build(); final Volume volume = new VolumeBuilder().withPersistentVolumeClaim(pvcs) .withName(pvcName) .build(); pod.getSpec().getVolumes().add(volume); return; } } } } }
Source:
public String getPrimaryVideoTranscoder() { for (SupportSpec supportSpec : supportSpecs) { if (supportSpec.match(MPEGPS, MPEG2, AC3)) { return MPEGPS; } if (supportSpec.match(MPEGTS, MPEG2, AC3) || supportSpec.match(MPEGTS, MPEG2, AAC)) { return MPEGTS; } if (supportSpec.match(WMV, WMV, WMA)) { return WMV; } } return null; }

Target:
public String getPrimaryVideoTranscoder() { for (SupportSpec supportSpec : supportSpecs) { if (supportSpec.match(MPEGPS, MPEG2, AC3)) { return MPEGPS; } if (supportSpec.match(MPEGTS, MPEG2, AC3) || supportSpec.match(MPEGTS, H264, AAC)) { return MPEGTS; } if (supportSpec.match(WMV, WMV, WMA)) { return WMV; } } return null; }
Source:
private void validateTree() { try { String[] uniqueNames = preferences.node("/os").childrenNames(); for (String uniqueName : Arrays.asList(uniqueNames)) { Preferences node = getKeyNode(uniqueName, "derivedFrom", null); String id = getKeyNode(uniqueName, "id", null).get("value", "0"); if (node != null) { String derivedFrom = node.get("value", null); if (derivedFrom != null && !idToUnameLookup.containsValue(derivedFrom)) { idToUnameLookup.remove(Integer.valueOf(id)); preferences.node("/os/" + uniqueName).removeNode(); } } } } catch (BackingStoreException e) { throw new RuntimeException("Failed to validate Os Repository due to " + e); } }

Target:
private void validateTree() { try { String[] uniqueNames = preferences.node("/os").childrenNames(); for (String uniqueName : Arrays.asList(uniqueNames)) { Preferences node = getKeyNode(uniqueName, "derivedFrom", null); String id = getKeyNode(uniqueName, "id", null).get("value", "0"); if (node != null) { String derivedFrom = node.get("value", null); if (derivedFrom != null && !idToUnameLookup.containsValue(derivedFrom)) { idToUnameLookup.remove(Integer.valueOf(id)); preferences.node("/os/" + uniqueName).removeNode(); log.warn("Illegal parent for os: " + uniqueName); } } } } catch (BackingStoreException e) { log.warn("Failed to validate Os Repository due to " + e); throw new RuntimeException("Failed to validate Os Repository due to " + e); } }
Source:
public static String readContent(String url) throws IOException { HttpURLConnection conn = null; BufferedReader reader = null; try { conn = (HttpURLConnection)new URL(url).openConnection(); conn.connect(); int httpCode = conn.getResponseCode(); if (httpCode == 200) { reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); return reader.readLine(); } else if (httpCode == 404) { return null; } throw new RuntimeException("Un expected response code: " + httpCode); } finally { if (reader != null) { reader.close(); } if (conn != null) { conn.disconnect(); } } }

Target:
public static String readContent(String url) throws IOException { HttpURLConnection conn = null; try { conn = (HttpURLConnection)new URL(url).openConnection(); conn.connect(); int httpCode = conn.getResponseCode(); if (httpCode == 200) { try (InputStream input = conn.getInputStream(); InputStreamReader inputReader = new InputStreamReader(input); BufferedReader reader = new BufferedReader(inputReader)) { return reader.readLine(); } } else if (httpCode == 404) { return null; } throw new RuntimeException("Un expected response code: " + httpCode); } finally { if (conn != null) { conn.disconnect(); } } }
Source:
public void createObjects() { log = LoggerFactory.getLogger(OptimizerTOSCADecember2015AutoscalingPoliciesTest.class); log.info("Starting TEST optimizer for the TOSCA syntax of September 2015"); final String dir = System.getProperty("user.dir"); log.debug("Trying to open files: current executino dir = " + dir); try { appModel = filenameToString(TestConstants.APP_MODEL_FILENAME); } catch (IOException e) { log.error("File for APPmodel not found"); e.printStackTrace(); } try { suitableCloudOffer = filenameToString(TestConstants.CLOUD_OFFER_FILENAME_IN_JSON); } catch (IOException e) { log.error("File for Cloud Offers not found"); e.printStackTrace(); } }

Target:
public void createObjects() { log = LoggerFactory.getLogger(OptimizerTOSCADecember2015AutoscalingPoliciesTest.class); log.info("Starting TEST optimizer for the TOSCA syntax of September 2015"); openInputFiles(); }
Source:
public String getDescription() { return "1.13+ Flatting Spawn Egg Provider"; }

Target:
public String getDescription() { return "1.13+ Flattening Spawn Egg Provider"; }
Source:
public void enableProcessing(String queueId, boolean value) { WorkQueueDescriptor config = workQueueConfig.get(queueId); if (config == null) { throw new IllegalArgumentException("no such queue " + queueId); } if (!value) { if (!queuing.supportProcessingDisablement()) { log.error("Attempting to disable works processing on a WorkQueuing instance that does not support it." + "Works will still be processed."); } deactivateQueue(config); } else { activateQueue(config); } }

Target:
public void enableProcessing(String queueId, boolean value) { WorkQueueDescriptor config = workQueueConfig.get(queueId); if (config == null) { throw new IllegalArgumentException("no such queue " + queueId); } if (!value) { if (!queuing.supportsProcessingDisabling()) { log.error("Attempting to disable works processing on a WorkQueuing instance that does not support it." + "Works will still be processed." + "Disabling works processing to manage distribution finely can be done using Redis or Stream implementations."); } deactivateQueue(config); } else { activateQueue(config); } }
Source:
public void testZookeeperConnectionStartup() throws Exception { ClusterService service = ClusterServiceFactory.createClusterService( TestUtils.createGoldenConfiguration(testingServer.getConnectString())); service.startService(); synchronized((ZookeeperClusterService)service){ try{ (service).wait(); }catch(InterruptedException e){ e.printStackTrace(); } } Stat stat = client.checkExists().forPath("/jmxtrans/workers/worker_01"); assertThat(stat).isNotEqualTo(null); service.stopService(); }

Target:
public void testZookeeperConnectionStartup() throws Exception { ClusterService service = ClusterServiceFactory.createClusterService( ConfigurationFixtures.createGoldenConfiguration(testingServer.getConnectString())); service.startService(); synchronized(service){ try{ service.wait(); }catch(InterruptedException e){ e.printStackTrace(); } } Stat stat = client.checkExists().forPath("/jmxtrans/workers/worker_01"); assertThat(stat).isNotEqualTo(null); service.stopService(); }
Source:
@Override public void onPositiveClicked(@NonNull String instanceTag) { Fragment fragment = getMySiteFragment(); if (fragment != null) { getMySiteFragment().onPositiveClicked(instanceTag); } }

Target:
public void onPositiveClicked(@NonNull String instanceTag) { MySiteFragment fragment = getMySiteFragment(); if (fragment != null) { fragment.onPositiveClicked(instanceTag); } }
Source:
private boolean handleMultiDrag(final MotionEvent event) { if (event.getPointerCount() != 2) return false; if(initPointerDistance != -1){ float firstPointerMoveX = event.getX(0) - initFirstPointerX; float firstPointerMoveY = event.getY(0) - initFirstPointerY; float secPointerMoveX = event.getX(1) - initSecPointerX; float secPointerMoveY = event.getY(1) - initSecPointerY; int scaledTouchSlop = ViewConfiguration.get(PopupVideoPlayer.this).getScaledTouchSlop(); if(firstPointerMoveX > scaledTouchSlop ||firstPointerMoveY > scaledTouchSlop || secPointerMoveX > scaledTouchSlop || secPointerMoveY > scaledTouchSlop){ double newWidth = popupWidth; float currentXDiff = event.getX(0) - event.getX(1); float currentYDiff = event.getY(0) - event.getY(1); double currentPointerDistance = Math.sqrt(currentXDiff * currentXDiff + currentYDiff * currentYDiff); double scale = 1 + (currentPointerDistance - initPointerDistance)/ initPointerDistance; newWidth = (popupWidth * scale); if(currentPointerDistance > initPointerDistance){ popupLayoutParams.x -= (newWidth - popupWidth)/2; } else{ popupLayoutParams.x += (popupWidth - newWidth)/2; } initPointerDistance = currentPointerDistance; checkPopupPositionBounds(); updateScreenSize(); final int width = (int) Math.min(screenWidth, newWidth); updatePopupSize(width, -1); return true; } } return false; }

Target:
private boolean handleMultiDrag(final MotionEvent event) { if (initPointerDistance != -1 && event.getPointerCount() == 2) { double firstPointerMove = Math.hypot(event.getX(0) - initFirstPointerX, event.getY(0) - initFirstPointerY); double secPointerMove = Math.hypot(event.getX(1) - initSecPointerX, event.getY(1) - initSecPointerY); int minimumMove = ViewConfiguration.get(PopupVideoPlayer.this).getScaledTouchSlop(); if (Math.max(firstPointerMove, secPointerMove) > minimumMove) { double currentPointerDistance = Math.hypot(event.getX(0) - event.getX(1), event.getY(0) - event.getY(1)); double newWidth = (popupWidth * currentPointerDistance / initPointerDistance); initPointerDistance = currentPointerDistance; popupLayoutParams.x += (popupWidth - newWidth) / 2; checkPopupPositionBounds(); updateScreenSize(); updatePopupSize((int) Math.min(screenWidth, newWidth), -1); return true; } } return false; }
Source:
public StashNotifier( String stashServerBaseUrl, String stashUserName, String stashUserPassword, boolean ignoreUnverifiedSSLPeer) { this.stashServerBaseUrl = stashServerBaseUrl; this.stashUserName = stashUserName; this.stashUserPassword = stashUserPassword; this.ignoreUnverifiedSSLPeer = ignoreUnverifiedSSLPeer; jenkins = Jenkins.getInstance(); httpClientfactory = new ConcreteHttpClientFactory(); notifierService = new ConfigurableStashNotifierService( stashServerBaseUrl, new JsonBuildEntityFactory(), new BasicStashRequestConfigurator(stashUserName, stashUserPassword)); }

Target:
public StashNotifier( String stashServerBaseUrl, String stashUserName, String stashUserPassword, boolean ignoreUnverifiedSSLPeer) { this.stashServerBaseUrl = stashServerBaseUrl; this.stashUserName = stashUserName; this.stashUserPassword = stashUserPassword; this.ignoreUnverifiedSSLPeer = ignoreUnverifiedSSLPeer; httpClientfactory = new ConcreteHttpClientFactory(); notifierService = new ConfigurableStashNotifierService( stashServerBaseUrl, new JsonBuildEntityFactory(), new BasicStashRequestConfigurator(stashUserName, stashUserPassword)); }
Source:
@Override public void load(Request request, int networkPolicy, Callback callback) { try { ContentResolver contentResolver = context.getContentResolver(); int exifOrientation = getExifOrientation(contentResolver, request.uri); String mimeType = contentResolver.getType(request.uri); boolean isVideo = mimeType != null && mimeType.startsWith("video/"); if (request.hasSize()) { PicassoKind picassoKind = getPicassoKind(request.targetWidth, request.targetHeight); if (!isVideo && picassoKind == FULL) { Source source = Okio.source(getInputStream(request)); callback.onSuccess(new Result(null, source, DISK, exifOrientation)); } long id = parseId(request.uri); BitmapFactory.Options options = createBitmapOptions(request); options.inJustDecodeBounds = true; calculateInSampleSize(request.targetWidth, request.targetHeight, picassoKind.width, picassoKind.height, options, request); Bitmap bitmap; if (isVideo) { int kind = (picassoKind == FULL) ? Video.Thumbnails.MINI_KIND : picassoKind.androidKind; bitmap = Video.Thumbnails.getThumbnail(contentResolver, id, kind, options); } else { bitmap = Images.Thumbnails.getThumbnail(contentResolver, id, picassoKind.androidKind, options); } if (bitmap != null) { callback.onSuccess(new Result(bitmap, null, DISK, exifOrientation)); } } Source source = Okio.source(getInputStream(request)); callback.onSuccess(new Result(null, source, DISK, exifOrientation)); } catch (Exception e) { callback.onError(e); } }

Target:
@Override public void load(Request request, int networkPolicy, Callback callback) { boolean signaledCallback = false; try { ContentResolver contentResolver = context.getContentResolver(); int exifOrientation = getExifOrientation(contentResolver, request.uri); String mimeType = contentResolver.getType(request.uri); boolean isVideo = mimeType != null && mimeType.startsWith("video/"); if (request.hasSize()) { PicassoKind picassoKind = getPicassoKind(request.targetWidth, request.targetHeight); if (!isVideo && picassoKind == FULL) { Source source = Okio.source(getInputStream(request)); signaledCallback = true; callback.onSuccess(new Result(null, source, DISK, exifOrientation)); return; } long id = parseId(request.uri); BitmapFactory.Options options = createBitmapOptions(request); options.inJustDecodeBounds = true; calculateInSampleSize(request.targetWidth, request.targetHeight, picassoKind.width, picassoKind.height, options, request); Bitmap bitmap; if (isVideo) { int kind = (picassoKind == FULL) ? Video.Thumbnails.MINI_KIND : picassoKind.androidKind; bitmap = Video.Thumbnails.getThumbnail(contentResolver, id, kind, options); } else { bitmap = Images.Thumbnails.getThumbnail(contentResolver, id, picassoKind.androidKind, options); } if (bitmap != null) { signaledCallback = true; callback.onSuccess(new Result(bitmap, null, DISK, exifOrientation)); return; } } Source source = Okio.source(getInputStream(request)); signaledCallback = true; callback.onSuccess(new Result(null, source, DISK, exifOrientation)); } catch (Exception e) { if (!signaledCallback) { callback.onError(e); } } }