auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ITmfContext seekEvent(ITmfLocation location) { if (fFile == null) { return INVALID_CONTEXT; } final TmfContext context = new TmfContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); if (NULL_LOCATION.equals(location)) { return context; } try { if (location == null) { fFileInput.seek(0); long lineStartOffset = fFileInput.getFilePointer(); @Nullable String line = fFileInput.readLine(); Matcher matcher = IGenericFtraceConstants.FTRACE_PATTERN.matcher(line); while (!matcher.matches() && line != null) { lineStartOffset = fFileInput.getFilePointer(); line = fFileInput.readLine(); if (line == null) { break; } matcher = IGenericFtraceConstants.FTRACE_PATTERN.matcher(line); } fFileInput.seek(lineStartOffset); } else if (location.getLocationInfo() instanceof Long) { fFileInput.seek((Long) location.getLocationInfo()); } context.setLocation(new TmfLongLocation(fFileInput.getFilePointer())); context.setRank(0); return context; } catch (final FileNotFoundException e) { Activator.getInstance().logError("Error seeking event. File not found: " + getPath(), e); return context; } catch (final IOException e) { Activator.getInstance().logError("Error seeking event. File: " + getPath(), e); return context; } }

Target:
public ITmfContext seekEvent(ITmfLocation location) { if (fFile == null) { return INVALID_CONTEXT; } final TmfContext context = new TmfContext(NULL_LOCATION, ITmfContext.UNKNOWN_RANK); if (NULL_LOCATION.equals(location)) { return context; } try { if (location == null) { fFileInput.seek(0); long lineStartOffset = fFileInput.getFilePointer(); @Nullable String line = fFileInput.readLine(); Matcher matcher = IGenericFtraceConstants.FTRACE_PATTERN.matcher(line); while (line != null && !matcher.matches()) { lineStartOffset = fFileInput.getFilePointer(); line = fFileInput.readLine(); if (line == null) { break; } matcher = IGenericFtraceConstants.FTRACE_PATTERN.matcher(line); } fFileInput.seek(lineStartOffset); } else if (location.getLocationInfo() instanceof Long) { fFileInput.seek((Long) location.getLocationInfo()); } context.setLocation(new TmfLongLocation(fFileInput.getFilePointer())); context.setRank(0); return context; } catch (final FileNotFoundException e) { Activator.getInstance().logError("Error seeking event. File not found: " + getPath(), e); return context; } catch (final IOException e) { Activator.getInstance().logError("Error seeking event. File: " + getPath(), e); return context; } }
Source:
private void showAppSettingSnackbar() { Snackbar snackbar = FeedbackUtil.makeSnackbar(this, getString(R.string.offline_read_final_rationale), FeedbackUtil.LENGTH_DEFAULT); snackbar.setAction(getString(R.string.app_settings).toUpperCase(), (v) -> goToSettings()); snackbar.show(); }

Target:
private void showAppSettingSnackbar() { Snackbar snackbar = FeedbackUtil.makeSnackbar(this, getString(R.string.offline_read_final_rationale), FeedbackUtil.LENGTH_DEFAULT); snackbar.setAction(R.string.app_settings, (v) -> goToSystemAppSettings()); snackbar.show(); }
Source:
public void acceptRecord(final GcBiasCollectorArgs args) { final SAMRecord rec = args.getRec(); final String type; if (!rec.getReadUnmappedFlag()) { if(referenceIndex != rec.getReferenceIndex() || gc == null || refBases == null){ final ReferenceSequence ref = args.getRef(); refBases = ref.getBases(); StringUtil.toUpperCase(refBases); final int refLength = refBases.length; final int lastWindowStart = refLength - scanWindowSize; gc = GcBiasUtils.calculateAllGcs(refBases, lastWindowStart, scanWindowSize); referenceIndex=rec.getReferenceIndex(); } final String group; if (this.readGroup != null) { type = this.readGroup; group = "Read Group"; addRead(gcData.get(type), rec, group, gc, refBases); } else if (this.library != null) { type = this.library; group = "Library"; addRead(gcData.get(type), rec, group, gc, refBases); } else if (this.sample != null) { type = this.sample; group = "Sample"; addRead(gcData.get(type), rec, group, gc, refBases); } else { type = allReads; group = "All Reads"; addRead(gcData.get(type), rec, group, gc, refBases); } } else { for (final Map.Entry<String, GcObject> entry : gcData.entrySet()) { final GcObject gcCur = entry.getValue(); if (!rec.getReadPairedFlag() || rec.getFirstOfPairFlag()) ++gcCur.totalClusters; } } }

Target:
public void acceptRecord(final GcBiasCollectorArgs args) { final SAMRecord rec = args.getRec(); final String type; if (!rec.getReadUnmappedFlag()) { if(referenceIndex != rec.getReferenceIndex() || gc == null){ final ReferenceSequence ref = args.getRef(); refBases = ref.getBases(); StringUtil.toUpperCase(refBases); final int refLength = refBases.length; final int lastWindowStart = refLength - scanWindowSize; gc = GcBiasUtils.calculateAllGcs(refBases, lastWindowStart, scanWindowSize); referenceIndex=rec.getReferenceIndex(); } final String group; if (this.readGroup != null) { type = this.readGroup; group = "Read Group"; addRead(gcData.get(type), rec, group, gc, refBases); } else if (this.library != null) { type = this.library; group = "Library"; addRead(gcData.get(type), rec, group, gc, refBases); } else if (this.sample != null) { type = this.sample; group = "Sample"; addRead(gcData.get(type), rec, group, gc, refBases); } else { type = allReads; group = "All Reads"; addRead(gcData.get(type), rec, group, gc, refBases); } } else { for (final Map.Entry<String, GcObject> entry : gcData.entrySet()) { final GcObject gcCur = entry.getValue(); if (!rec.getReadPairedFlag() || rec.getFirstOfPairFlag()) ++gcCur.totalClusters; } } }
Source:
private Diagram doTransformation(final String fileName, final String raw) { final Metadata metadata = createMetadata(); final Graph<DefinitionSet, ?> graph = marshalling.unmarshall(metadata, raw); final Node<Definition<BPMNDiagram>, ?> diagramNode = GraphUtils.getFirstNode((Graph<?, Node>) graph, BPMNDiagramImpl.class); if (null == diagramNode) { throw new RuntimeException("No BPMN Diagram can be found."); } diagramNode.getContent().getDefinition().getDiagramSet().getName().setValue(fileName); diagramNode.getContent().getDefinition().getDiagramSet().getId().setValue(fileName); final String title = diagramNode.getContent().getDefinition().getDiagramSet().getName().getValue(); metadata.setTitle(title); final Diagram diagram = diagramFactory.build(title, metadata, graph); updateClientMetadata(diagram); return diagram; }

Target:
private Diagram doTransformation(final String fileName, final String raw) { final Metadata metadata = createMetadata(); final Graph<DefinitionSet, ?> graph = marshalling.unmarshall(metadata, raw); final Node<Definition<BPMNDiagram>, ?> diagramNode = GraphUtils.getFirstNode((Graph<?, Node>) graph, BPMNDiagramImpl.class); if (null == diagramNode) { throw new RuntimeException("No BPMN Diagram can be found."); } final BaseDiagramSet diagramSet = diagramNode.getContent().getDefinition().getDiagramSet(); if (diagramSet.getName().getValue().isEmpty()) { diagramSet.getName().setValue(fileName); } if (diagramSet.getId().getValue().isEmpty()) { diagramSet.getId().setValue(fileName); } final String title = diagramNode.getContent().getDefinition().getDiagramSet().getName().getValue(); metadata.setTitle(title); final Diagram diagram = diagramFactory.build(title, metadata, graph); updateClientMetadata(diagram); return diagram; }
Source:
private static Context buildWithApplicationContext(ApplicationContainerContext applicationContainerContext, ApplicationTaskContext applicationTaskContext) { return new ContextImpl(mock(JobContext.class), mock(ContainerContext.class), mock(TaskContext.class), applicationContainerContext, applicationTaskContext); ======= return new ContextImpl(null, null, null, applicationContainerContext, null); }

Target:
private static Context buildWithApplicationContext(ApplicationContainerContext applicationContainerContext, ApplicationTaskContext applicationTaskContext) { return new ContextImpl(mock(JobContext.class), mock(ContainerContext.class), mock(TaskContext.class), Optional.ofNullable(applicationContainerContext), Optional.ofNullable(applicationTaskContext)); }
Source:
public void run() { if (Misc.isNPCIncludingVillagers(player)) { return; } if (!player.isOnline()) { mcMMO.p.getLogger().info("Aborting profile loading recovery for " + player.getName() + " - player logged out"); return; } PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(player.getName(), player.getUniqueId(), true); if (profile.isLoaded()) { new ApplySuccessfulProfile(new McMMOPlayer(player, profile)).runTask(mcMMO.p); Bukkit.getScheduler().runTask(mcMMO.p, () -> { EventUtils.callPlayerProfileLoadEvent(player, profile); }); return; } if (attempt >= 3) { mcMMO.p.getLogger().severe(LocaleLoader.getString("Profile.Loading.FailureNotice", player.getName(), String.valueOf(attempt))); mcMMO.p.getServer().broadcast(LocaleLoader.getString("Profile.Loading.FailureNotice", player.getName()), Server.BROADCAST_CHANNEL_ADMINISTRATIVE); player.sendMessage(LocaleLoader.getString("Profile.Loading.FailurePlayer", String.valueOf(attempt)).split("\n")); } attempt++; new PlayerProfileLoadingTask(player, attempt).runTaskLaterAsynchronously(mcMMO.p, (100 + (attempt * 100))); }

Target:
public void run() { if (Misc.isNPCIncludingVillagers(player)) { return; } if (!player.isOnline()) { mcMMO.p.getLogger().info("Aborting profile loading recovery for " + player.getName() + " - player logged out"); return; } PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(player.getName(), player.getUniqueId(), true); if (profile.isLoaded()) { new ApplySuccessfulProfile(new McMMOPlayer(player, profile)).runTask(mcMMO.p); EventUtils.callPlayerProfileLoadEvent(player, profile); return; } if (attempt >= 3) { mcMMO.p.getLogger().severe(LocaleLoader.getString("Profile.Loading.FailureNotice", player.getName(), String.valueOf(attempt))); mcMMO.p.getServer().broadcast(LocaleLoader.getString("Profile.Loading.FailureNotice", player.getName()), Server.BROADCAST_CHANNEL_ADMINISTRATIVE); player.sendMessage(LocaleLoader.getString("Profile.Loading.FailurePlayer", String.valueOf(attempt)).split("\n")); } attempt++; new PlayerProfileLoadingTask(player, attempt).runTaskLaterAsynchronously(mcMMO.p, (100 + (attempt * 100))); }
Source:
public void trackValuePropModalView(@NonNull String courseId, @Nullable String assignmentId, @NonNull String screenName) { final SegmentEvent aEvent = new SegmentEvent(); aEvent.data.putValue(Keys.COURSE_ID, courseId); if (assignmentId != null) { aEvent.data.putValue(Keys.ASSIGNMENT_ID, assignmentId); } aEvent.data.putValue(Keys.SCREEN_NAME, screenName); trackSegmentEvent(Events.VALUE_PROP_MODAL_VIEW, aEvent.properties); }

Target:
public void trackValuePropModalView(@NonNull String courseId, @Nullable String assignmentId, @NonNull String screenName) { final SegmentEvent aEvent = new SegmentEvent(); aEvent.data.putValue(Keys.COURSE_ID, courseId); if (TextUtils.isEmpty(assignmentId)) { aEvent.data.putValue(Keys.ASSIGNMENT_ID, assignmentId); } aEvent.data.putValue(Keys.SCREEN_NAME, screenName); trackSegmentEvent(Events.VALUE_PROP_MODAL_VIEW, aEvent.properties); }
Source:
public static ImmutableList<Class<?>> findEntityClassesFromDirectory(String pckg) { Builder<Class<?>> builder = ImmutableList.<Class<?>>builder(); PackageNamesScanner scanner = new PackageNamesScanner(new String[] {pckg}, true); @SuppressWarnings("unchecked") final AnnotationAcceptingListener asl = new AnnotationAcceptingListener(Entity.class); while (scanner.hasNext()) { final String next = scanner.next(); if (asl.accept(next)) { final InputStream in = scanner.open(); try { asl.process(next, in); } catch (IOException e) { throw new RuntimeException("AnnotationAcceptingListener failed to process scanned resource: " + next); } finally { try { in.close(); } catch (IOException ex) { throw new RuntimeException("Error closing resource stream", ex); } } } } for (Class<?> clazz : asl.getAnnotatedClasses()) { builder.add(clazz); } return builder.build(); }

Target:
public static ImmutableList<Class<?>> findEntityClassesFromDirectory(String pckg) { @SuppressWarnings("unchecked") final AnnotationAcceptingListener asl = new AnnotationAcceptingListener(Entity.class); final PackageNamesScanner scanner = new PackageNamesScanner(new String[]{pckg}, true); while (scanner.hasNext()) { final String next = scanner.next(); if (asl.accept(next)) { try (final InputStream in = scanner.open()) { asl.process(next, in); } catch (IOException e) { throw new RuntimeException("AnnotationAcceptingListener failed to process scanned resource: " + next); } } } final Builder<Class<?>> builder = ImmutableList.builder(); for (Class<?> clazz : asl.getAnnotatedClasses()) { builder.add(clazz); } return builder.build(); }
Source:
private boolean handleArrayNode(ArrayNode array, Collection<Object> collection, Class<?> componentType, ObjectMapper mapper) throws Exception { Assert.notNull(array, "ArrayNode must not be null!"); Assert.notNull(collection, "Source collection must not be null!"); Assert.notNull(mapper, "ObjectMapper must not be null!"); Iterator<Object> value = collection.iterator(); boolean nestedObjectFound = false; for (JsonNode jsonNode : array) { if (!value.hasNext()) { if (componentType != null) { collection.add(mapper.treeToValue(jsonNode, componentType)); } return nestedObjectFound; } Object next = value.next(); if (ArrayNode.class.isInstance(jsonNode)) { final Collection<Object> nestedCollection = asCollection(next); final Iterator<Object> iterator = nestedCollection.iterator(); return handleArrayNode(array, nestedCollection, iterator.hasNext() ? iterator.next().getClass() : null, mapper); } if (ObjectNode.class.isInstance(jsonNode)) { nestedObjectFound = true; doMerge((ObjectNode) jsonNode, next, mapper); } } while (value.hasNext()) { value.next(); value.remove(); } return nestedObjectFound; }

Target:
private boolean handleArrayNode(ArrayNode array, Collection<Object> collection, Class<?> componentType, ObjectMapper mapper) throws Exception { Assert.notNull(array, "ArrayNode must not be null!"); Assert.notNull(collection, "Source collection must not be null!"); Assert.notNull(mapper, "ObjectMapper must not be null!"); Iterator<Object> value = new ArrayList<Object>(collection).iterator(); boolean nestedObjectFound = false; for (JsonNode jsonNode : array) { if (!value.hasNext()) { if (componentType != null) { collection.add(mapper.treeToValue(jsonNode, componentType)); continue; } } Object next = value.next(); if (ArrayNode.class.isInstance(jsonNode)) { Collection<Object> nestedCollection = asCollection(next); Iterator<Object> iterator = nestedCollection.iterator(); return handleArrayNode(array, nestedCollection, iterator.hasNext() ? iterator.next().getClass() : null, mapper); } if (ObjectNode.class.isInstance(jsonNode)) { nestedObjectFound = true; doMerge((ObjectNode) jsonNode, next, mapper); } } while (value.hasNext()) { collection.remove(value.next()); } return nestedObjectFound; }
Source:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final RepartitionTopicConfig that = (RepartitionTopicConfig) o; return Objects.equals(name, that.name) && Objects.equals(topicConfigs, that.topicConfigs) && Objects.equals(numberOfPartitions, that.numberOfPartitions); }

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final RepartitionTopicConfig that = (RepartitionTopicConfig) o; return Objects.equals(name, that.name) && Objects.equals(topicConfigs, that.topicConfigs) && Objects.equals(enforceNumberOfPartitions, that.enforceNumberOfPartitions); }
Source:
private double calculatePressureDrag(FlightConfiguration configuration, FlightConditions conditions, Map<RocketComponent, AerodynamicForces> map, WarningSet warnings) { double stagnation, base, total; double radius = 0; if (calcMap == null) buildCalcMap(configuration); stagnation = calculateStagnationCD(conditions.getMach()); base = calculateBaseCD(conditions.getMach()); total = 0; final InstanceMap imap = configuration.getActiveInstances(); for(Map.Entry<RocketComponent, ArrayList<InstanceContext>> entry: imap.entrySet() ) { final RocketComponent c = entry.getKey(); if (!c.isAerodynamic()) continue; final ArrayList<InstanceContext> contextList = entry.getValue(); for(InstanceContext context: contextList ) { double cd = calcMap.get(c).calculatePressureDragForce(conditions, stagnation, base, warnings); total += cd; if (map != null) { map.get(c).setPressureCD(cd); } if(c.isCDOverridden()) continue; if (c instanceof SymmetricComponent) { SymmetricComponent s = (SymmetricComponent) c; if (radius < s.getForeRadius()) { double area = Math.PI * (pow2(s.getForeRadius()) - pow2(radius)); cd = stagnation * area / conditions.getRefArea(); total += cd; if (map != null) { map.get(c).setPressureCD(map.get(c).getPressureCD() + cd); } } radius = s.getAftRadius(); } } } return total; }

Target:
private double calculatePressureDrag(FlightConfiguration configuration, FlightConditions conditions, Map<RocketComponent, AerodynamicForces> map, WarningSet warnings) { double stagnation, base, total; if (calcMap == null) buildCalcMap(configuration); stagnation = calculateStagnationCD(conditions.getMach()); base = calculateBaseCD(conditions.getMach()); total = 0; final InstanceMap imap = configuration.getActiveInstances(); for(Map.Entry<RocketComponent, ArrayList<InstanceContext>> entry: imap.entrySet() ) { final RocketComponent c = entry.getKey(); if (!c.isAerodynamic()) continue; final ArrayList<InstanceContext> contextList = entry.getValue(); for(InstanceContext context: contextList ) { double cd = calcMap.get(c).calculatePressureDragForce(conditions, stagnation, base, warnings); total += cd; if (map != null) { map.get(c).setPressureCD(cd); } if(c.isCDOverridden()) continue; if (c instanceof SymmetricComponent) { SymmetricComponent s = (SymmetricComponent) c; double radius = 0; final SymmetricComponent prevComponent = s.getPreviousSymmetricComponent(); if (prevComponent != null) radius = prevComponent.getAftRadius(); if (radius < s.getForeRadius()) { double area = Math.PI * (pow2(s.getForeRadius()) - pow2(radius)); cd = stagnation * area / conditions.getRefArea(); total += cd; if (map != null) { map.get(c).setPressureCD(map.get(c).getPressureCD() + cd); } } } } } return total; }
Source:
public void run() { LOGGER.info(() -> "[TimeGraphView:BuildThreadStart] uid=" + fUniqueDebuggingId + ", trace=" + fBuildTrace.getName()); buildEntryList(fBuildTrace, fParentTrace, fMonitor); synchronized (fBuildThreadMap) { fBuildThreadMap.remove(fBuildTrace); } LOGGER.info(() -> "[TimeGraphView:BuildThreadEnd]"); }

Target:
public void run() { LOGGER.info(() -> "[TimeGraphView:BuildThreadStart] viewId=" + getViewId() + ", trace=" + fBuildTrace.getName()); buildEntryList(fBuildTrace, fParentTrace, fMonitor); synchronized (fBuildThreadMap) { fBuildThreadMap.remove(fBuildTrace); } LOGGER.info(() -> "[TimeGraphView:BuildThreadEnd]"); }
Source:
public void checkSpecificAccessControl() { if (!userInfo.isInstructor && !userInfo.isAdmin) { throw new UnauthorizedAccessException("Instructor or Admin privilege is required to access this resource."); } }

Target:
public void checkSpecificAccessControl() { if (!userInfo.isInstructor) { throw new UnauthorizedAccessException("Instructor privilege is required to access this resource."); } }
Source:
Object getEvent(int i, DateTime timestamp) { Map<String, Object> event = new HashMap<>(); event.put("page", "Gypsy Danger"); event.put("language", "en"); event.put("user", "nuclear"); event.put("unpatrolled", "true"); event.put("newPage", "true"); event.put("robot", "false"); event.put("anonymous", "false"); event.put("namespace", "article"); event.put("continent", "North Americ"); event.put("country", "United States"); event.put("region", "Bay Area"); event.put("city", "San Francisco"); event.put("timestamp", DATE_TIME_FORMATTER.print(timestamp)); event.put("added", i); event.put("deleted", 0); event.put("delta", i); return event; }

Target:
Object getEvent(int i, DateTime timestamp) { Map<String, Object> event = new HashMap<>(); event.put("page", "Gypsy Danger"); event.put("language", "en"); event.put("user", "nuclear"); event.put("unpatrolled", "true"); event.put("newPage", "true"); event.put("robot", "false"); event.put("anonymous", "false"); event.put("namespace", "article"); event.put("continent", "North America"); event.put("country", "United States"); event.put("region", "Bay Area"); event.put("city", "San Francisco"); event.put("timestamp", DATE_TIME_FORMATTER.print(timestamp)); event.put("added", i); event.put("deleted", 0); event.put("delta", i); return event; }
Source:
public IOpResponse execute(ThirdPartyLoginParams params) throws Exception { final Rp rp = getRp(); String authorizationEndpoint = getDiscoveryService().getConnectDiscoveryResponse(rp).getAuthorizationEndpoint(); String state = getStateService().generateState(); String nonce = getStateService().generateNonce(); String clientId = getConfigurationService().getConfiguration().getEncodeClientIdInAuthorizationUrl() ? Utils.encode(rp.getClientId()) : rp.getClientId(); String redirectUri = rp.getRedirectUri(); authorizationEndpoint += "?response_type=" + Utils.joinAndUrlEncode(rp.getResponseTypes()); authorizationEndpoint += "&client_id=" + clientId; authorizationEndpoint += "&redirect_uri=" + redirectUri; authorizationEndpoint += "&scope=" + Utils.joinAndUrlEncode(rp.getScope()); authorizationEndpoint += "&state=" + state; authorizationEndpoint += "&nonce=" + nonce; return new GetAuthorizationUrlResponse(authorizationEndpoint); }

Target:
public IOpResponse execute(ThirdPartyLoginParams params) throws Exception { final Rp rp = getRp(); if (Strings.isNullOrEmpty(params.getIss())) { LOG.error("'iss' is empty or not specified in parameter."); throw new HttpException(ErrorResponseCode.BAD_REQUEST_NO_ISSUER); } if (!Strings.isNullOrEmpty(params.getTargetLinkUri()) && !rp.getRedirectUris().stream().anyMatch(uri -> getHost(uri) == getHost(params.getTargetLinkUri()))) { LOG.error("The hostname of `target_link_uri` should match with the hostname of `redirect_uri` of RP."); throw new HttpException(ErrorResponseCode.BAD_REQUEST_INVALID_TARGET_URI); } String authorizationEndpoint = getDiscoveryService().getConnectDiscoveryResponse(rp).getAuthorizationEndpoint(); String state = getStateService().generateState(); String nonce = getStateService().generateNonce(); String clientId = getConfigurationService().getConfiguration().getEncodeClientIdInAuthorizationUrl() ? Utils.encode(rp.getClientId()) : rp.getClientId(); String redirectUri = rp.getRedirectUri(); authorizationEndpoint += "?response_type=" + Utils.joinAndUrlEncode(rp.getResponseTypes()); authorizationEndpoint += "&client_id=" + clientId; authorizationEndpoint += "&redirect_uri=" + redirectUri; authorizationEndpoint += "&scope=" + Utils.joinAndUrlEncode(rp.getScope()); authorizationEndpoint += "&state=" + state; authorizationEndpoint += "&nonce=" + nonce; return new GetAuthorizationUrlResponse(authorizationEndpoint); }
Source:
Bitmap loadConstrainedBitmap(Uri uri) throws FileNotFoundException { if (uri == null || mContext == null) { throw new IllegalArgumentException("bad argument to getScaledBitmap"); } BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inJustDecodeBounds = true; loadBitmap(uri, opt); int w = opt.outWidth; int h = opt.outHeight; if (w <= 0 || h <= 0) { return null; } int imageSide = Math.max(w, h); int sampleSize = 1; while (imageSide > MAX_PRINT_SIZE) { imageSide >>>= 1; sampleSize <<= 1; } if (sampleSize <= 0 || 0 >= (Math.min(w, h) / sampleSize)) { return null; } BitmapFactory.Options decodeOptions; synchronized (mLock) { mDecodeOptions = new BitmapFactory.Options(); mDecodeOptions.inMutable = true; mDecodeOptions.inSampleSize = sampleSize; mDecodeOptions.inPreferredColorSpace = ColorSpace.get(ColorSpace.Named.SRGB); decodeOptions = mDecodeOptions; } try { return loadBitmap(uri, decodeOptions); } finally { synchronized (mLock) { mDecodeOptions = null; } } }

Target:
Bitmap loadConstrainedBitmap(Uri uri) throws FileNotFoundException { if (uri == null || mContext == null) { throw new IllegalArgumentException("bad argument to getScaledBitmap"); } BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inJustDecodeBounds = true; loadBitmap(uri, opt); int w = opt.outWidth; int h = opt.outHeight; if (w <= 0 || h <= 0) { return null; } int imageSide = Math.max(w, h); int sampleSize = 1; while (imageSide > MAX_PRINT_SIZE) { imageSide >>>= 1; sampleSize <<= 1; } if (sampleSize <= 0 || 0 >= (Math.min(w, h) / sampleSize)) { return null; } BitmapFactory.Options decodeOptions; synchronized (mLock) { mDecodeOptions = new BitmapFactory.Options(); mDecodeOptions.inMutable = true; mDecodeOptions.inSampleSize = sampleSize; if (Build.VERSION.SDK_INT >= 26) { mDecodeOptions.inPreferredColorSpace = ColorSpace.get(ColorSpace.Named.SRGB); } decodeOptions = mDecodeOptions; } try { return loadBitmap(uri, decodeOptions); } finally { synchronized (mLock) { mDecodeOptions = null; } } }
Source:
public void testTrimRetryServerEpochChange() throws Exception{ final int nEntries = 5; final long initEpoch = 0; final long finalEpoch = 1; Map<String, String> testMap = getDefaultRuntime().getObjectsView().build() .setTypeToken(new TypeToken<SMRMap<String, String>>() { }) .setStreamName("test") .open(); testMap.put("k1", "1"); testMap.put("k2", "2"); testMap.put("k3", "3"); testMap.put("k4", "4"); testMap.put("k5", "5"); MultiCheckpointWriter mcw = new MultiCheckpointWriter(); mcw.addMap((SMRMap) testMap); Token checkpointAddress = mcw.appendCheckpoints(getRuntime(), "author"); assertThat(checkpointAddress).isEqualTo(new Token(initEpoch, nEntries - 1)); Layout l = new Layout(getLayoutServer(0).getCurrentLayout()); l.setEpoch(l.getEpoch() + 1); getDefaultRuntime().getLayoutView().getRuntimeLayout(l).sealMinServerSet(); getDefaultRuntime().getLayoutView().updateLayout(l, 1L); boolean exceptionCaught = false; try { getDefaultRuntime().getAddressSpaceView().prefixTrim(new Token(finalEpoch, nEntries - 1)); } catch (Exception e) { exceptionCaught = true; assertThat(e).isInstanceOf(RuntimeException.class); assertThat(e).hasCauseInstanceOf(WrongEpochException.class); } assertThat(exceptionCaught).isFalse(); Token trimMark = getDefaultRuntime().getAddressSpaceView().getTrimMark(); assertThat(trimMark).isEqualTo(new Token(finalEpoch, nEntries)); }

Target:
public void testTrimRetryServerEpochChange() throws Exception{ Map<String, String> testMap = getDefaultRuntime().getObjectsView().build() .setTypeToken(new TypeToken<SMRMap<String, String>>() { }) .setStreamName("test") .open(); Layout l = new Layout(getLayoutServer(0).getCurrentLayout()); final long finalEpoch = l.getEpoch() + 1; l.setEpoch(finalEpoch); getDefaultRuntime().getLayoutView().getRuntimeLayout(l).sealMinServerSet(); getDefaultRuntime().getLayoutView().updateLayout(l, 1L); boolean exceptionCaught = false; try { getDefaultRuntime().getAddressSpaceView().prefixTrim(new Token(finalEpoch, Address.NON_ADDRESS)); } catch (Exception e) { exceptionCaught = true; assertThat(e) .isInstanceOf(WrongEpochException.class); } assertThat(exceptionCaught).isFalse(); Token trimMark = getDefaultRuntime().getAddressSpaceView().getTrimMark(); assertThat(trimMark).isEqualTo(new Token(finalEpoch, 0L)); }
Source:
public void dispose() { LogManager.logInfo("Disposing", this); fWindow= null; }

Target:
public void dispose() { fWindow= null; }
Source:
private int pingIsAlive( ) { try { final HttpClient client = HttpClientManager.getInstance().createDefaultClient(); final URIBuilder uriBuilder = new URIBuilder() .setScheme( HTTP_SCHEME ) .setHost( WN_HOST ) .setPort( WN_PORT ) .setPath( IS_ALIVE_ENDPOINT ); final URI pingIsAliveURI = uriBuilder.build(); final HttpGet pingIsAlive = new HttpGet( pingIsAliveURI.toString() ); final HttpResponse response = client.execute( pingIsAlive ); return response.getStatusLine().getStatusCode(); } catch ( URISyntaxException | IOException e ) { logger.error( e.getMessage() ); } return HttpStatus.SC_INTERNAL_SERVER_ERROR; }

Target:
private int pingIsAlive( ) { if ( logger.isDebugEnabled() ) { logger.debug( " Checking is alive endpoint..." ); } try { final HttpClient client = HttpClientManager.getInstance().createDefaultClient(); final URIBuilder uriBuilder = new URIBuilder() .setScheme( HTTP_SCHEME ) .setHost( WN_HOST ) .setPort( WN_PORT ) .setPath( IS_ALIVE_ENDPOINT ); final URI pingIsAliveURI = uriBuilder.build(); final HttpGet pingIsAlive = new HttpGet( pingIsAliveURI.toString() ); final HttpResponse response = client.execute( pingIsAlive ); return response.getStatusLine().getStatusCode(); } catch ( URISyntaxException | IOException e ) { logger.error( e.getMessage() ); } return HttpStatus.SC_INTERNAL_SERVER_ERROR; }
Source:
Bubble(int x, int y, int id, int radius) { this.x = x; this.y = y; this.id = id; this.radius = radius; }

Target:
Bubble(int x, int y, int id, int radius) { super(x,y,id); this.radius = radius; }
Source:
public void testAddIgnoredFile() throws Exception { assertTrue(new File(db.getWorkTree(), "sub").mkdir()); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); PrintWriter writer = new PrintWriter(file); writer.print("content"); writer.close(); File ignoreFile = new File(db.getWorkTree(), ".gitignore"); FileUtils.createNewFile(ignoreFile); writer = new PrintWriter(ignoreFile); writer.print("sub/b.txt"); writer.close(); File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); writer = new PrintWriter(file2); writer.print("content b"); writer.close(); Git git = new Git(db); git.add().addFilepattern("sub").call(); assertEquals( "[sub/a.txt, mode:100644, content:content]", indexState(CONTENT)); }

Target:
public void testAddIgnoredFile() throws Exception { FileUtils.mkdir(new File(db.getWorkTree(), "sub")); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); PrintWriter writer = new PrintWriter(file); writer.print("content"); writer.close(); File ignoreFile = new File(db.getWorkTree(), ".gitignore"); FileUtils.createNewFile(ignoreFile); writer = new PrintWriter(ignoreFile); writer.print("sub/b.txt"); writer.close(); File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); writer = new PrintWriter(file2); writer.print("content b"); writer.close(); Git git = new Git(db); git.add().addFilepattern("sub").call(); assertEquals( "[sub/a.txt, mode:100644, content:content]", indexState(CONTENT)); }
Source:
private boolean isCourseArchived(CourseAttributes course, String googleId) { InstructorAttributes instructor = logic.getInstructorForGoogleId(course.id, googleId); boolean isCourseArchived = (instructor.isArchived != null)? instructor.isArchived : course.isArchived; return isCourseArchived; }

Target:
private boolean isCourseArchived(CourseAttributes course, String googleId) { return logic.isCourseArchived(course.id, googleId); }
Source:
public List<UserCertificationBodyMapDTO> getByUserId(Long userId) { Query query = entityManager.createQuery( "from UserCertificationBodyMapEntity ucbm " + "join fetch ucbm.certificationBody cb " + "join fetch ucbm.user u " + "where (ucbm.deleted != true) AND (u.id = :userId) ", UserCertificationBodyMapEntity.class); query.setParameter("userId", userId); List<UserCertificationBodyMapEntity> result = query.getResultList(); List<UserCertificationBodyMapDTO> dtos = new ArrayList<UserCertificationBodyMapDTO>(); for (UserCertificationBodyMapEntity entity : result) { dtos.add(new UserCertificationBodyMapDTO(entity)); } return dtos; }

Target:
public List<UserCertificationBodyMapDTO> getByUserId(Long userId) { Query query = entityManager.createQuery( "from UserCertificationBodyMapEntity ucbm " + "join fetch ucbm.certificationBody cb " + "join fetch ucbm.user u " + "where (ucbm.deleted != true) AND (u.id = :userId) ", UserCertificationBodyMapEntity.class); query.setParameter("userId", userId); List<UserCertificationBodyMapEntity> result = query.getResultList(); List<UserCertificationBodyMapDTO> dtos = new ArrayList<UserCertificationBodyMapDTO>(); if (result != null) { for (UserCertificationBodyMapEntity entity : result) { dtos.add(new UserCertificationBodyMapDTO(entity)); } } return dtos; }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClassLoaderModel that = (ClassLoaderModel) o; return getArtifactCoordinates().equals(that.getArtifactCoordinates()); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClassLoaderModel that = (ClassLoaderModel) o; return getArtifactCoordinates().equals(that.getArtifactCoordinates()); }
Source:
public String edit() { logger.debug("Edit"); try { savedId.clear(); ResourceInterface resource = this.loadResource(this.getResourceId()); this.setResourceTypeCode(resource.getType()); List fileDescr = new ArrayList<String>(); fileDescr.add(resource.getDescription()); setFileDescriptions(fileDescr); List<Category> resCategories = resource.getCategories(); for (Category cat : resCategories) { this.getCategoryCodes().add(cat.getCode()); } this.setMainGroup(resource.getMainGroup()); this.setStrutsAction(ApsAdminSystemConstants.EDIT); this.setMetadata(resource.getMetadata()); } catch (Throwable t) { logger.error("error in edit", t); return FAILURE; } return SUCCESS; }

Target:
public String edit() { logger.debug("Edit in multiple resource action for id {}", this.getResourceId() ); try { savedId.clear(); ResourceInterface resource = this.loadResource(this.getResourceId()); this.setResourceTypeCode(resource.getType()); List fileDescr = new ArrayList<String>(); fileDescr.add(resource.getDescription()); setFileDescriptions(fileDescr); List<Category> resCategories = resource.getCategories(); for (Category cat : resCategories) { this.getCategoryCodes().add(cat.getCode()); } this.setMainGroup(resource.getMainGroup()); this.setStrutsAction(ApsAdminSystemConstants.EDIT); this.setMetadata(resource.getMetadata()); } catch (Throwable t) { logger.error("error in edit", t); return FAILURE; } return SUCCESS; }
Source:
private boolean initGlusterPeerProcess() { Map<String, Pair<String, String>> exclusiveLocks = new HashMap<String, Pair<String, String>>(); exclusiveLocks.put(getVds().getVdsGroupId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.GLUSTER, VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_OPERATION_INPROGRESS)); EngineLock lock = new EngineLock(exclusiveLocks, null); getLockManager().acquireLockWait(lock); try { glusterPeerListSucceeded = true; glusterPeerProbeSucceeded = true; List<VDS> vdsList = getVdsDAO().getAllForVdsGroupWithStatus(getVdsGroupId(), VDSStatus.Up); if (vdsList != null && vdsList.size() > 0) { VDS upServer = null; for (VDS vds : vdsList) { if (!getVdsId().equals(vds.getId())) { upServer = vds; break; } } if (upServer != null) { List<GlusterServerInfo> glusterServers = getGlusterPeers(upServer.getId()); Map<String, String> customLogValues = new HashMap<String, String>(); customLogValues.put("Server", upServer.getHostName()); if (glusterServers.size() == 0) { customLogValues.put("Command", "gluster peer status"); setNonOperational(NonOperationalReason.GLUSTER_COMMAND_FAILED, customLogValues); return false; } else if (!hostExists(glusterServers, getVds())) { if (!glusterPeerProbe(upServer.getId(), getVds().getHostName())) { customLogValues.put("Command", "gluster peer probe " + getVds().getHostName()); setNonOperational(NonOperationalReason.GLUSTER_COMMAND_FAILED, customLogValues); return false; } } } } return true; } finally { getLockManager().releaseLock(lock); } }

Target:
private boolean initGlusterPeerProcess() { EngineLock lock = GlusterUtil.getInstance().acquireGlusterLockWait(getVds().getVdsGroupId()); try { glusterPeerListSucceeded = true; glusterPeerProbeSucceeded = true; List<VDS> vdsList = getVdsDAO().getAllForVdsGroupWithStatus(getVdsGroupId(), VDSStatus.Up); if (vdsList != null && vdsList.size() > 0) { VDS upServer = null; for (VDS vds : vdsList) { if (!getVdsId().equals(vds.getId())) { upServer = vds; break; } } if (upServer != null) { List<GlusterServerInfo> glusterServers = getGlusterPeers(upServer.getId()); Map<String, String> customLogValues = new HashMap<String, String>(); customLogValues.put("Server", upServer.getHostName()); if (glusterServers.size() == 0) { customLogValues.put("Command", "gluster peer status"); setNonOperational(NonOperationalReason.GLUSTER_COMMAND_FAILED, customLogValues); return false; } else if (!hostExists(glusterServers, getVds())) { if (!glusterPeerProbe(upServer.getId(), getVds().getHostName())) { customLogValues.put("Command", "gluster peer probe " + getVds().getHostName()); setNonOperational(NonOperationalReason.GLUSTER_COMMAND_FAILED, customLogValues); return false; } } } } return true; } finally { getLockManager().releaseLock(lock); } }
Source:
private void appendPortsToConfig(File tempFile) throws IOException { for(CouchbasePort port: CouchbasePort.values()) { if (! port.isBootstrap()) { String config = String.format("{%s, %d}.\n", port.name, getMappedPort(port)); FileUtils.writeStringToFile(tempFile, config, "UTF-8", true); } } }

Target:
private void appendPortsToConfig(File tempFile) throws IOException { for (CouchbasePort port : CouchbasePort.values()) { if (!port.isDynamic()) { String config = String.format("{%s, %d}.\n", port.name, getMappedPort(port)); FileUtils.writeStringToFile(tempFile, config, "UTF-8", true); } } }
Source:
public boolean equals(final Object o) { if (o instanceof DenseMatrix) { return breezeMatrix.equals(((DenseMatrix) o).breezeMatrix); } if (o instanceof CSCMatrix) { return breezeMatrix.equals(((CSCMatrix) o).getBreezeMatrix()); } return false; }

Target:
public boolean equals(final Object o) { if (this == o) { return true; } else if (o instanceof DenseMatrix) { return breezeMatrix.equals(((DenseMatrix) o).breezeMatrix); } else if (o instanceof CSCMatrix) { return breezeMatrix.equals(((CSCMatrix) o).getBreezeMatrix()); } else { return false; } }
Source:
public static void logS3GuardDisabled(Logger logger, String warnLevelStr, String bucket) throws UnsupportedOperationException, IllegalArgumentException { final DisabledWarnLevel warnLevel; try { warnLevel = DisabledWarnLevel.valueOf(warnLevelStr); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(UNKNOWN_WARN_LEVEL + warnLevelStr, e); } switch (warnLevel) { case SILENT: break; case INFORM: logger.info(DISABLED_LOG_MSG, bucket); break; case WARN: logger.warn(DISABLED_LOG_MSG, bucket); break; case FAIL: logger.error(DISABLED_LOG_MSG, bucket); throw new UnsupportedOperationException(DISABLED_LOG_MSG + bucket); default: throw new IllegalArgumentException(UNKNOWN_WARN_LEVEL + warnLevelStr); } }

Target:
public static void logS3GuardDisabled(Logger logger, String warnLevelStr, String bucket) throws UnsupportedOperationException, IllegalArgumentException { final DisabledWarnLevel warnLevel; try { warnLevel = DisabledWarnLevel.valueOf(warnLevelStr.toUpperCase(Locale.US)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(UNKNOWN_WARN_LEVEL + warnLevelStr, e); } switch (warnLevel) { case SILENT: logger.debug(DISABLED_LOG_MSG, bucket); break; case INFORM: logger.info(DISABLED_LOG_MSG, bucket); break; case WARN: logger.warn(DISABLED_LOG_MSG, bucket); break; case FAIL: logger.error(DISABLED_LOG_MSG, bucket); throw new UnsupportedOperationException(DISABLED_LOG_MSG + bucket); default: throw new IllegalArgumentException(UNKNOWN_WARN_LEVEL + warnLevelStr); } }
Source:
void exec(String[] cmdArray, final BluetoothProcessListener listener) { logger.debug("Executing: {}", Arrays.toString(cmdArray)); Consumer<CommandStatus> callback = status -> logger.debug("Command ended with exit value {}", status.getExitStatus().getExitValue()); Command command = new Command(String.join(" ", cmdArray)); command.setOutputStream(this.outputStream); command.setErrorStream(this.errorStream); this.executorService.execute(command, callback); this.futureInputGobbler = streamGobblers.submit(() -> { Thread.currentThread().setName("BluetoothProcess Input Stream Gobbler"); try { readInputStreamFully(this.readOutputStream, listener); } catch (IOException | KuraException e) { logger.error("Process input stream failed", e); } }); this.futureErrorGobbler = streamGobblers.submit(() -> { Thread.currentThread().setName("BluetoothProcess ErrorStream Gobbler"); try { readErrorStreamFully(this.readErrorStream, listener); } catch (IOException | KuraException e) { logger.error("Process error stream failed", e); } }); }

Target:
void exec(String[] cmdArray, final BluetoothProcessListener listener) { if (logger.isDebugEnabled()) { logger.debug("Executing: {}", Arrays.toString(cmdArray)); } Consumer<CommandStatus> callback = status -> logger.debug("Command ended with exit value {}", status.getExitStatus().getExitValue()); Command command = new Command(cmdArray); command.setOutputStream(this.outputStream); command.setErrorStream(this.errorStream); this.executorService.execute(command, callback); this.futureInputGobbler = streamGobblers.submit(() -> { Thread.currentThread().setName("BluetoothProcess Input Stream Gobbler"); try { readInputStreamFully(this.readOutputStream, listener); } catch (IOException | KuraException e) { logger.error("Process input stream failed", e); } }); this.futureErrorGobbler = streamGobblers.submit(() -> { Thread.currentThread().setName("BluetoothProcess ErrorStream Gobbler"); try { readErrorStreamFully(this.readErrorStream, listener); } catch (IOException | KuraException e) { logger.error("Process error stream failed", e); } }); }
Source:
private void showTagsDialog() { String[] tagList = new String[mTags.size()]; int current = -1; for (int i = 0; i < mTags.size(); i++) { tagList[i] = mTags.get(i).getName(); if (mTags.get(i).getCommit().getSha() == mSelectedRef) { current = i; } } AlertDialog.Builder builder = UiUtils.createDialogBuilder(this); builder.setCancelable(true); builder.setTitle(R.string.repo_tags); builder.setSingleChoiceItems(tagList, current, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mSelectedRef = mTags.get(which).getCommit().getSha(); mSelectBranchTag = mTags.get(which).getName(); } }); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { refreshFragment(); } }); builder.show(); }

Target:
private void showTagsDialog() { String[] tagList = new String[mTags.size()]; int current = -1; for (int i = 0; i < mTags.size(); i++) { tagList[i] = mTags.get(i).getName(); if (mTags.get(i).getCommit().getSha().equals(mSelectedRef)) { current = i; } } AlertDialog.Builder builder = UiUtils.createDialogBuilder(this); builder.setCancelable(true); builder.setTitle(R.string.repo_tags); builder.setSingleChoiceItems(tagList, current, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mSelectedRef = mTags.get(which).getCommit().getSha(); mSelectBranchTag = mTags.get(which).getName(); } }); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { refreshFragment(); } }); builder.show(); }
Source:
public HttpServerRequest streamPriorityHandler(Handler<StreamPriority> handler) { streamPriorityHandler = handler; return this; }

Target:
public HttpServerRequest streamPriorityHandler(Handler<StreamPriority> handler) { synchronized (conn) { streamPriorityHandler = handler; } return this; }
Source:
public boolean emit(U update) { return true; }

Target:
public boolean emit(U update) { return false; }
Source:
public final FieldArray clone() { int size = size(); FieldArray clone = new FieldArray(size); System.arraycopy(mFieldNumbers, 0, clone.mFieldNumbers, 0, size); for (int i = 0; i < mData.length; i++) { if (mData[i] != null) { clone.mData[i] = mData[i].clone(); } } clone.mSize = mSize; return clone; }

Target:
public final FieldArray clone() { int size = size(); FieldArray clone = new FieldArray(size); System.arraycopy(mFieldNumbers, 0, clone.mFieldNumbers, 0, size); for (int i = 0; i < size; i++) { if (mData[i] != null) { clone.mData[i] = mData[i].clone(); } } clone.mSize = size; return clone; }
Source:
private void acquireUnmanagedUsbController( VmBase vmBase, List<VmDevice> managedUsbControllers, List<VmDevice> unmanagedControllers) { if (unmanagedControllers.size() > 1) { throw new IllegalStateException(format("At most one unmanaged USB controller expected for VM=%s(%s), found=%s", vmBase.getName(), vmBase.getId(), unmanagedControllers)); } final UsbControllerModel controllerModel = getUsbControllerModel(vmBase); if (unmanagedControllers.size() == 1) { removeVmDevices(managedUsbControllers); VmDevice device = unmanagedControllers.iterator().next(); device.setManaged(true); device.setPlugged(true); device.setReadOnly(false); device.setSpecParams(createUsbControllerSpecParams(controllerModel.libvirtName, 0)); vmDeviceDao.update(device); return; } }

Target:
private void acquireUnmanagedUsbController( VmBase vmBase, List<VmDevice> managedUsbControllers, List<VmDevice> unmanagedControllers) { if (unmanagedControllers.size() > 1) { throw new IllegalStateException(format("At most one unmanaged USB controller expected for VM=%s(%s), found=%s", vmBase.getName(), vmBase.getId(), unmanagedControllers)); } final UsbControllerModel controllerModel = getUsbControllerModel(vmBase); if (unmanagedControllers.size() != 1) { return; } removeVmDevices(managedUsbControllers); VmDevice device = unmanagedControllers.iterator().next(); device.setManaged(true); device.setPlugged(true); device.setReadOnly(false); device.setSpecParams(createUsbControllerSpecParams(controllerModel.libvirtName, 0)); vmDeviceDao.update(device); }
Source:
public void onPostChanged(OnPostChanged event) { switch (event.causeOfChange) { case FETCH_POSTS: case FETCH_PAGES: mIsFetchingPosts = false; if (!isAdded()) { return; } setRefreshing(false); hideLoadMoreProgress(); if (!event.isError()) { mCanLoadMorePosts = event.canLoadMore; int count; if (mIsPage) { count = mPostStore.getPagesCountForSite(mSite); } else { count = mPostStore.getPostsCountForSite(mSite); } if (count > 0) { hideEmptyView(); } else { if (NetworkUtils.isNetworkAvailable(getActivity())) { updateEmptyView(EmptyViewMessageType.NO_CONTENT); } else { updateEmptyView(EmptyViewMessageType.NETWORK_ERROR); } } loadPosts(LoadMode.IF_CHANGED); } else { PostError error = event.error; switch (error.type) { case UNAUTHORIZED: updateEmptyView(EmptyViewMessageType.PERMISSION_ERROR); break; default: updateEmptyView(EmptyViewMessageType.GENERIC_ERROR); break; } } break; case DELETE_POST: if (event.isError()) { String message = String.format(getText(R.string.error_delete_post).toString(), mIsPage ? "page" : "post"); ToastUtils.showToast(getActivity(), message, ToastUtils.Duration.SHORT); loadPosts(LoadMode.IF_CHANGED); } break; } }

Target:
public void onPostChanged(OnPostChanged event) { switch (event.causeOfChange) { case FETCH_POSTS: case FETCH_PAGES: mIsFetchingPosts = false; if (!isAdded()) { return; } setRefreshing(false); hideLoadMoreProgress(); if (!event.isError()) { mCanLoadMorePosts = event.canLoadMore; loadPosts(LoadMode.IF_CHANGED); } else { PostError error = event.error; switch (error.type) { case UNAUTHORIZED: updateEmptyView(EmptyViewMessageType.PERMISSION_ERROR); break; default: updateEmptyView(EmptyViewMessageType.GENERIC_ERROR); break; } } break; case DELETE_POST: if (event.isError()) { String message = String.format(getText(R.string.error_delete_post).toString(), mIsPage ? "page" : "post"); ToastUtils.showToast(getActivity(), message, ToastUtils.Duration.SHORT); loadPosts(LoadMode.IF_CHANGED); } break; } }