auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void expireMapping(final K key, final ValueHolder<V> value) { map.computeIfPresent(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(K mappedKey, final OnHeapValueHolder<V> mappedValue) { if(mappedValue.equals(key)) { onExpiration(key, value); return null; } return mappedValue; } }); }

Target:
private void expireMapping(final K key, final ValueHolder<V> value) { map.computeIfPresent(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(K mappedKey, final OnHeapValueHolder<V> mappedValue) { if(mappedValue.equals(value)) { onExpiration(key, value); return null; } return mappedValue; } }); }
Source:
public void setAllowedHeaderNames(final Set<String> allowedHeaderNames) { this.allowedHeaderNames = allowedHeaderNames; }

Target:
public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) { this.allowedHeaderNames = allowedHeaderNames; return this; }
Source:
void performRetry(BitmapHunter hunter) { if (hunter.isCancelled()) return; if (service.isShutdown()) { performError(hunter); return; } NetworkInfo networkInfo = null; if (scansNetworkChanges) { ConnectivityManager connectivityManager = ContextCompat.getSystemService(context, ConnectivityManager.class); if (connectivityManager != null) { networkInfo = connectivityManager.getActiveNetworkInfo(); } } if (hunter.shouldRetry(airplaneMode, networkInfo)) { if (hunter.getPicasso().loggingEnabled) { log(OWNER_DISPATCHER, VERB_RETRYING, getLogIdsForHunter(hunter)); } if (hunter.getException() instanceof NetworkRequestHandler.ContentLengthException) { hunter.setData(hunter.getData().newBuilder().networkPolicy(NetworkPolicy.NO_CACHE).build()); } hunter.setFuture(service.submit(hunter)); } else { performError(hunter); if (scansNetworkChanges && hunter.supportsReplay()) { markForReplay(hunter); } } }

Target:
void performRetry(BitmapHunter hunter) { if (hunter.isCancelled()) return; if (service.isShutdown()) { performError(hunter); return; } NetworkInfo networkInfo = null; if (scansNetworkChanges) { ConnectivityManager connectivityManager = ContextCompat.getSystemService(context, ConnectivityManager.class); if (connectivityManager != null) { networkInfo = connectivityManager.getActiveNetworkInfo(); } } if (hunter.shouldRetry(airplaneMode, networkInfo)) { if (hunter.picasso.loggingEnabled) { log(OWNER_DISPATCHER, VERB_RETRYING, getLogIdsForHunter(hunter)); } if (hunter.getException() instanceof NetworkRequestHandler.ContentLengthException) { hunter.data = hunter.data.newBuilder().networkPolicy(NetworkPolicy.NO_CACHE).build(); } hunter.future = service.submit(hunter); } else { performError(hunter); if (scansNetworkChanges && hunter.supportsReplay()) { markForReplay(hunter); } } }
Source:
private static void deserializeColumn(List<Column> tobeAdded, List<ColumnProto> protos, int serializedColumnIndex) { ColumnProto columnProto = protos.get(serializedColumnIndex); if (columnProto.getDataType().getType() == Type.RECORD) { int childNum = columnProto.getDataType().getNumNestedFields(); int childStartIndex = tobeAdded.size() - childNum; List<Column> nestedColumns = new ArrayList<>(); nestedColumns.addAll(tobeAdded.subList(childStartIndex, childStartIndex + childNum)); for (int i = 0; i < childNum; i++) { tobeAdded.remove(tobeAdded.size() - 1); } tobeAdded.add(new Column(columnProto.getName(), new TypeDesc(new Schema(nestedColumns)))); } else { tobeAdded.add(new Column(protos.get(serializedColumnIndex))); } }

Target:
private static void deserializeColumn(List<Column> tobeAdded, List<ColumnProto> protos, int serializedColumnIndex) { ColumnProto columnProto = protos.get(serializedColumnIndex); if (columnProto.getDataType().getType() == Type.RECORD) { int childNum = columnProto.getDataType().getNumNestedFields(); int childStartIndex = tobeAdded.size() - childNum; List<Column> nestedColumns = new ArrayList<>(tobeAdded.subList(childStartIndex, childStartIndex + childNum)); for (int i = 0; i < childNum; i++) { tobeAdded.remove(tobeAdded.size() - 1); } tobeAdded.add(new Column(columnProto.getName(), new TypeDesc(new Schema(nestedColumns)))); } else { tobeAdded.add(new Column(protos.get(serializedColumnIndex))); } }
Source:
private synchronized void connect(Handler<HttpVersion> headersHandler) { if (connecting) { return; } if (method == HttpMethod.OTHER && rawMethod == null) { throw new IllegalStateException("You must provide a rawMethod when using an HttpMethod.OTHER method"); } String peerHost; if (hostHeader != null) { int idx = hostHeader.lastIndexOf(':'); if (idx != -1) { peerHost = hostHeader.substring(0, idx); } else { peerHost = hostHeader; } } else { peerHost = host; } Handler<HttpConnection> initializer = connectionHandler; ContextInternal connectCtx = vertx.getOrCreateContext(); connecting = true; client.getConnectionForRequest(connectCtx, peerHost, ssl, port, host, ar1 -> { if (ar1.succeeded()) { HttpClientStream stream = ar1.result(); ContextInternal ctx = (ContextInternal) stream.getContext(); if(stream.connection() != null) { stream.connection().exceptionHandler(client.exceptionHandler()); } if (stream.id() == 1 && initializer != null) { ctx.executeFromIO(v -> { initializer.handle(stream.connection()); }); } if (exceptionOccurred != null || reset != null) { stream.reset(0); } else { ctx.executeFromIO(v -> { connected(headersHandler, stream); }); } } else { connectCtx.executeFromIO(v -> { handleException(ar1.cause()); }); } }); }

Target:
private synchronized void connect(Handler<HttpVersion> headersHandler) { if (!connecting) { if (method == HttpMethod.OTHER && rawMethod == null) { throw new IllegalStateException("You must provide a rawMethod when using an HttpMethod.OTHER method"); } String peerHost; if (hostHeader != null) { int idx = hostHeader.lastIndexOf(':'); if (idx != -1) { peerHost = hostHeader.substring(0, idx); } else { peerHost = hostHeader; } } else { peerHost = host; } Handler<HttpConnection> h1 = connectionHandler; Handler<HttpConnection> h2 = client.connectionHandler(); Handler<HttpConnection> initializer; if (h1 != null) { if (h2 != null) { initializer = conn -> { h1.handle(conn); h2.handle(conn); }; } else { initializer = h1; } } else { initializer = h2; } ContextInternal connectCtx = vertx.getOrCreateContext(); connecting = true; client.getConnectionForRequest(connectCtx, peerHost, ssl, port, host, ar1 -> { if (ar1.succeeded()) { HttpClientStream stream = ar1.result(); ContextInternal ctx = (ContextInternal) stream.getContext(); if (stream.id() == 1 && initializer != null) { ctx.executeFromIO(v -> { initializer.handle(stream.connection()); }); } if (exceptionOccurred != null || reset != null) { stream.reset(0); } else { ctx.executeFromIO(v -> { connected(headersHandler, stream); }); } } else { connectCtx.executeFromIO(v -> { handleException(ar1.cause()); }); } }); } }
Source:
public void startActivity(String appPackage, String appActivity, String appWaitPackage, String appWaitActivity) throws IllegalArgumentException { Preconditions.checkArgument((_isNotNullOrEmpty(appPackage) && _isNotNullOrEmpty(appActivity)), String.format("'%s' and '%s' are required.", MobileCapabilityType.APP_PACKAGE, MobileCapabilityType.APP_ACTIVITY)); appWaitPackage = _isNotNullOrEmpty(appWaitPackage) ? appWaitPackage : ""; appWaitActivity = _isNotNullOrEmpty(appWaitActivity) ? appWaitActivity : ""; ImmutableMap<String, String> parameters = ImmutableMap.of(MobileCapabilityType.APP_PACKAGE, appPackage, MobileCapabilityType.APP_ACTIVITY, appActivity, MobileCapabilityType.APP_WAIT_PACKAGE, appWaitPackage, MobileCapabilityType.APP_WAIT_ACTIVITY, appWaitActivity); execute(START_ACTIVITY, parameters); }

Target:
public void startActivity(String appPackage, String appActivity, String appWaitPackage, String appWaitActivity) throws IllegalArgumentException { checkArgument((_isNotNullOrEmpty(appPackage) && _isNotNullOrEmpty(appActivity)), String.format("'%s' and '%s' are required.", APP_PACKAGE, APP_ACTIVITY)); appWaitPackage = _isNotNullOrEmpty(appWaitPackage) ? appWaitPackage : ""; appWaitActivity = _isNotNullOrEmpty(appWaitActivity) ? appWaitActivity : ""; ImmutableMap<String, String> parameters = ImmutableMap.of(APP_PACKAGE, appPackage, APP_ACTIVITY, appActivity, APP_WAIT_PACKAGE, appWaitPackage, APP_WAIT_ACTIVITY, appWaitActivity); execute(START_ACTIVITY, parameters); }
Source:
private static Set<File> getFilesForPattern(Path baseDir, String pathPattern, boolean libraryProperty) { try { Path filePath = resolvePath(baseDir, pathPattern); if ((pathPattern.endsWith(".jar") || pathPattern.endsWith(".zip")) && Files.isRegularFile(filePath)) { return Collections.singleton(filePath.toFile()); } if (Files.isDirectory(filePath)) { if (libraryProperty) { Set<File> matches = new LibraryFinder().find(filePath, p -> true); matches.add(filePath.toFile()); return matches; } else { return Collections.singleton(filePath.toFile()); } } } catch (IOException e) { } String dirPath; String fileNamePattern; int wildcardIndex = pathPattern.indexOf('*'); if (wildcardIndex >= 0) { dirPath = pathPattern.substring(0, wildcardIndex); } else { dirPath = pathPattern; } int lastPathSeparator = Math.max(dirPath.lastIndexOf('/'), dirPath.lastIndexOf('\\')); if (lastPathSeparator == -1) { dirPath = "."; fileNamePattern = pathPattern; } else { dirPath = pathPattern.substring(0, lastPathSeparator); fileNamePattern = pathPattern.substring(lastPathSeparator + 1); } Path dir = resolvePath(baseDir, dirPath); if (!Files.isDirectory(dir)) { return Collections.emptySet(); } try { if (libraryProperty) { return getMatchingLibraries(fileNamePattern, dir); } else { return getMatchingDirs(fileNamePattern, dir); } } catch (IOException e) { throw new IllegalStateException(e); } }

Target:
private static Set<File> getFilesForPattern(Path baseDir, String pathPattern, boolean libraryProperty) { try { Path filePath = resolvePath(baseDir, pathPattern); if ((pathPattern.endsWith(".jar") || pathPattern.endsWith(".zip")) && Files.isRegularFile(filePath)) { return Collections.singleton(filePath.toFile()); } if (Files.isDirectory(filePath)) { return getMatchesInDir(filePath, libraryProperty); } } catch (IOException e) { } String dirPath; String fileNamePattern; int wildcardIndex = pathPattern.indexOf('*'); if (wildcardIndex >= 0) { dirPath = pathPattern.substring(0, wildcardIndex); } else { dirPath = pathPattern; } int lastPathSeparator = Math.max(dirPath.lastIndexOf('/'), dirPath.lastIndexOf('\\')); if (lastPathSeparator == -1) { dirPath = "."; fileNamePattern = pathPattern; } else { dirPath = pathPattern.substring(0, lastPathSeparator); fileNamePattern = pathPattern.substring(lastPathSeparator + 1); } Path dir = resolvePath(baseDir, dirPath); if (!Files.isDirectory(dir)) { return Collections.emptySet(); } try { if (libraryProperty) { return getMatchingLibraries(fileNamePattern, dir); } else { return getMatchingDirs(fileNamePattern, dir); } } catch (IOException e) { throw new IllegalStateException(e); } }
Source:
public static void parser(String[] args) { for (int i = 0; i < args.length; i++) { if (args[i].charAt(0) == '-') { switch (args[i].charAt(1)) { case 't': if (args.length == i + 1 || timeZone != null) { uError(); } else { i++; String[] tzNames = TimeZone.getAvailableIDs(); String TZName = args[i]; for (int j = 0; j < tzNames.length; ++j) { if (TZName.equals(tzNames[j])) { timeZone = TimeZone.getTimeZone(TZName); calendar.setTimeZone(timeZone); } } if (timeZone == null) { System.err.println("Incorrect time zone."); System.exit(1); } } break; case 'm': i++; month = Integer.parseInt(args[i]) - 1; if (calendar.getActualMinimum(Calendar.MONTH) > month || calendar.getActualMaximum(Calendar.MONTH) < month) { uError(); } break; case 'y': i++; year = Integer.parseInt(args[i]) - 1; if (calendar.getActualMinimum(Calendar.YEAR) > year || calendar.getActualMaximum(Calendar.YEAR) < year) { uError(); } break; case 'w': weeksNeeded = true; break; default: uError(); } } else { uError(); } } if (month == null) { month = calendar.get(Calendar.MONTH); } if (year == null) { year = calendar.get(Calendar.YEAR); } }

Target:
public static void parser(String[] args) { for (int i = 0; i < args.length; i++) { if (args[i].charAt(0) == '-') { switch (args[i].charAt(1)) { case 't': if (args.length == i + 1 || timeZone != null) { uError(); } else { i++; String[] timeZoneNames = TimeZone.getAvailableIDs(); String timeZoneName = args[i]; for (String timeZoneName1 : timeZoneNames) { if (timeZoneName.equals(timeZoneName1)) { timeZone = TimeZone.getTimeZone(timeZoneName); calendar.setTimeZone(timeZone); } } if (timeZone == null) { System.err.println("Incorrect time zone."); System.exit(1); } } break; case 'm': i++; if (args.length <= i || month != null) { uError(); } else { try { month = Integer.parseInt(args[i]) - 1; } catch (NumberFormatException exception) { System.err.println(exception.getMessage()); System.exit(1); } } if (calendar.getActualMinimum(Calendar.MONTH) > month || calendar.getActualMaximum(Calendar.MONTH) < month) { uError(); } break; case 'y': i++; year = Integer.parseInt(args[i]) - 1; if (calendar.getActualMinimum(Calendar.YEAR) > year || calendar.getActualMaximum(Calendar.YEAR) < year) { uError(); } break; case 'w': weeksNeeded = true; break; default: uError(); } } else { uError(); } } if (month == null) { month = calendar.get(Calendar.MONTH); } if (year == null) { year = calendar.get(Calendar.YEAR); } }
Source:
public static void loadTestBook(final Ds3Client client, final String fileName, final String objectName, final String bucketName) throws IOException, URISyntaxException { final Path filePath = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + fileName); final Ds3Object obj = new Ds3Object(objectName, Files.size(filePath)); final Ds3ClientHelpers helpers = Ds3ClientHelpers.wrap(client); final Ds3ClientHelpers.Job job = helpers.startWriteJob(bucketName, ImmutableList.of(obj)); job.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() { @Override public SeekableByteChannel buildChannel(final String key) throws IOException { return FileChannel.open(filePath, StandardOpenOption.READ); } }); }

Target:
public static void loadTestBook(final Ds3Client client, final String fileName, final String objectName, final String bucketName) throws IOException, URISyntaxException { final Path filePath = ResourceUtils.loadFileResource(RESOURCE_BASE_NAME + fileName); final Ds3Object obj = new Ds3Object(objectName, Files.size(filePath)); final Ds3ClientHelpers helpers = Ds3ClientHelpers.wrap(client); final Ds3ClientHelpers.Job job = helpers.startWriteJob(bucketName, ImmutableList.of(obj)); job.transfer(key -> FileChannel.open(filePath, StandardOpenOption.READ)); }
Source:
private void assertMultiPoint(String expectedWkt, String... pointWkts) { assertFunction(format("ST_MultiPoint(array[%s])", ImmutableList.copyOf(pointWkts).stream() .map(wkt -> wkt.equalsIgnoreCase("null") ? "null" : format("ST_GeometryFromText('%s')", wkt)) .collect(Collectors.joining(","))), GEOMETRY, expectedWkt); }

Target:
private void assertMultiPoint(String expectedWkt, String... pointWkts) { assertFunction( format( "ST_MultiPoint(array[%s])", Arrays.stream(pointWkts) .map(wkt -> wkt == null ? "null" : format("ST_GeometryFromText('%s')", wkt)) .collect(Collectors.joining(","))), GEOMETRY, expectedWkt); }
Source:
public Map<String, Object> doLogoutAs(final String principalUserId, final User currentLoginAsUser, final String serverName) throws DotDataException, DotSecurityException { User systemUser = this.userAPI.getSystemUser(); if (!UtilMethods.isSet(principalUserId)) { throw new DotDataException("Current user [" + currentLoginAsUser.getUserId() + "] is not logged in as a different user."); } Host host = null; if (UtilMethods.isSet(serverName)) { host = hostWebAPI.findByName(serverName, systemUser, false); if (host == null) { host = hostWebAPI.findByAlias(serverName, systemUser, false); } if (host == null) { host = hostWebAPI.findDefaultHost(systemUser, false); } } else { host = hostWebAPI.findDefaultHost(systemUser, false); } Map<String, Object> sessionData = map(com.dotmarketing.util.WebKeys.CURRENT_HOST, host); return sessionData; }

Target:
public Map<String, Object> doLogoutAs(final String principalUserId, final User currentLoginAsUser, final String serverName) throws DotDataException, DotSecurityException { if (!UtilMethods.isSet(principalUserId)) { throw new DotDataException("Current user [" + currentLoginAsUser.getUserId() + "] is not logged in as a different user."); } final User systemUser = this.userAPI.getSystemUser(); Host host = null; if (UtilMethods.isSet(serverName)) { host = this.hostWebAPI.findByName(serverName, systemUser, false); if (host == null) { host = this.hostWebAPI.findByAlias(serverName, systemUser, false); } if (host == null) { host = this.hostWebAPI.findDefaultHost(systemUser, false); } } else { host = this.hostWebAPI.findDefaultHost(systemUser, false); } final Map<String, Object> sessionData = map(com.dotmarketing.util.WebKeys.CURRENT_HOST, host); return sessionData; }
Source:
private void addOvfStoreDiskToDomain(DiskImage ovfDisk) { if (ovfDisk != null) { StorageDomainOvfInfo storageDomainOvfInfo = new StorageDomainOvfInfo(getStorageDomainId(), null, ovfDisk.getId(), StorageDomainOvfInfoStatus.OUTDATED, null); getDbFacade().getStorageDomainOvfInfoDao().save(storageDomainOvfInfo); } }

Target:
private void addOvfStoreDiskToDomain(DiskImage ovfDisk) { StorageDomainOvfInfo storageDomainOvfInfo = new StorageDomainOvfInfo(getStorageDomainId(), null, ovfDisk.getId(), StorageDomainOvfInfoStatus.OUTDATED, null); getDbFacade().getStorageDomainOvfInfoDao().save(storageDomainOvfInfo); }
Source:
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx, Object... nodeOutputs) throws SemanticException { AnnotateStatsProcCtx aspCtx = (AnnotateStatsProcCtx) procCtx; FilterOperator fop = (FilterOperator) nd; Operator<? extends OperatorDesc> parent = fop.getParentOperators().get(0); Statistics parentStats = parent.getStatistics(); List<String> neededCols = null; if (parent instanceof TableScanOperator) { TableScanOperator tsop = (TableScanOperator) parent; neededCols = tsop.getNeededColumns(); } if (parentStats != null) { ExprNodeDesc pred = fop.getConf().getPredicate(); final boolean uniformWithinRange = HiveConf.getBoolVar( aspCtx.getConf(), HiveConf.ConfVars.HIVE_STATS_RANGE_SELECTIVITY_UNIFORM_DISTRIBUTION); aspCtx.clearAffectedColumns(); long newNumRows = evaluateExpression(parentStats, pred, aspCtx, neededCols, fop, parentStats.getNumRows(), uniformWithinRange); Statistics st = parentStats.clone(); if (satisfyPrecondition(parentStats)) { if (newNumRows <= parentStats.getNumRows()) { StatsUtils.updateStats(st, newNumRows, true, fop, aspCtx.getAffectedColumns()); } if (LOG.isDebugEnabled()) { LOG.debug("[0] STATS-" + fop.toString() + ": " + st.extendedToString()); } } else { if (newNumRows <= parentStats.getNumRows()) { StatsUtils.updateStats(st, newNumRows, false, fop); } if (LOG.isDebugEnabled()) { LOG.debug("[1] STATS-" + fop.toString() + ": " + st.extendedToString()); } } st = applyRuntimeStats(aspCtx.getParseContext().getContext(), st, fop); fop.setStatistics(st); aspCtx.setAndExprStats(null); } return null; }

Target:
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx, Object... nodeOutputs) throws SemanticException { AnnotateStatsProcCtx aspCtx = (AnnotateStatsProcCtx) procCtx; FilterOperator fop = (FilterOperator) nd; Operator<? extends OperatorDesc> parent = fop.getParentOperators().get(0); Statistics parentStats = parent.getStatistics(); List<String> neededCols = null; if (parent instanceof TableScanOperator) { TableScanOperator tsop = (TableScanOperator) parent; neededCols = tsop.getNeededColumns(); } if (parentStats != null) { ExprNodeDesc pred = fop.getConf().getPredicate(); aspCtx.clearAffectedColumns(); long newNumRows = evaluateExpression(parentStats, pred, aspCtx, neededCols, fop, parentStats.getNumRows()); Statistics st = parentStats.clone(); if (satisfyPrecondition(parentStats)) { if (newNumRows <= parentStats.getNumRows()) { StatsUtils.updateStats(st, newNumRows, true, fop, aspCtx.getAffectedColumns()); } if (LOG.isDebugEnabled()) { LOG.debug("[0] STATS-" + fop.toString() + ": " + st.extendedToString()); } } else { if (newNumRows <= parentStats.getNumRows()) { StatsUtils.updateStats(st, newNumRows, false, fop); } if (LOG.isDebugEnabled()) { LOG.debug("[1] STATS-" + fop.toString() + ": " + st.extendedToString()); } } st = applyRuntimeStats(aspCtx.getParseContext().getContext(), st, fop); fop.setStatistics(st); aspCtx.setAndExprStats(null); } return null; }
Source:
public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities, Messenger messenger, IBinder binder) { if (!hasWifiNetworkListenPermission(networkCapabilities)) { enforceAccessPermission(); } NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities); restrictRequestUidsForCaller(nc); restrictBackgroundRequestForCaller(nc); ensureValidNetworkSpecifier(networkCapabilities); NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN); NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder); if (VDBG) log("listenForNetwork for " + nri); mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); return networkRequest; }

Target:
public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities, Messenger messenger, IBinder binder) { if (!hasWifiNetworkListenPermission(networkCapabilities)) { enforceAccessPermission(); } NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities); restrictRequestUidsForCaller(nc); restrictBackgroundRequestForCaller(nc); ensureValidNetworkSpecifier(nc); NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN); NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder); if (VDBG) log("listenForNetwork for " + nri); mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri)); return networkRequest; }
Source:
Map<String, Object> getDeviceMetadata() { Map<String, Object> map = new HashMap<>(); map.put("batteryLevel", getBatteryLevel()); map.put("charging", isCharging()); map.put("locationStatus", getLocationStatus()); map.put("networkAccess", getNetworkAccess()); map.put("brand", Build.BRAND); map.put("screenDensity", screenDensity); map.put("dpi", dpi); map.put("emulator", emulator); map.put("screenResolution", screenResolution); return map; }

Target:
Map<String, Object> getDeviceMetadata() { Map<String, Object> map = new HashMap<>(); map.put("batteryLevel", getBatteryLevel()); map.put("charging", isCharging()); map.put("locationStatus", getLocationStatus()); map.put("networkAccess", getNetworkAccess()); map.put("brand", buildInfo.getBrand()); map.put("screenDensity", screenDensity); map.put("dpi", dpi); map.put("emulator", emulator); map.put("screenResolution", screenResolution); return map; }
Source:
private HttpPost createRequest(URL url, String token) throws URISyntaxException { RequestConfig defaultRequestConfig = RequestConfig.custom() .setConnectTimeout(JMeterUtils.getPropDefault("backend_influxdb.connection_timeout", 1000)) .setSocketTimeout(JMeterUtils.getPropDefault("backend_influxdb.socket_timeout", 3000)) .setConnectionRequestTimeout(JMeterUtils.getPropDefault("backend_influxdb.connection_request_timeout", 100)) .build(); HttpPost currentHttpRequest = new HttpPost(url.toURI()); currentHttpRequest.setConfig(defaultRequestConfig); if (token != null) { currentHttpRequest.setHeader("Authorization", "Token " + token); } log.debug("Created InfluxDBMetricsSender with url: {}", url); return currentHttpRequest; }

Target:
private HttpPost createRequest(URL url, String token) throws URISyntaxException { RequestConfig defaultRequestConfig = RequestConfig.custom() .setConnectTimeout(JMeterUtils.getPropDefault("backend_influxdb.connection_timeout", 1000)) .setSocketTimeout(JMeterUtils.getPropDefault("backend_influxdb.socket_timeout", 3000)) .setConnectionRequestTimeout(JMeterUtils.getPropDefault("backend_influxdb.connection_request_timeout", 100)) .build(); HttpPost currentHttpRequest = new HttpPost(url.toURI()); currentHttpRequest.setConfig(defaultRequestConfig); if (StringUtils.isNotBlank(token)) { currentHttpRequest.setHeader(AUTHORIZATION_HEADER_NAME, AUTHORIZATION_HEADER_VALUE + token); } log.debug("Created InfluxDBMetricsSender with url: {}", url); return currentHttpRequest; }
Source:
private void compareTracedItems(Resource changedResource) { TracePersistenceAdapter persistenceAdapter = ExtensionPointHelper.getTracePersistenceAdapter().get(); ResourceSetImpl newResourceSet = new ResourceSetImpl(); EObject traceModel = persistenceAdapter.getTraceModel(newResourceSet); if (traceModel.eContents().size() > 0) { IPath path = new Path(EcoreUtil.getURI(traceModel).toPlatformString(false)); IFile traceContainer = ResourcesPlugin.getWorkspace().getRoot().getFile(path); TraceMetaModelAdapter traceMetamodelAdapter = ExtensionPointHelper.getTraceMetamodelAdapter().get(); List<Connection> connections = traceMetamodelAdapter .getAllTraceLinks(persistenceAdapter.getTraceModel(new ResourceSetImpl())); if (!connections.isEmpty()) { for (Connection c : connections) { List<EObject> tempList = new ArrayList<>(); tempList.add(c.getOrigin()); tempList.addAll(c.getTargets()); for (EObject tracedItem : tempList) { Resource oldResource = tracedItem.eResource(); if (oldResource == null) oldResource = newResourceSet.getResource(EcoreUtil.getURI(tracedItem).trimFragment(), true); if (oldResource != null) { if (CapraNotificationHelper.getFileUri(oldResource) .equals(CapraNotificationHelper.getFileUri(changedResource))) { IComparisonScope scope = new DefaultComparisonScope(changedResource, oldResource, null); Comparison comparison = EMFCompare.builder().build().compare(scope); for (Match match : comparison.getMatches()) resolveMatch(tracedItem, match, null, traceContainer); } } } } } } }

Target:
private void compareTracedItems(Resource changedResource) { TracePersistenceAdapter persistenceAdapter = ExtensionPointHelper.getTracePersistenceAdapter().get(); ResourceSetImpl newResourceSet = new ResourceSetImpl(); EObject traceModel = persistenceAdapter.getTraceModel(newResourceSet); if (traceModel!=null && traceModel.eContents().size() > 0) { IPath path = new Path(EcoreUtil.getURI(traceModel).toPlatformString(false)); IFile traceContainer = ResourcesPlugin.getWorkspace().getRoot().getFile(path); TraceMetaModelAdapter traceMetamodelAdapter = ExtensionPointHelper.getTraceMetamodelAdapter().get(); List<Connection> connections = traceMetamodelAdapter .getAllTraceLinks(persistenceAdapter.getTraceModel(new ResourceSetImpl())); if (!connections.isEmpty()) { for (Connection c : connections) { List<EObject> tempList = new ArrayList<>(); tempList.add(c.getOrigin()); tempList.addAll(c.getTargets()); for (EObject tracedItem : tempList) { Resource oldResource = tracedItem.eResource(); if (oldResource == null) oldResource = newResourceSet.getResource(EcoreUtil.getURI(tracedItem).trimFragment(), true); if (oldResource != null) { if (CapraNotificationHelper.getFileUri(oldResource) .equals(CapraNotificationHelper.getFileUri(changedResource))) { IComparisonScope scope = new DefaultComparisonScope(changedResource, oldResource, null); Comparison comparison = EMFCompare.builder().build().compare(scope); for (Match match : comparison.getMatches()) resolveMatch(tracedItem, match, null, traceContainer); } } } } } } }
Source:
public static void sync(String modid, Config.Type type) { FMLLog.log.debug("Attempting to inject @Config classes into for type {}", modid, type); ClassLoader mcl = Loader.instance().getModClassLoader(); File configDir = Loader.instance().getConfigDir(); Multimap<Config.Type, ASMData> map = asm_data.get(modid); if (map == null) return; for (ASMData targ : map.get(type)) { try { Class<?> cls = Class.forName(targ.getClassName(), true, mcl); Set<Class<?>> modConfigClasses = MOD_CONFIG_CLASSES.computeIfAbsent(modid, k -> Sets.<Class<?>>newHashSet()); modConfigClasses.add(cls); String name = (String)targ.getAnnotationInfo().get("name"); if (name == null) name = modid; String category = (String)targ.getAnnotationInfo().get("category"); if (category == null) category = "general"; File file = new File(configDir, name + ".cfg"); Configuration cfg = CONFIGS.get(file.getAbsolutePath()); if (cfg == null) { cfg = new Configuration(file); cfg.load(); CONFIGS.put(file.getAbsolutePath(), cfg); } sync(cfg, cls, modid, category, !LoaderState.AVAILABLE.equals(Loader.instance().getLoaderState()), null); cfg.save(); } catch (Exception e) { FMLLog.log.error("An error occurred trying to load a config for into {}", targ.getClassName(), e); throw new LoaderException(e); } } }

Target:
public static void sync(String modid, Config.Type type) { FMLLog.log.debug("Attempting to inject @Config classes into for type {}", modid, type); ClassLoader mcl = Loader.instance().getModClassLoader(); File configDir = Loader.instance().getConfigDir(); Multimap<Config.Type, ASMData> map = asm_data.get(modid); if (map == null) return; for (ASMData targ : map.get(type)) { try { Class<?> cls = Class.forName(targ.getClassName(), true, mcl); Set<Class<?>> modConfigClasses = MOD_CONFIG_CLASSES.computeIfAbsent(modid, k -> Sets.<Class<?>>newHashSet()); modConfigClasses.add(cls); String name = (String)targ.getAnnotationInfo().get("name"); if (name == null) name = modid; String category = (String)targ.getAnnotationInfo().get("category"); if (category == null) category = "general"; File file = new File(configDir, name + ".cfg"); Configuration cfg = CONFIGS.get(file.getAbsolutePath()); if (cfg == null) { cfg = new Configuration(file); cfg.load(); CONFIGS.put(file.getAbsolutePath(), cfg); } sync(cfg, cls, modid, category, !Loader.instance().hasReachedState(LoaderState.AVAILABLE), null); cfg.save(); } catch (Exception e) { FMLLog.log.error("An error occurred trying to load a config for into {}", targ.getClassName(), e); throw new LoaderException(e); } } }
Source:
public Optional<Payload> payloadFrom(String broadcastImi, ItemBroadcastHierarchy broadcastHierarchy) throws PayloadGenerationException { try { JAXBElement<TVAMainType> tvaElem = generator.generateBroadcastTVAFrom(broadcastHierarchy, broadcastImi); if (hasPCrid(broadcastHierarchy.broadcast())) { if (rollingWindowBroadcastEventDeduplicator.shouldUpload(tvaElem)) { rollingWindowBroadcastEventDeduplicator.recordUpload(tvaElem, broadcastHierarchy.broadcast()); } else { log.trace("Not uploading broadcast, since its ProgramURL has already been associated with this service ID and item"); return Optional.absent(); } } return Optional.of(new Payload(converter.convert(tvaElem), clock.now())); } catch (TvaGenerationException e) { throw new PayloadGenerationException(e); } }

Target:
public Optional<Payload> payloadFrom(String broadcastImi, ItemBroadcastHierarchy broadcastHierarchy) throws PayloadGenerationException { try { JAXBElement<TVAMainType> tvaElem = generator.generateBroadcastTVAFrom(broadcastHierarchy, broadcastImi); if (hasPCrid(broadcastHierarchy.broadcast())) { if (broadcastEventDeduplicator.shouldUpload(tvaElem)) { broadcastEventDeduplicator.recordUpload(tvaElem, broadcastHierarchy.broadcast()); } else { return Optional.absent(); } } return Optional.of(new Payload(converter.convert(tvaElem), clock.now())); } catch (TvaGenerationException e) { throw new PayloadGenerationException(e); } }
Source:
public List<E> filterByName(List<E> list, String contains) { return list .stream() .filter(e -> e.getName().toLowerCase().replaceAll("\\s+", "").contains(contains.toLowerCase().replaceAll("\\s+", ""))) .sorted(comparing(E::getName)) .collect(Collectors.toList()); }

Target:
public List<E> filterByName(List<E> list, String contains) { return list .stream() .filter(e -> containsIgnoreCaseIgnoreSpaces(e.getName(), contains)) .sorted(comparing(E::getName)) .collect(Collectors.toList()); }
Source:
static URL pathToURL(String path) throws MalformedURLException { if (path.isEmpty()) { throw new MalformedURLException("JENKINS-37599: empty classpath entries not allowed"); } try { return new URL(path); } catch (MalformedURLException x) { File f = new File(path); if (f.isAbsolute()) { return f.toURI().toURL(); } else { throw new MalformedURLException("classpath entries must be URLs or absolute file paths"); } } }

Target:
static URL pathToURL(String path) throws MalformedURLException { if (path.isEmpty()) { throw new MalformedURLException("JENKINS-37599: empty classpath entries not allowed"); } try { return new URL(path); } catch (MalformedURLException x) { File f = new File(path); if (f.isAbsolute()) { return f.toURI().toURL(); } else { throw new MalformedURLException("Classpath entry ‘" + path + "’ does not look like either a URL or an absolute file path"); } } }
Source:
private static <T> T doAsUser(UserGroupInformation ugi, PrivilegedExceptionAction<T> action) throws IOException { try { return ugi.doAs(action); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new IOException(ie); } }

Target:
private static <T> T doAsUser(UserGroupInformation ugi, PrivilegedExceptionAction<T> action) throws IOException { try { return ugi.doAs(action); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new InterruptedIOException("Action interrupted"); } }
Source:
protected void internalStop(Map<String, String> stopOptions) throws InfrastructureException { if (startSynchronizer.startThread != null) { startSynchronizer.interruptStartThread(); try { startSynchronizer.await(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new InfrastructureException("Interrupted while waiting for start task cancellation", ex); } } else { destroyRuntime(stopOptions); } }

Target:
protected void internalStop(Map<String, String> stopOptions) throws InfrastructureException { if (startSynchronizer.interrupt()) { try { startSynchronizer.await(); } catch (RuntimeStartInterruptedException ex) { } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new InfrastructureException("Interrupted while waiting for start task cancellation", ex); } } else { destroyRuntime(stopOptions); } }
Source:
AzureFileSystem(AzureFileSystemProvider parentFileSystemProvider, String accountName, Map<String, ?> config) throws IOException { if (Objects.isNull(parentFileSystemProvider)) { throw Utility.logError(logger, new IllegalArgumentException("AzureFileSystem cannot be instantiated" + " without a parent FileSystemProvider")); } this.parentFileSystemProvider = parentFileSystemProvider; try { this.blobServiceClient = this.buildBlobServiceClient(accountName, config); Object blockSize = config.get(AZURE_STORAGE_UPLOAD_BLOCK_SIZE); if (blockSize instanceof Integer) { this.blockSize = Long.valueOf((Integer) blockSize); } else { this.blockSize = (Long) blockSize; } this.downloadResumeRetries = (Integer) config.get(AZURE_STORAGE_DOWNLOAD_RESUME_RETRIES); this.fileStores = this.initializeFileStores(config); } catch (RuntimeException e) { throw Utility.logError(logger, new IllegalArgumentException("There was an error parsing the configurations " + "map. Please ensure all fields are set to a legal value of the correct type.")); } catch (IOException e) { throw Utility.logError(logger, new IOException("Initializing FileStores failed. FileSystem could not be opened.", e)); } this.closed = false; }

Target:
AzureFileSystem(AzureFileSystemProvider parentFileSystemProvider, String accountName, Map<String, ?> config) throws IOException { if (Objects.isNull(parentFileSystemProvider)) { throw LoggingUtility.logError(logger, new IllegalArgumentException("AzureFileSystem cannot be instantiated" + " without a parent FileSystemProvider")); } this.parentFileSystemProvider = parentFileSystemProvider; try { this.blobServiceClient = this.buildBlobServiceClient(accountName, config); Object blockSize = config.get(AZURE_STORAGE_UPLOAD_BLOCK_SIZE); if (blockSize instanceof Integer) { this.blockSize = Long.valueOf((Integer) blockSize); } else { this.blockSize = (Long) blockSize; } this.downloadResumeRetries = (Integer) config.get(AZURE_STORAGE_DOWNLOAD_RESUME_RETRIES); this.fileStores = this.initializeFileStores(config); } catch (RuntimeException e) { throw LoggingUtility.logError(logger, new IllegalArgumentException("There was an error parsing the " + "configurations map. Please ensure all fields are set to a legal value of the correct type.")); } catch (IOException e) { throw LoggingUtility.logError(logger, new IOException("Initializing FileStores failed. FileSystem could not be opened.", e)); } this.closed = false; }
Source:
public void testCreateRequestMessageBuilderPublishedAtIsAfterCreatedAt() { String bodyText = "body text"; Payload requestPayload = TestUtils.createPayloadWithTextBody(bodyText); Builder requestMessageBuilder = TestUtils.createMessageBuilder(); Message message = messageFactory.createRequestMessage(requestMessageBuilder, requestPayload); assertTrue(message.getMeta().getPublishedAt().isAfter(message.getMeta().getCreatedAt())); }

Target:
public void testCreateRequestMessageBuilderPublishedAtIsAfterCreatedAt() { String bodyText = "body text"; Payload requestPayload = TestUtils.createPayloadWithTextBody(bodyText); Builder requestMessageBuilder = TestUtils.createMessageBuilder(Clock.systemDefaultZone()); Message message = messageFactory.createRequestMessage(requestMessageBuilder, requestPayload); Instant publishedAt = message.getMeta().getPublishedAt(); Instant createdAt = message.getMeta().getCreatedAt(); assertTrue(publishedAt.isAfter(createdAt)); }
Source:
public void checkIn(Exchange exchange) throws Exception { validateRequiredHeader(exchange, CamelCMISConstants.CMIS_OBJECT_ID); Message message = exchange.getIn(); String objectId = message.getHeader(CamelCMISConstants.CMIS_OBJECT_ID, String.class); String checkInComment = message.getHeader(PropertyIds.CHECKIN_COMMENT, String.class); String fileName = message.getHeader(PropertyIds.NAME, String.class); String mimeType = getMimeType(message); InputStream inputStream = (InputStream) message.getBody(); byte[] bytes = StreamUtils.copyToByteArray(inputStream); Document document = (Document) getSessionFacade().getObjectById(objectId); Map<String, Object> properties = filterTypeProperties(message.getHeaders()); ContentStream contentStream = getSessionFacade().createContentStream(fileName, bytes, mimeType); document.checkIn(true, properties, contentStream, checkInComment); }

Target:
public void checkIn(Exchange exchange) throws Exception { validateRequiredHeader(exchange, CamelCMISConstants.CMIS_OBJECT_ID); Message message = exchange.getIn(); String objectId = message.getHeader(CamelCMISConstants.CMIS_OBJECT_ID, String.class); String checkInComment = message.getHeader(PropertyIds.CHECKIN_COMMENT, String.class); String fileName = message.getHeader(PropertyIds.NAME, String.class); String mimeType = getMimeType(message); InputStream inputStream = (InputStream) message.getBody(); byte[] bytes = message.getBody(byte[].class); Document document = (Document) getSessionFacade().getObjectById(objectId); Map<String, Object> properties = filterTypeProperties(message.getHeaders()); ContentStream contentStream = getSessionFacade().createContentStream(fileName, bytes, mimeType); document.checkIn(true, properties, contentStream, checkInComment); }
Source:
private VXQueryIndexingDataSource(int id, String collection, String index, Object[] types, String functionCall) { this.dataSourceId = id; this.collectionName = collection; this.indexName = index; this.function = functionCall; collectionPartitions = collectionName.split(DELIMITER); this.types = types; final IPhysicalPropertiesVector vec = new StructuralPropertiesVector( new RandomPartitioningProperty(new CollectionFileDomain(indexName)), new ArrayList<ILocalStructuralProperty>()); propProvider = new IDataSourcePropertiesProvider() { @Override public IPhysicalPropertiesVector computePropertiesVector(List<LogicalVariable> scanVariables) { return vec; } }; this.tag = null; this.childSeq = new ArrayList<>(); }

Target:
private VXQueryIndexingDataSource(int id, String collection, String index, Object[] types, String functionCall) { this.dataSourceId = id; this.collectionName = collection; this.elementPath = index; this.function = functionCall; this.collectionPartitions = collectionName.split(DELIMITER); this.types = types; final IPhysicalPropertiesVector vec = new StructuralPropertiesVector( new RandomPartitioningProperty(new CollectionFileDomain(collectionName)), new ArrayList<>()); propProvider = new IDataSourcePropertiesProvider() { @Override public IPhysicalPropertiesVector computePropertiesVector(List<LogicalVariable> scanVariables) { return vec; } }; this.tag = null; this.childSeq = new ArrayList<>(); }
Source:
private static LwM2mNode parseJSON(LwM2mJsonObject jsonObject, LwM2mPath path, LwM2mModel model) throws InvalidValueException { LOG.trace("Parsing JSON content for path {}: {}", path, jsonObject); if (path.isObject()) { throw new InvalidValueException("Not yet implemented: " + " Object Path ", path); } else if (path.isObjectInstance()) { Map<Integer,LwM2mResource> resourceMap = parseJsonPayLoadLwM2mResources(jsonObject, path, model); LwM2mResource[] resources = new LwM2mResource[resourceMap.size()]; int k=0; for (Entry<Integer,LwM2mResource> entry : resourceMap.entrySet()) { LwM2mResource resource = entry.getValue(); resources[k] = resource; k++; } return new LwM2mObjectInstance(path.getObjectInstanceId(), resources); } else { Map<Integer,LwM2mResource> resourceMap = parseJsonPayLoadLwM2mResources(jsonObject, path, model); LwM2mResource resource = resourceMap.get(0); return resource; } }

Target:
private static LwM2mNode parseJSON(LwM2mJsonObject jsonObject, LwM2mPath path, LwM2mModel model) throws InvalidValueException, IllegalStateException { LOG.trace("Parsing JSON content for path {}: {}", path, jsonObject); if (path.isObject()) { throw new IllegalStateException("Not implemented"); } else if (path.isObjectInstance()) { Map<Integer,LwM2mResource> resourceMap = parseJsonPayLoadLwM2mResources(jsonObject, path, model); LwM2mResource[] resources = new LwM2mResource[resourceMap.size()]; int k=0; for (Entry<Integer,LwM2mResource> entry : resourceMap.entrySet()) { LwM2mResource resource = entry.getValue(); resources[k] = resource; k++; } return new LwM2mObjectInstance(path.getObjectInstanceId(), resources); } else { Map<Integer,LwM2mResource> resourceMap = parseJsonPayLoadLwM2mResources(jsonObject, path, model); LwM2mResource resource = resourceMap.get(0); return resource; } }
Source:
protected Iterable<IAnalysisModule> getDependentAnalyses() { ITmfTrace trace = getTrace(); if (trace != null) { LatencyAnalysis module = checkNotNull(TmfTraceUtils.getAnalysisModuleOfClass(trace, LatencyAnalysis.class, checkNotNull(LatencyAnalysis.ID))); fLatencyModule = module; return checkNotNull(ImmutableList.of((IAnalysisModule) module)); } return super.getDependentAnalyses(); }

Target:
protected Iterable<IAnalysisModule> getDependentAnalyses() { ITmfTrace trace = getTrace(); if (trace != null) { LatencyAnalysis module = TmfTraceUtils.getAnalysisModuleOfClass(trace, LatencyAnalysis.class, LatencyAnalysis.ID); if (module == null) { Activator.getDefault().logError("Could not find expected module of class LatencyAnalysis"); throw new IllegalStateException(); } fLatencyModule = module; return checkNotNull(ImmutableList.of(module)); } return super.getDependentAnalyses(); }
Source:
private void checkForDefaultListAndAddIfNeeded(List<ReadingList> lists, SQLiteDatabase db) { if (lists.size() == 0 || !dbHasSavedList(lists)) { createList("", context.getString(R.string.default_list_desc)); try (Cursor cursor = db.query(ReadingListContract.TABLE, null, null, null, null, null, null)) { while (cursor.moveToNext()) { ReadingList list = ReadingList.DATABASE_TABLE.fromCursor(cursor); lists.add(list); } } } }

Target:
private void checkForDefaultListAndAddIfNeeded(List<ReadingList> lists, SQLiteDatabase db) { if (lists.size() == 0 || !listCollectionContainsDefault(lists)) { createList("", context.getString(R.string.default_list_desc)); try (Cursor cursor = db.query(ReadingListContract.TABLE, null, null, null, null, null, null)) { while (cursor.moveToNext()) { ReadingList list = ReadingList.DATABASE_TABLE.fromCursor(cursor); lists.add(list); } } } }
Source:
void refreshTopicPartitions() throws InterruptedException, ExecutionException { knownSourceTopicPartitions = findSourceTopicPartitions(); knownTargetTopicPartitions = findExistingTargetTopicPartitions(); List<TopicPartition> targetTopicPartitionsUpstream = knownTargetTopicPartitions.stream() .map(x -> new TopicPartition(replicationPolicy.upstreamTopic(x.topic()), x.partition())) .collect(Collectors.toList()); Set<TopicPartition> newTopicPartitions = new HashSet<>(); newTopicPartitions.addAll(knownSourceTopicPartitions); newTopicPartitions.removeAll(targetTopicPartitionsUpstream); Set<TopicPartition> deadTopicPartitions = new HashSet<>(); deadTopicPartitions.addAll(targetTopicPartitionsUpstream); deadTopicPartitions.removeAll(knownSourceTopicPartitions); if (!newTopicPartitions.isEmpty() || !deadTopicPartitions.isEmpty()) { log.info("Found topic-partitions on {}. are new. were removed. Previously had {}.", knownSourceTopicPartitions.size(), sourceAndTarget.source(), newTopicPartitions.size(), deadTopicPartitions.size(), knownSourceTopicPartitions.size()); log.trace("Found new topic-partitions: {}", newTopicPartitions); computeAndCreateTopicPartitions(); context.requestTaskReconfiguration(); } }

Target:
void refreshTopicPartitions() throws InterruptedException, ExecutionException { knownSourceTopicPartitions = findSourceTopicPartitions(); knownTargetTopicPartitions = findTargetTopicPartitions(); List<TopicPartition> upstreamTargetTopicPartitions = knownTargetTopicPartitions.stream() .map(x -> new TopicPartition(replicationPolicy.upstreamTopic(x.topic()), x.partition())) .collect(Collectors.toList()); Set<TopicPartition> newTopicPartitions = new HashSet<>(); newTopicPartitions.addAll(knownSourceTopicPartitions); newTopicPartitions.removeAll(upstreamTargetTopicPartitions); Set<TopicPartition> deadTopicPartitions = new HashSet<>(); deadTopicPartitions.addAll(upstreamTargetTopicPartitions); deadTopicPartitions.removeAll(knownSourceTopicPartitions); if (!newTopicPartitions.isEmpty() || !deadTopicPartitions.isEmpty()) { log.info("Found topic-partitions on {}. are new. were removed. Previously had {}.", knownSourceTopicPartitions.size(), sourceAndTarget.source(), newTopicPartitions.size(), deadTopicPartitions.size(), knownSourceTopicPartitions.size()); log.trace("Found new topic-partitions: {}", newTopicPartitions); computeAndCreateTopicPartitions(); context.requestTaskReconfiguration(); } }
Source:
private void setCacheSize(Preference preference) { long bytes = getCacheSize(Glide.getPhotoCacheDir(getActivity())); preference.setSummary(FileUtils.byteCountToDisplaySize(bytes)); }

Target:
private void setCacheSize(Preference preference) { subscriptions.add(Single.<Long>create(subscriber -> { File dir = Glide.getPhotoCacheDir(getActivity()); subscriber.onSuccess(getCacheSize(dir)); }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(bytes -> { String humanReadableSize = FileUtils.byteCountToDisplaySize(bytes); preference.setSummary(humanReadableSize); })); }