diff --git "a/kotlin_code_documentation_train.tsv" "b/kotlin_code_documentation_train.tsv" new file mode 100644--- /dev/null +++ "b/kotlin_code_documentation_train.tsv" @@ -0,0 +1,2004 @@ +code_function document +@Throws(IOException::class) fun execute(): Response actual fun enqueue(responseCallback: Callback) actual fun cancel() actual fun isExecuted(): Boolean actual fun isCanceled(): Boolean fun timeout(): Timeout public actual override fun clone(): Call actual fun interface Factory { actual fun newCall(request: Request): Call } } "Invokes the request immediately, and blocks until the response can be processed or is in error.To avoid leaking resources callers should close the [Response] which in turn will close the underlying [ResponseBody]. The caller may read the response body with the response's [Response.body] method. To avoid leaking resources callers must [close the response body][ResponseBody] or the response. Note that transport-layer success (receiving a HTTP response code, headers and body) does not necessarily indicate application-layer success: `response` may still indicate an unhappy HTTP response code like 404 or 500. @throws IOException if the request could not be executed due to cancellation, a connectivity problem or timeout. Because networks can fail during an exchange, it is possible that the remote server accepted the request before the failure. @throws IllegalStateException when the call has already been executed." +"class Handshake internal constructor( @get:JvmName(""tlsVersion"") val tlsVersion: TlsVersion, @get:JvmName(""cipherSuite"") val cipherSuite: CipherSuite, @get:JvmName(""localCertificates"") val localCertificates: List, peerCertificatesFn: () -> List ) { @get:JvmName(""peerCertificates"") val peerCertificates: List by lazy { try { peerCertificatesFn() } catch (spue: SSLPeerUnverifiedException) { listOf() } } @JvmName(""-deprecated_tlsVersion"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""tlsVersion""), level = DeprecationLevel.ERROR) fun tlsVersion(): TlsVersion = tlsVersion @JvmName(""-deprecated_cipherSuite"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""cipherSuite""), level = DeprecationLevel.ERROR) fun cipherSuite(): CipherSuite = cipherSuite @JvmName(""-deprecated_peerCertificates"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""peerCertificates""), level = DeprecationLevel.ERROR) fun peerCertificates(): List = peerCertificates /** Returns the remote peer's principle, or null if that peer is anonymous. */ @get:JvmName(""peerPrincipal"") val peerPrincipal: Principal? get() = (peerCertificates.firstOrNull() as? X509Certificate)?.subjectX500Principal @JvmName(""-deprecated_peerPrincipal"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""peerPrincipal""), level = DeprecationLevel.ERROR) fun peerPrincipal(): Principal? = peerPrincipal @JvmName(""-deprecated_localCertificates"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""localCertificates""), level = DeprecationLevel.ERROR) fun localCertificates(): List = localCertificates @get:JvmName(""localPrincipal"") val localPrincipal: Principal? get() = (localCertificates.firstOrNull() as? X509Certificate)?.subjectX500Principal @JvmName(""-deprecated_localPrincipal"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""localPrincipal""), level = DeprecationLevel.ERROR) fun localPrincipal(): Principal? = localPrincipal override fun equals(other: Any?): Boolean { return other is Handshake && other.tlsVersion == tlsVersion && other.cipherSuite == cipherSuite && other.peerCertificates == peerCertificates && other.localCertificates == localCertificates } override fun hashCode(): Int { var result = 17 result = 31 * result + tlsVersion.hashCode() result = 31 * result + cipherSuite.hashCode() result = 31 * result + peerCertificates.hashCode() result = 31 * result + localCertificates.hashCode() return result } override fun toString(): String { val peerCertificatesString = peerCertificates.map { it.name }.toString() return ""Handshake{"" + ""tlsVersion=$tlsVersion "" + ""cipherSuite=$cipherSuite "" + ""peerCertificates=$peerCertificatesString "" + ""localCertificates=${localCertificates.map { it.name }}}"" } private val Certificate.name: String get() = when (this) { is X509Certificate -> subjectDN.toString() else -> type } companion object { @Throws(IOException::class) @JvmStatic @JvmName(""get"") fun SSLSession.handshake(): Handshake { val cipherSuite = when (val cipherSuiteString = checkNotNull(cipherSuite) { ""cipherSuite == null"" }) { ""TLS_NULL_WITH_NULL_NULL"", ""SSL_NULL_WITH_NULL_NULL"" -> { throw IOException(""cipherSuite == $cipherSuiteString"") } else -> CipherSuite.forJavaName(cipherSuiteString) } val tlsVersionString = checkNotNull(protocol) { ""tlsVersion == null"" } if (""NONE"" == tlsVersionString) throw IOException(""tlsVersion == NONE"") val tlsVersion = TlsVersion.forJavaName(tlsVersionString) val peerCertificatesCopy = try { peerCertificates.toImmutableList() } catch (_: SSLPeerUnverifiedException) { listOf() } return Handshake(tlsVersion, cipherSuite, localCertificates.toImmutableList()) { peerCertificatesCopy } } private fun Array?.toImmutableList(): List { return if (this != null) { immutableListOf(*this) } else { emptyList() } } @Throws(IOException::class) @JvmName(""-deprecated_get"") @Deprecated( message = ""moved to extension function"", replaceWith = ReplaceWith(expression = ""sslSession.handshake()""), level = DeprecationLevel.ERROR) fun get(sslSession: SSLSession) = sslSession.handshake() @JvmStatic fun get( tlsVersion: TlsVersion, cipherSuite: CipherSuite, peerCertificates: List, localCertificates: List ): Handshake { val peerCertificatesCopy = peerCertificates.toImmutableList() return Handshake(tlsVersion, cipherSuite, localCertificates.toImmutableList()) { peerCertificatesCopy } } } }" "A record of a TLS handshake. For HTTPS clients, the client is *local* and the remote server is its *peer*. This value object describes a completed handshake. Use [ConnectionSpec] to set policy for new handshakes." +"fun interface Dns {@Throws(UnknownHostException::class) fun lookup(hostname: String): List companion object { @JvmField val SYSTEM: Dns = DnsSystem() private class DnsSystem : Dns { override fun lookup(hostname: String): List { try { return InetAddress.getAllByName(hostname).toList() } catch (e: NullPointerException) { throw UnknownHostException(""Broken system behaviour for dns lookup of $hostname"").apply { initCause(e) } } } } } }" "A domain name service that resolves IP addresses for host names. Most applications will use the [system DNS service][SYSTEM], which is the default. Some applications may provide their own implementation to use a different DNS server, to prefer IPv6 addresses, to prefer IPv4 addresses, or to force a specific known IP address. Implementations of this interface must be safe for concurrent use." +"class Dispatcher() { @get:Synchronized var maxRequests = 64 set(maxRequests) { require(maxRequests >= 1) { ""max < 1: $maxRequests"" } synchronized(this) { field = maxRequests } promoteAndExecute() } @get:Synchronized var maxRequestsPerHost = 5 set(maxRequestsPerHost) { require(maxRequestsPerHost >= 1) { ""max < 1: $maxRequestsPerHost"" } synchronized(this) { field = maxRequestsPerHost } promoteAndExecute() } @set:Synchronized @get:Synchronized var idleCallback: Runnable? = null private var executorServiceOrNull: ExecutorService? = null @get:Synchronized @get:JvmName(""executorService"") val executorService: ExecutorService get() { if (executorServiceOrNull == null) { executorServiceOrNull = ThreadPoolExecutor(0, Int.MAX_VALUE, 60, TimeUnit.SECONDS, SynchronousQueue(), threadFactory(""$okHttpName Dispatcher"", false)) } return executorServiceOrNull!! } private val readyAsyncCalls = ArrayDeque() private val runningAsyncCalls = ArrayDeque() private val runningSyncCalls = ArrayDeque() constructor(executorService: ExecutorService) : this() { this.executorServiceOrNull = executorService } internal fun enqueue(call: AsyncCall) { synchronized(this) { readyAsyncCalls.add(call) if (!call.call.forWebSocket) { val existingCall = findExistingCallWithHost(call.host) if (existingCall != null) call.reuseCallsPerHostFrom(existingCall) } } promoteAndExecute() } private fun findExistingCallWithHost(host: String): AsyncCall? { for (existingCall in runningAsyncCalls) { if (existingCall.host == host) return existingCall } for (existingCall in readyAsyncCalls) { if (existingCall.host == host) return existingCall } return null } @Synchronized fun cancelAll() { for (call in readyAsyncCalls) { call.call.cancel() } for (call in runningAsyncCalls) { call.call.cancel() } for (call in runningSyncCalls) { call.cancel() } } private fun promoteAndExecute(): Boolean { this.assertThreadDoesntHoldLock() val executableCalls = mutableListOf() val isRunning: Boolean synchronized(this) { val i = readyAsyncCalls.iterator() while (i.hasNext()) { val asyncCall = i.next() if (runningAsyncCalls.size >= this.maxRequests) break // Max capacity. if (asyncCall.callsPerHost.get() >= this.maxRequestsPerHost) continue // Host max capacity. i.remove() asyncCall.callsPerHost.incrementAndGet() executableCalls.add(asyncCall) runningAsyncCalls.add(asyncCall) } isRunning = runningCallsCount() > 0 } if (executorService.isShutdown) { for (i in 0 until executableCalls.size) { val asyncCall = executableCalls[i] asyncCall.callsPerHost.decrementAndGet() synchronized(this) { runningAsyncCalls.remove(asyncCall) } asyncCall.failRejected() } idleCallback?.run() } else { for (i in 0 until executableCalls.size) { val asyncCall = executableCalls[i] asyncCall.executeOn(executorService) } } return isRunning } @Synchronized internal fun executed(call: RealCall) { runningSyncCalls.add(call) } internal fun finished(call: AsyncCall) { call.callsPerHost.decrementAndGet() finished(runningAsyncCalls, call) } internal fun finished(call: RealCall) { finished(runningSyncCalls, call) } private fun finished(calls: Deque, call: T) { val idleCallback: Runnable? synchronized(this) { if (!calls.remove(call)) throw AssertionError(""Call wasn't in-flight!"") idleCallback = this.idleCallback } val isRunning = promoteAndExecute() if (!isRunning && idleCallback != null) { idleCallback.run() } } @Synchronized fun queuedCalls(): List { return Collections.unmodifiableList(readyAsyncCalls.map { it.call }) } @Synchronized fun runningCalls(): List { return Collections.unmodifiableList(runningSyncCalls + runningAsyncCalls.map { it.call }) } @Synchronized fun queuedCallsCount(): Int = readyAsyncCalls.size @Synchronized fun runningCallsCount(): Int = runningAsyncCalls.size + runningSyncCalls.size @JvmName(""-deprecated_executorService"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""executorService""), level = DeprecationLevel.ERROR) fun executorService(): ExecutorService = executorService }" "Policy on when async requests are executed. Each dispatcher uses an [ExecutorService] to run calls internally. If you supply your own executor, it should be able to run [the configured maximum][maxRequests] number of calls concurrently." +"class ConnectionPool internal constructor( internal val delegate: RealConnectionPool ) { internal constructor( maxIdleConnections: Int = 5, keepAliveDuration: Long = 5, timeUnit: TimeUnit = TimeUnit.MINUTES, taskRunner: TaskRunner = TaskRunner.INSTANCE, connectionListener: ConnectionListener = ConnectionListener.NONE, ) : this(RealConnectionPool( taskRunner = taskRunner, maxIdleConnections = maxIdleConnections, keepAliveDuration = keepAliveDuration, timeUnit = timeUnit, connectionListener = connectionListener )) constructor( maxIdleConnections: Int = 5, keepAliveDuration: Long = 5, timeUnit: TimeUnit = TimeUnit.MINUTES, connectionListener: ConnectionListener = ConnectionListener.NONE, ) : this( taskRunner = TaskRunner.INSTANCE, maxIdleConnections = maxIdleConnections, keepAliveDuration = keepAliveDuration, timeUnit = timeUnit, connectionListener = connectionListener ) constructor( maxIdleConnections: Int, keepAliveDuration: Long, timeUnit: TimeUnit, ) : this( maxIdleConnections = maxIdleConnections, keepAliveDuration = keepAliveDuration, timeUnit = timeUnit, taskRunner = TaskRunner.INSTANCE, connectionListener = ConnectionListener.NONE ) constructor() : this(5, 5, TimeUnit.MINUTES) fun idleConnectionCount(): Int = delegate.idleConnectionCount() fun connectionCount(): Int = delegate.connectionCount() internal val connectionListener: ConnectionListener get() = delegate.connectionListener fun evictAll() { delegate.evictAll() } }" Manages reuse of HTTP and HTTP/2 connections for reduced network latency. HTTP requests that share the same [Address] may share a [Connection]. This class implements the policy of which connections to keep open for future use. @constructor Create a new connection pool with tuning parameters appropriate for a single-user application. The tuning parameters in this pool are subject to change in future OkHttp releases. Currently this pool holds up to 5 idle connections which will be evicted after 5 minutes of inactivity. +"abstract class ConnectionListener { open fun connectStart(route: Route, call: Call) {} open fun connectFailed(route: Route, call: Call, failure: IOException) {} open fun connectEnd(connection: Connection, route: Route, call: RealCall) {} open fun connectionClosed(connection: Connection) {} open fun connectionAcquired(connection: Connection, call: Call) {} open fun connectionReleased(connection: Connection, call: Call) {} open fun noNewExchanges(connection: Connection) {} companion object { val NONE: ConnectionListener = object : ConnectionListener() {} } }" "Listener for connection events. Extend this class to monitor the new connections and closes.All event methods must execute fast, without external locking, cannot throw exceptions,attempt to mutate the event parameters, or be reentrant back into the client.Any IO - writing to files or network should be done asynchronously." +"@RequiresApi(Build.VERSION_CODES.Q) class AndroidAsyncDns( private val dnsClass: AsyncDns.DnsClass, private val network: Network? = null, ) : AsyncDns { @RequiresApi(Build.VERSION_CODES.Q) private val resolver = DnsResolver.getInstance() private val executor = Executors.newSingleThreadExecutor() override fun query(hostname: String, callback: AsyncDns.Callback) { resolver.query( network, hostname, dnsClass.type, DnsResolver.FLAG_EMPTY, executor, null, object : DnsResolver.Callback> { override fun onAnswer(addresses: List, rCode: Int) { callback.onResponse(hostname, addresses) } override fun onError(e: DnsResolver.DnsException) { callback.onFailure(hostname, UnknownHostException(e.message).apply { initCause(e) }) } } ) } companion object { val IPv4 = AndroidAsyncDns(dnsClass = AsyncDns.DnsClass.IPV4) val IPv6 = AndroidAsyncDns(dnsClass = AsyncDns.DnsClass.IPV6) } }" "DNS implementation based on android.net.DnsResolver, which submits a request for A or AAAA records, and returns the addresses or exception. Two instances must be used to get all results for an address.@param network network to use, if not selects the default network." +Application that sets up Timber in the DEBUG BuildConfig.Read Timber's documentation for production setups. @HiltAndroidApp class TodoApplication : Application() { override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) Timber.plant(DebugTree()) } } +sealed class Async { object Loading : Async() data class Success(val data: T) : Async() } A generic class that holds a loading signal or the result of an async operation. +"@Composable fun LoadingContent( loading: Boolean, empty: Boolean, emptyContent: @Composable () -> Unit, onRefresh: () -> Unit, modifier: Modifier = Modifier, content: @Composable () -> Unit ) { if (empty) { emptyContent() } else { SwipeRefresh( state = rememberSwipeRefreshState(loading), onRefresh = onRefresh, modifier = modifier, content = content, ) } }" "Display an initial empty state or swipe to refresh content. @param loading (state) when true, display a loading spinner over [content] @param empty (state) when true, display [emptyContent] @param emptyContent (slot) the content to display for the empty state @param onRefresh (event) event to request refresh @param modifier the modifier to apply to this layout. @param content (slot) the main content to show" +"class SimpleCountingIdlingResource(private val resourceName: String) : IdlingResource { private val counter = AtomicInteger(0) @Volatile private var resourceCallback: IdlingResource.ResourceCallback? = null override fun getName() = resourceName override fun isIdleNow() = counter.get() == 0 override fun registerIdleTransitionCallback(resourceCallback: IdlingResource.ResourceCallback) { this.resourceCallback = resourceCallback } fun increment() { counter.getAndIncrement() } fun decrement() { val counterVal = counter.decrementAndGet() if (counterVal == 0) { // we've gone from non-zero to zero. That means we're idle now! Tell espresso. resourceCallback?.onTransitionToIdle() } else if (counterVal < 0) { throw IllegalStateException(""Counter has been corrupted!"") } } }" "An simple counter implementation of [IdlingResource] that determines idleness by maintaining an internal counter. When the counter is 0 - it is considered to be idle, when it is non-zero it is not idle. This is very similar to the way a [java.util.concurrent.Semaphore] behaves. This class can then be used to wrap up operations that while in progress should block tests from accessing the UI." +"@AndroidEntryPoint class ReminderReceiver : BroadcastReceiver() { @Inject lateinit var settings: PresentlySettings override fun onReceive(context: Context, intent: Intent) { val openActivityIntent = Intent(context, ContainerActivity::class.java) openActivityIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP //set flag to restart/relaunch the app openActivityIntent.putExtra(fromNotification, true) val pendingIntent = PendingIntent.getActivity( context, ALARM_TYPE_RTC, openActivityIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) createLocalNotification(context, pendingIntent) NotificationScheduler().configureNotifications(context, settings) } private fun createLocalNotification(context: Context, pendingIntent: PendingIntent) { val title = context.getString(R.string.reminder_title) val content = context.getString(R.string.what_are_you_thankful_for_today) val notificationBuilder = NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_app_icon) .setContentTitle(title) .setContentText(content) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .setCategory(Notification.CATEGORY_REMINDER) .setAutoCancel(true) val notificationManager = NotificationManagerCompat.from(context) notificationManager.notify(ALARM_TYPE_RTC, notificationBuilder.build()) } companion object { const val fromNotification = ""fromNotification"" } }" Receives broadcasts from an alarm and creates notifications +"@LogLifecykle @AndroidEntryPoint @Suppress(""TooManyFunctions"") class Activity : AppCompatActivity(), AuthCaster.AuthCasterListener, Flow { @Inject lateinit var authCaster: AuthCaster private val viewModel by viewModels() private lateinit var activityDrawer: DrawerLayout private lateinit var appBarConfiguration: AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { setTheme(R.style.AppTheme_NoActionBar) super.onCreate(savedInstanceState) setContentView(R.layout.activity) activityDrawer = findViewById(R.id.activityDrawer) setSupportActionBar(findViewById(R.id.appBarToolbar)) setupNavController() observeViewModel() authCaster.subscribeToAuthError(this) } private fun observeViewModel() { viewModel.user.observe(this) { user -> if (user is User.Found) { updateAvatar(findViewById(R.id.activityNavigationView), user.domain) } } viewModel.navigation.observe(this) { findNavController(R.id.activityNavigation).navigate(it) } viewModel.snackBar.observe(this) { showSnackbarError() } } private fun showSnackbarError() { findViewById(R.id.activityDrawer)?.let { view -> Snackbar.make(view, R.string.logout_forced, Snackbar.LENGTH_LONG).show() } } override fun onDestroy() { authCaster.unsubscribeFromAuthError(this) super.onDestroy() } override fun onBackPressed() { if (activityDrawer.isDrawerOpen(GravityCompat.START)) { activityDrawer.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } private fun setupNavController() { appBarConfiguration = AppBarConfiguration( setOf( R.id.animeFragment, R.id.mangaFragment, R.id.discoverFragment, R.id.hostFragment, R.id.timelineFragment ), findViewById(R.id.activityDrawer) ) with(findNavController(R.id.activityNavigation)) { findViewById(R.id.activityNavigationView).setupWithNavController(this) setupActionBarWithNavController(this, appBarConfiguration) addOnDestinationChangedListener { _, destination, _ -> when (destination.id) { R.id.credentialsFragment, R.id.syncingFragment -> disableDrawer() else -> enableDrawer() } } } } override fun onSupportNavigateUp() = findNavController(R.id.activityNavigation).navigateUp(appBarConfiguration) override fun unableToRefresh() { Timber.w(""unableToRefresh has occurred"") performLogout(true) } /** * Shows a dialog asking the user if they wish to logout. * This is called from the menu_navigation.xml menu resource in order to allow it to still * function while using the nav component. */ fun requestUserLogout(@Suppress(""UNUSED_PARAMETER"") item: MenuItem) { MaterialDialog(this).show { message(R.string.menu_logout_prompt_message) positiveButton(R.string.menu_logout_prompt_confirm) { performLogout() } negativeButton(R.string.menu_logout_prompt_cancel) lifecycleOwner(this@Activity) } } private fun performLogout(isFailure: Boolean = false) { Timber.w(""Logout called, now attempting"") viewModel.logout(isFailure) } private fun disableDrawer() { supportActionBar?.hide() activityDrawer.setDrawerLockMode(LOCK_MODE_LOCKED_CLOSED) } private fun enableDrawer() { supportActionBar?.show() activityDrawer.setDrawerLockMode(LOCK_MODE_UNLOCKED) } override fun finishLogin() { viewModel.navigateToDefaultHome() } }" "Single host activity for the application, handles all required logic of the activity such as hiding/showing the drawer." +"@HiltWorker class RefreshAuthWorker @AssistedInject constructor( @Assisted appContext: Context, @Assisted workerParams: WorkerParameters, private val userRepo: UserRepository, private val auth: AccessTokenRepository ) : CoroutineWorker(appContext, workerParams) { override suspend fun doWork(): Result { Timber.i(""doWork RefreshAuthWorker"") if (userRepo.retrieveUserId() == null) { Timber.i(""doWork no userId found, so cancelling"") return Result.success() } Timber.i(""doWork userId found, beginning to refresh"") return if (auth.refresh() !is AccessTokenResult.Success) { Result.retry() } else { Result.success() } } }" Worker object that handles updating a users authenticated state. When scheduled to run it will send a request to the [userRepo] to try to refresh the current user. +"@HiltWorker class RefreshSeriesWorker @AssistedInject constructor( @Assisted appContext: Context, @Assisted workerParams: WorkerParameters, private val seriesRepo: SeriesRepository, private val userRepo: UserRepository ) : CoroutineWorker(appContext, workerParams) { override suspend fun doWork(): Result { Timber.i(""doWork RefreshSeriesWorker"") if (userRepo.retrieveUserId() == null) { Timber.i(""doWork no userId found, so cancelling"") return Result.success() } Timber.i(""doWork userId found, beginning to refresh"") return if ( listOf( seriesRepo.refreshAnime(), seriesRepo.refreshManga() ).any { it is Resource.Error } ) { Result.retry() } else { Result.success() } } }" "Worker object that handles updating a users Series if possible. When scheduled to run it will send a request to the [seriesRepo] to try to update the series,letting the [seriesRepo] handle what to do with the results." +"@HiltWorker class RefreshUserWorker @AssistedInject constructor( @Assisted appContext: Context, @Assisted workerParams: WorkerParameters, private val userRepo: UserRepository ) : CoroutineWorker(appContext, workerParams) { override suspend fun doWork(): Result { Timber.i(""doWork RefreshUserWorker"") if (userRepo.retrieveUserId() == null) { Timber.i(""doWork no userId found, so cancelling"") return Result.success() } Timber.i(""doWork userId found, beginning to refresh"") return if (userRepo.refreshUser() is Resource.Error) { Result.retry() } else { Result.success() } } }" Worker object that handles updating the information for a user. When scheduled to run it will send a request to the [userRepo] to try to refresh the current user data. +"class WorkerQueue @Inject constructor(private val workManager: WorkManager) { private val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() fun enqueueAuthRefresh() { val request = PeriodicWorkRequestBuilder(7, TimeUnit.DAYS) .setConstraints(constraints) .addTag(AUTH_REFRESH_TAG) .build() workManager.enqueueUniquePeriodicWork( AUTH_UNIQUE_NAME, ExistingPeriodicWorkPolicy.KEEP, request ) } fun enqueueSeriesRefresh() { val request = PeriodicWorkRequestBuilder(12, TimeUnit.HOURS) .setConstraints(constraints) .addTag(SERIES_REFRESH_TAG) .build() workManager.enqueueUniquePeriodicWork( SERIES_UNIQUE_NAME, ExistingPeriodicWorkPolicy.KEEP, request ) } Starts up the worker to perform user refreshing. fun enqueueUserRefresh() { val request = PeriodicWorkRequestBuilder(12, TimeUnit.HOURS) .setConstraints(constraints) .addTag(USER_REFRESH_TAG) .build() workManager.enqueueUniquePeriodicWork( USER_UNIQUE_NAME, ExistingPeriodicWorkPolicy.KEEP, request ) } }" Allows starting up workers. Starts up the worker to perform auth refreshing. Starts up the worker to perform series refreshing. Starts up the worker to perform user refreshing. +@Module @InstallIn(ViewModelComponent::class) abstract class ActivityModule { companion object { @Provides @Reusable fun providesActivityService(httpClient: OkHttpClient): KitsuActivityService { val moshi = Moshi.Builder() .add(ChangedDataContainerAdapter()) .build() return Retrofit.Builder() .baseUrl(KITSU_URL) .client(httpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() .create(KitsuActivityService::class.java) } } @Binds abstract fun bindApi(api: KitsuActivity): ActivityApi } Provides a Hilt module for usage of [ActivityApi] and Builds and provides the instance of [KitsuActivityService]. Binds [api] to an instance of [ActivityApi]. +@Module @InstallIn(SingletonComponent::class) object WorkerModule { @Provides fun providesWorkManager(@ApplicationContext context: Context) = WorkManager.getInstance(context) } Dagger [Module] to provide the systems [WorkManager] and Provides a [WorkManager] instance to the dependency graph. +@Module @InstallIn(SingletonComponent::class) abstract class UserModule { companion object { @Provides @Reusable fun providesUserService(httpClient: OkHttpClient): KitsuUserService { val moshi = Moshi.Builder() .add(RatingSystemAdapter()) .add(ImageModelAdapter()) .build() return Retrofit.Builder() .baseUrl(KITSU_URL) .client(httpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() .create(KitsuUserService::class.java) } } @Binds abstract fun bindApi(api: KitsuUser): UserApi } Provides a Hilt module for usage of [UserApi]. Builds and provides the instance of [KitsuUserService]. Binds [api] to an instance of [UserApi]. +@Module @InstallIn(SingletonComponent::class) abstract class UrlModule { @Binds abstract fun providesUrlHandler(urlHandler: CustomTabsUrl): UrlHandler } Dagger [Module] to bind [UrlHandler]. Binds the instance of [CustomTabsUrl] to [UrlHandler]. +@Module @InstallIn(SingletonComponent::class) abstract class TrendingModule { companion object { @Provides @Reusable fun providesTrendingService(httpClient: OkHttpClient): KitsuTrendingService { val moshi = Moshi.Builder() .add(ImageModelAdapter()) .add(SeriesStatusAdapter()) .add(SeriesTypeAdapter()) .add(SubtypeAdapter()) .build() return Retrofit.Builder() .baseUrl(KITSU_URL) .client(httpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() .create(KitsuTrendingService::class.java) } } Binds [api] to an instance of [TrendingApi]. @Binds abstract fun bindApi(api: KitsuTrending): TrendingApi } Provides a Hilt module for usage of [TrendingApi]. Builds and provides the instance of [KitsuTrendingService]. +"@Module @InstallIn(SingletonComponent::class) object ServerModule { @Provides @Reusable fun providesAuthenticatedClient( authInjection: AuthInjectionInterceptor, authRefresh: AuthRefreshInterceptor ): OkHttpClient { return OkHttpClient() .newBuilder() .addInterceptor(authInjection) .addInterceptor(authRefresh) .also { httpClient -> if (BuildConfig.DEBUG) { httpClient.addInterceptor( HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } ) } } .build() } } Footer" "Dagger [Module] for the [com.chesire.nekome.server] package and Provides an instance of [OkHttpClient] with the authentication injectors pre-setup, so that authentication is already handled." +"@Module @InstallIn(SingletonComponent::class) object SeriesModule { @Provides fun bindUserProvider(binder: UserProviderBinder): UserProvider = binder @Provides fun provideSeriesRepository( dao: SeriesDao, api: SeriesApi, user: UserProvider, map: SeriesMapper ) = SeriesRepository(dao, api, user, map) }" Dagger [Module] for the [com.chesire.nekome.series] package. Provides a [UserProvider] to the series repository. Provides the [SeriesRepository] to the dependency graph. +@Module @InstallIn(SingletonComponent::class) abstract class SearchModule { companion object { @Provides @Reusable fun providesSearchService(httpClient: OkHttpClient): KitsuSearchService { val moshi = Moshi.Builder() .add(ImageModelAdapter()) .add(SeriesStatusAdapter()) .add(SeriesTypeAdapter()) .add(SubtypeAdapter()) .build() return Retrofit.Builder() .baseUrl(KITSU_URL) .client(httpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() .create(KitsuSearchService::class.java) } } @Binds abstract fun bindApi(api: KitsuSearch): SearchApi } Provides a Hilt module for usage of [SearchApi]. Builds and provides the instance of [KitsuSearchService]. Binds [api] to an instance of [SearchApi]. +@Module @InstallIn(SingletonComponent::class) abstract class LibraryModule { companion object { @Provides @Reusable fun providesLibraryService(httpClient: OkHttpClient): KitsuLibraryService { val moshi = Moshi.Builder() .add(ImageModelAdapter()) .add(SeriesStatusAdapter()) .add(SeriesTypeAdapter()) .add(SubtypeAdapter()) .add(UserSeriesStatusAdapter()) .build() return Retrofit.Builder() .baseUrl(KITSU_URL) .client(httpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() .create(KitsuLibraryService::class.java) } } @Binds abstract fun bindApi(api: KitsuLibrary): SeriesApi } Provides a Hilt module for usage of [SeriesApi]. Builds and provides the instance of [KitsuTrendingService]. Binds [api] to an instance of [SeriesApi]. +@Module @InstallIn(FragmentComponent::class) object FieldProvider { @Provides fun provideFields(): Array = R.string::class.java.fields } Footer Dagger [Module] to provide the application [Field] and Provides the string fields. For use to show the open source libraries used. +@Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Provides @Singleton fun provideDB(@ApplicationContext context: Context) = RoomDB.build(context) @Provides @Singleton fun provideSeries(db: RoomDB) = db.series() @Provides @Singleton fun provideUser(db: RoomDB) = db.user() } Dagger [Module] for the [com.chesire.nekome.database] package and Provides the build [RoomDB] and Provides the [SeriesDao] table from [RoomDB] and Provides the [UserDao] table from [RoomDB]. +@Module @InstallIn(SingletonComponent::class) object CoroutineModule { @Provides @IOContext fun providesIOContext(): CoroutineContext = Dispatchers.IO } Footer Dagger [Module] for providing [CoroutineContext] to parts of the application and Provides a [CoroutineContext] of [Dispatchers.IO] providing the annotation [IOContext] is used. +@Module @InstallIn(SingletonComponent::class) abstract class AuthModule { companion object { @Provides @Reusable fun providesAuthService(): KitsuAuthService { return Retrofit.Builder() .baseUrl(KITSU_URL) .client(OkHttpClient()) .addConverterFactory( MoshiConverterFactory.create(Moshi.Builder().build()) ) .build() .create(KitsuAuthService::class.java) } } @Binds abstract fun bindApi(api: KitsuAuth): AuthApi } Provides a Hilt module for usage of [AuthApi] and Builds and provides the instance of [KitsuAuthService] and Binds [api] to an instance of [AuthApi]. +@Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Reusable fun provideSharedPreferences(@ApplicationContext context: Context): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) } Dagger [Module] for generic application items and Provides the default [SharedPreferences] for the application. +"@Database(entities = [Sleep::class], version = 3, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun sleepDao(): SleepDao }" Contains the database holder and serves as the main access point for the stored data. +"object DataModel { lateinit var preferences: SharedPreferences var preferencesActivity: PreferencesActivity? = null var start: Date? = null set(start) { field = start val editor = preferences.edit() field?.let { editor.putLong(""start"", it.time) } editor.apply() } var stop: Date? = null lateinit var database: AppDatabase val sleepsLive: LiveData> get() = database.sleepDao().getAllLive() private var initialized: Boolean = false fun init(context: Context, preferences: SharedPreferences) { if (initialized) { return } this.preferences = preferences val start = preferences.getLong(""start"", 0) if (start > 0) { this.start = Date(start) } database = Room.databaseBuilder(context, AppDatabase::class.java, ""database"") .addMigrations(MIGRATION_1_2) .addMigrations(MIGRATION_2_3) .build() initialized = true } private fun getStartDelay(): Int { val startDelayStr = preferences.getString(""sleep_start_delta"", ""0"") ?: ""0"" return startDelayStr.toIntOrNull() ?: 0 } fun getCompactView(): Boolean { return preferences.getBoolean(""compact_view"", false) } suspend fun storeSleep() { val sleep = Sleep() start?.let { sleep.start = it.time } stop?.let { sleep.stop = it.time } val startDelayMS = getStartDelay() * 60 * 1000 if (sleep.start + startDelayMS > sleep.stop) { sleep.start = sleep.stop } else { sleep.start += startDelayMS } database.sleepDao().insert(sleep) val editor = preferences.edit() editor.remove(""start"") editor.apply() } suspend fun insertSleep(sleep: Sleep) { database.sleepDao().insert(sleep) } private suspend fun insertSleeps(sleepList: List) { database.sleepDao().insert(sleepList) } suspend fun updateSleep(sleep: Sleep) { database.sleepDao().update(sleep) } suspend fun deleteSleep(sleep: Sleep) { database.sleepDao().delete(sleep) } suspend fun deleteAllSleep() { database.sleepDao().deleteAll() } suspend fun getSleepById(sid: Int): Sleep { return database.sleepDao().getById(sid) } fun getSleepsAfterLive(after: Date): LiveData> { return database.sleepDao().getAfterLive(after.time) } suspend fun importData(context: Context, cr: ContentResolver, uri: Uri) { val inputStream = cr.openInputStream(uri) val records: Iterable = CSVFormat.DEFAULT.parse(InputStreamReader(inputStream)) val importedSleeps = mutableListOf() try { var first = true for (cells in records) { if (first) { first = false continue } val sleep = Sleep() sleep.start = cells[1].toLong() sleep.stop = cells[2].toLong() if (cells.isSet(3)) { sleep.rating = cells[3].toLong() } if (cells.isSet(4)) { sleep.comment = cells[4] } importedSleeps.add(sleep) } val oldSleeps = database.sleepDao().getAll() val newSleeps = importedSleeps.subtract(oldSleeps.toSet()) database.sleepDao().insert(newSleeps.toList()) } catch (e: IOException) { Log.e(TAG, ""importData: readLine() failed"") return } finally { if (inputStream != null) { try { inputStream.close() } catch (_: Exception) { } } } val text = context.getString(R.string.import_success) val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(context, text, duration) toast.show() } suspend fun importDataFromCalendar(context: Context, calendarId: String) { val importedSleeps = CalendarImport.queryForEvents( context, calendarId ).map(CalendarImport::mapEventToSleep) val oldSleeps = database.sleepDao().getAll() val newSleeps = importedSleeps.subtract(oldSleeps.toSet()) insertSleeps(newSleeps.toList()) val text = context.resources.getQuantityString( R.plurals.imported_items, newSleeps.size, newSleeps.size ) val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(context, text, duration) toast.show() } suspend fun exportDataToCalendar(context: Context, calendarId: String) { val calendarSleeps = CalendarImport.queryForEvents( context, calendarId ).map(CalendarImport::mapEventToSleep) val sleeps = database.sleepDao().getAll() val exportedSleeps = sleeps.subtract(calendarSleeps.toSet()) CalendarExport.exportSleep(context, calendarId, exportedSleeps.toList()) val text = context.resources.getQuantityString( R.plurals.exported_items, exportedSleeps.size, exportedSleeps.size ) val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(context, text, duration) toast.show() } suspend fun backupSleeps(context: Context, cr: ContentResolver) { val autoBackup = preferences.getBoolean(""auto_backup"", false) val autoBackupPath = preferences.getString(""auto_backup_path"", """") if (!autoBackup || autoBackupPath == null || autoBackupPath.isEmpty()) { return } val folder = DocumentFile.fromTreeUri(context, Uri.parse(autoBackupPath)) ?: return val oldBackup = folder.findFile(""backup.csv"") if (oldBackup != null && oldBackup.exists()) { oldBackup.delete() } val backup = folder.createFile(""text/csv"", ""backup.csv"") ?: return exportDataToFile( context, cr, backup.uri, showToast = false ) } suspend fun exportDataToFile( context: Context, cr: ContentResolver, uri: Uri, showToast: Boolean ) { val sleeps = database.sleepDao().getAll() try { cr.takePersistableUriPermission( uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION ) } catch (e: SecurityException) { Log.e(TAG, ""exportData: takePersistableUriPermission() failed for write"") } val os: OutputStream? = cr.openOutputStream(uri) if (os == null) { Log.e(TAG, ""exportData: openOutputStream() failed"") return } try { val writer = CSVPrinter(OutputStreamWriter(os, ""UTF-8""), CSVFormat.DEFAULT) writer.printRecord(""sid"", ""start"", ""stop"", ""rating"", ""comment"") for (sleep in sleeps) { writer.printRecord(sleep.sid, sleep.start, sleep.stop, sleep.rating, sleep.comment) } writer.close() } catch (e: IOException) { Log.e(TAG, ""exportData: write() failed"") return } finally { try { os.close() } catch (_: Exception) { } } if (!showToast) { return } val text = context.getString(R.string.export_success) val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(context, text, duration) toast.show() } private const val TAG = ""DataModel"" fun getSleepCountStat(sleeps: List): String { return sleeps.size.toString() } fun getSleepDurationStat(sleeps: List, compactView: Boolean): String { var sum: Long = 0 for (sleep in sleeps) { var diff = sleep.stop - sleep.start diff /= 1000 sum += diff } val count = sleeps.size return if (count == 0) { """" } else formatDuration(sum / count, compactView) } fun getSleepDurationDailyStat(sleeps: List, compactView: Boolean): String { // Day -> sum (in seconds) map. val sums = HashMap() var minKey: Long = Long.MAX_VALUE var maxKey: Long = 0 for (sleep in sleeps) { var diff = sleep.stop - sleep.start diff /= 1000 // Calculate stop day val stopDate = Calendar.getInstance() stopDate.timeInMillis = sleep.stop val day = Calendar.getInstance() day.timeInMillis = 0 val startYear = stopDate.get(Calendar.YEAR) day.set(Calendar.YEAR, startYear) val startMonth = stopDate.get(Calendar.MONTH) day.set(Calendar.MONTH, startMonth) val startDay = stopDate.get(Calendar.DAY_OF_MONTH) day.set(Calendar.DAY_OF_MONTH, startDay) val key = day.timeInMillis minKey = minOf(minKey, key) maxKey = maxOf(maxKey, key) val sum = sums[key] if (sum != null) { sums[key] = sum + diff } else { sums[key] = diff } } if (sums.size == 0) { return """" } val msPerDay = 86400 * 1000 val count = (maxKey - minKey) / msPerDay + 1 return formatDuration(sums.values.sum() / count, compactView) } fun formatDuration(seconds: Long, compactView: Boolean): String { if (compactView) { return String.format( Locale.getDefault(), ""%d:%02d"", seconds / 3600, seconds % 3600 / 60 ) } return String.format( Locale.getDefault(), ""%d:%02d:%02d"", seconds / 3600, seconds % 3600 / 60, seconds % 60 ) } fun formatTimestamp(date: Date, compactView: Boolean): String { val sdf = if (compactView) { SimpleDateFormat(""yyyy-MM-dd HH:mm"", Locale.getDefault()) } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { SimpleDateFormat(""yyyy-MM-dd HH:mm:ss XXX"", Locale.getDefault()) } else { SimpleDateFormat(""yyyy-MM-dd HH:mm:ss"", Locale.getDefault()) } return sdf.format(date) } fun filterSleeps(sleeps: List, after: Date): List { return sleeps.filter { it.stop > after.time } } }" Data model is the singleton shared state between the activity and the service. +"class UserEvent(cursor: Cursor) { val id: String = cursor.getString(CalendarImport.EVENT_PROJECTION_ID) val calendarId: String = cursor.getString(CalendarImport.EVENT_PROJECTION_CAL_ID) val title: String = cursor.getString(CalendarImport.EVENT_PROJECTION_TITLE) val start: Long = cursor.getLong(CalendarImport.EVENT_PROJECTION_START) val end: Long = cursor.getLong(CalendarImport.EVENT_PROJECTION_END) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as UserEvent if (id != other.id) return false if (calendarId != other.calendarId) return false if (title != other.title) return false if (start != other.start) return false if (end != other.end) return false return true } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + calendarId.hashCode() result = 31 * result + title.hashCode() result = 31 * result + start.hashCode() result = 31 * result + end.hashCode() return result } override fun toString(): String { return """""" UserEvent(id='$id', calendarId='$calendarId', title='$title', start='$start', end='$end') """""".trimIndent() } }" "Represents a single event record, as found in a user's calendar" +"class UserCalendar(cursor: Cursor) { val id: String = cursor.getString(CalendarImport.CALENDAR_PROJECTION_ID) val name: String = cursor.getString(CalendarImport.CALENDAR_PROJECTION_DISPLAY_NAME) val owner: String = cursor.getString(CalendarImport.CALENDAR_PROJECTION_ACCOUNT_NAME) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as UserCalendar if (id != other.id) return false if (name != other.name) return false if (owner != other.owner) return false return true } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + name.hashCode() result = 31 * result + owner.hashCode() return result } override fun toString(): String { return ""UserCalendar(id='$id', name='$name', owner='$owner')"" } }" "Represents a single calendar record, as found within the user's connected calendar" +fun Cursor.map(block: (Cursor) -> T): List { val items = mutableListOf() use { while (!it.isClosed && it.moveToNext()) { items += block(it) } } return items } Apply a transformation [block] to all records in a Cursor +"object CalendarImport { private const val DEFAULT_EVENT_TITLE = ""Sleep"" const val CALENDAR_PROJECTION_ID = 0 const val CALENDAR_PROJECTION_ACCOUNT_NAME = 1 const val CALENDAR_PROJECTION_DISPLAY_NAME = 2 private val CALENDAR_PROJECTION: Array = arrayOf( Calendars._ID, // 0 Calendars.ACCOUNT_NAME, // 1 Calendars.CALENDAR_DISPLAY_NAME, // 2 ) const val EVENT_PROJECTION_CAL_ID = 0 const val EVENT_PROJECTION_TITLE = 1 const val EVENT_PROJECTION_ID = 2 const val EVENT_PROJECTION_START = 3 const val EVENT_PROJECTION_END = 4 private val EVENT_PROJECTION: Array = arrayOf( Events.CALENDAR_ID, // 0 Events.TITLE, // 1 Events._ID, // 2 Events.DTSTART, // 3 Events.DTEND, // 4 ) fun queryForCalendars(context: Context): List { val uri: Uri = Calendars.CONTENT_URI val contentResolver: ContentResolver = context.contentResolver contentResolver.query( uri, CALENDAR_PROJECTION, null, null, null ).use { cursor -> return cursor?.map(::UserCalendar).orEmpty() } } fun queryForEvents( context: Context, calendarId: String, title: String = DEFAULT_EVENT_TITLE ): List { val uri = Events.CONTENT_URI val contentResolver: ContentResolver = context.contentResolver val selection = """""" (${Events.CALENDAR_ID} = ?) AND (${Events.TITLE} LIKE ? COLLATE NOCASE) AND (${Events.DTSTART} IS NOT NULL) AND (${Events.DTEND} IS NOT NULL AND ${Events.DTEND} != 0) """""".trimIndent() val selectionArgs = arrayOf(calendarId, ""%$title%"") contentResolver.query( uri, EVENT_PROJECTION, selection, selectionArgs, null ).use { cursor -> return cursor?.map(::UserEvent).orEmpty() } } fun mapEventToSleep(event: UserEvent): Sleep { return Sleep().apply { start = event.start stop = event.end } } }" Singleton helper for importing sleeps from a user's local calendars +"object CalendarExport { fun exportSleep(context: Context, calendarId: String, sleepList: List) { sleepList.forEach { sleep -> val values = ContentValues().apply { put(CalendarContract.Events.DTSTART, sleep.start) put(CalendarContract.Events.DTEND, sleep.stop) put(CalendarContract.Events.TITLE, context.getString(R.string.exported_event_title)) val description = context.getString(R.string.exported_event_description) put(CalendarContract.Events.DESCRIPTION, description) put(CalendarContract.Events.CALENDAR_ID, calendarId) put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().id) } context.contentResolver.insert(CalendarContract.Events.CONTENT_URI, values) } } }" Singleton helper for exporting sleeps to a user's local calendars and Exports a list of Sleep [sleepList] to the selected user calendar +"class ToggleWidget : AppWidgetProvider() { override fun onUpdate( context: Context?, appWidgetManager: AppWidgetManager?, appWidgetIds: IntArray? ) { if (context == null) { return } if (appWidgetManager == null) { return } if (appWidgetIds == null) { return } for (appWidgetId in appWidgetIds) { val intent = Intent(context, MainActivity::class.java) intent.putExtra(""startStop"", true) val pendingIntent = PendingIntent.getActivity( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT ) val remoteViews = RemoteViews(context.packageName, R.layout.widget_layout_toggle) remoteViews.setOnClickPendingIntent(R.id.widget_toggle, pendingIntent) appWidgetManager.updateAppWidget(appWidgetId, remoteViews) } } }" Provides a widget that opens the main activity and immediately toggles between started/stopped sleep tracking. +"@RequiresApi(api = Build.VERSION_CODES.N) class TileService : android.service.quicksettings.TileService() { override fun onStartListening() { refreshTile() } override fun onTileAdded() { refreshTile() } private fun refreshTile() { val preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext) DataModel.init(applicationContext, preferences) val active = DataModel.start != null && DataModel.stop == null if (active) { qsTile.state = Tile.STATE_ACTIVE } else { qsTile.state = Tile.STATE_INACTIVE } qsTile.updateTile() } override fun onClick() { try { if (qsTile.state == Tile.STATE_ACTIVE) { qsTile.state = Tile.STATE_INACTIVE } else { qsTile.state = Tile.STATE_ACTIVE } qsTile.updateTile() val intent = Intent(applicationContext, MainActivity::class.java) intent.putExtra(""startStop"", true) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivityAndCollapse(intent) } catch (e: Exception) { Log.e(TAG, ""onClick: uncaught exception: $e"") } } companion object { private const val TAG = ""TileService"" } }" Provides a quick settings tile that opens the main activity and immediately toggles between started/stopped sleep tracking. +"class StatsFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_stats, container, false) } }" "Shows stats, counting sleeps after a certain point in the past." +"class StatsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_stats) title = getString(R.string.stats) // Show a back button. actionBar?.setDisplayHomeAsUpEnabled(true) DataModel.sleepsLive.observe( this, { sleeps -> if (sleeps != null) { val fragments = supportFragmentManager // Last week val lastWeek = Calendar.getInstance() lastWeek.add(Calendar.DATE, -7) val lastWeekSleeps = DataModel.filterSleeps(sleeps, lastWeek.time) val lastWeekFragment = fragments.findFragmentById(R.id.last_week_body) populateFragment(lastWeekFragment, lastWeekSleeps) // Last two weeks val lastTwoWeeks = Calendar.getInstance() lastTwoWeeks.add(Calendar.DATE, -14) val lastTwoWeekSleeps = DataModel.filterSleeps(sleeps, lastTwoWeeks.time) val lastTwoWeeksFragment = fragments.findFragmentById(R.id.last_two_weeks_body) populateFragment(lastTwoWeeksFragment, lastTwoWeekSleeps) // Last month val lastMonth = Calendar.getInstance() lastMonth.add(Calendar.DATE, -30) val lastMonthSleeps = DataModel.filterSleeps(sleeps, lastMonth.time) val lastMonthFragments = fragments.findFragmentById(R.id.last_month_body) populateFragment(lastMonthFragments, lastMonthSleeps) // Last year val lastYear = Calendar.getInstance() lastYear.add(Calendar.DATE, -365) val lastYearSleeps = DataModel.filterSleeps(sleeps, lastYear.time) val lastYearFragment = fragments.findFragmentById(R.id.last_year_body) populateFragment(lastYearFragment, lastYearSleeps) // All time, i.e. no filter val allTimeFragment = fragments.findFragmentById(R.id.all_time_body) populateFragment(allTimeFragment, sleeps) } } ) } private fun populateFragment(fragment: Fragment?, sleeps: List) { val view = fragment?.view val count = view?.findViewById(R.id.fragment_stats_sleeps) count?.text = DataModel.getSleepCountStat(sleeps) val average = view?.findViewById(R.id.fragment_stats_average) average?.text = DataModel.getSleepDurationStat(sleeps, DataModel.getCompactView()) val daily = view?.findViewById(R.id.fragment_stats_daily) daily?.text = DataModel.getSleepDurationDailyStat(sleeps, DataModel.getCompactView()) } }" "This activity provides additional stats for a limited period of time. This is in contrast with the main activity, which considers all sleeps within the specified duration." +inner class SleepViewHolder(view: View) : RecyclerView.ViewHolder(view) { val start: TextView = view.findViewById(R.id.sleep_item_start) val stop: TextView = view.findViewById(R.id.sleep_item_stop) val duration: TextView = view.findViewById(R.id.sleep_item_duration) val durationWakeImage: View = view.findViewById(R.id.wake_time_image) val durationWakeHeader: View = view.findViewById(R.id.wake_time_header) val durationWake: TextView = view.findViewById(R.id.wake_item_duration) val rating: RatingBar = view.findViewById(R.id.sleep_item_rating) val swipeable: View = view.findViewById(R.id.sleep_swipeable) private val deleteLeft: ImageView = view.findViewById(R.id.sleep_delete_left) private val deleteRight: ImageView = view.findViewById(R.id.sleep_delete_right) fun showSwipeDelete(left: Boolean) { deleteLeft.visibility = if (left) View.VISIBLE else View.INVISIBLE deleteRight.visibility = if (left) View.INVISIBLE else View.VISIBLE } } The view holder holds all views that will display one Sleep. +"class SleepsAdapter( private val preferences: SharedPreferences ) : RecyclerView.Adapter() { var data: List = ArrayList() set(newData) { val previousData = field field = newData DiffUtil.calculateDiff(object : DiffUtil.Callback() { override fun getOldListSize(): Int { return previousData.size } override fun getNewListSize(): Int { return newData.size } /** * Compares old and new based on their ID only. */ override fun areItemsTheSame( oldItemPosition: Int, newItemPosition: Int ): Boolean { val oldSid = previousData[oldItemPosition].sid val newSid = newData[newItemPosition].sid return oldSid == newSid } /** * Compares old and new based on their value. */ override fun areContentsTheSame( oldItemPosition: Int, newItemPosition: Int ): Boolean { return previousData[oldItemPosition] == newData[newItemPosition] } }).dispatchUpdatesTo(this) }" This is the adapter between RecyclerView and SleepDao. +"class SleepViewModel : ViewModel() { private var sleepCommentCallback: SleepCommentCallback? = null fun showSleep(activity: SleepActivity, sid: Int) { val viewModel = this viewModelScope.launch { val sleep = DataModel.getSleepById(sid) val start = activity.findViewById(R.id.sleep_start) start.text = DataModel.formatTimestamp(Date(sleep.start), DataModel.getCompactView()) val stop = activity.findViewById(R.id.sleep_stop) stop.text = DataModel.formatTimestamp(Date(sleep.stop), DataModel.getCompactView()) val rating = activity.findViewById(R.id.sleep_item_rating) rating.rating = sleep.rating.toFloat() rating.onRatingBarChangeListener = SleepRateCallback(viewModel, sleep) val comment = activity.findViewById(R.id.sleep_item_comment) viewModel.sleepCommentCallback?.let { comment.removeTextChangedListener(it) } comment.setText(sleep.comment) viewModel.sleepCommentCallback = SleepCommentCallback(viewModel, sleep) comment.addTextChangedListener(viewModel.sleepCommentCallback) } } fun editSleep( activity: SleepActivity, sid: Int, isStart: Boolean, context: Context, cr: ContentResolver ) { viewModelScope.launch { val sleep = DataModel.getSleepById(sid) val dateTime = Calendar.getInstance() dateTime.time = if (isStart) { Date(sleep.start) } else { Date(sleep.stop) } DatePickerDialog( activity, { _/*view*/, year, monthOfYear, dayOfMonth -> dateTime.set(year, monthOfYear, dayOfMonth) TimePickerDialog( activity, { _/*view*/, hourOfDay, minute -> dateTime[Calendar.HOUR_OF_DAY] = hourOfDay dateTime[Calendar.MINUTE] = minute if (isStart) { sleep.start = dateTime.time.time } else { sleep.stop = dateTime.time.time } if (sleep.start < sleep.stop) { updateSleep(activity, sleep, context, cr) } else { val text = context.getString(R.string.negative_duration) val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(context, text, duration) toast.show() } }, dateTime[Calendar.HOUR_OF_DAY], dateTime[Calendar.MINUTE], /*is24HourView=*/DateFormat.is24HourFormat(activity) ).show() }, dateTime[Calendar.YEAR], dateTime[Calendar.MONTH], dateTime[Calendar.DATE] ).show() } } private fun updateSleep( activity: SleepActivity, sleep: Sleep, context: Context, cr: ContentResolver ) { viewModelScope.launch { DataModel.updateSleep(sleep) DataModel.backupSleeps(context, cr) showSleep(activity, sleep.sid) } } fun updateSleep(sleep: Sleep) { viewModelScope.launch { DataModel.updateSleep(sleep) } } }" "This is the view model of SleepActivity, providing coroutine scopes." +"class SleepTouchCallback( private val context: Context, private val contentResolver: ContentResolver, private val viewModel: MainViewModel, private val adapter: SleepsAdapter ) : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onSwiped( viewHolder: RecyclerView.ViewHolder, direction: Int ) { val sleep = adapter.data[viewHolder.adapterPosition] viewModel.deleteSleep(sleep, context, contentResolver) val view = viewHolder.itemView val snackbar = Snackbar.make(view, R.string.deleted, Snackbar.LENGTH_LONG) snackbar.setAction(context.getString(R.string.undo)) { viewModel.insertSleep(sleep) } snackbar.show() } override fun onChildDraw( c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean ) { if (viewHolder is SleepsAdapter.SleepViewHolder) { viewHolder.showSwipeDelete(dX > 0) getDefaultUIUtil().onDraw( c, recyclerView, viewHolder.swipeable, dX, dY, actionState, isCurrentlyActive ) } } override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) { if (viewHolder is SleepsAdapter.SleepViewHolder) { getDefaultUIUtil().clearView(viewHolder.swipeable) } } }" This callback handles deletion of one recorded sleep in the sleep list. Listens to left/right swipes only. +"class SleepRateCallback( private val viewModel: SleepViewModel, private val sleep: Sleep ) : RatingBar.OnRatingBarChangeListener { override fun onRatingChanged(ratingBar: RatingBar?, rating: Float, fromUser: Boolean) { if (sleep.rating != rating.toLong()) { sleep.rating = rating.toLong() viewModel.updateSleep(sleep) } } }" This callback handles the rating of an individual sleep. +"@Dao interface SleepDao { @Query(""SELECT * FROM sleep ORDER BY sid ASC"") suspend fun getAll(): List @Query(""SELECT * FROM sleep ORDER BY start_date DESC"") fun getAllLive(): LiveData> @Query(""SELECT * from sleep where sid = :id LIMIT 1"") suspend fun getById(id: Int): Sleep @Query(""SELECT * FROM sleep WHERE stop_date > :after ORDER BY start_date DESC"") fun getAfterLive(after: Long): LiveData> @Insert suspend fun insert(sleepList: List) @Insert suspend fun insert(sleep: Sleep) @Update suspend fun update(sleep: Sleep) @Delete suspend fun delete(sleep: Sleep) @Query(""delete from sleep"") suspend fun deleteAll() }" Accesses the database of Sleep objects. +"class SleepClickCallback( private val mainActivity: MainActivity, private val adapter: SleepsAdapter, private val recyclerView: RecyclerView ) : View.OnClickListener { override fun onClick(view: View?) { if (view == null) { return } val itemPosition = recyclerView.getChildLayoutPosition(view) val sleep = adapter.data[itemPosition] val intent = Intent(mainActivity, SleepActivity::class.java) val bundle = Bundle() bundle.putInt(""sid"", sleep.sid) intent.putExtras(bundle) mainActivity.startActivity(intent) } }" This callback handles editing of one recorded sleep in the sleep list. Listens to clicks only. +"class SleepActivity : AppCompatActivity(), View.OnClickListener { private lateinit var viewModel: SleepViewModel private var sid: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProvider.NewInstanceFactory().create(SleepViewModel::class.java) setContentView(R.layout.activity_sleep) val start = findViewById(R.id.sleep_start) start.setOnClickListener(this) val stop = findViewById(R.id.sleep_stop) stop.setOnClickListener(this) val bundle = intent.extras ?: return sid = bundle.getInt(""sid"") title = String.format(getString(R.string.sleep_id), sid) // Show a back button. actionBar?.setDisplayHomeAsUpEnabled(true) viewModel.showSleep(this, sid) } override fun onClick(view: View?) { val isStart = view == findViewById(R.id.sleep_start) viewModel.editSleep(this, sid, isStart, applicationContext, contentResolver) } }" The activity is the editing UI of a single sleep. +"@Entity class Sleep { @PrimaryKey(autoGenerate = true) var sid: Int = 0 @ColumnInfo(name = ""start_date"") var start: Long = 0 @ColumnInfo(name = ""stop_date"") var stop: Long = 0 @ColumnInfo(name = ""rating"") var rating: Long = 0 @ColumnInfo(name = ""comment"") var comment: String = """" private val lengthMs get() = stop - start val lengthHours get() = lengthMs.toFloat() / DateUtils.HOUR_IN_MILLIS override fun equals(other: Any?): Boolean = other is Sleep && other.start == start && other.stop == stop override fun hashCode(): Int { var result = start.hashCode() result = 31 * result + stop.hashCode() return result } }" Represents one tracked sleep. +"class MainViewModel(application: Application) : AndroidViewModel(application) { private val preferences = PreferenceManager.getDefaultSharedPreferences(application) val durationSleepsLive: LiveData> = Transformations.switchMap(preferences.liveData(""dashboard_duration"", ""0"")) { durationStr -> val duration = durationStr?.toInt() ?: 0 val date = if (duration == 0) { Date(0) } else { val cal = Calendar.getInstance() cal.add(Calendar.DATE, duration) cal.time } DataModel.getSleepsAfterLive(date) } fun stopSleep(context: Context, cr: ContentResolver) { viewModelScope.launch { DataModel.storeSleep() DataModel.backupSleeps(context, cr) } } fun exportDataToFile(context: Context, cr: ContentResolver, uri: Uri, showToast: Boolean) { viewModelScope.launch { DataModel.exportDataToFile(context, cr, uri, showToast) } } fun importDataFromCalendar(context: Context, calendarId: String) { viewModelScope.launch { DataModel.importDataFromCalendar(context, calendarId) } } fun exportDataToCalendar(context: Context, calendarId: String) { viewModelScope.launch { DataModel.exportDataToCalendar(context, calendarId) } } fun importData(context: Context, cr: ContentResolver, uri: Uri) { viewModelScope.launch { DataModel.importData(context, cr, uri) } } fun insertSleep(sleep: Sleep) { viewModelScope.launch { DataModel.insertSleep(sleep) } } fun deleteSleep(sleep: Sleep, context: Context, cr: ContentResolver) { viewModelScope.launch { DataModel.deleteSleep(sleep) DataModel.backupSleeps(context, cr) } } fun deleteAllSleep() { viewModelScope.launch { DataModel.deleteAllSleep() } } }" "This is the view model of MainActivity, providing coroutine scopes." +"class MainService : Service() { override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { val channel = NotificationChannel( NOTIFICATION_CHANNEL_ID, getString(R.string.notification_channel_name), NotificationManager.IMPORTANCE_DEFAULT ) // Avoid unwanted vibration. channel.vibrationPattern = longArrayOf(0) channel.enableVibration(true) notificationManager.createNotificationChannel(channel) } val notificationIntent = Intent(this, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, FLAG_IMMUTABLE) var contentText = """" DataModel.start?.let { start -> contentText = String.format( getString(R.string.sleeping_since), DataModel.formatTimestamp(start, DataModel.getCompactView()) ) } val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setContentText(contentText) .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentIntent(pendingIntent) .build() startForeground(NOTIFICATION_CODE, notification) return START_STICKY } override fun onBind(intent: Intent): IBinder? { // We don't provide binding, so return null return null } companion object { private const val NOTIFICATION_CHANNEL_ID = ""Notification"" private const val NOTIFICATION_CODE = 1 } }" "A foreground service that just keeps the app alive, so the state is not lost while tracking is on." +"/** * The activity is the primary UI of the app: allows starting and stopping the * tracking. */ class MainActivity : AppCompatActivity(), View.OnClickListener { private lateinit var viewModel: MainViewModel // SharedPreferences keeps listeners in a WeakHashMap, so keep this as a member. private val sharedPreferenceListener = SharedPreferencesChangeListener() private val exportPermissionLauncher = registerForActivityResult( RequestMultiplePermissions() ) { permissions: Map -> checkCalendarPermissionGranted(permissions, ::exportCalendarData) } private val importPermissionLauncher = registerForActivityResult( RequestMultiplePermissions() ) { permissions: Map -> checkCalendarPermissionGranted(permissions, ::importCalendarData) } private val importActivityResult = registerForActivityResult(StartActivityForResult()) { result -> try { result.data?.data?.let { uri -> viewModel.importData(applicationContext, contentResolver, uri) updateView() } } catch (e: Exception) { Log.e(TAG, ""onActivityResult: importData() failed"") } } private val exportActivityResult = registerForActivityResult(StartActivityForResult()) { result -> try { result.data?.data?.let { uri -> viewModel.exportDataToFile( applicationContext, contentResolver, uri, showToast = true ) } } catch (e: Exception) { Log.e(TAG, ""onActivityResult: exportData() failed"") } } private fun setDashboardText(durationStr: String) { var index = resources.getStringArray(R.array.duration_entry_values).indexOf(durationStr) val durations = resources.getStringArray(R.array.duration_entries) if (index == -1) { index = durations.size - 1 // indexOf may return -1, which will out of bounds. } val durationHeaderStr = resources.getStringArray(R.array.duration_entries)[index] findViewById(R.id.dashboard_header)?.text = getString(R.string.dashboard, durationHeaderStr) } private fun handleIntent(intent: Intent?) { intent?.let { if (it.getBooleanExtra(""startStop"", false)) { onClick(findViewById(R.id.start_stop_layout)) } } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) handleIntent(intent) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) sharedPreferenceListener.applyTheme(PreferenceManager.getDefaultSharedPreferences(this)) viewModel = ViewModelProvider.AndroidViewModelFactory(application) .create(MainViewModel::class.java) setContentView(R.layout.activity_main) val startStop = findViewById(R.id.start_stop_layout) startStop.setOnClickListener(this) val preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext) preferences.registerOnSharedPreferenceChangeListener(sharedPreferenceListener) DataModel.init(applicationContext, preferences) preferences.liveData(""dashboard_duration"", ""-7"").observe( this ) { setDashboardText(it ?: ""0"") } // Hide plain avg and avg(daily sum) if requested: preferences.liveDataBoolean(""show_average_sleep_durations"", false).observe( this ) { it?.let { val fragments = supportFragmentManager val stats = fragments.findFragmentById(R.id.dashboard_body)?.view val layout = stats?.findViewById(R.id.fragment_stats_average_layout) if (it) { layout?.visibility = View.VISIBLE } else { layout?.visibility = View.GONE } } } preferences.liveDataBoolean(""show_average_daily_sums"", true).observe( this ) { it?.let { val fragments = supportFragmentManager val stats = fragments.findFragmentById(R.id.dashboard_body)?.view val layout = stats?.findViewById(R.id.fragment_stats_daily_layout) if (it) { layout?.visibility = View.VISIBLE } else { layout?.visibility = View.GONE } } } val sleepsAdapter = SleepsAdapter(preferences) val recyclerView = findViewById(R.id.sleeps) viewModel.durationSleepsLive.observe( this ) { sleeps -> if (sleeps != null) { val fragments = supportFragmentManager val stats = fragments.findFragmentById(R.id.dashboard_body)?.view val countStat = stats?.findViewById(R.id.fragment_stats_sleeps) countStat?.text = DataModel.getSleepCountStat(sleeps) val durationStat = stats?.findViewById(R.id.fragment_stats_average) durationStat?.text = DataModel.getSleepDurationStat( sleeps, DataModel.getCompactView() ) val durationDailyStat = stats?.findViewById(R.id.fragment_stats_daily) durationDailyStat?.text = DataModel.getSleepDurationDailyStat( sleeps, DataModel.getCompactView() ) sleepsAdapter.data = sleeps // Set up placeholder text if there are no sleeps. val noSleepsView = findViewById(R.id.no_sleeps) if (sleeps.isEmpty()) { recyclerView.visibility = View.GONE noSleepsView.visibility = View.VISIBLE } else { recyclerView.visibility = View.VISIBLE noSleepsView.visibility = View.GONE } } } val recyclerViewLayout = LinearLayoutManager(this) recyclerView.layoutManager = recyclerViewLayout recyclerView.setHasFixedSize(true) recyclerView.itemAnimator = DefaultItemAnimator() recyclerView.adapter = sleepsAdapter // Enable separators between sleep items. val dividerItemDecoration = DividerItemDecoration( recyclerView.context, recyclerViewLayout.orientation ) recyclerView.addItemDecoration(dividerItemDecoration) sleepsAdapter.registerAdapterDataObserver( object : RecyclerView.AdapterDataObserver() { override fun onItemRangeInserted( positionStart: Int, itemCount: Int ) { recyclerView.scrollToPosition(positionStart) } }) // Otherwise swipe on a card view deletes it. val itemTouchHelper = ItemTouchHelper( SleepTouchCallback( applicationContext, contentResolver, viewModel, sleepsAdapter ) ) itemTouchHelper.attachToRecyclerView(recyclerView) val sleepClickCallback = SleepClickCallback(this, sleepsAdapter, recyclerView) sleepsAdapter.clickCallback = sleepClickCallback // Hide label of FAB on scroll. val fabText = findViewById(R.id.start_stop_text) val listener = View.OnScrollChangeListener { _, _, scrollY, _, oldScrollY -> if (scrollY > oldScrollY) { fabText.visibility = View.GONE } else { fabText.visibility = View.VISIBLE } } recyclerView.setOnScrollChangeListener(listener) // See if the activity is triggered from the widget. If so, toggle the start/stop state. handleIntent(intent) updateView() } override fun onStart() { super.onStart() val intent = Intent(this, MainService::class.java) stopService(intent) val recyclerView = findViewById(R.id.sleeps) recyclerView.findViewHolderForAdapterPosition(0)?.let { // Since the adapter unconditionally gets assigned in `onCreate()` // it shouldn't be necessary to consider fixing it here. // If it is null at this point a lot more must have gone wrong as well. recyclerView.adapter?.onBindViewHolder(it, 0) } } override fun onStop() { super.onStop() val intent = Intent(this, MainService::class.java) if (DataModel.start != null && DataModel.stop == null) { startService(intent) } } override fun onClick(view: View?) { when (view?.id) { R.id.start_stop_layout -> { if (DataModel.start != null && DataModel.stop == null) { DataModel.stop = Calendar.getInstance().time viewModel.stopSleep(applicationContext, contentResolver) } else { DataModel.start = Calendar.getInstance().time DataModel.stop = null } updateView() } } } private fun exportFileData() { val intent = Intent(Intent.ACTION_CREATE_DOCUMENT) intent.addCategory(Intent.CATEGORY_OPENABLE) intent.type = ""text/csv"" intent.putExtra(Intent.EXTRA_TITLE, ""plees-tracker.csv"") exportActivityResult.launch(intent) } private fun importFileData() { val intent = Intent(Intent.ACTION_GET_CONTENT) intent.type = ""text/*"" val mimeTypes = arrayOf(""text/csv"", ""text/comma-separated-values"") intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes) importActivityResult.launch(intent) } private fun createColorStateList(color: Int): ColorStateList { return ColorStateList.valueOf(ContextCompat.getColor(this, color)) } private fun updateView() { val status = findViewById(R.id.status) val startStopLayout = findViewById(R.id.start_stop_layout) val startStop = findViewById(R.id.start_stop) val startStopText = findViewById(R.id.start_stop_text) if (DataModel.start != null && DataModel.stop != null) { status.text = getString(R.string.tracking_stopped) startStop.contentDescription = getString(R.string.start_again) startStop.setImageResource(R.drawable.ic_start) startStopText.text = getString(R.string.start) // Set to custom, ~blue. startStop.backgroundTintList = createColorStateList(R.color.colorFabPrimary) startStopLayout.backgroundTintList = startStop.backgroundTintList return } DataModel.start?.let { start -> status.text = String.format( getString(R.string.sleeping_since), DataModel.formatTimestamp(start, DataModel.getCompactView()) ) startStop.contentDescription = getString(R.string.stop) startStop.setImageResource(R.drawable.ic_stop) startStopText.text = getString(R.string.stop) // Back to default, ~red. startStop.backgroundTintList = createColorStateList(R.color.colorFabAccent) startStopLayout.backgroundTintList = startStop.backgroundTintList return } // Set to custom, ~blue. startStop.backgroundTintList = createColorStateList(R.color.colorFabPrimary) startStopLayout.backgroundTintList = startStop.backgroundTintList } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.import_calendar_data -> { checkForCalendarPermission(importPermissionLauncher, ::importCalendarData) return true } R.id.import_file_data -> { importFileData() return true } R.id.export_file_data -> { exportFileData() return true } R.id.export_calendar_data -> { checkForCalendarPermission(exportPermissionLauncher, ::exportCalendarData) return true } R.id.about -> { LibsBuilder() .withActivityTitle(getString(R.string.about_toolbar)) .withAboutAppName(getString(R.string.app_name)) .withActivityStyle(Libs.ActivityStyle.LIGHT_DARK_TOOLBAR) .withAboutDescription(getString(R.string.app_description)) .start(this) return true } R.id.documentation -> { val website = getString(R.string.website_link) open(Uri.parse(website)) return true } R.id.settings -> { startActivity(Intent(this, PreferencesActivity::class.java)) return true } R.id.delete_all_sleep -> { val builder = AlertDialog.Builder(this) builder.setMessage(getString(R.string.delete_all_message)) .setCancelable(false) .setPositiveButton(getString(R.string.delete_all_positive)) { _, _ -> viewModel.deleteAllSleep() } .setNegativeButton(getString(R.string.delete_all_negative)) { dialog, _ -> dialog.dismiss() } val alert = builder.create() alert.show() return true } R.id.stats -> { startActivity(Intent(this, StatsActivity::class.java)) return true } R.id.graphs -> { startActivity(Intent(this, GraphsActivity::class.java)) return true } else -> return super.onOptionsItemSelected(item) } } private fun checkCalendarPermissionGranted( granted: Map, onSuccess: (UserCalendar) -> Unit ) { // Check all permissions were granted if (granted.values.all { it }) { // Start picker for calendar showUserCalendarPicker(onSuccess) } else { // Permission denied Toast.makeText( this, getString(R.string.calendar_permission_required), Toast.LENGTH_LONG ).show() } } private fun checkForCalendarPermission( permissionLauncher: ActivityResultLauncher>, block: (UserCalendar) -> Unit ) { when (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR)) { PackageManager.PERMISSION_GRANTED -> showUserCalendarPicker(block) else -> { // Directly ask for the permissions permissionLauncher.launch( arrayOf( Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR ) ) } } } private inline fun showUserCalendarPicker(crossinline block: (cal: UserCalendar) -> Unit) { // Fetch calendar data val calendars = CalendarImport.queryForCalendars(this) // No user calendars found, show dialog informing user if (calendars.isEmpty()) { showNoCalendarsFoundDialog() return } // Get name of calendar(s) val titles = calendars.map(UserCalendar::name).toTypedArray() var selectedItem = 0 // Show User Calendar picker MaterialAlertDialogBuilder(this) .setTitle(getString(R.string.select_calendar_dialog_title)) .setNeutralButton(getString(R.string.select_calendar_dialog_negative), null) .setPositiveButton(getString(R.string.select_calendar_dialog_positive)) { _, _ -> block.invoke(calendars[selectedItem]) }.setSingleChoiceItems(titles, selectedItem) { _, newSelection -> selectedItem = newSelection }.show() } private fun importCalendarData(selectedItem: UserCalendar) { viewModel.importDataFromCalendar(this, selectedItem.id) } private fun exportCalendarData(selectedItem: UserCalendar) { viewModel.exportDataToCalendar(this, selectedItem.id) } private fun showNoCalendarsFoundDialog() { MaterialAlertDialogBuilder(this) .setTitle(getString(R.string.select_calendar_dialog_title)) .setMessage(getString(R.string.import_dialog_error_message)) .setNegativeButton(getString(R.string.dismiss), null) .show() } private fun open(link: Uri) { val intent = Intent(Intent.ACTION_VIEW, link) startActivity(intent) } companion object { private const val TAG = ""MainActivity"" } }" "A foreground service that just keeps the app alive, so the state is not lost while tracking is on." +"@InstallIn(SingletonComponent::class) @Module class AppModule { @Provides fun provideWifiManager(@ApplicationContext context: Context): WifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager @Provides fun provideConnectivityManager(@ApplicationContext context: Context): ConnectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager @Provides fun provideClipboardManager(@ApplicationContext context: Context): ClipboardManager = context.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager @ApplicationScope @Singleton @Provides fun providesApplicationScope( @DefaultDispatcher defaultDispatcher: CoroutineDispatcher ): CoroutineScope = CoroutineScope(SupervisorJob() + defaultDispatcher) @Singleton @Provides @MainThreadHandler fun provideMainThreadHandler(): IOSchedHandler = IOSchedMainHandler() @Singleton @Provides fun provideAnalyticsHelper( @ApplicationScope applicationScope: CoroutineScope, signInDelegate: SignInViewModelDelegate, preferenceStorage: PreferenceStorage ): AnalyticsHelper = FirebaseAnalyticsHelper(applicationScope, signInDelegate, preferenceStorage) @Singleton @Provides fun provideAgendaRepository(appConfigDataSource: AppConfigDataSource): AgendaRepository = DefaultAgendaRepository(appConfigDataSource) @Singleton @Provides fun provideAppDatabase(@ApplicationContext context: Context): AppDatabase { return AppDatabase.buildDatabase(context) } @Singleton @Provides fun provideGson(): Gson { return GsonBuilder().create() } }" "Defines all the classes that need to be provided in the scope of the app. Define here all objects that are shared throughout the app, like SharedPreferences, navigators or others. If some of those objects are singletons, they should be annotated with `@Singleton`." +"class AgendaHeadersDecoration( context: Context, blocks: List, inConferenceTimeZone: Boolean ) : ItemDecoration() { private val paint: TextPaint private val textWidth: Int private val decorHeight: Int private val verticalBias: Float init { val attrs = context.obtainStyledAttributes( R.style.Widget_IOSched_DateHeaders, R.styleable.DateHeader ) paint = TextPaint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG).apply { color = attrs.getColorOrThrow(R.styleable.DateHeader_android_textColor) textSize = attrs.getDimensionOrThrow(R.styleable.DateHeader_android_textSize) try { typeface = ResourcesCompat.getFont( context, attrs.getResourceIdOrThrow(R.styleable.DateHeader_android_fontFamily) ) } catch (_: Exception) { // ignore } } textWidth = attrs.getDimensionPixelSizeOrThrow(R.styleable.DateHeader_android_width) val height = attrs.getDimensionPixelSizeOrThrow(R.styleable.DateHeader_android_height) val minHeight = ceil(paint.textSize).toInt() decorHeight = Math.max(height, minHeight) verticalBias = attrs.getFloat(R.styleable.DateHeader_verticalBias, 0.5f).coerceIn(0f, 1f) attrs.recycle() } // Get the block index:day and create header layouts for each private val daySlots: Map = indexAgendaHeaders(blocks).map { it.first to createHeader(context, it.second, inConferenceTimeZone) }.toMap() override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: State) { val position = parent.getChildAdapterPosition(view) outRect.top = if (daySlots.containsKey(position)) decorHeight else 0 } override fun onDraw(canvas: Canvas, parent: RecyclerView, state: State) { val layoutManager = parent.layoutManager ?: return val centerX = parent.width / 2f parent.forEach { child -> if (child.top < parent.height && child.bottom > 0) { // Child is visible val layout = daySlots[parent.getChildAdapterPosition(child)] if (layout != null) { val dx = centerX - (layout.width / 2) val dy = layoutManager.getDecoratedTop(child) + child.translationY + // offset vertically within the space according to the bias (decorHeight - layout.height) * verticalBias canvas.withTranslation(x = dx, y = dy) { layout.draw(this) } } } } } /** * Create a header layout for the given [time] */ private fun createHeader( context: Context, time: ZonedDateTime, inConferenceTimeZone: Boolean ): StaticLayout { val labelRes = TimeUtils.getLabelResForTime(time, inConferenceTimeZone) val text = context.getText(labelRes) return newStaticLayout(text, paint, textWidth, ALIGN_CENTER, 1f, 0f, false) } }" A [RecyclerView.ItemDecoration] which draws sticky headers marking the days in a given list of [Block]s. It also inserts gaps between days. +"fun indexAgendaHeaders(agendaItems: List): List> { return agendaItems .mapIndexed { index, block -> index to block.startTime } .distinctBy { it.second.dayOfMonth } }" Find the first block of each day (rounded down to nearest day) and return pairs of iindex to start time. Assumes that [agendaItems] are sorted by ascending start time. +"class WifiInstaller @Inject constructor( private val wifiManager: WifiManager, private val clipboardManager: ClipboardManager ) { fun installConferenceWifi(rawWifiConfig: WifiConfiguration): Boolean { val conferenceWifiConfig = rawWifiConfig.quoteSsidAndPassword() if (!wifiManager.isWifiEnabled) { wifiManager.isWifiEnabled = true } var success = false val netId = wifiManager.addNetwork(conferenceWifiConfig) if (netId != -1) { wifiManager.enableNetwork(netId, false) success = true } else { val clip: ClipData = ClipData.newPlainText( ""wifi_password"", conferenceWifiConfig.unquoteSsidAndPassword().preSharedKey ) clipboardManager.setPrimaryClip(clip) } return success } }" Installs WiFi on device given a WiFi configuration. +"object FirebaseAuthErrorCodeConverter { fun convert(code: Int): Int { return when (code) { ErrorCodes.NO_NETWORK -> { Timber.e(""FirebaseAuth error: no_network"") R.string.firebase_auth_no_network_connection } ErrorCodes.DEVELOPER_ERROR -> { Timber.e(""FirebaseAuth error: developer_error"") R.string.firebase_auth_unknown_error } ErrorCodes.PLAY_SERVICES_UPDATE_CANCELLED -> { Timber.e(""FirebaseAuth error: play_services_update_cancelled"") R.string.firebase_auth_unknown_error } ErrorCodes.PROVIDER_ERROR -> { Timber.e(""FirebaseAuth error: provider_error"") R.string.firebase_auth_unknown_error } else -> { Timber.e(""FirebaseAuth error: unknown_error"") R.string.firebase_auth_unknown_error } } } }" Converts [ErrorCodes] from firebase to translatable strings. +"@HiltViewModel class FeedViewModel @Inject constructor( private val loadCurrentMomentUseCase: LoadCurrentMomentUseCase, loadAnnouncementsUseCase: LoadAnnouncementsUseCase, private val loadStarredAndReservedSessionsUseCase: LoadStarredAndReservedSessionsUseCase, getTimeZoneUseCase: GetTimeZoneUseCase, getConferenceStateUseCase: GetConferenceStateUseCase, private val timeProvider: TimeProvider, private val analyticsHelper: AnalyticsHelper, private val signInViewModelDelegate: SignInViewModelDelegate, themedActivityDelegate: ThemedActivityDelegate, private val snackbarMessageManager: SnackbarMessageManager ) : ViewModel(), FeedEventListener, ThemedActivityDelegate by themedActivityDelegate, SignInViewModelDelegate by signInViewModelDelegate { companion object { // Show at max 10 sessions in the horizontal sessions list as user can click on // View All sessions and go to schedule to view the full list private const val MAX_SESSIONS = 10 // Indicates there is no header to show at the current time. private object NoHeader // Indicates there is no sessions related display on the home screen as the conference is // over. private object NoSessionsContainer } @Inject @JvmField @ReservationEnabledFlag var isReservationEnabledByRemoteConfig: Boolean = false @Inject @JvmField @MapFeatureEnabledFlag var isMapEnabledByRemoteConfig: Boolean = false // Exposed to the view as a StateFlow but it's a one-shot operation. val timeZoneId = flow { if (getTimeZoneUseCase(Unit).successOr(true)) { emit(TimeUtils.CONFERENCE_TIMEZONE) } else { emit(ZoneId.systemDefault()) } }.stateIn(viewModelScope, Eagerly, TimeUtils.CONFERENCE_TIMEZONE) private val loadSessionsResult: StateFlow>> = signInViewModelDelegate.userId .flatMapLatest { // TODO(jdkoren): might need to show sessions for not signed in users too... loadStarredAndReservedSessionsUseCase(it) } .stateIn(viewModelScope, WhileViewSubscribed, Result.Loading) private val conferenceState: StateFlow = getConferenceStateUseCase(Unit) .onEach { if (it is Result.Error) { snackbarMessageManager.addMessage(SnackbarMessage(R.string.feed_loading_error)) } } .map { it.successOr(UPCOMING) } .stateIn(viewModelScope, WhileViewSubscribed, UPCOMING) // SIDE EFFECTS: Navigation actions private val _navigationActions = Channel(capacity = Channel.CONFLATED) // Exposed with receiveAsFlow to make sure that only one observer receives updates. val navigationActions = _navigationActions.receiveAsFlow() private val currentMomentResult: StateFlow> = conferenceState.map { // Reload if conferenceState changes loadCurrentMomentUseCase(timeProvider.now()) }.stateIn(viewModelScope, WhileViewSubscribed, Result.Loading) private val loadAnnouncementsResult: StateFlow>> = flow { emit(loadAnnouncementsUseCase(timeProvider.now())) }.onEach { if (it is Result.Error) { snackbarMessageManager.addMessage(SnackbarMessage(R.string.feed_loading_error)) } }.stateIn(viewModelScope, WhileViewSubscribed, Result.Loading) private val announcementsPreview: StateFlow> = loadAnnouncementsResult.map { val announcementsHeader = AnnouncementsHeader( showPastNotificationsButton = it.successOr(emptyList()).size > 1 ) if (it is Result.Loading) { listOf(announcementsHeader, LoadingIndicator) } else { listOf( announcementsHeader, it.successOr(emptyList()).firstOrNull() ?: AnnouncementsEmpty ) } }.stateIn(viewModelScope, WhileViewSubscribed, emptyList()) private val feedSessionsContainer: Flow = loadSessionsResult .combine(timeZoneId) { sessions, timeZone -> createFeedSessionsContainer(sessions, timeZone) } private val sessionContainer: StateFlow = combine( feedSessionsContainer, conferenceState, signInViewModelDelegate.userInfo ) { sessionsContainer: FeedSessions, conferenceState: ConferenceState, userInfo: AuthenticatedUserInfo? -> val isSignedIn = userInfo?.isSignedIn() ?: false val isRegistered = userInfo?.isRegistered() ?: false if (conferenceState != ENDED && isSignedIn && isRegistered && isReservationEnabledByRemoteConfig ) { sessionsContainer } else { NoSessionsContainer } }.stateIn(viewModelScope, WhileViewSubscribed, NoSessionsContainer) private val currentFeedHeader: StateFlow = conferenceState.combine( currentMomentResult ) { conferenceStarted: ConferenceState, momentResult -> if (conferenceStarted == UPCOMING) { CountdownItem } else { // Use case can return null even on success, so replace nulls with a sentinel momentResult.successOr(null) ?: NoHeader } }.stateIn(viewModelScope, WhileViewSubscribed, NoHeader) // TODO: Replace Any with something meaningful. val feed: StateFlow> = combine( currentFeedHeader, sessionContainer, announcementsPreview ) { feedHeader: Any, sessionContainer: Any, announcementsPreview: List -> val feedItems = mutableListOf() if (feedHeader != NoHeader) { feedItems.add(feedHeader) } if (sessionContainer != NoSessionsContainer) { feedItems.add(sessionContainer) } feedItems .plus(announcementsPreview) .plus(FeedSustainabilitySection) .plus(FeedSocialChannelsSection) }.stateIn(viewModelScope, WhileViewSubscribed, emptyList()) private fun createFeedSessionsContainer( sessionsResult: Result>, timeZoneId: ZoneId ): FeedSessions { val sessions = sessionsResult.successOr(emptyList()) val now = ZonedDateTime.ofInstant(timeProvider.now(), timeZoneId) // TODO: Making conferenceState a sealed class and moving currentDay in STARTED // state might be a better option val currentDayEndTime = TimeUtils.getCurrentConferenceDay()?.end // Treat start of the conference as endTime as sessions shouldn't be shown if the // currentConferenceDay is null ?: ConferenceDays.first().start val upcomingReservedSessions = sessions .filter { it.userEvent.isReserved() && it.session.endTime.isAfter(now) && it.session.endTime.isBefore(currentDayEndTime) } .take(MAX_SESSIONS) val titleId = R.string.feed_sessions_title val actionId = R.string.feed_view_full_schedule return FeedSessions( titleId = titleId, actionTextId = actionId, userSessions = upcomingReservedSessions, timeZoneId = timeZoneId, isLoading = sessionsResult is Result.Loading, isMapFeatureEnabled = isMapEnabledByRemoteConfig ) } override fun openEventDetail(id: SessionId) { analyticsHelper.logUiEvent( ""Home to event detail"", AnalyticsActions.HOME_TO_SESSION_DETAIL ) _navigationActions.tryOffer(FeedNavigationAction.NavigateToSession(id)) } override fun openSchedule(showOnlyPinnedSessions: Boolean) { analyticsHelper.logUiEvent(""Home to Schedule"", AnalyticsActions.HOME_TO_SCHEDULE) _navigationActions.tryOffer(FeedNavigationAction.NavigateToScheduleAction) } override fun onStarClicked(userSession: UserSession) { TODO(""not implemented"") } override fun signIn() { analyticsHelper.logUiEvent(""Home to Sign In"", AnalyticsActions.HOME_TO_SIGN_IN) _navigationActions.tryOffer(FeedNavigationAction.OpenSignInDialogAction) } override fun openMap(moment: Moment) { analyticsHelper.logUiEvent(moment.title.toString(), AnalyticsActions.HOME_TO_MAP) _navigationActions.tryOffer( FeedNavigationAction.NavigateAction( FeedFragmentDirections.toMap( featureId = moment.featureId, startTime = moment.startTime.toEpochMilli() ) ) ) } override fun openLiveStream(liveStreamUrl: String) { analyticsHelper.logUiEvent(liveStreamUrl, AnalyticsActions.HOME_TO_LIVESTREAM) _navigationActions.tryOffer(FeedNavigationAction.OpenLiveStreamAction(liveStreamUrl)) } override fun openMapForSession(session: Session) { analyticsHelper.logUiEvent(session.id, AnalyticsActions.HOME_TO_MAP) val directions = FeedFragmentDirections.toMap( featureId = session.room?.id, startTime = session.startTime.toEpochMilli() ) _navigationActions.tryOffer(FeedNavigationAction.NavigateAction(directions)) } override fun openPastAnnouncements() { analyticsHelper.logUiEvent("""", AnalyticsActions.HOME_TO_ANNOUNCEMENTS) val directions = FeedFragmentDirections.toAnnouncementsFragment() _navigationActions.tryOffer(FeedNavigationAction.NavigateAction(directions)) } }" "Loads data and exposes it to the view. By annotating the constructor with [@Inject], Dagger will use that constructor when needing to create the object, so defining a [@Provides] method for this class won't be needed." +"abstract class FiltersFragment : Fragment() { companion object { private const val ALPHA_CONTENT_START = 0.1f private const val ALPHA_CONTENT_END = 0.3f } private lateinit var viewModel: FiltersViewModelDelegate private lateinit var filterAdapter: SelectableFilterChipAdapter private lateinit var binding: FragmentFiltersBinding private lateinit var behavior: BottomSheetBehavior<*> private var contentAlpha = ObservableFloat(1f) private val backPressedCallback = object : OnBackPressedCallback(false) { override fun handleOnBackPressed() { if (::behavior.isInitialized && behavior.state == STATE_EXPANDED) { behavior.state = STATE_HIDDEN } } } private var pendingSheetState = -1 abstract fun resolveViewModelDelegate(): FiltersViewModelDelegate override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requireActivity().onBackPressedDispatcher.addCallback(this, backPressedCallback) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentFiltersBinding.inflate(inflater, container, false).apply { lifecycleOwner = viewLifecycleOwner contentAlpha = this@FiltersFragment.contentAlpha } binding.recyclerviewFilters.doOnApplyWindowInsets { v, insets, padding -> val systemInsets = insets.getInsets( WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime() ) v.updatePadding(bottom = padding.bottom + systemInsets.bottom) } return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = resolveViewModelDelegate() binding.viewModel = viewModel behavior = BottomSheetBehavior.from(binding.filterSheet) filterAdapter = SelectableFilterChipAdapter(viewModel) binding.recyclerviewFilters.apply { adapter = filterAdapter setHasFixedSize(true) itemAnimator = null addOnScrollListener(object : OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { binding.filtersHeaderShadow.isActivated = recyclerView.canScrollVertically(-1) } }) addItemDecoration( FlexboxItemDecoration(context).apply { setDrawable(context.getDrawable(R.drawable.divider_empty_margin_small)) setOrientation(FlexboxItemDecoration.VERTICAL) } ) } val peekHeight = behavior.peekHeight val marginBottom = binding.root.marginBottom binding.root.doOnApplyWindowInsets { v, insets, _ -> val gestureInsets = insets.getInsets(WindowInsetsCompat.Type.systemGestures()) // Update the peek height so that it is above the navigation bar behavior.peekHeight = gestureInsets.bottom + peekHeight v.updateLayoutParams { bottomMargin = marginBottom + gestureInsets.top } } behavior.addBottomSheetCallback(object : BottomSheetCallback { override fun onSlide(bottomSheet: View, slideOffset: Float) { updateFilterContentsAlpha(slideOffset) } override fun onStateChanged(bottomSheet: View, newState: Int) { updateBackPressedCallbackEnabled(newState) } }) binding.collapseArrow.setOnClickListener { behavior.state = if (behavior.skipCollapsed) STATE_HIDDEN else STATE_COLLAPSED } binding.filterSheet.doOnLayout { val slideOffset = when (behavior.state) { STATE_EXPANDED -> 1f STATE_COLLAPSED -> 0f else /*BottomSheetBehavior.STATE_HIDDEN*/ -> -1f } updateFilterContentsAlpha(slideOffset) } if (pendingSheetState != -1) { behavior.state = pendingSheetState pendingSheetState = -1 } updateBackPressedCallbackEnabled(behavior.state) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) launchAndRepeatWithViewLifecycle { viewModel.filterChips.collect { filterAdapter.submitFilterList(it) } } } private fun updateFilterContentsAlpha(slideOffset: Float) { contentAlpha.set( slideOffsetToAlpha(slideOffset, ALPHA_CONTENT_START, ALPHA_CONTENT_END) ) } private fun updateBackPressedCallbackEnabled(state: Int) { backPressedCallback.isEnabled = !(state == STATE_COLLAPSED || state == STATE_HIDDEN) } fun showFiltersSheet() { if (::behavior.isInitialized) { behavior.state = STATE_EXPANDED } else { pendingSheetState = STATE_EXPANDED } } fun hideFiltersSheet() { if (::behavior.isInitialized) { behavior.state = STATE_HIDDEN } else { pendingSheetState = STATE_HIDDEN } } }" Fragment that shows the list of filters for the Schedule +"@DrawableRes fun getDrawableResourceForIcon(context: Context, iconType: String?): Int { if (iconType == null) { return 0 } return context.resources.getIdentifier( iconType.toLowerCase(Locale.US), ""drawable"", context.packageName ) }" "Returns the drawable resource id for an icon marker, or 0 if no resource with this name exists." +"private fun createIconMarker( context: Context, drawableRes: Int, title: String ): GeoJsonPointStyle { val bitmap = drawableToBitmap(context, drawableRes) val icon = BitmapDescriptorFactory.fromBitmap(bitmap) return GeoJsonPointStyle().apply { setAnchor(0.5f, 1f) setTitle(title) setIcon(icon) } }" Creates a GeoJsonPointStyle for a map icon. The icon is chosen based on the marker type and is anchored at the bottom center of the marker's location. +"enum class MapVariant( val start: Instant, val end: Instant, @StringRes val labelResId: Int, @DrawableRes val iconResId: Int, @RawRes val markersResId: Int, @RawRes val styleResId: Int, val mapTilePrefix: String ) { AFTER_DARK( ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY1_AFTERHOURS_START).toInstant(), ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY1_END).toInstant(), R.string.map_variant_after_dark, R.drawable.ic_map_after_dark, R.raw.map_markers_night, R.raw.map_style_night, ""night"" ), CONCERT( ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY2_CONCERT_START).toInstant(), ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY2_END).toInstant(), R.string.map_variant_concert, R.drawable.ic_map_concert, R.raw.map_markers_concert, R.raw.map_style_night, ""concert"" ), // Note: must be last to facilitate [forTime] DAY( ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY1_START).toInstant(), ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY3_END).toInstant(), R.string.map_variant_daytime, R.drawable.ic_map_daytime, R.raw.map_markers_day, R.raw.map_style_day, ""day"" ); operator fun contains(time: Instant): Boolean { return time in start..end } companion object { /** Returns the first variant containing the specified time, or [DAY] if none is found. */ fun forTime(time: Instant = Instant.now()): MapVariant { return values().find { variant -> time in variant } ?: DAY } } }" "A variant of the map UI. Depending on the variant, Map UI may show different markers, tile overlays, etc." +"fun Fragment.setupSnackbarManager( snackbarMessageManager: SnackbarMessageManager, fadingSnackbar: FadingSnackbar ) { launchAndRepeatWithViewLifecycle { snackbarMessageManager.currentSnackbar.collect { message -> if (message == null) { return@collect } val messageText = HtmlCompat.fromHtml( requireContext().getString(message.messageId, message.session?.title), FROM_HTML_MODE_LEGACY ) fadingSnackbar.show( messageText = messageText, actionId = message.actionId, longDuration = message.longDuration, actionClick = { snackbarMessageManager.processDismissedMessage(message) fadingSnackbar.dismiss() }, // When the snackbar is dismissed, ping the snackbar message manager in case there // are pending messages. dismissListener = { snackbarMessageManager.removeMessageAndLoadNext(message) } ) } } }" An extension for Fragments that sets up a Snackbar with a [SnackbarMessageManager]. +"@Singleton open class SnackbarMessageManager @Inject constructor( private val preferenceStorage: PreferenceStorage, @ApplicationScope private val coroutineScope: CoroutineScope, private val stopSnackbarActionUseCase: StopSnackbarActionUseCase ) { companion object { // Keep a fixed number of old items @VisibleForTesting const val MAX_ITEMS = 10 } private val messages = mutableListOf() private val _currentSnackbar = MutableStateFlow(null) val currentSnackbar: StateFlow = _currentSnackbar fun addMessage(msg: SnackbarMessage) { coroutineScope.launch { if (!shouldSnackbarBeIgnored(msg)) { // Limit amount of pending messages if (messages.size > MAX_ITEMS) { Timber.e(""Too many Snackbar messages. Message id: ${msg.messageId}"") return@launch } // If the new message is about the same change as a pending one, keep the old one. (rare) val sameRequestId = messages.find { it.requestChangeId == msg.requestChangeId } if (sameRequestId == null) { messages.add(msg) } loadNext() } } } private fun loadNext() { if (_currentSnackbar.value == null) { _currentSnackbar.value = messages.firstOrNull() } } fun removeMessageAndLoadNext(shownMsg: SnackbarMessage?) { messages.removeAll { it == shownMsg } if (_currentSnackbar.value == shownMsg) { _currentSnackbar.value = null } loadNext() } fun processDismissedMessage(message: SnackbarMessage) { if (message.actionId == R.string.dont_show) { coroutineScope.launch { stopSnackbarActionUseCase(true) } } } private suspend fun shouldSnackbarBeIgnored(msg: SnackbarMessage): Boolean { return preferenceStorage.isSnackbarStopped() && msg.actionId == R.string.dont_show } }" "A single source of Snackbar messages related to reservations. Only shows one Snackbar related to one change across all screens Emits new values on request (when a Snackbar is dismissed and ready to show a new message) It keeps a list of [MAX_ITEMS] items, enough to figure out if a message has already been shown, but limited to avoid wasting resources." +"@HiltViewModel class OnboardingViewModel @Inject constructor( private val onboardingCompleteActionUseCase: OnboardingCompleteActionUseCase, signInViewModelDelegate: SignInViewModelDelegate ) : ViewModel(), SignInViewModelDelegate by signInViewModelDelegate { private val _navigationActions = Channel(Channel.CONFLATED) val navigationActions = _navigationActions.receiveAsFlow() fun getStartedClick() { viewModelScope.launch { onboardingCompleteActionUseCase(true) _navigationActions.send(OnboardingNavigationAction.NavigateToMainScreen) } } fun onSigninClicked() { _navigationActions.tryOffer(OnboardingNavigationAction.NavigateToSignInDialog) } }" Records that onboarding has been completed and navigates user onward. +"class ViewPagerPager(private val viewPager: ViewPager) { private val fastOutSlowIn = AnimationUtils.loadInterpolator(viewPager.context, android.R.interpolator.fast_out_slow_in) fun advance() { if (viewPager.width <= 0) return val current = viewPager.currentItem val next = ((current + 1) % requireNotNull(viewPager.adapter).count) val pages = next - current val dragDistance = pages * viewPager.width ValueAnimator.ofInt(0, dragDistance).apply { var dragProgress = 0 var draggedPages = 0 addListener( onStart = { viewPager.beginFakeDrag() }, onEnd = { viewPager.endFakeDrag() } ) addUpdateListener { if (!viewPager.isFakeDragging) { return@addUpdateListener } val dragPoint = (animatedValue as Int) val dragBy = dragPoint - dragProgress viewPager.fakeDragBy(-dragBy.toFloat()) dragProgress = dragPoint val draggedPagesProgress = dragProgress / viewPager.width if (draggedPagesProgress != draggedPages) { viewPager.endFakeDrag() viewPager.beginFakeDrag() draggedPages = draggedPagesProgress } } duration = if (pages == 1) PAGE_CHANGE_DURATION else MULTI_PAGE_CHANGE_DURATION interpolator = fastOutSlowIn }.start() } companion object { private const val PAGE_CHANGE_DURATION = 400L private const val MULTI_PAGE_CHANGE_DURATION = 600L } }" Helper class for automatically scrolling pages of a [ViewPager] which does not allow you to customize the speed at which it changes page when directly setting the current page. +"@AndroidEntryPoint class WelcomeDuringConferenceFragment : Fragment() { private lateinit var binding: FragmentOnboardingWelcomeDuringBinding private val viewModel: OnboardingViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentOnboardingWelcomeDuringBinding.inflate(inflater, container, false).apply { lifecycleOwner = viewLifecycleOwner } return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) binding.activityViewModel = viewModel binding.buttonSignin.doOnLayout { activity?.reportFullyDrawn() } } }" First page of onboarding showing a welcome message during the conference. +"@AndroidEntryPoint class RemoveReservationDialogFragment : AppCompatDialogFragment() { companion object { const val DIALOG_REMOVE_RESERVATION = ""dialog_remove_reservation"" private const val USER_ID_KEY = ""user_id"" private const val SESSION_ID_KEY = ""session_id"" private const val SESSION_TITLE_KEY = ""session_title"" fun newInstance( parameters: RemoveReservationDialogParameters ): RemoveReservationDialogFragment { val bundle = Bundle().apply { putString(USER_ID_KEY, parameters.userId) putString(SESSION_ID_KEY, parameters.sessionId) putString(SESSION_TITLE_KEY, parameters.sessionTitle) } return RemoveReservationDialogFragment().apply { arguments = bundle } } } private val viewModel: RemoveReservationViewModel by viewModels() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val context = requireContext() val args = requireNotNull(arguments) val sessionTitle = requireNotNull(args.getString(SESSION_TITLE_KEY)) return MaterialAlertDialogBuilder(context) .setTitle(R.string.remove_reservation_title) .setMessage(formatRemoveReservationMessage(context.resources, sessionTitle)) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.remove) { _, _ -> viewModel.removeReservation() } .create() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val sessionId = arguments?.getString(SESSION_ID_KEY) if (sessionId == null) { dismiss() } return super.onCreateView(inflater, container, savedInstanceState) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycleScope.launch { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.snackbarMessages.collect { // Using Toast instead of Snackbar as it's easier for DialogFragment Toast.makeText( requireContext(), it.messageId, if (it.longDuration) Toast.LENGTH_LONG else Toast.LENGTH_SHORT ).show() } } } } private fun formatRemoveReservationMessage( res: Resources, sessionTitle: String ): CharSequence { val text = res.getString(R.string.remove_reservation_content, sessionTitle) return text.makeBold(sessionTitle) } } data class RemoveReservationDialogParameters( val userId: String, val sessionId: SessionId, val sessionTitle: String )" Dialog that confirms the user really wants to cancel their reservation +"@AndroidEntryPoint class SwapReservationDialogFragment : AppCompatDialogFragment() { companion object { const val DIALOG_SWAP_RESERVATION = ""dialog_swap_reservation"" private const val USER_ID_KEY = ""user_id"" private const val FROM_ID_KEY = ""from_id"" private const val FROM_TITLE_KEY = ""from_title"" private const val TO_ID_KEY = ""to_id"" private const val TO_TITLE_KEY = ""to_title"" fun newInstance(parameters: SwapRequestParameters): SwapReservationDialogFragment { val bundle = Bundle().apply { putString(USER_ID_KEY, parameters.userId) putString(FROM_ID_KEY, parameters.fromId) putString(FROM_TITLE_KEY, parameters.fromTitle) putString(TO_ID_KEY, parameters.toId) putString(TO_TITLE_KEY, parameters.toTitle) } return SwapReservationDialogFragment().apply { arguments = bundle } } } @Inject lateinit var swapActionUseCase: SwapActionUseCase override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val context = requireContext() val args = requireNotNull(arguments) val userId = requireNotNull(args.getString(USER_ID_KEY)) val fromId = requireNotNull(args.getString(FROM_ID_KEY)) val fromTitle = requireNotNull(args.getString(FROM_TITLE_KEY)) val toId = requireNotNull(args.getString(TO_ID_KEY)) val toTitle = requireNotNull(args.getString(TO_TITLE_KEY)) return MaterialAlertDialogBuilder(context) .setTitle(R.string.swap_reservation_title) .setMessage(formatSwapReservationMessage(context.resources, fromTitle, toTitle)) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.swap) { _, _ -> viewLifecycleOwner.lifecycle.coroutineScope.launch { swapActionUseCase( SwapRequestParameters(userId, fromId, fromTitle, toId, toTitle) ) } } .create() } private fun formatSwapReservationMessage( res: Resources, fromTitle: String, toTitle: String ): CharSequence { val text = res.getString(R.string.swap_reservation_content, fromTitle, toTitle) return text.makeBold(fromTitle).makeBold(toTitle) } }" Dialog that confirms the user wants to replace their reservations +"class StarReserveFab( context: Context, attrs: AttributeSet ) : FloatingActionButton(context, attrs), Checkable { private var mode = RESERVE private var _checked = false set(value) { if (field != value || mode != STAR) { field = value currentDrawable = R.drawable.asld_star_event mode = STAR val contentDescRes = if (value) R.string.a11y_starred else R.string.a11y_unstarred contentDescription = context.getString(contentDescRes) refreshDrawableState() } } var reservationStatus: ReservationViewState? = null set(value) { if (value != field || mode != RESERVE) { field = value currentDrawable = R.drawable.asld_reservation mode = RESERVE if (value != null) { contentDescription = context.getString(value.contentDescription) } refreshDrawableState() } } @DrawableRes private var currentDrawable = 0 set(value) { if (field != value) { field = value setImageResource(value) } } override fun isChecked() = _checked override fun setChecked(checked: Boolean) { _checked = checked } override fun toggle() { _checked = !_checked } override fun onCreateDrawableState(extraSpace: Int): IntArray { if (!isShowingStar() && !isShowingReservation()) { return super.onCreateDrawableState(extraSpace) } val drawableState = super.onCreateDrawableState(extraSpace + 1) when { isShowingStar() -> { val state = if (_checked) stateChecked else stateUnchecked mergeDrawableStates(drawableState, state) } isShowingReservation() -> { mergeDrawableStates(drawableState, reservationStatus?.state) } } return drawableState } private fun isShowingReservation() = currentDrawable == R.drawable.asld_reservation private fun isShowingStar() = currentDrawable == R.drawable.asld_star_event companion object { private val stateChecked = intArrayOf(android.R.attr.state_checked) private val stateUnchecked = intArrayOf(-android.R.attr.state_checked) } }" +"class ReserveButton(context: Context, attrs: AttributeSet) : AppCompatImageButton(context, attrs) { var status = ReservationViewState.RESERVATION_DISABLED set(value) { if (value == field) return field = value contentDescription = context.getString(value.contentDescription) refreshDrawableState() } init { // Drawable defining drawables for each reservation state setImageResource(R.drawable.ic_reservation) status = ReservationViewState.RESERVABLE } override fun onCreateDrawableState(extraSpace: Int): IntArray { @Suppress(""SENSELESS_COMPARISON"") // Status is null during super init if (status == null) return super.onCreateDrawableState(extraSpace) val drawableState = super.onCreateDrawableState(extraSpace + 1) mergeDrawableStates(drawableState, status.state) return drawableState } }" "An [AppCompatImageButton] extension supporting multiple custom states, representing the status of a user's reservation for an event." +"enum class ReservationViewState( val state: IntArray, @StringRes val text: Int, @StringRes val contentDescription: Int ) { RESERVABLE( intArrayOf(R.attr.state_reservable), R.string.reservation_reservable, R.string.a11y_reservation_available ), WAIT_LIST_AVAILABLE( intArrayOf(R.attr.state_wait_list_available), R.string.reservation_waitlist_available, R.string.a11y_reservation_wait_list_available ), WAIT_LISTED( intArrayOf(R.attr.state_wait_listed), R.string.reservation_waitlisted, R.string.a11y_reservation_wait_listed ), RESERVED( intArrayOf(R.attr.state_reserved), R.string.reservation_reserved, R.string.a11y_reservation_reserved ), RESERVATION_PENDING( intArrayOf(R.attr.state_reservation_pending), R.string.reservation_pending, R.string.a11y_reservation_pending ), RESERVATION_DISABLED( intArrayOf(R.attr.state_reservation_disabled), R.string.reservation_disabled, R.string.a11y_reservation_disabled );" Models the different states of a reservation and a corresponding content description. +"class ReservationTextView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.textViewStyle ) : AppCompatTextView(context, attrs, defStyleAttr) { var status = ReservationViewState.RESERVABLE set(value) { if (value == field) return field = value setText(value.text) refreshDrawableState() } init { setText(ReservationViewState.RESERVABLE.text) val drawable = context.getDrawable(R.drawable.asld_reservation) setCompoundDrawablesRelativeWithIntrinsicBounds(drawable, null, null, null) } override fun onCreateDrawableState(extraSpace: Int): IntArray { @Suppress(""SENSELESS_COMPARISON"") // Status is null during super init if (status == null) return super.onCreateDrawableState(extraSpace) val drawableState = super.onCreateDrawableState(extraSpace + 1) mergeDrawableStates(drawableState, status.state) return drawableState } } Footer" "An [AppCompatTextView] extension supporting multiple custom states, representing the status of a user's reservation for an event." +"fun indexSessionHeaders(sessions: List, zoneId: ZoneId): List> { return sessions .mapIndexed { index, session -> index to TimeUtils.zonedTime(session.startTime, zoneId) } .distinctBy { it.second.truncatedTo(ChronoUnit.MINUTES) } }" Find the first session at each start time (rounded down to nearest minute) and return pairs of index to start time. Assumes that [sessions] are sorted by ascending start time. +"@HiltViewModel class ScheduleViewModel @Inject constructor( private val loadScheduleUserSessionsUseCase: LoadScheduleUserSessionsUseCase, signInViewModelDelegate: SignInViewModelDelegate, scheduleUiHintsShownUseCase: ScheduleUiHintsShownUseCase, topicSubscriber: TopicSubscriber, private val snackbarMessageManager: SnackbarMessageManager, getTimeZoneUseCase: GetTimeZoneUseCase, private val refreshConferenceDataUseCase: RefreshConferenceDataUseCase, observeConferenceDataUseCase: ObserveConferenceDataUseCase ) : ViewModel(), SignInViewModelDelegate by signInViewModelDelegate { val timeZoneId = flow { if (getTimeZoneUseCase(Unit).successOr(true)) { emit(TimeUtils.CONFERENCE_TIMEZONE) } else { emit(ZoneId.systemDefault()) } }.stateIn(viewModelScope, Lazily, TimeUtils.CONFERENCE_TIMEZONE) val isConferenceTimeZone: StateFlow = timeZoneId.mapLatest { zoneId -> TimeUtils.isConferenceTimeZone(zoneId) }.stateIn(viewModelScope, Lazily, true) private lateinit var dayIndexer: ConferenceDayIndexer private val refreshSignal = MutableSharedFlow() private val loadDataSignal: Flow = flow { emit(Unit) emitAll(refreshSignal) }" "Loads data and exposes it to the view. By annotating the constructor with [@Inject], Dagger will use that constructor when needing to create the object, so defining a [@Provides] method for this class won't be needed." +"override fun onDrawOver(c: Canvas, parent: RecyclerView, state: State) { if (timeSlots.isEmpty() || parent.isEmpty()) return val isRtl = parent.isRtl() if (isRtl) { c.save() c.translate((parent.width - width).toFloat(), 0f) } val parentPadding = parent.paddingTop var earliestPosition = Int.MAX_VALUE var previousHeaderPosition = -1 var previousHasHeader = false var earliestChild: View? = null for (i in parent.childCount - 1 downTo 0) { val child = parent.getChildAt(i) if (child == null) { Timber.w( """"""View is null. Index: $i, childCount: ${parent.childCount}, |RecyclerView.State: $state"""""".trimMargin() ) continue } if (child.y > parent.height || (child.y + child.height) < 0) { continue } val position = parent.getChildAdapterPosition(child) if (position < 0) { continue } if (position < earliestPosition) { earliestPosition = position earliestChild = child } val header = timeSlots[position] if (header != null) { drawHeader(c, child, parentPadding, header, child.alpha, previousHasHeader) previousHeaderPosition = position previousHasHeader = true } else { previousHasHeader = false } } if (earliestChild != null && earliestPosition != previousHeaderPosition) { findHeaderBeforePosition(earliestPosition)?.let { stickyHeader -> previousHasHeader = previousHeaderPosition - earliestPosition == 1 drawHeader(c, earliestChild, parentPadding, stickyHeader, 1f, previousHasHeader) } } if (isRtl) { c.restore() } }" Loop over each child and draw any corresponding headers i.e. items who's position is a key in [timeSlots]. We also look back to see if there are any headers _before_ the first header we found i.e. which needs to be sticky. +"@InstallIn(FragmentComponent::class) @Module internal class SessionViewPoolModule { @FragmentScoped @Provides @Named(""sessionViewPool"") fun providesSessionViewPool(): RecyclerView.RecycledViewPool = RecyclerView.RecycledViewPool() @FragmentScoped @Provides @Named(""tagViewPool"") fun providesTagViewPool(): RecyclerView.RecycledViewPool = RecyclerView.RecycledViewPool() }" Provides [RecyclerView.RecycledViewPool]s to share views between [RecyclerView]s. E.g. Between different days of the schedule. +@InternalStreamChatApi public const val GIPHY_INFO_DEFAULT_WIDTH_DP: Int = 200 Default width used for Giphy Images if no width metadata is available. +@InternalStreamChatApi public const val GIPHY_INFO_DEFAULT_HEIGHT_DP: Int = 200 Default height used for Giphy Images if no width metadata is available. +"public fun Attachment.giphyInfo(field: GiphyInfoType): GiphyInfo? { val giphyInfoMap =(extraData[ModelType.attach_giphy] as? Map?)?.get(field.value) as? Map? return giphyInfoMap?.let { map -> GiphyInfo( url = map[""url""] ?: """", width = getGiphySize(map, ""width"", Utils.dpToPx(GIPHY_INFO_DEFAULT_WIDTH_DP)), height = getGiphySize(map, ""height"", Utils.dpToPx(GIPHY_INFO_DEFAULT_HEIGHT_DP)) ) } }" Returns an object containing extra information about the Giphy image based on its type. +"private fun getGiphySize(map: Map, size: String, defaultValue: Int): Int { return if (!map[size].isNullOrBlank()) map[size]?.toInt() ?: defaultValue else defaultValue }" Returns specified size for the giphy. +"public data class GiphyInfo( val url: String, @Px val width: Int, @Px val height: Int, )" Contains extra information about Giphy attachments. +"@OptIn(ExperimentalCoroutinesApi::class) @InternalStreamChatApi @Suppress(""TooManyFunctions"") public class MessageComposerController( private val channelId: String, private val chatClient: ChatClient = ChatClient.instance(), private val maxAttachmentCount: Int = AttachmentConstants.MAX_ATTACHMENTS_COUNT,private val maxAttachmentSize: Long = AttachmentConstants.MAX_UPLOAD_FILE_SIZE, ) { }" "Controller responsible for handling the composing and sending of messages. It acts as a central place for both the core business logic and state required to create and send messages, handle attachments, message actions and more. If you require more state and business logic, compose this Controller with your code and apply the necessary changes." +private val scope = CoroutineScope(DispatcherProvider.Immediate) Creates a [CoroutineScope] that allows us to cancel the ongoing work when the parent  ViewModel is disposed. +"public var typingUpdatesBuffer: TypingUpdatesBuffer = DefaultTypingUpdatesBuffer( onTypingStarted = ::sendKeystrokeEvent, onTypingStopped = ::sendStopTypingEvent, coroutineScope = scope )" Buffers typing updates. +"public val channelState: Flow = chatClient.watchChannelAsState( cid = channelId, messageLimit = DefaultMessageLimit, coroutineScope = scope ).filterNotNull()" Holds information about the current state of the [Channel]. +"public val ownCapabilities: StateFlow> = channelState.flatMapLatest { it.channelData } .map { it.ownCapabilities } .stateIn( scope = scope, started = SharingStarted.Eagerly, initialValue = setOf() )" Holds information about the abilities the current user is able to exercise in the given channel. +"private val canSendTypingUpdates = ownCapabilities.map { it.contains(ChannelCapabilities.SEND_TYPING_EVENTS) } .stateIn( scope = scope, started = SharingStarted.Eagerly, initialValue = false )" Signals if the user's typing will send a typing update in the given channel. +"private val canSendLinks = ownCapabilities.map { it.contains(ChannelCapabilities.SEND_LINKS) }.stateIn(scope = scope,started = SharingStarted.Eagerly,initialValue = false)" Signals if the user is allowed to send links. +"private val isSlowModeActive = ownCapabilities.map { it.contains(ChannelCapabilities.SLOW_MODE) } .stateIn( scope = scope, started = SharingStarted.Eagerly, initialValue = false )" Signals if the user needs to wait before sending the next message. +public val state: MutableStateFlow = MutableStateFlow(MessageComposerState()) Full message composer state holding all the required information. +"public val input: MutableStateFlow = MutableStateFlow("""")" UI state of the current composer input. +public val alsoSendToChannel: MutableStateFlow = MutableStateFlow(false) If the message will be shown in the channel after it is sent. +public val cooldownTimer: MutableStateFlow = MutableStateFlow(0) Represents the remaining time until the user is allowed to send the next message. +public val selectedAttachments: MutableStateFlow> = MutableStateFlow(emptyList()) "Represents the currently selected attachments, that are shown within the composer UI." +public val validationErrors: MutableStateFlow> = MutableStateFlow(emptyList()) Represents the list of validation errors for the current text input and the currently selected attachments. +public val mentionSuggestions: MutableStateFlow> = MutableStateFlow(emptyList()) Represents the list of users that can be used to autocomplete the current mention input. +public val commandSuggestions: MutableStateFlow> = MutableStateFlow(emptyList()) Represents the list of commands that can be executed for the channel. +private var users: List = emptyList() Represents the list of users in the channel. +private var commands: List = emptyList() Represents the list of available commands in the channel. +private var maxMessageLength: Int = DefaultMaxMessageLength Represents the maximum allowed message length in the message input. +private var cooldownTimerJob: Job? = null Represents the coroutine [Job] used to update the countdown +private var cooldownInterval: Int = 0 Represents the cooldown interval in seconds. +public val messageMode: MutableStateFlow = MutableStateFlow(MessageMode.Normal) "Current message mode, either [MessageMode.Normal] or [MessageMode.MessageThread]. Used to determine if we're sending a thread reply or a regular message." +public val messageActions: MutableStateFlow> = MutableStateFlow(mutableSetOf()) "Set of currently active message actions. These are used to display different UI in the composer, as well as help us decorate the message with information, such as the quoted message id." +public val lastActiveAction: Flow get() = messageActions.map { actions -> actions.lastOrNull { it is Edit || it is Reply } } "Represents a Flow that holds the last active [MessageAction] that is either the [Edit], [Reply]." +private val activeAction: MessageAction? get() = messageActions.value.lastOrNull { it is Edit || it is Reply } "Gets the active [Edit] or [Reply] action, whichever is last, to show on the UI." +private val isInEditMode: Boolean get() = activeAction is Edit "Gives us information if the active action is Edit, for business logic purposes." +private val parentMessageId: String? get() = (messageMode.value as? MessageMode.MessageThread)?.parentMessage?.id "Gets the parent message id if we are in thread mode, or null otherwise." +private val messageText: String get() = input.value Gets the current text input in the message composer.  +private val isInThread: Boolean get() = messageMode.value is MessageMode.MessageThread "Gives us information if the composer is in the ""thread"" mode." +private val selectedMentions: MutableSet = mutableSetOf() Represents the selected mentions based on the message suggestion list. +init { channelState.flatMapLatest { it.channelConfig }.onEach { maxMessageLength = it.maxMessageLength commands = it.commands state.value = state.value.copy(hasCommands = commands.isNotEmpty()) }.launchIn(scope)  channelState.flatMapLatest { it.members }.onEach { members -> users = members.map { it.user } }.launchIn(scope)  channelState.flatMapLatest { it.channelData }.onEach { cooldownInterval = it.cooldown }.launchIn(scope)  setupComposerState() } Sets up the data loading operations such as observing the maximum allowed message length. +private fun setupComposerState() { input.onEach { input -> state.value = state.value.copy(inputValue = input) }.launchIn(scope)  selectedAttachments.onEach { selectedAttachments -> state.value = state.value.copy(attachments = selectedAttachments) }.launchIn(scope)  lastActiveAction.onEach { activeAction -> state.value = state.value.copy(action = activeAction) }.launchIn(scope)  validationErrors.onEach { validationErrors -> state.value = state.value.copy(validationErrors = validationErrors) }.launchIn(scope)  mentionSuggestions.onEach { mentionSuggestions -> state.value = state.value.copy(mentionSuggestions = mentionSuggestions) }.launchIn(scope)  commandSuggestions.onEach { commandSuggestions -> state.value = state.value.copy(commandSuggestions = commandSuggestions) }.launchIn(scope)  cooldownTimer.onEach { cooldownTimer -> state.value = state.value.copy(coolDownTime = cooldownTimer) }.launchIn(scope)  messageMode.onEach { messageMode -> state.value = state.value.copy(messageMode = messageMode) }.launchIn(scope)  alsoSendToChannel.onEach { alsoSendToChannel -> state.value = state.value.copy(alsoSendToChannel = alsoSendToChannel) }.launchIn(scope)  ownCapabilities.onEach { ownCapabilities -> state.value = state.value.copy(ownCapabilities = ownCapabilities) }.launchIn(scope) } Sets up the observing operations for various composer states. +public fun setMessageInput(value: String) { this.input.value = value  if (canSendTypingUpdates.value) { typingUpdatesBuffer.onKeystroke() } handleMentionSuggestions() handleCommandSuggestions() handleValidationErrors() } Called when the input changes and the internal state needs to be updated. +public fun setMessageMode(messageMode: MessageMode) { this.messageMode.value = messageMode } Called when the message mode changes and the internal state needs to be updated. +public fun setAlsoSendToChannel(alsoSendToChannel: Boolean) { this.alsoSendToChannel.value = alsoSendToChannel } "Called when the ""Also send as a direct message"" checkbox is checked or unchecked." +"public fun performMessageAction(messageAction: MessageAction) { when (messageAction) { is ThreadReply -> { setMessageMode(MessageMode.MessageThread(messageAction.message)) } is Reply -> { messageActions.value = messageActions.value + messageAction } is Edit -> { input.value = messageAction.message.text selectedAttachments.value = messageAction.message.attachments messageActions.value = messageActions.value + messageAction } else -> { // no op, custom user action } } }" Handles selected [messageAction]. We only have three actions we can react to in the composer: +"public fun dismissMessageActions() { if (isInEditMode) { setMessageInput("""") this.selectedAttachments.value = emptyList(  }) this.messageActions.value = emptySet() }" Dismisses all message actions from the UI and clears the input if [isInEditMode] is true. +public fun addSelectedAttachments(attachments: List) { val newAttachments = (selectedAttachments.value + attachments).distinctBy { if (it.name != null) { it.name } else { it } } selectedAttachments.value = newAttachments  handleValidationErrors() } "Stores the selected attachments from the attachment picker. These will be shown in the UI, within the composer component. We upload and send these attachments once the user taps on the send button." +public fun removeSelectedAttachment(attachment: Attachment) { selectedAttachments.value = selectedAttachments.value - attachment  handleValidationErrors() } "Removes a selected attachment from the list, when the user taps on the cancel/delete button." +"public fun clearData() { input.value = """" selectedAttachments.value = emptyList() validationErrors.value = emptyList() alsoSendToChannel.value = false }" Clears all the data from the input - both the current [input] value and the [selectedAttachments]. +"public fun sendMessage(message: Message) { val activeMessage = activeAction?.message ?: message val sendMessageCall = if (isInEditMode && !activeMessage.isModerationFailed(chatClient)) { getEditMessageCall(message) } else { message.showInChannel = isInThread && alsoSendToChannel.value val (channelType, channelId) = message.cid.cidToTypeAndId() if (activeMessage.isModerationFailed(chatClient)) { chatClient.deleteMessage(activeMessage.id, true).enqueue() }  chatClient.sendMessage(channelType, channelId, message) }  dismissMessageActions() clearData()  sendMessageCall.enqueueAndHandleSlowMode() }" "Sends a given message using our Stream API. Based on [isInEditMode], we either edit an existing message, or we send a new message, using [ChatClient]. In case the message is a moderated message the old one is deleted before the replacing one is sent." +"public fun buildNewMessage( message: String, attachments: List = emptyList(), ): Message { val activeAction = activeAction  val trimmedMessage = message.trim() val activeMessage = activeAction?.message ?: Message() val replyMessageId = (activeAction as? Reply)?.message?.id val mentions = filterMentions(selectedMentions, trimmedMessage)  return if (isInEditMode && !activeMessage.isModerationFailed(chatClient)) { activeMessage.copy( text = trimmedMessage, attachments = attachments.toMutableList(), mentionedUsersIds = mentions ) } else { Message( cid = channelId, text = trimmedMessage, parentId = parentMessageId, replyMessageId = replyMessageId, attachments = attachments.toMutableList(), mentionedUsersIds = mentions ) } }" "Builds a new [Message] to send to our API. If [isInEditMode] is true, we use the current action's message and apply the given changes." +"private fun filterMentions(selectedMentions: Set, message: String): MutableList {val text = message.lowercase()val remainingMentions =selectedMentions.filter {text.contains(""@${it.name.lowercase()}"")}.map { it.id }this.selectedMentions.clear()return remainingMentions.toMutableList()}" Filters the current input and the mentions the user selected from the suggestion list. Removes any mentions which are selected but no longer present in the input. +public fun leaveThread() {setMessageMode(MessageMode.Normal)dismissMessageActions() } "Updates the UI state when leaving the thread, to switch back to the [MessageMode.Normal], by calling [setMessageMode]." +public fun onCleared() {typingUpdatesBuffer.clear()scope.cancel()} Cancels any pending work when the parent ViewModel is about to be destroyed. +"private fun handleValidationErrors() {validationErrors.value = mutableListOf().apply {val message = input.valueval messageLength = message.length if (messageLength > maxMessageLength) {add( ValidationError.MessageLengthExceeded(messageLength = messageLength,maxMessageLength = maxMessageLength))} val attachmentCount = selectedAttachments.value.size if (attachmentCount > maxAttachmentCount) { add( ValidationError.AttachmentCountExceeded( attachmentCount = attachmentCount, maxAttachmentCount = maxAttachmentCount ) ) }  val attachments: List = selectedAttachments.value .filter { it.fileSize > maxAttachmentSize } if (attachments.isNotEmpty()) { add( ValidationError.AttachmentSizeExceeded( attachments = attachments, maxAttachmentSize = maxAttachmentSize ) ) } if (!canSendLinks.value && message.containsLinks()) { add( ValidationError.ContainsLinksWhenNotAllowed ) } } }" Checks the current input for validation errors. +"public fun selectMention(user: User) { val augmentedMessageText = ""${messageText.substringBeforeLast(""@"")}@${user.name} ""  setMessageInput(augmentedMessageText) selectedMentions += user }" Autocompletes the current text input with the mention from the selected user. +"public fun selectCommand(command: Command) { setMessageInput(""/${command.name} "") }" Switches the message composer to the command input mode. +public fun toggleCommandsVisibility() { val isHidden = commandSuggestions.value.isEmpty()  commandSuggestions.value = if (isHidden) commands else emptyList() } Toggles the visibility of the command suggestion list popup. +public fun dismissSuggestionsPopup() { mentionSuggestions.value = emptyList() commandSuggestions.value = emptyList() } Dismisses the suggestions popup above the message composer. +"private fun handleMentionSuggestions() { val containsMention = MentionPattern.matcher(messageText).find()  mentionSuggestions.value = if (containsMention) { users.filter { it.name.contains(messageText.substringAfterLast(""@""), true) } } else { emptyList() } }" Shows the mention suggestion list popup if necessary. +"private fun handleCommandSuggestions() { val containsCommand = CommandPattern.matcher(messageText).find()  commandSuggestions.value = if (containsCommand && selectedAttachments.value.isEmpty()) { val commandPattern = messageText.removePrefix(""/"") commands.filter { it.name.startsWith(commandPattern) } } else { emptyList() } }" Shows the command suggestion list popup if necessary. +private fun Call.enqueueAndHandleSlowMode() { if (cooldownInterval > 0 && isSlowModeActive.value && !isInEditMode) { cooldownTimerJob?.cancel()  cooldownTimer.value = cooldownInterval enqueue { if (it.isSuccess || !chatClient.clientState.isNetworkAvailable) { cooldownTimerJob = scope.launch { for (timeRemaining in cooldownInterval downTo 0) { cooldownTimer.value = timeRemaining delay(OneSecond) } } } else { cooldownTimer.value = 0 } } } else { enqueue() } } Executes the message Call and shows cooldown countdown timer instead of send button when slow mode is enabled.  +private fun getEditMessageCall(message: Message): Call { return chatClient.updateMessage(message) } Gets the edit message call using [ChatClient]. +"private fun sendKeystrokeEvent() { val (type, id) = channelId.cidToTypeAndId()  chatClient.keystroke(type, id, parentMessageId).enqueue() }" Makes an API call signaling that a typing event has occurred. +"private fun sendStopTypingEvent() { val (type, id) = channelId.cidToTypeAndId()  chatClient.stopTyping(type, id, parentMessageId).enqueue() }" Makes an API call signaling that a stop typing event has occurred. +public sealed class ModeratedMessageOption(public val text: Int) Represents possible options user can take upon moderating a message. +public object SendAnyway : ModeratedMessageOption(R.string.stream_ui_moderation_dialog_send) Prompts the user to send the message anyway if the message was flagged by moderation. +public object EditMessage : ModeratedMessageOption(R.string.stream_ui_moderation_dialog_edit) Prompts the user to edit the message if the message was flagged by moderation. +public object DeleteMessage : ModeratedMessageOption(R.string.stream_ui_moderation_dialog_delete) Prompts the user to delete the message if the message was flagged by moderation. +"public class CustomModerationOption( text: Int, public val extraData: Map = emptyMap(), ) : ModeratedMessageOption(text)" Custom actions that you can define for moderated messages. +"@InternalStreamChatApi public fun defaultMessageModerationOptions(): List = listOf( SendAnyway, EditMessage, DeleteMessage )" return A list of [ModeratedMessageOption] to show to the user. +"@StreamHandsOff( reason = ""This class shouldn't be renamed without verifying it works correctly on Chat Client Artifacts because "" + ""we are using it by reflection"" ) public class StreamCoilUserIconBuilder(private val context: Context) : UserIconBuilder { override suspend fun buildIcon(user: User): IconCompat? = StreamImageLoader .instance() .loadAsBitmap(context, user.image, StreamImageLoader.ImageTransformation.Circle) ?.let(IconCompat::createWithBitmap) }" "Produces an [IconCompat] using Coil, which downloads and caches the user image." +public class CoilDisposable(private val disposable: coil.request.Disposable) : Disposable {override val isDisposed: Boolean get() = disposable.isDisposed Wrapper around the Coil Disposable. +override fun dispose() { disposable.dispose() } } Dispose all the source. Use it when the resource is already used or the result is no longer needed. +"private fun setPassword(value:String) { _uiState.value = uiState.value.copy(password = InputWrapper(value = value)) viewModelScope.launch(Dispatchers.IO) { when(val error = getPasswordFieldErrors()) {null -> { _uiState.value = uiState.value.copy( passErrorState = PasswordErrorState( length = false, lowerUpper = false, containsNumber = false, containsSpecial = false ) ) } else -> { _uiState.value = uiState.value.copy( passErrorState = PasswordErrorState( length = error.validLength, lowerUpper = error.validLowerUpper, containsNumber = error.validNumber, containsSpecial = error.validSpecial ) ) } } } }" Function to save the user entered password in the UI state Also handles the error state for the password requirements +"private fun setCompanyName(companyName: String) { _uiState.value = uiState.value.copy(companyName = InputWrapper(value = companyName, errorId = null) ) }" This method save company name entered in the UI form +"private fun setAddress( address1: String? = null, address2: String? = null, address3: String? = null, city: String? = null, zipcode: String? = null ) { if (address1 != null) { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( address1 = InputWrapper(value = address1, errorId = null) ) ) } if (address2 != null) { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( address2 = InputWrapper(value = address2, errorId = null) ) ) } if (address3 != null) { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( address3 = InputWrapper(value = address3, errorId = null) ) ) } if (city != null) { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( city = InputWrapper(value = city, errorId = null) ) ) } if (zipcode != null) { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( zipcode = InputWrapper(value = zipcode, errorId = null) ) ) } }" This method save the address fields in the UI form +private fun setConfirmPassword(value: String) { _uiState.value = uiState.value.copy(confirmPassword = InputWrapper(value = value)) } Function to save the user entered confirm password in the UI state +private fun userNameChanged(userName: String) { _uiState.value = uiState.value.copy(userName = InputWrapper(value = userName)) } Function to change the username +"private fun useEmailAsUserName(value: Boolean) { _uiState.value = uiState.value.copy( emailAsUser = value, userName = uiState.value.email ) }" Function to change the state of the checkbox for user email as username +private fun matchResultSelected(result: MatchResult) {_uiState.value = uiState.value.copy( selectedMatchResult = result ) } Saves the selected Matched result from the DuplicateCheck Screen in the UI State this will be useful in further userflow of Contact Admin +private fun yourNameUpdated(name: String) { _uiState.value = uiState.value.copy( yourName = InputWrapper(value = name) ) } This function save and updated the UIState with the user provided input for UserName +private fun userPhoneUpdated(number: String) { _uiState.value = uiState.value.copy( userPhone = InputWrapper(value = number) ) } This function saves and updates the UIState with the user provided input for Phone number +private fun userMessageUpdated(message: String) { _uiState.value = uiState.value.copy( userMessage = InputWrapper(value = message) ) } This function updates the custom user message entered +"private fun sendEmailClicked() { ReCaptchaService.validateWithEnterpriseReCaptchaService( null, ReCaptchaEventEnum.CONTACT_ADMIN) }" This function trigger the user flow further to process the send email request +private fun setFirstName(name: String) { _uiState.value = uiState.value.copy( firstName = InputWrapper(value = name) ) } Saves the first name entered on the userinformation screen +private fun setLastName(last: String) { _uiState.value = uiState.value.copy( lastName = InputWrapper(value = last) ) } This functions saves the Last name entered on the user information screen +private fun setBusinessRole(business: String) { _uiState.value = uiState.value.copy( selectedBusinessRole = business ) } This functions saves the business role entered on the user information screen +private fun setOtherBusinessRole(role: String) { _uiState.value = uiState.value.copy( selectedOtherBusinessRole = role ) } This function saves the other business role entered by the user +"fun handleRegistrationScreenEvent(registrationScreenEvent: RegistrationScreenEvent) { when(registrationScreenEvent) { is RegistrationScreenEvent.TouClicked -> { _uiState.value = uiState.value.copy( isTouChecked = registrationScreenEvent.checked, displayTouError = false ) } is RegistrationScreenEvent.PrivacyStatementClicked -> { _uiState.value = uiState.value.copy( isPrivacyStatementChecked = registrationScreenEvent.checked, displayPrivacyStatementError = false ) } is RegistrationScreenEvent.NextClicked -> { navigateToNextScreen(registrationScreenEvent.registrationScreenType) } is RegistrationScreenEvent.SignInClicked -> {  } is RegistrationScreenEvent.ShowError -> { val pError = uiState.value.privacyStatementVisible && !uiState.value.isPrivacyStatementChecked val tError = uiState.value.touVisible && !uiState.value.isTouChecked _uiState.value = uiState.value.copy( displayPrivacyStatementError = pError, displayTouError = tError ) } is RegistrationScreenEvent.CompanyNameUpdated -> { setCompanyName(registrationScreenEvent.name) } is RegistrationScreenEvent.AddressFieldsUpdated -> { setAddress( address1 = registrationScreenEvent.address1, address2 = registrationScreenEvent.address2, address3 = registrationScreenEvent.address3, city = registrationScreenEvent.city, zipcode = registrationScreenEvent.zipCode ) } is RegistrationScreenEvent.CountrySelected -> { updateCountryList(registrationScreenEvent.index) } is RegistrationScreenEvent.StateSelected -> { saveSelectedState(registrationScreenEvent.index) } is RegistrationScreenEvent.RecommendationSelected -> { _uiState.value = uiState.value.copy( isRecommendedSelected = registrationScreenEvent.isSelected ) } is RegistrationScreenEvent.RecommendationConfirmed -> { _uiState.value = uiState.value.copy( recommendedScreenSeen = true ) navigateToNextScreen(RegistrationScreenType.CompanyInformationScreen()) } is RegistrationScreenEvent.EmailChanged -> { setEmail(registrationScreenEvent.emailAddress) } is RegistrationScreenEvent.PasswordChanged -> { setPassword(registrationScreenEvent.password) } is RegistrationScreenEvent.ConfirmPasswordChanged -> { setConfirmPassword(registrationScreenEvent.confirmPassword) } is RegistrationScreenEvent.UserEmailAsUsername -> { useEmailAsUserName(registrationScreenEvent.checked) } is RegistrationScreenEvent.UserNameChanged -> { userNameChanged(registrationScreenEvent.userName) } is RegistrationScreenEvent.SelectedMatchedResult -> { matchResultSelected(registrationScreenEvent.result) } is RegistrationScreenEvent.ContinueNewAccountClicked -> { navigateToNextScreen(RegistrationScreenType.UserInformationScreen()) } is RegistrationScreenEvent.UserNameUpdated -> { yourNameUpdated(registrationScreenEvent.name) } is RegistrationScreenEvent.UserPhoneUpdated -> { userPhoneUpdated(registrationScreenEvent.number) } is RegistrationScreenEvent.SendEmailClicked -> { sendEmailClicked() } is RegistrationScreenEvent.UserMessageUpdated -> { userMessageUpdated(registrationScreenEvent.message) } is RegistrationScreenEvent.DifferentAccount -> { viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenAccountReviewScreen) } } is RegistrationScreenEvent.ContinueNewAccount -> { viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenAccountInformationScreen) } } is RegistrationScreenEvent.FirstNameUpdated -> { setFirstName(registrationScreenEvent.firstName) } is RegistrationScreenEvent.LastNameUpdated -> { setLastName(registrationScreenEvent.lastName) } is RegistrationScreenEvent.BusinessRoleUpdated -> { setBusinessRole(registrationScreenEvent.businessRole) } is RegistrationScreenEvent.OtherBusinessRoleUpdated -> { setOtherBusinessRole(registrationScreenEvent.otherBusinessRole) } } }" @param registrationScreenEvent - [RegistrationScreenEvent] is a class which holds multiple Events types from UI to ViewModel This method helps in communicating the UI events from Registration Screen and ViewModel. Any future Event that is added needs to be added in the as well. +"private fun navigateToNextScreen(screenType: RegistrationScreenType) { when(screenType) { is RegistrationScreenType.CompanyInformationScreen -> { viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenCompanyInformationScreen) } _uiState.value = uiState.value.copy( dotPagerList = listOf( Dot(completed = true),Dot(),Dot(),Dot()),isLoading = true)getCountryData() getCountryStateData() } is RegistrationScreenType.AgreementsScreen -> {  } is RegistrationScreenType.AccountInformationScreen -> { _uiState.value = uiState.value.copy( signInProcessing = true ) //Starting DQM string checking API call, if error t val parameters = JsonObject() parameters.addProperty(""name"",uiState.value.companyName.value) dqmStringCheckerForCompanyName(parameters) getAddressFieldErrorsOrNull() } is RegistrationScreenType.RecommendationScreen -> { viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenRecommendationScreen) } } is RegistrationScreenType.AccountReviewScreen -> { _uiState.value = uiState.value.copy( signInProcessing = true, dotPagerList = listOf( Dot(completed = true), Dot(completed = true), Dot(completed = true), Dot() ) ) when(val validationResult = validateAccountInformationScreen()) { null -> { goToUniqueUserNameCheck() } else -> { displayAccountInformationErrors(validationResult) } } } is RegistrationScreenType.UserInformationScreen -> { viewModelScope.launch(Dispatchers.Main) { _uiState.value = uiState.value.copy( signInProcessing = true ) navigationEvent.emit(RegistrationNavigationEvent.OpenUserInformationScreen) getBusinessRoles() } } is RegistrationScreenType.SignUpEmailConfirmationScreen -> { when(val validationResult = validateUserInformationScreen()) { null -> { _uiState.value = uiState.value.copy( signInProcessing = true ) dqmStringCheckForFirstName() } else  > { displayUserInformationErrors(validationResult) } } } } }" This method navigates the registration flow to the next appropriate screen for the registration +"private fun getCountryData() {viewModelScope.launch(Dispatchers.IO) {inputStreamForCountriesJSONObject = CountriesRegistrationFormat.instance.getCountriesRegistrationFormat() selectedCountriesJSONObject = inputStreamForCountriesJSONObject!!.optJSONArray(LocaleUtils.instance.localeCountry) for (i in 0 until selectedCountriesJSONObject!!.length()) { val selectedCountryAttributes = selectedCountriesJSONObject!!.optJSONObject(i) val keyAttribute = selectedCountryAttributes!!.optString(""name"") val keyAttributeRequired = selectedCountryAttributes.optBoolean(""required"") when (keyAttribute) { ""PROVINCE"" -> { } ""STATE"" -> { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( selectedState = _uiState.value.addressFields.selectedState.copy( isRequired = keyAttributeRequired ) ) ) } ""POSTAL_CODE"" -> { } ""ZIP_CODE"" -> { _uiState.value = uiState.value.copy( addressFields = uiState.value.addressFields.copy( zipcode = uiState.value.addressFields.zipcode.copy( isRequired = keyAttributeRequired ) ) ) } ""STREET1"" -> { _uiState.value = uiState.value.copy( addressFields = uiState.value.addressFields.copy( address1 = uiState.value.addressFields.address1.copy( isRequired = keyAttributeRequired ) ) ) } ""STREET2"" -> { _uiState.value = uiState.value.copy( addressFields = uiState.value.addressFields.copy( address2 = uiState.value.addressFields.address2.copy( isRequired = keyAttributeRequired ) ) ) } ""STREET3"" -> { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( address3 = _uiState.value.addressFields.address3.copy( isRequired = keyAttributeRequired ) ) ) } ""STREET4"" -> { } ""MUNICIPALITY"" -> { //Ying confirmed no Latin for Municipality in AN and API call } ""CITY"" -> { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( city = _uiState.value.addressFields.city.copy( isRequired = keyAttributeRequired ) ) ) } ""STATE_TEXT"" -> { } ""COUNTRY"" -> { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( selectedCountry = _uiState.value.addressFields.selectedCountry.copy( isRequired = keyAttributeRequired ) ) ) } } } } }" implementation for taking the fields required for the Company information Form +"private fun getCountryStateData() { viewModelScope.launch(Dispatchers.IO) { when(val result = getCountryDataUseCase.getCountryState( fullUrl = NetworkingService.instance.getOnboardingAPIURL(""onboarding/countries-states""), headers = NetworkingService.instance.anAccessTokenHeadersForSignUp )) { is RemoteResponse.Success -> { _uiState.value = uiState.value.copy( countryOptions = result.value.countries, isLoading = false ) } is RemoteResponse.Failure -> {  } } } }" This method gets the list of all the countries and states for all of the countries in the world +"private fun updateCountryList(countrySelected: Int) { _uiState.value = uiState.value.copy( addressFields = uiState.value.addressFields.copy( selectedCountry = uiState.value.addressFields.selectedCountry.copy( value = uiState.value.countryOptions[countrySelected].name ), selectedIso2Code = uiState.value.countryOptions[countrySelected].isoA2Code, selectedIso3Code = uiState.value.countryOptions[countrySelected].isoA3Code ), stateList = uiState.value.countryOptions[countrySelected].states?: listOf() ) if (uiState.value.countryOptions[countrySelected].isoA2Code.equals(""US"",ignoreCase = true)) { _uiState.value = uiState.value.copy( isZipCodeVerificationRequired = true ) } else { _uiState.value = uiState.value.copy( isZipCodeVerificationRequired = false ) } }" This method saves the selected country in the view-state and also updates the state list to be shown in the State dropdown menu +private fun saveSelectedState(stateSelected: Int) { _uiState.value = uiState.value.copy( addressFields = uiState.value.addressFields.copy( selectedState = uiState.value.addressFields.selectedState.copy( value = uiState.value.stateList[stateSelected].name ) ) ) _uiState.value = uiState.value.copy( selectedStateAbb = uiState.value.stateList[stateSelected].regionCode ) } This method saves the selected state in the View-state +"private fun dqmStringCheckForFirstName() { val parameters = JsonObject() parameters.addProperty(""userFirstName"", uiState.value.firstName.value) viewModelScope.launch(Dispatchers.IO) { when(val result = getCountryDataUseCase.checkDqmStringChecker( body = parameters )) { is RemoteResponse.Success -> { result.value.results.forEach { if (it.fieldName == ""CP_FIRSTNAME"" && it.severity == ""E"") { when (val value = validateUserInformationScreen(errorTypeForFirst = ErrorType.Error)) { null -> {  } else -> { displayUserInformationErrors(value) } } } else if (it.fieldName == ""CP_FIRSTNAME"" && it.severity == ""W"") { when (val value = validateUserInformationScreen(errorTypeForFirst = ErrorType.Warning)) { null -> {  } else -> { displayUserInformationErrors(value) } } } else if (it.fieldName == ""CP_FIRSTNAME"" && it.valid) { dqmStringCheckForLastName() } } } is RemoteResponse.Failure -> {  } } } }" This function runs the dqm checker API for the first name +"private fun dqmStringCheckForLastName() { val userParams = JsonObject() userParams.addProperty(""userLastName"", uiState.value.lastName.value) viewModelScope.launch(Dispatchers.IO) { when(val result = getCountryDataUseCase.checkDqmStringChecker( body = userParams )) { is RemoteResponse.Success -> { result.value.results.forEach { if(it.fieldName == ""CP_LASTNAME"" && it.severity == ""E"") { when(val value = validateUserInformationScreen(errorTypeForLast = ErrorType.Error)) { null -> { } else -> { displayUserInformationErrors(value) } } } else if(it.fieldName == ""CP_LASTNAME"" && it.severity == ""W"") { when(val value = validateUserInformationScreen(errorTypeForLast = ErrorType.Warning)) { null -> { } else -> { displayUserInformationErrors(value) } } } else if (it.fieldName == ""CP_LASTNAME"" && it.valid) { ReCaptchaService.validateWithEnterpriseReCaptchaService( null, ReCaptchaEventEnum.CREATE_ACCOUNT ) } } } is RemoteResponse.Failure -> { } } } }" This function runs the dqm checker API for the last name +"private fun dqmStringCheckerForCompanyName(parameters: JsonObject) { viewModelScope.launch(Dispatchers.IO) { when(val result = getCountryDataUseCase.checkDqmStringChecker( body = parameters )) { is RemoteResponse.Success -> { result.value.results.forEach { // Check if the company name has errors if (it.fieldName == ""ACCOUNT_NAME"" && it.severity == ""E"" && !it.valid) { when(val value = getCompanyNameErrorsOrNull(ErrorType.Error)) { // if there are no errors then proce null -> { } //if error are there display errors else -> displayCompanyInfoErrors(value) } } else if(it.fieldName == ""ACCOUNT_NAME"" && it.severity == ""W"") { when(val value = getCompanyNameErrorsOrNull(ErrorType.Warning)) { null -> { when(val addressValidation = getAddressFieldErrorsOrNull()) { null -> { } else -> { displayCompanyInfoErrors(addressValidation) } } } else -> displayCompanyInfoErrors(value) } } else { when (val addressValidation = getAddressFieldErrorsOrNull()) { null -> { if (uiState.value.isZipCodeVerificationRequired == true) { checkZipCode() } else { } } else -> { displayCompanyInfoErrors(addressValidation) } } } } } is RemoteResponse.Failure -> { } } } }" Post DQM string checker API call is made to check the error in the registration form +"private fun proceedToAccountCreationApiCall(): JSONObject { val userParams = JSONObject() val createParams = JSONObject() val supplierParams = JSONObject() val addressParams = JSONObject() val touArr = JSONArray() userParams.putOpt(""userId"", uiState.value.userName.value) userParams.putOpt(""password"", uiState.value.password.value) userParams.putOpt(""firstName"",uiState.value.firstName.value) userParams.putOpt(""lastName"",uiState.value.lastName.value) userParams.putOpt(""language"",Resources.getSystem().configuration.locale.language) userParams.putOpt(""email"",uiState.value.email.value) userParams.putOpt(""businessRole"", uiState.value.selectedBusinessRole) if (uiState.value.selectedBusinessRole == ""OTHER"") { userParams.putOpt(""businessRoleOtherValue"", uiState.value.selectedOtherBusinessRole) } createParams.putOpt(""user"", userParams) addressParams.putOpt(""street1"", uiState.value.addressFields.address1.value?:"""") addressParams.putOpt(""street2"", uiState.value.addressFields.address2.value?:"""") addressParams.putOpt(""street3"", uiState.value.addressFields.address3.value?:"""") addressParams.putOpt(""city"", uiState.value.addressFields.city.value?:"""") addressParams.putOpt(""state"", uiState.value.addressFields.address1.value?:"""") addressParams.putOpt(""isoStateCode"", uiState.value.selectedStateAbb?:"""") addressParams.putOpt(""postalCode"", uiState.value.addressFields.zipcode.value?:"""") addressParams.putOpt(""isoCountryCode"",uiState.value.addressFields.selectedIso2Code?:"""") supplierParams.putOpt(""name"", uiState.value.companyName.value) supplierParams.putOpt(""accountType"", ""LIGHT"") supplierParams.putOpt(""routingEmail"", uiState.value.email.value) supplierParams.putOpt(""address"", addressParams) createParams.putOpt(""supplier"", supplierParams) createParams.putOpt(""source"", ""MOBILE"") touArr.put(""TOU_UNIFIED"") touArr.put(""SYSTEM_PRIVACY_STATEMENT"") createParams.putOpt(""documentTypes"", touArr) return createParams } private fun proceedToContactAdminEmailConfirmationScreen() { viewModelScope.launch(Dispatchers.IO) { navigationEvent.emit(RegistrationNavigationEvent.OpenContactAdminEmailConfirmationScreen) } }" This function creates the param required for account creation and makes the api call for the account creation. Based on the response received from the API call it navigates the UI flow further. +"private suspend fun goToDuplicateCheck(isContactAdmin: Boolean = false) { val userParams = JsonObject() userParams.addProperty(""companyName"", uiState.value.companyName.value) userParams.addProperty(""city"", uiState.value.addressFields.city.value) userParams.addProperty(""email"", uiState.value.email.value) userParams.addProperty(""username"", uiState.value.userName.value) userParams.addProperty(""country"", uiState.value.addressFields.selectedIso3Code) when (val dupResult = getAccountInformationUseCase.getDuplicateResult( url = NetworkingService.instance.getOnboardingAPIURL(""onboarding/dupcheck""), headers = if (isContactAdmin) { NetworkingService.instance.anAccessTokenHeadersForGoogleRecaptchaForContactAdmin } else { NetworkingService.instance.anAccessTokenHeadersForGoogleRecaptcha }, body = userParams )) { is RemoteResponse.Success -> { if (dupResult.value.matchResults.isEmpty()) { _uiState.value = uiState.value.copy( signInProcessing = false ) //TODO go to next step in sign up } else { _uiState.value = uiState.value.copy( signInProcessing = false, matchedResult = dupResult.value.matchResults ) navigationEvent.emit(RegistrationNavigationEvent.OpenAccountReviewScreen) } } is RemoteResponse.Failure -> { } } }" Function to make the api call for the Duplicate check of the account and provide the recommendation +"private fun getCompanyNameErrorsOrNull(errorType: ErrorType): InputErrors? { val companyNameError = InputValidator.getDqmErrorIdOrNull(errorType) return if (companyNameError == null) { null } else { InputErrors(companyNameError,null, null,null,null,null,null,null,null) } }" Util function for checking if the company name field has any error or not +"private fun getAddressFieldErrorsOrNull(): InputErrors? { val address1 = InputValidator.checkIfFieldRequired(uiState.value.addressFields.address1.value?:"""", uiState.value.addressFields.address1.isRequired) val address2 = InputValidator.checkIfFieldRequired(uiState.value.addressFields.address2.value?:"""", uiState.value.addressFields.address2.isRequired) val address3 = InputValidator.checkIfFieldRequired(uiState.value.addressFields.address3.value?:"""", uiState.value.addressFields.address3.isRequired) val city = InputValidator.checkIfFieldRequired(uiState.value.addressFields.city.value?:"""", uiState.value.addressFields.city.isRequired) val state = InputValidator.checkIfFieldRequired(uiState.value.addressFields.selectedState.value?:"""", uiState.value.addressFields.selectedState.isRequired) val zipCode = InputValidator.checkIfFieldRequired(uiState.value.addressFields.zipcode.value?:"""", uiState.value.addressFields.zipcode.isRequired) val country = InputValidator.checkIfFieldRequired(uiState.value.addressFields.selectedCountry.value?:"""", uiState.value.addressFields.selectedCountry.isRequired) return if (address1 == null && address2 == null && address3 == null && city == null && state == null && zipCode == null && country == null) { null } else { InputErrors( companyNameErrorId = null, companyNameWarningId = null, address1 = address1, address2 = address2, address3 = address3, city = city, state = state, zipCode = zipCode, country = country ) } }" Util function is for Address fields in Compnay Information Screen This functions check for validation requirement for all the fields and returns error if any of them does not match any requirement for validation +"private fun getPasswordFieldErrors(): PasswordInputErrors? { val validLength = InputValidator.validPasswordLength(uiState.value.password.value?:"""") val validLowerUpper = InputValidator.validUpperAndLowerCase(uiState.value.password.value?:"""") val validNumber = InputValidator.containsNumber(uiState.value.password.value?:"""") val validSpecial = InputValidator.containSpecialCharacter(uiState.value.password.value?:"""") return if (!validLength && !validLowerUpper && !validNumber && !validSpecial ) { null } else { PasswordInputErrors( validLength = validLength, validLowerUpper = validLowerUpper, validNumber = validNumber, validSpecial = validSpecial ) } }" Util function for Password field in the AccountInformation Screen This functions check for validation requirement for the password and returns error if password does not match any requirement +"private fun validateAccountInformationScreen(): AccountInformationErrors? { val emailValid = InputValidator.checkIfFieldRequired(uiState.value.email.value?:"""", true) val userNameValid = InputValidator.checkIfFieldRequired(uiState.value.userName.value?:"""", true) val passwordValid = InputValidator.checkIfFieldRequired(uiState.value.password.value?:"""", true) val confirmPasswordValid = InputValidator.checkIfFieldRequired(uiState.value.confirmPassword.value?:"""", true) return if (emailValid == null && userNameValid == null && passwordValid == null && confirmPasswordValid == null) { null } else { AccountInformationErrors( emailNameErrorId = emailValid, userNameErrorId = userNameValid, passwordErrorId = passwordValid, verifyPasswordErrorId = confirmPasswordValid ) } }" "This function validates the information on the Account Information screen. If input validation fails for any of the fields, this functions assigns the error strings to be shown by the UI" +"private fun validateUserInformationScreen( errorTypeForFirst: ErrorType? = null, errorTypeForLast: ErrorType? = null ): UserInformationErrors? { val firstNameValid = if (errorTypeForFirst == null) { InputValidator.checkIfFieldRequired(uiState.value.firstName.value ?: """", true) } else { InputValidator.getDqmErrorIdOrNull(errorTypeForFirst) } val lastNameValid = if (errorTypeForLast == null) { InputValidator.checkIfFieldRequired(uiState.value.lastName.value ?: """", true) } else { InputValidator.getDqmErrorIdOrNull(errorTypeForLast) } return if (firstNameValid == null && lastNameValid == null) { null } else { UserInformationErrors( firstNameErrorId = firstNameValid, lastNameErrorId = lastNameValid ) } }" "This function validates the information on the UserInformationScreen. If input validates fails for any of the fields, this functions assigns the error strings to be shown by the UI" +"private fun checkZipCode() { val parameters = HashMap() parameters[""zipCode""] = uiState.value.addressFields.zipcode.value!! parameters[""isoCountryCode""] = ""US"" viewModelScope.launch(Dispatchers.IO) { when(val result = getCountryDataUseCase.verifyZipCodeForUS( fullUrl = NetworkingService.instance.getOnboardingAPIURL(""onboarding/states/"") + (uiState.value.selectedStateAbb?.split(""-"".toRegex())?.toTypedArray() ?.get(1) ?: """"), queryMap = parameters )) { is RemoteResponse.Success -> { if (result.value.abbreviation.isNullOrEmpty()) { val zipCode = InputValidator.validZipCode(true) displayCompanyInfoErrors( InputErrors( companyNameErrorId = null, companyNameWarningId = null, address1 = null, address2 = null, address3 = null, city = null, state = null, zipCode = zipCode, country = null ) ) } else { // [displayInputErrors] is not required as there are no errors, but still implemented to keep the code in proper structure val zipCode = InputValidator.validZipCode(false) displayCompanyInfoErrors( InputErrors( companyNameErrorId = null, companyNameWarningId = null, address1 = null, address2 = null, address3 = null, city = null, state = null, zipCode = zipCode, country = null ), signInProcessing = true ) if (uiState.value.recommendedScreenSeen) { _uiState.value = uiState.value.copy( dotPagerList = listOf( Dot(completed = true), Dot(completed = true), Dot(), Dot() ), signInProcessing = false ) viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenAccountInformationScreen) } } else { getTokenForRecommendationApi() } } } is RemoteResponse.Failure -> { } } } }" "This Api call method which validates the Zipcode enters by the user, this only runs if the input country is US" +"private fun getTokenForRecommendationApi() { viewModelScope.launch(Dispatchers.IO) { val tokenHeaders = HashMap() tokenHeaders[""Authorization""] = ""Basic "" + SecurityService.instance.getString(SecurityService.Keys.saphcpToken) when(val result = getCountryDataUseCase.addressCleanser( fullUrl = NetworkingService.getAddressCorrectionTokenURL(), headers = tokenHeaders )) { is RemoteResponse.Success -> { getRecommendationDetails(result.value) } is RemoteResponse.Failure -> { } } } }" Function to get the Recommendation token details for the address entered by the user +"private fun getRecommendationDetails(token: AddressCleanser) { val headers = HashMap() headers[""Authorization""] = ""Bearer "" + token.accessToken val parameters = JsonObject() parameters.add(""outputFields"", addressCleanseOutputFields()) parameters.add(""addressInput"", addressCleanseInputFields()) viewModelScope.launch(Dispatchers.IO) { when(val result = getCountryDataUseCase.getRecommendationDetails( headers = headers, body = parameters )) { is RemoteResponse.Success -> { if (result.value.stdAddrAddressDelivery.isEmpty() || result.value.stdAddrLocalityFull.isEmpty() || result.value.stdAddrRegionCode.isEmpty() ) { _uiState.value = uiState.value.copy( dotPagerList = listOf( Dot(completed = true), Dot(completed = true), Dot(), Dot() ), signInProcessing = false ) viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenAccountInformationScreen) } } else { _uiState.value = uiState.value.copy( recommendedAddress = RegistrationAddressFields( address1 = InputWrapper(value = result.value.stdAddrAddressDelivery), city = InputWrapper(value = result.value.stdAddrLocalityFull), zipcode = InputWrapper( value = result.value.stdAddrPostcodeFull.split( ""-"".toRegex() ).map { it.trim() }[0] ), selectedState = InputWrapper(value = result.value.stdAddrRegionFull), selectedCountry = InputWrapper(value = result.value.stdAddrCountry2char) ), signInProcessing = false ) navigateToNextScreen(RegistrationScreenType.RecommendationScreen()) } } is RemoteResponse.Failure -> { } } } }" Function to get the Recommendation details for the address entered by the user +"private suspend fun getBusinessRoles() { when(val roles = getBusinessRoleUseCase.getBusinessRole( fullUrl = NetworkingService.instance.getOnboardingAPIURL(""onboarding/business-roles""), headers = NetworkingService.instance.anAccessTokenHeadersForSignUp as HashMap /* = java.util.HashMap */, )) { is RemoteResponse.Success -> { _uiState.value = uiState.value.copy( signInProcessing = false, businessRole = roles.value.results ) } is RemoteResponse.Failure -> { } } } private fun createAccount() { NetworkingService.instance.anNewStackAPIsGoogleRecaptchaPost( ""onboarding/accounts"", proceedToAccountCreationApiCall(), isContactAdmin = false, object : JSONObjectRequestListener { override fun onResponse(response: JSONObject) { _uiState.value = uiState.value.copy( signInProcessing = false ) viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenSignUpConfirmationScreen) } } override fun onError(ANError: ANError) { } }, false, false, ) }" This functions gets the business role list fro the API call +"private fun displayCompanyInfoErrors(inputErrors: InputErrors, signInProcessing: Boolean = false) { _uiState.value = uiState.value.copy( companyName = uiState.value.companyName.copy( errorId = inputErrors.companyNameErrorId ), addressFields = uiState.value.addressFields.copy( address1 = uiState.value.addressFields.address1.copy( errorId = inputErrors.address1 ), address2 = uiState.value.addressFields.address2.copy( errorId = inputErrors.address2 ), address3 = uiState.value.addressFields.address3.copy( errorId = inputErrors.address3 ), city = uiState.value.addressFields.city.copy( errorId = inputErrors.city ), zipcode = uiState.value.addressFields.zipcode.copy( errorId = inputErrors.zipCode ), selectedState = uiState.value.addressFields.selectedState.copy( errorId = inputErrors.state ), selectedCountry = uiState.value.addressFields.selectedCountry.copy( errorId = inputErrors.country ) ), signInProcessing = signInProcessing ) }" Displaying errors on the fields in the CompanyInfo screen +"private fun displayAccountInformationErrors(inputErrors: AccountInformationErrors) { _uiState.value = uiState.value.copy( email = uiState.value.email.copy( errorId = inputErrors.emailNameErrorId ), userName = uiState.value.userName.copy( errorId = inputErrors.userNameErrorId ), password = uiState.value.password.copy( errorId = inputErrors.passwordErrorId ), confirmPassword = uiState.value.confirmPassword.copy( errorId = inputErrors.verifyPasswordErrorId ), signInProcessing = false ) }" This function display the errors on the AccountInformationScreen +"private fun displayUserInformationErrors(inputErrors: UserInformationErrors) { _uiState.value = uiState.value.copy( firstName = uiState.value.firstName.copy( errorId = inputErrors.firstNameErrorId ), lastName = uiState.value.lastName.copy( errorId = inputErrors.lastNameErrorId ), signInProcessing = false ) }" This function displays the error on the User Information Screen +"object UnsplashSizingInterceptor : Interceptor { override suspend fun intercept(chain: Interceptor.Chain): ImageResult { val data = chain.request.data val widthPx = chain.size.width.pxOrElse { -1 } val heightPx = chain.size.height.pxOrElse { -1 } if (widthPx > 0 && heightPx > 0 && data is String && data.startsWith(""https://images.unsplash.com/photo-"") ) { val url = data.toHttpUrl() .newBuilder() .addQueryParameter(""w"", widthPx.toString()) .addQueryParameter(""h"", heightPx.toString()) .build() val request = chain.request.newBuilder().data(url).build() return chain.proceed(request) } return chain.proceed(chain.request) } }" A Coil [Interceptor] which appends query params to Unsplash urls to request sized images. +fun YearMonth.getNumberWeeks(weekFields: WeekFields = CALENDAR_STARTS_ON): Int { val firstWeekNumber = this.atDay(1)[weekFields.weekOfMonth()] val lastWeekNumber = this.atEndOfMonth()[weekFields.weekOfMonth()] return lastWeekNumber - firstWeekNumber + 1 // Both weeks inclusive } This function get the number of weeks in the month +"public fun produceRequestedResources( resourceResults: R, requestParams: RequestBuilders.ResourcesRequest, ): Resources" Produce resources for the given request. The implementation should read [androidx.wear.tiles.RequestBuilders.ResourcesRequest.getResourceIds] and if not empty only return the requested resources. +"public class ThemePreviewTileRenderer(context: Context, private val thisTheme: Colors) : SingleTileLayoutRenderer(context) { override fun createTheme(): Colors = thisTheme override fun renderTile( state: Unit, deviceParameters: DeviceParameters ): LayoutElement { return Box.Builder() .setWidth(ExpandedDimensionProp.Builder().build()) .setHeight(ExpandedDimensionProp.Builder().build()) .setHorizontalAlignment(HORIZONTAL_ALIGN_CENTER) .setVerticalAlignment(VERTICAL_ALIGN_CENTER) .addContent( Column.Builder() .addContent(title()) .addContent(primaryIconButton()) .addContent(primaryChip(deviceParameters)) .addContent(secondaryCompactChip(deviceParameters)) .addContent(secondaryIconButton()) .build() ) .build() } internal fun title() = Text.Builder(context, ""Title"") .setTypography(Typography.TYPOGRAPHY_CAPTION1) .setColor(ColorBuilders.argb(theme.onSurface)) .build() internal fun primaryChip( deviceParameters: DeviceParameters ) = Chip.Builder(context, NoOpClickable, deviceParameters) .setPrimaryLabelContent(""Primary Chip"") .setIconContent(Icon) .setChipColors(ChipColors.primaryChipColors(theme)) .build() internal fun secondaryCompactChip( deviceParameters: DeviceParameters ) = CompactChip.Builder(context, ""Secondary Chip"", NoOpClickable, deviceParameters) .setChipColors(ChipColors.secondaryChipColors(theme)) .build() internal fun primaryIconButton() = Button.Builder(context, NoOpClickable) .setIconContent(Icon) .setButtonColors(ButtonColors.primaryButtonColors(theme)) .build() internal fun secondaryIconButton() = Button.Builder(context, NoOpClickable) .setIconContent(Icon) .setButtonColors(ButtonColors.secondaryButtonColors(theme)) .build() override fun ResourceBuilders.Resources.Builder.produceRequestedResources( resourceResults: Unit, deviceParameters: DeviceParameters, resourceIds: MutableList ) { addIdToImageMapping(Icon, drawableResToImageResource(R.drawable.ic_nordic)) } private companion object { private const val Icon = ""icon"" } }" Tile that renders components with typical layouts and a theme colour. +public fun drawableResToImageResource(@DrawableRes id: Int): ImageResource = ImageResource.Builder() .setAndroidResourceByResId( AndroidImageResourceByResId.Builder() .setResourceId(id) .build() ) .build() Load a resource from the res/drawable* directories. +"public suspend fun ImageLoader.loadImage( context: Context, data: Any?, configurer: ImageRequest.Builder.() -> Unit = {} ): Bitmap? { val request = ImageRequest.Builder(context) .data(data) .apply(configurer) .allowRgb565(true) .allowHardware(false) .build() val response = execute(request) return (response.drawable as? BitmapDrawable)?.bitmap }" Load a Bitmap from a CoilImage loader. +"public suspend fun ImageLoader.loadImageResource( context: Context, data: Any?, configurer: ImageRequest.Builder.() -> Unit = {} ): ImageResource? = loadImage(context, data, configurer)?.toImageResource()" Load an ImageResource from a CoilImage loader. +"public fun Bitmap.toImageResource(): ImageResource { val rgb565Bitmap = if (config == Bitmap.Config.RGB_565) { this } else { copy(Bitmap.Config.RGB_565, false) } val byteBuffer = ByteBuffer.allocate(rgb565Bitmap.byteCount) rgb565Bitmap.copyPixelsToBuffer(byteBuffer) val bytes: ByteArray = byteBuffer.array() return ImageResource.Builder().setInlineResource( ResourceBuilders.InlineImageResource.Builder() .setData(bytes) .setWidthPx(rgb565Bitmap.width) .setHeightPx(rgb565Bitmap.height) .setFormat(ResourceBuilders.IMAGE_FORMAT_RGB_565) .build() ) .build() }" Convert a bitmap to a ImageResource. +"public val NoOpClickable: ModifiersBuilders.Clickable = ModifiersBuilders.Clickable.Builder() .setId(""noop"") .build()" Simple NoOp clickable for preview use. +"public abstract class DataComplicationService> : SuspendingComplicationDataSourceService() { public abstract val renderer: R public abstract suspend fun data(request: ComplicationRequest): D public abstract fun previewData(type: ComplicationType): D override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData { val data: D = data(request) return render(request.complicationType, data) } override fun getPreviewData(type: ComplicationType): ComplicationData? { val data: D = previewData(type) return render(type, data) } public fun render(type: ComplicationType, data: D): ComplicationData { return renderer.render(type, data) } }" "A complication service based on a [ComplicationTemplate]. The implementation is effectively two parts, first creating some simple data model using a suspending [data] function. Then a render phase." +"public fun drawToBitmap( bitmap: Bitmap, density: Density, size: Size, onDraw: DrawScope.() -> Unit ) { val androidCanvas = AndroidCanvas(bitmap) val composeCanvas = ComposeCanvas(androidCanvas) val canvasDrawScope = CanvasDrawScope() canvasDrawScope.draw(density, LayoutDirection.Ltr, composeCanvas, size) { onDraw() } }" Render an element normally drawn within a Compose Canvas into a Bitmap. This allows shared elements between the app and tiles. +Render an element normally drawn within a Compose Canvas into a Bitmap and then convert to a Tiles ImageResource. "@RequiresApi(VERSION_CODES.O) public fun canvasToImageResource( size: Size, density: Density, onDraw: DrawScope.() -> Unit ): ImageResource { return Bitmap.createBitmap( size.width.toInt(), size.height.toInt(), Bitmap.Config.RGB_565, false ).apply { drawToBitmap(bitmap = this, density = density, size = size, onDraw = onDraw) }.toImageResource() }" +public interface NetworkingRules { public fun isHighBandwidthRequest(requestType: RequestType): Boolean} Implementation of app rules for network usage. A way to implement logic such as +"public fun checkValidRequest( requestType: RequestType, currentNetworkType: NetworkType ): RequestCheck" Checks whether this request is allowed on the current network type. +Returns the preferred network for a request. Null means no suitable network. "public fun getPreferredNetwork( networks: Networks, requestType: RequestType ): NetworkStatus?" +"public object Lenient : NetworkingRules { override fun isHighBandwidthRequest(requestType: RequestType): Boolean { return requestType is RequestType.MediaRequest } override fun checkValidRequest( requestType: RequestType, currentNetworkType: NetworkType ): RequestCheck { return Allow } override fun getPreferredNetwork( networks: Networks, requestType: RequestType ): NetworkStatus? { return networks.networks.firstOrNull { it.type is NetworkType.Wifi } } }" +"public object Conservative : NetworkingRules { override fun isHighBandwidthRequest(requestType: RequestType): Boolean { return requestType is RequestType.MediaRequest } override fun checkValidRequest( requestType: RequestType, currentNetworkType: NetworkType ): RequestCheck { if (requestType is RequestType.MediaRequest) { return if (requestType.type == RequestType.MediaRequest.MediaRequestType.Download) { if (currentNetworkType is NetworkType.Wifi || currentNetworkType is NetworkType.Cellular) { Allow } else { Fail(""downloads only possible over Wifi/LTE"") } } else { Fail(""streaming disabled"") } } return Allow } override fun getPreferredNetwork( networks: Networks, requestType: RequestType ): NetworkStatus? { val cell = networks.networks.firstOrNull { it.type is NetworkType.Cellular } val ble = networks.networks.firstOrNull { it.type is NetworkType.Bluetooth } return networks.networks.firstOrNull { it.type is NetworkType.Wifi } ?: if (requestType is RequestType.MediaRequest) { cell } else { ble } } } }" "Conservative rules don't allow Streaming, and only allow Downloads over high bandwidth networks." +"public class NetworkingRulesEngine( internal val networkRepository: NetworkRepository, internal val logger: NetworkStatusLogger = NetworkStatusLogger.Logging, private val networkingRules: NetworkingRules = NetworkingRules.Conservative ) { public fun preferredNetwork(requestType: RequestType): NetworkStatus? { val networks = networkRepository.networkStatus.value return networkingRules.getPreferredNetwork(networks, requestType) } public fun checkValidRequest( requestType: RequestType, currentNetworkType: NetworkType? ): RequestCheck { return networkingRules.checkValidRequest(requestType, currentNetworkType ?: NetworkType.Unknown(""unknown"")) } public fun isHighBandwidthRequest(requestType: RequestType): Boolean { return networkingRules.isHighBandwidthRequest(requestType) } @Suppress(""UNUSED_PARAMETER"") public fun reportConnectionFailure(inetSocketAddress: InetSocketAddress, networkType: NetworkType?) { // TODO check for no internet on BLE and other scenarios } }" "Networking Rules that bridges between app specific rules and specific network actions, like opening a network socket." +"@ExperimentalHorologistMediaUiApi @Composable public fun ShowPlaylistChip( artworkUri: Any?, name: String?, onClick: () -> Unit, modifier: Modifier = Modifier, placeholder: Painter? = null, ) { val appIcon: (@Composable BoxScope.() -> Unit)? = artworkUri?.let { { MediaArtwork( modifier = Modifier.size(ChipDefaults.LargeIconSize), contentDescription = name, artworkUri = artworkUri, placeholder = placeholder, ) } } Chip( modifier = modifier.fillMaxWidth(), colors = ChipDefaults.secondaryChipColors(), icon = appIcon, label = { Text( text = name.orEmpty(), overflow = TextOverflow.Ellipsis ) }, onClick = onClick ) }" [Chip] to show all items in the selected category. +"class ServiceWorkerSupportFeature( private val homeActivity: HomeActivity, ) : ServiceWorkerDelegate, DefaultLifecycleObserver { override fun onDestroy(owner: LifecycleOwner) { homeActivity.components.core.engine.unregisterServiceWorkerDelegate() } override fun onCreate(owner: LifecycleOwner) { homeActivity.components.core.engine.registerServiceWorkerDelegate(this) } override fun addNewTab(engineSession: EngineSession): Boolean { with(homeActivity) { openToBrowser(BrowserDirection.FromHome) components.useCases.tabsUseCases.addTab( flags = LoadUrlFlags.external(), engineSession = engineSession, source = SessionState.Source.Internal.None, ) } return true } }" Fenix own version of the `ServiceWorkerSupportFeature` from Android-Components which adds the ability to navigate to the browser before opening a new tab. Will automatically register callbacks for service workers requests and cleanup when [homeActivity] is destroyed. +"enum class BrowserDirection(@IdRes val fragmentId: Int) { FromGlobal(0), FromHome(R.id.homeFragment), FromWallpaper(R.id.wallpaperSettingsFragment), FromSearchDialog(R.id.searchDialogFragment), FromSettings(R.id.settingsFragment), FromBookmarks(R.id.bookmarkFragment), FromBookmarkSearchDialog(R.id.bookmarkSearchDialogFragment), FromHistory(R.id.historyFragment), FromHistorySearchDialog(R.id.historySearchDialogFragment), FromHistoryMetadataGroup(R.id.historyMetadataGroupFragment), FromTrackingProtectionExceptions(R.id.trackingProtectionExceptionsFragment), FromAbout(R.id.aboutFragment), FromTrackingProtection(R.id.trackingProtectionFragment), FromHttpsOnlyMode(R.id.httpsOnlyFragment), FromCookieBanner(R.id.cookieBannerFragment), FromTrackingProtectionDialog(R.id.trackingProtectionPanelDialogFragment), FromSavedLoginsFragment(R.id.savedLoginsFragment), FromAddNewDeviceFragment(R.id.addNewDeviceFragment), FromAddSearchEngineFragment(R.id.addSearchEngineFragment), FromEditCustomSearchEngineFragment(R.id.editCustomSearchEngineFragment), FromAddonDetailsFragment(R.id.addonDetailsFragment), FromStudiesFragment(R.id.studiesFragment), FromAddonPermissionsDetailsFragment(R.id.addonPermissionsDetailFragment), FromLoginDetailFragment(R.id.loginDetailFragment), FromTabsTray(R.id.tabsTrayFragment), FromRecentlyClosed(R.id.recentlyClosedFragment), }" Used with [HomeActivity.openToBrowser] to indicate which fragment the browser is being opened from. +"class FenixLogSink(private val logsDebug: Boolean = true) : LogSink { private val androidLogSink = AndroidLogSink() override fun log( priority: Log.Priority, tag: String?, throwable: Throwable?, message: String?, ) { if (priority == Log.Priority.DEBUG && !logsDebug) { return } androidLogSink.log(priority, tag, throwable, message) } }" "Fenix [LogSink] implementation that writes to Android's log, depending on settings." +"enum class GlobalDirections(val navDirections: NavDirections, val destinationId: Int) { Home(NavGraphDirections.actionGlobalHome(), R.id.homeFragment), Bookmarks( NavGraphDirections.actionGlobalBookmarkFragment(BookmarkRoot.Root.id), R.id.bookmarkFragment, ), History( NavGraphDirections.actionGlobalHistoryFragment(), R.id.historyFragment, ), Settings( NavGraphDirections.actionGlobalSettingsFragment(), R.id.settingsFragment, ), Sync( NavGraphDirections.actionGlobalTurnOnSync(), R.id.turnOnSyncFragment, ), SearchEngine( NavGraphDirections.actionGlobalSearchEngineFragment(), R.id.searchEngineFragment, ), Accessibility( NavGraphDirections.actionGlobalAccessibilityFragment(), R.id.accessibilityFragment, ), DeleteData( NavGraphDirections.actionGlobalDeleteBrowsingDataFragment(), R.id.deleteBrowsingDataFragment, ), SettingsAddonManager( NavGraphDirections.actionGlobalAddonsManagementFragment(), R.id.addonsManagementFragment, ), SettingsLogins( NavGraphDirections.actionGlobalSavedLoginsAuthFragment(), R.id.saveLoginSettingFragment, ), SettingsTrackingProtection( NavGraphDirections.actionGlobalTrackingProtectionFragment(), R.id.trackingProtectionFragment, ), WallpaperSettings( NavGraphDirections.actionGlobalWallpaperSettingsFragment(), R.id.wallpaperSettingsFragment, ), }" Used with [HomeActivity] global navigation to indicate which fragment is being opened. +open class SecureFragment(@LayoutRes contentLayoutId: Int) : Fragment(contentLayoutId) { constructor() : this(0) { Fragment() } override fun onCreate(savedInstanceState: Bundle?) { this.secure() super.onCreate(savedInstanceState) } override fun onDestroy() { this.removeSecure() super.onDestroy() } } A [Fragment] implementation that can be used to secure screens displaying sensitive information by not allowing taking screenshots of their content. Fragments displaying such screens should extend [SecureFragment] instead of [Fragment] class. +class WifiConnectionMonitor(app: Application) { @VisibleForTesting internal val callbacks = mutableListOf<(Boolean) -> Unit>() @VisibleForTesting internal var connectivityManager = app.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager @VisibleForTesting internal var lastKnownStateWasAvailable: Boolean? = null @VisibleForTesting internal var isRegistered = false @Synchronized set @VisibleForTesting internal val frameworkListener = object : ConnectivityManager.NetworkCallback() { override fun onLost(network: Network) { notifyListeners(false) lastKnownStateWasAvailable = false } override fun onAvailable(network: Network) { notifyListeners(true) lastKnownStateWasAvailable = true } } internal fun notifyListeners(value: Boolean) { val items = ArrayList(callbacks) items.forEach { it(value) } } Attaches itself to the [Application] and listens for WIFI available/not available events. This allows the calling code to set simpler listeners. +"fun start() { // Framework code throws if a listener is registered twice without unregistering. if (isRegistered) return val request = NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .build() // AFAICT, the framework does not send an event when a new NetworkCallback is registered // while the WIFI is not connected, so we push this manually. If the WIFI is on, it will send // a follow up event shortly val noCallbacksReceivedYet = lastKnownStateWasAvailable == null if (noCallbacksReceivedYet) { lastKnownStateWasAvailable = false notifyListeners(false) } connectivityManager.registerNetworkCallback(request, frameworkListener) isRegistered = true }" "Attaches the [WifiConnectionMonitor] to the application. After this has been called, callbacks added via [addOnWifiConnectedChangedListener] will be called until either the app exits, or [stop] is called." +fun stop() { // Framework code will throw if an unregistered listener attempts to unregister. if (!isRegistered) return connectivityManager.unregisterNetworkCallback(frameworkListener) isRegistered = false lastKnownStateWasAvailable = null callbacks.clear() } Detatches the [WifiConnectionMonitor] from the app. No callbacks added via [addOnWifiConnectedChangedListener] will be called after this has been called. +fun addOnWifiConnectedChangedListener(onWifiChanged: (Boolean) -> Unit) { val lastKnownState = lastKnownStateWasAvailable if (callbacks.add(onWifiChanged) && lastKnownState != null) { onWifiChanged(lastKnownState) } } Adds [onWifiChanged] to a list of listeners that will be called whenever WIFI connects or disconnects. +fun removeOnWifiConnectedChangedListener(onWifiChanged: (Boolean) -> Unit) { callbacks.remove(onWifiChanged) } } Removes [onWifiChanged] from the list of listeners to be called whenever WIFI connects or disconnects. +"enum class ImageFileState { Unavailable, Downloading, Downloaded, Error, }" Defines the download state of wallpaper asset. +fun lowercase(): String = this.name.lowercase() } Get a lowercase string representation of the [ImageType.name] for use in path segments. +"enum class ImageType { Portrait, Landscape, Thumbnail, ;" Defines various image asset types that can be downloaded for each wallpaper. +"fun nameIsDefault(name: String): Boolean = name.isEmpty() || name == defaultName || name.lowercase() == ""none"" }" "Check if a wallpaper name matches the default. Considers empty strings to be default since that likely means a wallpaper has never been set. The ""none"" case here is to deal with a legacy case where the default wallpaper used to be Wallpaper.NONE. See commit 7a44412, Wallpaper.NONE and Settings.currentWallpaper (legacy name) for context." +"@Suppress(""ComplexCondition"") fun getCurrentWallpaperFromSettings(settings: Settings): Wallpaper? { val name = settings.currentWallpaperName val textColor = settings.currentWallpaperTextColor val cardColorLight = settings.currentWallpaperCardColorLight val cardColorDark = settings.currentWallpaperCardColorDark return if (name.isNotEmpty() && textColor != 0L && cardColorLight != 0L && cardColorDark != 0L) { Wallpaper( name = name, textColor = textColor, cardColorLight = cardColorLight, cardColorDark = cardColorDark, collection = DefaultCollection, thumbnailFileState = ImageFileState.Downloaded, assetsFileState = ImageFileState.Downloaded, ) } else { null } }" Generate a wallpaper from metadata cached in Settings. +"fun getLocalPath(name: String, type: ImageType) = ""wallpapers/$name/${type.lowercase()}.png""" Defines the standard path at which a wallpaper resource is kept on disk. +"fun legacyGetLocalPath(orientation: String, theme: String, name: String): String = ""wallpapers/$orientation/$theme/$name.png""" Defines the standard path at which a wallpaper resource is kept on disk. +"const val classicFirefoxCollectionName = ""classic-firefox"" val ClassicFirefoxCollection = Collection( name = classicFirefoxCollectionName, heading = null, description = null, learnMoreUrl = null, availableLocales = null, startDate = null, endDate = null, ) val DefaultCollection = Collection( name = defaultName, heading = null, description = null, learnMoreUrl = null, availableLocales = null, startDate = null, endDate = null, ) val Default = Wallpaper( name = defaultName, collection = DefaultCollection, textColor = null, cardColorLight = null, cardColorDark = null, thumbnailFileState = ImageFileState.Downloaded, assetsFileState = ImageFileState.Downloaded, )" "Note: this collection could get out of sync with the version of it generated when fetching remote metadata. It is included mostly for convenience, but use with utmost care until we find a better way of handling the edge cases around this collection. It is generally safer to do comparison directly with the collection name" +"data class Collection( val name: String, val heading: String?, val description: String?, val learnMoreUrl: String?, val availableLocales: List?, val startDate: Date?, val endDate: Date?, )  companion object { const val amethystName = ""amethyst"" const val ceruleanName = ""cerulean"" const val sunriseName = ""sunrise"" const val twilightHillsName = ""twilight-hills"" const val beachVibeName = ""beach-vibe"" const val firefoxCollectionName = ""firefox"" const val defaultName = ""default""" "Type that represents a collection that a [Wallpaper] belongs to. @property name The name of the collection the wallpaper belongs to. @property learnMoreUrl The URL that can be visited to learn more about a collection, if any. @property availableLocales The locales that this wallpaper is restricted to. If null, the wallpaper is not restricted. @property startDate The date the wallpaper becomes available in a promotion. If null, it is available from any date. @property endDate The date the wallpaper stops being available in a promotion. If null, the wallpaper will be available to any date." +"data class Wallpaper( val name: String, val collection: Collection, val textColor: Long?, val cardColorLight: Long?, val cardColorDark: Long?, val thumbnailFileState: ImageFileState, val assetsFileState: ImageFileState, ) {" Type that represents wallpapers. @property name The name of the wallpaper. @property collection The name of the collection the wallpaper belongs to. is not restricted. @property textColor The 8 digit hex code color that should be used for text overlaying the wallpaper. @property cardColorLight The 8 digit hex code color that should be used for cards overlaying the wallpaper when the user's theme is set to Light. @property cardColorDark The 8 digit hex code color that should be used for cards overlaying the wallpaper when the user's theme is set to Dark. +"suspend fun downloadThumbnail(wallpaper: Wallpaper): Wallpaper.ImageFileState = withContext(dispatcher) { downloadAsset(wallpaper, Wallpaper.ImageType.Thumbnail)" Downloads a thumbnail for a wallpaper from the network. This is expected to be found remotely at: ///thumbnail.png and stored locally at: wallpapers//thumbnail.png +"suspend fun downloadWallpaper(wallpaper: Wallpaper): Wallpaper.ImageFileState = withContext(dispatcher) { val portraitResult = downloadAsset(wallpaper, Wallpaper.ImageType.Portrait) val landscapeResult = downloadAsset(wallpaper, Wallpaper.ImageType.Landscape) return@withContext if (portraitResult == Wallpaper.ImageFileState.Downloaded && landscapeResult == Wallpaper.ImageFileState.Downloaded ) { Wallpaper.ImageFileState.Downloaded } else { Wallpaper.ImageFileState.Error } }" Downloads a wallpaper from the network. Will try to fetch 2 versions of each wallpaper: portrait and landscape. These are expected to be found at a remote path in the form: ///.png and will be stored in the local path: wallpapers//.png +"class WallpaperDownloader( private val storageRootDirectory: File, private val client: Client, private val dispatcher: CoroutineDispatcher = Dispatchers.IO, ) { private val remoteHost = BuildConfig.WALLPAPER_URL" Can download wallpapers from a remote host. +suspend fun wallpaperImagesExist(wallpaper: Wallpaper): Boolean = withContext(coroutineDispatcher) { allAssetsExist(wallpaper.name) } Checks whether all the assets for a wallpaper exist on the file system. +"fun clean(currentWallpaper: Wallpaper, availableWallpapers: List) { CoroutineScope(coroutineDispatcher).launch { val wallpapersToKeep = (listOf(currentWallpaper) + availableWallpapers).map { it.name } wallpapersDirectory.listFiles()?.forEach { file -> if (file.isDirectory && !wallpapersToKeep.contains(file.name)) { file.deleteRecursively() } } } }" Remove all wallpapers that are not the [currentWallpaper] or in [availableWallpapers]. +"suspend fun lookupExpiredWallpaper(settings: Settings): Wallpaper? = withContext(coroutineDispatcher) { val name = settings.currentWallpaperName if (allAssetsExist(name)) { Wallpaper( name = name, collection = Wallpaper.DefaultCollection, textColor = settings.currentWallpaperTextColor, cardColorLight = settings.currentWallpaperCardColorLight, cardColorDark = settings.currentWallpaperCardColorDark, thumbnailFileState = Wallpaper.ImageFileState.Downloaded, assetsFileState = Wallpaper.ImageFileState.Downloaded, ) } else { null } }  private fun allAssetsExist(name: String): Boolean = Wallpaper.ImageType.values().all { type -> File(storageRootDirectory, getLocalPath(name, type)).exists() }" Lookup all the files for a wallpaper name. This lookup will fail if there are not files for each of a portrait and landscape orientation as well as a thumbnail. +"fun runIfWallpaperCardColorsAreAvailable( run: (cardColorLight: Int, cardColorDark: Int) -> Unit, ) { if (currentWallpaper.cardColorLight != null && currentWallpaper.cardColorDark != null) { run(currentWallpaper.cardColorLight.toInt(), currentWallpaper.cardColorDark.toInt()) } } }" Run the [run] block only if the current wallpaper's card colors are available. +"@Composable fun composeRunIfWallpaperCardColorsAreAvailable( run: @Composable (cardColorLight: Color, cardColorDark: Color) -> Unit, ) { if (currentWallpaper.cardColorLight != null && currentWallpaper.cardColorDark != null) { run(Color(currentWallpaper.cardColorLight), Color(currentWallpaper.cardColorDark)) } }" Run the Composable [run] block only if the current wallpaper's card colors are available. +val wallpaperCardColor: Color @Composable get() = when { currentWallpaper.cardColorLight != null && currentWallpaper.cardColorDark != null -> { if (isSystemInDarkTheme()) { Color(currentWallpaper.cardColorDark) } else { Color(currentWallpaper.cardColorLight) } } else -> FirefoxTheme.colors.layer2 } Helper property used to obtain the [Color] to fill-in cards in front of a wallpaper. +"data class WallpaperState( val currentWallpaper: Wallpaper, val availableWallpapers: List, ) { companion object { val default = WallpaperState( currentWallpaper = Wallpaper.Default, availableWallpapers = listOf(), ) }" Represents all state related to the Wallpapers feature. +"@JvmStatic fun userViewedWhatsNew(context: Context) { userViewedWhatsNew( SharedPreferenceWhatsNewStorage( context, ), ) }} }" Convenience function to run from the context. +@JvmStatic private fun userViewedWhatsNew(storage: WhatsNewStorage) { wasUpdatedRecently = false storage.setWhatsNewHasBeenCleared(true) } "Reset the ""updated"" state and continue as if the app was not updated recently." +"fun shouldHighlightWhatsNew(context: Context): Boolean { return shouldHighlightWhatsNew( ContextWhatsNewVersion(context), context.components.strictMode.resetAfter(StrictMode.allowThreadDiskReads()) { SharedPreferenceWhatsNewStorage(context) }, ) }" Convenience function to run from the context. +"@JvmStatic fun shouldHighlightWhatsNew(currentVersion: WhatsNewVersion, storage: WhatsNewStorage): Boolean { // Cache the value for the lifetime of this process (or until userViewedWhatsNew() is called) if (wasUpdatedRecently == null) { val whatsNew = WhatsNew(storage) wasUpdatedRecently = whatsNew.hasBeenUpdatedRecently(currentVersion) } return wasUpdatedRecently!! }" "Should we highlight the ""What's new"" menu item because this app been updated recently? This method returns true either if this is the first start of the application since it was updated or this is a later start but still recent enough to consider the app to be updated recently." +class WhatsNew private constructor(private val storage: WhatsNewStorage) { private fun hasBeenUpdatedRecently(currentVersion: WhatsNewVersion): Boolean { val lastKnownAppVersion = storage.getVersion() // Update the version and date if *just* updated if (lastKnownAppVersion == null || currentVersion.majorVersionNumber > lastKnownAppVersion.majorVersionNumber ) { storage.setVersion(currentVersion) storage.setDateOfUpdate(System.currentTimeMillis()) return true } return (!storage.getWhatsNewHasBeenCleared() && storage.getDaysSinceUpdate() < DAYS_PER_UPDATE) } } "Helper class tracking whether the application was recently updated in order to show ""What's new"" menu items and indicators in the application UI. The application is considered updated when the application's version name changes (versionName in the manifest). The applications version code would be a good candidates too, but it might  change more often (RC builds) without the application actually changing from the user's point of view. Whenever the application was updated we still consider the application to be ""recently updated for the next few days." +"class AccessibilityGridLayoutManager( context: Context, spanCount: Int, ) : GridLayoutManager( context, spanCount, ) { override fun getColumnCountForAccessibility( recycler: RecyclerView.Recycler, state: RecyclerView.State, ): Int { return if (itemCount < spanCount) { itemCount } else { super.getColumnCountForAccessibility(recycler, state) } } }" A GridLayoutManager that can be used to override methods in Android implementation to improve ayy1 or fix a11y issues. +private fun MotionEvent.endDrawableTouched() = (layoutDirection == LAYOUT_DIRECTION_LTR && rawX >= (right - compoundPaddingRight)) || (layoutDirection == LAYOUT_DIRECTION_RTL && rawX <= (left + compoundPaddingLeft)) } Returns true if the location of the [MotionEvent] is on top of the end drawable. +private fun shouldShowClearButton(length: Int) = length > 0 && error == null Checks if the clear button should be displayed. +"override fun onTextChanged(text: CharSequence?, start: Int, lengthBefore: Int, lengthAfter: Int) { onTextChanged(text) } fun onTextChanged(text: CharSequence?) { // lengthAfter has inconsistent behaviour when there are spaces in the entered text, so we'll use text.length. val textLength = text?.length ?: 0 val drawable = if (shouldShowClearButton(textLength)) { AppCompatResources.getDrawable(context, R.drawable.mozac_ic_clear)?.apply { colorFilter = createBlendModeColorFilterCompat(context.getColorFromAttr(R.attr.textPrimary), SRC_IN) } } else { null } putCompoundDrawablesRelativeWithIntrinsicBounds(end = drawable) }" Displays a clear icon if text has been entered. +"@SuppressLint(""ClickableViewAccessibility"") override fun onTouchEvent(event: MotionEvent): Boolean { if (shouldShowClearButton(length()) && event.action == ACTION_UP && event.endDrawableTouched()) { setText("""") return true } return super.onTouchEvent(event) }" "Clears the text when the clear icon is touched. Since the icon is just a compound drawable, we check the tap location to see if the X position of the tap is where the drawable is located." +"class ClearableEditText @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.editTextStyle, ) : AppCompatEditText(context, attrs, defStyleAttr) {" An [AppCompatEditText] that shows a clear button to the user. +fun getHttpsOnlyMode(): HttpsOnlyMode { return if (!shouldUseHttpsOnly) { HttpsOnlyMode.DISABLED } else if (shouldUseHttpsOnlyInPrivateTabsOnly) { HttpsOnlyMode.ENABLED_PRIVATE_ONLY } else { HttpsOnlyMode.ENABLED } } Get the current mode for how https-only is enabled. +fun getCookieBannerHandling(): CookieBannerHandlingMode { return when (shouldUseCookieBanner) { true -> CookieBannerHandlingMode.REJECT_ALL false -> if (shouldShowCookieBannerUI && !userOptOutOfReEngageCookieBannerDialog) { CookieBannerHandlingMode.DETECT_ONLY } else { CookieBannerHandlingMode.DISABLED } } } Get the current mode for cookie banner handling +"var showSyncCFR by lazyFeatureFlagPreference(appContext.getPreferenceKey(R.string.pref_key_should_show_sync_cfr), featureFlag = true, default = { mr2022Sections[Mr2022Section.SYNC_CFR] == true }, )" Indicates if sync onboarding CFR should be shown. +"var showHomeOnboardingDialog by lazyFeatureFlagPreference(appContext.getPreferenceKey(R.string.pref_key_should_show_home_onboarding_dialog), featureFlag = true, default = { mr2022Sections[Mr2022Section.HOME_ONBOARDING_DIALOG_EXISTING_USERS] == true }, )" Indicates if home onboarding dialog should be shown. +"var showRecentTabsFeature by lazyFeatureFlagPreference( appContext.getPreferenceKey(R.string.pref_key_recent_tabs), featureFlag = true, default = { homescreenSections[HomeScreenSection.JUMP_BACK_IN] == true }, )" Indicates if the recent tabs functionality should be visible. +"var showRecentBookmarksFeature by lazyFeatureFlagPreference( appContext.getPreferenceKey(R.string.pref_key_recent_bookmarks), default = { homescreenSections[HomeScreenSection.RECENTLY_SAVED] == true }, featureFlag = true, )" Indicates if the recent saved bookmarks functionality should be visible. +"var openNextTabInDesktopMode by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_open_next_tab_desktop_mode), default = false, )" "Storing desktop item checkbox value in the home screen menu.If set to true, next opened tab from home screen will be opened in desktop mode." +"var shouldAutofillCreditCardDetails by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_credit_cards_save_and_autofill_cards), default = true, )" "Storing the user choice from the ""Credit cards"" settings for whether save and autofill cards should be enabled or not. If set to `true` when the user focuses on credit card fields in the webpage an Android prompt letting her select the card details to be automatically filled will appear." +"var shouldAutofillAddressDetails by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_addresses_save_and_autofill_addresses), default = true, )" "Stores the user choice from the ""Autofill Addresses"" settings for whether save and autofill addresses should be enabled or not. If set to `true` when the user focuses on address fields in a webpage an Android prompt is shown, allowing the selection of an address details to be automatically filled in the webpage fields." +"var showPocketRecommendationsFeature by lazyFeatureFlagPreference( appContext.getPreferenceKey(R.string.pref_key_pocket_homescreen_recommendations), featureFlag = FeatureFlags.isPocketRecommendationsFeatureEnabled(appContext), default = { homescreenSections[HomeScreenSection.POCKET] == true }, )" Indicates if the Pocket recommended stories homescreen section should be shown. +"val showPocketSponsoredStories by lazyFeatureFlagPreference( key = appContext.getPreferenceKey(R.string.pref_key_pocket_sponsored_stories), default = { homescreenSections[HomeScreenSection.POCKET_SPONSORED_STORIES] == true }, featureFlag = FeatureFlags.isPocketSponsoredStoriesFeatureEnabled(appContext), )" Indicates if the Pocket recommendations homescreen section should also show sponsored stories. +"val pocketSponsoredStoriesProfileId by stringPreference( appContext.getPreferenceKey(R.string.pref_key_pocket_sponsored_stories_profile), default = UUID.randomUUID().toString(), persistDefaultIfNotExists = true, )" Get the profile id to use in the sponsored stories communications with the Pocket endpoint. +"var showContileFeature by booleanPreference( key = appContext.getPreferenceKey(R.string.pref_key_enable_contile), default = true, )" Indicates if the Contile functionality should be visible. +"var enableTaskContinuityEnhancements by booleanPreference( key = appContext.getPreferenceKey(R.string.pref_key_enable_task_continuity), default = true, )" Indicates if the Task Continuity enhancements are enabled. +"var showUnifiedSearchFeature by lazyFeatureFlagPreference( key = appContext.getPreferenceKey(R.string.pref_key_show_unified_search), default = { FxNimbus.features.unifiedSearch.value(appContext).enabled }, featureFlag = FeatureFlags.unifiedSearchFeature, )" Indicates if the Unified Search feature should be visible. +"var homescreenBlocklist by stringSetPreference( appContext.getPreferenceKey(R.string.pref_key_home_blocklist), default = setOf(), )" Blocklist used to filter items from the home screen that have previously been removed. +"var notificationPrePermissionPromptEnabled by lazyFeatureFlagPreference( key = appContext.getPreferenceKey(R.string.pref_key_notification_pre_permission_prompt_enabled), default = { FxNimbus.features.prePermissionNotificationPrompt.value(appContext).enabled }, featureFlag = FeatureFlags.notificationPrePermissionPromptEnabled, )" Indicates if notification pre permission prompt feature is enabled. +"var isNotificationPrePermissionShown by booleanPreference( key = appContext.getPreferenceKey(R.string.pref_key_is_notification_pre_permission_prompt_shown), default = false, )" Indicates if notification permission prompt has been shown to the user. +"var installedAddonsCount by intPreference( appContext.getPreferenceKey(R.string.pref_key_installed_addons_count), 0, )" Storing number of installed add-ons for telemetry purposes +"var installedAddonsList by stringPreference( appContext.getPreferenceKey(R.string.pref_key_installed_addons_list), default = """", )" Storing the list of installed add-ons for telemetry purposes +"val frecencyFilterQuery by stringPreference( appContext.getPreferenceKey(R.string.pref_key_frecency_filter_query), default = ""mfadid=adm"", // Parameter provided by adM )" URLs from the user's history that contain this search param will be hidden. +"var enabledAddonsCount by intPreference( appContext.getPreferenceKey(R.string.pref_key_enabled_addons_count), 0, )" Storing number of enabled add-ons for telemetry purposes +"var enabledAddonsList by stringPreference( appContext.getPreferenceKey(R.string.pref_key_enabled_addons_list), default = """", )" Storing the list of enabled add-ons for telemetry purposes +"var hasInactiveTabsAutoCloseDialogBeenDismissed by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_has_inactive_tabs_auto_close_dialog_dismissed), default = false, )" Indicates if the auto-close dialog for inactive tabs has been dismissed before. +fun shouldShowInactiveTabsAutoCloseDialog(numbersOfTabs: Int): Boolean { return !hasInactiveTabsAutoCloseDialogBeenDismissed && numbersOfTabs >= INACTIVE_TAB_MINIMUM_TO_SHOW_AUTO_CLOSE_DIALOG && !closeTabsAfterOneMonth } "Indicates if the auto-close dialog should be visible based on if the user has dismissed it before [hasInactiveTabsAutoCloseDialogBeenDismissed], if the minimum number of tabs has been accumulated [numbersOfTabs] and if the auto-close setting is already set to [closeTabsAfterOneMonth]." +"var shouldShowJumpBackInCFR by lazyFeatureFlagPreference( appContext.getPreferenceKey(R.string.pref_key_should_show_jump_back_in_tabs_popup), featureFlag = true, default = { mr2022Sections[Mr2022Section.JUMP_BACK_IN_CFR] == true }, )" Indicates if the jump back in CRF should be shown. +"fun getSitePermissionsPhoneFeatureAction( feature: PhoneFeature, default: Action = Action.ASK_TO_ALLOW, ) = preferences.getInt(feature.getPreferenceKey(appContext), default.toInt()).toAction()" Returns a sitePermissions action for the provided [feature]. +"fun setAutoplayUserSetting( autoplaySetting: Int,) { preferences.edit().putInt(AUTOPLAY_USER_SETTING, autoplaySetting).apply() }" Saves the user selected autoplay setting. +"fun getAutoplayUserSetting() = preferences.getInt(AUTOPLAY_USER_SETTING, AUTOPLAY_BLOCK_AUDIBLE) private fun getSitePermissionsPhoneFeatureAutoplayAction( feature: PhoneFeature, default: AutoplayAction = AutoplayAction.BLOCKED, ) = preferences.getInt(feature.getPreferenceKey(appContext), default.toInt()).toAutoplayAction()" Gets the user selected autoplay setting. +"fun setSitePermissionsPhoneFeatureAction( feature: PhoneFeature, value: Action, ) { preferences.edit().putInt(feature.getPreferenceKey(appContext), value.toInt()).apply() }" Sets a sitePermissions action for the provided [feature]. +fun shouldSetReEngagementNotification(): Boolean { return numberOfAppLaunches <= 1 && !reEngagementNotificationShown } Check if we should set the re-engagement notification +fun shouldShowReEngagementNotification(): Boolean { return !reEngagementNotificationShown && !isDefaultBrowserBlocking() } Check if we should show the re-engagement notification. +"var reEngagementNotificationEnabled by lazyFeatureFlagPreference( key = appContext.getPreferenceKey(R.string.pref_key_re_engagement_notification_enabled), default = { FxNimbus.features.reEngagementNotification.value(appContext).enabled }, featureFlag = true, )" Indicates if the re-engagement notification feature is enabled +@VisibleForTesting internal val timerForCookieBannerDialog: Long get() = 60 * 60 * 1000L * (cookieBannersSection[CookieBannersSection.DIALOG_RE_ENGAGE_TIME] ?: 4) Indicates after how many hours a cookie banner dialog should be shown again +fun shouldCookieBannerReEngagementDialog(): Boolean { val shouldShowDialog = shouldShowCookieBannerUI && !userOptOutOfReEngageCookieBannerDialog && !shouldUseCookieBanner return if (!shouldShowTotalCookieProtectionCFR && shouldShowDialog) { !cookieBannerDetectedPreviously || timeNowInMillis() - lastInteractionWithReEngageCookieBannerDialogInMs >= timerForCookieBannerDialog } else { false } } Indicates if we should should show the cookie banner dialog that invites the user to turn-on the setting. +"fun checkIfFenixIsDefaultBrowserOnAppResume(): Boolean { val prefKey = appContext.getPreferenceKey(R.string.pref_key_default_browser) val isDefaultBrowserNow = isDefaultBrowserBlocking() val wasDefaultBrowserOnLastResume = this.preferences.getBoolean(prefKey, isDefaultBrowserNow) this.preferences.edit().putBoolean(prefKey, isDefaultBrowserNow).apply() return isDefaultBrowserNow && !wasDefaultBrowserOnLastResume }" "Declared as a function for performance purposes. This could be declared as a variable using booleanPreference like other members of this class. However, doing so will make it so it will be initialized once Settings.kt is first called, which in turn will call `isDefaultBrowserBlocking()`. This will lead to a performance regression since that function can be expensive to call." +fun isDefaultBrowserBlocking(): Boolean { val browsers = BrowsersCache.all(appContext) return browsers.isDefaultBrowser } "This function is ""blocking"" since calling this can take approx. 30-40ms (timing taken on a G5+)." +"var lastBrowseActivity by longPreference( appContext.getPreferenceKey(R.string.pref_key_last_browse_activity_time), default = 0L, )" "Indicates the last time when the user was interacting with the [BrowserFragment], This is useful to determine if the user has to start on the [HomeFragment] or it should go directly to the [BrowserFragment]." +"var openHomepageAfterFourHoursOfInactivity by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_start_on_home_after_four_hours), default = true, )" Indicates if the user has selected the option to start on the home screen after four hours of inactivity. +"var alwaysOpenTheHomepageWhenOpeningTheApp by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_start_on_home_always), default = false, )" Indicates if the user has selected the option to always start on the home screen. +"var alwaysOpenTheLastTabWhenOpeningTheApp by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_start_on_home_never), default = false, )" Indicates if the user has selected the option to never start on the home screen and have their last tab opened. +fun shouldStartOnHome(): Boolean { return when { openHomepageAfterFourHoursOfInactivity -> timeNowInMillis() - lastBrowseActivity >= FOUR_HOURS_MS alwaysOpenTheHomepageWhenOpeningTheApp -> true alwaysOpenTheLastTabWhenOpeningTheApp -> false else -> false } } "Indicates if the user should start on the home screen, based on the user's preferences." +"var inactiveTabsAreEnabled by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_inactive_tabs), default = true, )" Indicates if the user has enabled the inactive tabs feature. +fun updateIfNeeded(newTrackers: List) { if (newTrackers != trackers) { trackers = newTrackers buckets = putTrackersInBuckets(newTrackers) } } "If [newTrackers] has changed since the last call, update [buckets] based on the new tracker log list." +fun blockedIsEmpty() = buckets.blockedBucketMap.isEmpty() Returns true if there are no trackers being blocked. +fun loadedIsEmpty() = buckets.loadedBucketMap.isEmpty() Returns true if there are no trackers loaded. +"fun get(key: TrackingProtectionCategory, blocked: Boolean) = if (blocked) buckets.blockedBucketMap[key].orEmpty() else buckets.loadedBucketMap[key].orEmpty() companion object { private fun putTrackersInBuckets( list: List, ): BucketedTrackerLog { val blockedMap = createMap() val loadedMap = createMap() for (item in list) { if (item.cookiesHasBeenBlocked) { blockedMap.addTrackerHost(CROSS_SITE_TRACKING_COOKIES, item) } // Blocked categories for (category in item.blockedCategories) { blockedMap.addTrackerHost(category, item) } // Loaded categories for (category in item.loadedCategories) { loadedMap.addTrackerHost(category, item) } } return BucketedTrackerLog(blockedMap, loadedMap) }" Gets the tracker URLs for a given category. +"private fun createMap() = EnumMap>(TrackingProtectionCategory::class.java)" Create an empty mutable map of [TrackingProtectionCategory] to hostnames. +"private fun MutableMap>.addTrackerHost( category: TrackingCategory, tracker: TrackerLog, ) { val key = when (category) { TrackingCategory.CRYPTOMINING -> CRYPTOMINERS TrackingCategory.FINGERPRINTING -> FINGERPRINTERS TrackingCategory.MOZILLA_SOCIAL -> SOCIAL_MEDIA_TRACKERS TrackingCategory.SCRIPTS_AND_SUB_RESOURCES -> TRACKING_CONTENT else -> return } addTrackerHost(key, tracker) }" "Add the hostname of the [TrackerLog.url] into the map for the given category from Android Components. The category is transformed into a corresponding Fenix bucket, and the item is discarded if the category doesn't have a match." +"private fun MutableMap>.addTrackerHost( key: TrackingProtectionCategory, tracker: TrackerLog, ) { getOrPut(key) { mutableListOf() }.add(tracker) } }" Add the hostname of the [TrackerLog] into the map for the given [TrackingProtectionCategory]. +"class ProtectionsStore(initialState: ProtectionsState) : Store( initialState, ::protectionsStateReducer, )" The [Store] for holding the [ProtectionsState] and applying [ProtectionsAction]s. +sealed class ProtectionsAction : Action { } Actions to dispatch through the `TrackingProtectionStore` to modify `ProtectionsState` through the reducer. +"data class Change( val url: String, val isTrackingProtectionEnabled: Boolean, val isCookieBannerHandlingEnabled: Boolean, val listTrackers: List, val mode: ProtectionsState.Mode, ) : ProtectionsAction()"  The values of the tracking protection view has been changed. +data class ToggleCookieBannerHandlingProtectionEnabled(val isEnabled: Boolean) : ProtectionsAction() Toggles the enabled state of cookie banner handling protection. +data class UrlChange(val url: String) : ProtectionsAction() Indicates the url has changed. +data class TrackerLogChange(val listTrackers: List) : ProtectionsAction() Indicates the url has the list of trackers has been updated. +object ExitDetailsMode : ProtectionsAction() Indicates the user is leaving the detailed view. +"data class EnterDetailsMode( val category: TrackingProtectionCategory, val categoryBlocked: Boolean, ) : ProtectionsAction() }" Holds the data to show a detailed tracking protection view. +"data class ProtectionsState( val tab: SessionState?, val url: String, val isTrackingProtectionEnabled: Boolean, val isCookieBannerHandlingEnabled: Boolean, val listTrackers: List, val mode: Mode, val lastAccessedCategory: String,)  : State { }" The state for the Protections Panel +sealed class Mode { } Indicates the modes in which a tracking protection view could be in. +object Normal : Mode() Indicates that tracking protection view should not be in detail mode. +"data class Details(val selectedCategory: TrackingProtectionCategory,val categoryBlocked: Boolean,) : Mode()}" Indicates that tracking protection view in detailed mode. +"enum class TrackingProtectionCategory( @StringRes val title: Int, @StringRes val description: Int, ) { SOCIAL_MEDIA_TRACKERS( R.string.etp_social_media_trackers_title, R.string.etp_social_media_trackers_description, ), CROSS_SITE_TRACKING_COOKIES( R.string.etp_cookies_title, R.string.etp_cookies_description, ), CRYPTOMINERS( R.string.etp_cryptominers_title, R.string.etp_cryptominers_description, ), FINGERPRINTERS( R.string.etp_fingerprinters_title, R.string.etp_fingerprinters_description, ), TRACKING_CONTENT( R.string.etp_tracking_content_title, R.string.etp_tracking_content_description, ), REDIRECT_TRACKERS( R.string.etp_redirect_trackers_title, R.string.etp_redirect_trackers_description, ), }" The 5 categories of Tracking Protection to display +"fun protectionsStateReducer( state: ProtectionsState, action: ProtectionsAction, ): ProtectionsState { return when (action) { is ProtectionsAction.Change -> state.copy( url = action.url, isTrackingProtectionEnabled = action.isTrackingProtectionEnabled, isCookieBannerHandlingEnabled = action.isCookieBannerHandlingEnabled, listTrackers = action.listTrackers, mode = action.mode, ) is ProtectionsAction.UrlChange -> state.copy( url = action.url, ) is ProtectionsAction.TrackerLogChange -> state.copy(listTrackers = action.listTrackers) ProtectionsAction.ExitDetailsMode -> state.copy( mode = ProtectionsState.Mode.Normal, ) is ProtectionsAction.EnterDetailsMode -> state.copy( mode = ProtectionsState.Mode.Details( action.category, action.categoryBlocked, ), lastAccessedCategory = action.category.name, ) is ProtectionsAction.ToggleCookieBannerHandlingProtectionEnabled -> state.copy( isCookieBannerHandlingEnabled = action.isEnabled, ) }" The [ProtectionsState] reducer. +"class TabsTrayStore( initialState: TabsTrayState = TabsTrayState(), middlewares: List> = emptyList(), ) : Store( initialState, TabsTrayReducer::reduce, middlewares, )" A [Store] that holds the [TabsTrayState] for the tabs tray and reduces [TabsTrayAction]sdispatched to the store. +"internal object TabsTrayReducer { fun reduce(state: TabsTrayState, action: TabsTrayAction): TabsTrayState { return when (action) { is TabsTrayAction.EnterSelectMode -> state.copy(mode = TabsTrayState.Mode.Select(emptySet())) is TabsTrayAction.ExitSelectMode -> state.copy(mode = TabsTrayState.Mode.Normal) is TabsTrayAction.AddSelectTab -> state.copy(mode = TabsTrayState.Mode.Select(state.mode.selectedTabs + action.tab)) is TabsTrayAction.RemoveSelectTab -> { val selected = state.mode.selectedTabs.filter { it.id != action.tab.id }.toSet() state.copy( mode = if (selected.isEmpty()) { TabsTrayState.Mode.Normal } else { TabsTrayState.Mode.Select(selected) }, ) } is TabsTrayAction.PageSelected -> state.copy(selectedPage = action.page) is TabsTrayAction.SyncNow -> state.copy(syncing = true) is TabsTrayAction.SyncCompleted -> state.copy(syncing = false) is TabsTrayAction.UpdateInactiveTabs -> state.copy(inactiveTabs = action.tabs) is TabsTrayAction.UpdateNormalTabs -> state.copy(normalTabs = action.tabs) is TabsTrayAction.UpdatePrivateTabs -> state.copy(privateTabs = action.tabs) is TabsTrayAction.UpdateSyncedTabs -> state.copy(syncedTabs = action.tabs) } } }" Reducer for [TabsTrayStore]. +data class UpdateSyncedTabs(val tabs: List) : TabsTrayAction()} Updates the list of synced tabs in [TabsTrayState.syncedTabs]. +data class UpdatePrivateTabs(val tabs: List) : TabsTrayAction() Updates the list of tabs in [TabsTrayState.privateTabs]. +data class UpdateNormalTabs(val tabs: List) : TabsTrayAction() Updates the list of tabs in [TabsTrayState.normalTabs]. +data class UpdateInactiveTabs(val tabs: List) : TabsTrayAction() Updates the list of tabs in [TabsTrayState.inactiveTabs]. +object SyncCompleted : TabsTrayAction() "When a ""sync"" action has completed; this can be triggered immediately after [SyncNow] if no sync action was able to be performed." +object SyncNow : TabsTrayAction() "A request to perform a ""sync"" action." +data class PageSelected(val page: Page) : TabsTrayAction() the active page in the tray that is now in focus. +data class RemoveSelectTab(val tab: TabSessionState) : TabsTrayAction() Removed a [TabSessionState] from the selection set. +data class AddSelectTab(val tab: TabSessionState) : TabsTrayAction() Added a new [TabSessionState] to the selection set. +object ExitSelectMode : TabsTrayAction() Exited multi-select mode. +object EnterSelectMode : TabsTrayAction() Entered multi-select mode. +sealed class TabsTrayAction : Action {} [Action] implementation related to [TabsTrayStore]. +data class Select(override val selectedTabs: Set) : Mode({} The multi-select mode that the tabs list is in containing the set of currently selected tabs. +object Normal : Mode() The default mode the tabs list is in. +open val selectedTabs = emptySet() A set of selected tabs which we would want to perform an action on. +sealed class Mode { } The current mode that the tabs list is in. +"data class TabsTrayState( val selectedPage: Page = Page.NormalTabs, val mode: Mode = Mode.Normal, val inactiveTabs: List = emptyList(), val normalTabs: List = emptyList(), val privateTabs: List = emptyList(), val syncedTabs: List = emptyList(), val syncing: Boolean = false, ) : State { }" Value type that represents the state of the tabs tray. +"abstract class AbstractPageViewHolder constructor( val containerView: View, ) : RecyclerView.ViewHolder(containerView) { }" An abstract [RecyclerView.ViewHolder] for [TrayPagerAdapter] items. +"abstract fun bind( adapter: RecyclerView.Adapter, )" Invoked when the nested [RecyclerView.Adapter] is bound to the [RecyclerView.ViewHolder]. +abstract fun attachedToWindow() Invoked when the [RecyclerView.ViewHolder] is attached from the window. This could have previously been bound and is now attached again. +abstract fun detachedFromWindow() } Invoked when the [RecyclerView.ViewHolder] is detached from the window. +"override fun attachedToWindow() { adapterRef?.let { adapter -> adapterObserver = object : RecyclerView.AdapterDataObserver() { override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { updateTrayVisibility(showTrayList(adapter)) }  override fun onItemRangeRemoved(positionstart: Int, itemcount: Int) { updateTrayVisibility(showTrayList(adapter)) } } adapterObserver?.let { adapter.registerAdapterDataObserver(it) } } }" When the [RecyclerView.Adapter] is attached to the window we register a data observer to always check whether to call [updateTrayVisibility]. +override fun detachedFromWindow() { adapterObserver?.let { adapterRef?.unregisterAdapterDataObserver(it) adapterObserver = null } } "[RecyclerView.AdapterDataObserver]s are responsible to be unregistered when they are done, so we do that here when our [TrayPagerAdapter] page is detached from the window." +open fun showTrayList(adapter: RecyclerView.Adapter): Boolean = adapter.itemCount > 0 A way for an implementor of [AbstractBrowserPageViewHolder] to define their own behavior of when to show/hide the tray list and empty list UI. +fun updateTrayVisibility(showTrayList: Boolean) { trayList.isVisible = showTrayList emptyList.isVisible = !showTrayList } Helper function used to toggle the visibility of the tabs tray lists and the empty list message. +"fun BrowserMenu.showWithTheme(view: View) { show(view).also { popupMenu -> (popupMenu.contentView as? CardView)?.setCardBackgroundColor( ContextCompat.getColor( view.context, R.color.fx_mobile_layer_color_2, ), ) } }" Invokes [BrowserMenu.show] and applies the default theme color background. +"@OptIn(ExperimentalCoroutinesApi::class) class SyncButtonBinding( tabsTrayStore: TabsTrayStore, private val onSyncNow: () -> Unit, ) : AbstractBinding(tabsTrayStore) { override suspend fun onState(flow: Flow) { flow.map { it.syncing } .ifChanged() .collect { syncingNow -> if (syncingNow) { onSyncNow() } } } }" An [AbstractBinding] that invokes the [onSyncNow] callback when the [TabsTrayState.syncing] is set. +fun TabSessionState.hasSearchTerm(): Boolean { return content.searchTerms.isNotEmpty() || !historyMetadata?.searchTerm.isNullOrBlank() } Returns true if the [TabSessionState] has a search term. +internal fun TabSessionState.isNormalTabActive(maxActiveTime: Long): Boolean { return isActive(maxActiveTime) && !content.private } Returns true if the [TabSessionState] is considered active based on the [maxActiveTime]. +internal fun TabSessionState.isNormalTabActiveWithSearchTerm(maxActiveTime: Long): Boolean { return isNormalTabActive(maxActiveTime) && hasSearchTerm() } Returns true if the [TabSessionState] have a search term. +internal fun TabSessionState.isNormalTabWithSearchTerm(): Boolean { return hasSearchTerm() && !content.private } Returns true if the [TabSessionState] has a search term but may or may not be active. +internal fun TabSessionState.isNormalTabInactive(maxActiveTime: Long): Boolean { return !isActive(maxActiveTime) && !content.private } Returns true if the [TabSessionState] is considered active based on the [maxActiveTime]. +internal fun TabSessionState.isNormalTab(): Boolean { return !content.private } Returns true if the [TabSessionState] is not private.  +fun TabSessionState.toDisplayTitle(): String = content.title.ifEmpty { content.url.trimmed() } Returns a [String] for displaying a [TabSessionState]'s title or its url when a title is not available. +"fun BrowserState.getNormalTrayTabs( inactiveTabsEnabled: Boolean, ): List { return normalTabs.run { if (inactiveTabsEnabled) { filter { it.isNormalTabActive(maxActiveTime) } } else { this } } }" The list of normal tabs in the tabs tray filtered appropriately based on feature flags. +fun BrowserState.findPrivateTab(tabId: String): TabSessionState? { return privateTabs.firstOrNull { it.id == tabId } } Finds and returns the private tab with the given id. Returns null if no matching tab could be found. +val BrowserState.selectedPrivateTab: TabSessionState? get() = selectedTabId?.let { id -> findPrivateTab(id) } The currently selected tab if there's one that is private. +"fun SyncedTabsView.ErrorType.toSyncedTabsListItem(context: Context, navController: NavController) = when (this) { SyncedTabsView.ErrorType.MULTIPLE_DEVICES_UNAVAILABLE -> SyncedTabsListItem.Error(errorText = context.getString(R.string.synced_tabs_connect_another_device)) SyncedTabsView.ErrorType.SYNC_ENGINE_UNAVAILABLE -> SyncedTabsListItem.Error(errorText = context.getString(R.string.synced_tabs_enable_tab_syncing)) SyncedTabsView.ErrorType.SYNC_NEEDS_REAUTHENTICATION -> SyncedTabsListItem.Error(errorText = context.getString(R.string.synced_tabs_reauth)) SyncedTabsView.ErrorType.NO_TABS_AVAILABLE -> SyncedTabsListItem.Error( errorText = context.getString(R.string.synced_tabs_no_tabs), ) SyncedTabsView.ErrorType.SYNC_UNAVAILABLE -> SyncedTabsListItem.Error( errorText = context.getString(R.string.synced_tabs_sign_in_message), errorButton = SyncedTabsListItem.ErrorButton( buttonText = context.getString(R.string.synced_tabs_sign_in_button), ) { navController.navigate(NavGraphDirections.actionGlobalTurnOnSync()) }, ) }" Converts [SyncedTabsView.ErrorType] to [SyncedTabsListItem.Error] with a lambda for ONLY [SyncedTabsView.ErrorType.SYNC_UNAVAILABLE] +"fun List.toComposeList( taskContinuityEnabled: Boolean, ): List = asSequence().flatMap { (device, tabs) -> if (taskContinuityEnabled) { val deviceTabs = if (tabs.isEmpty()) { emptyList() } else { tabs.map { val url = it.active().url val titleText = it.active().title.ifEmpty { url.trimmed() } SyncedTabsListItem.Tab(titleText, url, it) } } sequenceOf(SyncedTabsListItem.DeviceSection(device.displayName, deviceTabs)) } else { val deviceTabs = if (tabs.isEmpty()) { sequenceOf(SyncedTabsListItem.NoTabs) } else { tabs.asSequence().map { val url = it.active().url val titleText = it.active().title.ifEmpty { url.trimmed() } SyncedTabsListItem.Tab(titleText, url, it) } } sequenceOf(SyncedTabsListItem.Device(device.displayName)) + deviceTabs } }.toList()" Converts a list of [SyncedDeviceTabs] into a list of [SyncedTabsListItem]. +"fun RecyclerView.Adapter.observeFirstInsert(block: () -> Unit) { val observer = object : RecyclerView.AdapterDataObserver() { override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { block.invoke() unregisterAdapterDataObserver(this) } } registerAdapterDataObserver(observer) }" Observes the adapter and invokes the callback [block] only when data is first inserted to the adapter. +internal val Context.defaultBrowserLayoutColumns: Int get() { return if (components.settings.gridTabView) { numberOfGridColumns } else { 1 } } Returns the default number of columns a browser tray list should display based on user preferences. +internal val Context.numberOfGridColumns: Int get() { val displayMetrics = resources.displayMetrics val screenWidthDp = displayMetrics.widthPixels / displayMetrics.density return (screenWidthDp / MIN_COLUMN_WIDTH_DP).toInt().coerceAtLeast(2) } Returns the number of grid columns we can fit on the screen in the tabs tray. +internal val ConcatAdapter.browserAdapter get() = adapters.find { it is BrowserTabsAdapter } as BrowserTabsAdapter A convenience binding for retrieving the [BrowserTabsAdapter] from the [ConcatAdapter]. +internal val ConcatAdapter.inactiveTabsAdapter get() = adapters.find { it is InactiveTabsAdapter } as InactiveTabsAdapter A convenience binding for retrieving the [InactiveTabsAdapter] from the [ConcatAdapter]. +fun BrowserStore.getTabSessionState(tabs: Collection): List { return tabs.mapNotNull { state.findTab(it.id) } } Find and extract a list [TabSessionState] from the [BrowserStore] using the IDs from [tabs]. +Opens the provided inactive tab. fun handleInactiveTabClicked(tab: TabSessionState) +fun handleCloseInactiveTabClicked(tab: TabSessionState) Closes the provided inactive tab. +fun handleInactiveTabsHeaderClicked(expanded: Boolean) Expands or collapses the inactive tabs section. +fun handleInactiveTabsAutoCloseDialogDismiss() Dismisses the inactive tabs auto-close dialog. +fun handleEnableInactiveTabsAutoCloseClicked() Enables the inactive tabs auto-close feature with a default time period. +fun handleDeleteAllInactiveTabsClicked() Deletes all inactive tabs. +"fun open(tab: TabSessionState, source: String? = null)" Open a tab. +"fun close(tab: TabSessionState, source: String? = null)" Close the tab. +fun onFabClicked(isPrivate: Boolean) TabTray's Floating Action Button clicked. +fun onRecentlyClosedClicked() Recently Closed item is clicked. +fun onMediaClicked(tab: TabSessionState) Indicates Play/Pause item is clicked. +"fun onMultiSelectClicked( tab: TabSessionState, holder: SelectionHolder, source: String?, )" Handles clicks when multi-selection is enabled. +"fun onLongClicked( tab: TabSessionState, holder: SelectionHolder, ): Boolean" Handles long click events when tab item is clicked. +"private fun updateSyncPreferenceNeedsReauth() { syncPreference.apply { isSwitchWidgetVisible = false title = loggedOffTitle setOnPreferenceChangeListener { _, _ -> onReconnectClicked() false } } }" Displays the logged off title to prompt the user to to re-authenticate their sync account. +"private fun updateSyncPreferenceNeedsLogin() { syncPreference.apply { isSwitchWidgetVisible = false title = loggedOffTitle setOnPreferenceChangeListener { _, _ -> onSyncSignInClicked() false } } }" Display that the user can sync across devices when the user is logged off. +"private fun updateSyncPreferenceStatus() { syncPreference.apply { isSwitchWidgetVisible = true val syncEnginesStatus = SyncEnginesStorage(context).getStatus() val syncStatus = syncEnginesStatus.getOrElse(syncEngine) { false } title = loggedInTitle isChecked = syncStatus setOnPreferenceChangeListener { _, newValue -> SyncEnginesStorage(context).setStatus(syncEngine, newValue as Boolean) setSwitchCheckedState(newValue) true } } }" Shows a switch toggle for the sync preference when the user is logged in. +"fun getSumoURLForTopic( context: Context, topic: SumoTopic, locale: Locale = Locale.getDefault(), ): String { val escapedTopic = getEncodedTopicUTF8(topic.topicStr) // Remove the whitespace so a search is not triggered: val appVersion = context.appVersionName.replace("" "", """") val osTarget = ""Android"" val langTag = getLanguageTag(locale) return ""https://support.mozilla.org/1/mobile/$appVersion/$osTarget/$langTag/$escapedTopic"" }" Gets a support page URL for the corresponding topic. +"fun getGenericSumoURLForTopic(topic: SumoTopic, locale: Locale = Locale.getDefault()): String { val escapedTopic = getEncodedTopicUTF8(topic.topicStr) val langTag = getLanguageTag(locale) return ""https://support.mozilla.org/$langTag/kb/$escapedTopic"" }" Gets a support page URL for the corresponding topic.Used when the app version and os are not part of the URL. +"open class StringSharedPreferenceUpdater : Preference.OnPreferenceChangeListener { override fun onPreferenceChange(preference: Preference, newValue: Any?): Boolean { val newStringValue = newValue as? String ?: return false preference.context.settings().preferences.edit { putString(preference.key, newStringValue) } return true } }" Updates the corresponding [android.content.SharedPreferences] when the String [Preference] is changed. The preference key is used as the shared preference key. +"open class SharedPreferenceUpdater : Preference.OnPreferenceChangeListener { override fun onPreferenceChange(preference: Preference, newValue: Any?): Boolean { val newBooleanValue = newValue as? Boolean ?: return false preference.context.settings().preferences.edit { putBoolean(preference.key, newBooleanValue) } return true } }" Updates the corresponding [android.content.SharedPreferences] when the boolean [Preference] is changed. The preference key is used as the shared preference key. +open fun getDescription(): String? = null Returns the description to be used the UI. +abstract fun getLearnMoreUrl(): String Returns the URL that should be used when the learn more link is clicked. +abstract fun getSwitchValue(): Boolean Indicates the value which the switch widget should show. +"fun RadioButton.setStartCheckedIndicator() { val attr = context.theme.resolveAttribute(android.R.attr.listChoiceIndicatorSingle) val buttonDrawable = AppCompatResources.getDrawable(context, attr) buttonDrawable?.apply { setBounds(0, 0, intrinsicWidth, intrinsicHeight) } putCompoundDrawablesRelative(start = buttonDrawable) }" "In devices with Android 6, when we use android:button=""@null"" android:drawableStart doesn't work via xml as a result we have to apply it programmatically. More info about this issue https://github.com/mozilla-mobile/fenix/issues/1414" +"inline fun Preference.setOnPreferenceChangeListener( crossinline onPreferenceChangeListener: (Preference, T) -> Boolean, ) { setOnPreferenceChangeListener { preference: Preference, newValue: Any -> (newValue as? T)?.let { onPreferenceChangeListener(preference, it) } ?: false } }" Sets the callback to be invoked when this preference is changed by the user (but before the internal state has been updated). Allows the type of the preference to be specified. If the new value doesn't match the preference type the listener isn't called. +fun PreferenceFragmentCompat.requirePreference(@StringRes preferenceId: Int) = requireNotNull(findPreference(getPreferenceKey(preferenceId))) Find a preference with the corresponding key and throw if it does not exist. +"class AuthIntentReceiverActivity : Activity() { @VisibleForTesting override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) MainScope().launch { // The intent property is nullable, but the rest of the code below // assumes it is not. If it's null, then we make a new one and open // the HomeActivity. val intent = intent?.let { Intent(intent) } ?: Intent() if (settings().lastKnownMode.isPrivate) { components.intentProcessors.privateCustomTabIntentProcessor.process(intent) } else { components.intentProcessors.customTabIntentProcessor.process(intent) } intent.setClassName(applicationContext, AuthCustomTabActivity::class.java.name) intent.putExtra(HomeActivity.OPEN_TO_BROWSER, true) startActivity(intent) finish() } } }" Processes incoming intents and sends them to the corresponding activity. +"fun updateAccountUIState(context: Context, profile: Profile?) { val account = accountManager.authenticatedAccount() updateFxAAllowDomesticChinaServerMenu() // Signed-in, no problems. if (account != null && !accountManager.accountNeedsReauth()) { preferenceSignIn.isVisible = false avatarJob?.cancel() val avatarUrl = profile?.avatar?.url if (avatarUrl != null) { avatarJob = scope.launch { val roundedAvatarDrawable = toRoundedDrawable(avatarUrl, context) preferenceFirefoxAccount.icon = roundedAvatarDrawable ?: genericAvatar(context) } } else { avatarJob = null preferenceFirefoxAccount.icon = genericAvatar(context) } preferenceSignIn.onPreferenceClickListener = null preferenceFirefoxAccountAuthError.isVisible = false preferenceFirefoxAccount.isVisible = true accountPreferenceCategory.isVisible = true preferenceFirefoxAccount.displayName = profile?.displayName preferenceFirefoxAccount.email = profile?.email // Signed-in, need to re-authenticate. } else if (account != null && accountManager.accountNeedsReauth()) { preferenceFirefoxAccount.isVisible = false preferenceFirefoxAccountAuthError.isVisible = true accountPreferenceCategory.isVisible = true preferenceSignIn.isVisible = false preferenceSignIn.onPreferenceClickListener = null preferenceFirefoxAccountAuthError.email = profile?.email // Signed-out. } else { preferenceSignIn.isVisible = true preferenceFirefoxAccount.isVisible = false preferenceFirefoxAccountAuthError.isVisible = false accountPreferenceCategory.isVisible = false } }" "Updates the UI to reflect current account state. Possible conditions are logged-in without problems, logged-out, and logged-in but needs to re-authenticate." +fun cancel() { scope.cancel() } Cancel any running coroutine jobs for loading account images. +"private fun genericAvatar(context: Context) = AppCompatResources.getDrawable(context, R.drawable.ic_account)" Returns generic avatar for accounts. +"private suspend fun toRoundedDrawable( url: String, context: Context, ) = httpClient.bitmapForUrl(url)?.let { bitmap -> RoundedBitmapDrawableFactory.create(context.resources, bitmap).apply { isCircular = true setAntiAlias(true) } }" "Gets a rounded drawable from a URL if possible, else null." +"fun verifyCredentialsOrShowSetupWarning(context: Context, prefList: List) { // Use the BiometricPrompt if available if (BiometricPromptFeature.canUseFeature(context)) { togglePrefsEnabled(prefList, false) biometricPromptFeature.get()?.requestAuthentication(unlockMessage()) return } // Fallback to prompting for password with the KeyguardManager val manager = context.getSystemService() if (manager?.isKeyguardSecure == true) { showPinVerification(manager) } else { // Warn that the device has not been secured if (context.settings().shouldShowSecurityPinWarning) { showPinDialogWarning(context) } else { navigateOnSuccess() } } }" Use [BiometricPromptFeature] or [KeyguardManager] to confirm device security. +"fun setBiometricPrompt(view: View, prefList: List) { biometricPromptFeature.set( feature = BiometricPromptFeature( context = requireContext(), fragment = this, onAuthFailure = { togglePrefsEnabled(prefList, true) }, onAuthSuccess = ::navigateOnSuccess, ), owner = this, view = view, ) }" Sets the biometric prompt feature. +"@Suppress(""Deprecation"") abstract fun showPinVerification(manager: KeyguardManager)" Creates a prompt to verify the device's pin/password and start activity based on the result. This is only used when BiometricPrompt is unavailable on the device. +"fun togglePrefsEnabled(prefList: List, enabled: Boolean) { for (preference in prefList) { requirePreference(preference).isEnabled = enabled } }" Toggle preferences to enable or disable navigation during authentication flows. +abstract fun showPinDialogWarning(context: Context) Shows a dialog warning to set up a pin/password when the device is not secured. This is only used when BiometricPrompt is unavailable on the device. +abstract fun navigateOnSuccess() Navigate when authentication is successful. +abstract fun unlockMessage(): String Gets the string to be used for [BiometricPromptFeature.requestAuthentication] prompting to unlock the device. +fun BiometricManager.isEnrolled(): Boolean { val status = canAuthenticate(BIOMETRIC_WEAK) return status == BIOMETRIC_SUCCESS } Checks if the user can use the [BiometricManager] and is therefore enrolled. +fun BiometricManager.isHardwareAvailable(): Boolean { val status = canAuthenticate(BIOMETRIC_WEAK) return status != BIOMETRIC_ERROR_NO_HARDWARE && status != BIOMETRIC_ERROR_HW_UNAVAILABLE } Checks if the hardware requirements are met for using the [BiometricManager]. +"private fun autofillFragmentStateReducer( state: AutofillFragmentState, action: AutofillAction, ): AutofillFragmentState { return when (action) { is AutofillAction.UpdateAddresses -> { state.copy( addresses = action.addresses, isLoading = false, ) } is AutofillAction.UpdateCreditCards -> { state.copy( creditCards = action.creditCards, isLoading = false, ) } } }" Reduces the autofill state from the current state with the provided [action] to be performed. +"fun LocaleManager.getSelectedLocale( context: Context, localeList: List = getSupportedLocales(), ): Locale { val selectedLocale = getCurrentLocale(context)?.toLanguageTag() val defaultLocale = getSystemDefault() return if (selectedLocale == null) { defaultLocale } else { val supportedMatch = localeList .firstOrNull { it.toLanguageTag() == selectedLocale } supportedMatch ?: defaultLocale } }" "Returns the locale that corresponds to the language stored locally by us. If no suitable one is found, return default." +"fun LocaleManager.getSupportedLocales(): List { val resultLocaleList: MutableList = ArrayList() resultLocaleList.add(0, getSystemDefault()) resultLocaleList.addAll( BuildConfig.SUPPORTED_LOCALE_ARRAY .toList() .map { it.toLocale() }.sortedWith( compareBy( { it.displayLanguage }, { it.displayCountry }, ), ), ) return resultLocaleList }" "Returns a list of currently supported locales, with the system default set as the first one" +"private fun localeSettingsStateReducer( state: LocaleSettingsState, action: LocaleSettingsAction, ): LocaleSettingsState { return when (action) { is LocaleSettingsAction.Select -> { state.copy(selectedLocale = action.selectedItem, searchedLocaleList = state.localeList) } is LocaleSettingsAction.Search -> { val searchedItems = state.localeList.filter { it.getDisplayLanguage(it).startsWith(action.query, ignoreCase = true) || it.displayLanguage.startsWith(action.query, ignoreCase = true) || it === state.localeList[0] } state.copy(searchedLocaleList = searchedItems) } } }" Reduces the locale state from the current state and an action performed on it. +sealed class LocaleSettingsAction : Action { data class Select(val selectedItem: Locale) : LocaleSettingsAction() data class Search(val query: String) : LocaleSettingsAction() } Actions to dispatch through the `LocaleSettingsStore` to modify `LocaleSettingsState` through the reducer. +"data class LocaleSettingsState( val localeList: List, val searchedLocaleList: List, val selectedLocale: Locale, ) : State fun createInitialLocaleSettingsState(context: Context): LocaleSettingsState { val supportedLocales = LocaleManager.getSupportedLocales() return LocaleSettingsState( supportedLocales, supportedLocales, selectedLocale = LocaleManager.getSelectedLocale(context), ) }" The state of the language selection page +"private fun Locale.getProperDisplayName(): String { val displayName = this.displayName.capitalize(Locale.getDefault()) if (displayName.equals(this.toString(), ignoreCase = true)) { return LocaleViewHolder.LOCALE_TO_DISPLAY_ENGLISH_NAME_MAP[this.toString()] ?: displayName } return displayName }" "Returns the locale in the selected language, with fallback to English name" +"private fun String.capitalize(locale: Locale): String { return substring(0, 1).uppercase(locale) + substring(1) }" "Similar to Kotlin's capitalize with locale parameter, but that method is currently experimental" +"fun Address.getAddressLabel(): String = listOf( streetAddress.toOneLineAddress(), addressLevel3, addressLevel2, organization, addressLevel1, country, postalCode, tel, email, ).filter { it.isNotEmpty() }.joinToString("", "")" Generate a description item text for an [Address].  +"fun Address.getFullName(): String = listOf(givenName, additionalName, familyName) .filter { it.isNotEmpty() } .joinToString("" "")" Generate a label item text for an [Address] +private fun loadAddresses() { lifecycleScope.launch { val addresses = requireContext().components.core.autofillStorage.getAllAddresses() lifecycleScope.launch(Dispatchers.Main) { store.dispatch(AutofillAction.UpdateAddresses(addresses)) } } } Fetches all the addresses from the autofill storage and updates the [AutofillFragmentStore] with the list of addresses. +"@Composable fun AddressList( addresses: List
, onAddressClick: (Address) -> Unit, onAddAddressButtonClick: () -> Unit, ) { LazyColumn { items(addresses) { address -> TextListItem( label = address.getFullName(), modifier = Modifier.padding(start = 56.dp), description = address.getAddressLabel(), maxDescriptionLines = 2, onClick = { onAddressClick(address) }, ) } item { IconListItem( label = stringResource(R.string.preferences_addresses_add_address), beforeIconPainter = painterResource(R.drawable.ic_new), onClick = onAddAddressButtonClick, ) } } }" A list of addresses. +"fun onUpdateAddress(guid: String, addressFields: UpdatableAddressFields)" "Updates the provided address in the autofill storage. Called when a user taps on the update menu item or ""Update"" button." +fun onDeleteAddress(guid: String) "Deletes the provided address from the autofill storage. Called when a user taps on the save menu item or ""Save"" button." +fun onSaveAddress(addressFields: UpdatableAddressFields) "Saves the provided address field into the autofill storage. Called when a user taps on the save menu item or ""Save"" button." +fun onCancelButtonClicked() "Navigates back to the autofill preference settings. Called when a user taps on the ""Cancel"" button." +"private fun syncDeviceName(newDeviceName: String): Boolean { if (newDeviceName.trim().isEmpty()) { return false } // This may fail, and we'll have a disparity in the UI until `updateDeviceName` is called. viewLifecycleOwner.lifecycleScope.launch(Main) { context?.let { accountManager.authenticatedAccount() ?.deviceConstellation() ?.setDeviceName(newDeviceName, it) } } return true }" Takes a non-empty value and sets the device name. May fail due to authentication. +private fun syncNow() { viewLifecycleOwner.lifecycleScope.launch { SyncAccount.syncNow.record(NoExtras()) // Trigger a sync. requireComponents.backgroundServices.accountManager.syncNow(SyncReason.User) // Poll for device events & update devices. accountManager.authenticatedAccount() ?.deviceConstellation()?.run { refreshDevices() pollForCommands() } } } Manual sync triggered by the user. This also checks account authentication and refreshes the device list. +private fun updateSyncEngineStates() { val syncEnginesStatus = SyncEnginesStorage(requireContext()).getStatus() requirePreference(R.string.pref_key_sync_bookmarks).apply { isEnabled = syncEnginesStatus.containsKey(SyncEngine.Bookmarks) isChecked = syncEnginesStatus.getOrElse(SyncEngine.Bookmarks) { true } } requirePreference(R.string.pref_key_sync_credit_cards).apply { isEnabled = syncEnginesStatus.containsKey(SyncEngine.CreditCards) isChecked = syncEnginesStatus.getOrElse(SyncEngine.CreditCards) { true } } requirePreference(R.string.pref_key_sync_history).apply { isEnabled = syncEnginesStatus.containsKey(SyncEngine.History) isChecked = syncEnginesStatus.getOrElse(SyncEngine.History) { true } } requirePreference(R.string.pref_key_sync_logins).apply { isEnabled = syncEnginesStatus.containsKey(SyncEngine.Passwords) isChecked = syncEnginesStatus.getOrElse(SyncEngine.Passwords) { true } } requirePreference(R.string.pref_key_sync_tabs).apply { isEnabled = syncEnginesStatus.containsKey(SyncEngine.Tabs) isChecked = syncEnginesStatus.getOrElse(SyncEngine.Tabs) { true } } requirePreference(R.string.pref_key_sync_address).apply { isVisible = FeatureFlags.syncAddressesFeature isEnabled = syncEnginesStatus.containsKey(SyncEngine.Addresses) isChecked = syncEnginesStatus.getOrElse(SyncEngine.Addresses) { true } } } Updates the status of all [SyncEngine] states. +"private fun showPinDialogWarning(syncEngine: SyncEngine, newValue: Boolean) { context?.let { AlertDialog.Builder(it).apply { setTitle(getString(R.string.logins_warning_dialog_title)) setMessage( getString(R.string.logins_warning_dialog_message), ) setNegativeButton(getString(R.string.logins_warning_dialog_later)) { _: DialogInterface, _ -> updateSyncEngineState(syncEngine, newValue) } setPositiveButton(getString(R.string.logins_warning_dialog_set_up_now)) { it: DialogInterface, _ -> it.dismiss() val intent = Intent( Settings.ACTION_SECURITY_SETTINGS, ) startActivity(intent) } create() }.show().secure(activity) it.settings().incrementShowLoginsSecureWarningSyncCount() } }" Creates and shows a warning dialog that prompts the user to create a pin/password to secure their device when none is detected. The user has the option to continue with updating their sync preferences (updates the [SyncEngine] state) or navigating to device security settings to create a pin/password. +"private fun updateSyncEngineState(engine: SyncEngine, newValue: Boolean) { SyncEnginesStorage(requireContext()).setStatus(engine, newValue) viewLifecycleOwner.lifecycleScope.launch { requireContext().components.backgroundServices.accountManager.syncNow(SyncReason.EngineChange) } }" Updates the sync engine status with the new state of the preference and triggers a sync event. +"private fun updateSyncEngineStateWithPinWarning( syncEngine: SyncEngine, newValue: Boolean, ) { val manager = activity?.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager if (manager.isKeyguardSecure || !newValue || !requireContext().settings().shouldShowSecurityPinWarningSync ) { updateSyncEngineState(syncEngine, newValue) } else { showPinDialogWarning(syncEngine, newValue) } }" "Prompts the user if they do not have a password/pin set up to secure their device, and updates the state of the sync engine with the new checkbox value." +"private fun accountStateReducer( state: AccountSettingsFragmentState, action: AccountSettingsFragmentAction, ): AccountSettingsFragmentState { return when (action) { is AccountSettingsFragmentAction.SyncFailed -> state.copy(lastSyncedDate = LastSyncTime.Failed(action.time)) is AccountSettingsFragmentAction.SyncEnded -> state.copy(lastSyncedDate = LastSyncTime.Success(action.time)) is AccountSettingsFragmentAction.UpdateDeviceName -> state.copy(deviceName = action.name) } }" The SearchState Reducer. +sealed class AccountSettingsFragmentAction : Action { data class SyncFailed(val time: Long) : AccountSettingsFragmentAction() data class SyncEnded(val time: Long) : AccountSettingsFragmentAction() data class UpdateDeviceName(val name: String) : AccountSettingsFragmentAction() } Actions to dispatch through the `SearchStore` to modify `SearchState` through the reducer. +"data class AccountSettingsFragmentState( val lastSyncedDate: LastSyncTime = LastSyncTime.Never, val deviceName: String = """", ) : State" The state for the Account Settings Screen +fun onCancelButtonClicked() "Navigates back to the credit card preference settings. Called when a user taps on the  ""Cancel"" button." +fun onDeleteCardButtonClicked(guid: String) "Deletes the provided credit card in the credit card storage. Called when a user taps on the delete menu item or ""Delete card"" button." +fun onSaveCreditCard(creditCardFields: NewCreditCardFields) "Saves the provided credit card field into the credit card storage. Called when a user taps on the save menu item or ""Save"" button." +"fun onUpdateCreditCard(guid: String, creditCardFields: UpdatableCreditCardFields) }" "Updates the provided credit card with the new credit card fields. Called when a user taps on the save menu item or ""Save"" button when editing an existing credit card." +"class DefaultCreditCardEditorInteractor( private val controller: CreditCardEditorController, ) : CreditCardEditorInteractor { }" The default implementation of [CreditCardEditorInteractor]. +fun onSelectCreditCard(creditCard: CreditCard) Navigates to the credit card editor to edit the selected credit card. Called when a user taps on a credit card item. +fun onAddCreditCardClick() } Navigates to the credit card editor to add a new credit card. Called when a user taps on 'Add credit card' button. +"class DefaultCreditCardsManagementInteractor(private val controller: CreditCardsManagementController,) : CreditCardsManagementInteractor {override fun onSelectCreditCard(creditCard: CreditCard) { controller.handleCreditCardClicked(creditCard) CreditCards.managementCardTapped.record(NoExtras()) } override fun onAddCreditCardClick() { controller.handleAddCreditCardClicked() CreditCards.managementAddTapped.record(NoExtras()) } }" The default implementation of [CreditCardsManagementInteractor]. +"fun bind(state: CreditCardEditorState) { if (state.isEditing) { binding.deleteButton.apply { visibility = View.VISIBLE setOnClickListener { interactor.onDeleteCardButtonClicked(state.guid) } } } binding.cancelButton.setOnClickListener { interactor.onCancelButtonClicked() } binding.saveButton.setOnClickListener { saveCreditCard(state) } binding.cardNumberInput.text = state.cardNumber.toEditable() binding.nameOnCardInput.text = state.billingName.toEditable() binding.cardNumberLayout.setErrorTextColor( ColorStateList.valueOf( binding.root.context.getColorFromAttr(R.attr.textWarning), ), ) binding.nameOnCardLayout.setErrorTextColor( ColorStateList.valueOf( binding.root.context.getColorFromAttr(R.attr.textWarning), ), ) bindExpiryMonthDropDown(state.expiryMonth) bindExpiryYearDropDown(state.expiryYears) }" Binds the given [CreditCardEditorState] in the [CreditCardEditorFragment]. +"internal fun saveCreditCard(state: CreditCardEditorState) { binding.root.hideKeyboard() if (validateForm()) { val cardNumber = binding.cardNumberInput.text.toString().toCreditCardNumber() if (state.isEditing) { val fields = UpdatableCreditCardFields( billingName = binding.nameOnCardInput.text.toString(), cardNumber = CreditCardNumber.Plaintext(cardNumber), cardNumberLast4 = cardNumber.last4Digits(), expiryMonth = (binding.expiryMonthDropDown.selectedItemPosition + 1).toLong(), expiryYear = binding.expiryYearDropDown.selectedItem.toString().toLong(), cardType = cardNumber.creditCardIIN()?.creditCardIssuerNetwork?.name ?: """", ) interactor.onUpdateCreditCard(state.guid, fields) } else { val fields = NewCreditCardFields( billingName = binding.nameOnCardInput.text.toString(), plaintextCardNumber = CreditCardNumber.Plaintext(cardNumber), cardNumberLast4 = cardNumber.last4Digits(), expiryMonth = (binding.expiryMonthDropDown.selectedItemPosition + 1).toLong(), expiryYear = binding.expiryYearDropDown.selectedItem.toString().toLong(), cardType = cardNumber.creditCardIIN()?.creditCardIssuerNetwork?.name ?: """", ) interactor.onSaveCreditCard(fields) } } }" Saves a new credit card or updates an existing one with data from the user input. +@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal fun validateForm(): Boolean { var isValid = true if (binding.cardNumberInput.text.toString().validateCreditCardNumber()) { binding.cardNumberLayout.error = null binding.cardNumberTitle.setTextColor(binding.root.context.getColorFromAttr(R.attr.textPrimary)) } else { isValid = false binding.cardNumberLayout.error = binding.root.context.getString(R.string.credit_cards_number_validation_error_message) binding.cardNumberTitle.setTextColor(binding.root.context.getColorFromAttr(R.attr.textWarning)) } if (binding.nameOnCardInput.text.toString().isNotBlank()) { binding.nameOnCardLayout.error = null binding.nameOnCardTitle.setTextColor(binding.root.context.getColorFromAttr(R.attr.textPrimary)) } else { isValid = false binding.nameOnCardLayout.error = binding.root.context.getString(R.string.credit_cards_name_on_card_validation_error_message) binding.nameOnCardTitle.setTextColor(binding.root.context.getColorFromAttr(R.attr.textWarning)) } return isValid } Validates the credit card information entered by the user. +"private fun bindExpiryMonthDropDown(expiryMonth: Int) { val adapter = ArrayAdapter( binding.root.context, android.R.layout.simple_spinner_dropdown_item, ) val dateFormat = SimpleDateFormat(""MMMM (MM)"", Locale.getDefault()) val calendar = Calendar.getInstance() calendar.set(Calendar.DAY_OF_MONTH, 1) for (month in 0..NUMBER_OF_MONTHS) { calendar.set(Calendar.MONTH, month) adapter.add(dateFormat.format(calendar.time)) } binding.expiryMonthDropDown.adapter = adapter binding.expiryMonthDropDown.setSelection(expiryMonth - 1) }" "Setup the expiry month dropdown by formatting and populating it with the months in a calendar year, and set the selection to the provided expiry month." +"private fun bindExpiryYearDropDown(expiryYears: Pair) { val adapter = ArrayAdapter( binding.root.context, android.R.layout.simple_spinner_dropdown_item, ) val (startYear, endYear) = expiryYears for (year in startYear until endYear) { adapter.add(year.toString()) } binding.expiryYearDropDown.adapter = adapter }" Setup the expiry year dropdown with the range specified by the provided expiryYears +"private fun bindCreditCardExpiryDate( creditCard: CreditCard, binding: CreditCardListItemBinding, ) { val dateFormat = SimpleDateFormat(DATE_PATTERN, Locale.getDefault()) val calendar = Calendar.getInstance() calendar.set(Calendar.DAY_OF_MONTH, 1) // Subtract 1 from the expiry month since Calendar.Month is based on a 0-indexed. calendar.set(Calendar.MONTH, creditCard.expiryMonth.toInt() - 1) calendar.set(Calendar.YEAR, creditCard.expiryYear.toInt()) binding.expiryDate.text = dateFormat.format(calendar.time) }" Set the credit card expiry date formatted according to the locale. +"class CreditCardsAdapter( private val interactor: CreditCardsManagementInteractor, ) : ListAdapter(DiffCallback) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CreditCardItemViewHolder { val view = LayoutInflater.from(parent.context) .inflate(CreditCardItemViewHolder.LAYOUT_ID, parent, false) return CreditCardItemViewHolder(view, interactor) } override fun onBindViewHolder(holder: CreditCardItemViewHolder, position: Int) { holder.bind(getItem(position)) } internal object DiffCallback : DiffUtil.ItemCallback() { override fun areItemsTheSame(oldItem: CreditCard, newItem: CreditCard) = oldItem.guid == newItem.guid override fun areContentsTheSame(oldItem: CreditCard, newItem: CreditCard) = oldItem == newItem } }" Adapter for a list of credit cards to be displayed. +Updates the display of the credit cards based on the given [AutofillFragmentState]. fun update(state: AutofillFragmentState) { binding.progressBar.isVisible = state.isLoading binding.creditCardsList.isVisible = state.creditCards.isNotEmpty() creditCardsAdapter.submitList(state.creditCards) } +"suspend fun CreditCard.toCreditCardEditorState(storage: AutofillCreditCardsAddressesStorage): CreditCardEditorState { val crypto = storage.getCreditCardCrypto() val key = crypto.getOrGenerateKey() val cardNumber = crypto.decrypt(key, encryptedCardNumber)?.number ?: """" val startYear = expiryYear.toInt() val endYear = startYear + NUMBER_OF_YEARS_TO_SHOW return CreditCardEditorState( guid = guid, billingName = billingName, cardNumber = cardNumber, expiryMonth = expiryMonth.toInt(), expiryYears = Pair(startYear, endYear), isEditing = true, ) }" Returns a [CreditCardEditorState] from the given [CreditCard]. +"fun getInitialCreditCardEditorState(): CreditCardEditorState { val calendar = Calendar.getInstance() val startYear = calendar.get(Calendar.YEAR) val endYear = startYear + NUMBER_OF_YEARS_TO_SHOW return CreditCardEditorState( expiryYears = Pair(startYear, endYear), ) }" Returns the initial credit editor state if no credit card is provided. +"override fun onPause() { // Don't redirect if the user is navigating to the credit card editor fragment. redirectToReAuth( listOf(R.id.creditCardEditorFragment), findNavController().currentDestination?.id, R.id.creditCardsManagementFragment, ) super.onPause() }" "When the fragment is paused, navigate back to the settings page to reauthenticate." +private fun loadCreditCards() { lifecycleScope.launch(Dispatchers.IO) { val creditCards = requireContext().components.core.autofillStorage.getAllCreditCards() lifecycleScope.launch(Dispatchers.Main) { store.dispatch(AutofillAction.UpdateCreditCards(creditCards)) } } } Fetches all the credit cards from the autofill storage and updates the [AutofillFragmentStore] with the list of credit cards. +fun String.toCreditCardNumber(): String { return this.filter { it.isDigit() } } Strips characters other than digits from a string. Used to strip a credit card number user input of spaces and separators. +fun String.last4Digits(): String { return this.takeLast(LAST_VISIBLE_DIGITS_COUNT) } Returns the last 4 digits from a formatted credit card number string. +fun String.validateCreditCardNumber(): Boolean { val creditCardNumber = this.toCreditCardNumber() if (creditCardNumber != this || creditCardNumber.creditCardIIN() == null) { return false } return luhnAlgorithmValidation(creditCardNumber) } "Returns true if the provided string is a valid credit card by checking if it has a matching credit card issuer network passes the Luhn Algorithm, and false otherwise." +"@Suppress(""MagicNumber"") @VisibleForTesting internal fun luhnAlgorithmValidation(creditCardNumber: String): Boolean { var checksum = 0 val reversedCardNumber = creditCardNumber.reversed() for (index in reversedCardNumber.indices) { val digit = Character.getNumericValue(reversedCardNumber[index]) checksum += if (index % 2 == 0) digit else (digit * 2).let { (it / 10) + (it % 10) } } return (checksum % 10) == 0 }" Implementation of Luhn Algorithm validation (https://en.wikipedia.org/wiki/Luhn_algorithm) +"fun bind(item: History.Metadata, isPendingDeletion: Boolean) { binding.historyLayout.isVisible = !isPendingDeletion binding.historyLayout.titleView.text = item.title binding.historyLayout.urlView.text = item.url binding.historyLayout.setSelectionInteractor(item, selectionHolder, interactor) binding.historyLayout.changeSelected(item in selectionHolder.selectedItems) if (this.item?.url != item.url) { binding.historyLayout.loadFavicon(item.url) } if (selectionHolder.selectedItems.isEmpty()) { binding.historyLayout.overflowView.showAndEnable() } else { binding.historyLayout.overflowView.hideAndDisable() } this.item = item }" Displays the data of the given history record. +fun onShareMenuItem(items: Set) "Opens the share sheet for a set of history [items]. Called when a user clicks on the ""Share"" menu item." +fun onDeleteAllConfirmed() Called when a user has confirmed the deletion of the group. +fun onDeleteAll() "Called when a user clicks on the ""Delete history"" menu item." +fun onDelete(items: Set) "Deletes the given set of history metadata [items]. Called when a user clicks on the ""Delete"" menu item or the ""x"" button associated with a history metadata item." +fun onBackPressed(items: Set): Boolean Called on backpressed to deselect all the given [items]. +fun handleDeleteAllConfirmed() Deletes history metadata items in this group. +fun handleDeleteAll() Displays a [DeleteAllConfirmationDialogFragment] prompt. +fun handleDelete(items: Set) Deletes the given history metadata [items] from storage. +fun handleShare(items: Set) Opens the share sheet for a set of history [items]. +fun handleBackPressed(items: Set): Boolean Called on backpressed to deselect all the given [items]. +fun handleDeselect(item: History.Metadata) Toggles the given history [item] to be deselected in multi-select mode. +fun handleSelect(item: History.Metadata) Toggles the given history [item] to be selected in multi-select mode. +fun handleOpen(item: History.Metadata) Opens the given history [item] in a new tab. +"private fun nimbusBranchesFragmentStateReducer( state: NimbusBranchesState, action: NimbusBranchesAction, ): NimbusBranchesState { return when (action) { is NimbusBranchesAction.UpdateBranches -> { state.copy( branches = action.branches, selectedBranch = action.selectedBranch, isLoading = false, ) } is NimbusBranchesAction.UpdateSelectedBranch -> { state.copy(selectedBranch = action.selectedBranch) } is NimbusBranchesAction.UpdateUnselectBranch -> { state.copy(selectedBranch = """") } } }" Reduces the Nimbus branches state from the current state with the provided [action] to be performed. +private fun getCFRToShow(): Result { var result: Result = Result.None val count = recyclerView.adapter?.itemCount ?: return result for (index in count downTo 0) { val viewHolder = recyclerView.findViewHolderForAdapterPosition(index) if (context.settings().showSyncCFR && viewHolder is RecentSyncedTabViewHolder) { result = Result.SyncedTab(view = viewHolder.composeView) break } else if (context.settings().shouldShowJumpBackInCFR && viewHolder is RecentTabsHeaderViewHolder ) { result = Result.JumpBackIn(view = viewHolder.composeView) } } return result } Returns a [Result] that indicates the CFR that should be shown on the Home screen if any based on the views available and the preferences. +"@Composable fun NotificationPermissionDialogScreen( onDismiss: () -> Unit, grantNotificationPermission: () -> Unit, ) { NotificationPermissionContent( notificationPermissionPageState = NotificationPageState, onDismiss = { onDismiss() Onboarding.notifPppCloseClick.record(NoExtras()) }, onPrimaryButtonClick = { grantNotificationPermission() Onboarding.notifPppPositiveBtnClick.record(NoExtras()) }, onSecondaryButtonClick = { onDismiss() Onboarding.notifPppNegativeBtnClick.record(NoExtras()) }, ) }" A screen for displaying notification pre permission prompt. +"private data class NotificationPermissionPageState( @DrawableRes val image: Int, @StringRes val title: Int, @StringRes val description: Int, @StringRes val primaryButtonText: Int, @StringRes val secondaryButtonText: Int? = null, val onRecordImpressionEvent: () -> Unit, )" Model containing data for the [NotificationPermissionPage]. +fun onTextChanged(text: String) Called whenever the text inside the [ToolbarView] changes +fun onEditingCanceled() Called when a user removes focus from the [ToolbarView] +"fun onUrlCommitted(url: String, fromHomeScreen: Boolean = false)" Called when a user hits the return key while [ToolbarView] has focus. +fun onSearchEngineSuggestionSelected(searchEngine: SearchEngine) Called whenever search engine suggestion is tapped +fun onSearchShortcutsButtonClicked() Called whenever the Shortcuts button is clicked +fun onExistingSessionSelected(tabId: String) Called whenever an existing session is selected from the sessionSuggestionProvider +fun onClickSearchEngineSettings() "Called whenever the ""Search Engine Settings"" item is tapped" +fun onSearchShortcutEngineSelected(searchEngine: SearchEngine) Called whenever a search engine shortcut is tapped @param searchEngine the searchEngine that was selected +fun onSearchTermsTapped(searchTerms: String) Called whenever a search engine suggestion is tapped +"fun onUrlTapped(url: String, flags: LoadUrlFlags = LoadUrlFlags.none())" Called whenever a suggestion containing a URL is tapped +fun deselect(item: T) Called when a selected item is tapped in selection mode and should no longer be selected. +fun select(item: T) "Called when an item is long pressed and selection mode is started, or when selection mode has already started an an item is tapped." +fun open(item: T) Called when an item is tapped to open it. +fun onAutoplayChanged(value: AutoplayValue) Indicates the user changed the status of a an autoplay permission. +fun onPermissionToggled(permissionState: WebsitePermission) Indicates the user changed the status of a certain website permission. +fun onPermissionsShown() "Indicates there are website permissions allowed / blocked for the current website. which, status which is shown to the user." +fun handleClearSiteDataClicked(baseDomain: String) Clears site data for the current website. Called when a user clicks on the section to clear site data. +fun handleConnectionDetailsClicked() "Navigates to the connection details. Called when a user clicks on the ""Secured or Insecure Connection"" section." +fun handleTrackingProtectionDetailsClicked() Navigates to the tracking protection details panel. +fun handleCookieBannerHandlingDetailsClicked() Navigates to the cookie banners details panel. +fun handleAndroidPermissionGranted(feature: PhoneFeature) Handles a certain set of Android permissions being explicitly granted by the user. +fun handleAutoplayChanged(autoplayValue: AutoplayValue) Handles change a [WebsitePermission.Autoplay]. +fun handlePermissionToggled(permission: WebsitePermission) Handles toggling a [WebsitePermission]. +fun handlePermissionsShown() Handles the case of the [WebsitePermissionsView] needed to be displayed to the user. +"class ConnectionDetailsInteractor( private val controller: ConnectionDetailsController, ) : WebSiteInfoInteractor {  override fun onBackPressed() { controller.handleBackPressed() } }" "[ConnectionPanelDialogFragment] interactor. Implements callbacks for each of [ConnectionPanelDialogFragment]'s Views declared possible user interactions, delegates all such user events to the [ConnectionDetailsController]." +fun onTrackingProtectionDetailsClicked() "Navigates to the tracking protection preferences. Called when a user clicks on the ""Details"" button." +fun onCookieBannerHandlingDetailsClicked() Navigates to the tracking protection details panel. +fun onTrackingProtectionToggled(isEnabled: Boolean) Called whenever the tracking protection toggle for this site is toggled. +"class DefaultCookieBannerDetailsInteractor( private val controller: CookieBannerDetailsController, ) : CookieBannerDetailsInteractor { override fun onBackPressed() { controller.handleBackPressed() } override fun onTogglePressed(vale: Boolean) { controller.handleTogglePressed(vale) } }" "CookieBannerPanelDialogFragment] interactor. Implements callbacks for each of [CookieBannerPanelDialogFragment]'s Views declared possible user interactions, delegates all such user events to the [CookieBannerDetailsController]." +interface CookieBannerDetailsInteractor { Called whenever back is pressed. fun onBackPressed() = Unit Called whenever the user press the toggle widget. fun onTogglePressed(vale: Boolean) = Unit } Contract declaring all possible user interactions with [CookieBannerHandlingDetailsView]. +"data class CookieBannerDialogVariant( val title: String, val message: String, val positiveTextButton: String, ) }" Data class for cookie banner dialog variant +"fun tryToShowReEngagementDialog( settings: Settings, status: CookieBannerHandlingStatus, navController: NavController, ) { if (status == CookieBannerHandlingStatus.DETECTED && settings.shouldCookieBannerReEngagementDialog() ) { settings.lastInteractionWithReEngageCookieBannerDialogInMs = System.currentTimeMillis() settings.cookieBannerDetectedPreviously = true val directions = BrowserFragmentDirections.actionBrowserFragmentToCookieBannerDialogFragment() navController.nav(R.id.browserFragment, directions) } }" "Tries to show the re-engagement cookie banner dialog, when the right conditions are met, o otherwise the dialog won't show." +"fun PhoneFeature.isUserPermissionGranted( sitePermissions: SitePermissions?, settings: Settings, ) = getStatus(sitePermissions, settings) == SitePermissions.Status.ALLOWED" Common [PhoneFeature] extensions used for **quicksettings**. Whether the website permission associated with this [PhoneFeature] was specifically allowed by the user.  To check whether the needed Android permission is also allowed [PhoneFeature#isAndroidPermissionGranted()] can be used. +"fun PhoneFeature.shouldBeEnabled( context: Context, sitePermissions: SitePermissions?, settings: Settings, ) = isAndroidPermissionGranted(context) && isUserPermissionGranted(sitePermissions, settings)" Common [PhoneFeature] extensions used for **quicksettings**. Whether the website permission associated with this [PhoneFeature] should allow user interaction. +"fun PhoneFeature.shouldBeVisible( sitePermissions: SitePermissions?, settings: Settings, ): Boolean { // We have to check if the site have a site permission exception, // if it doesn't the feature shouldn't be visible return if (sitePermissions == null) { false } else { getStatus(sitePermissions, settings) != SitePermissions.Status.NO_DECISION } }" Common [PhoneFeature] extensions used for **quicksettings**. Whether the website permission associated with this [PhoneFeature] should be shown to the user. +fun onPermissionsShown() "Indicates there are website permissions allowed / blocked for the current website. which, status which is shown to the user." +fun handleClearSiteDataClicked(baseDomain: String) Clears site data for the current website. Called when a user clicks on the section to clear site data. +fun handleConnectionDetailsClicked() "Navigates to the connection details. Called when a user clicks on the ""Secured or Insecure Connection"" section." +fun handleTrackingProtectionDetailsClicked() Navigates to the tracking protection details panel. +fun handleCookieBannerHandlingDetailsClicked() Navigates to the cookie banners details panel. +fun handleAndroidPermissionGranted(feature: PhoneFeature) Handles a certain set of Android permissions being explicitly granted by the user. +fun handleAutoplayChanged(autoplayValue: AutoplayValue) Handles change a [WebsitePermission.Autoplay]. +fun handlePermissionToggled(permission: WebsitePermission) Handles toggling a [WebsitePermission]. +fun handlePermissionsShown() Handles the case of the [WebsitePermissionsView] needed to be displayed to the user. +"class ConnectionDetailsInteractor( private val controller: ConnectionDetailsController, ) : WebSiteInfoInteractor {  override fun onBackPressed() { controller.handleBackPressed() } }" "[ConnectionPanelDialogFragment] interactor. Implements callbacks for each of [ConnectionPanelDialogFragment]'s Views declared possible user interactions, delegates all such user events to the [ConnectionDetailsController]." +fun onTrackingProtectionDetailsClicked() "Navigates to the tracking protection preferences. Called when a user clicks on the ""Details"" button." +fun onCookieBannerHandlingDetailsClicked() Navigates to the tracking protection details panel. +fun onTrackingProtectionToggled(isEnabled: Boolean) Called whenever the tracking protection toggle for this site is toggled. +"class DefaultCookieBannerDetailsInteractor( private val controller: CookieBannerDetailsController, ) : CookieBannerDetailsInteractor { override fun onBackPressed() { controller.handleBackPressed() } override fun onTogglePressed(vale: Boolean) { controller.handleTogglePressed(vale) } }" "CookieBannerPanelDialogFragment] interactor. Implements callbacks for each of [CookieBannerPanelDialogFragment]'s Views declared possible user interactions, delegates all such user events to the [CookieBannerDetailsController]." +interface CookieBannerDetailsInteractor { Called whenever back is pressed. fun onBackPressed() = Unit Called whenever the user press the toggle widget. fun onTogglePressed(vale: Boolean) = Unit } Contract declaring all possible user interactions with [CookieBannerHandlingDetailsView]. +"data class CookieBannerDialogVariant( val title: String, val message: String, val positiveTextButton: String, ) }" Data class for cookie banner dialog variant +"fun tryToShowReEngagementDialog( settings: Settings, status: CookieBannerHandlingStatus, navController: NavController, ) { if (status == CookieBannerHandlingStatus.DETECTED && settings.shouldCookieBannerReEngagementDialog() ) { settings.lastInteractionWithReEngageCookieBannerDialogInMs = System.currentTimeMillis() settings.cookieBannerDetectedPreviously = true val directions = BrowserFragmentDirections.actionBrowserFragmentToCookieBannerDialogFragment() navController.nav(R.id.browserFragment, directions) } }" "Tries to show the re-engagement cookie banner dialog, when the right conditions are met, o otherwise the dialog won't show." +"fun PhoneFeature.isUserPermissionGranted( sitePermissions: SitePermissions?, settings: Settings, ) = getStatus(sitePermissions, settings) == SitePermissions.Status.ALLOWED" Common [PhoneFeature] extensions used for **quicksettings**. Whether the website permission associated with this [PhoneFeature] was specifically allowed by the user.  To check whether the needed Android permission is also allowed [PhoneFeature#isAndroidPermissionGranted()] can be used. +"fun PhoneFeature.shouldBeEnabled( context: Context, sitePermissions: SitePermissions?, settings: Settings, ) = isAndroidPermissionGranted(context) && isUserPermissionGranted(sitePermissions, settings)" Common [PhoneFeature] extensions used for **quicksettings**. Whether the website permission associated with this [PhoneFeature] should allow user interaction. +"fun PhoneFeature.shouldBeVisible( sitePermissions: SitePermissions?, settings: Settings, ): Boolean { // We have to check if the site have a site permission exception, // if it doesn't the feature shouldn't be visible return if (sitePermissions == null) { false } else { getStatus(sitePermissions, settings) != SitePermissions.Status.NO_DECISION } }" Common [PhoneFeature] extensions used for **quicksettings**. Whether the website permission associated with this [PhoneFeature] should be shown to the user. +"private fun filterItems( searchedForText: String?, sortingStrategy: SortingStrategy, state: LoginsListState, ): LoginsListState { return if (searchedForText.isNullOrBlank()) { state.copy( isLoading = false, sortingStrategy = sortingStrategy, highlightedItem = sortingStrategyToMenuItem(sortingStrategy), searchedForText = searchedForText, filteredItems = sortingStrategy(state.loginList), ) } else { state.copy( isLoading = false, sortingStrategy = sortingStrategy, highlightedItem = sortingStrategyToMenuItem(sortingStrategy), searchedForText = searchedForText, filteredItems = sortingStrategy(state.loginList).filter { it.origin.contains( searchedForText, ) }, ) } }"  [LoginsListState] containing a new [LoginsListState.filteredItems] with filtered [LoginsListState.items] +"private fun savedLoginsStateReducer( state: LoginsListState, action: LoginsAction, ): LoginsListState { return when (action) { is LoginsAction.LoginsListUpToDate -> { state.copy(isLoading = false) } is LoginsAction.UpdateLoginsList -> { state.copy( isLoading = false, loginList = action.list, filteredItems = state.sortingStrategy(action.list), ) } is LoginsAction.FilterLogins -> { filterItems( action.newText, state.sortingStrategy, state, ) } is LoginsAction.UpdateCurrentLogin -> { state.copy( currentItem = action.item, ) } is LoginsAction.SortLogins -> { filterItems( state.searchedForText, action.sortingStrategy, state, ) } is LoginsAction.LoginSelected -> { state.copy( isLoading = true, ) } is LoginsAction.DuplicateLogin -> { state.copy( duplicateLogin = action.dupe, ) } } }" "Handles changes in the saved logins list, including updates and filtering." +"data class LoginsListState( val isLoading: Boolean = false, val loginList: List, val filteredItems: List, val currentItem: SavedLogin? = null, val searchedForText: String?, val sortingStrategy: SortingStrategy, val highlightedItem: SavedLoginsSortingStrategyMenu.Item, val duplicateLogin: SavedLogin? = null, ) : State fun createInitialLoginsListState(settings: Settings) = LoginsListState( isLoading = true, loginList = emptyList(), filteredItems = emptyList(), searchedForText = null, sortingStrategy = settings.savedLoginsSortingStrategy, highlightedItem = settings.savedLoginsMenuHighlightedItem, )" View that contains and configures the Login Details +"class SavedLoginsInteractor( private val loginsListController: LoginsListController, private val savedLoginsStorageController: SavedLoginsStorageController, ) { fun onItemClicked(item: SavedLogin) { loginsListController.handleItemClicked(item) } fun onLearnMoreClicked() { loginsListController.handleLearnMoreClicked() } fun onSortingStrategyChanged(sortingStrategy: SortingStrategy) { loginsListController.handleSort(sortingStrategy) } fun loadAndMapLogins() { savedLoginsStorageController.handleLoadAndMapLogins() } fun onAddLoginClick() { loginsListController.handleAddLoginClicked() } }" Interactor for the saved logins screen +"class LoginDetailInteractor( private val savedLoginsController: SavedLoginsStorageController, ) { fun onFetchLoginList(loginId: String) { savedLoginsController.fetchLoginDetails(loginId) } fun onDeleteLogin(loginId: String) { savedLoginsController.delete(loginId) } }" Interactor for the login detail screen +"class EditLoginInteractor( private val savedLoginsController: SavedLoginsStorageController, ) { fun findDuplicate(loginId: String, usernameText: String, passwordText: String) { savedLoginsController.findDuplicateForSave(loginId, usernameText, passwordText) } fun onSaveLogin(loginId: String, usernameText: String, passwordText: String) { savedLoginsController.save(loginId, usernameText, passwordText) } }" Interactor for the edit login screen +"class AddLoginInteractor( private val savedLoginsController: SavedLoginsStorageController, ) { fun findDuplicate(originText: String, usernameText: String, passwordText: String) { savedLoginsController.findDuplicateForAdd(originText, usernameText, passwordText) } fun onAddLogin(originText: String, usernameText: String, passwordText: String) { savedLoginsController.add(originText, usernameText, passwordText) } }" Interactor for the add login screen +"@Composable private fun PlaceHolderTabIcon(modifier: Modifier) { Box( modifier = modifier.background( color = when (isSystemInDarkTheme()) { true -> PhotonColors.DarkGrey60 false -> PhotonColors.LightGrey30 }, ), ) }" A placeholder for the recent tab icon. +"@Composable private fun RecentTabIcon( url: String, modifier: Modifier = Modifier, contentScale: ContentScale = ContentScale.Fit, alignment: Alignment = Alignment.Center, icon: Bitmap? = null, ) { when { icon != null -> { Image( painter = BitmapPainter(icon.asImageBitmap()), contentDescription = null, modifier = modifier, contentScale = contentScale, alignment = alignment, ) } !inComposePreview -> { components.core.icons.Loader(url) { Placeholder { PlaceHolderTabIcon(modifier) } WithIcon { icon -> Image( painter = icon.painter, contentDescription = null, modifier = modifier, contentScale = contentScale, ) } } } else -> { PlaceHolderTabIcon(modifier) } } }" A recent tab icon. +"@OptIn(ExperimentalComposeUiApi::class) @Composable private fun RecentTabMenu( showMenu: Boolean, menuItems: List, tab: RecentTab.Tab, onDismissRequest: () -> Unit, ) { DisposableEffect(LocalConfiguration.current.orientation) { onDispose { onDismissRequest() } } DropdownMenu( expanded = showMenu, onDismissRequest = { onDismissRequest() }, modifier = Modifier .background(color = FirefoxTheme.colors.layer2) .semantics { testTagsAsResourceId = true testTag = ""recent.tab.menu"" }, ) { for (item in menuItems) { DropdownMenuItem( onClick = { onDismissRequest() item.onClick(tab) }, ) { Text( text = item.title, color = FirefoxTheme.colors.textPrimary, maxLines = 1, modifier = Modifier .fillMaxHeight() .align(Alignment.CenterVertically), ) } } } }" Menu shown for a [RecentTab.Tab]. +"@Composable fun RecentTabImage( tab: RecentTab.Tab, modifier: Modifier = Modifier, contentScale: ContentScale = ContentScale.FillWidth, ) { val previewImageUrl = tab.state.content.previewImageUrl when { !previewImageUrl.isNullOrEmpty() -> { Image( url = previewImageUrl, modifier = modifier, targetSize = 108.dp, contentScale = ContentScale.Crop, ) } else -> ThumbnailCard( url = tab.state.content.url, key = tab.state.id, modifier = modifier, contentScale = contentScale, ) } }" A recent tab image. +"@OptIn( ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class, ) @Composable @Suppress(""LongMethod"") private fun RecentTabItem( tab: RecentTab.Tab, menuItems: List, backgroundColor: Color, onRecentTabClick: (String) -> Unit = {}, ) { var isMenuExpanded by remember { mutableStateOf(false) } Card( modifier = Modifier .fillMaxWidth() .height(112.dp) .combinedClickable( enabled = true, onClick = { onRecentTabClick(tab.state.id) }, onLongClick = { isMenuExpanded = true }, ), shape = RoundedCornerShape(8.dp), backgroundColor = backgroundColor, elevation = 6.dp, ) { Row( modifier = Modifier.padding(16.dp), ) { RecentTabImage( tab = tab, modifier = Modifier .size(108.dp, 80.dp) .clip(RoundedCornerShape(8.dp)), contentScale = ContentScale.Crop, ) Spacer(modifier = Modifier.width(16.dp)) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.SpaceBetween, ) { Text( text = tab.state.content.title.ifEmpty { tab.state.content.url.trimmed() }, modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""recent.tab.title"" }, color = FirefoxTheme.colors.textPrimary, fontSize = 14.sp, maxLines = 2, overflow = TextOverflow.Ellipsis, ) Row { RecentTabIcon( url = tab.state.content.url, modifier = Modifier .size(18.dp) .clip(RoundedCornerShape(2.dp)), contentScale = ContentScale.Crop, icon = tab.state.content.icon, ) Spacer(modifier = Modifier.width(8.dp)) Text( text = tab.state.content.url.trimmed(), modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""recent.tab.url"" }, color = FirefoxTheme.colors.textSecondary, fontSize = 12.sp, overflow = TextOverflow.Ellipsis, maxLines = 1, ) } } RecentTabMenu( showMenu = isMenuExpanded, menuItems = menuItems, tab = tab, onDismissRequest = { isMenuExpanded = false }, ) } } }" A recent tab item. +"fun TextView.setOnboardingIcon(@DrawableRes id: Int) { val icon = context.getDrawableWithTint(id, context.getColorFromAttr(R.attr.iconActive))?.apply { val size = context.resources.getDimensionPixelSize(R.dimen.onboarding_header_icon_height_width) setBounds(size) } putCompoundDrawablesRelative(start = icon) }" Sets the drawableStart of a header in an onboarding card. +"@VisibleForTesting internal fun restoreSelectedCategories( coroutineScope: CoroutineScope, currentCategories: List, store: Store, selectedPocketCategoriesDataStore: DataStore, ) { coroutineScope.launch { store.dispatch( AppAction.PocketStoriesCategoriesSelectionsChange( currentCategories, selectedPocketCategoriesDataStore.data.first() .valuesList.map { PocketRecommendedStoriesSelectedCategory( name = it.name, selectionTimestamp = it.selectionTimestamp, ) }, ), ) } }" Combines [currentCategories] with the locally persisted data about previously selected categories and emits a new [AppAction.PocketStoriesCategoriesSelectionsChange] to update these in store. +"@VisibleForTesting internal fun persistSelectedCategories( coroutineScope: CoroutineScope, currentCategoriesSelections: List, selectedPocketCategoriesDataStore: DataStore, ) { val selectedCategories = currentCategoriesSelections .map { SelectedPocketStoriesCategory.newBuilder().apply { name = it.name selectionTimestamp = it.selectionTimestamp }.build() } // Irrespective of the current selections or their number overwrite everything we had. coroutineScope.launch { selectedPocketCategoriesDataStore.updateData { data -> data.newBuilderForType().addAllValues(selectedCategories).build() } } }" Persist [currentCategoriesSelections] for making this details available in between app restarts. +"private fun bookmarkSearchStateReducer( state: BookmarkSearchFragmentState, action: BookmarkSearchFragmentAction, ): BookmarkSearchFragmentState { return when (action) { is BookmarkSearchFragmentAction.UpdateQuery -> state.copy(query = action.query) } }" The [BookmarkSearchFragmentState] Reducer. +"suspend fun updateMenu(itemType: BookmarkNodeType, itemId: String) { menuController.submitList(menuItems(itemType, itemId)) }" Update the menu items for the type of bookmark. +private fun differentFromSelectedFolder(arguments: Bundle?): Boolean { return arguments != null && BookmarkFragmentArgs.fromBundle(arguments).currentRoot != viewModel.selectedFolder?.guid } Returns true if the currentRoot listed in the [arguments] is different from the current selected folder. +"override fun onDestinationChanged(controller: NavController, destination: NavDestination, arguments: Bundle?) { if (destination.id != R.id.bookmarkFragment || differentFromSelectedFolder(arguments)) { // TODO this is currently called when opening the bookmark menu. Fix this if possible bookmarkInteractor.onAllBookmarksDeselected() } }" Deselects all items when the user navigates to a different fragment or a different folder. +"private fun downloadStateReducer( state: DownloadFragmentState, action: DownloadFragmentAction, ): DownloadFragmentState { return when (action) { is DownloadFragmentAction.AddItemForRemoval -> state.copy(mode = DownloadFragmentState.Mode.Editing(state.mode.selectedItems + action.item)) is DownloadFragmentAction.RemoveItemForRemoval -> { val selected = state.mode.selectedItems - action.item state.copy( mode = if (selected.isEmpty()) { DownloadFragmentState.Mode.Normal } else { DownloadFragmentState.Mode.Editing(selected) }, ) } is DownloadFragmentAction.ExitEditMode -> state.copy(mode = DownloadFragmentState.Mode.Normal) is DownloadFragmentAction.EnterDeletionMode -> state.copy(isDeletingItems = true) is DownloadFragmentAction.ExitDeletionMode -> state.copy(isDeletingItems = false) is DownloadFragmentAction.AddPendingDeletionSet -> state.copy( pendingDeletionIds = state.pendingDeletionIds + action.itemIds, ) is DownloadFragmentAction.UndoPendingDeletionSet -> state.copy( pendingDeletionIds = state.pendingDeletionIds - action.itemIds, ) } }" The DownloadState Reducer. +"private fun deleteDownloadItems(items: Set) { updatePendingDownloadToDelete(items) MainScope().allowUndo( requireActivity().getRootView()!!, getMultiSelectSnackBarMessage(items), getString(R.string.bookmark_undo_deletion), onCancel = { undoPendingDeletion(items) }, operation = getDeleteDownloadItemsOperation(items), ) }" "Schedules [items] for deletion. Note: When tapping on a download item's ""trash"" button (itemView.overflow_menu) this [items].size() will be 1." +"fun History.toPendingDeletionHistory(): PendingDeletionHistory { return when (this) { is History.Regular -> PendingDeletionHistory.Item(visitedAt = visitedAt, url = url) is History.Group -> PendingDeletionHistory.Group( visitedAt = visitedAt, historyMetadata = items.map { historyMetadata -> PendingDeletionHistory.MetaData( historyMetadata.visitedAt, historyMetadata.historyMetadataKey, ) }, ) is History.Metadata -> PendingDeletionHistory.MetaData(visitedAt, historyMetadataKey) } }" Maps an instance of [History] to an instance of [PendingDeletionHistory]. +fun changeSelected(isSelected: Boolean) { binding.icon.displayedChild = if (isSelected) 1 else 0 } Changes the icon to show a check mark if [isSelected] +fun displayAs(mode: ItemType) { urlView.isVisible = mode == ItemType.SITE } Change visibility of parts of this view based on what type of item is being represented. +"private fun recentlyClosedStateReducer( state: RecentlyClosedFragmentState, action: RecentlyClosedFragmentAction, ): RecentlyClosedFragmentState { return when (action) { is RecentlyClosedFragmentAction.Change -> state.copy(items = action.list) is RecentlyClosedFragmentAction.Select -> { state.copy(selectedTabs = state.selectedTabs + action.tab) } is RecentlyClosedFragmentAction.Deselect -> { state.copy(selectedTabs = state.selectedTabs - action.tab) } RecentlyClosedFragmentAction.DeselectAll -> state.copy(selectedTabs = emptySet()) } }" +"private fun historyStateReducer( state: HistoryMetadataGroupFragmentState, action: HistoryMetadataGroupFragmentAction, ): HistoryMetadataGroupFragmentState { return when (action) { is HistoryMetadataGroupFragmentAction.UpdateHistoryItems -> state.copy(items = action.items) is HistoryMetadataGroupFragmentAction.Select -> state.copy( items = state.items.toMutableList() .map { if (it == action.item) { it.copy(selected = true) } else { it } }, ) is HistoryMetadataGroupFragmentAction.Deselect -> state.copy( items = state.items.toMutableList() .map { if (it == action.item) { it.copy(selected = false) } else { it } }, ) is HistoryMetadataGroupFragmentAction.DeselectAll -> state.copy( items = state.items.toMutableList() .map { it.copy(selected = false) }, ) is HistoryMetadataGroupFragmentAction.Delete -> { val items = state.items.toMutableList() items.remove(action.item) state.copy(items = items) } is HistoryMetadataGroupFragmentAction.DeleteAll -> state.copy(items = emptyList()) is HistoryMetadataGroupFragmentAction.UpdatePendingDeletionItems -> state.copy(pendingDeletionItems = action.pendingDeletionItems) is HistoryMetadataGroupFragmentAction.ChangeEmptyState -> state.copy( isEmpty = action.isEmpty, ) }" The RecentlyClosedFragmentState Reducer. +"private fun historyStateReducer( state: HistoryMetadataGroupFragmentState, action: HistoryMetadataGroupFragmentAction, ): HistoryMetadataGroupFragmentState { return when (action) { is HistoryMetadataGroupFragmentAction.UpdateHistoryItems -> state.copy(items = action.items) is HistoryMetadataGroupFragmentAction.Select -> state.copy( items = state.items.toMutableList() .map { if (it == action.item) { it.copy(selected = true) } else { it } }, ) is HistoryMetadataGroupFragmentAction.Deselect -> state.copy( items = state.items.toMutableList() .map { if (it == action.item) { it.copy(selected = false) } else { it } }, ) is HistoryMetadataGroupFragmentAction.DeselectAll -> state.copy( items = state.items.toMutableList() .map { it.copy(selected = false) }, ) is HistoryMetadataGroupFragmentAction.Delete -> { val items = state.items.toMutableList() items.remove(action.item) state.copy(items = items) } is HistoryMetadataGroupFragmentAction.DeleteAll -> state.copy(items = emptyList()) is HistoryMetadataGroupFragmentAction.UpdatePendingDeletionItems -> state.copy(pendingDeletionItems = action.pendingDeletionItems) is HistoryMetadataGroupFragmentAction.ChangeEmptyState -> state.copy( isEmpty = action.isEmpty, ) }" Reduces the history metadata state from the current state with the provided [action] to be performed. +"override fun handleHistoryShowAllClicked() { navController.navigate( HomeFragmentDirections.actionGlobalHistoryFragment(), ) }" Shows the history fragment. +"override fun handleRecentHistoryGroupClicked(recentHistoryGroup: RecentHistoryGroup) { navController.navigate( HomeFragmentDirections.actionGlobalHistoryMetadataGroup( title = recentHistoryGroup.title, historyMetadataItems = recentHistoryGroup.historyMetadata .mapIndexed { index, item -> item.toHistoryMetadata(index) }.toTypedArray(), ), ) }" Navigates to the history metadata group fragment to display the group. +"override fun handleRemoveRecentHistoryGroup(groupTitle: String) { // We want to update the UI right away in response to user action without waiting for the IO. // First, dispatch actions that will clean up search groups in the two stores that have // metadata-related state. store.dispatch(HistoryMetadataAction.DisbandSearchGroupAction(searchTerm = groupTitle)) appStore.dispatch(AppAction.DisbandSearchGroupAction(searchTerm = groupTitle)) // Then, perform the expensive IO work of removing search groups from storage. scope.launch { storage.deleteHistoryMetadata(groupTitle) } RecentSearches.groupDeleted.record(NoExtras()) }" Removes a [RecentHistoryGroup] with the given title from the homescreen. +override fun handleRecentHistoryHighlightClicked(recentHistoryHighlight: RecentHistoryHighlight) { selectOrAddTabUseCase.invoke(recentHistoryHighlight.url) navController.navigate(R.id.browserFragment) } Switch to an already open tab for [recentHistoryHighlight] if one exists or create a new tab in which to load this item's URL. +override fun handleRemoveRecentHistoryHighlight(highlightUrl: String) { appStore.dispatch(AppAction.RemoveRecentHistoryHighlight(highlightUrl)) scope.launch { storage.deleteHistoryMetadataForUrl(highlightUrl) } } Removes a [RecentHistoryHighlight] with the given title from the homescreen. +"@OptIn(ExperimentalComposeUiApi::class) @Composable fun RecentlyVisited( recentVisits: List, menuItems: List, backgroundColor: Color = FirefoxTheme.colors.layer2, onRecentVisitClick: (RecentlyVisitedItem, Int) -> Unit = { _, _ -> }, ) { Card( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(8.dp), backgroundColor = backgroundColor, elevation = 6.dp, ) { val listState = rememberLazyListState() val flingBehavior = EagerFlingBehavior(lazyRowState = listState) LazyRow( modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""recent.visits"" }, state = listState, contentPadding = PaddingValues(16.dp), horizontalArrangement = Arrangement.spacedBy(32.dp), flingBehavior = flingBehavior, ) { val itemsList = recentVisits.chunked(VISITS_PER_COLUMN) itemsIndexed(itemsList) { pageIndex, items -> Column( modifier = Modifier.fillMaxWidth(), ) { items.forEachIndexed { index, recentVisit -> when (recentVisit) { is RecentHistoryHighlight -> RecentlyVisitedHistoryHighlight( recentVisit = recentVisit, menuItems = menuItems, clickableEnabled = listState.atLeastHalfVisibleItems.contains(pageIndex), showDividerLine = index < items.size - 1, onRecentVisitClick = { onRecentVisitClick(it, pageIndex + 1) }, ) is RecentHistoryGroup -> RecentlyVisitedHistoryGroup( recentVisit = recentVisit, menuItems = menuItems, clickableEnabled = listState.atLeastHalfVisibleItems.contains(pageIndex), showDividerLine = index < items.size - 1, onRecentVisitClick = { onRecentVisitClick(it, pageIndex + 1) }, ) } } } } } } }" A list of recently visited items. +"@OptIn( ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class, ) @Composable private fun RecentlyVisitedHistoryGroup( recentVisit: RecentHistoryGroup, menuItems: List, clickableEnabled: Boolean, showDividerLine: Boolean, onRecentVisitClick: (RecentHistoryGroup) -> Unit = { _ -> }, ) { var isMenuExpanded by remember { mutableStateOf(false) } Row( modifier = Modifier .combinedClickable( enabled = clickableEnabled, onClick = { onRecentVisitClick(recentVisit) }, onLongClick = { isMenuExpanded = true }, ) .size(268.dp, 56.dp) .semantics { testTagsAsResourceId = true testTag = ""recent.visits.group"" }, verticalAlignment = Alignment.CenterVertically, ) { Image( painter = painterResource(R.drawable.ic_multiple_tabs), contentDescription = null, modifier = Modifier.size(24.dp), ) Spacer(modifier = Modifier.width(16.dp)) Column( modifier = Modifier.fillMaxSize(), ) { RecentlyVisitedTitle( text = recentVisit.title, modifier = Modifier .padding(top = 7.dp, bottom = 2.dp) .weight(1f) .semantics { testTagsAsResourceId = true testTag = ""recent.visits.group.title"" }, ) RecentlyVisitedCaption( count = recentVisit.historyMetadata.size, modifier = Modifier .weight(1f) .semantics { testTagsAsResourceId = true testTag = ""recent.visits.group.caption"" }, ) if (showDividerLine) { Divider() } } RecentlyVisitedMenu( showMenu = isMenuExpanded, menuItems = menuItems, recentVisit = recentVisit, onDismissRequest = { isMenuExpanded = false }, ) } }" A recently visited history group. +"@OptIn( ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class, ) @Composable private fun RecentlyVisitedHistoryHighlight( recentVisit: RecentHistoryHighlight, menuItems: List, clickableEnabled: Boolean, showDividerLine: Boolean, onRecentVisitClick: (RecentHistoryHighlight) -> Unit = { _ -> }, ) { var isMenuExpanded by remember { mutableStateOf(false) } Row( modifier = Modifier .combinedClickable( enabled = clickableEnabled, onClick = { onRecentVisitClick(recentVisit) }, onLongClick = { isMenuExpanded = true }, ) .size(268.dp, 56.dp) .semantics { testTagsAsResourceId = true testTag = ""recent.visits.highlight"" }, verticalAlignment = Alignment.CenterVertically, ) { Favicon(url = recentVisit.url, size = 24.dp) Spacer(modifier = Modifier.width(16.dp)) Box(modifier = Modifier.fillMaxSize()) { RecentlyVisitedTitle( text = recentVisit.title.trimmed(), modifier = Modifier .align(Alignment.CenterStart) .semantics { testTagsAsResourceId = true testTag = ""recent.visits.highlight.title"" }, ) if (showDividerLine) { Divider(modifier = Modifier.align(Alignment.BottomCenter)) } } RecentlyVisitedMenu( showMenu = isMenuExpanded, menuItems = menuItems, recentVisit = recentVisit, onDismissRequest = { isMenuExpanded = false }, ) } }" A recently visited history item. +"@Composable private fun RecentlyVisitedTitle( text: String, modifier: Modifier = Modifier, ) { Text( text = text, modifier = modifier, color = FirefoxTheme.colors.textPrimary, fontSize = 16.sp, overflow = TextOverflow.Ellipsis, maxLines = 1, ) }" The title of a recent visit. +"@Composable private fun RecentlyVisitedCaption( count: Int, modifier: Modifier, ) { val stringId = if (count == 1) { R.string.history_search_group_site } else { R.string.history_search_group_sites } Text( text = String.format(LocalContext.current.getString(stringId), count), modifier = modifier, color = when (isSystemInDarkTheme()) { true -> FirefoxTheme.colors.textPrimary false -> FirefoxTheme.colors.textSecondary }, fontSize = 12.sp, overflow = TextOverflow.Ellipsis, maxLines = 1, ) }" The caption text for a recent visit. +"@OptIn(ExperimentalComposeUiApi::class) @Composable private fun RecentlyVisitedMenu( showMenu: Boolean, menuItems: List, recentVisit: RecentlyVisitedItem, onDismissRequest: () -> Unit, ) { DisposableEffect(LocalConfiguration.current.orientation) { onDispose { onDismissRequest() } } DropdownMenu( expanded = showMenu, onDismissRequest = { onDismissRequest() }, modifier = Modifier .background(color = FirefoxTheme.colors.layer2) .semantics { testTagsAsResourceId = true testTag = ""recent.visit.menu"" }, ) { for (item in menuItems) { DropdownMenuItem( onClick = { onDismissRequest() item.onClick(recentVisit) }, ) { Text( text = item.title, color = FirefoxTheme.colors.textPrimary, maxLines = 1, modifier = Modifier .fillMaxHeight() .align(Alignment.CenterVertically), ) } } } }" Menu shown for a [RecentlyVisitedItem]. +"private val LazyListState.atLeastHalfVisibleItems get() = layoutInfo .visibleItemsInfo .filter { val startEdge = maxOf(0, layoutInfo.viewportStartOffset - it.offset) val endEdge = maxOf(0, it.offset + it.size - layoutInfo.viewportEndOffset) return@filter startEdge + endEdge < it.size / 2 }.map { it.index }" Get the indexes in list of all items which have more than half showing. +"@VisibleForTesting internal fun getCombinedHistory( historyHighlights: List, historyGroups: List, ): List { // Cleanup highlights now to avoid counting them below and then removing the ones found in groups. val distinctHighlights = historyHighlights .removeHighlightsAlreadyInGroups(historyGroups) val totalItemsCount = distinctHighlights.size + historyGroups.size return if (totalItemsCount <= MAX_RESULTS_TOTAL) { getSortedHistory( distinctHighlights.sortedByDescending { it.lastAccessedTime }, historyGroups.sortedByDescending { it.lastAccessedTime }, ) } else { var groupsCount = 0 var highlightCount = 0 while ((highlightCount + groupsCount) < MAX_RESULTS_TOTAL) { if ((highlightCount + groupsCount) < MAX_RESULTS_TOTAL && distinctHighlights.getOrNull(highlightCount) != null ) { highlightCount += 1 } if ((highlightCount + groupsCount) < MAX_RESULTS_TOTAL && historyGroups.getOrNull(groupsCount) != null ) { groupsCount += 1 } } getSortedHistory( distinctHighlights .sortedByDescending { it.lastAccessedTime } .take(highlightCount), historyGroups .sortedByDescending { it.lastAccessedTime } .take(groupsCount), ) } }" Get up to [MAX_RESULTS_TOTAL] items if available as an even split of history highlights and history groups. If more items then needed are available then highlights will be more by one. +"@VisibleForTesting internal fun getHistoryHighlights( highlights: List, metadata: List, ): List { val highlightsUrls = highlights.map { it.url } val highlightsLastUpdatedTime = metadata .filter { highlightsUrls.contains(it.key.url) } .groupBy { it.key.url } .map { (url, data) -> url to data.maxByOrNull { it.updatedAt }!! } return highlights.map { HistoryHighlightInternal( historyHighlight = it, lastAccessedTime = highlightsLastUpdatedTime .firstOrNull { (url, _) -> url == it.url }?.second?.updatedAt ?: 0, ) } }" Perform an in-memory mapping of a history highlight to metadata records to compute its last access time. +"@VisibleForTesting internal fun getHistorySearchGroups( metadata: List, ): List { return metadata .filter { it.totalViewTime > 0 && it.key.searchTerm != null } .groupBy { it.key.searchTerm!! } .mapValues { group -> // Within a group, we dedupe entries based on their url so we don't display // a page multiple times in the same group, and we sum up the total view time // of deduped entries while making sure to keep the latest updatedAt value. val metadataInGroup = group.value val metadataUrlGroups = metadataInGroup.groupBy { metadata -> metadata.key.url } metadataUrlGroups.map { metadata -> metadata.value.reduce { acc, elem -> acc.copy( totalViewTime = acc.totalViewTime + elem.totalViewTime, updatedAt = max(acc.updatedAt, elem.updatedAt), ) } } } .map { HistoryGroupInternal( groupName = it.key, groupItems = it.value, ) } .filter { it.groupItems.size >= SEARCH_GROUP_MINIMUM_SITES } }" Group all urls accessed following a particular search. Automatically dedupes identical urls and adds each url's view time to the group's total. +"@VisibleForTesting internal fun getSortedHistory( historyHighlights: List, historyGroups: List, ): List { return (historyHighlights + historyGroups) .sortedByDescending { it.lastAccessedTime } .map { when (it) { is HistoryHighlightInternal -> RecentHistoryHighlight( title = if (it.historyHighlight.title.isNullOrBlank()) { it.historyHighlight.url } else { it.historyHighlight.title!! }, url = it.historyHighlight.url, ) is HistoryGroupInternal -> RecentHistoryGroup( title = it.groupName, historyMetadata = it.groupItems, ) } } } override fun stop() { job?.cancel() } }" Maps the internal highlights and search groups to the final objects to be returned. Items will be sorted by their last accessed date so that the most recent will be first. +"@VisibleForTesting internal fun List.removeHighlightsAlreadyInGroups( historyMetadata: List, ): List { return filterNot { highlight -> historyMetadata.any { it.groupItems.any { it.key.url == highlight.historyHighlight.url } } } }" Filter out highlights that are already part of a history group. +"@OptIn(ExperimentalComposeUiApi::class) @Composable fun PocketStory( @PreviewParameter(PocketStoryProvider::class) story: PocketRecommendedStory, backgroundColor: Color, onStoryClick: (PocketRecommendedStory) -> Unit, ) { val imageUrl = story.imageUrl.replace( ""{wh}"", with(LocalDensity.current) { ""${116.dp.toPx().roundToInt()}x${84.dp.toPx().roundToInt()}"" }, ) val isValidPublisher = story.publisher.isNotBlank() val isValidTimeToRead = story.timeToRead >= 0 ListItemTabLarge( imageUrl = imageUrl, backgroundColor = backgroundColor, onClick = { onStoryClick(story) }, title = { Text( text = story.title, modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.story.title"" }, color = FirefoxTheme.colors.textPrimary, overflow = TextOverflow.Ellipsis, maxLines = 2, style = FirefoxTheme.typography.body2, ) }, subtitle = { if (isValidPublisher && isValidTimeToRead) { TabSubtitleWithInterdot(story.publisher, ""${story.timeToRead} min"") } else if (isValidPublisher) { Text( text = story.publisher, modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.story.publisher"" }, color = FirefoxTheme.colors.textSecondary, overflow = TextOverflow.Ellipsis, maxLines = 1, style = FirefoxTheme.typography.caption, ) } else if (isValidTimeToRead) { Text( text = ""${story.timeToRead} min"", modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.story.timeToRead"" }, color = FirefoxTheme.colors.textSecondary, overflow = TextOverflow.Ellipsis, maxLines = 1, style = FirefoxTheme.typography.caption, ) } }, ) }" Displays a single [PocketRecommendedStory]. +"@OptIn(ExperimentalComposeUiApi::class) @Composable fun PocketSponsoredStory( story: PocketSponsoredStory, backgroundColor: Color, onStoryClick: (PocketSponsoredStory) -> Unit, ) { val (imageWidth, imageHeight) = with(LocalDensity.current) { 116.dp.toPx().roundToInt() to 84.dp.toPx().roundToInt() } val imageUrl = story.imageUrl.replace( ""&resize=w[0-9]+-h[0-9]+"".toRegex(), ""&resize=w$imageWidth-h$imageHeight"", ) ListItemTabSurface( imageUrl = imageUrl, backgroundColor = backgroundColor, onClick = { onStoryClick(story) }, ) { Text( text = story.title, modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.sponsoredStory.title"" }, color = FirefoxTheme.colors.textPrimary, overflow = TextOverflow.Ellipsis, maxLines = 2, style = FirefoxTheme.typography.body2, ) Spacer(Modifier.height(9.dp)) Text( text = stringResource(R.string.pocket_stories_sponsor_indication), modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.sponsoredStory.identifier"" }, color = FirefoxTheme.colors.textSecondary, overflow = TextOverflow.Ellipsis, maxLines = 1, style = FirefoxTheme.typography.caption, ) Spacer(Modifier.height(7.dp)) Text( text = story.sponsor, modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.sponsoredStory.sponsor"" }, color = FirefoxTheme.colors.textSecondary, overflow = TextOverflow.Ellipsis, maxLines = 1, style = FirefoxTheme.typography.caption, ) } }" Displays a single [PocketSponsoredStory]. +"@OptIn(ExperimentalComposeUiApi::class) @Suppress(""LongParameterList"") @Composable fun PocketStories( @PreviewParameter(PocketStoryProvider::class) stories: List, contentPadding: Dp, backgroundColor: Color = FirefoxTheme.colors.layer2, onStoryShown: (PocketStory, Pair) -> Unit, onStoryClicked: (PocketStory, Pair) -> Unit, onDiscoverMoreClicked: (String) -> Unit, ) { // Show stories in at most 3 rows but on any number of columns depending on the data received. val maxRowsNo = 3 val storiesToShow = (stories + placeholderStory).chunked(maxRowsNo) val listState = rememberLazyListState() val flingBehavior = EagerFlingBehavior(lazyRowState = listState) LazyRow( modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.stories"" }, contentPadding = PaddingValues(horizontal = contentPadding), state = listState, flingBehavior = flingBehavior, horizontalArrangement = Arrangement.spacedBy(8.dp), ) { itemsIndexed(storiesToShow) { columnIndex, columnItems -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { columnItems.forEachIndexed { rowIndex, story -> Box( modifier = Modifier.semantics { testTagsAsResourceId = true testTag = when (story) { placeholderStory -> ""pocket.discover.more.story"" is PocketRecommendedStory -> ""pocket.recommended.story"" else -> ""pocket.sponsored.story"" } }, ) { if (story == placeholderStory) { ListItemTabLargePlaceholder(stringResource(R.string.pocket_stories_placeholder_text)) { onDiscoverMoreClicked(""https://getpocket.com/explore?$POCKET_FEATURE_UTM_KEY_VALUE"") } } else if (story is PocketRecommendedStory) { PocketStory( story = story, backgroundColor = backgroundColor, ) { val uri = Uri.parse(story.url) .buildUpon() .appendQueryParameter(URI_PARAM_UTM_KEY, POCKET_STORIES_UTM_VALUE) .build().toString() onStoryClicked(it.copy(url = uri), rowIndex to columnIndex) } } else if (story is PocketSponsoredStory) { Box( modifier = Modifier.onShown(0.5f) { onStoryShown(story, rowIndex to columnIndex) }, ) { PocketSponsoredStory( story = story, backgroundColor = backgroundColor, ) { onStoryClicked(story, rowIndex to columnIndex) } } } } } } } } }" Displays a list of [PocketStory]es on 3 by 3 grid. If there aren't enough stories to fill all columns placeholders containing an external link to go to Pocket for more recommendations are added. +"private fun Modifier.onShown( @FloatRange(from = 0.0, to = 1.0) threshold: Float, onVisible: () -> Unit, ): Modifier { val initialTime = System.currentTimeMillis() var lastVisibleCoordinates: LayoutCoordinates? = null return composed { if (inComposePreview) { Modifier } else { val context = LocalContext.current var wasEventReported by remember { mutableStateOf(false) } val toolbarHeight = context.resources.getDimensionPixelSize(R.dimen.browser_toolbar_height) val isToolbarPlacedAtBottom = context.settings().shouldUseBottomToolbar // Get a Rect of the entire screen minus system insets minus the toolbar val screenBounds = Rect() .apply { LocalView.current.getWindowVisibleDisplayFrame(this) } .apply { when (isToolbarPlacedAtBottom) { true -> bottom -= toolbarHeight false -> top += toolbarHeight } } // In the event this composable starts as visible but then gets pushed offscreen // before MINIMUM_TIME_TO_SETTLE_MS we will not report is as being visible. // In the LaunchedEffect we add support for when the composable starts as visible and then // it's position isn't changed after MINIMUM_TIME_TO_SETTLE_MS so it must be reported as visible. LaunchedEffect(initialTime) { delay(MINIMUM_TIME_TO_SETTLE_MS.toLong()) if (!wasEventReported && lastVisibleCoordinates?.isVisible(screenBounds, threshold) == true) { wasEventReported = true onVisible() } } onGloballyPositioned { coordinates -> if (!wasEventReported && coordinates.isVisible(screenBounds, threshold)) { if (System.currentTimeMillis() - initialTime > MINIMUM_TIME_TO_SETTLE_MS) { wasEventReported = true onVisible() } else { lastVisibleCoordinates = coordinates } } } } } }" "Add a callback for when this Composable is ""shown"" on the screen. This checks whether the composable has at least [threshold] ratio of it's total area drawn inside the screen bounds. Does not account for other Views / Windows covering it." +Return whether this has at least [threshold] ratio of it's total area drawn inside the screen bounds. "private fun LayoutCoordinates.isVisible( visibleRect: Rect, @FloatRange(from = 0.0, to = 1.0) threshold: Float, ): Boolean { if (!isAttached) return false return boundsInWindow().toAndroidRect().getIntersectPercentage(size, visibleRect) >= threshold }" +"@FloatRange(from = 0.0, to = 1.0) private fun Rect.getIntersectPercentage(realSize: IntSize, other: Rect): Float { val composableArea = realSize.height * realSize.width val heightOverlap = max(0, min(bottom, other.bottom) - max(top, other.top)) val widthOverlap = max(0, min(right, other.right) - max(left, other.left)) val intersectionArea = heightOverlap * widthOverlap return (intersectionArea.toFloat() / composableArea) }" Returns the ratio of how much this intersects with [other]. +"@OptIn(ExperimentalComposeUiApi::class) @Suppress(""LongParameterList"") @Composable fun PocketStoriesCategories( categories: List, selections: List, modifier: Modifier = Modifier, categoryColors: PocketStoriesCategoryColors = PocketStoriesCategoryColors.buildColors(), onCategoryClick: (PocketRecommendedStoriesCategory) -> Unit, ) { Box( modifier = modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.categories"" }, ) { StaggeredHorizontalGrid( horizontalItemsSpacing = 16.dp, verticalItemsSpacing = 16.dp, ) { categories.filter { it.name != POCKET_STORIES_DEFAULT_CATEGORY_NAME }.forEach { category -> SelectableChip( text = category.name, isSelected = selections.map { it.name }.contains(category.name), selectedTextColor = categoryColors.selectedTextColor, unselectedTextColor = categoryColors.unselectedTextColor, selectedBackgroundColor = categoryColors.selectedBackgroundColor, unselectedBackgroundColor = categoryColors.unselectedBackgroundColor, ) { onCategoryClick(category) } } } } }" Displays a list of [PocketRecommendedStoriesCategory]s. +"data class PocketStoriesCategoryColors( val selectedBackgroundColor: Color, val unselectedBackgroundColor: Color, val selectedTextColor: Color, val unselectedTextColor: Color, ) { companion object { @Composable fun buildColors( selectedBackgroundColor: Color = FirefoxTheme.colors.actionPrimary, unselectedBackgroundColor: Color = FirefoxTheme.colors.actionTertiary, selectedTextColor: Color = FirefoxTheme.colors.textActionPrimary, unselectedTextColor: Color = FirefoxTheme.colors.textActionTertiary, ) = PocketStoriesCategoryColors( selectedBackgroundColor = selectedBackgroundColor, unselectedBackgroundColor = unselectedBackgroundColor, selectedTextColor = selectedTextColor, unselectedTextColor = unselectedTextColor, ) } }" Wrapper for the color parameters of [PocketStoriesCategories]. +"@OptIn(ExperimentalComposeUiApi::class) @Composable fun PoweredByPocketHeader( onLearnMoreClicked: (String) -> Unit, modifier: Modifier = Modifier, textColor: Color = FirefoxTheme.colors.textPrimary, linkTextColor: Color = FirefoxTheme.colors.textAccent, ) { val link = stringResource(R.string.pocket_stories_feature_learn_more) val text = stringResource(R.string.pocket_stories_feature_caption, link) val linkStartIndex = text.indexOf(link) val linkEndIndex = linkStartIndex + link.length Column( modifier = modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.header"" }, horizontalAlignment = Alignment.CenterHorizontally, ) { Row( Modifier .fillMaxWidth() .semantics(mergeDescendants = true) {}, verticalAlignment = Alignment.CenterVertically, ) { Icon( painter = painterResource(id = R.drawable.pocket_vector), contentDescription = null, // Apply the red tint in code. Otherwise the image is black and white. tint = Color(0xFFEF4056), ) Spacer(modifier = Modifier.width(16.dp)) Column { Text( text = stringResource( R.string.pocket_stories_feature_title_2, LocalContext.current.getString(R.string.pocket_product_name), ), modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.header.title"" }, color = textColor, style = FirefoxTheme.typography.caption, ) Box( modifier = modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.header.subtitle"" }, ) { ClickableSubstringLink( text = text, textColor = textColor, linkTextColor = linkTextColor, linkTextDecoration = TextDecoration.Underline, clickableStartIndex = linkStartIndex, clickableEndIndex = linkEndIndex, ) { onLearnMoreClicked( ""https://www.mozilla.org/en-US/firefox/pocket/?$POCKET_FEATURE_UTM_KEY_VALUE"", ) } } } } } }" Pocket feature section title. Shows a default text about Pocket and offers a external link to learn more. +"@OptIn(ExperimentalComposeUiApi::class) @Composable private fun RecentBookmarksMenu( showMenu: Boolean, menuItems: List, recentBookmark: RecentBookmark, onDismissRequest: () -> Unit, ) { DropdownMenu( expanded = showMenu, onDismissRequest = { onDismissRequest() }, modifier = Modifier .background(color = FirefoxTheme.colors.layer2) .semantics { testTagsAsResourceId = true testTag = ""recent.bookmark.menu"" }, ) { for (item in menuItems) { DropdownMenuItem( onClick = { onDismissRequest() item.onClick(recentBookmark) }, ) { Text( text = item.title, color = FirefoxTheme.colors.textPrimary, maxLines = 1, modifier = Modifier .fillMaxHeight() .align(Alignment.CenterVertically), ) } } } }" Menu shown for a [RecentBookmark]. +"@OptIn(ExperimentalComposeUiApi::class) @Composable fun RecentBookmarks( bookmarks: List, menuItems: List, backgroundColor: Color, onRecentBookmarkClick: (RecentBookmark) -> Unit = {}, ) { LazyRow( modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""recent.bookmarks"" }, contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { items(bookmarks) { bookmark -> RecentBookmarkItem( bookmark = bookmark, menuItems = menuItems, backgroundColor = backgroundColor, onRecentBookmarkClick = onRecentBookmarkClick, ) } } }" A list of recent bookmarks. +"@OptIn( ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class, ) @Composable private fun RecentBookmarkItem( bookmark: RecentBookmark, menuItems: List, backgroundColor: Color, onRecentBookmarkClick: (RecentBookmark) -> Unit = {}, ) { var isMenuExpanded by remember { mutableStateOf(false) } Card( modifier = Modifier .width(158.dp) .combinedClickable( enabled = true, onClick = { onRecentBookmarkClick(bookmark) }, onLongClick = { isMenuExpanded = true }, ), shape = cardShape, backgroundColor = backgroundColor, elevation = 6.dp, ) { Column( modifier = Modifier .fillMaxWidth() .padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 8.dp), ) { RecentBookmarkImage(bookmark) Spacer(modifier = Modifier.height(8.dp)) Text( text = bookmark.title ?: bookmark.url ?: """", modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""recent.bookmark.title"" }, color = FirefoxTheme.colors.textPrimary, overflow = TextOverflow.Ellipsis, maxLines = 1, style = FirefoxTheme.typography.caption, ) RecentBookmarksMenu( showMenu = isMenuExpanded, menuItems = menuItems, recentBookmark = bookmark, onDismissRequest = { isMenuExpanded = false }, ) } } }" A recent bookmark item. +@InternalStreamChatApi public const val GIPHY_INFO_DEFAULT_WIDTH_DP: Int = 200 Default width used for Giphy Images if no width metadata is available. +@InternalStreamChatApi public const val GIPHY_INFO_DEFAULT_HEIGHT_DP: Int = 200 Default height used for Giphy Images if no width metadata is available. +"public fun Attachment.giphyInfo(field: GiphyInfoType): GiphyInfo? { val giphyInfoMap =(extraData[ModelType.attach_giphy] as? Map?)?.get(field.value) as? Map? return giphyInfoMap?.let { map -> GiphyInfo( url = map[""url""] ?: """", width = getGiphySize(map, ""width"", Utils.dpToPx(GIPHY_INFO_DEFAULT_WIDTH_DP)), height = getGiphySize(map, ""height"", Utils.dpToPx(GIPHY_INFO_DEFAULT_HEIGHT_DP)) ) } }" Returns an object containing extra information about the Giphy image based on its type. +"private fun getGiphySize(map: Map, size: String, defaultValue: Int): Int { return if (!map[size].isNullOrBlank()) map[size]?.toInt() ?: defaultValue else defaultValue }" Returns specified size for the giphy. +"public data class GiphyInfo( val url: String, @Px val width: Int, @Px val height: Int, )" Contains extra information about Giphy attachments. +"@OptIn(ExperimentalCoroutinesApi::class) @InternalStreamChatApi @Suppress(""TooManyFunctions"") public class MessageComposerController( private val channelId: String, private val chatClient: ChatClient = ChatClient.instance(), private val maxAttachmentCount: Int = AttachmentConstants.MAX_ATTACHMENTS_COUNT,private val maxAttachmentSize: Long = AttachmentConstants.MAX_UPLOAD_FILE_SIZE, ) { }" "Controller responsible for handling the composing and sending of messages. It acts as a central place for both the core business logic and state required to create and send messages, handle attachments, message actions and more. If you require more state and business logic, compose this Controller with your code and apply the necessary changes." +private val scope = CoroutineScope(DispatcherProvider.Immediate) Creates a [CoroutineScope] that allows us to cancel the ongoing work when the parent  ViewModel is disposed. +"public var typingUpdatesBuffer: TypingUpdatesBuffer = DefaultTypingUpdatesBuffer( onTypingStarted = ::sendKeystrokeEvent, onTypingStopped = ::sendStopTypingEvent, coroutineScope = scope )" Buffers typing updates. +"public val channelState: Flow = chatClient.watchChannelAsState( cid = channelId, messageLimit = DefaultMessageLimit, coroutineScope = scope ).filterNotNull()" Holds information about the current state of the [Channel]. +"public val ownCapabilities: StateFlow> = channelState.flatMapLatest { it.channelData } .map { it.ownCapabilities } .stateIn( scope = scope, started = SharingStarted.Eagerly, initialValue = setOf() )" Holds information about the abilities the current user is able to exercise in the given channel. +"private val canSendTypingUpdates = ownCapabilities.map { it.contains(ChannelCapabilities.SEND_TYPING_EVENTS) } .stateIn( scope = scope, started = SharingStarted.Eagerly, initialValue = false )" Signals if the user's typing will send a typing update in the given channel. +"private val canSendLinks = ownCapabilities.map { it.contains(ChannelCapabilities.SEND_LINKS) }.stateIn(scope = scope,started = SharingStarted.Eagerly,initialValue = false)" Signals if the user is allowed to send links. +"private val isSlowModeActive = ownCapabilities.map { it.contains(ChannelCapabilities.SLOW_MODE) } .stateIn( scope = scope, started = SharingStarted.Eagerly, initialValue = false )" Signals if the user needs to wait before sending the next message. +public val state: MutableStateFlow = MutableStateFlow(MessageComposerState()) Full message composer state holding all the required information. +"public val input: MutableStateFlow = MutableStateFlow("""")" UI state of the current composer input. +public val alsoSendToChannel: MutableStateFlow = MutableStateFlow(false) If the message will be shown in the channel after it is sent. +public val cooldownTimer: MutableStateFlow = MutableStateFlow(0) Represents the remaining time until the user is allowed to send the next message. +public val selectedAttachments: MutableStateFlow> = MutableStateFlow(emptyList()) "Represents the currently selected attachments, that are shown within the composer UI." +public val validationErrors: MutableStateFlow> = MutableStateFlow(emptyList()) Represents the list of validation errors for the current text input and the currently selected attachments. +public val mentionSuggestions: MutableStateFlow> = MutableStateFlow(emptyList()) Represents the list of users that can be used to autocomplete the current mention input. +public val commandSuggestions: MutableStateFlow> = MutableStateFlow(emptyList()) Represents the list of commands that can be executed for the channel. +private var users: List = emptyList() Represents the list of users in the channel. +private var commands: List = emptyList() Represents the list of available commands in the channel. +"public BiCorpus alignedFromFiles ( String f ) throws IOException { return new BiCorpus ( fpath + f + extf , epath + f + exte , apath + f + exta ) ; }" Generate aligned BiCorpus . +"public LognormalDistr ( double shape , double scale ) { numGen = new LogNormalDistribution ( scale , shape ) ; }" Instantiates a new Log-normal pseudo random number generator . +"private static String contentLengthHeader ( final long length ) { return String . format ( ""Content-Length: %d"" , length ) ; }" Format Content-Length header . +@ Bean @ ConditionalOnMissingBean public AmqpSenderService amqpSenderServiceBean ( ) { return new DefaultAmqpSenderService ( rabbitTemplate ( ) ) ; } Create default amqp sender service bean . +"@ Override protected void initialize ( ) { super . initialize ( ) ; m_Processor = new MarkdownProcessor ( ) ; m_Markdown = """" ; }" Initializes the members . +"public void upperBound ( byte [ ] key ) throws IOException { upperBound ( key , 0 , key . length ) ; }" "Move the cursor to the first entry whose key is strictly greater than the input key . Synonymous to upperBound ( key , 0 , key.length ) . The entry returned by the previous entry ( ) call will be invalid ." +"public static String replaceLast ( String s , char sub , char with ) { int index = s . lastIndexOf ( sub ) ; if ( index == - 1 ) { return s ; } char [ ] str = s . toCharArray ( ) ; str [ index ] = with ; return new String ( str ) ; }" Replaces the very last occurrence of a character in a string . +public static void main ( String [ ] args ) { Thrust simulation = new Thrust ( ) ; simulation . run ( ) ; } Entry point for the example application . +"public static < T > T checkNotNull ( T reference , @ Nullable String errorMessageTemplate , @ Nullable Object ... errorMessageArgs ) { if ( reference == null ) { throw new NullPointerException ( format ( errorMessageTemplate , errorMessageArgs ) ) ; } return reference ; }" Ensures that an object reference passed as a parameter to the calling method is not null . +"public boolean insert ( String name , RegExp definition ) { if ( Options . DEBUG ) Out . debug ( ""inserting macro "" + name + "" with definition :"" + Out . NL + definition ) ; used . put ( name , Boolean . FALSE ) ; return macros . put ( name , definition ) == null ; }" Stores a new macro and its definition . +public boolean add ( Object o ) { ensureCapacity ( size + 1 ) ; elementData [ size ++ ] = o ; return true ; } Appends the specified element to the end of this list . +"public InvocationTargetException ( Throwable target , String s ) { super ( s , null ) ; this . target = target ; }" Constructs a InvocationTargetException with a target exception and a detail message . +public boolean isExternalSkin ( ) { return ! isDefaultSkin && mResources != null ; } whether the skin being used is from external .skin file +"private void updateActions ( ) { actions . removeAll ( ) ; final ActionGroup mainActionGroup = ( ActionGroup ) actionManager . getAction ( getGroupMenu ( ) ) ; if ( mainActionGroup == null ) { return ; } final Action [ ] children = mainActionGroup . getChildren ( null ) ; for ( final Action action : children ) { final Presentation presentation = presentationFactory . getPresentation ( action ) ; final ActionEvent e = new ActionEvent ( ActionPlaces . MAIN_CONTEXT_MENU , presentation , actionManager , 0 ) ; action . update ( e ) ; if ( presentation . isVisible ( ) ) { actions . add ( action ) ; } } }" Updates the list of visible actions . +private void showFeedback ( String message ) { if ( myHost != null ) { myHost . showFeedback ( message ) ; } else { System . out . println ( message ) ; } } Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface . +TechCategory fallthrough ( ) { switch ( this ) { case OMNI_AERO : return OMNI ; case CLAN_AERO : case CLAN_VEE : return CLAN ; case IS_ADVANCED_AERO : case IS_ADVANCED_VEE : return IS_ADVANCED ; default : return null ; } } "If no value is provided for ASFs or Vees , use the base value ." +"static void svd_dscal ( int n , double da , double [ ] dx , int incx ) { if ( n <= 0 || incx == 0 ) return ; int ix = ( incx < 0 ) ? n - 1 : 0 ; for ( int i = 0 ; i < n ; i ++ ) { dx [ ix ] *= da ; ix += incx ; } return ; }" Function scales a vector by a constant . * Based on Fortran-77 routine from Linpack by J. Dongarra +"public CampoFechaVO insertValue ( final CampoFechaVO value ) { try { DbConnection conn = getConnection ( ) ; DbInsertFns . insert ( conn , TABLE_NAME , DbUtil . getColumnNames ( COL_DEFS ) , new SigiaDbInputRecord ( COL_DEFS , value ) ) ; return value ; } catch ( Exception e ) { logger . error ( ""Error insertando campo de tipo fecha para el descriptor "" + value . getIdObjeto ( ) , e ) ; throw new DBException ( ""insertando campo de tipo fecha"" , e ) ; } }" Inserta un valor de tipo fecha . +"private synchronized void closeActiveFile ( ) { StringWriterFile activeFile = this . activeFile ; try { this . activeFile = null ; if ( activeFile != null ) { activeFile . close ( ) ; getPolicy ( ) . closeActiveFile ( activeFile . path ( ) ) ; activeFile = null ; } } catch ( IOException e ) { trace . error ( ""error closing active file '{}'"" , activeFile . path ( ) , e ) ; } }" "close , finalize , and apply retention policy" +"public void testWARTypeEquality ( ) { WAR war1 = new WAR ( ""/some/path/to/file.war"" ) ; WAR war2 = new WAR ( ""/otherfile.war"" ) ; assertEquals ( war1 . getType ( ) , war2 . getType ( ) ) ; }" Test equality between WAR deployables . +"public static Vector readSignatureAlgorithmsExtension ( byte [ ] extensionData ) throws IOException { if ( extensionData == null ) { throw new IllegalArgumentException ( ""'extensionData' cannot be null"" ) ; } ByteArrayInputStream buf = new ByteArrayInputStream ( extensionData ) ; Vector supported_signature_algorithms = parseSupportedSignatureAlgorithms ( false , buf ) ; TlsProtocol . assertEmpty ( buf ) ; return supported_signature_algorithms ; }" Read 'signature_algorithms ' extension data . +"public void updateNCharacterStream ( int columnIndex , java . io . Reader x , long length ) throws SQLException { throw new SQLFeatureNotSupportedException ( resBundle . handleGetObject ( ""jdbcrowsetimpl.featnotsupp"" ) . toString ( ) ) ; }" "Updates the designated column with a character stream value , which will have the specified number of bytes . The driver does the necessary conversion from Java character format to the national character set in the database . It is intended for use when updating NCHAR , NVARCHAR and LONGNVARCHAR columns . The updater methods are used to update column values in the current row or the insert row . The updater methods do not update the underlying database ; instead the updateRow or insertRow methods are called to update the database ." +public boolean isModified ( ) { return isCustom ( ) && ! isUserAdded ( ) ; } "Returns whether the receiver represents a modified template , i.e . a contributed template that has been changed ." +"public String toString ( ) { return this . getClass ( ) . getName ( ) + ""("" + my_k + "")"" ; }" Returns a String representation of the receiver . +"private static PostingsEnum termDocs ( IndexReader reader , Term term ) throws IOException { return MultiFields . getTermDocsEnum ( reader , MultiFields . getLiveDocs ( reader ) , term . field ( ) , term . bytes ( ) ) ; }" NB : this is a convenient but very slow way of getting termDocs . It is sufficient for testing purposes . +public boolean isSubregion ( ) { return subregion ; } "Returns true if the Region is a subregion of a Component , otherwise false . For example , < code > Region.BUTTON < /code > corresponds do a < code > Component < /code > so that < code > Region.BUTTON.isSubregion ( ) < /code > returns false ." +"public static void encodeToFile ( byte [ ] dataToEncode , String filename ) throws java . io . IOException { if ( dataToEncode == null ) { throw new NullPointerException ( ""Data to encode was null."" ) ; } Base64 . OutputStream bos = null ; try { bos = new Base64 . OutputStream ( new java . io . FileOutputStream ( filename ) , Base64 . ENCODE ) ; bos . write ( dataToEncode ) ; } catch ( java . io . IOException e ) { throw e ; } finally { try { bos . close ( ) ; } catch ( Exception e ) { } } }" "Convenience method for encoding data to a file . < p > As of v 2.3 , if there is a error , the method will throw an java.io.IOException . < b > This is new to v2.3 ! < /b > In earlier versions , it just returned false , but in retrospect that 's a pretty poor way to handle it. < /p >" +public synchronized void addDataStatusListener ( DataStatusListener l ) { m_mTab . addDataStatusListener ( l ) ; } Add Data Status Listener - pass on to MTab +"protected void addField ( DurationFieldType field , int value ) { addFieldInto ( iValues , field , value ) ; }" Adds the value of a field in this period . +@ Override public int perimeter ( int size ) { size = size / 2 ; int retval = sw . perimeter ( size ) ; retval += se . perimeter ( size ) ; retval += ne . perimeter ( size ) ; retval += nw . perimeter ( size ) ; return retval ; } Compute the perimeter for a grey node using Samet 's algorithm . +"public BigdataStatementIterator addedIterator ( ) { final IChunkedOrderedIterator < ISPO > src = new ChunkedWrappedIterator < ISPO > ( added . iterator ( ) ) ; return new BigdataStatementIteratorImpl ( kb , src ) . start ( kb . getExecutorService ( ) ) ; }" Return iterator visiting the inferences that were added to the KB . +"public < V extends Object , C extends RTSpan < V > > void applyEffect ( Effect < V , C > effect , V value ) { if ( mUseRTFormatting && ! mIsSelectionChanging && ! mIsSaving ) { Spannable oldSpannable = mIgnoreTextChanges ? null : cloneSpannable ( ) ; effect . applyToSelection ( this , value ) ; synchronized ( this ) { if ( mListener != null && ! mIgnoreTextChanges ) { Spannable newSpannable = cloneSpannable ( ) ; mListener . onTextChanged ( this , oldSpannable , newSpannable , getSelectionStart ( ) , getSelectionEnd ( ) , getSelectionStart ( ) , getSelectionEnd ( ) ) ; } mLayoutChanged = true ; } } }" "Call this to have an effect applied to the current selection . You get the Effect object via the static data members ( e.g. , RTEditText.BOLD ) . The value for most effects is a Boolean , indicating whether to add or remove the effect ." +"public DefaultLmlParser ( final LmlData data , final LmlSyntax syntax , final LmlTemplateReader templateReader , final boolean strict ) { super ( data , syntax , templateReader , new DefaultLmlStyleSheet ( ) , strict ) ; }" "Creates a new parser with custom syntax , reader and strict setting ." +"private static void populateFancy ( SQLiteDatabase writableDb ) { long startOfToday = DateUtil . parse ( DateUtil . format ( System . currentTimeMillis ( ) ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Clothes"" , ""New jeans"" , 10000 , startOfToday , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Flat / House"" , ""Monthly rent"" , 35000 , startOfToday , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Grocery"" , ""Fruits & vegetables"" , 3567 , DateUtil . parse ( ""19/08/2015"" ) , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Fuel"" , ""Full gas tank"" , 7590 , DateUtil . parse ( ""14/08/2015"" ) , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Clothes"" , ""New shirt"" , 3599 , DateUtil . parse ( ""11/08/2015"" ) , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Restaurant"" , ""Family get together"" , 3691 , DateUtil . parse ( ""05/08/2015"" ) , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_INCOME , ""Salary"" , """" , 90000 , DateUtil . parse ( ""31/07/2015"" ) , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Personal care"" , ""New perfume"" , 3865 , DateUtil . parse ( ""29/07/2015"" ) , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Grocery"" , ""Bottle of milk"" , 345 , DateUtil . parse ( ""26/07/2015"" ) , Item . NO_ID ) ) ; }" Generates reasonable amount of good-looking income / expense items . +"public TestEntity ( int index , String text , String value , double minConfidence ) { super ( index , text ) ; this . value = value ; this . minConfidence = minConfidence ; }" "New instance , with a value ." +"public boolean contains ( JComponent a , int b , int c ) { boolean returnValue = ( ( ComponentUI ) ( uis . elementAt ( 0 ) ) ) . contains ( a , b , c ) ; for ( int i = 1 ; i < uis . size ( ) ; i ++ ) { ( ( ComponentUI ) ( uis . elementAt ( i ) ) ) . contains ( a , b , c ) ; } return returnValue ; }" Invokes the < code > contains < /code > method on each UI handled by this object . +public boolean isClosed ( ) { return closed ; } Returns true if this contour path is closed ( loops back on itself ) or false if it is not . +"public void store ( float val , Offset offset ) { this . plus ( offset ) . store ( val ) ; }" Stores the float value in the memory location pointed to by the current instance . +"public List < IvrZone > showIvrZones ( boolean active ) throws NetworkDeviceControllerException { List < IvrZone > zones = new ArrayList < IvrZone > ( ) ; SSHPrompt [ ] prompts = { SSHPrompt . POUND , SSHPrompt . GREATER_THAN } ; StringBuilder buf = new StringBuilder ( ) ; String cmdKey = active ? ""MDSDialog.ivr.show.zone.active.cmd"" : ""MDSDialog.ivr.show.zone.cmd"" ; sendWaitFor ( MDSDialogProperties . getString ( cmdKey ) , defaultTimeout , prompts , buf ) ; String [ ] lines = getLines ( buf ) ; IvrZone zone = null ; IvrZoneMember member = null ; String [ ] regex = { MDSDialogProperties . getString ( ""MDSDialog.ivr.showZoneset.zone.name.match"" ) , MDSDialogProperties . getString ( ""MDSDialog.ivr.showZoneset.zone.member.match"" ) } ; String [ ] groups = new String [ 10 ] ; for ( String line : lines ) { int index = match ( line , regex , groups ) ; switch ( index ) { case 0 : zone = new IvrZone ( groups [ 0 ] ) ; zones . add ( zone ) ; break ; case 1 : member = new IvrZoneMember ( groups [ 0 ] , Integer . valueOf ( groups [ 3 ] ) ) ; zone . getMembers ( ) . add ( member ) ; break ; } } return zones ; }" Get switch ivr zones +"public static void append ( File file , Reader reader , String charset ) throws IOException { append ( file , reader , charset , false ) ; }" "Append the text supplied by the Reader at the end of the File without writing a BOM , using a specified encoding ." +public static LifetimeAttribute createLifetimeAttribute ( int lifetime ) { LifetimeAttribute attribute = new LifetimeAttribute ( ) ; attribute . setLifetime ( lifetime ) ; return attribute ; } Create a LifetimeAttribute . +"public void testFilePrimary ( ) throws Exception { start ( ) ; igfsPrimary . create ( FILE , true ) . close ( ) ; checkEvictionPolicy ( 0 , 0 ) ; int blockSize = igfsPrimary . info ( FILE ) . blockSize ( ) ; append ( FILE , blockSize ) ; checkEvictionPolicy ( 0 , 0 ) ; read ( FILE , 0 , blockSize ) ; checkEvictionPolicy ( 0 , 0 ) ; }" Test how evictions are handled for a file working in PRIMARY mode . +"public static String createTestPtStationCSVFile ( File file ) { try ( BufferedWriter bw = new BufferedWriter ( new FileWriter ( file ) ) ) { bw . write ( ""id,x,y"" ) ; bw . newLine ( ) ; bw . write ( ""1,10,10"" ) ; bw . newLine ( ) ; bw . write ( ""2,10, 190"" ) ; bw . newLine ( ) ; bw . write ( ""3,190,190"" ) ; bw . newLine ( ) ; bw . write ( ""4,190,10"" ) ; bw . newLine ( ) ; return file . getCanonicalPath ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }" This method creates 4 pt stops for the test network from createTestNetwork ( ) . The information about the coordinates will be written to a csv file . The 4 pt stops are located as a square in the coordinate plane with a side length of 180 meter ( see the sketch below ) . +@ Override public int hashCode ( ) { int result = super . hashCode ( ) ; return result ; } Returns a hash code for the renderer . +@ Override public void eUnset ( int featureID ) { switch ( featureID ) { case SGenPackage . FEATURE_TYPE__DEPRECATED : setDeprecated ( DEPRECATED_EDEFAULT ) ; return ; case SGenPackage . FEATURE_TYPE__COMMENT : setComment ( COMMENT_EDEFAULT ) ; return ; case SGenPackage . FEATURE_TYPE__PARAMETERS : getParameters ( ) . clear ( ) ; return ; case SGenPackage . FEATURE_TYPE__OPTIONAL : setOptional ( OPTIONAL_EDEFAULT ) ; return ; } super . eUnset ( featureID ) ; } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"public boolean isVMAX3VolumeCompressionEnabled ( URI blockObjectURI ) { VirtualPool virtualPool = null ; Volume volume = null ; if ( URIUtil . isType ( blockObjectURI , Volume . class ) ) { volume = _dbClient . queryObject ( Volume . class , blockObjectURI ) ; } else if ( URIUtil . isType ( blockObjectURI , BlockSnapshot . class ) ) { BlockSnapshot snapshot = _dbClient . queryObject ( BlockSnapshot . class , blockObjectURI ) ; volume = _dbClient . queryObject ( Volume . class , snapshot . getParent ( ) ) ; } else if ( URIUtil . isType ( blockObjectURI , BlockMirror . class ) ) { BlockMirror mirror = _dbClient . queryObject ( BlockMirror . class , blockObjectURI ) ; virtualPool = _dbClient . queryObject ( VirtualPool . class , mirror . getVirtualPool ( ) ) ; } if ( volume != null ) { virtualPool = _dbClient . queryObject ( VirtualPool . class , volume . getVirtualPool ( ) ) ; } return ( ( virtualPool != null ) && virtualPool . getCompressionEnabled ( ) ) ; }" This method is will check if the volume associated with virtual Pool has compression enabled . +public void releaseConnection ( Database conn ) { if ( conn != null ) conn . close ( ) ; } Releases a connection . +"public final void testRemoveHelperTextId ( ) { PasswordEditText passwordEditText = new PasswordEditText ( getContext ( ) ) ; passwordEditText . addHelperTextId ( android . R . string . cancel ) ; passwordEditText . addHelperTextId ( android . R . string . copy ) ; passwordEditText . removeHelperTextId ( android . R . string . cancel ) ; passwordEditText . removeHelperTextId ( android . R . string . cancel ) ; assertEquals ( 1 , passwordEditText . getHelperTexts ( ) . size ( ) ) ; assertEquals ( getContext ( ) . getText ( android . R . string . copy ) , passwordEditText . getHelperTexts ( ) . iterator ( ) . next ( ) ) ; }" "Tests the functionality of the method , which allows to remove a helper text by its id ." +"private void logMessage ( String msg , Object [ ] obj ) { if ( getMonitoringPropertiesLoader ( ) . isToLogIndications ( ) ) { _logger . debug ( msg , obj ) ; } }" Log the messages . This method eliminates the logging condition check every time when we need to log a message . +public static Float toRef ( float f ) { return new Float ( f ) ; } cast a float value to his ( CFML ) reference type Float +@ Override protected boolean shouldComposeCreationImage ( ) { return true ; } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +public synchronized void promote ( Tile tile ) { if ( tileQueue . contains ( tile ) ) { try { tileQueue . remove ( tile ) ; tile . setPriority ( Tile . Priority . High ) ; tileQueue . put ( tile ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } } Increase the priority of this tile so it will be loaded sooner . +"public void exitApp ( ) { this . webView . getPluginManager ( ) . postMessage ( ""exit"" , null ) ; }" Exit the Android application . +"public void test_getInnerCause01_reject_otherType ( ) { Throwable t = new Throwable ( ) ; assertNull ( getInnerCause ( t , Exception . class ) ) ; }" Does not find cause when it is on top of the stack trace and not either the desired type or a subclass of the desired type . +public Handshake handshake ( ) { return handshake ; } "Returns the TLS handshake of the connection that carried this response , or null if the response was received without TLS ." +"private Coordinate averagePoint ( CoordinateSequence seq ) { Coordinate a = new Coordinate ( 0 , 0 , 0 ) ; int n = seq . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { a . x += seq . getOrdinate ( i , CoordinateSequence . X ) ; a . y += seq . getOrdinate ( i , CoordinateSequence . Y ) ; a . z += seq . getOrdinate ( i , CoordinateSequence . Z ) ; } a . x /= n ; a . y /= n ; a . z /= n ; return a ; }" "Computes a point which is the average of all coordinates in a sequence . If the sequence lies in a single plane , the computed point also lies in the plane ." +"public static void invokeWebserviceASync ( WSDefinition def , SuccessCallback scall , FailureCallback fcall , Object ... arguments ) { WSConnection cr = new WSConnection ( def , scall , fcall , arguments ) ; NetworkManager . getInstance ( ) . addToQueue ( cr ) ; }" Invokes a web asynchronously and calls the callback on completion +public PutResponseMessage ( PutResponseMessage other ) { if ( other . isSetHeader ( ) ) { this . header = new AsyncMessageHeader ( other . header ) ; } } Performs a deep copy on < i > other < /i > . +private boolean isSynthetic ( Method m ) { if ( ( m . getAccessFlags ( ) & Constants . ACC_SYNTHETIC ) != 0 ) { return true ; } Attribute [ ] attrs = m . getAttributes ( ) ; for ( Attribute attr : attrs ) { if ( attr instanceof Synthetic ) { return true ; } } return false ; } Methods marked with the `` Synthetic '' attribute do not appear in the source code +public boolean isTagline ( ) { return tagline ; } Checks if is tagline . +"protected LocaTable ( TrueTypeFont ttf ) { super ( TrueTypeTable . LOCA_TABLE ) ; MaxpTable maxp = ( MaxpTable ) ttf . getTable ( ""maxp"" ) ; int numGlyphs = maxp . getNumGlyphs ( ) ; HeadTable head = ( HeadTable ) ttf . getTable ( ""head"" ) ; short format = head . getIndexToLocFormat ( ) ; isLong = ( format == 1 ) ; offsets = new int [ numGlyphs + 1 ] ; }" Creates a new instance of HmtxTable +public static < T > T create ( Class < T > theQueryClass ) { return AgentClass . createAgent ( theQueryClass ) ; } Create a database query dynamically +"@ DSComment ( ""From safe class list"" ) @ DSSafe ( DSCat . SAFE_LIST ) @ DSGenerator ( tool_name = ""Doppelganger"" , tool_version = ""2.0"" , generated_on = ""2013-12-30 13:02:44.163 -0500"" , hash_original_method = ""CE28B7D5A93F674A0286463AAF68C789"" , hash_generated_method = ""4C5D61097E13A407D793E43190510D41"" ) public synchronized void addFailure ( Test test , AssertionFailedError t ) { fFailures . addElement ( new TestFailure ( test , t ) ) ; for ( Enumeration e = cloneListeners ( ) . elements ( ) ; e . hasMoreElements ( ) ; ) { ( ( TestListener ) e . nextElement ( ) ) . addFailure ( test , t ) ; } }" Adds a failure to the list of failures . The passed in exception caused the failure . +public ExtendedKeyUsage ( byte [ ] encoding ) { super ( encoding ) ; } Creates the extension object on the base of its encoded form . +"public Iterator < E > subsetIterator ( E from , E to ) { return new BinarySearchTreeIterator < E > ( this . root , from , to ) ; }" Returns the in-order ( ascending ) iterator . +public int valueForXPosition ( int xPos ) { int value ; int minValue = slider . getMinimum ( ) ; int maxValue = slider . getMaximum ( ) ; int trackLeft = trackRect . x + thumbRect . width / 2 + trackBorder ; int trackRight = trackRect . x + trackRect . width - thumbRect . width / 2 - trackBorder ; int trackLength = trackRight - trackLeft ; if ( xPos <= trackLeft ) { value = drawInverted ( ) ? maxValue : minValue ; } else if ( xPos >= trackRight ) { value = drawInverted ( ) ? minValue : maxValue ; } else { int distanceFromTrackLeft = xPos - trackLeft ; double valueRange = ( double ) maxValue - ( double ) minValue ; double valuePerPixel = valueRange / ( double ) trackLength ; int valueFromTrackLeft = ( int ) Math . round ( distanceFromTrackLeft * valuePerPixel ) ; value = drawInverted ( ) ? maxValue - valueFromTrackLeft : minValue + valueFromTrackLeft ; } return value ; } "Returns a value give an x position . If xPos is past the track at the left or the right it will set the value to the min or max of the slider , depending if the slider is inverted or not ." +@ Override protected EClass eStaticClass ( ) { return SRuntimePackage . Literals . COMPOSITE_SLOT ; } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"public static void main ( final String [ ] args ) { DOMTestCase . doMain ( documentcreateattributeNS03 . class , args ) ; }" Runs this test from the command line . +public ListIterator < AbstractInsnNode > iterator ( ) { return iterator ( 0 ) ; } Returns an iterator over the instructions in this list . +public static String escapeXml ( String str ) { if ( str == null ) { return null ; } return EntitiesUtils . XML . escape ( str ) ; } "< p > Escapes the characters in a < code > String < /code > using XML entities. < /p > < p > For example : < tt > '' bread '' & `` butter '' < /tt > = > < tt > & amp ; quot ; bread & amp ; quot ; & amp ; amp ; & amp ; quot ; butter & amp ; quot ; < /tt > . < /p > < p > Supports only the five basic XML entities ( gt , lt , quot , amp , apos ) . Does not support DTDs or external entities. < /p > < p > Note that unicode characters greater than 0x7f are currently escaped to their numerical \\u equivalent . This may change in future releases . < /p >" +"public boolean isProcessed ( ) { Object oo = get_Value ( COLUMNNAME_Processed ) ; if ( oo != null ) { if ( oo instanceof Boolean ) return ( ( Boolean ) oo ) . booleanValue ( ) ; return ""Y"" . equals ( oo ) ; } return false ; }" Get Processed . +"public void processResponse ( SIPResponse response , MessageChannel incomingMessageChannel , SIPDialog dialog ) { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logDebug ( ""PROCESSING INCOMING RESPONSE"" + response . encodeMessage ( ) ) ; } if ( listeningPoint == null ) { if ( sipStack . isLoggingEnabled ( ) ) sipStack . getStackLogger ( ) . logError ( ""Dropping message: No listening point"" + "" registered!"" ) ; return ; } if ( sipStack . checkBranchId ( ) && ! Utils . getInstance ( ) . responseBelongsToUs ( response ) ) { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logError ( ""Dropping response - topmost VIA header does not originate from this stack"" ) ; } return ; } SipProviderImpl sipProvider = listeningPoint . getProvider ( ) ; if ( sipProvider == null ) { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logError ( ""Dropping message: no provider"" ) ; } return ; } if ( sipProvider . getSipListener ( ) == null ) { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logError ( ""No listener -- dropping response!"" ) ; } return ; } SIPClientTransaction transaction = ( SIPClientTransaction ) this . transactionChannel ; SipStackImpl sipStackImpl = sipProvider . sipStack ; if ( sipStack . isLoggingEnabled ( ) ) { sipStackImpl . getStackLogger ( ) . logDebug ( ""Transaction = "" + transaction ) ; } if ( transaction == null ) { if ( dialog != null ) { if ( response . getStatusCode ( ) / 100 != 2 ) { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logDebug ( ""Response is not a final response and dialog is found for response -- dropping response!"" ) ; } return ; } else if ( dialog . getState ( ) == DialogState . TERMINATED ) { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logDebug ( ""Dialog is terminated -- dropping response!"" ) ; } return ; } else { boolean ackAlreadySent = false ; if ( dialog . isAckSeen ( ) && dialog . getLastAckSent ( ) != null ) { if ( dialog . getLastAckSent ( ) . getCSeq ( ) . getSeqNumber ( ) == response . getCSeq ( ) . getSeqNumber ( ) ) { ackAlreadySent = true ; } } if ( ackAlreadySent && response . getCSeq ( ) . getMethod ( ) . equals ( dialog . getMethod ( ) ) ) { try { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logDebug ( ""Retransmission of OK detected: Resending last ACK"" ) ; } dialog . resendAck ( ) ; return ; } catch ( SipException ex ) { if ( sipStack . isLoggingEnabled ( ) ) sipStack . getStackLogger ( ) . logError ( ""could not resend ack"" , ex ) ; } } } } if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logDebug ( ""could not find tx, handling statelessly Dialog = "" + dialog ) ; } ResponseEventExt sipEvent = new ResponseEventExt ( sipProvider , transaction , dialog , ( Response ) response ) ; if ( response . getCSeqHeader ( ) . getMethod ( ) . equals ( Request . INVITE ) ) { SIPClientTransaction forked = this . sipStack . getForkedTransaction ( response . getTransactionId ( ) ) ; sipEvent . setOriginalTransaction ( forked ) ; } sipProvider . handleEvent ( sipEvent , transaction ) ; return ; } ResponseEventExt responseEvent = null ; responseEvent = new ResponseEventExt ( sipProvider , ( ClientTransactionExt ) transaction , dialog , ( Response ) response ) ; if ( response . getCSeqHeader ( ) . getMethod ( ) . equals ( Request . INVITE ) ) { SIPClientTransaction forked = this . sipStack . getForkedTransaction ( response . getTransactionId ( ) ) ; responseEvent . setOriginalTransaction ( forked ) ; } if ( dialog != null && response . getStatusCode ( ) != 100 ) { dialog . setLastResponse ( transaction , response ) ; transaction . setDialog ( dialog , dialog . getDialogId ( ) ) ; } sipProvider . handleEvent ( responseEvent , transaction ) ; }" Process the response . +"public AnnotationAtttributeProposalInfo ( IJavaProject project , CompletionProposal proposal ) { super ( project , proposal ) ; }" Creates a new proposal info . +"public static void restoreReminderPreference ( Context context ) { int hour = MehPreferencesManager . getNotificationPreferenceHour ( context ) ; int minute = MehPreferencesManager . getNotificationPreferenceMinute ( context ) ; scheduleDailyReminder ( context , hour , minute ) ; }" "Restore the daily reminder , with the times already in preferences . Useful for device reboot or switched on from the settings screen" +@ Override public boolean isActive ( ) { return amIActive ; } Used by the Whitebox GUI to tell if this plugin is still running . +BarChart ( ) { } Instantiates a new bar chart . +"public boolean isTransactionRelevant ( Transaction tx ) throws ScriptException { lock . lock ( ) ; try { return tx . getValueSentFromMe ( this ) . signum ( ) > 0 || tx . getValueSentToMe ( this ) . signum ( ) > 0 || ! findDoubleSpendsAgainst ( tx , transactions ) . isEmpty ( ) ; } finally { lock . unlock ( ) ; } }" "< p > Returns true if the given transaction sends coins to any of our keys , or has inputs spending any of our outputs , and also returns true if tx has inputs that are spending outputs which are not ours but which are spent by pending transactions. < /p > < p > Note that if the tx has inputs containing one of our keys , but the connected transaction is not in the wallet , it will not be considered relevant. < /p >" +"public void free ( GL2 gl ) { if ( vbos [ 0 ] >= 0 ) { gl . glDeleteBuffers ( 1 , vbos , 0 ) ; } vbos [ 0 ] = - 1 ; }" Free all memory allocations . +"public Vector3 ( float x , float y , float z ) { this . set ( x , y , z ) ; }" Creates a vector with the given components +protected S_ActionImpl ( ) { super ( ) ; } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +public void clear ( int maximumCapacity ) { if ( capacity <= maximumCapacity ) { clear ( ) ; return ; } zeroValue = null ; hasZeroValue = false ; size = 0 ; resize ( maximumCapacity ) ; } Clears the map and reduces the size of the backing arrays to be the specified capacity if they are larger . +"public void bulkLoad ( DBIDs ids ) { if ( ids . size ( ) == 0 ) { return ; } assert ( root == null ) : ""Tree already initialized."" ; DBIDIter it = ids . iter ( ) ; DBID first = DBIDUtil . deref ( it ) ; ModifiableDoubleDBIDList candidates = DBIDUtil . newDistanceDBIDList ( ids . size ( ) - 1 ) ; for ( it . advance ( ) ; it . valid ( ) ; it . advance ( ) ) { candidates . add ( distance ( first , it ) , it ) ; } root = bulkConstruct ( first , Integer . MAX_VALUE , candidates ) ; }" Bulk-load the index . +"protected ExtendedSolrQueryParser createEdismaxQueryParser ( QParser qParser , String field ) { return new ExtendedSolrQueryParser ( qParser , field ) ; }" "Creates an instance of ExtendedSolrQueryParser , the query parser that 's going to be used to parse the query ." +"protected void appendSummary ( StringBuffer buffer , String fieldName , long [ ] array ) { appendSummarySize ( buffer , fieldName , array . length ) ; }" < p > Append to the < code > toString < /code > a summary of a < code > long < /code > array. < /p > +protected UndoableEdit editToBeRedone ( ) { int count = edits . size ( ) ; int i = indexOfNextAdd ; while ( i < count ) { UndoableEdit edit = edits . elementAt ( i ++ ) ; if ( edit . isSignificant ( ) ) { return edit ; } } return null ; } Returns the the next significant edit to be redone if < code > redo < /code > is invoked . This returns < code > null < /code > if there are no edits to be redone . +"public void actionPerformed ( ActionEvent e ) { Box b1 = Box . createVerticalBox ( ) ; Version currentVersion = Version . currentViewableVersion ( ) ; String copyright = LicenseUtils . copyright ( ) ; copyright = copyright . replaceAll ( ""\n"" , ""
"" ) ; String latestVersion = LatestClient . getInstance ( ) . getLatestResult ( 60 ) ; latestVersion = latestVersion . replaceAll ( ""\n"" , ""
"" ) ; JLabel label = new JLabel ( ) ; label . setText ( """" + ""Tetrad "" + currentVersion + """" + ""
"" + ""
Laboratory for Symbolic and Educational Computing"" + ""
Department of Philosophy"" + ""
Carnegie Mellon University"" + ""
"" + ""
Project Direction: Clark Glymour, Richard Scheines, Peter Spirtes"" + ""
Lead Developer: Joseph Ramsey"" + ""
"" + copyright + ""
"" + latestVersion + """" ) ; label . setBackground ( Color . LIGHT_GRAY ) ; label . setFont ( new Font ( ""Dialog"" , Font . PLAIN , 12 ) ) ; label . setBorder ( new CompoundBorder ( new LineBorder ( Color . DARK_GRAY ) , new EmptyBorder ( 10 , 10 , 10 , 10 ) ) ) ; b1 . add ( label ) ; JOptionPane . showMessageDialog ( JOptionUtils . centeringComp ( ) , b1 , ""About Tetrad..."" , JOptionPane . PLAIN_MESSAGE ) ; }" Closes the frontmost session of this action 's desktop . +private void redrawMarkers ( ) { UI . execute ( null ) ; } Redraw all markers and set them straight to their current locations without animations . +public void addToolTipSeries ( List toolTips ) { this . toolTipSeries . add ( toolTips ) ; } Adds a list of tooltips for a series . +"static private String [ ] alphaMixedNumeric ( ) { return StringFunctions . combineStringArrays ( StringFunctions . alphaMixed ( ) , StringFunctions . numeric ) ; }" Combine the alpha mixed and numeric collections into one +long incrementInMsgs ( ) { return inMsgs . incrementAndGet ( ) ; } Increments the number of messages received on this connection . +public final void yyreset ( java . io . Reader reader ) { zzBuffer = s . array ; zzStartRead = s . offset ; zzEndRead = zzStartRead + s . count - 1 ; zzCurrentPos = zzMarkedPos = s . offset ; zzLexicalState = YYINITIAL ; zzReader = reader ; zzAtEOF = false ; } "Resets the scanner to read from a new input stream . Does not close the old reader . All internal variables are reset , the old input stream < b > can not < /b > be reused ( internal buffer is discarded and lost ) . Lexical state is set to < tt > YY_INITIAL < /tt > ." +"public IntArraySpliterator ( int [ ] array , int origin , int fence , int additionalCharacteristics ) { this . array = array ; this . index = origin ; this . fence = fence ; this . characteristics = additionalCharacteristics | Spliterator . SIZED | Spliterator . SUBSIZED ; }" Creates a spliterator covering the given array and range +"@ Override public void populateDAG ( DAG dag , Configuration conf ) { TweetsInput input = new TweetsInput ( ) ; Collector collector = new Collector ( ) ; WindowOption windowOption = new WindowOption . GlobalWindow ( ) ; ApexStream < String > tags = StreamFactory . fromInput ( input , input . output , name ( ""tweetSampler"" ) ) . flatMap ( new ExtractHashtags ( ) ) ; tags . window ( windowOption , new TriggerOption ( ) . accumulatingFiredPanes ( ) . withEarlyFiringsAtEvery ( 1 ) ) . addCompositeStreams ( ComputeTopCompletions . top ( 10 , true ) ) . print ( name ( ""console"" ) ) . endWith ( collector , collector . input , name ( ""collector"" ) ) . populateDag ( dag ) ; }" Populate the dag with High-Level API . +"public void testBug21947042 ( ) throws Exception { Connection sslConn = null ; Properties props = new Properties ( ) ; props . setProperty ( ""logger"" , ""StandardLogger"" ) ; StandardLogger . startLoggingToBuffer ( ) ; try { int searchFrom = 0 ; int found = 0 ; sslConn = getConnectionWithProps ( props ) ; if ( versionMeetsMinimum ( 5 , 7 ) ) { assertTrue ( ( ( MySQLConnection ) sslConn ) . getUseSSL ( ) ) ; assertFalse ( ( ( MySQLConnection ) sslConn ) . getVerifyServerCertificate ( ) ) ; assertTrue ( ( ( MySQLConnection ) sslConn ) . getIO ( ) . isSSLEstablished ( ) ) ; } else { assertFalse ( ( ( MySQLConnection ) sslConn ) . getUseSSL ( ) ) ; assertTrue ( ( ( MySQLConnection ) sslConn ) . getVerifyServerCertificate ( ) ) ; assertFalse ( ( ( MySQLConnection ) sslConn ) . getIO ( ) . isSSLEstablished ( ) ) ; } ResultSet rset = sslConn . createStatement ( ) . executeQuery ( ""SHOW STATUS LIKE 'ssl_cipher'"" ) ; assertTrue ( rset . next ( ) ) ; String cipher = rset . getString ( 2 ) ; System . out . println ( ""ssl_cipher="" + cipher ) ; rset = sslConn . createStatement ( ) . executeQuery ( ""SHOW STATUS LIKE 'ssl_version'"" ) ; assertTrue ( rset . next ( ) ) ; cipher = rset . getString ( 2 ) ; System . out . println ( ""ssl_version="" + cipher ) ; sslConn . close ( ) ; String log = StandardLogger . getBuffer ( ) . toString ( ) ; found = log . indexOf ( Messages . getString ( ""MysqlIO.SSLWarning"" ) , searchFrom ) ; searchFrom = found + 1 ; if ( versionMeetsMinimum ( 5 , 7 ) ) { assertTrue ( found != - 1 ) ; } props . setProperty ( ""useSSL"" , ""false"" ) ; sslConn = getConnectionWithProps ( props ) ; assertFalse ( ( ( MySQLConnection ) sslConn ) . getUseSSL ( ) ) ; assertTrue ( ( ( MySQLConnection ) sslConn ) . getVerifyServerCertificate ( ) ) ; assertFalse ( ( ( MySQLConnection ) sslConn ) . getIO ( ) . isSSLEstablished ( ) ) ; rset = sslConn . createStatement ( ) . executeQuery ( ""SHOW STATUS LIKE 'ssl_cipher'"" ) ; assertTrue ( rset . next ( ) ) ; cipher = rset . getString ( 2 ) ; System . out . println ( ""ssl_cipher="" + cipher ) ; rset = sslConn . createStatement ( ) . executeQuery ( ""SHOW STATUS LIKE 'ssl_version'"" ) ; assertTrue ( rset . next ( ) ) ; cipher = rset . getString ( 2 ) ; System . out . println ( ""ssl_version="" + cipher ) ; sslConn . close ( ) ; log = StandardLogger . getBuffer ( ) . toString ( ) ; found = log . indexOf ( Messages . getString ( ""MysqlIO.SSLWarning"" ) , searchFrom ) ; if ( found != - 1 ) { searchFrom = found + 1 ; fail ( ""Warning is not expected when useSSL is explicitly set to 'false'."" ) ; } props . setProperty ( ""useSSL"" , ""true"" ) ; props . setProperty ( ""trustCertificateKeyStoreUrl"" , ""file:src/testsuite/ssl-test-certs/test-cert-store"" ) ; props . setProperty ( ""trustCertificateKeyStoreType"" , ""JKS"" ) ; props . setProperty ( ""trustCertificateKeyStorePassword"" , ""password"" ) ; sslConn = getConnectionWithProps ( props ) ; assertTrue ( ( ( MySQLConnection ) sslConn ) . getUseSSL ( ) ) ; assertTrue ( ( ( MySQLConnection ) sslConn ) . getVerifyServerCertificate ( ) ) ; assertTrue ( ( ( MySQLConnection ) sslConn ) . getIO ( ) . isSSLEstablished ( ) ) ; rset = sslConn . createStatement ( ) . executeQuery ( ""SHOW STATUS LIKE 'ssl_cipher'"" ) ; assertTrue ( rset . next ( ) ) ; cipher = rset . getString ( 2 ) ; System . out . println ( ""ssl_cipher="" + cipher ) ; rset = sslConn . createStatement ( ) . executeQuery ( ""SHOW STATUS LIKE 'ssl_version'"" ) ; assertTrue ( rset . next ( ) ) ; cipher = rset . getString ( 2 ) ; System . out . println ( ""ssl_version="" + cipher ) ; sslConn . close ( ) ; log = StandardLogger . getBuffer ( ) . toString ( ) ; found = log . indexOf ( Messages . getString ( ""MysqlIO.SSLWarning"" ) , searchFrom ) ; if ( found != - 1 ) { searchFrom = found + 1 ; fail ( ""Warning is not expected when useSSL is explicitly set to 'false'."" ) ; } } finally { StandardLogger . dropBuffer ( ) ; } }" "Tests fix for BUG # 21947042 , PREFER TLS WHERE SUPPORTED BY MYSQL SERVER . Requires test certificates from testsuite/ssl-test-certs to be installed on the server being tested ." +"public JComponent createEmbeddedPropertyGUI ( String prefix , Properties props , Properties info ) { if ( Debug . debugging ( ""inspectordetail"" ) ) { Debug . output ( ""Inspector creating GUI for "" + prefix + ""\nPROPERTIES "" + props + ""\nPROP INFO "" + info ) ; } String propertyList = info . getProperty ( PropertyConsumer . initPropertiesProperty ) ; Vector < String > sortedKeys ; if ( propertyList != null ) { Vector < String > propertiesToShow = PropUtils . parseSpacedMarkers ( propertyList ) ; for ( int i = 0 ; i < propertiesToShow . size ( ) ; i ++ ) { propertiesToShow . set ( i , prefix + ""."" + propertiesToShow . get ( i ) ) ; } sortedKeys = propertiesToShow ; } else { sortedKeys = sortKeys ( props . keySet ( ) ) ; } editors = new Hashtable < String , PropertyEditor > ( sortedKeys . size ( ) ) ; JPanel component = new JPanel ( ) ; component . setLayout ( new BorderLayout ( ) ) ; JPanel propertyPanel = new JPanel ( ) ; GridBagLayout gridbag = new GridBagLayout ( ) ; GridBagConstraints c = new GridBagConstraints ( ) ; c . insets = new Insets ( 2 , 10 , 2 , 10 ) ; propertyPanel . setLayout ( gridbag ) ; int i = 0 ; for ( String prop : sortedKeys ) { String marker = prop ; if ( prefix != null && prop . startsWith ( prefix ) ) { marker = prop . substring ( prefix . length ( ) + 1 ) ; } if ( marker . startsWith ( ""."" ) ) { marker = marker . substring ( 1 ) ; } String editorMarker = marker + PropertyConsumer . ScopedEditorProperty ; String editorClass = info . getProperty ( editorMarker ) ; if ( editorClass == null ) { editorClass = defaultEditorClass ; } Class < ? > propertyEditorClass = null ; PropertyEditor editor = null ; try { propertyEditorClass = Class . forName ( editorClass ) ; editor = ( PropertyEditor ) propertyEditorClass . newInstance ( ) ; if ( editor instanceof PropertyConsumer ) { ( ( PropertyConsumer ) editor ) . setProperties ( marker , info ) ; } editors . put ( prop , editor ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; editorClass = null ; } Component editorFace = null ; if ( editor != null && editor . supportsCustomEditor ( ) ) { editorFace = editor . getCustomEditor ( ) ; } else { editorFace = new JLabel ( i18n . get ( Inspector . class , ""Does_not_support_custom_editor"" , ""Does not support custom editor"" ) ) ; } if ( editor != null ) { Object propVal = props . get ( prop ) ; if ( Debug . debugging ( ""inspector"" ) ) { Debug . output ( ""Inspector loading "" + prop + ""("" + propVal + "")"" ) ; } editor . setValue ( propVal ) ; } String labelMarker = marker + PropertyConsumer . LabelEditorProperty ; String labelText = info . getProperty ( labelMarker ) ; if ( labelText == null ) { labelText = marker ; } JLabel label = new JLabel ( labelText + "":"" ) ; label . setHorizontalAlignment ( SwingConstants . RIGHT ) ; c . gridx = 0 ; c . gridy = i ++ ; c . weightx = 0 ; c . fill = GridBagConstraints . NONE ; c . anchor = GridBagConstraints . EAST ; gridbag . setConstraints ( label , c ) ; propertyPanel . add ( label ) ; c . gridx = 1 ; c . anchor = GridBagConstraints . WEST ; c . fill = GridBagConstraints . HORIZONTAL ; c . weightx = 1f ; gridbag . setConstraints ( editorFace , c ) ; propertyPanel . add ( editorFace ) ; String toolTip = ( String ) info . get ( marker ) ; label . setToolTipText ( toolTip == null ? i18n . get ( Inspector . class , ""No_further_information_available"" , ""No further information available."" ) : toolTip ) ; } JScrollPane scrollPane = new JScrollPane ( propertyPanel , ScrollPaneConstants . VERTICAL_SCROLLBAR_AS_NEEDED , ScrollPaneConstants . HORIZONTAL_SCROLLBAR_NEVER ) ; scrollPane . setBorder ( null ) ; scrollPane . setAlignmentY ( Component . TOP_ALIGNMENT ) ; component . add ( scrollPane , BorderLayout . CENTER ) ; return component ; }" Creates a JComponent with the properties to be changed . This component is suitable for inclusion into a GUI . Do n't use this method directly ! Use the createPropertyGUI ( PropertyConsumer ) instead . You will get a NullPointerException if you use this method without setting the PropertyConsumer in the Inspector . +"public void onScanImageClick ( View v ) { Intent intent = new Intent ( this , ScanImageActivity . class ) ; intent . putExtra ( ExtrasKeys . EXTRAS_LICENSE_KEY , LICENSE_KEY ) ; intent . putExtra ( ExtrasKeys . EXTRAS_RECOGNITION_SETTINGS , mRecognitionSettings ) ; startActivityForResult ( intent , MY_REQUEST_CODE ) ; }" Handler for `` Scan Image '' button +"public boolean isReadOnly ( ) { Object oo = get_Value ( COLUMNNAME_IsReadOnly ) ; if ( oo != null ) { if ( oo instanceof Boolean ) return ( ( Boolean ) oo ) . booleanValue ( ) ; return ""Y"" . equals ( oo ) ; } return false ; }" Get Read Only . +"public static < K , V > Map < K , V > asSynchronized ( Map < K , V > self ) { return Collections . synchronizedMap ( self ) ; }" A convenience method for creating a synchronized Map . +private boolean isRecursive ( Nonterminal nonterm ) { return comp . getNodes ( ) . contains ( nonterm ) ; } Return true if the nonterminal is recursive . +"private void initInfo ( int record_id , String value ) { if ( ! ( record_id == 0 ) && value != null && value . length ( ) > 0 ) { log . severe ( ""Received both a record_id and a value: "" + record_id + "" - "" + value ) ; } if ( ! ( record_id == 0 ) ) { fieldID = record_id ; } else { if ( value != null && value . length ( ) > 0 ) { fDocumentNo . setValue ( value ) ; } else { String id ; id = Env . getContext ( Env . getCtx ( ) , p_WindowNo , p_TabNo , ""M_InOut_ID"" , true ) ; if ( id != null && id . length ( ) != 0 && ( new Integer ( id ) . intValue ( ) > 0 ) ) { fieldID = new Integer ( id ) . intValue ( ) ; } id = Env . getContext ( Env . getCtx ( ) , p_WindowNo , p_TabNo , ""C_BPartner_ID"" , true ) ; if ( id != null && id . length ( ) != 0 && ( new Integer ( id ) . intValue ( ) > 0 ) ) fBPartner_ID . setValue ( new Integer ( id ) ) ; id = Env . getContext ( Env . getCtx ( ) , p_WindowNo , p_TabNo , ""M_Shipper_ID"" , true ) ; if ( id != null && id . length ( ) != 0 && ( new Integer ( id ) . intValue ( ) > 0 ) ) { fShipper_ID . setValue ( new Integer ( id ) . intValue ( ) ) ; } } } }" General Init +public IssueMatcher add ( ) { IssueMatcher issueMatcher = new IssueMatcher ( ) ; issueMatchers . add ( issueMatcher ) ; return issueMatcher ; } Creates a new issue matcher and adds it to this matcher . +protected ParameterizedPropertyAccessExpression_IMImpl ( ) { super ( ) ; } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"private void loadFinishScreen ( ) { CoordinatorLayout . LayoutParams lp = new CoordinatorLayout . LayoutParams ( CoordinatorLayout . LayoutParams . WRAP_CONTENT , CoordinatorLayout . LayoutParams . WRAP_CONTENT ) ; mFloatingActionButton . setLayoutParams ( lp ) ; mFloatingActionButton . setVisibility ( View . INVISIBLE ) ; NestedScrollView contentLayout = ( NestedScrollView ) findViewById ( R . id . challenge_rootcontainer ) ; if ( contentLayout != null ) { contentLayout . removeAllViews ( ) ; View view = getLayoutInflater ( ) . inflate ( R . layout . fragment_finish_challenge , contentLayout , false ) ; contentLayout . addView ( view ) ; } }" Loads the finish screen and unloads all other screens +"private void compactSegment ( Segment segment , OffsetPredicate predicate , Segment compactSegment ) { for ( long i = segment . firstIndex ( ) ; i <= segment . lastIndex ( ) ; i ++ ) { checkEntry ( i , segment , predicate , compactSegment ) ; } }" Compacts the given segment . +"public static Class < ? > forName ( String name , ClassLoader classLoader ) throws ClassNotFoundException , LinkageError { Assert . notNull ( name , ""Name must not be null"" ) ; Class < ? > clazz = resolvePrimitiveClassName ( name ) ; if ( clazz == null ) { clazz = commonClassCache . get ( name ) ; } if ( clazz != null ) { return clazz ; } if ( name . endsWith ( ARRAY_SUFFIX ) ) { String elementClassName = name . substring ( 0 , name . length ( ) - ARRAY_SUFFIX . length ( ) ) ; Class < ? > elementClass = forName ( elementClassName , classLoader ) ; return Array . newInstance ( elementClass , 0 ) . getClass ( ) ; } if ( name . startsWith ( NON_PRIMITIVE_ARRAY_PREFIX ) && name . endsWith ( "";"" ) ) { String elementName = name . substring ( NON_PRIMITIVE_ARRAY_PREFIX . length ( ) , name . length ( ) - 1 ) ; Class < ? > elementClass = forName ( elementName , classLoader ) ; return Array . newInstance ( elementClass , 0 ) . getClass ( ) ; } if ( name . startsWith ( INTERNAL_ARRAY_PREFIX ) ) { String elementName = name . substring ( INTERNAL_ARRAY_PREFIX . length ( ) ) ; Class < ? > elementClass = forName ( elementName , classLoader ) ; return Array . newInstance ( elementClass , 0 ) . getClass ( ) ; } ClassLoader classLoaderToUse = classLoader ; if ( classLoaderToUse == null ) { classLoaderToUse = getDefaultClassLoader ( ) ; } try { return classLoaderToUse . loadClass ( name ) ; } catch ( ClassNotFoundException ex ) { int lastDotIndex = name . lastIndexOf ( '.' ) ; if ( lastDotIndex != - 1 ) { String innerClassName = name . substring ( 0 , lastDotIndex ) + '$' + name . substring ( lastDotIndex + 1 ) ; try { return classLoaderToUse . loadClass ( innerClassName ) ; } catch ( ClassNotFoundException ex2 ) { } } throw ex ; } }" "Replacement for < code > Class.forName ( ) < /code > that also returns Class instances for primitives ( e.g . `` int '' ) and array class names ( e.g . `` String [ ] '' ) . Furthermore , it is also capable of resolving inner class names in Java source style ( e.g . `` java.lang.Thread.State '' instead of `` java.lang.Thread $ State '' ) ." +"public String toString ( int indentFactor ) throws JSONException { return toString ( indentFactor , 0 ) ; }" Make a prettyprinted JSON text of this JSONObject . < p > Warning : This method assumes that the data structure is acyclical . +"@ SuppressWarnings ( ""MethodWithMultipleReturnPoints"" ) public static boolean checkSu ( ) { if ( ! new File ( ""/system/bin/su"" ) . exists ( ) && ! new File ( ""/system/xbin/su"" ) . exists ( ) ) { Log . e ( TAG , ""su binary does not exist!!!"" ) ; return false ; } try { if ( runSuCommand ( ""ls /data/app-private"" ) . success ( ) ) { Log . i ( TAG , "" SU exists and we have permission"" ) ; return true ; } else { Log . i ( TAG , "" SU exists but we don't have permission"" ) ; return false ; } } catch ( NullPointerException e ) { Log . e ( TAG , ""NullPointer throw while looking for su binary"" , e ) ; return false ; } }" Checks device for SuperUser permission +"public String toString ( int indentFactor ) throws JSONException { StringWriter sw = new StringWriter ( ) ; synchronized ( sw . getBuffer ( ) ) { return this . write ( sw , indentFactor , 0 ) . toString ( ) ; } }" Make a prettyprinted JSON text of this JSONArray . Warning : This method assumes that the data structure is acyclical . +public Boolean isHttpSupportInformation ( ) { return httpSupportInformation ; } Ruft den Wert der httpSupportInformation-Eigenschaft ab . +"public static URLConnection createConnectionToURL ( final String url , final Map < String , String > requestHeaders ) throws IOException { final URL connectionURL = URLUtility . stringToUrl ( url ) ; if ( connectionURL == null ) { throw new IOException ( ""Invalid url format: "" + url ) ; } final URLConnection urlConnection = connectionURL . openConnection ( ) ; urlConnection . setConnectTimeout ( CONNECTION_TIMEOUT ) ; urlConnection . setReadTimeout ( READ_TIMEOUT ) ; if ( requestHeaders != null ) { for ( final Map . Entry < String , String > entry : requestHeaders . entrySet ( ) ) { urlConnection . setRequestProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return urlConnection ; }" Create URLConnection instance . +public ASN1Primitive toASN1Primitive ( ) { try { if ( certificateType == profileType ) { return profileToASN1Object ( ) ; } if ( certificateType == requestType ) { return requestToASN1Object ( ) ; } } catch ( IOException e ) { return null ; } return null ; } create a `` request '' or `` profile '' type Iso7816CertificateBody according to the variables sets . +public Builder mapper ( final Mapper < ObjectMapper > mapper ) { this . mapper = mapper ; return this ; } Override all of the builder options with this mapper . If this value is set to something other than null then that value will be used to construct the writer . +"private int [ ] [ ] div ( int [ ] a , int [ ] f ) { int df = computeDegree ( f ) ; int da = computeDegree ( a ) + 1 ; if ( df == - 1 ) { throw new ArithmeticException ( ""Division by zero."" ) ; } int [ ] [ ] result = new int [ 2 ] [ ] ; result [ 0 ] = new int [ 1 ] ; result [ 1 ] = new int [ da ] ; int hc = headCoefficient ( f ) ; hc = field . inverse ( hc ) ; result [ 0 ] [ 0 ] = 0 ; System . arraycopy ( a , 0 , result [ 1 ] , 0 , result [ 1 ] . length ) ; while ( df <= computeDegree ( result [ 1 ] ) ) { int [ ] q ; int [ ] coeff = new int [ 1 ] ; coeff [ 0 ] = field . mult ( headCoefficient ( result [ 1 ] ) , hc ) ; q = multWithElement ( f , coeff [ 0 ] ) ; int n = computeDegree ( result [ 1 ] ) - df ; q = multWithMonomial ( q , n ) ; coeff = multWithMonomial ( coeff , n ) ; result [ 0 ] = add ( coeff , result [ 0 ] ) ; result [ 1 ] = add ( q , result [ 1 ] ) ; } return result ; }" Compute the result of the division of two polynomials over the field < tt > GF ( 2^m ) < /tt > . +"public static short toShort ( byte [ ] bytes , int start ) { return toShort ( bytes [ start ] , bytes [ start + 1 ] ) ; }" Returns short from given array of bytes . < br > Array must have at least start + 2 elements in it . +"public void addAttribute ( AttributedCharacterIterator . Attribute attribute , Object value , int start , int end ) { if ( attribute == null ) { throw new NullPointerException ( ""attribute == null"" ) ; } if ( start < 0 || end > text . length ( ) || start >= end ) { throw new IllegalArgumentException ( ) ; } if ( value == null ) { return ; } List < Range > ranges = attributeMap . get ( attribute ) ; if ( ranges == null ) { ranges = new ArrayList < Range > ( 1 ) ; ranges . add ( new Range ( start , end , value ) ) ; attributeMap . put ( attribute , ranges ) ; return ; } ListIterator < Range > it = ranges . listIterator ( ) ; while ( it . hasNext ( ) ) { Range range = it . next ( ) ; if ( end <= range . start ) { it . previous ( ) ; break ; } else if ( start < range . end || ( start == range . end && value . equals ( range . value ) ) ) { Range r1 = null , r3 ; it . remove ( ) ; r1 = new Range ( range . start , start , range . value ) ; r3 = new Range ( end , range . end , range . value ) ; while ( end > range . end && it . hasNext ( ) ) { range = it . next ( ) ; if ( end <= range . end ) { if ( end > range . start || ( end == range . start && value . equals ( range . value ) ) ) { it . remove ( ) ; r3 = new Range ( end , range . end , range . value ) ; break ; } } else { it . remove ( ) ; } } if ( value . equals ( r1 . value ) ) { if ( value . equals ( r3 . value ) ) { it . add ( new Range ( r1 . start < start ? r1 . start : start , r3 . end > end ? r3 . end : end , r1 . value ) ) ; } else { it . add ( new Range ( r1 . start < start ? r1 . start : start , end , r1 . value ) ) ; if ( r3 . start < r3 . end ) { it . add ( r3 ) ; } } } else { if ( value . equals ( r3 . value ) ) { if ( r1 . start < r1 . end ) { it . add ( r1 ) ; } it . add ( new Range ( start , r3 . end > end ? r3 . end : end , r3 . value ) ) ; } else { if ( r1 . start < r1 . end ) { it . add ( r1 ) ; } it . add ( new Range ( start , end , value ) ) ; if ( r3 . start < r3 . end ) { it . add ( r3 ) ; } } } return ; } } it . add ( new Range ( start , end , value ) ) ; }" Applies a given attribute to the given range of this string . +"@ Override public Double hincrByFloat ( final String key , final String field , final double value ) { checkIsInMultiOrPipeline ( ) ; client . hincrByFloat ( key , field , value ) ; final String dval = client . getBulkReply ( ) ; return ( dval != null ? new Double ( dval ) : null ) ; }" "Increment the number stored at field in the hash at key by a double precision floating point value . If key does not exist , a new key holding a hash is created . If field does not exist or holds a string , the value is set to 0 before applying the operation . Since the value argument is signed you can use this command to perform both increments and decrements . < p > The range of values supported by HINCRBYFLOAT is limited to double precision floating point values . < p > < b > Time complexity : < /b > O ( 1 )" +public DrawerBuilder withFooter ( @ NonNull View footerView ) { this . mFooterView = footerView ; return this ; } Add a footer to the DrawerBuilder ListView . This can be any view +"@ Override public int compareTo ( final Object obj ) throws ClassCastException { final URI another = ( URI ) obj ; if ( ! equals ( _authority , another . getRawAuthority ( ) ) ) { return - 1 ; } return toString ( ) . compareTo ( another . toString ( ) ) ; }" Compare this URI to another object . +public boolean isNavigationAtBottom ( ) { return ( mSmallestWidthDp >= 600 || mInPortrait ) ; } Should a navigation bar appear at the bottom of the screen in the current device configuration ? A navigation bar may appear on the right side of the screen in certain configurations . +"@ Override public void execute ( String filePath ) { final CurrentProject currentProject = appContext . getCurrentProject ( ) ; if ( filePath != null && ! filePath . startsWith ( ""/"" ) ) { filePath = ""/"" . concat ( filePath ) ; } if ( currentProject != null ) { String fullPath = currentProject . getRootProject ( ) . getPath ( ) + filePath ; log . debug ( ""Open file {0}"" , fullPath ) ; currentProject . getCurrentTree ( ) . getNodeByPath ( fullPath , new TreeNodeAsyncCallback ( ) ) ; } }" Open a file for the current given path . +"public void executionDetailsEnd ( final ConcurrentHashMap < Integer , TradeOrder > tradeOrders ) { try { Tradingday todayTradingday = m_tradingdays . getTradingday ( TradingCalendar . getTradingDayStart ( TradingCalendar . getDateTimeNowMarketTimeZone ( ) ) , TradingCalendar . getTradingDayEnd ( TradingCalendar . getDateTimeNowMarketTimeZone ( ) ) ) ; if ( null == todayTradingday ) { return ; } tradingdayPanel . doRefresh ( todayTradingday ) ; tradingdayPanel . doRefreshTradingdayTable ( todayTradingday ) ; } catch ( Exception ex ) { this . setErrorMessage ( ""Error starting PositionManagerRule."" , ex . getMessage ( ) , ex ) ; } }" This method is fired when the Brokermodel has completed the request for Execution Details see doFetchExecution or connectionOpened i.e from a BrokerModel event all executions for the filter have now been received . Check to see if we need to close any trades for these order fills . +public void successfullyCreated ( ) { if ( notification != null ) { notification . setStatus ( SUCCESS ) ; notification . setTitle ( locale . createSnapshotSuccess ( ) ) ; } } Changes notification state to successfully finished . +"public HybridTimestampFactory ( int counterBits ) { if ( counterBits < 0 || counterBits > 31 ) { throw new IllegalArgumentException ( ""counterBits must be in [0:31]"" ) ; } lastTimestamp = 0L ; this . counterBits = counterBits ; maxCounter = BigInteger . valueOf ( 2 ) . pow ( counterBits ) . intValue ( ) - 1 ; log . warn ( ""#counterBits="" + counterBits + "", maxCounter="" + maxCounter ) ; }" Allows up to < code > 2^counterBits < /code > distinct timestamps per millisecond . +@ Override public void clear ( ) { this . _map . clear ( ) ; } Empties the map . +"public boolean removeElement ( int s ) { if ( null == m_map ) return false ; for ( int i = 0 ; i < m_firstFree ; i ++ ) { int node = m_map [ i ] ; if ( node == s ) { if ( i > m_firstFree ) System . arraycopy ( m_map , i + 1 , m_map , i - 1 , m_firstFree - i ) ; else m_map [ i ] = DTM . NULL ; m_firstFree -- ; return true ; } } return false ; }" "Removes the first occurrence of the argument from this vector . If the object is found in this vector , each component in the vector with an index greater or equal to the object 's index is shifted downward to have an index one smaller than the value it had previously ." +"private void addSingleton ( TempCluster clus , DBIDRef id , double dist , boolean asCluster ) { if ( asCluster ) { clus . addChild ( makeSingletonCluster ( id , dist ) ) ; } else { clus . add ( id ) ; } clus . depth = dist ; }" "Add a singleton object , as point or cluster ." +public int size ( ) { return values . length ; } Returns the number of values in this kernel . +"private void testServerJoinLate ( Member . Type type , CopycatServer . State state ) throws Throwable { createServers ( 3 ) ; CopycatClient client = createClient ( ) ; submit ( client , 0 , 1000 ) ; await ( 30000 ) ; CopycatServer joiner = createServer ( nextMember ( type ) ) ; joiner . onStateChange ( null ) ; joiner . join ( members . stream ( ) . map ( null ) . collect ( Collectors . toList ( ) ) ) . thenRun ( null ) ; await ( 30000 , 2 ) ; }" Tests joining a server after many entries have been committed . +"fun createRadioButton(x: Int, y: Int, diameter: Int): Shape? { return createEllipseInternal(x, y, diameter, diameter) }" Return a path for a radio button 's concentric sections . +"@DSComment(""From safe class list"") @DSSafe(DSCat.SAFE_LIST) @DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2013-12-30 12:57:11.638 -0500"", hash_original_method = ""3CEC44303CC022BBEC9F119BC403FDBC"", hash_generated_method = ""FD349EDA389F166F5AB5B32AD7B69928"" ) fun size(): Int { return al.size() }" Returns the number of elements in this set . +"fun formatRateString(rate: Float): String? { return String.format(Locale.US, ""%.2fx"", rate) }" Get the formatted current playback speed in the form of 1.00x +"@Throws(FileNotFoundException::class) private fun decodeImageForOption(resolver: ContentResolver, uri: Uri): BitmapFactory.Options? { var stream: InputStream? = null return try { stream = resolver.openInputStream(uri) val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeStream(stream, EMPTY_RECT, options) options.inJustDecodeBounds = false options } finally { closeSafe(stream) } }" Decode image from uri using `` inJustDecodeBounds '' to get the image dimensions . +fun FinalSQLString(sqlstring: BasicSQLString) { this.delegate = sqlstring } Should only be called inside SQLString because this class essentially verifies that we 've checked for updates . +fun loadArgArray() { push(argumentTypes.length) newArray(jdk.internal.org.objectweb.asm.commons.InstructionAdapter.OBJECT_TYPE) for (i in 0 until argumentTypes.length) { dup() push(i) loadArg(i) jdk.internal.vm.compiler.word.impl.WordBoxFactory.box( argumentTypes.get(i) ) arrayStore(jdk.internal.org.objectweb.asm.commons.InstructionAdapter.OBJECT_TYPE) } } "Generates the instructions to load all the method arguments on the stack , as a single object array ." +"@Throws(ServletException::class, IOException::class) fun doGet(request: HttpServletRequest?, response: HttpServletResponse?) { WebUtil.createLoginPage(request, response, this, null, null) }" Process the HTTP Get request +"private fun DeferredFileOutputStream( threshold: Int, outputFile: File, prefix: String, suffix: String, directory: File ) { super(threshold) outputFile = outputFile memoryOutputStream = ByteArrayOutputStream() currentOutputStream = memoryOutputStream prefix = prefix suffix = suffix directory = directory }" "Constructs an instance of this class which will trigger an event at the specified threshold , and save data either to a file beyond that point ." +"fun testSetSystemScope() { val systemScope: IdentityScope = IdentityScope.getSystemScope() try { `is` = IdentityScopeStub(""Aleksei Semenov"") IdentityScopeStub.mySetSystemScope(`is`) assertSame(`is`, IdentityScope.getSystemScope()) } finally { IdentityScopeStub.mySetSystemScope(systemScope) } }" check that if permission given - set/get works if permission is denied than SecurityException is thrown +"@JvmStatic fun main(args: Array) { runEvaluator(WrapperSubsetEval(), args) }" Main method for testing this class . +"fun v(tag: String?, msg: String?, vararg args: Any?) { var msg = msg if (sLevel > LEVEL_VERBOSE) { return } if (args.size > 0) { msg = String.format(msg!!, *args) } Log.v(tag, msg) }" Send a VERBOSE log message . +"@DSComment(""Package priviledge"") @DSBan(DSCat.DEFAULT_MODIFIER) @DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"",generated_on = ""2013-12-30 12:58:04.267 -0500"", hash_original_method = ""2CE5F24A4C571BEECB25C40400E44908"", hash_generated_method = ""A3579B97578194B5EA0183D0F747142C"" ) fun computeNextElement() { while (true) { if (currentBits !== 0) { mask = currentBits and -currentBits return } else if (++index < bits.length) { currentBits = bits.get(index) } else { mask = 0 return } } }" "Assigns mask and index to the next available value , cycling currentBits as necessary ." +"fun HierarchyEvent( source: Component?, id: Int, changed: Component, changedParent: Container, changeFlags: Long ) { super(source, id) changed = changed changedParent = changedParent changeFlags = changeFlags }" Constructs an < code > HierarchyEvent < /code > object to identify a change in the < code > Component < /code > hierarchy . < p > This method throws an < code > IllegalArgumentException < /code > if < code > source < /code > is < code > null < /code > . +fun step(state: SimState?) {} "This method is performed when the next step for the agent is computed . This agent does nothing , so nothing is inside the body of the method ." +fun resetRuntime() { currentTime = 1392409281320L wasTimeAccessed = false hashKeys.clear() restoreProperties() needToRestoreProperties = false } Reset runtime to initial state +"fun ExpandCaseMultipliersAction(editor: DataEditor?) { super(""Expand Case Multipliers"") if (editor == null) { throw NullPointerException() } this.dataEditor = editor }" Creates a new action to split by collinear columns . +fun ScaleFake() {} Creates a new instance of ScaleFake +protected fun ArrayElementImpl() { super() } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"fun FilterRowIterator(rows: IntIterator, t: Table, p: Predicate) { this.predicate = p rows = rows t = t next = advance() }" Create a new FilterRowIterator . +"@Throws(JasperException::class) private fun scanJar(conn: JarURLConnection, tldNames: List?, isLocal: Boolean) { val resourcePath: String = conn.getJarFileURL().toString() var tldInfos: Array = jarTldCacheLocal.get(resourcePath) if (tldInfos != null && tldInfos.size == 0) { try { conn.getJarFile().close() } catch (ex: IOException) { } return } if (tldInfos == null) { var jarFile: JarFile? = null val tldInfoA: ArrayList = ArrayList() try { jarFile = conn.getJarFile() if (tldNames != null) { for (tldName in tldNames) { val entry: JarEntry = jarFile.getJarEntry(tldName) val stream: InputStream = jarFile.getInputStream(entry) tldInfoA.add(scanTld(resourcePath, tldName, stream)) } } else { val entries: Enumeration = jarFile.entries() while (entries.hasMoreElements()) { val entry: JarEntry = entries.nextElement() val name: String = entry.getName() if (!name.startsWith(""META-INF/"")) continue if (!name.endsWith("".tld"")) continue val stream: InputStream = jarFile.getInputStream(entry) tldInfoA.add(scanTld(resourcePath, name, stream)) } } } catch (ex: IOException) { if (resourcePath.startsWith(FILE_PROTOCOL) && !File(resourcePath).exists()) { if (log.isLoggable(Level.WARNING)) { log.log( Level.WARNING, Localizer.getMessage(""jsp.warn.nojar"", resourcePath), ex ) } } else { throw JasperException( Localizer.getMessage(""jsp.error.jar.io"", resourcePath), ex ) } } finally { if (jarFile != null) { try { jarFile.close() } catch (t: Throwable) { } } } tldInfos = tldInfoA.toArray(arrayOfNulls(tldInfoA.size())) jarTldCacheLocal.put(resourcePath, tldInfos) if (!isLocal) { jarTldCache.put(resourcePath, tldInfos) } } for (tldInfo in tldInfos) { if (scanListeners) { addListener(tldInfo, isLocal) } mapTldLocation(resourcePath, tldInfo, isLocal) } }" "Scans the given JarURLConnection for TLD files located in META-INF ( or a subdirectory of it ) . If the scanning in is done as part of the ServletContextInitializer , the listeners in the tlds in this jar file are added to the servlet context , and for any TLD that has a < uri > element , an implicit map entry is added to the taglib map ." +fun cosft1(y: DoubleArray?) { com.nr.fft.FFT.cosft1(y) } "Calculates the cosine transform of a set y [ 0..n ] of real-valued data points . The transformed data replace the original data in array y. n must be a power of 2 . This program , without changes , also calculates the inverse cosine transform , but in this case the output array should be multiplied by 2/n ." +fun stop() { mRunning = false mStop = true } Stops the animation in place . It does not snap the image to its final translation . +operator fun hasNext(): Boolean { return cursor > 0 } This is used to determine if the cursor has reached the start of the list . When the cursor reaches the start of the list then this method returns false . +"protected fun onFinished(player: Player, successful: Boolean) { if (successful) { val itemName: String = items.get(Rand.rand(items.length)) val item: Item = SingletonRepository.getEntityManager().getItem(itemName) var amount = 1 if (itemName == ""dark dagger"" || itemName == ""horned golden helmet"") { item.setBoundTo(player.getName()) } else if (itemName == ""money"") { amount = Rand.roll1D100() (item as StackableItem).setQuantity(amount) } player.equipOrPutOnGround(item) player.incObtainedForItem(item.getName(), item.getQuantity()) SingletonRepository.getAchievementNotifier().onObtain(player) player.sendPrivateText( ""You were lucky and found "" + com.sun.org.apache.xerces.internal.xni.grammars.Grammar.quantityplnoun( amount, itemName, ""a"" ).toString() + ""."" ) } else { player.sendPrivateText(""Your wish didn't come true."") } }" Called when the activity has finished . +"fun saveWalletAndWalletInfoSimple( perWalletModelData: WalletData, walletFilename: String?, walletInfoFilename: String? ) { val walletFile = File(walletFilename) val walletInfo: WalletInfoData = perWalletModelData.getWalletInfo() var fileOutputStream: FileOutputStream? = null try { if (perWalletModelData.getWallet() != null) { if (walletInfo != null) { val walletDescriptionInInfoFile: String = walletInfo.getProperty(WalletInfoData.DESCRIPTION_PROPERTY) if (walletDescriptionInInfoFile != null) { perWalletModelData.getWallet().setDescription(walletDescriptionInInfoFile) } } log.debug( ""Saving wallet file '"" + walletFile.getAbsolutePath().toString() + ""' ..."" ) if (MultiBitWalletVersion.SERIALIZED === walletInfo.getWalletVersion()) { throw WalletSaveException( ""Cannot save wallet '"" + walletFile.getAbsolutePath() .toString() + ""'. Serialized wallets are no longer supported."" ) } else { var walletIsActuallyEncrypted = false val wallet: Wallet = perWalletModelData.getWallet() for (key in wallet.getKeychain()) { if (key.isEncrypted()) { walletIsActuallyEncrypted = true break } } if (walletIsActuallyEncrypted) { walletInfo.setWalletVersion(MultiBitWalletVersion.PROTOBUF_ENCRYPTED) } if (MultiBitWalletVersion.PROTOBUF === walletInfo.getWalletVersion()) { perWalletModelData.getWallet().saveToFile(walletFile) } else if (MultiBitWalletVersion.PROTOBUF_ENCRYPTED === walletInfo.getWalletVersion()) { fileOutputStream = FileOutputStream(walletFile) walletProtobufSerializer.writeWallet( perWalletModelData.getWallet(), fileOutputStream ) } else { throw WalletVersionException( ""Cannot save wallet '"" + perWalletModelData.getWalletFilename() .toString() + ""'. Its wallet version is '"" + walletInfo.getWalletVersion() .toString() .toString() + ""' but this version of MultiBit does not understand that format."" ) } } log.debug(""... done saving wallet file."") } } catch (ioe: IOException) { throw WalletSaveException( ""Cannot save wallet '"" + perWalletModelData.getWalletFilename(), ioe ) } finally { if (fileOutputStream != null) { try { fileOutputStream.flush() fileOutputStream.close() } catch (e: IOException) { throw WalletSaveException( ""Cannot save wallet '"" + perWalletModelData.getWalletFilename(), e ) } } } walletInfo.writeToFile(walletInfoFilename, walletInfo.getWalletVersion()) }" Simply save the wallet and wallet info files . Used for backup writes . +"@Throws(CloneNotSupportedException::class) fun clone(): Any? { val clone: DefaultIntervalXYDataset = super.clone() as DefaultIntervalXYDataset clone.seriesKeys = ArrayList(this.seriesKeys) clone.seriesList = ArrayList(this.seriesList.size()) for (i in 0 until this.seriesList.size()) { val data = this.seriesList.get(i) as Array val x = data[0] val xStart = data[1] val xEnd = data[2] val y = data[3] val yStart = data[4] val yEnd = data[5] val xx = DoubleArray(x.size) val xxStart = DoubleArray(xStart.size) val xxEnd = DoubleArray(xEnd.size) val yy = DoubleArray(y.size) val yyStart = DoubleArray(yStart.size) val yyEnd = DoubleArray(yEnd.size) System.arraycopy(x, 0, xx, 0, x.size) System.arraycopy(xStart, 0, xxStart, 0, xStart.size) System.arraycopy(xEnd, 0, xxEnd, 0, xEnd.size) System.arraycopy(y, 0, yy, 0, y.size) System.arraycopy(yStart, 0, yyStart, 0, yStart.size) System.arraycopy(yEnd, 0, yyEnd, 0, yEnd.size) clone.seriesList.add(i, arrayOf(xx, xxStart, xxEnd, yy, yyStart, yyEnd)) } return clone }" Returns a clone of this dataset . +"fun EveningActivityMovement(settings: Settings) { super(settings) super.backAllowed = false pathFinder = DijkstraPathFinder(null) mode = WALKING_TO_MEETING_SPOT_MODE nrOfMeetingSpots = settings.getInt(NR_OF_MEETING_SPOTS_SETTING) minGroupSize = settings.getInt(MIN_GROUP_SIZE_SETTING) maxGroupSize = settings.getInt(MAX_GROUP_SIZE_SETTING) val mapNodes: Array = jdk.nashorn.internal.objects.Global.getMap().getNodes() .toArray(arrayOfNulls(0)) var shoppingSpotsFile: String? = null try { shoppingSpotsFile = settings.getSetting(MEETING_SPOTS_FILE_SETTING) } catch (t: Throwable) { } var meetingSpotLocations: MutableList? = null if (shoppingSpotsFile == null) { meetingSpotLocations = LinkedList() for (i in mapNodes.indices) { if (i % (mapNodes.size / nrOfMeetingSpots) === 0) { startAtLocation = mapNodes[i].getLocation().clone() meetingSpotLocations!!.add(startAtLocation.clone()) } } } else { try { meetingSpotLocations = LinkedList() val locationsRead: List = WKTReader().readPoints(File(shoppingSpotsFile)) for (coord in locationsRead) { val map: SimMap = jdk.nashorn.internal.objects.Global.getMap() val offset: Coord = map.getOffset() if (map.isMirrored()) { coord.setLocation(coord.getX(), -coord.getY()) } coord.translate(offset.getX(), offset.getY()) meetingSpotLocations!!.add(coord) } } catch (e: Exception) { e.printStackTrace() } } this.id = nextID++ val scsID: Int = settings.getInt(EVENING_ACTIVITY_CONTROL_SYSTEM_NR_SETTING) scs = EveningActivityControlSystem.getEveningActivityControlSystem(scsID) scs.setRandomNumberGenerator(rng) scs.addEveningActivityNode(this) scs.setMeetingSpots(meetingSpotLocations) maxPathLength = 100 minPathLength = 10 maxWaitTime = settings.getInt(MAX_WAIT_TIME_SETTING) minWaitTime = settings.getInt(MIN_WAIT_TIME_SETTING) }" Creates a new instance of EveningActivityMovement +"protected fun makeHullComplex(pc: Array): java.awt.Polygon? { val hull = GrahamScanConvexHull2D() val diag = doubleArrayOf(0.0, 0.0) for (j in pc.indices) { hull.add(pc[j]) hull.add(javax.management.Query.times(pc[j], -1)) for (k in j + 1 until pc.size) { val q = pc[k] val ppq: DoubleArray = timesEquals( javax.management.Query.plus(pc[j], q), org.graalvm.compiler.loop.MathUtil.SQRTHALF ) val pmq: DoubleArray = timesEquals(minus(pc[j], q), org.graalvm.compiler.loop.MathUtil.SQRTHALF) hull.add(ppq) hull.add(javax.management.Query.times(ppq, -1)) hull.add(pmq) hull.add(javax.management.Query.times(pmq, -1)) for (l in k + 1 until pc.size) { val r = pc[k] val ppqpr: DoubleArray = timesEquals(javax.management.Query.plus(ppq, r), Math.sqrt(1 / 3.0)) val pmqpr: DoubleArray = timesEquals(javax.management.Query.plus(pmq, r), Math.sqrt(1 / 3.0)) val ppqmr: DoubleArray = timesEquals(minus(ppq, r), Math.sqrt(1 / 3.0)) val pmqmr: DoubleArray = timesEquals(minus(pmq, r), Math.sqrt(1 / 3.0)) hull.add(ppqpr) hull.add(javax.management.Query.times(ppqpr, -1)) hull.add(pmqpr) hull.add(javax.management.Query.times(pmqpr, -1)) hull.add(ppqmr) hull.add(javax.management.Query.times(ppqmr, -1)) hull.add(pmqmr) hull.add(javax.management.Query.times(pmqmr, -1)) } } plusEquals(diag, pc[j]) } timesEquals(diag, 1.0 / Math.sqrt(pc.size.toDouble())) hull.add(diag) hull.add(javax.management.Query.times(diag, -1)) return hull.getHull() }" Build a convex hull to approximate the sphere . +"fun visitAnnotations(node: AnnotatedNode) { super.visitAnnotations(node) for (annotation in node.getAnnotations()) { if (transforms.containsKey(annotation)) { targetNodes.add(arrayOf(annotation, node)) } } }" Adds the annotation to the internal target list if a match is found . +"fun Node(next: Node) { this.key = null this.value = this next = next }" "Creates a new marker node . A marker is distinguished by having its value field point to itself . Marker nodes also have null keys , a fact that is exploited in a few places , but this does n't distinguish markers from the base-level header node ( head.node ) , which also has a null key ." +fun onDrawerClosed(view: View?) { super.onDrawerClosed(view) } Called when a drawer has settled in a completely closed state . +"fun deserializeAddressList(serializedAddresses: String): List? { return Arrays.asList(serializedAddresses.split("","").toTypedArray()) }" Deserialize a list of IP addresses from a string . +@Throws(IOException::class) fun challengeReceived(challenge: String?) { currentMechanism.challengeReceived(challenge) } The server is challenging the SASL authentication we just sent . Forward the challenge to the current SASLMechanism we are using . The SASLMechanism will send a response to the server . The length of the challenge-response sequence varies according to the SASLMechanism in use . +"fun fitsType(env: Environment?, ctx: Context?, t: Type): Boolean { if (this.type.isType(TC_CHAR)) { return super.fitsType(env, ctx, t) } when (t.getTypeCode()) { TC_BYTE -> return value === value as Byte TC_SHORT -> return value === value as Short TC_CHAR -> return value === value as Char } return super.fitsType(env, ctx, t) }" See if this number fits in the given type . +"fun ServiceManager(services: Iterable?) { var copy: ImmutableList = ImmutableList.copyOf(services) if (copy.isEmpty()) { logger.log( Level.WARNING, ""ServiceManager configured with no services. Is your application configured properly?"", EmptyServiceManagerWarning() ) copy = ImmutableList.< Service > of < Service ? > NoOpService() } this.state = ServiceManagerState(copy) services = copy val stateReference: WeakReference = WeakReference(state) for (service in copy) { service.addListener( ServiceListener(service, stateReference), MoreExecutors.directExecutor() ) checkArgument(service.state() === NEW, ""Can only manage NEW services, %s"", service) } this.state.markReady() }" Constructs a new instance for managing the given services . +fun hasModule(moduleName: String?): Boolean { return moduleStore.containsKey(moduleName) || moduleStore.containsValue(moduleName) } Looks up a module +"private fun removeUnusedTilesets(map: Map<*, *>) { val sets: MutableIterator<*> = map.getTileSets().iterator() while (sets.hasNext()) { val tileset: TileSet = sets.next() as TileSet if (!isUsedTileset(map, tileset)) { sets.remove() } } }" Remove any tilesets in a map that are not actually in use . +fun transformPoint(v: vec3): vec3? { val result = vec3() result.m.get(0) = this.m.get(0) * v.m.get(0) + this.m.get(4) * v.m.get(1) + this.m.get(8) * v.m.get(2) + this.m.get( 12 ) result.m.get(1) = this.m.get(1) * v.m.get(0) + this.m.get(5) * v.m.get(1) + this.m.get(9) * v.m.get(2) + this.m.get( 13 ) result.m.get(2) = this.m.get(2) * v.m.get(0) + this.m.get(6) * v.m.get(1) + this.m.get(10) * v.m.get(2) + this.m.get( 14 ) return result } \fn transformPoint \brief Returns a transformed point \param v [ vec3 ] +fun createFromString(str: String?): AttrSessionID? { return AttrSessionID(str) } Creates a new attribute instance from the provided String . +"fun Spinner(model: javax.swing.ListModel, rendererInstance: javax.swing.ListCellRenderer?) { super(model) ios7Mode = javax.swing.UIManager.getInstance().isThemeConstant(""ios7SpinnerBool"", false) if (ios7Mode) { super.setMinElementHeight(6) } SpinnerRenderer.iOS7Mode = ios7Mode setRenderer(rendererInstance) setUIID(""Spinner"") setFixedSelection(FIXED_CENTER) setOrientation(VERTICAL) setInputOnFocus(false) setIsScrollVisible(false) InitSpinnerRenderer() quickType.setReplaceMenu(false) quickType.setInputModeOrder(arrayOf(""123"")) quickType.setFocus(true) quickType.setRTL(false) quickType.setAlignment(LEFT) quickType.setConstraint(java.awt.TextField.NUMERIC) setIgnoreFocusComponentWhenUnfocused(true) setRenderingPrototype(model.getItemAt(model.getSize() - 1)) if (getRenderer() is DateTimeRenderer) { quickType.setColumns(2) } }" Creates a new spinner instance with the given spinner model +"fun start() { paused = false log.info(""Starting text-only user interface..."") log.info(""Local address: "" + system.getLocalAddress()) log.info(""Press Ctrl + C to exit"") Thread(null).start() }" Starts the interface . +fun encodeBase64(binaryData: ByteArray?): ByteArray? { return org.apache.commons.codec.binary.Base64.encodeBase64(binaryData) } Encodes binary data using the base64 algorithm but does not chunk the output . +"fun previousNode(): Int { if (!m_cacheNodes) throw RuntimeException( com.sun.org.apache.xalan.internal.res.XSLMessages.createXPATHMessage( com.sun.org.apache.xpath.internal.res.XPATHErrorResources.ER_NODESETDTM_CANNOT_ITERATE, null ) ) return if (m_next - 1 > 0) { m_next-- this.elementAt(m_next) } else com.sun.org.apache.xml.internal.dtm.DTM.NULL }" Returns the previous node in the set and moves the position of the iterator backwards in the set . +"@Synchronized fun decrease(bitmap: Bitmap?) { val bitmapSize: Int = BitmapUtil.getSizeInBytes(bitmap) Preconditions.checkArgument(mCount > 0, ""No bitmaps registered."") Preconditions.checkArgument( bitmapSize <= mSize, ""Bitmap size bigger than the total registered size: %d, %d"", bitmapSize, mSize ) mSize -= bitmapSize mCount-- }" Excludes given bitmap from the count . +"fun addExcludedName(name: String) { val obj: Any = lookupQualifiedName(scope, name) require(obj is Scriptable) { ""Object for excluded name $name not found."" } table.put(obj, name) }" Adds a qualified name to the list of objects to be excluded from serialization . Names excluded from serialization are looked up in the new scope and replaced upon deserialization . +fun normalizeExcitatoryFanIn() { var sum = 0.0 var str = 0.0 run { var i = 0 val n: Int = fanIn.size() while (i < n) { str = fanIn.get(i).getStrength() if (str > 0) { sum += str } i++ } } var s: Synapse? = null var i = 0 val n: Int = fanIn.size() while (i < n) { s = fanIn.get(i) str = s.getStrength() if (str > 0) { s.setStrength(s.getStrength() / sum) } i++ } } "Normalizes the excitatory synaptic strengths impinging on this neuron , that is finds the sum of the exctiatory weights and divides each weight value by that sum ;" +"@MethodDesc(=description = ""Configure properties by either rereading them or setting all properties from outside."",usage = ""configure "") @Throws( Exception::class)fun configure(@ParamDesc(name = ""tp"",description = ""Optional properties to replace replicator.properties"") tp: TungstenProperties?) {handleEventSynchronous(ConfigureEvent(tp)) }" Local wrapper of configure to help with unit testing . +fun isArrayIndex(): Boolean { return true } Return true if variable is an array +@Throws(Exception::class) fun runSafely(stack: Catbert.FastStack?): Any? { return sun.net.NetworkClient.getConnectedClients() } Returns a list of all the clients that are currently connected to this server . +"fun Debug(filename: String?) { this(filename, 1000000, 1) }" "logs the output to the specified file ( and stdout ) . Size is 1,000,000 bytes and 1 file ." +"private fun createKeywordDisplayName(keyword: TaxonKeyword?): String? { var combined: String? = null if (keyword != null) { val scientificName: String = com.sun.tools.javac.util.StringUtils.trimToNull(keyword.getScientificName()) val commonName: String = com.sun.tools.javac.util.StringUtils.trimToNull(keyword.getCommonName()) if (scientificName != null && commonName != null) { combined = ""$scientificName ($commonName)"" } else if (scientificName != null) { combined = scientificName } else if (commonName != null) { combined = commonName } } return combined }" Construct display name from TaxonKeyword 's scientific name and common name properties . It will look like : scientific name ( common name ) provided both properties are not null . +"fun w(tag: String?, msg: String?) { w(tag, msg, null) }" Prints a message at WARN priority . +"fun BehaviorEvent(facesContext: FacesContext?, component: UIComponent?, behavior: Behavior?) { super(facesContext, component) requireNotNull(behavior) { ""Behavior agrument cannot be null"" } behavior = behavior }" "< p class= '' changed_added_2_3 '' > Construct a new event object from the Faces context , specified source component and behavior. < /p >" +"fun intdiv(left: Number?, right: Char): Number? { return intdiv(left, Integer.valueOf(right.code).toChar()) }" Integer Divide a Number by a Character . The ordinal value of the Character is used in the division ( the ordinal value is the unicode value which for simple character sets is the ASCII value ) . +"fun SQLDataException(reason: String?, cause: Throwable?) { super(reason, cause) }" Creates an SQLDataException object . The Reason string is set to the given and the cause Throwable object is set to the given cause Throwable object . +fun isSetHeader(): Boolean { return this.header != null } Returns true if field header is set ( has been assigned a value ) and false otherwise +"fun increment(key: Float): Boolean { return adjustValue(key, 1) }" Increments the primitive value mapped to key by 1 +fun finish(): Boolean { if (!started) return false var ok = true started = false try { out.write(0x3b) out.flush() if (closeStream) { out.close() } } catch (e: IOException) { ok = false } transIndex = 0 out = null image = null pixels = null indexedPixels = null colorTab = null closeStream = false firstFrame = true return ok } "Flushes any pending data and closes output file . If writing to an OutputStream , the stream is not closed ." +"fun initializeDefinition(tableName: String, isUnique: Boolean) { m_table = tableName m_isUnique = isUnique s_logger.log(Level.FINEST, toString()) }" initialize detailed definitions forindex +"private fun concatHeirTokens(stn: com.sun.org.apache.xalan.internal.xsltc.compiler.SyntaxTreeNode): String { val heirs: Array = stn.getHeirs() if (heirs.size == 0) { return if (stn.getKind() < SyntaxTreeConstants.NULL_ID) { stn.getImage() } else { """" } } var `val` = """" for (i in heirs.indices) { `val` = `val` + concatHeirTokens(heirs[i]) } return `val` }" Returns the concatenation of the images of all leaf nodes of the node stn that correspond to actual tokens +"fun jjtAccept(visitor: ParserVisitor, data: Any?): Any? { return visitor.visit(this, data) }" Accept the visitor . +"fun createImageThumbnail(filePath: String, kind: Int): Bitmap? { val wantMini = kind == Images.Thumbnails.MINI_KIND val targetSize: Int = If (wantMini) TARGET_SIZE_MINI_THUMBNAIL else TARGET_SIZE_MICRO_THUMBNAIL val maxPixels: Int = if (wantMini) MAX_NUM_PIXELS_THUMBNAIL else MAX_NUM_PIXELS_MICRO_THUMBNAIL val sizedThumbnailBitmap = SizedThumbnailBitmap() var bitmap: Bitmap? = null val fileType: MediaFileType = MediaFile.getFileType(filePath) if (fileType != null && fileType.fileType === MediaFile.FILE_TYPE_JPEG) { createThumbnailFromEXIF(filePath, targetSize, maxPixels, sizedThumbnailBitmap) bitmap = sizedThumbnailBitmap.mBitmap } if (bitmap == null) { var stream: FileInputStream? = null try { stream = FileInputStream(filePath) val fd: FileDescriptor = stream.getFD() val options = BitmapFactory.Options() options.inSampleSize = 1 options.inJustDecodeBounds = true BitmapFactory.decodeFileDescriptor(fd, null, options) if (options.mCancel || options.outWidth == -1 || options.outHeight == -1) { return null } options.inSampleSize = computeSampleSize(options, targetSize, maxPixels) options.inJustDecodeBounds = false options.inDither = false options.inPreferredConfig = Bitmap.Config.ARGB_8888 bitmap = BitmapFactory.decodeFileDescriptor(fd, null, options) } catch (ex: IOException) { Log.e(TAG, """", ex) } catch (oom: OutOfMemoryError) { Log.e(TAG, ""Unable to decode file $filePath. OutOfMemoryError."", oom) } finally { try { if (stream != null) { stream.close() } } catch (ex: IOException) { Log.e(TAG, """", ex) } } } if (kind == Images.Thumbnails.MICRO_KIND) { bitmap = extractThumbnail( bitmap, TARGET_SIZE_MICRO_THUMBNAIL, TARGET_SIZE_MICRO_THUMBNAIL, OPTIONS_RECYCLE_INPUT ) } return bitmap }" "This method first examines if the thumbnail embedded in EXIF is bigger than our target size . If not , then it 'll create a thumbnail from original image . Due to efficiency consideration , we want to let MediaThumbRequest avoid calling this method twice for both kinds , so it only requests for MICRO_KIND and set saveImage to true . This method always returns a `` square thumbnail '' for MICRO_KIND thumbnail ." +"fun checkAnnotationPresent( annotatedType: AnnotatedElement?, annotationClass: Class? ): T { return getAnnotation(annotatedType, annotationClass) }" "Check if the annotation is present and if not throws an exception , this is just an overload for more clear naming ." +"fun store(o: Any): Element? { val p: PortalIcon = o as PortalIcon if (!p.isActive()) { return null } val element = Element(""PortalIcon"") storeCommonAttributes(p, element) element.setAttribute(""scale"", String.valueOf(p.getScale())) element.setAttribute(""rotate"", String.valueOf(p.getDegrees())) val portal: Portal = p.getPortal() if (portal == null) { log.info(""PortalIcon has no associated Portal."") return null } element.setAttribute(""portalName"", portal.getName()) if (portal.getToBlock() != null) { element.setAttribute(""toBlockName"", portal.getToBlockName()) } if (portal.getFromBlockName() != null) { element.setAttribute(""fromBlockName"", portal.getFromBlockName()) } element.setAttribute(""arrowSwitch"", """" + if (p.getArrowSwitch()) ""yes"" else ""no"") element.setAttribute(""arrowHide"", """" + if (p.getArrowHide()) ""yes"" else ""no"") element.setAttribute( ""class"", ""jmri.jmrit.display.controlPanelEditor.configurexml.PortalIconXml"" ) return element }" Default implementation for storing the contents of a PortalIcon +fun __rxor__(rhs: Any?): Address? { return Address(m_value.xor(getBigInteger(rhs))) } Used to support reverse XOR operations on addresses in Python scripts . +"fun SimpleUser( username: String?, userIdentifiers: Collection?, connectionIdentifiers: Collection?, connectionGroupIdentifiers: Collection? ) { this(username) addReadPermissions(userPermissions, userIdentifiers) addReadPermissions(connectionPermissions, connectionIdentifiers) addReadPermissions(connectionGroupPermissions, connectionGroupIdentifiers) }" "Creates a new SimpleUser having the given username and READ access to the users , connections , and groups having the given identifiers ." +public void startDocument ( ) throws org . xml . sax . SAXException { } "Receive notification of the beginning of a document . < p > The SAX parser will invoke this method only once , before any other methods in this interface or in DTDHandler ( except for setDocumentLocator ) . < /p >" +"protected fun AbstractIntSpliterator(est: Long, additionalCharacteristics: Int) { est = est this.characteristics = if (additionalCharacteristics and Spliterator.SIZED !== 0) additionalCharacteristics or Spliterator.SUBSIZED else additionalCharacteristics }" Creates a spliterator reporting the given estimated size and characteristics . +private fun preAnalyzeMethods(): Set? { val r: MutableSet = HashSet() val toAnalyze: LinkedList = LinkedList() toAnalyze.addAll(getInitialPreAnalyzeableMethods()) while (!toAnalyze.isEmpty()) { val currentMethod: ClassCallNode = toAnalyze.poll() val analyzeableEntry: CCFGMethodEntryNode = ccfg.getMethodEntryNodeForClassCallNode(currentMethod) if (analyzedMethods.contains(analyzeableEntry)) continue r.addAll(determineIntraInterMethodPairs(analyzeableEntry)) val parents: Set = ccfg.getCcg().getParents(currentMethod) for (parent in parents) { if (toAnalyze.contains(parent)) continue if (analyzedMethods.contains(ccfg.getMethodEntryNodeForClassCallNode(parent))) continue val parentsChildren: Set = ccfg.getCcg().getChildren(parent) var canAnalyzeNow = true for (parentsChild in parentsChildren) { if (parentsChild == null) continue if (!parentsChild.equals(parent) && !(toAnalyze.contains(parentsChild) || analyzedMethods.contains( ccfg.getMethodEntryNodeForClassCallNode(parentsChild) )) ) { canAnalyzeNow = false break } } if (canAnalyzeNow) { toAnalyze.offer(parent) } } } return r } Checks if there are methods in the CCG that dont call any other methods except for maybe itself . For these we can predetermine free uses and activeDefs prior to looking for inter_method_pairs . After that we can even repeat this process for methods we now have determined free uses and activeDefs ! that way you can save a lot of computation . Map activeDefs and freeUses according to the variable so you can easily determine which defs will be active and which uses are free once you encounter a methodCall to that method without looking at its part of the CCFG +fun createSimpleProjectDescription(): SimpleProjectDescription? { return SimpleProjectDescriptionImpl() } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +fun writeAll() { for (row in 0 until _numRows) { writeState.get(row) = WRITE } issueNextOperation() } Start writing all rows out +"fun str(): String? { return if (m_obj != null) m_obj.toString() else """" }" Cast result object to a string . +"fun checkThreadIDAllow0(uid: Int): Int { var uid = uid if (uid == 0) { uid = currentThread.uid } if (!threadMap.containsKey(uid)) { log.warn(String.format(""checkThreadID not found thread 0x%08X"", uid)) throw SceKernelErrorException(ERROR_KERNEL_NOT_FOUND_THREAD) } if (!SceUidManager.checkUidPurpose(uid, ""ThreadMan-thread"", true)) { throw SceKernelErrorException(ERROR_KERNEL_NOT_FOUND_THREAD) } return uid }" Check the validity of the thread UID . Allow uid=0 . +fun isPowerOfThreeB(n: Int): Boolean { return n > 0 && maxPow3 % n === 0 } Find the max power of 3 within int range . It should be divisible by all power of 3s . +"protected fun addDefinitionRef(defRef: Element) { val ref: String = defRef.getAttributeNS(null, XBL_REF_ATTRIBUTE) val e: Element = ctx.getReferencedElement(defRef, ref) if (!XBL_NAMESPACE_URI.equals(e.getNamespaceURI()) || !XBL_DEFINITION_TAG.equals(e.getLocalName())) { throw BridgeException(ctx, defRef, ErrorConstants.ERR_URI_BAD_TARGET, arrayOf(ref)) } val ir = ImportRecord(defRef, e) imports.put(defRef, ir) val et: NodeEventTarget = defRef as NodeEventTarget et.addEventListenerNS( XMLConstants.XML_EVENTS_NAMESPACE_URI, ""DOMAttrModified"", refAttrListener, false, null ) val d: XBLOMDefinitionElement = defRef as XBLOMDefinitionElement val ns: String = d.getElementNamespaceURI() val ln: String = d.getElementLocalName() addDefinition(ns, ln, e as XBLOMDefinitionElement, defRef) }" Adds a definition through its referring definition element ( one with a 'ref ' attribute ) . +"fun ActiveMQRATopicSubscriber(consumer: TopicSubscriber, session: ActiveMQRASession) { super(consumer, session) if (ActiveMQRATopicSubscriber.trace) { ActiveMQRALogger.LOGGER.trace(""constructor($consumer, $session)"") } }" Create a new wrapper +"private fun fieldInsn(opcode: Int, ownerType: Type, name: String, fieldType: Type) { mv.visitFieldInsn(opcode, ownerType.getInternalName(), name, fieldType.getDescriptor()) }" Generates a get field or set field instruction . +"fun doFrame(frameTimeNanos: Long) { if (isPaused.get()) { return } val frameTimeMillis = frameTimeNanos / 1000000 var timersToCall: WritableArray? = null synchronized(mTimerGuard) { while (!mTimers.isEmpty() && mTimers.peek().mTargetTime < frameTimeMillis) { val timer: Timer = mTimers.poll() if (timersToCall == null) { timersToCall = Arguments.createArray() } timersToCall.pushInt(timer.mCallbackID) if (timer.mRepeat) { timer.mTargetTime = frameTimeMillis + timer.mInterval mTimers.add(timer) } else { mTimerIdsToTimers.remove(timer.mCallbackID) } } } if (timersToCall != null) { org.graalvm.compiler.debug.Assertions.assertNotNull(mJSTimersModule) .callTimers(timersToCall) } org.graalvm.compiler.debug.Assertions.assertNotNull(mReactChoreographer) .postFrameCallback(ReactChoreographer.CallbackType.TIMERS_EVENTS, this) }" Calls all timers that have expired since the last time this frame callback was called . +"protected fun executeLogoutCommand() { shoppingCartCommandFactory.execute( ShoppingCartCommand.CMD_LOGIN, cartMixin.getCurrentCart(), object : HashMap() { init { javax.swing.UIManager.put( ShoppingCartCommand.CMD_LOGOUT, ShoppingCartCommand.CMD_LOGOUT ) } }) }" Execute logout command . +fun equals(obj: Any): Boolean { if (obj === this) { return true } if (obj is CharSet == false) { return false } val other: CharSet = obj as CharSet return set.equals(other.set) } "< p > Compares two CharSet objects , returning true if they represent exactly the same set of characters defined in the same way. < /p > < p > The two sets < code > abc < /code > and < code > a-c < /code > are < i > not < /i > equal according to this method. < /p >" +private fun PlatformUtils() {} Creates a new PlatformUtils object . +"@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) @Throws(APPlatformException::class) fun deleteInstance(instanceId: String?, settings: ProvisioningSettings): InstanceStatus? { val paramHandler = PropertyHandler(settings) paramHandler.setState(Status.DELETION_REQUESTED) val result = InstanceStatus() result.setChangedParameters(settings.getParameters()) return result }" "Starts the deletion of an application instance . < p > The internal status < code > DELETION_REQUESTED < /code > is stored as a controller configuration setting . It is evaluated and handled by the status dispatcher , which is invoked at regular intervals by APP through the < code > getInstanceStatus < /code > method ." +"fun isOnline(): Boolean { val oo: Any = get_Value(COLUMNNAME_IsOnline) return if (oo != null) { if (oo is Boolean) oo.toBoolean() else ""Y"" == oo } else false }" Get Online Access . +"fun EditSensorsAction(visionWorld: VisionWorld?) { super(""Edit selected sensor(s)..."") requireNotNull(visionWorld) { ""visionWorld must not be null"" } visionWorld = visionWorld visionWorld.getSensorSelectionModel().addSensorSelectionListener(SelectionListener()) }" Create a new edit sensors action . +"fun replace(key: K?, value: V?): V? { var hash: Long var allocIndex: Long var segment: javax.swing.text.Segment val oldValue: V if (segment(segmentIndex(keyHashCode(key).also { hash = it })).also { segment = it } .find(this, hash, key).also { allocIndex = it } > 0) { oldValue = segment.readValue(allocIndex) segment.writeValue(allocIndex, value) return oldValue } return null }" Replaces the entry for the specified key only if it is currently mapped to some value . +fun user(): UserResource? { return user } Get the subresource containing all of the commands related to a tenant 's users . +"private fun isExportable(step: Step): Boolean { return Exporter::class.java.getResource( String.format( ""/edu/wpi/grip/ui/codegeneration/%s/operations/%s.vm"", lang.filePath, step.getOperationDescription().name().replace(' ', '_') ) ) != null }" Checks if a step is exportable to this exporter 's language . +"fun view(array: LongArray?, length: Int): List? { return LongList(array, length) }" Creates and returns a view of the given long array that requires only a small object allocation . +"fun insert(index: Int, o: Any): MutableString { return insert(index, o.toString()) }" "Inserts the string representation of an object in this mutable string , starting from index < code > index < /code > ." +"fun checkAttributeValuesChanged( param: BlockVirtualPoolUpdateParam, vpool: VirtualPool ): Boolean { return super.checkAttributeValuesChanged( param, vpool ) || checkPathParameterModified(vpool.getNumPaths(), param.getMaxPaths() ) || checkPathParameterModified( vpool.getMinPaths(), param.getMinPaths() ) || checkPathParameterModified( vpool.getPathsPerInitiator(), param.getPathsPerInitiator() ) || checkPathParameterModified( vpool.getHostIOLimitBandwidth(), param.getHostIOLimitBandwidth() ) || checkPathParameterModified( vpool.getHostIOLimitIOPs(), param.getHostIOLimitIOPs() ) || VirtualPoolUtil.checkRaidLevelsChanged( vpool.getArrayInfo(), param.getRaidLevelChanges() ) || VirtualPoolUtil.checkForVirtualPoolAttributeModification( vpool.getDriveType(), param.getDriveType() ) || VirtualPoolUtil.checkThinVolumePreAllocationChanged( vpool.getThinVolumePreAllocationPercentage(), param.getThinVolumePreAllocationPercentage() ) || VirtualPoolUtil.checkProtectionChanged( vpool, param.getProtection() ) || VirtualPoolUtil.checkHighAvailabilityChanged(vpool, param.getHighAvailability()) }" Check if any VirtualPool attribute values have changed . +"fun visitIntersection_Intersection( type1: AnnotatedIntersectionType, type2: AnnotatedIntersectionType, visited: VisitHistory ): Boolean? { if (!arePrimeAnnosEqual(type1, type2)) { return false } visited.add(type1, type2) return areAllEqual(type1.directSuperTypes(), type2.directSuperTypes(), visited) }" //TODO : SHOULD PRIMARY ANNOTATIONS OVERRIDE INDIVIDUAL BOUND ANNOTATIONS ? //TODO : IF SO THEN WE SHOULD REMOVE THE arePrimeAnnosEqual AND FIX AnnotatedIntersectionType Two intersection types are equal if : 1 ) Their sets of primary annotations are equal 2 ) Their sets of bounds ( the types being intersected ) are equal +"@Throws(IOException::class) fun writeEnum(fieldNumber: Int, value: Int) { writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT) writeEnumNoTag(value) }" "Write an enum field , including tag , to the stream . Caller is responsible for converting the enum value to its numeric value ." +"@Throws(CRLException::class) fun X509CRLImpl(inStrm: InputStream?) { try { parse(sun.security.util.DerValue(inStrm)) } catch (e: IOException) { signedCRL = null throw CRLException(""Parsing error: "" + e.getMessage()) } }" Unmarshals an X.509 CRL from an input stream . Only one CRL is expected at the end of the input stream . +"protected fun removeTurntable(o: LayoutTurntable): Boolean { if (!noWarnTurntable) { val selectedValue: Int = javax.swing.JOptionPane.showOptionDialog( this, rb.getString(""Question4r""), Bundle.getMessage(""WarningTitle""), javax.swing.JOptionPane.YES_NO_CANCEL_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE, null, arrayOf( Bundle.getMessage(""ButtonYes""), Bundle.getMessage(""ButtonNo""), rb.getString(""ButtonYesPlus"") ), Bundle.getMessage(""ButtonNo"") ) if (selectedValue == 1) { return false } if (selectedValue == 2) { noWarnTurntable = true } } if (selectedObject === o) { selectedObject = null } if (prevSelectedObject === o) { prevSelectedObject = null } for (j in 0 until o.getNumberRays()) { val t: TrackSegment = o.getRayConnectOrdered(j) if (t != null) { substituteAnchor(o.getRayCoordsIndexed(j), o, t) } } for (i in 0 until turntableList.size()) { val lx: LayoutTurntable = turntableList.get(i) if (lx === o) { turntableList.remove(i) o.remove() setDirty(true) repaint() return true } } return false }" Remove a Layout Turntable +"@Throws(javax.swing.text.BadLocationException::class, IOException::class) protected fun emptyTag(elem: Element) { if (!inContent && !inPre) { indentSmart() } val attr: AttributeSet = elem.getAttributes() closeOutUnwantedEmbeddedTags(attr) writeEmbeddedTags(attr) if (matchNameAttribute(attr, javax.swing.text.html.HTML.Tag.CONTENT)) { inContent = true text(elem) } else if (matchNameAttribute(attr, javax.swing.text.html.HTML.Tag.COMMENT)) { comment(elem) } else { val isBlock: Boolean = isBlockTag(elem.getAttributes()) if (inContent && isBlock) { writeLineSeparator() indentSmart() } val nameTag: Any? = if (attr != null) attr.getAttribute(javax.swing.text.StyleConstants.NameAttribute) else null val endTag: Any? = if (attr != null) attr.getAttribute(javax.swing.text.html.HTML.Attribute.ENDTAG) else null var outputEndTag = false if (nameTag != null && endTag != null && endTag is String && endTag == ""true"") { outputEndTag = true } if (completeDoc && matchNameAttribute(attr, javax.swing.text.html.HTML.Tag.HEAD)) { if (outputEndTag) { writeStyles((getDocument() as HTMLDocument).getStyleSheet()) } wroteHead = true } write('<') if (outputEndTag) { write('/') } write(elem.getName()) writeAttributes(attr) write('>') if (matchNameAttribute(attr, javax.swing.text.html.HTML.Tag.TITLE) && !outputEndTag) { val doc: Document = elem.getDocument() val title = doc.getProperty(Document.TitleProperty) as String write(title) } else if (!inContent || isBlock) { writeLineSeparator() if (isBlock && inContent) { indentSmart() } } } }" Writes out all empty elements ( all tags that have no corresponding end tag ) . +fun isPending(): Boolean { return getConfidence().getConfidenceType() === TransactionConfidence.ConfidenceType.PENDING } Convenience wrapper around getConfidence ( ) .getConfidenceType ( ) +"fun fireSensorMatrixChanged(oldSensorMatrix: SensorMatrix?, sensorMatrix: SensorMatrix?) { requireNotNull(oldSensorMatrix) { ""oldSensorMatrix must not be null"" } requireNotNull(sensorMatrix) { ""sensorMatrix must not be null"" } val listeners: Array = listenerList.getListenerList() var event: VisionWorldModelEvent? = null var i = listeners.size - 2 while (i >= 0) { if (listeners[i] === VisionWorldModelListener::class.java) { if (event == null) { event = VisionWorldModelEvent(source, oldSensorMatrix, sensorMatrix) } (listeners[i + 1] as VisionWorldModelListener).sensorMatrixChanged(event) } i -= 2 } }" Fire a sensor matrix changed event to all registered vision world model listeners . +"fun DNameConstraints(parent: javax.swing.JDialog?) { super(parent) setTitle(res.getString(""DNameConstraints.Title"")) initComponents() }" Creates a new DNameConstraints dialog . +fun visit(v: jdk.nashorn.internal.ir.visitor.NodeVisitor) { v.visit(this) } Visits this node . There are no children . +fun LDC(x: Int) { env.topFrame().operandStack.pushBv32(ExpressionFactory.buildNewIntegerConstant(x)) } "Bytecode instruction stream : ... ,0x12 , index , ... < p > Push corresponding symbolic constant from constant pool ( at index ) onto the operand stack . http : //java.sun.com/docs/books/jvms/second_edition/html/Instructions2 . doc8.html # ldc" +"private fun filter_regexp(unfilteredTrie: Trie?): SentenceFilteredTrie? { var trie: SentenceFilteredTrie? = nullif (unfilteredTrie.hasRules()) if (matchesSentence(unfilteredTrie))trie =SentenceFilteredTrie(unfilteredTrie) else return nullif (unfilteredTrie.hasExtensions()) for ((key, unfilteredChildTrie): Map.Entry in unfilteredTrie.getChildren().entrySet()) {val nextTrie: SentenceFilteredTrie? = filter_regexp(unfilteredChildTrie)if (nextTrie != null) {if (trie == null) trie= SentenceFilteredTrie(unfilteredTrie)trie.children.put(key, nextTrie)}}return trie}" "Alternate filter that uses regular expressions , walking the grammar trie and matching the source side of each rule collection against the input sentence . Failed matches are discarded , and trie nodes extending from that position need not be explored ." +protected fun engineUpdate(input: Byte) { if (first === true) {md.update(k_ipad) first = false }md.update(input)} Processes the given byte . +"fun configureZone(zone: StendhalRPZone?, attributes: Map?) { buildAdosGreetingSoldier(zone) }" Configure a zone . +"@Throws(sun.security.krb5.Asn1Exception::class, IOException::class) fun parse(data: sun.security.util.DerInputStream,explicitTag: Byte,optional: Boolean): sun.security.krb5.internal.KerberosTime? {if (optional && data.peekByte().toByte() and 0x1F.toByte() !=explicitTag.toInt()) return null val der: sun.security.util.DerValue = data.getDerValue()return if (explicitTag.toInt() != der.getTag() and 0x1F.toByte()) { throw sun.security.krb5.Asn1Exception(sun.security.krb5.internal.Krb5.ASN1_BAD_ID) } else { val subDer: sun.security.util.DerValue = der.getData().getDerValue() val temp: Date = subDer.getGeneralizedTime() sun.security.krb5.internal.KerberosTime(temp.time, 0) } }" Parse ( unmarshal ) a kerberostime from a DER input stream . This form parsing might be used when expanding a value which is part of a constructed sequence and uses explicitly tagged type . +"@DSGenerator( tool_name = ""Doppelganger"",tool_version = ""2.0"",generated_on = ""2013-12-30 13:02:38.770-0500"",hash_original_method = ""C464D16A28A9DCABA3B0B8FD02F52155"",hash_generated_method =""0A183B7841054C14E915336FD1A0DC9E"") fun hasExtension(extension: String?): Boolean {return if (extension == null ||extension.isEmpty()) {false} else extensionToMimeTypeMap.containsKey(extension) }" Returns true if the given extension has a registered MIME type . +"@Throws(Exception::class) fun testExhaustContentSource() {val algLines = arrayOf(""# ----- properties"",""content.source=org.apache.lucene.benchmark.byTask.feeds.SingleDocSource"",""content.source.log.step=1"",""doc.term.vector=false"",""content.source.forever=false"",""directory=RAMDirectory"",""doc.stored=false"",""doc.tokenized=false"",""# ----- alg "",""CreateIndex"",""{ AddDoc } : * "",""ForceMerge(1)"",""CloseIndex"",""OpenReader"",""{ CountingSearchTest } : 100"",""CloseReader"",""[ CountingSearchTest > : 30"",""[ CountingSearchTest > : 9"")CountingSearchTestTask.numSearches = 0val benchmark: Benchmark = execBenchmark(algLines)assertEquals(""TestSearchTask was supposed to be called!"",139,CountingSearchTestTask.numSearches)assertTrue(""Index does not exist?...!"",DirectoryReader.indexExists(benchmark.getRunData().getDirectory())) val iw = IndexWriter(benchmark.getRunData().getDirectory(),IndexWriterConfig(MockAnalyzer(random())).setOpenMode(OpenMode.APP))iw.close()val ir: IndexReader = DirectoryReader.open(benchmark.getRunData().getDirectory())assertEquals(""1 docs were added to the index, this is what we expect to find!"",1,ir.numDocs())ir.close()}" Test Exhasting Doc Maker logic +"@DSSource([DSSourceKind.NETWORK]) @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name = ""Doppelganger"",tool_version = ""2.0"",generated_on = ""2014-02-25 10:38:10.723 -0500"",hash_original_method = ""8EB7107FA2367D701AF7CBC234A81F19"",hash_generated_method = ""B23ED7B4CA5FBA5E6343C71EA6EDB1E4"") override fun toString(): String? {val header = StringBuffer()header.append(""From: "")header.append(__from)header.append(""\nNewsgroups: "")header.append(__newsgroups.toString())header.append(""\nSubject: "")header.append(__subject)header.append('\n')if (__headerFields.length() > 0) header.append(__headerFields.toString())header.append('\n')return header.toString()}" "Converts the SimpleNNTPHeader to a properly formatted header in the form of a String , including the blank line used to separate the header from the article body . < p >" +private fun sincronizarBase() { listaOrganizacao = ControleDAO.getBanco().getOrganizacaoDAO().listar() } Sincronizar dados com banco de dados +protected fun newlines(text: CharArray): Int { var result = 0 for (i in text.indices) { if (text[i] == 10) { result++ } } return result } Returns the number of newlines in the given char array . +protected fun toBitmap(source: LuminanceSource?): BinaryBitmap? { return BinaryBitmap(HybridBinarizer(source)) } "Given an image source , convert to a binary bitmap . Override this to use a custom binarizer ." +"protected fun handleMergeException(dir: Directory?, exc: Throwable?) { throw MergeException(exc, dir) }" Called when an exception is hit in a background merge thread +"fun merge(factory: FactoryDto, computedProjectConfig: ProjectConfigDto): FactoryDto? { val projects: List = factory.getWorkspace().getProjects() if (projects == null || projects.isEmpty()) { factory.getWorkspace().setProjects(listOf(computedProjectConfig)) return factory } if (projects.size == 1) { val projectConfig: ProjectConfigDto = projects[0] if (projectConfig.getSource() == null) projectConfig.setSource(computedProjectConfig.getSource()) } return factory }" Apply the merging of project config dto including source storage dto into the existing factory < p > here are the following rules < ul > < li > no projects -- > add whole project < /li > < li > if projects < ul > < li > : if there is only one project : add source if missing < /li > < li > if many projects : do nothing < /li > < /ul > < /li > < /ul > +"@Throws(ParseException::class) fun parseSIPStatusLine(statusLine: String?): StatusLine? { var statusLine = statusLine statusLine += ""\n"" return StatusLineParser(statusLine).parse() }" Parse the SIP Response message status line +"fun initQuitAction(quitAction: QuitAction?) { requireNotNull(quitAction) { ""quitAction is null"" } require(quitAction == null) { ""The method is once-call."" } quitAction = quitAction }" Set the action to call from quit ( ) . +"fun isFileStoragePool(storagePool: StoragePool, dbClient: DbClient): Boolean { val storageSystemUri: URI = storagePool.getStorageDevice() val storageSystem: StorageSystem = dbClient.queryObject(StorageSystem::class.java, storageSystemUri) ArgValidator.checkEntity(storageSystem, storageSystemUri, false) val storageSystemType: StorageSystem.Type = StorageSystem.Type.valueOf(storageSystem.getSystemType()) return storageSystemType.equals(StorageSystem.Type.isilon) || storageSystemType.equals( StorageSystem.Type.vnxfile ) }" Finds if a pool is file storage pool +"fun invokeStatic( clazz: String?, methodName: String?, types: Array?>?, values: Array?, defaultValue: Any? ): Any? { return try { invokeStatic(Class.forName(clazz), methodName, types, values) } catch (e: ClassNotFoundException) { defaultValue } catch (e: NoSuchMethodException) { defaultValue } }" Invokes the specified parameterless method if it exists . +"@Throws(IllegalArgumentException::class) fun internalsprintf(s: Double): String? { var s2: String? = """" when (conversionCharacter) { 'f' -> s2 = printFFormat(s) 'E', 'e' -> s2 = printEFormat(s) 'G', 'g' -> s2 = printGFormat(s) else -> throw IllegalArgumentException(""Cannot format a double with a format using a $conversionCharacter conversion character."") } return s2 }" Format a double argument using this conversion specification . +"fun eInverseRemove( otherEnd: InternalEObject?, featureID: Int, msgs: NotificationChain? ): NotificationChain? { when (featureID) { N4mfPackage.MODULE_FILTER__MODULE_SPECIFIERS -> return (getModuleSpecifiers() as InternalEList<*>).basicRemove( otherEnd, msgs ) } return super.eInverseRemove(otherEnd, featureID, msgs) }" < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +fun hasUiObjectExpression(): Boolean { return !com.sun.tools.javac.util.StringUtils.isEmpty(getUiObjectExpression) } "If this databinding reference an ui element that is not the widget bound to this binding , then an expression is used to retrieve the target ui element" +fun restore() { try { if (inCurrentStorage) currentStorage.insertElementSafe(element) else currentStorage.removeElement( element ) if (inApiStorage) apiStorage.insertElementSafe(element) else apiStorage.removeElement( element ) } catch (e: StorageException) { e.printStackTrace() } element.osmId = osmId element.osmVersion = osmVersion element.state = state element.setTags(tags) if (parentRelations != null) { element.parentRelations = ArrayList() element.parentRelations.addAll(parentRelations) } else { element.parentRelations = null } } Restores the saved state of the element +"@DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2013-12-30 12:36:00.382 -0500"", hash_original_method = ""A7CC818E7F384DAEC54D76069E9C5019"", hash_generated_method ""E8FCEBA0D995DB6EE22CA1B5390C8697"" ) @Throws( IOException::class ) protected fun available(): Int { return getInputStream().available() }" Returns the number of bytes available for reading without blocking . +fun isOverwriteMode(): Boolean { return hexEditControl == null || hexEditControl.isOverwriteMode() } Tells whether the input is in overwrite or insert mode +"fun loadStrings(filename: String): Array? { val `is`: InputStream = createInput(filename) if (`is` != null) return loadStrings(`is`) System.err.println(""The file \""$filename\"" is missing or inaccessible, make sure the URL is valid or that the file has been added to your sketch and is readable."") return null }" "Load data from a file and shove it into a String array . < p/ > Exceptions are handled internally , when an error , occurs , an exception is printed to the console and 'null ' is returned , but the program continues running . This is a tradeoff between 1 ) showing the user that there was a problem but 2 ) not requiring that all i/o code is contained in try/catch blocks , for the sake of new users ( or people who are just trying to get things done in a `` scripting '' fashion . If you want to handle exceptions , use Java methods for I/O ." +"private fun fieldsWithAnnotation(cls: Class<*>): Iterable? { synchronized(mux) { var fields: MutableList? = fieldCache.get(cls) if (fields == null) { fields = ArrayList() for (field in cls.declaredFields) { val ann: Annotation = field.getAnnotation(annCls) if (ann != null || needsRecursion(field)) fields!!.add(field) } if (!fields!!.isEmpty()) fieldCache.put(cls, fields) } return fields } }" Gets all entries from the specified class or its super-classes that have been annotated with annotation provided . +"@Throws(Exception::class) fun mapRelations( `object`: jdk.internal.loader.Resource, jsonObject: JSONObject, included: List? ): jdk.internal.loader.Resource? { val relationshipNames: HashMap = getRelationshipNames(`object`.javaClass) for (relationship in relationshipNames.keySet()) { var relationJsonObject: JSONObject? = null relationJsonObject = try { jsonObject.getJSONObject(relationship) } catch (e: JSONException) { Logger.debug(""Relationship named "" + relationship + ""not found in JSON"") continue } var relationDataObject: JSONObject? = null try { relationDataObject = relationJsonObject.getJSONObject(""data"") var relationObject: jdk.internal.loader.Resource? = Factory.newObjectFromJSONObject(relationDataObject, null) relationObject = matchIncludedToRelation(relationObject, included) mDeserializer.setField(`object`, relationshipNames[relationship], relationObject) } catch (e: JSONException) { Logger.debug(""JSON relationship does not contain data"") } var relationDataArray: JSONArray? = null try { relationDataArray = relationJsonObject.getJSONArray(""data"") var relationArray: List? = Factory.newObjectFromJSONArray(relationDataArray, null) relationArray = matchIncludedToRelation(relationArray, included) mDeserializer.setField(`object`, relationshipNames[relationship], relationArray) } catch (e: JSONException) { Logger.debug(""JSON relationship does not contain data"") } } return `object` }" Loops through relation JSON array and maps annotated objects . +override fun onDestroyView() { mIsWebViewAvailable = false super.onDestroyView() } Called when the WebView has been detached from the fragment . The WebView is no longer available after this time . +fun clearMovementData() {pathSprites = ArrayList() movementTarget = null checkFoVHexImageCacheClear() repaint() refreshMoveVectors() } Clears current movement data from the screen +"@Throws(Exception::class) fun execute( mapping: ActionMapping, form: ActionForm, request: HttpServletRequest, response: HttpServletResponse): ActionForward? { val editRoomDeptForm: EditRoomDeptForm = form as EditRoomDeptForm val rsc: MessageResources = getResources(request) val doit: String = editRoomDeptForm.getDoit() if (doit != null) { if (doit == rsc.getMessage(""button.update"")) { var errors = ActionMessages() errors = editRoomDeptForm.validate(mapping, request) if (errors.size() === 0) { doUpdate(editRoomDeptForm, request) return mapping.findForward(""showRoomDetail"") } else { saveErrors(request, errors) } } if (doit == rsc.getMessage(""button.returnToRoomDetail"")) { response.sendRedirect(""roomDetail.do?id="" + editRoomDeptForm.getId()) return null } if (doit == rsc.getMessage(""button.addRoomDept"")) { if (editRoomDeptForm.getDept() == null || editRoomDeptForm.getDept() .length() === 0 ) { val errors = ActionMessages() errors.add(""roomDept"", ActionMessage(""errors.required"", ""Department"")) saveErrors(request, errors) } else if (editRoomDeptForm.getDepartmentIds() .contains(editRoomDeptForm.getDept()) ) { val errors = ActionMessages() errors.add(""roomDept"", ActionMessage(""errors.alreadyPresent"", ""Department"")) saveErrors(request, errors) } else { editRoomDeptForm.addDepartment(editRoomDeptForm.getDept()) } } if (doit == rsc.getMessage(""button.removeRoomDept"")) { if (editRoomDeptForm.getDept() == null || editRoomDeptForm.getDept() .length() === 0 ) { val errors = ActionMessages() errors.add(""roomDept"", ActionMessage(""errors.required"", ""Department"")) saveErrors(request, errors) } else if (!editRoomDeptForm.getDepartmentIds() .contains(editRoomDeptForm.getDept()) ) { val errors = ActionMessages() errors.add(""roomDept"", ActionMessage(""errors.notPresent"", ""Department"")) saveErrors(request, errors) } else { editRoomDeptForm.removeDepartment(editRoomDeptForm.getDept()) } } } val id: Long = java.lang.Long.valueOf(request.getParameter(""id"")) val ldao = LocationDAO() val location: Location = ldao.get(id) sessionContext.checkPermission(location, Right.RoomEditAvailability) if (doit != null && doit == rsc.getMessage(""button.modifyRoomDepts"")) { val roomDepts = TreeSet(location.getRoomDepts()) val i: Iterator<*> = roomDepts.iterator() while (i.hasNext()) { val roomDept: RoomDept = i.next() as RoomDept editRoomDeptForm.addDepartment(roomDept.getDepartment().getUniqueId().toString()) } } val timeVertical: Boolean = CommonValues.VerticalGrid.eq(UserProperty.GridOrientation.get(sessionContext.getUser())) val rtt: RequiredTimeTable = location.getRoomSharingTable( sessionContext.getUser(), editRoomDeptForm.getDepartmentIds() ) rtt.getModel().setDefaultSelection(UserProperty.GridSize.get(sessionContext.getUser())) if (doit != null && (doit == rsc.getMessage(""button.removeRoomDept"") || doit == rsc.getMessage( ""button.addRoomDept"" )) ) { rtt.update(request) } editRoomDeptForm.setSharingTable(rtt.print(true, timeVertical)) if (location is Room) { val r: Room = location as Room editRoomDeptForm.setName(r.getLabel()) editRoomDeptForm.setNonUniv(false) } else if (location is NonUniversityLocation) { val nonUnivLocation: NonUniversityLocation = location as NonUniversityLocation editRoomDeptForm.setName(nonUnivLocation.getName()) editRoomDeptForm.setNonUniv(true) } else { val errors = ActionMessages() errors.add(""editRoomDept"", ActionMessage(""errors.lookup.notFound"", ""Room Department"")) saveErrors(request, errors) } setupDepartments(editRoomDeptForm, request, location) return mapping.findForward(""showEditRoomDept"") }" Method execute +"fun execute(timeSeries: MetricTimeSeries, functionValueMap: FunctionValueMap) { if (timeSeries.isEmpty()) { functionValueMap.add(this, false, null) return } val points: DoubleList = timeSeries.getValues() val q1: Double = Percentile.evaluate(points, .25) val q3: Double = Percentile.evaluate(points, .75) val threshold = (q3 - q1) * 1.5 + q3 for (i in 0 until points.size()) { val point: Double = points.get(i) if (point > threshold) { functionValueMap.add(this, true, null) return } } functionValueMap.add(this, false, null) }" Detects outliers using the default box plot implementation . An outlier every value that is above ( q3-q1 ) *1.5*q3 where qN is the nth percentile +fun DuplicatePrimaryPartitionException(message: String?) { super(message) } Creates a new < code > DuplicatePrimaryPartitionException < /code > with the given detail message . +fun buildFieldTypes(tableDef: TableDefinition) { (tableDef as JPAMTableDefinition).buildFieldTypes(getSession()) } INTERNAL : builds the field names based on the type read in from the builder +fun clearCache() { softCache = SoftReference>(null) } Clear the cache . This method is used for testing . +fun clear() { oredCriteria.clear() orderByClause = null distinct = false } This method was generated by MyBatis Generator . This method corresponds to the database table activity +protected fun remove(id: Int) { nodes.remove(id) } Removes the node with the specified identifier from this problem instance . +fun addHaptic(id: Int) { mHapticFeedback.add(id) } Adds haptic feedback to this utterance . +"private fun init() { val grid = Grid() appendChild(grid) grid.setWidth(""100%"") grid.setStyle(""margin:0; padding:0; position: absolute;"") grid.makeNoStrip() grid.setOddRowSclass(""even"") val rows: jdk.internal.joptsimple.internal.Rows = jdk.internal.joptsimple.internal.Rows() grid.appendChild(rows) for (i in 0 until m_goals.length) { val row = Row() rows.appendChild(row) row.setWidth(""100%"") val pi = WPerformanceIndicator(m_goals.get(i)) row.appendChild(pi) pi.addEventListener(Events.ON_CLICK, this) } }" Static/Dynamic Init +fun deleteBack(): Int { val oldBack: Int = getBack() size = size - 1 return oldBack } Deletes item from back of the list and returns deleted item . +fun isLicensed(): Boolean { return resourceExists(thresholdFileResource) && resourceExists(overlappingFileResource) } This method returns true if the threshold and overlap files are present . +protected fun SimplePhase(name: String?) { super(name) } Construct a phase given just a name and a global/local ordering scheme . +private fun URIUtil() {} Prevent instance creation . +"@Synchronized fun processResponse( transactionResponse: SIPResponse, sourceChannel: MessageChannel?, dialog: SIPDialog ) { if (getState() == null) return if ((TransactionState.COMPLETED === this.getState() || TransactionState.TERMINATED === this.getState()) && transactionResponse.getStatusCode() / 100 === 1) { return } if (sipStack.isLoggingEnabled()) { sipStack.getStackLogger().logDebug( ""processing "" + transactionResponse.getFirstLine() .toString() + ""current state = "" + getState() ) sipStack.getStackLogger().logDebug(""dialog = $dialog"") } this.lastResponse = transactionResponse try { if (isInviteTransaction()) inviteClientTransaction( transactionResponse, sourceChannel, dialog ) else nonInviteClientTransaction(transactionResponse, sourceChannel, dialog) } catch (ex: IOException) { if (sipStack.isLoggingEnabled()) sipStack.getStackLogger().logException(ex) this.setState(TransactionState.TERMINATED) raiseErrorEvent(SIPTransactionErrorEvent.TRANSPORT_ERROR) } }" "Process a new response message through this transaction . If necessary , this message will also be passed onto the TU ." +"fun disable(adapter: BluetoothAdapter) { var mask: Int = BluetoothReceiver.STATE_TURNING_OFF_FLAG or BluetoothReceiver.STATE_OFF_FLAG or BluetoothReceiver.SCAN_MODE_NONE_FLAG var start: Long = -1 val receiver: BluetoothReceiver = getBluetoothReceiver(mask) var state = adapter.state when (state) { BluetoothAdapter.STATE_OFF -> { assertFalse(adapter.isEnabled) removeReceiver(receiver) return } BluetoothAdapter.STATE_TURNING_ON -> { assertFalse(adapter.isEnabled) start = System.currentTimeMillis() } BluetoothAdapter.STATE_ON -> { assertTrue(adapter.isEnabled) start = System.currentTimeMillis() assertTrue(adapter.disable()) } BluetoothAdapter.STATE_TURNING_OFF -> { assertFalse(adapter.isEnabled) mask = 0 } else -> { removeReceiver(receiver) fail(String.format(""disable() invalid state: state=%d"", state)) } } val s = System.currentTimeMillis() while (System.currentTimeMillis() - s < ENABLE_DISABLE_TIMEOUT) { state = adapter.state if (state == BluetoothAdapter.STATE_OFF && receiver.getFiredFlags() and mask === mask) { assertFalse(adapter.isEnabled) val finish: Long = receiver.getCompletedTime() if (start != -1L && finish != -1L) { writeOutput(String.format(""disable() completed in %d ms"", finish - start)) } else { writeOutput(""disable() completed"") } removeReceiver(receiver) return } sleep(POLL_TIME) } val firedFlags: Int = receiver.getFiredFlags() removeReceiver(receiver) fail( String.format( ""disable() timeout: state=%d (expected %d), flags=0x%x (expected 0x%x)"", state, BluetoothAdapter.STATE_OFF, firedFlags, mask ) ) }" Disables Bluetooth and checks to make sure that Bluetooth was turned off and that the correct actions were broadcast . +fun isLocal(): Boolean { return local } Indicates if the ejb referenced is a local ejb . +"fun PowerDecay() { this(10, 0.5) }" Creates a new Power Decay rate +fun isStorageIORMSupported(): Boolean? { return storageIORMSupported } Gets the value of the storageIORMSupported property . +fun array(): ByteArray { return array } Returns the underlying byte array . +"@Throws(Exception::class) fun buildClassifier(D: Instances) { val r = Random(m_seed) if (fastaram) { networks = arrayOfNulls(numberofnetworks) } else if (sparsearam) { networks = arrayOfNulls(numberofnetworks) } else if (sparsearamH) { networks = arrayOfNulls(numberofnetworks) } else if (sparsearamHT) { networks = arrayOfNulls(numberofnetworks) } else { networks = arrayOfNulls(numberofnetworks) } numClasses = D.classIndex() if (tfastaram) { val bc: Array = arrayOfNulls(numberofnetworks) for (i in 0 until numberofnetworks) { val list: MutableList = ArrayList() for (j in 0 until D.numInstances()) { list.add(j) } Collections.shuffle(list, r) if (fastaram) { networks.get(i) = ARAMNetworkfast() } else if (sparsearam) { networks.get(i) = ARAMNetworkSparse() } else if (sparsearamH) { networks.get(i) = ARAMNetworkSparseV() } else if (sparsearamHT) { networks.get(i) = ARAMNetworkSparseHT() } else { networks.get(i) = ARAMNetwork() } networks.get(i).order = list networks.get(i).roa = roa bc[i] = BuildClassifier(networks.get(i)) bc[i].setinstances(D) bc[i].start() } for (i in 0 until numberofnetworks) { bc[i].join() networks.get(i) = bc[i].m_network networks.get(i).learningphase = false } } else { for (i in 0 until numberofnetworks) { if (fastaram) { networks.get(i) = ARAMNetworkfast() } else if (sparsearam) { networks.get(i) = ARAMNetworkSparse() } else if (sparsearamH) { networks.get(i) = ARAMNetworkSparseV() } else if (sparsearamHT) { networks.get(i) = ARAMNetworkSparseHT() } else { networks.get(i) = ARAMNetwork() } networks.get(i).roa = roa networks.get(i).buildClassifier(D) networks.get(i).learningphase = false D.randomize(r) } } dc = arrayOfNulls(numberofnetworks) }" Generates the classifier . +"private fun startCameraSource() { val code: Int = GoogleApiAvailability.getInstance() .isGooglePlayServicesAvailable(ApplicationProvider.getApplicationContext()) if (code != ConnectionResult.SUCCESS) { val dlg: Dialog = GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS) dlg.show() } if (mCameraSource != null) { try { mPreview.start(mCameraSource, mGraphicOverlay) } catch (e: IOException) { Log.e(TAG, ""Unable to start camera source."", e) mCameraSource.release() mCameraSource = null } } }" "Starts or restarts the camera source , if it exists . If the camera source does n't exist yet ( e.g. , because onResume was called before the camera source was created ) , this will be called again when the camera source is created ." +"fun Timezone(text: String?) { this(null, text) }" Creates a timezone property . +"fun putAt(self: MutableMap, key: K, value: V): V { self[key] = value return value }" A helper method to allow maps to work with subscript operators +"override fun toString(): String? { return toString("","") }" Form a string listing all elements with comma as the separator character . +"@DSSafe(DSCat.SAFE_LIST) @DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2014-09-03 14:59:51.857 -0400"", hash_original_method = ""8DBE36D3CC23C0C9E5FAAD9804EB9F8E"", hash_generated_method = ""B8E268DF01A1D59287B8F2ED5303EAE7"" ) @Throws( IOException::class ) private fun processInput(endOfInput: Boolean) { decoderIn.flip() var coderResult: CoderResult while (true) { coderResult = decoder.decode(decoderIn, decoderOut, endOfInput) if (coderResult.isOverflow()) { flushOutput() } else if (coderResult.isUnderflow()) { break } else { throw IOException(""Unexpected coder result"") } } decoderIn.compact() }" Decode the contents of the input ByteBuffer into a CharBuffer . +fun byte52ToFloat(b: Byte): Float { if (b.toInt() == 0) return 0.0f var bits: Int = b and 0xff shl 24 - 5 bits += 63 - 2 shl 24 return java.lang.Float.intBitsToFloat(bits) } "byteToFloat ( b , mantissaBits=5 , zeroExponent=2 )" +"private fun createAndRegisterObserverProxyLocked(observer: IContentObserver) { check(mObserver == null) { ""an observer is already registered"" } mObserver = ContentObserverProxy(observer, this) mCursor.registerContentObserver(mObserver) }" Create a ContentObserver from the observer and register it as an observer on the underlying cursor . +"fun compressEstim(src: ByteArray?, srcOff: Int, srcLen: Int): Int { var srcOff = srcOff if (srcLen < 10) return srcLen var stride: Int = LZ4_64K_LIMIT - 1 val segments = (srcLen + stride - 1) / stride stride = srcLen / segments if (stride >= LZ4_64K_LIMIT - 1 || stride * segments > srcLen || segments < 1 || stride < 1) throw RuntimeException( ""?? $srcLen"" ) var bytesIn = 0 var bytesOut = 0 var len = srcLen while (len > 0) { if (len > stride) len = stride bytesOut += compress64k(src, srcOff, len) srcOff += len bytesIn += len len = srcLen - bytesIn } val ratio = bytesOut / bytesIn.toDouble() return if (bytesIn == srcLen) bytesOut else (ratio * srcLen + 0.5).toInt() }" "Estimates the length of the compressed bytes , as compressed by Lz4 WARNING : if larger than LZ4_64K_LIMIT it cuts it in fragments WARNING : if some part of the input is discarded , this should return the proportional ( so that returnValue/srcLen=compressionRatio )" +fun eIsSet(featureID: Int): Boolean { when (featureID) { N4JSPackage.ARRAY_LITERAL__ELEMENTS -> return elements != null && !elements.isEmpty() N4JSPackage.ARRAY_LITERAL__TRAILING_COMMA -> return trailingComma !== TRAILING_COMMA_EDEFAULT } return super.eIsSet(featureID) } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +fun FilterStreamSpecRaw() {} Default ctor . +fun onMenuVisibilityChanged(isVisible: Boolean) { for (i in 0 until mObservers.size()) { mObservers.get(i).onMenuVisibilityChanged(isVisible) } } Called by AppMenu to report that the App Menu visibility has changed . +fun updateDownload() { val ongoingDownloads: ArrayList = getOngoingDownloads() if (!ongoingDownloads.isEmpty()) { updateProgress() } else { timer.cancel() timer.purge() stopSelf() mBuilder = null stopForeground(true) isStopped = true } } "Updates the download list and stops the service if it 's empty . If not , updates the progress in the Notification bar" +"private fun remoteAddPois(pois: List, changeSetId: String): Int { var count = 0 for (poi in pois) { if (remoteAddPoi(poi, changeSetId)) { count++ } } return count }" Add a List of POIs to the backend . +fun CopyOnWriteArraySet(c: Collection?) { al = CopyOnWriteArrayList() al.addAllAbsent(c) } Creates a set containing all of the elements of the specified collection . +@Throws(SQLException::class) fun close() { try { super.close() } finally { this.outputLogger.close() } } This method will close the connection to the output . +"@DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2013-12-30 12:55:41.688 -0500"", hash_original_method = ""1623111994CBCA0890DA0FF2A1E140E0"", hash_generated_method = ""478ACA79A313929F4EF55B9242DEEF4D"" ) fun isBackToBackUserAgent(): Boolean { return super.isBackToBackUserAgent }" Get the `` back to back User Agent '' flag . return the value of the flag +"fun EnglishMinimalStemFilterFactory(args: Map) { super(args) require(args.isEmpty()) { ""Unknown parameters: $args"" } }" Creates a new EnglishMinimalStemFilterFactory +"fun AABB(pos: ReadonlyVec3D?, extent: Float) { super(pos) setExtent(Vec3D(extent, extent, extent)) }" Creates a new instance from centre point and uniform extent in all directions . +fun subscriber(): JavaslangSubscriber? { return JavaslangSubscriber() } A reactive-streams subscriber than can generate Javaslang traversable types +"fun SQLNonTransientException(reason: String?, cause: Throwable?) { super(reason, cause) }" Creates an SQLNonTransientException object . The Reason string is set to the given and the cause Throwable object is set to the given cause Throwable object . +fun localTransactionCommitted(event: ConnectionEvent?) {} Ignored event callback +"protected fun runAndReset(): Boolean { if (state !== NEW || !UNSAFE.compareAndSwapObject( this, runnerOffset, null,Thread.currentThread() ) ) return false var ran = false var s: Int = state try { val c: Callable = callable if (c != null && s == NEW) { try { c.call() ran = true } catch (ex: Throwable) { setException(ex) } } } finally { runner = null s = state if (s >= INTERRUPTING) handlePossibleCancellationInterrupt(s) } return ran && s == NEW }" "Executes the computation without setting its result , and then resets this future to initial state , failing to do so if the computation encounters an exception or is cancelled . This is designed for use with tasks that intrinsically execute more than once ." +fun addCookie(cookie: GoogleCookie?) { if (cookieManager != null) { cookieManager.addCookie(cookie) } } Adds a new GoogleCookie instance to the cache . +"fun debug(trace: String?) { printTrace(trace, DEBUG_LEVEL) }" Debug trace +fun isAutoIndentEnabled(): Boolean { return autoIndentEnabled } Returns whether or not auto-indent is enabled . +"fun disableHardwareLayersForContent() { val widget: View = org.jcp.xml.dsig.internal.dom.DOMKeyInfo.getContent() if (widget != null) { widget.setLayerType(LAYER_TYPE_NONE, null) } }" "Because this view has fading outlines , it is essential that we enable hardware layers on the content ( child ) so that updating the alpha of the outlines does n't result in the content layer being recreated ." + Construct payment gateway descriptor . +"@Throws(ParseException::class) fun parseDateLong(dateString: String?, pattern: String?): Date? { return getSimplDateFormat(pattern).parse(dateString) }" Returns date parsed from string by given pattern +"fun add(i: Int, coord: Coordinate?, allowRepeated: Boolean) { if (!allowRepeated) { val size: Int = size() if (size > 0) { if (i > 0) { val prev: Coordinate = get(i - 1) as Coordinate if (prev.equals2D(coord)) return } if (i < size) { val next: Coordinate = get(i) as Coordinate if (next.equals2D(coord)) return } } } super.add(i, coord) }" Inserts the specified coordinate at the specified position in this list . +"private fun loadAppThemeDefaults() { val typedValue = TypedValue() val a = context!!.obtainStyledAttributes( typedValue.data, intArrayOf(attr.colorAccent, attr.textColorPrimary, attr.colorControlNormal) ) dialColor = a.getColor(0, dialColor) textColor = a.getColor(1, textColor) clockColor = a.getColor(2, clockColor) a.recycle() }" Sets default theme attributes for picker These will be used if picker 's attributes are'nt set +fun increaseRefcount() { refcount++ } Increase number of data points by one . +"fun computePolygonAreaFromVertices(points: Iterable?): Double { if (points == null) { val message: String = Logging.getMessage(""nullValue.IterableIsNull"") Logging.logger().severe(message) throw IllegalArgumentException(message) } val iter: Iterator = points.iterator() if (!iter.hasNext()) { return 0 } var area = 0.0 val firstPoint: Vec4? = iter.next() var point: Vec4? = firstPoint while (iter.hasNext()) { val nextLocation: Vec4? = iter.next() area += point.x * nextLocation.y area -= nextLocation.x * point.y point = nextLocation } if (!point.equals(firstPoint)) { area += point.x * firstPoint.y area -= firstPoint.x * point.y } area /= 2.0 return area }" "Returns the area enclosed by the specified ( x , y ) points ( the z and w coordinates are ignored ) . If the specified points do not define a closed loop , then the loop is automatically closed by simulating appending the first point to the last point ." +fun init(param: KeyGenerationParameters) { this.params = param as NTRUEncryptionKeyGenerationParameters } Constructs a new instance with a set of encryption parameters . +"fun createDemoPanel(): javax.swing.JPanel? { val chart: JFreeChart = createChart(createDataset()) val panel = ChartPanel(chart, false) panel.setFillZoomRectangle(true) panel.setMouseWheelEnabled(true) return panel }" Creates a panel for the demo ( used by SuperDemo.java ) . +"@Throws(Throwable::class) fun deleteVMsOnThisEndpoint( host: VerificationHost?, isMock: Boolean, parentComputeLink: String?, instanceIdsToDelete: List? ) { deleteVMsOnThisEndpoint(host, null, isMock, parentComputeLink, instanceIdsToDelete, null) }" A utility method that deletes the VMs on the specified endpoint filtered by the instanceIds that are passed in . +fun isIn(i: Byte): Boolean { return i >= this.min && i <= this.max } Check if given number is in range . +"fun completeAll() { val currentCompleted: Long = completedCount val size = Math.max(1, actionList.size()) while (completedCount - currentCompleted < size) { if (getState() !== Thread.State.BLOCKED && getState() !== Thread.State.RUNNABLE) break try { Thread.sleep(50) } catch (ex: InterruptedException) { break } } }" "< p > Complete all scheduled actions at the time of this call . Since other threads may keep adding actions , this method makes sure that only the actions in the queue at the time of the call are waited upon . < /p >" +override fun toString(): String? { return image } Returns the image . +fun KtVisualPanel1() { initComponents() } Creates new form KtVisualPanel1 +"@Throws(MalformedURIException::class) fun URI(p_scheme: String?, p_schemeSpecificPart: String?) { if (p_scheme == null || p_scheme.trim { it <= ' ' }.length == 0) { throw MalformedURIException(""Cannot construct URI with null/empty scheme!"") } if (p_schemeSpecificPart == null || p_schemeSpecificPart.trim { it <= ' ' }.length == 0) { throw MalformedURIException(""Cannot construct URI with null/empty scheme-specific part!"") } setScheme(p_scheme) setPath(p_schemeSpecificPart) }" Construct a new URI that does not follow the generic URI syntax . Only the scheme and scheme-specific part ( stored as the path ) are initialized . +fun isDoingRangedAttack(): Boolean { return isDoingRangedAttack } Check if the currently performed attack is ranged . +"@Throws(IOException::class) fun SdfReaderWrapper(sdfDir: File?, useMem: Boolean, checkConsistency: Boolean) { mIsPaired = jdk.internal.org.jline.reader.impl.ReaderUtils.isPairedEndDirectory(sdfDir) if (mIsPaired) { mSingle = null mLeft = createSequencesReader( jdk.internal.org.jline.reader.impl.ReaderUtils.getLeftEnd(sdfDir), useMem ) mRight = createSequencesReader( jdk.internal.org.jline.reader.impl.ReaderUtils.getRightEnd(sdfDir), useMem ) if (checkConsistency) { if (mLeft.numberSequences() !== mRight.numberSequences() || !mLeft.type() .equals(mRight.type()) || mLeft.hasQualityData() !== mRight.hasQualityData() || mLeft.hasNames() !== mRight.hasNames() ) { throw NoTalkbackSlimException( ErrorType.INFO_ERROR, ""Paired end SDF has inconsistencies between arms."" ) } } } else { mLeft = null mRight = null mSingle = createSequencesReader(sdfDir, useMem) } }" Wrapper for the readers . +fun DefaultRenderStack() { stack = ArrayDeque() } Constructs the stack . +"fun onLocationChanged(location: Location?) { if (location == null) { return } val distance: Float = getDistanceFromNetwork(location) mTrackerData.writeEntry(location, distance) }" "Writes details of location update to tracking file , including recording the distance between this location update and the last network location update" +"fun secondaryIndexFileName(data: File): File? { val extensionIndex: Int = data.getName().lastIndexOf('.') return if (extensionIndex != -1) { File( data.getParentFile(), data.getName().substring(0, extensionIndex) + BamIndexer.BAM_INDEX_EXTENSION ) } else indexFileName(data) }" Get the secondary possible name for an index to have for a given data file ( Will return same as indexFileName if there is no file extension ) +"@Throws(IOException::class) private fun cancelOrder(contract: Contract, order: TradeOrder) { val orderState = OrderState() orderState.m_status = OrderStatus.CANCELLED this.brokerModel.openOrder(order.getOrderKey(), contract, order, orderState) order.setStatus(OrderStatus.CANCELLED) }" Method cancelOrder . +"private fun TempTripleStore(store: TemporaryStore, properties: Properties) { this(store, UUID.randomUUID().toString() + ""kb"", ITx.UNISOLATED, properties) }" Note : This is here just to make it easy to have the reference to the [ store ] and its [ uuid ] when we create one in the calling ctor . +"fun newSameSize(list: List<*>?, cpType: Class?): Array? { return if (list == null) create(cpType, 0) else create(cpType, list.size) }" "Creates an array with the same size as the given list . If the list is null , a zero-length array is created ." +fun addPaintListener(pl: PaintListener?) { if (m_painters == null) { m_painters = CopyOnWriteArrayList() } m_painters.add(pl) } Add a PaintListener to this Display to receive notifications about paint events . +fun isNamed(): Boolean { return flags and NO_NAME === 0 } Returns true if this method is anonymous . +"fun CopyOnWriteMap() { internalMap = HashMap() }" Creates a new instance of CopyOnWriteMap . +"fun runTrialParallel( size: Int,set: TrialSuite,pts: Array,selector: IPivotIndex?,numThreads: Int,ratio: Int) {val ar = arrayOfNulls(size) run { var i = 0 var idx = 0 while (i < pts.size) { ar[idx++] = (pts[i].getX() * BASE) as Int ar[idx++] = (pts[i].getY() * BASE) as Int i++ } } val qs: MultiThreadQuickSort = MultiThreadQuickSort(ar) qs.setPivotMethod(selector) qs.setNumberHelperThreads(numThreads) qs.setThresholdRatio(ratio) System.gc() val start = System.currentTimeMillis() qs.qsort(0, size - 1) val end = System.currentTimeMillis() set.addTrial(size, start, end) for (i in 0 until ar.size - 1) { assert(ar[i]!! <= ar[i + 1]!!) } }" Change the number of helper threads inside to try different configurations . < p > Set to NUM_THREADS by default . +"private fun initResumableMediaRequest( request: GDataRequest, file: MediaFileSource, title: String ) { initMediaRequest(request, title) request.setHeader(GDataProtocol.Header.X_UPLOAD_CONTENT_TYPE, file.getContentType()) request.setHeader( GDataProtocol.Header.X_UPLOAD_CONTENT_LENGTH, file.getContentLength().toString() ) }" Initialize a resumable media upload request . +fun toShortArray(array: Array): ShortArray? { val result = ShortArray(array.size) for (i in array.indices) { result[i] = array[i] } return result } Coverts given shorts array to array of shorts . +"fun createTable(db: SQLiteDatabase, ifNotExists: Boolean) { val constraint = if (ifNotExists) ""IF NOT EXISTS "" else """" db.execSQL(""CREATE TABLE $constraint'SIMPLE_ADDRESS_ITEM' ('_id' INTEGER PRIMARY KEY ,'NAME' TEXT,'ADDRESS' TEXT,'CITY' TEXT,'STATE' TEXT,'PHONE' INTEGER);"") }" Creates the underlying database table . +"fun eInverseRemove(otherEnd: InternalEObject?,featureID: Int,msgs: NotificationChain?): NotificationChain? {when (featureID) { UmplePackage.ABSTRACT_METHOD_DECLARATION___METHOD_DECLARATOR_1 -> return (getMethodDeclarator_1() as InternalEList<*>).basicRemove( otherEnd, msgs ) } return super.eInverseRemove(otherEnd, featureID, msgs) }" < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"protected fun emit_N4SetterDeclaration_SemicolonKeyword_5_q( semanticObject: EObject?, transition: ISynNavigable?, nodes: List? ) { acceptNodes(transition, nodes) }" Ambiguous syntax : ' ; ' ? This ambiguous syntax occurs at : body=Block ( ambiguity ) ( rule end ) fpar=FormalParameter ' ) ' ( ambiguity ) ( rule end ) +"private fun updateProgress(progressLabel: String, progress: Int) { if (myHost != null && (progress != previousProgress || progressLabel != previousProgressLabel)) { myHost.updateProgress(progressLabel, progress) } previousProgress = progress previousProgressLabel = progressLabel }" Used to communicate a progress update between a plugin tool and the main Whitebox user interface . +"@Throws(FitsException::class) fun FitsDate(dStr: String?) { if (dStr == null || dStr.isEmpty()) { return } var match: Matcher = FitsDate.NORMAL_REGEX.matcher(dStr) if (match.matches()) { this.year = getInt(match, FitsDate.NEW_FORMAT_YEAR_GROUP) this.month = getInt(match, FitsDate.NEW_FORMAT_MONTH_GROUP) this.mday = getInt(match, FitsDate.NEW_FORMAT_DAY_OF_MONTH_GROUP) this.hour = getInt(match, FitsDate.NEW_FORMAT_HOUR_GROUP) this.minute = getInt(match, FitsDate.NEW_FORMAT_MINUTE_GROUP) this.second = getInt(match, FitsDate.NEW_FORMAT_SECOND_GROUP) this.millisecond = jdk.nashorn.internal.objects.NativeDate.getMilliseconds( match, FitsDate.NEW_FORMAT_MILLISECOND_GROUP ) } else { match = FitsDate.OLD_REGEX.matcher(dStr) if (match.matches()) { this.year = getInt(match, FitsDate.OLD_FORMAT_YEAR_GROUP) + FitsDate.YEAR_OFFSET this.month = getInt(match, FitsDate.OLD_FORMAT_MONTH_GROUP) this.mday = getInt(match, FitsDate.OLD_FORMAT_DAY_OF_MONTH_GROUP) } else { if (dStr.trim { it <= ' ' }.isEmpty()) { return } throw FitsException(""Bad FITS date string \""$dStr\"""") } } }" Convert a FITS date string to a Java < CODE > Date < /CODE > object . +"fun fromBytes(value: ByteArray?, clazz: Class): T { return try { val input = Input(ByteArrayInputStream(value)) clazz.cast(kryo.get().readClassAndObject(input)) } catch (t: Throwable) { LOG.error(""Unable to deserialize because "" + t.message, t) throw t } }" Deserialize a profile measurement 's value . The value produced by a Profile definition can be any numeric data type . The data type depends on how the profile is defined by the user . The user should be able to choose the data type that is most suitable for their use case . +"fun SequencesWriter( source: SequenceDataSource?, outputDir: File?, sizeLimit: Long, type: PrereadType?, compressed: Boolean ) { this(source, outputDir, sizeLimit, null, type, compressed, null) }" Creates a writer for processing sequences from provided data source . +fun allowStyling(): HtmlPolicyBuilder? { allowStyling(CssSchema.DEFAULT) return this } "Convert < code > style= '' & lt ; CSS & gt ; '' < /code > to sanitized CSS which allows color , font-size , type-face , and other styling using the default schema ; but which does not allow content to escape its clipping context ." +"private fun PhoneUtil() { throw Error(""Do not need instantiate!"") }" Do n't let anyone instantiate this class . +fun unregisterTap(tap: Tap?) { mTaps.remove(tap) } Remove instrumentation tap +fun isNavBarTintEnabled(): Boolean { return mNavBarTintEnabled } Is tinting enabled for the system navigation bar ? +"override fun equals(other: Any?): Boolean { return if (_map.equals(other)) { true } else if (other is Map<*, *>) { val that = other if (that.size != _map.size()) { false } else { val it: Iterator<*> = that.entries.iterator() var i = that.size while (i-- > 0) { val (key1, value) = it.next() as Map.Entry<*, *> val key = key1!! val `val` = value!! if (key is Float) { val k: Float = unwrapKey(key) val v: Any = unwrapValue(`val` as V) if (_map.containsKey(k) && v === _map.get(k)) { } else { return false } } else { return false } } true } } else { false } }" Compares this map with another map for equality of their stored entries . +private fun declareExtensions() { BlogCommentFeed().declareExtensions(extProfile) BlogFeed().declareExtensions(extProfile) BlogPostFeed().declareExtensions(extProfile) PostCommentFeed().declareExtensions(extProfile) } Declare the extensions of the feeds for the Blogger service . +fun eIsSet(featureID: Int): Boolean { when (featureID) { UmplePackage.ANONYMOUS_GEN_EXPR_2__INDEX_1 -> return if (INDEX_1_EDEFAULT == null) index_1 != null else !INDEX_1_EDEFAULT.equals( index_1 ) } return super.eIsSet(featureID) } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +fun sequence(name: String?): ReferenceSequence? { return mReferences.get(name) } Get the < code > ReferenceSequence < /code > selected by name . +"private fun ChainBuilder(frame: javax.swing.JFrame) { super(java.awt.BorderLayout()) frame = frame THIS = this val customPanel: javax.swing.JPanel = createCustomizationPanel() val presetPanel: javax.swing.JPanel = createPresetPanel() label = javax.swing.JLabel( ""Click the \""Begin Generating\"" button"" + "" to begin generating phrases"", javax.swing.JLabel.CENTER ) val padding: javax.swing.border.Border = javax.swing.BorderFactory.createEmptyBorder(20, 20, 5, 20) customPanel.setBorder(padding) presetPanel.setBorder(padding) val tabbedPane: javax.swing.JTabbedPane = javax.swing.JTabbedPane() tabbedPane.addTab(""Build your own"", null, customPanel, customizationPanelDescription) tabbedPane.addTab(""Presets"", null, presetPanel, presetPanelDescription) add(tabbedPane, java.awt.BorderLayout.CENTER) add(label, java.awt.BorderLayout.PAGE_END) label.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10)) }" Creates the GUI shown inside the frame 's content pane . +override fun toString(): String? { return this.materialPackageBO.toString() } A method that returns a string representation of a parsed MaterialPackage object +protected fun VirtualBaseTypeImpl() { super() } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"private fun removeParserNotices(parser: Parser) { if (noticesToHighlights != null) { val h: RSyntaxTextAreaHighlighter = textArea.getHighlighter() as RSyntaxTextAreaHighlighter val i: MutableIterator<*> = noticesToHighlights.entrySet().iterator() while (i.hasNext()) { val (key, value) = i.next() as Map.Entry<*, *> val notice: ParserNotice = key as ParserNotice if (notice.getParser() === parser && value != null) { h.removeParserHighlight(value) i.remove() } } } }" Removes all parser notices ( and clears highlights in the editor ) from a particular parser . +"fun TextLineDecoder(charset: Charset?, delimiter: String?) { this(charset, LineDelimiter(delimiter)) }" Creates a new instance with the spcified < tt > charset < /tt > and the specified < tt > delimiter < /tt > . +"fun resetViewableArea() { throw RuntimeException(""resetViewableArea called in PdfDecoderFx"") }" "NOT PART OF API turns off the viewable area , scaling the page back to original scaling" +private fun postResults() { this.reportTestCase.host.updateSystemInfo(false) this.trState.systemInfo = this.reportTestCase.host.getSystemInfo() val factoryPost: Operation = Operation.createPost(this.remoteTestResultService) .setReferer(this.reportTestCase.host.getReferer()).setBody(this.trState) .setCompletion(null) this.reportTestCase.host.testStart(1) this.reportTestCase.host.sendRequest(factoryPost) try { this.reportTestCase.host.testWait() } catch (throwable: Throwable) { throwable.printStackTrace() } } "Send current test state to a remote server , by creating an instance for this particular run ." +fun clear(iterator: MutableIterator<*>) { checkNotNull(iterator) while (iterator.hasNext()) { iterator.next() iterator.remove() } } Clears the iterator using its remove method . +fun isTop(fact: BitSet): Boolean { return fact[topBit] } Return whether or not given fact is the special TOP value . +fun eraseMap() { if (MAP_STORE.getMap(MAP_STORE.getSelectedMapName()) == null) { return } for (r in MAP_STORE.getMap(MAP_STORE.getSelectedMapName()).getRoutes()) { eraseRoute(r) } } Non-destructively erases all displayed content from the map display +"fun doTestTransfer(size: Int) { Thread.setDefaultUncaughtExceptionHandler(this) val start: Long val elapsed: Long val received: Int sendData = createDummyData(size) sendStreamSize = size recvStream = ByteArrayOutputStream(size) start = PseudoTCPBase.now() startClocks() try { connect() } catch (ex: IOException) { fail(ex.getMessage()) } assert_Connected_wait(kConnectTimeoutMs) val transferTout: Long = maxTransferTime(sendData.length, kMinTransferRate) val transfferInTime: Boolean = assert_Disconnected_wait(transferTout) elapsed = PseudoTCPBase.now() - start stopClocks() received = recvStream.size() assertEquals( ""Transfer timeout, transferred: "" + received + "" required: "" + sendData.length + "" elapsed: "" + elapsed + "" limit: "" + transferTout, true, transfferInTime ) assertEquals(size, received) val recvdArray: ByteArray = recvStream.toByteArray() assertArrayEquals(sendData, recvdArray) logger.log( Level.INFO, ""Transferred "" + received + "" bytes in "" + elapsed + "" ms ("" + size * 8 / elapsed + "" Kbps"" ) }" Transfers the data of < tt > size < /tt > bytes +"protected fun sequence_SkillFakeDefinition( context: ISerializationContext?, semanticObject: SkillFakeDefinition ) { if (errorAcceptor != null) { if (transientValues.isValueTransient( semanticObject, GamlPackage.Literals.GAML_DEFINITION__NAME ) === ValueTransient.YES ) errorAcceptor.accept( diagnosticProvider.createFeatureValueMissing( semanticObject, GamlPackage.Literals.GAML_DEFINITION__NAME ) ) } val feeder: SequenceFeeder = createSequencerFeeder(context, semanticObject) feeder.accept( grammarAccess.getSkillFakeDefinitionAccess().getNameIDTerminalRuleCall_1_0(), semanticObject.getName() ) feeder.finish() }" Contexts : GamlDefinition returns SkillFakeDefinition SkillFakeDefinition returns SkillFakeDefinition Constraint : name=ID +fun closeDriver() { if (camera != null) { FlashlightManager.disableFlashlight() camera.release() camera = null } } Closes the camera driver if still in use . +"@Throws(PageException::class) fun removeSecurityManager(password: sun.security.util.Password?, id: String) { checkWriteAccess() (ConfigImpl.getConfigServer(config, password) as ConfigServerImpl).removeSecurityManager(id) val security: Element = _getRootElement(""security"") val children: Array = XMLConfigWebFactory.getChildren(security, ""accessor"") for (i in children.indices) { if (id == children[i].getAttribute(""id"")) { security.removeChild(children[i]) } } }" remove security manager matching given id +"fun circle(x: Double, y: Double, r: Double) { require(r >= 0) { ""circle radius must be nonnegative"" } val xs: Double = scaleX(x) val ys: Double = scaleY(y) val ws: Double = factorX(2 * r) val hs: Double = factorY(2 * r) if (ws <= 1 && hs <= 1) pixel( x, y ) else offscreen.draw(java.awt.geom.Ellipse2D.Double(xs - ws / 2, ys - hs / 2, ws, hs)) draw() }" "Draw a circle of radius r , centered on ( x , y ) ." +"fun run() { amIActive = true val inputFile: String = args.get(0) if (inputFile.lowercase(Locale.getDefault()).contains("".dep"")) { calculateRaster() } else if (inputFile.lowercase(Locale.getDefault()).contains("".shp"")) { calculateVector() } else { showFeedback(""There was a problem reading the input file."") } }" Used to execute this plugin tool . +"private fun create(cls: Class, qname: QName): T { return Configuration.getBuilderFactory().getBuilder(qname).buildObject(qname) }" Create object using OpenSAML 's builder system . +fun createHttpConnection(): HttpConnection? { return AndroidHttpConnection() } Create an HTTP connection +"private fun parseWaveformsFromJsonFile(waveformsFile: File): Map? { var waveformsMap: Map? try { waveformsMap = parseJsonFile(waveformsFile) as Map? LOG.info(""Loaded waveform images from {}"", waveformsFile) } catch (exception: IOException) { waveformsMap = HashMap() LOG.error(""Error loading waveform thumbnails: {}"", exception.getMessage(), exception) } return waveformsMap }" Loads the waveforms from a saved file formatted in JSON +"fun drawShape(gl: GL2?, s: Shape?, points: Boolean) { if (s is Circle) { RenderUtilities.drawCircle(gl, s as Circle?, points, true) } else if (s is java.awt.Rectangle) { RenderUtilities.drawRectangle(gl, s as java.awt.Rectangle?, points) } else if (s is java.awt.Polygon) { RenderUtilities.drawPolygon(gl, s as java.awt.Polygon?, points) } else if (s is javax.swing.text.Segment) { RenderUtilities.drawLineSegment(gl, s as javax.swing.text.Segment?, points) } else { } }" Draws the given shape . +"@Throws(IOException::class) fun write(writer: Writer) { val map: MutableMap = HashMap() map[""vcards""] = vcards map[""utils""] = TemplateUtils() map[""translucentBg""] = readImage(""translucent-bg.png"", ImageType.PNG) map[""noProfile""] = readImage(""no-profile.png"", ImageType.PNG) map[""ezVCardVersion""] = Ezvcard.VERSION map[""ezVCardUrl""] = Ezvcard.URL map[""scribeIndex""] = ScribeIndex() try { template.process(map, writer) } catch (e: TemplateException) { throw RuntimeException(e) } writer.flush() }" Writes the HTML document to a writer . +"fun toString(field: String): String? { val buffer = StringBuilder() if (sun.reflect.misc.FieldUtil.getField() != field) { buffer.append(sun.reflect.misc.FieldUtil.getField()) buffer.append("":"") } buffer.append(if (includeLower) '[' else '{') buffer.append( if (lowerTerm != null) if (""*"" == Term.toString(lowerTerm)) ""\\*"" else Term.toString( lowerTerm ) else ""*"" ) buffer.append("" TO "") buffer.append( if (upperTerm != null) if (""*"" == Term.toString(upperTerm)) ""\\*"" else Term.toString( upperTerm ) else ""*"" ) buffer.append(if (includeUpper) ']' else '}') return buffer.toString() }" Prints a user-readable version of this query . +"@Throws(ReplicatorException::class, InterruptedException::class) fun prepare(context: PluginContext?) { logger.info( ""Import tables from "" + this.uri.getPath() .toString() + "" to the "" + this.getDefaultSchema().toString() + "" schema"" ) tableNames = ArrayList() columnDefinitions = HashMap>() parser = CSVParser(',', '""') val importDirectory = File(this.uri.getPath()) if (!importDirectory.exists()) { throw ReplicatorException( ""The "" + this.uri.getPath().toString() + "" directory does not exist"" ) } for (f in importDirectory.listFiles()) { if (f.getName().endsWith("".def"")) { this.prepareTableDefinition(f) } } if (this.tableNames.size() === 0) { throw ReplicatorException(""There are no tables to load"") } }" Prepare plug-in for use . This method is assumed to allocate all required resources . It is called before the plug-in performs any operations . +"fun plot(draw: AbstractDrawer) { if (!visible) return draw.setColor(color) draw.setFont(font) draw.setBaseOffset(base_offset) draw.setTextOffset(cornerE, cornerN) draw.setTextAngle(angle) draw.drawText(label, coord) draw.setBaseOffset(null) }" see Text for formatted text output +"fun testShiftRight4() { val aBytes = byteArrayOf(1, -128, 56, 100, -2, -76, 89, 45, 91, 3, -15, 35, 26) val aSign = 1 val number = 45 val rBytes = byteArrayOf(12, 1, -61, 39, -11, -94, -55) val aNumber = BigInteger(aSign, aBytes) val result: BigInteger = aNumber.shiftRight(number) var resBytes = ByteArray(rBytes.size) resBytes = result.toByteArray() for (i in resBytes.indices) { assertTrue(resBytes[i] == rBytes[i]) } assertEquals(""incorrect sign"", 1, result.signum()) }" "shiftRight ( int n ) , n > 32" +fun fixStatsError(sendCommand: Int) { while (this.affectedRows.length < sendCommand) { this.affectedRows.get(currentStat++) = Statement.EXECUTE_FAILED } } Add missing information when Exception is thrown . +"@Throws(IOException::class) fun readRawBytes(size: Int): ByteArray? { if (size < 0) { throw InvalidProtocolBufferNanoException.negativeSize() } if (bufferPos + size > currentLimit) { skipRawBytes(currentLimit - bufferPos) throw InvalidProtocolBufferNanoException.truncatedMessage() } return if (size <= bufferSize - bufferPos) { val bytes = ByteArray(size) System.arraycopy(buffer, bufferPos, bytes, 0, size) bufferPos += size bytes } else { throw InvalidProtocolBufferNanoException.truncatedMessage() } }" Read a fixed size of bytes from the input . +private fun resetToXMLSAXHandler() { this.m_escapeSetting = true } Reset all of the fields owned by ToXMLSAXHandler class +"fun cuCmplx(r: Float, i: Float): cuComplex? { val res = cuComplex() res.x = r res.y = i return res }" Creates a new complex number consisting of the given real and imaginary part . +"fun make( rawSig: String?, f: sun.reflect.generics.factory.GenericsFactory? ): sun.reflect.generics.repository.MethodRepository? { return sun.reflect.generics.repository.MethodRepository(rawSig, f) }" Static factory method . +fun add(`object`: T?) { mObjects.add(`object`) notifyItemInserted(getItemCount() - 1) } Adds the specified object at the end of the array . +"fun compareHardware(hwMap: Map, checkDisk: Boolean): String? { val localMemSizeStr: String = ServerProbe.getInstance().getMemorySize() val localCpuCoreStr: String = ServerProbe.getInstance().getCpuCoreNum() hwMap[PropertyConstants.PROPERTY_KEY_DISK_CAPACITY] if (localMemSizeStr != hwMap[PropertyConstants.PROPERTY_KEY_MEMORY_SIZE]) { log.warn( ""Local memory {} is not the same as selected cluster {}"", localMemSizeStr, hwMap[PropertyConstants.PROPERTY_KEY_MEMORY_SIZE] ) return String.format( ""Local memory {%s} is not the same as selected cluster {%s}"", localMemSizeStr, hwMap[PropertyConstants.PROPERTY_KEY_MEMORY_SIZE] ) } if (localCpuCoreStr != hwMap[PropertyConstants.PROPERTY_KEY_CPU_CORE]) { log.warn( ""Local CPU core number {} is not the same as selected cluster {}"", localCpuCoreStr, hwMap[PropertyConstants.PROPERTY_KEY_CPU_CORE] )return String.format( ""Local CPU core number {%s} is not the same as selected cluster {%s}"", localCpuCoreStr, hwMap[PropertyConstants.PROPERTY_KEY_CPU_CORE] ) } if (checkDisk && !hasSameDiskInfo( hwMap[PropertyConstants.PROPERTY_KEY_DISK], hwMap[PropertyConstants.PROPERTY_KEY_DISK_CAPACITY] ) ) { log.warn( ""Local disk(s) are not the same as selected cluster capacity {}"", hwMap[PropertyConstants.PROPERTY_KEY_DISK_CAPACITY] ) return String.format( ""Local disk(s) are not the same as selected cluster capacity {%s}"", hwMap[PropertyConstants.PROPERTY_KEY_DISK_CAPACITY] ) } return null }" "Check local node hardware ( i.e . Memory size , CPU core , Disk Capacity ) are the same as in the input map ." +"fun tearDown(bot: SWTWorkbenchBot) { SwtBotUtils.print(""Tear Down"") bot.resetWorkbench() SwtBotUtils.print(""Tear Down "") }" Performs the necessary tear down work for most SWTBot tests . +"private fun handleMessage(data: ByteArray) { val buffer = Buffer() buffer.write(data) val type: Int = buffer.readShort() and 0xffff and APP_MSG_RESPONSE_BIT.inv() if (type == BeanMessageID.SERIAL_DATA.getRawValue()) beanListener.onSerialMessageReceived(buffer.readByteArray()) } else if (type == BeanMessageID.BT_GET_CONFIG.getRawValue()) { returnConfig(buffer) } else if (type == BeanMessageID.CC_TEMP_READ.getRawValue()) { returnTemperature(buffer) } else if (type == BeanMessageID.BL_GET_META.getRawValue()) { returnMetadata(buffer) } else if (type == BeanMessageID.BT_GET_SCRATCH.getRawValue()) { returnScratchData(buffer) } else if (type == BeanMessageID.CC_LED_READ_ALL.getRawValue()) { returnLed(buffer) } else if (type == BeanMessageID.CC_ACCEL_READ.getRawValue()) { returnAcceleration(buffer) } else if (type == BeanMessageID.CC_ACCEL_GET_RANGE.getRawValue()) { returnAccelerometerRange(buffer) } else if (type == BeanMessageID.CC_GET_AR_POWER.getRawValue()) { returnArduinoPowerState(buffer) } else if (type == BeanMessageID.BL_STATUS.getRawValue()) { try { val status: Status = Status.fromPayload(buffer) handleStatus(status) } catch (e: NoEnumFoundException) { Log.e(TAG, ""Unable to parse status from buffer: "" + buffer.toString()) e.printStackTrace() } } else { var fourDigitHex = Integer.toHexString(type) while (fourDigitHex.length < 4) { fourDigitHex = ""0$fourDigitHex"" } Log.e(TAG, ""Received message of unknown type 0x$fourDigitHex"") returnError(BeanError.UNKNOWN_MESSAGE_ID) } }" Handles incoming messages from the Bean and dispatches them to the proper handlers . +"fun newEmptyHashMap(iterable: Iterable<*>?): HashMap? { return if (iterable is Collection<*>) Maps.newHashMapWithExpectedSize( iterable.size ) else Maps.newHashMap() }" "Returns an empty map with expected size matching the iterable size if it 's of type Collection . Otherwise , an empty map with the default size is returned ." +"fun calculateScrollY(firstVisiblePosition: Int, visibleItemCount: Int): Int { mFirstVisiblePosition = firstVisiblePosition if (mReferencePosition < 0) { mReferencePosition = mFirstVisiblePosition } if (visibleItemCount > 0) { val c: View = mListView.getListChildAt(0) var scrollY = -c.top mListViewItemHeights.put(firstVisiblePosition, c.measuredHeight) return if (mFirstVisiblePosition >= mReferencePosition) { for (i in mReferencePosition until firstVisiblePosition) { if (mListViewItemHeights.get(i) == null) { mListViewItemHeights.put(i, c.measuredHeight) } scrollY += mListViewItemHeights.get(i) } scrollY } else { for (i in mReferencePosition - 1 downTo firstVisiblePosition) { if (mListViewItemHeights.get(i) == null) { mListViewItemHeights.put(i, c.measuredHeight) } scrollY -= mListViewItemHeights.get(i) } scrollY } } return 0 }" Call from an AbsListView.OnScrollListener to calculate the scrollY ( Here we definite as the distance in pixels compared to the position representing the current date ) . +fun DynamicRegionFactoryImpl() {} create an instance of the factory . This is normally only done by DynamicRegionFactory 's static initialization +"fun DViewAsymmetricKeyFields( parent: javax.swing.JDialog?, title: String?, dsaPublicKey: DSAPublicKey ) { super(parent, title, Dialog.ModalityType.DOCUMENT_MODAL) key = dsaPublicKey initFields() }" Creates new DViewAsymmetricKeyFields dialog . +fun removeAllActions(target: CCNode?) { if (target == null) return val element: HashElement = targets.get(target) if (element != null) { deleteHashElement(element) } else { } } Removes all actions from a certain target . All the actions that belongs to the target will be removed . +"private fun normalizeName(name: String): String? { var name: String? = name name = name?.trim { it <= ' ' } ?: """" return if (name.isEmpty()) MISSING_NAME else name }" Normalizes a name to something OpenMRS will accept . +@Throws(QueryNodeException::class) fun build(queryNode: QueryNode): Any? { process(queryNode) return queryNode.getTag(QUERY_TREE_BUILDER_TAGID) } Builds some kind of object from a query tree . Each node in the query tree is built using an specific builder associated to it . +fun isEnableLighting(): Boolean { return false } Returns false . +"protected fun prepare() { val para: Array = getParameter() for (i in para.indices) { val name: String = para[i].getParameterName() if (para[i].getParameter() == null) ; else log.log( Level.SEVERE, ""prepare - Unknown Parameter: $name"" ) } }" "Prepare - e.g. , get Parameters ." +"fun fling(velocityX: Int, velocityY: Int) { if (getChildCount() > 0) { val height: Int = getHeight() - getPaddingBottom() - getPaddingTop() val bottom: Int = getChildAt(0).getHeight() val width: Int = getWidth() - getPaddingRight() - getPaddingLeft() val right: Int = getChildAt(0).getWidth() mScroller.fling( getScrollX(), getScrollY(), velocityX, velocityY, 0, right - width, 0, bottom - height ) val movingDown = velocityY > 0 val movingRight = velocityX > 0 var newFocused: View = findFocusableViewInMyBounds( movingRight, mScroller.getFinalX(), movingDown, mScroller.getFinalY(), findFocus() ) if (newFocused == null) { newFocused = this } if (newFocused !== findFocus() && newFocused.requestFocus(if (movingDown) View.FOCUS_DOWN else View.FOCUS_UP)) { mTwoDScrollViewMovedFocus = true mTwoDScrollViewMovedFocus = false } awakenScrollBars(mScroller.getDuration()) invalidate() } }" Fling the scroll view +protected fun createSocket(): Socket? { return Socket() } Creates a new unconnected Socket instance . Subclasses may use this method to override the default socket implementation . +"@DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2013-12-30 12:36:21.616 -0500"", hash_original_method = ""F5BF0DDF083843E14FDE0C117BAE250E"", hash_generated_method = ""E1C3BB6772CE07721D8608A1E4D81EE1"" ) fun netmaskIntToPrefixLength(netmask: Int): Int { return Integer.bitCount(netmask) }" Convert a IPv4 netmask integer to a prefix length +"fun createWritableChild( x: Int, y: Int, width: Int, height: Int, x0: Int, y0: Int, bandList: IntArray? ): java.awt.image.WritableRaster? { if (x < this.minX) { throw java.awt.image.RasterFormatException(""x lies outside the raster"") } if (y < this.minY) { throw java.awt.image.RasterFormatException(""y lies outside the raster"") } if (x + width < x || x + width > this.minX + width) { throw java.awt.image.RasterFormatException(""(x + width) is outside of Raster"") } if (y + height < y || y + height > this.minY + height) { throw java.awt.image.RasterFormatException(""(y + height) is outside of Raster"") } val sm: java.awt.image.SampleModel if (bandList != null) sm = sampleModel.createSubsetSampleModel(bandList) else sm = sampleModel val deltaX = x0 - x val deltaY = y0 - y return sun.awt.image.ShortInterleavedRaster( sm, dataBuffer, java.awt.Rectangle(x0, y0, width, height), Point(sampleModelTranslateX + deltaX, sampleModelTranslateY + deltaY), this ) }" "Creates a Writable subRaster given a region of the Raster . The x and y coordinates specify the horizontal and vertical offsets from the upper-left corner of this Raster to the upper-left corner of the subRaster . A subset of the bands of the parent Raster may be specified . If this is null , then all the bands are present in the subRaster . A translation to the subRaster may also be specified . Note that the subRaster will reference the same DataBuffers as the parent Raster , but using different offsets ." +"private fun isBlockCommented( startLine: Int, endLine: Int, prefixes: Array, document: IDocument ): Boolean { try { for (i in startLine..endLine) { val line: IRegion = document.getLineInformation(i) val text: String = document.get(line.getOffset(), line.getLength()) val found: IntArray = TextUtilities.indexOf(prefixes, text, 0) if (found[0] == -1) return false var s: String = document.get(line.getOffset(), found[0]) s = s.trim { it <= ' ' } if (s.length != 0) return false } return true } catch (x: javax.swing.text.BadLocationException) { } return false }" Determines whether each line is prefixed by one of the prefixes . +fun eUnset(featureID: Int) { when (featureID) { GamlPackage.PARAMETERS__PARAMS -> { setParams(null as jdk.nashorn.internal.ir.ExpressionList?) return } } super.eUnset(featureID) } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"@JvmStatic fun main(args: Array) { var matrixFilename: String? = null var coordinateFilename: String? = null var externalZonesFilename: String? = null var networkFilename: String? = null var plansFilename: String? = null var populationFraction: Double? = null require(args.size == 6) { ""Wrong number of arguments"" } matrixFilename = args[0] coordinateFilename = args[1] externalZonesFilename = args[2] networkFilename = args[3] plansFilename = args[4] populationFraction = args[5].toDouble() val list: MutableList = ArrayList() try { val br: BufferedReader = sun.security.util.IOUtils.getBufferedReader(externalZonesFilename) try { var line: String? = null while (br.readLine().also { line = it } != null) { list.add(line) } } finally { br.close() } } catch (e: FileNotFoundException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } val mdm = MyDemandMatrix() mdm.readLocationCoordinates(coordinateFilename, 2, 0, 1) mdm.parseMatrix(matrixFilename, ""Saturn"", ""Saturn model received for Sanral project"") val sc: Scenario = mdm.generateDemand(list, Random(5463), populationFraction, ""car"") val nr = NetworkReaderMatsimV1(sc.getNetwork()) nr.readFile(networkFilename) val xy = XY2Links(sc.getNetwork(), null) xy.run(sc.getPopulation()) val pw = PopulationWriter(sc.getPopulation(), sc.getNetwork()) pw.write(plansFilename) }" "Class to generate plans files from the Saturn OD-matrices provided by Sanral 's modelling consultant , Alan Robinson ." +"private fun partition(a: IntArray, left: Int, right: Int): Int { var left = left var right = right val pivot = a[left + (right - left) / 2] while (left <= right) { while (a[left] > pivot) left++ while (a[right] < pivot) right-- if (left <= right) { val temp = a[left] a[left] = a[right] a[right] = temp left++ right-- } } return left }" Choose mid value as pivot Move two pointers Swap and move on Return left pointer +fun isDone(): Boolean {return one.getHand().empty() || two.getHand().empty() } Returns true if either hand is empty . +"fun ClassNotFoundException(@Nullable s: String?, @Nullable ex: Throwable) { super(s, null) ex = ex }" Constructs a < code > ClassNotFoundException < /code > with the specified detail message and optional exception that was raised while loading the class . +fun eIsSet(featureID: Int): Boolean { when (featureID) { BasePackage.DOCUMENTED_ELEMENT__DOCUMENTATION -> return if (DOCUMENTATION_EDEFAULT == null) documentation != null else !DOCUMENTATION_EDEFAULT.equals( documentation ) } return super.eIsSet(featureID) } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"fun drawRangeLine( g2: java.awt.Graphics2D, plot: CategoryPlot, axis: ValueAxis, dataArea: java.awt.geom.Rectangle2D, value: Double, paint: Paint?, stroke: java.awt.Stroke? ) { val range: Range = axis.getRange() if (!range.contains(value)) { return } val adjusted: java.awt.geom.Rectangle2D = java.awt.geom.Rectangle2D.Double( dataArea.getX(), dataArea.getY() + getYOffset(), dataArea.getWidth() - getXOffset(), dataArea.getHeight() - getYOffset() ) var line1: java.awt.geom.Line2D? = null var line2: java.awt.geom.Line2D? = null val orientation: PlotOrientation = plot.getOrientation() if (orientation === PlotOrientation.HORIZONTAL) { val x0: Double = axis.valueToJava2D(value, adjusted, plot.getRangeAxisEdge()) val x1: Double = x0 + getXOffset() val y0: Double = dataArea.getMaxY() val y1: Double = y0 - getYOffset() val y2: Double = dataArea.getMinY() line1 = java.awt.geom.Line2D.Double(x0, y0, x1, y1) line2 = java.awt.geom.Line2D.Double(x1, y1, x1, y2) } else if (orientation === PlotOrientation.VERTICAL) { val y0: Double = axis.valueToJava2D(value, adjusted, plot.getRangeAxisEdge()) val y1: Double = y0 - getYOffset() val x0: Double = dataArea.getMinX() val x1: Double = x0 + getXOffset() val x2: Double = dataArea.getMaxX() line1 = java.awt.geom.Line2D.Double(x0, y0, x1, y1) line2 = java.awt.geom.Line2D.Double(x1, y1, x2, y1) } g2.setPaint(paint) g2.setStroke(stroke) g2.draw(line1) g2.draw(line2) }" Draws a line perpendicular to the range axis . +fun startFading() { mHandler.removeMessages(MSG_FADE) scheduleFade() } "Start up the pulse to fade the screen , clearing any existing pulse to ensure that we do n't have multiple pulses running at a time ." +"@Throws(Exception::class) protected fun createConnection(): Connection? { val factory = ActiveMQConnectionFactory(""vm://localhost?broker.persistent=false"") return factory.createConnection() }" Creates a connection . +"protected fun drawView( g: java.awt.Graphics2D, r: java.awt.Rectangle, view: View, fontHeight: Int, y: Int ) { var y = y var x: Float = r.x.toFloat() val h: javax.swing.text.LayeredHighlighter = attr.host.getHighlighter() as javax.swing.text.LayeredHighlighter val document: RSyntaxDocument = com.sun.org.apache.xerces.internal.util.DOMUtil.getDocument() as RSyntaxDocument val map: Element = getElement() var p0: Int = view.getStartOffset() val lineNumber: Int = map.getElementIndex(p0) val p1: Int = view.getEndOffset() setSegment(p0, p1 - 1, document, drawSeg) val start: Int = p0 - drawSeg.offset var token: Token = document.getTokenListForLine(lineNumber)if (token != null && token.type === Token.NULL) { h.paintLayeredHighlights(g, p0, p1, r, attr.host, this) return } while (token != null && token.isPaintable()) { val p: Int = calculateBreakPosition(p0, token, x) x = r.x.toFloat() h.paintLayeredHighlights(g, p0, p, r, attr.host, this) while (token != null && token.isPaintable() && token.offset + token.textCount - 1 < p) { x = token.paint(g, x, y, attr.host, this) token = token.getNextToken() } if (token != null && token.isPaintable() && token.offset < p) { val tokenOffset: Int = token.offset var temp: Token? = DefaultToken( drawSeg, tokenOffset - start, p - 1 - start, tokenOffset, token.type ) temp.paint(g, x, y, attr.host, this) temp = null token.makeStartAt(p) } p0 = if (p == p0) p1 else p y += fontHeight } if (attr.host.getEOLMarkersVisible()) { g.setColor(attr.host.getForegroundForTokenType(Token.WHITESPACE)) g.setFont(attr.host.getFontForTokenType(Token.WHITESPACE)) g.drawString(""¶"", x, (y - fontHeight).toFloat()) } }" "Draws a single view ( i.e. , a line of text for a wrapped view ) , wrapping the text onto multiple lines if necessary ." +"fun containsKey(key: Any?): Boolean {var key = key if (key == null) {key = NULL_OBJECT}val index: Int = findIndex(key, elementData) return elementData.get(index) === key }" Returns whether this map contains the specified key . +"fun autoCorrectText(): Boolean { return preferences.getBoolean( resources.getString(R.string.key_autocorrect_text), java.lang.Boolean.parseBoolean(resources.getString(R.string.default_autocorrect_text)) ) }" Whether message text should be autocorrected . +"@Throws(Exception::class) protected fun removeNode(id: Int) { val idx: Int var node: FolderTokenDocTreeNode? = null idx = findIndexById(id) if (idx == -1) { throw IeciTdException(FolderBaseError.EC_NOT_FOUND, FolderBaseError.EM_NOT_FOUND) } node = m_nodes.get(idx) as FolderTokenDocTreeNode if (node.isNew()) m_nodes.remove(idx) else node.setEditFlag(FolderEditFlag.REMOVE) }" Elimina de la lista de nodos el nodo con el id especificado +fun deleteAttributes(columnIndices: IntArray?) { (getModel() as ArffTableModel).deleteAttributes(columnIndices) } deletes the attributes at the given indices +"fun onSuccess(statusCode: Int, headers: Array?, response: JSONObject?) { Log.w( LOG_TAG, ""onSuccess(int, Header[], JSONObject) was not overriden, but callback was received"" ) }" Returns when request succeeds +"fun lastIndexOfFromTo(element: Byte, from: Int, to: Int): Int {if (size === 0) return -1 checkRangeFromTo(from, to, size) val theElements: ByteArray = elements for (i in to downTo from) { if (element == theElements[i]) { return i } } return -1 }" "Returns the index of the last occurrence of the specified element . Returns < code > -1 < /code > if the receiver does not contain this element . Searches beginning at < code > to < /code > , inclusive until < code > from < /code > , inclusive . Tests for identity ." +fun put(key: Long) { if (key == FREE_KEY) { m_hasFreeKey = true return } var ptr = (Tools.phiMix(key) and m_mask) as Int var e: Long = m_data.get(ptr) if (e == FREE_KEY) { m_data.get(ptr) = key if (m_size >= m_threshold) { rehash(m_data.length * 2) } else { ++m_size } return } else if (e == key) { return } while (true) { ptr = (ptr + 1 and m_mask) e = m_data.get(ptr) if (e == FREE_KEY) { m_data.get(ptr) = key if (m_size >= m_threshold) { rehash(m_data.length * 2) } else { ++m_size } return } else if (e == key) { return } } Add a single element to the map +"@Throws(InstantiationException::class, IllegalAccessException::class, ClassNotFoundException::class ) fun PredictiveInfoCalculatorKraskov(calculatorName: String) { super(calculatorName) if (!calculatorName.equals( MI_CALCULATOR_KRASKOV1, ignoreCase = true ) && !calculatorName.equals(MI_CALCULATOR_KRASKOV2, ignoreCase = true) ) { throw ClassNotFoundException(""Must be an underlying Kraskov-Grassberger calculator"") } }" "Creates a new instance of the Kraskov-Stoegbauer-Grassberger estimator for PI , with the supplied MI calculator name ." +"fun DefaultDirectAdjacentSelector(type: Short, parent: Selector?, simple: SimpleSelector?) { super(type, parent, simple) }" Creates a new DefaultDirectAdjacentSelector object . +"@Inline fun postCopy(`object`: com.sun.jdi.ObjectReference?, majorGC: Boolean) { initializeHeader(`object`, false) if (!HEADER_MARK_BITS) { testAndSetLiveBit(`object`) } }" Perform any required post copy ( i.e . in-GC allocation ) initialization . This is relevant ( for example ) when MS is used as the mature space in a copying GC . +"fun parseRulesFile(`is`: InputStream): LinkedHashMap? { val rules: LinkedHashMap = LinkedHashMap() val br = BufferedReader( sun.security.util.IOUtils.getDecodingReader( `is`, StandardCharsets.UTF_ ) ) var line: String try { var linenum = 0 while (br.readLine().also { line = it } != null) { linenum++ val arr = line.split(""#"").toTypedArray() if (arr.size > 0) line = arr[0].trim { it <= ' ' } if (line.length == 0) continue val sep = line.indexOf(""="") if (sep <= 0) { log.warn(""Wrong format of password line $linenum"") continue } val pass = line.substring(sep + 1).trim { it <= ' ' } val regex = line.substring(0, sep).trim { it <= ' ' } try { val pattern: Pattern = Pattern.compile(regex) rules[pattern] = pass } catch (pse: PatternSyntaxException) { log.warn(""Key of line $linenum was not a valid regex pattern"", pse) continue } } `is`.close() } catch (e: IOException) { throw RuntimeException(e) } return rules }" Parses rule file from stream and returns a Map of all rules found +fun isItemForce(): Boolean {return true } Returns true . +"fun document(document: InputStream, mediaType: String): Builder? { documentInputStream = document mediaType = mediaType return this }" Sets the document as an input stream and its media type . +"override fun toString(): String { val text = StringBuffer() text.append( """""" Print statistic values of instances (${first.toString()}-${last.toString()}= """""".trimIndent() ) text.append( """""" Number of instances: ${numInstances.toString()} """""" ) text.append( """""" NUmber of instances with unknowns: ${missingInstances.toString()} """""" ) text.append( """""" Attribute: :${attr.toString()} """""" ) text.append( """""" Sum: ${sum.toString()} """""" ) text.append( """""" Squared sum: ${sqrSum.toString()} """""" ) text.append( """""" Stanard Deviation: ${sd.toString()} """""" ) return text.toString() }" Converts the stats to a string +"private fun scanAndLock(key: Any, hash: Int) { var first: HashEntry = entryForHash(this, hash) var e: HashEntry = first var retries = -1 while (!tryLock()) { var f: HashEntry if (retries < 0) { if (e == null || key == e.key) retries = 0 else e = e.next } else if (++retries > MAX_SCAN_RETRIES) { lock() break } else if (retries and 1 == 0 && entryForHash(this, hash).also { f = it } !== first) { first = f e = first retries = -1 } } }" "Scans for a node containing the given key while trying to acquire lock for a remove or replace operation . Upon return , guarantees that lock is held . Note that we must lock even if the key is not found , to ensure sequential consistency of updates ." +fun oldColor(oldColor: Int): IntentBuilder? { mOldColor = oldColor return this } "Sets the old color to show on the bottom `` Cancel '' half circle , and also the initial value for the picked color . The default value is black ." +fun __setDaoSession(daoSession: DaoSession) {daoSession = daoSessionmyDao = if (daoSession != null) daoSession.getUserDBDao() else null } "called by internal mechanisms , do not call yourself ." +fun equals(obj: Any): Boolean { if (obj === this) { return true } if (obj !is TimeTableXYDataset) { return false } val that: TimeTableXYDataset = obj as TimeTableXYDataset if (this.domainIsPointsInTime !== that.domainIsPointsInTime) { return false if (this.xPosition !== that.xPosition) { return false } if (!this.workingCalendar.getTimeZone().equals(that.workingCalendar.getTimeZone())) { return false } return if (!this.values.equals(that.values)) { false } else true } Tests this dataset for equality with an arbitrary object . +"private fun startContext(crawlJob: CrawlJob) { LOGGER.debug(""Starting context"") val ac: PathSharingContext = crawlJob.getJobContext() ac.addApplicationListener(this) try { ac.start() } catch (be: BeansException) { LOGGER.warn(be.getMessage()) ac.close() } catch (e: Exception) { LOGGER.warn(e.message) try { ac.close() } catch (e2: Exception) { e2.printStackTrace(System.err) } finally { } } LOGGER.debug(""Context started"") }" "Start the context , catching and reporting any BeansExceptions ." +fun performCancel(): Boolean { CnAElementFactory.getInstance().reloadModelFromDatabase() return true } Cause update to risk analysis object in loaded model . +fun isOpaque(): Boolean { checkOpacityMethodClient() return explicitlyOpaque } Returns whether the background of this < code > BasicPanel < /code > will be painted when it is rendered . +"@Throws(IOException::class, ClassNotFoundException::class) private fun readObject(s: ObjectInputStream) { s.defaultReadObject() } }" "Adds semantic checks to the default deserialization method . This method must have the standard signature for a readObject method , and the body of the method must begin with `` s.defaultReadObject ( ) ; '' . Other than that , any semantic checks can be specified and do not need to stay the same from version to version . A readObject method of this form may be added to any class , even if Tetrad sessions were previously saved out using a version of the class that did n't include it . ( That 's what the `` s.defaultReadObject ( ) ; '' is for . See J. Bloch , Effective Java , for help ." +"@Throws(Exception::class) fun resetDistribution(data: Instances) { val insts = Instances(data, data.numInstances()) for (i in 0 until data.numInstances()) { if (whichSubset(data.instance(i)) > -1) { insts.add(data.instance(i)) } } val newD = Distribution(insts, this) newD.addInstWithUnknown(data, m_attIndex) m_distribution = newD }" Sets distribution associated with model . +"@Throws(NoSuchFieldException::class) fun readStaticField(klass: Class?, fieldName: String?): R { return readAvailableField(klass, null, fieldName) }" Reads the static field with given fieldName in given klass . +"fun extractFactor_Display(laggedFactor: String): String? { val colonIndex = laggedFactor.indexOf("":L"") return laggedFactor.substring(0, colonIndex) }" Parses the given string representing a lagged factor and return the part that represents the factor . +"@Throws(IOException::class) protected fun deployCargoPing(container: WebLogicLocalContainer) { val deployDir: String = getFileHandler().createDirectory(getDomainHome(), container.getAutoDeployDirectory()) getResourceUtils().copyResource( RESOURCE_PATH.toString() + ""cargocpc.war"", getFileHandler().append(deployDir, ""cargocpc.war""), getFileHandler() ) }" Deploy the Cargo Ping utility to the container . +fun size(): Int {return this.count } Returns the number of mappings in this map +"@Throws(Exception::class) protected fun parse(stream: DataInputStream) { var size: Int = stream.readInt() var ret: Int var read = 0 data = ByteArray(size) while (size > 0) { ret = stream.read(data, read, size) size -= ret read += ret } }" Loading method . ( see NBT_Tag ) +"@Ignore(""NaN behavior TBD"") @Test @Throws(Exception::class) fun testLinearAzimuth_WithNaN() { val begin = Location(Double.NaN, Double.NaN) val end = Location(34.2, -119.2) val azimuth: Double = begin.linearAzimuth(end) assertTrue(""expecting NaN"", java.lang.Double.isNaN(azimuth)) }" Ensures linear azimuth is NaN when NaN members are used . +"fun MutableValueBuffer(capacity: Int, src: IRaba?) { requireNotNull(src) checkCapacity(capacity) require(capacity >= src.capacity()) nvalues = src.size() values = arrayOfNulls(capacity) var i = 0 for (a in src) { values.get(i++) = a } }" Builds a mutable value buffer . +fun OutOfLineContent() { super(KEY) } Constructs a new instance using the default metadata . +"private fun rewriteTermBruteForce(term: String): List? { val termsList: MutableList = rewriteBrute(term) if (term === """" || term != termsList[termsList.size - 1]) termsList.add(term) return termsList }" "Wrapper over main recursive method , rewriteBrute which performs the fuzzy tokenization of a term The original term may not be a valid dictionary word , but be a term particular to the database The method rewriteBrute only considers terms which are valid dictionary words In case original term is not a dictionary word , it will not be added to queryList by method rewriteBrute This wrapper ensures that if rewriteBrute does not include the original term , it will still be included For example , for the term `` newyork '' , rewriteBrute will return the list < `` new york '' > But `` newyork '' also needs to be included in the list to support particular user queries This wrapper includes `` newyork '' in this list" +"@Throws(Exception::class) fun test_sssp_linkType_constraint() { val p: SmallWeightedGraphProblem = setupSmallWeightedGraphProblem() val gasEngine: IGASEngine = getGraphFixture().newGASEngine(1) try { val graphAccessor: IGraphAccessor = getGraphFixture().newGraphAccessor(null) val gasContext: IGASContext = gasEngine.newGASContext(graphAccessor, SSSP()) gasContext.setLinkType(p.getFoafKnows() as URI) val gasState: IGASState = gasContext.getGASState() gasState.setFrontier(gasContext, p.getV1()) gasContext.call() assertEquals(0.0, gasState.getState(p.getV1()).dist()) assertEquals(1.0, gasState.getState(p.getV2()).dist()) assertEquals(1.0, gasState.getState(p.getV3()).dist()) assertEquals(2.0, gasState.getState(p.getV4()).dist()) assertEquals(2.0, gasState.getState(p.getV5()).dist()) } finally { gasEngine.shutdownNow() } }" A unit test based on graph with link weights - in this version of the test we constrain the link type but do not specify the link attribute type . Hence it ignores the link weights . This provides a test of the optimized access path when just the link type constraint is specified . +"fun convertNodeId2NotExpandedCrossingNodeId(nodeId: Id): Id? { val idString: String = nodeId.toString() return idPool.createId(idString, DgCrossingNode::class.java) }" converts a matsim node ID of a node outside the signals bounding box to the single crossing node ID existing for the not expanded crossing in the ks-model . ( the signals bounding box determines the region of spatial expansion : all nodes within this area will be expanded . ) +"@Throws(Exception::class) fun runSafely(stack: Catbert.FastStack?): Any? { val k = getString(stack) val r = getString(stack) return if (!Sage.WINDOWS_OS) Pooler.EMPTY_STRING_ARRAY else Sage.getRegistryNames( Sage.getHKEYForName( r ), k ) }" "Returns a list of the Windows registry names which exist under the specified root & amp ; key ( Windows only ) Acceptable values for the Root are : `` HKCR '' , `` HKEY_CLASSES_ROOT '' , `` HKCC '' , `` HKEY_CURRENT_CONFIG '' , `` HKCU '' , `` HKEY_CURRENT_USER '' , `` HKU '' , `` HKEY_USERS '' , `` HKLM '' or `` HKEY_LOCAL_MACHINE '' ( HKLM is the default if nothing matches )" +fun APIPermissionSet() {} Creates a new permission set which contains no granted permissions . Any permissions must be added by manipulating or replacing the applicable permission collection . +"@RequestMapping( value = ""/upload/single/initiation"", method = RequestMethod.POST, consumes = [""application/xml"", ""application/json""] ) @Secured(SecurityFunctions.FN_UPLOAD_POST) fun initiateUploadSingle(@RequestBody uploadSingleInitiationRequest: UploadSingleInitiationRequest?): UploadSingleInitiationResponse? { val uploadSingleInitiationResponse: UploadSingleInitiationResponse = uploadDownloadService.initiateUploadSingle(uploadSingleInitiationRequest) for (businessObjectData in Arrays.asList( uploadSingleInitiationResponse.getSourceBusinessObjectData(), uploadSingleInitiationResponse.getTargetBusinessObjectData() )) { val businessObjectDataKey: BusinessObjectDataKey = businessObjectDataHelper.getBusinessObjectDataKey(businessObjectData) for (eventType in Arrays.asList( NotificationEventTypeEntity.EventTypesBdata.BUS_OBJCT_DATA_RGSTN, NotificationEventTypeEntity.EventTypesBdata.BUS_OBJCT_DATA_STTS_CHG )) { notificationEventService.processBusinessObjectDataNotificationEventAsync( eventType, businessObjectDataKey, businessObjectData.getStatus(), null ) } for (storageUnit in businessObjectData.getStorageUnits()) { notificationEventService.processStorageUnitNotificationEventAsync( NotificationEventTypeEntity.EventTypesStorageUnit.STRGE_UNIT_STTS_CHG, businessObjectDataKey, storageUnit.getStorage().getName(), storageUnit.getStorageUnitStatus(), null ) } } return uploadSingleInitiationResponse }" Initiates a single file upload capability by creating the relative business object data instance in UPLOADING state and allowing write access to a specific location in S3_MANAGED_LOADING_DOCK storage . < p > Requires WRITE permission on namespace < /p > +"fun ArrayIntCompressed(size: Int, leadingClearBits: Int, trailingClearBits: Int) {init(size, BIT_LENGTH - leadingClearBits trailingClearBits, trailingClearBits) }" "Create < code > IntArrayCompressed < /code > from number of ints to be stored , the number of leading and trailing clear bits . Everything else is stored in the internal data structure ." +"fun compXmlStringAt(arr: ByteArray, strOff: Int): String? { val strLen: Int = arr[strOff + 1] shl 8 and 0xff00 or arr[strOff] and 0xff val chars = CharArray(strLen) for (ii in 0 until strLen) { val p0 = strOff + 2 + ii * 2 if (p0 >= arr.size - 1) break chars[ii] = ((arr[p0 + 1] and 0x00FF shl 8) + (arr[p0] and 0x00FF)).toChar() } return String(chars) }" "Return the string stored in StringTable format at offset strOff . This offset points to the 16 bit string length , which is followed by that number of 16 bit ( Unicode ) chars ." +"fun AbstractExportOperation(archiveFile: File, mainFile: IFile, project: IN4JSEclipseProject) { this.targetFile = archiveFile mainFile = mainFile project = project this.workspace = project.getProject().getWorkspace() rootLocation = project.getLocation().appendSegment("""") }" Create an operation that will export the given project to the given zip file . +"@Throws(SQLException::class) fun supportsMixedCaseQuotedIdentifiers(): Boolean { debugCodeCall(""supportsMixedCaseQuotedIdentifiers"") val m: String = conn.getMode() return if (m == ""MySQL"") { false } else true }" Checks if a table created with CREATE TABLE `` Test '' ( ID INT ) is a different table than a table created with CREATE TABLE TEST ( ID INT ) . +"private fun leftEdge(image: java.awt.image.BufferedImage): Shape? { val path: java.awt.geom.GeneralPath = java.awt.geom.GeneralPath() var p1: java.awt.geom.Point2D? = null var p2: java.awt.geom.Point2D? = null val line: java.awt.geom.Line2D = java.awt.geom.Line2D.Float() var p: java.awt.geom.Point2D = java.awt.geom.Point2D.Float() var foundPointY = -1 for (i in 0 until image.getHeight()) { for (j in 0 until image.getWidth()) { if (image.getRGB(j, i) and -0x1000000 != 0) { p = java.awt.geom.Point2D.Float(j, i) foundPointY = i break } } if (foundPointY >= 0) { if (p2 == null) { p1 = java.awt.geom.Point2D.Float(image.getWidth() - 1, foundPointY) path.moveTo(p1.getX(), p1.getY()) p2 = java.awt.geom.Point2D.Float() p2.setLocation(p) } else { p2 = detectLine(p1, p2, p, line, path) } } } path.lineTo(p.getX(), p.getY()) if (foundPointY >= 0) { path.lineTo((image.getWidth() - 1).toFloat(), foundPointY.toFloat()) } path.closePath() return path }" trace the left side of the image +"@Throws(Exception::class) fun testSetMaxRows() { var maxRowsStmt: Statement? = null try { maxRowsStmt = this.conn.createStatement() maxRowsStmt.setMaxRows(1) this.rs = maxRowsStmt.executeQuery(""SELECT 1"") } finally { if (maxRowsStmt != null) { maxRowsStmt.close() } } }" Tests fix for BUG # 907 +fun unregisterMbeans() { unregisterMbeans(ManagementFactory.getPlatformMBeanServer()) } unRegister all jamon related mbeans +fun free(value: T?): Boolean { return _ringQueue.offer(value) } "Frees the object . If the free list is full , the object will be garbage collected ." +"fun basicSet_lok( new_lok: LocalArgumentsVariable, msgs: NotificationChain? ): NotificationChain? { var msgs: NotificationChain? = msgs val old_lok: LocalArgumentsVariable = _lok _lok = new_lok if (eNotificationRequired()) { val notification = ENotificationImpl( this, Notification.SET, N4JSPackage.FUNCTION_DECLARATION__LOK, old_lok, new_lok ) if (msgs == null) msgs = notification else msgs.add(notification) } return msgs }" < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"fun query(onlyCurrentRows: Boolean, onlyCurrentDays: Int, maxRows: Int) { m_mTab.query(onlyCurrentRows, onlyCurrentDays, maxRows) if (!isSingleRow()) vTable.autoSize(true) activateChilds() }" Query Tab and resize Table ( called from APanel ) +"fun queryProb(query: Query.ProbQuery?): EmpiricalDistribution? { val isquery = LikelihoodWeighting(query, nbSamples, maxSamplingTime) val samples: List = isquery.getSamples() return EmpiricalDistribution(samples) }" "Queries for the probability distribution of the set of random variables in the Bayesian network , given the provided evidence" +fun loadChar(offset: Offset?): Char { if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED) return 0.toChar() } Loads a char from the memory location pointed to by the current instance . +"fun put(src: FloatArray, off: Int, len: Int): FloatBuffer? {val length = src.size if (off < 0 || len < 0 || off.toLong() + len.toLong() > length) { throw IndexOutOfBoundsException() } if (len > remaining()) { throw BufferOverflowException() } for (i in off until off + len) { put(src[i]) } return this }" "Writes floats from the given float array , starting from the specified offset , to the current position and increases the position by the number of floats written ." +"@Throws(InterruptedException::class, KeeperException::class) fun deleteCollectionLevelSnapshot( zkClient: SolrZkClient, collectionName: String?, commitName: String? ) { val zkPath: String = getSnapshotMetaDataZkPath(collectionName, Optional.of(commitName)) zkClient.delete(zkPath, -1, true) }" This method deletes an entry for the named snapshot for the specified collection in Zookeeper . +"private fun turn22(grid: IntGrid2D, x: Int, y: Int) { val p1: Int val p2: Int val p3: Int val p4: Int p1 = grid.get(grid.stx(x), grid.sty(y)) p2 = grid.get(grid.stx(x + 1), grid.sty(y)) p3 = grid.get(grid.stx(x + 1), grid.sty(y + 1)) p4 = grid.get(grid.stx(x), grid.sty(y + 1))if (p.r.nextBoolean()) { grid.set(grid.stx(x), grid.sty(y), p4) grid.set(grid.stx(x + 1), grid.sty(y), p1) grid.set(grid.stx(x + 1), grid.sty(y + 1), p2) grid.set(grid.stx(x), grid.sty(y + 1), p3) } else { grid.set(grid.stx(x), grid.sty(y), p2) grid.set(grid.stx(x + 1), grid.sty(y), p3) grid.set(grid.stx(x + 1), grid.sty(y + 1), p4) grid.set(grid.stx(x), grid.sty(y + 1), p1) } }" Diffuse a 2x2 block clockwise or counter-clockwise . This procedure was published by Toffoli and Margolus to simulate the diffusion in an ideal gas . The 2x2 blocks will be turned by random in one direction ( clockwise or counter clockwise ) . Usually a second run will be done but this time with a offset of one to the previous run +"fun magnitude(u: DoubleArray?): Double { return Math.sqrt(dot(u, u)) }" Returns the magnitude ( Euclidean norm ) of the specified vector . +override fun toString(): String? { return statusString } Returns the String representation for thiz . +"fun chopFrame(offsetDelta: Int, k: Int) { numOfEntries++ output.write(251 - k) write16(offsetDelta) }" Writes a < code > chop_frame < /code > . +"fun AsyncHttpClient(fixNoHttpResponseException: Boolean, httpPort: Int, httpsPort: Int) { this(getDefaultSchemeRegistry(fixNoHttpResponseException, httpPort, httpsPort)) }" Creates new AsyncHttpClient using given params +"fun verify(signature: ByteArray?): Boolean { return verify(signature, false) }" Verifies the data ( computes the secure hash and compares it to the input ) +override fun toString(): String? { return name().toLowerCase() } override fun toString(): String? { return name().toLowerCase() } +"fun StringBand(initialCapacity: Int) { require(initialCapacity > 0) { ""Invalid initial capacity"" } array = arrayOfNulls StringBand < /code > with provided capacity . Capacity refers to internal string array ( i.e . number of joins ) and not the total string size . +fun removeConstraint(c: ParticleConstraint2D?): Boolean { return constraints.remove(c) } Attempts to remove the given constraint instance from the list of active constraints . +"private fun DoneCallback( cb: GridClientFutureCallback, lsnr: GridClientFutureListener, chainedFut: GridClientFutureAdapter ) { cb = cb lsnr = lsnr chainedFut = chainedFut }" Constructs future finished notification callback . +"private fun addSignatureProfile(signature: SignatureWrapper, xmlSignature: XmlSignature) {var signatureType: SignatureType = SignatureType.NA val certificateId: String = signature.getSigningCertificateId() if (certificateId != null) { signatureType = getSignatureType(certificateId) } xmlSignature.setSignatureLevel(signatureType.name()) }" Here we determine the type of the signature . +fun isArray(): Boolean { return false } Determines if this Class object represents an array class . +"fun NewSessionAction() { super(""New Session"") }" Creates a new session action for the given desktop . +"private fun appendIfNotNull(source: StringBuilder,addStr: String?,delimiter: String): StringBuilder? {var delimiter: String? = delimiter if (addStr != null) {if (addStr.length == 0) {delimiter = """"}return source.append(addStr).append(delimiter)}return source}" "Takes a string and adds to it , with a separator , if the bit to be added is n't null . Since the logger takes so many arguments that might be null , this method helps cut out some of the agonizing tedium of writing the same 3 lines over and over ." +"@Throws(IOException::class) fun write(out: OutStream) { out.flushBits() out.writeUBits(5, getBitSize()) out.writeSBits(bitSize, minX) out.writeSBits(bitSize, maxX out.writeSBits(bitSize, minY) out.writeSBits(bitSize, maxY) out.flushBits() }" Write the rect contents to the output stream +"private fun checkCenter(center: LatLon) { println(""Testing fromLatLngToPoint using: $center"") val p: java.awt.geom.Point2D = googleMap.fromLatLngToPoint(center.toLatLong()) println(""Testing fromLatLngToPoint result: $p"") System.out.println(""Testing fromLatLngToPoint expected: "" + (mapComponent.getWidth() / 2).toString() + "", "" + mapComponent.getHeight() / 2) System.out.println(""type = "" + org.graalvm.compiler.nodeinfo.StructuralInput.MarkerType.BROWN.iconPath()) }" Demonstrates how to go from lat/lon to pixel coordinates . +"fun createBusinessObjectDataAttributeEntity( namespaceCode: String?, businessObjectDefinitionName: String?, businessObjectFormatUsage: String?,businessObjectFormatFileType: String?,businessObjectFormatVersion: Int?,businessObjectDataPartitionValue: String?,businessObjectDataSubPartitionValues: List?,businessObjectDataVersion: Int?,businessObjectDataAttributeName: String?,businessObjectDataAttributeValue: String?): BusinessObjectDataAttributeEntity? {val businessObjectDataKey = BusinessObjectDataKey(namespaceCode,businessObjectDefinitionName, businessObjectFormatUsage,businessObjectFormatFileType,businessObjectFormatVersion,businessObjectDataPartitionValue,businessObjectDataSubPartitionValues,businessObjectDataVersion)return createBusinessObjectDataAttributeEntity(businessObjectDataKey,businessObjectDataAttributeName,businessObjectDataAttributeValue)}" Creates and persists a new business object data attribute entity . +"@Synchronized private fun containsMapping(key: Any, value: Any): Boolean {val hash: Int = Collections.secondaryHash(key)val tab: Array> = table val index = hash and tab.size - 1var e: sun.jvm.hotspot.utilities.HashtableEntry = tab[index] while (e != null) { if (e.hash === hash && e.key.equals(key)) {return e.value.equals(value)}e = e.next}return false}" Returns true if this map contains the specified mapping . +"fun Setting(value: Any, type: Int, save: Boolean, file: String) { value = value if (type == MAP) { this.defaultValue = HashMap(value as Map<*, *>) } else if (type == LIST) { this.defaultValue = copyCollection(value as Collection<*>) } else { this.defaultValue = value } save = save type = type file = file }" Creates a new Setting object with some initial values . +"protected fun layoutGraphicModifiers( dc: DrawContext?, modifiers: AVList?, osym: OrderedSymbol? ) { }" "Layout static graphic modifiers around the symbol . Static modifiers are not expected to change due to changes in view . The static layout is computed when a modifier is changed , but may not be computed each frame . For example , a text modifier indicating a symbol identifier would only need to be laid out when the text is changed , so this is best treated as a static modifier . However a direction of movement line that needs to be computed based on the current eye position should be treated as a dynamic modifier ." +"@HLEFunction(nid = -0x1e29de29, version = 150, checkInsideInterrupt = true) fun sceNetAdhocInit(): Int { log.info( String.format( ""sceNetAdhocInit: using MAC address=%s, nick name='%s'"", sceNet.convertMacAddressToString(Wlan.getMacAddress()), sceUtility.getSystemParamNickname() ) ) if (isInitialized) { return SceKernelErrors.ERROR_NET_ADHOC_ALREADY_INITIALIZED } isInitialized = true return 0 }" Initialize the adhoc library . +fun Assignment(booleanAssigns: List) { this() booleanAssigns.stream().forEach(null) } Creates an assignment with a list of boolean assignments ( cf . method above ) . +"@Throws(Exception::class) fun testMergeSameFilterInTwoDocuments() { val srcXml = """" + "" "" + "" f1"" + "" fclass1"" + "" "" + "" "" + "" f1"" + "" /f1mapping1"" + "" "" + """" val srcWebXml: WebXml = WebXmlIo.parseWebXml(ByteArrayInputStream(srcXml.toByteArray(charset(""UTF-8""))), null) val mergeXml = """" + "" "" + "" f1"" + "" fclass1"" + "" "" + "" "" + "" f1"" + "" /f1mapping1"" + "" "" + """" val mergeWebXml: WebXml = WebXmlIo.parseWebXml(ByteArrayInputStream(mergeXml.toByteArray(charset(""UTF-8""))), null) val merger = WebXmlMerger(srcWebXml) merger.mergeFilters(mergeWebXml) assertTrue(WebXmlUtils.hasFilter(srcWebXml, ""f1"")) val filterMappings: List = WebXmlUtils.getFilterMappings(srcWebXml, ""f1"") assertEquals(1, filterMappings.size) assertEquals(""/f1mapping1"", filterMappings[0]) }" "Tests whether the same filter in two different files is mapped correctly ( i.e. , once ) ." +"fun countPeriods(haystack: String?): Int { return com.sun.tools.javac.util.StringUtils.countOccurrencesOf(haystack, ""."") }" Count the number of periods in a value . +"@JvmStatic fun main(args: Array) { DOMTestCase.doMain(nodegetfirstchildnull::class.java, args) }" Runs this test from the command line . +"fun actionPerformed(e: java.awt.event.ActionEvent?) { val target: javax.swing.text.JTextComponent = getTextComponent(e) if (target != null && e != null) { if (!target.isEditable() || !target.isEnabled()) { javax.swing.UIManager.getLookAndFeel().provideErrorFeedback(target) return } var content: String = target.getText() if (content != null && target.getSelectionStart() > 0) { content = content.substring(0, target.getSelectionStart()) } if (content != null) { target.setText(getNextMatch(content)) adaptor.markText(content.length) } } }" Shows the next match . +"fun clear() { super.clear() LEFT_PARENTHESES = """" RIGHT_PARENTHESES = """" }" removes the stored data but retains the dimensions of the matrix . +"fun deleteChannel(jsonChannel: CumulusChannel) { val jsonString: String = jsonChannel.toString() val i = Intent(""com.felkertech.cumulustv.RECEIVER"") i.putExtra(INTENT_EXTRA_JSON, jsonString) i.putExtra(INTENT_EXTRA_ACTION, INTENT_EXTRA_ACTION_DELETE) sendBroadcast(i) finish() }" Deletes the provided channel and resyncs . Then the app closes . +"fun toStringExclude(`object`: Any?, excludeFieldNames: Collection<*>?): String? { return toStringExclude(`object`, toNoNullStringArray(excludeFieldNames)) }" Builds a String for a toString method excluding the given field names . +"fun StringDict(reader: BufferedReader?) { val lines: Array = PApplet.loadStrings(reader) keys = arrayOfNulls(lines.size) values = arrayOfNulls(lines.size) for (i in lines.indices) { val pieces: Array = PApplet.split(lines[i], '\t') if (pieces.size == 2) { keys.get(count) = pieces[0] values.get(count) = pieces[1] count++ } } }" "Read a set of entries from a Reader that has each key/value pair on a single line , separated by a tab ." +"@Throws(IOException::class) fun writeMap(map: Map, stream: ObjectOutputStream) { stream.writeInt(map.size) for ((key, value): Map.Entry in map) { stream.writeObject(key) stream.writeObject(value) } }" "Stores the contents of a map in an output stream , as part of serialization . It does not support concurrent maps whose content may change while the method is running . < p > The serialized output consists of the number of entries , first key , first value , second key , second value , and so on ." +"fun NioDatagramAcceptor() { this(DefaultDatagramSessionConfig(), null) }" Creates a new instance . +"fun callWithRetry(callable: Callable, isRetryable: Predicate): V { var failures = 0 while (true) { try { return callable.call() } catch (e: Throwable) { if (++failures == attempts || !isRetryable.apply(e)) { androidx.test.espresso.core.internal.deps.guava.base.Throwables.throwIfUnchecked( e ) throw RuntimeException(e) } logger.info(e, ""Retrying transient error, attempt $failures"") try { sleeper.sleep(Duration.millis(pow(2, failures) * 100)) } catch (e2: InterruptedException) { Thread.currentThread().interrupt() androidx.test.espresso.core.internal.deps.guava.base.Throwables.throwIfUnchecked( e ) throw RuntimeException(e) } } } }" "Retries a unit of work in the face of transient errors . < p > Retrying is done a fixed number of times , with exponential backoff , if the exception that is thrown is deemed retryable by the predicate . If the error is not considered retryable , or if the thread is interrupted , or if the allowable number of attempts has been exhausted , the original exception is propagated through to the caller ." +fun size(): Int { return n } Returns the number of items in this queue . +"fun toXML(network: Network?): String? { val writer = StringWriter() writeXML(network, writer) writer.flush() return writer.toString() }" Covert the network into xml . +private fun parseEntityAttribute(fieldName: String): String? { val m: Matcher = _fnPattern.matcher(fieldName) return if (m.find()) { m.group(1) } else null } check whether this field is one entity attribute or not +"fun addScrapView(scrap: View, position: Int, viewType: Int) { if (viewTypeCount === 1) { currentScrapViews.put(position, scrap) } else { scrapViews.get(viewType).put(position, scrap) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { scrap.setAccessibilityDelegate(null) } }" Put a view into the ScrapViews list . These views are unordered . +fun AStart() {} Construct the applet +fun dispose() { disposeColors() disposeImages() disposeFonts() disposeCursors() } Dispose of cached objects and their underlying OS resources . This should only be called when the cached objects are no longer needed ( e.g . on application shutdown ) . +"protected fun bends(g1: Geo, g2: Geo?, g3: Geo?): Int { val bend: Double = g1.crossNormalize(g2).distance(g3) - Math.PI / 2.0 if (Math.abs(bend) < .0001) { return STRAIGHT } else { if (bend < 0) { return BENDS_LEFT } } return BENDS_RIGHT }" Method that determines which way the angle between the three points bends . +fun eIsSet(featureID: Int): Boolean { when (featureID) { TypesPackage.PRIMITIVE_TYPE__DECLARED_ELEMENT_TYPE -> return declaredElementType != null TypesPackage.PRIMITIVE_TYPE__ASSIGNMENT_COMPATIBLE -> return assignmentCompatible != null TypesPackage.PRIMITIVE_TYPE__AUTOBOXED_TYPE -> return autoboxedType != null } return super.eIsSet(featureID) } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"@Description(summary = ""Create h2client.jar with only the remote JDBC implementation."") fun jarClient() { compile(true, true, false) var files: FileList? = files(""temp"").exclude(""temp/org/h2/build/*"").exclude(""temp/org/h2/dev/*"") .exclude(""temp/org/h2/jaqu/*"").exclude(""temp/org/h2/java/*"") .exclude(""temp/org/h2/jcr/*"").exclude(""temp/org/h2/mode/*"") .exclude(""temp/org/h2/samples/*"").exclude(""temp/org/h2/test/*"").exclude(""*.bat"") .exclude(""*.sh"").exclude(""*.txt"").exclude(""*.DS_Store"") files = excludeTestMetaInfFiles(files) val kb: Long = jar(""bin/h2-client"" + getJarSuffix(), files, ""temp"") if (kb < 350 || kb > 450) { throw RuntimeException(""Expected file size 350 - 450 KB, got: $kb"") } }" Create the h2client.jar . This only contains the remote JDBC implementation . +"fun Messages(name: String?) { this(null as Messages?, name) }" Creates a messages bundle by full name . +fun providesSingletonInScope() { this@Binding.singletonInScope() isProvidingSingletonInScope = true } to provide a singleton using the binding 's scope and reuse it inside the binding 's scope +fun dispose() { m_table.getColumn(m_field).removeColumnListener(this) } "Dispose of this metadata , freeing any resources and unregistering any listeners ." +"fun updateUI() { super.updateUI() if (myTree != null) { myTree.updateUI() } javax.swing.LookAndFeel.installColorsAndFont( this, ""Tree.background"", ""Tree.foreground"", ""Tree.font"" ) }" Overridden to message super and forward the method to the tree . Since the tree is not actually in the component hierarchy it will never receive this unless we forward it in this manner . +fun ResourceNotificationException(message: String?) { super(message) } Creates a new < code > ResourceNotificationException < /code > object +fun variance(vector: DoubleArray): Double { var sum = 0.0 var sumSquared = 0.0 if (vector.size <= 1) { return 0 } for (i in vector.indices) { sum += vector[i] sumSquared += vector[i] * vector[i] } val result = sumSquared - sum * sum / vector.size.toDouble() / (vector.size - 1).toDouble() return if (result < 0) { 0 } else { result } } Computes the variance for an array of doubles . +fun taskClass(): Class? { return IgniteSinkTask::class.java } Obtains a sink task class to be instantiated for feeding data into grid . +"fun createNode(path: String?, watch: Boolean, ephimeral: Boolean): String? { var createdNodePath: String? = null createdNodePath = try { val nodeStat: Stat = zooKeeper.exists(path, watch) if (nodeStat == null) { zooKeeper.create( path, ByteArray(0), Ids.OPEN_ACL_UNSAFE, if (ephimeral) CreateMode.EPHEMERAL_SEQUENTIAL else CreateMode.PERSISTENT ) } else { path } } catch (e: KeeperException) { throw IllegalStateException(e) } catch (e: InterruptedException) { throw IllegalStateException(e) } return createdNodePath }" Create a zookeeper node +@Throws(ConfigurationError::class) fun findClassLoader(): ClassLoader? { val ss: SecuritySupport = SecuritySupport.getInstance() val context: ClassLoader = ss.getContextClassLoader() val system: ClassLoader = ss.getSystemClassLoader() var chain = system while (true) { if (context === chain) { val current: ClassLoader = ObjectFactory::class.java.getClassLoader() chain = system while (true) { if (current === chain) { return system } if (chain == null) { break } chain = ss.getParentClassLoader(chain) } return current } if (chain == null) { break } chain = ss.getParentClassLoader(chain) } return context } Figure out which ClassLoader to use . For JDK 1.2 and later use the context ClassLoader . +"private fun updateProgress(progressLabel: String, progress: Int) { if (myHost != null && (progress != previousProgress || progressLabel) != previousProgressLabel) { myHost.updateProgress(progressLabel, progress) } previousProgress = progress previousProgressLabel = progressLabel }" Used to communicate a progress update between a plugin tool and the main Whitebox user interface . +fun isCellEditable(anEvent: EventObject): Boolean { if (!m_mField.isEditable(false)) return false log.fine(m_mField.getHeader()) if (anEvent is MouseEvent && (anEvent as MouseEvent).getClickCount() < CLICK_TO_START) return false if (m_editor == null) createEditor() return true } Ask the editor if it can start editing using anEvent . If editing can be started this method returns true . Previously called : MTable.isCellEditable +"@Throws(BadLocationException::class) fun applyAll(changes: Collection?) { val changesPerFile: Map> = organize(changes) for (currURI in changesPerFile.keySet()) { val document: IXtextDocument = getDocument(currURI) applyAllInSameDocument(changesPerFile[currURI], document) } }" Applies all given changes . +fun beginApplyInterval() { intervalStartMillis = System.currentTimeMillis() endMillis = intervalStartMillis state = org.gradle.api.tasks.TaskState.apply } Start an apply interval . +"fun updateDataset(source: CandleDataset?, seriesIndex: Int, newBar: Boolean) { requireNotNull(source) { ""Null source (CandleDataset)."" } for (i in 0 until this.getSeriesCount()) { val series: CandleSeries = this.getSeries(i) series.updateSeries( source.getSeries(seriesIndex), source.getSeries(seriesIndex).getItemCount() - 1, newBar ) } }" Method updateDataset . +"fun optInt(key: String?): Int { return optInt(key, 0) }" "Get an optional int value associated with a key , or zero if there is no such key or if the value is not a number . If the value is a string , an attempt will be made to evaluate it as a number ." +"@DSSafe(DSCat.SAFE_LIST) @DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2013-12-30 12:30:28.318 -0500"", hash_original_method = ""FEDEC1668E99CC7AC8B63903F046C2E4"", hash_generated_method = ""270B33800028B49BD2EC75D7757AD67D"" ) protected fun onStartLoading() { if (mCursor != null) deliverResult(mCursor) } if (takeContentChanged() || mCursor == null) { forceLoad() } }" Starts an asynchronous load of the contacts list data . When the result is ready the callbacks will be called on the UI thread . If a previous load has been completed and is still valid the result may be passed to the callbacks immediately . Must be called from the UI thread +"@Throws(IOException::class) fun name(name: String?): JsonWriter? { if (name == null) { throw NullPointerException(""name == null"") } beforeName() string(name) return this }" Encodes the property name . +"protected fun changeTimeBy(amount: Long) { changeTimeBy( amount, timeWrap, if (amount >= 0) TimerStatus.FORWARD else TimerStatus.BACKWARD ) }" Call setTime with the amount given added to the current time . The amount should be negative if you are going backward through time . You need to make sure manageGraphics is called for the map to update . < p > +"@Throws(Exception::class) fun testCreateRenameNoClose() { if (dual) return create(igfs, paths(DIR, SUBDIR), null) var os: IgfsOutputStream? = null try { os = igfs.create(FILE, true) igfs.rename(FILE, FILE2) os.close() } finally { javax.swing.text.html.HTML.Tag.U.closeQuiet(os) } }" Test rename on the file when it was opened for write ( create ) and is not closed yet . +override fun equals(other: Any?): Boolean { if (other == null) return false if (javaClass != other.javaClass) { return false } val that: HostPort = other as HostPort return port === that.port && host!!.equals(that.host) } "returns true if the two objects are equals , false otherwise ." +fun ensureParentFolderHierarchyExists(folder: IFolder) { val parent: IContainer = folder.getParent() if (parent is IFolder) { ensureFolderHierarchyExists(parent as IFolder) } } Ensures the given folder 's parent hierarchy is created if they do not already exist . +private fun Trees() { throw UnsupportedOperationException() } Utility classes should not be instantiated . +"private fun drawLine(iter: DBIDRef): Element? { val path = SVGPath() val obj: SpatialComparable = relation.get(iter) val dims: Int = proj.getVisibleDimensions() var drawn = false var valid = 0 var prevpos = Double.NaN for (i in 0 until dims) { val d: Int = proj.getDimForAxis(i) val minPos: Double = proj.fastProjectDataToRenderSpace(obj.getMin(d), i) if (minPos != minPos) { valid = 0 continue } ++valid if (valid > 1) { if (valid == 2) { path.moveTo(getVisibleAxisX(d - 1), prevpos) } path.lineTo(getVisibleAxisX(d), minPos) drawn = true } prevpos = minPos } valid = 0 for (i in dims - 1 downTo 0) { val d: Int = proj.getDimForAxis(i) val maxPos: Double = proj.fastProjectDataToRenderSpace(obj.getMax(d), i) if (maxPos != maxPos) { valid = 0 continue } ++valid if (valid > 1) { if (valid == 2) { path.moveTo(getVisibleAxisX(d + 1), prevpos) } path.lineTo(getVisibleAxisX(d), maxPos) drawn = true } prevpos = maxPos } return if (!drawn) { null } else path.makeElement(svgp) }" Draw a single line . +"@Throws(Exception::class) fun testExceptionWithEmpty() { val mapper = ObjectMapper() try { val result: Any = mapper.readValue("" "", Any::class.java) fail(""Expected an exception, but got result value: $result"") } catch (e: Exception) { verifyException(e, EOFException::class.java, ""No content"") } }" Simple test to check behavior when end-of-stream is encountered without content . Should throw EOFException . +"@Throws(SQLException::class) fun dropUser(user: User, ignore: Boolean) { val sql = String.format(""drop user %s"", user.getLogin()) try { execute(sql) } catch (e: SQLException) { if (!ignore) { throw e } else if (logger.isDebugEnabled()) { logger.debug(""Drop user failed: $sql"", e) } } }" "Drops user , ignoring errors if desired by caller ." +"fun loadSoundEffects(): Boolean { var attempts = 3 val reply = LoadSoundEffectReply() synchronized(reply) { sendMsg(mAudioHandler, MSG_LOAD_SOUND_EFFECTS, SENDMSG_QUEUE, 0, 0, reply, 0) while (reply.mStatus === 1 && attempts-- > 0) { try { reply.wait(SOUND_EFECTS_LOAD_TIMEOUT_MS) } catch (e: InterruptedException) { Log.w(TAG, ""loadSoundEffects Interrupted while waiting sound pool loaded."") } } } return reply.mStatus === 0 }" Loads samples into the soundpool . This method must be called at first when sound effects are enabled +"fun gcd(p: Int, q: Int): Int { return if (q == 0) { p } else gcd(q, p % q) }" Computes the Greatest Common Devisor of integers p and q . +"fun sort(keys: IntArray?, values: IntArray?, offset: Int, length: Int) { hybridsort(keys, values, offset, offset + length - 1) }" "Sorts a range from the keys in an increasing order . Elements key [ i ] and values [ i ] are always swapped together in the corresponding arrays . < p > A mixture of several sorting algorithms is used : < p > A radix sort performs better on the numeric data we sort , but requires additional storage to perform the sorting . Therefore only the not-very-large parts produced by a quick sort are sorted with radix sort . An insertion sort is used to sort the smallest arrays , where the the overhead of the radix sort is also bigger" +fun isRegistered(name: javax.management.ObjectName?): Boolean { return mbsInterceptor.isRegistered(name) } "Checks whether an MBean , identified by its object name , is already registered with the MBean server ." +"private fun startItemListItem(result: StringBuilder, rootId: String, itemId: String) { result.append(""
"") result.append(""
"") }" Called to start adding an item to an item list . +@Throws(IOException::class) fun write(ios: javax.imageio.stream.ImageOutputStream?) { } Writes the data for this segment to the stream in valid JPEG format . +fun PatternEveryExpr() {} "Ctor - for use to create a pattern expression tree , without pattern child expression ." +"private fun tryQueueCurrentBuffer(elapsedWaiting: Long): Boolean { if (currentBuffer.isEmpty()) return true return if (isOpen && neverPubQueue.size() < neverPubCapacity) { neverPubQueue.add(currentBuffer) totalQueuedRecords.addAndGet(currentBuffer.sizeRecords()) totalQueuedBuffers.incrementAndGet() onQueueBufferSuccess(currentBuffer, elapsedWaiting) currentBuffer = RecordBuffer(flow) true } else if (elapsedWaiting > 0) { onQueueBufferTimeout(currentBuffer, elapsedWaiting) false } else false }" Keep private . Call only when holding lock . +"private fun writeKeysWithPrefix(prefix: String, exclude: String) { for (key in keys) { if (key.startsWith(prefix) && !key.startsWith(exclude)) { ps.println(key + ""="" + prop.getProperty(key)) } } ps.println() }" writes all keys starting with the specified prefix and not starting with the exclude prefix in alphabetical order . +"fun ProtocolInfo( name: String, connectionForms: Collection, sharingProfileForms: Collection ) { name = name connectionForms = connectionForms sharingProfileForms = sharingProfileForms }" Creates a new ProtocolInfo having the given name and forms . The given collections of forms are used to describe the parameters for connections and sharing profiles respectively . +fun prepare(sql: String?): Prepared? {val p: Prepared = parse(sql)p.prepare()if (currentTokenType !== END) {throw getSyntaxError()} return p } Parse the statement and prepare it for execution . +"fun logging(msg1: String?, msg2: String?, msg3: String?) { print(msg1) print("" "") print(msg2) print("" "") println(msg3)" Prints a log message . +"fun initQueryStringHandlers() { this.transport = SimpleTargetedChain() this.transport.setOption(""qs.list"", ""org.apache.axis.transport.http.QSListHandler"") this.transport.setOption(""qs.method"", ""org.apache.axis.transport.http.QSMethodHandler"") this.transport.setOption(""qs.wsdl"", ""org.apache.axis.transport.http.QSWSDLHandler"") }" Initialize a Handler for the transport defined in the Axis server config . This includes optionally filling in query string handlers . +"@DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2013-12-30 13:00:42.071 -0500"", hash_original_method = ""236CE70381CAE691CF8D03F3D0A7E2E8"", hash_generated_method = ""34048EFAD324F63AAF648818713681BB"" ) fun toUpperCase(string: String): String? { var changed = false val chars = string.toCharArray() for (i in chars.indices) { val ch = chars[i] if ('a' <= ch && 'z' >= ch) { changed = true chars[i] = (ch.code - 'a'.code + 'A'.code).toChar() } } return if (changed) { String(chars) } else string }" A locale independent version of toUpperCase . +"fun HTMLForm(htmlC: HTMLComponent, action: String?, method: String?, encType: String) { htmlC = htmlC action = htmlC.convertURL(action) encType = encType if (htmlC.getHTMLCallback() != null) { val linkProps: Int = htmlC.getHTMLCallback().getLinkProperties(htmlC, action) if (linkProps and HTMLCallback.LINK_FORBIDDEN !== 0) { action = null } } this.isPostMethod = method != null && method.equals(""post"", ignoreCase = true) }" Constructs the HTMLForm +"fun CurlInterceptor(logger: jdk.nashorn.internal.runtime.logging.Loggable, limit: Long) { logger = logger limit = limit }" Interceptor responsible for printing curl logs +override fun toString(): String? { return java.lang.String.valueOf(value) } Returns the String value of this mutable . +fun unRegisterImpulseConstraint(con: ImpulseConstraint) { collisionResponseRows -= (con as ImpulseConstraint).GetCollisionResponseRows() collisions.remove(con) } Un-registers an impulse constraint with the constraint engine +"fun Index(node: Node, down: Index, right: Index) { node = node down = down right = right }" Creates index node with given values . +fun isInBoundsX(x: Float): Boolean { return if (isInBoundsLeft(x) && isInBoundsRight(x)) true else false } BELOW METHODS FOR BOUNDS CHECK +fun caseAnonymous_constraint_1_(`object`: Anonymous_constraint_1_?): T? { return null } Returns the result of interpreting the object as an instance of ' < em > Anonymous constraint 1 < /em > ' . < ! -- begin-user-doc -- > This implementation returns null ; returning a non-null result will terminate the switch . < ! -- end-user-doc -- > +fun CProjectLoaderReporter(listeners: ListenerProvider) { m_listeners = listeners } Creates a new reporter object . +"@Throws(InvalidArgument::class,NotFound::class,InvalidSession::class,StorageFault::class,NotImplemented::class) fun queryUniqueIdentifiersForLuns(arrayUniqueId: String): Array? { val methodName = ""queryUniqueIdentifiersForLuns(): "" log.info(methodName + ""Entry with arrayUniqueId["" + arrayUniqueId + ""]"") sslUtil.checkHttpRequest(true, true) val sosManager: SOSManager = contextManager.getSOSManager() val ids: Array = sosManager.queryUniqueIdentifiersForLuns(arrayUniqueId) log.info(methodName + ""Exit returning ids of size["" + ids.size + ""]"") return ids }" Returns unique identifiers for LUNs for the give array Id +"fun onCreateOptionsMenu(menu: Menu): Boolean { mOpsOptionsMenu = menu val inflater: MenuInflater = getMenuInflater() inflater.inflate(R.menu.ops_options_menu, menu) return true }" Inflates the Operations ( `` Ops '' ) Option Menu . +protected fun PackageImpl() { super() } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"fun fillAttributeSet(attrSet: MutableSet<*>) { attrSet.add(""lang"") }" Fills the given set with the attribute names found in this selector . +"fun addColumn(columnFamily: String?, columnQualifier: String?) { var columns: MutableSet = this.columnFamilies.get(columnFamily) if (columns == null) { columns = HashSet() } columns.add(columnQualifier) this.columnFamilies.put(columnFamily, columns) }" Add column family and column qualifier to be extracted from tuple +"fun ofString(name: String?, description: String?): Field? { return Field(name, String::class.java, description) }" Break down metrics by string . < p > Each unique string will allocate a new submetric . < b > Do not use user content as a field value < /b > as field values are never reclaimed . +"fun OMPoint(lat: Double, lon: Double, radius: Int) { setRenderType(RENDERTYPE_LATLON) set(lat, lon) radius = radius }" "Create an OMPoint at a lat/lon position , with the specified radius ." +"@Throws(GamaRuntimeException::class) private fun saveMicroAgents(scope: IScope, agent: IMacroAgent) { innerPopulations = THashMap>() for (microPop in agent.getMicroPopulations()) { val savedAgents: MutableList = ArrayList() val it: Iterator = microPop.iterator() while (it.hasNext()) { savedAgents.add(SavedAgent(scope, it.next())) } innerPopulations.put(microPop.getSpecies().getName(), savedAgents) } }" Recursively save micro-agents of an agent . +"fun GenerationResult( parent: jdk.nashorn.tools.Shell?, style: Int,location: IPath,target: IResource) {super(parent, style) location = location this.targetResource = target setText(""EvoSuite Result"") }" Create the dialog . +"fun run() { ActivationLibrary.deactivate(this, getID()) }" "Thread to deactivate object . First attempts to make object inactive ( via the inactive method ) . If that fails ( the object may still have pending/executing calls ) , then unexport the object forcibly ." +"private fun createImageLink( AD_Language: String, name: String, js_command: String, enabled: Boolean, pressed: Boolean ): a? { var js_command: String? = js_command val img = a(""#"", jdk.tools.jlink.internal.JlinkTask.createImage(AD_Language, name)) if (!pressed || !enabled) img.setID(""imgButtonLink"") else img.setID(""imgButtonPressedLink"") if (js_command == null) js_command = ""'Submit'"" if (js_command.length > 0 && enabled) { if (js_command.startsWith(""startPopup"")) img.setOnClick(js_command) else img.setOnClick( ""SubmitForm('$name', $js_command,'toolbar');return false;"" ) } img.setClass(""ToolbarButton"") img.setOnMouseOver(""window.status='$name';return true;"") img.setOnMouseOut(""window.status='';return true;"") img.setOnBlur(""this.hideFocus=false"") return img }" "Create Image with name , id of button_name and set P_Command onClick" +"fun CassandraStatus(mode: CassandraMode,joined: Boolean,rpcRunning: Boolean,nativeTransportRunning: Boolean,gossipInitialized: Boolean,gossipRunning: Boolean,hostId: String,endpoint: String,tokenCount: Int,dataCenter: String,rack: String,version: String) {mode = mode joined = joined rpcRunning = rpcRunning nativeTransportRunning = nativeTransportRunning gossipInitialized = gossipInitialized gossipRunning = gossipRunning hostId = hostId endpoint = endpoint tokenCount = tokenCount dataCenter = dataCenter rack = rack version = version }" Constructs a CassandraStatus . +"@Throws(GenericEntityException::class) fun checkDataSource( modelEntities: Map?, messages: List?, addMissing: Boolean ) { genericDAO.checkDb(modelEntities, messages, addMissing) }" "Check the datasource to make sure the entity definitions are correct , optionally adding missing entities or fields on the server" +"fun string2HashMap(paramString: String): HashMap? { val params: HashMap = HashMap() for (keyValue in paramString.split("" *& *"".toRegex()).dropLastWhile { it.isEmpty() } .toTypedArray()) { val pairs = keyValue.split("" *= *"".toRegex(), limit = 2).toTypedArray() params[pairs[0]] = if (pairs.size == 1) """" else pairs[1] } return params }" "Convert key=value type String to HashMap < String , String >" +"@LargeTest @Throws(Exception::class) fun testMediaVideoItemRenderingModes() { val videoItemFileName: String = INPUT_FILE_PATH + ""H263_profile0_176x144_15fps_256kbps_AACLC_32kHz_128kbps_s_0_26.3gp"" val videoItemRenderingMode: Int = MediaItem.RENDERING_MODE_BLACK_BORDER var flagForException = false val mediaVideoItem1: MediaVideoItem = mVideoEditorHelper.createMediaItem( mVideoEditor, ""mediaVideoItem1"", videoItemFileName, videoItemRenderingMode ) mVideoEditor.addMediaItem(mediaVideoItem1) mediaVideoItem1.setRenderingMode(MediaItem.RENDERING_MODE_CROPPING) assertEquals( ""MediaVideo Item rendering Mode"", MediaItem.RENDERING_MODE_CROPPING, mediaVideoItem1.getRenderingMode() ) try { mediaVideoItem1.setRenderingMode(MediaItem.RENDERING_MODE_CROPPING + 911) } catch (e: IllegalArgumentException) { flagForException = true } assertTrue(""Media Item Invalid rendering Mode"", flagForException) flagForException = false try { mediaVideoItem1.setRenderingMode(MediaItem.RENDERING_MODE_BLACK_BORDER - 11) } catch (e: IllegalArgumentException) { flagForException = true } assertTrue(""Media Item Invalid rendering Mode"", flagForException) assertEquals( ""MediaVideo Item rendering Mode"", MediaItem.RENDERING_MODE_CROPPING, mediaVideoItem1.getRenderingMode() ) mediaVideoItem1.setRenderingMode(MediaItem.RENDERING_MODE_STRETCH) assertEquals( ""MediaVideo Item rendering Mode"", MediaItem.RENDERING_MODE_STRETCH, mediaVideoItem1.getRenderingMode() ) }" To test creation of Media Video Item with Set and Get rendering Mode +fun visitTree(tree: com.sun.tools.javac.tree.JCTree?) {} Default member enter visitor method : do nothing +"private fun createControls(): EventLogControlPanel? { val c = EventLogControlPanel() c.addHeading(""connections"") conUpCheck = c.addControl(""up"") conDownCheck = c.addControl(""down"") c.addHeading(""messages"") msgCreateCheck = c.addControl(""created"") msgTransferStartCheck = c.addControl(""started relay"") msgRelayCheck = c.addControl(""relayed"") msgDeliveredCheck = c.addControl(""delivered"") msgRemoveCheck = c.addControl(""removed"") msgDropCheck = c.addControl(""dropped"") msgAbortCheck = c.addControl(""aborted"") return c }" Creates a control panel for the log +fun type(): String? { return type } Returns the type of document to get the term vector for . +"fun `test_getIterator$Ljava_text_AttributedCharacterIterator$AttributeII`() { val test = ""Test string"" try { val hm: MutableMap = HashMap() val aci: Array = arrayOfNulls(3) aci[0] = TestAttributedCharacterIteratorAttribute(""att1"") aci[1] = TestAttributedCharacterIteratorAttribute(""att2"") aci[2] = TestAttributedCharacterIteratorAttribute(""att3"") hm[aci[0]] = ""value1"" hm[aci[1]] = ""value2"" val attrString = AttributedString(test) attrString.addAttributes(hm, 2, 4) val it: AttributedCharacterIterator = attrString.getIterator(aci, 1, 5) assertTrue(""Incorrect iteration on AttributedString"", it.getAttribute(aci[0]) == null) assertTrue(""Incorrect iteration on AttributedString"", it.getAttribute(aci[1]) == null) assertTrue(""Incorrect iteration on AttributedString"", it.getAttribute(aci[2]) == null) it.next() assertTrue( ""Incorrect iteration on AttributedString"", it.getAttribute(aci[0]).equals(""value1"") ) assertTrue( ""Incorrect iteration on AttributedString"", it.getAttribute(aci[1]).equals(""value2"") ) assertTrue(""Incorrect iteration on AttributedString"", it.getAttribute(aci[2]) == null) try { attrString.getIterator(aci, -1, 5) fail(""IllegalArgumentException is not thrown."") } catch (iae: IllegalArgumentException) { } }try { attrString.getIterator(aci, 6, 5) fail(""IllegalArgumentException is not thrown."") } catch (iae: IllegalArgumentException) { } try { attrString.getIterator(aci, 3, 2) fail(""IllegalArgumentException is not thrown."") } catch (iae: IllegalArgumentException) { } } catch (e: Exception) { fail(""Unexpected exceptiption $e"") } }" "java.text.AttributedString # getIterator ( AttributedCharacterIterator.Attribute [ ] , int , int ) Test of method java.text.AttributedString # getIterator ( AttributedCharacterIterator.Attribute [ ] , int , int ) ." +private fun newplan(plan: TransformationPlan) { if (plan.replaces(plan)) { plan = plan } } Install a new plan iff it 's more drastic than the existing plan +"private fun buildSmallContingencyTables(): SmallContingencyTables? { val allLabelSet: MutableSet = TreeSet() for (outcome in id2Outcome.getOutcomes()) { allLabelSet.addAll(outcome.getLabels()) } val labelList: List = ArrayList(allLabelSet) val numberOfLabels = labelList.size val counterIncreaseValue = 1.0 val smallContingencyTables = SmallContingencyTables(labelList) for (allLabelsClassId in 0 until numberOfLabels) { for (outcome in id2Outcome.getOutcomes()) { val localClassId: Int = outcome.getReverseLabelMapping(labelList).get(allLabelsClassId) val threshold: Double = outcome.getBipartitionThreshold() var goldValue: Double var predictionValue: Double if (localClassId == -1) { goldValue = 0.0 predictionValue = 0.0 } else { goldValue = outcome.getGoldstandard().get(localClassId) predictionValue = outcome.getPrediction().get(localClassId) } if (goldValue >= threshold) { if (predictionValue >= threshold) { smallContingencyTables.addTruePositives( allLabelsClassId, counterIncreaseValue ) } else { smallContingencyTables.addFalseNegatives( allLabelsClassId, counterIncreaseValue ) } } else { if (predictionValue >= threshold) { smallContingencyTables.addFalsePositives( allLabelsClassId, counterIncreaseValue ) } else { smallContingencyTables.addTrueNegatives( allLabelsClassId, counterIncreaseValue ) } } } } return smallContingencyTables }" build small contingency tables ( a small contingency table for each label ) from id2Outcome +"fun commandTopic(command: String?): String? { var command = command if (command == null) { command = ""+"" } return cmdTopic.replace(""{COMMAND}"", command) }" Get the MQTT topic for a command . +fun hasExtension(extension: String?): Boolean { return if (TextUtils.isEmpty(extension)) { false } else extensionToMimeTypeMap.containsKey(extension) } Returns true if the given extension has a registered MIME type . +"@Before fun onBefore() { tut = TransportUnitType(""TUT"") loc1 = Location(LocationPK(""AREA"", ""ASL"", ""X"", ""Y"", ""Z"")) loc2 = Location(LocationPK(""ARE2"", ""ASL2"", ""X2"", ""Y2"", ""Z2"")) product = Product(""tttt"") entityManager.persist(product) entityManager.persist(tut) entityManager.persist(loc1) entityManager.persist(loc2) tu = TransportUnit(""TEST"") tu.setTransportUnitType(tut) tu.setActualLocation(loc1) entityManager.persist(tu) entityManager.flush() }" Setup some test data . +fun beforeRerunningIndexCreationQuery() {} "Asif : Called just before IndexManager executes the function rerunIndexCreationQuery . After this function gets invoked , IndexManager will iterate over all the indexes of the region making the data maps null & re running the index creation query on the region . The method of Index Manager gets executed from the clear function of the Region" +fun buffered(): Float { return if (totalSize > 0) Futures.getUnchecked(response).cache.cacheSize() / totalSize as Float else -1 } "Returns the percentage that is buffered , or -1 , if unknown" +"fun accept(dir: File?, name: String?): Boolean { return accept(File(dir, name)) }" Returns true if the file in the given directory with the given name should be accepted . +@Throws(Exception::class) @JvmStatic fun main(a: Array) { TestBase.createCaller().init().test() } Run just this test . +fun isFieldPresent(field: String?): Boolean { return fields.containsKey(field) } Checks if the given field is present in this extension because not every field is mandatory ( according to scim 2.0 spec ) . +"fun mapToStr(map: Map?): String? { if (map == null) return null val buf = StringBuilder() var first = true for (entry in map.entrySet()) { val key: Any = entry.getKey() val value: Any = entry.getValue() if (key !is String || value !is String) continue var encodedName: String? = null try { encodedName = URLEncoder.encode(key, ""UTF-8"") } catch (e: UnsupportedEncodingException) { Debug.logError(e, module) } var encodedValue: String? = null try { encodedValue = URLEncoder.encode(value, ""UTF-8"") } catch (e: UnsupportedEncodingException) { Debug.logError(e, module) } if (first) first = false else buf.append(""|"") buf.append(encodedName) buf.append(""="") buf.append(encodedValue) } return buf.toString() }" Creates an encoded String from a Map of name/value pairs ( MUST BE STRINGS ! ) +"@DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2013-12-30 13:00:42.074 -0500"", hash_original_method = ""002C3CFFC816A38E005543BB54E228FD"", hash_generated_method = ""24D6A751F50FC61EC42FBA4D0FC608F4"" ) fun toLowerCase(string: String): String? { var changed = false val chars = string.toCharArray() for (i in chars.indices) { val ch = chars[i] if ('A' <= ch && 'Z' >= ch) { changed = true chars[i] = (ch.code - 'A'.code + 'a'.code).toChar() } } return if (changed) { String(chars) } else string }" A locale independent version of toLowerCase . +"fun numberToWords(num: Int): String? { var num = num if (num == 0) { return LESS_THAN_TWENTY.get(0) } var i = 0 val res = StringBuilder() while (num > 0) { if (num % 1000 != 0) { res.insert(0, "" "") res.insert(0, THOUSANDS.get(i)) res.insert(0, helper(num % 1000)) } num /= 1000 i++ } return res.toString().trim { it <= ' ' } }" "Math , String . Try to find the pattern first . The numbers less than 1000 , e.g . xyz , can be x Hundred y '' ty '' z . The numbers larger than 1000 , we need to add thousand or million or billion . Given a number num , we pronounce the least significant digits first . Then concat the result to the end to next three least significant digits . So the recurrence relation is : Next result of num = the pronunciation of least three digits + current result of num After that , remove those three digits from number . Stop when number is 0 ." +fun hasLat(): Boolean { return super.hasAttribute(LAT) } Returns whether it has the Latitude . +"fun test_ConstructorIF() { val hs2 = HashSet(5, 0.5.toFloat()) assertEquals(""Created incorrect HashSet"", 0, hs2.size()) try { HashSet(0, 0) } catch (e: IllegalArgumentException) { return } fail(""Failed to throw IllegalArgumentException for initial load factor <= 0"") }" "java.util.HashSet # HashSet ( int , float )" +"private fun emitCharMapArray(): Int { val cl: CharClasses = parser.getCharClasses() if (cl.getMaxCharCode() < 256) { emitCharMapArrayUnPacked() return 0 } intervals = cl.getIntervals() println("""") println("" /** "") println("" * Translates characters to character classes"") println("" */"") println("" private static final String ZZ_CMAP_PACKED = "") var n = 0 print("" \"""") var i = 0 var numPairs = 0 var count: Int var value: Int while (i < intervals.length) { count = intervals.get(i).end - intervals.get(i).start + 1 value = colMap.get(intervals.get(i).charClass) while (count > 0xFFFF) { printUC(0xFFFF) printUC(value) count -= 0xFFFF numPairs++ n++ } numPairs++ printUC(count) printUC(value) if (i < intervals.length - 1) { if (++n >= 10) { println(""\""+"") print("" \"""") n = 0 } } i++ } println(""\"";"") println() println("" /** "") println("" * Translates characters to character classes"") println("" */"") println("" private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);"") println() return numPairs }" "Returns the number of elements in the packed char map array , or zero if the char map array will be not be packed . This will be more than intervals.length if the count for any of the values is more than 0xFFFF , since the number of char map array entries per value is ceil ( count / 0xFFFF )" +fun size(): Int { return mSize } Returns the number of key-value mappings that this SparseDoubleArray currently stores . +"fun depends(parent: Int, child: Int) { dag.addNode(child) dag.addNode(parent) dag.addEdge(parent, child) }" "Adds a dependency relation ship between two variables that will be in the network . The integer value corresponds the the index of the i'th categorical variable , where the class target 's value is the number of categorical variables ." +fun DiscreteTransfer(tableValues: IntArray) { tableValues = tableValues this.n = tableValues.size } The input is an int array which will be used later to construct the lut data +"fun roundTo(`val`: Float, prec: Float): Float { return floor(`val` / prec + 0.5f) * prec }" Rounds a single precision value to the given precision . +"fun readKeyValues( topic: String?, consumerConfig: Properties?, maxMessages: Int ): List>? { val consumer: KafkaConsumer = KafkaConsumer(consumerConfig) consumer.subscribe(Collections.singletonList(topic)) val pollIntervalMs = 100 val maxTotalPollTimeMs = 2000 var totalPollTimeMs = 0 val consumedValues: MutableList> = ArrayList() while (totalPollTimeMs < maxTotalPollTimeMs && continueConsuming( consumedValues.size, maxMessages ) ) { totalPollTimeMs += pollIntervalMs val records: ConsumerRecords = consumer.poll(pollIntervalMs) for (record in records) { consumedValues.add(KeyValue(record.key(), record.value())) } } consumer.close() return consumedValues }" Returns up to ` maxMessages ` by reading via the provided consumer ( the topic ( s ) to read from are already configured in the consumer ) . +private fun segment(key: Any): Int { return Math.abs(key.hashCode() % size) } This method performs the translation of the key hash code to the segment index within the list . Translation is done by acquiring the modulus of the hash and the list size . +"private fun handleStateLeaving(endpoint: InetAddress) { val tokens: Collection = getTokensFor(endpoint) if (logger.isDebugEnabled()) logger.debug( ""Node {} state leaving, tokens {}"", endpoint, tokens ) if (!tokenMetadata.isMember(endpoint)) { logger.info(""Node {} state jump to leaving"", endpoint) tokenMetadata.updateNormalTokens(tokens, endpoint) } else if (!tokenMetadata.getTokens(endpoint).containsAll(tokens)) { logger.warn(""Node {} 'leaving' token mismatch. Long network partition?"", endpoint) tokenMetadata.updateNormalTokens(tokens, endpoint) } tokenMetadata.addLeavingEndpoint(endpoint) PendingRangeCalculatorService.instance.update() }" Handle node preparing to leave the ring +"fun MAttributeInstance( ctx: Properties?, M_Attribute_ID: Int, M_AttributeSetInstance_ID: Int, BDValue: BigDecimal?, trxName: String? ) { super(ctx, 0, trxName) setM_Attribute_ID(M_Attribute_ID) setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID) setValueNumber(BDValue) }" Number Value Constructior +"fun supportsPositionedUpdate(): Boolean { debugCodeCall(""supportsPositionedUpdate"") return true }" Returns whether positioned updates are supported . +"private fun prepareMapping(index: String, defaultMappings: Map): Boolean { var success = true for (stringObjectEntry in defaultMappings.entrySet()) { val mapping = stringObjectEntry.getValue() as Map ?: throw RuntimeException(""type mapping not defined"") val putMappingRequestBuilder: PutMappingRequestBuilder = client.admin().indices().preparePutMapping().setIndices(index) putMappingRequestBuilder.setType(stringObjectEntry.getKey()) putMappingRequestBuilder.setSource(mapping) if (log.isLoggable(Level.FINE)) { log.fine(""Elasticsearch create mapping for index '"" + index + "" and type '"" + stringObjectEntry.getKey() + ""': "" + mapping) } val resp: PutMappingResponse = putMappingRequestBuilder.execute().actionGet() if (resp.isAcknowledged()) { if (log.isLoggable(Level.FINE)) { log.fine(""Elasticsearch mapping for index '"" + index + "" and type '"" + stringObjectEntry.getKey() + ""' was acknowledged"") } } else { success = false log.warning(""Elasticsearch mapping creation was not acknowledged for index '"" + index + "" and type '"" + stringObjectEntry.getKey() + ""'"") } } return success }" This method applies the supplied mapping to the index . +fun disableOcr() { if (!ocrDisabled) { excludeParser(TesseractOCRParser::class.java) ocrDisabled = true pdfConfig.setExtractInlineImages(false) } } Disable OCR . This method only has an effect if Tesseract is installed . +"fun eInverseRemove( otherEnd: InternalEObject?, featureID: Int, msgs: NotificationChain? ): NotificationChain? { when (featureID) { DatatypePackage.DICTIONARY_PROPERTY_TYPE__KEY_TYPE -> return basicSetKeyType(null, msgs) DatatypePackage.DICTIONARY_PROPERTY_TYPE__VALUE_TYPE -> return basicSetValueType( null, msgs ) } return super.eInverseRemove(otherEnd, featureID, msgs) }" < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +@JvmStatic fun main(args: Array) { Am().run(args) Command-line entry point . +fun removeAllHighlights() { } Removes all highlights . +fun init() { val p: Properties? p = try { System.getProperties() } catch (ace: AccessControlException) { Properties() } init(p) } Initialize debugging from the system properties . +fun bySecond(vararg seconds: Int?): Builder? { return bySecond(Arrays.asList(seconds)) } Adds one or more BYSECOND rule parts . +fun CakePHP3CustomizerPanel() { initComponents() init() } Creates new form CakePHP3CustomizerPanel +"private fun updateProgress(progressLabel: String, progress: Int) { if (myHost != null && (progress != previousProgress || progressLabel) != previousProgressLabel) { myHost.updateProgress(progressLabel, progress) } previousProgress = progress previousProgressLabel = progressLabel }" Used to communicate a progress update between a plugin tool and the main Whitebox user interface . +fun first(): Char { pos = 0 return current() } Sets the position to getBeginIndex ( ) and returns the character at that position . +@Benchmark @Throws(IOException::class) fun test4_UsingKeySetAndForEach(): Long { var i: Long = 0 for (key in map.keySet()) { i += key + map.get(key) } return i } 4 . Using keySet and foreach +fun eUnset(featureID: Int) { when (featureID) { N4JSPackage.N4_FIELD_DECLARATION__DECLARED_TYPE_REF -> { setDeclaredTypeRef(null as TypeRef?) return } N4JSPackage.N4_FIELD_DECLARATION__BOGUS_TYPE_REF -> { setBogusTypeRef(null as TypeRef?) return } N4JSPackage.N4_FIELD_DECLARATION__DECLARED_NAME -> { setDeclaredName(null as LiteralOrComputedPropertyName?) return } N4JSPackage.N4_FIELD_DECLARATION__DEFINED_FIELD -> { setDefinedField(null as TField?) return } N4JSPackage.N4_FIELD_DECLARATION__EXPRESSION -> { setExpression(null as Expression?) return } } super.eUnset(featureID) } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"private fun StringTextStore(text: String?) { super() fText = text ?: """" fCopyLimit = if (fText.length() > SMALL_TEXT_LIMIT) fText.length() / 2 else 0 }" Create a text store with initial content . +"fun incompleteGammaP(a: Double, x: Double): Double { return incompleteGamma(x, a, lnGamma(a)) }" "Incomplete Gamma function P ( a , x ) = 1-Q ( a , x ) ( a cleanroom implementation of Numerical Recipes gammp ( a , x ) ; in Mathematica this function is 1-GammaRegularized )" +"@Scheduled(fixedDelay = 60000) fun controlHerdJmsMessageListener() { try { val jmsMessageListenerEnabled: Boolean = java.lang.Boolean.valueOf(configurationHelper.getProperty(ConfigurationValue.JMS_LISTENER_ENABLED)) val registry: JmsListenerEndpointRegistry = ApplicationContextHolder.getApplicationContext().getBean( ""org.springframework.jms.config.internalJmsListenerEndpointRegistry"", JmsListenerEndpointRegistry::class.java ) val jmsMessageListenerContainer: MessageListenerContainer = registry.getListenerContainer(HerdJmsDestinationResolver.SQS_DESTINATION_HERD_INCOMING) LOGGER.debug( ""controlHerdJmsMessageListener(): {}={} jmsMessageListenerContainer.isRunning()={}"", ConfigurationValue.JMS_LISTENER_ENABLED.getKey(), jmsMessageListenerEnabled, jmsMessageListenerContainer.isRunning() ) if (!jmsMessageListenerEnabled && jmsMessageListenerContainer.isRunning()) { LOGGER.info(""controlHerdJmsMessageListener(): Stopping the herd JMS message listener ..."") jmsMessageListenerContainer.stop() LOGGER.info(""controlHerdJmsMessageListener(): Done"") } else if (jmsMessageListenerEnabled && !jmsMessageListenerContainer.isRunning()) { LOGGER.info(""controlHerdJmsMessageListener(): Starting the herd JMS message listener ..."") jmsMessageListenerContainer.start() LOGGER.info(""controlHerdJmsMessageListener(): Done"") } } catch (e: Exception) { LOGGER.error( ""controlHerdJmsMessageListener(): Failed to control the herd Jms message listener service."", e ) } }" "Periodically check the configuration and apply the action to the herd JMS message listener service , if needed ." +"@DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2014-08-13 13:14:13.408 -0400"", hash_original_method = ""FC36FCA077BB9356BFDFCA10D99D0311"", hash_generated_method = ""2430FCC224E47ADC0C94FB89530AAC4A"" ) fun AnnotationTypeMismatchException(element: Method, foundType: String) { super(""The annotation element $element doesn't match the type $foundType"") element = element foundType = foundType }" Constructs an instance for the given type element and the type found . +"@Throws(java.awt.dnd.InvalidDnDOperationException::class) fun startDrag( trigger: java.awt.dnd.DragGestureEvent?, dragCursor: Cursor?, transferable: java.awt.datatransfer.Transferable?, dsl: java.awt.dnd.DragSourceListener? ) { startDrag(trigger, dragCursor, null, null, transferable, dsl, null) }" "Start a drag , given the < code > DragGestureEvent < /code > that initiated the drag , the initial < code > Cursor < /code > to use , the < code > Transferable < /code > subject data of the drag , and the < code > DragSourceListener < /code > . < P >" +fun dynamicStartCache(){ } Dynamically starts cache . +"private fun createFieldMenu(): HtmlSelectOneMenu? { val field = HtmlSelectOneMenu() val children: MutableList<*> = field.getChildren() children.add(createSelectItem(""Subject"")) children.add(createSelectItem(""Sender"")) children.add(createSelectItem(""Date"")) children.add(createSelectItem(""Priority"")) children.add(createSelectItem(""Status"")) children.add(createSelectItem(""To"")) children.add(createSelectItem(""Cc"")) children.add(createSelectItem(""To or Cc"")) return field }" Creates the menu that allows the user to select a field . +"public void close ( ) { synchronized ( mDiskCacheLock ) { if ( mDiskLruCache != null ) { try { if ( ! mDiskLruCache . isClosed ( ) ) { mDiskLruCache . close ( ) ; } } catch ( Throwable e ) { LogUtils . e ( e . getMessage ( ) , e ) ; } mDiskLruCache = null ; } } }" Closes the disk cache associated with this ImageCache object . Note that this includes disk access so this should not be executed on the main/UI thread . +"fun close() { synchronized(mDiskCacheLock) { if (mDiskLruCache != null) { try { if (!mDiskLruCache.isClosed()) { mDiskLruCache.close() } } catch (e: Throwable) { LogUtils.e(e.message, e) } mDiskLruCache = null } } }" Common initialization code for new list entries . +public _ScheduleDays ( ) { super ( ) ; } Constructs a _ScheduleDays with no flags initially set . +"public int allocLow ( int size , int addrAlignment ) { for ( MemoryChunk memoryChunk = low ; memoryChunk != null ; memoryChunk = memoryChunk . next ) { if ( memoryChunk . isAvailable ( size , addrAlignment ) ) { return allocLow ( memoryChunk , size , addrAlignment ) ; } } return 0 ; }" Allocate a memory at the lowest address . +public double heapInit ( ) { return memory . getHeapMemoryUsage ( ) . getInit ( ) ; } Returns the heap initial memory of the current JVM . +public final long size ( ) { int sum = 0 ; for ( int i = 0 ; i < this . sets . length ; i ++ ) { sum += this . sets [ i ] . size ( ) ; } return sum ; } Returns the number of fingerprints in this set . Warning : The size is only accurate in single-threaded mode . +"private static Location initLocation ( GlowSession session , PlayerReader reader ) { if ( reader . hasPlayedBefore ( ) ) { Location loc = reader . getLocation ( ) ; if ( loc != null ) { return loc ; } } return session . getServer ( ) . getWorlds ( ) . get ( 0 ) . getSpawnLocation ( ) ; }" Read the location from a PlayerReader for entity initialization . Will fall back to a reasonable default rather than returning null . +"public fun performMessageAction(messageAction: MessageAction) { removeOverlay() when (messageAction) { is Resend -> resendMessage(messageAction.message)is ThreadReply -> { messageActions = messageActions + Reply(messageAction.message) loadThread(messageAction.message) } is Delete, is Flag -> {messageActions = messageActions + messageAction } is Copy -> copyMessage(messageAction.message)is MuteUser -> updateUserMute(messageAction.message.user)is React -> reactToMessage(messageAction.reaction, messageAction.message) is Pin -> updateMessagePin(messageAction.message)else -> {// no op, custom user action}}}" "Triggered when the user selects a new message action, in the message overlay." +public fun dismissAllMessageActions() {this.messageActions = emptySet()} "Dismisses all message actions, when we cancel them in the rest of the UI." +public fun dismissMessageAction(messageAction: MessageAction) {this.messageActions = messageActions - messageAction} "Used to dismiss a specific message action, such as delete, reply, edit or something similar." +@Preview @Composable fun RotatingSquareComponentPreview() { RotatingSquareComponent() } "Android Studio lets you preview your composable functions within the IDE itself, instead of needing to download the app to an Android device or emulator. This is a fantastic feature as you can preview all your custom components(read composable functions) from the comforts of the IDE. The main restriction is, the composable function must not take any parameters. If your composable function requires a parameter, you can simply wrap your component inside another composable function that doesn't take any parameters and call your composable function with the appropriate params. Also, don't forget to annotate it with @Preview & @Composable annotations." +@Composable fun MyApp() { val backgroundColor by animateColorAsState(MaterialTheme.colors.background) Surface(color = backgroundColor) { NewtonsTimerScreen() } } Start building your app here! +override suspend fun handleEvent(event: RootEvent) = when (event) { RootEvent.AppOpen -> handleAppOpen() } region Event Handling +"@Composable public fun BackButton( painter: Painter, onBackPressed: () -> Unit, modifier: Modifier = Modifier, ) { IconButton( modifier = modifier, onClick = onBackPressed ) { Icon( painter = painter, contentDescription = null, tint = ChatTheme.colors.textHighEmphasis, ) } }" "Basic back button, that shows an icon and calls [onBackPressed] when tapped. @param painter The icon or image to show. @param onBackPressed Handler for the back action. @param modifier Modifier for styling." +"@Composable public fun CancelIcon( modifier: Modifier = Modifier, onClick: () -> Unit, ) { Icon( modifier = modifier .background(shape = CircleShape, color = ChatTheme.colors.overlayDark). clickable( indication = null, interactionSource = remember { MutableInteractionSource() }, onClick = onClick ), painter = painterResource(id = R.drawable.stream_compose_ic_close), contentDescription = stringResource(id = R.string.stream_compose_cancel), tint = ChatTheme.colors.appBackground ) }" Represents a simple cancel icon that is used primarily for attachments. @param modifier Modifier for styling. @param onClick Handler when the user clicks on the icon. +"@Composable public fun EmptyContent( text: String, painter: Painter, modifier: Modifier = Modifier, ) { Column( modifier = modifier.background(color = ChatTheme.colors.appBackground), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Icon( painter = painter, contentDescription = null, tint = ChatTheme.colors.disabled, modifier = Modifier.size(96.dp), ) Spacer(Modifier.size(16.dp)) Text( text = text,style = ChatTheme.typography.title3, color = ChatTheme.colors.textLowEmphasis, textAlign = TextAlign.Center ) } }" The view that's shown when there's no data available. Consists of an icon and a caption below it. @param text The text to be displayed. @param painter The painter for the icon. @param modifier Modifier for styling. +"@Composable public fun LoadingFooter(modifier: Modifier = Modifier) { Box( modifier = modifier .background(color = ChatTheme.colors.appBackground) .padding(top = 8.dp, bottom = 48.dp) ) { LoadingIndicator( modifier = Modifier.size(16.dp).align(Alignment.Center)) } }" Shows the loading footer UI in lists. @param modifier Modifier for styling. +"@Composable public fun LoadingIndicator(modifier: Modifier = Modifier) { Box( modifier, contentAlignment = Alignment.Center, ) { CircularProgressIndicator(strokeWidth = 2.dp, color = ChatTheme.colors.primaryAccent) } }" Shows the default loading UI. @param modifier Modifier for styling. +"@Composable public fun NetworkLoadingIndicator( modifier: Modifier = Modifier, spinnerSize: Dp = 18.dp, textStyle: TextStyle = ChatTheme.typography.title3Bold, textColor: Color = ChatTheme.colors.textHighEmphasis, ) { Row( modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { CircularProgressIndicator( modifier = Modifier .padding(horizontal = 8.dp) .size(spinnerSize), strokeWidth = 2.dp, color = ChatTheme.colors.primaryAccent, ) Text( text = stringResource(id = R.string.stream_compose_waiting_for_network), style = textStyle, color = textColor, ) } }" "Represents the default network loading view for the header, in case the network is down. @param modifier Styling for the [Row]. @param spinnerSize The size of the spinner. @param textStyle The text style of the inner text. @param textColor The text color of the inner text." +"@Composable public fun OnlineIndicator(modifier: Modifier = Modifier) { Box( modifier = modifier .size(12.dp).background(ChatTheme.colors.appBackground, CircleShape).padding(2.dp).background(ChatTheme.colors.infoAccent, CircleShape) ) }" Component that represents an online indicator to be used with [io.getstream.chat.android.compose.ui.components.avatar.UserAvatar]. @param modifier Modifier for styling. +"@Composable internal fun DefaultSearchLabel() { Text( text = stringResource(id = R.string.stream_compose_search_input_hint),style = ChatTheme.typography.body,color = ChatTheme.colors.textLowEmphasis, ) }" Default search input field label. +"@Composable internal fun RowScope.DefaultSearchLeadingIcon() { Icon( modifier = Modifier.weight(1f), painter = painterResource(id =R.drawable.stream_compose_ic_search), contentDescription = null, tint = ChatTheme.colors.textLowEmphasis, ) }" "Default search input field leading ""search"" icon." +"@Composable public fun SearchInput(query: String,onValueChange: (String) -> Unit,modifier: Modifier = Modifier,onSearchStarted: () -> Unit = {},leadingIcon: @Composable RowScope.() -> Unit = { DefaultSearchLeadingIcon() }, label: @Composable () -> Unit = { DefaultSearchLabel() }, ) { var isFocused by remember { mutableStateOf(false) } val trailingIcon: (@Composable RowScope.() -> Unit)? = if (isFocused && query.isNotEmpty()) { @Composable { IconButton( modifier = Modifier .weight(1f) .size(24.dp), onClick = { onValueChange("""") }, content = { Icon( painter = painterResource(id = R.drawable.stream_compose_ic_clear), contentDescription = stringResource(id = R.string.stream_compose_search_input_cancel), tint = ChatTheme.colors.textLowEmphasis, ) } ) } } else null InputField( modifier = modifier .onFocusEvent { newState -> val wasPreviouslyFocused = isFocused if (!wasPreviouslyFocused && newState.isFocused) { onSearchStarted() } isFocused = newState.isFocused},value = query,onValueChange = onValueChange, decorationBox = { innerTextField ->Row(Modifier.fillMaxWidth(),verticalAlignment = Alignment.CenterVertically) {leadingIcon() Box(modifier = Modifier.weight(8f)) { if (query.isEmpty()) { label() } innerTextField() } trailingIcon?.invoke(this) } }, maxLines = 1, innerPadding = PaddingValues(4.dp) ) }" "The search component that allows the user to fill in a search query and filter their items. It also holds a clear action, that is active when the search is in focus and not empty, to clear the input. @param query Current query value. @param onValueChange Handler when the value changes. @param modifier Modifier for styling. @param onSearchStarted Handler when the search starts, by focusing the input field. @param leadingIcon The icon at the start of the search component that's customizable, but shows [DefaultSearchLeadingIcon] by default. @param label The label shown in the search component, when there's no input." +"@Composable public fun SimpleDialog( title: String, message: String, onPositiveAction: () -> Unit, onDismiss: () -> Unit, modifier: Modifier = Modifier, ) { AlertDialog( modifier = modifier, onDismissRequest = onDismiss, title = { Text( text = title, color = ChatTheme.colors.textHighEmphasis, style = ChatTheme.typography.title3Bold, ) }, text = { Text( text = message, color = ChatTheme.colors.textHighEmphasis, style = ChatTheme.typography.body, ) }, confirmButton = { TextButton( colors = ButtonDefaults.textButtonColors(contentColor = ChatTheme.colors.primaryAccent), onClick = { onPositiveAction() } ) { Text(text = stringResource(id = R.string.stream_compose_ok)) } }, dismissButton = { TextButton( colors = ButtonDefaults.textButtonColors(contentColor = ChatTheme.colors.primaryAccent), onClick = onDismiss ) { Text(text = stringResource(id = R.string.stream_compose_cancel)) } }, backgroundColor = ChatTheme.colors.barsBackground, ) }" Generic dialog component that allows us to prompt the user. +"@Composable public fun SimpleMenu( modifier: Modifier = Modifier, shape: Shape = ChatTheme.shapes.bottomSheet, overlayColor: Color = ChatTheme.colors.overlay, onDismiss: () -> Unit = {}, headerContent: @Composable ColumnScope.() -> Unit = {}, centerContent: @Composable ColumnScope.() -> Unit = {}, ) { Box( modifier = Modifier .background(overlayColor) .fillMaxSize() .clickable( onClick = onDismiss, indication = null, interactionSource = remember { MutableInteractionSource() } ) ) { Card( modifier = modifier.clickable( onClick = {},indication = null, interactionSource = remember { MutableInteractionSource() } ), shape = shape, backgroundColor = ChatTheme.colors.barsBackground ) { Column { headerContent() centerContent()}}}BackHandler(enabled = true, onBack = onDismiss)}" Represents a reusable and generic modal menu useful for showing info about selected items. +"@Composable public fun Timestamp( date: Date?, modifier: Modifier = Modifier,formatter: DateFormatter = ChatTheme.dateFormatter,formatType: DateFormatType = DATE, ) {val timestamp = if (LocalInspectionMode.current) {""13:49""} else {when (formatType) {TIME -> formatter.formatTime(date)DATE -> formatter.formatDate(date)}}Text(modifier = modifier,text = timestamp,style = ChatTheme.typography.footnote,color = ChatTheme.colors.textLowEmphasis)}" "Represents a timestamp in the app, that's used primarily for channels and messages." +"@Composable public fun TypingIndicator(modifier: Modifier = Modifier) { Row(modifier = modifier, horizontalArrangement = Arrangement.spacedBy(3.dp)) { TypingIndicatorAnimatedDot(0 * DotAnimationDurationMillis) TypingIndicatorAnimatedDot(1 * DotAnimationDurationMillis) TypingIndicatorAnimatedDot(2 * DotAnimationDurationMillis) } }" Represents a simple typing indicator that consists of three animated dots +"@Composable public fun TypingIndicatorAnimatedDot( initialDelayMillis: Int, ) { val alpha = remember { Animatable(0.5f) } LaunchedEffect(initialDelayMillis) { delay(initialDelayMillis.toLong()) alpha.animateTo( targetValue = 1f, animationSpec = infiniteRepeatable( animation = tween( durationMillis = DotAnimationDurationMillis, delayMillis = DotAnimationDurationMillis, ), repeatMode = RepeatMode.Reverse, ), ) } val color: Color = ChatTheme.colors.textLowEmphasis.copy(alpha = alpha.value) Box( Modifier.background(color, CircleShape).size(5.dp) ) }" Show a dot with infinite alpha animation +"@Composable internal fun DefaultFilesPickerItem( fileItem: AttachmentPickerItemState, onItemSelected: (AttachmentPickerItemState) -> Unit, ) { Row( Modifier.fillMaxWidth().clickable(interactionSource = remember { MutableInteractionSource() },indication = rememberRipple(),onClick = { onItemSelected(fileItem) }).padding(vertical = 8.dp, horizontal = 16.dp),verticalAlignment = Alignment.CenterVertically) { Box(contentAlignment = Alignment.Center) { Checkbox(checked = fileItem.isSelected,onCheckedChange = null,colors = CheckboxDefaults.colors(checkedColor = ChatTheme.colors.primaryAccent,uncheckedColor = ChatTheme.colors.disabled,checkmarkColor = Color.White,disabledColor = ChatTheme.colors.disabled,disabledIndeterminateColor = ChatTheme.colors.disabled),)} FilesPickerItemImage( fileItem = fileItem, modifier = Modifier .padding(start = 16.dp) .size(size = 40.dp) ) Column( modifier = Modifier.padding(start = 16.dp), horizontalAlignment = Alignment.Start, verticalArrangement = Arrangement.Center ) { Text( text = fileItem.attachmentMetaData.title ?: """", style = ChatTheme.typography.bodyBold, color = ChatTheme.colors.textHighEmphasis, ) Text( text = MediaStringUtil.convertFileSizeByteCount(fileItem.attachmentMetaData.size), style = ChatTheme.typography.footnote, color = ChatTheme.colors.textLowEmphasis, ) } } }" Represents a single item in the file picker list.@param fileItem File to render.@param onItemSelected Handler when the item is selected. +"@Composable public fun FilesPicker( files: List, onItemSelected: (AttachmentPickerItemState) -> Unit, onBrowseFilesResult: (List) -> Unit, modifier: Modifier = Modifier, itemContent: @Composable (AttachmentPickerItemState) -> Unit = { DefaultFilesPickerItem( fileItem = it, onItemSelected = onItemSelected ) }, ) { val fileSelectContract = rememberLauncherForActivityResult(contract = SelectFilesContract()) { onBrowseFilesResult(it) } Column(modifier = modifier) { Row(Modifier.fillMaxWidth()) { Text( modifier = Modifier.padding(16.dp), text = stringResource(id = R.string.stream_compose_recent_files), style = ChatTheme.typography.bodyBold, color = ChatTheme.colors.textHighEmphasis, ) Spacer(modifier = Modifier.weight(6f)) IconButton( content = { Icon( painter = painterResource(id = R.drawable.stream_compose_ic_more_files), contentDescription = stringResource(id = R.string.stream_compose_send_attachment), tint = ChatTheme.colors.primaryAccent, ) }, onClick = { fileSelectContract.launch(Unit) } ) } LazyColumn(modifier) { items(files) { fileItem -> itemContent(fileItem) } } } }" Shows the UI for files the user can pick for message attachments. Exposes the logic of selecting items and browsing for extra files. +"@Composable public fun FilesPickerItemImage( fileItem: AttachmentPickerItemState, modifier: Modifier = Modifier, ) { val attachment = fileItem.attachmentMetaData val isImage = fileItem.attachmentMetaData.type == ""image"" val painter = if (isImage) { val dataToLoad = attachment.uri ?: attachment.file rememberStreamImagePainter(dataToLoad) } else { painterResource(id = MimeTypeIconProvider.getIconRes(attachment.mimeType)) } val shape = if (isImage) ChatTheme.shapes.imageThumbnail else null val imageModifier = modifier.let { baseModifier -> if (shape != null) baseModifier.clip(shape) else baseModifier } Image( modifier = imageModifier, painter = painter, contentDescription = null, contentScale = if (isImage) ContentScale.Crop else ContentScale.Fit ) }" Represents the image that's shown in file picker items. This can be either an image/icon that represents the file type or a thumbnail in case the file type is an image. +"@Composable private fun AvatarPreview( imageUrl: String, initials: String, ) { ChatTheme { Avatar( modifier = Modifier.size(36.dp), imageUrl = imageUrl, initials = initials ) } }" Shows [Avatar] preview for the provided parameters. +"@Preview(showBackground = true, name = ""Avatar Preview (Without image URL)"") @Composable private fun AvatarWithoutImageUrlPreview() { AvatarPreview(imageUrl ="""",initials = ""JC"" ) }" Preview of [Avatar] for a user which is online.Should show a background gradient with fallback initials. +"@Preview(showBackground = true, name = ""Avatar Preview (With image URL)"") @Composable private fun AvatarWithImageUrlPreview() { AvatarPreview( imageUrl = ""https://sample.com/image.png"", initials = ""JC"" ) }" Preview of [Avatar] for a valid image URL.Should show the provided image. +"@Composable public fun Avatar( imageUrl: String, initials: String, modifier: Modifier = Modifier, shape: Shape = ChatTheme.shapes.avatar, textStyle: TextStyle = ChatTheme.typography.title3Bold, placeholderPainter: Painter? = null, contentDescription: String? = null, initialsAvatarOffset: DpOffset = DpOffset(0.dp, 0.dp), onClick: (() -> Unit)? = null, ) { if (LocalInspectionMode.current && imageUrl.isNotBlank()) { ImageAvatar( modifier = modifier, shape = shape, painter = painterResource(id = R.drawable.stream_compose_preview_avatar), contentDescription = contentDescription,onClick = onClick)return}if (imageUrl.isBlank()) {InitialsAvatar(modifier = modifier, initials = initials, shape = shape,textStyle = textStyle,onClick = onClick,avatarOffset = initialsAvatarOffset)return}val painter = rememberStreamImagePainter(data = imageUrl,placeholderPainter = painterResource(id = R.drawable.stream_compose_preview_avatar))if (painter.state is AsyncImagePainter.State.Error) {InitialsAvatar( modifier = modifier, initials = initials, shape = shape, textStyle = textStyle, onClick = onClick, avatarOffset = initialsAvatarOffset ) } else if (painter.state is AsyncImagePainter.State.Loading && placeholderPainter != null) { ImageAvatar( modifier = modifier, shape = shape, painter = placeholderPainter, contentDescription = contentDescription, onClick = onClick ) } else { ImageAvatar( modifier = modifier, shape = shape, painter = painter, contentDescription = contentDescription, onClick = onClick ) } }" "An avatar that renders an image from the provided image URL. In case the image URL was empty or there was an error loading the image, it falls back to the initials avatar." +"@Composable private fun ChannelAvatarPreview(channel: Channel) { ChatTheme { ChannelAvatar( channel = channel, currentUser = PreviewUserData.user1, modifier = Modifier.size(36.dp) ) } }" Shows [ChannelAvatar] preview for the provided parameters. +"@Preview(showBackground = true, name = ""ChannelAvatar Preview (Many members)"") @Composable private fun ChannelAvatarForChannelWithManyMembersPreview() {ChannelAvatarPreview(PreviewChannelData.channelWithManyMembers) }" Preview of [ChannelAvatar] for a channel without image and with many members. Should show an avatar with 4 sections that represent the avatars of the first 4 members of the channel. +"@Composable public fun ChannelAvatar( channel: Channel,currentUser: User?,modifier: Modifier = Modifier,shape: Shape = ChatTheme.shapes.avatar,textStyle: TextStyle = ChatTheme.typography.title3Bold,groupAvatarTextStyle: TextStyle = ChatTheme.typography.captionBold,showOnlineIndicator: Boolean = true,onlineIndicatorAlignment: OnlineIndicatorAlignment = OnlineIndicatorAlignment.TopEnd,onlineIndicator: @Composable BoxScope.() -> Unit = {DefaultOnlineIndicator(onlineIndicatorAlignment)}, contentDescription: String? = null,onClick: (() -> Unit)? = null,) {val members = channel.membersval memberCount = members.sizewhen {channel.image.isNotEmpty() -> { Avatar( modifier = modifier,imageUrl = channel.image,initials = channel.initials,textStyle = textStyle,shape = shape,contentDescription = contentDescription,onClick = onClick)}memberCount == 1 -> {val user = members.first().userUserAvatar(modifier = modifier,user = user,shape = shape,contentDescription = user.name, showOnlineIndicator = showOnlineIndicator,onlineIndicatorAlignment = onlineIndicatorAlignment,onlineIndicator = onlineIndicator,onClick = onClick)}memberCount == 2 && members.any { it.user.id == currentUser?.id } -> {val user = members.first { it.user.id != currentUser?.id }.user UserAvatar(modifier = modifier,user = user,shape = shape, contentDescription = user.name,showOnlineIndicator = showOnlineIndicator,onlineIndicatorAlignment = onlineIndicatorAlignment,onlineIndicator = onlineIndicator, onClick = onClick)}else -> {val users = members.filter { it.user.id != currentUser?.id }.map { it.user }GroupAvatar(users = users,modifier = modifier,shape = shape,textStyle = groupAvatarTextStyle,onClick = onClick,)}}}" "Represents the [Channel] avatar that's shown when browsing channels or when you open the Messages screen.Based on the state of the [Channel] and the number of members, it shows different types of images." +"@Preview(showBackground = true, name = ""ChannelAvatar Preview (With image)"") @Composable private fun ChannelWithImageAvatarPreview() { ChannelAvatarPreview(PreviewChannelData.channelWithImage) }" Preview of [ChannelAvatar] for a channel with an avatar image. Should show a channel image. +"@Preview(showBackground = true, name = ""ChannelAvatar Preview (Online user)"") @Composable private fun ChannelAvatarForDirectChannelWithOnlineUserPreview() { ChannelAvatarPreview(PreviewChannelData.channelWithOnlineUser) }" Preview of [ChannelAvatar] for a direct conversation with an online user. Should show a user avatar with an online indicator. +"@Preview(showBackground = true, name = ""ChannelAvatar Preview (Only one user)"")@Composableprivate fun ChannelAvatarForDirectChannelWithOneUserPreview() { ChannelAvatarPreview(PreviewChannelData.channelWithOneUser) }" Preview of [ChannelAvatar] for a direct conversation with only one user.Should show a user avatar with an online indicator. +"@Preview(showBackground = true, name = ""ChannelAvatar Preview (Few members)"") @Composable private fun ChannelAvatarForChannelWithFewMembersPreview() { ChannelAvatarPreview(PreviewChannelData.channelWithFewMembers) }" Preview of [ChannelAvatar] for a channel without image and with few members.Should show an avatar with 2 sections that represent the avatars of the first 2 members of the channel. +"@Composable public fun GroupAvatar( users: List, modifier: Modifier = Modifier, shape: Shape = ChatTheme.shapes.avatar, textStyle: TextStyle = ChatTheme.typography.captionBold, onClick: (() -> Unit)? = null, ) { val avatarUsers = users.take(DefaultNumberOfAvatars) val imageCount = avatarUsers.size val clickableModifier: Modifier = if (onClick != null) { modifier.clickable( onClick = onClick, indication = rememberRipple(bounded = false), interactionSource = remember { MutableInteractionSource() } ) } else { modifier } Row(clickableModifier.clip(shape)) { Column( modifier = Modifier .weight(1f, fill = false).fillMaxHeight()) {for (imageIndex in 0 until imageCount step 2) {if (imageIndex < imageCount) {UserAvatar(modifier = Modifier.weight(1f).fillMaxSize(),user = avatarUsers[imageIndex],shape = RectangleShape,textStyle = textStyle,showOnlineIndicator = false,initialsAvatarOffset = getAvatarPositionOffset(dimens = ChatTheme.dimens,userPosition = imageIndex, memberCount = imageCount))}}}Column(modifier = Modifier.weight(1f, fill = false).fillMaxHeight()) {for (imageIndex in 1 until imageCount step 2) {if (imageIndex < imageCount) {UserAvatar(modifier = Modifier.weight(1f).fillMaxSize(),user = avatarUsers[imageIndex],shape = RectangleShape,textStyle = textStyle,showOnlineIndicator = false,initialsAvatarOffset = getAvatarPositionOffset(dimens = ChatTheme.dimens,userPosition = imageIndex,memberCount = imageCount))}}}}}" Represents an avatar with a matrix of user images or initials. +"@Composable public fun ImageAvatar( painter: Painter, modifier: Modifier = Modifier, shape: Shape = ChatTheme.shapes.avatar, contentDescription: String? = null, onClick: (() -> Unit)? = null, ) { val clickableModifier: Modifier = if (onClick != null) { modifier.clickable( onClick = onClick, indication = rememberRipple(bounded = false), interactionSource = remember { MutableInteractionSource() } ) } else { modifier } Image( modifier = clickableModifier.clip(shape), contentScale = ContentScale.Crop,painter = painter, contentDescription = contentDescription ) }" "Renders an image the [painter] provides. It allows for customization,uses the 'avatar' shape from [ChatTheme.shapes] for the clipping and exposes an [onClick] action." +"@Composable public fun InitialsAvatar( initials: String, modifier: Modifier = Modifier,shape: Shape = ChatTheme.shapes.avatar,textStyle: TextStyle = ChatTheme.typography.title3Bold,avatarOffset: DpOffset = DpOffset(0.dp, 0.dp),onClick: (() -> Unit)? = null,) {val clickableModifier: Modifier = if (onClick != null) { modifier.clickable(onClick = onClick,indication = rememberRipple(bounded = false),interactionSource = remember { MutableInteractionSource() })} else {modifier } val initialsGradient = initialsGradient(initials = initials) Box( modifier = clickableModifier.clip(shape).background(brush = initialsGradient)) { Text(modifier = Modifier.align(Alignment.Center) .offset(avatarOffset.x, avatarOffset.y),text = initials,style = textStyle,color = Color.White)} }" Represents a special avatar case when we need to show the initials instead of an image. Usually happens when there are no images to show in the avatar. +"@Composable public fun UserAvatar( user: User, modifier: Modifier = Modifier, shape: Shape = ChatTheme.shapes.avatar, textStyle: TextStyle = ChatTheme.typography.title3Bold, contentDescription: String? = null, showOnlineIndicator: Boolean = true, onlineIndicatorAlignment: OnlineIndicatorAlignment = OnlineIndicatorAlignment.TopEnd, initialsAvatarOffset: DpOffset = DpOffset(0.dp, 0.dp), onlineIndicator: @Composable BoxScope.() -> Unit = { DefaultOnlineIndicator(onlineIndicatorAlignment) }, onClick: (() -> Unit)? = null, ) { Box(modifier = modifier) { Avatar( modifier = Modifier.fillMaxSize(), imageUrl = user.image, initials = user.initials, textStyle = textStyle, shape = shape, contentDescription = contentDescription, onClick = onClick, initialsAvatarOffset = initialsAvatarOffset ) if (showOnlineIndicator && user.online) { onlineIndicator() } } }" "Represents the [User] avatar that's shown on the Messages screen or in headers of DMs. Based on the state within the [User], we either show an image or their initials." +@Composable internal fun BoxScope.DefaultOnlineIndicator(onlineIndicatorAlignment: OnlineIndicatorAlignment) { OnlineIndicator(modifier = Modifier.align(onlineIndicatorAlignment.alignment)) } The default online indicator for channel members. +"@Preview(showBackground = true, name = ""UserAvatar Preview (With avatar image)"") @Composable private fun UserAvatarForUserWithImagePreview() { UserAvatarPreview(PreviewUserData.userWithImage) }" Preview of [UserAvatar] for a user with avatar image. Should show a placeholder that represents user avatar image. +"@Preview(showBackground = true, name = ""UserAvatar Preview (With online status)"") @Composable private fun UserAvatarForOnlineUserPreview() { UserAvatarPreview(PreviewUserData.userWithOnlineStatus) }" Preview of [UserAvatar] for a user which is online. Should show an avatar with an online indicator in the upper right corner. +"@Preview(showBackground = true, name = ""UserAvatar Preview (Without avatar image)"") @Composable private fun UserAvatarForUserWithoutImagePreview() { UserAvatarPreview(PreviewUserData.userWithoutImage) }" Preview of [UserAvatar] for a user without avatar image.Should show background gradient and user initials. +"@Composable private fun UserAvatarPreview(user: User) { ChatTheme { UserAvatar( modifier = Modifier.size(36.dp), user = user, showOnlineIndicator = true, ) } }" Shows [UserAvatar] preview for the provided parameters. +"@Composable public fun ChannelMembers(members: List,modifier: Modifier = Modifier,) {LazyRow(modifier = modifier.fillMaxWidth().padding(vertical = 24.dp),horizontalArrangement = Arrangement.Center,contentPadding = PaddingValues(start = 16.dp, end = 16.dp)) {items(members) { member ->ChannelMembersItem( modifier = Modifier.width(ChatTheme.dimens.selectedChannelMenuUserItemWidth).padding(horizontal = ChatTheme.dimens.selectedChannelMenuUserItemHorizontalPadding),member = member,)}}}" Represents a list of members in the channel. +"@Preview(showBackground = true, name = ""ChannelMembers Preview (One member)"") @Composable private fun OneMemberChannelMembersPreview() { ChatTheme { ChannelMembers(members = PreviewMembersData.oneMember) } }" Preview of [ChannelMembers] with one channel member. +"@Preview(showBackground = true, name = ""ChannelMembers Preview (Many members)"")@Composableprivate fun ManyMembersChannelMembersPreview() {ChatTheme { ChannelMembers(members = PreviewMembersData.manyMembers) } }" Preview of [ChannelMembers] with many channel members. +"@Composable internal fun ChannelMembersItem( member: Member, modifier: Modifier = Modifier, ) { val memberName = member.user.name Column( modifier = modifier, verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { UserAvatar( modifier = Modifier.size(ChatTheme.dimens.selectedChannelMenuUserItemAvatarSize), user = member.user, contentDescription = memberName ) Text( text = memberName, style = ChatTheme.typography.footnoteBold, overflow = TextOverflow.Ellipsis, maxLines = 1, color = ChatTheme.colors.textHighEmphasis, ) } }" "The UI component that shows a user avatar and user name, as a member of a channel." +"@Preview(showBackground = true, name = ""ChannelMembersItem Preview"") @Composable private fun ChannelMemberItemPreview() { ChatTheme { ChannelMembersItem(Member(user = PreviewUserData.user1)) } }" Preview of [ChannelMembersItem].Should show user avatar and user name. +"@Composable public fun ChannelOptions( options: List, onChannelOptionClick: (ChannelAction) -> Unit, modifier: Modifier = Modifier, ) { LazyColumn( modifier = modifier.fillMaxWidth().wrapContentHeight()) {items(options) { option ->Spacer(modifier = Modifier.fillMaxWidth().height(0.5.dp).background(color = ChatTheme.colors.borders)) ChannelOptionsItem(title = option.title,titleColor = option.titleColor,leadingIcon = {Icon(modifier = Modifier.size(56.dp).padding(16.dp), painter = option.iconPainter,tint = option.iconColor,contentDescription = null)},onClick = { onChannelOptionClick(option.action) })}}}" " This is the default bottom drawer UI that shows up when the user long taps on a channel item. It sets up different actions that we provide, based on user permissions." +"@Composable public fun buildDefaultChannelOptionsState( selectedChannel: Channel, isMuted: Boolean, ownCapabilities: Set, ): List { val canLeaveChannel = ownCapabilities.contains(ChannelCapabilities.LEAVE_CHANNEL) val canDeleteChannel = ownCapabilities.contains(ChannelCapabilities.DELETE_CHANNEL) return listOfNotNull( ChannelOptionState( title = stringResource(id = R.string.stream_compose_selected_channel_menu_view_info), titleColor = ChatTheme.colors.textHighEmphasis, iconPainter = painterResource(id = R.drawable.stream_compose_ic_person), iconColor = ChatTheme.colors.textLowEmphasis, action = ViewInfo(selectedChannel) ), if (canLeaveChannel) { ChannelOptionState( title = stringResource(id = R.string.stream_compose_selected_channel_menu_leave_group), titleColor = ChatTheme.colors.textHighEmphasis, iconPainter = painterResource(id = R.drawable.stream_compose_ic_person_remove), iconColor = ChatTheme.colors.textLowEmphasis, action = LeaveGroup(selectedChannel) ) } else null, if (isMuted) { ChannelOptionState( title = stringResource(id = R.string.stream_compose_selected_channel_menu_unmute_channel), titleColor = ChatTheme.colors.textHighEmphasis, iconPainter = painterResource(id = R.drawable.stream_compose_ic_unmute), iconColor = ChatTheme.colors.textLowEmphasis, action = UnmuteChannel(selectedChannel) ) } else { ChannelOptionState( title = stringResource(id = R.string.stream_compose_selected_channel_menu_mute_channel), titleColor = ChatTheme.colors.textHighEmphasis, iconPainter = painterResource(id = R.drawable.stream_compose_ic_mute), iconColor = ChatTheme.colors.textLowEmphasis, action = MuteChannel(selectedChannel) ) }, if (canDeleteChannel) { ChannelOptionState( title = stringResource(id = R.string.stream_compose_selected_channel_menu_delete_conversation), titleColor = ChatTheme.colors.errorAccent, iconPainter = painterResource(id = R.drawable.stream_compose_ic_delete), iconColor = ChatTheme.colors.errorAccent, action = DeleteConversation(selectedChannel) ) } else null, ChannelOptionState( title = stringResource(id = R.string.stream_compose_selected_channel_menu_dismiss), titleColor = ChatTheme.colors.textHighEmphasis, iconPainter = painterResource(id = R.drawable.stream_compose_ic_clear), iconColor = ChatTheme.colors.textLowEmphasis, action = Cancel, ) ) }" "Builds the default list of channel options, based on the current user and the state of the channel." +"@Preview(showBackground = true, name = ""ChannelOptions Preview"") @Composable private fun ChannelOptionsPreview() { ChatTheme { ChannelOptions( options = buildDefaultChannelOptionsState( selectedChannel = PreviewChannelData.channelWithMessages, isMuted = false, ownCapabilities = ChannelCapabilities.toSet() ), onChannelOptionClick = {} ) } }" Preview of [ChannelOptions]. Should show a list of available actions for the channel. +"@Composable internal fun ChannelOptionsItem( title: String,titleColor: Color,leadingIcon: @Composable () -> Unit,onClick: () -> Unit,modifier: Modifier = Modifier,) {Row( modifier.fillMaxWidth().height(56.dp).clickable(onClick = onClick,indication = rememberRipple(),interactionSource = remember { MutableInteractionSource() }), verticalAlignment = Alignment.CenterVertically,horizontalArrangement = Arrangement.Start) {leadingIcon()Text(text = title,style = ChatTheme.typography.bodyBold,color = titleColor)}}" Default component for selected channel menu options. +"@Preview(showBackground = true, name = ""ChannelOptionsItem Preview"") @Composableprivate fun ChannelOptionsItemPreview() {ChatTheme {ChannelOptionsItem( title = stringResource(id = R.string.stream_compose_selected_channel_menu_view_info),titleColor = ChatTheme.colors.textHighEmphasis,leadingIcon = {Icon(modifier = Modifier.size(56.dp).padding(16.dp),painter = painterResource(id = R.drawable.stream_compose_ic_person),tint = ChatTheme.colors.textLowEmphasis,contentDescription = null)}, onClick = {} ) } }" Preview of [ChannelOptionsItem]. Should show a channel action item with an icon and a name. +"@Composable public fun MessageReadStatusIcon( channel: Channel, message: Message, currentUser: User?, modifier: Modifier = Modifier, ) { val readStatues = channel.getReadStatuses(userToIgnore = currentUser)val readCount = readStatues.count { it.time >= message.getCreatedAtOrThrow().time }val isMessageRead = readCount != 0 MessageReadStatusIcon(message = message,isMessageRead = isMessageRead,modifier = modifier,)}" Shows a delivery status indicator for a particular message +"@Composable public fun MessageReadStatusIcon(message: Message,isMessageRead: Boolean,modifier: Modifier = Modifier,) {val syncStatus = message.syncStatus when { isMessageRead -> { Icon( modifier = modifier, painter = painterResource(id = R.drawable.stream_compose_message_seen), contentDescription = null, tint = ChatTheme.colors.primaryAccent, ) } syncStatus == SyncStatus.SYNC_NEEDED || syncStatus == SyncStatus.AWAITING_ATTACHMENTS -> { Icon( modifier = modifier, painter = painterResource(id = R.drawable.stream_compose_ic_clock), contentDescription = null, tint = ChatTheme.colors.textLowEmphasis, ) } syncStatus == SyncStatus.COMPLETED -> { Icon( modifier = modifier, painter = painterResource(id = R.drawable.stream_compose_message_sent), contentDescription = null, tint = ChatTheme.colors.textLowEmphasis, ) } } }" Shows a delivery status indicator for a particular message. +"@Preview(showBackground = true, name = ""MessageReadStatusIcon Preview (Seen message)"")@Composableprivate fun SeenMessageReadStatusIcon() {ChatTheme { MessageReadStatusIcon( message = PreviewMessageData.message2, isMessageRead = true, ) }}" Preview of [MessageReadStatusIcon] for a seen message. Should show a double tick indicator. +"@Composable public fun UnreadCountIndicator( unreadCount: Int, modifier: Modifier = Modifier, color: Color = ChatTheme.colors.errorAccent, ) { val displayText = if (unreadCount > LimitTooManyUnreadCount) UnreadCountMany else unreadCount.toString() val shape = RoundedCornerShape(9.dp) Box( modifier = modifier .defaultMinSize(minWidth = 18.dp, minHeight = 18.dp) .background(shape = shape, color = color) .padding(horizontal = 4.dp), contentAlignment = Alignment.Center ) { Text( text = displayText, color = Color.White, textAlign = TextAlign.Center, style = ChatTheme.typography.captionBold ) } }" "Shows the unread count badge for each channel item, to showcase how many messages the user didn't read." +"@Preview(showBackground = true, name = ""UnreadCountIndicator Preview (Few unread messages)"")@Composableprivate fun FewMessagesUnreadCountIndicatorPreview() { ChatTheme { UnreadCountIndicator(unreadCount = 5) } }" Preview of [UnreadCountIndicator] with few unread messages.Should show a badge with the number of unread messages. +"@Preview(showBackground = true, name = ""UnreadCountIndicator Preview (Many unread messages)"") @Composableprivate fun ManyMessagesUnreadCountIndicatorPreview() {ChatTheme {UnreadCountIndicator(unreadCount = 200)} }" Preview of [UnreadCountIndicator] with many unread messages. Should show a badge with the placeholder text. +"@Composable public fun CoolDownIndicator( coolDownTime: Int, modifier: Modifier = Modifier, ) {Box( modifier = modifier.size(48.dp).padding(12.dp).background(shape = RoundedCornerShape(24.dp), color = ChatTheme.colors.disabled),contentAlignment = Alignment.Center) {Text(text = coolDownTime.toString(),color = Color.White,textAlign = TextAlign.Center,style = ChatTheme.typography.bodyBold)}}" Represent a timer that show the remaining time until the user is allowed to send the next message. +"@Composablepublic fun InputField(value: String,onValueChange: (String) -> Unit,modifier: Modifier = Modifier,enabled: Boolean = true,maxLines: Int = Int.MAX_VALUE,border: BorderStroke = BorderStroke(1.dp, ChatTheme.colors.borders),innerPadding: PaddingValues = PaddingValues(horizontal = 16.dp, vertical = 8.dp),keyboardOptions: KeyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences),decorationBox: @Composable (innerTextField:@Composable () -> Unit) -> Unit,) {var textFieldValueState by remember { mutableStateOf(TextFieldValue(text = value)) } val selection = if (textFieldValueState.isCursorAtTheEnd()) {TextRange(value.length)} else {textFieldValueState.selection}val textFieldValue = textFieldValueState.copy(text = value,selection = selection) val description = stringResource(id = R.string.stream_compose_cd_message_input) BasicTextField(modifier = modifier.border(border = border, shape =ChatTheme.shapes.inputField).clip(ChatTheme.shapes.inputField).background(ChatTheme.colors.inputBackground).padding(innerPadding).semantics {contentDescription = description },value = textFieldValue,onValueChange = {textFieldValueState = itif (value != it.text) {onValueChange(it.text)}},textStyle = ChatTheme.typography.body.copy(color = ChatTheme.colors.textHighEmphasis,textDirection = TextDirection.Content),cursorBrush = SolidColor(ChatTheme.colors.primaryAccent),decorationBox = { innerTextField -> decorationBox(innerTextField) },maxLines = maxLines,singleLine = maxLines == 1,enabled = enabled,keyboardOptions = keyboardOptions)}" "Custom input field that we use for our UI. It's fairly simple - shows a basic input with clipped corners and a border stroke, with some extra padding on each side.Within it, we allow for custom decoration, so that the user can define what the input field looks like when filled with content." +private fun TextFieldValue.isCursorAtTheEnd(): Boolean {val textLength = text.lengthval selectionStart = selection.startval selectionEnd = selection.endreturn textLength == selectionStart && textLength == selectionEnd} Check if the [TextFieldValue] state represents a UI with the cursor at the end of the input. +"@Composable public fun MessageInputOptions( activeAction: MessageAction,onCancelAction: () -> Unit,modifier: Modifier = Modifier,) {val optionImage =painterResource(id = if (activeAction is Reply) R.drawable.stream_compose_ic_reply else R.drawable.stream_compose_ic_edit)val title = stringResource(id = if (activeAction is Reply) R.string.stream_compose_reply_to_messageelse R.string.stream_compose_edit_message)Row(modifier, verticalAlignment = Alignment.CenterVertically,horizontalArrangement = Arrangement.SpaceBetween) {Icon(modifier = Modifier.padding(4.dp), painter = optionImage,contentDescription = null,tint = ChatTheme.colors.textLowEmphasis,)Text(text = title,style = ChatTheme.typography.bodyBold,color = ChatTheme.colors.textHighEmphasis,)Icon(modifier = Modifier.padding(4.dp).clickable(onClick = onCancelAction,indication = rememberRipple(bounded = false), interactionSource = remember { MutableInteractionSource() }),painter = painterResource(id = R.drawable.stream_compose_ic_close),contentDescription = stringResource(id= R.string.stream_compose_cancel),tint = ChatTheme.colors.textLowEmphasis,)}}" "Shows the options ""header"" for the message input component. This is based on the currently active message action - [io.getstream.chat.android.common.state.Reply] or [io.getstream.chat.android.common.state.Edit]." +"@Composable public fun MessageOptionItem( option: MessageOptionItemState, modifier: Modifier = Modifier, verticalAlignment: Alignment.Vertical = Alignment.CenterVertically, horizontalArrangement: Arrangement.Horizontal = Arrangement.Start, ) { val title = stringResource(id = option.title) Row( modifier = modifier, verticalAlignment = verticalAlignment,horizontalArrangement = horizontalArrangement ) { Icon( modifier = Modifier.padding(horizontal = 16.dp), painter = option.iconPainter, tint = option.iconColor, contentDescription = title, ) Text( text = title, style = ChatTheme.typography.body, color = option.titleColor ) } }" Each option item in the column of options. +"@Preview(showBackground = true, name = ""MessageOptionItem Preview"")@Composableprivate fun MessageOptionItemPreview() {ChatTheme {val option = MessageOptionItemState(title = R.string.stream_compose_reply,iconPainter = painterResource(R.drawable.stream_compose_ic_reply),action = Reply(PreviewMessageData.message1),titleColor = ChatTheme.colors.textHighEmphasis,iconColor = ChatTheme.colors.textLowEmphasis,)MessageOptionItem(modifier = Modifier.fillMaxWidth(),option = option)}}" Preview of [MessageOptionItem]. +"@Preview(showBackground = true, name = ""MessageOptions Preview (Own Message)"") @Composableprivate fun MessageOptionsForOwnMessagePreview() { MessageOptionsPreview( messageUser = PreviewUserData.user1, currentUser = PreviewUserData.user1, syncStatus = SyncStatus.COMPLETED, ) }" Preview of [MessageOptions] for a delivered message of the current user. +"@Preview(showBackground = true, name = ""MessageOptions Preview (Theirs Message)"") @Composable private fun MessageOptionsForTheirsMessagePreview() { MessageOptionsPreview( messageUser = PreviewUserData.user1, currentUser = PreviewUserData.user2, syncStatus = SyncStatus.COMPLETED, ) }" Preview of [MessageOptions] for theirs message. +"@Preview(showBackground = true, name = ""MessageOptions Preview (Failed Message)"") @Composable private fun MessageOptionsForFailedMessagePreview() { MessageOptionsPreview( messageUser = PreviewUserData.user1, currentUser = PreviewUserData.user1, syncStatus = SyncStatus.FAILED_PERMANENTLY, ) }" Preview of [MessageOptions] for a failed message. +"@Composable private fun MessageOptionsPreview( messageUser: User, currentUser: User, syncStatus: SyncStatus, ) { ChatTheme { val selectedMMessage = PreviewMessageData.message1.copy( user = messageUser, syncStatus = syncStatus ) val messageOptionsStateList = defaultMessageOptionsState( selectedMessage = selectedMMessage, currentUser = currentUser, isInThread = false, ownCapabilities = ChannelCapabilities.toSet() ) MessageOptions(options = messageOptionsStateList, onMessageOptionSelected = {}) } }" Shows [MessageOptions] preview for the provided parameters. +"@Composable public fun ModeratedMessageDialog( message: Message, onDismissRequest: () -> Unit, onDialogOptionInteraction: (message: Message, option: ModeratedMessageOption) -> Unit, modifier: Modifier = Modifier, moderatedMessageOptions: List = defaultMessageModerationOptions(), dialogTitle: @Composable () -> Unit = { DefaultModeratedMessageDialogTitle() }, dialogDescription: @Composable () -> Unit = { DefaultModeratedMessageDialogDescription() }, dialogOptions: @Composable () -> Unit = { DefaultModeratedDialogOptions( message = message, moderatedMessageOptions = moderatedMessageOptions, onDialogOptionInteraction = onDialogOptionInteraction, onDismissRequest = onDismissRequest ) }, ) { Dialog(onDismissRequest = onDismissRequest) { Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally ) { dialogTitle() dialogDescription() dialogOptions() } } }" "Dialog that is shown when user clicks or long taps on a moderated message. Gives the user the ability to either send the message again, edit it and then send it or to delete it." +"@Composable internal fun DefaultModeratedDialogOptions( message: Message, moderatedMessageOptions: List, onDialogOptionInteraction: (message: Message, option: ModeratedMessageOption) -> Unit, onDismissRequest: () -> Unit, ) { Spacer(modifier = Modifier.height(12.dp)) ModeratedMessageDialogOptions( message = message, options = moderatedMessageOptions, onDismissRequest = onDismissRequest,onDialogOptionInteraction onDialogOptionInteraction)}" "Represents the default content shown for the moderated message dialog options.By default we show the options to send the message anyway, edit it or delete it." +"@Composable internal fun DefaultModeratedMessageDialogTitle() { Spacer(modifier = Modifier.height(12.dp))val painter = painterResource(id = R.drawable.stream_compose_ic_flag)Image(painter = painter,contentDescription = """",colorFilter = ColorFilter.tint(ChatTheme.colors.primaryAccent),)Spacer(modifier = Modifier.height(4.dp))Text(text = stringResource(id = R.string.stream_ui_moderation_dialog_title),textAlign = TextAlign.Center,style = ChatTheme.typography.title3,color =ChatTheme.colors.textHighEmphasis)}" Moderated message dialog title composable. Shows an icon and a title. +"@Composableinternal fun DefaultModeratedMessageDialogDescription() {Spacer(modifier = Modifier.height(12.dp))Text(modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),text = stringResource(id = R.string.stream_ui_moderation_dialog_description),textAlign = TextAlign.Center,style = ChatTheme.typography.body,color = ChatTheme.colors.textLowEmphasis)]}" Moderated message dialog description composable. +"@Composable public fun ModeratedMessageDialogOptions(message: Message,options: List,modifier: Modifier = Modifier,onDismissRequest:() -> Unit = {},onDialogOptionInteraction: (message: Message, option: ModeratedMessageOption) -> Unit = { _, _ -> },itemContent:@Composable(ModeratedMessageOption)-> Unit = { option ->DefaultModeratedMessageOptionItem(message, option, onDismissRequest, onDialogOptionInteraction)},) {LazyColumn(modifier = modifier){items(options) { option ->itemContent(option)}}}" Composable that represents the dialog options a user can select to act upon a moderated message. +"@Composableinternal fun DefaultModeratedMessageOptionItem(message: Message,option: ModeratedMessageOption,onDismissRequest: () -> Unit,onDialogOptionInteraction: (message: Message, option: ModeratedMessageOption) -> Unit,) {ModeratedMessageOptionItem(option = option,modifier = Modifier.fillMaxWidth().height(50.dp).clickable(interactionSource = remember { MutableInteractionSource() },indication = rememberRipple()) {onDialogOptionInteraction(message, option)onDismissRequest()})}" Represents the default moderated message options item. By default shows only text of the action a user can perform. +"@Composable public fun ModeratedMessageOptionItem( option: ModeratedMessageOption, modifier: Modifier = Modifier, ) { Divider(color = ChatTheme.colors.borders) Box( modifier = modifier, contentAlignment = Alignment.Center ) { Text( text = stringResource(id = option.text), style = ChatTheme.typography.body, color = ChatTheme.colors.primaryAccent ) } }" Composable that represents a single option inside the [ModeratedMessageDialog].By default shows only text of the action a user can perform. +"@ExperimentalFoundationApi @Composable public fun ExtendedReactionsOptions( ownReactions: List, onReactionOptionSelected: (ReactionOptionItemState) -> Unit, modifier: Modifier = Modifier, cells: GridCells = GridCells.Fixed(DefaultNumberOfColumns), reactionTypes: Map = ChatTheme.reactionIconFactory.createReactionIcons(), itemContent: @Composable LazyGridScope.(ReactionOptionItemState) -> Unit = { option -> DefaultExtendedReactionsItemContent( option = option, onReactionOptionSelected = onReactionOptionSelected ) }, ) { val options = reactionTypes.entries.map { (type, reactionIcon) - val isSelected = ownReactions.any { ownReaction -> ownReaction.type == type } ReactionOptionItemState( painter = reactionIcon.getPainter(isSelected), type = type ) } LazyVerticalGrid(modifier = modifier, columns = cells) { items(options) { item -> key(item.type) { this@LazyVerticalGrid.itemContent(item) } } } }" Displays all available reactions a user can set on a message. +"@Composable internal fun DefaultExtendedReactionsItemContent( option: ReactionOptionItemState, onReactionOptionSelected: (ReactionOptionItemState) -> Unit, ) { ReactionOptionItem( modifier = Modifier .padding(vertical = 8.dp) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = rememberRipple(bounded = false), onClick = { onReactionOptionSelected(option) } ), option = option) }" The default item content inside [ExtendedReactionsOptions]. Shows an individual reaction. +"@ExperimentalFoundationApi @Preview(showBackground = true, name = ""ExtendedReactionOptions Preview"")@Composable internal fun ExtendedReactionOptionsPreview() { ChatTheme {ExtendedReactionsOptions(ownReactions = listOf(),onReactionOptionSelected = {})}}" Preview for [ExtendedReactionsOptions] with no reaction selected. +"@ExperimentalFoundationApi @Preview(showBackground = true, name = ""ExtendedReactionOptions Preview (With Own Reaction)"") @Composable internal fun ExtendedReactionOptionsWithOwnReactionPreview() {ChatTheme {ExtendedReactionsOptions(ownReactions = listOf(Reaction(messageId = ""messageId"",type = ""haha""),onReactionOptionSelected = {})}}" Preview for [ExtendedReactionsOptions] with a selected reaction. +"@Composable public fun ReactionOptionItem( option: ReactionOptionItemState, modifier: Modifier = Modifier, ) { Image( modifier = modifier, painter = option.painter, contentDescription = option.type, ) }" Individual reaction item. +"@Preview(showBackground = true, name = ""ReactionOptionItem Preview (Not Selected)"") @Composableprivate fun ReactionOptionItemNotSelectedPreview() {ChatTheme {(option = PreviewReactionOptionData.reactionOption1())}}" Preview of [ReactionOptionItem] in its non selected state. +"@Preview(showBackground = true, name = ""ReactionOptionItem Preview (Selected)"")@Composableprivate fun ReactionOptionItemSelectedPreview() {ChatTheme {ReactionOptionItem(option = PreviewReactionOptionData.reactionOption2())}}" Preview of [ReactionOptionItem] in its selected state. +"@Composablepublic fun ReactionOptions(ownReactions: List,onReactionOptionSelected: (ReactionOptionItemState) -> Unit,onShowMoreReactionsSelected: () -> Unit,modifier: Modifier = Modifier,numberOfReactionsShown: Int = DefaultNumberOfReactionsShown,horizontalArrangement: Arrangement.Horizontal =Arrangement.SpaceBetween,reactionTypes: Map = ChatTheme.reactionIconFactory.createReactionIcons(),@DrawableReshowMoreReactionsIcon: Int = R.drawable.stream_compose_ic_more, itemContent: @Composable RowScope.(ReactionOptionItemState) -> Unit = { option -> DefaultReactionOptionItem( option = option, onReactionOptionSelected = onReactionOptionSelected ) }, ) { val options = reactionTypes.entries.map { (type, reactionIcon) -> val isSelected = ownReactions.any { ownReaction -> ownReaction.type == type } val painter = reactionIcon.getPainter(isSelected) ReactionOptionItemState( painter = painter, type = type ) }Row( modifier = modifier, horizontalArrangement = horizontalArrangement ) { options.take(numberOfReactionsShown).forEach { option -> key(option.type) { itemContent(option) } } if(options.size > numberOfReactionsShown) { Icon( modifier = Modifier.clickable( interactionSource = remember { MutableInteractionSource() }, indication = rememberRipple(bounded = false), onClick = { onShowMoreReactionsSelected() } ), painter = painterResource(id = showMoreReactionsIcon), contentDescription = LocalContext.current.getString(R.string.stream_compose_show_more_reactions), tint = ChatTheme.colors.textLowEmphasis, ) } } }" Displays all available reactions. +"@Composable internal fun DefaultReactionOptionItem(option: ReactionOptionItemState,onReactionOptionSelected: (ReactionOptionItemState) -> Unit,){ReactionOptionItem(modifier = Modifier.size(24.dp).size(ChatTheme.dimens.reactionOptionItemIconSize).clickable(interactionSource = remember { MutableInteractionSource() },indication = rememberRipple(bounded = false),onClick = { onReactionOptionSelected(option) }),option = option)}" The default reaction option item. +"@Preview(showBackground = true, name = ""ReactionOptions Preview"") @Composable private fun ReactionOptionsPreview() { ChatTheme { val reactionType = ChatTheme.reactionIconFactory.createReactionIcons().keys.firstOrNull() if (reactionType != null) { ReactionOptions(ownReactions =listOf(Reaction(reactionType)),onReactionOptionSelected = {},onShowMoreReactionsSelected = {}}}" Preview of [ReactionOptions] with a single item selected. +"@OptIn(ExperimentalFoundationApi::class) @Composable public fun ReactionsPicker( message: Message, onMessageAction: (MessageAction) -> Unit, modifier: Modifier = Modifier, shape: Shape = ChatTheme.shapes.bottomSheet, overlayColor: Color = ChatTheme.colors.overlay, cells: GridCells = GridCells.Fixed(DefaultNumberOfReactions), onDismiss: () -> Unit = {}, reactionTypes: Map = ChatTheme.reactionIconFactory.createReactionIcons(), headerContent: @Composable ColumnScope.() -> Unit = {}, centerContent: @Composable ColumnScope.() -> Unit = { DefaultReactionsPickerCenterContent( message = message, onMessageAction = onMessageAction, cells = cells, reactionTypes = reactionTypes ) }, ) { SimpleMenu( modifier = modifier, shape = shape, overlayColor = overlayColor, headerContent = headerContent, centerContent = centerContent, onDismiss = onDismiss ) }" Displays all of the available reactions the user can set on a message. +"@OptIn(ExperimentalFoundationApi::class) @Composable internal fun DefaultReactionsPickerCenterContent( message: Message, onMessageAction: (MessageAction) -> Unit, cells: GridCells = GridCells.Fixed(DefaultNumberOfReactions), reactionTypes: Map = ChatTheme.reactionIconFactory.createReactionIcons(),{ ExtendedReactionsOptions(modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 12.dp, bottom = 12.dp),reactionTypes = reactionTypes,ownReactions = message.ownReactions,onReactionOptionSelected = { reactionOptionItemState ->onMessageAction(React(reaction = Reaction(messageId = message.id, reactionOptionItemState.type),message = message))},cells = cells)}" The Default center content for the [ReactionsPicker]. Shows all available reactions. +"@ExperimentalFoundationApi@Preview(showBackground = true, name = ""ReactionPicker Preview"")@Composableinternal fun ReactionPickerPreview() {ChatTheme {ReactionsPicker(message = PreviewMessageData.messageWithOwnReaction,onMessageAction = {})}}" Preview of [ReactionsPicker] with a reaction selected. +"@Composable public fun SelectedMessageMenu( message: Message, messageOptions: List,ownCapabilities: Set,onMessageAction: (MessageAction) -> Unit, onShowMoreReactionsSelected: () -> Unit, modifier: Modifier = Modifier, shape: Shape = ChatTheme.shapes.bottomSheet, overlayColor: Color = ChatTheme.colors.overlay, reactionTypes: Map = ChatTheme.reactionIconFactory.createReactionIcons(), @DrawableRes showMoreReactionsIcon: Int = R.drawable.stream_compose_ic_more, onDismiss: () -> Unit = {}, headerContent: @Composable ColumnScope.() -> Unit = { val canLeaveReaction = ownCapabilities.contains(ChannelCapabilities.SEND_REACTION) if (canLeaveReaction) { DefaultSelectedMessageReactionOptions( message = message, reactionTypes = reactionTypes, showMoreReactionsDrawableRes = showMoreReactionsIcon, onMessageAction = onMessageAction, showMoreReactionsIcon = onShowMoreReactionsSelected ) } }, centerContent: @Composable ColumnScope.() -> Unit = {DefaultSelectedMessageOptions( messageOptions =messageOptions,onMessageAction = onMessageAction ) }, ) { SimpleMenu( modifier = modifier, shape = shape, overlayColor = overlayColor, onDismiss = onDismiss, headerContent = headerContent, centerContent = centerContent ) }" Represents the options user can take after selecting a message. +"@Composable internal fun DefaultSelectedMessageOptions( messageOptions: List, onMessageAction: (MessageAction) -> Unit, ) { MessageOptions( options = messageOptions, onMessageOptionSelected = { onMessageAction(it.action) } ) }" Default selected message options. +"@Preview(showBackground = true, name = ""SelectedMessageMenu Preview"")@Composableprivate fun SelectedMessageMenuPreview() {ChatTheme {val messageOptionsStateList = defaultMessageOptionsState(selectedMessage = Message(),currentUser = User(),isInThread = false,ownCapabilities = ChannelCapabilities.toSet())SelectedMessageMenu(message = Message(),messageOptions = messageOptionsStateList,onMessageAction = {}, onShowMoreReactionsSelected = {},ownCapabilities = ChannelCapabilities.toSet())}}" Preview of [SelectedMessageMenu]. +"@Composable public fun SelectedReactionsMenu(message: Message,currentUser: User?,ownCapabilities: Set,onMessageAction: (MessageAction) -> Unit,onShowMoreReactionsSelected: () -> Unit,modifier: Modifier = Modifier,shape: Shape = ChatTheme.shapes.bottomSheet,overlayColor: Color = ChatTheme.colors.overlay,reactionTypes: Map = ChatTheme.reactionIconFactory.createReactionIcons(),@DrawableRes showMoreReactionsIcon: Int = R.drawable.stream_compose_ic_more,onDismiss: () -> Unit = {},headerContent: @Composable ColumnScope.() -> Unit = {val canLeaveReaction = ownCapabilities.contains(ChannelCapabilities.SEND_REACTION)if (canLeaveReaction) {DefaultSelectedReactionsHeaderContent(message = message,reactionTypes =reactionTypes,showMoreReactionsIcon = showMoreReactionsIcon,onMessageAction = onMessageAction,onShowMoreReactionsSelected =onShowMoreReactionsSelected)}},centerContent: @Composable ColumnScope.() -> Unit = {DefaultSelectedReactionsCenterContent(message = message,currentUser = currentUser)},) {SimpleMenu(modifier = modifier,shape = shape,overlayColor = overlayColor,onDismiss = onDismiss, headerContent = headerContent,centerContent = centerContent)}" Represents the list of user reactions. +"@Composableinternal fun DefaultSelectedReactionsHeaderContent(message: Message,reactionTypes: Map,@DrawableRes showMoreReactionsIcon: Int = R.drawable.stream_compose_ic_more,onMessageAction: (MessageAction) -> Unit,onShowMoreReactionsSelected: () -> Unit,) ReactionOptions(modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 8.dp, top = 20.dp),reactionTypes = reactionTypes,showMoreReactionsIcon = showMoreReactionsIcon,onReactionOptionSelected = {onMessageAction(React(reaction = Reaction(messageId = message.id, type = it.type),message = message) ])},onShowMoreReactionsSelected = onShowMoreReactionsSelected,ownReactions = message.ownReactions)}" Default header content for the selected reactions menu. +"@Composableinternal fun DefaultSelectedReactionsCenterContent(message: Message,currentUser: User?,) {UserReactions(modifier = Modifier.fillMaxWidth().heightIn(max = ChatTheme.dimens.userReactionsMaxHeight).padding(vertical = 16.dp),items = buildUserReactionItems(message = message,currentUser = currentUser))}" Default center content for the selected reactions menu. +"@Composableprivate fun buildUserReactionItems(message: Message,currentUser: User?,): List {val iconFactory = ChatTheme.reactionIconFactoryreturn message.latestReactions.filter { it.user != null && iconFactory.isReactionSupported(it.type) }.map {val user = requireNotNull(it.user) val type = it.typeval isMine = currentUser?.id == user.idval painter = iconFactory.createReactionIcon(type).getPainter(isMine)UserReactionItemState(user = user,painter = painter,type = type)}}" "Builds a list of user reactions, based on the current user and the selected message." +"@Preview@Composableprivate fun OneSelectedReactionMenuPreview() {ChatTheme {val message = Message(latestReactions = PreviewReactionData.oneReaction.toMutableList())SelectedReactionsMenu(message = message,currentUser = PreviewUserData.user1,onMessageAction = {} ,onShowMoreReactionsSelected = {},ownCapabilities = ChannelCapabilities.toSet())}}" Preview of the [SelectedReactionsMenu] component with 1 reaction. +"@Preview@Composableprivate fun ManySelectedReactionsMenuPreview() {ChatTheme {val message = Message(latestReactions = PreviewReactionData.manyReaction.toMutableList())SelectedReactionsMenu(message = message,currentUser = PreviewUserData.user1,onMessageAction = {}, onShowMoreReactionsSelected = {},ownCapabilities = ChannelCapabilities.toSet())}}" Preview of the [SelectedReactionsMenu] component with many reactions. +"@Composablepublic fun SuggestionList(modifier: Modifier = Modifier,shape: Shape = ChatTheme.shapes.suggestionList,contentPadding: PaddingValues = PaddingValues(vertical = ChatTheme.dimens.suggestionListPadding),headerContent: @Composable () -> Unit = {},centerContent: @Composable () -> Unit,) {Popup(popupPositionProvider = AboveAnchorPopupPositionProvider()) {Card(modifier = modifier,elevation = ChatTheme.dimens.suggestionListElevation,shape = shape,backgroundColor = ChatTheme.colors.barsBackground,) {Column(Modifier.padding(contentPadding)) {headerContent()centerContent()}}}}" Represents the suggestion list popup that allows user to auto complete the current input. +"@Composable public fun MentionSuggestionList(users: List,modifier: Modifier = Modifier,onMentionSelected: (User) -> Unit = {},itemContent: @Composable (User) > Unit = { user ->DefaultMentionSuggestionItem(user = user,onMentionSelected = onMentionSelected,)},) {SuggestionList(modifier = modifier.fillMaxWidth().heightIn(max = ChatTheme.dimens.suggestionListMaxHeight)) {LazyColumn(horizontalAlignment = Alignment.CenterHorizontally) {items(items = users,key = User::id) { user ->itemContent(user)}}}}" Represents the mention suggestion list popup. +"@Composable internal fun DefaultMentionSuggestionItem(user: User, onMentionSelected: (User) -> Unit,) { MentionSuggestionItem( user = user, onMentionSelected = onMentionSelected, ) }" The default mention suggestion item. +"@Composable public fun MentionSuggestionItem(user: User,onMentionSelected: (User) -> Unit,modifier: Modifier = Modifier,leadingContent: @Composable RowScope.(User) -> Unit = {DefaultMentionSuggestionItemLeadingContent(user = it)},centerContent: @Composable RowScope.(User) -> Unit = {DefaultMentionSuggestionItemCenterContent(user = it)},trailingContent: @Composable RowScope.(User) -> Unit = {DefaultMentionSuggestionItemTrailingContent()},) {Row(modifier = modifier.fillMaxWidth().wrapContentHeight().clickable(onClick = { onMentionSelected(user) },indication = rememberRipple(),interactionSource = remember { MutableInteractionSource() }).padding(vertical = ChatTheme.dimens.mentionSuggestionItemVerticalPadding,horizontal = ChatTheme.dimens.mentionSuggestionItemHorizontalPadding),verticalAlignment = Alignment.CenterVertically,) {leadingContent(user)centerContent(user)trailingContent(user)}}" Represents the mention suggestion item in the mention suggestion list popup. +"@Composable internal fun DefaultMentionSuggestionItemLeadingContent(user: User) { UserAvatar( modifier = Modifier .padding(end = 8.dp) .size(ChatTheme.dimens.mentionSuggestionItemAvatarSize), user = user, showOnlineIndicator = true, ) }" Represents the default content shown at the start of the mention list item. +"@Composable internal fun RowScope.DefaultMentionSuggestionItemCenterContent(user: User) {Column(modifier = Modifier.weight(1f).wrapContentHeight()) {Text(text = user.name,style = ChatTheme.typography.bodyBold,color = ChatTheme.colors.textHighEmphasis,maxLines = 1,overflow = TextOverflow.Ellipsis)Text(text = ""@${user.id}"",style = ChatTheme.typography.footnote,color = ChatTheme.colors.textLowEmphasis,maxLines = 1,overflow = TextOverflow.Ellipsis)}=}" "Represents the center portion of the mention item, that show the user name and the user ID." +"@Composableinternal fun DefaultMentionSuggestionItemTrailingContent() {Icon(modifier = Modifier.padding(start = 8.dp).size(24.dp),painter = painterResource(id = R.drawable.stream_compose_ic_mention),contentDescription = null,tint = ChatTheme.colors.primaryAccent)}" Represents the default content shown at the end of the mention list item. +"@Composable public fun CommandSuggestionItem( command: Command,modifier: Modifier = Modifier,onCommandSelected: (Command) -> Unit = {},leadingContent: @Composable RowScope.(Command) -> Unit = {DefaultCommandSuggestionItemLeadingContent()},centerContent: @Composable RowScope.(Command) -> Unit = {DefaultCommandSuggestionItemCenterContent(command = it)},) {Row(modifier = modifier.fillMaxWidth().wrapContentHeight().clickable(onClick = { onCommandSelected(command) },indication = rememberRipple(),interactionSource = remember { MutableInteractionSource() }).padding(vertical = ChatTheme.dimens.commandSuggestionItemVerticalPadding,horizontal = ChatTheme.dimens.commandSuggestionItemHorizontalPadding),verticalAlignment =Alignment.CenterVertically,) {leadingContent(command)centerContent(command)}}" Represents the command suggestion item in the command suggestion list popup. +"@Composableinternal fun DefaultCommandSuggestionItemLeadingContent() {Image(modifier = Modifier.padding(end = 8.dp).size(ChatTheme.dimens.commandSuggestionItemIconSize),painter = painterResource(id = R.drawable.stream_compose_ic_giphy),contentDescription = null)}" Represents the default content shown at the start of the command list item. +"@Composable internal fun RowScope.DefaultCommandSuggestionItemCenterContent(command: Command,modifier: Modifier = Modifier,) {val commandDescription = LocalContext.current.getString(R.string.stream_compose_message_composer_command_template,command.name,command.args)Row(modifier = modifier.weight(1f).wrapContentHeight(),verticalAlignment = Alignment.CenterVertically) {Text(text = command.name.replaceFirstChar(Char::uppercase),style = ChatTheme.typography.bodyBold,color = ChatTheme.colors.textHighEmphasis,maxLines = 1,overflow = TextOverflow.Ellipsis) Spacer(modifier = Modifier.width(8.dp))  Text(text = commandDescription, style = ChatTheme.typography.body,color = ChatTheme.colors.textLowEmphasis,maxLines = 1,overflow = TextOverflow.Ellipsis)}}" "Represents the center portion of the command item, that show the user name and the user ID." +"@Composable public fun CommandSuggestionList(commands: List,modifier: Modifier = Modifier,onCommandSelected: (Command) -> Unit = {},itemContent: @Composable (Command) -> Unit = { command -> DefaultCommandSuggestionItem( command = command, onCommandSelected = onCommandSelected, ) }, ) { SuggestionList( modifier = modifier.fillMaxWidth() .heightIn(max = ChatTheme.dimens.suggestionListMaxHeight) .padding(ChatTheme.dimens.suggestionListPadding), headerContent = {Row(modifier = Modifier.fillMaxWidth().height(40.dp),verticalAlignment = Alignment.CenterVertically) {Icon(modifier = Modifier.padding(horizontal = 8.dp).size(24.dp),painter = painterResource(id = R.drawable.stream_compose_ic_command),tint = ChatTheme.colors.primaryAccent,contentDescription = null)Text( text = stringResource(id = R.string.stream_compose_message_composer_instant_commands),style = ChatTheme.typography.body,maxLines = 1,color = ChatTheme.colors.textLowEmphasis)}}) {LazyColumn(horizontalAlignment = Alignment.CenterHorizontally) {items(items = commands,key = Command::name) { command -> itemContent(command)}}}}" Represents the command suggestion list popup. +"@Composable internal fun DefaultCommandSuggestionItem(command: Command,onCommandSelected: (Command) -> Unit,) {CommandSuggestionItem(command = command, onCommandSelected = onCommandSelected) }" The default command suggestion item. +"@Composable public fun UserReactionItem(item: UserReactionItemState,modifier: Modifier = Modifier,) {val (user, painter, type) = item Column(modifier = modifier,horizontalAlignment = Alignment.CenterHorizontally) {val isMine = user.id == ChatClient.instance().getCurrentUser()?.idval isStartAlignment = ChatTheme.messageOptionsUserReactionAlignment.isStartAlignment(isMine) val alignment = if (isStartAlignment) Alignment.BottomStart else Alignment.BottomEnd Box(modifier = Modifier.width(64.dp)) { UserAvatar(user = user,showOnlineIndicator = false,modifier = Modifier.size(ChatTheme.dimens.userReactionItemAvatarSize)) Image(modifier = Modifier.background(shape = RoundedCornerShape(16.dp), color = ChatTheme.colors.barsBackground).size(ChatTheme.dimens.userReactionItemIconSize).padding(4.dp).align(alignment),painter = painter,contentDescription = type,)} Spacer(modifier = Modifier.height(8.dp))Text(text = user.name,style = ChatTheme.typography.footnoteBold,maxLines = 1,overflow = TextOverflow.Ellipsis,color = ChatTheme.colors.textHighEmphasis,textAlign = TextAlign.Center,)}}" Represent a reaction item with the user who left it. +@Preview@Composablepublic fun CurrentUserReactionItemPreview() {ChatTheme {UserReactionItem(item = PreviewUserReactionData.user1Reaction())}} Preview of the [UserReactionItem] component with a reaction left by the current user. +@Preview@Composablepublic fun OtherUserReactionItemPreview() {ChatTheme {UserReactionItem(item = PreviewUserReactionData.user2Reaction()) } } Preview of the [UserReactionItem] component with a reaction left by another user. +"@OptIn(ExperimentalFoundationApi::class) @Composablepublic fun UserReactions( items: List,modifier: Modifier = Modifier,itemContent: @Composable (UserReactionItemState) -> Unit = {DefaultUserReactionItem(item = it)},) {val reactionCount = items.sizeval reactionCountText = LocalContext.current.resources.getQuantityString(R.plurals.stream_compose_message_reactions,reactionCount,reactionCount)Column(horizontalAlignment = Alignment.CenterHorizontally,modifier = modifier.background(ChatTheme.colors.barsBackground)) {Text(text = reactionCountText,style = ChatTheme.typography.title3Bold,maxLines = 1,overflow = TextOverflow.Ellipsis,color = ChatTheme.colors.textHighEmphasis) Spacer(modifier = Modifier.height(16.dp)) if (reactionCount > 0) {BoxWithConstraints(modifier = Modifier.fillMaxWidth(),contentAlignment = Alignment.Center) {val reactionItemWidth = ChatTheme.dimens.userReactionItemWidth val maxColumns = maxOf((maxWidth / reactionItemWidth).toInt(), 1)val columns = reactionCount.coerceAtMost(maxColumns) val reactionGridWidth = reactionItemWidth * columns LazyVerticalGrid(modifier = Modifier.width(reactionGridWidth).align(Alignment.Center),columns = GridCells.Fixed(columns)) {items(reactionCount) { index ->itemContent(items[index])}}}}}}" Represent a section with a list of reactions left for the message. +"@Composable internal fun DefaultUserReactionItem(item: UserReactionItemState) {UserReactionItem(item = item,modifier = Modifier,)}" Default user reactions item for the user reactions component. +@Preview @Composable private fun OneUserReactionPreview() {ChatTheme {UserReactions(items = PreviewUserReactionData.oneUserReaction())}} Preview of the [UserReactions] component with one user reaction. +@Preview@Composable private fun ManyUserReactionsPreview() {ChatTheme {UserReactions(items = PreviewUserReactionData.manyUserReactions())}} Preview of the [UserReactions] component with many user reactions. +"@OptIn(ExperimentalFoundationApi::class) @Composable public fun FileAttachmentContent( attachmentState: AttachmentState,modifier: Modifier = Modifier,) {val (message, onItemLongClick) = attachmentState val previewHandlers = ChatTheme.attachmentPreviewHandlers Column(modifier = modifier.combinedClickable( indication = null, interactionSource = remember { MutableInteractionSource() }, onClick = {}, onLongClick = { onItemLongClick(message) })) {for (attachment in message.attachments) {FileAttachmentItem(modifier = Modifier.padding(2.dp).fillMaxWidth().combinedClickable(indication = null,interactionSource = remember { MutableInteractionSource() },onClick = {previewHandlers.firstOrNull { it.canHandle(attachment) }.handleAttachmentPreview(attachment)},onLongClick = { onItemLongClick(message) },),attachment = attachment)}}}" Builds a file attachment message which shows a list of files. +"@Composable public fun FileAttachmentItem(attachment: Attachment,modifier: Modifier = Modifier,) { Surface(modifier = modifier,color = ChatTheme.colors.appBackground,shape = ChatTheme.shapes.attachment) {Row(Modifier.fillMaxWidth().height(50.dp).padding(vertical = 8.dp, horizontal = 8.dp),verticalAlignment = Alignment.CenterVertically) {FileAttachmentImage(attachment = attachment)FileAttachmentDescription(attachment = attachment)FileAttachmentDownloadIcon(attachment = attachment)}}}" Represents each file item in the list of file attachments. +"@Composable private fun FileAttachmentDescription(attachment: Attachment) {Column(modifier = Modifier.fillMaxWidth(0.85f).padding(start = 16.dp, end = 8.dp),horizontalAlignment = Alignment.Start,verticalArrangement = Arrangement.Center) {Text(text = attachment.title ?: attachment.name ?: """",style = ChatTheme.typography.bodyBold,maxLines = 1,overflow = TextOverflow.Ellipsis,color = ChatTheme.colors.textHighEmphasis)Text(text = MediaStringUtil.convertFileSizeByteCount(attachment.fileSize.toLong()),style = ChatTheme.typography.footnote,color = ChatTheme.colors.textLowEmphasis)}}" Displays information about the attachment such as the attachment title and its size in bytes. +"@Composable private fun RowScope.FileAttachmentDownloadIcon(attachment: Attachment) {val permissionHandlers = ChatTheme.permissionHandlerProvider Icon( modifier = Modifier.align(Alignment.Top).padding(end = 2.dp).clickable(interactionSource = remember { MutableInteractionSource() },indication = rememberRipple(bounded = false)) {permissionHandlers.first { it.canHandle(Manifest.permission.WRITE_EXTERNAL_STORAGE) }.apply {onHandleRequest(mapOf(PayloadAttachment to attachment))}},painter = painterResource(id = R.drawable.stream_compose_ic_file_download),contentDescription = stringResource(id = R.string.stream_compose_download),tint = ChatTheme.colors.textHighEmphasis)}" Downloads the given attachment when clicked. +"@Composable public fun FileAttachmentImage(attachment: Attachment) {val isImage = attachment.type == ""image""val painter = if (isImage) {val dataToLoad = attachment.imageUrl ?: attachment.upload rememberStreamImagePainter(dataToLoad)} else {painterResource(id = MimeTypeIconProvider.getIconRes(attachment.mimeType))} val shape = if (isImage) ChatTheme.shapes.imageThumbnail else nullval imageModifier = Modifier.size(height = 40.dp, width = 35.dp).let { baseModifier -> if (shape != null) baseModifier.clip(shape) else baseModifier } Image(modifier = imageModifier, painter = painter, contentDescription = null, contentScale = if (isImage) ContentScale.Crop else ContentScale.Fit) }" Represents the image that's shown in file attachments. This can be either an image/icon that represents the file type or a thumbnail in case the file type is an image. +"@Suppress(""FunctionName"") public fun FileAttachmentFactory(): AttachmentFactory = AttachmentFactory( canHandle = { attachments ->attachments.any { it.isFile() } }, previewContent = @Composable { modifier, attachments, onAttachmentRemoved -> FileAttachmentPreviewContent(modifier = modifier, attachments = attachments, onAttachmentRemoved = onAttachmentRemoved)},content = @Composable { modifier, state ->FileAttachmentContent(modifier = modifier.wrapContentHeight().width(ChatTheme.dimens.attachmentsContentFileWidth),attachmentState = state)},)" An [AttachmentFactory] that validates attachments as files and uses [FileAttachmentContent] to build the UI for the message. +"@Suppress(""FunctionName"") public fun GiphyAttachmentFactory(giphyInfoType: GiphyInfoType = GiphyInfoType.FIXED_HEIGHT_DOWNSAMPLED,giphySizingMode: GiphySizingMode = GiphySizingMode.ADAPTIVE,contentScale: ContentScale = ContentScale.Crop,): AttachmentFactory =AttachmentFactory(canHandle = { attachments -> attachments.any { it.type == ModelType.attach_giphy } },content = @Composable { modifier, state ->GiphyAttachmentContent(modifier = modifier.wrapContentSize(),attachmentState = state,giphyInfoType = giphyInfoType,giphySizingMode = giphySizingMode,contentScale = contentScale,)},)" "An [AttachmentFactory] that validates and shows Giphy attachments using [GiphyAttachmentContent]. Has no ""preview content"", given that this attachment only exists after being sent." +"@Suppress(""FunctionName"") public fun ImageAttachmentFactory(): AttachmentFactory = AttachmentFactory( canHandle = { attachments -> attachments.all { it.isMedia() } }, previewContent = { modifier, attachments, onAttachmentRemoved -> ImageAttachmentPreviewContent(modifier = modifier,attachments = attachments, onAttachmentRemoved = onAttachmentRemoved )},content = @Composable { modifier, state ->ImageAttachmentContent(modifier = modifier.width(ChatTheme.dimens.attachmentsContentImageWidth).wrapContentHeight().heightIn(max = ChatTheme.dimens.attachmentsContentImageMaxHeight),attachmentState = state)},)" An [AttachmentFactory] that validates attachments as images and uses [ImageAttachmentContent] to build the UI for the message. +"@Suppress(""FunctionName"") public fun LinkAttachmentFactory(linkDescriptionMaxLines: Int, ): AttachmentFactory = AttachmentFactory(canHandle = { links -> links.any { it.hasLink() && it.type != ModelType.attach_giphy } }, content = @Composable { modifier, state -> LinkAttachmentContent( modifier = modifier.width(ChatTheme.dimens.attachmentsContentLinkWidth).wrapContentHeight(),attachmentState = state,linkDescriptionMaxLines = linkDescriptionMaxLines)},)" "An [AttachmentFactory] that validates attachments as images and uses [LinkAttachmentContent] to build the UI for the message. Has no ""preview content"", given that this attachment only exists after being sent." +"@Suppress(""FunctionName"") public fun QuotedAttachmentFactory(): AttachmentFactory = AttachmentFactory(canHandle = {if (it.isEmpty()) return@AttachmentFactory false val attachment = it.first() attachment.isFile() || attachment.isMedia() || attachment.hasLink() },content = @Composable { modifier, attachmentState ->val attachment = attachmentState.message.attachments.first() val isFile = attachment.isFile() val isImage = attachment.isMedia() val isLink = attachment.hasLink() when { isImage || isLink -> ImageAttachmentQuotedContent(modifier = modifier, attachment = attachment) isFile -> FileAttachmentQuotedContent(modifier = modifier, attachment = attachment)}})" An [AttachmentFactory] that validates attachments as files and uses [ImageAttachmentQuotedContent] in case the attachment is a media attachment or [FileAttachmentQuotedContent] in case the attachment is a file to build the UI for the quoted message. +"@Suppress(""FunctionName"") public fun UploadAttachmentFactory(): AttachmentFactory = AttachmentFactory( canHandle = { attachments -> attachments.any {it.isUploading() } }, content = @Composable { modifier, state ->FileUploadContent(modifier = modifier.wrapContentHeight().width(ChatTheme.dimens.attachmentsContentFileUploadWidth),attachmentState = state)},)" "An [AttachmentFactory] that validates and shows uploading attachments using [FileUploadContent]. Has no ""preview content"", given that this attachment only exists after being sent." +"public open class AttachmentFactory constructor( public val canHandle: (attachments: List) -> Boolean, public val previewContent: ( @Composable (modifier: Modifier,attachments: List,onAttachmentRemoved: (Attachment) -> Unit,) -> Unit)? = null,public val content: @Composable (modifier: Modifier,attachmentState: AttachmentState,) -> Unit,public val textFormatter: (attachments: Attachment) -> String = Attachment::previewText,)" Holds the information required to build an attachment message. +"public fun defaultFactories( linkDescriptionMaxLines: Int = DEFAULT_LINK_DESCRIPTION_MAX_LINES,giphyInfoType: GiphyInfoType = GiphyInfoType.ORIGINAL,giphySizingMode: GiphySizingMode = GiphySizingMode.ADAPTIVE,contentScale: ContentScale = ContentScale.Crop,):List = listOf(UploadAttachmentFactory(),LinkAttachmentFactory(linkDescriptionMaxLines),GiphyAttachmentFactory(giphyInfoType = giphyInfoType,giphySizingMode = giphySizingMode,contentScale = contentScale,),ImageAttachmentFactory(),FileAttachmentFactory(),)" "Default attachment factories we provide, which can transform image, file and link attachments." +public fun defaultQuotedFactories(): List = listOf(QuotedAttachmentFactory())} "Default quoted attachment factories we provide, which can transform image, file and link attachments." +"@Composable public fun ChannelList(modifier: Modifier = Modifier,contentPadding: PaddingValues = PaddingValues(),viewModel: ChannelListViewModel = viewModel(factory =ChannelViewModelFactory(ChatClient.instance(),QuerySortByField.descByName(""last_updated""),filters = null)),lazyListState: LazyListState = rememberLazyListState(),onLastItemReached: () -> Unit = { viewModel.loadMore() },onChannelClick: (Channel) -> Unit = {},onChannelLongClick: (Channel) -> Unit = { viewModel.selectChannel(it) },loadingContent: @Composable () -> Unit = { LoadingIndicator(modifier) },emptyContent: @Composable () -> Unit = {DefaultChannelListEmptyContent(modifier) },emptySearchContent: @Composable (String) -> Unit = { searchQuery ->DefaultChannelSearchEmptyContent(searchQuery = searchQuery,modifier = modifier)},helperContent: @Composable BoxScope.() -> Unit = {},loadingMoreContent: @Composable () -> Unit = { DefaultChannelsLoadingMoreIndicator() },itemContent: @Composable (ChannelItemState) -> Unit = { channelItem ->val user by viewModel.user.collectAsState()DefaultChannelItem(channelItem = channelItem,currentUser = user,onChannelClick = onChannelClick,onChannelLongClick =onChannelLongClick)},divider: @Composable () -> Unit = { DefaultChannelItemDivider() },) {val user by viewModel.user.collectAsState()ChannelList(modifier = modifier,contentPadding = contentPadding,channelsState = viewModel.channelsState,currentUser = user,lazyListState = lazyListState,onLastItemReached =onLastItemReached,onChannelClick = onChannelClick,onChannelLongClick = onChannelLongClick,loadingContent = loadingContent,emptyContent = emptyContent,emptySearchContent = emptySearchContent,helperContent = helperContent,loadingMoreContent = loadingMoreContent,itemContent = itemContent,divider = divider)}" "Default ChannelList component, that relies on the [ChannelListViewModel] to load the data and show it on the UI." +"@Composable public fun ChannelList( channelsState: ChannelsState,currentUser: User?,modifier: Modifier = Modifier,contentPadding: PaddingValues = PaddingValues(0.dp),lazyListState: LazyListState = rememberLazyListState(),onLastItemReached: () -> Unit = {},onChannelClick: (Channel) -> Unit = {},onChannelLongClick: (Channel) -> Unit = {},loadingContent: @Composable () -> Unit = { DefaultChannelListLoadingIndicator(modifier) },emptyContent: @Composable () -> Unit = { DefaultChannelListEmptyContent(modifier) },emptySearchContent: @Composable (String) -> Unit = { searchQuery ->DefaultChannelSearchEmptyContent(searchQuery = searchQuery,modifier = modifier)},helperContent: @Composable BoxScope.() -> Unit = {},loadingMoreContent: @Composable () -> Unit = {DefaultChannelsLoadingMoreIndicator() },itemContent: @Composable (ChannelItemState) -> Unit = { channelItem ->DefaultChannelItem(channelItem = channelItem,currentUser = currentUser,onChannelClick = onChannelClick,onChannelLongClick = onChannelLongClick)},divider: @Composable () -> Unit = { DefaultChannelItemDivider() },) {val (isLoading, _, _, channels, searchQuery) = channelsState when {isLoading -> loadingContent() !isLoading && channels.isNotEmpty() -> Channels( modifier = modifier, contentPadding = contentPadding, channelsState = channelsState, lazyListState = lazyListState, onLastItemReached = onLastItemReached, helperContent = helperContent, loadingMoreContent = loadingMoreContent, itemContent = itemContent, divider = divider searchQuery.isNotEmpty() -> emptySearchContent(searchQuery) else -> emptyContent()} }" "Root Channel list component, that represents different UI, based on the current channel state.This is decoupled from ViewModels, so the user can provide manual and custom data handling,as well as define a completely custom UI component for the channel item.If there is no state, no query active or the data is being loaded, we show the [LoadingIndicator].If there are no results or we're offline, usually due to an error in the API or network, we show an [EmptyContent]. If there is data available and it is not empty, we show [Channels]." +"@Composable internal fun DefaultChannelItem( channelItem: ChannelItemState, currentUser: User?, onChannelClick: (Channel) -> Unit, onChannelLongClick: (Channel) -> Unit, ) {ChannelItem(channelItem = channelItem,currentUser = currentUser,onChannelClick = onChannelClick,onChannelLongClick = onChannelLongClick)}" The default channel item. +@Composable internal fun DefaultChannelListLoadingIndicator(modifier: Modifier) {LoadingIndicator(modifier)} Default loading indicator. +"@Composable internal fun DefaultChannelListEmptyContent(modifier: Modifier = Modifier) {EmptyContent(modifier = modifier,painter = painterResource(id = R.drawable.stream_compose_empty_channels),text = stringResource(R.string.stream_compose_channel_list_empty_channels),)}" The default empty placeholder for the case when there are no channels available to the user. +"@Composable internal fun DefaultChannelSearchEmptyContent(searchQuery: String,modifier: Modifier = Modifier,) {EmptyContent(modifier = modifier,painter = painterResource(id = R.drawable.stream_compose_empty_search_results),text = stringResource(R.string.stream_compose_channel_list_empty_search_results, searchQuery),)}" The default empty placeholder for the case when channel search returns no results. +@Composable public fun DefaultChannelItemDivider() { Spacer(modifier = Modifier.fillMaxWidth().height(0.5.dp).background(color = ChatTheme.colors.borders))} Represents the default item divider in channel items. +"@Preview(showBackground = true, name = ""ChannelList Preview (Content state)"")@Composableprivate fun ChannelListForContentStatePreview() {ChannelListPreview(ChannelsState(isLoading = false,channelItems = listOf(ChannelItemState(channel = PreviewChannelData.channelWithImage),ChannelItemState(channel = PreviewChannelData.channelWithMessages),ChannelItemState(channel =PreviewChannelData.channelWithFewMembers),ChannelItemState(channel = PreviewChannelData.channelWithManyMembers),ChannelItemState(channel = PreviewChannelData.channelWithOnlineUser))))}" Preview of [ChannelItem] for a list of channels. Should show a list of channels. +"@Preview(showBackground = true, name = ""ChannelList Preview (Empty state)"")@Composableprivate fun ChannelListForEmptyStatePreview() {ChannelListPreview(ChannelsState(isLoading = false,channelItems = emptyList()))}" Preview of [ChannelItem] for an empty state.Should show an empty placeholder. +"@Preview(showBackground = true, name = ""ChannelList Preview (Loading state)"")@Composable private fun ChannelListForLoadingStatePreview() {ChannelListPreview(ChannelsState(isLoading = true))}" Preview of [ChannelItem] for a loading state. Should show a progress indicator. +"@Composable private fun ChannelListPreview(channelsState: ChannelsState) {ChatTheme {ChannelList(modifier = Modifier.fillMaxSize(),channelsState = channelsState, currentUser = PreviewUserData.user1,)}}" Shows [ChannelList] preview for the provided parameters. +"@Composable public fun Channels( channelsState: ChannelsState, lazyListState: LazyListState, onLastItemReached: () -> Unit, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues(), helperContent: @Composable BoxScope.() -> Unit = {}, loadingMoreContent: @Composable () -> Unit = { DefaultChannelsLoadingMoreIndicator() }, itemContent: @Composable (ChannelItemState) -> Unit, divider: @Composable () -> Unit, ) { val (_, isLoadingMore, endOfChannels, channelItems) = channelsState Box(modifier = modifier) { LazyColumn( modifier = Modifier.fillMaxSize(), state = lazyListState, horizontalAlignment = Alignment.CenterHorizontally, contentPadding = contentPadding ) { item { DummyFirstChannelItem() }  items( items = channelItems, key = { it.channel.cid }) { item ->itemContent(item)divider()}if (isLoadingMore) {item {loadingMoreContent()}}} if (!endOfChannels && channelItems.isNotEmpty()) {LoadMoreHandler(lazyListState) {onLastItemReached() }}helperContent()}}" "Builds a list of [ChannelItem] elements, based on [channelsState] and action handlers that it receives." +@Composable internal fun DefaultChannelsLoadingMoreIndicator() {LoadingFooter(modifier = Modifier.fillMaxWidth())} The default loading more indicator. +@Composable private fun DummyFirstChannelItem() {Box(modifier = Modifier.height(1.dp).fillMaxWidth())} "Represents an almost invisible dummy item to be added to the top of the list.If the list is scrolled to the top and a channel new item is added or moved to the position above, then the list will automatically autoscroll to it." +"@OptIn(ExperimentalFoundationApi::class)@Composablepublic fun ChannelItem(channelItem: ChannelItemState,currentUser: User?,onChannelClick: (Channel) -> Unit,onChannelLongClick: (Channel) -> Unit,modifier: Modifier = Modifier,leadingContent: @Composable RowScope.(ChannelItemState) -> Unit = {DefaultChannelItemLeadingContent(channelItem = it,currentUser = currentUser)},centerContent: @Composable RowScope.(ChannelItemState) -> Unit = { DefaultChannelItemCenterContent(channel = it.channel,isMuted = it.isMuted,currentUser = currentUser)},trailingContent: @Composable RowScope.(ChannelItemState) -> Unit = {DefaultChannelItemTrailingContent(channel = it.channel,currentUser = currentUser,)},) {val channel = channelItem.channelval description = stringResource(id = R.string.stream_compose_cd_channel_item)Column(modifier = modifier.fillMaxWidth().wrapContentHeight().semantics { contentDescription = description}.combinedClickable(onClick = { onChannelClick(channel) },onLongClick = { onChannelLongClick(channel) },indication = rememberRipple(),interactionSource = remember { MutableInteractionSource() }),) {Row(modifier = Modifier.fillMaxWidth(),verticalAlignment = Alignment.CenterVertically,) {leadingContent(channelItem)centerContent(channelItem)trailingContent(channelItem)}}}" "The basic channel item, that shows the channel in a list and exposes single and long click actions." +"@Composable internal fun DefaultChannelItemLeadingContent(channelItem: ChannelItemState,currentUser: User?,) {ChannelAvatar(modifier = Modifier.padding(start = ChatTheme.dimens.channelItemHorizontalPadding,end = 4.dp,top = ChatTheme.dimens.channelItemVerticalPadding,bottom = ChatTheme.dimens.channelItemVerticalPadding).size(ChatTheme.dimens.channelAvatarSize),channel = channelItem.channel,currentUser = currentUser)}" "Represents the default leading content of [ChannelItem], that shows the channel avatar." +"@Composableinternal fun RowScope.DefaultChannelItemCenterContent(channel: Channel,isMuted: Boolean,currentUser: User?,) {Column(modifier = Modifier.padding(start = 4.dp, end = 4.dp).weight(1f).wrapContentHeight(),verticalArrangement = Arrangement.Center) {val channelName: (@Composable (modifier: Modifier) -> Unit) = @Composable {Text(modifier = it,text = ChatTheme.channelNameFormatter.formatChannelName(channel, currentUser),style = ChatTheme.typography.bodyBold,fontSize = 16.sp,maxLines = 1,overflow = TextOverflow.Ellipsis,color = ChatTheme.colors.textHighEmphasis,)}if (isMuted) {Row(verticalAlignment = Alignment.CenterVertically) {channelName(Modifier.weight(weight = 1f, fill = false))Icon(modifier = Modifier.padding(start = 8.dp).size(16.dp), painter = painterResource(id = R.drawable.stream_compose_ic_muted),contentDescription = null,tint = ChatTheme.colors.textLowEmphasis,)}} else {channelName(Modifier)} val lastMessageText = channel.getLastMessage(currentUser)?.let { lastMessage -> ChatTheme.messagePreviewFormatter.formatMessagePreview(lastMessage, currentUser)} ?: AnnotatedString("""")if (lastMessageText.isNotEmpty()) {Text(text = lastMessageText,maxLines = 1,overflow = TextOverflow.Ellipsis,style = ChatTheme.typography.body,color = ChatTheme.colors.textLowEmphasis,)}}}" "Represents the center portion of [ChannelItem], that shows the channel display name and the last message text preview." +"@Composable internal fun RowScope.DefaultChannelItemTrailingContent(channel: Channel,currentUser: User?,) {val lastMessage = channel.getLastMessage(currentUser) if (lastMessage != null) {Column(modifier = Modifier.padding(start = 4.dp,end = ChatTheme.dimens.channelItemHorizontalPadding,top = ChatTheme.dimens.channelItemVerticalPadding,bottom = ChatTheme.dimens.channelItemVerticalPadding).wrapContentHeight().align(Alignment.Bottom),horizontalAlignment = Alignment.End) {val unreadCount = channel.unreadCountif (unreadCount != null && unreadCount > 0) {UnreadCountIndicator(modifier = Modifier.padding(bottom = 4.dp),unreadCount = unreadCount)}val isLastMessageFromCurrentUser = lastMessage.user.id == currentUser?.id Row(verticalAlignment = Alignment.CenterVertically) {if (isLastMessageFromCurrentUser) {MessageReadStatusIcon(channel = channel,message = lastMessage,currentUser = currentUser,modifier = Modifier.padding(end = 8.dp).size(16.dp))} Timestamp(date = channel.lastUpdated)}}}}" "Represents the default trailing content for the channel item. By default it shows the the information about the last message for the channel item, such as its read state,timestamp and how many unread messages the user has." +"@Preview(showBackground = true, name = ""ChannelItem Preview (Channel with unread)"") @Composableprivate fun ChannelItemForChannelWithUnreadMessagesPreview() {ChannelItemPreview(channel = PreviewChannelData.channelWithMessages,currentUser = PreviewUserData.user1)}" "Preview of the [ChannelItem] component for a channel with unread messages. Should show unread count badge, delivery indicator and timestamp." +"@Preview(showBackground = true, name = ""ChannelItem Preview (Muted channel)"") @Composableprivate fun ChannelItemForMutedChannelPreview() {ChannelItemPreview(channel = PreviewChannelData.channelWithMessages,currentUser = PreviewUserData.user1,isMuted = true)}" Preview of [ChannelItem] for a muted channel. Should show a muted icon next to the channel name. +"@Preview(showBackground = true, name = ""ChannelItem Preview (Without messages)"") @Composableprivate fun ChannelItemForChannelWithoutMessagesPreview() { ChannelItemPreview(channel = PreviewChannelData.channelWithImage, isMuted = false,currentUser = PreviewUserData.user1)}" Preview of [ChannelItem] for a channel without messages. Should show only channel name that is centered vertically. +"@Composable private fun ChannelItemPreview(channel: Channel,isMuted: Boolean = false,currentUser: User? = null,) {ChatTheme {ChannelItem(channelItem = ChannelItemState(channel = channel,isMuted = isMuted),currentUser = currentUser,onChannelClick = {},onChannelLongClick = {})}}" Shows [ChannelItem] preview for the provided parameters. +"@Composable public fun SelectedChannelMenu(selectedChannel: Channel,isMuted: Boolean,currentUser: User?,onChannelOptionClick: (ChannelAction) -> Unit, onDismiss: () -> Unit,modifier: Modifier = Modifier,shape: Shape = ChatTheme.shapes.bottomSheet,overlayColor: Color = ChatTheme.colors.overlay,headerContent: @Composable ColumnScope.() -> Unit = { DefaultSelectedChannelMenuHeaderContent( selectedChannel = selectedChannel,currentUser = currentUser)}, centerContent: @Composable ColumnScope.() -> Unit = {DefaultSelectedChannelMenuCenterContent(selectedChannel = selectedChannel,isMuted = isMuted,onChannelOptionClick = onChannelOptionClick,ownCapabilities = selectedChannel.ownCapabilities)},) {SimpleMenu(modifier = modifier, shape = shape,overlayColor = overlayColor,onDismiss = onDismiss,headerContent = headerContent,centerContent = centerContent)}" "Shows special UI when an item is selected. It also prepares the available options for the channel, based on if we're an admin or not." +"@Composable internal fun DefaultSelectedChannelMenuHeaderContent(selectedChannel: Channel,currentUser: User?,) {val channelMembers = selectedChannel.membersval membersToDisplay = if (selectedChannel.isOneToOne(currentUser)) {channelMembers.filter { it.user.id != currentUser?.id }} else {channelMembers } Text(modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, top = 16.dp),textAlign = TextAlign.Center,text = ChatTheme.channelNameFormatter.formatChannelName(selectedChannel, currentUser),style = ChatTheme.typography.title3Bold,color = ChatTheme.colors.textHighEmphasis,maxLines = 1,overflow = TextOverflow.Ellipsis)Text(modifier = Modifier.fillMaxWidth(),textAlign = TextAlign.Center,text = selectedChannel.getMembersStatusText(LocalContext.current, currentUser),style = ChatTheme.typography.footnoteBold,color = ChatTheme.colors.textLowEmphasis,) ChannelMembers(membersToDisplay) }" Represents the default content shown at the top of [SelectedChannelMenu] dialog. +"@Composable internal fun DefaultSelectedChannelMenuCenterContent(selectedChannel: Channel,isMuted: Boolean,onChannelOptionClick: (ChannelAction) -> Unit,ownCapabilities: Set,) {val channelOptions = buildDefaultChannelOptionsState(selectedChannel = selectedChannel,isMuted = isMuted,ownCapabilities = ownCapabilities)ChannelOptions(channelOptions, onChannelOptionClick)}" Represents the default content shown at the center of [SelectedChannelMenu] dialog. +"@Preview(showBackground = true, name = ""SelectedChannelMenu Preview (Centered dialog)"") @Composableprivate fun SelectedChannelMenuCenteredDialogPreview() {ChatTheme {Box(modifier = Modifier.fillMaxSize()) {SelectedChannelMenu(modifier = Modifier.padding(16.dp).fillMaxWidth().wrapContentHeight().align(Alignment.Center),shape = RoundedCornerShape(16.dp),selectedChannel =PreviewChannelData.channelWithManyMembers,isMuted = false,currentUser = PreviewUserData.user1,onChannelOptionClick = {},onDismiss = {})}}}" Preview of [SelectedChannelMenu] styled as a centered modal dialog. Should show a centered dialog with channel members and channel options. +"@Preview(showBackground = true, name = ""SelectedChannelMenu Preview (Bottom sheet dialog)"") @Composableprivate fun SelectedChannelMenuBottomSheetDialogPreview() { ChatTheme {Box(modifier = Modifier.fillMaxSize()) {SelectedChannelMenu(modifier = Modifier.fillMaxWidth().wrapContentHeight().align(Alignment.BottomCenter),shape = ChatTheme.shapes.bottomSheet,selectedChannel = PreviewChannelData.channelWithManyMembers,isMuted = false,currentUser = PreviewUserData.user1,onChannelOptionClick = {},onDismiss = {})}}}" Preview of [SelectedChannelMenu] styled as a bottom sheet dialog. Should show a bottom sheet dialog with channel members and channel options. +"@Composable public fun ChannelListHeader(modifier: Modifier = Modifier,title: String = """",currentUser: User? = null,connectionState: ConnectionState ConnectionState.CONNECTED,color: Color = ChatTheme.colors.barsBackground,shape: Shape = ChatTheme.shapes.header,elevation: Dp ChatTheme.dimens.headerElevation,onAvatarClick: (User?) -> Unit = {},onHeaderActionClick: () -> Unit = {},leadingContent: @Composable RowScope.() -> Unit = { DefaultChannelHeaderLeadingContent(currentUser = currentUser,onAvatarClick = onAvatarClick)},centerContent: @Composable RowScope.() -> Unit = { DefaultChannelListHeaderCenterContent( connectionState = connectionState,title = title)},trailingContent: @Composable RowScope.() -> Unit = {DefaultChannelListHeaderTrailingContent(onHeaderActionClick = onHeaderActionClick)},) {Surface(modifier = modifier.fillMaxWidth(),elevation = elevation,color = color,shape = shape) {Row(Modifier.fillMaxWidth().padding(8.dp),verticalAlignment = Alignment.CenterVertically,) {leadingContent()centerContent()trailingContent()}}}" "A clean, decoupled UI element that doesn't rely on ViewModels or our custom architecture setup. This allows the user to fully govern how the [ChannelListHeader] behaves, by passing in all the data that's required to display it and drive its actions." +"@Composable internal fun DefaultChannelHeaderLeadingContent(currentUser: User?,onAvatarClick: (User?) -> Unit,) {val size = Modifier.size(40.dp)if (currentUser != null) { UserAvatar(modifier = size,user = currentUser,contentDescription = currentUser.name,showOnlineIndicator = false,onClick = { onAvatarClick(currentUser) })} else {Spacer(modifier = size)}}" "Represents the default leading content for the [ChannelListHeader], which is a [UserAvatar]. We show the avatar if the user is available, otherwise we add a spacer to make sure the alignment is correct." +"@Composable internal fun RowScope.DefaultChannelListHeaderCenterContent( connectionState: ConnectionState, title: String,) {when (connectionState) {ConnectionState.CONNECTED -> {Text(modifier = Modifier.weight(1f).wrapContentWidth().padding(horizontal = 16.dp),text = title,style = ChatTheme.typography.title3Bold,maxLines = 1,color = ChatTheme.colors.textHighEmphasis)}ConnectionState.CONNECTING -> NetworkLoadingIndicator(modifier = Modifier.weight(1f))ConnectionState.OFFLINE -> {Text(modifier = Modifier.weight(1f).wrapContentWidth().padding(horizontal = 16.dp),text = stringResource(R.string.stream_compose_disconnected),style = ChatTheme.typography.title3Bold,maxLines = 1,color = ChatTheme.colors.textHighEmphasis)}}}" "Represents the channel header's center slot. It either shows a [Text] if [connectionState] is [ConnectionState.CONNECTED], or a [NetworkLoadingIndicator] if there is no connections." +"@OptIn(ExperimentalMaterialApi::class) @Composableinternal fun DefaultChannelListHeaderTrailingContent(onHeaderActionClick: () -> Unit,) {Surface(modifier =Modifier.size(40.dp), onClick = onHeaderActionClick,interactionSource = remember { MutableInteractionSource() },color = ChatTheme.colors.primaryAccent,shape = ChatTheme.shapes.avatar,elevation = 4.dp) {Icon(modifier = Modifier.wrapContentSize(),painter = painterResource(id = R.drawable.stream_compose_ic_new_chat),contentDescription = stringResource(id = R.string.stream_compose_channel_list_header_new_chat),tint = Color.White,)}}" "Represents the default trailing content for the [ChannelListHeader], which is an action icon." +"@Preview(name = ""ChannelListHeader Preview (Connected state)"")@Composableprivate fun ChannelListHeaderForConnectedStatePreview(){ChannelListHeaderPreview(connectionState = ConnectionState.CONNECTED)}" "Preview of [ChannelListHeader] for the client that is connected to the WS. Should show a user avatar, a title, and an action button." +"@Preview(name = ""ChannelListHeader Preview (Connecting state)"") @Composable private fun ChannelListHeaderForConnectingStatePreview()  {ChannelListHeaderPreview(connectionState = ConnectionState.CONNECTING)}" "Preview of [ChannelListHeader] for the client that is trying to connect to the WS. Should show a user avatar, ""Waiting for network"" caption, and an action button." +"@Composable private fun ChannelListHeaderPreview(title: String = ""Stream Chat"",currentUser: User? = PreviewUserData.user1,connectionState: ConnectionState = ConnectionState.CONNECTED,) {ChatTheme {ChannelListHeader(title = title,currentUser = currentUser,connectionState = connectionState)}}" Shows [ChannelListHeader] preview for the provided parameters. +"internal class AboveAnchorPopupPositionProvider : PopupPositionProvider { override fun calculatePosition(anchorBounds: IntRect,windowSize: IntSize,layoutDirection: LayoutDirection,popupContentSize: IntSize,): IntOffset {return IntOffset(x = 0,y = anchorBounds.top - popupContentSize.height)}}" Calculates the position of the suggestion list [Popup] on the screen. +"public fun defaultFormatter( context: Context,maxMembers: Int = 5,): ChannelNameFormatter {return DefaultChannelNameFormatter(context, maxMembers)}}}" Build the default channel name formatter. +"private class DefaultChannelNameFormatter(private val context: Context,private val maxMembers: Int,) : ChannelNameFormatter {}" A simple implementation of [ChannelNameFormatter] that allows to generate a name for a channel based on the following rules: +"override fun formatChannelName(channel: Channel, currentUser: User?): String {return channel.getDisplayName(context, currentUser,R.string.stream_compose_untitled_channel, maxMembers)}}" Generates a name for the given channel. +public fun Channel.getLastMessage(currentUser: User?): Message? = getPreviewMessage(currentUser) "Returns channel's last regular or system message if exists. Deleted and silent messages, as well as messages from shadow-banned users, are not taken into account." +public fun Channel.getReadStatuses(userToIgnore: User?): List { return read.filter { it.user.id != userToIgnore?.id }.mapNotNull { it.lastRead }} Filters the read status of each person other than the target user. +"public fun Channel.isDistinct(): Boolean = cid.contains(""!members"")" "Checks if the channel is distinct. A distinct channel is a channel created without ID based on members. Internally the server creates a CID which starts with ""!members"" prefix and is unique for this particular group of users." +public fun Channel.isOneToOne(currentUser: User?): Boolean { return isDistinct() && members.size == 2 && members.any { it.user.id == currentUser?.id } } Checks if the channel is a direct conversation between the current user and some other user. A one-to-one chat is basically a corner case of a distinct channel with only 2 members. +"public fun Channel.getMembersStatusText(context: Context, currentUser: User?): String { return getMembersStatusText(context = context,currentUser = currentUser, userOnlineResId = R.string.stream_compose_user_status_online, userLastSeenJustNowResId = R.string.stream_compose_user_status_last_seen_just_now, userLastSeenResId = R.string.stream_compose_user_status_last_seen, memberCountResId = R.plurals.stream_compose_member_count, memberCountWithOnlineResId = R.string.stream_compose_member_count_online,) }" Returns a string describing the member status of the channel: either a member count for a group channel or the last seen text for a direct one-to-one conversation with the current user. +public fun Channel.getOtherUsers(currentUser: User?): List { val currentUserId = currentUser?.id return if (currentUserId != null) {members.filterNot { it.user.id == currentUserId }} else {members}.map { it.user } } Returns a list of users that are members of the channel excluding the currently logged in user. +"@Composable @ReadOnlyComposable internal fun initialsGradient(initials: String): Brush {val gradientBaseColors = LocalContext.current.resources.getIntArray(R.array.stream_compose_avatar_gradient_colors)val baseColorIndex = abs(initials.hashCode()) % gradientBaseColors.sizeval baseColor = gradientBaseColors[baseColorIndex]return Brush.linearGradient(listOf(Color(adjustColorBrightness(baseColor, GradientDarkerColorFactor)),Color(adjustColorBrightness(baseColor, GradientLighterColorFactor)),))}" Generates a gradient for an initials avatar based on the user initials. +"public fun Modifier.mirrorRtl(layoutDirection: LayoutDirection): Modifier { return this.scale( scaleX = if (layoutDirection == LayoutDirection.Ltr) 1f else -1f, scaleY = 1f ) }" Applies the given mirroring scaleX based on the [layoutDirection] that's currently configured in the UI. Useful since the Painter from Compose doesn't know how to parse autoMirrored` flags in SVGs. +"@Composable public fun rememberStreamImagePainter( data: Any?, placeholderPainter: Painter? = null, errorPainter: Painter? = null, fallbackPainter: Painter? = errorPainter, onLoading: ((AsyncImagePainter.State.Loading) -> Unit)? = null, onSuccess: ((AsyncImagePainter.State.Success) -> Unit)? = null, onError: ((AsyncImagePainter.State.Error) -> Unit)? = null, contentScale: ContentScale = ContentScale.Fit, filterQuality: FilterQuality = DrawScope.DefaultFilterQuality, ): AsyncImagePainter { return rememberAsyncImagePainter( model = ImageRequest.Builder(LocalContext.current) .data(data).build(), imageLoader = LocalStreamImageLoader.current, placeholder = placeholderPainter, error = errorPainter, fallback = fallbackPainter, contentScale = contentScale, onSuccess = onSuccess, onError = onError, onLoading = onLoading, filterQuality = filterQuality ) }" "Wrapper around the [coil.compose.rememberAsyncImagePainter] that plugs in our [LocalStreamImageLoader] singleton that can be used to customize all image loading requests, like adding headers, interceptors and similar." +public val LocalStreamImageLoader: StreamImageLoaderProvidableCompositionLocal = StreamImageLoaderProvidableCompositionLocal() "A [CompositionLocal] that returns the current [ImageLoader] for the composition. If a local [ImageLoader] has not been provided, it returns the singleton instance of [ImageLoader] in [Coil]. " +"@JvmInline public value class StreamImageLoaderProvidableCompositionLocal internal constructor(private val delegate: ProvidableCompositionLocal = staticCompositionLocalOf { null }, ) {public val current: ImageLoader@Composable@ReadOnlyComposableget() = delegate.current ?: LocalContext.current.imageLoader public infix fun provides(value: ImageLoader): ProvidedValue = delegate provides value }" A provider of [CompositionLocal] that returns the current [ImageLoader] for the composition. +"@Composable public fun rememberMessageListState(initialFirstVisibleItemIndex: Int = 0,initialFirstVisibleItemScrollOffset: Int = 0,parentMessageId: String? = null,): LazyListState {val baseListState = rememberLazyListState(initialFirstVisibleItemIndex, initialFirstVisibleItemScrollOffset) return if (parentMessageId != null) { rememberLazyListState() } else { baseListState } }" "Provides a [LazyListState] that's tied to a given message list. This is the default behavior, where we keep the base scroll position of the list persisted at all times, while the thread scroll state is always new, whenever we enter a thread. In case you want to customize the behavior, provide the [LazyListState] based on your logic and conditions." +"private class DefaultMessagePreviewFormatter( private val context: Context,private val messageTextStyle: TextStyle,private val senderNameTextStyle: TextStyle,private val attachmentTextFontStyle: TextStyle,private val attachmentFactories: List,) : MessagePreviewFormatter {" "The default implementation of [MessagePreviewFormatter] that allows to generate a preview text for a message with the following spans: sender name, message text, attachments preview text." +"override fun formatMessagePreview(message: Message,currentUser: User?,): AnnotatedString {return buildAnnotatedString {message.let { message ->val messageText = message.text.trim()if (message.isSystem()) {append(messageText)} else {appendSenderName(message = message,currentUser = currentUser,senderNameTextStyle = senderNameTextStyle)appendMessageText(messageText = messageText,messageTextStyle = messageTextStyle)appendAttachmentText(attachments = message.attachments, attachmentFactories = attachmentFactories,attachmentTextStyle = attachmentTextFontStyle)}}}}" Generates a preview text for the given message. +"private fun AnnotatedString.Builder.appendSenderName(message: Message,currentUser: User?,senderNameTextStyle: TextStyle,) {val sender = message.getSenderDisplayName(context, currentUser)if (sender != null) {append(""$sender: "")addStyle(SpanStyle(fontStyle = senderNameTextStyle.fontStyle,fontWeight = senderNameTextStyle.fontWeight,fontFamily = senderNameTextStyle.fontFamily),start = 0,end = sender.length)}}" Appends the sender name to the [AnnotatedString]. +"private fun AnnotatedString.Builder.appendMessageText(messageText: String,messageTextStyle: TextStyle,) {if (messageText.isNotEmpty()) {val startIndex = this.lengthappend(""$messageText "")addStyle(SpanStyle(fontStyle = messageTextStyle.fontStyle,fontFamily = messageTextStyle.fontFamily),start = startIndex,end = startIndex + messageText.length)}}" Appends the message text to the [AnnotatedString]. +"private fun AnnotatedString.Builder.appendAttachmentText(attachments: List,attachmentFactories: List,attachmentTextStyle: TextStyle,) {if (attachments.isNotEmpty()) {attachmentFactories.firstOrNull { it.canHandle(attachments) }?.textFormatter?.let { textFormatter ->attachments.mapNotNull { attachment ->textFormatter.invoke(attachment).let { previewText ->previewText.ifEmpty { null }}}.joinToString()}?.let { attachmentText ->val startIndex = this.lengthappend(attachmentText) addStyle(SpanStyle(fontStyle = attachmentTextStyle.fontStyle,fontFamily = attachmentTextStyle.fontFamily),start = startIndex,end = startIndex + attachmentText.length)}}}}" Appends a string representations of [attachments] to the [AnnotatedString]. +fun getIconRes(mimeType: String?): Int {if (mimeType == null) {return R.drawable.stream_compose_ic_file_generic}return mimeTypesToIconResMap[mimeType] ?: when { mimeType.contains(ModelType.attach_audio) -> R.drawable.stream_compose_ic_file_audio_genericmimeType.contains(ModelType.attach_video) -> R.drawable.stream_compose_ic_file_video_genericelse -> R.drawable.stream_compose_ic_file_generic}} Returns a drawable resource for the given MIME type. +"private class DefaultReactionIconFactory( private val supportedReactions: Map = mapOf(THUMBS_UP to ReactionDrawable(iconResId = R.drawable.stream_compose_ic_reaction_thumbs_up,selectedIconResId = R.drawable.stream_compose_ic_reaction_thumbs_up_selected),LOVE to ReactionDrawable(iconResId = R.drawable.stream_compose_ic_reaction_love,selectedIconResId = R.drawable.stream_compose_ic_reaction_love_selected),LOL to ReactionDrawable(iconResId = R.drawable.stream_compose_ic_reaction_lol,selectedIconResId = R.drawable.stream_compose_ic_reaction_lol_selected),WUT to ReactionDrawable(iconResId = R.drawable.stream_compose_ic_reaction_wut,selectedIconResId = R.drawable.stream_compose_ic_reaction_wut_selected),THUMBS_DOWN to ReactionDrawable(iconResId = R.drawable.stream_compose_ic_reaction_thumbs_down,selectedIconResId = R.drawable.stream_compose_ic_reaction_thumbs_down_selected)),) : ReactionIconFactory { }" The default implementation of [ReactionIconFactory] that uses drawable resources to create reaction icons. +override fun isReactionSupported(type: String): Boolean {return supportedReactions.containsKey(type)} Checks if the factory is capable of creating an icon for the given reaction type. +"@Composable override fun createReactionIcon(type: String): ReactionIcon {val reactionDrawable = requireNotNull(supportedReactions[type])return ReactionIcon(painter = painterResource(reactionDrawable.iconResId),selectedPainter = painterResource(reactionDrawable.selectedIconResId))}" Creates an instance of [ReactionIcon] for the given reaction type. +"@Composable override fun createReactionIcons(): Map {return supportedReactions.mapValues { createReactionIcon(it.key)}} companion object { private const val LOVE: String = ""love"" private const val THUMBS_UP: String = ""like""private const val THUMBS_DOWN: String = ""sad""private const val LOL: String = ""haha""private const val WUT: String = ""wow""}}" Creates [ReactionIcon]s for all the supported reaction types. +"public data class ReactionDrawable(@DrawableRes public val iconResId: Int,@DrawableRes public val selectedIconResId: Int,)" Contains drawable resources for normal and selected reaction states. +"public data class ReactionIcon(val painter: Painter,val selectedPainter: Painter,) {}" Contains [Painter]s for normal and selected states of the reaction icon. +public fun getFiles(): List { return attachmentFilter.filterAttachments(storageHelper.getFileAttachments(context)) } Loads a list of file metadata from the system and filters it against file types accepted by the backend. +public fun getMedia(): List { return attachmentFilter.filterAttachments(storageHelper.getMediaAttachments(context)) } Loads a list of media metadata from the system. +public fun getAttachmentsForUpload(attachments: List): List { return getAttachmentsFromMetaData(attachments) } Transforms a list of [AttachmentMetaData] into a list of [Attachment]s. This is required because we need to prepare the files for upload. +"private fun getAttachmentsFromMetaData(metaData: List): List { return metaData.map { val fileFromUri = storageHelper.getCachedFileFromUri(context, it) Attachment( upload = fileFromUri, type = it.type, name = it.title ?: fileFromUri.name ?: """", fileSize = it.size.toInt(), mimeType = it.mimeType ) } }" "Loads attachment files from the provided metadata, so that we can upload them." +public fun getAttachmentsFromUris(uris: List): List { return getAttachmentsMetadataFromUris(uris).let(::getAttachmentsFromMetaData) } Takes a list of file Uris and transforms them into a list of [Attachment]s so that we can upload them. +"public fun getAttachmentsMetadataFromUris(uris: List): List { return storageHelper.getAttachmentsFromUriList(context, uris) .let(attachmentFilter::filterAttachments) }" Takes a list of file Uris and transforms them into a list of [AttachmentMetaData]. +"public fun User.getLastSeenText(context: Context): String { return getLastSeenText(context = contextuserOnlineResId = R.string.stream_compose_user_status_online,userLastSeenJustNowResId = R.string.stream_compose_user_status_last_seen_just_now,userLastSeenResId = R.string.stream_compose_user_status_last_seen,)}" "Returns a string describing the elapsed time since the user was online (was watching the channel). Depending on the elapsed time, the string can have one of the following formats:- Online - Last seen just now - Last seen 13 hours ago" +"@Composable public fun AttachmentsPicker(attachmentsPickerViewModel: AttachmentsPickerViewModel,onAttachmentsSelected: (List) -> Unit,onDismiss: () -> Unit, modifier: Modifier = Modifier, tabFactories: List = ChatTheme.attachmentsPickerTabFactories,shape: Shape = ChatTheme.shapes.bottomSheet,) {var selectedTabIndex by remember { mutableStateOf(0) }Box(modifier = Modifier.fillMaxSize().background(ChatTheme.colors.overlay).clickable(onClick = onDismiss,indication = null,interactionSource = remember { MutableInteractionSource() })) {Card(modifier = modifier.clickable(indication = null,onClick = {},interactionSource = remember { MutableInteractionSource() }),elevation = 4.dp,shape = shape,backgroundColor = ChatTheme.colors.inputBackground,) {Column {AttachmentPickerOptions(hasPickedAttachments = attachmentsPickerViewModel.hasPickedAttachments,tabFactories = tabFactories,tabIndex = selectedTabIndex,onTabClick = { index, attachmentPickerMode -> selectedTabIndex = indexattachmentsPickerViewModel.changeAttachmentPickerMode(attachmentPickerMode) { false }},onSendAttachmentsClick = {onAttachmentsSelected(attachmentsPickerViewModel.getSelectedAttachments())},)Surface(modifier = Modifier.fillMaxSize(),shape = RoundedCornerShape(topStart =16.dp, topEnd = 16.dp),color = ChatTheme.colors.barsBackground,) {tabFactories.getOrNull(selectedTabIndex)?.pickerTabContent(attachments =attachmentsPickerViewModel.attachments,onAttachmentItemSelected = attachmentsPickerViewModel::changeSelectedAttachments,onAttachmentsChanged = { attachmentsPickerViewModel.attachments = it },onAttachmentsSubmitted = {onAttachmentsSelected(attachmentsPickerViewModel.getAttachmentsFromMetaData(it))},)}}}}}" "Represents the bottom bar UI that allows users to pick attachments. The picker renders its tabs based on the [tabFactories] parameter. Out of the box we provide factories for images, files and media capture tabs." +"Composable private fun AttachmentPickerOptions( hasPickedAttachments: Boolean, tabFactories: List, tabIndex: Int, onTabClick: (Int, AttachmentsPickerMode) -> Unit, onSendAttachmentsClick: () -> Unit, ) { Row( Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Row(horizontalArrangement = Arrangement.SpaceEvenly) { tabFactories.forEachIndexed { index, tabFactory -> val isSelected = index == tabIndex val isEnabled = isSelected || (!isSelected && !hasPickedAttachments) IconButton( enabled = isEnabled, content = { tabFactory.pickerTabIcon( isEnabled = isEnabled, isSelected = isSelected ) }, onClick = { onTabClick(index, tabFactory.attachmentsPickerMode) } ) } }  Spacer(modifier = Modifier.weight(1f))  IconButton( enabled = hasPickedAttachments, onClick = onSendAttachmentsClick, content = { val layoutDirection = LocalLayoutDirection.current  Icon( modifier = Modifier .weight(1f).mirrorRtl(layoutDirection = layoutDirection),painter = painterResource(id = R.drawable.stream_compose_ic_circle_left),contentDescription = stringResource(id = R.string.stream_compose_send_attachment),tint = if (hasPickedAttachments){ChatTheme.colors.primaryAccent} else {ChatTheme.colors.textLowEmphasis})})}}" The options for the Attachment picker. Shows tabs based on the provided list of [tabFactories] and a button to submit the selected attachments. +"@Composable override fun pickerTabIcon(isEnabled: Boolean, isSelected: Boolean) {Icon(painter = painterResource(id =R.drawable.stream_compose_ic_media_picker),contentDescription = stringResource(id = R.string.stream_compose_capture_option),tint = when {isSelected -> ChatTheme.colors.primaryAccentisEnabled -> ChatTheme.colors.textLowEmphasiselse -> ChatTheme.colors.disabled},)}" Emits a camera icon for this tab. +"@OptIn(ExperimentalPermissionsApi::class) @Composable override fun pickerTabContent(attachments: List,onAttachmentsChanged: (List) -> Unit,onAttachmentItemSelected: (AttachmentPickerItemState) -> Unit,onAttachmentsSubmitted: (List) -> Unit,) {val context = LocalContext.current val requiresCameraPermission = isCameraPermissionDeclared(context) val cameraPermissionState = if (requiresCameraPermission) rememberPermissionState(permission = Manifest.permission.CAMERA) else null val mediaCaptureResultLauncher = rememberLauncherForActivityResult(contract = CaptureMediaContract()) { file: File? -> val attachments = if (file == null) {emptyList()} else {listOf(AttachmentMetaData(context, file))} onAttachmentsSubmitted(attachments) }  if (cameraPermissionState == null || cameraPermissionState.status == PermissionStatus.Granted) { Box(modifier = Modifier.fillMaxSize()) { LaunchedEffect(Unit) { mediaCaptureResultLauncher.launch(Unit) } } } else if (cameraPermissionState.status is PermissionStatus.Denied) { MissingPermissionContent(cameraPermissionState) } }" Emits content that allows users to start media capture. +"private fun isCameraPermissionDeclared(context: Context): Boolean { return context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS) .requestedPermissions .contains(Manifest.permission.CAMERA) }" Returns if we need to check for the camera permission or not. +"public fun defaultFactories(imagesTabEnabled: Boolean = true,filesTabEnabled: Boolean = true,mediaCaptureTabEnabled: Boolean = true,): List {return listOfNotNull(if (imagesTabEnabled) AttachmentsPickerImagesTabFactory() else null,if (filesTabEnabled) AttachmentsPickerFilesTabFactory() else null,if (mediaCaptureTabEnabled) AttachmentsPickerMediaCaptureTabFactory() else null,)}" Builds the default list of attachment picker tab factories. +"@Composable public fun pickerTabContent(attachments: List,onAttachmentsChanged: (List) -> Unit,onAttachmentItemSelected: (AttachmentPickerItemState) -> Unit,onAttachmentsSubmitted: (List) -> Unit,)" Emits a content for the tab. +"@Composable public fun pickerTabIcon(isEnabled: Boolean, isSelected: Boolean)" Emits an icon for the tab. +private val filterFlow: MutableStateFlow = MutableStateFlow(initialFilters) State flow that keeps the value of the current [FilterObject] for channels. +private val querySortFlow: MutableStateFlow> = MutableStateFlow(initialSort) State flow that keeps the value of the current [QuerySorter] for channels. +"private val queryConfigFlow = filterFlow.filterNotNull().combine(querySortFlow) { filters, sort -> QueryConfig(filters = filters, querySort = sort) }" "The currently active query configuration, stored in a [MutableStateFlow]. It's created using the `initialFilters` parameter and the initial sort, but can be changed." +"private val searchQuery = MutableStateFlow("""")" "The current state of the search input. When changed, it emits a new value in a flow, which queries and loads new data." +public var channelsState: ChannelsState by mutableStateOf(ChannelsState()) private set The current state of the channels screen. It holds all the information required to render the UI. +public var selectedChannel: MutableState = mutableStateOf(null) private set "Currently selected channel, if any. Used to show the bottom drawer information when long tapping on a list item." +public var activeChannelAction: ChannelAction? by mutableStateOf(null) private set "Currently active channel action, if any. Used to show a dialog for deleting or leaving a channel/conversation." +public val connectionState: StateFlow = chatClient.clientState.connectionState "The state of our network connection - if we're online, connecting or offline." +public val user: StateFlow = chatClient.clientState.user The state of the currently logged in user. +public val channelMutes: StateFlow> = chatClient.globalState.channelMutes Gives us the information about the list of channels mutes by the current user. +private fun buildDefaultFilter(): Flow { return chatClient.clientState.user.map(Filters::defaultChannelListFilter).filterNotNull() } "Builds the default channel filter, which represents ""messaging"" channels that the current user is a part of." +public fun isChannelMuted(cid: String): Boolean {return channelMutes.value.any { cid == it.channel.cid }} Checks if the channel is muted for the current user. +private var queryChannelsState: StateFlow = MutableStateFlow(null) "Current query channels state that contains filter, sort and other states related to channels query." +init { if (initialFilters == null) {viewModelScope.launch {val filter = buildDefaultFilter().first()this@ChannelListViewModel.filterFlow.value = filter}}viewModelScope.launch {init()}} Combines the latest search query and filter to fetch channels and emit them to the UI. +"private suspend fun init() { logger.d { ""Initializing ChannelListViewModel"" } searchQuery.combine(queryConfigFlow) { query, config -> query to config }.collectLatest { (query, config) ->val queryChannelsRequest = QueryChannelsRequest(filter = createQueryChannelsFilter(config.filters, query),querySort = config.querySort,limit = channelLimit,messageLimit = messageLimit,memberLimit = memberLimit,) logger.d { ""Querying channels as state"" } queryChannelsState = chatClient.queryChannelsAsState( request = queryChannelsRequest, chatEventHandlerFactory = chatEventHandlerFactory, coroutineScope = viewModelScope, )observeChannels(searchQuery = query)}}" Makes the initial query to request channels and starts observing state changes. +"private fun createQueryChannelsFilter(filter: FilterObject, searchQuery: String): FilterObject { return if (searchQuery.isNotEmpty()) {Filters.and(Filter,Filters.or(Filters.and( Filters.autocomplete(""member.user.name"", searchQuery),Filters.notExists(""name"")),Filters.autocomplete(""name"", searchQuery)))} else {filter}}" "Creates a filter that is used to query channels. If the [searchQuery] is empty, then returns the original [filter] provided by the user. Otherwise, returns a wrapped [filter] that also checks that the channel name match the [searchQuery]." +"private suspend fun observeChannels(searchQuery: String) { logger.d { ""ViewModel is observing channels. When state is available, it will be notified"" }queryChannelsState.filterNotNull().collectLatest { queryChannelsState ->channelMutes.combine(queryChannelsState.channelsStateData, ::Pair).map { (channelMutes, state) ->when (state) {ChannelsStateData.NoQueryActive,ChannelsStateData.Loading,-> channelsState.copy(isLoading = true,searchQuery = searchQuery).also {logger.d { ""Loading state for query"" }}ChannelsStateData.OfflineNoResults -> {logger.d { ""No offline results. Channels are empty"" }channelsState.copy(isLoading = false,channelItems = emptyList(),searchQuery = searchQuery)}is ChannelsStateData.Result -> {logger.d { ""Received result for state of channels"" }channelsState.copy(isLoading = false,channelItems = createChannelItems(state.channels, channelMutes),isLoadingMore = false,endOfChannels = queryChannelsState.endOfChannels.value,searchQuery = searchQuery)}}}.collectLatest { newState -> channelsState = newState }}}" "Kicks off operations required to combine and build the [ChannelsState] object for the UI. t connects the 'loadingMore', 'channelsState' and 'endOfChannels' properties from the [queryChannelsState]. @param searchQuery The search query string used to search channels." +public fun selectChannel(channel: Channel?) { this.selectedChannel.value = channel} Changes the currently selected channel state. This updates the UI state and allows us to observe the state change. +public fun setSearchQuery(newQuery: String) { this.searchQuery.value = newQuery} Changes the current query state. This updates the data flow and triggers another query operation. The new operation will hold the channels that match the new query. +public fun setFilters(newFilters: FilterObject) {this.filterFlow.tryEmit(value = newFilters)} Allows for the change of filters used for channel queries. +public fun setQuerySort(querySort: QuerySorter) {this.querySortFlow.tryEmit(value = querySort)} Allows for the change of the query sort used for channel queries. +"public fun loadMore() {logger.d { ""Loading more channels"" }if (chatClient.clientState.isOffline) returnval currentConfig = QueryConfigfilters = filterFlow.value ?: return, querySort = querySortFlow.value)channelsState = channelsState.copy(isLoadingMore = true)val currentQuery = queryChannelsState.value?.nextPageRequest?.value currentQuery?.copy( filter = createQueryChannelsFilter(currentConfig.filters, searchQuery.value),querySort = currentConfig.querySort)?.let { queryChannelsRequest ->chatClient.queryChannels(queryChannelsRequest).enqueue()}}" Loads more data when the user reaches the end of the channels list. +public fun performChannelAction(channelAction: ChannelAction) { if (channelAction is Cancel) {selectedChannel.value = null}activeChannelAction = if (channelAction == Cancel) {null} else { channelAction} } "Clears the active action if we've chosen [Cancel], otherwise, stores the selected action as the currently active action, in [activeChannelAction]." +"public fun muteChannel(channel: Channel) { dismissChannelAction()  chatClient.muteChannel(channel.type, channel.id).enqueue() }" Mutes a channel. +"public fun unmuteChannel(channel: Channel) { dismissChannelAction() chatClient.unmuteChannel(channel.type, channel.id).enqueue() }" Unmutes a channel. @param channel The channel to unmute. +public fun deleteConversation(channel: Channel) { dismissChannelAction() chatClient.channel(channel.cid).delete().toUnitCall().enqueue() } "Deletes a channel, after the user chooses the delete [ChannelAction]. It also removes the [activeChannelAction], to remove the dialog from the UI." +"public fun leaveGroup(channel: Channel) { dismissChannelAction()  chatClient.getCurrentUser()?.let { user -> chatClient.channel(channel.type, channel.id).removeMembers(listOf(user.id)).enqueue() } }" "Leaves a channel, after the user chooses the leave [ChannelAction]. It also removes the [activeChannelAction], to remove the dialog from the UI." +public fun dismissChannelAction() { activeChannelAction = null selectedChannel.value = null } Dismisses the [activeChannelAction] and removes it from the UI. +"private fun createChannelItems(channels: List, channelMutes: List): List { val mutedChannelIds = channelMutes.map { channelMute -> channelMute.channel.cid }.toSet() return channels.map { ChannelItemState(it, it.cid in mutedChannelIds) } }" Creates a list of [ChannelItemState] that represents channel items we show in the list of channels. +public val user: StateFlow = chatClient.clientState.user The currently logged in user. +public var message: Message by mutableStateOf(Message()) private set Represents the message that we observe to show the UI data. +public var isShowingOptions: Boolean by mutableStateOf(false) private set Shows or hides the image options menu and overlay in the UI. +public var isShowingGallery: Boolean by mutableStateOf(false) private set Shows or hides the image gallery menu in the UI. +init { chatClient.getMessage(messageId).enqueue { result ->if (result.isSuccess) {this.message = result.data()}}} "Loads the message data, which then updates the UI state to shows images." +public fun toggleImageOptions(isShowingOptions: Boolean) {this.isShowingOptions = isShowingOptions} Toggles if we're showing the image options menu. +public fun toggleGallery(isShowingGallery: Boolean) {this.isShowingGallery = isShowingGallery} Toggles if we're showing the gallery screen. +public fun deleteCurrentImage(currentImage: Attachment) {val attachments = message.attachmentsval numberOfAttachments = attachments.sizeif (message.text.isNotEmpty() || numberOfAttachments > 1) {val imageUrl = currentImage.assetUrl ?: currentImage.imageUrlval message = message attachments.removeAll { it.assetUrl == imageUrl || it.imageUrl == imageUrl} chatClient.updateMessage(message).enqueue()} else if (message.text.isEmpty() && numberOfAttachments == 1) { chatClient.deleteMessage(message.id).enqueue { result ->if (result.isSuccess) { message = result.data()}}}} "Deletes the current image from the message we're observing, if possible. This will in turn update the UI accordingly or finish this screen in case there are no more images to show." +public var attachmentsPickerMode: AttachmentsPickerMode by mutableStateOf(Images) private set "Currently selected picker mode. [Images], [Files] or [MediaCapture]." +public var images: List by mutableStateOf(emptyList()) "List of images available, from the system." +public var files: List by mutableStateOf(emptyList()) "List of files available, from the system." +public var attachments: List by mutableStateOf(emptyList()) "List of attachments available, from the system." +public val hasPickedFiles: Boolean get() = files.any { it.isSelected } Gives us info if there are any file items that are selected. +public val hasPickedImages: Boolean get() = images.any { it.isSelected } Gives us info if there are any image items that are selected. +public val hasPickedAttachments: Boolean get() = attachments.any { it.isSelected } Gives us info if there are any attachment items that are selected. +public var isShowingAttachments: Boolean by mutableStateOf(false) private set Gives us information if we're showing the attachments picker or not. +public fun loadData() { loadAttachmentsData(attachmentsPickerMode)} Loads all the items based on the current type. +"public fun changeAttachmentPickerMode( attachmentsPickerMode: AttachmentsPickerMode, hasPermission: () -> Boolean = { true },) {this.attachmentsPickerMode = attachmentsPickerMode if (hasPermission()) loadAttachmentsData(attachmentsPickerMode) }" Changes the currently selected [AttachmentsPickerMode] and loads the required data. If no permission is granted will not try and load data to avoid crashes. +public fun changeAttachmentState(showAttachments: Boolean) { isShowingAttachments = showAttachments  if (!showAttachments) {dismissAttachments()}} Notifies the ViewModel if we should show attachments or not. +"private fun loadAttachmentsData(attachmentsPickerMode: AttachmentsPickerMode) { if (attachmentsPickerMode == Images) {val images = storageHelper.getMedia().map { AttachmentPickerItemState(it, false) } this.images = images this.attachments = images this.files = emptyList() } else if (attachmentsPickerMode == Files) {val files = storageHelper.getFiles().map { AttachmentPickerItemState(it, false) } this.files = files this.attachments = files this.images = emptyList() } }" "Loads the attachment data, based on the [AttachmentsPickerMode]." +"public fun changeSelectedAttachments(attachmentItem: AttachmentPickerItemState) { val dataSet = attachments val itemIndex = dataSet.indexOf(attachmentItem) val newFiles = dataSet.toMutableList() val newItem = dataSet[itemIndex].copy(isSelected = !newFiles[itemIndex].isSelected) newFiles.removeAt(itemIndex)  newFiles.add(itemIndex, newItem) if (attachmentsPickerMode == Files) { files = newFiles } else if (attachmentsPickerMode == Images) { images = newFiles } attachments = newFiles }" "Triggered when an [AttachmentMetaData] is selected in the list. Added or removed from the corresponding list, be it [files] or [images], based on [attachmentsPickerMode]." +public fun getSelectedAttachments(): List { val dataSet = if (attachmentsPickerMode == Files) files else images val selectedAttachments = dataSet.filter { it.isSelected } return storageHelper.getAttachmentsForUpload(selectedAttachments.map { it.attachmentMetaData }) } "Loads up the currently selected attachments. It uses the [attachmentsPickerMode] to know which attachments to use - files or images. It maps all files to a list of [Attachment] objects, based on their type." +public fun getAttachmentsFromUris(uris: List): List { return storageHelper.getAttachmentsFromUris(uris) } Transforms selected file Uris to a list of [Attachment]s we can upload. +public fun getAttachmentsFromMetaData(metaData: List): List { return storageHelper.getAttachmentsForUpload(metaData) } Transforms the selected meta data into a list of [Attachment]s we can upload. +public fun dismissAttachments() { attachmentsPickerMode = Images images = emptyList() files = emptyList() } "Triggered when we dismiss the attachments picker. We reset the state to show images and clear the items for now, until the user needs them again." +"private val channelState: StateFlow = chatClient.watchChannelAsState( cid = channelId, messageLimit = messageLimit, coroutineScope = viewModelScope)" Holds information about the current state of the [Channel]. +"private val ownCapabilities: StateFlow> = channelState.filterNotNull().flatMapLatest { it.channelData }.map { it.ownCapabilities }.stateIn(scope =viewModelScope,started = SharingStarted.Eagerly,initialValue = setOf())" Holds information about the abilities the current user is able to exercise in the given channel. +public val currentMessagesState: MessagesState get() = if (isInThread) threadMessagesState else messagesState "State handler for the UI, which holds all the information the UI needs to render messages. It chooses between [threadMessagesState] and [messagesState] based on if we're in a thread or not." +private var messagesState: MessagesState by mutableStateOf(MessagesState()) "State of the screen, for [MessageMode.Normal]." +private var threadMessagesState: MessagesState by mutableStateOf(MessagesState()) "State of the screen, for [MessageMode.MessageThread]." +public var messageMode: MessageMode by mutableStateOf(MessageMode.Normal) private set Holds the current [MessageMode] that's used for the messages list. [MessageMode.Normal] by default. +public var channel: Channel by mutableStateOf(Channel()) private set The information for the current [Channel]. +public var typingUsers: List by mutableStateOf(emptyList()) private set The list of typing users. +public var messageActions: Set by mutableStateOf(mutableSetOf()) private set "Set of currently active [MessageAction]s. Used to show things like edit, reply, delete and similar actions." +public val isInThread: Boolean get() = messageMode is MessageMode.MessageThread Gives us information if we're currently in the [Thread] message mode. +public val isShowingOverlay: Boolean get() = messagesState.selectedMessageState != null || threadMessagesState.selectedMessageState != null Gives us information if we have selected a message. +public val connectionState: StateFlow by chatClient.clientState::connectionState Gives us information about the online state of the device. +public val isOnline: Flow get() = chatClient.clientState.connectionState.map { it == ConnectionState.CONNECTED } Gives us information about the online state of the device. +public val user: StateFlow get() = chatClient.clientState.user Gives us information about the logged in user state. +private var threadJob: Job? = null [Job] that's used to keep the thread data loading operations. We cancel it when the user goes out of the thread state. +private var lastLoadedMessage: Message? = null "Represents the last loaded message in the list, for comparison when determining the [NewMessageState] for the screen." +private var lastLoadedThreadMessage: Message? = null "Represents the last loaded message in the thread, for comparison when determining the NewMessage" +private var lastSeenChannelMessage: Message? by mutableStateOf(null) Represents the latest message we've seen in the channel. +private var lastSeenThreadMessage: Message? by mutableStateOf(null) Represents the latest message we've seen in the active thread. +private var scrollToMessage: Message? = null Represents the message we wish to scroll to. +"private val logger = StreamLog.getLogger(""Chat:MessageListViewModel"")" Instance of [TaggedLogger] to log exceptional and warning cases in behavior. +init { observeTypingUsers() observeMessages() observeChannel()} Sets up the core data loading operations - such as observing the current channel and loading messages and other pieces of information. +"private fun observeMessages() { viewModelScope.launch { channelState.filterNotNull().collectLatest { channelState ->combine(channelState.messagesState, user, channelState.reads) { state, user, reads -> when (state) { is io.getstream.chat.android.offline.plugin.state.channel.MessagesState.NoQueryActive,is io.getstream.chat.android.offline.plugin.state.channel.MessagesState.Loading, -> messagesState.copy(isLoading = true) is io.getstream.chat.android.offline.plugin.state.channel.MessagesState.OfflineNoResults -> messagesState.copy( isLoading = false, messageItems = emptyList(), ) is io.getstream.chat.android.offline.plugin.state.channel.MessagesState.Result -> { messagesState.copy( isLoading = false, messageItems = groupMessages( messages = filterMessagesToShow(state.messages), isInThread = false, reads = reads, ), isLoadingMore = false, endOfMessages = channelState.endOfOlderMessages.value, currentUser = user, ) } } } .catch { it.cause?.printStackTrace() showEmptyState() } .collect { newState -> val newLastMessage = (newState.messageItems.firstOrNull { it is MessageItemState } as? MessageItemState)?.message val hasNewMessage = lastLoadedMessage != null && messagesState.messageItems.isNotEmpty() && newLastMessage?.id != lastLoadedMessage?.id messagesState = if (hasNewMessage) { val newMessageState = getNewMessageState(newLastMessage, lastLoadedMessage) newState.copy( newMessageState = newMessageState, unreadCount = getUnreadMessageCount(newMessageState) ) } else { newState }  messagesState.messageItems.firstOrNull { it is MessageItemState && it.message.id == scrollToMessage?.id }?.let { focusMessage((it as MessageItemState).message.id) }  lastLoadedMessage = newLastMessage } } } }" "Starts observing the messages in the current channel. We observe the 'messagesState', 'user' and endOfOlderMessages' states, as well as build the `newMessageState` using [getNewMessageState] and combine it into a [MessagesState] that holds all the information required for the screen." +private fun observeTypingUsers() { viewModelScope.launch { channelState.filterNotNull().flatMapLatest { it.typing }.collect { typingUsers = it.users }} } Starts observing the list of typing users. +"private fun observeChannel() { viewModelScope.launch {channelState.filterNotNull().flatMapLatest { state  >combine(state.channelData,state.membersCount,state.watcherCount,) { _, _, _ ->state.toChannel()}}.collect { channel  >chatClient.notifications.dismissChannelNotifications(channelType = channel.type,channelId = channel.id)setCurrentChannel(channel)}}}" "Starts observing the current [Channel] created from [ChannelState]. It emits new data when either channel data, member count or online member count updates." +private fun setCurrentChannel(channel: Channel) { this.channel = channel } "Sets the current channel, used to show info in the UI." +private fun filterMessagesToShow(messages: List): List { val currentUser = user.value return messages.filter { val shouldShowIfDeleted = when (deletedMessageVisibility) { DeletedMessageVisibility.ALWAYS_VISIBLE -> true DeletedMessageVisibility.VISIBLE_FOR_CURRENT_USER -> { !(it.deletedAt != null && it.user.id != currentUser?.id) } else -> it.deletedAt == null } val isSystemMessage = it.isSystem() || it.isError()  shouldShowIfDeleted || (isSystemMessage && showSystemMessages) } } Used to filter messages which we should show to the current user. +"private fun getNewMessageState(lastMessage: Message?, lastLoadedMessage: Message?): NewMessageState? { val currentUser = user.value  return if (lastMessage != null && lastLoadedMessage != null && lastMessage.id != lastLoadedMessage.id) { if (lastMessage.user.id == currentUser?.id) { MyOwn } else { Other } } else { null } }" "Builds the [NewMessageState] for the UI, whenever the message state changes. This is used to allow us to show the user a floating button giving them the option to scroll to the bottom when needed." +private fun getUnreadMessageCount(newMessageState: NewMessageState? = currentMessagesState.newMessageState): Int { if (newMessageState == null || newMessageState == MyOwn) return 0  val messageItems = currentMessagesState.messageItems val lastSeenMessagePosition = getLastSeenMessagePosition(if (isInThread) lastSeenThreadMessage else lastSeenChannelMessage) var unreadCount = 0  for (i in 0..lastSeenMessagePosition) { val messageItem = messageItems[i]  if (messageItem is MessageItemState && !messageItem.isMine && messageItem.message.deletedAt == null) { unreadCount++ } }  return unreadCount } "Counts how many messages the user hasn't read already. This is based on what the last message they've seen is, and the current message state." +private fun getLastSeenMessagePosition(lastSeenMessage: Message?): Int { if (lastSeenMessage == null) return 0  return currentMessagesState.messageItems.indexOfFirst { it is MessageItemState && it.message.id == lastSeenMessage.id } } Gets the list position of the last seen message in the list. +public fun updateLastSeenMessage(message: Message) { val lastSeenMessage = if (isInThread) lastSeenThreadMessage else lastSeenChannelMessage  if (lastSeenMessage == null) { updateLastSeenMessageState(message) return }  if (message.id == lastSeenMessage.id) { return }  val lastSeenMessageDate = lastSeenMessage.createdAt ?: Date() val currentMessageDate = message.createdAt ?: Date() if (currentMessageDate < lastSeenMessageDate) { return } updateLastSeenMessageState(message) }  Attempts to update the last seen message in the channel or thread. We only update the last seen message the first time the data loads and whenever we see a message that's newer than the current last seen message. +"private fun updateLastSeenMessageState(currentMessage: Message) { if (isInThread) { lastSeenThreadMessage = currentMessage  threadMessagesState = threadMessagesState.copy(unreadCount = getUnreadMessageCount()) } else { lastSeenChannelMessage = currentMessage  messagesState = messagesState.copy(unreadCount = getUnreadMessageCount()) }  val (channelType, id) = channelId.cidToTypeAndId()  val latestMessage: MessageItemState? = currentMessagesState.messageItems.firstOrNull { messageItem -> messageItem is MessageItemState } as? MessageItemState  if (currentMessage.id == latestMessage?.message?.id) { chatClient.markRead(channelType, id).enqueue() } }" Updates the state of the last seen message. Updates corresponding state based on [isInThread]. +"private fun showEmptyState() { messagesState = messagesState.copy(isLoading = false, messageItems = emptyList()) }" "If there's an error, we just set the current state to be empty - 'isLoading' as false and 'messages' as an empty list." +"public fun loadMore() { if (chatClient.clientState.isOffline) return val messageMode = messageMode  if (messageMode is MessageMode.MessageThread) { threadLoadMore(messageMode) } else { messagesState = messagesState.copy(isLoadingMore = true) chatClient.loadOlderMessages(channelId, messageLimit).enqueue() } }" Triggered when the user loads more data by reaching the end of the current messages. +"private fun threadLoadMore(threadMode: MessageMode.MessageThread) { threadMessagesState = threadMessagesState.copy(isLoadingMore = true) if (threadMode.threadState != null) { chatClient.getRepliesMore( messageId = threadMode.parentMessage.id, firstId = threadMode.threadState?.oldestInThread?.value?.id ?: threadMode.parentMessage.id, limit = DefaultMessageLimit, ).enqueue() } else { threadMessagesState = threadMessagesState.copy(isLoadingMore = false) logger.w { ""Thread state must be not null for offline plugin thread load more!"" } } }" Load older messages for the specified thread [MessageMode.MessageThread.parentMessage]. +"private fun loadMessage(message: Message) { val cid = channelState.value?.cid if (cid == null || chatClient.clientState.isOffline) return  chatClient.loadMessageById(cid, message.id).enqueue() }" Loads the selected message we wish to scroll to when the message can't be found in the current list. +"public fun selectMessage(message: Message?) { if (message != null) {changeSelectMessageState(if (message.isModerationFailed(chatClient)) {SelectedMessageFailedModerationState(message = message,ownCapabilities = ownCapabilities.value)} else {SelectedMessageOptionsState(message = message,ownCapabilities = ownCapabilities.value)})}}" Triggered when the user long taps on and selects a message. +"public fun selectReactions(message: Message?) {if (message != null) {changeSelectMessageState(SelectedMessageReactionsState(message = message,ownCapabilities = ownCapabilities.value))}}" Triggered when the user taps on and selects message reactions. +"public fun selectExtendedReactions(message: Message?) {if (message != null) {changeSelectMessageState(SelectedMessageReactionsPickerState(message = message,ownCapabilities = ownCapabilities.value))}}" Triggered when the user taps the show more reactions button. +private fun changeSelectMessageState(selectedMessageState: SelectedMessageState) {if (isInThread) {threadMessagesState = threadMessagesState.copy(selectedMessageState = selectedMessageState)} else {messagesState = messagesState.copy(selectedMessageState = selectedMessageState)}} Changes the state of [threadMessagesState] or [messagesState] depending on the thread mode. +public fun openMessageThread(message: Message) {loadThread(message)} Triggered when the user taps on a message that has a thread active. +"private fun loadThread(parentMessage: Message) {val threadState = chatClient.getRepliesAsState(parentMessage.id, DefaultMessageLimit)val channelState = channelState.value ?: returnmessageMode = MessageMode.MessageThread(parentMessage, threadState)observeThreadMessages(threadId = threadState.parentId,messages = threadState.messages,endOfOlderMessages = threadState.endOfOlderMessages,reads = channelState.reads)}" Changes the current [messageMode] to be [Thread] with [ThreadState] and Loads thread data using ChatClient directly. The data is observed by using [ThreadState]. +"private fun observeThreadMessages( threadId: String,messages: StateFlow>,endOfOlderMessages: StateFlow,reads: StateFlow>,) {threadJob = viewModelScope.launch {combine(user, endOfOlderMessages, messages, reads) { user, endOfOlderMessages, messages, reads ->threadMessagesState.copy(isLoading = false,messageItems = groupMessages(messages = filterMessagesToShow(messages),isInThread = true,reads = reads,),isLoadingMore = false,endOfMessages = endOfOlderMessages,currentUser = user,parentMessageId = threadId)}.collect { newState ->val newLastMessage =(newState.messageItems.firstOrNull { it is MessageItemState } as? MessageItemState)?.messagethreadMessagesState = newState.copy(newMessageState getNewMessageState(newLastMessage, lastLoadedThreadMessage))lastLoadedThreadMessage = newLastMessage}}}" "Observes the currently active thread. In process, this creates a [threadJob] that we can cancel once we leave the thread." +"private fun groupMessages(messages: List,isInThread: Boolean,reads: List,): List {val parentMessageId =(messageMode as? MessageMode.MessageThread)?.parentMessage?.idval currentUser = user.valueval groupedMessages = mutableListOf()val lastRead = reads.filter { it.user.id != currentUser?.id }.mapNotNull { it.lastRead }.maxOrNull() messages.forEachIndexed { index, message ->val user = message.user val previousMessage = messages.getOrNull(index - 1) val nextMessage = messages.getOrNull(index + 1) val previousUser = previousMessage?.user val nextUser = nextMessage?.user val willSeparateNextMessage = nextMessage?.let { shouldAddDateSeparator(message, it) } ?: false  val position = when { previousUser != user && nextUser == user && !willSeparateNextMessage -> MessageItemGroupPosition.Top previousUser == user && nextUser == user && !willSeparateNextMessage -> MessageItemGroupPosition.Middle previousUser == user && nextUser != user -> MessageItemGroupPosition.Bottom else -> MessageItemGroupPosition.None }  val isLastMessageInGroup = position == MessageItemGroupPosition.Bottom || position == MessageItemGroupPosition.None  val shouldShowFooter = messageFooterVisibility.shouldShowMessageFooter( message = message, isLastMessageInGroup = isLastMessageInGroup, nextMessage = nextMessage )  if (shouldAddDateSeparator(previousMessage, message)) { groupedMessages.add(DateSeparatorState(message.getCreatedAtOrThrow())) }  if (message.isSystem() || message.isError()) { groupedMessages.add(SystemMessageState(message = message)) } else { val isMessageRead = message.createdAt ?.let { lastRead != null && it <= lastRead } ?: false  groupedMessages.add( MessageItemState( message = message, currentUser = currentUser, groupPosition = position, parentMessageId = parentMessageId, isMine = user.id == currentUser?.id, isInThread = isInThread, isMessageRead = isMessageRead, shouldShowFooter = shouldShowFooter, deletedMessageVisibility = deletedMessageVisibility ) ) }  if (index == 0 && isInThread) { groupedMessages.add(ThreadSeparatorState(message.replyCount)) } }  return groupedMessages.reversed() }" "Takes in the available messages for a [Channel] and groups them based on the sender ID. We put the message in a group, where the positions can be [MessageItemGroupPosition.Top], [MessageItemGroupPosition.Middle],  [MessageItemGroupPosition.Bottom] or [MessageItemGroupPosition.None] if the message isn't in a group." +"private fun shouldAddDateSeparator(previousMessage: Message?, message: Message): Boolean { return if (!showDateSeparators) { false } else if (previousMessage == null) { true } else { val timeDifference = message.getCreatedAtOrThrow().time - previousMessage.getCreatedAtOrThrow().time  return timeDifference > dateSeparatorThresholdMillis } }" Decides if we need to add a date separator or not. +"@JvmOverloads @Suppress(""ConvertArgumentToSet"") public fun deleteMessage(message: Message, hard: Boolean = false) { messageActions = messageActions - messageActions.filterIsInstance() removeOverlay()  chatClient.deleteMessage(message.id, hard).enqueue() }" "Removes the delete actions from our [messageActions], as well as the overlay, before deleting the selected message." +"@Suppress(""ConvertArgumentToSet"") public fun flagMessage(message: Message) { messageActions = messageActions - messageActions.filterIsInstance() removeOverlay()  chatClient.flagMessage(message.id).enqueue() }" "Removes the flag actions from our [messageActions], as well as the overlay, before flagging  the selected message." +"private fun resendMessage(message: Message) { val (channelType, channelId) = message.cid.cidToTypeAndId()  chatClient.sendMessage(channelType, channelId, message).enqueue() }" Retries sending a message that has failed to send. +private fun copyMessage(message: Message) { clipboardHandler.copyMessage(message) } Copies the message content using the [ClipboardHandler] we provide. This can copy both attachment and text messages. +private fun updateUserMute(user: User) { val isUserMuted = chatClient.globalState.muted.value.any { it.target.id == user.id }  if (isUserMuted) { unmuteUser(user.id) } else { muteUser(user.id) } } Mutes or unmutes the user that sent a particular message. +"public fun muteUser( userId: String, timeout: Int? = null, ) { chatClient.muteUser(userId, timeout) .enqueue(onError = { chatError -> val errorMessage = chatError.message ?: chatError.cause?.message ?: ""Unable to mute the user"" StreamLog.e(""MessageListViewModel.muteUser"") { errorMessage } }) }" Mutes the given user inside this channel. +"public fun unmuteUser(userId: String) { chatClient.unmuteUser(userId) .enqueue(onError = { chatError -> val errorMessage = chatError.message ?: chatError.cause?.message ?: ""Unable to unmute the user""  StreamLog.e(""MessageListViewModel.unMuteUser"") { errorMessage } }) }" Unmutes the given user inside this channel. +"public fun banUser( userId: String, reason: String? = null, timeout: Int? = null, ) { chatClient.channel(channelId).banUser(userId, reason, timeout) .enqueue(onError = { chatError -> val errorMessage = chatError.message ?: chatError.cause?.message ?: ""Unable to ban the user""  StreamLog.e(""MessageListViewModel.banUser"") { errorMessage } }) }" Bans the given user inside this channel. +"public fun unbanUser(userId: String) { chatClient.channel(channelId).unbanUser(userId).enqueue(onError = { chatError -> val errorMessage = chatError.message ?: chatError.cause?.message ?: ""Unable to unban the user""  StreamLog.e(""MessageListViewModel.unban"") { errorMessage } }) }" Unbans the given user inside this channel. +"public fun shadowBanUser( userId: String, reason: String? = null, timeout: Int? = null, ) { chatClient.channel(channelId).shadowBanUser(userId, reason, timeout) .enqueue(onError = { chatError -> val errorMessage = chatError.message ?: chatError.cause?.message ?: ""Unable to shadow ban the user""  StreamLog.e(""MessageListViewModel.shadowBanUser"") { errorMessage } }) }" Shadow bans the given user inside this channel. +"public fun removeShadowBanFromUser(userId: String) { chatClient.channel(channelId).removeShadowBan(userId) .enqueue(onError = { chatError -> val errorMessage = chatError.message ?: chatError.cause?.message ?: ""Unable to remove the user shadow ban""  StreamLog.e(""MessageListViewModel.removeShadowBanFromUser"") { errorMessage } }) }" Removes the shaddow ban for the given user inside this channel. +"private fun reactToMessage(reaction: Reaction, message: Message) { val channelState = channelState.value ?: return  if (message.ownReactions.any { it.messageId == reaction.messageId && it.type == reaction.type }) { chatClient.deleteReaction( messageId = message.id, reactionType = reaction.type, cid = channelState.cid ).enqueue() } else { chatClient.sendReaction( reaction = reaction, enforceUnique = enforceUniqueReactions, cid = channelState.cid ).enqueue() } }" "Triggered when the user chooses the [React] action for the currently selected message. If the message already has that reaction, from the current user, we remove it. Otherwise we add a new reaction." +"private fun updateMessagePin(message: Message) { val updateCall = if (message.pinned) { chatClient.unpinMessage(message) } else { chatClient.pinMessage(message = message, expirationDate = null) }  updateCall.enqueue() }" Pins or unpins the message from the current channel based on its state. +public fun leaveThread() { messageMode = MessageMode.Normal messagesState = messagesState.copy(selectedMessageState = null) threadMessagesState = MessagesState() lastSeenThreadMessage = null threadJob?.cancel() } Leaves the thread we're in and resets the state of the [messageMode] and both of the [MessagesState]s. +public fun removeOverlay() { threadMessagesState = threadMessagesState.copy(selectedMessageState = null) messagesState = messagesState.copy(selectedMessageState = null) } "Resets the [MessagesState]s, to remove the message overlay, by setting 'selectedMessage' to null." +"public fun clearNewMessageState() { threadMessagesState = threadMessagesState.copy(newMessageState = null, unreadCount = 0) messagesState = messagesState.copy(newMessageState = null, unreadCount = 0) }" "Clears the [NewMessageState] from our UI state, after the user taps on the ""Scroll to bottom"" or ""New Message"" actions in the list or simply scrolls to the bottom." +public fun focusMessage(messageId: String) { val messages = currentMessagesState.messageItems.map { if (it is MessageItemState && it.message.id == messageId) { it.copy(focusState = MessageFocused) } else { it } }  viewModelScope.launch { updateMessages(messages) delay(RemoveMessageFocusDelay) removeMessageFocus(messageId) } } "Sets the focused message to be the message with the given ID, after which it removes it from focus with a delay." +private fun removeMessageFocus(messageId: String) { val messages = currentMessagesState.messageItems.map { if (it is MessageItemState && it.message.id == messageId) { it.copy(focusState = MessageFocusRemoved) } else { it } }  if (scrollToMessage?.id == messageId) { scrollToMessage = null }  updateMessages(messages) } Removes the focus from the message with the given ID. +private fun updateMessages(messages: List) { if (isInThread) { this.threadMessagesState = threadMessagesState.copy(messageItems = messages) } else { this.messagesState = messagesState.copy(messageItems = messages) } } Updates the current message state with new messages. +public fun getMessageWithId(messageId: String): Message? { val messageItem =currentMessagesState.messageItems.firstOrNull { it is MessageItemState && it.message.id == messageId }  return (messageItem as? MessageItemState)?.message } Returns a message with the given ID from the [currentMessagesState]. +public fun performGiphyAction(action: GiphyAction) { val message = action.message when (action) { is SendGiphy -> chatClient.sendGiphy(message) is ShuffleGiphy -> chatClient.shuffleGiphy(message) is CancelGiphy -> chatClient.cancelEphemeralMessage(message) }.exhaustive.enqueue() } Executes one of the actions for the given ephemeral giphy message. +public fun scrollToSelectedMessage(message: Message) { val isMessageInList = currentMessagesState.messageItems.firstOrNull { it is MessageItemState && it.message.id == message.id } != null  if (isMessageInList) { focusMessage(message.id) } else { scrollToMessage = message loadMessage(message = message) } } Scrolls to message if in list otherwise get the message from backend. +"fun save(filename: String?): Boolean { try { mOutput = FileOutputStream(filename) val output = ByteArray(BUFFER_SIZE) while (mInput.available() > 0) { val size: Int = read(output) if (size > 0) { mOutput.write(output, 0, size) } else break } mInput.close() mOutput.close() return true } catch (e: Exception) { e.printStackTrace() } try { if (mInput != null) mInput.close() if (mOutput != null) mOutput.close() } catch (e: IOException) { e.printStackTrace() } return false }" Saves an unencrypted copy of the music file as an Mp3 +fun isSingleton(): Boolean { return true } Always returns < code > true < /code > . +fun append(s: String?) { compoundID.append(s) } Append a new segment to the compound name of the operator +fun eUnset(featureID: Int) { when (featureID) { TypesPackage.TSTRUCT_GETTER__DEFINED_MEMBER -> { setDefinedMember(null as TStructMember?) return } } super.eUnset(featureID) } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +private fun doSetRhythmDrawable(@Nullable drawable: RhythmDrawable) { if (mRhythmDrawable != null) { mRhythmDrawable.setCallback(null) } mRhythmDrawable = drawable if (mRhythmDrawable != null) { mRhythmDrawable.setBounds(mBounds) mRhythmDrawable.setCallback(this) } } Links new drawable to this view +protected fun AbstractSVGFilterPrimitiveElementBridge() {} Constructs a new bridge for a filter primitive element . +"@Pointcut(""within(@javax.persistence.Entity *) || "" + ""within(@javax.persistence.MappedSuperclass *) || "" + ""within(@javax.persistence.Embeddable *)"") fun jpa() { }" Pointcut for jpa entities +"fun OMGrid( lat: Double, lon: Double, x: Int, y: Int, vResolution: Double, hResolution: Double, data: Array? ) { setRenderType(RENDERTYPE_OFFSET) set(lat, lon, x, y, vResolution, hResolution, data) }" "Create a OMGrid that covers a x/y screen area , anchored to a lat/lon point . Column major by default . If your data is row major , use null for the data , set the major direction , and then set the data ." +"operator fun compareTo(other: SpatialObjectPair): Int { return java.lang.Double.compare(this.distance, other.distance) }" "Compares this object with the specified object for order . Returns a negative integer , zero , or a positive integer as this object is less than , equal to , or greater than the specified object . < p/ >" +"fun checkLabel(label: Label?, checkVisited: Boolean, msg: String) { requireNotNull(label) { ""Invalid $msg (must not be null)"" } require( (checkVisited && labels.get(label) == null)) { ""Invalid $msg (must be visited first)"" } }" Checks that the given label is not null . This method can also check that the label has been visited . +"@Throws(MissingResourceException::class) fun MinecraftlyLogger(core: MinecraftlyCore, parentLogger: Logger) { super(""Core "" + parentLogger.getName(), parentLogger.getResourceBundleName()) core = core this.debug = File(core.getMinecraftlyDataFolder(), "".debugging"").exists() setParent(parentLogger) setUseParentHandlers(true) }" Method to construct a logger for Minecraftly 's Core . +"fun cleanIndex( mutator: RowMutator, doType: DataObjectType, listToCleanRef: SoftReference ) { val listToClean: IndexCleanupList = listToCleanRef.get() if (listToClean == null) { _log.warn( ""clean up list for {} has been recycled by GC, skip it"", doType.getClass().getName() ) return } val cleanList: Map>> = listToClean.getColumnsToClean() val entryIt: Iterator>>> = cleanList.entries.iterator() val dependentFields: MutableMap = HashMap() while (entryIt.hasNext()) { val (rowKey, cols) = entryIt.next() for (i in cols.indices) { val column: Column = cols[i] val field: ColumnField = doType.getColumnField(column.getName().getOne()) field.removeColumn(rowKey, column, mutator, listToClean.getAllColumns(rowKey)) for (depField in field.getDependentFields()) { dependentFields[depField.getName()] = depField } } for (depField in dependentFields.values) { depField.removeIndex( rowKey, null, mutator, listToClean.getAllColumns(rowKey), listToClean.getObject(rowKey) ) } } removeIndexOfInactiveObjects(mutator, doType, listToClean as IndexCleanupList, true) mutator.executeIndexFirst() }" Clean out old column / index entries synchronously +@Throws(IOException::class) protected fun onPrepareRequest(request: HttpUriRequest?) { } Called before the request is executed using the underlying HttpClient . < p > Overwrite in subclasses to augment the request. < /p > +"override fun toString(): String? { return super.toString() + ""NameConstraints: ["" + (if (permitted == null) """" else """""" Permitted:${permitted.toString()}"""""") + (if (excluded == null) """" else """""" Excluded:${excluded.toString()}"""""") + "" ]\n"" }" Return the printable string . +"fun LRUCache(initialSize: Int, maxSize: Int) { this(initialSize, maxSize, 1) }" Create a new LRU cache . +"@Throws(Exception::class) fun HarCapabilityContainerTest(testName: String?, testData: EnvironmentTestData?) { super(testName, testData) }" Initializes the test case . +"private fun locate(name: String): File? { var prefix = """" var sourceFile: File? = null var idx = 0 while (true) { if (idx == 0 && ToolIO.getUserDir() != null) { sourceFile = File(ToolIO.getUserDir(), name) } else { sourceFile = File(prefix + name) } if (sourceFile.exists()) break if (idx >= libraryPathEntries.size()) break prefix = libraryPathEntries.elementAt(idx++) } return sourceFile }" Searches for the file in current directory ( ToolIO.userDirectory ) and in library paths +"@JvmStatic fun main(args: Array) { val timeResolution = TimeResolution() timeResolution.measureTimer() timeResolution.measureTimeFunctions(javax.accessibility.AccessibleAction.INCREMENT, MAX) timeResolution.measureSleep() timeResolution.measureWait() }" Execute the various timer resolution tests . +"@Throws(IOException::class, ClassNotFoundException::class) private fun readObject(s: ObjectInputStream) { try { s.defaultReadObject() this.queue = arrayOfNulls(q.size()) comparator = q.comparator() addAll(q) } finally { q = null } }" "Reconstitutes this queue from a stream ( that is , deserializes it ) ." +"fun createEdge(source: BasicBlock?, dest: BasicBlock?, @Edge.Type type: Int): Edge { val edge: Edge = createEdge(source, dest) edge.setType(type) return edge }" Add a unique edge to the graph . There must be no other edge already in the CFG with the same source and destination blocks . +private fun initialize() { this.setContentPane(getJPanel()) this.pack() } This method initializes this +"fun translate(x: Float, y: Float, z: Float) { val tmp = Matrix4f() tmp.loadTranslate(x, y, z) multiply(tmp) }" Modifies the current matrix by post-multiplying it with a translation matrix of given dimensions +fun AdaptiveJobCountLoadProbe() {} Initializes active job probe . +"fun primeFncName(s: Session?, line: Int) { primeAllFncNames(s) }" Called in order to make sure that we have a function name available at the given location . For AVM+ swfs we do n't need a swd and therefore do n't have access to function names in the same fashion . We need to ask the player for a particular function name . +"fun addDistinctEntry(sourceList: MutableList?, entry: V): Boolean { return if (sourceList != null && !sourceList.contains(entry)) sourceList.add(entry) else false }" add distinct entry to list +"protected fun initFromJar(file: File) { val jar: JarFile var entry: JarEntry val enm: Enumeration if (VERBOSE) { println(""Analyzing jar: $file"") } if (!file.exists()) { println(""Jar does not exist: $file"") return } try { jar = JarFile(file) enm = jar.entries() while (enm.hasMoreElements()) { entry = enm.nextElement() if (entry.getName().endsWith("".class"")) { add(entry.getName()) } } initFromManifest(jar.getManifest()) } catch (e: Exception) { e.printStackTrace() } }" Fills the class cache with classes from the specified jar . +"fun build(@Nullable quadConsumer: Consumer?): List? { val quads: MutableList = ArrayList(this.vertices.size() / 4) if (this.vertices.size() % 4 !== 0) throw RuntimeException(""Invalid number of vertices"") var i = 0 while (i < this.vertices.size()) { val vert1: sun.security.provider.certpath.Vertex = this.vertices.get(i) val vert2: sun.security.provider.certpath.Vertex = this.vertices.get(i + 1)" Builds the quads . Specify a consumer to modify the quads +fun newJdbcExceptionTranslator(): SQLExceptionTranslator? { return SQLStateSQLExceptionTranslator() } "Create an appropriate SQLExceptionTranslator for the given TransactionManager . If a DataSource is found , a SQLErrorCodeSQLExceptionTranslator for the DataSource is created ; else , a SQLStateSQLExceptionTranslator as fallback ." +"override fun onSaveInstanceState(outState: Bundle) { outState.putBoolean(""SlidingActivityHelper.open"", mSlidingMenu.isMenuShowing()) outState.putBoolean( ""SlidingActivityHelper.secondary"", mSlidingMenu.isSecondaryMenuShowing() ) }" Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate ( Bundle ) or onRestoreInstanceState ( Bundle ) ( the Bundle populated by this method will be passed to both ) . +"fun `steFor_$fieldInit`(): SymbolTableEntryInternal? { return getSymbolTableEntryInternal(""\$fieldInit"", true) }" `` $ fieldInit '' - retrieve the internal symbol table entry for the symbol `` $ fieldInit '' +"fun isProcessing(): Boolean { val oo: Any = get_Value(COLUMNNAME_Processing) return if (oo != null) { if (oo is Boolean) oo.toBoolean() else ""Y"" == oo } else false }" Get Process Now . +"fun createFromCommandline(args: Array): Profile? { val profile = Profile() var i = 0 while (i != args.size) { if (args[i] == ""-u"") { profile.setUser(args[i + 1])} else if (args[i] == ""-p"") { profile.setPassword(args[i + 1]) } else if (args[i] == ""-c"") { profile.setCharacter(args[i + 1]) } else if (args[i] == ""-h"") { profile.setHost(args[i + 1]) } else if (args[i] == ""-P"") { profile.setPort(args[i + 1].toInt()) } else if (args[i] == ""-S"") { profile.setSeed(args[i + 1]) } i++ } if (profile.getCharacter() == null) { profile.setCharacter(profile.getUser()) } return profile }" create a profile based on command line arguments < ul > < li > -u : username < /li > < li > -p : password < /li > < li > -c : character name ( defaults to username ) < /li > < li > -h : hostname < /li > < li > -P : port < /li > < li > -S : pre authentication seed < /li > < /ul > +"fun MainWindow() { super(""Main Window"") settings = Settings() update = UpdateWindow() blocksWindow = BlockListWindow() consoleLog = GUIConsoleLog() if (settings.getPreferences().getBoolean(""OPEN_CONSOLE_ON_START"", true)) { consoleLog.setVisible(true) } export = ExportWindow() main = this setSize(1000, 800) setMinimumSize(Dimension(400, 400)) setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) setTitle(""jMC2Obj"") setLocationRelativeTo(null) panel = MainPanel() add(panel) setVisible(true) }" Window contructor . +fun findAndInit(it: Iterator<*>) { while (it.hasNext()) { findAndInit(it.next()) } } "Eventually gets called when the MouseDelegator is added to the BeanContext , and when other objects are added to the BeanContext anytime after that . The MouseDelegator looks for a MapBean to manage MouseEvents for , and MouseModes to use to manage those events . If a MapBean is added to the BeanContext while another already is in use , the second MapBean will take the place of the first ." +fun wantsFutureVariantBases(): Boolean { return mHaplotypeA.wantsFutureVariantBases() || mHaplotypeB.wantsFutureVariantBases() } Test whether a deficit of variant bases are upstream in the queue in order to perform a step . +"fun createPotentialProducer(baseObject: Any?,methodName: String?,dataType: Class<*>?): PotentialProducer? {val description: String = getDescriptionString(baseObject, methodName, dataType) return PotentialProducer(parentComponent,baseObject,methodName,dataType,null,null,description)}" Create a potential producer ( without auxiliary arguments ) . This is probably the main method to use in a script . +"fun Hashtable() { this(11, 0.75f) }" "Constructs a new , empty hashtable with a default initial capacity ( 11 ) and load factor , which is < tt > 0.75 < /tt > ." +"private fun runRoutesDistance(runNr: String, sc: Scenario) { val ug: UserGroup = UserGroup.URBAN val lastIteration: Int = sc.getConfig().controler().getLastIteration() val eventsFile: String = sc.getConfig().controler() .getOutputDirectory() + ""/ITERS/it."" + lastIteration + ""/"" + lastIteration + "".events.xml.gz"" val lmdfed = LegModeRouteDistanceDistributionAnalyzer() lmdfed.init(sc, eventsFile) lmdfed.preProcessData() lmdfed.postProcessData() File(RUN_DIR + ""/analysis/legModeDistributions/"").mkdirs() lmdfed.writeResults(RUN_DIR + ""/analysis/legModeDistributions/"" + runNr + ""_it."" + lastIteration + ""_"") }" It will write route distance distribution from events and take the beeline distance for teleported modes +@Throws(IOException::class) fun findAvailableStrings(uri: String): List? { _resourcesNotLoaded.clear() val fulluri: String = _path + uri val strings: MutableList = ArrayList() val resources: Enumeration = getResources(fulluri) while (resources.hasMoreElements()) { val url: URL = resources.nextElement() try { val string: String = readContents(url) strings.add(string) } catch (notAvailable: IOException) { _resourcesNotLoaded.add(url.toExternalForm()) } } return strings } Reads the contents of the found URLs as a Strings and returns them . Individual URLs that can not be read are skipped and added to the list of 'resourcesNotLoaded ' +"fun computeInPlace(vararg dataset: Double): Double { checkArgument(dataset.size > 0, ""Cannot calculate quantiles of an empty dataset"")if (containsNaN(dataset)) return NaN } val numerator = index as Long * (dataset.size - 1) val quotient = LongMath.divide(numerator, scale, RoundingMode.DOWN) as Int val remainder = (numerator - quotient.toLong() * scale) as Int selectInPlace(quotient, dataset, 0, dataset.size - 1) return if (remainder == 0) { dataset[quotient] } else { selectInPlace(quotient + 1, dataset, quotient + 1, dataset.size - 1) interpolate(dataset[quotient], dataset[quotient + 1], remainder, scale) } }" "Computes the quantile value of the given dataset , performing the computation in-place ." +"fun scale(factor: Double): Ellipse? { val r: RotatedRect = rect.clone() r.size = Size(factor * rect.size.width, factor * rect.size.height) return Ellipse(r) v }" Scale this ellipse by a scaling factor about its center +"@Throws(Exception::class) private fun waitForReportRunCompletion( reporting: Dfareporting, userProfileId: Long, file: File ): File? { var file: File = file var interval: Int for (i in 0..MAX_POLLING_ATTEMPTS) { if (!file.getStatus().equals(""PROCESSING"")) { break } interval = (POLL_TIME_INCREMENT * Math.pow(1.6, i.toDouble())) System.out.printf(""Polling again in %s ms.%n"", interval) Thread.sleep(interval.toLong()) file = reporting.reports().files().get(userProfileId, file.getReportId(), file.getId()) .execute() } return file }" Waits for a report file to generate with exponential back-off . +private fun showFeedback(message: String) { if (myHost != null) { myHost.showFeedback(message) } else { println(message) } } Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface . +"fun AllocationSite() { this(0, 0) }" An anonymous allocation site +@Synchronized override fun equals(o: Any?): Boolean { return super.equals(o) } "Compares the specified Object with this Vector for equality . Returns true if and only if the specified Object is also a List , both Lists have the same size , and all corresponding pairs of elements in the two Lists are < em > equal < /em > . ( Two elements < code > e1 < /code > and < code > e2 < /code > are < em > equal < /em > if < code > ( e1==null ? e2==null : e1.equals ( e2 ) ) < /code > . ) In other words , two Lists are defined to be equal if they contain the same elements in the same order ." +protected fun makeConverter(): DateTimeConverter? { return jdk.internal.joptsimple.util.DateConverter() } Create the Converter with no default value . +"fun skip(str: String, csq: CharSequence?): Boolean { return if (this.at(str, csq)) { index += str.length true } else { false } }" "Moves this cursor forward only if at the specified string . This method is equivalent to : [ code ] if ( at ( str , csq ) ) increment ( str.length ( ) ) ; [ /code ]" +"fun deleteExpectedPartitionValues(expectedPartitionValuesDeleteRequest: ExpectedPartitionValuesDeleteRequest): ExpectedPartitionValuesInformation? { validateExpectedPartitionValuesDeleteRequest(expectedPartitionValuesDeleteRequest) val partitionKeyGroupEntity: PartitionKeyGroupEntity = partitionKeyGroupDaoHelper.getPartitionKeyGroupEntity( expectedPartitionValuesDeleteRequest.getPartitionKeyGroupKey() ) val expectedPartitionValueEntityMap: Map = getExpectedPartitionValueEntityMap(partitionKeyGroupEntity.getExpectedPartitionValues()) val deletedExpectedPartitionValueEntities: MutableCollection = ArrayList() for (expectedPartitionValue in expectedPartitionValuesDeleteRequest.getExpectedPartitionValues()) { val expectedPartitionValueEntity: ExpectedPartitionValueEntity? = expectedPartitionValueEntityMap[expectedPartitionValue] if (expectedPartitionValueEntity != null) { deletedExpectedPartitionValueEntities.add(expectedPartitionValueEntity) } else { throw ObjectNotFoundException( java.lang.String.format( ""Expected partition value \""%s\"" doesn't exist in \""%s\"" partition key group."", expectedPartitionValue, partitionKeyGroupEntity.getPartitionKeyGroupName() ) ) } } for (expectedPartitionValueEntity in deletedExpectedPartitionValueEntities) { partitionKeyGroupEntity.getExpectedPartitionValues() .remove(expectedPartitionValueEntity) } expectedPartitionValueDao.saveAndRefresh(partitionKeyGroupEntity) return createExpectedPartitionValuesInformationFromEntities( partitionKeyGroupEntity, deletedExpectedPartitionValueEntities ) }" Deletes specified expected partition values from an existing partition key group which is identified by name . +"@JvmStatic fun main(args: Array) { DOMTestCase.doMain(hasAttribute01::class.java, args) }" Runs this test from the command line . +"fun launch() { val parentActivity: Activity = ActivityDelegate.getActivityForTabId(mParentId) mLaunchedId = ChromeLauncherActivity.launchDocumentInstance( parentActivity, mIsIncognito, mAsyncParams ) mLaunchTimestamp = SystemClock.elapsedRealtime() run()}" Starts an Activity to with the stored parameters . +"fun unlink(succ: Index): Boolean { return !indexesDeletedNode() && casRight(succ, succ.right) }" Tries to CAS right field to skip over apparent successor succ . Fails ( forcing a retraversal by caller ) if this node is known to be deleted . +"@Throws(IOException::class) fun wrap(reader: LeafReader?, sort: Sort?): LeafReader? { return wrap(reader, org.junit.runner.manipulation.Sorter(sort).sort(reader)) }" "Return a sorted view of < code > reader < /code > according to the order defined by < code > sort < /code > . If the reader is already sorted , this method might return the reader as-is ." +"private fun fillPomsFromChildren( poms: MutableCollection, art: ArtifactInformation, artifacts: Map ): Int { var cnt = 0 for (childId in art.getChildIds()) { val child: ArtifactInformation? = artifacts[childId] if (child != null) { val childName: String = child.getName() if (isPomFileName(childName)) { poms.add(child) ++cnt } } } return cnt }" Fill a collection with all POMs for the children of an artifact . +fun AxisSpace() { this.top = 0.0 this.bottom = 0.0 this.left = 0.0 this.right = 0.0 } Creates a new axis space record . +fun FontConverter(mapper: jdk.internal.module.ModuleLoaderMap.Mapper) { mapper = mapper if (mapper == null) { textAttributeConverter = null } else { textAttributeConverter = TextAttributeConverter() } } Constructs a FontConverter . +"fun typeName(): String? { return ""long"" }" Returns a String description of what kind of entry this is . +"fun d(tag: String?, s: String?) { if (LOG.DEBUG >= LOGLEVEL) Log.d(tag, s) }" Debug log message . +"fun EdgeInfo(start: Int, end: Int, cap: Int) { this(start, end, cap, 0) }" "Construct EdgeInfo from ( start , end ) vertices with given capacity ." +"private fun isSessionPaused(session: FileSharingSession?): Boolean { if (session == null) { throw ServerApiGenericException(""Unable to check if transfer is paused since session with file transfer ID '$mFileTransferId' not available!"") } return session.isFileTransferPaused() }" Is session paused ( only for HTTP transfer ) +private fun processProtein(){} "Implementation of Rob Finn 's algorithm for post processing , translated from Perl to Java . < p/ > Also includes additional code to ensure seed alignments are included as matches , regardless of score ." +"fun execute(timeSeries: MetricTimeSeries, functionValueMap: FunctionValueMap) { if (timeSeries.size() <= 0) { functionValueMap.add(this, Double.NaN) return } val values: DoubleArray = timeSeries.getValuesAsArray() var min = values[0] var max = values[0] for (i in 1 until values.size) { val current = values[i] if (current < min) { min = current } if (current > max) { max = current } } functionValueMap.add(this, Math.abs(max - min)) }" Gets difference between the maximum and the minimum value . It is always a positive value . +private fun returnData(ret: Any) { if (myHost != null) { myHost.returnData(ret) } } Used to communicate a return object from a plugin tool to the main Whitebox user-interface . +"fun ImpliedCovTable(wrapper: SemImWrapper, measured: Boolean, correlations: Boolean) { wrapper = wrapper measured = measured correlations = correlations this.nf = NumberFormatUtil.getInstance().getNumberFormat() if (measured() && covariances()) { matrix = getSemIm().getImplCovarMeas().toArray() } else if (measured() && !covariances()) { matrix = corr(getSemIm().getImplCovarMeas().toArray()) } else if (!measured() && covariances()) { val implCovarC: TetradMatrix = getSemIm().getImplCovar(false) matrix = implCovarC.toArray() } else if (!measured() && !covariances()) { val implCovarC: TetradMatrix = getSemIm().getImplCovar(false) matrix = corr(implCovarC.toArray()) }" "Constructs a new table for the given covariance matrix , the nodes for which are as specified ( in the order they appear in the matrix ) ." +"fun create(): Graphics? { return PSPathGraphics( getDelegate().create() as Graphics2D, java.awt.print.PrinterJob.getPrinterJob(), sun.swing.text.TextComponentPrintable.getPrintable(), getPageFormat(), getPageIndex(), canDoRedraws() ) }" Creates a new < code > Graphics < /code > object that is a copy of this < code > Graphics < /code > object . +"fun deriveThisOrNextChildKey(parent: DeterministicKey?, childNumber: Int): DeterministicKey? { var nAttempts = 0 var child = ChildNumber(childNumber) val isHardened: Boolean = child.isHardened() while (nAttempts < MAX_CHILD_DERIVATION_ATTEMPTS) { try { child = ChildNumber(child.num() + nAttempts, isHardened) return deriveChildKey(parent, child) } catch (ignore: HDDerivationException) { } nAttempts++ } throw HDDerivationException(""Maximum number of child derivation attempts reached, this is probably an indication of a bug."") }" "Derives a key of the `` extended '' child number , ie . with the 0x80000000 bit specifying whether to use hardened derivation or not . If derivation fails , tries a next child ." +fun merge(state: LR1State): LR1State? { val items: HashSet = HashSet() for (item1 in items) { var newItem: LR1Item = item1 val item2: LR1Item = state.getItemByLR0Kernel(item1.getLR0Kernel()) newItem = newItem.merge(item2) items.add(newItem) } return LR1State(items) } "Merges this state with the given one and returns the result . Only works , if both states have equal LR ( 0 ) kernels ." +"@DSComment(""constructor"") @DSSafe(DSCat.SAFE_OTHERS) @DSGenerator( tool_name = ""Doppelganger"",tool_version = ""2.0"", generated_on = ""2013-12-30 12:34:15.039 -0500"", hash_original_method = ""5474E95C495E2BDEA7848B2F1051B5AB"", hash_generated_method = ""1FFFECB7616C84868E8040908FCDEBA5"" ) @Deprecated("""") fun BitmapDrawable(`is`: InputStream) { this(BitmapState(BitmapFactory.decodeStream(`is`)), null) if (mBitmap == null) { Log.w(""BitmapDrawable"", ""BitmapDrawable cannot decode $`is`"") } }" Create a drawable by decoding a bitmap from the given input stream . +"fun toString(cls: Class?,obj: T?,name0: String?,val0: Any,name1: String?,val1: Any,name2: String?,val2: Any): String? {}" Produces auto-generated output of string presentation for given object and its declaration class . +"fun AsyncHttpClient(fixNoHttpResponseException: Boolean, httpPort: Int, httpsPort: Int) { this(getDefaultSchemeRegistry(fixNoHttpResponseException, httpPort, httpsPort)) }" Creates new AsyncHttpClient using given params +"private void extractExtensionHeader ( byte [ ] data , int length , int dataId , RtpPacket packet ) { byte [ ] extensionHeaderData = new byte [ length * 4 ] ; System . arraycopy ( data , ++ dataId , extensionHeaderData , 0 , extensionHeaderData . length ) ; packet . extensionHeader = new RtpExtensionHeader ( ) ; int i = 0 ; while ( packet . extensionHeader . elementsCount ( ) < length ) { byte idAndLength = extensionHeaderData [ i ] ; if ( idAndLength == 0x00 ) { i = i + 1 ; continue ; } int elementId = ( idAndLength & 0xf0 ) > > > 4 ; if ( elementId > 0 && elementId < 15 ) { int elementLength = ( idAndLength & 0x0f ) ; byte [ ] elementData = new byte [ elementLength + 1 ] ; System . arraycopy ( extensionHeaderData , i + 1 , elementData , 0 , elementData . length ) ; packet . extensionHeader . addElement ( elementId , elementData ) ; i = i + elementData . length + 1 ; } else { break ; } } }" Extract Extension Header +"fun showConfirmDialog( ctx: Context?, message: String?, yesListener: DialogInterface.OnClickListener?, noListener: DialogInterface.OnClickListener? ) { showConfirmDialog(ctx, message, yesListener, noListener, R.string.yes, R.string.no) }" Creates a confirmation dialog with Yes-No Button . By default the buttons just dismiss the dialog . +fun TelefoneTextWatcher(callbackErros: EventoDeValidacao?) { setEventoDeValidacao(callbackErros) } TODO Javadoc pendente +"fun RenameResourceProcessor(resource: IResource?) { require(!(resource == null || !resource.exists())) { ""resource must not be null and must exist"" } fResource = resource fRenameArguments = null fUpdateReferences = true setNewResourceName(resource.getName()) }" Creates a new rename resource processor . +fun perform() { } "Perform the operation by calling a function in the Python script . This method adapts each of the inputs into Python objects , calls the Python function , and then converts the outputs of the function back into Java objects and assigns them to the outputs array . The Python function should return a tuple , list , or other sequence containing the outputs . If there is only one output , it can just return a value . Either way , the number of inputs and outputs should match up with the number of parameters and return values of the function ." +"@Throws(JMSException::class) fun createConnectionConsumer( connection: Connection, destination: Destination?, ssp: ServerSessionPool? ): ConnectionConsumer? { return connection.createConnectionConsumer(destination, null, ssp, 1) }" Creates a connection for a consumer . +"fun covarianceMatrix( data1: Array, data2: Array, delay: Int ): Array? { }" "Compute the covariance matrix between all column pairs ( variables ) in the multivariate data set , which consists of two separate multivariate vectors ." +"fun isProcessed(): Boolean { val oo: Any = get_Value(COLUMNNAME_Processed) return if (oo != null) { if (oo is Boolean) oo.toBoolean() else ""Y"" == oo } else false }" Get Processed . +"private fun quickSort1(x: CharArray, off: Int, len: Int, comp: CharComparator) { }" Sorts the specified sub-array of chars into ascending order . +@Throws(NullPointerException::class) fun Sound(@Nonnull path: String?) { this(FileUtil.findURL(path)) } Create a Sound object using the media file at path +"fun hasGwtFacet(project: IProject?): Boolean { var hasFacet = false try { hasFacet = FacetedProjectFramework.hasProjectFacet(project, ""com.gwtplugins.gwt.facet"") } catch (e: CoreException) { CorePluginLog.logInfo(""hasGetFacet: Error, can't figure GWT facet."", e) } return hasFacet }" Returns if this project has a GWT facet . TODO use extension point to get query GwtWtpPlugin ... +"public Yytoken yylex ( ) throws java . io . IOException , ParseException { int zzInput ; int zzAction ; int zzCurrentPosL ; int zzMarkedPosL ; int zzEndReadL = zzEndRead ; char [ ] zzBufferL = zzBuffer ; char [ ] zzCMapL = ZZ_CMAP ; int [ ] zzTransL = ZZ_TRANS ; int [ ] zzRowMapL = ZZ_ROWMAP ; int [ ] zzAttrL = ZZ_ATTRIBUTE ; while ( true ) { zzMarkedPosL = zzMarkedPos ; yychar += zzMarkedPosL - zzStartRead ; zzAction = - 1 ; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL ; zzState = ZZ_LEXSTATE [ zzLexicalState ] ; zzForAction : { while ( true ) { if ( zzCurrentPosL < zzEndReadL ) zzInput = zzBufferL [ zzCurrentPosL ++ ] ; else if ( zzAtEOF ) { zzInput = YYEOF ; break zzForAction ; } else { zzCurrentPos = zzCurrentPosL ; zzMarkedPos = zzMarkedPosL ; boolean eof = zzRefill ( ) ; zzCurrentPosL = zzCurrentPos ; zzMarkedPosL = zzMarkedPos ; zzBufferL = zzBuffer ; zzEndReadL = zzEndRead ; if ( eof ) { zzInput = YYEOF ; break zzForAction ; } else { zzInput = zzBufferL [ zzCurrentPosL ++ ] ; } } int zzNext = zzTransL [ zzRowMapL [ zzState ] + zzCMapL [ zzInput ] ] ; if ( zzNext == - 1 ) break zzForAction ; zzState = zzNext ; int zzAttributes = zzAttrL [ zzState ] ; if ( ( zzAttributes & 1 ) == 1 ) { zzAction = zzState ; zzMarkedPosL = zzCurrentPosL ; if ( ( zzAttributes & 8 ) == 8 ) break zzForAction ; } } } zzMarkedPos = zzMarkedPosL ; switch ( zzAction < 0 ? zzAction : ZZ_ACTION [ zzAction ] ) { case 11 : { sb . append ( yytext ( ) ) ; } case 25 : break ; case 4 : { sb . delete ( 0 , sb . length ( ) ) ; yybegin ( STRING_BEGIN ) ; } case 26 : break ; case 16 : { sb . append ( '\b' ) ; } case 27 : break ; case 6 : { return new Yytoken ( Yytoken . TYPE_RIGHT_BRACE , null ) ; } case 28 : break ; case 23 : { Boolean val = Boolean . valueOf ( yytext ( ) ) ; return new Yytoken ( Yytoken . TYPE_VALUE , val ) ; } case 29 : break ; case 22 : { return new Yytoken ( Yytoken . TYPE_VALUE , null ) ; } case 30 : break ; case 13 : { yybegin ( YYINITIAL ) ; return new Yytoken ( Yytoken . TYPE_VALUE , sb . toString ( ) ) ; } case 31 : break ; case 12 : { sb . append ( '\\' ) ; } case 32 : break ; case 21 : { Double val = Double . valueOf ( yytext ( ) ) ; return new Yytoken ( Yytoken . TYPE_VALUE , val ) ; } case 33 : break ; case 1 : { throw new ParseException ( yychar , ParseException . ERROR_UNEXPECTED_CHAR , new Character ( yycharat ( 0 ) ) ) ; } case 34 : break ; case 8 : { return new Yytoken ( Yytoken . TYPE_RIGHT_SQUARE , null ) ; } case 35 : break ; case 19 : { sb . append ( '\r' ) ; } case 36 : break ; case 15 : { sb . append ( '/' ) ; } case 37 : break ; case 10 : { return new Yytoken ( Yytoken . TYPE_COLON , null ) ; } case 38 : break ; case 14 : { sb . append ( '""' ) ; } case 39 : break ; case 5 : { return new Yytoken ( Yytoken . TYPE_LEFT_BRACE , null ) ; } case 40 : break ; case 17 : { sb . append ( '\f' ) ; } case 41 : break ; case 24 : { try { int ch = Integer . parseInt ( yytext ( ) . substring ( 2 ) , 16 ) ; sb . append ( ( char ) ch ) ; } catch ( Exception e ) { throw new ParseException ( yychar , ParseException . ERROR_UNEXPECTED_EXCEPTION , e ) ; } } case 42 : break ; case 20 : { sb . append ( '\t' ) ; } case 43 : break ; case 7 : { return new Yytoken ( Yytoken . TYPE_LEFT_SQUARE , null ) ; } case 44 : break ; case 2 : { Long val = Long . valueOf ( yytext ( ) ) ; return new Yytoken ( Yytoken . TYPE_VALUE , val ) ; } case 45 : break ; case 18 : { sb . append ( '\n' ) ; } case 46 : break ; case 9 : { return new Yytoken ( Yytoken . TYPE_COMMA , null ) ; } case 47 : break ; case 3 : { } case 48 : break ; default : if ( zzInput == YYEOF && zzStartRead == zzCurrentPos ) { zzAtEOF = true ; return null ; } else { zzScanError ( ZZ_NO_MATCH ) ; } } } }" "Resumes scanning until the next regular expression is matched , the end of input is encountered or an I/O-Error occurs ." + @Throws(IOException::class) fun encode(out: OutputStream) { val tmp: sun.security.util.DerOutputStream = sun.security.util.DerOutputStream() if (extensionValue == null) { extensionId = sun.security.x509.PKIXExtensions.PolicyConstraints_Id critical = false encodeThis() } super.encode(tmp) out.write(tmp.toByteArray()) } Write the extension to the DerOutputStream . +" fun ?> introSort(a: Array?, fromIndex: Int, toIndex: Int) { if (toIndex - fromIndex <= 1) return introSort(a, fromIndex, toIndex, Comparator.naturalOrder()) }" "Sorts the given array slice in natural order . This method uses the intro sort algorithm , but falls back to insertion sort for small arrays ." +" @Throws(IOException::class) fun deleteLabel(projectId: Serializable?, label: GitlabLabel) { deleteLabel(projectId, label.getName()) }" Deletes an existing label . +" @Throws(ServiceException::class, IOException::class) private fun createSingleEvent( service: CalendarService, eventTitle: String, eventContent: String ): CalendarEventEntry? { return createEvent(service, eventTitle, eventContent, null, false.toInt(), null) }" Creates a single-occurrence event . +" @Throws(Exception::class) fun testParams() { val sim: ClassicSimilarity = getSimilarity(""text_overlap"", ClassicSimilarity::class.java) assertEquals(false, sim.getDiscountOverlaps()) }" Classic w/ explicit params + fun registerRecipes() { registerRecipeClasses() addCraftingRecipes() addBrewingRecipes() } Add this mod 's recipes . +fun taxApplies(): Boolean { val product: GenericValue = com.sun.org.apache.xml.internal.serializer.Version.getProduct() return if (product != null) { ProductWorker.taxApplies(product) } else { true } } Returns true if tax charges apply to this item . +"@Action(value = ""/receipts/challan-printChallan"") fun printChallan(): String? { try { reportId = collectionCommon.generateChallan(receiptHeader, true) } catch (e: Exception) { LOGGER.error(CollectionConstants.REPORT_GENERATION_ERROR, e) throw ApplicationRuntimeException(CollectionConstants.REPORT_GENERATION_ERROR, e) } setSourcePage(""viewChallan"") return CollectionConstants.REPORT }" This method generates the report for the requested challan +"fun testIsMultiValued() { val meta = SpellCheckedMetadata() assertFalse(meta.isMultiValued(""key"")) meta.add(""key"", ""value1"") assertFalse(meta.isMultiValued(""key"")) meta.add(""key"", ""value2"") assertTrue(meta.isMultiValued(""key"")) }" Test for < code > isMultiValued ( ) < /code > method . +fun InitializeLoginAction() {} Instantiates a new login action . +"fun Instrument( soundbank: javax.sound.midi.Soundbank?, patch: javax.sound.midi.Patch, name: String?, dataClass: Class<*>? ) { super(soundbank, name, dataClass) this.patch = patch }" "Constructs a new MIDI instrument from the specified < code > Patch < /code > . When a subsequent request is made to load the instrument , the sound bank will search its contents for this instrument 's < code > Patch < /code > , and the instrument will be loaded into the synthesizer at the bank and program location indicated by the < code > Patch < /code > object ." +"private fun putBytes( tgtBytes: ByteArray, tgtOffset: Int, srcBytes: ByteArray, srcOffset: Int, srcLength: Int ): Int { System.arraycopy(srcBytes, srcOffset, tgtBytes, tgtOffset, srcLength) return tgtOffset + srcLength }" Put bytes at the specified byte array position . +"fun HighlightTextView(context: Context?) { this(context, null) }" Instantiates a new Highlight text view . +fun trim() {} Does nothing . +fun reset(data: ByteArray) { pos = 0 mark = 0 buf = data count = data.size } Resets this < tt > BytesInputStream < /tt > using the given byte [ ] as new input buffer . +"fun ofObject( target: T, property: Property?, evaluator: TypeEvaluator?, vararg values: V ): ObjectAnimator? { val anim = ObjectAnimator(target, property) anim.setObjectValues(*values) anim.setEvaluator(evaluator) return anim }" "Constructs and returns an ObjectAnimator that animates between Object values . A single value implies that that value is the one being animated to . Two values imply a starting and ending values . More than two values imply a starting value , values to animate through along the way , and an ending value ( these values will be distributed evenly across the duration of the animation ) ." +private fun updateProgress(progress: Int) { if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress) } previousProgress = progress } Used to communicate a progress update between a plugin tool and the main Whitebox user interface . +"fun execUpdateGeo( context: Context, latitude: Double, longitude: Double, selectedItems: SelectedFiles? ): Int { val where = QueryParameter() setWhereSelectionPaths(where, selectedItems) val values = ContentValues(2) values.put(SQL_COL_LAT, DirectoryFormatter.parseLatLon(latitude)) values.put(SQL_COL_LON, DirectoryFormatter.parseLatLon(longitude)) val resolver: ContentResolver = context.getContentResolver() return resolver.update( SQL_TABLE_EXTERNAL_CONTENT_URI, values, where.toAndroidWhere(), where.toAndroidParameters() ) }" Write geo data ( lat/lon ) media database. < br/ > +fun reset() { windowedBlockStream.reset() } reset the environment to reuse the resource . +"@Throws(InternalTranslationException::class) fun generate( environment: ITranslationEnvironment, offset: Long, instructions: MutableList ): Pair? { Preconditions.checkNotNull(environment, ""Error: Argument environment can't be null"") Preconditions.checkNotNull(instructions, ""Error: Argument instructions can't be null"") Preconditions.checkArgument(offset >= 0, ""Error: Argument offset can't be less than 0"") val connected: String = environment.getNextVariableString() val negated: String = environment.getNextVariableString() instructions.add( ReilHelpers.createXor( offset, org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, SyncStateContract.Helpers.SIGN_FLAG, org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, SyncStateContract.Helpers.OVERFLOW_FLAG, org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, connected ) ) instructions.add( ReilHelpers.createXor( offset + 1, org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, connected, org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, ""1"", org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, negated ) ) return Pair( org.graalvm.compiler.asm.amd64.AMD64Assembler.OperandSize.BYTE, negated ) }" Generates code for the NotLess condition . +fun isFinished(): Boolean { return isCompleted() || isFailed() || isCanceled() } "< p > Finished means it is either completed , failed or canceled. < /p >" +"private fun drawBackground() { val rect: java.awt.Rectangle = getClientArea() cachedGC.setForeground(gradientStart) cachedGC.setBackground(gradientEnd) cachedGC.fillGradientRectangle(rect.x, rect.y, rect.width, rect.height / 2, true) cachedGC.setForeground(gradientEnd) cachedGC.setBackground(gradientStart) cachedGC.fillGradientRectangle(rect.x, rect.height / 2, rect.width, rect.height / 2, true) }" Draw the background +"fun read(buf: ByteArray) { var numToRead = buf.size if (position + numToRead > buffer.length) { numToRead = buffer.length - position System.arraycopy(buffer, position, buf, 0, numToRead) for (i in numToRead until buf.size) { buf[i] = 0 } } else { System.arraycopy(buffer, position, buf, 0, numToRead) } position += numToRead }" Reads up to < tt > buf.length < /tt > bytes from the stream into the given byte buffer . +fun QueryExecutionTimeoutException(msg: String?) { super(msg) } Constructs an instance of < code > QueryExecutionTimeoutException < /code > with the specified detail message . +"private fun displayInternalServerError() { alertDialog = CommonDialogUtils.getAlertDialogWithOneButtonAndTitle( context, getResources().getString(R.string.title_head_connection_error), getResources().getString(R.string.error_internal_server), getResources().getString(R.string.button_ok), null ) alertDialog.show() }" Displays an internal server error message to the user . +"fun updateOrdering(database: SQLiteDatabase, originalPosition: Long, newPosition: Long) { Log.d(""ItemDAO"", ""original: $originalPosition, newPosition:$newPosition"") if (originalPosition > newPosition) { database.execSQL( UPDATE_ORDER_MORE, arrayOf(newPosition.toString(), originalPosition.toString()) ) } else { database.execSQL( UPDATE_ORDER_LESS, arrayOf(originalPosition.toString(), newPosition.toString()) ) } }" Updates the orderings between the original and new positions +fun onAdChanged() { notifyDataSetChanged() } Raised when the number of ads have changed . Adapters that implement this class should notify their data views that the dataset has changed . +"@Throws(IOException::class) fun createSocket(host: InetAddress?, port: Int): Socket { val socket: Socket = createSocket() connectSocket(socket, InetSocketAddress(host, port)) return socket }" Creates a socket and connect it to the specified remote address on the specified remote port . +@Throws(Exception::class) fun openExistingFileForWrite(name: String?): sun.rmi.log.ReliableLog.LogFile? { val logfile = File(name) val tf: sun.rmi.log.ReliableLog.LogFile = sun.rmi.log.ReliableLog.LogFile(logfile) tf.openWrite() return tf } Open an existing file for writing . +fun AgeGreaterThanCondition(age: Int) { this.age = age } Creates a new AgeGreaterThanCondition . +"@ DSComment ( ""Private Method"" ) @ DSBan ( DSCat . PRIVATE_METHOD ) @ DSGenerator ( tool_name = ""Doppelganger"" , tool_version = ""2.0"" , generated_on = ""2013-12-30 12:57:24.266 -0500"" , hash_original_method = ""542A19C49303D6524BE63DEB812200B5"" , hash_generated_method = ""433131C2E635F21E7867A70992F1749C"" ) private ComparableTimSort ( Object [ ] a ) { this . a = a ; int len = a . length ; @ SuppressWarnings ( { ""unchecked"" , ""UnnecessaryLocalVariable"" } ) Object [ ] newArray = new Object [ len < 2 * INITIAL_TMP_STORAGE_LENGTH ? len > > > 1 : INITIAL_TMP_STORAGE_LENGTH ] ; tmp = newArray ; int stackLen = ( len < 120 ? 5 : len < 1542 ? 10 : len < 119151 ? 19 : 40 ) ; runBase = new int [ stackLen ] ; runLen = new int [ stackLen ] ; }" Creates a TimSort instance to maintain the state of an ongoing sort . +"fun compare(left: Date, right: Double): Int { return compare( left.getTime() / 1000, DateTimeUtil.getInstance().toDateTime(right).getTime() / 1000 ) }" compares a Date with a double +fun removeGraphNode(node: SpaceEffGraphNode) { if (node === _firstNode) { if (node === _lastNode) { _lastNode = null _firstNode = _lastNode } else { _firstNode = node.getNext() } } else if (node === _lastNode) { _lastNode = node.getPrev() } node.remove() numberOfNodes-- } Remove a node from the graph . +"fun fromJSONString(jsonString: String?, selectAs: String?): JSONProperty? { return fromJSONFunction(jdk.nashorn.internal.runtime.JSONFunctions.json(jsonString), selectAs) }" "Construct a JSONProperty from a JSON string and with the given alias , e.g . `` 'hello ' AS greeting '' . This is a convenience method equivalent to < code > fromJSONFunction ( JSONFunctions.json ( jsonString ) , selectAs ) < /code >" +"fun addGroupChatComposingStatus(chatId: String?, status: Boolean) { synchronized(getImsServiceSessionOperationLock()) { mGroupChatComposingStatusToNotify.put( chatId, status ) } }" Adds the group chat composing status to the map to enable re-sending upon media session restart +"@Throws(IOException::class) fun createCmds(runConfiguration: ChromeRunnerRunOptions): Array? { val commands: ArrayList = ArrayList() commands.add(nodeJsBinary.get().getBinaryAbsolutePath()) val nodeOptions = System.getProperty(NODE_OPTIONS) if (nodeOptions != null) { for (nodeOption in nodeOptions.split("" "".toRegex()).dropLastWhile { it.isEmpty() } .toTypedArray()) { commands.add(nodeOption) } } val elfData: StringBuilder = getELFCode( runConfiguration.getInitModules(), runConfiguration.getExecModule(), runConfiguration.getExecutionData() ) val elf: File = createTempFileFor(elfData.toString()) commands.add(elf.getCanonicalPath()) return commands.toArray(arrayOf()) }" "Creates commands for calling Node.js on command line . Data wrapped in passed parameter is used to configure node itself , and to generate file that will be executed by Node ." +"fun mulComponentWise(other: Matrix4x3dc?): Matrix4x3d? { return mulComponentWise(other, this) }" Component-wise multiply < code > this < /code > by < code > other < /code > . +"@Throws(Exception::class) fun testTypes() { try { this.stmt.execute(""DROP TABLE IF EXISTS typesRegressTest"") this.stmt.execute(""CREATE TABLE typesRegressTest (varcharField VARCHAR(32), charField CHAR(2), enumField ENUM('1','2'),"" + ""setField SET('1','2','3'), tinyblobField TINYBLOB, mediumBlobField MEDIUMBLOB, longblobField LONGBLOB, blobField BLOB)"") this.rs = this.stmt.executeQuery(""SELECT * from typesRegressTest"") val rsmd: ResultSetMetaData = this.rs.getMetaData() val numCols: Int = rsmd.getColumnCount() for (i in 0 until numCols) { val columnName: String = rsmd.getColumnName(i + 1) val columnTypeName: String = rsmd.getColumnTypeName(i + 1) println(""$columnName -> $columnTypeName"") } } finally { this.stmt.execute(""DROP TABLE IF EXISTS typesRegressTest"") } }" Tests for types being returned correctly +"fun deleteFile(context: Context, file: File): Boolean { var success: Boolean = file.delete() if (!success && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val document: DocumentFile = getDocumentFile(context, file, false, false) success = document != null && document.delete() } if (!success && Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { val resolver: ContentResolver = context.getContentResolver() success = try { val uri: Uri? = null if (uri != null) { resolver.delete(uri, null, null) } !file.exists() } catch (e: Exception) { Log.e(TAG, ""Error when deleting file "" + file.getAbsolutePath(), e) return false } } if (success) scanFile(context, arrayOf(file.getPath())) return success }" Delete a file . May be even on external SD card . +"fun displayInfoLine(infoLine: String?, labelDesignator: Int) { if (infoLineHolder != null) { setLabel( if (infoLine != null && infoLine.length > 0) infoLine else fudgeString, labelDesignator ) } }" Display a line of text in a designated info line . +"fun addMember( parentType: sun.reflect.generics.tree.BaseType?, memberType: sun.reflect.generics.tree.BaseType? ): DependenceResult? { Preconditions.checkNotNull(parentType, ""IE02762: Parent type can not be null."") Preconditions.checkNotNull(memberType, ""IE02763: Member type can not be null."") val memberTypeNode: Node = Preconditions.checkNotNull( containedRelationMap.get(memberType), ""Type node for member type must exist prior to adding a member."" ) val parentNode: Node = Preconditions.checkNotNull( containedRelationMap.get(parentType), ""Type node for member parent must exist prior to adding a member"" ) if (willCreateCycle(parentType, memberType)) { return DependenceResult(false, ImmutableSet.of()) } containedRelation.createEdge(memberTypeNode, parentNode) val search = TypeSearch(containedRelationMap.inverse()) search.start(containedRelation, containedRelationMap.get(parentType)) return DependenceResult(true, search.getDependentTypes()) }" Adds a member to the dependence graph and returns the set of base types that are affected by the changed compound type . This method assumes that all base type nodes that correspond to the member base type already exist . +"int [ ] decodeStart ( BitArray row ) throws NotFoundException { int endStart = skipWhiteSpace ( row ) ; int [ ] startPattern = findGuardPattern ( row , endStart , START_PATTERN ) ; this . narrowLineWidth = ( startPattern [ 1 ] - startPattern [ 0 ] ) > > 2 ; validateQuietZone ( row , startPattern [ 0 ] ) ; return startPattern ; } " Identify where the start of the middle / payload section starts . +"fun contains(array: IntArray?, value: Int): Boolean { return indexOf(array, value) !== -1 }" Returns < code > true < /code > if an array contains given value . +fun acosh(value: Double): Double { if (value <= 1.0) { return if (ANTI_JIT_OPTIM_CRASH_ON_NAN) { if (value < 1.0) Double.NaN else value - 1.0 } else { if (value == 1.0) 0.0 else Double.NaN } } val result: Double if (value < ASINH_ACOSH_SQRT_ELISION_THRESHOLD) { result = log(value + sqrt(value * value - 1.0)) } else { result = LOG_2 + log(value) } return result } "Some properties of acosh ( x ) = log ( x + sqrt ( x^2 - 1 ) ) : 1 ) defined on [ 1 , +Infinity [ 2 ) result in ] 0 , +Infinity [ ( by convention , since cosh ( x ) = cosh ( -x ) ) 3 ) acosh ( 1 ) = 0 4 ) acosh ( 1+epsilon ) ~= log ( 1 + sqrt ( 2*epsilon ) ) ~= sqrt ( 2*epsilon ) 5 ) lim ( acosh ( x ) , x- > +Infinity ) = +Infinity ( y increasing logarithmically slower than x )" +"fun fireDataStatusEEvent(AD_Message: String?, info: String?, isError: Boolean) { m_mTable.fireDataStatusEEvent(AD_Message, info, isError) }" Create and fire Data Status Error Event +"fun AttributeDefinition(attrs: TextAttributeSet, beginIndex: Int, endIndex: Int) { this.attrs = attrs this.beginIndex = beginIndex this.endIndex = endIndex }" Create new AttributeDefinition . +fun consumeGreedy(greedyToken: String) { if (greedyToken.length < sval.length()) { pushBack() setStartPosition(getStartPosition() + greedyToken.length) sval = sval.substring(greedyToken.length) } } Consumes a substring from the current sval of the StreamPosTokenizer . +@Throws(HexFormatException::class) fun hexToDecimal(hex: String): Int { var decimalValue = 0 for (i in 0 until hex.length) { if (!(hex[i] >= '0' && hex[i] <= '9' || hex[i] >= 'A' && hex[i] <= 'F')) throw HexFormatException( hex ) val hexChar = hex[i] decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar) } return decimalValue } Converts a hex string into a decimal number and throws a HexFormatException if the string is not a hex string +"@Throws(NotFoundException::class, ChecksumException::class, FormatException::class) fun decode(image: BinaryBitmap?): Result? { return decode(image, null) }" Locates and decodes a QR code in an image . +"fun listRawBackup(ignore: Boolean): BackupFileSet? { val clusterBackupFiles = BackupFileSet(this.quorumSize) val errorList: List = ArrayList() try { val backupTasks: List>> = BackupProcessor(getHosts(), Arrays.asList(ports.get(2)), null).process( ListBackupCallable(), false ) var result: Throwable? = null for (task in backupTasks) { try { clusterBackupFiles.addAll( task.getResponse().getFuture().get(), task.getRequest().getNode() ) log.info(""List backup on node({})success"", task.getRequest().getHost()) } catch (e: CancellationException) { log.warn( ""The task of listing backup on node({}) was canceled"", task.getRequest().getHost(), e ) } catch (e: InterruptedException) { log.error( java.lang.String.format( ""List backup on node(%s:%d) failed"", task.getRequest().getHost(), task.getRequest().getPort() ), e ) result = result ?: e errorList.add(task.getRequest().getNode()) } catch (e: ExecutionException) { val cause: Throwable = e.getCause() if (ignore) { log.warn( java.lang.String.format( ""List backup on node(%s:%d) failed."", task.getRequest().getHost(), task.getRequest().getPort() ), cause ) } else { log.error( java.lang.String.format( ""List backup on node(%s:%d) failed."", task.getRequest().getHost(), task.getRequest().getPort() ), cause ) } result = result ?: cause errorList.add(task.getRequest().getNode()) } } if (result != null) { if (result is Exception) { throw (result as Exception?)!! } else { throw Exception(result) } } } catch (e: Exception) { val cause = if (e.cause == null) e else e.cause!! if (ignore) { log.warn( ""List backup on nodes({}) failed, but ignore the errors"", errorList.toString(), cause ) } else { log.error(""Exception when listing backups"", e) throw BackupException.fatals.failedToListBackup(errorList.toString(), cause) } } return clusterBackupFiles }" Get a list of backup sets info +"fun CountingIdlingResource(resourceName: String, debugCounting: Boolean) { require(!TextUtils.isEmpty(resourceName)) { ""Resource name must not be empty or null"" } this.resourceName = resourceName this.debugCounting = debugCounting }" Creates a CountingIdlingResource . +"fun create(thisSize: String): ImageReuseInfo? { val list = ArrayList() var canBeReused = false for (i in 0 until mSizeList.length) { val size: String = mSizeList.get(i) if (!canBeReused && thisSize == size) { canBeReused = true continue } if (canBeReused && thisSize != size) { list.add(size) } } return if (list.size() === 0) { ImageReuseInfo(thisSize, null) } else { val sizeList = arrayOfNulls(list.size()) list.toArray(sizeList) ImageReuseInfo(thisSize, sizeList) } }" Find out the size list can be re-sued . +"fun sync(address: Address?, size: Int) { SysCall.sysCall.sysSyncCache(address, size) }" Synchronize a region of memory : force data in dcache to be written out to main memory so that it will be seen by icache when instructions are fetched back . +"fun MonthDateFormat(locale: Locale?) { this(TimeZone.getDefault(), locale, 1, true, false) }" Creates a new instance for the specified time zone . +"fun testConnectorSecuritySettingsSSL_alias_not_defined() { resetSecuritySystemProperties() var authInfo: sun.net.www.protocol.http.AuthenticationInfo? = null try { authInfo = SecurityHelper.loadAuthenticationInformation( ""test.ssl.alias.not.defined.security.properties"", true, TUNGSTEN_APPLICATION_NAME.CONNECTOR ) } catch (e: java.rmi.ServerRuntimeException) { assertTrue(""There should not be any exception thrown"", false) } catch (e: javax.naming.ConfigurationException) { assertFalse(""That should not be this kind of Exception being thrown"", true) } resetSecuritySystemProperties() }" Confirm behavior when connector.security.use.SSL=true and alias are not defined This shows that it uses first alias it finds +"@Synchronized fun add(x: Double, y: Double) { add(x, y, 0.0) }" Adds a new value to the series . +"@Synchronized fun add(x: Double, y: Double) { add(x, y, 0.0) }" This method is called when a fatal error occurs during parsing . This method rethrows the exception +"fun run() { amIActive = true if (args.length < 2) { showFeedback(""Plugin parameters have not been set properly."") return } val inputHeader: String = args.get(0) val outputHeader: String = args.get(1) if (inputHeader == null || outputHeader == null) { showFeedback(""One or more of the input parameters have not been set properly."") return } try { var row: Int var col: Int var z: Double var progress: Int var oldProgress = -1 var data: DoubleArray val inputFile = WhiteboxRaster(inputHeader, ""r"") val rows: Int = inputFile.getNumberRows() val cols: Int = inputFile.getNumberColumns() val noData: Double = inputFile.getNoDataValue() val outputFile = WhiteboxRaster(outputHeader, ""rw"", inputHeader, WhiteboxRaster.DataType.FLOAT, noData) outputFile.setPreferredPalette(inputFile.getPreferredPalette()) row = 0 while (row < rows) { data = inputFile.getRowValues(row) col = 0 while (col < cols) { z = data[col] if (z != noData) { outputFile.setValue(row, col, Math.asin(z)) } col++ } progress = (100f * row / (rows - 1)).toInt() if (progress != oldProgress) { oldProgress = progress updateProgress(progress) if (cancelOp) { cancelOperation() return } } row++ } outputFile.addMetadataEntry(""Created by the "" + getDescriptiveName() + "" tool."") outputFile.addMetadataEntry(""Created on "" + Date()) inputFile.close() outputFile.close() returnData(outputHeader) } catch (oe: OutOfMemoryError) { myHost.showFeedback(""An out-of-memory error has occurred during operation."") } catch (e: Exception) { myHost.showFeedback(""An error has occurred during operation. See log file for details."") myHost.logException(""Error in "" + getDescriptiveName(), e) } finally { updateProgress(""Progress: "", 0) amIActive = false myHost.pluginComplete() } }" Used to execute this plugin tool . +"fun addMoreComponents(cnt: Container, components: Array?, areThereMore: Boolean) { val ia: InfiniteScrollAdapter = cnt.getClientProperty(""cn1\$infinite"") as InfiniteScrollAdapter ia.addMoreComponents(components, areThereMore) }" "Invoke this method to add additional components to the container , if you use addComponent/removeComponent you will get undefined behavior . This is a convenience method saving the need to keep the InfiniteScrollAdapter as a variable" +fun progress(texture: CCTexture2D?): CCProgressTimer? { return CCProgressTimer(texture) } Creates a progress timer with the texture as the shape the timer goes through +fun EntityMappingModelImpl() { super() } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +fun match(): MatchResult? { check(matchSuccessful) return matcher.toMatchResult() } Returns the result of the last matching operation . < p > The next* and find* methods return the match result in the case of a successful match . +"fun dispatch(event: IEvent) { val eventType: Class = event.getClass() Discord4J.logger.debug(""Dispatching event of type {}."", eventType.simpleName) if (listenerMap.containsKey(eventType)) { for (listener in listenerMap.get(eventType)) { listener.receive(event) } } }" Sends an IEvent to all listeners that listen for that specific event . +fun createMouthComboBox(): javax.swing.JComboBox? { val cb: javax.swing.JComboBox = javax.swing.JComboBox() fillComboBox(cb) cb.addActionListener(this) return cb } Creates the mouth combo box . +"fun leverageForRule( premise: AprioriItemSet?, consequence: AprioriItemSet, premiseCount: Int, consequenceCount: Int ): Double { val coverageForItemSet = consequence.m_counter as Double / m_totalTransactions as Double val expectedCoverageIfIndependent = premiseCount.toDouble() / m_totalTransactions as Double * (consequenceCount.toDouble() / m_totalTransactions as Double) return coverageForItemSet - expectedCoverageIfIndependent }" Outputs the leverage for a rule . Leverage is defined as : < br > prob ( premise & consequence ) - ( prob ( premise ) * prob ( consequence ) ) +"fun RdKNNNode(capacity: Int, isLeaf: Boolean) { super(capacity, isLeaf, RdKNNEntry::class.java) }" Creates a new RdKNNNode object . +private fun adaptGridViewHeight() { if (gridView is DividableGridView) { (gridView as DividableGridView).adaptHeightToChildren() } } "Adapts the height of the grid view , which is used to show the bottom sheet 's items ." +fun validateOnStatus() { if (Command.STATUS.equals(getCommand())) { } } Validates the arguments passed to the Builder when the 'status ' command has been issued . +fun eagerCheck(): Optional? { return Optional.ofNullable(this.eagerCheck) } whether check errors as more as possible +"fun newInstance(song: Song?): NewPlaylistFragment? { val fragment = NewPlaylistFragment() val bundle = Bundle() bundle.putParcelable(KEY_SONG, song) fragment.setArguments(bundle) return fragment }" Creates a new instance of the New Playlist dialog fragment to create a new playlist and add a song to it . +"@DSSink([DSSinkKind.LOG]) @DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2013-12-30 12:29:19.771 -0500"", hash_original_method = ""06AF2B97EC9C8BBE1303A237FE727449"", hash_generated_method = ""103A7E1B02C228D1981B721CBC7DAC4C"" ) fun updateCursor(view: View, left: Int, top: Int, right: Int, bottom: Int) { checkFocus() synchronized(mH) { if (mServedView !== view && (mServedView == null || !mServedView.checkInputConnectionProxy( view )) || mCurrentTextBoxAttribute == null || mCurMethod == null ) { return } mTmpCursorRect.set(left, top, right, bottom) if (!mCursorRect.equals(mTmpCursorRect)) { if (DEBUG) Log.d(TAG, ""updateCursor"") try { if (DEBUG) Log.v(TAG, ""CURSOR CHANGE: $mCurMethod"") mCurMethod.updateCursor(mTmpCursorRect) mCursorRect.set(mTmpCursorRect) } catch (e: RemoteException) { Log.w(TAG, ""IME died: $mCurId"", e) } } } }" Report the current cursor location in its window . +"fun buildTextAnnotation( corpusId: String?, textId: String?, text: String?, tokens: Array, sentenceEndPositions: IntArray, sentenceViewGenerator: String?, sentenceViewScore: Double ): TextAnnotation? { require(sentenceEndPositions[sentenceEndPositions.size - 1] == tokens.size) { ""Invalid sentence boundary. Last element should be the number of tokens"" } val offsets: Array = TokenUtils.getTokenOffsets(text, tokens) assert(offsets.size == tokens.size) val ta = TextAnnotation(corpusId, textId, text, offsets, tokens, sentenceEndPositions) val view = SpanLabelView(ViewNames.SENTENCE, sentenceViewGenerator, ta, sentenceViewScore) var start = 0 for (s in sentenceEndPositions) { view.addSpanLabel(start, s, ViewNames.SENTENCE, 1.0) start = s } ta.addView(ViewNames.SENTENCE, view) val tokView = SpanLabelView(ViewNames.TOKENS, sentenceViewGenerator, ta, sentenceViewScore) for (tokIndex in tokens.indices) { tokView.addSpanLabel(tokIndex, tokIndex + 1, tokens[tokIndex], 1.0) } ta.addView(ViewNames.TOKENS, tokView) return ta }" instantiate a TextAnnotation using a SentenceViewGenerator to create an explicit Sentence view +"import java.util.* private fun guessContentType(url: String): String? { var url = url url = url.lowercase(Locale.getDefault()) return if (url.endsWith("".webm"")) { ""video/webm"" } else if (url.endsWith("".mp4"")) { ""video/mp4"" } else if (url.matches("".*\\.jpe?g"")) { ""image/jpeg"" } else if (url.endsWith("".png"")) { ""image/png"" } else if (url.endsWith("".gif"")) { ""image/gif"" } else { ""application/octet-stream"" } }" Guess a content type from the URL . +"fun FilteredTollHandler(simulationEndTime: Double, numberOfTimeBins: Int) { this(simulationEndTime, numberOfTimeBins, null, null) LOGGER.info(""No filtering is used, result will include all links, persons from all user groups."") }" "No filtering will be used , result will include all links , persons from all user groups ." +fun isSecondHandVisible(): Boolean { return secondHandVisible } Return secondHandVisible +"fun addStylesheet(href: String?, type: String?): XMLDocument? { val pi = PI() pi.setTarget(""xml-stylesheet"").addInstruction(""href"", href).addInstruction(""type"", type) prolog.addElement(pi) return this }" This adds a stylesheet to the XML document . +"fun GenericMTreeDistanceSearchCandidate(mindist: Double, nodeID: Int, routingObjectID: DBID?) { this.mindist = mindist this.nodeID = nodeID this.routingObjectID = routingObjectID }" Creates a new heap node with the specified parameters . +"private fun lf_delta1(x: Int): Int { return lf_S(x, 17) xor lf_S(x, 19) xor lf_R(x, 10) }" logical function delta1 ( x ) - xor of results of right shifts/rotations +"fun extractBestMaxRuleParse(start: Int, end: Int, sentence: List?): Tree? { return extractBestMaxRuleParse1(start, end, 0, sentence) }" "Returns the best parse , the one with maximum expected labelled recall . Assumes that the maxc* arrays have been filled ." +"fun lastIndexOf(ch: Char): Int { return lastIndexOf(ch, size - 1) }" Searches the string builder to find the last reference to the specified char . +fun m00(m00: Float): Matrix4x3f? { this.m00 = m00 properties = properties and (PROPERTY_IDENTITY or PROPERTY_TRANSLATION).inv() return this } Set the value of the matrix element at column 0 and row 0 +"@Throws(Exception::class) private fun processTargetPortsToFormHSDs( hdsApiClient: HDSApiClient, storage: StorageSystem, targetURIList: List, hostName: String, exportMask: ExportMask, hostModeInfo: Pair?, systemObjectID: String ): List? { val hsdList: List = ArrayList() var hostMode: String? = null var hostModeOption: String? = null if (hostModeInfo != null) { hostMode = hostModeInfo.first hostModeOption = hostModeInfo.second } for (targetPortURI in targetURIList) { val storagePort: StoragePort = dbClient.queryObject(StoragePort::class.java, targetPortURI) val storagePortNumber: String = getStoragePortNumber(storagePort.getNativeGuid()) val dataSource: DataSource = dataSourceFactory.createHSDNickNameDataSource(hostName, storagePortNumber, storage) val hsdNickName: String = customConfigHandler.getComputedCustomConfigValue( CustomConfigConstants.HDS_HOST_STORAGE_DOMAIN_NICKNAME_MASK_NAME, storage.getSystemType(), dataSource ) if (Transport.IP.name().equalsIgnoreCase(storagePort.getTransportType())) { log.info(""Populating iSCSI HSD for storage: {}"", storage.getSerialNumber()) val hostGroup = HostStorageDomain( storagePortNumber, exportMask.getMaskName(), HDSConstants.ISCSI_TARGET_DOMAIN_TYPE, hsdNickName ) hostGroup.setHostMode(hostMode) hostGroup.setHostModeOption(hostModeOption) hsdList.add(hostGroup) } if (Transport.FC.name().equalsIgnoreCase(storagePort.getTransportType())) { log.info(""Populating FC HSD for storage: {}"", storage.getSerialNumber()) val hostGroup = HostStorageDomain( storagePortNumber, exportMask.getMaskName(), HDSConstants.HOST_GROUP_DOMAIN_TYPE, hsdNickName ) hostGroup.setHostMode(hostMode) hostGroup.setHostModeOption(hostModeOption) hsdList.add(hostGroup) } } return hsdList }" This routine iterates through the target ports and prepares a batch of HostStorageDomain Objects with required information . +"private fun isInResults(results: ArrayList, id: String): Int { var i = 0 for (item in results) { if (item.videoId.equals(id)) return i i++ } return -1 }" Test if there is an item that already exists +"private fun parseToken(terminators: CharArray): String? { var ch: Char i1 = pos i2 = pos while (hasChar()) { ch = chars.get(pos) if (isOneOf(ch, terminators)) { break } i2++ pos++ } return getToken(false) }" Parse out a token until any of the given terminators is encountered . +"@Ignore(""TODO: disabled because rather than throwing an exception, getAll catches all exceptions and logs a warning message"") @Test fun testNonColocatedGetAll() { doNonColocatedbulkOp(OP.GETALL) }" "disabled because rather than throwing an exception , getAll catches all exceptions and logs a warning message" +"fun buildMatchObject( sequenceIdentifier: String?, model: String?, signatureLibraryRelease: String?, seqStart: Int, seqEnd: Int, cigarAlign: String?, score: Double?, profileLevel: ProfileScanRawMatch.Level?, patternLevel: PatternScanMatch.PatternScanLocation.Level? ): PfScanRawMatch? { return HamapRawMatch( sequenceIdentifier, model, signatureLibraryRelease, seqStart, seqEnd, cigarAlign, score, profileLevel ) }" Method to be implemented that builds the correct kind of PfScanRawMatch . +"private fun updateServerStatus() { try { val page = StringBuffer() page.append(""\n"") page.append(""\n\n R Server\n"") page.append("" \n"") page.append("" \n"") page.append(""\n\n"") page.append(""
\n\n"") page.append(""
\n"") page.append(""
\n"") page.append(""
\n"") page.append("" \n"") page.append("" \n\n"") page.append(""
\n\n"") page.append(""
\n"") page.append(""

R Server:

\n"") page.append( """""" Online""; } else { echo ""

Offline

""; } ?> """""".trimIndent() ) page.append(""
\n\n"") page.append(""
\n"") page.append("" \n"") page.append(""

Server Statistics

\n"") page.append(""\n"") page.append("" \n"") page.append("" \n \n"") page.append("" \n"") if (fullHostName != null) { page.append( """""" ${"" """""".trimIndent() ) } page.append( """""" ${"" """""".trimIndent() ) val runtime = Runtime.getRuntime() val memory = ((runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024).toString() + "" / "" + runtime.totalMemory() / 1024 / 1024 + "" MB"" try { var totalMem: Double = sigar.getMem().getTotal() / 1024 / 1024 / 1024.0 var usedMem: Double = (sigar.getMem().getTotal() - sigar.getMem().getFree()) / 1024 / 1024 / 1024.0 cpuLoad = 1 - sigar.getCpuPerc().getIdle() totalMem = (totalMem * 10).toInt() / 10.0 usedMem = (usedMem * 10).toInt() / 10.0 page.append("" \n"") page.append("" \n"") } catch (e: Exception) { log(""ERROR: unable to update system stats: "" + e.message) } page.append("" \n"") page.append( """""" """""" ) page.append( """""" """""" ) page.append( """""" ${"" """""".trimIndent() ) page.append( """""" ${"" """""".trimIndent() ) page.append(""
PropertyValue
Server Name$fullHostName""}
Server Updated"" + Date(System.currentTimeMillis()).toString()}
Server CPU Usage"" + (cpuLoad * 1000) as Int / 10.0 + ""%
Server Memory$usedMem / $totalMem GB
Application Memory$memory
Thread Count${Thread.activeCount()}
Git Updated${if (lastPerforceUpdate > 0) Date(lastPerforceUpdate).toString() else ""No history""}
Server Launched"" + Date(bootTime).toString()}
Server Version$ServerDate""}
\n\n"") page.append(""

R Server Reports

\n"") page.append(""\n"") page.append(""

Running Tasks

\n"") page.append(""\n"") page.append("" \n"") page.append( """""" """""" ) page.append("" \n"") synchronized(this@RServer) { for (task in runningTasks.values()) { val startTime: Long = task.getStartTime() val duration = (System.currentTimeMillis() - startTime) / 1000 page.append("" \n"") page.append("" "") if (task.getrScript().toLowerCase().contains("".r"") || task.getIsPython()) { val link = """" + task.getrScript() + """" page.append(""\n "") } else { page.append(""\n "") } page.append( """""" """""" ) page.append( """""" """""" ) page.append( """""" """""" ) page.append( """""" """""" ) if (PerforceTask.equalsIgnoreCase(task.getTaskName())) { page.append(""\n "") } else { page.append( """"""${ """""" """""" ) } page.append(""\n \n"") } } page.append(""
Task Name Log File Start Time Duration Runtime Parameters Owner End Process
"" + (if (task.getShinyApp()) """" else """") + task.getTaskName() + (if (task.getShinyApp()) """" else """") + ""$link ${Date(startTime).toString()}${if (task.getShinyApp()) """" else (duration / 60).toString() + "" m "" + duration % 60 + "" s""}${task.getParameters()}${task.getOwner()}
\n\n"") page.append(""

Recent Log Entries

\n"") synchronized(this@RServer) { page.append(""
    \n"") for (log in logEntries) { if (log.contains(""ERROR:"")) { page.append(""
  • $log
  • \n"") } else { page.append(""
  • $log
  • \n"") } } page.append(""
\n\n"") } page.append(""

Scheduled Tasks

\n"") page.append(""\n"") page.append("" \n"") page.append( """""" """""" ) page.append("" \n"") page.append(""
    \n"") if (schedulePath.split(""//"").length > 1) { page.append( """""" ${""
  • Schedule File: //"" + schedulePath.split(""//"").get(1)}
  • """""".trimIndent() ) } else { page.append( """""" ${""
  • Schedule File: $schedulePath""}
  • """""".trimIndent() ) } page.append(""
\n"") for (schedule in regularSchedules) { page.append("" \n"") page.append( """"""${ "" \n "" + ""\n "" + ""\n "" + ""\n \n \n "" + "" """""" ) page.append("" \n"") } page.append(""
Task Name R Script Runtime Parameters Frequency Next Run Time Owner Run Now
"" + schedule.getTaskName() .replace(""_"", "" "") + """" + schedule.getrScript().replace( ""_"", "" "" ) + """" + schedule.getParameters() + """" + (if (schedule.getFrequency() === Schedule.Frequency.Now) ""Startup"" else schedule.getFrequency()) + """" + (if (schedule.getFrequency() === Schedule.Frequency.Now || schedule.getFrequency() === Schedule.Frequency.Never) "" "" else Date( schedule.getNextRunTime() ).toString()) + """" + schedule.getOwner() + ""
"" + ""\n "" + ""\n "" + ""\n "" + ""\n "" + ""\n "" + ""\n "" + ""\n
\n\n"") page.append(""

Completed Tasks

\n"") page.append(""\n"") page.append("" \n"") page.append( """""" """""" ) page.append("" \n"") synchronized(this@RServer) { for (task in completed) { val duration: Long = (task.getEndTime() - task.getStartTime()) / 1000 page.append("" \n"") page.append( """"""${"" \n"" ) } else { page.append("" \n"") } page.append( """""" ${"" "" + "" """""".trimIndent() ) page.append("" \n"") } } page.append(""
Task Name Completion Time Duration Runtime Parameters Outcome.Rout log Owner
"" + task.getTaskName().replace(""_"", "" "")} """""" ) page.append( """"""${"" "" + Date(task.getEndTime()).toString()} """""" ) page.append( """""" ${(duration / 60).toString() + "" m "" + duration % 60 + "" s ""} """""" ) page.append( """"""${"" "" + task.getParameters()} """""" ) page.append( "" "" + if (task.getOutcome() .equals(""Success"") ) """" else """" ) page.append( """"""${"" "" + task.getOutcome()} """""" ) if (task.getRout() != null) { page.append( """" + task.getrScript() .replace(""_"", "" "") + """" + task.getOwner()}
\n\n"") page.append(""
\n\n"") page.append(""
\n"") page.append("" RServer on GitHub\n"") page.append(""
\n\n"") page.append(""
\n\n\n"") val writer = BufferedWriter(FileWriter(indexPagePath)) writer.write(page.toString()) writer.close() } catch (e: Exception) { log(""ERROR: failure updating server status: "" + e.message) e.printStackTrace() } }" Generates the index.php file for the server dashboard . +fun removeServerById(serverId: Int) { servers.remove(serverId) } Remove server with given unique id from list +fun TreeSet(c: Comparator?) { this(TreeMap(c)) } "Constructs a new , empty set , sorted according to the specified comparator . All elements inserted into the set must be < i > mutually comparable < /i > by the specified comparator : < tt > comparator.compare ( e1 , e2 ) < /tt > must not throw a < tt > ClassCastException < /tt > for any elements < tt > e1 < /tt > and < tt > e2 < /tt > in the set . If the user attempts to add an element to the set that violates this constraint , the < tt > add ( Object ) < /tt > call will throw a < tt > ClassCastException < /tt > ." +fun read(operation: Supplier): T { return try { lock.readLock().lock() operation.get() } finally { lock.readLock().unlock() } } "Obtain a read lock , perform the operation , and release the read lock ." +"public void test_nCopiesILjava_lang_Object ( ) { Object o = new Object ( ) ; List l = Collections . nCopies ( 100 , o ) ; Iterator i = l . iterator ( ) ; Object first = i . next ( ) ; assertTrue ( ""Returned list consists of copies not refs"" , first == o ) ; assertEquals ( ""Returned list of incorrect size"" , 100 , l . size ( ) ) ; assertTrue ( ""Contains"" , l . contains ( o ) ) ; assertTrue ( ""Contains null"" , ! l . contains ( null ) ) ; assertTrue ( ""null nCopies contains"" , ! Collections . nCopies ( 2 , null ) . contains ( o ) ) ; assertTrue ( ""null nCopies contains null"" , Collections . nCopies ( 2 , null ) . contains ( null ) ) ; l = Collections . nCopies ( 20 , null ) ; i = l . iterator ( ) ; for ( int counter = 0 ; i . hasNext ( ) ; counter ++ ) { assertTrue ( ""List is too large"" , counter < 20 ) ; assertNull ( ""Element should be null: "" + counter , i . next ( ) ) ; } try { l . add ( o ) ; fail ( ""Returned list is not immutable"" ) ; } catch ( UnsupportedOperationException e ) { return ; } try { Collections . nCopies ( - 2 , new HashSet ( ) ) ; fail ( ""nCopies with negative arg didn't throw IAE"" ) ; } catch ( IllegalArgumentException e ) { } }" "java.util.Collections # nCopies ( int , java.lang.Object )" +"fun test_nCopiesILjava_lang_Object() { val o = Any() var l: MutableList<*> = Collections.nCopies(100, o) var i: Iterator<*> = l.iterator() val first = i.next()!! assertTrue(""Returned list consists of copies not refs"", first === o) assertEquals(""Returned list of incorrect size"", 100, l.size) assertTrue(""Contains"", l.contains(o)) assertTrue(""Contains null"", !l.contains(null)) assertTrue(""null nCopies contains"", !Collections.nCopies(2, null).contains(o)) assertTrue(""null nCopies contains null"", Collections.nCopies(2, null).contains(null)) l = Collections.nCopies(20, null) i = l.iterator() var counter = 0 while (i.hasNext()) { assertTrue(""List is too large"", counter < 20) assertNull(""Element should be null: $counter"", i.next()) counter++ } try { l.add(o) fail(""Returned list is not immutable"") } catch (e: UnsupportedOperationException) { return } try { Collections.nCopies(-2, HashSet()) fail(""nCopies with negative arg didn't throw IAE"") } catch (e: IllegalArgumentException) { } }" "add a + b + 1 , returning the result in a . The a value is treated as a BigInteger of length ( b.length * 8 ) bits . The result is modulo 2^b.length in case of overflow ." +"fun findByThriftIdOrThrow(fieldId: Int): _Fields? { return findByThriftId(fieldId) ?: throw IllegalArgumentException(""Field $fieldId doesn't exist!"") }" "Find the _Fields constant that matches fieldId , throwing an exception if it is not found ." +fun outerResource(@LayoutRes resource: Int): DividerAdapterBuilder { return outerView(asViewFactory(resource)) } Sets the divider that appears before and after the wrapped adapters items . +fun ExecutionEntryImpl() { super() } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +fun logDiagnostic(msg: String) { if (isDiagnosticsEnabled()) { logRawDiagnostic(diagnosticPrefix + msg) } } Output a diagnostic message to a user-specified destination ( if the user has enabled diagnostic logging ) . +"fun Code39Reader(usingCheckDigit: Boolean, extendedMode: Boolean) { this.usingCheckDigit = usingCheckDigit this.extendedMode = extendedMode }" "Creates a reader that can be configured to check the last character as a check digit , or optionally attempt to decode `` extended Code 39 '' sequences that are used to encode the full ASCII character set ." +fun eStaticClass(): EClass? { return SexecPackage.Literals.UNSCHEDULE_TIME_EVENT } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"fun insertIfAbsent(s: K?, v: V?) { this.arc.get(getPartition(s)).insertIfAbsent(s, v) }" put a value to the cache if there was not an entry before do not return a previous content value +private fun Tokenizer(text: CharSequence) { this.text = text this.matcher = java.awt.font.GlyphMetrics.WHITESPACE.matcher(text) skipWhitespace() nextToken() } Construct a tokenizer that parses tokens from the given text . +"private fun BucketAdvisor(bucket: Bucket, regionAdvisor: RegionAdvisor) { super(bucket) this.regionAdvisor = regionAdvisor this.pRegion = this.regionAdvisor.getPartitionedRegion() resetParentAdvisor(bucket.getId()) }" Constructs a new BucketAdvisor for the Bucket owned by RegionAdvisor . +"fun prepareYLegend() { val yLegend = ArrayList() if (mRoundedYLegend) { val interval: Float = mDeltaY / (mYLegendCount - 1) val log10 = Math.log10(interval.toDouble()) var exp = Math.floor(log10).toInt() if (exp < 0) { exp = 0 } val tenPowExp: Double = POW_10.get(exp + 5) var multi = Math.round(interval / tenPowExp).toDouble() if (multi >= 1) { if (multi > 2 && multi <= 3) { multi = 3.0 } else if (multi > 3 && multi <= 5) { multi = 5.0 } else if (multi > 5 && multi < 10) { multi = 10.0 } } else { multi = 1.0 } val step = (multi * tenPowExp).toFloat() log("" log10 is $log10 interval is $interval mDeltaY is $mDeltaY tenPowExp is $tenPowExp multi is $multi mYChartMin is $mYChartMin step is $step"") var `val` = 0f if (step >= 1f) { `val` = (mYChartMin / step) as Int * step } else { `val` = mYChartMin } while (`val` <= mDeltaY + step + mYChartMin) { yLegend.add(`val`) `val` = `val` + step } if (step >= 1f) { mYChartMin = (mYChartMin / step) as Int * step log(""mYChartMin write --- step >= 1f -- and mYChartMin is $mYChartMin"") } mDeltaY = `val` - step - mYChartMin mYChartMax = yLegend[yLegend.size() - 1] } else { val interval: Float = mDeltaY / (mYLegendCount - 1) yLegend.add(mYChartMin) var i = 1 if (!isDrawOutline) { i = 0 } while (i < mYLegendCount - 1) { yLegend.add(mYChartMin + i.toFloat() * interval) i++ } yLegend.add(mDeltaY + mYChartMin) } mYLegend = yLegend.toArray(arrayOfNulls(0)) }" setup the Y legend +"private fun displayHeaders(headers: List) { for (header in headers) { System.out.printf(""%25s"", header.getName()) } println() }" Displays the headers for the report . +"fun initData() { var classLoader: ClassLoader? = this.getClassLoader() if (classLoader != null) { val t1: TextView = this.createdView() t1.text = ""[onCreate] classLoader "" + ++i + "" : "" + classLoader.toString() this.classLoaderRootLayout.addView(t1) while (classLoader!!.parent != null) { classLoader = classLoader.parent val t2: TextView = this.createdView() t2.text = ""[onCreate] classLoader "" + ++i + "" : "" + classLoader.toString() this.classLoaderRootLayout.addView(t2) } } }" Initialize the Activity data +"fun toType(value: String?, pattern: String?, locale: Locale?): Any? { val calendar: Calendar = toCalendar(value, pattern, locale) return toType(calendar) }" Parse a String value to the required type +"fun toggleSong(songId: Long?, songName: String?, albumName: String?, artistName: String?) { if (getSongId(songId) == null) { addSongId(songId, songName, albumName, artistName) } else { removeItem(songId) } }" Toggle the current song as favorite +"@DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2013-12-30 12:55:07.260 -0500"", hash_original_method = ""03611E3BB30258B8EC4FDC9F783CBCCF"", hash_generated_method = ""75EED4D564C6A1FA0F492FBBD941CE61"" ) fun createRouteHeader(address: Address?): RouteHeader? { if (address == null) throw NullPointerException(""null address arg"") val route = Route() route.setAddress(address) return route }" Creates a new RouteHeader based on the newly supplied address value . +"@Throws(Exception::class) fun NominalItem(att: Attribute, valueIndex: Int) { super(att) if (att.isNumeric()) { throw Exception(""NominalItem must be constructed using a nominal attribute"") } m_attribute = att if (m_attribute.numValues() === 1) { m_valueIndex = 0 } else { m_valueIndex = valueIndex } }" Constructs a new NominalItem . +"fun inferType(tuples: TupleSet, field: String): Class<*>? { return if (tuples is Table) { (tuples as Table).getColumnType(field) } else { var type: Class<*>? = null var type2: Class<*>? = null val iter: Iterator<*> = tuples.tuples() while (iter.hasNext()) { val t: Tuple = iter.next() as Tuple if (type == null) { type = t.getColumnType(field) } else if (type != t.getColumnType(field).also { type2 = it }) { if (type2!!.isAssignableFrom(type)) { type = type2 } else require(type.isAssignableFrom(type2)) { ""The data field [$field] does not have a consistent type across provided Tuples"" } } } type } }" Infer the data field type across all tuples in a TupleSet . +"private fun exactMinMax(relation: Relation, distFunc: DistanceQuery): DoubleMinMax? { val progress: FiniteProgress? = if (LOG.isVerbose()) FiniteProgress( ""Exact fitting distance computations"", relation.size(), LOG ) else null val minmax = DoubleMinMax() val iditer: DBIDIter = relation.iterDBIDs() while (iditer.valid()) { val iditer2: DBIDIter = relation.iterDBIDs() while (iditer2.valid()) { if (DBIDUtil.equal(iditer, iditer2)) { iditer2.advance() continue } val d: Double = distFunc.distance(iditer, iditer2) minmax.put(d) iditer2.advance() } LOG.incrementProcessed(progress) iditer.advance() } LOG.ensureCompleted(progress) return minmax }" Compute the exact maximum and minimum . +"fun testDoubleValueMinusZero() { val a = ""-123809648392384754573567356745735.63567890295784902768787678287E-400"" val aNumber = BigDecimal(a) val minusZero = (-9223372036854775808L).toLong() val result: Double = aNumber.doubleValue() assertTrue(""incorrect value"", java.lang.Double.doubleToLongBits(result) == minusZero) }" Double value of a small negative BigDecimal +"fun SeaGlassContext(component: JComponent?, region: Region?, style: SynthStyle?, state: Int) { super(component, region, style, state) if (component === fakeComponent) { this.component = null this.region = null this.style = null return } if (component == null || region == null || style == null) { throw NullPointerException(""You must supply a non-null component, region and style"") } reset(component, region, style, state) }" "Creates a SeaGlassContext with the specified values . This is meant for subclasses and custom UI implementors . You very rarely need to construct a SeaGlassContext , though some methods will take one ." +"fun same( tags1: ArrayList>, tags2: ArrayList?> ): Boolean { if (tags1.size() !== tags2.size()) { return false } for (i in 0 until tags1.size()) { if (!tags1[i].equals(tags2[i])) { return false } } return true }" Check if two lists of tags are the same Note : this considers order relevant +"fun copy(): TemplateEffect? { return TemplateEffect(labelTemplate, valueTemplate, attr.priority, exclusive, negated) }" Returns a copy of the effect . +fun RegionMBeanBridge(cachePerfStats: CachePerfStats) { this.regionStats = cachePerfStats this.regionMonitor = MBeanStatsMonitor(ManagementStrings.REGION_MONITOR.toLocalizedString()) regionMonitor.addStatisticsToMonitor(cachePerfStats.getStats()) configureRegionMetrics() } Statistic related Methods +fun Set(cl: Class<*>) { OptionInstance = false PlugInObject = cl ObjectName = (PlugInObject as Class<*>).simpleName ObjectName = Convert(ObjectName) } Defines the stored object as a class . +"@Throws(IOException::class) fun include(ctx: DefaultFaceletContext, parent: UIComponent?, url: URL?) { val f: DefaultFacelet = this.factory.getFacelet(ctx.getFacesContext(), url) as DefaultFacelet f.include(ctx, parent) }" Grabs a DefaultFacelet from referenced DefaultFaceletFacotry +"@DSComment(""From safe class list"") @DSSafe(DSCat.SAFE_LIST) @DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2013-12-30 12:56:30.241 -0500"", hash_original_method = ""6B85F90491881D2C299E5BF02CCF5806"", hash_generated_method = ""82489B93E2C39EE14F117933CF49B12C"" ) fun toHexString(v: Long): String? { return IntegralToString.longToHexString(v) }" Converts the specified long value into its hexadecimal string representation . The returned string is a concatenation of characters from ' 0 ' to ' 9 ' and ' a ' to ' f ' . +"private fun initializeProgressView(inflater: LayoutInflater, actionArea: ViewGroup) { if (mCard.mCardProgress != null) { val progressView: View = inflater.inflate(R.layout.card_progress, actionArea, false) val progressBar = progressView.findViewById(R.id.card_progress) as ProgressBar (progressView.findViewById(R.id.card_progress_text) as TextView).setText(mCard.mCardProgress.label) progressBar.max = mCard.mCardProgress.maxValue progressBar.progress = 0 mCard.mCardProgress.progressView = progressView mCard.mCardProgress.setProgressType(mCard.getProgressType()) actionArea.addView(progressView) } }" Build the progress view into the given ViewGroup . +@Synchronized fun resetReaders() { readers = null } "Resets a to-many relationship , making the next get call to query for a fresh result ." +"fun register(containerFactory: ContainerFactory) { containerFactory.registerContainer( ""wildfly8x"", ContainerType.INSTALLED, WildFly8xInstalledLocalContainer::class.java ) containerFactory.registerContainer( ""wildfly8x"", ContainerType.REMOTE, WildFly8xRemoteContainer::class.java ) containerFactory.registerContainer( ""wildfly9x"", ContainerType.INSTALLED, WildFly9xInstalledLocalContainer::class.java ) containerFactory.registerContainer( ""wildfly9x"", ContainerType.REMOTE, WildFly9xRemoteContainer::class.java ) containerFactory.registerContainer( ""wildfly10x"", ContainerType.INSTALLED, WildFly10xInstalledLocalContainer::class.java ) containerFactory.registerContainer( ""wildfly10x"", ContainerType.REMOTE, WildFly10xRemoteContainer::class.java ) }" Register container . +"public static byte [ ] decode ( String encoded ) { if ( encoded == null ) { return null ; } char [ ] base64Data = encoded . toCharArray ( ) ; int len = removeWhiteSpace ( base64Data ) ; if ( len % FOURBYTE != 0 ) { return null ; } int numberQuadruple = ( len / FOURBYTE ) ; if ( numberQuadruple == 0 ) { return new byte [ 0 ] ; } byte decodedData [ ] = null ; byte b1 = 0 , b2 = 0 , b3 = 0 , b4 = 0 ; char d1 = 0 , d2 = 0 , d3 = 0 , d4 = 0 ; int i = 0 ; int encodedIndex = 0 ; int dataIndex = 0 ; decodedData = new byte [ ( numberQuadruple ) * 3 ] ; for ( ; i < numberQuadruple - 1 ; i ++ ) { if ( ! isData ( ( d1 = base64Data [ dataIndex ++ ] ) ) || ! isData ( ( d2 = base64Data [ dataIndex ++ ] ) ) || ! isData ( ( d3 = base64Data [ dataIndex ++ ] ) ) || ! isData ( ( d4 = base64Data [ dataIndex ++ ] ) ) ) { return null ; } b1 = base64Alphabet [ d1 ] ; b2 = base64Alphabet [ d2 ] ; b3 = base64Alphabet [ d3 ] ; b4 = base64Alphabet [ d4 ] ; decodedData [ encodedIndex ++ ] = ( byte ) ( b1 << 2 | b2 > > 4 ) ; decodedData [ encodedIndex ++ ] = ( byte ) ( ( ( b2 & 0xf ) << 4 ) | ( ( b3 > > 2 ) & 0xf ) ) ; decodedData [ encodedIndex ++ ] = ( byte ) ( b3 << 6 | b4 ) ; } if ( ! isData ( ( d1 = base64Data [ dataIndex ++ ] ) ) || ! isData ( ( d2 = base64Data [ dataIndex ++ ] ) ) ) { return null ; } b1 = base64Alphabet [ d1 ] ; b2 = base64Alphabet [ d2 ] ; d3 = base64Data [ dataIndex ++ ] ; d4 = base64Data [ dataIndex ++ ] ; if ( ! isData ( ( d3 ) ) || ! isData ( ( d4 ) ) ) { if ( isPad ( d3 ) && isPad ( d4 ) ) { if ( ( b2 & 0xf ) != 0 ) { return null ; } byte [ ] tmp = new byte [ i * 3 + 1 ] ; System . arraycopy ( decodedData , 0 , tmp , 0 , i * 3 ) ; tmp [ encodedIndex ] = ( byte ) ( b1 << 2 | b2 > > 4 ) ; return tmp ; } else if ( ! isPad ( d3 ) && isPad ( d4 ) ) { b3 = base64Alphabet [ d3 ] ; if ( ( b3 & 0x3 ) != 0 ) { return null ; } byte [ ] tmp = new byte [ i * 3 + 2 ] ; System . arraycopy ( decodedData , 0 , tmp , 0 , i * 3 ) ; tmp [ encodedIndex ++ ] = ( byte ) ( b1 << 2 | b2 > > 4 ) ; tmp [ encodedIndex ] = ( byte ) ( ( ( b2 & 0xf ) << 4 ) | ( ( b3 > > 2 ) & 0xf ) ) ; return tmp ; } else { return null ; } } else { b3 = base64Alphabet [ d3 ] ; b4 = base64Alphabet [ d4 ] ; decodedData [ encodedIndex ++ ] = ( byte ) ( b1 << 2 | b2 > > 4 ) ; decodedData [ encodedIndex ++ ] = ( byte ) ( ( ( b2 & 0xf ) << 4 ) | ( ( b3 > > 2 ) & 0xf ) ) ; decodedData [ encodedIndex ++ ] = ( byte ) ( b3 << 6 | b4 ) ; } return decodedData ; } " Decodes Base64 data into octects +"@DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2013-12-30 12:55:34.017 -0500"", hash_original_method = ""647E85AB615972325C277E376A221EF0"", hash_generated_method = ""9835D90D4E0E7CCFFD07C436051E80EB"" ) fun hasIsdnSubaddress(): Boolean { return hasParm(ISUB) }" return true if the isdn subaddress exists . +private fun tryScrollBackToTopWhileLoading() { tryScrollBackToTop() } just make easier to understand +"private fun extractVariables(variablesBody: String): Map? { val map: Map = HashMap() val m: Matcher = PATTERN_VARIABLES_BODY.matcher(variablesBody) LOG.debug(""parsing variables body"") while (m.find()) { val key: String = m.group(1) val value: String = m.group(2) if (map.containsKey(key)) { LOG.warn(""A duplicate variable name found with name: {} and value: {}."", key, value) } map.put(key, value) } return map }" Extract variables map from variables body . +fun hashCode(): Int { val fh = if (first == null) 0 else first.hashCode() val sh = if (second == null) 0 else second.hashCode() return fh shl 16 or (sh and 0xFFFF) } "Returns this Pair 's hash code , of which the 16 high bits are the 16 low bits of < tt > getFirst ( ) .hashCode ( ) < /tt > are identical to the 16 low bits and the 16 low bits of < tt > getSecond ( ) .hashCode ( ) < /tt >" +"@Throws(Exception::class) private fun CallStaticVoidMethod(env: JNIEnvironment, classJREF: Int, methodID: Int) { if (VM.VerifyAssertions) { VM._assert(VM.BuildForPowerPC, ERROR_MSG_WRONG_IMPLEMENTATION) } if (traceJNI) VM.sysWrite(""JNI called: CallStaticVoidMethod \n"") RuntimeEntrypoints.checkJNICountDownToGC() try { JNIHelpers.invokeWithDotDotVarArg(methodID, TypeReference.Void) } catch (unexpected: Throwable) { if (traceJNI) unexpected.printStackTrace(System.err) env.recordException(unexpected) } }" "CallStaticVoidMethod : invoke a static method that returns void arguments passed using the vararg ... style NOTE : the vararg 's are not visible in the method signature here ; they are saved in the caller frame and the glue frame < p > < strong > NOTE : This implementation is NOT used for IA32 . On IA32 , it is overwritten with a C implementation in the bootloader when the VM starts. < /strong >" +fun visitInterface(): jdk.internal.org.objectweb.asm.signature.SignatureVisitor? { return this } Visits the type of an interface implemented by the class . +"fun intersect(line: javax.sound.sampled.Line?): Vec4? { val intersection: Intersection? = intersect(line, this.a, this.b, this.c) return if (intersection != null) intersection.getIntersectionPoint() else null }" Determine the intersection of the triangle with a specified line . +"fun lostOwnership( clipboard: java.awt.datatransfer.Clipboard?, contents: java.awt.datatransfer.Transferable? ) { }" Notifies this object that it is no longer the owner of the contents of the clipboard . +"fun testExample() { Locale.setDefault(Locale(""en"", ""UK"")) doTestExample(""fr"", ""CH"", arrayOf(""_fr_CH.class"", ""_fr.properties"", "".class"")) doTestExample(""fr"", ""FR"", arrayOf(""_fr.properties"", "".class"")) doTestExample(""de"", ""DE"", arrayOf(""_en.properties"", "".class"")) doTestExample(""en"", ""US"", arrayOf(""_en.properties"", "".class"")) doTestExample(""es"", ""ES"", arrayOf(""_es_ES.class"", "".class"")) }" Verifies the example from the getBundle specification . +"fun PubSubManager(connection: Connection, toAddress: String) { con = connection to = toAddress }" Create a pubsub manager associated to the specified connection where the pubsub requests require a specific to address for packets . +"fun discoverOnAllPorts() { log.info(""Sending LLDP packets out of all the enabled ports"") for (sw in switchService.getAllSwitchDpids()) { val iofSwitch: IOFSwitch = switchService.getSwitch(sw) ?: continue if (!iofSwitch.isActive()) continue val c: Collection = iofSwitch.getEnabledPortNumbers() if (c != null) { for (ofp in c) { if (isLinkDiscoverySuppressed(sw, ofp)) { continue } log.trace(""Enabled port: {}"", ofp) sendDiscoveryMessage(sw, ofp, true, false) val npt = NodePortTuple(sw, ofp) addToMaintenanceQueue(npt) } } } }" Send LLDPs to all switch-ports +"fun parseQuerystring(queryString: String?): Map? { val map: MutableMap = HashMap() if (queryString == null || queryString == """") { return map } val params = queryString.split(""&"".toRegex()).dropLastWhile { it.isEmpty() } .toTypedArray() for (param in params) { try { val keyValuePair = param.split(""="".toRegex(), limit = 2).toTypedArray() val name: String = URLDecoder.decode(keyValuePair[0], ""UTF-8"") if (name === """") { continue } val value = if (keyValuePair.size > 1) URLDecoder.decode(keyValuePair[1], ""UTF-8"") else """" map[name] = value } catch (e: UnsupportedEncodingException) { } } return map }" Parse a querystring into a map of key/value pairs . +fun isDiscardVisible(): Boolean { return m_ButtonDiscard.isVisible() } Returns the visibility of the discard button . +"private fun editNote(noteId: Int) { hideSoftKeyboard() val intent = Intent(this@MainActivity, NoteActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK intent.putExtra(""id"", noteId.toString()) startActivity(intent) }" Method used to enter note edition mode +"private fun createLeftSide(): javax.swing.JPanel? { val leftPanel: javax.swing.JPanel = javax.swing.JPanel() listModel = CustomListModel() leftPanel.setLayout(java.awt.BorderLayout()) listBox = javax.swing.JList(listModel) listBox.setCellRenderer(JlistRenderer()) listBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION) listBox.addListSelectionListener(CustomListSelectionListener()) val scrollPane: javax.swing.JScrollPane = javax.swing.JScrollPane(listBox) scrollPane.setBorder(javax.swing.BorderFactory.createEmptyBorder()) leftPanel.add(scrollPane, java.awt.BorderLayout.CENTER) scrollPane.setBorder(javax.swing.BorderFactory.createTitledBorder(""Dialogue states:"")) val controlPanel: javax.swing.JPanel = createControlPanel() leftPanel.add(controlPanel, java.awt.BorderLayout.SOUTH) return leftPanel }" Creates the panel on the left side of the window +"fun insertAt(dest: FloatArray, src: FloatArray, offset: Int): FloatArray? { val temp = FloatArray(dest.size + src.size - 1) System.arraycopy(dest, 0, temp, 0, offset) System.arraycopy(src, 0, temp, offset, src.size) System.arraycopy(dest, offset + 1, temp, src.size + offset, dest.size - offset - 1) return temp }" Inserts one array into another by replacing specified offset . +fun removeFailListener() { this.failedListener = null } "Unregister fail listener , initialised by Builder # failListener" +"private fun fieldsForOtherResourceSpecified( includedFields: TypedParams?, typeIncludedFields: IncludedFieldsParams ): Boolean { return includedFields != null && !includedFields.getParams() .isEmpty() && noResourceIncludedFieldsSpecified(typeIncludedFields) }" Checks if fields for other resource has been specified but not for the processed one +fun resolveReference(ref: MemberRef?): IBinding? { return null } Resolves the given reference and returns the binding for it . < p > The implementation of < code > MemberRef.resolveBinding < /code > forwards to this method . How the name resolves is often a function of the context in which the name node is embedded as well as the name itself . < /p > < p > The default implementation of this method returns < code > null < /code > . Subclasses may reimplement . < /p > +"@Scheduled(fixedRate = FIXED_RATE) fun logStatistics() { if (beansAvailable) { if (log.isInfoEnabled()) { logOperatingSystemStatistics() logRuntimeStatistics() logMemoryStatistics() logThreadStatistics() log.info(""\n"") } } if (log.isInfoEnabled()) { logDroppedData() logBufferStatistics() logStorageStatistics() } }" Log all the statistics . +"@HLEFunction(nid = -0x6cbbf4ef, version = 150) fun sceWlanDevIsPowerOn(): Int { return Wlan.getSwitchState() }" Determine if the wlan device is currently powered on +"@Throws(IOException::class) fun readTransformMetaDataFromFile(spec: String?, metapath: String?): FrameBlock? { return readTransformMetaDataFromFile(spec, metapath, TfUtils.TXMTD_SEP) }" "Reads transform meta data from an HDFS file path and converts it into an in-memory FrameBlock object . The column names in the meta data file 'column.names ' is processed with default separator ' , ' ." +"fun toString(codeset: String?): String { val retVal = StringBuffer() for (i in 0 until prolog.size()) { val e: ConcreteElement = prolog.elementAt(i) as ConcreteElement retVal.append(e.toString(getCodeset()) + ""\n"") } if (content != null) retVal.append(content.toString(getCodeset()) + ""\n"") return versionDecl + retVal.toString() }" Override toString so it prints something useful +fun isCompound(): Boolean { return splits.size() !== 1 } Checks if this instance is a compounding word . +fun hasAnnotation(annotation: Annotation?): Boolean { return annotationAccessor.typeHas(annotation) } Determines whether T has a particular annotation . +fun create(): Builder? { return Builder(false) } Constructs an asynchronous query task . +"@Throws(IOException::class) fun MP4Reader(fis: FileInputStream?) { if (null == fis) { log.warn(""Reader was passed a null file"") log.debug(""{}"", ToStringBuilder.reflectionToString(this)) } this.fis = MP4DataStream(fis) channel = fis.getChannel() decodeHeader() analyzeFrames() firstTags.add(createFileMeta()) createPreStreamingTags(0, false) }" "Creates MP4 reader from file input stream , sets up metadata generation flag ." +@Strictfp fun plusPIO2_strict(angRad: Double): Double { return if (angRad > -Math.PI / 4) { angRad + PIO2_LO + PIO2_HI } else { angRad + PIO2_HI + PIO2_LO } } Strict version . +@Synchronized private fun isSelectedTrackRecording(): Boolean { return trackDataHub != null && trackDataHub.isSelectedTrackRecording() } Returns true if the selected track is recording . Needs to be synchronized because trackDataHub can be accessed by multiple threads . +"fun loadIcon(suggestion: ApplicationSuggestion): Drawable? { return try { val `is`: InputStream = mContext.getContentResolver().openInputStream(suggestion.getThumbailUri()) Drawable.createFromStream(`is`, null) } catch (e: FileNotFoundException) { null } }" Loads the icon for the given suggestion . +fun isHead(): Boolean { return if (parent == null) true else false } Returns true if this node is the head of its DominatorTree . +"fun ofMethod(returnType: CtClass?, paramTypes: Array?): String? { val desc = StringBuffer() desc.append('(') if (paramTypes != null) { val n = paramTypes.size for (i in 0 until n) toDescriptor(desc, paramTypes[i]) } desc.append(')') if (returnType != null) toDescriptor(desc, returnType) return desc.toString() }" Returns the descriptor representing a method that receives the given parameter types and returns the given type . +"fun eGet(featureID: Int, resolve: Boolean, coreType: Boolean): Any? { when (featureID) { UmplePackage.GEN_EXPR___NAME_1 -> return getName_1() UmplePackage.GEN_EXPR___ANONYMOUS_GEN_EXPR_11 -> return getAnonymous_genExpr_1_1() UmplePackage.GEN_EXPR___EQUALITY_OP_1 -> return getEqualityOp_1() UmplePackage.GEN_EXPR___NAME_2 -> return getName_2() UmplePackage.GEN_EXPR___ANONYMOUS_GEN_EXPR_21 -> return getAnonymous_genExpr_2_1() } return super.eGet(featureID, resolve, coreType) }" < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +fun Main() {} Creates a new instance of Main +"fun serializeFile(path: String?, o: Any) { try { val context: JAXBContext = JAXBContext.newInstance(o.javaClass) val m: Marshaller = context.createMarshaller() m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE) val stream = FileOutputStream(path) m.marshal(o, stream) } catch (e: JAXBException) { e.printStackTrace() } catch (e: FileNotFoundException) { e.printStackTrace() } }" "Serializes an object and saves it to a file , located at given path ." +"fun min(expression: Expression?): MinProjectionExpression? { return MinProjectionExpression(expression, false) }" Minimum aggregation function . +fun onUIReset(frame: PtrFrameLayout?) { mScale = 1f mDrawable.stop() } "When the content view has reached top and refresh has been completed , view will be reset ." +fun forgetInstruction(ins: BytecodeInstruction): Boolean { if (!instructionMap.containsKey(ins.getClassName())) return false return if (!instructionMap.get(ins.getClassName()) .containsKey(ins.getMethodName()) ) false else instructionMap.get(ins.getClassName()).get(ins.getMethodName()).remove(ins) } < p > forgetInstruction < /p > +"@Throws(IOException::class) fun watchRecursive(path: Path?): Observable?>? { val recursive = true return ObservableFactory(path, recursive).create() }" "Creates an observable that watches the given directory and all its subdirectories . Directories that are created after subscription are watched , too ." +"fun invertMatrix(matrix: Matrix3?): Matrix3? { if (matrix == null) { throw IllegalArgumentException( Logger.logMessage( Logger.ERROR, ""Matrix3"", ""invertMatrix"", ""missingMatrix"" ) ) } throw UnsupportedOperationException(""Matrix3.invertMatrix is not implemented"") }" Inverts the specified matrix and stores the result in this matrix . < p/ > This throws an exception if the matrix is singular . < p/ > The result of this method is undefined if this matrix is passed in as the matrix to invert . +"fun sync(context: Context) { val cr: ContentResolver = cr() val proj = arrayOf(_ID, Syncs.TYPE_ID, Syncs.OBJECT_ID, millis(Syncs.ACTION_ON)) val sel: String = Syncs.STATUS_ID + "" = ?"" val args = arrayOf(java.lang.String.valueOf(ACTIVE.id)) val order: String = Syncs.ACTION_ON + "" DESC"" val c = EasyCursor(cr.query(Syncs.CONTENT_URI, proj, sel, args, order)) val count: Int = c.getCount() if (count > 0) { var users = 0 var reviews = 0 var review: Review? = null val lines: Set = LinkedHashSet() var `when` = 0L var icon: Bitmap? = null val syncIds: Set = HashSet(count) while (c.moveToNext()) { var photo: Uri? = null when (Sync.Type.get(c.getInt(Syncs.TYPE_ID))) { USER -> { photo = user(context, cr, c.getLong(Syncs.OBJECT_ID), lines, icon) if (photo != null) { users++ syncIds.add(java.lang.String.valueOf(c.getLong(_ID))) } } REVIEW -> { val (first, second) = review( context, cr, c.getLong(Syncs.OBJECT_ID), lines, icon ) photo = first if (second != null) { reviews++ syncIds.add(java.lang.String.valueOf(c.getLong(_ID))) if (review == null) { review = second } } } } if (`when` == 0L) { `when` = c.getLong(Syncs.ACTION_ON) } if (photo != null && photo !== EMPTY) { icon = photo(context, photo) } } val size: Int = lines.size() if (size > 0) { var bigText: CharSequence? = null var summary: CharSequence? = null val activity: Intent if (users > 0 && reviews == 0) { activity = Intent(context, FriendsActivity::class.java) } else if (users == 0 && (reviews == 1 || size == 1)) { bigText = ReviewAdapter.comments(review.comments) summary = context.getString(R.string.n_stars, review.rating) activity = Intent(context, RestaurantActivity::class.java).putExtra( EXTRA_ID, review.restaurantId ) if (review.type === GOOGLE) { activity.putExtra(EXTRA_TAB, TAB_PUBLIC) } } else { activity = Intent(context, NotificationsActivity::class.java) } notify(context, lines, bigText, summary, `when`, icon, users + reviews, activity) Prefs.putStringSet(context, APP, NEW_SYNC_IDS, syncIds) event(""notification"", ""notify"", ""sync"", size) } else { Managers.notification(context).cancel(TAG_SYNC, 0) context.startService(Intent(context, SyncsReadService::class.java)) } } c.close() }" Post a notification for any unread server changes . +"fun serializableInstance(): LogisticRegressionRunner? { val variables: MutableList = LinkedList() val var1 = ContinuousVariable(""X"") val var2 = ContinuousVariable(""Y"") variables.add(var1) variables.add(var2) val dataSet: DataSet = ColtDataSet(3, variables) val col1data = doubleArrayOf(0.0, 1.0, 2.0) val col2data = doubleArrayOf(2.3, 4.3, 2.5) for (i in 0..2) { dataSet.setDouble(i, 0, col1data[i]) dataSet.setDouble(i, 1, col2data[i]) } val dataWrapper = DataWrapper(dataSet) return LogisticRegressionRunner(dataWrapper, Parameters()) }" Generates a simple exemplar of this class to test serialization . +"fun ESHistory(documentId: String, events: Collection) { this.documentId = documentId this.events = events }" New instance with the specified content . +"fun executeDelayedExpensiveWrite(task: Runnable?): Boolean { val f: Future<*> = executeDiskStoreTask(task, this.delayedWritePool) lastDelayedWrite = f return f != null }" "Execute a task asynchronously , or in the calling thread if the bound is reached . This pool is used for write operations which can be delayed , but we have a limit on how many write operations we delay so that we do n't run out of disk space . Used for deletes , unpreblow , RAF close , etc ." +private fun resetMnemonics() { if (mnemonicToIndexMap != null) { mnemonicToIndexMap.clear() mnemonicInputMap.clear() } } Resets the mnemonics bindings to an empty state . +fun textureMode(mode: Int) { g.textureMode(mode) } Set texture mode to either to use coordinates based on the IMAGE ( more intuitive for new users ) or NORMALIZED ( better for advanced chaps ) +"fun execute(params: Array?): GetETLDriverInfo? { return try { val commandLine: CommandLine = getCommandLine(params, PARAMS_STRUCTURE) val minBId: String = commandLine.getOptionValue(""min-batch-id"") LOGGER.debug(""minimum-batch-id is $minBId"") val maxBId: String = commandLine.getOptionValue(""max-batch-id"") LOGGER.debug(""maximum-batch-id is $maxBId"") val getETLDriverInfoList: List = getETLInfoDAO.getETLInfo(minBId.toLong(), maxBId.toLong()) LOGGER.info(""list of File is "" + getETLDriverInfoList[0].getFileList()) getETLDriverInfoList[0] } catch (e: Exception) { LOGGER.error(""Error occurred"", e) throw MetadataException(e) } }" This method runs GetETLInfo proc and retrieves information regarding files available for batches mentioned . +fun FunctionblockFactoryImpl() { super() } Creates an instance of the factory . < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"fun writePopulation(outputfolder: String) { var outputfolder = outputfolder outputfolder = outputfolder + if (outputfolder.endsWith(""/"")) """" else ""/"" if (sc.getPopulation().getPersons().size() === 0 || sc.getPopulation() .getPersonAttributes() == null ) { throw RuntimeException(""Either no persons or person attributes to write."") } else { LOG.info(""Writing population to file... ("" + sc.getPopulation().getPersons().size() + "")"") val pw = PopulationWriter(sc.getPopulation(), sc.getNetwork()) pw.writeV5(outputfolder + ""Population.xml"") LOG.info(""Writing person attributes to file..."") val oaw = ObjectAttributesXmlWriter(sc.getPopulation().getPersonAttributes()) oaw.putAttributeConverter(IncomeImpl::class.java, SAIncomeConverter()) oaw.setPrettyPrint(true) oaw.writeFile(outputfolder + ""PersonAttributes.xml"") } }" Writes the population and their attributes to file . +"@Throws(LocalRepositoryException::class) fun restart(serviceName: String) { val prefix = ""restart(): serviceName=$serviceName "" _log.debug(prefix) val cmd = arrayOf(_SYSTOOL_CMD, _SYSTOOL_RESTART, serviceName) val result: Exec.Result = org.gradle.api.tasks.Exec.sudo(_SYSTOOL_TIMEOUT, cmd) checkFailure(result, prefix) }" Restart a service +public void receiveResultqueryStorageProcessors ( com . emc . storageos . vasa . VasaServiceStub . QueryStorageProcessorsResponse result ) { } auto generated Axis2 call back method for queryStorageProcessors method override this method for handling normal response from queryStorageProcessors operation +"public final void testNextBytesbyteArray02 ( ) { byte [ ] myBytes ; byte [ ] myBytes1 ; byte [ ] myBytes2 ; for ( int i = 1 ; i < LENGTH ; i += INCR ) { myBytes = new byte [ i ] ; for ( int j = 1 ; j < i ; j ++ ) { myBytes [ j ] = ( byte ) ( j & 0xFF ) ; } sr . setSeed ( myBytes ) ; sr2 . setSeed ( myBytes ) ; for ( int k = 1 ; k < LENGTH ; k += INCR ) { myBytes1 = new byte [ k ] ; myBytes2 = new byte [ k ] ; sr . nextBytes ( myBytes1 ) ; sr2 . nextBytes ( myBytes2 ) ; for ( int l = 0 ; l < k ; l ++ ) { assertFalse ( ""unexpected: myBytes1[l] != myBytes2[l] :: l=="" + l + "" k="" + k + "" i="" + i + "" myBytes1[l]="" + myBytes1 [ l ] + "" myBytes2[l]="" + myBytes2 [ l ] , myBytes1 [ l ] != myBytes2 [ l ] ) ; } } } for ( int n = 1 ; n < LENGTH ; n += INCR ) { int n1 = 10 ; int n2 = 20 ; int n3 = 100 ; byte [ ] [ ] bytes1 = new byte [ 10 ] [ n1 ] ; byte [ ] [ ] bytes2 = new byte [ 5 ] [ n2 ] ; for ( int k = 0 ; k < bytes1 . length ; k ++ ) { sr . nextBytes ( bytes1 [ k ] ) ; } for ( int k = 0 ; k < bytes2 . length ; k ++ ) { sr2 . nextBytes ( bytes2 [ k ] ) ; } for ( int k = 0 ; k < n3 ; k ++ ) { int i1 = k / n1 ; int i2 = k % n1 ; int i3 = k / n2 ; int i4 = k % n2 ; assertTrue ( ""non-equality: i1="" + i1 + "" i2="" + i2 + "" i3="" + i3 + "" i4="" + i4 , bytes1 [ i1 ] [ i2 ] == bytes2 [ i3 ] [ i4 ] ) ; } } }" test against the `` void nextBytes ( byte [ ] ) '' method ; it checks out that different SecureRandom objects being supplied with the same seed return the same sequencies of bytes as results of their `` nextBytes ( byte [ ] ) '' methods +"@DSSafe(DSCat.SAFE_LIST) @DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2013-12-30 12:29:27.931 -0500"", hash_original_method = ""92BE44E9F6280B7AE0D2A8904499350A"", hash_generated_method = ""5A68C897F2049F6754C8DA6E4CBD57CE"" ) fun translationXBy(value: Float): ViewPropertyAnimator? { animatePropertyBy(TRANSLATION_X, value) return this }" This method will cause the View 's < code > translationX < /code > property to be animated by the specified value . Animations already running on the property will be canceled . +"private fun loadServerDetailsActivity() { Preference.putString(context, Constants.PreferenceFlag.IP, null) val intent = Intent(this@AlreadyRegisteredActivity, ServerDetails::class.java) intent.putExtra(getResources().getString(R.string.intent_extra_regid), regId) intent.putExtra( getResources().getString(R.string.intent_extra_from_activity), AlreadyRegisteredActivity::class.java.getSimpleName() ) intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(intent) finish() }" Load server details activity . +"fun createNamedGraph(model: Model, graphNameNode: Resource?, elements: RDFList?): NamedGraph? { val result: NamedGraph = model.createResource(SP.NamedGraph).`as`(NamedGraph::class.java) result.addProperty(SP.graphNameNode, graphNameNode) result.addProperty(SP.elements, elements) return result }" Creates a new NamedGraph element as a blank node in a given Model . +"fun SQLWarning(reason: String?, SQLState: String?, vendorCode: Int, cause: Throwable?) { super(reason, SQLState, vendorCode, cause) }" "Creates an SQLWarning object . The Reason string is set to reason , the SQLState string is set to given SQLState and the Error Code is set to vendorCode , cause is set to the given cause" +"@POST @Path(""downloads"") @ApiOperation(value = ""Starts downloading artifacts"", response = DownloadToken::class) @ApiResponses( value = [ApiResponse(code = 202, message = ""OK""), ApiResponse( code = 400, message = ""Illegal version format or artifact name"" ), ApiResponse(code = 409, message = ""Downloading already in progress""), ApiResponse( code = 500, message = ""Server error"" )] ) fun startDownload( @QueryParam(value = ""artifact"") @ApiParam( value = ""Artifact name"", allowableValues = CDECArtifact.NAME ) artifactName: String?, @QueryParam(value = ""version"") @ApiParam(value = ""Version number"") versionNumber: String? ): Response? { return try { val downloadToken = DownloadToken() downloadToken.setId(DOWNLOAD_TOKEN) val artifact: Artifact = createArtifactOrNull(artifactName) val version: Version = createVersionOrNull(versionNumber) facade.startDownload(artifact, version) Response.status(Response.Status.ACCEPTED).entity(downloadToken).build() } catch (e: ArtifactNotFoundException) { handleException(e, Response.Status.BAD_REQUEST) } catch (e: IllegalVersionException) { handleException(e, Response.Status.BAD_REQUEST) } catch (e: DownloadAlreadyStartedException) { handleException(e, Response.Status.CONFLICT) } catch (e: Exception) { handleException(e) } }" Starts downloading artifacts . +"fun release() { this@PathLockFactory.release(path, permits) }" Release file permit . +fun BuddyPanel(model: BuddyListModel?) { super(model) setCellRenderer(BuddyLabel()) setOpaque(false) this.setFocusable(false) this.addMouseListener(BuddyPanelMouseListener()) } Create a new BuddyList . +fun createComponent(owner: Component?): Component? { return if (java.awt.GraphicsEnvironment.isHeadless()) { null } else HeavyWeightWindow(getParentWindow(owner)) } "Creates the Component to use as the parent of the < code > Popup < /code > . The default implementation creates a < code > Window < /code > , subclasses should override ." +"fun UnknownResolverVariableException(i18n: String?, vararg arguments: Any?) { super(i18n, arguments) }" Creates a parsing exception with message associated to the i18n and the arguments . +fun isEndNode(node: Node?): Boolean { return getDelegator().getCurrentStorage().isEndNode(node) } Test if the given Node is an end node of a Way . Isolated nodes not part of a way are not considered an end node . +"fun hasDefClearPathToMethodExit(duVertex: Definition): Boolean { require(graph.containsVertex(duVertex)) { ""vertex not in graph"" } return if (duVertex.isLocalDU()) false else hasDefClearPathToMethodExit( duVertex, duVertex, HashSet() ) }" < p > hasDefClearPathToMethodExit < /p > +"private fun resetAndGetFollowElements( tokens: ObservableXtextTokenStream, strict: Boolean ): Collection? { val parser: CustomInternalN4JSParser = createParser() parser.setStrict(strict) tokens.reset() return doGetFollowElements(parser, tokens) }" Create a fresh parser instance and process the tokens for a second pass . +"@Throws(IgniteException::class) private fun printInfo(fs: IgniteFileSystem, path: IgfsPath) { println() println(""Information for "" + path + "": "" + fs.info(path)) }" Prints information for file or directory . +fun makeHashValue(currentMaxListSize: Int): List? { return ArrayList(currentMaxListSize / 2 + 1) } Utility methods to make it easier to inserted custom store dependent list +"fun cdf(`val`: Double, loc: Double, scale: Double): Double { var `val` = `val` `val` = (`val` - loc) / scale return 1.0 / (1.0 + Math.exp(-`val`)) }" Cumulative density function . +"fun taskStateChanged(@TASK_STATE taskState: Int, tag: Serializable?) { when (taskState) { TASK_STATE_PREPARE -> { iView.layoutLoadingVisibility(isContentEmpty()) iView.layoutContentVisibility(!isContentEmpty()) iView.layoutEmptyVisibility(false) iView.layoutLoadFailedVisibility(false) } TASK_STATE_SUCCESS -> { iView.layoutLoadingVisibility(false) if (isContentEmpty()) { iView.layoutEmptyVisibility(true) } else { iView.layoutContentVisibility(true) } } TASK_STATE_FAILED -> { if (isContentEmpty()) { iView.layoutEmptyVisibility(false) iView.layoutLoadingVisibility(false) iView.layoutLoadFailedVisibility(true) if (tag != null) { iView.setTextLoadFailed(tag.toString()) } } } TASK_STATE_FINISH -> {} } }" According to the task execution state to update the page display state . +"@Throws(javax.swing.text.BadLocationException::class) fun addLineTrackingIcon(line: Int, icon: Icon?): GutterIconInfo? { val offs: Int = textArea.getLineStartOffset(line) return addOffsetTrackingIcon(offs, icon) }" "Adds an icon that tracks an offset in the document , and is displayed adjacent to the line numbers . This is useful for marking things such as source code errors ." +fun createVertex(point: Point?): SpatialSparseVertex? { if (point != null) point.setSRID(SRID) return SpatialSparseVertex(point) } Creates a new vertex located at < tt > point < /tt > . The spatial reference id is the to the one of the factory 's coordinate reference system . +"private fun indentString(): String? { val sb = StringBuffer() for (i in 0 until indent) { sb.append("" "") } return sb.toString() }" Indent child nodes to help visually identify the structure of the AST . +fun isProcessing(): Boolean { return isProcessing } Returns whether XBL processing is currently enabled . +"@Throws(IOException::class) fun computeCodebase( name: String?, jarFile: String?, port: String, srcRoot: String?, mdAlgorithm: String? ): String? { return computeCodebase(name, jarFile, port.toInt(), srcRoot, mdAlgorithm) }" Convenience method that ultimately calls the primary 5-argument version of this method . This method allows one to input a < code > String < /code > value for the port to use when constructing the codebase ; which can be useful when invoking this method from a Jini configuration file . +"private fun purgeRelayLogs(wait: Boolean) { if (relayLogRetention > 1) { logger.info(""Checking for old relay log files..."") val logDir = File(binlogDir) val filesToPurge: Array = FileCommands.filesOverRetentionAndInactive( logDir, binlogFilePattern, relayLogRetention, this.binlogPosition.getFileName() ) if (this.relayLogQueue != null) { for (fileToPurge in filesToPurge) { if (logger.isInfoEnabled()) { logger.debug(""Removing relay log file from relay log queue: "" + fileToPurge.getAbsolutePath()) } if (!relayLogQueue.remove(fileToPurge)) { logger.info(""Unable to remove relay log file from relay log queue, probably old: $fileToPurge"") } } } FileCommands.deleteFiles(filesToPurge, wait) } }" Purge old relay logs that have aged out past the number of retained files . +fun fromInteger(address: Int): Inet4Address? { return getInet4Address(Ints.toByteArray(address)) } Returns an Inet4Address having the integer value specified by the argument . +"fun isOverwriteUser1(): Boolean { val oo: Any = get_Value(COLUMNNAME_OverwriteUser1) return if (oo != null) { if (oo is Boolean) oo.toBoolean() else ""Y"" == oo } else false }" Get Overwrite User1 . +"private fun valEquals(o1: Any?, o2: Any?): Boolean { return if (o1 == null) o2 == null else o1 == o2 }" Test two values for equality . Differs from o1.equals ( o2 ) only in that it copes with with < tt > null < /tt > o1 properly . +"fun hasAttribute(name: String?): Boolean { return DTM.NULL !== dtm.getAttributeNode(node, null, name) }" Method hasAttribute +"fun init() { Environment.init(this) Debug.init( this, arrayOf(""debug.basic"", ""debug.cspec"", ""debug.layer"", ""debug.mapbean"", ""debug.plugin"") ) val propValue: String = getParameter(PropertiesProperty) var propHandler: PropertyHandler? = null try { if (propValue != null) { val builder: PropertyHandler.Builder = Builder().setPropertiesFile(propValue) propHandler = PropertyHandler(builder) if (Debug.debugging(""app"")) { Debug.output(""OpenMapApplet: Using properties from $propValue"") } } } catch (murle: MalformedURLException) { Debug.error(""OpenMap: property file specified: $propValue doesn't exist, searching for default openmap.properties file..."") } catch (ioe: IOException) { Debug.error(""OpenMap: There is a problem using the property file specified: $propValue, searching for default openmap.properties file..."") } if (propHandler == null) { propHandler = PropertyHandler() } val mapPanel: MapPanel = BasicMapPanel(propHandler) mapPanel.getMapHandler().add(this) Debug.message(""app"", ""OpenMapApplet.init()"") }" Called by the browser or applet viewer to inform this applet that it has been loaded into the system . It is always called before the first time that the < code > start < /code > method is called . < p > The implementation of this method provided by the < code > Applet < /code > class does nothing . +"@Throws(IOException::class) fun process(rb: ResponseBuilder) { val req: SolrQueryRequest = rb.req val rsp: SolrQueryResponse = rb.rsp val params: SolrParams = req.getParams() if (!params.getBool(COMPONENT_NAME, true)) { return } val searcher: SolrIndexSearcher = req.getSearcher() if (rb.getQueryCommand().getOffset() < 0) { throw SolrException( SolrException.ErrorCode.BAD_REQUEST, ""'start' parameter cannot be negative"" ) } val timeAllowed = params.getInt(CommonParams.TIME_ALLOWED, -1) as Long if (null != rb.getCursorMark() && 0 < timeAllowed) { throw SolrException( SolrException.ErrorCode.BAD_REQUEST, ""Can not search using both "" + CursorMarkParams.CURSOR_MARK_PARAM + "" and "" + CommonParams.TIME_ALLOWED ) } val ids: String = params.get(ShardParams.IDS) if (ids != null) { val idField: SchemaField = searcher.getSchema().getUniqueKeyField() val idArr: List = StrUtils.splitSmart(ids, "","", true) val luceneIds = IntArray(idArr.size) var docs = 0 for (i in idArr.indices) { val id: Int = req.getSearcher().getFirstMatch( Term( idField.getName(), idField.getType().toInternal( idArr[i] ) ) ) if (id >= 0) luceneIds[docs++] = id } val res = DocListAndSet() res.docList = DocSlice(0, docs, luceneIds, null, docs, 0) if (rb.isNeedDocSet()) { val queries: MutableList = ArrayList() queries.add(rb.getQuery()) val filters: List = rb.getFilters() if (filters != null) queries.addAll(filters) res.docSet = searcher.getDocSet(queries) } rb.setResults(res) val ctx = ResultContext() ctx.docs = rb.getResults().docList ctx.query = null rsp.add(""response"", ctx) return } val cmd: SolrIndexSearcher.QueryCommand = rb.getQueryCommand() cmd.setTimeAllowed(timeAllowed) val result: SolrIndexSearcher.QueryResult = QueryResult() val groupingSpec: GroupingSpecification = rb.getGroupingSpec() if (groupingSpec != null) { try { val needScores = cmd.getFlags() and SolrIndexSearcher.GET_SCORES !== 0 if (params.getBool(GroupParams.GROUP_DISTRIBUTED_FIRST, false)) { val topsGroupsActionBuilder: CommandHandler.Builder = Builder().setQueryCommand(cmd).setNeedDocSet(false).setIncludeHitCount(true) .setSearcher(searcher) for (field in groupingSpec.getFields()) { topsGroupsActionBuilder.addCommandField( Builder().setField( searcher.getSchema().getField(field) ).setGroupSort(groupingSpec.getGroupSort()) .setTopNGroups(cmd.getOffset() + cmd.getLen()) .setIncludeGroupCount(groupingSpec.isIncludeGroupCount()).build() ) } val commandHandler: CommandHandler = topsGroupsActionBuilder.build() commandHandler.execute() val serializer = SearchGroupsResultTransformer(searcher) rsp.add(""firstPhase"", commandHandler.processResult(result, serializer)) rsp.add(""totalHitCount"", commandHandler.getTotalHitCount()) rb.setResult(result) return } else if (params.getBool(GroupParams.GROUP_DISTRIBUTED_SECOND, false)) { val secondPhaseBuilder: CommandHandler.Builder = Builder().setQueryCommand(cmd) .setTruncateGroups(groupingSpec.isTruncateGroups() && groupingSpec.getFields().length > 0) .setSearcher(searcher) for (field in groupingSpec.getFields()) { var topGroupsParam: Array = params.getParams(GroupParams.GROUP_DISTRIBUTED_TOPGROUPS_PREFIX + field) if (topGroupsParam == null) { topGroupsParam = arrayOfNulls(0) } val topGroups: MutableList> = ArrayList(topGroupsParam.size) for (topGroup in topGroupsParam) { val searchGroup: SearchGroup = SearchGroup() if (topGroup != TopGroupsShardRequestFactory.GROUP_NULL_VALUE) { searchGroup.groupValue = BytesRef( searcher.getSchema().getField(field).getType() .readableToIndexed(topGroup) ) } topGroups.add(searchGroup) } secondPhaseBuilder.addCommandField( Builder().setField( searcher.getSchema().getField(field) ).setGroupSort(groupingSpec.getGroupSort()) .setSortWithinGroup(groupingSpec.getSortWithinGroup()) .setFirstPhaseGroups(topGroups) .setMaxDocPerGroup(groupingSpec.getGroupOffset() + groupingSpec.getGroupLimit()) .setNeedScores(needScores).setNeedMaxScore(needScores).build() ) } for (query in groupingSpec.getQueries()) { secondPhaseBuilder.addCommandField( Builder().setDocsToCollect(groupingSpec.getOffset() + groupingSpec.getLimit()) .setSort(groupingSpec.getGroupSort()).setQuery(query, rb.req) .setDocSet(searcher).build() ) } val commandHandler: CommandHandler = secondPhaseBuilder.build() commandHandler.execute() val serializer = TopGroupsResultTransformer(rb) rsp.add(""secondPhase"", commandHandler.processResult(result, serializer)) rb.setResult(result) return } val maxDocsPercentageToCache: Int = params.getInt(GroupParams.GROUP_CACHE_PERCENTAGE, 0) val cacheSecondPassSearch = maxDocsPercentageToCache >= 1 && maxDocsPercentageToCache <= 100 val defaultTotalCount: Grouping.TotalCount = if (groupingSpec.isIncludeGroupCount()) TotalCount.grouped else TotalCount.ungrouped val limitDefault: Int = cmd.getLen() val grouping: Grouping<*, *> = Grouping( searcher, result, cmd, cacheSecondPassSearch, maxDocsPercentageToCache, groupingSpec.isMain() ) grouping.setSort(groupingSpec.getGroupSort()) .setGroupSort(groupingSpec.getSortWithinGroup()) .setDefaultFormat(groupingSpec.getResponseFormat()).setLimitDefault(limitDefault) .setDefaultTotalCount(defaultTotalCount) .setDocsPerGroupDefault(groupingSpec.getGroupLimit()) .setGroupOffsetDefault(groupingSpec.getGroupOffset()) .setGetGroupedDocSet(groupingSpec.isTruncateGroups()) if (groupingSpec.getFields() != null) { for (field in groupingSpec.getFields()) { grouping.addFieldCommand(field, rb.req) } } if (groupingSpec.getFunctions() != null) { for (groupByStr in groupingSpec.getFunctions()) { grouping.addFunctionCommand(groupByStr, rb.req) } } if (groupingSpec.getQueries() != null) { for (groupByStr in groupingSpec.getQueries()) { grouping.addQueryCommand(groupByStr, rb.req) } } if (rb.doHighlights || rb.isDebug() || params.getBool(MoreLikeThisParams.MLT, false)) { cmd.setFlags(SolrIndexSearcher.GET_DOCLIST) } grouping.execute() if (grouping.isSignalCacheWarning()) { rsp.add( ""cacheWarning"", java.lang.String.format( Locale.ROOT, ""Cache limit of %d percent relative to maxdoc has exceeded. Please increase cache size or disable caching."", maxDocsPercentageToCache ) ) } rb.setResult(result) if (grouping.mainResult != null) { val ctx = ResultContext() ctx.docs = grouping.mainResult ctx.query = null rsp.add(""response"", ctx) rsp.getToLog().add(""hits"", grouping.mainResult.matches()) } else if (!grouping.getCommands().isEmpty()) { rsp.add(""grouped"", result.groupedResults) rsp.getToLog().add(""hits"", grouping.getCommands().get(0).getMatches()) } return } catch (e: jdk.internal.org.jline.reader.SyntaxError) { throw SolrException(SolrException.ErrorCode.BAD_REQUEST, e) } } searcher.search(result, cmd) rb.setResult(result) val ctx = ResultContext() ctx.docs = rb.getResults().docList ctx.query = rb.getQuery() rsp.add(""response"", ctx) rsp.getToLog().add(""hits"", rb.getResults().docList.matches()) if (!rb.req.getParams().getBool(ShardParams.IS_SHARD, false)) { if (null != rb.getNextCursorMark()) { rb.rsp.add( CursorMarkParams.CURSOR_MARK_NEXT, rb.getNextCursorMark().getSerializedTotem() ) } } if (rb.mergeFieldHandler != null) { rb.mergeFieldHandler.handleMergeFields(rb, searcher) } else { doFieldSortValues(rb, searcher) } doPrefetch(rb) }" Actually run the query +fun addUser(user: IUser?) { if (!this.users.contains(user) && user != null) this.users.add(user) } CACHES a user to the guild . +"fun create(prefix: String?, doc: Document?): Element? { return SVGOMForeignObjectElement(prefix, doc as javax.swing.text.AbstractDocument?) }" Creates an instance of the associated element type . +"public BiCorpus alignedFromFiles ( String f ) throws IOException { return new BiCorpus ( fpath + f + extf , epath + f + exte , apath + f + exta ) ; }" Generate aligned BiCorpus . +"public LognormalDistr ( double shape , double scale ) { numGen = new LogNormalDistribution ( scale , shape ) ; }" Instantiates a new Log-normal pseudo random number generator . +"private static String contentLengthHeader ( final long length ) { return String . format ( ""Content-Length: %d"" , length ) ; }" Format Content-Length header . +@ Bean @ ConditionalOnMissingBean public AmqpSenderService amqpSenderServiceBean ( ) { return new DefaultAmqpSenderService ( rabbitTemplate ( ) ) ; } Create default amqp sender service bean . +"@ Override protected void initialize ( ) { super . initialize ( ) ; m_Processor = new MarkdownProcessor ( ) ; m_Markdown = """" ; }" Initializes the members . +"public void upperBound ( byte [ ] key ) throws IOException { upperBound ( key , 0 , key . length ) ; }" "Move the cursor to the first entry whose key is strictly greater than the input key . Synonymous to upperBound ( key , 0 , key.length ) . The entry returned by the previous entry ( ) call will be invalid ." +"public static String replaceLast ( String s , char sub , char with ) { int index = s . lastIndexOf ( sub ) ; if ( index == - 1 ) { return s ; } char [ ] str = s . toCharArray ( ) ; str [ index ] = with ; return new String ( str ) ; }" Replaces the very last occurrence of a character in a string . +public static void main ( String [ ] args ) { Thrust simulation = new Thrust ( ) ; simulation . run ( ) ; } Entry point for the example application . +"public static < T > T checkNotNull ( T reference , @ Nullable String errorMessageTemplate , @ Nullable Object ... errorMessageArgs ) { if ( reference == null ) { throw new NullPointerException ( format ( errorMessageTemplate , errorMessageArgs ) ) ; } return reference ; }" Ensures that an object reference passed as a parameter to the calling method is not null . +"public boolean insert ( String name , RegExp definition ) { if ( Options . DEBUG ) Out . debug ( ""inserting macro "" + name + "" with definition :"" + Out . NL + definition ) ; used . put ( name , Boolean . FALSE ) ; return macros . put ( name , definition ) == null ; }" Stores a new macro and its definition . +public boolean add ( Object o ) { ensureCapacity ( size + 1 ) ; elementData [ size ++ ] = o ; return true ; } Appends the specified element to the end of this list . +"public InvocationTargetException ( Throwable target , String s ) { super ( s , null ) ; this . target = target ; }" Constructs a InvocationTargetException with a target exception and a detail message . +public boolean isExternalSkin ( ) { return ! isDefaultSkin && mResources != null ; } whether the skin being used is from external .skin file +"private void updateActions ( ) { actions . removeAll ( ) ; final ActionGroup mainActionGroup = ( ActionGroup ) actionManager . getAction ( getGroupMenu ( ) ) ; if ( mainActionGroup == null ) { return ; } final Action [ ] children = mainActionGroup . getChildren ( null ) ; for ( final Action action : children ) { final Presentation presentation = presentationFactory . getPresentation ( action ) ; final ActionEvent e = new ActionEvent ( ActionPlaces . MAIN_CONTEXT_MENU , presentation , actionManager , 0 ) ; action . update ( e ) ; if ( presentation . isVisible ( ) ) { actions . add ( action ) ; } } }" Updates the list of visible actions . +private void showFeedback ( String message ) { if ( myHost != null ) { myHost . showFeedback ( message ) ; } else { System . out . println ( message ) ; } } Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface . +TechCategory fallthrough ( ) { switch ( this ) { case OMNI_AERO : return OMNI ; case CLAN_AERO : case CLAN_VEE : return CLAN ; case IS_ADVANCED_AERO : case IS_ADVANCED_VEE : return IS_ADVANCED ; default : return null ; } } "If no value is provided for ASFs or Vees , use the base value ." +"static void svd_dscal ( int n , double da , double [ ] dx , int incx ) { if ( n <= 0 || incx == 0 ) return ; int ix = ( incx < 0 ) ? n - 1 : 0 ; for ( int i = 0 ; i < n ; i ++ ) { dx [ ix ] *= da ; ix += incx ; } return ; }" Function scales a vector by a constant . * Based on Fortran-77 routine from Linpack by J. Dongarra +"public CampoFechaVO insertValue ( final CampoFechaVO value ) { try { DbConnection conn = getConnection ( ) ; DbInsertFns . insert ( conn , TABLE_NAME , DbUtil . getColumnNames ( COL_DEFS ) , new SigiaDbInputRecord ( COL_DEFS , value ) ) ; return value ; } catch ( Exception e ) { logger . error ( ""Error insertando campo de tipo fecha para el descriptor "" + value . getIdObjeto ( ) , e ) ; throw new DBException ( ""insertando campo de tipo fecha"" , e ) ; } }" Inserta un valor de tipo fecha . +"private synchronized void closeActiveFile ( ) { StringWriterFile activeFile = this . activeFile ; try { this . activeFile = null ; if ( activeFile != null ) { activeFile . close ( ) ; getPolicy ( ) . closeActiveFile ( activeFile . path ( ) ) ; activeFile = null ; } } catch ( IOException e ) { trace . error ( ""error closing active file '{}'"" , activeFile . path ( ) , e ) ; } }" "close , finalize , and apply retention policy" +"public void testWARTypeEquality ( ) { WAR war1 = new WAR ( ""/some/path/to/file.war"" ) ; WAR war2 = new WAR ( ""/otherfile.war"" ) ; assertEquals ( war1 . getType ( ) , war2 . getType ( ) ) ; }" Test equality between WAR deployables . +"public static Vector readSignatureAlgorithmsExtension ( byte [ ] extensionData ) throws IOException { if ( extensionData == null ) { throw new IllegalArgumentException ( ""'extensionData' cannot be null"" ) ; } ByteArrayInputStream buf = new ByteArrayInputStream ( extensionData ) ; Vector supported_signature_algorithms = parseSupportedSignatureAlgorithms ( false , buf ) ; TlsProtocol . assertEmpty ( buf ) ; return supported_signature_algorithms ; }" Read 'signature_algorithms ' extension data . +"public void updateNCharacterStream ( int columnIndex , java . io . Reader x , long length ) throws SQLException { throw new SQLFeatureNotSupportedException ( resBundle . handleGetObject ( ""jdbcrowsetimpl.featnotsupp"" ) . toString ( ) ) ; }" "Updates the designated column with a character stream value , which will have the specified number of bytes . The driver does the necessary conversion from Java character format to the national character set in the database . It is intended for use when updating NCHAR , NVARCHAR and LONGNVARCHAR columns . The updater methods are used to update column values in the current row or the insert row . The updater methods do not update the underlying database ; instead the updateRow or insertRow methods are called to update the database ." +public boolean isModified ( ) { return isCustom ( ) && ! isUserAdded ( ) ; } "Returns whether the receiver represents a modified template , i.e . a contributed template that has been changed ." +"public String toString ( ) { return this . getClass ( ) . getName ( ) + ""("" + my_k + "")"" ; }" Returns a String representation of the receiver . +"private static PostingsEnum termDocs ( IndexReader reader , Term term ) throws IOException { return MultiFields . getTermDocsEnum ( reader , MultiFields . getLiveDocs ( reader ) , term . field ( ) , term . bytes ( ) ) ; }" NB : this is a convenient but very slow way of getting termDocs . It is sufficient for testing purposes . +public boolean isSubregion ( ) { return subregion ; } "Returns true if the Region is a subregion of a Component , otherwise false . For example , < code > Region.BUTTON < /code > corresponds do a < code > Component < /code > so that < code > Region.BUTTON.isSubregion ( ) < /code > returns false ." +"public static void encodeToFile ( byte [ ] dataToEncode , String filename ) throws java . io . IOException { if ( dataToEncode == null ) { throw new NullPointerException ( ""Data to encode was null."" ) ; } Base64 . OutputStream bos = null ; try { bos = new Base64 . OutputStream ( new java . io . FileOutputStream ( filename ) , Base64 . ENCODE ) ; bos . write ( dataToEncode ) ; } catch ( java . io . IOException e ) { throw e ; } finally { try { bos . close ( ) ; } catch ( Exception e ) { } } }" "Convenience method for encoding data to a file . < p > As of v 2.3 , if there is a error , the method will throw an java.io.IOException . < b > This is new to v2.3 ! < /b > In earlier versions , it just returned false , but in retrospect that 's a pretty poor way to handle it. < /p >" +public synchronized void addDataStatusListener ( DataStatusListener l ) { m_mTab . addDataStatusListener ( l ) ; } Add Data Status Listener - pass on to MTab +"protected void addField ( DurationFieldType field , int value ) { addFieldInto ( iValues , field , value ) ; }" Adds the value of a field in this period . +@ Override public int perimeter ( int size ) { size = size / 2 ; int retval = sw . perimeter ( size ) ; retval += se . perimeter ( size ) ; retval += ne . perimeter ( size ) ; retval += nw . perimeter ( size ) ; return retval ; } Compute the perimeter for a grey node using Samet 's algorithm . +"public BigdataStatementIterator addedIterator ( ) { final IChunkedOrderedIterator < ISPO > src = new ChunkedWrappedIterator < ISPO > ( added . iterator ( ) ) ; return new BigdataStatementIteratorImpl ( kb , src ) . start ( kb . getExecutorService ( ) ) ; }" Return iterator visiting the inferences that were added to the KB . +"public < V extends Object , C extends RTSpan < V > > void applyEffect ( Effect < V , C > effect , V value ) { if ( mUseRTFormatting && ! mIsSelectionChanging && ! mIsSaving ) { Spannable oldSpannable = mIgnoreTextChanges ? null : cloneSpannable ( ) ; effect . applyToSelection ( this , value ) ; synchronized ( this ) { if ( mListener != null && ! mIgnoreTextChanges ) { Spannable newSpannable = cloneSpannable ( ) ; mListener . onTextChanged ( this , oldSpannable , newSpannable , getSelectionStart ( ) , getSelectionEnd ( ) , getSelectionStart ( ) , getSelectionEnd ( ) ) ; } mLayoutChanged = true ; } } }" "Call this to have an effect applied to the current selection . You get the Effect object via the static data members ( e.g. , RTEditText.BOLD ) . The value for most effects is a Boolean , indicating whether to add or remove the effect ." +"public DefaultLmlParser ( final LmlData data , final LmlSyntax syntax , final LmlTemplateReader templateReader , final boolean strict ) { super ( data , syntax , templateReader , new DefaultLmlStyleSheet ( ) , strict ) ; }" "Creates a new parser with custom syntax , reader and strict setting ." +"private static void populateFancy ( SQLiteDatabase writableDb ) { long startOfToday = DateUtil . parse ( DateUtil . format ( System . currentTimeMillis ( ) ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Clothes"" , ""New jeans"" , 10000 , startOfToday , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Flat / House"" , ""Monthly rent"" , 35000 , startOfToday , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Grocery"" , ""Fruits & vegetables"" , 3567 , DateUtil . parse ( ""19/08/2015"" ) , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Fuel"" , ""Full gas tank"" , 7590 , DateUtil . parse ( ""14/08/2015"" ) , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Clothes"" , ""New shirt"" , 3599 , DateUtil . parse ( ""11/08/2015"" ) , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Restaurant"" , ""Family get together"" , 3691 , DateUtil . parse ( ""05/08/2015"" ) , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_INCOME , ""Salary"" , """" , 90000 , DateUtil . parse ( ""31/07/2015"" ) , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Personal care"" , ""New perfume"" , 3865 , DateUtil . parse ( ""29/07/2015"" ) , Item . NO_ID ) ) ; ItemDao . saveItem ( writableDb , new Item ( Item . TYPE_EXPENSE , ""Grocery"" , ""Bottle of milk"" , 345 , DateUtil . parse ( ""26/07/2015"" ) , Item . NO_ID ) ) ; }" Generates reasonable amount of good-looking income / expense items . +"public TestEntity ( int index , String text , String value , double minConfidence ) { super ( index , text ) ; this . value = value ; this . minConfidence = minConfidence ; }" "New instance , with a value ." +"public boolean contains ( JComponent a , int b , int c ) { boolean returnValue = ( ( ComponentUI ) ( uis . elementAt ( 0 ) ) ) . contains ( a , b , c ) ; for ( int i = 1 ; i < uis . size ( ) ; i ++ ) { ( ( ComponentUI ) ( uis . elementAt ( i ) ) ) . contains ( a , b , c ) ; } return returnValue ; }" Invokes the < code > contains < /code > method on each UI handled by this object . +public boolean isClosed ( ) { return closed ; } Returns true if this contour path is closed ( loops back on itself ) or false if it is not . +"public void store ( float val , Offset offset ) { this . plus ( offset ) . store ( val ) ; }" Stores the float value in the memory location pointed to by the current instance . +"public List < IvrZone > showIvrZones ( boolean active ) throws NetworkDeviceControllerException { List < IvrZone > zones = new ArrayList < IvrZone > ( ) ; SSHPrompt [ ] prompts = { SSHPrompt . POUND , SSHPrompt . GREATER_THAN } ; StringBuilder buf = new StringBuilder ( ) ; String cmdKey = active ? ""MDSDialog.ivr.show.zone.active.cmd"" : ""MDSDialog.ivr.show.zone.cmd"" ; sendWaitFor ( MDSDialogProperties . getString ( cmdKey ) , defaultTimeout , prompts , buf ) ; String [ ] lines = getLines ( buf ) ; IvrZone zone = null ; IvrZoneMember member = null ; String [ ] regex = { MDSDialogProperties . getString ( ""MDSDialog.ivr.showZoneset.zone.name.match"" ) , MDSDialogProperties . getString ( ""MDSDialog.ivr.showZoneset.zone.member.match"" ) } ; String [ ] groups = new String [ 10 ] ; for ( String line : lines ) { int index = match ( line , regex , groups ) ; switch ( index ) { case 0 : zone = new IvrZone ( groups [ 0 ] ) ; zones . add ( zone ) ; break ; case 1 : member = new IvrZoneMember ( groups [ 0 ] , Integer . valueOf ( groups [ 3 ] ) ) ; zone . getMembers ( ) . add ( member ) ; break ; } } return zones ; }" Get switch ivr zones +"public static void append ( File file , Reader reader , String charset ) throws IOException { append ( file , reader , charset , false ) ; }" "Append the text supplied by the Reader at the end of the File without writing a BOM , using a specified encoding ." +public static LifetimeAttribute createLifetimeAttribute ( int lifetime ) { LifetimeAttribute attribute = new LifetimeAttribute ( ) ; attribute . setLifetime ( lifetime ) ; return attribute ; } Create a LifetimeAttribute . +"public void testFilePrimary ( ) throws Exception { start ( ) ; igfsPrimary . create ( FILE , true ) . close ( ) ; checkEvictionPolicy ( 0 , 0 ) ; int blockSize = igfsPrimary . info ( FILE ) . blockSize ( ) ; append ( FILE , blockSize ) ; checkEvictionPolicy ( 0 , 0 ) ; read ( FILE , 0 , blockSize ) ; checkEvictionPolicy ( 0 , 0 ) ; }" Test how evictions are handled for a file working in PRIMARY mode . +"public static String createTestPtStationCSVFile ( File file ) { try ( BufferedWriter bw = new BufferedWriter ( new FileWriter ( file ) ) ) { bw . write ( ""id,x,y"" ) ; bw . newLine ( ) ; bw . write ( ""1,10,10"" ) ; bw . newLine ( ) ; bw . write ( ""2,10, 190"" ) ; bw . newLine ( ) ; bw . write ( ""3,190,190"" ) ; bw . newLine ( ) ; bw . write ( ""4,190,10"" ) ; bw . newLine ( ) ; return file . getCanonicalPath ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }" This method creates 4 pt stops for the test network from createTestNetwork ( ) . The information about the coordinates will be written to a csv file . The 4 pt stops are located as a square in the coordinate plane with a side length of 180 meter ( see the sketch below ) . +@ Override public int hashCode ( ) { int result = super . hashCode ( ) ; return result ; } Returns a hash code for the renderer . +@ Override public void eUnset ( int featureID ) { switch ( featureID ) { case SGenPackage . FEATURE_TYPE__DEPRECATED : setDeprecated ( DEPRECATED_EDEFAULT ) ; return ; case SGenPackage . FEATURE_TYPE__COMMENT : setComment ( COMMENT_EDEFAULT ) ; return ; case SGenPackage . FEATURE_TYPE__PARAMETERS : getParameters ( ) . clear ( ) ; return ; case SGenPackage . FEATURE_TYPE__OPTIONAL : setOptional ( OPTIONAL_EDEFAULT ) ; return ; } super . eUnset ( featureID ) ; } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"public boolean isVMAX3VolumeCompressionEnabled ( URI blockObjectURI ) { VirtualPool virtualPool = null ; Volume volume = null ; if ( URIUtil . isType ( blockObjectURI , Volume . class ) ) { volume = _dbClient . queryObject ( Volume . class , blockObjectURI ) ; } else if ( URIUtil . isType ( blockObjectURI , BlockSnapshot . class ) ) { BlockSnapshot snapshot = _dbClient . queryObject ( BlockSnapshot . class , blockObjectURI ) ; volume = _dbClient . queryObject ( Volume . class , snapshot . getParent ( ) ) ; } else if ( URIUtil . isType ( blockObjectURI , BlockMirror . class ) ) { BlockMirror mirror = _dbClient . queryObject ( BlockMirror . class , blockObjectURI ) ; virtualPool = _dbClient . queryObject ( VirtualPool . class , mirror . getVirtualPool ( ) ) ; } if ( volume != null ) { virtualPool = _dbClient . queryObject ( VirtualPool . class , volume . getVirtualPool ( ) ) ; } return ( ( virtualPool != null ) && virtualPool . getCompressionEnabled ( ) ) ; }" This method is will check if the volume associated with virtual Pool has compression enabled . +public void releaseConnection ( Database conn ) { if ( conn != null ) conn . close ( ) ; } Releases a connection . +"public final void testRemoveHelperTextId ( ) { PasswordEditText passwordEditText = new PasswordEditText ( getContext ( ) ) ; passwordEditText . addHelperTextId ( android . R . string . cancel ) ; passwordEditText . addHelperTextId ( android . R . string . copy ) ; passwordEditText . removeHelperTextId ( android . R . string . cancel ) ; passwordEditText . removeHelperTextId ( android . R . string . cancel ) ; assertEquals ( 1 , passwordEditText . getHelperTexts ( ) . size ( ) ) ; assertEquals ( getContext ( ) . getText ( android . R . string . copy ) , passwordEditText . getHelperTexts ( ) . iterator ( ) . next ( ) ) ; }" "Tests the functionality of the method , which allows to remove a helper text by its id ." +"private void logMessage ( String msg , Object [ ] obj ) { if ( getMonitoringPropertiesLoader ( ) . isToLogIndications ( ) ) { _logger . debug ( msg , obj ) ; } }" Log the messages . This method eliminates the logging condition check every time when we need to log a message . +public static Float toRef ( float f ) { return new Float ( f ) ; } cast a float value to his ( CFML ) reference type Float +@ Override protected boolean shouldComposeCreationImage ( ) { return true ; } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +public synchronized void promote ( Tile tile ) { if ( tileQueue . contains ( tile ) ) { try { tileQueue . remove ( tile ) ; tile . setPriority ( Tile . Priority . High ) ; tileQueue . put ( tile ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } } } Increase the priority of this tile so it will be loaded sooner . +"public void exitApp ( ) { this . webView . getPluginManager ( ) . postMessage ( ""exit"" , null ) ; }" Exit the Android application . +"public void test_getInnerCause01_reject_otherType ( ) { Throwable t = new Throwable ( ) ; assertNull ( getInnerCause ( t , Exception . class ) ) ; }" Does not find cause when it is on top of the stack trace and not either the desired type or a subclass of the desired type . +public Handshake handshake ( ) { return handshake ; } "Returns the TLS handshake of the connection that carried this response , or null if the response was received without TLS ." +"private Coordinate averagePoint ( CoordinateSequence seq ) { Coordinate a = new Coordinate ( 0 , 0 , 0 ) ; int n = seq . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { a . x += seq . getOrdinate ( i , CoordinateSequence . X ) ; a . y += seq . getOrdinate ( i , CoordinateSequence . Y ) ; a . z += seq . getOrdinate ( i , CoordinateSequence . Z ) ; } a . x /= n ; a . y /= n ; a . z /= n ; return a ; }" "Computes a point which is the average of all coordinates in a sequence . If the sequence lies in a single plane , the computed point also lies in the plane ." +"public static void invokeWebserviceASync ( WSDefinition def , SuccessCallback scall , FailureCallback fcall , Object ... arguments ) { WSConnection cr = new WSConnection ( def , scall , fcall , arguments ) ; NetworkManager . getInstance ( ) . addToQueue ( cr ) ; }" Invokes a web asynchronously and calls the callback on completion +public PutResponseMessage ( PutResponseMessage other ) { if ( other . isSetHeader ( ) ) { this . header = new AsyncMessageHeader ( other . header ) ; } } Performs a deep copy on < i > other < /i > . +private boolean isSynthetic ( Method m ) { if ( ( m . getAccessFlags ( ) & Constants . ACC_SYNTHETIC ) != 0 ) { return true ; } Attribute [ ] attrs = m . getAttributes ( ) ; for ( Attribute attr : attrs ) { if ( attr instanceof Synthetic ) { return true ; } } return false ; } Methods marked with the `` Synthetic '' attribute do not appear in the source code +public boolean isTagline ( ) { return tagline ; } Checks if is tagline . +"protected LocaTable ( TrueTypeFont ttf ) { super ( TrueTypeTable . LOCA_TABLE ) ; MaxpTable maxp = ( MaxpTable ) ttf . getTable ( ""maxp"" ) ; int numGlyphs = maxp . getNumGlyphs ( ) ; HeadTable head = ( HeadTable ) ttf . getTable ( ""head"" ) ; short format = head . getIndexToLocFormat ( ) ; isLong = ( format == 1 ) ; offsets = new int [ numGlyphs + 1 ] ; }" Creates a new instance of HmtxTable +public static < T > T create ( Class < T > theQueryClass ) { return AgentClass . createAgent ( theQueryClass ) ; } Create a database query dynamically +"@ DSComment ( ""From safe class list"" ) @ DSSafe ( DSCat . SAFE_LIST ) @ DSGenerator ( tool_name = ""Doppelganger"" , tool_version = ""2.0"" , generated_on = ""2013-12-30 13:02:44.163 -0500"" , hash_original_method = ""CE28B7D5A93F674A0286463AAF68C789"" , hash_generated_method = ""4C5D61097E13A407D793E43190510D41"" ) public synchronized void addFailure ( Test test , AssertionFailedError t ) { fFailures . addElement ( new TestFailure ( test , t ) ) ; for ( Enumeration e = cloneListeners ( ) . elements ( ) ; e . hasMoreElements ( ) ; ) { ( ( TestListener ) e . nextElement ( ) ) . addFailure ( test , t ) ; } }" Adds a failure to the list of failures . The passed in exception caused the failure . +public ExtendedKeyUsage ( byte [ ] encoding ) { super ( encoding ) ; } Creates the extension object on the base of its encoded form . +"public Iterator < E > subsetIterator ( E from , E to ) { return new BinarySearchTreeIterator < E > ( this . root , from , to ) ; }" Returns the in-order ( ascending ) iterator . +public int valueForXPosition ( int xPos ) { int value ; int minValue = slider . getMinimum ( ) ; int maxValue = slider . getMaximum ( ) ; int trackLeft = trackRect . x + thumbRect . width / 2 + trackBorder ; int trackRight = trackRect . x + trackRect . width - thumbRect . width / 2 - trackBorder ; int trackLength = trackRight - trackLeft ; if ( xPos <= trackLeft ) { value = drawInverted ( ) ? maxValue : minValue ; } else if ( xPos >= trackRight ) { value = drawInverted ( ) ? minValue : maxValue ; } else { int distanceFromTrackLeft = xPos - trackLeft ; double valueRange = ( double ) maxValue - ( double ) minValue ; double valuePerPixel = valueRange / ( double ) trackLength ; int valueFromTrackLeft = ( int ) Math . round ( distanceFromTrackLeft * valuePerPixel ) ; value = drawInverted ( ) ? maxValue - valueFromTrackLeft : minValue + valueFromTrackLeft ; } return value ; } "Returns a value give an x position . If xPos is past the track at the left or the right it will set the value to the min or max of the slider , depending if the slider is inverted or not ." +@ Override protected EClass eStaticClass ( ) { return SRuntimePackage . Literals . COMPOSITE_SLOT ; } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"public static void main ( final String [ ] args ) { DOMTestCase . doMain ( documentcreateattributeNS03 . class , args ) ; }" Runs this test from the command line . +public ListIterator < AbstractInsnNode > iterator ( ) { return iterator ( 0 ) ; } Returns an iterator over the instructions in this list . +public static String escapeXml ( String str ) { if ( str == null ) { return null ; } return EntitiesUtils . XML . escape ( str ) ; } "< p > Escapes the characters in a < code > String < /code > using XML entities. < /p > < p > For example : < tt > '' bread '' & `` butter '' < /tt > = > < tt > & amp ; quot ; bread & amp ; quot ; & amp ; amp ; & amp ; quot ; butter & amp ; quot ; < /tt > . < /p > < p > Supports only the five basic XML entities ( gt , lt , quot , amp , apos ) . Does not support DTDs or external entities. < /p > < p > Note that unicode characters greater than 0x7f are currently escaped to their numerical \\u equivalent . This may change in future releases . < /p >" +"public boolean isProcessed ( ) { Object oo = get_Value ( COLUMNNAME_Processed ) ; if ( oo != null ) { if ( oo instanceof Boolean ) return ( ( Boolean ) oo ) . booleanValue ( ) ; return ""Y"" . equals ( oo ) ; } return false ; }" Get Processed . +"public void processResponse ( SIPResponse response , MessageChannel incomingMessageChannel , SIPDialog dialog ) { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logDebug ( ""PROCESSING INCOMING RESPONSE"" + response . encodeMessage ( ) ) ; } if ( listeningPoint == null ) { if ( sipStack . isLoggingEnabled ( ) ) sipStack . getStackLogger ( ) . logError ( ""Dropping message: No listening point"" + "" registered!"" ) ; return ; } if ( sipStack . checkBranchId ( ) && ! Utils . getInstance ( ) . responseBelongsToUs ( response ) ) { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logError ( ""Dropping response - topmost VIA header does not originate from this stack"" ) ; } return ; } SipProviderImpl sipProvider = listeningPoint . getProvider ( ) ; if ( sipProvider == null ) { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logError ( ""Dropping message: no provider"" ) ; } return ; } if ( sipProvider . getSipListener ( ) == null ) { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logError ( ""No listener -- dropping response!"" ) ; } return ; } SIPClientTransaction transaction = ( SIPClientTransaction ) this . transactionChannel ; SipStackImpl sipStackImpl = sipProvider . sipStack ; if ( sipStack . isLoggingEnabled ( ) ) { sipStackImpl . getStackLogger ( ) . logDebug ( ""Transaction = "" + transaction ) ; } if ( transaction == null ) { if ( dialog != null ) { if ( response . getStatusCode ( ) / 100 != 2 ) { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logDebug ( ""Response is not a final response and dialog is found for response -- dropping response!"" ) ; } return ; } else if ( dialog . getState ( ) == DialogState . TERMINATED ) { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logDebug ( ""Dialog is terminated -- dropping response!"" ) ; } return ; } else { boolean ackAlreadySent = false ; if ( dialog . isAckSeen ( ) && dialog . getLastAckSent ( ) != null ) { if ( dialog . getLastAckSent ( ) . getCSeq ( ) . getSeqNumber ( ) == response . getCSeq ( ) . getSeqNumber ( ) ) { ackAlreadySent = true ; } } if ( ackAlreadySent && response . getCSeq ( ) . getMethod ( ) . equals ( dialog . getMethod ( ) ) ) { try { if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logDebug ( ""Retransmission of OK detected: Resending last ACK"" ) ; } dialog . resendAck ( ) ; return ; } catch ( SipException ex ) { if ( sipStack . isLoggingEnabled ( ) ) sipStack . getStackLogger ( ) . logError ( ""could not resend ack"" , ex ) ; } } } } if ( sipStack . isLoggingEnabled ( ) ) { sipStack . getStackLogger ( ) . logDebug ( ""could not find tx, handling statelessly Dialog = "" + dialog ) ; } ResponseEventExt sipEvent = new ResponseEventExt ( sipProvider , transaction , dialog , ( Response ) response ) ; if ( response . getCSeqHeader ( ) . getMethod ( ) . equals ( Request . INVITE ) ) { SIPClientTransaction forked = this . sipStack . getForkedTransaction ( response . getTransactionId ( ) ) ; sipEvent . setOriginalTransaction ( forked ) ; } sipProvider . handleEvent ( sipEvent , transaction ) ; return ; } ResponseEventExt responseEvent = null ; responseEvent = new ResponseEventExt ( sipProvider , ( ClientTransactionExt ) transaction , dialog , ( Response ) response ) ; if ( response . getCSeqHeader ( ) . getMethod ( ) . equals ( Request . INVITE ) ) { SIPClientTransaction forked = this . sipStack . getForkedTransaction ( response . getTransactionId ( ) ) ; responseEvent . setOriginalTransaction ( forked ) ; } if ( dialog != null && response . getStatusCode ( ) != 100 ) { dialog . setLastResponse ( transaction , response ) ; transaction . setDialog ( dialog , dialog . getDialogId ( ) ) ; } sipProvider . handleEvent ( responseEvent , transaction ) ; }" Process the response . +"public AnnotationAtttributeProposalInfo ( IJavaProject project , CompletionProposal proposal ) { super ( project , proposal ) ; }" Creates a new proposal info . +"public static void restoreReminderPreference ( Context context ) { int hour = MehPreferencesManager . getNotificationPreferenceHour ( context ) ; int minute = MehPreferencesManager . getNotificationPreferenceMinute ( context ) ; scheduleDailyReminder ( context , hour , minute ) ; }" "Restore the daily reminder , with the times already in preferences . Useful for device reboot or switched on from the settings screen" +@ Override public boolean isActive ( ) { return amIActive ; } Used by the Whitebox GUI to tell if this plugin is still running . +BarChart ( ) { } Instantiates a new bar chart . +"public boolean isTransactionRelevant ( Transaction tx ) throws ScriptException { lock . lock ( ) ; try { return tx . getValueSentFromMe ( this ) . signum ( ) > 0 || tx . getValueSentToMe ( this ) . signum ( ) > 0 || ! findDoubleSpendsAgainst ( tx , transactions ) . isEmpty ( ) ; } finally { lock . unlock ( ) ; } }" "< p > Returns true if the given transaction sends coins to any of our keys , or has inputs spending any of our outputs , and also returns true if tx has inputs that are spending outputs which are not ours but which are spent by pending transactions. < /p > < p > Note that if the tx has inputs containing one of our keys , but the connected transaction is not in the wallet , it will not be considered relevant. < /p >" +"public void free ( GL2 gl ) { if ( vbos [ 0 ] >= 0 ) { gl . glDeleteBuffers ( 1 , vbos , 0 ) ; } vbos [ 0 ] = - 1 ; }" Free all memory allocations . +"public Vector3 ( float x , float y , float z ) { this . set ( x , y , z ) ; }" Creates a vector with the given components +protected S_ActionImpl ( ) { super ( ) ; } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +public void clear ( int maximumCapacity ) { if ( capacity <= maximumCapacity ) { clear ( ) ; return ; } zeroValue = null ; hasZeroValue = false ; size = 0 ; resize ( maximumCapacity ) ; } Clears the map and reduces the size of the backing arrays to be the specified capacity if they are larger . +"public void bulkLoad ( DBIDs ids ) { if ( ids . size ( ) == 0 ) { return ; } assert ( root == null ) : ""Tree already initialized."" ; DBIDIter it = ids . iter ( ) ; DBID first = DBIDUtil . deref ( it ) ; ModifiableDoubleDBIDList candidates = DBIDUtil . newDistanceDBIDList ( ids . size ( ) - 1 ) ; for ( it . advance ( ) ; it . valid ( ) ; it . advance ( ) ) { candidates . add ( distance ( first , it ) , it ) ; } root = bulkConstruct ( first , Integer . MAX_VALUE , candidates ) ; }" Bulk-load the index . +"protected ExtendedSolrQueryParser createEdismaxQueryParser ( QParser qParser , String field ) { return new ExtendedSolrQueryParser ( qParser , field ) ; }" "Creates an instance of ExtendedSolrQueryParser , the query parser that 's going to be used to parse the query ." +"protected void appendSummary ( StringBuffer buffer , String fieldName , long [ ] array ) { appendSummarySize ( buffer , fieldName , array . length ) ; }" < p > Append to the < code > toString < /code > a summary of a < code > long < /code > array. < /p > +protected UndoableEdit editToBeRedone ( ) { int count = edits . size ( ) ; int i = indexOfNextAdd ; while ( i < count ) { UndoableEdit edit = edits . elementAt ( i ++ ) ; if ( edit . isSignificant ( ) ) { return edit ; } } return null ; } Returns the the next significant edit to be redone if < code > redo < /code > is invoked . This returns < code > null < /code > if there are no edits to be redone . +"public void actionPerformed ( ActionEvent e ) { Box b1 = Box . createVerticalBox ( ) ; Version currentVersion = Version . currentViewableVersion ( ) ; String copyright = LicenseUtils . copyright ( ) ; copyright = copyright . replaceAll ( ""\n"" , ""
"" ) ; String latestVersion = LatestClient . getInstance ( ) . getLatestResult ( 60 ) ; latestVersion = latestVersion . replaceAll ( ""\n"" , ""
"" ) ; JLabel label = new JLabel ( ) ; label . setText ( """" + ""Tetrad "" + currentVersion + """" + ""
"" + ""
Laboratory for Symbolic and Educational Computing"" + ""
Department of Philosophy"" + ""
Carnegie Mellon University"" + ""
"" + ""
Project Direction: Clark Glymour, Richard Scheines, Peter Spirtes"" + ""
Lead Developer: Joseph Ramsey"" + ""
"" + copyright + ""
"" + latestVersion + """" ) ; label . setBackground ( Color . LIGHT_GRAY ) ; label . setFont ( new Font ( ""Dialog"" , Font . PLAIN , 12 ) ) ; label . setBorder ( new CompoundBorder ( new LineBorder ( Color . DARK_GRAY ) , new EmptyBorder ( 10 , 10 , 10 , 10 ) ) ) ; b1 . add ( label ) ; JOptionPane . showMessageDialog ( JOptionUtils . centeringComp ( ) , b1 , ""About Tetrad..."" , JOptionPane . PLAIN_MESSAGE ) ; }" Closes the frontmost session of this action 's desktop . +private void redrawMarkers ( ) { UI . execute ( null ) ; } Redraw all markers and set them straight to their current locations without animations . +public void addToolTipSeries ( List toolTips ) { this . toolTipSeries . add ( toolTips ) ; } Adds a list of tooltips for a series . +"static private String [ ] alphaMixedNumeric ( ) { return StringFunctions . combineStringArrays ( StringFunctions . alphaMixed ( ) , StringFunctions . numeric ) ; }" Combine the alpha mixed and numeric collections into one +long incrementInMsgs ( ) { return inMsgs . incrementAndGet ( ) ; } Increments the number of messages received on this connection . +public final void yyreset ( java . io . Reader reader ) { zzBuffer = s . array ; zzStartRead = s . offset ; zzEndRead = zzStartRead + s . count - 1 ; zzCurrentPos = zzMarkedPos = s . offset ; zzLexicalState = YYINITIAL ; zzReader = reader ; zzAtEOF = false ; } "Resets the scanner to read from a new input stream . Does not close the old reader . All internal variables are reset , the old input stream < b > can not < /b > be reused ( internal buffer is discarded and lost ) . Lexical state is set to < tt > YY_INITIAL < /tt > ." +"public IntArraySpliterator ( int [ ] array , int origin , int fence , int additionalCharacteristics ) { this . array = array ; this . index = origin ; this . fence = fence ; this . characteristics = additionalCharacteristics | Spliterator . SIZED | Spliterator . SUBSIZED ; }" Creates a spliterator covering the given array and range +"@ Override public void populateDAG ( DAG dag , Configuration conf ) { TweetsInput input = new TweetsInput ( ) ; Collector collector = new Collector ( ) ; WindowOption windowOption = new WindowOption . GlobalWindow ( ) ; ApexStream < String > tags = StreamFactory . fromInput ( input , input . output , name ( ""tweetSampler"" ) ) . flatMap ( new ExtractHashtags ( ) ) ; tags . window ( windowOption , new TriggerOption ( ) . accumulatingFiredPanes ( ) . withEarlyFiringsAtEvery ( 1 ) ) . addCompositeStreams ( ComputeTopCompletions . top ( 10 , true ) ) . print ( name ( ""console"" ) ) . endWith ( collector , collector . input , name ( ""collector"" ) ) . populateDag ( dag ) ; }" Populate the dag with High-Level API . +"public void testBug21947042 ( ) throws Exception { Connection sslConn = null ; Properties props = new Properties ( ) ; props . setProperty ( ""logger"" , ""StandardLogger"" ) ; StandardLogger . startLoggingToBuffer ( ) ; try { int searchFrom = 0 ; int found = 0 ; sslConn = getConnectionWithProps ( props ) ; if ( versionMeetsMinimum ( 5 , 7 ) ) { assertTrue ( ( ( MySQLConnection ) sslConn ) . getUseSSL ( ) ) ; assertFalse ( ( ( MySQLConnection ) sslConn ) . getVerifyServerCertificate ( ) ) ; assertTrue ( ( ( MySQLConnection ) sslConn ) . getIO ( ) . isSSLEstablished ( ) ) ; } else { assertFalse ( ( ( MySQLConnection ) sslConn ) . getUseSSL ( ) ) ; assertTrue ( ( ( MySQLConnection ) sslConn ) . getVerifyServerCertificate ( ) ) ; assertFalse ( ( ( MySQLConnection ) sslConn ) . getIO ( ) . isSSLEstablished ( ) ) ; } ResultSet rset = sslConn . createStatement ( ) . executeQuery ( ""SHOW STATUS LIKE 'ssl_cipher'"" ) ; assertTrue ( rset . next ( ) ) ; String cipher = rset . getString ( 2 ) ; System . out . println ( ""ssl_cipher="" + cipher ) ; rset = sslConn . createStatement ( ) . executeQuery ( ""SHOW STATUS LIKE 'ssl_version'"" ) ; assertTrue ( rset . next ( ) ) ; cipher = rset . getString ( 2 ) ; System . out . println ( ""ssl_version="" + cipher ) ; sslConn . close ( ) ; String log = StandardLogger . getBuffer ( ) . toString ( ) ; found = log . indexOf ( Messages . getString ( ""MysqlIO.SSLWarning"" ) , searchFrom ) ; searchFrom = found + 1 ; if ( versionMeetsMinimum ( 5 , 7 ) ) { assertTrue ( found != - 1 ) ; } props . setProperty ( ""useSSL"" , ""false"" ) ; sslConn = getConnectionWithProps ( props ) ; assertFalse ( ( ( MySQLConnection ) sslConn ) . getUseSSL ( ) ) ; assertTrue ( ( ( MySQLConnection ) sslConn ) . getVerifyServerCertificate ( ) ) ; assertFalse ( ( ( MySQLConnection ) sslConn ) . getIO ( ) . isSSLEstablished ( ) ) ; rset = sslConn . createStatement ( ) . executeQuery ( ""SHOW STATUS LIKE 'ssl_cipher'"" ) ; assertTrue ( rset . next ( ) ) ; cipher = rset . getString ( 2 ) ; System . out . println ( ""ssl_cipher="" + cipher ) ; rset = sslConn . createStatement ( ) . executeQuery ( ""SHOW STATUS LIKE 'ssl_version'"" ) ; assertTrue ( rset . next ( ) ) ; cipher = rset . getString ( 2 ) ; System . out . println ( ""ssl_version="" + cipher ) ; sslConn . close ( ) ; log = StandardLogger . getBuffer ( ) . toString ( ) ; found = log . indexOf ( Messages . getString ( ""MysqlIO.SSLWarning"" ) , searchFrom ) ; if ( found != - 1 ) { searchFrom = found + 1 ; fail ( ""Warning is not expected when useSSL is explicitly set to 'false'."" ) ; } props . setProperty ( ""useSSL"" , ""true"" ) ; props . setProperty ( ""trustCertificateKeyStoreUrl"" , ""file:src/testsuite/ssl-test-certs/test-cert-store"" ) ; props . setProperty ( ""trustCertificateKeyStoreType"" , ""JKS"" ) ; props . setProperty ( ""trustCertificateKeyStorePassword"" , ""password"" ) ; sslConn = getConnectionWithProps ( props ) ; assertTrue ( ( ( MySQLConnection ) sslConn ) . getUseSSL ( ) ) ; assertTrue ( ( ( MySQLConnection ) sslConn ) . getVerifyServerCertificate ( ) ) ; assertTrue ( ( ( MySQLConnection ) sslConn ) . getIO ( ) . isSSLEstablished ( ) ) ; rset = sslConn . createStatement ( ) . executeQuery ( ""SHOW STATUS LIKE 'ssl_cipher'"" ) ; assertTrue ( rset . next ( ) ) ; cipher = rset . getString ( 2 ) ; System . out . println ( ""ssl_cipher="" + cipher ) ; rset = sslConn . createStatement ( ) . executeQuery ( ""SHOW STATUS LIKE 'ssl_version'"" ) ; assertTrue ( rset . next ( ) ) ; cipher = rset . getString ( 2 ) ; System . out . println ( ""ssl_version="" + cipher ) ; sslConn . close ( ) ; log = StandardLogger . getBuffer ( ) . toString ( ) ; found = log . indexOf ( Messages . getString ( ""MysqlIO.SSLWarning"" ) , searchFrom ) ; if ( found != - 1 ) { searchFrom = found + 1 ; fail ( ""Warning is not expected when useSSL is explicitly set to 'false'."" ) ; } } finally { StandardLogger . dropBuffer ( ) ; } }" "Tests fix for BUG # 21947042 , PREFER TLS WHERE SUPPORTED BY MYSQL SERVER . Requires test certificates from testsuite/ssl-test-certs to be installed on the server being tested ." +"public JComponent createEmbeddedPropertyGUI ( String prefix , Properties props , Properties info ) { if ( Debug . debugging ( ""inspectordetail"" ) ) { Debug . output ( ""Inspector creating GUI for "" + prefix + ""\nPROPERTIES "" + props + ""\nPROP INFO "" + info ) ; } String propertyList = info . getProperty ( PropertyConsumer . initPropertiesProperty ) ; Vector < String > sortedKeys ; if ( propertyList != null ) { Vector < String > propertiesToShow = PropUtils . parseSpacedMarkers ( propertyList ) ; for ( int i = 0 ; i < propertiesToShow . size ( ) ; i ++ ) { propertiesToShow . set ( i , prefix + ""."" + propertiesToShow . get ( i ) ) ; } sortedKeys = propertiesToShow ; } else { sortedKeys = sortKeys ( props . keySet ( ) ) ; } editors = new Hashtable < String , PropertyEditor > ( sortedKeys . size ( ) ) ; JPanel component = new JPanel ( ) ; component . setLayout ( new BorderLayout ( ) ) ; JPanel propertyPanel = new JPanel ( ) ; GridBagLayout gridbag = new GridBagLayout ( ) ; GridBagConstraints c = new GridBagConstraints ( ) ; c . insets = new Insets ( 2 , 10 , 2 , 10 ) ; propertyPanel . setLayout ( gridbag ) ; int i = 0 ; for ( String prop : sortedKeys ) { String marker = prop ; if ( prefix != null && prop . startsWith ( prefix ) ) { marker = prop . substring ( prefix . length ( ) + 1 ) ; } if ( marker . startsWith ( ""."" ) ) { marker = marker . substring ( 1 ) ; } String editorMarker = marker + PropertyConsumer . ScopedEditorProperty ; String editorClass = info . getProperty ( editorMarker ) ; if ( editorClass == null ) { editorClass = defaultEditorClass ; } Class < ? > propertyEditorClass = null ; PropertyEditor editor = null ; try { propertyEditorClass = Class . forName ( editorClass ) ; editor = ( PropertyEditor ) propertyEditorClass . newInstance ( ) ; if ( editor instanceof PropertyConsumer ) { ( ( PropertyConsumer ) editor ) . setProperties ( marker , info ) ; } editors . put ( prop , editor ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; editorClass = null ; } Component editorFace = null ; if ( editor != null && editor . supportsCustomEditor ( ) ) { editorFace = editor . getCustomEditor ( ) ; } else { editorFace = new JLabel ( i18n . get ( Inspector . class , ""Does_not_support_custom_editor"" , ""Does not support custom editor"" ) ) ; } if ( editor != null ) { Object propVal = props . get ( prop ) ; if ( Debug . debugging ( ""inspector"" ) ) { Debug . output ( ""Inspector loading "" + prop + ""("" + propVal + "")"" ) ; } editor . setValue ( propVal ) ; } String labelMarker = marker + PropertyConsumer . LabelEditorProperty ; String labelText = info . getProperty ( labelMarker ) ; if ( labelText == null ) { labelText = marker ; } JLabel label = new JLabel ( labelText + "":"" ) ; label . setHorizontalAlignment ( SwingConstants . RIGHT ) ; c . gridx = 0 ; c . gridy = i ++ ; c . weightx = 0 ; c . fill = GridBagConstraints . NONE ; c . anchor = GridBagConstraints . EAST ; gridbag . setConstraints ( label , c ) ; propertyPanel . add ( label ) ; c . gridx = 1 ; c . anchor = GridBagConstraints . WEST ; c . fill = GridBagConstraints . HORIZONTAL ; c . weightx = 1f ; gridbag . setConstraints ( editorFace , c ) ; propertyPanel . add ( editorFace ) ; String toolTip = ( String ) info . get ( marker ) ; label . setToolTipText ( toolTip == null ? i18n . get ( Inspector . class , ""No_further_information_available"" , ""No further information available."" ) : toolTip ) ; } JScrollPane scrollPane = new JScrollPane ( propertyPanel , ScrollPaneConstants . VERTICAL_SCROLLBAR_AS_NEEDED , ScrollPaneConstants . HORIZONTAL_SCROLLBAR_NEVER ) ; scrollPane . setBorder ( null ) ; scrollPane . setAlignmentY ( Component . TOP_ALIGNMENT ) ; component . add ( scrollPane , BorderLayout . CENTER ) ; return component ; }" Creates a JComponent with the properties to be changed . This component is suitable for inclusion into a GUI . Do n't use this method directly ! Use the createPropertyGUI ( PropertyConsumer ) instead . You will get a NullPointerException if you use this method without setting the PropertyConsumer in the Inspector . +"public void onScanImageClick ( View v ) { Intent intent = new Intent ( this , ScanImageActivity . class ) ; intent . putExtra ( ExtrasKeys . EXTRAS_LICENSE_KEY , LICENSE_KEY ) ; intent . putExtra ( ExtrasKeys . EXTRAS_RECOGNITION_SETTINGS , mRecognitionSettings ) ; startActivityForResult ( intent , MY_REQUEST_CODE ) ; }" Handler for `` Scan Image '' button +"public boolean isReadOnly ( ) { Object oo = get_Value ( COLUMNNAME_IsReadOnly ) ; if ( oo != null ) { if ( oo instanceof Boolean ) return ( ( Boolean ) oo ) . booleanValue ( ) ; return ""Y"" . equals ( oo ) ; } return false ; }" Get Read Only . +"public static < K , V > Map < K , V > asSynchronized ( Map < K , V > self ) { return Collections . synchronizedMap ( self ) ; }" A convenience method for creating a synchronized Map . +private boolean isRecursive ( Nonterminal nonterm ) { return comp . getNodes ( ) . contains ( nonterm ) ; } Return true if the nonterminal is recursive . +"private void initInfo ( int record_id , String value ) { if ( ! ( record_id == 0 ) && value != null && value . length ( ) > 0 ) { log . severe ( ""Received both a record_id and a value: "" + record_id + "" - "" + value ) ; } if ( ! ( record_id == 0 ) ) { fieldID = record_id ; } else { if ( value != null && value . length ( ) > 0 ) { fDocumentNo . setValue ( value ) ; } else { String id ; id = Env . getContext ( Env . getCtx ( ) , p_WindowNo , p_TabNo , ""M_InOut_ID"" , true ) ; if ( id != null && id . length ( ) != 0 && ( new Integer ( id ) . intValue ( ) > 0 ) ) { fieldID = new Integer ( id ) . intValue ( ) ; } id = Env . getContext ( Env . getCtx ( ) , p_WindowNo , p_TabNo , ""C_BPartner_ID"" , true ) ; if ( id != null && id . length ( ) != 0 && ( new Integer ( id ) . intValue ( ) > 0 ) ) fBPartner_ID . setValue ( new Integer ( id ) ) ; id = Env . getContext ( Env . getCtx ( ) , p_WindowNo , p_TabNo , ""M_Shipper_ID"" , true ) ; if ( id != null && id . length ( ) != 0 && ( new Integer ( id ) . intValue ( ) > 0 ) ) { fShipper_ID . setValue ( new Integer ( id ) . intValue ( ) ) ; } } } }" General Init +public IssueMatcher add ( ) { IssueMatcher issueMatcher = new IssueMatcher ( ) ; issueMatchers . add ( issueMatcher ) ; return issueMatcher ; } Creates a new issue matcher and adds it to this matcher . +protected ParameterizedPropertyAccessExpression_IMImpl ( ) { super ( ) ; } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"private void loadFinishScreen ( ) { CoordinatorLayout . LayoutParams lp = new CoordinatorLayout . LayoutParams ( CoordinatorLayout . LayoutParams . WRAP_CONTENT , CoordinatorLayout . LayoutParams . WRAP_CONTENT ) ; mFloatingActionButton . setLayoutParams ( lp ) ; mFloatingActionButton . setVisibility ( View . INVISIBLE ) ; NestedScrollView contentLayout = ( NestedScrollView ) findViewById ( R . id . challenge_rootcontainer ) ; if ( contentLayout != null ) { contentLayout . removeAllViews ( ) ; View view = getLayoutInflater ( ) . inflate ( R . layout . fragment_finish_challenge , contentLayout , false ) ; contentLayout . addView ( view ) ; } }" Loads the finish screen and unloads all other screens +"private void compactSegment ( Segment segment , OffsetPredicate predicate , Segment compactSegment ) { for ( long i = segment . firstIndex ( ) ; i <= segment . lastIndex ( ) ; i ++ ) { checkEntry ( i , segment , predicate , compactSegment ) ; } }" Compacts the given segment . +"public static Class < ? > forName ( String name , ClassLoader classLoader ) throws ClassNotFoundException , LinkageError { Assert . notNull ( name , ""Name must not be null"" ) ; Class < ? > clazz = resolvePrimitiveClassName ( name ) ; if ( clazz == null ) { clazz = commonClassCache . get ( name ) ; } if ( clazz != null ) { return clazz ; } if ( name . endsWith ( ARRAY_SUFFIX ) ) { String elementClassName = name . substring ( 0 , name . length ( ) - ARRAY_SUFFIX . length ( ) ) ; Class < ? > elementClass = forName ( elementClassName , classLoader ) ; return Array . newInstance ( elementClass , 0 ) . getClass ( ) ; } if ( name . startsWith ( NON_PRIMITIVE_ARRAY_PREFIX ) && name . endsWith ( "";"" ) ) { String elementName = name . substring ( NON_PRIMITIVE_ARRAY_PREFIX . length ( ) , name . length ( ) - 1 ) ; Class < ? > elementClass = forName ( elementName , classLoader ) ; return Array . newInstance ( elementClass , 0 ) . getClass ( ) ; } if ( name . startsWith ( INTERNAL_ARRAY_PREFIX ) ) { String elementName = name . substring ( INTERNAL_ARRAY_PREFIX . length ( ) ) ; Class < ? > elementClass = forName ( elementName , classLoader ) ; return Array . newInstance ( elementClass , 0 ) . getClass ( ) ; } ClassLoader classLoaderToUse = classLoader ; if ( classLoaderToUse == null ) { classLoaderToUse = getDefaultClassLoader ( ) ; } try { return classLoaderToUse . loadClass ( name ) ; } catch ( ClassNotFoundException ex ) { int lastDotIndex = name . lastIndexOf ( '.' ) ; if ( lastDotIndex != - 1 ) { String innerClassName = name . substring ( 0 , lastDotIndex ) + '$' + name . substring ( lastDotIndex + 1 ) ; try { return classLoaderToUse . loadClass ( innerClassName ) ; } catch ( ClassNotFoundException ex2 ) { } } throw ex ; } }" "Replacement for < code > Class.forName ( ) < /code > that also returns Class instances for primitives ( e.g . `` int '' ) and array class names ( e.g . `` String [ ] '' ) . Furthermore , it is also capable of resolving inner class names in Java source style ( e.g . `` java.lang.Thread.State '' instead of `` java.lang.Thread $ State '' ) ." +"public String toString ( int indentFactor ) throws JSONException { return toString ( indentFactor , 0 ) ; }" Make a prettyprinted JSON text of this JSONObject . < p > Warning : This method assumes that the data structure is acyclical . +"@ SuppressWarnings ( ""MethodWithMultipleReturnPoints"" ) public static boolean checkSu ( ) { if ( ! new File ( ""/system/bin/su"" ) . exists ( ) && ! new File ( ""/system/xbin/su"" ) . exists ( ) ) { Log . e ( TAG , ""su binary does not exist!!!"" ) ; return false ; } try { if ( runSuCommand ( ""ls /data/app-private"" ) . success ( ) ) { Log . i ( TAG , "" SU exists and we have permission"" ) ; return true ; } else { Log . i ( TAG , "" SU exists but we don't have permission"" ) ; return false ; } } catch ( NullPointerException e ) { Log . e ( TAG , ""NullPointer throw while looking for su binary"" , e ) ; return false ; } }" Checks device for SuperUser permission +"public String toString ( int indentFactor ) throws JSONException { StringWriter sw = new StringWriter ( ) ; synchronized ( sw . getBuffer ( ) ) { return this . write ( sw , indentFactor , 0 ) . toString ( ) ; } }" Make a prettyprinted JSON text of this JSONArray . Warning : This method assumes that the data structure is acyclical . +public Boolean isHttpSupportInformation ( ) { return httpSupportInformation ; } Ruft den Wert der httpSupportInformation-Eigenschaft ab . +"public static URLConnection createConnectionToURL ( final String url , final Map < String , String > requestHeaders ) throws IOException { final URL connectionURL = URLUtility . stringToUrl ( url ) ; if ( connectionURL == null ) { throw new IOException ( ""Invalid url format: "" + url ) ; } final URLConnection urlConnection = connectionURL . openConnection ( ) ; urlConnection . setConnectTimeout ( CONNECTION_TIMEOUT ) ; urlConnection . setReadTimeout ( READ_TIMEOUT ) ; if ( requestHeaders != null ) { for ( final Map . Entry < String , String > entry : requestHeaders . entrySet ( ) ) { urlConnection . setRequestProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return urlConnection ; }" Create URLConnection instance . +public ASN1Primitive toASN1Primitive ( ) { try { if ( certificateType == profileType ) { return profileToASN1Object ( ) ; } if ( certificateType == requestType ) { return requestToASN1Object ( ) ; } } catch ( IOException e ) { return null ; } return null ; } create a `` request '' or `` profile '' type Iso7816CertificateBody according to the variables sets . +public Builder mapper ( final Mapper < ObjectMapper > mapper ) { this . mapper = mapper ; return this ; } Override all of the builder options with this mapper . If this value is set to something other than null then that value will be used to construct the writer . +"private int [ ] [ ] div ( int [ ] a , int [ ] f ) { int df = computeDegree ( f ) ; int da = computeDegree ( a ) + 1 ; if ( df == - 1 ) { throw new ArithmeticException ( ""Division by zero."" ) ; } int [ ] [ ] result = new int [ 2 ] [ ] ; result [ 0 ] = new int [ 1 ] ; result [ 1 ] = new int [ da ] ; int hc = headCoefficient ( f ) ; hc = field . inverse ( hc ) ; result [ 0 ] [ 0 ] = 0 ; System . arraycopy ( a , 0 , result [ 1 ] , 0 , result [ 1 ] . length ) ; while ( df <= computeDegree ( result [ 1 ] ) ) { int [ ] q ; int [ ] coeff = new int [ 1 ] ; coeff [ 0 ] = field . mult ( headCoefficient ( result [ 1 ] ) , hc ) ; q = multWithElement ( f , coeff [ 0 ] ) ; int n = computeDegree ( result [ 1 ] ) - df ; q = multWithMonomial ( q , n ) ; coeff = multWithMonomial ( coeff , n ) ; result [ 0 ] = add ( coeff , result [ 0 ] ) ; result [ 1 ] = add ( q , result [ 1 ] ) ; } return result ; }" Compute the result of the division of two polynomials over the field < tt > GF ( 2^m ) < /tt > . +"public static short toShort ( byte [ ] bytes , int start ) { return toShort ( bytes [ start ] , bytes [ start + 1 ] ) ; }" Returns short from given array of bytes . < br > Array must have at least start + 2 elements in it . +"public void addAttribute ( AttributedCharacterIterator . Attribute attribute , Object value , int start , int end ) { if ( attribute == null ) { throw new NullPointerException ( ""attribute == null"" ) ; } if ( start < 0 || end > text . length ( ) || start >= end ) { throw new IllegalArgumentException ( ) ; } if ( value == null ) { return ; } List < Range > ranges = attributeMap . get ( attribute ) ; if ( ranges == null ) { ranges = new ArrayList < Range > ( 1 ) ; ranges . add ( new Range ( start , end , value ) ) ; attributeMap . put ( attribute , ranges ) ; return ; } ListIterator < Range > it = ranges . listIterator ( ) ; while ( it . hasNext ( ) ) { Range range = it . next ( ) ; if ( end <= range . start ) { it . previous ( ) ; break ; } else if ( start < range . end || ( start == range . end && value . equals ( range . value ) ) ) { Range r1 = null , r3 ; it . remove ( ) ; r1 = new Range ( range . start , start , range . value ) ; r3 = new Range ( end , range . end , range . value ) ; while ( end > range . end && it . hasNext ( ) ) { range = it . next ( ) ; if ( end <= range . end ) { if ( end > range . start || ( end == range . start && value . equals ( range . value ) ) ) { it . remove ( ) ; r3 = new Range ( end , range . end , range . value ) ; break ; } } else { it . remove ( ) ; } } if ( value . equals ( r1 . value ) ) { if ( value . equals ( r3 . value ) ) { it . add ( new Range ( r1 . start < start ? r1 . start : start , r3 . end > end ? r3 . end : end , r1 . value ) ) ; } else { it . add ( new Range ( r1 . start < start ? r1 . start : start , end , r1 . value ) ) ; if ( r3 . start < r3 . end ) { it . add ( r3 ) ; } } } else { if ( value . equals ( r3 . value ) ) { if ( r1 . start < r1 . end ) { it . add ( r1 ) ; } it . add ( new Range ( start , r3 . end > end ? r3 . end : end , r3 . value ) ) ; } else { if ( r1 . start < r1 . end ) { it . add ( r1 ) ; } it . add ( new Range ( start , end , value ) ) ; if ( r3 . start < r3 . end ) { it . add ( r3 ) ; } } } return ; } } it . add ( new Range ( start , end , value ) ) ; }" Applies a given attribute to the given range of this string . +"@ Override public Double hincrByFloat ( final String key , final String field , final double value ) { checkIsInMultiOrPipeline ( ) ; client . hincrByFloat ( key , field , value ) ; final String dval = client . getBulkReply ( ) ; return ( dval != null ? new Double ( dval ) : null ) ; }" "Increment the number stored at field in the hash at key by a double precision floating point value . If key does not exist , a new key holding a hash is created . If field does not exist or holds a string , the value is set to 0 before applying the operation . Since the value argument is signed you can use this command to perform both increments and decrements . < p > The range of values supported by HINCRBYFLOAT is limited to double precision floating point values . < p > < b > Time complexity : < /b > O ( 1 )" +public DrawerBuilder withFooter ( @ NonNull View footerView ) { this . mFooterView = footerView ; return this ; } Add a footer to the DrawerBuilder ListView . This can be any view +"@ Override public int compareTo ( final Object obj ) throws ClassCastException { final URI another = ( URI ) obj ; if ( ! equals ( _authority , another . getRawAuthority ( ) ) ) { return - 1 ; } return toString ( ) . compareTo ( another . toString ( ) ) ; }" Compare this URI to another object . +public boolean isNavigationAtBottom ( ) { return ( mSmallestWidthDp >= 600 || mInPortrait ) ; } Should a navigation bar appear at the bottom of the screen in the current device configuration ? A navigation bar may appear on the right side of the screen in certain configurations . +"@ Override public void execute ( String filePath ) { final CurrentProject currentProject = appContext . getCurrentProject ( ) ; if ( filePath != null && ! filePath . startsWith ( ""/"" ) ) { filePath = ""/"" . concat ( filePath ) ; } if ( currentProject != null ) { String fullPath = currentProject . getRootProject ( ) . getPath ( ) + filePath ; log . debug ( ""Open file {0}"" , fullPath ) ; currentProject . getCurrentTree ( ) . getNodeByPath ( fullPath , new TreeNodeAsyncCallback ( ) ) ; } }" Open a file for the current given path . +"public void executionDetailsEnd ( final ConcurrentHashMap < Integer , TradeOrder > tradeOrders ) { try { Tradingday todayTradingday = m_tradingdays . getTradingday ( TradingCalendar . getTradingDayStart ( TradingCalendar . getDateTimeNowMarketTimeZone ( ) ) , TradingCalendar . getTradingDayEnd ( TradingCalendar . getDateTimeNowMarketTimeZone ( ) ) ) ; if ( null == todayTradingday ) { return ; } tradingdayPanel . doRefresh ( todayTradingday ) ; tradingdayPanel . doRefreshTradingdayTable ( todayTradingday ) ; } catch ( Exception ex ) { this . setErrorMessage ( ""Error starting PositionManagerRule."" , ex . getMessage ( ) , ex ) ; } }" This method is fired when the Brokermodel has completed the request for Execution Details see doFetchExecution or connectionOpened i.e from a BrokerModel event all executions for the filter have now been received . Check to see if we need to close any trades for these order fills . +public void successfullyCreated ( ) { if ( notification != null ) { notification . setStatus ( SUCCESS ) ; notification . setTitle ( locale . createSnapshotSuccess ( ) ) ; } } Changes notification state to successfully finished . +"public HybridTimestampFactory ( int counterBits ) { if ( counterBits < 0 || counterBits > 31 ) { throw new IllegalArgumentException ( ""counterBits must be in [0:31]"" ) ; } lastTimestamp = 0L ; this . counterBits = counterBits ; maxCounter = BigInteger . valueOf ( 2 ) . pow ( counterBits ) . intValue ( ) - 1 ; log . warn ( ""#counterBits="" + counterBits + "", maxCounter="" + maxCounter ) ; }" Allows up to < code > 2^counterBits < /code > distinct timestamps per millisecond . +@ Override public void clear ( ) { this . _map . clear ( ) ; } Empties the map . +"public boolean removeElement ( int s ) { if ( null == m_map ) return false ; for ( int i = 0 ; i < m_firstFree ; i ++ ) { int node = m_map [ i ] ; if ( node == s ) { if ( i > m_firstFree ) System . arraycopy ( m_map , i + 1 , m_map , i - 1 , m_firstFree - i ) ; else m_map [ i ] = DTM . NULL ; m_firstFree -- ; return true ; } } return false ; }" "Removes the first occurrence of the argument from this vector . If the object is found in this vector , each component in the vector with an index greater or equal to the object 's index is shifted downward to have an index one smaller than the value it had previously ." +"private void addSingleton ( TempCluster clus , DBIDRef id , double dist , boolean asCluster ) { if ( asCluster ) { clus . addChild ( makeSingletonCluster ( id , dist ) ) ; } else { clus . add ( id ) ; } clus . depth = dist ; }" "Add a singleton object , as point or cluster ." +public int size ( ) { return values . length ; } Returns the number of values in this kernel . +"private void testServerJoinLate ( Member . Type type , CopycatServer . State state ) throws Throwable { createServers ( 3 ) ; CopycatClient client = createClient ( ) ; submit ( client , 0 , 1000 ) ; await ( 30000 ) ; CopycatServer joiner = createServer ( nextMember ( type ) ) ; joiner . onStateChange ( null ) ; joiner . join ( members . stream ( ) . map ( null ) . collect ( Collectors . toList ( ) ) ) . thenRun ( null ) ; await ( 30000 , 2 ) ; }" Tests joining a server after many entries have been committed . +"fun createRadioButton(x: Int, y: Int, diameter: Int): Shape? { return createEllipseInternal(x, y, diameter, diameter) }" Return a path for a radio button 's concentric sections . +"@DSComment(""From safe class list"") @DSSafe(DSCat.SAFE_LIST) @DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"", generated_on = ""2013-12-30 12:57:11.638 -0500"", hash_original_method = ""3CEC44303CC022BBEC9F119BC403FDBC"", hash_generated_method = ""FD349EDA389F166F5AB5B32AD7B69928"" ) fun size(): Int { return al.size() }" Returns the number of elements in this set . +"fun formatRateString(rate: Float): String? { return String.format(Locale.US, ""%.2fx"", rate) }" Get the formatted current playback speed in the form of 1.00x +"@Throws(FileNotFoundException::class) private fun decodeImageForOption(resolver: ContentResolver, uri: Uri): BitmapFactory.Options? { var stream: InputStream? = null return try { stream = resolver.openInputStream(uri) val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeStream(stream, EMPTY_RECT, options) options.inJustDecodeBounds = false options } finally { closeSafe(stream) } }" Decode image from uri using `` inJustDecodeBounds '' to get the image dimensions . +fun FinalSQLString(sqlstring: BasicSQLString) { this.delegate = sqlstring } Should only be called inside SQLString because this class essentially verifies that we 've checked for updates . +fun loadArgArray() { push(argumentTypes.length) newArray(jdk.internal.org.objectweb.asm.commons.InstructionAdapter.OBJECT_TYPE) for (i in 0 until argumentTypes.length) { dup() push(i) loadArg(i) jdk.internal.vm.compiler.word.impl.WordBoxFactory.box( argumentTypes.get(i) ) arrayStore(jdk.internal.org.objectweb.asm.commons.InstructionAdapter.OBJECT_TYPE) } } "Generates the instructions to load all the method arguments on the stack , as a single object array ." +"@Throws(ServletException::class, IOException::class) fun doGet(request: HttpServletRequest?, response: HttpServletResponse?) { WebUtil.createLoginPage(request, response, this, null, null) }" Process the HTTP Get request +"private fun DeferredFileOutputStream( threshold: Int, outputFile: File, prefix: String, suffix: String, directory: File ) { super(threshold) outputFile = outputFile memoryOutputStream = ByteArrayOutputStream() currentOutputStream = memoryOutputStream prefix = prefix suffix = suffix directory = directory }" "Constructs an instance of this class which will trigger an event at the specified threshold , and save data either to a file beyond that point ." +"fun testSetSystemScope() { val systemScope: IdentityScope = IdentityScope.getSystemScope() try { `is` = IdentityScopeStub(""Aleksei Semenov"") IdentityScopeStub.mySetSystemScope(`is`) assertSame(`is`, IdentityScope.getSystemScope()) } finally { IdentityScopeStub.mySetSystemScope(systemScope) } }" check that if permission given - set/get works if permission is denied than SecurityException is thrown +"@JvmStatic fun main(args: Array) { runEvaluator(WrapperSubsetEval(), args) }" Main method for testing this class . +"fun v(tag: String?, msg: String?, vararg args: Any?) { var msg = msg if (sLevel > LEVEL_VERBOSE) { return } if (args.size > 0) { msg = String.format(msg!!, *args) } Log.v(tag, msg) }" Send a VERBOSE log message . +"@DSComment(""Package priviledge"") @DSBan(DSCat.DEFAULT_MODIFIER) @DSGenerator( tool_name = ""Doppelganger"", tool_version = ""2.0"",generated_on = ""2013-12-30 12:58:04.267 -0500"", hash_original_method = ""2CE5F24A4C571BEECB25C40400E44908"", hash_generated_method = ""A3579B97578194B5EA0183D0F747142C"" ) fun computeNextElement() { while (true) { if (currentBits !== 0) { mask = currentBits and -currentBits return } else if (++index < bits.length) { currentBits = bits.get(index) } else { mask = 0 return } } }" "Assigns mask and index to the next available value , cycling currentBits as necessary ." +"fun HierarchyEvent( source: Component?, id: Int, changed: Component, changedParent: Container, changeFlags: Long ) { super(source, id) changed = changed changedParent = changedParent changeFlags = changeFlags }" Constructs an < code > HierarchyEvent < /code > object to identify a change in the < code > Component < /code > hierarchy . < p > This method throws an < code > IllegalArgumentException < /code > if < code > source < /code > is < code > null < /code > . +fun step(state: SimState?) {} "This method is performed when the next step for the agent is computed . This agent does nothing , so nothing is inside the body of the method ." +fun resetRuntime() { currentTime = 1392409281320L wasTimeAccessed = false hashKeys.clear() restoreProperties() needToRestoreProperties = false } Reset runtime to initial state +"fun ExpandCaseMultipliersAction(editor: DataEditor?) { super(""Expand Case Multipliers"") if (editor == null) { throw NullPointerException() } this.dataEditor = editor }" Creates a new action to split by collinear columns . +fun ScaleFake() {} Creates a new instance of ScaleFake +protected fun ArrayElementImpl() { super() } < ! -- begin-user-doc -- > < ! -- end-user-doc -- > +"fun FilterRowIterator(rows: IntIterator, t: Table, p: Predicate) { this.predicate = p rows = rows t = t next = advance() }" Create a new FilterRowIterator . +"@Throws(JasperException::class) private fun scanJar(conn: JarURLConnection, tldNames: List?, isLocal: Boolean) { val resourcePath: String = conn.getJarFileURL().toString() var tldInfos: Array = jarTldCacheLocal.get(resourcePath) if (tldInfos != null && tldInfos.size == 0) { try { conn.getJarFile().close() } catch (ex: IOException) { } return } if (tldInfos == null) { var jarFile: JarFile? = null val tldInfoA: ArrayList = ArrayList() try { jarFile = conn.getJarFile() if (tldNames != null) { for (tldName in tldNames) { val entry: JarEntry = jarFile.getJarEntry(tldName) val stream: InputStream = jarFile.getInputStream(entry) tldInfoA.add(scanTld(resourcePath, tldName, stream)) } } else { val entries: Enumeration = jarFile.entries() while (entries.hasMoreElements()) { val entry: JarEntry = entries.nextElement() val name: String = entry.getName() if (!name.startsWith(""META-INF/"")) continue if (!name.endsWith("".tld"")) continue val stream: InputStream = jarFile.getInputStream(entry) tldInfoA.add(scanTld(resourcePath, name, stream)) } } } catch (ex: IOException) { if (resourcePath.startsWith(FILE_PROTOCOL) && !File(resourcePath).exists()) { if (log.isLoggable(Level.WARNING)) { log.log( Level.WARNING, Localizer.getMessage(""jsp.warn.nojar"", resourcePath), ex ) } } else { throw JasperException( Localizer.getMessage(""jsp.error.jar.io"", resourcePath), ex ) } } finally { if (jarFile != null) { try { jarFile.close() } catch (t: Throwable) { } } } tldInfos = tldInfoA.toArray(arrayOfNulls(tldInfoA.size())) jarTldCacheLocal.put(resourcePath, tldInfos) if (!isLocal) { jarTldCache.put(resourcePath, tldInfos) } } for (tldInfo in tldInfos) { if (scanListeners) { addListener(tldInfo, isLocal) } mapTldLocation(resourcePath, tldInfo, isLocal) } }" "Scans the given JarURLConnection for TLD files located in META-INF ( or a subdirectory of it ) . If the scanning in is done as part of the ServletContextInitializer , the listeners in the tlds in this jar file are added to the servlet context , and for any TLD that has a < uri > element , an implicit map entry is added to the taglib map ." +fun cosft1(y: DoubleArray?) { com.nr.fft.FFT.cosft1(y) } "Calculates the cosine transform of a set y [ 0..n ] of real-valued data points . The transformed data replace the original data in array y. n must be a power of 2 . This program , without changes , also calculates the inverse cosine transform , but in this case the output array should be multiplied by 2/n ." +fun stop() { mRunning = false mStop = true } Stops the animation in place . It does not snap the image to its final translation . +operator fun hasNext(): Boolean { return cursor > 0 } This is used to determine if the cursor has reached the start of the list . When the cursor reaches the start of the list then this method returns false . +"protected fun onFinished(player: Player, successful: Boolean) { if (successful) { val itemName: String = items.get(Rand.rand(items.length)) val item: Item = SingletonRepository.getEntityManager().getItem(itemName) var amount = 1 if (itemName == ""dark dagger"" || itemName == ""horned golden helmet"") { item.setBoundTo(player.getName()) } else if (itemName == ""money"") { amount = Rand.roll1D100() (item as StackableItem).setQuantity(amount) } player.equipOrPutOnGround(item) player.incObtainedForItem(item.getName(), item.getQuantity()) SingletonRepository.getAchievementNotifier().onObtain(player) player.sendPrivateText( ""You were lucky and found "" + com.sun.org.apache.xerces.internal.xni.grammars.Grammar.quantityplnoun( amount, itemName, ""a"" ).toString() + ""."" ) } else { player.sendPrivateText(""Your wish didn't come true."") } }" Called when the activity has finished . +"fun saveWalletAndWalletInfoSimple( perWalletModelData: WalletData, walletFilename: String?, walletInfoFilename: String? ) { val walletFile = File(walletFilename) val walletInfo: WalletInfoData = perWalletModelData.getWalletInfo() var fileOutputStream: FileOutputStream? = null try { if (perWalletModelData.getWallet() != null) { if (walletInfo != null) { val walletDescriptionInInfoFile: String = walletInfo.getProperty(WalletInfoData.DESCRIPTION_PROPERTY) if (walletDescriptionInInfoFile != null) { perWalletModelData.getWallet().setDescription(walletDescriptionInInfoFile) } } log.debug( ""Saving wallet file '"" + walletFile.getAbsolutePath().toString() + ""' ..."" ) if (MultiBitWalletVersion.SERIALIZED === walletInfo.getWalletVersion()) { throw WalletSaveException( ""Cannot save wallet '"" + walletFile.getAbsolutePath() .toString() + ""'. Serialized wallets are no longer supported."" ) } else { var walletIsActuallyEncrypted = false val wallet: Wallet = perWalletModelData.getWallet() for (key in wallet.getKeychain()) { if (key.isEncrypted()) { walletIsActuallyEncrypted = true break } } if (walletIsActuallyEncrypted) { walletInfo.setWalletVersion(MultiBitWalletVersion.PROTOBUF_ENCRYPTED) } if (MultiBitWalletVersion.PROTOBUF === walletInfo.getWalletVersion()) { perWalletModelData.getWallet().saveToFile(walletFile) } else if (MultiBitWalletVersion.PROTOBUF_ENCRYPTED === walletInfo.getWalletVersion()) { fileOutputStream = FileOutputStream(walletFile) walletProtobufSerializer.writeWallet( perWalletModelData.getWallet(), fileOutputStream ) } else { throw WalletVersionException( ""Cannot save wallet '"" + perWalletModelData.getWalletFilename() .toString() + ""'. Its wallet version is '"" + walletInfo.getWalletVersion() .toString() .toString() + ""' but this version of MultiBit does not understand that format."" ) } } log.debug(""... done saving wallet file."") } } catch (ioe: IOException) { throw WalletSaveException( ""Cannot save wallet '"" + perWalletModelData.getWalletFilename(), ioe ) } finally { if (fileOutputStream != null) { try { fileOutputStream.flush() fileOutputStream.close() } catch (e: IOException) { throw WalletSaveException( ""Cannot save wallet '"" + perWalletModelData.getWalletFilename(), e ) } } } walletInfo.writeToFile(walletInfoFilename, walletInfo.getWalletVersion()) }" Simply save the wallet and wallet info files . Used for backup writes . +"@Throws(CloneNotSupportedException::class) fun clone(): Any? { val clone: DefaultIntervalXYDataset = super.clone() as DefaultIntervalXYDataset clone.seriesKeys = ArrayList(this.seriesKeys) clone.seriesList = ArrayList(this.seriesList.size()) for (i in 0 until this.seriesList.size()) { val data = this.seriesList.get(i) as Array val x = data[0] val xStart = data[1] val xEnd = data[2] val y = data[3] val yStart = data[4] val yEnd = data[5] val xx = DoubleArray(x.size) val xxStart = DoubleArray(xStart.size) val xxEnd = DoubleArray(xEnd.size) val yy = DoubleArray(y.size) val yyStart = DoubleArray(yStart.size) val yyEnd = DoubleArray(yEnd.size) System.arraycopy(x, 0, xx, 0, x.size) System.arraycopy(xStart, 0, xxStart, 0, xStart.size) System.arraycopy(xEnd, 0, xxEnd, 0, xEnd.size) System.arraycopy(y, 0, yy, 0, y.size) System.arraycopy(yStart, 0, yyStart, 0, yStart.size) System.arraycopy(yEnd, 0, yyEnd, 0, yEnd.size) clone.seriesList.add(i, arrayOf(xx, xxStart, xxEnd, yy, yyStart, yyEnd)) } return clone }" Returns a clone of this dataset . +"fun EveningActivityMovement(settings: Settings) { super(settings) super.backAllowed = false pathFinder = DijkstraPathFinder(null) mode = WALKING_TO_MEETING_SPOT_MODE nrOfMeetingSpots = settings.getInt(NR_OF_MEETING_SPOTS_SETTING) minGroupSize = settings.getInt(MIN_GROUP_SIZE_SETTING) maxGroupSize = settings.getInt(MAX_GROUP_SIZE_SETTING) val mapNodes: Array = jdk.nashorn.internal.objects.Global.getMap().getNodes() .toArray(arrayOfNulls(0)) var shoppingSpotsFile: String? = null try { shoppingSpotsFile = settings.getSetting(MEETING_SPOTS_FILE_SETTING) } catch (t: Throwable) { } var meetingSpotLocations: MutableList? = null if (shoppingSpotsFile == null) { meetingSpotLocations = LinkedList() for (i in mapNodes.indices) { if (i % (mapNodes.size / nrOfMeetingSpots) === 0) { startAtLocation = mapNodes[i].getLocation().clone() meetingSpotLocations!!.add(startAtLocation.clone()) } } } else { try { meetingSpotLocations = LinkedList() val locationsRead: List = WKTReader().readPoints(File(shoppingSpotsFile)) for (coord in locationsRead) { val map: SimMap = jdk.nashorn.internal.objects.Global.getMap() val offset: Coord = map.getOffset() if (map.isMirrored()) { coord.setLocation(coord.getX(), -coord.getY()) } coord.translate(offset.getX(), offset.getY()) meetingSpotLocations!!.add(coord) } } catch (e: Exception) { e.printStackTrace() } } this.id = nextID++ val scsID: Int = settings.getInt(EVENING_ACTIVITY_CONTROL_SYSTEM_NR_SETTING) scs = EveningActivityControlSystem.getEveningActivityControlSystem(scsID) scs.setRandomNumberGenerator(rng) scs.addEveningActivityNode(this) scs.setMeetingSpots(meetingSpotLocations) maxPathLength = 100 minPathLength = 10 maxWaitTime = settings.getInt(MAX_WAIT_TIME_SETTING) minWaitTime = settings.getInt(MIN_WAIT_TIME_SETTING) }" Creates a new instance of EveningActivityMovement +"protected fun makeHullComplex(pc: Array): java.awt.Polygon? { val hull = GrahamScanConvexHull2D() val diag = doubleArrayOf(0.0, 0.0) for (j in pc.indices) { hull.add(pc[j]) hull.add(javax.management.Query.times(pc[j], -1)) for (k in j + 1 until pc.size) { val q = pc[k] val ppq: DoubleArray = timesEquals( javax.management.Query.plus(pc[j], q), org.graalvm.compiler.loop.MathUtil.SQRTHALF ) val pmq: DoubleArray = timesEquals(minus(pc[j], q), org.graalvm.compiler.loop.MathUtil.SQRTHALF) hull.add(ppq) hull.add(javax.management.Query.times(ppq, -1)) hull.add(pmq) hull.add(javax.management.Query.times(pmq, -1)) for (l in k + 1 until pc.size) { val r = pc[k] val ppqpr: DoubleArray = timesEquals(javax.management.Query.plus(ppq, r), Math.sqrt(1 / 3.0)) val pmqpr: DoubleArray = timesEquals(javax.management.Query.plus(pmq, r), Math.sqrt(1 / 3.0)) val ppqmr: DoubleArray = timesEquals(minus(ppq, r), Math.sqrt(1 / 3.0)) val pmqmr: DoubleArray = timesEquals(minus(pmq, r), Math.sqrt(1 / 3.0)) hull.add(ppqpr) hull.add(javax.management.Query.times(ppqpr, -1)) hull.add(pmqpr) hull.add(javax.management.Query.times(pmqpr, -1)) hull.add(ppqmr) hull.add(javax.management.Query.times(ppqmr, -1)) hull.add(pmqmr) hull.add(javax.management.Query.times(pmqmr, -1)) } } plusEquals(diag, pc[j]) } timesEquals(diag, 1.0 / Math.sqrt(pc.size.toDouble())) hull.add(diag) hull.add(javax.management.Query.times(diag, -1)) return hull.getHull() }" Build a convex hull to approximate the sphere . +"fun visitAnnotations(node: AnnotatedNode) { super.visitAnnotations(node) for (annotation in node.getAnnotations()) { if (transforms.containsKey(annotation)) { targetNodes.add(arrayOf(annotation, node)) } } }" Adds the annotation to the internal target list if a match is found . +"fun Node(next: Node) { this.key = null this.value = this next = next }" "Creates a new marker node . A marker is distinguished by having its value field point to itself . Marker nodes also have null keys , a fact that is exploited in a few places , but this does n't distinguish markers from the base-level header node ( head.node ) , which also has a null key ." +fun onDrawerClosed(view: View?) { super.onDrawerClosed(view) } Called when a drawer has settled in a completely closed state . +"fun deserializeAddressList(serializedAddresses: String): List? { return Arrays.asList(serializedAddresses.split("","").toTypedArray()) }" Deserialize a list of IP addresses from a string . +@Throws(IOException::class) fun challengeReceived(challenge: String?) { currentMechanism.challengeReceived(challenge) } The server is challenging the SASL authentication we just sent . Forward the challenge to the current SASLMechanism we are using . The SASLMechanism will send a response to the server . The length of the challenge-response sequence varies according to the SASLMechanism in use . +"fun fitsType(env: Environment?, ctx: Context?, t: Type): Boolean { if (this.type.isType(TC_CHAR)) { return super.fitsType(env, ctx, t) } when (t.getTypeCode()) { TC_BYTE -> return value === value as Byte TC_SHORT -> return value === value as Short TC_CHAR -> return value === value as Char } return super.fitsType(env, ctx, t) }" See if this number fits in the given type . +"fun ServiceManager(services: Iterable?) { var copy: ImmutableList = ImmutableList.copyOf(services) if (copy.isEmpty()) { logger.log( Level.WARNING, ""ServiceManager configured with no services. Is your application configured properly?"", EmptyServiceManagerWarning() ) copy = ImmutableList.< Service > of < Service ? > NoOpService() } this.state = ServiceManagerState(copy) services = copy val stateReference: WeakReference = WeakReference(state) for (service in copy) { service.addListener( ServiceListener(service, stateReference), MoreExecutors.directExecutor() ) checkArgument(service.state() === NEW, ""Can only manage NEW services, %s"", service) } this.state.markReady() }" Constructs a new instance for managing the given services . +fun hasModule(moduleName: String?): Boolean { return moduleStore.containsKey(moduleName) || moduleStore.containsValue(moduleName) } Looks up a module +"private fun removeUnusedTilesets(map: Map<*, *>) { val sets: MutableIterator<*> = map.getTileSets().iterator() while (sets.hasNext()) { val tileset: TileSet = sets.next() as TileSet if (!isUsedTileset(map, tileset)) { sets.remove() } } }" Remove any tilesets in a map that are not actually in use . +fun transformPoint(v: vec3): vec3? { val result = vec3() result.m.get(0) = this.m.get(0) * v.m.get(0) + this.m.get(4) * v.m.get(1) + this.m.get(8) * v.m.get(2) + this.m.get( 12 ) result.m.get(1) = this.m.get(1) * v.m.get(0) + this.m.get(5) * v.m.get(1) + this.m.get(9) * v.m.get(2) + this.m.get( 13 ) result.m.get(2) = this.m.get(2) * v.m.get(0) + this.m.get(6) * v.m.get(1) + this.m.get(10) * v.m.get(2) + this.m.get( 14 ) return result } \fn transformPoint \brief Returns a transformed point \param v [ vec3 ] +fun createFromString(str: String?): AttrSessionID? { return AttrSessionID(str) } Creates a new attribute instance from the provided String . +"fun Spinner(model: javax.swing.ListModel, rendererInstance: javax.swing.ListCellRenderer?) { super(model) ios7Mode = javax.swing.UIManager.getInstance().isThemeConstant(""ios7SpinnerBool"", false) if (ios7Mode) { super.setMinElementHeight(6) } SpinnerRenderer.iOS7Mode = ios7Mode setRenderer(rendererInstance) setUIID(""Spinner"") setFixedSelection(FIXED_CENTER) setOrientation(VERTICAL) setInputOnFocus(false) setIsScrollVisible(false) InitSpinnerRenderer() quickType.setReplaceMenu(false) quickType.setInputModeOrder(arrayOf(""123"")) quickType.setFocus(true) quickType.setRTL(false) quickType.setAlignment(LEFT) quickType.setConstraint(java.awt.TextField.NUMERIC) setIgnoreFocusComponentWhenUnfocused(true) setRenderingPrototype(model.getItemAt(model.getSize() - 1)) if (getRenderer() is DateTimeRenderer) { quickType.setColumns(2) } }" Creates a new spinner instance with the given spinner model +"fun start() { paused = false log.info(""Starting text-only user interface..."") log.info(""Local address: "" + system.getLocalAddress()) log.info(""Press Ctrl + C to exit"") Thread(null).start() }" Starts the interface . +fun encodeBase64(binaryData: ByteArray?): ByteArray? { return org.apache.commons.codec.binary.Base64.encodeBase64(binaryData) } Encodes binary data using the base64 algorithm but does not chunk the output . +"fun previousNode(): Int { if (!m_cacheNodes) throw RuntimeException( com.sun.org.apache.xalan.internal.res.XSLMessages.createXPATHMessage( com.sun.org.apache.xpath.internal.res.XPATHErrorResources.ER_NODESETDTM_CANNOT_ITERATE, null ) ) return if (m_next - 1 > 0) { m_next-- this.elementAt(m_next) } else com.sun.org.apache.xml.internal.dtm.DTM.NULL }" Returns the previous node in the set and moves the position of the iterator backwards in the set . +"@Synchronized fun decrease(bitmap: Bitmap?) { val bitmapSize: Int = BitmapUtil.getSizeInBytes(bitmap) Preconditions.checkArgument(mCount > 0, ""No bitmaps registered."") Preconditions.checkArgument( bitmapSize <= mSize, ""Bitmap size bigger than the total registered size: %d, %d"", bitmapSize, mSize ) mSize -= bitmapSize mCount-- }" Excludes given bitmap from the count . +"fun addExcludedName(name: String) { val obj: Any = lookupQualifiedName(scope, name) require(obj is Scriptable) { ""Object for excluded name $name not found."" } table.put(obj, name) }" Adds a qualified name to the list of objects to be excluded from serialization . Names excluded from serialization are looked up in the new scope and replaced upon deserialization . +fun normalizeExcitatoryFanIn() { var sum = 0.0 var str = 0.0 run { var i = 0 val n: Int = fanIn.size() while (i < n) { str = fanIn.get(i).getStrength() if (str > 0) { sum += str } i++ } } var s: Synapse? = null var i = 0 val n: Int = fanIn.size() while (i < n) { s = fanIn.get(i) str = s.getStrength() if (str > 0) { s.setStrength(s.getStrength() / sum) } i++ } } "Normalizes the excitatory synaptic strengths impinging on this neuron , that is finds the sum of the exctiatory weights and divides each weight value by that sum ;" +"@MethodDesc(=description = ""Configure properties by either rereading them or setting all properties from outside."",usage = ""configure "") @Throws( Exception::class)fun configure(@ParamDesc(name = ""tp"",description = ""Optional properties to replace replicator.properties"") tp: TungstenProperties?) {handleEventSynchronous(ConfigureEvent(tp)) }" Local wrapper of configure to help with unit testing . +fun isArrayIndex(): Boolean { return true } Return true if variable is an array +@Throws(Exception::class) fun runSafely(stack: Catbert.FastStack?): Any? { return sun.net.NetworkClient.getConnectedClients() } Returns a list of all the clients that are currently connected to this server . \ No newline at end of file