content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.github.mauricio.async.db.postgresql.messages.frontend interface InitialClientMessage
postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/messages/frontend/InitialClientMessage.kt
3083075087
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.professions.bukkit.database import com.rpkit.core.database.Database import org.jooq.DSLContext import org.jooq.SQLDialect import org.jooq.conf.Settings import org.jooq.impl.DSL private val settings = Settings().withRenderSchema(false) val Database.create: DSLContext get() = DSL.using( dataSource, SQLDialect.valueOf(connectionProperties.sqlDialect), settings )
bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/database/DatabaseJooq.kt
1308943621
/* * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.uamp.media import android.app.Notification import android.app.PendingIntent import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.ResultReceiver import android.support.v4.media.MediaBrowserCompat import android.support.v4.media.MediaBrowserCompat.MediaItem import android.support.v4.media.MediaDescriptionCompat import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import android.util.Log import android.widget.Toast import androidx.core.content.ContextCompat import androidx.media.MediaBrowserServiceCompat import androidx.media.MediaBrowserServiceCompat.BrowserRoot.EXTRA_RECENT import com.example.android.uamp.media.extensions.album import com.example.android.uamp.media.extensions.flag import com.example.android.uamp.media.extensions.id import com.example.android.uamp.media.extensions.toMediaQueueItem import com.example.android.uamp.media.extensions.toMediaSource import com.example.android.uamp.media.extensions.trackNumber import com.example.android.uamp.media.library.AbstractMusicSource import com.example.android.uamp.media.library.BrowseTree import com.example.android.uamp.media.library.JsonSource import com.example.android.uamp.media.library.MEDIA_SEARCH_SUPPORTED import com.example.android.uamp.media.library.MusicSource import com.example.android.uamp.media.library.UAMP_BROWSABLE_ROOT import com.example.android.uamp.media.library.UAMP_EMPTY_ROOT import com.example.android.uamp.media.library.UAMP_RECENT_ROOT import com.google.android.exoplayer2.C import com.google.android.exoplayer2.ControlDispatcher import com.google.android.exoplayer2.ExoPlaybackException import com.google.android.exoplayer2.ExoPlayer import com.google.android.exoplayer2.Player import com.google.android.exoplayer2.SimpleExoPlayer import com.google.android.exoplayer2.audio.AudioAttributes import com.google.android.exoplayer2.ext.cast.CastPlayer import com.google.android.exoplayer2.ext.cast.SessionAvailabilityListener import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector import com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator import com.google.android.exoplayer2.ui.PlayerNotificationManager import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory import com.google.android.exoplayer2.util.Util import com.google.android.gms.cast.MediaQueueItem import com.google.android.gms.cast.framework.CastContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch /** * This class is the entry point for browsing and playback commands from the APP's UI * and other apps that wish to play music via UAMP (for example, Android Auto or * the Google Assistant). * * Browsing begins with the method [MusicService.onGetRoot], and continues in * the callback [MusicService.onLoadChildren]. * * For more information on implementing a MediaBrowserService, * visit [https://developer.android.com/guide/topics/media-apps/audio-app/building-a-mediabrowserservice.html](https://developer.android.com/guide/topics/media-apps/audio-app/building-a-mediabrowserservice.html). * * This class also handles playback for Cast sessions. * When a Cast session is active, playback commands are passed to a * [CastPlayer](https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/ext/cast/CastPlayer.html), * otherwise they are passed to an ExoPlayer for local playback. */ open class MusicService : MediaBrowserServiceCompat() { private lateinit var notificationManager: UampNotificationManager private lateinit var mediaSource: MusicSource private lateinit var packageValidator: PackageValidator // The current player will either be an ExoPlayer (for local playback) or a CastPlayer (for // remote playback through a Cast device). private lateinit var currentPlayer: Player private val serviceJob = SupervisorJob() private val serviceScope = CoroutineScope(Dispatchers.Main + serviceJob) protected lateinit var mediaSession: MediaSessionCompat protected lateinit var mediaSessionConnector: MediaSessionConnector private var currentPlaylistItems: List<MediaMetadataCompat> = emptyList() private lateinit var storage: PersistentStorage /** * This must be `by lazy` because the source won't initially be ready. * See [MusicService.onLoadChildren] to see where it's accessed (and first * constructed). */ private val browseTree: BrowseTree by lazy { BrowseTree(applicationContext, mediaSource) } private val dataSourceFactory: DefaultDataSourceFactory by lazy { DefaultDataSourceFactory( /* context= */ this, Util.getUserAgent(/* context= */ this, UAMP_USER_AGENT), /* listener= */ null ) } private var isForegroundService = false private val remoteJsonSource: Uri = Uri.parse("https://storage.googleapis.com/uamp/catalog.json") private val uAmpAudioAttributes = AudioAttributes.Builder() .setContentType(C.CONTENT_TYPE_MUSIC) .setUsage(C.USAGE_MEDIA) .build() private val playerListener = PlayerEventListener() /** * Configure ExoPlayer to handle audio focus for us. * See [Player.AudioComponent.setAudioAttributes] for details. */ private val exoPlayer: ExoPlayer by lazy { SimpleExoPlayer.Builder(this).build().apply { setAudioAttributes(uAmpAudioAttributes, true) setHandleAudioBecomingNoisy(true) addListener(playerListener) } } /** * Create a CastPlayer to handle communication with a Cast session. */ private val castPlayer: CastPlayer by lazy { CastPlayer(CastContext.getSharedInstance(this)).apply { setSessionAvailabilityListener(UampCastSessionAvailabilityListener()) addListener(playerListener) } } @ExperimentalCoroutinesApi override fun onCreate() { super.onCreate() // Build a PendingIntent that can be used to launch the UI. val sessionActivityPendingIntent = packageManager?.getLaunchIntentForPackage(packageName)?.let { sessionIntent -> PendingIntent.getActivity(this, 0, sessionIntent, 0) } // Create a new MediaSession. mediaSession = MediaSessionCompat(this, "MusicService") .apply { setSessionActivity(sessionActivityPendingIntent) isActive = true } /** * In order for [MediaBrowserCompat.ConnectionCallback.onConnected] to be called, * a [MediaSessionCompat.Token] needs to be set on the [MediaBrowserServiceCompat]. * * It is possible to wait to set the session token, if required for a specific use-case. * However, the token *must* be set by the time [MediaBrowserServiceCompat.onGetRoot] * returns, or the connection will fail silently. (The system will not even call * [MediaBrowserCompat.ConnectionCallback.onConnectionFailed].) */ sessionToken = mediaSession.sessionToken /** * The notification manager will use our player and media session to decide when to post * notifications. When notifications are posted or removed our listener will be called, this * allows us to promote the service to foreground (required so that we're not killed if * the main UI is not visible). */ notificationManager = UampNotificationManager( this, mediaSession.sessionToken, PlayerNotificationListener() ) // The media library is built from a remote JSON file. We'll create the source here, // and then use a suspend function to perform the download off the main thread. mediaSource = JsonSource(source = remoteJsonSource) serviceScope.launch { mediaSource.load() } // ExoPlayer will manage the MediaSession for us. mediaSessionConnector = MediaSessionConnector(mediaSession) mediaSessionConnector.setPlaybackPreparer(UampPlaybackPreparer()) mediaSessionConnector.setQueueNavigator(UampQueueNavigator(mediaSession)) switchToPlayer( previousPlayer = null, newPlayer = if (castPlayer.isCastSessionAvailable) castPlayer else exoPlayer ) notificationManager.showNotificationForPlayer(currentPlayer) packageValidator = PackageValidator(this, R.xml.allowed_media_browser_callers) storage = PersistentStorage.getInstance(applicationContext) } /** * This is the code that causes UAMP to stop playing when swiping the activity away from * recents. The choice to do this is app specific. Some apps stop playback, while others allow * playback to continue and allow users to stop it with the notification. */ override fun onTaskRemoved(rootIntent: Intent) { saveRecentSongToStorage() super.onTaskRemoved(rootIntent) /** * By stopping playback, the player will transition to [Player.STATE_IDLE] triggering * [Player.EventListener.onPlayerStateChanged] to be called. This will cause the * notification to be hidden and trigger * [PlayerNotificationManager.NotificationListener.onNotificationCancelled] to be called. * The service will then remove itself as a foreground service, and will call * [stopSelf]. */ currentPlayer.stop(/* reset= */true) } override fun onDestroy() { mediaSession.run { isActive = false release() } // Cancel coroutines when the service is going away. serviceJob.cancel() // Free ExoPlayer resources. exoPlayer.removeListener(playerListener) exoPlayer.release() } /** * Returns the "root" media ID that the client should request to get the list of * [MediaItem]s to browse/play. */ override fun onGetRoot( clientPackageName: String, clientUid: Int, rootHints: Bundle? ): BrowserRoot? { /* * By default, all known clients are permitted to search, but only tell unknown callers * about search if permitted by the [BrowseTree]. */ val isKnownCaller = packageValidator.isKnownCaller(clientPackageName, clientUid) val rootExtras = Bundle().apply { putBoolean( MEDIA_SEARCH_SUPPORTED, isKnownCaller || browseTree.searchableByUnknownCaller ) putBoolean(CONTENT_STYLE_SUPPORTED, true) putInt(CONTENT_STYLE_BROWSABLE_HINT, CONTENT_STYLE_GRID) putInt(CONTENT_STYLE_PLAYABLE_HINT, CONTENT_STYLE_LIST) } return if (isKnownCaller) { /** * By default return the browsable root. Treat the EXTRA_RECENT flag as a special case * and return the recent root instead. */ val isRecentRequest = rootHints?.getBoolean(EXTRA_RECENT) ?: false val browserRootPath = if (isRecentRequest) UAMP_RECENT_ROOT else UAMP_BROWSABLE_ROOT BrowserRoot(browserRootPath, rootExtras) } else { /** * Unknown caller. There are two main ways to handle this: * 1) Return a root without any content, which still allows the connecting client * to issue commands. * 2) Return `null`, which will cause the system to disconnect the app. * * UAMP takes the first approach for a variety of reasons, but both are valid * options. */ BrowserRoot(UAMP_EMPTY_ROOT, rootExtras) } } /** * Returns (via the [result] parameter) a list of [MediaItem]s that are child * items of the provided [parentMediaId]. See [BrowseTree] for more details on * how this is build/more details about the relationships. */ override fun onLoadChildren( parentMediaId: String, result: Result<List<MediaItem>> ) { /** * If the caller requests the recent root, return the most recently played song. */ if (parentMediaId == UAMP_RECENT_ROOT) { result.sendResult(storage.loadRecentSong()?.let { song -> listOf(song) }) } else { // If the media source is ready, the results will be set synchronously here. val resultsSent = mediaSource.whenReady { successfullyInitialized -> if (successfullyInitialized) { val children = browseTree[parentMediaId]?.map { item -> MediaItem(item.description, item.flag) } result.sendResult(children) } else { mediaSession.sendSessionEvent(NETWORK_FAILURE, null) result.sendResult(null) } } // If the results are not ready, the service must "detach" the results before // the method returns. After the source is ready, the lambda above will run, // and the caller will be notified that the results are ready. // // See [MediaItemFragmentViewModel.subscriptionCallback] for how this is passed to the // UI/displayed in the [RecyclerView]. if (!resultsSent) { result.detach() } } } /** * Returns a list of [MediaItem]s that match the given search query */ override fun onSearch( query: String, extras: Bundle?, result: Result<List<MediaItem>> ) { val resultsSent = mediaSource.whenReady { successfullyInitialized -> if (successfullyInitialized) { val resultsList = mediaSource.search(query, extras ?: Bundle.EMPTY) .map { mediaMetadata -> MediaItem(mediaMetadata.description, mediaMetadata.flag) } result.sendResult(resultsList) } } if (!resultsSent) { result.detach() } } /** * Load the supplied list of songs and the song to play into the current player. */ private fun preparePlaylist( metadataList: List<MediaMetadataCompat>, itemToPlay: MediaMetadataCompat?, playWhenReady: Boolean, playbackStartPositionMs: Long ) { // Since the playlist was probably based on some ordering (such as tracks // on an album), find which window index to play first so that the song the // user actually wants to hear plays first. val initialWindowIndex = if (itemToPlay == null) 0 else metadataList.indexOf(itemToPlay) currentPlaylistItems = metadataList currentPlayer.playWhenReady = playWhenReady currentPlayer.stop(/* reset= */ true) if (currentPlayer == exoPlayer) { val mediaSource = metadataList.toMediaSource(dataSourceFactory) exoPlayer.prepare(mediaSource) exoPlayer.seekTo(initialWindowIndex, playbackStartPositionMs) } else /* currentPlayer == castPlayer */ { val items: Array<MediaQueueItem> = metadataList.map { it.toMediaQueueItem() }.toTypedArray() castPlayer.loadItems( items, initialWindowIndex, playbackStartPositionMs, Player.REPEAT_MODE_OFF ) } } private fun switchToPlayer(previousPlayer: Player?, newPlayer: Player) { if (previousPlayer == newPlayer) { return } currentPlayer = newPlayer if (previousPlayer != null) { val playbackState = previousPlayer.playbackState if (currentPlaylistItems.isEmpty()) { // We are joining a playback session. Loading the session from the new player is // not supported, so we stop playback. currentPlayer.stop(/* reset= */true) } else if (playbackState != Player.STATE_IDLE && playbackState != Player.STATE_ENDED) { preparePlaylist( metadataList = currentPlaylistItems, itemToPlay = currentPlaylistItems[previousPlayer.currentWindowIndex], playWhenReady = previousPlayer.playWhenReady, playbackStartPositionMs = previousPlayer.currentPosition ) } } mediaSessionConnector.setPlayer(newPlayer) previousPlayer?.stop(/* reset= */true) } private fun saveRecentSongToStorage() { // Obtain the current song details *before* saving them on a separate thread, otherwise // the current player may have been unloaded by the time the save routine runs. val description = currentPlaylistItems[currentPlayer.currentWindowIndex].description val position = currentPlayer.currentPosition serviceScope.launch { storage.saveRecentSong( description, position ) } } private inner class UampCastSessionAvailabilityListener : SessionAvailabilityListener { /** * Called when a Cast session has started and the user wishes to control playback on a * remote Cast receiver rather than play audio locally. */ override fun onCastSessionAvailable() { switchToPlayer(currentPlayer, castPlayer) } /** * Called when a Cast session has ended and the user wishes to control playback locally. */ override fun onCastSessionUnavailable() { switchToPlayer(currentPlayer, exoPlayer) } } private inner class UampQueueNavigator( mediaSession: MediaSessionCompat ) : TimelineQueueNavigator(mediaSession) { override fun getMediaDescription(player: Player, windowIndex: Int): MediaDescriptionCompat = currentPlaylistItems[windowIndex].description } private inner class UampPlaybackPreparer : MediaSessionConnector.PlaybackPreparer { /** * UAMP supports preparing (and playing) from search, as well as media ID, so those * capabilities are declared here. * * TODO: Add support for ACTION_PREPARE and ACTION_PLAY, which mean "prepare/play something". */ override fun getSupportedPrepareActions(): Long = PlaybackStateCompat.ACTION_PREPARE_FROM_MEDIA_ID or PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID or PlaybackStateCompat.ACTION_PREPARE_FROM_SEARCH or PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH override fun onPrepare(playWhenReady: Boolean) { val recentSong = storage.loadRecentSong() if (recentSong != null) { onPrepareFromMediaId( recentSong.mediaId!!, playWhenReady, recentSong.description.extras ) } } override fun onPrepareFromMediaId( mediaId: String, playWhenReady: Boolean, extras: Bundle? ) { mediaSource.whenReady { val itemToPlay: MediaMetadataCompat? = mediaSource.find { item -> item.id == mediaId } if (itemToPlay == null) { Log.w(TAG, "Content not found: MediaID=$mediaId") // TODO: Notify caller of the error. } else { val playbackStartPositionMs = extras?.getLong(MEDIA_DESCRIPTION_EXTRAS_START_PLAYBACK_POSITION_MS, C.TIME_UNSET) ?: C.TIME_UNSET preparePlaylist( buildPlaylist(itemToPlay), itemToPlay, playWhenReady, playbackStartPositionMs ) } } } /** * This method is used by the Google Assistant to respond to requests such as: * - Play Geisha from Wake Up on UAMP * - Play electronic music on UAMP * - Play music on UAMP * * For details on how search is handled, see [AbstractMusicSource.search]. */ override fun onPrepareFromSearch(query: String, playWhenReady: Boolean, extras: Bundle?) { mediaSource.whenReady { val metadataList = mediaSource.search(query, extras ?: Bundle.EMPTY) if (metadataList.isNotEmpty()) { preparePlaylist( metadataList, metadataList[0], playWhenReady, playbackStartPositionMs = C.TIME_UNSET ) } } } override fun onPrepareFromUri(uri: Uri, playWhenReady: Boolean, extras: Bundle?) = Unit override fun onCommand( player: Player, controlDispatcher: ControlDispatcher, command: String, extras: Bundle?, cb: ResultReceiver? ) = false /** * Builds a playlist based on a [MediaMetadataCompat]. * * TODO: Support building a playlist by artist, genre, etc... * * @param item Item to base the playlist on. * @return a [List] of [MediaMetadataCompat] objects representing a playlist. */ private fun buildPlaylist(item: MediaMetadataCompat): List<MediaMetadataCompat> = mediaSource.filter { it.album == item.album }.sortedBy { it.trackNumber } } /** * Listen for notification events. */ private inner class PlayerNotificationListener : PlayerNotificationManager.NotificationListener { override fun onNotificationPosted( notificationId: Int, notification: Notification, ongoing: Boolean ) { if (ongoing && !isForegroundService) { ContextCompat.startForegroundService( applicationContext, Intent(applicationContext, [email protected]) ) startForeground(notificationId, notification) isForegroundService = true } } override fun onNotificationCancelled(notificationId: Int, dismissedByUser: Boolean) { stopForeground(true) isForegroundService = false stopSelf() } } /** * Listen for events from ExoPlayer. */ private inner class PlayerEventListener : Player.EventListener { override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) { when (playbackState) { Player.STATE_BUFFERING, Player.STATE_READY -> { notificationManager.showNotificationForPlayer(currentPlayer) if (playbackState == Player.STATE_READY) { // When playing/paused save the current media item in persistent // storage so that playback can be resumed between device reboots. // Search for "media resumption" for more information. saveRecentSongToStorage() if (!playWhenReady) { // If playback is paused we remove the foreground state which allows the // notification to be dismissed. An alternative would be to provide a // "close" button in the notification which stops playback and clears // the notification. stopForeground(false) } } } else -> { notificationManager.hideNotification() } } } override fun onPlayerError(error: ExoPlaybackException) { var message = R.string.generic_error; when (error.type) { // If the data from MediaSource object could not be loaded the Exoplayer raises // a type_source error. // An error message is printed to UI via Toast message to inform the user. ExoPlaybackException.TYPE_SOURCE -> { message = R.string.error_media_not_found; Log.e(TAG, "TYPE_SOURCE: " + error.sourceException.message) } // If the error occurs in a render component, Exoplayer raises a type_remote error. ExoPlaybackException.TYPE_RENDERER -> { Log.e(TAG, "TYPE_RENDERER: " + error.rendererException.message) } // If occurs an unexpected RuntimeException Exoplayer raises a type_unexpected error. ExoPlaybackException.TYPE_UNEXPECTED -> { Log.e(TAG, "TYPE_UNEXPECTED: " + error.unexpectedException.message) } // Occurs when there is a OutOfMemory error. ExoPlaybackException.TYPE_OUT_OF_MEMORY -> { Log.e(TAG, "TYPE_OUT_OF_MEMORY: " + error.outOfMemoryError.message) } // If the error occurs in a remote component, Exoplayer raises a type_remote error. ExoPlaybackException.TYPE_REMOTE -> { Log.e(TAG, "TYPE_REMOTE: " + error.message) } } Toast.makeText( applicationContext, message, Toast.LENGTH_LONG ).show() } } } /* * (Media) Session events */ const val NETWORK_FAILURE = "com.example.android.uamp.media.session.NETWORK_FAILURE" /** Content styling constants */ private const val CONTENT_STYLE_BROWSABLE_HINT = "android.media.browse.CONTENT_STYLE_BROWSABLE_HINT" private const val CONTENT_STYLE_PLAYABLE_HINT = "android.media.browse.CONTENT_STYLE_PLAYABLE_HINT" private const val CONTENT_STYLE_SUPPORTED = "android.media.browse.CONTENT_STYLE_SUPPORTED" private const val CONTENT_STYLE_LIST = 1 private const val CONTENT_STYLE_GRID = 2 private const val UAMP_USER_AGENT = "uamp.next" val MEDIA_DESCRIPTION_EXTRAS_START_PLAYBACK_POSITION_MS = "playback_start_position_ms" private const val TAG = "MusicService"
common/src/main/java/com/example/android/uamp/media/MusicService.kt
4003337679
package main.tut14 import com.jogamp.newt.event.KeyEvent import com.jogamp.newt.event.MouseEvent import com.jogamp.opengl.GL2ES2.GL_RED import com.jogamp.opengl.GL2ES3.* import com.jogamp.opengl.GL2GL3.GL_TEXTURE_1D import com.jogamp.opengl.GL3 import com.jogamp.opengl.GL3.GL_DEPTH_CLAMP import glNext.* import glm.* import glm.mat.Mat4 import glm.quat.Quat import glm.vec._3.Vec3 import glm.vec._4.Vec4 import main.framework.Framework import main.framework.Semantic import main.framework.component.Mesh import uno.buffer.* import uno.glm.MatrixStack import uno.glsl.programOf import uno.mousePole.* import uno.time.Timer import java.nio.ByteBuffer /** * Created by elect on 28/03/17. */ fun main(args: Array<String>) { BasicTexture_().setup("Tutorial 14 - Basic Texture") } class BasicTexture_ : Framework() { lateinit var litShaderProg: ProgramData lateinit var litTextureProg: ProgramData lateinit var unlit: UnlitProgData val initialObjectData = ObjectData( Vec3(0.0f, 0.5f, 0.0f), Quat(1.0f, 0.0f, 0.0f, 0.0f)) val initialViewData = ViewData( Vec3(initialObjectData.position), Quat(0.92387953f, 0.3826834f, 0.0f, 0.0f), 10.0f, 0.0f) val viewScale = ViewScale( 1.5f, 70.0f, 1.5f, 0.5f, 0.0f, 0.0f, //No camera movement. 90.0f / 250.0f) val viewPole = ViewPole(initialViewData, viewScale, MouseEvent.BUTTON1) val objectPole = ObjectPole(initialObjectData, 90.0f / 250.0f, MouseEvent.BUTTON3, viewPole) lateinit var objectMesh: Mesh lateinit var cube: Mesh object Buffer { val PROJECTION = 0 val LIGHT = 1 val MATERIAL = 2 val MAX = 3 } val gaussTextures = intBufferBig(NUM_GAUSSIAN_TEXTURES) val gaussSampler = intBufferBig(1) val bufferName = intBufferBig(Buffer.MAX) var drawCameraPos = false var drawLights = true var useTexture = false val specularShininess = 0.2f val lightHeight = 1.0f val lightRadius = 3.0f val halfLightDistance = 25.0f val lightAttenuation = 1.0f / (halfLightDistance * halfLightDistance) val lightTimer = Timer(Timer.Type.Loop, 6.0f) val lightBuffer = byteBufferBig(LightBlock.SIZE) var currTexture = 0 companion object { val NUMBER_OF_LIGHTS = 2 val NUM_GAUSSIAN_TEXTURES = 4 } override fun init(gl: GL3) = with(gl) { initializePrograms(gl) objectMesh = Mesh(gl, javaClass, "tut14/Infinity.xml") cube = Mesh(gl, javaClass, "tut14/UnitCube.xml") val depthZNear = 0.0f val depthZFar = 1.0f glEnable(GL_CULL_FACE) glCullFace(GL_BACK) glFrontFace(GL_CW) glEnable(GL_DEPTH_TEST) glDepthMask(true) glDepthFunc(GL_LEQUAL) glDepthRangef(depthZNear, depthZFar) glEnable(GL_DEPTH_CLAMP) //Setup our Uniform Buffers val mtl = MaterialBlock mtl.diffuseColor = Vec4(1.0f, 0.673f, 0.043f, 1.0f) mtl.specularColor = Vec4(1.0f, 0.673f, 0.043f, 1.0f) mtl.specularShininess = specularShininess val mtlBuffer = mtl.to(byteBufferBig(MaterialBlock.SIZE)) glGenBuffers(bufferName) glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.MATERIAL]) glBufferData(GL_UNIFORM_BUFFER, mtlBuffer, GL_STATIC_DRAW) glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.LIGHT]) glBufferData(GL_UNIFORM_BUFFER, LightBlock.SIZE, GL_DYNAMIC_DRAW) glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.PROJECTION]) glBufferData(GL_UNIFORM_BUFFER, Mat4.SIZE, GL_DYNAMIC_DRAW) //Bind the static buffers. glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.LIGHT, bufferName[Buffer.LIGHT], 0, LightBlock.SIZE.L) glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.PROJECTION, bufferName[Buffer.PROJECTION], 0, Mat4.SIZE.L) glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.MATERIAL, bufferName[Buffer.MATERIAL], 0, MaterialBlock.SIZE.L) glBindBuffer(GL_UNIFORM_BUFFER) createGaussianTextures(gl) mtlBuffer.destroy() } fun initializePrograms(gl: GL3) { litShaderProg = ProgramData(gl, "pn.vert", "shader-gaussian.frag") litTextureProg = ProgramData(gl, "pn.vert", "texture-gaussian.frag") unlit = UnlitProgData(gl, "unlit") } fun createGaussianTextures(gl: GL3) = with(gl) { glGenTextures(NUM_GAUSSIAN_TEXTURES, gaussTextures) repeat(NUM_GAUSSIAN_TEXTURES) { val cosAngleResolution = calcCosAngleResolution(it) createGaussianTexture(gl, it, cosAngleResolution) } glGenSampler(gaussSampler) glSamplerParameteri(gaussSampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glSamplerParameteri(gaussSampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glSamplerParameteri(gaussSampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) } fun calcCosAngleResolution(level: Int): Int { val cosAngleStart = 64 return cosAngleStart * glm.pow(2f, level.f).i } fun createGaussianTexture(gl: GL3, index: Int, cosAngleResolution: Int) = with(gl) { val textureData = buildGaussianData(cosAngleResolution) glBindTexture(GL_TEXTURE_1D, gaussTextures[index]) glTexImage1D(GL_TEXTURE_1D, 0, GL_R8, cosAngleResolution, 0, GL_RED, GL_UNSIGNED_BYTE, textureData) glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_BASE_LEVEL, 0) glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0) glBindTexture(GL_TEXTURE_1D) textureData.destroy() } fun buildGaussianData(cosAngleResolution: Int): ByteBuffer { val textureData = byteBufferBig(cosAngleResolution) repeat(cosAngleResolution) { iCosAng -> val cosAng = iCosAng / (cosAngleResolution - 1).f val angle = glm.acos(cosAng) var exponent = angle / specularShininess exponent = -(exponent * exponent) val gaussianTerm = glm.exp(exponent) textureData[iCosAng] = (gaussianTerm * 255f).b } return textureData } override fun display(gl: GL3) = with(gl) { lightTimer.update() glClearBufferf(GL_COLOR, 0.75f, 0.75f, 1.0f, 1.0f) glClearBufferf(GL_DEPTH) val modelMatrix = MatrixStack(viewPole.calcMatrix()) val worldToCamMat = modelMatrix.top() val globalLightDirection = Vec3(0.707f, 0.707f, 0.0f) val lightData = LightBlock lightData.ambientIntensity = Vec4(0.2f, 0.2f, 0.2f, 1.0f) lightData.lightAttenuation = lightAttenuation lightData.lights[0].cameraSpaceLightPos = worldToCamMat * Vec4(globalLightDirection, 0.0f) lightData.lights[0].lightIntensity = Vec4(0.6f, 0.6f, 0.6f, 1.0f) lightData.lights[1].cameraSpaceLightPos = worldToCamMat * calcLightPosition() lightData.lights[1].lightIntensity = Vec4(0.4f, 0.4f, 0.4f, 1.0f) glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.LIGHT]) glBufferSubData(GL_UNIFORM_BUFFER, lightData to lightBuffer) glBindBuffer(GL_UNIFORM_BUFFER) run { glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.MATERIAL, bufferName[Buffer.MATERIAL], 0, MaterialBlock.SIZE.L) modelMatrix run { applyMatrix(objectPole.calcMatrix()) scale(2.0f) val normMatrix = top().toMat3() normMatrix.inverse_().transpose_() val prog = if (useTexture) litTextureProg else litShaderProg glUseProgram(prog.theProgram) glUniformMatrix4f(prog.modelToCameraMatrixUnif, top()) glUniformMatrix3f(prog.normalModelToCameraMatrixUnif, normMatrix) glActiveTexture(GL_TEXTURE0 + Semantic.Sampler.GAUSSIAN_TEXTURE) glBindTexture(GL_TEXTURE_1D, gaussTextures[currTexture]) glBindSampler(Semantic.Sampler.GAUSSIAN_TEXTURE, gaussSampler) objectMesh.render(gl, "lit") glBindSampler(Semantic.Sampler.GAUSSIAN_TEXTURE) glBindTexture(GL_TEXTURE_1D) glUseProgram() glBindBufferBase(GL_UNIFORM_BUFFER, Semantic.Uniform.MATERIAL) } } if (drawLights) modelMatrix run { translate(calcLightPosition()) scale(0.25f) glUseProgram(unlit.theProgram) glUniformMatrix4f(unlit.modelToCameraMatrixUnif, top()) val lightColor = Vec4(1.0f) glUniform4f(unlit.objectColorUnif, lightColor) cube.render(gl, "flat") reset() translate(globalLightDirection * 100.0f) scale(5.0f) glUniformMatrix4f(unlit.modelToCameraMatrixUnif, top()) cube.render(gl, "flat") glUseProgram() } if (drawCameraPos) modelMatrix run { setIdentity() translate(0.0f, 0.0f, -viewPole.getView().radius) scale(0.25f) glDisable(GL_DEPTH_TEST) glDepthMask(false) glUseProgram(unlit.theProgram) glUniformMatrix4f(unlit.modelToCameraMatrixUnif, top()) glUniform4f(unlit.objectColorUnif, 0.25f, 0.25f, 0.25f, 1.0f) cube.render(gl, "flat") glDepthMask(true) glEnable(GL_DEPTH_TEST) glUniform4f(unlit.objectColorUnif, 1.0f) cube.render(gl, "flat") } } fun calcLightPosition(): Vec4 { val scale = glm.PIf * 2.0f val timeThroughLoop = lightTimer.getAlpha() val ret = Vec4(0.0f, lightHeight, 0.0f, 1.0f) ret.x = glm.cos(timeThroughLoop * scale) * lightRadius ret.z = glm.sin(timeThroughLoop * scale) * lightRadius return ret } override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) { val zNear = 1.0f val zFar = 1_000f val perspMatrix = MatrixStack() val proj = perspMatrix.perspective(45.0f, w.f / h, zNear, zFar).top() glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.PROJECTION]) glBufferSubData(GL_UNIFORM_BUFFER, proj) glBindBuffer(GL_UNIFORM_BUFFER) glViewport(w, h) } override fun mousePressed(e: MouseEvent) { viewPole.mousePressed(e) } override fun mouseDragged(e: MouseEvent) { viewPole.mouseDragged(e) } override fun mouseReleased(e: MouseEvent) { viewPole.mouseReleased(e) } override fun mouseWheelMoved(e: MouseEvent) { viewPole.mouseWheel(e) } override fun keyPressed(e: KeyEvent) { when (e.keyCode) { KeyEvent.VK_ESCAPE -> quit() KeyEvent.VK_P -> lightTimer.togglePause() KeyEvent.VK_MINUS -> lightTimer.rewind(0.5f) KeyEvent.VK_PLUS -> lightTimer.fastForward(0.5f) KeyEvent.VK_T -> drawCameraPos = !drawCameraPos KeyEvent.VK_G -> drawLights = !drawLights KeyEvent.VK_SPACE -> useTexture = !useTexture } if (e.keyCode in KeyEvent.VK_1 .. KeyEvent.VK_9) { val number = e.keyCode - KeyEvent.VK_1 if (number < NUM_GAUSSIAN_TEXTURES) { println("Angle Resolution: " + calcCosAngleResolution(number)) currTexture = number } } viewPole.keyPressed(e) } override fun end(gl: GL3) = with(gl) { glDeletePrograms(litShaderProg.theProgram, litTextureProg.theProgram, unlit.theProgram) glDeleteBuffers(bufferName) glDeleteSampler(gaussSampler) glDeleteTextures(gaussTextures) objectMesh.dispose(gl) cube.dispose(gl) destroyBuffers(bufferName, gaussSampler, gaussTextures, lightBuffer) } object MaterialBlock { lateinit var diffuseColor: Vec4 lateinit var specularColor: Vec4 var specularShininess = 0f var padding = FloatArray(3) fun to(buffer: ByteBuffer, offset: Int = 0): ByteBuffer { diffuseColor.to(buffer, offset) specularColor.to(buffer, offset + Vec4.SIZE) return buffer.putFloat(offset + 2 * Vec4.SIZE, specularShininess) } val SIZE = 3 * Vec4.SIZE } class PerLight { var cameraSpaceLightPos = Vec4() var lightIntensity = Vec4() fun to(buffer: ByteBuffer, offset: Int): ByteBuffer { cameraSpaceLightPos.to(buffer, offset) return lightIntensity.to(buffer, offset + Vec4.SIZE) } companion object { val SIZE = Vec4.SIZE * 2 } } object LightBlock { lateinit var ambientIntensity: Vec4 var lightAttenuation = 0f var padding = FloatArray(3) var lights = arrayOf(PerLight(), PerLight()) infix fun to(buffer: ByteBuffer) = to(buffer, 0) fun to(buffer: ByteBuffer, offset: Int): ByteBuffer { ambientIntensity.to(buffer, offset) buffer.putFloat(offset + Vec4.SIZE, lightAttenuation) repeat(NUMBER_OF_LIGHTS) { lights[it].to(buffer, offset + 2 * Vec4.SIZE + it * PerLight.SIZE) } return buffer } val SIZE = Vec4.SIZE * 2 + NUMBER_OF_LIGHTS * PerLight.SIZE } class ProgramData(gl: GL3, vertex: String, fragment: String) { var theProgram = programOf(gl, javaClass, "tut14", vertex, fragment) var modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix") var normalModelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "normalModelToCameraMatrix") init { with(gl) { glUniformBlockBinding( theProgram, glGetUniformBlockIndex(theProgram, "Projection"), Semantic.Uniform.PROJECTION) glUniformBlockBinding( theProgram, glGetUniformBlockIndex(theProgram, "Material"), Semantic.Uniform.MATERIAL) glUniformBlockBinding( theProgram, glGetUniformBlockIndex(theProgram, "Light"), Semantic.Uniform.LIGHT) glUseProgram(theProgram) glUniform1i( glGetUniformLocation(theProgram, "gaussianTexture"), Semantic.Sampler.GAUSSIAN_TEXTURE) glUseProgram(theProgram) } } } inner class UnlitProgData(gl: GL3, shader: String) { var theProgram = programOf(gl, javaClass, "tut14", shader + ".vert", shader + ".frag") var objectColorUnif = gl.glGetUniformLocation(theProgram, "objectColor") var modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix") init { gl.glUniformBlockBinding( theProgram, gl.glGetUniformBlockIndex(theProgram, "Projection"), Semantic.Uniform.PROJECTION) } } }
src/main/kotlin/main/tut14/basicTexture.kt
1070387291
package cn.yiiguxing.plugin.translate.ui.form import cn.yiiguxing.plugin.translate.TTSSource import cn.yiiguxing.plugin.translate.TargetLanguageSelection import cn.yiiguxing.plugin.translate.message import cn.yiiguxing.plugin.translate.trans.Lang import cn.yiiguxing.plugin.translate.ui.ActionLink import cn.yiiguxing.plugin.translate.ui.UI.emptyBorder import cn.yiiguxing.plugin.translate.ui.UI.fill import cn.yiiguxing.plugin.translate.ui.UI.fillX import cn.yiiguxing.plugin.translate.ui.UI.fillY import cn.yiiguxing.plugin.translate.ui.UI.migLayout import cn.yiiguxing.plugin.translate.ui.UI.migLayoutVertical import cn.yiiguxing.plugin.translate.ui.UI.plus import cn.yiiguxing.plugin.translate.ui.UI.wrap import cn.yiiguxing.plugin.translate.ui.selected import cn.yiiguxing.plugin.translate.ui.settings.TranslationEngine import cn.yiiguxing.plugin.translate.util.IdeVersion import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.ui.ComboBox import com.intellij.ui.* import com.intellij.ui.components.JBCheckBox import com.intellij.ui.components.labels.LinkLabel import com.intellij.util.ui.JBUI import icons.TranslationIcons import net.miginfocom.layout.CC import java.awt.Dimension import javax.swing.* import javax.swing.text.AttributeSet import javax.swing.text.JTextComponent import javax.swing.text.PlainDocument abstract class SettingsForm { protected val wholePanel: JPanel = JPanel() protected val configureTranslationEngineLink: ActionLink = ActionLink(message("settings.configure.link")) {} protected val translationEngineComboBox: ComboBox<TranslationEngine> = comboBox<TranslationEngine>().apply { renderer = SimpleListCellRenderer.create { label, value, _ -> label.text = value.translatorName label.icon = value.icon } addItemListener { fixEngineConfigurationComponent() } } protected val primaryLanguageComboBox: ComboBox<Lang> = comboBox<Lang>().apply { renderer = SimpleListCellRenderer.create { label, lang, _ -> label.text = lang.langName } } protected val targetLangSelectionComboBox: ComboBox<TargetLanguageSelection> = comboBox<TargetLanguageSelection>().apply { renderer = SimpleListCellRenderer.create("") { it.displayName } } protected val takeWordCheckBox: JBCheckBox = JBCheckBox(message("settings.options.take.word.when.translation.dialog.opens")) protected val takeNearestWordCheckBox: JCheckBox = JCheckBox(message("settings.options.take.single.word")) protected val keepFormatCheckBox: JBCheckBox = JBCheckBox(message("settings.options.keepFormatting")) protected lateinit var ignoreRegExp: EditorTextField protected val checkIgnoreRegExpButton: JButton = JButton(message("settings.button.check")) protected val ignoreRegExpMsg: JLabel = JLabel() protected val separatorsTextField: JTextField = JTextField().apply { document = object : PlainDocument() { override fun insertString(offset: Int, str: String?, attr: AttributeSet?) { val text = getText(0, length) val stringToInsert = str ?.filter { it in ' '..'~' && !Character.isLetterOrDigit(it) && !text.contains(it) } ?.toSet() ?.take(10 - length) ?.joinToString("") ?: return if (stringToInsert.isNotEmpty()) { super.insertString(offset, stringToInsert, attr) } } } } protected var primaryFontComboBox: FontComboBox = createFontComboBox(filterNonLatin = false) protected var phoneticFontComboBox: FontComboBox = createFontComboBox(filterNonLatin = true) protected val primaryFontPreview: JTextComponent = JEditorPane( "text/plain", message("settings.font.default.preview.text") ) protected val phoneticFontPreview: JLabel = JLabel(PHONETIC_CHARACTERS) protected val restoreDefaultButton = JButton(message("settings.button.restore.default.fonts")) protected val foldOriginalCheckBox: JBCheckBox = JBCheckBox(message("settings.options.foldOriginal")) protected val ttsSourceComboBox: ComboBox<TTSSource> = ComboBox(CollectionComboBoxModel(TTSSource.values().asList())).apply { renderer = SimpleListCellRenderer.create("") { it.displayName } preferredSize = Dimension(preferredSize.width, JBUI.scale(26)) } protected val autoPlayTTSCheckBox: JBCheckBox = JBCheckBox(message("settings.options.autoPlayTTS")).apply { addItemListener { ttsSourceComboBox.isEnabled = isSelected } } protected val showWordFormsCheckBox: JBCheckBox = JBCheckBox(message("settings.options.showWordForms")) protected val autoReplaceCheckBox: JBCheckBox = JBCheckBox(message("settings.options.autoReplace")) protected val showReplacementActionCheckBox: JBCheckBox = JBCheckBox(message("settings.options.show.replacement.action")) protected val selectTargetLanguageCheckBox: JBCheckBox = JBCheckBox(message("settings.options.selectLanguage")) protected val showWordsOnStartupCheckBox: JBCheckBox = JBCheckBox(message("settings.options.showWordsOnStartup")) protected val showExplanationCheckBox: JBCheckBox = JBCheckBox(message("settings.options.showExplanation")) protected val maxHistoriesSizeComboBox: ComboBox<Int> = comboBox(50, 30, 20, 10, 0).apply { isEditable = true } protected val clearHistoriesButton: JButton = JButton(message("settings.clear.history.button")) protected val cacheSizeLabel: JLabel = JLabel("0KB") protected val clearCacheButton: JButton = JButton(message("settings.cache.button.clear")) protected val translateDocumentationCheckBox: JBCheckBox = JBCheckBox(message("settings.options.translate.documentation")) protected val showActionsInContextMenuOnlyWithSelectionCheckbox: JBCheckBox = JBCheckBox(message("settings.options.show.actions.only.with.selection")) protected val supportLinkLabel: LinkLabel<*> = LinkLabel<Any>(message("support.or.donate"), TranslationIcons.Support).apply { border = JBUI.Borders.empty(20, 0, 0, 0) } protected fun doLayout() { val generalPanel = titledPanel(message("settings.panel.title.general")) { val comboboxGroup = "combobox" add(JLabel(message("settings.label.translation.engine"))) add(translationEngineComboBox, CC().sizeGroupX(comboboxGroup)) val configurePanel = Box.createHorizontalBox().apply { add(configureTranslationEngineLink) fixEngineConfigurationComponent() } add(configurePanel, wrap().gapBefore("indent").span(2)) add(JLabel(message("settings.label.primaryLanguage"))) add(primaryLanguageComboBox, wrap().sizeGroupX(comboboxGroup)) add(JLabel(message("settings.label.targetLanguage"))) add(targetLangSelectionComboBox, wrap().sizeGroupX(comboboxGroup)) } val textSelectionPanel = titledPanel(message("settings.panel.title.text.selection")) { add(keepFormatCheckBox, wrap().span(4)) add(takeNearestWordCheckBox, wrap().span(4)) add(takeWordCheckBox, wrap().span(4)) add(JLabel(message("settings.label.ignore"))) val ignoreRegexComponent: JComponent = if (ApplicationManager.getApplication() != null) ignoreRegExp else JTextField() add(ignoreRegexComponent) add(checkIgnoreRegExpButton) add(ignoreRegExpMsg, wrap()) setMinWidth(ignoreRegexComponent) } val fontsPanel = titledPanel(message("settings.panel.title.fonts")) { add(JLabel(message("settings.font.label.primary"))) add(JLabel(message("settings.font.label.phonetic")), wrap()) add(primaryFontComboBox) add(phoneticFontComboBox, wrap()) val primaryPreviewPanel = JPanel(migLayout()).apply { add(primaryFontPreview, fillX()) } val phoneticPreviewPanel = JPanel(migLayout()).apply { add(phoneticFontPreview, fillX().dockNorth()) } add(primaryPreviewPanel, fillX()) add(phoneticPreviewPanel, fill().wrap()) add(restoreDefaultButton) //compensate custom border of ComboBox primaryFontPreview.border = emptyBorder(3) + JBUI.Borders.customLine(JBColor.border()) primaryPreviewPanel.border = emptyBorder(3) phoneticFontPreview.border = emptyBorder(6) } val translationPopupPanel = titledPanel(message("settings.panel.title.translation.popup")) { add(foldOriginalCheckBox, wrap().span(2)) add(showWordFormsCheckBox, wrap().span(2)) add(autoPlayTTSCheckBox) add(ttsSourceComboBox, wrap()) } val translateAndReplacePanel = titledPanel(message("settings.panel.title.translate.and.replace")) { add(showReplacementActionCheckBox, wrap().span(2)) add(selectTargetLanguageCheckBox, wrap().span(2)) add(autoReplaceCheckBox, wrap().span(2)) add(JLabel(message("settings.label.separators")).apply { toolTipText = message("settings.tip.separators") }) add(separatorsTextField, wrap()) setMinWidth(separatorsTextField) } val wordOfTheDayPanel = titledPanel(message("settings.panel.title.word.of.the.day")) { add(showWordsOnStartupCheckBox, wrap()) add(showExplanationCheckBox, wrap()) } val cacheAndHistoryPanel = titledPanel(message("settings.panel.title.cacheAndHistory")) { add(JPanel(migLayout()).apply { add(JLabel(message("settings.cache.label.diskCache"))) add(cacheSizeLabel) add(clearCacheButton, wrap()) }, wrap().span(2)) add(JPanel(migLayout()).apply { add(JLabel(message("settings.history.label.maxLength"))) add(maxHistoriesSizeComboBox) add(clearHistoriesButton, wrap()) }, CC().span(2)) setMinWidth(maxHistoriesSizeComboBox) cacheSizeLabel.border = JBUI.Borders.empty(0, 2, 0, 10) } val otherPanel = titledPanel(message("settings.panel.title.other")) { if (isSupportDocumentTranslation()) { add(translateDocumentationCheckBox, wrap()) } add(showActionsInContextMenuOnlyWithSelectionCheckbox, wrap()) } wholePanel.addVertically( generalPanel, fontsPanel, textSelectionPanel, translationPopupPanel, translateAndReplacePanel, wordOfTheDayPanel, cacheAndHistoryPanel, otherPanel, supportLinkLabel ) } fun createMainPanel(): JPanel { doLayout() return wholePanel } private fun fixEngineConfigurationComponent() { configureTranslationEngineLink.isVisible = translationEngineComboBox.selected != TranslationEngine.GOOGLE } open fun isSupportDocumentTranslation(): Boolean { // Documentation translation is not supported before Rider 2022.1. return IdeVersion >= IdeVersion.IDE2022_1 || IdeVersion.buildNumber.productCode != "RD" } companion object { private const val PHONETIC_CHARACTERS = "ˈ'ˌːiɜɑɔuɪeæʌɒʊəaɛpbtdkgfvszθðʃʒrzmnŋhljw" private const val MIN_ELEMENT_WIDTH = 80 private fun setMinWidth(component: JComponent) = component.apply { minimumSize = Dimension(MIN_ELEMENT_WIDTH, height) } private fun createFontComboBox(filterNonLatin: Boolean): FontComboBox = FontComboBox(false, filterNonLatin, false) private fun titledPanel(title: String, body: JPanel.() -> Unit): JComponent { val innerPanel = JPanel(migLayout()) innerPanel.body() return JPanel(migLayout()).apply { border = IdeBorderFactory.createTitledBorder(title) add(innerPanel) add(JPanel(), fillX()) } } private fun JPanel.addVertically(vararg components: JComponent) { layout = migLayoutVertical() components.forEach { add(it, fillX()) } add(JPanel(), fillY()) } private fun <T> comboBox(elements: List<T>): ComboBox<T> = ComboBox(CollectionComboBoxModel(elements)) private fun <T> comboBox(vararg elements: T): ComboBox<T> = comboBox(elements.toList()) private inline fun <reified T : Enum<T>> comboBox(): ComboBox<T> = comboBox(enumValues<T>().toList()) } }
src/main/kotlin/cn/yiiguxing/plugin/translate/ui/form/SettingsForm.kt
2782393090
/* * The MIT License (MIT) * * Copyright (c) skrypton-api by waicool20 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.waicool20.skrypton import com.waicool20.skrypton.jni.objects.SKryptonApp import com.waicool20.skrypton.sikulix.screen import org.sikuli.script.ImagePath import java.util.concurrent.TimeUnit fun main(args: Array<String>) { SKryptonApp.initialize(args, remoteDebugPort = 8888) { screen("https://gist.github.com/") { ImagePath.add(ClassLoader.getSystemClassLoader().getResource("images")) TimeUnit.SECONDS.sleep(4) type(center, "SKrypton is a project that can automate your browser projects/test." + "\nEverything you're seeing is being automated by SKrypton.\nIt can do more!") webView.runJavaScript("window.onbeforeunload = null;") TimeUnit.SECONDS.sleep(3) webView.load("https://github.com/waicool20/SKrypton") find("issues.png").click() TimeUnit.SECONDS.sleep(1) find("newissue.png").click() TimeUnit.SECONDS.sleep(1) type("SKrypton is awesome!") TimeUnit.SECONDS.sleep(3) find("cross.png").click() TimeUnit.SECONDS.sleep(1) find("star.png").apply { highlight("green") hover() while (true) { hover(topLeft) hover(bottomLeft) hover(bottomRight) hover(topRight) } } } }.exec(true) }
src/test/kotlin/com/waicool20/skrypton/SKryptonGithub.kt
2977501808
@file:JvmMultifileClass @file:JvmName("RxRecyclerViewAdapter") package com.jakewharton.rxbinding4.recyclerview import androidx.annotation.CheckResult import androidx.recyclerview.widget.RecyclerView.Adapter import androidx.recyclerview.widget.RecyclerView.AdapterDataObserver import androidx.recyclerview.widget.RecyclerView.ViewHolder import com.jakewharton.rxbinding4.InitialValueObservable import com.jakewharton.rxbinding4.internal.checkMainThread import io.reactivex.rxjava3.core.Observer import io.reactivex.rxjava3.android.MainThreadDisposable /** * Create an observable of data change events for `RecyclerView.adapter`. * * *Note:* A value will be emitted immediately on subscribe. */ @CheckResult fun <T : Adapter<out ViewHolder>> T.dataChanges(): InitialValueObservable<T> = RecyclerAdapterDataChangeObservable(this) private class RecyclerAdapterDataChangeObservable<T : Adapter<out ViewHolder>>( private val adapter: T ) : InitialValueObservable<T>() { override fun subscribeListener(observer: Observer<in T>) { if (!checkMainThread(observer)) { return } val listener = Listener( adapter, observer) observer.onSubscribe(listener) adapter.registerAdapterDataObserver(listener.dataObserver) } override val initialValue get() = adapter class Listener<T : Adapter<out ViewHolder>>( private val recyclerAdapter: T, observer: Observer<in T> ) : MainThreadDisposable() { val dataObserver = object : AdapterDataObserver() { override fun onChanged() { if (!isDisposed) { observer.onNext(recyclerAdapter) } } } override fun onDispose() { recyclerAdapter.unregisterAdapterDataObserver(dataObserver) } } }
rxbinding-recyclerview/src/main/java/com/jakewharton/rxbinding4/recyclerview/RecyclerAdapterDataChangeObservable.kt
2355801614
package com.github.K0zka.kotlin import com.github.K0zka.HelloService public class KotlinHello : HelloService { override fun greet(name: String?): String { return "Hello ${name}!" } }
stringperf-kotlin/src/main/kotlin/com/github/K0zka/kotlin/KotlinHello.kt
3887860125
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package xyz.cardstock.cardstock.commands import org.jetbrains.spek.api.Spek import org.kitteh.irc.client.library.element.User import org.kitteh.irc.client.library.event.helper.ActorEvent import xyz.cardstock.cardstock.implementations.commands.CompleteTestCommand import xyz.cardstock.cardstock.implementations.commands.NoOpDummyCommand import xyz.cardstock.cardstock.implementations.commands.TestCommand import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue class BaseCommandSpec : Spek({ given("an unannotated test command") { val command = UnannotatedTestCommand() on("accessing its name") { it("should throw an NPE") { assertFailsWith(NullPointerException::class) { command.name } } } on("accessing its aliases") { it("should throw an NPE") { assertFailsWith(NullPointerException::class) { command.aliases } } } on("accessing its description") { it("should throw an NPE") { assertFailsWith(NullPointerException::class) { command.description } } } on("accessing its usage") { it("should throw an NPE") { assertFailsWith(NullPointerException::class) { command.usage } } } on("accessing its CommandType") { it("should throw an NPE") { assertFailsWith(NullPointerException::class) { command.commandType } } } } given("a partially-annotated test command") { val command = TestCommand() on("accessing its name") { val name = command.name it("should be \"test\"") { assertEquals("test", name) } } on("accessing its aliases") { val aliases = command.aliases it("should only have one alias") { assertEquals(1, aliases.size) } it("should have an alias called \"spec\"") { assertEquals("spec", aliases[0]) } } on("accessing its description") { val description = command.description it("should be an empty string") { assertTrue(description.isEmpty()) } } on("accessing its usage") { val usage = command.usage it("should be \"<command>\"") { assertEquals("<command>", usage) } } on("accessing it CommandType") { val commandType = command.commandType it("should be BOTH") { assertEquals(BaseCommand.CommandType.BOTH, commandType) } } } given("a completely-annotated test command") { val command = CompleteTestCommand() on("accessing its name") { val name = command.name it("should be \"completetest\"") { assertEquals("completetest", name) } } on("accessing its aliases") { val aliases = command.aliases it("should only have one alias") { assertEquals(1, aliases.size) } it("should have an alias called \"testcomplete\"") { assertEquals("testcomplete", aliases[0]) } } on("accessing its description") { val description = command.description it("should be \"A test command.\"") { assertEquals("A test command.", description) } } on("accessing its usage") { val usage = command.usage it("should be \"<command> [something]\"") { assertEquals("<command> [something]", usage) } } on("accessing it CommandType") { val commandType = command.commandType it("should be CHANNEL") { assertEquals(BaseCommand.CommandType.CHANNEL, commandType) } } } given("a command") { val command = NoOpDummyCommand("noop") on("comparison with a command with the same metadata") { val commandTwo = NoOpDummyCommand("noop") val equals = command == commandTwo it("should equal") { assertTrue(equals) } } on("comparison with a command with completely different metadata") { val commandTwo = NoOpDummyCommand("derp", arrayOf("herp"), description = "Herp derp", usage = "<command> herp", commandType = BaseCommand.CommandType.CHANNEL) val equals = command == commandTwo it("should not equal") { assertFalse(equals) } } on("comparison with a command with a different name") { val commandTwo = NoOpDummyCommand("derp") val equals = command == commandTwo it("should not equal") { assertFalse(equals) } } on("comparison with a command with different aliases") { val commandTwo = NoOpDummyCommand("noop", arrayOf("herp")) val equals = command == commandTwo it("should not equal") { assertFalse(equals) } } on("comparison with a command with a different description") { val commandTwo = NoOpDummyCommand("noop", description = "Herp derp") val equals = command == commandTwo it("should not equal") { assertFalse(equals) } } on("comparison with a command with a different usage") { val commandTwo = NoOpDummyCommand("noop", usage = "<command> herp") val equals = command == commandTwo it("should not equal") { assertFalse(equals) } } on("comparison with a command with a different command type") { val commandTwo = NoOpDummyCommand("noop", commandType = BaseCommand.CommandType.CHANNEL) val equals = command == commandTwo it("should not equal") { assertFalse(equals) } } on("comparison an unrelated object") { val obj = object {} val equals = command.equals(obj) it("should not equal") { assertFalse(equals) } } on("comparison with null") { val equals = command.equals(null) it("should not equal") { assertFalse(equals) } } } }) private class UnannotatedTestCommand : BaseCommand() { override fun run(event: ActorEvent<User>, callInfo: CallInfo, arguments: List<String>) { throw UnsupportedOperationException() } }
src/test/kotlin/xyz/cardstock/cardstock/commands/BaseCommandSpec.kt
3170305872
/* * Copyright @ 2018 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jitsi.jibri.service import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import io.kotest.core.spec.IsolationMode import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.maps.shouldContainExactly import io.kotest.matchers.maps.shouldContainKey import io.kotest.matchers.shouldNotBe internal class AppDataTest : ShouldSpec() { override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf init { context("a json-encoded app data structure") { val appDataJsonStr = """ { "file_recording_metadata": { "upload_credentials": { "service_name":"dropbox", "token":"XXXXXXXXYYYYYYYYYZZZZZZAAAAAAABBBBBBCCCDDD" } } } """.trimIndent() should("be parsed correctly") { val appData = jacksonObjectMapper().readValue<AppData>(appDataJsonStr) appData.fileRecordingMetadata shouldNotBe null appData.fileRecordingMetadata?.shouldContainKey("upload_credentials") appData.fileRecordingMetadata?.get("upload_credentials") shouldNotBe null @Suppress("UNCHECKED_CAST") (appData.fileRecordingMetadata?.get("upload_credentials") as Map<Any, Any>) .shouldContainExactly( mapOf<Any, Any>( "service_name" to "dropbox", "token" to "XXXXXXXXYYYYYYYYYZZZZZZAAAAAAABBBBBBCCCDDD" ) ) } } context("a json-encoded app data structure with an extra top-level field") { val appDataJsonStr = """ { "file_recording_metadata": { "upload_credentials": { "service_name":"dropbox", "token":"XXXXXXXXYYYYYYYYYZZZZZZAAAAAAABBBBBBCCCDDD" } }, "other_new_field": "hello" } """.trimIndent() should("be parsed correctly and ignore unknown fields") { val appData = jacksonObjectMapper().readValue<AppData>(appDataJsonStr) appData.fileRecordingMetadata shouldNotBe null appData.fileRecordingMetadata?.shouldContainKey("upload_credentials") appData.fileRecordingMetadata?.get("upload_credentials") shouldNotBe null @Suppress("UNCHECKED_CAST") (appData.fileRecordingMetadata?.get("upload_credentials") as Map<Any, Any>) .shouldContainExactly( mapOf<Any, Any>( "service_name" to "dropbox", "token" to "XXXXXXXXYYYYYYYYYZZZZZZAAAAAAABBBBBBCCCDDD" ) ) } } } }
src/test/kotlin/org/jitsi/jibri/service/AppDataTest.kt
2333199596
/* * Copyright 2019 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.lightsaber.processor.model import io.michaelrocks.grip.mirrors.Type import io.michaelrocks.grip.mirrors.isConstructor import io.michaelrocks.lightsaber.processor.commons.toFieldDescriptor import io.michaelrocks.lightsaber.processor.commons.toMethodDescriptor import io.michaelrocks.lightsaber.processor.descriptors.FieldDescriptor import io.michaelrocks.lightsaber.processor.descriptors.MethodDescriptor import java.util.HashSet data class InjectionTarget( val type: Type.Object, val injectionPoints: Collection<InjectionPoint> ) { private val fields: Set<FieldDescriptor> private val methods: Set<MethodDescriptor> private val constructors: Set<MethodDescriptor> init { val constructors = HashSet<MethodDescriptor>() val fields = HashSet<FieldDescriptor>() val methods = HashSet<MethodDescriptor>() injectionPoints.forEach { injectionPoint -> when (injectionPoint) { is InjectionPoint.Field -> fields += injectionPoint.field.toFieldDescriptor() is InjectionPoint.Method -> if (injectionPoint.method.isConstructor) constructors += injectionPoint.method.toMethodDescriptor() else methods += injectionPoint.method.toMethodDescriptor() } } this.constructors = constructors this.fields = fields this.methods = methods } fun isInjectableField(field: FieldDescriptor) = field in fields fun isInjectableMethod(method: MethodDescriptor) = method in methods fun isInjectableConstructor(method: MethodDescriptor) = method in constructors }
processor/src/main/java/io/michaelrocks/lightsaber/processor/model/InjectionTarget.kt
4101753823
package org.owntracks.android.ui.preferences.about import androidx.fragment.app.Fragment import dagger.hilt.android.AndroidEntryPoint import org.owntracks.android.ui.preferences.PreferencesActivity @AndroidEntryPoint class AboutActivity : PreferencesActivity() { override val startFragment: Fragment? get() = AboutFragment() }
project/app/src/main/java/org/owntracks/android/ui/preferences/about/AboutActivity.kt
267069592
package com.androidvip.hebf.ui.main.battery.doze import android.os.Build import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CompoundButton import android.widget.ImageView import android.widget.LinearLayout import android.widget.Toast import androidx.annotation.RequiresApi import androidx.lifecycle.lifecycleScope import com.androidvip.hebf.R import com.androidvip.hebf.goAway import com.androidvip.hebf.runSafeOnUiThread import com.androidvip.hebf.services.PowerConnectedWork import com.androidvip.hebf.show import com.androidvip.hebf.ui.base.BaseFragment import com.androidvip.hebf.utils.* import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.fragment_doze_settings.* import kotlinx.coroutines.launch import java.util.* @RequiresApi(Build.VERSION_CODES.M) class DozeSettingsFragment : BaseFragment(), CompoundButton.OnCheckedChangeListener { private lateinit var fab: FloatingActionButton override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_doze_settings, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if (isActivityAlive) { fab = requireActivity().findViewById(R.id.doze_fab) } setUpInfoListeners(view) val savedIdlingMode = prefs.getString(K.PREF.DOZE_IDLING_MODE, Doze.IDLING_MODE_DEEP) if (savedIdlingMode == Doze.IDLING_MODE_LIGHT) { setIdlingMode(savedIdlingMode, getString(R.string.doze_record_type_light)) } else { setIdlingMode(savedIdlingMode, getString(R.string.doze_record_type_deep)) } setWaitingInterval(prefs.getInt(K.PREF.DOZE_INTERVAL_MINUTES, 20).toString()) lifecycleScope.launch(workerContext) { val deviceIdleEnabled = Doze.deviceIdleEnabled() val isIdle = Doze.isInIdleState val isRooted = isRooted() runSafeOnUiThread { dozeProgressSettings.goAway() dozeScrollSettings.show() if (!isRooted) { dozeMasterSwitch.isChecked = true dozeMasterSwitch.isEnabled = false dozeChargerSwitch.isEnabled = false aggressiveDozeSwitch.isEnabled = false } else { dozeMasterSwitch.isChecked = deviceIdleEnabled if (isIdle) { dozeUnforceButton.isEnabled = true } dozeMasterSwitch.setOnCheckedChangeListener(null) aggressiveDozeSwitch.setOnCheckedChangeListener(null) dozeChargerSwitch.setOnCheckedChangeListener(null) dozeMasterSwitch.setOnCheckedChangeListener(this@DozeSettingsFragment) aggressiveDozeSwitch.isChecked = dozeMasterSwitch.isChecked && prefs.getBoolean(K.PREF.DOZE_AGGRESSIVE, false) dozeChargerSwitch.isChecked = prefs.getBoolean(K.PREF.DOZE_CHARGER, false) dozeChargerSwitch.isEnabled = isRooted dozeChargerSwitch.setOnCheckedChangeListener(this@DozeSettingsFragment) aggressiveDozeSwitch.setOnCheckedChangeListener(this@DozeSettingsFragment) if (!aggressiveDozeSwitch.isChecked) { dozeChargerSwitch.isChecked = false dozeChargerSwitch.isEnabled = false } dozeUnforceButton.setOnClickListener { v -> Doze.unforceIdle() Logger.logInfo("Unforcing doze", findContext()) Snackbar.make(v, R.string.done, Snackbar.LENGTH_SHORT).show() } } } } val idlingModeLayout = view.findViewById<LinearLayout>(R.id.doze_layout_idling_mode) val waitingIntervalLayout = view.findViewById<LinearLayout>(R.id.doze_layout_waiting_interval) waitingIntervalLayout.setOnClickListener { val checkedItem: Int = when (prefs.getInt(K.PREF.DOZE_INTERVAL_MINUTES, 20)) { 10 -> 0 15 -> 1 20 -> 2 30 -> 3 45 -> 4 else -> 2 } val items = resources.getStringArray(R.array.doze_waiting_intervals) MaterialAlertDialogBuilder(findContext()) .setTitle(R.string.doze_waiting_interval) .setNegativeButton(android.R.string.cancel) { _, _ -> } .setSingleChoiceItems(items, checkedItem) { dialog, which -> dialog.dismiss() when (which) { 0 -> setWaitingInterval("10") 1 -> setWaitingInterval("15") 2 -> setWaitingInterval("20") 3 -> setWaitingInterval("30") 4 -> setWaitingInterval("45") else -> setWaitingInterval("20") } } .show() } idlingModeLayout.setOnClickListener { val checkedItem: Int = when (prefs.getString(K.PREF.DOZE_IDLING_MODE, Doze.IDLING_MODE_DEEP)) { Doze.IDLING_MODE_LIGHT -> 0 Doze.IDLING_MODE_DEEP -> 1 else -> 1 } MaterialAlertDialogBuilder(findContext()) .setTitle(R.string.doze_idling_mode) .setNegativeButton(android.R.string.cancel) { _, _ -> } .setSingleChoiceItems(resources.getStringArray(R.array.doze_idling_modes), checkedItem) { dialog, which -> dialog.dismiss() when (which) { 0 -> setIdlingMode(Doze.IDLING_MODE_LIGHT, getString(R.string.doze_record_type_light)) 1 -> setIdlingMode(Doze.IDLING_MODE_DEEP, getString(R.string.doze_record_type_deep)) else -> setIdlingMode(Doze.IDLING_MODE_DEEP, getString(R.string.doze_record_type_deep)) } } .show() } } override fun onResume() { super.onResume() runCatching { fab.hide() fab.setOnClickListener(null) } } override fun onCheckedChanged(compoundButton: CompoundButton, isChecked: Boolean) { when (compoundButton.id) { R.id.dozeMasterSwitch -> { lifecycleScope.launch(workerContext) { Doze.toggleDeviceIdle(isChecked) runSafeOnUiThread { if (isChecked) { enableEverything() Logger.logInfo("Enabled doze mode", findContext()) } else { disableEverything() Logger.logInfo("Disabled doze mode", findContext()) } } } } R.id.aggressiveDozeSwitch -> if (isChecked) { prefs.putBoolean(K.PREF.DOZE_AGGRESSIVE, true) Snackbar.make(aggressiveDozeSwitch, R.string.aggressive_doze_on, Snackbar.LENGTH_SHORT).show() Doze.toggleDozeService(true, context) dozeChargerSwitch.isEnabled = true Logger.logInfo("Enabled aggressive doze", findContext()) } else { prefs.putBoolean(K.PREF.DOZE_AGGRESSIVE, false) Snackbar.make(aggressiveDozeSwitch, R.string.aggressive_doze_off, Snackbar.LENGTH_SHORT).show() Doze.toggleDozeService(false, context) dozeChargerSwitch.isEnabled = false Logger.logInfo("Disabled aggressive doze", findContext()) } R.id.dozeChargerSwitch -> { if (isChecked) { PowerConnectedWork.scheduleJobPeriodic(applicationContext) prefs.putBoolean(K.PREF.DOZE_CHARGER, true) } else { // Don't cancel the service (VIP may depend on it) prefs.putBoolean(K.PREF.DOZE_CHARGER, false) } } } } private fun setIdlingMode(idlingMode: String, newText: String) { prefs.putString(K.PREF.DOZE_IDLING_MODE, idlingMode) this.dozeIdlingModeText.text = newText setWaitingInterval(prefs.getInt(K.PREF.DOZE_INTERVAL_MINUTES, 20).toString()) } private fun setWaitingInterval(strMinutes: String) { val minutes = runCatching { if (strMinutes.toInt() < 10) 20 else strMinutes.toInt() }.getOrDefault(20) prefs.putInt(K.PREF.DOZE_INTERVAL_MINUTES, minutes) dozeWaitingIntervalText.text = String.format(getString(R.string.doze_waiting_interval_sum), strMinutes, dozeIdlingModeText.text) } private fun disableEverything() { aggressiveDozeSwitch.isChecked = false aggressiveDozeSwitch.isEnabled = false dozeChargerSwitch.isChecked = false dozeChargerSwitch.isEnabled = false } private fun enableEverything() { aggressiveDozeSwitch.isEnabled = true dozeChargerSwitch.isEnabled = true } private fun infoDialogListener(message: String): View.OnClickListener { return View.OnClickListener { val achievementsSet = userPrefs.getStringSet(K.PREF.ACHIEVEMENT_SET, HashSet()) if (!achievementsSet.contains("help")) { Utils.addAchievement(requireContext().applicationContext, "help") Toast.makeText(findContext(), getString(R.string.achievement_unlocked, getString(R.string.achievement_help)), Toast.LENGTH_LONG).show() } if (isAdded) { ModalBottomSheet.newInstance("Info", message).show(parentFragmentManager, "sheet") } } } private fun setUpInfoListeners(view: View) { val instantInfo = view.findViewById<ImageView>(R.id.doze_info_instant_doze) val chargerInfo = view.findViewById<ImageView>(R.id.doze_info_turn_off_charger) instantInfo.setOnClickListener(infoDialogListener(getString(R.string.aggressive_doze_sum))) chargerInfo.setOnClickListener(infoDialogListener(getString(R.string.vip_disable_when_connecting_sum))) } }
app/src/main/java/com/androidvip/hebf/ui/main/battery/doze/DozeSettingsFragment.kt
1648926394
package iii_conventions import util.TODO class Invokable { private var numberOfInvocations: Int = 0 operator fun invoke(): Invokable { numberOfInvocations++ return this } fun getNumberOfInvocations(): Int = numberOfInvocations } fun todoTask31(): Nothing = TODO( """ Task 31. Change class Invokable to count the number of invocations (round brackets). Uncomment the commented code - it should return 4. """, references = { invokable: Invokable -> }) fun task31(invokable: Invokable): Int { return invokable()()()().getNumberOfInvocations() }
src/iii_conventions/_31_Invoke_.kt
2162279519
package at.cpickl.gadsu.mail import at.cpickl.gadsu.isNotValidMail import at.cpickl.gadsu.isValidMail import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.testng.annotations.DataProvider import org.testng.annotations.Test @Test class IsValidMailTest { @DataProvider fun provideValidMailAddresses(): Array<Array<out Any>> = addresses( "[email protected]", "[email protected]" ) @DataProvider fun provideInvalidMailAddresses(): Array<Array<out Any>> = addresses( "", "a", "[email protected]", "[email protected]", "[email protected]" ) private fun addresses(vararg addresses: String): Array<Array<out Any>> { return addresses.map { arrayOf(it) }.toTypedArray() } @Test(dataProvider = "provideValidMailAddresses") fun `valid mail addresses`(address: String) { assertThat(address.isValidMail(), equalTo(true)) assertThat(address.isNotValidMail(), equalTo(false)) } @Test(dataProvider = "provideInvalidMailAddresses") fun `invalid mail addresses`(address: String) { assertThat(address.isValidMail(), equalTo(false)) assertThat(address.isNotValidMail(), equalTo(true)) } }
src/test/kotlin/at/cpickl/gadsu/mail/mail_test.kt
1957485103
package com.nullpointerbay.u2020k.di import com.github.salomonbrys.kodein.Kodein import com.github.salomonbrys.kodein.instance import com.github.salomonbrys.kodein.provider import com.nullpointerbay.u2020k.dao.RepoDao import com.nullpointerbay.u2020k.dao.RepoDaoImpl fun daoModule() = Kodein.Module { bind<RepoDao>() with provider { RepoDaoImpl(instance()) } }
app/src/prod/kotlin/com/nullpointerbay/u2020k/di/DaoModule.kt
1335604609
VE=SEPF_SHV-E300K_5.0.1_0017 HS=ab8ab48e78d16aab82a3fdbe3b925e38e37773eff6bf77795364ed9374608b61 HA=4182fd9caeac941149af0ea38409e5408d9f88936315072a1d2835479c2d033d HP=cea1c7b175be18a96820c791c5e659ee8cb6853168985fdecffedbef5205ae19 HF=b259db05c7340ed9324cf86570e1fb16682eda5c35fef36cbcb8fa0ad1f37d48 HM=b2312a2e536bc725b2801c00b63ab1ab557180e14bef97b1693ae617ebb68992 HV=fc4a9948530866f2133f9eaf678481773f7a9ac540480b17164bfe775ae22729 BD=Fri Jun 05 09:34:35 2015 MP=SHA-256 MV=SHA-256
build/ramdisk/tw-lollipop/sepolicy_version.kt
987770993
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vanniktech.emoji.material import android.content.Context import android.text.SpannableStringBuilder import android.util.AttributeSet import androidx.annotation.AttrRes import androidx.annotation.CallSuper import androidx.annotation.DimenRes import androidx.annotation.Px import com.google.android.material.checkbox.MaterialCheckBox import com.vanniktech.emoji.EmojiDisplayable import com.vanniktech.emoji.EmojiManager import com.vanniktech.emoji.init import com.vanniktech.emoji.replaceWithImages import kotlin.jvm.JvmOverloads open class EmojiMaterialCheckBox @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr: Int = com.google.android.material.R.attr.checkboxStyle, ) : MaterialCheckBox(context, attrs, defStyleAttr), EmojiDisplayable { @Px private var emojiSize: Float init { emojiSize = init(attrs, R.styleable.EmojiMaterialCheckBox, R.styleable.EmojiMaterialCheckBox_emojiSize) } @CallSuper override fun setText(rawText: CharSequence?, type: BufferType) { if (isInEditMode) { super.setText(rawText, type) return } val spannableStringBuilder = SpannableStringBuilder(rawText ?: "") val fontMetrics = paint.fontMetrics val defaultEmojiSize = fontMetrics.descent - fontMetrics.ascent EmojiManager.replaceWithImages(context, spannableStringBuilder, if (emojiSize != 0f) emojiSize else defaultEmojiSize) super.setText(spannableStringBuilder, type) } override fun getEmojiSize() = emojiSize override fun setEmojiSize(@Px pixels: Int) = setEmojiSize(pixels, true) override fun setEmojiSize(@Px pixels: Int, shouldInvalidate: Boolean) { emojiSize = pixels.toFloat() if (shouldInvalidate) { text = text } } override fun setEmojiSizeRes(@DimenRes res: Int) = setEmojiSizeRes(res, true) override fun setEmojiSizeRes(@DimenRes res: Int, shouldInvalidate: Boolean) = setEmojiSize(resources.getDimensionPixelSize(res), shouldInvalidate) }
emoji-material/src/androidMain/kotlin/com/vanniktech/emoji/material/EmojiMaterialCheckBox.kt
771089471
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * * INCLUDES MODIFICATIONS BY RICHARD ZSCHECH AS WELL AS GOOGLE. */ package java.util import kotlin.math.ln import kotlin.math.sqrt import kotlin.synchronized open class Random internal constructor(var ktRandom: kotlin.random.Random) { var haveNextNextGaussian = false var nextNextGaussian = 0.0 constructor() : this(kotlin.random.Random.Default) constructor(seed: Long) : this(kotlin.random.Random(seed)) fun nextBoolean() = ktRandom.nextBoolean() fun nextBytes(buf: ByteArray) = ktRandom.nextBytes(buf) fun nextDouble() = ktRandom.nextDouble() fun nextFloat() = ktRandom.nextFloat() fun nextGaussian(): Double { return synchronized(this) { if (haveNextNextGaussian) { // if X1 has been returned, return the second Gaussian haveNextNextGaussian = false nextNextGaussian } else { var s: Double var v1: Double var v2: Double do { // Generates two independent random variables U1, U2 v1 = 2 * nextDouble() - 1 v2 = 2 * nextDouble() - 1 s = v1 * v1 + v2 * v2 } while (s >= 1) // See errata for TAOCP vol. 2, 3rd ed. for proper handling of s == 0 case // (page 5 of http://www-cs-faculty.stanford.edu/~uno/err2.ps.gz) val norm = if (s == 0.0) 0.0 else sqrt(-2.0 * ln(s) / s) nextNextGaussian = v2 * norm haveNextNextGaussian = true v1 * norm } } } fun nextInt() = ktRandom.nextInt() fun nextInt(n: Int) = ktRandom.nextInt(n) fun nextLong() = ktRandom.nextLong() fun setSeed(seed: Long) { synchronized(this) { haveNextNextGaussian = false ktRandom = kotlin.random.Random(seed) } } }
j2kt/jre/java/native/java/util/Random.kt
1421015329
package com.sakebook.android.nexustimer.model /** * Created by sakemotoshinya on 16/06/05. */ enum class OffTimer(val minute: Int) { FIVE(5), ONE_FIVE(15), THREE_ZERO(30), SIX_ZERO(60), NINE_ZERO(90), ONE_TWO_ZERO(120), ; }
app/src/main/java/com/sakebook/android/nexustimer/model/OffTimer.kt
3782734743
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.dfn.dsl.ondemand import androidx.fragment.app.FragmentActivity class FeatureActivity : FragmentActivity(R.layout.feature_activity)
DynamicFeatureNavigation/DSL/ondemand/src/main/java/com/example/android/dfn/dsl/ondemand/FeatureActivity.kt
3469410801
/* * Copyright 2015 eje inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.meganekkovr /** * Copied from VrAppFramework/Include/Input.h */ object JoyButton { const val BUTTON_A = 1 shl 0 const val BUTTON_B = 1 shl 1 const val BUTTON_X = 1 shl 2 const val BUTTON_Y = 1 shl 3 const val BUTTON_START = 1 shl 4 const val BUTTON_BACK = 1 shl 5 const val BUTTON_SELECT = 1 shl 6 const val BUTTON_MENU = 1 shl 7 const val BUTTON_RIGHT_TRIGGER = 1 shl 8 const val BUTTON_LEFT_TRIGGER = 1 shl 9 const val BUTTON_DPAD_UP = 1 shl 10 const val BUTTON_DPAD_DOWN = 1 shl 11 const val BUTTON_DPAD_LEFT = 1 shl 12 const val BUTTON_DPAD_RIGHT = 1 shl 13 const val BUTTON_LSTICK_UP = 1 shl 14 const val BUTTON_LSTICK_DOWN = 1 shl 15 const val BUTTON_LSTICK_LEFT = 1 shl 16 const val BUTTON_LSTICK_RIGHT = 1 shl 17 const val BUTTON_RSTICK_UP = 1 shl 18 const val BUTTON_RSTICK_DOWN = 1 shl 19 const val BUTTON_RSTICK_LEFT = 1 shl 20 const val BUTTON_RSTICK_RIGHT = 1 shl 21 const val BUTTON_TOUCH = 1 shl 22 const val BUTTON_SWIPE_UP = 1 shl 23 const val BUTTON_SWIPE_DOWN = 1 shl 24 const val BUTTON_SWIPE_FORWARD = 1 shl 25 const val BUTTON_SWIPE_BACK = 1 shl 26 const val BUTTON_TOUCH_WAS_SWIPE = 1 shl 27 const val BUTTON_TOUCH_SINGLE = 1 shl 28 const val BUTTON_TOUCH_DOUBLE = 1 shl 29 const val BUTTON_TOUCH_LONGPRESS = 1 shl 30 /** * @param buttonState Returned value from `FrameInput#getButtonPressed()`, * `FrameInput#getButtonReleased()` or * `FrameInput#getButtonState()`. * @param code JoyButton.BUTTON_* constant value. * @return true if `buttonState` contains `code` in bit flags. */ @JvmStatic fun contains(buttonState: Int, code: Int): Boolean { return buttonState and code > 0 } }
library/src/main/java/org/meganekkovr/JoyButton.kt
2914994451
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package codegen import org.gradle.api.provider.Property import org.gradle.api.tasks.Input import java.io.File @Suppress("unused") abstract class GenerateKotlinDependencyExtensions : CodeGenerationTask() { @get:Input abstract val embeddedKotlinVersion: Property<String> @get:Input abstract val kotlinDslPluginsVersion: Property<String> override fun File.writeFiles() { val kotlinDslPluginsVersion = kotlinDslPluginsVersion.get() val embeddedKotlinVersion = embeddedKotlinVersion.get() // IMPORTANT: kotlinDslPluginsVersion should NOT be made a `const` to avoid inlining writeFile( "org/gradle/kotlin/dsl/support/KotlinDslPlugins.kt", """$licenseHeader package org.gradle.kotlin.dsl.support /** * Expected version of the `kotlin-dsl` plugin for the running Gradle version. */ @Suppress("unused") val expectedKotlinDslPluginsVersion: String get() = "$kotlinDslPluginsVersion" """) writeFile( "org/gradle/kotlin/dsl/KotlinDependencyExtensions.kt", """$licenseHeader package org.gradle.kotlin.dsl import org.gradle.api.artifacts.dsl.DependencyHandler import org.gradle.plugin.use.PluginDependenciesSpec import org.gradle.plugin.use.PluginDependencySpec /** * The version of the Kotlin compiler embedded in gradle-kotlin-dsl (currently _${embeddedKotlinVersion}_). */ val embeddedKotlinVersion = "$embeddedKotlinVersion" /** * Builds the dependency notation for the named Kotlin [module] at the embedded version (currently _${embeddedKotlinVersion}_). * * @param module simple name of the Kotlin module, for example "reflect". */ fun DependencyHandler.embeddedKotlin(module: String): Any = kotlin(module, embeddedKotlinVersion) /** * Builds the dependency notation for the named Kotlin [module] at the given [version]. * * @param module simple name of the Kotlin module, for example "reflect". * @param version optional desired version, unspecified if null. */ fun DependencyHandler.kotlin(module: String, version: String? = null): Any = "org.jetbrains.kotlin:kotlin-${'$'}module${'$'}{version?.let { ":${'$'}version" } ?: ""}" /** * Applies the given Kotlin plugin [module]. * * For example: `plugins { kotlin("jvm") version "$embeddedKotlinVersion" }` * * Visit the [plugin portal](https://plugins.gradle.org/search?term=org.jetbrains.kotlin) to see the list of available plugins. * * @param module simple name of the Kotlin Gradle plugin module, for example "jvm", "android", "kapt", "plugin.allopen" etc... */ fun PluginDependenciesSpec.kotlin(module: String): PluginDependencySpec = id("org.jetbrains.kotlin.${'$'}module") /** * The `embedded-kotlin` plugin. * * Equivalent to `id("org.gradle.kotlin.embedded-kotlin") version "$kotlinDslPluginsVersion"` * * @see org.gradle.kotlin.dsl.plugins.embedded.EmbeddedKotlinPlugin */ val PluginDependenciesSpec.`embedded-kotlin`: PluginDependencySpec get() = id("org.gradle.kotlin.embedded-kotlin") version "$kotlinDslPluginsVersion" /** * The `kotlin-dsl` plugin. * * Equivalent to `id("org.gradle.kotlin.kotlin-dsl") version "$kotlinDslPluginsVersion"` * * @see org.gradle.kotlin.dsl.plugins.dsl.KotlinDslPlugin */ val PluginDependenciesSpec.`kotlin-dsl`: PluginDependencySpec get() = id("org.gradle.kotlin.kotlin-dsl") version "$kotlinDslPluginsVersion" /** * The `kotlin-dsl.base` plugin. * * Equivalent to `id("org.gradle.kotlin.kotlin-dsl.base") version "$kotlinDslPluginsVersion"` * * @see org.gradle.kotlin.dsl.plugins.base.KotlinDslBasePlugin */ val PluginDependenciesSpec.`kotlin-dsl-base`: PluginDependencySpec get() = id("org.gradle.kotlin.kotlin-dsl.base") version "$kotlinDslPluginsVersion" /** * The `kotlin-dsl.precompiled-script-plugins` plugin. * * Equivalent to `id("org.gradle.kotlin.kotlin-dsl.precompiled-script-plugins") version "$kotlinDslPluginsVersion"` * * @see org.gradle.kotlin.dsl.plugins.precompiled.PrecompiledScriptPlugins */ val PluginDependenciesSpec.`kotlin-dsl-precompiled-script-plugins`: PluginDependencySpec get() = id("org.gradle.kotlin.kotlin-dsl.precompiled-script-plugins") version "$kotlinDslPluginsVersion" """) } }
buildSrc/subprojects/kotlin-dsl/src/main/kotlin/codegen/GenerateKotlinDependencyExtensions.kt
545739352
package configurations import jetbrains.buildServer.configs.kotlin.v2018_2.AbsoluteId import model.CIBuildModel import model.Stage class DependenciesCheck(model: CIBuildModel, stage: Stage) : BaseGradleBuildType(model, stage = stage, init = { uuid = "${model.projectPrefix}DependenciesCheck" id = AbsoluteId(uuid) name = "Dependencies Check - Java8 Linux" description = "Checks external dependencies in Gradle distribution for known, published vulnerabilities" params { param("env.JAVA_HOME", buildJavaHome) } features { publishBuildStatusToGithub(model) } applyDefaults( model, this, "dependencyCheckAnalyze", notQuick = true, extraParameters = buildScanTag("DependenciesCheck") ) })
.teamcity/Gradle_Check/configurations/DependenciesCheck.kt
944069421
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.particle.mesh.ui.setup.barcodescanning import android.content.Context import android.content.pm.PackageManager import android.os.Bundle import androidx.core.app.ActivityCompat import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback import androidx.core.content.ContextCompat import androidx.appcompat.app.AppCompatActivity import android.util.Log import com.google.android.gms.common.annotation.KeepName import java.io.IOException import java.util.ArrayList import io.particle.mesh.ui.setup.barcodescanning.barcode.BarcodeScanningProcessor import io.particle.mesh.ui.R /** * Demo app showing the various features of ML Kit for Firebase. This class is used to * set up continuous frame processing on frames from a camera source. */ @KeepName class LivePreviewActivity : AppCompatActivity(), OnRequestPermissionsResultCallback { private var cameraSource: CameraSource? = null private var preview: CameraSourcePreview? = null private var graphicOverlay: GraphicOverlay? = null private val selectedModel = "Barcode Detection" private val requiredPermissions: Array<String> get() { return try { val info = this.packageManager.getPackageInfo( this.packageName, PackageManager.GET_PERMISSIONS) val ps = info.requestedPermissions if (ps != null && ps.size > 0) { ps } else { Array(0) { "" } } } catch (e: Exception) { Array(0) { "" } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, "onCreate") // setContentView(R.layout.activity_live_preview) preview = findViewById(R.id.scanPreview) if (preview == null) { Log.d(TAG, "Preview is null") } graphicOverlay = findViewById(R.id.scanPreviewOverlay) if (graphicOverlay == null) { Log.d(TAG, "graphicOverlay is null") } if (allPermissionsGranted()) { createCameraSource() } else { getRuntimePermissions() } } private fun createCameraSource() { // If there's no existing cameraSource, create one. if (cameraSource == null) { cameraSource = CameraSource(this, graphicOverlay) } cameraSource!!.setFacing(CameraSource.CAMERA_FACING_BACK) cameraSource!!.setMachineLearningFrameProcessor(BarcodeScanningProcessor()) } /** * Starts or restarts the camera source, if it exists. If the camera source doesn'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. */ private fun startCameraSource() { if (cameraSource != null) { try { if (preview == null) { Log.d(TAG, "resume: Preview is null") } if (graphicOverlay == null) { Log.d(TAG, "resume: graphOverlay is null") } preview!!.start(cameraSource, graphicOverlay) } catch (e: IOException) { Log.e(TAG, "Unable to start camera source.", e) cameraSource!!.release() cameraSource = null } } } public override fun onResume() { super.onResume() Log.d(TAG, "onResume") startCameraSource() } /** * Stops the camera. */ override fun onPause() { super.onPause() preview!!.stop() } public override fun onDestroy() { super.onDestroy() if (cameraSource != null) { cameraSource!!.release() } } private fun allPermissionsGranted(): Boolean { for (permission in requiredPermissions) { if (!isPermissionGranted(this, permission)) { return false } } return true } private fun getRuntimePermissions() { val allNeededPermissions = ArrayList<String>() for (permission in requiredPermissions) { if (!isPermissionGranted(this, permission)) { allNeededPermissions.add(permission) } } if (!allNeededPermissions.isEmpty()) { ActivityCompat.requestPermissions( this, allNeededPermissions.toTypedArray(), PERMISSION_REQUESTS) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray) { Log.i(TAG, "Permission granted!") if (allPermissionsGranted()) { createCameraSource() } super.onRequestPermissionsResult(requestCode, permissions, grantResults) } companion object { private val TAG = "LivePreviewActivity" private val PERMISSION_REQUESTS = 1 private fun isPermissionGranted(context: Context, permission: String): Boolean { if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) { Log.i(TAG, "Permission granted: $permission") return true } Log.i(TAG, "Permission NOT granted: $permission") return false } } }
meshui/src/main/java/io/particle/mesh/ui/setup/barcodescanning/LivePreviewActivity.kt
2977457723
package com.waz.zclient.feature.backup.conversations import com.waz.zclient.core.extension.empty import com.waz.zclient.feature.backup.BackUpDataMapper import com.waz.zclient.feature.backup.BackUpDataSource import com.waz.zclient.feature.backup.BackUpIOHandler import com.waz.zclient.storage.db.conversations.ConversationsEntity import kotlinx.serialization.Serializable import java.io.File @Serializable data class ConversationsBackUpModel( val id: String, val remoteId: String = String.empty(), val name: String? = null, val creator: String = String.empty(), val conversationType: Int = 0, val team: String? = null, val managed: Boolean? = null, val lastEventTime: Long = 0, val active: Boolean = false, val lastRead: Long = 0, val mutedStatus: Int = 0, val muteTime: Long = 0, val archived: Boolean = false, val archiveTime: Long = 0, val cleared: Long? = null, val generatedName: String = String.empty(), val searchKey: String? = null, val unreadCount: Int = 0, val unsentCount: Int = 0, val hidden: Boolean = false, val missedCall: String? = null, val incomingKnock: String? = null, val verified: String? = null, val ephemeral: Long? = null, val globalEphemeral: Long? = null, val unreadCallCount: Int = 0, val unreadPingCount: Int = 0, val access: String? = null, val accessRole: String? = null, val link: String? = null, val unreadMentionsCount: Int = 0, val unreadQuoteCount: Int = 0, val receiptMode: Int? = null, val legalHoldStatus: Int = 0, val domain: String? = null ) class ConversationsBackupMapper : BackUpDataMapper<ConversationsBackUpModel, ConversationsEntity> { override fun fromEntity(entity: ConversationsEntity) = ConversationsBackUpModel( id = entity.id, remoteId = entity.remoteId, name = entity.name, creator = entity.creator, conversationType = entity.conversationType, team = entity.team, managed = entity.managed, lastEventTime = entity.lastEventTime, active = entity.active, lastRead = entity.lastRead, mutedStatus = entity.mutedStatus, muteTime = entity.muteTime, archived = entity.archived, archiveTime = entity.archiveTime, cleared = entity.cleared, generatedName = entity.generatedName, searchKey = entity.searchKey, unreadCount = entity.unreadCount, unsentCount = entity.unsentCount, hidden = entity.hidden, missedCall = entity.missedCall, incomingKnock = entity.incomingKnock, verified = entity.verified, ephemeral = entity.ephemeral, globalEphemeral = entity.globalEphemeral, unreadCallCount = entity.unreadCallCount, unreadPingCount = entity.unreadPingCount, access = entity.access, accessRole = entity.accessRole, link = entity.link, unreadMentionsCount = entity.unreadMentionsCount, unreadQuoteCount = entity.unreadQuoteCount, receiptMode = entity.receiptMode, legalHoldStatus = entity.legalHoldStatus, domain = entity.domain ) override fun toEntity(model: ConversationsBackUpModel) = ConversationsEntity( id = model.id, remoteId = model.remoteId, name = model.name, creator = model.creator, conversationType = model.conversationType, team = model.team, managed = model.managed, lastEventTime = model.lastEventTime, active = model.active, lastRead = model.lastRead, mutedStatus = model.mutedStatus, muteTime = model.muteTime, archived = model.archived, archiveTime = model.archiveTime, cleared = model.cleared, generatedName = model.generatedName, searchKey = model.searchKey, unreadCount = model.unreadCount, unsentCount = model.unsentCount, hidden = model.hidden, missedCall = model.missedCall, incomingKnock = model.incomingKnock, verified = model.verified, ephemeral = model.ephemeral, globalEphemeral = model.globalEphemeral, unreadCallCount = model.unreadCallCount, unreadPingCount = model.unreadPingCount, access = model.access, accessRole = model.accessRole, link = model.link, unreadMentionsCount = model.unreadMentionsCount, unreadQuoteCount = model.unreadQuoteCount, receiptMode = model.receiptMode, legalHoldStatus = model.legalHoldStatus, domain = model.domain ) } class ConversationsBackupDataSource( override val databaseLocalDataSource: BackUpIOHandler<ConversationsEntity, Unit>, override val backUpLocalDataSource: BackUpIOHandler<ConversationsBackUpModel, File>, override val mapper: BackUpDataMapper<ConversationsBackUpModel, ConversationsEntity> ) : BackUpDataSource<ConversationsBackUpModel, ConversationsEntity>()
app/src/main/kotlin/com/waz/zclient/feature/backup/conversations/ConversationsBackupDataSource.kt
866710362
package cn.thens.kdroid.sample.nature.base import android.graphics.Canvas import android.graphics.PointF import androidx.annotation.CallSuper interface Sprite { val stage: Stage val position: PointF val mas: Float val velocity: PointF val acceleration: Set<PointF> var x: Float get() = position.x set(value) { position.x = Math.min(stage.width.toFloat(), Math.max(0F, value)) } var y: Float get() = position.y set(value) { position.y = Math.min(stage.height.toFloat(), Math.max(0F, value)) } @CallSuper fun onDraw(canvas: Canvas) { var ax = 0F var ay = 0F acceleration.forEach { ax += it.x; ay += it.y } velocity.offset(ax * Stage.SPEED_FACTOR, ay * Stage.SPEED_FACTOR) x = position.x + velocity.x * Stage.SPEED_FACTOR y = position.y + velocity.y * Stage.SPEED_FACTOR } }
sample/src/main/java/cn/thens/kdroid/sample/nature/base/Sprite.kt
1464808556
/* * Copyright 2017 vinayagasundar * Copyright 2017 randhirgupta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package you.devknights.minimalweather.ui.landing import android.app.Application import android.arch.lifecycle.AndroidViewModel import android.arch.lifecycle.LiveData import android.location.Location import javax.inject.Inject import you.devknights.minimalweather.database.entity.WeatherEntity import you.devknights.minimalweather.model.Resource import you.devknights.minimalweather.repo.weather.WeatherRepository /** * @author vinayagasundar */ class LandingViewModel @Inject constructor(application: Application, private val weatherRepository: WeatherRepository) : AndroidViewModel(application) { @Inject lateinit var location: LiveData<Location> fun getWeatherData(location: Location): LiveData<Resource<WeatherEntity>> { return weatherRepository.getWeatherInfoAsLiveData(location) } }
app/src/main/java/you/devknights/minimalweather/ui/landing/LandingViewModel.kt
628925781
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.codelab.events import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.facebook.litho.ComponentContext import com.facebook.litho.LithoView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val componentContext = ComponentContext(this) setContentView(LithoView.create(this, RootComponent.create(componentContext).build())) } }
codelabs/events/app/src/main/java/com/facebook/litho/codelab/events/MainActivity.kt
3082655073
/* * Copyright 2017 vinayagasundar * Copyright 2017 randhirgupta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package you.devknights.minimalweather.di import dagger.Module import dagger.android.ContributesAndroidInjector import you.devknights.minimalweather.ui.landing.LandingFragment /** * @author vinayagasundar */ @Module abstract class FragmentBuilderModule { @ContributesAndroidInjector internal abstract fun contributeLandingFragment(): LandingFragment }
app/src/main/java/you/devknights/minimalweather/di/FragmentBuilderModule.kt
4179545696
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.tiles import android.os.Looper import androidx.wear.tiles.RequestBuilders import androidx.wear.tiles.testing.TestTileClient import com.google.common.truth.Truth.assertThat import com.google.common.util.concurrent.MoreExecutors import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf @RunWith(RobolectricTestRunner::class) public class CoroutinesTileTest { private val fakeTileService = TestTileService() private lateinit var clientUnderTest: TestTileClient<TestTileService> @Before public fun setUp() { val executor = MoreExecutors.directExecutor() clientUnderTest = TestTileClient(fakeTileService, executor) } @Test public fun canCallOnTileRequest() { val future = clientUnderTest.requestTile(RequestBuilders.TileRequest.Builder().build()) shadowOf(Looper.getMainLooper()).idle() assertThat(future.isDone).isTrue() assertThat(future.get().resourcesVersion).isEqualTo(TestTileService.FAKE_VERSION) } @Test public fun canCallOnResourcesRequest() { val future = clientUnderTest.requestResources( RequestBuilders.ResourcesRequest.Builder().build() ) shadowOf(Looper.getMainLooper()).idle() assertThat(future.isDone).isTrue() assertThat(future.get().version).isEqualTo(TestTileService.FAKE_VERSION) } }
tiles/src/test/java/com/google/android/horologist/tiles/CoroutinesTileTest.kt
313547043
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalHorologistMediaDataApi::class) package com.google.android.horologist.media.data.mapper import com.google.android.horologist.media.data.ExperimentalHorologistMediaDataApi import com.google.android.horologist.media.data.database.model.MediaDownloadEntity import com.google.android.horologist.media.data.database.model.MediaEntity import com.google.android.horologist.media.data.database.model.PlaylistEntity import com.google.android.horologist.media.data.database.model.PopulatedPlaylist import com.google.android.horologist.media.model.Media import com.google.android.horologist.media.model.MediaDownload import com.google.android.horologist.media.model.Playlist import com.google.android.horologist.media.model.PlaylistDownload import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Test class PlaylistDownloadMapperTest { private lateinit var sut: PlaylistDownloadMapper @Before fun setUp() { sut = PlaylistDownloadMapper(PlaylistMapper(MediaMapper(MediaExtrasMapperNoopImpl))) } @Test fun mapsCorrectly() { // given val playlistId = "playlistId" val playlistName = "playlistName" val playlistArtworkUri = "playlistArtworkUri" val mediaId = "mediaId" val mediaUrl = "mediaUrl" val artworkUrl = "artworkUrl" val title = "title" val artist = "artist" val populatedPlaylist = PopulatedPlaylist( PlaylistEntity( playlistId = playlistId, name = playlistName, artworkUri = playlistArtworkUri ), listOf( MediaEntity( mediaId = mediaId, mediaUrl = mediaUrl, artworkUrl = artworkUrl, title = title, artist = artist ) ) ) val expectedMedia = Media( id = mediaId, uri = mediaUrl, title = title, artist = artist, artworkUri = artworkUrl ) val mediaDownloadEntity = listOf<MediaDownloadEntity>() // then val result = sut.map(populatedPlaylist, mediaDownloadEntity) // then assertThat(result).isEqualTo( PlaylistDownload( playlist = Playlist( id = playlistId, name = playlistName, artworkUri = playlistArtworkUri, mediaList = listOf( expectedMedia ) ), mediaList = listOf( MediaDownload( media = expectedMedia, status = MediaDownload.Status.Idle, size = MediaDownload.Size.Unknown ) ) ) ) } }
media-data/src/test/java/com/google/android/horologist/media/data/mapper/PlaylistDownloadMapperTest.kt
3636365998
package com.ystore.lib.chess import kotlin.io.* import java.io.File import java.util.zip.Inflater import java.util.zip.DataFormatException import java.io.ByteArrayOutputStream import java.util.zip.Deflater import com.ystore.lib.BytesReader class CBL(val bytes:ByteArray){ val manuals = arrayListOf<Manual>() val info = CBLInfo() class object { fun load(fileName:String):CBL{ return CBL(File(fileName).readBytes()) } } fun init(){ val zipByte = ByteArray(bytes.size-20) System.arraycopy(bytes,20,zipByte,0,zipByte.size) val textByte = decompress(zipByte) val f = File("/tmp/unzip.cbl") f.writeBytes(textByte) val reader = BytesReader(textByte) info.load(reader) for (i in 0..info.getManualCount()-1) { val manual = CBLManual() manual.load(reader) manuals.add(manual) } } fun debug(){ manuals.forEach { m -> println("======================================================") println(m.getInfo()) println("=======================") println(m.getTree()) } } private fun decompress(zipByte : ByteArray) : ByteArray { var aos : ByteArrayOutputStream? = ByteArrayOutputStream() var inflater : Inflater = Inflater() inflater.setInput(zipByte) var buff : ByteArray = ByteArray(1024 * 1000) var byteNum: Int while (!inflater.finished()){ try{ byteNum = inflater.inflate(buff) aos?.write(buff, 0, byteNum) } catch (e : DataFormatException) { e.printStackTrace() } } return aos?.toByteArray()!! } private fun compress(bytes : ByteArray) : ByteArray { var aos : ByteArrayOutputStream = ByteArrayOutputStream() var inflater : Deflater = Deflater() inflater.setInput(bytes) inflater.finish() var buff : ByteArray = ByteArray(1024) var byteNum : Int while (!inflater.finished()) { byteNum = inflater.deflate(buff) aos.write(buff, 0, byteNum) } return aos.toByteArray() } } fun main(args:Array<String>){ val cbl = CBL.load("/tmp/m3.cbl") cbl.init() cbl.debug() }
ystore-lib/src/main/java/chess.kt
243096790
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.codeInsight.typing import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.util.QualifiedName import com.jetbrains.python.PythonHelpersLocator import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.TYPING import com.jetbrains.python.packaging.PyPIPackageUtil import com.jetbrains.python.packaging.PyPackageManagers import com.jetbrains.python.packaging.PyPackageUtil import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.sdk.PythonSdkType import java.io.File /** * Utilities for managing the local copy of the typeshed repository. * * The original Git repo is located [here](https://github.com/JetBrains/typeshed). * * @author vlan */ object PyTypeShed { private val ONLY_SUPPORTED_PY2_MINOR = 7 private val SUPPORTED_PY3_MINORS = 2..7 val WHITE_LIST = setOf(TYPING, "six", "__builtin__", "builtins", "exceptions", "types", "datetime", "functools", "shutil", "re", "time", "argparse", "uuid", "threading", "signal", "collections") private val BLACK_LIST = setOf<String>() /** * Returns true if we allow to search typeshed for a stub for [name]. */ fun maySearchForStubInRoot(name: QualifiedName, root: VirtualFile, sdk : Sdk): Boolean { val topLevelPackage = name.firstComponent ?: return false if (topLevelPackage in BLACK_LIST) { return false } if (topLevelPackage !in WHITE_LIST) { return false } if (isInStandardLibrary(root)) { return true } if (isInThirdPartyLibraries(root)) { if (ApplicationManager.getApplication().isUnitTestMode) { return true } val pyPIPackages = PyPIPackageUtil.PACKAGES_TOPLEVEL[topLevelPackage] ?: emptyList() val packages = PyPackageManagers.getInstance().forSdk(sdk).packages ?: return true return PyPackageUtil.findPackage(packages, topLevelPackage) != null || pyPIPackages.any { PyPackageUtil.findPackage(packages, it) != null } } return false } /** * Returns the list of roots in typeshed for the Python language level of [sdk]. */ fun findRootsForSdk(sdk: Sdk): List<VirtualFile> { val level = PythonSdkType.getLanguageLevelForSdk(sdk) val dir = directory ?: return emptyList() return findRootsForLanguageLevel(level) .asSequence() .map { dir.findFileByRelativePath(it) } .filterNotNull() .toList() } /** * Returns the list of roots in typeshed for the specified Python language [level]. */ fun findRootsForLanguageLevel(level: LanguageLevel): List<String> { val minors = when (level.major) { 2 -> listOf(ONLY_SUPPORTED_PY2_MINOR) 3 -> SUPPORTED_PY3_MINORS.reversed().filter { it <= level.minor } else -> return emptyList() } return minors.map { "stdlib/${level.major}.$it" } + listOf("stdlib/${level.major}", "stdlib/2and3", "third_party/${level.major}", "third_party/2and3") } /** * Checks if the [file] is located inside the typeshed directory. */ fun isInside(file: VirtualFile): Boolean { val dir = directory return dir != null && VfsUtilCore.isAncestor(dir, file, true) } /** * The actual typeshed directory. */ val directory: VirtualFile? by lazy { val path = directoryPath ?: return@lazy null StandardFileSystems.local().findFileByPath(path) } val directoryPath: String? get() { val paths = listOf("${PathManager.getConfigPath()}/typeshed", "${PathManager.getConfigPath()}/../typeshed", PythonHelpersLocator.getHelperPath("typeshed")) return paths.asSequence() .filter { File(it).exists() } .firstOrNull() } /** * A shallow check for a [file] being located inside the typeshed third-party stubs. */ fun isInThirdPartyLibraries(file: VirtualFile) = "third_party" in file.path fun isInStandardLibrary(file: VirtualFile) = "stdlib" in file.path private val LanguageLevel.major: Int get() = this.version / 10 private val LanguageLevel.minor: Int get() = this.version % 10 }
python/src/com/jetbrains/python/codeInsight/typing/PyTypeShed.kt
1228921732
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve enum class PropertyKind(private val prefix: String) { GETTER("get"), BOOLEAN_GETTER("is"), SETTER("set"); /** * @return accessor name by [propertyName] assuming it is valid */ fun getAccessorName(propertyName: String): String { val suffix = if (propertyName.length > 1 && propertyName[1].isUpperCase()) { propertyName } else { propertyName.capitalize() } return prefix + suffix } }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/PropertyKind.kt
1205776484
/* * MIT License * * Copyright (c) 2020 emufog contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package emufog.reader.caida import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.assertThrows import java.nio.file.Paths @TestInstance(TestInstance.Lifecycle.PER_CLASS) internal class CaidaFormatReaderTest { private val resourcePath = Paths.get("src", "test", "resources", "caida") private val defaultNodesGeo = resourcePath.resolve("topo.nodes.geo") private val defaultNodesAs = resourcePath.resolve("topo.nodes.as") private val defaultLinks = resourcePath.resolve("topo.links") private val defaultBaseAddress = "1.2.3.4" @Test fun `empty list of files should fail`() { assertThrows<IllegalArgumentException> { CaidaFormatReader.readGraph(emptyList(), defaultBaseAddress) } } @Test fun `no nodes geo file should fail`() { assertThrows<IllegalArgumentException> { CaidaFormatReader.readGraph(listOf(defaultNodesAs, defaultLinks), defaultBaseAddress) } } @Test fun `no nodes as file should fail`() { assertThrows<IllegalArgumentException> { CaidaFormatReader.readGraph(listOf(defaultNodesGeo, defaultLinks), defaultBaseAddress) } } @Test fun `no links file should fail`() { assertThrows<IllegalArgumentException> { CaidaFormatReader.readGraph(listOf(defaultNodesAs, defaultNodesGeo), defaultBaseAddress) } } @Test fun `should skip lines if number of columns in link file is too small`() { expectEmptyLinkList("small_column.links") } @Test fun `should skip lines if the id of a link is no int`() { expectEmptyLinkList("id_no_int.links") } @Test fun `should skip lines if the id of a link's source is no int`() { expectEmptyLinkList("source_no_int.links") } @Test fun `should skip lines if the id of a link's destination is no int`() { expectEmptyLinkList("destination_no_int.links") } @Test fun `should skip lines if the source node is null`() { expectEmptyLinkList("missing_source.links") } @Test fun `should skip lines if the destination node is null`() { expectEmptyLinkList("missing_destination.links") } private fun expectEmptyLinkList(file: String) { val graph = CaidaFormatReader.readGraph( listOf(defaultNodesGeo, resourcePath.resolve(file), defaultNodesAs), defaultBaseAddress ) assertEquals(0, graph.edges.size) } @Test fun `should skip lines if the number of columns in as file is too small`() { expectEmptyNodeList("small_column.nodes.as") } @Test fun `should skip lines if the id of a node is no int`() { expectEmptyNodeList("id_no_int.nodes.as") } @Test fun `should skip lines if the node's system is no int`() { expectEmptyNodeList("system_no_int.nodes.as") } private fun expectEmptyNodeList(file: String) { val graph = CaidaFormatReader.readGraph( listOf(defaultNodesGeo, defaultLinks, resourcePath.resolve(file)), defaultBaseAddress ) assertEquals(0, graph.edgeNodes.size) } @Test fun `should skip lines if the number of columns in geo file is too small`() { verifySkipOnCoordinates("small_column.nodes.geo") } @Test fun `should skip lines if the id of a node in geo file is no int`() { verifySkipOnCoordinates("id_no_int.nodes.geo") } @Test fun `should skip lines if the node's latitude is no float`() { verifySkipOnCoordinates("lat_no_float.nodes.geo") } @Test fun `should skip lines if the node's longitude is no float`() { verifySkipOnCoordinates("lon_no_float.nodes.geo") } private fun verifySkipOnCoordinates(file: String) { CaidaFormatReader.readGraph( listOf(resourcePath.resolve(file), defaultLinks, defaultNodesAs), defaultBaseAddress ) } @Test fun `read in a sample topology #1`() { val graph = CaidaFormatReader.readGraph( listOf(defaultNodesGeo, defaultLinks, defaultNodesAs), defaultBaseAddress ) assertEquals(10, graph.edgeNodes.size) for (i in 1 until 11) { assertNotNull(graph.getEdgeNode(i)) } assertEquals(0, graph.backboneNodes.size) assertEquals(0, graph.hostDevices.size) assertEquals(0, graph.hostDevices.size) assertEquals(8, graph.systems.size) assertNotNull(graph.getAutonomousSystem(5645)) assertNotNull(graph.getAutonomousSystem(9381)) assertNotNull(graph.getAutonomousSystem(1680)) assertNotNull(graph.getAutonomousSystem(5384)) assertNotNull(graph.getAutonomousSystem(6057)) assertNotNull(graph.getAutonomousSystem(17547)) assertNotNull(graph.getAutonomousSystem(6057)) assertNotNull(graph.getAutonomousSystem(36149)) assertNotNull(graph.getAutonomousSystem(1213)) assertEquals(14, graph.edges.size) val link9707 = graph.edges.firstOrNull { it.id == 9707 } assertNotNull(link9707) assertEquals(9, link9707!!.source.id) assertEquals(2, link9707.destination.id) } }
src/test/kotlin/emufog/reader/caida/CaidaFormatReaderTest.kt
3736133096
package com.github.shynixn.blockball.api.business.enumeration /** * Supported versions. */ enum class Version( /** * Id of the bukkit versions. */ val bukkitId: String, /** * General id. */ val id: String, /** * Numeric Id for calculations. */ val numericId: Double ) { /** * Unknown version. */ VERSION_UNKNOWN("", "", 0.0), /** * Version 1.8.0 - 1.8.2. */ VERSION_1_8_R1("v1_8_R1", "1.8.2", 1.081), /** * Version 1.8.3 - 1.8.4. */ VERSION_1_8_R2("v1_8_R2", "1.8.3", 1.082), /** * Version 1.8.5 - 1.8.9. */ VERSION_1_8_R3("v1_8_R3", "1.8.9", 1.083), /** * Version 1.9.0 - 1.9.1. */ VERSION_1_9_R1("v1_9_R1", "1.9.1", 1.091), /** * Version 1.9.2 - 1.9.4 */ VERSION_1_9_R2("v1_9_R2", "1.9.4", 1.092), /** * Version 1.10.0 - 1.10.2. */ VERSION_1_10_R1("v1_10_R1", "1.10.2", 1.10), /** * Version 1.11.0 - 1.11.2. */ VERSION_1_11_R1("v1_11_R1", "1.11.2", 1.11), /** * Version 1.12.0 - 1.12.2. */ VERSION_1_12_R1("v1_12_R1", "1.12.2", 1.12), /** * Version 1.13.0 - 1.13.0. */ VERSION_1_13_R1("v1_13_R1", "1.13.0", 1.13), /** * Version 1.13.1 - 1.13.2. */ VERSION_1_13_R2("v1_13_R2", "1.13.2", 1.131), /** * Version 1.14.0 - 1.14.4. */ VERSION_1_14_R1("v1_14_R1", "1.14.4", 1.144), /** * Version 1.15.0 - 1.15.2. */ VERSION_1_15_R1("v1_15_R1", "1.15.2", 1.150), /** * Version 1.16.0 - 1.16.1. */ VERSION_1_16_R1("v1_16_R1", "1.16.1", 1.160), /** * Version 1.16.2 - 1.16.3. */ VERSION_1_16_R2("v1_16_R2", "1.16.2", 1.161), /** * Version 1.16.4 - 1.16.5. */ VERSION_1_16_R3("v1_16_R3", "1.16.5", 1.162), /** * Version 1.17.0 - 1.17.1. */ VERSION_1_17_R1("v1_17_R1", "1.17.0", 1.170), /** * Version 1.18.0 - 1.18.1. */ VERSION_1_18_R1("v1_18_R1", "1.18.0", 1.180), /** * Version 1.18.2 - 1.18.2. */ VERSION_1_18_R2("v1_18_R2", "1.18.2", 1.182), /** * Version 1.19.0 - 1.19.0. */ VERSION_1_19_R1("v1_19_R1", "1.19.0", 1.190); /** * Gets if this version is same or greater than the given version by parameter. */ fun isVersionSameOrGreaterThan(version: Version): Boolean { val result = this.numericId.compareTo(version.numericId) return result == 0 || result == 1 } /** * Gets if the version is the same or lower than the given version by parameter. */ fun isVersionSameOrLowerThan(version: Version): Boolean { val result = this.numericId.compareTo(version.numericId) return result == 0 || result == -1 } /** * Gets if this version is compatible to the versions given as parameter. */ fun isCompatible(vararg versions: Version): Boolean { for (version in versions) { if (this.bukkitId == version.bukkitId) { return true } } return false } }
blockball-api/src/main/java/com/github/shynixn/blockball/api/business/enumeration/Version.kt
3880759183
/* * Copyright (c) 2022 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.settings.view.screen import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.padding import androidx.compose.material.ScrollableTabRow import androidx.compose.material.Tab import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.viewmodel.compose.viewModel import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.yobidashi.R @Composable fun SettingTopUi() { val activityContext = LocalContext.current val preferenceApplier = PreferenceApplier(activityContext) val contentViewModel = (activityContext as? ViewModelStoreOwner)?.let { viewModel(ContentViewModel::class.java, activityContext) } val selectedIndex = remember { mutableStateOf(0) } SwitchContentWithTabIndex(selectedIndex) contentViewModel?.replaceAppBarContent { val pages = arrayOf( R.string.subhead_displaying, R.string.title_settings_color, R.string.search, R.string.subhead_browser, R.string.subhead_editor, R.string.title_color_filter, R.string.subhead_others ) ScrollableTabRow( selectedTabIndex = selectedIndex.value, edgePadding = 8.dp, backgroundColor = Color.Transparent, modifier = Modifier.fillMaxHeight() ) { pages.forEachIndexed { index, page -> Tab( selected = selectedIndex.value == index, onClick = { selectedIndex.value = index }, modifier = Modifier.padding(start = 4.dp, end = 4.dp) ) { Text( text = stringResource(id = page), color = Color(preferenceApplier.fontColor), fontSize = 16.sp ) } } } } DisposableEffect(key1 = "refresh") { onDispose { contentViewModel?.refresh() } } contentViewModel?.clearOptionMenus() } @Composable private fun SwitchContentWithTabIndex(selectedIndex: MutableState<Int>) { when (selectedIndex.value) { 0 -> DisplaySettingUi() 1 -> ColorSettingUi() 2 -> SearchSettingUi() 3 -> BrowserSettingUi() 4 -> EditorSettingUi() 5 -> ColorFilterSettingUi() 6 -> OtherSettingUi() else -> DisplaySettingUi() } }
app/src/main/java/jp/toastkid/yobidashi/settings/view/screen/SettingTopUi.kt
3914786736
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.util import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module abstract class AnalyticsModule { @Singleton @Binds internal abstract fun provideAnalytics(bind: TiviAnalytics): Analytics }
core/analytics/src/main/java/app/tivi/util/AnalyticsModule.kt
2206522280
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sdibt.korm.core.callbacks class Callback { var processors: MutableList<CallBackProcessors> = mutableListOf() var inserts: MutableList<(scope: Scope) -> Scope> = mutableListOf() var batchInserts: MutableList<(scope: Scope) -> Scope> = mutableListOf() var updates: MutableList<(scope: Scope) -> Scope> = mutableListOf() var deletes: MutableList<(scope: Scope) -> Scope> = mutableListOf() var selects: MutableList<(scope: Scope) -> Scope> = mutableListOf() var executes: MutableList<(scope: Scope) -> Scope> = mutableListOf() fun reset() { processors.clear() inserts.clear() batchInserts.clear() updates.clear() deletes.clear() selects.clear() executes.clear() } fun delete(): CallBackProcessors { return CallBackProcessors("delete", this) } fun update(): CallBackProcessors { return CallBackProcessors("update", this) } fun insert(): CallBackProcessors { return CallBackProcessors("insert", this) } fun batchInsert(): CallBackProcessors { return CallBackProcessors("batchInsert", this) } fun select(): CallBackProcessors { return CallBackProcessors("select", this) } fun execute(): CallBackProcessors { return CallBackProcessors("execute", this) } }
src/main/kotlin/com/sdibt/korm/core/callbacks/Callback.kt
3067601093
/* generated file, don't edit. */ package de.tutao.tutanota.ipc import kotlinx.serialization.* import kotlinx.serialization.json.* @Serializable data class NativeContact( val name: String, val mailAddress: String, )
app-android/app/src/main/java/de/tutao/tutanota/generated_ipc/NativeContact.kt
3942142702
package guide.howto.create_a_distributed_tracing_tree import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.http4k.core.HttpHandler import org.http4k.core.Method import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status import org.http4k.core.Status.Companion.OK import org.http4k.core.Uri import org.http4k.core.then import org.http4k.events.EventFilters.AddServiceName import org.http4k.events.EventFilters.AddZipkinTraces import org.http4k.events.Events import org.http4k.events.HttpEvent import org.http4k.events.HttpEvent.Incoming import org.http4k.events.HttpEvent.Outgoing import org.http4k.events.MetadataEvent import org.http4k.events.then import org.http4k.filter.ClientFilters import org.http4k.filter.ClientFilters.ResetRequestTracing import org.http4k.filter.ResponseFilters.ReportHttpTransaction import org.http4k.filter.ServerFilters.RequestTracing import org.http4k.filter.ZipkinTraces import org.http4k.filter.debug import org.http4k.routing.bind import org.http4k.routing.reverseProxy import org.http4k.routing.routes import org.http4k.testing.RecordingEvents // standardised events stack which records the service name and adds tracing fun TraceEvents(actorName: String) = AddZipkinTraces().then(AddServiceName(actorName)) // standardised client filter stack which adds tracing and records traffic events fun ClientStack(events: Events) = ReportHttpTransaction { events(Outgoing(it)) } .then(ClientFilters.RequestTracing()) // standardised server filter stack which adds tracing and records traffic events fun ServerStack(events: Events) = ReportHttpTransaction { events(Incoming(it)) } .then(RequestTracing()) // Our "User" object who will send a request to our system class User(rawEvents: Events, rawHttp: HttpHandler) { private val events = TraceEvents("user").then(rawEvents) // as the user is the initiator of requests, we need to reset the tracing for each call. private val http = ResetRequestTracing().then(ClientStack(events)).then(rawHttp) fun initiateCall() = http(Request(GET, "http://internal1/int1")) } // the first internal app fun Internal1(rawEvents: Events, rawHttp: HttpHandler): HttpHandler { val events = TraceEvents("internal1").then(rawEvents).then(rawEvents) val http = ClientStack(events).then(rawHttp) return ServerStack(events) .then( routes("/int1" bind { _: Request -> http(Request(GET, "http://external1/ext1")) http(Request(GET, "http://internal2/int2")) }) ) } // the second internal app fun Internal2(rawEvents: Events, rawHttp: HttpHandler): HttpHandler { val events = TraceEvents("internal2").then(rawEvents).then(rawEvents) val http = ClientStack(events).then(rawHttp) return ServerStack(events) .then( routes("/int2" bind { _: Request -> http(Request(GET, "http://external2/ext2")) }) ) } // an external fake system fun FakeExternal1(): HttpHandler = { Response(OK) } // another external fake system fun FakeExternal2(): HttpHandler = { Response(OK) } fun main() { val events = RecordingEvents() // compose our application(s) together val internalApp = Internal1( events, reverseProxy( "external1" to FakeExternal1(), "internal2" to Internal2(events, FakeExternal2()) ) ) // make a request to the composed stack User(events, internalApp).initiateCall() // convert the recorded events into a tree of HTTP calls val callTree = events.createCallTree() println(callTree) // check that we created the correct thing assertThat(callTree, equalTo(listOf(expectedCallTree))) } private fun RecordingEvents.createCallTree(): List<HttpCallTree> { val outbound = filterIsInstance<MetadataEvent>().filter { it.event is Outgoing } return outbound .filter { it.traces().parentSpanId == null } .map { it.toCallTree(outbound - it) } } // recursively create the call tree from the event list private fun MetadataEvent.toCallTree(calls: List<MetadataEvent>): HttpCallTree { val httpEvent = event as HttpEvent return HttpCallTree( service(), httpEvent.uri, httpEvent.method, httpEvent.status, calls.filter { httpEvent.uri.host == it.service() && traces().spanId == it.traces().parentSpanId }.map { it.toCallTree(calls - it) }) } private fun MetadataEvent.service() = metadata["service"].toString() private fun MetadataEvent.traces() = (metadata["traces"] as ZipkinTraces) data class HttpCallTree( val origin: String, val uri: Uri, val method: Method, val status: Status, val children: List<HttpCallTree> ) val expectedCallTree = HttpCallTree( "user", Uri.of("http://internal1/int1"), GET, OK, listOf( HttpCallTree( origin = "internal1", uri = Uri.of("http://external1/ext1"), method = GET, status = OK, children = emptyList() ), HttpCallTree( "internal1", Uri.of("http://internal2/int2"), GET, OK, listOf( HttpCallTree( origin = "internal2", uri = Uri.of("http://external2/ext2"), method = GET, status = OK, children = emptyList() ), ) ) ) )
src/docs/guide/howto/create_a_distributed_tracing_tree/example.kt
2104050150
package de.tutao.tutanota.credentials import androidx.biometric.BiometricPrompt import androidx.biometric.BiometricPrompt.PromptInfo import androidx.core.content.ContextCompat import androidx.fragment.app.FragmentActivity import de.tutao.tutanota.CredentialAuthenticationException import java.util.concurrent.Semaphore /** * Class to display an authentication prompt using various authentication methods to unlock keystore keys. */ class AuthenticationPrompt internal constructor() { /** * We use a semaphore to ensure that an authentication prompt can only be displayed once. This prevents multiple * requests from the web layer trying to open multiple authentication prompts which would lead to a * [android.security.keystore.UserNotAuthenticatedException]. */ private val sem: Semaphore = Semaphore(1) /** * Displays an authentication prompt. This refreshes ambient system authentication. * @param activity Activity on which to display the authentication prompt fragment. * @param promptInfo Configuration object for the authentication prompt to be displayed. * @throws CredentialAuthenticationException If authentication fails by either cancelling authentication or exceeded limit of failed attempts. */ @Throws(CredentialAuthenticationException::class) fun authenticate( activity: FragmentActivity, promptInfo: PromptInfo, ) { showPrompt(activity, promptInfo, null) } /** * Displays an authentication prompt. This authenticates exactly one operation using {@param cryptoObject}. * @param activity Activity on which to display the authentication prompt fragment. * @param promptInfo Configuration object for the authentication prompt to be displayed. * @param cryptoObject * @throws CredentialAuthenticationException If authentication fails by either cancelling authentication or exceeded limit of failed attempts. */ @Throws(CredentialAuthenticationException::class) fun authenticateCryptoObject( activity: FragmentActivity, promptInfo: PromptInfo, cryptoObject: BiometricPrompt.CryptoObject?, ) { showPrompt(activity, promptInfo, cryptoObject) } @Throws(CredentialAuthenticationException::class) private fun showPrompt( activity: FragmentActivity, promptInfo: PromptInfo, cryptoObject: BiometricPrompt.CryptoObject?, ) { sem.acquireUninterruptibly() var error: String? = null activity.runOnUiThread { val biometricPrompt = BiometricPrompt( activity, ContextCompat.getMainExecutor(activity), object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { error = errString.toString() sem.release() } override fun onAuthenticationSucceeded( result: BiometricPrompt.AuthenticationResult, ) { sem.release() } override fun onAuthenticationFailed() {} }) if (cryptoObject != null) { biometricPrompt.authenticate(promptInfo, cryptoObject) } else { biometricPrompt.authenticate(promptInfo) } } try { sem.acquire() sem.release() } catch (ignored: InterruptedException) { } error?.let { throw CredentialAuthenticationException(it) } } }
app-android/app/src/main/java/de/tutao/tutanota/credentials/AuthenticationPrompt.kt
1399128224
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.apiUsage import com.intellij.codeInsight.daemon.impl.analysis.JavaHighlightUtil import com.intellij.psi.* import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.infos.MethodCandidateInfo /** * Non-recursive PSI visitor that detects usages of APIs and reports them via [ApiUsageDetector] interface. * This visitor is mainly designed for Java, but may basically work with any language, including Kotlin. * Inheritors should provide at least implementation of [processReference]. */ abstract class ApiUsageVisitorBase : PsiElementVisitor(), ApiUsageDetector { final override fun visitElement(element: PsiElement) { super.visitElement(element) if (element is PsiLanguageInjectionHost || element is LeafPsiElement) { //Better performance. return } when (element) { is PsiClass -> visitClass(element) is PsiMethod -> visitMethod(element) is PsiNewExpression -> visitNewExpression(element) else -> processReferences(element) } } private fun processReferences(element: PsiElement) { if (shouldProcessReferences(element)) { for (reference in element.references) { processReference(reference) } } } private fun visitClass(aClass: PsiClass) { if (aClass is PsiTypeParameter || aClass is PsiAnonymousClass) return if (aClass.constructors.isEmpty()) { val superClass = aClass.superClass ?: return val superConstructors = superClass.constructors if (superConstructors.isEmpty() || superConstructors.any { it.parameterList.isEmpty }) { processEmptyConstructorOfSuperClassImplicitInvocationAtSubclassDeclaration(aClass, superClass) } } } private fun visitMethod(method: PsiMethod) { if (method.isConstructor) { checkImplicitCallToSuper(method) } else { checkMethodOverriding(method) } } private fun visitNewExpression(expression: PsiNewExpression) { var classType = expression.type as? PsiClassType ?: return val argumentList = expression.argumentList ?: return val classReference = expression.classOrAnonymousClassReference ?: return var typeResult = classType.resolveGenerics() var aClass = typeResult.element ?: return if (aClass is PsiAnonymousClass) { classType = aClass.baseClassType typeResult = classType.resolveGenerics() aClass = typeResult.element ?: return } if (aClass.constructors.isEmpty()) { processDefaultConstructorInvocation(classReference) } else { val results = JavaPsiFacade .getInstance(expression.project) .resolveHelper .multiResolveConstructor(classType, argumentList, argumentList) val result = results.singleOrNull() as? MethodCandidateInfo ?: return val constructor = result.element processConstructorInvocation(classReference, constructor) } } private fun checkImplicitCallToSuper(constructor: PsiMethod) { val superClass = constructor.containingClass?.superClass ?: return val statements = constructor.body?.statements ?: return if (statements.isEmpty() || !JavaHighlightUtil.isSuperOrThisCall(statements.first(), true, true)) { processEmptyConstructorOfSuperClassImplicitInvocationAtSubclassConstructor(superClass, constructor) } } private fun checkMethodOverriding(method: PsiMethod) { val superSignatures = method.findSuperMethodSignaturesIncludingStatic(true) for (superSignature in superSignatures) { val superMethod = superSignature.method processMethodOverriding(method, superMethod) } } }
java/java-analysis-impl/src/com/intellij/codeInspection/apiUsage/ApiUsageVisitorBase.kt
514724675
package components.progressBar import java.awt.event.ActionEvent import javax.swing.JComponent import javax.swing.JMenu import javax.swing.JMenuBar import javax.swing.JMenuItem /** * Created by vicboma on 05/12/16. */ class MenuBarImpl internal constructor() : JMenuBar(), MenuBar { companion object { fun create() : MenuBar { return MenuBarImpl() } } init { } override fun createMenu(map : Map<String,Map<String, (ActionEvent)-> Unit>>) : JMenu? { fun createMenu(nameMenu: String, map: Map<String, (ActionEvent) -> Unit>) : JMenu { val menu = JMenu(nameMenu) for (entry in map.entries) { when { entry.key.subSequence(0, 3) == "---" -> menu.addSeparator() else -> { val menuItem = JMenuItem(entry.key) menuItem.addActionListener(entry.value) menu.add(menuItem) } } } return menu } var res : JMenu? = null for(entry in map.entries){ val menuBarMenu = entry.key val menuBarItems = entry.value res = createMenu(menuBarMenu, menuBarItems) } return res } override fun addMenu(name : JComponent?) : MenuBar { this.add(name) return this } override fun addMenu(list : MutableList<JComponent?>) : MenuBar { for( it in list) this.addMenu(it) return this } override fun createSubMenu(parent : JMenu?, child : JComponent?) : MenuBar { parent?.add(child) return this } override fun createSubMenu(parent : JMenu?, child : MutableList<JComponent?>) : MenuBar { for( it in child) parent?.add(it) return this } override fun addSeparator(menu : JMenu?) : MenuBar { menu?.addSeparator() return this } override fun component(): JMenuBar = this }
09-start-async-radiobutton-application/src/main/kotlin/components/menuBar/MenuBarImpl.kt
2475829582
/** * Created by guofeng on 2017/6/20. * https://leetcode.com/problems/hamming-distance/#/description */ class HammingDistance { fun solution(x: Int, y: Int): Int? { val max = Math.pow(2.0, 31.0).toInt() if (x !in 0..max - 1 || y !in 0..max - 1) return null val xi = getIndex(x) val yi = getIndex(y) val xyi = (xi + yi) / 2 return Math.pow(2.0, xyi.toDouble()).toInt() } fun getIndex(x: Int): Int { val xb = Integer.toBinaryString(x) val xi: Int = xb.indexOf("1") + 1 return xi } }
src/main/kotlin/HammingDistance.kt
3176540292
package org.intellij.markdown.parser.markerblocks.impl import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.lexer.Compat.assert import org.intellij.markdown.parser.LookaheadText import org.intellij.markdown.parser.ProductionHolder import org.intellij.markdown.parser.constraints.MarkdownConstraints import org.intellij.markdown.parser.constraints.applyToNextLineAndAddModifiers import org.intellij.markdown.parser.constraints.getCharsEaten import org.intellij.markdown.parser.markerblocks.MarkdownParserUtil import org.intellij.markdown.parser.markerblocks.MarkerBlock import org.intellij.markdown.parser.markerblocks.MarkerBlockImpl import org.intellij.markdown.parser.sequentialparsers.SequentialParser class CodeBlockMarkerBlock(myConstraints: MarkdownConstraints, private val productionHolder: ProductionHolder, startPosition: LookaheadText.Position) : MarkerBlockImpl(myConstraints, productionHolder.mark()) { init { productionHolder.addProduction(listOf(SequentialParser.Node( startPosition.offset..startPosition.nextLineOrEofOffset, MarkdownTokenTypes.CODE_LINE))) } override fun allowsSubBlocks(): Boolean = false override fun isInterestingOffset(pos: LookaheadText.Position): Boolean = true private var realInterestingOffset = -1 override fun calcNextInterestingOffset(pos: LookaheadText.Position): Int { return pos.nextLineOrEofOffset } override fun getDefaultAction(): MarkerBlock.ClosingAction { return MarkerBlock.ClosingAction.DONE } override fun doProcessToken(pos: LookaheadText.Position, currentConstraints: MarkdownConstraints): MarkerBlock.ProcessingResult { if (pos.offset < realInterestingOffset) { return MarkerBlock.ProcessingResult.CANCEL } // Eat everything if we're on code line if (pos.offsetInCurrentLine != -1) { return MarkerBlock.ProcessingResult.CANCEL } assert(pos.offsetInCurrentLine == -1) val nonemptyPos = MarkdownParserUtil.findNonEmptyLineWithSameConstraints(constraints, pos) ?: return MarkerBlock.ProcessingResult.DEFAULT val nextConstraints = constraints.applyToNextLineAndAddModifiers(nonemptyPos) val shifted = nonemptyPos.nextPosition(1 + nextConstraints.getCharsEaten(nonemptyPos.currentLine)) val nonWhitespace = shifted?.nextPosition(shifted.charsToNonWhitespace() ?: 0) ?: return MarkerBlock.ProcessingResult.DEFAULT if (!MarkdownParserUtil.hasCodeBlockIndent(nonWhitespace, nextConstraints)) { return MarkerBlock.ProcessingResult.DEFAULT } else { // We'll add the current line anyway val nextLineConstraints = constraints.applyToNextLineAndAddModifiers(pos) val nodeRange = pos.offset + 1 + nextLineConstraints.getCharsEaten(pos.currentLine)..pos.nextLineOrEofOffset if (nodeRange.last - nodeRange.first > 0) { productionHolder.addProduction(listOf(SequentialParser.Node( nodeRange, MarkdownTokenTypes.CODE_LINE))) } realInterestingOffset = pos.nextLineOrEofOffset return MarkerBlock.ProcessingResult.CANCEL } } override fun getDefaultNodeType(): IElementType { return MarkdownElementTypes.CODE_BLOCK } }
src/commonMain/kotlin/org/intellij/markdown/parser/markerblocks/impl/CodeBlockMarkerBlock.kt
3945326175
package dam.isi.frsf.utn.edu.ar.delivery.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.TextView import com.koushikdutta.ion.Ion import dam.isi.frsf.utn.edu.ar.delivery.R import dam.isi.frsf.utn.edu.ar.delivery.model.Sauce class SaucesAdapter(context: Context, sauces: List<Sauce>) : ArrayAdapter<Sauce>(context, R.layout.listview_addins_row, sauces) { var inflater: LayoutInflater = LayoutInflater.from(context) override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var row = convertView if (row == null) { row = inflater.inflate(R.layout.listview_addins_row, parent, false) } var holder: SauceHolder? = row!!.tag as SauceHolder? if (holder == null) { holder = SauceHolder(row) row.tag = holder } if (this.getItem(position)!!.label !== context.getString(R.string.no_sauce_label)) { Ion.with(holder.saucePic!!) .fitCenter() .placeholder(R.drawable.placeholder) .error(R.drawable.error) .load(this.getItem(position)!!.completeImgURL) } holder.textViewName!!.text = this.getItem(position)!!.label return row } internal inner class SauceHolder(row: View) { var textViewName: TextView? = null var saucePic: ImageView? = null init { textViewName = row.findViewById(R.id.addin_name) as TextView saucePic = row.findViewById(R.id.imageview_addin) as ImageView } } }
mobile/app/src/main/java/dam/isi/frsf/utn/edu/ar/delivery/adapter/SaucesAdapter.kt
4279943300
package io.gitlab.arturbosch.detekt.rules.complexity import io.gitlab.arturbosch.detekt.api.AnnotationExcluder import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Metric import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.ThresholdedCodeSmell import io.gitlab.arturbosch.detekt.rules.isOverride import io.gitlab.arturbosch.detekt.rules.valueOrDefaultCommaSeparated import org.jetbrains.kotlin.psi.KtAnnotated import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtConstructor import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtParameterList import org.jetbrains.kotlin.psi.KtPrimaryConstructor import org.jetbrains.kotlin.psi.KtSecondaryConstructor import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject /** * Reports functions and constructors which have more parameters than a certain threshold. * * @configuration threshold - number of parameters required to trigger the rule (default: `6`) * (deprecated: "Use `functionThreshold` and `constructorThreshold` instead") * @configuration functionThreshold - number of function parameters required to trigger the rule (default: `6`) * @configuration constructorThreshold - number of constructor parameters required to trigger the rule (default: `7`) * @configuration ignoreDefaultParameters - ignore parameters that have a default value (default: `false`) * @configuration ignoreDataClasses - ignore long constructor parameters list for data classes (default: `true`) * @configuration ignoreAnnotated - ignore long parameters list for constructors or functions in the context of these * annotation class names (default: `[]`) * * @active since v1.0.0 */ class LongParameterList( config: Config = Config.empty ) : Rule(config) { override val issue = Issue("LongParameterList", Severity.Maintainability, "The more parameters a function has the more complex it is. Long parameter lists are often " + "used to control complex algorithms and violate the Single Responsibility Principle. " + "Prefer functions with short parameter lists.", Debt.TWENTY_MINS) private val functionThreshold: Int = valueOrDefault(FUNCTION_THRESHOLD, valueOrDefault(THRESHOLD, DEFAULT_FUNCTION_THRESHOLD)) private val constructorThreshold: Int = valueOrDefault(CONSTRUCTOR_THRESHOLD, valueOrDefault(THRESHOLD, DEFAULT_CONSTRUCTOR_THRESHOLD)) private val ignoreDefaultParameters = valueOrDefault(IGNORE_DEFAULT_PARAMETERS, false) private val ignoreDataClasses = valueOrDefault(IGNORE_DATA_CLASSES, true) private val ignoreAnnotated = valueOrDefaultCommaSeparated(IGNORE_ANNOTATED, emptyList()) .map { it.removePrefix("*").removeSuffix("*") } private lateinit var annotationExcluder: AnnotationExcluder override fun visitKtFile(file: KtFile) { annotationExcluder = AnnotationExcluder(file, ignoreAnnotated) super.visitKtFile(file) } override fun visitNamedFunction(function: KtNamedFunction) { val owner = function.containingClassOrObject if (owner is KtClass && owner.isIgnored()) { return } validateFunction(function, functionThreshold) } override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) { validateConstructor(constructor) } override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) { validateConstructor(constructor) } private fun KtAnnotated.isIgnored(): Boolean { return annotationExcluder.shouldExclude(annotationEntries) } private fun validateConstructor(constructor: KtConstructor<*>) { val owner = constructor.getContainingClassOrObject() if (owner is KtClass && owner.isDataClassOrIgnored()) { return } validateFunction(constructor, constructorThreshold) } private fun KtClass.isDataClassOrIgnored() = isIgnored() || ignoreDataClasses && isData() private fun validateFunction(function: KtFunction, threshold: Int) { if (function.isOverride() || function.isIgnored() || function.containingKtFile.isIgnored()) return val parameterList = function.valueParameterList val parameters = parameterList?.parameterCount() if (parameters != null && parameters >= threshold) { report(ThresholdedCodeSmell(issue, Entity.from(parameterList), Metric("SIZE", parameters, threshold), "The function ${function.nameAsSafeName} has too many parameters. The current threshold" + " is set to $threshold.")) } } private fun KtParameterList.parameterCount(): Int { return if (ignoreDefaultParameters) { parameters.filter { !it.hasDefaultValue() }.size } else { parameters.size } } companion object { const val THRESHOLD = "threshold" const val FUNCTION_THRESHOLD = "functionThreshold" const val CONSTRUCTOR_THRESHOLD = "constructorThreshold" const val IGNORE_DEFAULT_PARAMETERS = "ignoreDefaultParameters" const val IGNORE_DATA_CLASSES = "ignoreDataClasses" const val IGNORE_ANNOTATED = "ignoreAnnotated" const val DEFAULT_FUNCTION_THRESHOLD = 6 const val DEFAULT_CONSTRUCTOR_THRESHOLD = 7 } }
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/complexity/LongParameterList.kt
1116530425
/* * Copyright (c) 2021 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.libanki import androidx.annotation.CheckResult import org.json.JSONArray import org.json.JSONObject abstract class ConfigManager { @CheckResult abstract fun has(key: String): Boolean /** * Returns true if this object has no mapping for [key]or if it has * a mapping whose value is [JSONObject.NULL]. */ @CheckResult abstract fun isNull(key: String): Boolean @CheckResult abstract fun getString(key: String): String @CheckResult abstract fun getBoolean(key: String): Boolean @CheckResult abstract fun getDouble(key: String): Double @CheckResult abstract fun getInt(key: String): Int @CheckResult abstract fun getLong(key: String): Long @CheckResult abstract fun getJSONArray(key: String): JSONArray @CheckResult abstract fun getJSONObject(key: String): JSONObject abstract fun put(key: String, value: Boolean) abstract fun put(key: String, value: Long) abstract fun put(key: String, value: Int) abstract fun put(key: String, value: Double) abstract fun put(key: String, value: String) abstract fun put(key: String, value: JSONArray) abstract fun put(key: String, value: JSONObject) abstract fun put(key: String, value: Any?) abstract fun remove(key: String) abstract var json: JSONObject }
AnkiDroid/src/main/java/com/ichi2/libanki/ConfigManager.kt
2857396680
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.model.local import com.squareup.moshi.Moshi import com.toshi.crypto.util.TypeConverter import java.io.IOException data class PersonalMessage(val from: String, var data: String) { companion object { @Throws(IOException::class) @JvmStatic fun build(msgParams: String): PersonalMessage { val personalMessageSignJsonAdapter = Moshi.Builder().build().adapter(PersonalMessage::class.java) return personalMessageSignJsonAdapter.fromJson(msgParams) } } fun getDataFromMessageAsString(): String { val bytes = TypeConverter.StringHexToByteArray(data) return String(bytes) } fun getDataFromMessageAsBytes(): ByteArray = TypeConverter.StringHexToByteArray(data) }
app/src/main/java/com/toshi/model/local/PersonalMessage.kt
2134857476
package me.wayne.dp import kotlin.math.max val ARR = arrayListOf(1, 2, 4, 1, 7, 8, 3) fun main() { println("recOpt1 = " + recOpt1(ARR, 6)) println("dpOpt1 = " + dpOpt1(ARR, 6)) println("recOpt2 = " + recOpt2(ARR, 6, 19)) } fun recOpt1(arr: List<Int>, index: Int): Int { return when (index) { 0 -> { arr[0] } 1 -> { max(arr[0], arr[1]) } else -> { val choose = arr[index] + recOpt1(arr, index - 2) val giveUp = recOpt1(arr, index - 1) max(choose, giveUp) } } } fun dpOpt1(arr: List<Int>, index: Int): Int { val resultArr = mutableListOf<Int>() resultArr.add(0, arr[0]) resultArr.add(1, max(arr[0], arr[1])) for (i in 2 until arr.size) { val choose = arr[i] + resultArr[i - 2] val giveUp = resultArr[i - 1] resultArr.add(i, max(choose, giveUp)) } return resultArr[index] } fun recOpt2(arr: List<Int>, index: Int, value: Int): Boolean { return when { value == 0 -> { true } index == 0 -> { arr[index] == value } arr[index] > value -> { return recOpt2(arr, index - 1, value) } else -> { val choose = recOpt2(arr, index - 1, value - arr[index]) val giveUp = recOpt2(arr, index - 1, value) choose || giveUp } } }
src/main/java/me/wayne/dp/DynamicProgramming.kt
3588513701
package com.boardgamegeek.ui import android.content.Context import android.content.Intent import android.os.Bundle import android.view.MenuItem import androidx.fragment.app.Fragment import com.boardgamegeek.R import com.boardgamegeek.entities.ForumEntity import com.boardgamegeek.extensions.clearTop import com.boardgamegeek.extensions.intentFor import com.boardgamegeek.extensions.linkToBgg import com.boardgamegeek.provider.BggContract import com.boardgamegeek.ui.ForumsActivity.Companion.startUp import com.boardgamegeek.ui.GameActivity.Companion.startUp import com.boardgamegeek.ui.PersonActivity.Companion.startUpForArtist import com.boardgamegeek.ui.PersonActivity.Companion.startUpForDesigner import com.boardgamegeek.ui.PersonActivity.Companion.startUpForPublisher import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.logEvent class ForumActivity : SimpleSinglePaneActivity() { private var forumId = BggContract.INVALID_ID private var forumTitle = "" private var objectId = BggContract.INVALID_ID private var objectName = "" private var objectType = ForumEntity.ForumType.REGION override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (forumTitle.isNotEmpty()) { if (objectName.isNotEmpty()) { supportActionBar?.title = objectName } supportActionBar?.subtitle = forumTitle } if (savedInstanceState == null) { firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM) { param(FirebaseAnalytics.Param.CONTENT_TYPE, "Forum") param(FirebaseAnalytics.Param.ITEM_ID, forumId.toString()) param(FirebaseAnalytics.Param.ITEM_NAME, forumTitle) } } } override fun readIntent(intent: Intent) { forumId = intent.getIntExtra(KEY_FORUM_ID, BggContract.INVALID_ID) forumTitle = intent.getStringExtra(KEY_FORUM_TITLE).orEmpty() objectId = intent.getIntExtra(KEY_OBJECT_ID, BggContract.INVALID_ID) objectType = intent.getSerializableExtra(KEY_OBJECT_TYPE) as ForumEntity.ForumType objectName = intent.getStringExtra(KEY_OBJECT_NAME).orEmpty() } override fun onCreatePane(intent: Intent): Fragment { return ForumFragment.newInstance(forumId, forumTitle, objectId, objectName, objectType) } override val optionsMenuId = R.menu.view override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { when (objectType) { ForumEntity.ForumType.REGION -> startUp(this) ForumEntity.ForumType.GAME -> startUp(this, objectId, objectName) ForumEntity.ForumType.ARTIST -> startUpForArtist(this, objectId, objectName) ForumEntity.ForumType.DESIGNER -> startUpForDesigner(this, objectId, objectName) ForumEntity.ForumType.PUBLISHER -> startUpForPublisher(this, objectId, objectName) } finish() } R.id.menu_view -> linkToBgg("forum/$forumId") else -> super.onOptionsItemSelected(item) } return true } companion object { private const val KEY_FORUM_ID = "FORUM_ID" private const val KEY_FORUM_TITLE = "FORUM_TITLE" private const val KEY_OBJECT_ID = "OBJECT_ID" private const val KEY_OBJECT_NAME = "OBJECT_NAME" private const val KEY_OBJECT_TYPE = "OBJECT_TYPE" fun start(context: Context, forumId: Int, forumTitle: String, objectId: Int, objectName: String, objectType: ForumEntity.ForumType) { context.startActivity(createIntent(context, forumId, forumTitle, objectId, objectName, objectType)) } fun startUp(context: Context, forumId: Int, forumTitle: String, objectId: Int, objectName: String, objectType: ForumEntity.ForumType) { context.startActivity(createIntent(context, forumId, forumTitle, objectId, objectName, objectType).clearTop()) } private fun createIntent( context: Context, forumId: Int, forumTitle: String, objectId: Int, objectName: String, objectType: ForumEntity.ForumType ): Intent { return context.intentFor<ForumActivity>( KEY_FORUM_ID to forumId, KEY_FORUM_TITLE to forumTitle, KEY_OBJECT_ID to objectId, KEY_OBJECT_NAME to objectName, KEY_OBJECT_TYPE to objectType, ) } } }
app/src/main/java/com/boardgamegeek/ui/ForumActivity.kt
926522647
package com.boardgamegeek.ui.adapter import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.boardgamegeek.R import com.boardgamegeek.databinding.RowCollectionBuddyBinding import com.boardgamegeek.entities.CollectionItemEntity import com.boardgamegeek.extensions.firstChar import com.boardgamegeek.extensions.inflate import com.boardgamegeek.ui.GameActivity.Companion.start import com.boardgamegeek.ui.adapter.BuddyCollectionAdapter.BuddyGameViewHolder import com.boardgamegeek.ui.widget.RecyclerSectionItemDecoration.SectionCallback import kotlin.properties.Delegates class BuddyCollectionAdapter : RecyclerView.Adapter<BuddyGameViewHolder>(), AutoUpdatableAdapter, SectionCallback { var items: List<CollectionItemEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue -> autoNotify(oldValue, newValue) { old, new -> old.collectionId == new.collectionId } } override fun getItemCount() = items.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BuddyGameViewHolder { return BuddyGameViewHolder(parent.inflate(R.layout.row_collection_buddy)) } override fun onBindViewHolder(holder: BuddyGameViewHolder, position: Int) { holder.bind(items.getOrNull(position)) } inner class BuddyGameViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val binding = RowCollectionBuddyBinding.bind(itemView) fun bind(item: CollectionItemEntity?) { binding.nameView.text = item?.gameName.orEmpty() binding.yearView.text = item?.gameId?.toString().orEmpty() itemView.setOnClickListener { if (item != null) start(itemView.context, item.gameId, item.gameName) } } } override fun isSection(position: Int): Boolean { if (position == RecyclerView.NO_POSITION) return false if (items.isEmpty()) return false if (position == 0) return true val thisLetter = items.getOrNull(position)?.sortName.firstChar() val lastLetter = items.getOrNull(position - 1)?.sortName.firstChar() return thisLetter != lastLetter } override fun getSectionHeader(position: Int): CharSequence { return when { position == RecyclerView.NO_POSITION -> return "-" items.isEmpty() -> return "-" position < 0 || position >= items.size -> "-" else -> items[position].sortName.firstChar() } } }
app/src/main/java/com/boardgamegeek/ui/adapter/BuddyCollectionAdapter.kt
3768648575
package com.sbhachu.bootstrap.extensions import android.app.Application import com.sbhachu.bootstrap.extensions.listener.ApplicationLifecycleCallbacks fun Application.addLifecycleCallbacks(init: ApplicationLifecycleCallbacks.() -> Unit) { registerActivityLifecycleCallbacks(ApplicationLifecycleCallbacks().apply(init)) }
app/src/main/kotlin/com/sbhachu/bootstrap/extensions/Application.kt
272215869
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ @file:JvmName("TextFormatFactory") @file:Suppress("UNUSED_PARAMETER", "NOTHING_TO_INLINE", "FunctionName") package org.lanternpowered.api.text.format typealias TextColor = net.kyori.adventure.text.format.TextColor typealias NamedTextColor = net.kyori.adventure.text.format.NamedTextColor typealias TextDecoration = net.kyori.adventure.text.format.TextDecoration typealias TextDecorationState = net.kyori.adventure.text.format.TextDecoration.State typealias TextStyle = net.kyori.adventure.text.format.Style fun textStyleOf(color: TextColor): TextStyle = TextStyle.style(color as TextColor?) fun textStyleOf(color: TextColor, vararg decorations: TextDecoration): TextStyle = TextStyle.style(color as TextColor?, *decorations) fun textStyleOf(vararg decorations: TextDecoration): TextStyle = TextStyle.style(*decorations) inline operator fun TextStyle.plus(decoration: TextDecoration): TextStyle = decoration(decoration, true) inline operator fun TextStyle.plus(color: TextColor): TextStyle = color(color) inline operator fun TextStyle.plus(style: TextStyle): TextStyle = merge(style) inline operator fun TextStyle.contains(decoration: TextDecoration): Boolean = hasDecoration(decoration) inline operator fun TextDecoration.plus(decoration: TextDecoration): TextStyle = TextStyle.style(this, decoration) inline operator fun TextDecoration.plus(color: TextColor): TextStyle = TextStyle.style(this, color) inline operator fun TextColor.plus(decoration: TextDecoration): TextStyle = TextStyle.style(decoration, this)
src/main/kotlin/org/lanternpowered/api/text/format/TextFormat.kt
2811566316
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.state import org.spongepowered.api.state.State import org.spongepowered.api.state.StateContainer /** * Represents the builder of a [State]. */ interface StateBuilder<S : State<S>> { /** * Is called when all the states of the * [StateContainer] are initialized. */ fun whenCompleted(fn: () -> Unit) }
src/main/kotlin/org/lanternpowered/server/state/StateBuilder.kt
3319810534
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.protocol import org.lanternpowered.server.inventory.PlayerInventoryContainerSession import org.lanternpowered.server.network.vanilla.packet.codec.DisconnectEncoder import org.lanternpowered.server.network.vanilla.packet.codec.EncoderPlaceholder import org.lanternpowered.server.network.vanilla.packet.codec.KeepAliveCodec import org.lanternpowered.server.network.vanilla.packet.codec.play.* import org.lanternpowered.server.network.vanilla.packet.handler.play.ChannelPayloadHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientAdvancementTreeHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientBlockPlacementHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientDiggingHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientEditBookHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientFinishUsingItemHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientFlyingStateHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientLockDifficultyHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientModifySignHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientMovementInputHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientPlayerLookHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientPlayerMovementAndLookHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientPlayerMovementHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientPlayerOnGroundStateHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientPlayerSwingArmHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientPlayerVehicleMovementHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientRecipeBookStateHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientRequestRespawnHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientRequestStatisticsHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientSendChatMessageHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientSetDifficultyHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientSettingsHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientSignBookHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientSneakStateHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientSprintStateHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientStartElytraFlyingHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientSwapHandItemsHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientUseItemHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ContainerSessionForwardingHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ClientTabCompleteHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.RegisterChannelsHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.ResourcePackStatusHandler import org.lanternpowered.server.network.vanilla.packet.handler.play.UnregisterChannelsHandler import org.lanternpowered.server.network.vanilla.packet.processor.play.ParticleEffectProcessor import org.lanternpowered.server.network.vanilla.packet.processor.play.SetGameModeProcessor import org.lanternpowered.server.network.vanilla.packet.processor.play.TabListProcessor import org.lanternpowered.server.network.vanilla.packet.processor.play.TheEndMessageProcessor import org.lanternpowered.server.network.vanilla.packet.processor.play.UpdateWorldSkyProcessor import org.lanternpowered.server.network.vanilla.packet.type.DisconnectPacket import org.lanternpowered.server.network.vanilla.packet.type.KeepAlivePacket import org.lanternpowered.server.network.vanilla.packet.type.play.* import org.lanternpowered.server.network.vanilla.packet.type.play.internal.ChangeGameStatePacket val PlayProtocol = protocol { inbound { bind().decoder(ClientConfirmTeleportDecoder) bind().decoder(ClientRequestBlockDataDecoder) bind().decoder(ClientSetDifficultyDecoder) bind().decoder(ClientSendChatMessageDecoder) bind().decoder(ClientStatusDecoder) bind().decoder(ClientSettingsDecoder) bind().decoder(ClientTabCompleteDecoder) bind().decoder(ConfirmWindowTransactionCodec) bind().decoder(ClientClickWindowButtonDecoder) bind().decoder(ClientClickWindowDecoder) bind().decoder(CloseWindowCodec) bind().decoder(ChannelPayloadCodec) bind().decoder(ClientModifyBookDecoder) bind().decoder(ClientRequestEntityDataDecoder) bind().decoder(ClientUseEntityDecoder) bind().decoder(GenerateJigsawStructureDecoder) bind().decoder(KeepAliveCodec) bind().decoder(ClientLockDifficultyDecoder) bind().decoder(ClientPlayerMovementDecoder) bind().decoder(ClientPlayerMovementAndLookDecoder) bind().decoder(ClientPlayerLookDecoder) bind().decoder(ClientPlayerOnGroundStateDecoder) bind().decoder(ClientPlayerVehicleMovementDecoder) bind().decoder(ClientBoatControlsDecoder) bind().decoder(ClientPickItemDecoder) bind().decoder(ClientClickRecipeDecoder) bind().decoder(ClientFlyingStateDecoder) bind().decoder(ClientDiggingDecoder) bind().decoder(ClientPlayerActionDecoder) bind().decoder(ClientVehicleControlsDecoder) bind().decoder(ClientSetDisplayedRecipeDecoder) bind().decoder(ClientRecipeBookStateDecoder) bind().decoder(ClientItemRenameDecoder) bind().decoder(ResourcePackStatusDecoder) bind().decoder(ChangeAdvancementTreeDecoder) bind().decoder(ClientChangeTradeOfferDecoder) bind().decoder(ClientAcceptBeaconEffectsDecoder) bind().decoder(PlayerHeldItemChangeCodec) bind().decoder(ClientEditCommandBlockBlockDecoder) bind().decoder(ClientEditCommandBlockEntityDecoder) bind().decoder(ClientCreativeWindowActionDecoder) bind().decoder(ClientUpdateJigsawBlockDecoder) bind().decoder(ClientUpdateStructureBlockDecoder) bind().decoder(ClientModifySignDecoder) bind().decoder(ClientPlayerSwingArmDecoder) bind().decoder(ClientSpectateDecoder) bind().decoder(ClientBlockPlacementDecoder) bind().decoder(ClientUseItemDecoder) type(ClientConfirmTeleportPacket::class) // TODO: Handler type(ClientRequestDataPacket.Block::class) // TODO: Handler type(ClientSetDifficultyPacket::class).handler(ClientSetDifficultyHandler) type(ClientSendChatMessagePacket::class).handler(ClientSendChatMessageHandler) type(ClientRequestRespawnPacket::class).handler(ClientRequestRespawnHandler) type(ClientRequestStatisticsPacket::class).handler(ClientRequestStatisticsHandler) type(ClientSettingsPacket::class).handler(ClientSettingsHandler) type(ClientTabCompletePacket::class).handler(ClientTabCompleteHandler) type(ChannelPayloadPacket::class).handler(ChannelPayloadHandler) type(RegisterChannelsPacket::class).handler(RegisterChannelsHandler) type(UnregisterChannelsPacket::class).handler(UnregisterChannelsHandler) type(BrandPacket::class) // TODO: Handler type(ClientModifyBookPacket.Edit::class).handler(ClientEditBookHandler) type(ClientModifyBookPacket.Sign::class).handler(ClientSignBookHandler) type(ClientRequestDataPacket.Entity::class) // TODO: Handler type(ClientUseEntityPacket::class) // TODO: Handler type(GenerateJigsawStructurePacket::class) // TODO: Handler type(KeepAlivePacket::class) type(ClientLockDifficultyPacket::class).handler(ClientLockDifficultyHandler) type(ClientPlayerMovementPacket::class).handler(ClientPlayerMovementHandler) type(ClientPlayerMovementAndLookPacket::class).handler(ClientPlayerMovementAndLookHandler) type(ClientPlayerLookPacket::class).handler(ClientPlayerLookHandler) type(ClientPlayerOnGroundStatePacket::class).handler(ClientPlayerOnGroundStateHandler) type(ClientPlayerVehicleMovementPacket::class).handler(ClientPlayerVehicleMovementHandler) type(ClientFlyingStatePacket::class).handler(ClientFlyingStateHandler) type(ClientDiggingPacket::class).handler(ClientDiggingHandler) type(ClientDropHeldItemPacket::class).handler(ContainerSessionForwardingHandler(PlayerInventoryContainerSession::handleItemDrop)) type(FinishUsingItemPacket::class).handler(ClientFinishUsingItemHandler) type(ClientSwapHandItemsPacket::class).handler(ClientSwapHandItemsHandler) type(ClientLeaveBedPacket::class) // TODO: Handler type(ClientStartElytraFlyingPacket::class).handler(ClientStartElytraFlyingHandler) type(ClientSneakStatePacket::class).handler(ClientSneakStateHandler) type(ClientSprintStatePacket::class).handler(ClientSprintStateHandler) type(ClientVehicleJumpPacket::class) // TODO: Handler type(ClientMovementInputPacket::class).handler(ClientMovementInputHandler) type(ClientRecipeBookStatePacket::class).handler(ClientRecipeBookStateHandler) type(ResourcePackStatusPacket::class).handler(ResourcePackStatusHandler) type(ChangeAdvancementTreePacket.Open::class).handler(ClientAdvancementTreeHandler) type(ChangeAdvancementTreePacket.Close::class).handler(ClientAdvancementTreeHandler) type(ClientEditCommandBlockPacket.Block::class) // TODO: Handler type(ClientEditCommandBlockPacket.Entity::class) // TODO: Handler type(ClientUpdateJigsawBlockPacket::class) // TODO: Handler type(ClientUpdateStructureBlockPacket::class) // TODO: Handler type(ClientModifySignPacket::class).handler(ClientModifySignHandler) type(ClientPlayerSwingArmPacket::class).handler(ClientPlayerSwingArmHandler) type(ClientSpectatePacket::class) // TODO: Handler type(ClientBlockPlacementPacket::class).handler(ClientBlockPlacementHandler) type(ClientUseItemPacket::class).handler(ClientUseItemHandler) type(ClientBoatControlsPacket::class) // TODO: Handler type(ConfirmWindowTransactionPacket::class) // TODO: Handler type(ClientClickWindowButtonPacket::class) .handler(ContainerSessionForwardingHandler(PlayerInventoryContainerSession::handleEnchantItem)) type(ClientClickWindowPacket::class) .handler(ContainerSessionForwardingHandler(PlayerInventoryContainerSession::handleWindowClick)) type(CloseWindowPacket::class) .handler(ContainerSessionForwardingHandler(PlayerInventoryContainerSession::handleWindowClose)) type(ClientPickItemPacket::class) .handler(ContainerSessionForwardingHandler(PlayerInventoryContainerSession::handlePickItem)) type(ClientClickRecipePacket::class) .handler(ContainerSessionForwardingHandler(PlayerInventoryContainerSession::handleRecipeClick)) type(ClientSetDisplayedRecipePacket::class) .handler(ContainerSessionForwardingHandler(PlayerInventoryContainerSession::handleDisplayedRecipe)) type(ClientItemRenamePacket::class) .handler(ContainerSessionForwardingHandler(PlayerInventoryContainerSession::handleItemRename)) type(ClientChangeTradeOfferPacket::class) .handler(ContainerSessionForwardingHandler(PlayerInventoryContainerSession::handleOfferChange)) type(ClientAcceptBeaconEffectsPacket::class) .handler(ContainerSessionForwardingHandler(PlayerInventoryContainerSession::handleAcceptBeaconEffects)) type(PlayerHeldItemChangePacket::class) .handler(ContainerSessionForwardingHandler(PlayerInventoryContainerSession::handleHeldItemChange)) type(ClientCreativeWindowActionPacket::class) .handler(ContainerSessionForwardingHandler(PlayerInventoryContainerSession::handleWindowCreativeClick)) } outbound { // With processors type(TheEndPacket::class).processor(TheEndMessageProcessor) type(ParticleEffectPacket::class).processor(ParticleEffectProcessor) type(SetGameModePacket::class).processor(SetGameModeProcessor) type(UpdateWorldSkyPacket::class).processor(UpdateWorldSkyProcessor) type(TabListPacket::class).processor(TabListProcessor) // With opcodes bind().encoder(SpawnObjectEncoder).accept(SpawnObjectPacket::class) bind().encoder(SpawnExperienceOrbEncoder).accept(SpawnExperienceOrbPacket::class) bind().encoder(SpawnMobEncoder).accept(SpawnMobPacket::class) bind().encoder(SpawnPaintingEncoder).accept(SpawnPaintingPacket::class) bind().encoder(SpawnPlayerEncoder).accept(SpawnPlayerPacket::class) bind().encoder(EntityAnimationEncoder).accept(EntityAnimationPacket::class) bind().encoder(StatisticsEncoder).accept(StatisticsPacket::class) bind().encoder(BlockBreakAnimationEncoder).accept(BlockBreakAnimationPacket::class) bind().encoder(UpdateBlockEntityEncoder).accept(UpdateBlockEntityPacket::class) bind().encoder(BlockActionEncoder).accept(BlockActionPacket::class) bind().encoder(BlockChangeEncoder).accept(BlockChangePacket::class) bind().encoder(BossBarEncoder).acceptAll(BossBarPacket.Add::class, BossBarPacket.Remove::class, BossBarPacket.UpdateFlags::class, BossBarPacket.UpdateName::class, BossBarPacket.UpdatePercent::class, BossBarPacket.UpdateStyle::class ) bind().encoder(SetDifficultyEncoder).accept(SetDifficultyPacket::class) bind().encoder(ChatMessageEncoder).accept(ChatMessagePacket::class) bind().encoder(MultiBlockChangeEncoder).accept(MultiBlockChangePacket::class) bind().encoder(TabCompleteEncoder).accept(TabCompletePacket::class) bind().encoder(SetCommandsEncoder).accept(SetCommandsPacket::class) bind().encoder(ConfirmWindowTransactionCodec).accept(ConfirmWindowTransactionPacket::class) bind().encoder(CloseWindowCodec).accept(CloseWindowPacket::class) bind().encoder(SetWindowItemsEncoder).accept(SetWindowItemsPacket::class) bind().encoder(SetWindowPropertyEncoder).accept(SetWindowPropertyPacket::class) bind().encoder(SetWindowSlotEncoder).accept(SetWindowSlotPacket::class) bind().encoder(SetCooldownEncoder).accept(SetCooldownPacket::class) bind().encoder(ChannelPayloadCodec).acceptAll(ChannelPayloadPacket::class, BrandPacket::class) bind().encoder(NamedSoundEffectEncoder).accept(NamedSoundEffectPacket::class) bind().encoder(DisconnectEncoder).accept(DisconnectPacket::class) bind().encoder(EntityStatusEncoder).acceptAll(EntityStatusPacket::class, SetOpLevelPacket::class, SetReducedDebugPacket::class, FinishUsingItemPacket::class ) bind().encoder(ChunkUnloadEncoder).accept(ChunkPacket.Unload::class) bind().encoder(ChangeGameStateEncoder).accept(ChangeGameStatePacket::class) bind().encoder(OpenHorseWindowEncoder).accept(OpenHorseWindowPacket::class) bind().encoder(KeepAliveCodec).accept(KeepAlivePacket::class) bind().encoder(ChunkInitOrUpdateEncoder).acceptAll(ChunkPacket.Init::class, ChunkPacket.Update::class) bind().encoder(EffectEncoder).acceptAll(EffectPacket::class, SetMusicDiscPacket::class) bind().encoder(SpawnParticleEncoder).accept(SpawnParticlePacket::class) bind().encoder(UpdateLightEncoder).accept(UpdateLightPacket::class) bind().encoder(PlayerJoinEncoder).accept(PlayerJoinPacket::class) bind().encoder(EncoderPlaceholder).accept(MapPacket::class) bind().encoder(SetWindowTradeOffersEncoder).accept(SetWindowTradeOffersPacket::class) bind().encoder(EntityRelativeMoveEncoder).accept(EntityRelativeMovePacket::class) bind().encoder(EntityLookAndRelativeMoveEncoder).accept(EntityLookAndRelativeMovePacket::class) bind().encoder(EntityLookEncoder).accept(EntityLookPacket::class) bind() // "Entity" packet, not used bind().encoder(EncoderPlaceholder).accept(VehicleMovePacket::class) bind().encoder(OpenSignEncoder).accept(OpenSignPacket::class) bind().encoder(OpenWindowEncoder).accept(OpenWindowPacket::class) bind().encoder(OpenBookEncoder).accept(OpenBookPacket::class) bind().encoder(EncoderPlaceholder).accept(CombatEventPacket::class) bind().encoder(TabListEncoder).accept(TabListPacket::class) bind().encoder(PlayerFaceAtEncoder).acceptAll( PlayerFaceAtPacket.Entity::class, PlayerFaceAtPacket.Position::class ) bind().encoder(PlayerPositionAndLookEncoder).accept(PlayerPositionAndLookPacket::class) bind().encoder(UnlockRecipesEncoder).acceptAll( UnlockRecipesPacket.Add::class, UnlockRecipesPacket.Init::class, UnlockRecipesPacket.Remove::class ) bind().encoder(DestroyEntitiesEncoder).accept(DestroyEntitiesPacket::class) bind().encoder(RemovePotionEffectEncoder).accept(RemovePotionEffectPacket::class) bind().encoder(SetResourcePackEncoder).accept(SetResourcePackPacket::class) bind().encoder(PlayerRespawnEncoder).accept(PlayerRespawnPacket::class) bind().encoder(EntityHeadLookEncoder).accept(EntityHeadLookPacket::class) bind().encoder(SetActiveAdvancementTreeEncoder).accept(SetActiveAdvancementTreePacket::class) bind().encoder(WorldBorderEncoder).acceptAll( WorldBorderPacket.Init::class, WorldBorderPacket.UpdateCenter::class, WorldBorderPacket.UpdateDiameter::class, WorldBorderPacket.UpdateLerpedDiameter::class, WorldBorderPacket.UpdateWarningDistance::class, WorldBorderPacket.UpdateWarningTime::class ) bind().encoder(SetCameraEncoder).accept(SetCameraPacket::class) bind().encoder(PlayerHeldItemChangeCodec).accept(PlayerHeldItemChangePacket::class) bind().encoder(UpdateViewPositionEncoder).accept(UpdateViewPositionPacket::class) bind().encoder(UpdateViewDistanceEncoder).accept(UpdateViewDistancePacket::class) bind().encoder(PlayerSpawnPositionEncoder).accept(PlayerSpawnPositionPacket::class) bind().encoder(SetActiveScoreboardObjectiveEncoder).accept(SetActiveScoreboardObjectivePacket::class) bind().encoder(EntityMetadataEncoder).accept(EntityMetadataPacket::class) bind().encoder(EncoderPlaceholder).accept(AttachEntityPacket::class) bind().encoder(EntityVelocityEncoder).accept(EntityVelocityPacket::class) bind().encoder(EntityEquipmentEncoder).accept(EntityEquipmentPacket::class) bind().encoder(SetExperienceEncoder).accept(SetExperiencePacket::class) bind().encoder(PlayerHealthEncoder).accept(PlayerHealthPacket::class) bind().encoder(ScoreboardObjectiveEncoder).acceptAll( ScoreboardObjectivePacket.Create::class, ScoreboardObjectivePacket.Remove::class, ScoreboardObjectivePacket.Update::class ) bind().encoder(SetEntityPassengersCodec).accept(SetEntityPassengersPacket::class) bind().encoder(TeamEncoder).acceptAll( TeamPacket.AddMembers::class, TeamPacket.Create::class, TeamPacket.Update::class, TeamPacket.Remove::class, TeamPacket.RemoveMembers::class ) bind().encoder(ScoreboardScoreEncoder).acceptAll( ScoreboardScorePacket.CreateOrUpdate::class, ScoreboardScorePacket.Remove::class ) bind().encoder(WorldTimeEncoder).accept(WorldTimePacket::class) bind().encoder(TitleEncoder).acceptAll( TitlePacket.SetActionbarTitle::class, TitlePacket.SetSubtitle::class, TitlePacket.SetTitle::class, TitlePacket.SetTimes::class, TitlePacket.Clear::class, TitlePacket.Reset::class ) bind().encoder(EntitySoundEffectEncoder).accept(EntitySoundEffectPacket::class) bind().encoder(SoundEffectEncoder).accept(SoundEffectPacket::class) bind().encoder(StopSoundsEncoder).accept(StopSoundsPacket::class) bind().encoder(TabListHeaderAndFooterEncoder).accept(TabListHeaderAndFooterPacket::class) bind().encoder(DataResponseEncoder).accept(DataResponsePacket::class) bind().encoder(EntityCollectItemEncoder).accept(EntityCollectItemPacket::class) bind().encoder(EntityTeleportEncoder).accept(EntityTeleportPacket::class) bind().encoder(AdvancementsEncoder).accept(AdvancementsPacket::class) bind().encoder(EncoderPlaceholder).accept(EntityPropertiesPacket::class) bind().encoder(AddPotionEffectEncoder).accept(AddPotionEffectPacket::class) bind().encoder(SetRecipesEncoder).accept(SetRecipesPacket::class) bind().encoder(TagsEncoder).accept(TagsPacket::class) } }
src/main/kotlin/org/lanternpowered/server/network/protocol/PlayProtocol.kt
3857198635
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.data import org.lanternpowered.api.util.optional.orNull import org.spongepowered.api.data.DataHolder import org.spongepowered.api.data.Key import org.spongepowered.api.data.value.Value import kotlin.reflect.KProperty internal open class OptionalKeyValueProperty<V : Value<E>, E : Any, H : DataHolder>(val key: Key<V>) : DataHolderProperty<H, V?> { override fun getValue(thisRef: H, property: KProperty<*>) = thisRef.getValue(this.key).orNull() }
src/main/kotlin/org/lanternpowered/server/data/OptionalKeyValueProperty.kt
4174160288
/* * Copyright 2018 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotlinx.serialization import kotlinx.serialization.json.* import org.junit.* import org.junit.Assert.* class SerializationCasesTest : JsonTestBase() { @Serializable data class Data1(val a: Int, val b: Int) @Serializer(forClass = Data1::class) object ExtDataSerializer1 @Test fun testConstructorValProperties() { val data = Data1(1, 2) // Serialize with internal serializer for Data class assertEquals("""{"a":1,"b":2}""", default.encodeToString(data)) assertEquals(data, Json.decodeFromString<Data1>("""{"a":1,"b":2}""")) // Serialize with external serializer for Data class assertEquals("""{"a":1,"b":2}""", default.encodeToString(ExtDataSerializer1, data)) assertEquals(data, Json.decodeFromString(ExtDataSerializer1, """{"a":1,"b":2}""")) } @Serializable class Data2 { var a = 0 var b = 0 override fun equals(other: Any?) = other is Data2 && other.a == a && other.b == b } @Serializer(forClass=Data2::class) object ExtDataSerializer2 @Test fun testBodyVarProperties() { val data = Data2().apply { a = 1 b = 2 } // Serialize with internal serializer for Data class assertEquals("""{"a":1,"b":2}""", default.encodeToString(data)) assertEquals(data, Json.decodeFromString<Data2>("""{"a":1,"b":2}""")) // Serialize with external serializer for Data class assertEquals("""{"a":1,"b":2}""", default.encodeToString(ExtDataSerializer2, data)) assertEquals(data, Json.decodeFromString(ExtDataSerializer2, """{"a":1,"b":2}""")) } enum class TintEnum { LIGHT, DARK } @Serializable data class Data3( val a: String, val b: List<Int>, val c: Map<String, TintEnum> ) // Serialize with external serializer for Data class @Serializer(forClass = Data3::class) object ExtDataSerializer3 @Test fun testNestedValues() { val data = Data3("Str", listOf(1, 2), mapOf("lt" to TintEnum.LIGHT, "dk" to TintEnum.DARK)) // Serialize with internal serializer for Data class val expected = """{"a":"Str","b":[1,2],"c":{"lt":"LIGHT","dk":"DARK"}}""" assertEquals(expected, default.encodeToString(data)) assertEquals(data, Json.decodeFromString<Data3>(expected)) assertEquals(expected, default.encodeToString(ExtDataSerializer3, data)) assertEquals(data, Json.decodeFromString(ExtDataSerializer3, expected)) } }
formats/json-tests/jvmTest/src/kotlinx/serialization/SerializationCasesTest.kt
182862624
package me.echeung.moemoekyun.util.ext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import kotlinx.coroutines.withContext private val scope = CoroutineScope(SupervisorJob()) fun launchIO(block: suspend CoroutineScope.() -> Unit): Job = scope.launch(Dispatchers.IO, CoroutineStart.DEFAULT, block) fun launchNow(block: suspend CoroutineScope.() -> Unit): Job = scope.launch(Dispatchers.Main, CoroutineStart.UNDISPATCHED, block) fun CoroutineScope.launchIO(block: suspend CoroutineScope.() -> Unit): Job = launch(Dispatchers.IO, block = block) suspend fun <T> withUIContext(block: suspend CoroutineScope.() -> T) = withContext(Dispatchers.Main, block)
app/src/main/kotlin/me/echeung/moemoekyun/util/ext/CoroutineExtensions.kt
1893318471
package com.github.feed.sample.data.model import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.SerializedName data class Actor( @SerializedName("login") val username: String, @SerializedName("avatar_url") val avatar: String ) : Parcelable { // region Parcelable Implementation companion object { @JvmField val CREATOR: Parcelable.Creator<Actor> = object : Parcelable.Creator<Actor> { override fun createFromParcel(source: Parcel): Actor = Actor(source) override fun newArray(size: Int): Array<Actor?> = arrayOfNulls(size) } } constructor(source: Parcel) : this( source.readString(), source.readString() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(username) dest.writeString(avatar) } // endregion }
app/src/main/kotlin/com/github/feed/sample/data/model/Actor.kt
3543482869
package nl.hannahsten.texifyidea.action import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.impl.source.tree.LeafPsiElement import nl.hannahsten.texifyidea.TexifyIcons import nl.hannahsten.texifyidea.lang.magic.magicComment import nl.hannahsten.texifyidea.psi.LatexCommands import nl.hannahsten.texifyidea.psi.LatexGroup import nl.hannahsten.texifyidea.psi.LatexTypes import nl.hannahsten.texifyidea.util.getParentOfType import nl.hannahsten.texifyidea.util.parentOfType /** * @author Hannah Schellekens */ class LatexToggleStarAction : EditorAction("Toggle Star", TexifyIcons.TOGGLE_STAR) { override fun actionPerformed(file: VirtualFile, project: Project, textEditor: TextEditor) { val element = getElement(file, project, textEditor) val editor = textEditor.editor val psiFile = getPsiFile(file, project) element?.parentOfType(LatexGroup::class)?.let { println(it.magicComment()) } val commands = getParentOfType(element, LatexCommands::class.java) ?: return runWriteAction(project) { toggleStar(editor, psiFile, commands) } } /** * Removes the star from a latex commands or adds it when there was no star in the first place. * * @param editor * The current editor. * @param psiFile * The current file. * @param commands * The latex command to toggle the star of. */ private fun toggleStar(editor: Editor, psiFile: PsiFile?, commands: LatexCommands?) { if (removeStar(commands!!)) { return } addStar(editor, psiFile, commands) } /** * Removes the star from a LaTeX command. * * @param commands * The command to remove the star from. * @return `true` when the star was removed, `false` when the star was not removed. */ private fun removeStar(commands: LatexCommands): Boolean { val lastChild = commands.lastChild var elt: PsiElement? = commands.firstChild while (elt !== lastChild && elt != null) { if (elt !is LeafPsiElement) { elt = elt.nextSibling continue } if (elt.elementType === LatexTypes.STAR) { elt.delete() return true } elt = elt.nextSibling } return false } /** * Adds a star to a latex command. * * @param editor * The current editor. * @param file * The current file. * @param commands * The latex command to add a star to. */ private fun addStar(editor: Editor, file: PsiFile?, commands: LatexCommands) { val document = editor.document var position = editor.caretModel.offset while (position > 0) { val text = document.getText(TextRange(position, position + 1)) val elt = file!!.findElementAt(position) val parent = getParentOfType(elt, LatexCommands::class.java) if (text.equals("\\", ignoreCase = true) && (elt == null || parent === commands)) { document.insertString(position + commands.commandToken.text.length, "*") return } position-- } } }
src/nl/hannahsten/texifyidea/action/LatexToggleStarAction.kt
97525263
/* * Copyright (c) 2016. KESTI co, ltd * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package debop4k.core.cryptography import org.jasypt.salt.SaltGenerator /** * 바이트 배열을 Digest (Hash 암호화)를 수행하는 interface * * @author [email protected] */ interface ByteDigester { /** * Digest 암호화를 위한 알고리즘 명 */ val algorithm: String /** * 암호화 시에 사용하는 Salt 값 생성기를 반환합니다. */ val saltGenerator: SaltGenerator /** * 바이트 배열 정보를 암호화 합니다. * @param message 바이트 배열 * @return 암호화된 바이트 배열 */ fun digest(message: ByteArray): ByteArray /** * Message 를 암호화하면, digest 와 같은 값이 되는지 확인한다. * @param message 암호화된 바이트 배열과 비교할 message * @param digest 암호화된 바이트 배열 * @return 같은 값이 되는지 여부 */ fun matches(message: ByteArray, digest: ByteArray): Boolean }
debop4k-core/src/main/kotlin/debop4k/core/cryptography/ByteDigester.kt
1486804236
package com.chandilsachin.diettracker.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Filter import android.widget.Filterable import android.widget.TextView import com.chandilsachin.diettracker.R import com.chandilsachin.diettracker.database.DietFood import ru.rambler.libs.swipe_layout.SwipeLayout /** * Created by Sachin Chandil on 29/04/2017. */ class DietListAdapter(context: android.content.Context, val editable:Boolean = true) : RecyclerView.Adapter<DietListAdapter.ViewHolder>(){ var foodList: List<DietFood> = emptyList() private val inflater = LayoutInflater.from(context) var onItemEditClick: (food: DietFood) -> Unit = {} var onItemDeleteClick: (food: DietFood) -> Unit = {} override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): com.chandilsachin.diettracker.adapters.DietListAdapter.ViewHolder { val holder = ViewHolder(inflater.inflate(R.layout.layout_food_list_item, parent, false)) return holder } override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bindView(foodList[position]) override fun getItemCount() = foodList.size inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val textViewFoodName = itemView.findViewById(R.id.textViewFoodName) as TextView private val textViewFoodDesc = itemView.findViewById(R.id.textViewFoodDesc) as TextView private val textViewQuantity = itemView.findViewById(R.id.textViewQuantity) as TextView private val swipeLayoutDietListItem = itemView.findViewById(R.id.swipeLayoutDietListItem) as SwipeLayout private val textViewDietItemDelete = itemView.findViewById(R.id.textViewDietItemDelete) as TextView private val textViewDietItemEdit = itemView.findViewById(R.id.textViewDietItemEdit) as TextView fun bindView(food: DietFood) { textViewFoodName.text = food.foodName textViewFoodDesc.text = food.foodDesc textViewQuantity.text = "x${food.quantity}" textViewQuantity.visibility = View.VISIBLE if(editable){ swipeLayoutDietListItem.isRightSwipeEnabled = true swipeLayoutDietListItem.isLeftSwipeEnabled = true textViewDietItemEdit.setOnClickListener { onItemEditClick(food) swipeLayoutDietListItem.reset() } textViewDietItemDelete.setOnClickListener(View.OnClickListener { onItemDeleteClick(food) swipeLayoutDietListItem.reset() }) } } } }
app/src/main/java/com/chandilsachin/diettracker/adapters/DietListAdapter.kt
1103817684
package nl.hannahsten.texifyidea.run.latex.externaltool import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.CommandLineState import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.KillableProcessHandler import com.intellij.execution.process.ProcessHandler import com.intellij.execution.process.ProcessTerminatedListener import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.vfs.VirtualFile import nl.hannahsten.texifyidea.run.compiler.ExternalTool /** * Run an external tool. */ class ExternalToolCommandLineState( environment: ExecutionEnvironment, private val mainFile: VirtualFile?, private val workingDirectory: VirtualFile?, private val tool: ExternalTool ) : CommandLineState(environment) { @Throws(ExecutionException::class) override fun startProcess(): ProcessHandler { if (mainFile == null) { throw ExecutionException("Main file to compile is not found or missing.") } val command = listOf(tool.executableName, mainFile.nameWithoutExtension) val commandLine = GeneralCommandLine(command).withWorkDirectory(workingDirectory?.path) val handler: ProcessHandler = KillableProcessHandler(commandLine) // Reports exit code to run output window when command is terminated ProcessTerminatedListener.attach(handler, environment.project) return handler } }
src/nl/hannahsten/texifyidea/run/latex/externaltool/ExternalToolCommandLineState.kt
3954515
package me.hyemdooly.sangs.dimigo.app.project.util import android.content.Context import android.view.KeyCharacterMap import android.view.KeyEvent import android.view.ViewConfiguration import android.view.View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR import android.app.Activity import android.os.Build import android.support.annotation.RequiresApi import android.view.View /** * Created by dsa28s on 8/26/17. */ fun getNavigationHeight(context: Context): Int { val resources = context.getResources() val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android") return if(isNavigationBarUsed(context)) { if (resourceId > 0) { resources.getDimensionPixelSize(resourceId) } else 0 } else { 0 } } fun isNavigationBarUsed(context: Context): Boolean { val hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey() val hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK) return !hasMenuKey && !hasBackKey } @RequiresApi(api = Build.VERSION_CODES.M) fun setSystemBarTheme(view: View, pIsDark: Boolean) { if(!pIsDark) { view.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } else { view.systemUiVisibility = 0 } //val lFlags = pActivity.window.decorView.systemUiVisibility //pActivity.window.decorView.systemUiVisibility = if (pIsDark) lFlags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv() else lFlags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } fun getStatusBarHeight(context: Context): Int { var result = 0 val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android") if (resourceId > 0) { result = context.resources.getDimensionPixelSize(resourceId) } return result }
app/src/main/kotlin/me/hyemdooly/sangs/dimigo/app/project/util/DisplayUtils.kt
1940612858
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.revert import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.util.containers.OpenTHashSet import com.intellij.vcs.log.Hash import com.intellij.vcs.log.VcsFullCommitDetails import git4idea.GitApplyChangesProcess import git4idea.commands.Git import git4idea.commands.GitCommandResult import git4idea.commands.GitLineHandlerListener import git4idea.repo.GitRepository /** * Commits should be provided in the "UI" order, i.e. as if `git log --date-order` is called, i.e. in reverse-chronological order. * They are going to be reverted in the reverse order, but the GitRevertOperation will reverse them on its own. */ class GitRevertOperation(private val project: Project, private val commits: List<VcsFullCommitDetails>, private val autoCommit: Boolean) { private val git = Git.getInstance() fun execute() { GitApplyChangesProcess(project, commits.reversed(), autoCommit, "revert", "reverted", command = { repository, hash, autoCommit, listeners -> doRevert(autoCommit, repository, hash, listeners) }, emptyCommitDetector = { result -> result.outputAsJoinedString.contains("nothing to commit") }, defaultCommitMessageGenerator = { commit -> """ Revert ${commit.subject} This reverts commit ${commit.id.asString()}""".trimIndent() }, findLocalChanges = { changesInCommit -> val allChanges = OpenTHashSet(ChangeListManager.getInstance(project).allChanges) changesInCommit.mapNotNull { allChanges.get(reverseChange(it)) } }).execute() } private fun doRevert(autoCommit: Boolean, repository: GitRepository, hash: Hash, listeners: List<GitLineHandlerListener>): GitCommandResult { return git.revert(repository, hash.asString(), autoCommit, *listeners.toTypedArray()) } private fun reverseChange(change: Change) = Change(change.afterRevision, change.beforeRevision) }
plugins/git4idea/src/git4idea/revert/GitRevertOperation.kt
4130503902
package de.thm.arsnova.service.httpgateway.service import de.thm.arsnova.service.httpgateway.config.HttpGatewayProperties import de.thm.arsnova.service.httpgateway.model.WsGatewayStats import org.slf4j.LoggerFactory import org.springframework.core.ParameterizedTypeReference import org.springframework.stereotype.Service import org.springframework.web.reactive.function.client.WebClient import reactor.core.publisher.Flux import reactor.core.publisher.Mono import java.util.Optional @Service class WsGatewayService( private val webClient: WebClient, private val httpGatewayProperties: HttpGatewayProperties ) { private val logger = LoggerFactory.getLogger(javaClass) fun getUsercount(roomIds: List<String>): Flux<Optional<Int>> { val url = "${httpGatewayProperties.httpClient.wsGateway}/roomsubscription/usercount?ids=${roomIds.joinToString(",")}" val typeRef: ParameterizedTypeReference<List<Int?>> = object : ParameterizedTypeReference<List<Int?>>() {} return webClient.get() .uri(url) .retrieve().bodyToMono(typeRef) .checkpoint("Request failed in ${this::class.simpleName}::${::getUsercount.name}.") .flatMapMany { userCounts: List<Int?> -> Flux.fromIterable( userCounts.map { entry -> if (entry != null) { Optional.of(entry) } else { Optional.empty() } } ) } .onErrorResume { exception -> logger.debug("Exception on getting room subscription user count from ws gw", exception) Flux.fromIterable( roomIds.map { // using a local var for this is needed because otherwise type can't be interfered val h: Optional<Int> = Optional.empty() h } ) } } fun getGatewayStats(): Mono<WsGatewayStats> { val url = "${httpGatewayProperties.httpClient.wsGateway}/stats" logger.trace("Querying ws gateway for stats with url: {}", url) return webClient.get() .uri(url) .retrieve().bodyToMono(WsGatewayStats::class.java) .checkpoint("Request failed in ${this::class.simpleName}::${::getGatewayStats.name}.") } }
gateway/src/main/kotlin/de/thm/arsnova/service/httpgateway/service/WsGatewayService.kt
3495447440
/* Copyright 2015 Andreas Würl Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.blitzortung.android.map.overlay interface LayerOverlay { val name: String var enabled: Boolean var visible: Boolean }
app/src/main/java/org/blitzortung/android/map/overlay/LayerOverlay.kt
471247253
package io.gitlab.arturbosch.detekt.rules.bugs import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext import org.assertj.core.api.Assertions.assertThat import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class UnsafeCastSpec : Spek({ setupKotlinEnvironment() val env: KotlinCoreEnvironment by memoized() val subject by memoized { UnsafeCast() } describe("check safe and unsafe casts") { it("reports cast that cannot succeed") { val code = """ fun test(s: String) { println(s as Int) }""" assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1) } it("reports 'safe' cast that cannot succeed") { val code = """ fun test(s: String) { println((s as? Int) ?: 0) }""" assertThat(subject.compileAndLintWithContext(env, code)).hasSize(1) } it("does not report cast that might succeed") { val code = """ fun test(s: Any) { println(s as Int) }""" assertThat(subject.compileAndLintWithContext(env, code)).isEmpty() } it("does not report 'safe' cast that might succeed") { val code = """ fun test(s: Any) { println((s as? Int) ?: 0) }""" assertThat(subject.compileAndLintWithContext(env, code)).isEmpty() } } })
detekt-rules-errorprone/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/UnsafeCastSpec.kt
3692935615
package com.cout970.magneticraft.misc.gui import com.cout970.magneticraft.misc.network.FloatSyncVariable /** * Created by cout970 on 10/07/2016. */ class ValueAverage(val maxCounter: Int = 20) { private var accumulated: Float = 0f private var counter: Int = 0 var storage: Float = 0f var average: Float = 0f private set fun tick() { counter++ if (counter >= maxCounter) { average = accumulated / counter accumulated = 0f counter = 0 } } operator fun plusAssign(value: Double) { accumulated += value.toFloat() } operator fun plusAssign(value: Float) { accumulated += value } operator fun plusAssign(value: Int) { accumulated += value.toFloat() } operator fun minusAssign(value: Number) { accumulated -= value.toFloat() } fun toSyncVariable(id: Int) = FloatSyncVariable(id, getter = { average }, setter = { storage = it }) }
src/main/kotlin/com/cout970/magneticraft/misc/gui/ValueAverage.kt
3829672276
package com.jereksel.libresubstratumlib.compilercommon class InvalidInvocationException(text: String): Exception(text)
sublib/compilercommon/src/main/java/com/jereksel/libresubstratumlib/compilercommon/InvalidInvocationException.kt
1838286062
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package sample.globalstate import kotlin.native.concurrent.* import kotlinx.cinterop.* import platform.posix.* inline fun Int.ensureUnixCallResult(op: String, predicate: (Int) -> Boolean = { x -> x == 0} ): Int { if (!predicate(this)) { throw Error("$op: ${strerror(posix_errno())!!.toKString()}") } return this } data class SharedDataMember(val double: Double) data class SharedData(val string: String, val int: Int, val member: SharedDataMember) // Here we access the same shared frozen Kotlin object from multiple threads. val globalObject: SharedData? get() = sharedData.frozenKotlinObject?.asStableRef<SharedData>()?.get() fun dumpShared(prefix: String) { println(""" $prefix: ${pthread_self()} x=${sharedData.x} f=${sharedData.f} s=${sharedData.string!!.toKString()} """.trimIndent()) } fun main() { // Arena owning all native allocs. val arena = Arena() // Assign global data. sharedData.x = 239 sharedData.f = 0.5f sharedData.string = "Hello Kotlin!".cstr.getPointer(arena) // Here we create detached mutable object, which could be later reattached by another thread. sharedData.kotlinObject = DetachedObjectGraph { SharedData("A string", 42, SharedDataMember(2.39)) }.asCPointer() // Here we create shared frozen object reference, val stableRef = StableRef.create(SharedData("Shared", 239, SharedDataMember(2.71)).freeze()) sharedData.frozenKotlinObject = stableRef.asCPointer() dumpShared("thread1") println("frozen is $globalObject") // Start a new thread, that sees the variable. // memScoped is needed to pass thread's local address to pthread_create(). memScoped { val thread = alloc<pthread_tVar>() pthread_create(thread.ptr, null, staticCFunction { argC -> initRuntimeIfNeeded() dumpShared("thread2") val kotlinObject = DetachedObjectGraph<SharedData>(sharedData.kotlinObject).attach() val arg = DetachedObjectGraph<SharedDataMember>(argC).attach() println("thread arg is $arg Kotlin object is $kotlinObject frozen is $globalObject") // Workaround for compiler issue. null as COpaquePointer? }, DetachedObjectGraph { SharedDataMember(3.14)}.asCPointer() ).ensureUnixCallResult("pthread_create") pthread_join(thread.value, null).ensureUnixCallResult("pthread_join") } // At this moment we do not need data stored in shared data, so clean up the data // and free memory. sharedData.string = null stableRef.dispose() arena.clear() }
samples/globalState/src/globalStateMain/kotlin/Global.kt
2992721892
package net.blakelee.coinprofits.models import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class ChartData { @SerializedName("market_cap_by_available_supply") @Expose var marketCapByAvailableSupply: List<List<Long>>? = null @SerializedName("price_btc") @Expose var priceBtc: List<List<Long>>? = null @SerializedName("price_usd") @Expose var priceUsd: List<List<Float>>? = null }
app/src/main/java/net/blakelee/coinprofits/models/ChartData.kt
1179716621
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.lang.structure import com.intellij.ide.structureView.StructureViewBuilder import com.intellij.ide.structureView.TreeBasedStructureViewBuilder import com.intellij.lang.PsiStructureViewFactory import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiFile class LangStructureViewFactory : PsiStructureViewFactory { override fun getStructureViewBuilder(psiFile: PsiFile): StructureViewBuilder? { return object : TreeBasedStructureViewBuilder() { override fun createStructureViewModel(editor: Editor?) = LangStructureViewModel(psiFile) } } }
src/main/kotlin/translations/lang/structure/LangStructureViewFactory.kt
2487017649
package org.equeim.tremotesf.torrentfile import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertNotSame import org.junit.Assert.assertSame import org.junit.Assert.assertThrows import org.junit.Test class NodeTest { @Test fun `Add file to node without children`() { val rootNode = TorrentFilesTree.DirectoryNode.createRootNode() val node = rootNode.addDirectory("0") val expectedItem = expectedFileItem(99, intArrayOf(0, 0)) node.addFile(expectedItem.fileId, expectedItem.name, expectedItem.size, expectedItem.completedSize, expectedItem.wantedState, expectedItem.priority) checkLastChild(node, expectedItem) } @Test fun `Add directory to node without children`() { val rootNode = TorrentFilesTree.DirectoryNode.createRootNode() val node = rootNode.addDirectory("0") val expectedItem = expectedDirectoryItem(intArrayOf(0, 0)) node.addDirectory(expectedItem.name) checkLastChild(node, expectedItem) } @Test fun `Add file to node with children`() { val rootNode = TorrentFilesTree.DirectoryNode.createRootNode() val node = rootNode.addDirectory("0") node.addFile(98, "foo", 1, 0, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal) val expectedItem = expectedFileItem(99, intArrayOf(0, 1)) node.addFile(expectedItem.fileId, expectedItem.name, expectedItem.size, expectedItem.completedSize, expectedItem.wantedState, expectedItem.priority) checkLastChild(node, expectedItem) } @Test fun `Add file with wrong id`() { val rootNode = TorrentFilesTree.DirectoryNode.createRootNode() val node = rootNode.addDirectory("0") val expectedItem = expectedFileItem(-666, intArrayOf(0, 0)) assertThrows(IllegalArgumentException::class.java) { node.addFile(expectedItem.fileId, expectedItem.name, expectedItem.size, expectedItem.completedSize, expectedItem.wantedState, expectedItem.priority) } } @Test fun `Add directory to node with children`() { val rootNode = TorrentFilesTree.DirectoryNode.createRootNode() val node = rootNode.addDirectory("0") node.addFile(98, "foo", 1, 0, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal) val expectedItem = expectedDirectoryItem(intArrayOf(0, 1)) node.addDirectory(expectedItem.name) checkLastChild(node, expectedItem) } private fun checkLastChild(node: TorrentFilesTree.DirectoryNode, expectedItem: TorrentFilesTree.Item) { val lastChild = node.children.last() assertEquals(lastChild, node.getChildByItemNameOrNull(expectedItem.name)) assertEquals(expectedItem, lastChild.item) assertArrayEquals(expectedItem.nodePath, lastChild.path) } @Test fun `Recalculating from children`() { val rootNode = TorrentFilesTree.DirectoryNode.createRootNode() val directory = rootNode.addDirectory("0").apply { addFile(98, "foo", 1, 42, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal) addFile(99, "bar", 1, 42, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Low) addDirectory("1") .addFile(100, "foo", 1, 42, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Low) } var item = directory.item assertEquals(0, item.size) assertEquals(0, item.completedSize) assertEquals(TorrentFilesTree.Item.WantedState.Wanted, item.wantedState) assertEquals(TorrentFilesTree.Item.Priority.Normal, item.priority) directory.recalculateFromChildren() assertNotSame(item, directory.item) item = directory.item assertEquals(2, item.size) assertEquals(84, item.completedSize) assertEquals(TorrentFilesTree.Item.WantedState.Wanted, item.wantedState) assertEquals(TorrentFilesTree.Item.Priority.Mixed, item.priority) } @Test fun `Initially calculate from children recursively`() { val (directory, nestedDirectory) = createDirectoryWithSubdirectory() val directoryItem = directory.item val nestedDirectoryItem = nestedDirectory.item for (item in listOf(directoryItem, nestedDirectoryItem)) { assertEquals(0, item.size) assertEquals(0, item.completedSize) assertEquals(TorrentFilesTree.Item.WantedState.Wanted, item.wantedState) assertEquals(TorrentFilesTree.Item.Priority.Normal, item.priority) } directory.initiallyCalculateFromChildrenRecursively() assertSame(nestedDirectoryItem, nestedDirectory.item) assertEquals(2, nestedDirectoryItem.size) assertEquals(708, nestedDirectoryItem.completedSize) assertEquals(TorrentFilesTree.Item.WantedState.Mixed, nestedDirectoryItem.wantedState) assertEquals(TorrentFilesTree.Item.Priority.Low, nestedDirectoryItem.priority) assertSame(directoryItem, directory.item) assertEquals(4, directoryItem.size) assertEquals(792, directoryItem.completedSize) assertEquals(TorrentFilesTree.Item.WantedState.Mixed, directoryItem.wantedState) assertEquals(TorrentFilesTree.Item.Priority.Mixed, directoryItem.priority) } @Test fun `Set wanted state recursively`() { checkSetWantedStateOrPriority( operation = { setItemWantedRecursively(false, it) }, itemAssert = { assertEquals(TorrentFilesTree.Item.WantedState.Unwanted, wantedState) } ) } @Test fun `Set priority recursively`() { checkSetWantedStateOrPriority( operation = { setItemPriorityRecursively(TorrentFilesTree.Item.Priority.High, it) }, itemAssert = { assertEquals(TorrentFilesTree.Item.Priority.High, priority) } ) } private fun checkSetWantedStateOrPriority(operation: TorrentFilesTree.Node.(MutableList<Int>) -> Unit, itemAssert: TorrentFilesTree.Item.() -> Unit) { val (directory, _) = createDirectoryWithSubdirectory() directory.initiallyCalculateFromChildrenRecursively() fun getItems(node: TorrentFilesTree.Node, items: MutableList<TorrentFilesTree.Item>) { items.add(node.item) (node as? TorrentFilesTree.DirectoryNode)?.children?.forEach { getItems(it, items) } } val oldItems = mutableListOf<TorrentFilesTree.Item>() getItems(directory, oldItems) val ids = mutableListOf<Int>() directory.operation(ids) val newItems = mutableListOf<TorrentFilesTree.Item>() getItems(directory, newItems) oldItems.asSequence().zip(newItems.asSequence()).forEach { (oldItem, newItem) -> assertNotSame(oldItem, newItem) newItem.itemAssert() } assertEquals(setOf(98, 99, 100, 101), ids.toSet()) } private fun createDirectoryWithSubdirectory(): Pair<TorrentFilesTree.DirectoryNode, TorrentFilesTree.DirectoryNode> { val rootNode = TorrentFilesTree.DirectoryNode.createRootNode() val directory = rootNode.addDirectory("0").apply { addFile(98, "foo", 1, 42, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal) addFile(99, "bar", 1, 42, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Low) } val nestedDirectory = directory.addDirectory("1").apply { addFile(100, "foo", 1, 42, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Low) addFile(101, "bar", 1, 666, TorrentFilesTree.Item.WantedState.Unwanted, TorrentFilesTree.Item.Priority.Low) } return directory to nestedDirectory } }
torrentfile/src/test/kotlin/org/equeim/tremotesf/torrentfile/NodeTest.kt
2659166463
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.ext.gitlfs.server import jakarta.servlet.http.HttpServletRequest import org.apache.commons.io.IOUtils import org.tmatesoft.svn.core.SVNException import ru.bozaro.gitlfs.common.Constants import ru.bozaro.gitlfs.common.data.Meta import ru.bozaro.gitlfs.server.ContentManager import ru.bozaro.gitlfs.server.ContentManager.Downloader import ru.bozaro.gitlfs.server.ContentManager.Uploader import ru.bozaro.gitlfs.server.ForbiddenError import ru.bozaro.gitlfs.server.UnauthorizedError import svnserver.auth.User import svnserver.context.LocalContext import svnserver.ext.gitlfs.LfsAuthHelper import svnserver.ext.gitlfs.storage.LfsStorage import svnserver.ext.web.server.WebServer import svnserver.repository.VcsAccess import java.io.FileNotFoundException import java.io.IOException import java.io.InputStream import java.util.* /** * ContentManager wrapper for shared LFS server implementation. * * @author Artem V. Navrotskiy <[email protected]> */ class LfsContentManager internal constructor(private val context: LocalContext, val storage: LfsStorage, private val tokenExpireSec: Long, private val tokenEnsureTime: Float) : ContentManager { @Throws(IOException::class, ForbiddenError::class, UnauthorizedError::class) override fun checkDownloadAccess(request: HttpServletRequest): Downloader { val user = checkDownload(request) val header: Map<String, String> = createHeader(request, user) return object : Downloader { @Throws(IOException::class) override fun openObject(hash: String): InputStream { val reader = storage.getReader(LfsStorage.OID_PREFIX + hash, -1) ?: throw FileNotFoundException(hash) return reader.openStream() } @Throws(IOException::class) override fun openObjectGzipped(hash: String): InputStream? { val reader = storage.getReader(LfsStorage.OID_PREFIX + hash, -1) ?: throw FileNotFoundException(hash) return reader.openGzipStream() } override fun createHeader(defaultHeader: Map<String, String>): Map<String, String> { return header } } } @Throws(IOException::class, UnauthorizedError::class, ForbiddenError::class) fun checkDownload(request: HttpServletRequest): User { val access = context.sure(VcsAccess::class.java) return checkAccess(request) { user: User, branch: String, path: String -> access.checkRead(user, branch, path) } } private fun createHeader(request: HttpServletRequest, user: User): Map<String, String> { val auth = request.getHeader(Constants.HEADER_AUTHORIZATION) ?: return emptyMap() return if (auth.startsWith(WebServer.AUTH_TOKEN)) { mapOf(Constants.HEADER_AUTHORIZATION to auth) } else { LfsAuthHelper.createTokenHeader(context.shared, user, LfsAuthHelper.getExpire(tokenExpireSec)) } } @Throws(IOException::class, UnauthorizedError::class, ForbiddenError::class) private fun checkAccess(request: HttpServletRequest, checker: Checker): User { val user = getAuthInfo(request) try { // This is a *bit* of a hack. // If user accesses LFS, it means she is using git. If she uses git, she has whole repository contents. // If she has full repository contents, it doesn't make sense to apply path-based authorization. // Setups where where user has Git access but is not allowed to write via path-based authorization are declared bogus. checker.check(user, org.eclipse.jgit.lib.Constants.MASTER, "/") } catch (ignored: SVNException) { if (user.isAnonymous) { throw UnauthorizedError("Basic realm=\"" + context.shared.realm + "\"") } else { throw ForbiddenError() } } return user } private fun getAuthInfo(request: HttpServletRequest): User { val server = context.shared.sure(WebServer::class.java) val user = server.getAuthInfo(request.getHeader(Constants.HEADER_AUTHORIZATION), Math.round(tokenExpireSec * tokenEnsureTime)) return user ?: User.anonymous } @Throws(IOException::class, ForbiddenError::class, UnauthorizedError::class) override fun checkUploadAccess(request: HttpServletRequest): Uploader { val user = checkUpload(request) val header = createHeader(request, user) return object : Uploader { @Throws(IOException::class) override fun saveObject(meta: Meta, content: InputStream) { storage.getWriter(Objects.requireNonNull(user)).use { writer -> IOUtils.copy(content, writer) writer.finish(LfsStorage.OID_PREFIX + meta.oid) } } override fun createHeader(defaultHeader: Map<String, String>): Map<String, String> { return header } } } @Throws(IOException::class, UnauthorizedError::class, ForbiddenError::class) fun checkUpload(request: HttpServletRequest): User { val access = context.sure(VcsAccess::class.java) return checkAccess(request) { user: User, branch: String, path: String -> access.checkWrite(user, branch, path) } } @Throws(IOException::class) override fun getMetadata(hash: String): Meta? { val reader = storage.getReader(LfsStorage.OID_PREFIX + hash, -1) ?: return null return Meta(reader.getOid(true), reader.size) } fun interface Checker { @Throws(SVNException::class, IOException::class) fun check(user: User, branch: String, path: String) } }
src/main/kotlin/svnserver/ext/gitlfs/server/LfsContentManager.kt
1366140267
package com.dewarder.akommons.binding.dimen import android.content.Context import com.dewarder.akommons.binding.* import com.dewarder.akommons.binding.common.NO_DIMEN1 import com.dewarder.akommons.binding.common.NO_DIMEN2 import com.dewarder.akommons.binding.common.dimen.TestableDimen import com.dewarder.akommons.binding.common.R class TestDimenContextProvider(private val context: Context) : ContextProvider, TestableDimen { override fun provideContext() = context override val dimenRequiredExist by dimen(R.dimen.test_dimen_8dp) override val dimenRequiredAbsent by dimen(NO_DIMEN1) override val dimenOptionalExist by dimenOptional(R.dimen.test_dimen_8dp) override val dimenOptionalAbsent by dimenOptional(NO_DIMEN1) override val dimenRequiredExistPx by dimen(R.dimen.test_dimen_8px, DimensionType.PX) override val dimenRequiredExistDp by dimen(R.dimen.test_dimen_8dp, DimensionType.DP) override val dimenRequiredExistSp by dimen(R.dimen.test_dimen_8sp, DimensionType.SP) override val dimenOptionalExistPx by dimen(R.dimen.test_dimen_8px, DimensionType.PX) override val dimenOptionalExistDp by dimen(R.dimen.test_dimen_8dp, DimensionType.DP) override val dimenOptionalExistSp by dimen(R.dimen.test_dimen_8sp, DimensionType.SP) override val dimensRequiredAllExist by dimens(R.dimen.test_dimen_4dp, R.dimen.test_dimen_8dp) override val dimensRequiredAllAbsent by dimens(NO_DIMEN1, NO_DIMEN2) override val dimensOptionalAllExist by dimensOptional(R.dimen.test_dimen_4dp, R.dimen.test_dimen_8dp) override val dimensOptionalAllAbsent by dimensOptional(NO_DIMEN1, NO_DIMEN2) override val dimensRequiredFirstExistSecondAbsent by dimens(R.dimen.test_dimen_4dp, NO_DIMEN1) override val dimensOptionalFirstExistSecondAbsent by dimensOptional(R.dimen.test_dimen_4dp, NO_DIMEN1) override val dimensRequiredExistPxDpSpAllPx by dimens(R.dimen.test_dimen_8px, R.dimen.test_dimen_8dp, R.dimen.test_dimen_8sp) override val dimensOptionalExistPxDpSpAllPx by dimensOptional(R.dimen.test_dimen_8px, R.dimen.test_dimen_8dp, R.dimen.test_dimen_8sp) override val dimensRequiredExistPxDpSpAllDp by dimens(R.dimen.test_dimen_8px, R.dimen.test_dimen_8dp, R.dimen.test_dimen_8sp, dimension = DimensionType.DP) override val dimensOptionalExistPxDpSpAllDp by dimens(R.dimen.test_dimen_8px, R.dimen.test_dimen_8dp, R.dimen.test_dimen_8sp, dimension = DimensionType.DP) }
akommons-bindings/src/androidTest/java/com/dewarder/akommons/binding/dimen/TestDimenContextProvider.kt
212153161
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.repository.git.push import org.eclipse.jgit.lib.ObjectId import org.eclipse.jgit.lib.Repository import org.tmatesoft.svn.core.SVNException import svnserver.auth.User import java.io.IOException /** * Interface for pushing new commit to the repository. * * @author Artem V. Navrotskiy <[email protected]> */ interface GitPusher { /** * Push commits. Only fast forward support * * @param repository Repository * @param commitId Commit ID * @param branch Branch name * @param userInfo User info * @return Return true if data is pushed successfully. And false on non fast-forward push failure. */ @Throws(SVNException::class, IOException::class) fun push(repository: Repository, commitId: ObjectId, branch: String, userInfo: User): Boolean }
src/main/kotlin/svnserver/repository/git/push/GitPusher.kt
2857758623
package co.nums.intellij.aem.htl.file import co.nums.intellij.aem.htl.HtlLanguage import co.nums.intellij.aem.htl.psi.* import com.intellij.lang.* import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.impl.source.PsiFileImpl import com.intellij.psi.templateLanguages.* import com.intellij.util.containers.ContainerUtil class HtlFileViewProvider @JvmOverloads constructor(private val psiManager: PsiManager, file: VirtualFile, physical: Boolean, private val baseLanguage: Language, private val templateDataLanguage: Language = getTemplateDataLanguage(psiManager, file)) : MultiplePsiFilesPerDocumentFileViewProvider(psiManager, file, physical), ConfigurableTemplateLanguageFileViewProvider { companion object { private val HTL_FRAGMENT = HtlElementType("HTL_FRAGMENT") private val TEMPLATE_DATA_TO_LANG = ContainerUtil.newConcurrentMap<String, TemplateDataElementType>() } override fun getBaseLanguage() = baseLanguage override fun getTemplateDataLanguage() = templateDataLanguage override fun getLanguages(): Set<Language> = setOf(baseLanguage, templateDataLanguage) override fun supportsIncrementalReparse(rootLanguage: Language) = false override fun cloneInner(virtualFile: VirtualFile) = HtlFileViewProvider(psiManager, virtualFile, false, baseLanguage, templateDataLanguage) override fun createFile(language: Language): PsiFile? { val parserDefinition = getParserDefinition(language) return when { language === templateDataLanguage -> { val file = parserDefinition.createFile(this) as PsiFileImpl file.contentElementType = getTemplateDataElementType(baseLanguage) file } language.isKindOf(baseLanguage) -> parserDefinition.createFile(this) else -> null } } private fun getParserDefinition(language: Language): ParserDefinition { val parserLanguage = when { language === baseLanguage -> language language.isKindOf(baseLanguage) -> baseLanguage else -> language } return LanguageParserDefinitions.INSTANCE.forLanguage(parserLanguage) } private fun getTemplateDataElementType(language: Language): TemplateDataElementType { val result = TEMPLATE_DATA_TO_LANG[language.id] if (result != null) { return result } val created = TemplateDataElementType("HTL_TEMPLATE_DATA", language, HtlTypes.OUTER_TEXT, HTL_FRAGMENT) val prevValue = TEMPLATE_DATA_TO_LANG.putIfAbsent(language.id, created) return prevValue ?: created } } private fun getTemplateDataLanguage(psiManager: PsiManager, file: VirtualFile): Language { var dataLanguage = TemplateDataLanguageMappings.getInstance(psiManager.project)?.getMapping(file) ?: HtlLanguage.getTemplateLanguageFileType().language val substituteLanguage = LanguageSubstitutors.INSTANCE.substituteLanguage(dataLanguage, file, psiManager.project) // only use a substituted language if it's templateable if (TemplateDataLanguageMappings.getTemplateableLanguages().contains(substituteLanguage)) { dataLanguage = substituteLanguage } return dataLanguage }
src/main/kotlin/co/nums/intellij/aem/htl/file/HtlFileViewProvider.kt
4249981854
package app.cash.sqldelight.intellij.run import app.cash.sqldelight.core.SqlDelightProjectService import app.cash.sqldelight.dialect.api.ConnectionManager import com.alecstrong.sql.psi.core.psi.SqlStmt import com.alecstrong.sql.psi.core.psi.SqlVisitor import com.intellij.icons.AllIcons import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.editor.markup.GutterIconRenderer import javax.swing.Icon internal class SqlDelightRunVisitor( private val holder: AnnotationHolder, private val connectionOptions: ConnectionOptions, ) : SqlVisitor() { override fun visitStmt(o: SqlStmt) { val connectionManager = SqlDelightProjectService.getInstance(o.project).dialect.connectionManager ?: return if (connectionOptions.selectedOption() == null) return holder.newAnnotation(HighlightSeverity.INFORMATION, "") .gutterIconRenderer(RunSqliteStatementGutterIconRenderer(o, connectionManager)) .create() } private data class RunSqliteStatementGutterIconRenderer( private val stmt: SqlStmt, private val connectionManager: ConnectionManager, ) : GutterIconRenderer() { override fun isNavigateAction() = true override fun getIcon(): Icon = AllIcons.RunConfigurations.TestState.Run override fun getTooltipText(): String = "Run statement" override fun getClickAction() = RunSqlAction(stmt, connectionManager) } }
sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/run/SqlDelightRunVisitor.kt
2754912529
package org.pixelndice.table.pixelclient.fx import javafx.scene.canvas.GraphicsContext import javafx.scene.paint.Color import javafx.scene.text.Font import org.pixelndice.table.pixelclient.currentBoard import org.pixelndice.table.pixelclient.currentCampaign import org.pixelndice.table.pixelclient.currentCanvas import org.pixelndice.table.pixelclient.misc.Point import kotlin.math.pow /** * @author Marcelo costa Toyama * Distance Ruler class for measuring distances in PixelCanvas */ class DistanceRuler(val origin: Point, val destination: Point){ /** * Draws arrow and shows distance in board units (default: feet) */ fun draw(gc: GraphicsContext){ val dx = destination.x - origin.x val dy = destination.y - origin.y val end1 = Point() end1.x = destination.x - (dx*cos + dy * -sin) end1.y = destination.y - (dx *sin + dy * cos) val end2 = Point() end2.x = destination.x - (dx * cos + dy * sin) end2.y = destination.y - (dx * -sin + dy * cos) val mag1 = Math.sqrt((end1.x-destination.x).pow(2) + (end1.y-destination.y).pow(2)) end1.x = destination.x + ((end1.x-destination.x)/mag1) * PixelCanvas.GRID_WIDTH end1.y = destination.y + ((end1.y-destination.y)/mag1) * PixelCanvas.GRID_HEIGHT val mag2 = Math.sqrt((end2.x-destination.x).pow(2) + (end2.y-destination.y).pow(2)) end2.x = destination.x + ((end2.x-destination.x)/mag2) * PixelCanvas.GRID_WIDTH end2.y = destination.y + ((end2.y-destination.y)/mag2) * PixelCanvas.GRID_HEIGHT gc.save() gc.lineWidth = 5.0 gc.strokeLine(origin.x, origin.y, destination.x, destination.y) gc.strokeLine(destination.x, destination.y, end1.x, end1.y) gc.strokeLine(destination.x, destination.y, end2.x, end2.y) gc.restore() val distance = currentCanvas?.distanceCanvasToBoard(origin,destination) ?: Point() distance.x = distance.x * ((currentBoard?.distance ?: 0.0) / PixelCanvas.GRID_WIDTH) distance.y = distance.y * ((currentBoard?.distance ?: 0.0) / PixelCanvas.GRID_HEIGHT) val hypotenuse = Math.sqrt(distance.x.pow(2)+distance.y.pow(2)) gc.save() gc.fill = Color.BLACK gc.font = Font(18.0) gc.fillText("%.2f ${currentBoard?.distanceUnit}".format(hypotenuse),destination.x+PixelCanvas.GRID_WIDTH, destination.y+PixelCanvas.GRID_HEIGHT) gc.restore() } companion object { private const val cos = 0.866 private const val sin = 0.500 } }
src/main/kotlin/org/pixelndice/table/pixelclient/fx/DistanceRuler.kt
1633917188
package com.pennapps.labs.pennmobile.components.floatingbottombar.utils import androidx.annotation.IdRes import androidx.constraintlayout.widget.ConstraintSet internal fun ConstraintSet.createChain( @IdRes firstItemId: Int, @IdRes secondItemId: Int, chainStyle: Int ) { val chainViews = intArrayOf(firstItemId, secondItemId) val chainWeights = floatArrayOf(0f, 0f) this.createHorizontalChain( firstItemId, ConstraintSet.LEFT, secondItemId, ConstraintSet.RIGHT, chainViews, chainWeights, chainStyle ) }
PennMobile/src/main/java/com/pennapps/labs/pennmobile/components/floatingbottombar/utils/ConstraintLayoutHelper.kt
1895704761
package org.wikipedia.descriptions import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.widget.LinearLayout import androidx.appcompat.content.res.AppCompatResources import androidx.core.net.toUri import androidx.core.view.isVisible import androidx.core.widget.TextViewCompat import org.wikipedia.R import org.wikipedia.auth.AccountUtil import org.wikipedia.databinding.ViewDescriptionEditLicenseBinding import org.wikipedia.page.LinkMovementMethodExt import org.wikipedia.richtext.RichTextUtil import org.wikipedia.util.StringUtil import org.wikipedia.util.UriUtil class DescriptionEditLicenseView constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout(context, attrs) { fun interface Callback { fun onLoginClick() } var callback: Callback? = null private val binding = ViewDescriptionEditLicenseBinding.inflate(LayoutInflater.from(context), this) private val movementMethod = LinkMovementMethodExt { url: String -> if (url == "https://#login") { callback?.onLoginClick() } else { UriUtil.handleExternalLink(context, url.toUri()) } } init { orientation = VERTICAL binding.licenseText.movementMethod = movementMethod binding.anonWarningText.movementMethod = movementMethod buildLicenseNotice(ARG_NOTICE_DEFAULT) } fun buildLicenseNotice(arg: String, lang: String? = null) { if ((arg == ARG_NOTICE_ARTICLE_DESCRIPTION || arg == ARG_NOTICE_DEFAULT) && DescriptionEditFragment.wikiUsesLocalDescriptions(lang.orEmpty())) { binding.licenseText.text = StringUtil.fromHtml(context.getString(R.string.edit_save_action_license_logged_in, context.getString(R.string.terms_of_use_url), context.getString(R.string.cc_by_sa_3_url))) } else { binding.licenseText.text = StringUtil.fromHtml(context.getString(when (arg) { ARG_NOTICE_ARTICLE_DESCRIPTION -> R.string.suggested_edits_license_notice ARG_NOTICE_IMAGE_CAPTION -> R.string.suggested_edits_image_caption_license_notice else -> R.string.description_edit_license_notice }, context.getString(R.string.terms_of_use_url), context.getString(R.string.cc_0_url))) } binding.anonWarningText.text = StringUtil.fromHtml(context.getString(R.string.edit_anon_warning)) binding.anonWarningText.isVisible = !AccountUtil.isLoggedIn RichTextUtil.removeUnderlinesFromLinks(binding.licenseText) RichTextUtil.removeUnderlinesFromLinks(binding.anonWarningText) } fun darkLicenseView() { val white70 = AppCompatResources.getColorStateList(context, R.color.white70) setBackgroundResource(android.R.color.black) binding.licenseText.setTextColor(white70) binding.licenseText.setLinkTextColor(white70) TextViewCompat.setCompoundDrawableTintList(binding.licenseText, white70) binding.anonWarningText.setTextColor(white70) binding.anonWarningText.setLinkTextColor(white70) } companion object { const val ARG_NOTICE_DEFAULT = "defaultNotice" const val ARG_NOTICE_IMAGE_CAPTION = "imageCaptionNotice" const val ARG_NOTICE_ARTICLE_DESCRIPTION = "articleDescriptionNotice" } }
app/src/main/java/org/wikipedia/descriptions/DescriptionEditLicenseView.kt
1762393179
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.util.shortcut import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.Drawable import android.os.Build import android.support.v4.content.pm.ShortcutInfoCompat import android.support.v4.content.pm.ShortcutManagerCompat import android.support.v4.graphics.drawable.IconCompat import com.bumptech.glide.Glide import nl.komponents.kovenant.Promise import nl.komponents.kovenant.combine.and import nl.komponents.kovenant.then import nl.komponents.kovenant.ui.alwaysUi import nl.komponents.kovenant.ui.successUi import org.mariotaku.kpreferences.get import de.vanita5.twittnuker.R import de.vanita5.twittnuker.annotation.ImageShapeStyle import de.vanita5.twittnuker.constant.iWantMyStarsBackKey import de.vanita5.twittnuker.constant.nameFirstKey import de.vanita5.twittnuker.constant.profileImageStyleKey import de.vanita5.twittnuker.extension.dismissProgressDialog import de.vanita5.twittnuker.extension.loadProfileImage import de.vanita5.twittnuker.extension.showProgressDialog import de.vanita5.twittnuker.fragment.BaseFragment import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.model.ParcelableUserList import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.util.IntentUtils import de.vanita5.twittnuker.util.dagger.DependencyHolder import de.vanita5.twittnuker.util.glide.DeferredTarget import java.lang.ref.WeakReference object ShortcutCreator { private val useAdaptiveIcon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O private const val adaptiveIconSizeDp = 108 private const val adaptiveIconOuterSidesDp = 18 fun user(context: Context, accountKey: UserKey?, user: ParcelableUser): Promise<ShortcutInfoCompat, Exception> { val holder = DependencyHolder.get(context) val preferences = holder.preferences val userColorNameManager = holder.userColorNameManager val profileImageStyle = if (useAdaptiveIcon) ImageShapeStyle.SHAPE_RECTANGLE else preferences[profileImageStyleKey] val profileImageCornerRadiusRatio = if (useAdaptiveIcon) 0f else 0.1f val deferred = Glide.with(context).loadProfileImage(context, user, shapeStyle = profileImageStyle, cornerRadiusRatio = profileImageCornerRadiusRatio, size = context.getString(R.string.profile_image_size)).into(DeferredTarget()) val weakContext = WeakReference(context) return deferred.promise.then { drawable -> val ctx = weakContext.get() ?: throw InterruptedException() val builder = ShortcutInfoCompat.Builder(ctx, "$accountKey:user:${user.key}") builder.setIcon(drawable.toProfileImageIcon(ctx)) builder.setShortLabel(userColorNameManager.getDisplayName(user, preferences[nameFirstKey])) val launchIntent = IntentUtils.userProfile(accountKey, user.key, user.screen_name, profileUrl = user.extras?.statusnet_profile_url) builder.setIntent(launchIntent) return@then builder.build() } } fun userFavorites(context: Context, accountKey: UserKey?, user: ParcelableUser): Promise<ShortcutInfoCompat, Exception> { val holder = DependencyHolder.get(context) val preferences = holder.preferences val userColorNameManager = holder.userColorNameManager val launchIntent = IntentUtils.userFavorites(accountKey, user.key, user.screen_name, profileUrl = user.extras?.statusnet_profile_url) val builder = ShortcutInfoCompat.Builder(context, "$accountKey:user-favorites:${user.key}") builder.setIntent(launchIntent) builder.setShortLabel(userColorNameManager.getDisplayName(user, preferences[nameFirstKey])) if (preferences[iWantMyStarsBackKey]) { builder.setIcon(IconCompat.createWithResource(context, R.mipmap.ic_shortcut_favorite)) } else { builder.setIcon(IconCompat.createWithResource(context, R.mipmap.ic_shortcut_like)) } return Promise.of(builder.build()) } fun userTimeline(context: Context, accountKey: UserKey?, user: ParcelableUser): Promise<ShortcutInfoCompat, Exception> { val holder = DependencyHolder.get(context) val preferences = holder.preferences val userColorNameManager = holder.userColorNameManager val launchIntent = IntentUtils.userTimeline(accountKey, user.key, user.screen_name, profileUrl = user.extras?.statusnet_profile_url) val builder = ShortcutInfoCompat.Builder(context, "$accountKey:user-timeline:${user.key}") builder.setIntent(launchIntent) builder.setShortLabel(userColorNameManager.getDisplayName(user, preferences[nameFirstKey])) builder.setIcon(IconCompat.createWithResource(context, R.mipmap.ic_shortcut_quote)) return Promise.of(builder.build()) } fun userMediaTimeline(context: Context, accountKey: UserKey?, user: ParcelableUser): Promise<ShortcutInfoCompat, Exception> { val holder = DependencyHolder.get(context) val preferences = holder.preferences val userColorNameManager = holder.userColorNameManager val launchIntent = IntentUtils.userMediaTimeline(accountKey, user.key, user.screen_name, profileUrl = user.extras?.statusnet_profile_url) val builder = ShortcutInfoCompat.Builder(context, "$accountKey:user-media-timeline:${user.key}") builder.setIntent(launchIntent) builder.setShortLabel(userColorNameManager.getDisplayName(user, preferences[nameFirstKey])) builder.setIcon(IconCompat.createWithResource(context, R.mipmap.ic_shortcut_gallery)) return Promise.of(builder.build()) } fun userListTimeline(context: Context, accountKey: UserKey?, list: ParcelableUserList): Promise<ShortcutInfoCompat, Exception> { val launchIntent = IntentUtils.userListTimeline(accountKey, list.id, list.user_key, list.user_screen_name, list.name) val builder = ShortcutInfoCompat.Builder(context, "$accountKey:user-list-timeline:${list.id}") builder.setIntent(launchIntent) builder.setShortLabel(list.name) builder.setIcon(IconCompat.createWithResource(context, R.mipmap.ic_shortcut_list)) return Promise.of(builder.build()) } inline fun performCreation(fragment: BaseFragment, createPromise: () -> Promise<ShortcutInfoCompat, Exception>) { if (!ShortcutManagerCompat.isRequestPinShortcutSupported(fragment.context)) return val promise = fragment.showProgressDialog("create_shortcut") .and(createPromise()) val weakThis = WeakReference(fragment) promise.successUi { (_, shortcut) -> val f = weakThis.get() ?: return@successUi ShortcutManagerCompat.requestPinShortcut(f.context, shortcut, null) }.alwaysUi { val f = weakThis.get() ?: return@alwaysUi f.dismissProgressDialog("create_shortcut") } } private fun Drawable.toProfileImageIcon(context: Context): IconCompat { if (useAdaptiveIcon) { val density = context.resources.displayMetrics.density val adaptiveIconSize = Math.round(adaptiveIconSizeDp * density) val adaptiveIconOuterSides = Math.round(adaptiveIconOuterSidesDp * density) val bitmap = Bitmap.createBitmap(adaptiveIconSize, adaptiveIconSize, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) setBounds(adaptiveIconOuterSides, adaptiveIconOuterSides, adaptiveIconSize - adaptiveIconOuterSides, adaptiveIconSize - adaptiveIconOuterSides) draw(canvas) return IconCompat.createWithAdaptiveBitmap(bitmap) } else { val bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) setBounds(0, 0, bitmap.width, bitmap.height) draw(canvas) return IconCompat.createWithBitmap(bitmap) } } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/shortcut/ShortcutCreator.kt
2741282390
package org.wikipedia.edit.richtext import android.content.Context import android.graphics.Color import android.graphics.Typeface import android.os.Build import androidx.annotation.RequiresApi import androidx.core.content.ContextCompat import org.wikipedia.R import org.wikipedia.util.ResourceUtil.getThemedColor enum class SyntaxRuleStyle { TEMPLATE { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return ColorSpanEx(getThemedColor(ctx, R.attr.secondary_text_color), Color.TRANSPARENT, spanStart, syntaxItem) } }, INTERNAL_LINK { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return ColorSpanEx(getThemedColor(ctx, R.attr.colorAccent), Color.TRANSPARENT, spanStart, syntaxItem) } }, EXTERNAL_LINK { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return ColorSpanEx(getThemedColor(ctx, R.attr.colorAccent), Color.TRANSPARENT, spanStart, syntaxItem) } }, REF { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return ColorSpanEx(getThemedColor(ctx, R.attr.green_highlight_color), Color.TRANSPARENT, spanStart, syntaxItem) } }, BOLD { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return StyleSpanEx(Typeface.BOLD, spanStart, syntaxItem) } }, ITALIC { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return StyleSpanEx(Typeface.ITALIC, spanStart, syntaxItem) } }, UNDERLINE { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return UnderlineSpanEx(spanStart, syntaxItem) } }, STRIKETHROUGH { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return StrikethroughSpanEx(spanStart, syntaxItem) } }, TEXT_LARGE { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return RelativeSizeSpanEx(1.2f, spanStart, syntaxItem) } }, TEXT_SMALL { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return RelativeSizeSpanEx(0.8f, spanStart, syntaxItem) } }, CODE { @RequiresApi(Build.VERSION_CODES.P) override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return TypefaceSpanEx(Typeface.MONOSPACE, spanStart, syntaxItem) } }, SUPERSCRIPT { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return SuperscriptSpanEx(spanStart, syntaxItem) } }, SUBSCRIPT { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return SubscriptSpanEx(spanStart, syntaxItem) } }, HEADING_LARGE { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return RelativeSizeSpanEx(1.3f, spanStart, syntaxItem) } }, HEADING_MEDIUM { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return RelativeSizeSpanEx(1.2f, spanStart, syntaxItem) } }, HEADING_SMALL { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return RelativeSizeSpanEx(1.1f, spanStart, syntaxItem) } }, SEARCH_MATCHES { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return ColorSpanEx(Color.BLACK, ContextCompat.getColor(ctx, R.color.find_in_page), spanStart, syntaxItem) } }, SEARCH_MATCH_SELECTED { override fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents { return ColorSpanEx(Color.BLACK, ContextCompat.getColor(ctx, R.color.find_in_page_active), spanStart, syntaxItem) } }; abstract fun createSpan(ctx: Context, spanStart: Int, syntaxItem: SyntaxRule): SpanExtents }
app/src/main/java/org/wikipedia/edit/richtext/SyntaxRuleStyle.kt
2590636027
package net.numa08.gochisou.data.model import org.parceler.Parcel import org.parceler.ParcelConstructor import org.parceler.ParcelProperty sealed class NavigationIdentifier(val name: String, val avatar: String, val loginProfile: LoginProfile) { @Parcel(Parcel.Serialization.BEAN) class PostNavigationIdentifier @ParcelConstructor constructor( @ParcelProperty("name") name: String, @ParcelProperty("avatar") avatar: String, @ParcelProperty("loginProfile") loginProfile: LoginProfile ) : NavigationIdentifier(name, avatar, loginProfile) @Parcel(Parcel.Serialization.BEAN) class PostDetailNavigationIdentifier @ParcelConstructor constructor( @ParcelProperty("name") name: String, @ParcelProperty("avatar") avatar: String, @ParcelProperty("loginProfile") loginProfile: LoginProfile, @ParcelProperty("fullName") val fullName: String ) : NavigationIdentifier(name, avatar, loginProfile) { override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false if (!super.equals(other)) return false other as PostDetailNavigationIdentifier if (fullName != other.fullName) return false return true } override fun hashCode(): Int { var result = super.hashCode() result += 31 * result + fullName.hashCode() return result } override fun toString(): String{ return "PostDetailNavigationIdentifier(fullName='$fullName')" } } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as NavigationIdentifier if (name != other.name) return false if (avatar != other.avatar) return false if (loginProfile != other.loginProfile) return false return true } override fun hashCode(): Int { var result = name.hashCode() result += 31 * result + avatar.hashCode() result += 31 * result + loginProfile.hashCode() return result } override fun toString(): String{ return "NavigationIdentifier(name='$name', avatar='$avatar', loginProfile=$loginProfile)" } }
app/src/main/java/net/numa08/gochisou/data/model/NavigationIdentifier.kt
3722572198
package com.stripe.example.activity import android.os.Bundle import androidx.activity.compose.setContent import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material.LinearProgressIndicator import androidx.compose.material.Scaffold import androidx.compose.material.ScaffoldState import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import com.stripe.android.googlepaylauncher.GooglePayEnvironment import com.stripe.android.googlepaylauncher.GooglePayLauncher import kotlinx.coroutines.launch class GooglePayLauncherComposeActivity : StripeIntentActivity() { private val googlePayConfig = GooglePayLauncher.Config( environment = GooglePayEnvironment.Test, merchantCountryCode = COUNTRY_CODE, merchantName = "Widget Store", billingAddressConfig = GooglePayLauncher.BillingAddressConfig( isRequired = true, format = GooglePayLauncher.BillingAddressConfig.Format.Full, isPhoneNumberRequired = false ), existingPaymentMethodRequired = false ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { GooglePayLauncherScreen() } } @Composable private fun GooglePayLauncherScreen() { val scaffoldState = rememberScaffoldState() val scope = rememberCoroutineScope() var clientSecret by rememberSaveable { mutableStateOf("") } var googlePayReady by rememberSaveable { mutableStateOf<Boolean?>(null) } var completed by rememberSaveable { mutableStateOf(false) } LaunchedEffect(Unit) { if (clientSecret.isBlank()) { viewModel.createPaymentIntent(COUNTRY_CODE).observe( this@GooglePayLauncherComposeActivity ) { result -> result.fold( onSuccess = { json -> clientSecret = json.getString("secret") }, onFailure = { error -> scope.launch { scaffoldState.snackbarHostState.showSnackbar( "Could not create PaymentIntent. ${error.message}" ) } completed = true } ) } } } val googlePayLauncher = GooglePayLauncher.rememberLauncher( config = googlePayConfig, readyCallback = { ready -> if (googlePayReady == null) { googlePayReady = ready if (!ready) { completed = true } scope.launch { scaffoldState.snackbarHostState.showSnackbar("Google Pay ready? $ready") } } }, resultCallback = { result -> when (result) { GooglePayLauncher.Result.Completed -> { "Successfully collected payment." } GooglePayLauncher.Result.Canceled -> { "Customer cancelled Google Pay." } is GooglePayLauncher.Result.Failed -> { "Google Pay failed. ${result.error.message}" } }.let { scope.launch { scaffoldState.snackbarHostState.showSnackbar(it) completed = true } } } ) GooglePayLauncherScreen( scaffoldState = scaffoldState, clientSecret = clientSecret, googlePayReady = googlePayReady, completed = completed, onLaunchGooglePay = { googlePayLauncher.presentForPaymentIntent(it) } ) } @Composable private fun GooglePayLauncherScreen( scaffoldState: ScaffoldState, clientSecret: String, googlePayReady: Boolean?, completed: Boolean, onLaunchGooglePay: (String) -> Unit ) { Scaffold(scaffoldState = scaffoldState) { Column(Modifier.fillMaxWidth()) { if (googlePayReady == null || clientSecret.isBlank()) { LinearProgressIndicator(Modifier.fillMaxWidth()) } Spacer( Modifier .height(8.dp) .fillMaxWidth() ) AndroidView( factory = { context -> GooglePayButton(context) }, modifier = Modifier .wrapContentWidth() .clickable( enabled = googlePayReady == true && clientSecret.isNotBlank() && !completed, onClick = { onLaunchGooglePay(clientSecret) } ) ) } } } private companion object { private const val COUNTRY_CODE = "US" } }
example/src/main/java/com/stripe/example/activity/GooglePayLauncherComposeActivity.kt
547899499
package com.stripe.android.view import android.content.Intent import android.net.Uri import android.webkit.URLUtil import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import androidx.annotation.VisibleForTesting import androidx.lifecycle.MutableLiveData import com.stripe.android.core.Logger import com.stripe.android.payments.DefaultReturnUrl internal class PaymentAuthWebViewClient( private val logger: Logger, private val isPageLoaded: MutableLiveData<Boolean>, private val clientSecret: String, returnUrl: String?, private val activityStarter: (Intent) -> Unit, private val activityFinisher: (Throwable?) -> Unit ) : WebViewClient() { // user-specified return URL private val userReturnUri: Uri? = returnUrl?.let { Uri.parse(it) } var completionUrlParam: String? = null private set internal var hasLoadedBlank: Boolean = false override fun onPageFinished(view: WebView, url: String?) { logger.debug("PaymentAuthWebViewClient#onPageFinished() - $url") super.onPageFinished(view, url) if (!hasLoadedBlank) { // hide the progress bar here because doing it in `onPageCommitVisible()` // potentially causes a crash hideProgressBar() } if (url != null && isCompletionUrl(url)) { logger.debug("$url is a completion URL") onAuthCompleted() } } private fun hideProgressBar() { logger.debug("PaymentAuthWebViewClient#hideProgressBar()") isPageLoaded.value = true } override fun shouldOverrideUrlLoading( view: WebView, request: WebResourceRequest ): Boolean { val url = request.url logger.debug("PaymentAuthWebViewClient#shouldOverrideUrlLoading(): $url") updateCompletionUrl(url) return if (isReturnUrl(url)) { logger.debug("PaymentAuthWebViewClient#shouldOverrideUrlLoading() - handle return URL") onAuthCompleted() true } else if ("intent".equals(url.scheme, ignoreCase = true)) { openIntentScheme(url) true } else if (!URLUtil.isNetworkUrl(url.toString())) { // Non-network URLs are likely deep-links into banking apps. If the deep-link can be // opened via an Intent, start it. Otherwise, stop the authentication attempt. openIntent( Intent(Intent.ACTION_VIEW, url) ) true } else { super.shouldOverrideUrlLoading(view, request) } } private fun openIntentScheme(uri: Uri) { logger.debug("PaymentAuthWebViewClient#openIntentScheme()") runCatching { openIntent( Intent.parseUri(uri.toString(), Intent.URI_INTENT_SCHEME) ) }.onFailure { error -> logger.error("Failed to start Intent.", error) onAuthCompleted(error) } } /** * See https://developer.android.com/training/basics/intents/package-visibility-use-cases * for more details on app-to-app interaction. */ private fun openIntent( intent: Intent ) { logger.debug("PaymentAuthWebViewClient#openIntent()") runCatching { activityStarter(intent) }.onFailure { error -> logger.error("Failed to start Intent.", error) if (intent.scheme != "alipays") { // complete auth if the deep-link can't be opened unless it is Alipay. // The Alipay web view tries to open the Alipay app as soon as it is opened // irrespective of whether or not the app is installed. // If this intent fails to resolve, we should still let the user // continue on the mobile site. onAuthCompleted(error) } } } private fun updateCompletionUrl(uri: Uri) { logger.debug("PaymentAuthWebViewClient#updateCompletionUrl()") val returnUrlParam = if (isAuthenticateUrl(uri.toString())) { uri.getQueryParameter(PARAM_RETURN_URL) } else { null } if (!returnUrlParam.isNullOrBlank()) { completionUrlParam = returnUrlParam } } private fun isReturnUrl(uri: Uri): Boolean { logger.debug("PaymentAuthWebViewClient#isReturnUrl()") when { isPredefinedReturnUrl(uri) -> return true // If the `userReturnUri` is known, look for URIs that match it. userReturnUri != null -> return userReturnUri.scheme != null && userReturnUri.scheme == uri.scheme && userReturnUri.host != null && userReturnUri.host == uri.host else -> { // Skip opaque (i.e. non-hierarchical) URIs if (uri.isOpaque) { return false } // If the `userReturnUri` is unknown, look for URIs that contain a // `payment_intent_client_secret` or `setup_intent_client_secret` // query parameter, and check if its values matches the given `clientSecret` // as a query parameter. val paramNames = uri.queryParameterNames val clientSecret = when { paramNames.contains(PARAM_PAYMENT_CLIENT_SECRET) -> uri.getQueryParameter(PARAM_PAYMENT_CLIENT_SECRET) paramNames.contains(PARAM_SETUP_CLIENT_SECRET) -> uri.getQueryParameter(PARAM_SETUP_CLIENT_SECRET) else -> null } return this.clientSecret == clientSecret } } } // pre-defined return URLs private fun isPredefinedReturnUrl(uri: Uri): Boolean { return "stripejs://use_stripe_sdk/return_url" == uri.toString() || uri.toString().startsWith(DefaultReturnUrl.PREFIX) } /** * Invoked when authentication flow has completed, whether succeeded or failed. */ private fun onAuthCompleted( error: Throwable? = null ) { logger.debug("PaymentAuthWebViewClient#onAuthCompleted()") activityFinisher(error) } internal companion object { internal const val PARAM_PAYMENT_CLIENT_SECRET = "payment_intent_client_secret" internal const val PARAM_SETUP_CLIENT_SECRET = "setup_intent_client_secret" private val AUTHENTICATE_URLS = setOf( "https://hooks.stripe.com/three_d_secure/authenticate" ) private val COMPLETION_URLS = setOf( "https://hooks.stripe.com/redirect/complete/", "https://hooks.stripe.com/3d_secure/complete/", "https://hooks.stripe.com/3d_secure_2/hosted/complete" ) private const val PARAM_RETURN_URL = "return_url" internal const val BLANK_PAGE = "about:blank" @VisibleForTesting internal fun isCompletionUrl( url: String ): Boolean { return COMPLETION_URLS.any(url::startsWith) } private fun isAuthenticateUrl( url: String ): Boolean { return AUTHENTICATE_URLS.any(url::startsWith) } } }
payments-core/src/main/java/com/stripe/android/view/PaymentAuthWebViewClient.kt
444260449
package com.stripe.android.cards import com.stripe.android.model.AccountRange import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine internal class DefaultCardAccountRangeRepository( private val inMemorySource: CardAccountRangeSource, private val remoteSource: CardAccountRangeSource, private val staticSource: CardAccountRangeSource, private val store: CardAccountRangeStore ) : CardAccountRangeRepository { override suspend fun getAccountRange( cardNumber: CardNumber.Unvalidated ): AccountRange? { return cardNumber.bin?.let { bin -> if (store.contains(bin)) { inMemorySource.getAccountRange(cardNumber) } else { remoteSource.getAccountRange(cardNumber) } ?: staticSource.getAccountRange(cardNumber) } } override val loading: Flow<Boolean> = combine( listOf( inMemorySource.loading, remoteSource.loading, staticSource.loading ) ) { loading -> // emit true if any of the sources are loading data loading.any { it } } }
payments-core/src/main/java/com/stripe/android/cards/DefaultCardAccountRangeRepository.kt
2287905309
package com.stripe.android.core.model.parsers import androidx.annotation.RestrictTo import com.stripe.android.core.model.StripeModel import org.json.JSONArray import org.json.JSONObject @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) interface ModelJsonParser<out ModelType : StripeModel> { fun parse(json: JSONObject): ModelType? @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) companion object { fun jsonArrayToList(jsonArray: JSONArray?): List<String> { return jsonArray?.let { (0 until jsonArray.length()).map { jsonArray.getString(it) } } ?: emptyList() } } }
stripe-core/src/main/java/com/stripe/android/core/model/parsers/ModelJsonParser.kt
1735329413
package com.stripe.android.ui.core.elements import androidx.annotation.RestrictTo import com.stripe.android.ui.core.forms.FormFieldEntry import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) data class EmptyFormElement( override val identifier: IdentifierSpec = IdentifierSpec.Generic("empty_form"), override val controller: Controller? = null ) : FormElement() { override fun getFormFieldValueFlow(): Flow<List<Pair<IdentifierSpec, FormFieldEntry>>> = MutableStateFlow(emptyList()) }
payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/EmptyFormElement.kt
432407872
package au.com.codeka.warworlds.client.concurrency import au.com.codeka.warworlds.client.concurrency.RunnableTask.* import java.util.* import java.util.concurrent.ThreadPoolExecutor /** * This is a class for running tasks on various threads. You can run a task on any thread defined * in [Threads]. */ class TaskRunner { val backgroundExecutor: ThreadPoolExecutor private val timer: Timer /** * Run the given [Runnable] on the given [Threads]. * * @return A [Task] that you can use to chain further tasks after this one has finished. */ fun runTask(runnable: Runnable?, thread: Threads): Task<*, *> { return runTask(RunnableTask<Void?, Void>(this, runnable, thread), null) } /** * Run the given [RunnableTask.RunnableP] on the given [Threads]. * * @return A [Task] that you can use to chain further tasks after this one has finished. */ fun <P> runTask(runnable: RunnableP<P>?, thread: Threads): Task<*, *> { return runTask(RunnableTask<P, Void>(this, runnable, thread), null) } /** * Run the given [RunnableTask.RunnableR] on the given [Threads]. * * @return A [Task] that you can use to chain further tasks after this one has finished. */ fun <R> runTask(runnable: RunnableR<R>?, thread: Threads): Task<*, *> { return runTask(RunnableTask<Void?, R>(this, runnable, thread), null) } /** * Run the given [RunnableTask.RunnablePR] on the given [Threads]. * * @return A [Task] that you can use to chain further tasks after this one has finished. */ fun <P, R> runTask(runnable: RunnablePR<P, R>?, thread: Threads): Task<*, *> { return runTask(RunnableTask(this, runnable, thread), null) } fun <P> runTask(task: Task<P, *>, param: P?): Task<*, *> { task.run(param) return task } /** * Runs the given GmsCore [com.google.android.gms.tasks.Task], and returns a [Task] * that you can then use to chain other tasks, etc. * * @param gmsTask The GmsCore task to run. * @param <R> The type of result to expect from the GmsCore task. * @return A [Task] that you can use to chain callbacks. </R> */ fun <R> runTask(gmsTask: com.google.android.gms.tasks.Task<R>): Task<Void, R> { return GmsTask(this, gmsTask) } /** Run a task after the given delay. */ fun runTask(runnable: Runnable?, thread: Threads, delayMs: Long) { if (delayMs == 0L) { runTask(runnable, thread) } else { timer.schedule(object : TimerTask() { override fun run() { runTask(runnable, thread) } }, delayMs) } } init { val backgroundThreadPool = ThreadPool( Threads.BACKGROUND, 750 /* maxQueuedItems */, 5 /* minThreads */, 20 /* maxThreads */, 1000 /* keepAliveMs */) backgroundExecutor = backgroundThreadPool.executor Threads.BACKGROUND.setThreadPool(backgroundThreadPool) timer = Timer("Timer") } }
client/src/main/kotlin/au/com/codeka/warworlds/client/concurrency/TaskRunner.kt
2070205170
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.integration.extensions import android.content.Context import android.graphics.ImageFormat import android.graphics.SurfaceTexture import android.hardware.camera2.CameraCaptureSession import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CameraDevice import android.hardware.camera2.CameraManager import android.hardware.camera2.CaptureRequest import android.hardware.camera2.params.OutputConfiguration import android.hardware.camera2.params.SessionConfiguration import android.media.ImageReader import android.util.Size import android.view.Surface import androidx.annotation.RequiresApi import androidx.camera.camera2.internal.compat.params.SessionConfigurationCompat import androidx.camera.camera2.interop.Camera2CameraInfo import androidx.camera.core.impl.utils.executor.CameraXExecutors import androidx.camera.extensions.ExtensionsManager import androidx.camera.extensions.impl.advanced.AdvancedExtenderImpl import androidx.camera.extensions.impl.advanced.Camera2OutputConfigImpl import androidx.camera.extensions.impl.advanced.Camera2SessionConfigImpl import androidx.camera.extensions.impl.advanced.ImageReaderOutputConfigImpl import androidx.camera.extensions.impl.advanced.MultiResolutionImageReaderOutputConfigImpl import androidx.camera.extensions.impl.advanced.OutputSurfaceImpl import androidx.camera.extensions.impl.advanced.SurfaceOutputConfigImpl import androidx.camera.extensions.internal.ExtensionVersion import androidx.camera.extensions.internal.Version import androidx.camera.integration.extensions.util.CameraXExtensionsTestUtil import androidx.camera.integration.extensions.utils.CameraSelectorUtil import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.testing.fakes.FakeLifecycleOwner import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import java.util.concurrent.TimeUnit import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.junit.Assume import org.junit.Assume.assumeTrue @RequiresApi(28) class AdvancedExtenderValidation( private val cameraId: String, private val extensionMode: Int ) { private val context = ApplicationProvider.getApplicationContext<Context>() private lateinit var cameraProvider: ProcessCameraProvider private lateinit var extensionsManager: ExtensionsManager private lateinit var cameraCharacteristicsMap: Map<String, CameraCharacteristics> private lateinit var advancedImpl: AdvancedExtenderImpl fun setUp(): Unit = runBlocking { cameraProvider = ProcessCameraProvider.getInstance(context)[10000, TimeUnit.MILLISECONDS] extensionsManager = ExtensionsManager.getInstanceAsync( context, cameraProvider )[10000, TimeUnit.MILLISECONDS] assumeTrue(CameraXExtensionsTestUtil.isAdvancedExtenderImplemented()) val baseCameraSelector = CameraSelectorUtil.createCameraSelectorById(cameraId) assumeTrue(extensionsManager.isExtensionAvailable(baseCameraSelector, extensionMode)) val extensionCameraSelector = extensionsManager.getExtensionEnabledCameraSelector( baseCameraSelector, extensionMode ) val cameraInfo = withContext(Dispatchers.Main) { cameraProvider.bindToLifecycle(FakeLifecycleOwner(), extensionCameraSelector).cameraInfo } cameraCharacteristicsMap = Camera2CameraInfo.from(cameraInfo).cameraCharacteristicsMap advancedImpl = CameraXExtensionsTestUtil .createAdvancedExtenderImpl(extensionMode, cameraId, cameraInfo) } private val teardownFunctions = mutableListOf<() -> Unit>() // Adding block to be invoked when tearing down. The last added will be invoked the first. private fun addTearDown(teardown: () -> Unit) { synchronized(teardownFunctions) { teardownFunctions.add(0, teardown) // added to the head } } fun tearDown(): Unit = runBlocking { synchronized(teardownFunctions) { for (teardownFunction in teardownFunctions) { teardownFunction() } teardownFunctions.clear() } withContext(Dispatchers.Main) { extensionsManager.shutdown()[10000, TimeUnit.MILLISECONDS] cameraProvider.shutdown()[10000, TimeUnit.MILLISECONDS] } } // Test fun getSupportedPreviewOutputResolutions_returnValidData() { val map = advancedImpl.getSupportedPreviewOutputResolutions(cameraId) assertThat(map[ImageFormat.PRIVATE]).isNotEmpty() } // Test fun getSupportedCaptureOutputResolutions_returnValidData() { val map = advancedImpl.getSupportedCaptureOutputResolutions(cameraId) assertThat(map[ImageFormat.JPEG]).isNotEmpty() assertThat(map[ImageFormat.YUV_420_888]).isNotEmpty() } // Test fun getAvailableCaptureRequestKeys_existAfter1_3() { assumeTrue(ExtensionVersion.getRuntimeVersion()!! >= Version.VERSION_1_3) advancedImpl.getAvailableCaptureRequestKeys() } // Test fun getAvailableCaptureResultKeys_existAfter1_3() { assumeTrue(ExtensionVersion.getRuntimeVersion()!! >= Version.VERSION_1_3) advancedImpl.getAvailableCaptureResultKeys() } enum class SizeCategory { MAXIMUM, MEDIAN, MINIMUM } private fun createPreviewOutput( impl: AdvancedExtenderImpl, sizeCategory: SizeCategory ): OutputSurfaceImpl { val previewSizeMap = impl.getSupportedPreviewOutputResolutions(cameraId) assertThat(previewSizeMap[ImageFormat.PRIVATE]).isNotEmpty() val previewSizes = previewSizeMap[ImageFormat.PRIVATE]!! val previewSize = getSizeByClass(previewSizes, sizeCategory) val surfaceTexture = SurfaceTexture(0) surfaceTexture.setDefaultBufferSize(previewSize.width, previewSize.height) val previewSurface = Surface(surfaceTexture) addTearDown { surfaceTexture.release() } return OutputSurface(previewSurface, previewSize, ImageFormat.PRIVATE) } private fun createCaptureOutput( impl: AdvancedExtenderImpl, sizeCategory: SizeCategory ): OutputSurfaceImpl { val captureSizeMap = impl.getSupportedCaptureOutputResolutions(cameraId) assertThat(captureSizeMap[ImageFormat.JPEG]).isNotEmpty() val captureSizes = captureSizeMap[ImageFormat.JPEG]!! var captureSize = getSizeByClass(captureSizes, sizeCategory) val imageReader = ImageReader.newInstance( captureSize.width, captureSize.height, ImageFormat.JPEG, 1 ) addTearDown { imageReader.close() } return OutputSurface(imageReader.surface, captureSize, ImageFormat.JPEG) } private fun getSizeByClass( sizes: List<Size>, sizeCategory: SizeCategory ): Size { val sortedList = sizes.sortedByDescending { it.width * it.height } var size = when (sizeCategory) { SizeCategory.MAXIMUM -> { sortedList[0] } SizeCategory.MEDIAN -> { sortedList[sortedList.size / 2] } SizeCategory.MINIMUM -> { sortedList[sortedList.size - 1] } } return size } private fun createAnalysisOutput( impl: AdvancedExtenderImpl, sizeCategory: SizeCategory ): OutputSurfaceImpl { val analysisSizes = impl.getSupportedYuvAnalysisResolutions(cameraId) assertThat(analysisSizes).isNotEmpty() var analysisSize = getSizeByClass(analysisSizes, sizeCategory) val imageReader = ImageReader.newInstance( analysisSize.width, analysisSize.height, ImageFormat.YUV_420_888, 1 ) addTearDown { imageReader.close() } return OutputSurface(imageReader.surface, analysisSize, ImageFormat.YUV_420_888) } // Test fun initSession_maxSize_canConfigureSession() = initSessionTest( previewOutputSizeCategory = SizeCategory.MAXIMUM, captureOutputSizeCategory = SizeCategory.MAXIMUM ) // Test fun initSession_minSize_canConfigureSession() = initSessionTest( previewOutputSizeCategory = SizeCategory.MINIMUM, captureOutputSizeCategory = SizeCategory.MINIMUM ) // Test fun initSession_medianSize_canConfigureSession() = initSessionTest( previewOutputSizeCategory = SizeCategory.MEDIAN, captureOutputSizeCategory = SizeCategory.MEDIAN ) // Test fun initSessionWithAnalysis_maxSize_canConfigureSession() = initSessionTest( previewOutputSizeCategory = SizeCategory.MAXIMUM, captureOutputSizeCategory = SizeCategory.MAXIMUM, analysisOutputSizeCategory = SizeCategory.MAXIMUM ) // Test fun initSessionWithAnalysis_minSize_canConfigureSession() = initSessionTest( previewOutputSizeCategory = SizeCategory.MINIMUM, captureOutputSizeCategory = SizeCategory.MINIMUM, analysisOutputSizeCategory = SizeCategory.MINIMUM ) // Test fun initSessionWithAnalysis_medianSize_canConfigureSession() = initSessionTest( previewOutputSizeCategory = SizeCategory.MEDIAN, captureOutputSizeCategory = SizeCategory.MEDIAN, analysisOutputSizeCategory = SizeCategory.MEDIAN ) fun initSessionTest( previewOutputSizeCategory: SizeCategory, captureOutputSizeCategory: SizeCategory, analysisOutputSizeCategory: SizeCategory? = null ): Unit = runBlocking { if (analysisOutputSizeCategory != null) { Assume.assumeFalse( advancedImpl.getSupportedYuvAnalysisResolutions(cameraId).isNullOrEmpty() ) } val sessionProcessor = advancedImpl.createSessionProcessor() val previewOutput = createPreviewOutput(advancedImpl, previewOutputSizeCategory) val captureOutput = createCaptureOutput(advancedImpl, captureOutputSizeCategory) val analysisOutput = analysisOutputSizeCategory?.let { createAnalysisOutput(advancedImpl, analysisOutputSizeCategory) } addTearDown { sessionProcessor.deInitSession() } var camera2SessionConfigImpl = sessionProcessor.initSession( cameraId, cameraCharacteristicsMap, context, previewOutput, captureOutput, analysisOutput ) verifyCamera2SessionConfig(camera2SessionConfigImpl) } private class OutputSurface( private val surface: Surface, private val size: Size, private val imageFormat: Int ) : OutputSurfaceImpl { override fun getSurface() = surface override fun getSize() = size override fun getImageFormat() = imageFormat } private fun getOutputConfiguration( outputConfigImpl: Camera2OutputConfigImpl ): OutputConfiguration { var outputConfiguration: OutputConfiguration when (outputConfigImpl) { is SurfaceOutputConfigImpl -> { val surface = outputConfigImpl.surface outputConfiguration = OutputConfiguration(outputConfigImpl.surfaceGroupId, surface) } is ImageReaderOutputConfigImpl -> { val imageReader = ImageReader.newInstance( outputConfigImpl.size.width, outputConfigImpl.size.height, outputConfigImpl.imageFormat, outputConfigImpl.maxImages ) val surface = imageReader.surface addTearDown { imageReader.close() } outputConfiguration = OutputConfiguration(outputConfigImpl.surfaceGroupId, surface) } is MultiResolutionImageReaderOutputConfigImpl -> throw java.lang.UnsupportedOperationException( "MultiResolutionImageReaderOutputConfigImpl not supported" ) else -> throw java.lang.UnsupportedOperationException( "Output configuration type not supported" ) } if (outputConfigImpl.physicalCameraId != null) { outputConfiguration.setPhysicalCameraId(outputConfigImpl.physicalCameraId) } if (outputConfigImpl.surfaceSharingOutputConfigs != null) { for (surfaceSharingOutputConfig in outputConfigImpl.surfaceSharingOutputConfigs) { val sharingOutputConfiguration = getOutputConfiguration(surfaceSharingOutputConfig) outputConfiguration.addSurface(sharingOutputConfiguration.surface!!) outputConfiguration.enableSurfaceSharing() } } return outputConfiguration } private suspend fun openCameraDevice(cameraId: String): CameraDevice { val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager val deferred = CompletableDeferred<CameraDevice>() cameraManager.openCamera( cameraId, CameraXExecutors.ioExecutor(), object : CameraDevice.StateCallback() { override fun onOpened(cameraDevice: CameraDevice) { deferred.complete(cameraDevice) } override fun onClosed(camera: CameraDevice) { super.onClosed(camera) } override fun onDisconnected(cameraDevice: CameraDevice) { deferred.completeExceptionally(RuntimeException("Camera Disconnected")) } override fun onError(cameraDevice: CameraDevice, error: Int) { deferred.completeExceptionally( RuntimeException("Camera onError(error=$cameraDevice)") ) } }) return deferred.await() } private suspend fun openCaptureSession( cameraDevice: CameraDevice, camera2SessionConfig: Camera2SessionConfigImpl ): CameraCaptureSession { val outputConfigurationList = mutableListOf<OutputConfiguration>() for (outputConfig in camera2SessionConfig.outputConfigs) { val outputConfiguration = getOutputConfiguration(outputConfig) outputConfigurationList.add(outputConfiguration) } val sessionDeferred = CompletableDeferred<CameraCaptureSession>() val sessionConfiguration = SessionConfiguration( SessionConfigurationCompat.SESSION_REGULAR, outputConfigurationList, CameraXExecutors.ioExecutor(), object : CameraCaptureSession.StateCallback() { override fun onConfigured(session: CameraCaptureSession) { sessionDeferred.complete(session) } override fun onConfigureFailed(session: CameraCaptureSession) { sessionDeferred.completeExceptionally(RuntimeException("onConfigureFailed")) } override fun onReady(session: CameraCaptureSession) { } override fun onActive(session: CameraCaptureSession) { } override fun onCaptureQueueEmpty(session: CameraCaptureSession) { } override fun onClosed(session: CameraCaptureSession) { super.onClosed(session) } override fun onSurfacePrepared(session: CameraCaptureSession, surface: Surface) { super.onSurfacePrepared(session, surface) } } ) val requestBuilder = cameraDevice.createCaptureRequest( camera2SessionConfig.sessionTemplateId ) camera2SessionConfig.sessionParameters.forEach { (key, value) -> @Suppress("UNCHECKED_CAST") requestBuilder.set(key as CaptureRequest.Key<Any>, value) } sessionConfiguration.sessionParameters = requestBuilder.build() cameraDevice.createCaptureSession(sessionConfiguration) return sessionDeferred.await() } private suspend fun verifyCamera2SessionConfig(camera2SessionConfig: Camera2SessionConfigImpl) { val cameraDevice = openCameraDevice(cameraId) assertThat(cameraDevice).isNotNull() addTearDown { cameraDevice.close() } val captureSession = openCaptureSession(cameraDevice, camera2SessionConfig) assertThat(captureSession).isNotNull() addTearDown { captureSession.close() } } }
camera/integration-tests/extensionstestapp/src/androidTest/java/androidx/camera/integration/extensions/AdvancedExtenderValidation.kt
1950380816
package com.github.kittinunf.fuel import com.github.kittinunf.fuel.core.FuelManager import com.github.kittinunf.fuel.core.Method import com.github.kittinunf.fuel.core.extensions.cUrlString import com.github.kittinunf.fuel.core.interceptors.LogRequestAsCurlInterceptor import com.github.kittinunf.fuel.core.interceptors.LogRequestInterceptor import com.github.kittinunf.fuel.core.interceptors.LogResponseInterceptor import com.github.kittinunf.fuel.test.MockHttpTestCase import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.not import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.CoreMatchers.nullValue import org.junit.After import org.junit.Assert.assertThat import org.junit.Before import org.junit.Test import java.io.ByteArrayOutputStream import java.io.PrintStream import java.net.HttpURLConnection import org.hamcrest.CoreMatchers.`is` as isEqualTo class InterceptorTest : MockHttpTestCase() { private val outContent = ByteArrayOutputStream() private val errContent = ByteArrayOutputStream() private val originalOut = System.out private val originalErr = System.err @Before fun prepareStream() { System.setOut(PrintStream(outContent)) System.setErr(PrintStream(errContent)) } @After fun teardownStreams() { System.setOut(originalOut) System.setErr(originalErr) } @Test fun testWithNoInterceptor() { val httpRequest = mock.request() .withMethod(Method.GET.value) .withPath("/get") mock.chain(request = httpRequest, response = mock.reflect()) val manager = FuelManager() val (request, response, result) = manager.request(Method.GET, mock.path("get")).response() val (data, error) = result assertThat(request, notNullValue()) assertThat(response, notNullValue()) assertThat(error, nullValue()) assertThat(data, notNullValue()) assertThat("Expected request not to be logged", outContent.toString(), not(containsString(request.toString()))) assertThat("Expected response not to be logged", outContent.toString(), not(containsString(response.toString()))) assertThat(response.statusCode, isEqualTo(HttpURLConnection.HTTP_OK)) } @Test fun testWithLoggingRequestInterceptor() { val httpRequest = mock.request() .withMethod(Method.GET.value) .withPath("/get") mock.chain(request = httpRequest, response = mock.reflect()) val manager = FuelManager() manager.addRequestInterceptor(LogRequestInterceptor) val (request, response, result) = manager.request(Method.GET, mock.path("get")).response() val (data, error) = result assertThat(request, notNullValue()) assertThat(response, notNullValue()) assertThat(error, nullValue()) assertThat(data, notNullValue()) assertThat("Expected request to be logged", outContent.toString(), containsString(request.toString())) assertThat("Expected response not to be logged", outContent.toString(), not(containsString(response.toString()))) assertThat(response.statusCode, isEqualTo(HttpURLConnection.HTTP_OK)) manager.removeRequestInterceptor(LogRequestInterceptor) } @Test fun testWithLoggingResponseInterceptor() { val httpRequest = mock.request() .withMethod(Method.GET.value) .withPath("/get") mock.chain(request = httpRequest, response = mock.reflect()) val manager = FuelManager() manager.addResponseInterceptor(LogResponseInterceptor) val (request, response, result) = manager.request(Method.GET, mock.path("get")).response() val (data, error) = result assertThat(request, notNullValue()) assertThat(response, notNullValue()) assertThat(error, nullValue()) assertThat(data, notNullValue()) assertThat("Expected response to be logged", outContent.toString(), containsString(response.toString())) assertThat(response.statusCode, isEqualTo(HttpURLConnection.HTTP_OK)) manager.removeResponseInterceptor(LogResponseInterceptor) } @Test fun testWithResponseToString() { val httpRequest = mock.request() .withMethod(Method.GET.value) .withPath("/get") mock.chain(request = httpRequest, response = mock.reflect()) val manager = FuelManager() val (request, response, result) = manager.request(Method.GET, mock.path("get")).response() val (data, error) = result assertThat(request, notNullValue()) assertThat(response, notNullValue()) assertThat(error, nullValue()) assertThat(data, notNullValue()) assertThat(response.statusCode, isEqualTo(HttpURLConnection.HTTP_OK)) assertThat(response.toString(), containsString("Response :")) assertThat(response.toString(), containsString("Length :")) assertThat(response.toString(), containsString("Body :")) assertThat(response.toString(), containsString("Headers :")) } @Test fun testWithMultipleInterceptors() { val httpRequest = mock.request() .withMethod(Method.GET.value) .withPath("/get") mock.chain(request = httpRequest, response = mock.reflect()) val manager = FuelManager() var interceptorCalled = false fun <T> customLoggingInterceptor() = { next: (T) -> T -> { t: T -> println("1: $t") interceptorCalled = true next(t) } } manager.apply { addRequestInterceptor(LogRequestAsCurlInterceptor) addRequestInterceptor(customLoggingInterceptor()) } val (request, response, result) = manager.request(Method.GET, mock.path("get")).header(mapOf("User-Agent" to "Fuel")).response() val (data, error) = result assertThat(request, notNullValue()) assertThat(response, notNullValue()) assertThat(error, nullValue()) assertThat(data, notNullValue()) assertThat(response.statusCode, isEqualTo(HttpURLConnection.HTTP_OK)) assertThat("Expected request to be curl logged", outContent.toString(), containsString(request.cUrlString())) assertThat(interceptorCalled, isEqualTo(true)) } @Test fun testWithBreakingChainInterceptor() { val httpRequest = mock.request() .withMethod(Method.GET.value) .withPath("/get") mock.chain(request = httpRequest, response = mock.reflect()) val manager = FuelManager() var interceptorCalled = false @Suppress("RedundantLambdaArrow") fun <T> customLoggingBreakingInterceptor() = { _: (T) -> T -> { t: T -> println("1: $t") interceptorCalled = true // if next is not called, next Interceptor will not be called as well t } } var interceptorNotCalled = true fun <T> customLoggingInterceptor() = { next: (T) -> T -> { t: T -> println("1: $t") interceptorNotCalled = false next(t) } } manager.apply { addRequestInterceptor(LogRequestAsCurlInterceptor) addRequestInterceptor(customLoggingBreakingInterceptor()) addRequestInterceptor(customLoggingInterceptor()) } val (request, response, result) = manager.request(Method.GET, mock.path("get")).header(mapOf("User-Agent" to "Fuel")).response() val (data, error) = result assertThat(request, notNullValue()) assertThat(response, notNullValue()) assertThat(error, nullValue()) assertThat(data, notNullValue()) assertThat(response.statusCode, isEqualTo(HttpURLConnection.HTTP_OK)) assertThat(interceptorCalled, isEqualTo(true)) assertThat(interceptorNotCalled, isEqualTo(true)) } @Test fun testWithoutDefaultRedirectionInterceptor() { val firstRequest = mock.request() .withMethod(Method.GET.value) .withPath("/redirect") val firstResponse = mock.response() .withHeader("Location", mock.path("redirected")) .withStatusCode(HttpURLConnection.HTTP_MOVED_TEMP) mock.chain(request = firstRequest, response = firstResponse) val manager = FuelManager() manager.addRequestInterceptor(LogRequestAsCurlInterceptor) manager.removeAllResponseInterceptors() val (request, response, result) = manager.request(Method.GET, mock.path("redirect")).header(mapOf("User-Agent" to "Fuel")).response() val (data, error) = result assertThat(request, notNullValue()) assertThat(response, notNullValue()) assertThat(error, nullValue()) assertThat(data, notNullValue()) assertThat(response.statusCode, isEqualTo(HttpURLConnection.HTTP_MOVED_TEMP)) } @Test fun testHttpExceptionWithRemoveValidator() { val firstRequest = mock.request() .withMethod(Method.GET.value) .withPath("/invalid") val firstResponse = mock.response() .withStatusCode(418) // I'm a teapot mock.chain(request = firstRequest, response = firstResponse) val manager = FuelManager() val (request, response, result) = manager.request(Method.GET, mock.path("invalid")) .validate { true } .responseString() val (data, error) = result assertThat(request, notNullValue()) assertThat(response, notNullValue()) assertThat(error, nullValue()) assertThat(data, notNullValue()) assertThat(response.statusCode, isEqualTo(418)) } @Test fun failsIfRequestedResourceReturns404() { val firstRequest = mock.request() .withMethod(Method.GET.value) .withPath("/not-found") val firstResponse = mock.response() .withStatusCode(HttpURLConnection.HTTP_NOT_FOUND) mock.chain(request = firstRequest, response = firstResponse) val manager = FuelManager() val (_, _, result) = manager.request(Method.GET, mock.path("not-found")).response() val (data, error) = result assertThat(error, notNullValue()) assertThat(data, nullValue()) } @Test fun testGetNotModified() { val firstRequest = mock.request() .withMethod(Method.GET.value) .withPath("/not-modified") val firstResponse = mock.response() .withStatusCode(HttpURLConnection.HTTP_NOT_MODIFIED) mock.chain(request = firstRequest, response = firstResponse) val manager = FuelManager() val (_, _, result) = manager.request(Method.GET, mock.path("not-modified")).responseString() val (data, error) = result assertThat(data, notNullValue()) assertThat(error, nullValue()) } @Test fun testRemoveAllRequestInterceptors() { val firstRequest = mock.request() .withMethod(Method.GET.value) .withPath("/teapot") val firstResponse = mock.response() .withStatusCode(418) mock.chain(request = firstRequest, response = firstResponse) val manager = FuelManager() manager.removeAllRequestInterceptors() val (request, response, result) = manager.request(Method.GET, mock.path("teapot")).responseString() val (data, error) = result assertThat(request, notNullValue()) assertThat(response, notNullValue()) assertThat(error, notNullValue()) assertThat(data, nullValue()) assertThat(response.statusCode, isEqualTo(418)) } }
fuel/src/test/kotlin/com/github/kittinunf/fuel/InterceptorTest.kt
1295889671
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.work.impl.constraints.trackers import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.ConnectivityManager import android.net.ConnectivityManager.NetworkCallback import android.net.Network import android.net.NetworkCapabilities import android.os.Build import androidx.annotation.RequiresApi import androidx.annotation.RestrictTo import androidx.core.net.ConnectivityManagerCompat import androidx.work.Logger import androidx.work.impl.constraints.NetworkState import androidx.work.impl.utils.getActiveNetworkCompat import androidx.work.impl.utils.getNetworkCapabilitiesCompat import androidx.work.impl.utils.hasCapabilityCompat import androidx.work.impl.utils.registerDefaultNetworkCallbackCompat import androidx.work.impl.utils.taskexecutor.TaskExecutor import androidx.work.impl.utils.unregisterNetworkCallbackCompat /** * A [ConstraintTracker] for monitoring network state. * * * For API 24 and up: Network state is tracked using a registered [NetworkCallback] with * [ConnectivityManager.registerDefaultNetworkCallback], added in API 24. * * * For API 23 and below: Network state is tracked using a [android.content.BroadcastReceiver]. * Much less efficient than tracking with [NetworkCallback]s and [ConnectivityManager]. * * * Based on [android.app.job.JobScheduler]'s ConnectivityController on API 26. * {@see https://android.googlesource.com/platform/frameworks/base/+/oreo-release/services/core/java/com/android/server/job/controllers/ConnectivityController.java} * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun NetworkStateTracker( context: Context, taskExecutor: TaskExecutor ): ConstraintTracker<NetworkState> { // Based on requiring ConnectivityManager#registerDefaultNetworkCallback - added in API 24. return if (Build.VERSION.SDK_INT >= 24) { NetworkStateTracker24(context, taskExecutor) } else { NetworkStateTrackerPre24(context, taskExecutor) } } private val TAG = Logger.tagWithPrefix("NetworkStateTracker") internal val ConnectivityManager.isActiveNetworkValidated: Boolean get() = if (Build.VERSION.SDK_INT < 23) { false // NET_CAPABILITY_VALIDATED not available until API 23. Used on API 26+. } else try { val network = getActiveNetworkCompat() val capabilities = getNetworkCapabilitiesCompat(network) (capabilities?.hasCapabilityCompat(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) ?: false } catch (exception: SecurityException) { // b/163342798 Logger.get().error(TAG, "Unable to validate active network", exception) false } @Suppress("DEPRECATION") internal val ConnectivityManager.activeNetworkState: NetworkState get() { // Use getActiveNetworkInfo() instead of getNetworkInfo(network) because it can detect VPNs. val info = activeNetworkInfo val isConnected = info != null && info.isConnected val isValidated = isActiveNetworkValidated val isMetered = ConnectivityManagerCompat.isActiveNetworkMetered(this) val isNotRoaming = info != null && !info.isRoaming return NetworkState(isConnected, isValidated, isMetered, isNotRoaming) } // b/163342798 internal class NetworkStateTrackerPre24(context: Context, taskExecutor: TaskExecutor) : BroadcastReceiverConstraintTracker<NetworkState>(context, taskExecutor) { private val connectivityManager: ConnectivityManager = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager override fun onBroadcastReceive(intent: Intent) { @Suppress("DEPRECATION") if (intent.action == ConnectivityManager.CONNECTIVITY_ACTION) { Logger.get().debug(TAG, "Network broadcast received") state = connectivityManager.activeNetworkState } } @Suppress("DEPRECATION") override val intentFilter: IntentFilter get() = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) override val initialState: NetworkState get() = connectivityManager.activeNetworkState } @RequiresApi(24) internal class NetworkStateTracker24(context: Context, taskExecutor: TaskExecutor) : ConstraintTracker<NetworkState>(context, taskExecutor) { private val connectivityManager: ConnectivityManager = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager override val initialState: NetworkState get() = connectivityManager.activeNetworkState private val networkCallback = object : NetworkCallback() { override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) { // The Network parameter is unreliable when a VPN app is running - use active network. Logger.get().debug(TAG, "Network capabilities changed: $capabilities") state = connectivityManager.activeNetworkState } override fun onLost(network: Network) { Logger.get().debug(TAG, "Network connection lost") state = connectivityManager.activeNetworkState } } override fun startTracking() { try { Logger.get().debug(TAG, "Registering network callback") connectivityManager.registerDefaultNetworkCallbackCompat(networkCallback) } catch (e: IllegalArgumentException) { // Catching the exceptions since and moving on - this tracker is only used for // GreedyScheduler and there is nothing to be done about device-specific bugs. // IllegalStateException: Happening on NVIDIA Shield K1 Tablets. See b/136569342. // SecurityException: Happening on Solone W1450. See b/153246136. Logger.get().error(TAG, "Received exception while registering network callback", e) } catch (e: SecurityException) { Logger.get().error(TAG, "Received exception while registering network callback", e) } } override fun stopTracking() { try { Logger.get().debug(TAG, "Unregistering network callback") connectivityManager.unregisterNetworkCallbackCompat(networkCallback) } catch (e: IllegalArgumentException) { // Catching the exceptions since and moving on - this tracker is only used for // GreedyScheduler and there is nothing to be done about device-specific bugs. // IllegalStateException: Happening on NVIDIA Shield K1 Tablets. See b/136569342. // SecurityException: Happening on Solone W1450. See b/153246136. Logger.get().error(TAG, "Received exception while unregistering network callback", e) } catch (e: SecurityException) { Logger.get().error(TAG, "Received exception while unregistering network callback", e) } } }
work/work-runtime/src/main/java/androidx/work/impl/constraints/trackers/NetworkStateTracker.kt
2340347927
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.macros import com.intellij.util.SmartList data class MappedText(val text: String, val ranges: RangeMap) { companion object { val EMPTY: MappedText = MappedText("", RangeMap.EMPTY) fun single(text: String, srcOffset: Int): MappedText { return if (text.isNotEmpty()) { MappedText( text, RangeMap.from(SmartList(MappedTextRange(srcOffset, 0, text.length))) ) } else { EMPTY } } } } class MutableMappedText private constructor( private val sb: StringBuilder, private val ranges: MutableList<MappedTextRange> = mutableListOf() ) { constructor(capacity: Int) : this(StringBuilder(capacity)) val length: Int get() = sb.length val text: CharSequence get() = sb fun appendUnmapped(text: CharSequence) { sb.append(text) } fun appendMapped(text: CharSequence, srcOffset: Int) { if (text.isNotEmpty()) { ranges.mergeAdd(MappedTextRange(srcOffset, sb.length, text.length)) sb.append(text) } } fun toMappedText(): MappedText = MappedText(sb.toString(), RangeMap.from(SmartList(ranges))) override fun toString(): String { return sb.toString() } }
src/main/kotlin/org/rust/lang/core/macros/MappedText.kt
4071715180
package com.habitrpg.android.habitica.models import com.habitrpg.android.habitica.models.notifications.AchievementData import com.habitrpg.android.habitica.models.notifications.ChallengeWonData import com.habitrpg.android.habitica.models.notifications.FirstDropData import com.habitrpg.android.habitica.models.notifications.GroupTaskApprovedData import com.habitrpg.android.habitica.models.notifications.GroupTaskNeedsWorkData import com.habitrpg.android.habitica.models.notifications.GroupTaskRequiresApprovalData import com.habitrpg.android.habitica.models.notifications.GuildInvitationData import com.habitrpg.android.habitica.models.notifications.LoginIncentiveData import com.habitrpg.android.habitica.models.notifications.NewChatMessageData import com.habitrpg.android.habitica.models.notifications.NewStuffData import com.habitrpg.android.habitica.models.notifications.NotificationData import com.habitrpg.android.habitica.models.notifications.PartyInvitationData import com.habitrpg.android.habitica.models.notifications.QuestInvitationData import com.habitrpg.android.habitica.models.notifications.UnallocatedPointsData class Notification { enum class Type(val type: String) { // Notification types coming from the server LOGIN_INCENTIVE("LOGIN_INCENTIVE"), NEW_STUFF("NEW_STUFF"), NEW_CHAT_MESSAGE("NEW_CHAT_MESSAGE"), NEW_MYSTERY_ITEMS("NEW_MYSTERY_ITEMS"), GROUP_TASK_NEEDS_WORK("GROUP_TASK_NEEDS_WORK"), GROUP_TASK_APPROVED("GROUP_TASK_APPROVED"), GROUP_TASK_REQUIRES_APPROVAL("GROUP_TASK_REQUIRES_APPROVAL"), UNALLOCATED_STATS_POINTS("UNALLOCATED_STATS_POINTS"), WON_CHALLENGE("WON_CHALLENGE"), // Achievements ACHIEVEMENT_PARTY_UP("ACHIEVEMENT_PARTY_UP"), ACHIEVEMENT_PARTY_ON("ACHIEVEMENT_PARTY_ON"), ACHIEVEMENT_BEAST_MASTER("ACHIEVEMENT_BEAST_MASTER"), ACHIEVEMENT_MOUNT_MASTER("ACHIEVEMENT_MOUNT_MASTER"), ACHIEVEMENT_TRIAD_BINGO("ACHIEVEMENT_TRIAD_BINGO"), ACHIEVEMENT_GUILD_JOINED("GUILD_JOINED_ACHIEVEMENT"), ACHIEVEMENT_CHALLENGE_JOINED("CHALLENGE_JOINED_ACHIEVEMENT"), ACHIEVEMENT_INVITED_FRIEND("INVITED_FRIEND_ACHIEVEMENT"), ACHIEVEMENT_GENERIC("ACHIEVEMENT"), ACHIEVEMENT_ONBOARDING_COMPLETE("ONBOARDING_COMPLETE"), ACHIEVEMENT_ALL_YOUR_BASE("ACHIEVEMENT_ALL_YOUR_BASE"), ACHIEVEMENT_BACK_TO_BASICS("ACHIEVEMENT_BACK_TO_BASICS"), ACHIEVEMENT_JUST_ADD_WATER("ACHIEVEMENT_JUST_ADD_WATER"), ACHIEVEMENT_LOST_MASTERCLASSER("ACHIEVEMENT_LOST_MASTERCLASSER"), ACHIEVEMENT_MIND_OVER_MATTER("ACHIEVEMENT_MIND_OVER_MATTER"), ACHIEVEMENT_DUST_DEVIL("ACHIEVEMENT_DUST_DEVIL"), ACHIEVEMENT_ARID_AUTHORITY("ACHIEVEMENT_ARID_AUTHORITY"), ACHIEVEMENT_MONSTER_MAGUS("ACHIEVEMENT_MONSTER_MAGUS"), ACHIEVEMENT_UNDEAD_UNDERTAKER("ACHIEVEMENT_UNDEAD_UNDERTAKER"), ACHIEVEMENT_PRIMED_FOR_PAINTING("ACHIEVEMENT_PRIMED_FOR_PAINTING"), ACHIEVEMENT_PEARLY_PRO("ACHIEVEMENT_PEARLY_PRO"), ACHIEVEMENT_TICKLED_PINK("ACHIEVEMENT_TICKLED_PINK"), ACHIEVEMENT_ROSY_OUTLOOK("ACHIEVEMENT_ROSY_OUTLOOK"), ACHIEVEMENT_BUG_BONANZA("ACHIEVEMENT_BUG_BONANZA"), ACHIEVEMENT_BARE_NECESSITIES("ACHIEVEMENT_BARE_NECESSITIES"), ACHIEVEMENT_FRESHWATER_FRIENDS("ACHIEVEMENT_FRESHWATER_FRIENDS"), ACHIEVEMENT_GOOD_AS_GOLD("ACHIEVEMENT_GOOD_AS_GOLD"), ACHIEVEMENT_ALL_THAT_GLITTERS("ACHIEVEMENT_ALL_THAT_GLITTERS"), ACHIEVEMENT_BONE_COLLECTOR("ACHIEVEMENT_BONE_COLLECTOR"), ACHIEVEMENT_SKELETON_CREW("ACHIEVEMENT_SKELETON_CREW"), ACHIEVEMENT_SEEING_RED("ACHIEVEMENT_SEEING_RED"), ACHIEVEMENT_RED_LETTER_DAY("ACHIEVEMENT_RED_LETTER_DAY"), FIRST_DROP("FIRST_DROPS"), // Custom notification types (created by this app) GUILD_INVITATION("GUILD_INVITATION"), PARTY_INVITATION("PARTY_INVITATION"), QUEST_INVITATION("QUEST_INVITATION"), } var id: String = "" var type: String? = null var seen: Boolean? = null var data: NotificationData? = null fun getDataType(): java.lang.reflect.Type? { return when (type) { Type.LOGIN_INCENTIVE.type -> LoginIncentiveData::class.java Type.NEW_STUFF.type -> NewStuffData::class.java Type.NEW_CHAT_MESSAGE.type -> NewChatMessageData::class.java Type.GROUP_TASK_NEEDS_WORK.type -> GroupTaskNeedsWorkData::class.java Type.GROUP_TASK_APPROVED.type -> GroupTaskApprovedData::class.java Type.GROUP_TASK_REQUIRES_APPROVAL.type -> GroupTaskRequiresApprovalData::class.java Type.UNALLOCATED_STATS_POINTS.type -> UnallocatedPointsData::class.java Type.GUILD_INVITATION.type -> GuildInvitationData::class.java Type.PARTY_INVITATION.type -> PartyInvitationData::class.java Type.QUEST_INVITATION.type -> QuestInvitationData::class.java Type.FIRST_DROP.type -> FirstDropData::class.java Type.ACHIEVEMENT_GENERIC.type -> AchievementData::class.java Type.WON_CHALLENGE.type -> ChallengeWonData::class.java Type.ACHIEVEMENT_ALL_YOUR_BASE.type -> AchievementData::class.java Type.ACHIEVEMENT_BACK_TO_BASICS.type -> AchievementData::class.java Type.ACHIEVEMENT_JUST_ADD_WATER.type -> AchievementData::class.java Type.ACHIEVEMENT_LOST_MASTERCLASSER.type -> AchievementData::class.java Type.ACHIEVEMENT_MIND_OVER_MATTER.type -> AchievementData::class.java Type.ACHIEVEMENT_DUST_DEVIL.type -> AchievementData::class.java Type.ACHIEVEMENT_ARID_AUTHORITY.type -> AchievementData::class.java Type.ACHIEVEMENT_MONSTER_MAGUS.type -> AchievementData::class.java Type.ACHIEVEMENT_UNDEAD_UNDERTAKER.type -> AchievementData::class.java Type.ACHIEVEMENT_PRIMED_FOR_PAINTING.type -> AchievementData::class.java Type.ACHIEVEMENT_PEARLY_PRO.type -> AchievementData::class.java Type.ACHIEVEMENT_TICKLED_PINK.type -> AchievementData::class.java Type.ACHIEVEMENT_ROSY_OUTLOOK.type -> AchievementData::class.java Type.ACHIEVEMENT_BUG_BONANZA.type -> AchievementData::class.java Type.ACHIEVEMENT_BARE_NECESSITIES.type -> AchievementData::class.java Type.ACHIEVEMENT_FRESHWATER_FRIENDS.type -> AchievementData::class.java Type.ACHIEVEMENT_GOOD_AS_GOLD.type -> AchievementData::class.java Type.ACHIEVEMENT_ALL_THAT_GLITTERS.type -> AchievementData::class.java Type.ACHIEVEMENT_GOOD_AS_GOLD.type -> AchievementData::class.java Type.ACHIEVEMENT_BONE_COLLECTOR.type -> AchievementData::class.java Type.ACHIEVEMENT_SKELETON_CREW.type -> AchievementData::class.java Type.ACHIEVEMENT_SEEING_RED.type -> AchievementData::class.java Type.ACHIEVEMENT_RED_LETTER_DAY.type -> AchievementData::class.java else -> null } } val priority: Int get() { return when (type) { Type.NEW_STUFF.type -> 1 Type.GUILD_INVITATION.type -> 2 Type.PARTY_INVITATION.type -> 3 Type.UNALLOCATED_STATS_POINTS.type -> 4 Type.NEW_MYSTERY_ITEMS.type -> 5 Type.NEW_CHAT_MESSAGE.type -> 6 else -> 100 } } }
Habitica/src/main/java/com/habitrpg/android/habitica/models/Notification.kt
1703780492
fun (suspend () -> Unit).foo() { }
core/testdata/format/renderFunctionalTypeInParenthesisWhenItIsReceiver.kt
345567493