path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
gradlePlugin/src/main/kotlin/pw/binom/gradle/MogotExtension.kt
caffeine-mgn
223,796,620
false
null
package pw.binom.gradle import java.io.File open class MogotExtension { var assets: File? = null fun assets(file: File) { this.assets = file } }
6
Kotlin
0
4
e673acfcb20e2d62d8e68c43d395731bd9d9d882
166
mogot
Apache License 2.0
k5-compose/src/main/kotlin/K5.kt
CuriousNikhil
415,380,983
false
null
import androidx.compose.animation.core.withInfiniteAnimationFrameMillis import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.IntSize import androidx.compose.ui.window.Window import androidx.compose.ui.window.application import androidx.compose.ui.window.rememberWindowState /** * Builder construct for the K5-compose. * Can be called like, main() = k5 {...} * All the params passed are applied to a [Window] component * * @param size The size param for the size of window - [Size] * The size is taken in floats in order to perform canvas related operations easily on floats which includes the * dimension of window * @param title The title of the window. * The title is displayed in the windows's native border. * @param size The initial size of the window. * @param icon The icon for the window displayed on the system taskbar. * @param undecorated Removes the native window border if set to true. The default value is false. * @param resizable Makes the window resizable if is set to true and unresizable if is set to * false. The default value is true. * @param focusable Can window receive focus * @param alwaysOnTop Should window always be on top of another windows * @param onPreviewKeyEvent This callback is invoked when the user interacts with the hardware * keyboard. It gives ancestors of a focused component the chance to intercept a [KeyEvent]. * Return true to stop propagation of this event. If you return false, the key event will be * sent to this [onPreviewKeyEvent]'s child. If none of the children consume the event, * it will be sent back up to the root using the onKeyEvent callback. * @param onKeyEvent This callback is invoked when the user interacts with the hardware * keyboard. While implementing this callback, return true to stop propagation of this event. * If you return false, the key event will be sent to this [onKeyEvent]'s parent. */ fun k5( size: Size = Size(1000f, 1000f), title: String = "K5 Compose Playground", icon: Painter? = null, undecorated: Boolean = false, resizable: Boolean = false, enabled: Boolean = true, focusable: Boolean = true, alwaysOnTop: Boolean = false, onPreviewKeyEvent: (KeyEvent) -> Boolean = { false }, onKeyEvent: (KeyEvent) -> Boolean = { false }, init: K5.() -> Unit ) { K5( size, title, icon, undecorated, resizable, enabled, focusable, alwaysOnTop, onPreviewKeyEvent, onKeyEvent ).init() } class K5( val size: Size, val title: String, val icon: Painter?, val undecorated: Boolean, val resizable: Boolean, val enabled: Boolean, val focusable: Boolean, val alwaysOnTop: Boolean, val onPreviewKeyEvent: (KeyEvent) -> Boolean, val onKeyEvent: (KeyEvent) -> Boolean, ) { private var stopLoop = false /** * Call method to stop the looping of canvas * You can also call it to freeze the time frame for a canvas */ fun noLoop() { this.stopLoop = true } /** * Use this property to get the actual [k5] Playground size in Floats. Subtracting the 56f - which is the toolbar height of the window. * When the size of the window is set with `size` param in [k5] builder, it's applied to window and when * the canvas is rendered in the window with [Modifier.fillMaxSize] it takes whole window except the toolbar. * * TODO: Fix the dimensions for a given k5 playground considering density */ val dimensFloat = Size(size.width, size.height - 56f) /** * Use this property to get the actual [k5] Playground size in Ints */ val dimensInt = IntSize(size.width.toInt(), size.height.toInt() - 56) /** * Shows the canvas window and renders it for each frame repetitively. * Internally, this starts the Jetpack Compose Window and renders the [sketch] requested by user into the Jetpack Compose * [Canvas] Composable. The size of the [Canvas] will be same as the [size] passed in [k5] method by default. * One can change the canvas size and window size with the help of modifiers. * In order to keep the animation running (rendering canvas continuously), it requests to run the frame of animation in nanos. * All the [modifier] will be applied to the [Canvas]. * * @param modifier Jetpack compose [Modifier] * @param sketch drawScope - Compose canvas drawscope */ fun show(modifier: Modifier = Modifier.fillMaxSize(), sketch: (drawScope: DrawScope) -> Unit) { render(modifier, sketch) } /** * Starts the Jetpack Compose Window and renders the [sketch] requested by user into the Jetpack Compose * [Canvas] Composable. * * @param modifier - Jetpack compose [Modifier]. Will be applied to the [Canvas] * @param sketch - The content to be drawn on to [Canvas] */ private fun render(modifier: Modifier, sketch: (drawScope: DrawScope) -> Unit) = application { val (width, height) = with(LocalDensity.current) { Pair(size.width.toDp(), size.height.toDp()) } Window( onCloseRequest = ::exitApplication, state = rememberWindowState(width = width, height = height), title = title, icon = icon, undecorated = undecorated, resizable = resizable, enabled = enabled, focusable = focusable, alwaysOnTop = alwaysOnTop, onPreviewKeyEvent = onPreviewKeyEvent, onKeyEvent = onKeyEvent ) { // dt = change in time val dt = remember { mutableStateOf(0f) } // TODO : Show elapsed time and frames per second on toolbar of window var startTime = remember { mutableStateOf(0L) } val previousTime = remember { mutableStateOf(System.nanoTime()) } Canvas(modifier = Modifier.fillMaxSize().background(Color.Black).then(modifier)) { val stepFrame = dt.value sketch(this) } if (!stopLoop) { requestAnimationFrame(dt, previousTime) } } } /** * Run frame time with nanoseconds * @param dt - Change it time * @param previousTime - previous time to calculate change in time */ @Composable private fun requestAnimationFrame(dt: MutableState<Float>, previousTime: MutableState<Long>) { LaunchedEffect(Unit) { while (true) { withInfiniteAnimationFrameMillis { dt.value = ((it - previousTime.value) / 1E7).toFloat() previousTime.value = it } } } } }
1
Kotlin
6
99
106deec4165a44c3590c6c9ea335b97d29e54cf5
7,403
k5-compose
Apache License 2.0
app/src/main/java/com/mongodb/moodlogger/views/MoodDialog.kt
mongodb-developer
416,011,359
false
{"Kotlin": 16723}
package com.mongodb.moodlogger.views import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredWidth import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import com.mongodb.moodlogger.viewmodels.MoodDialogViewModel @Composable fun MoodDialog(viewModel: MoodDialogViewModel, onShowChange: (Boolean) -> Unit) { Dialog( onDismissRequest = { /*TODO*/ } ) { Surface( modifier = Modifier.requiredWidth(LocalConfiguration.current.screenWidthDp.dp * 0.96f), shape = RoundedCornerShape(8.dp), color = MaterialTheme.colors.background ) { Column(modifier = Modifier.padding(24.dp)) { Text( text = "Choose your mood", style = MaterialTheme.typography.h5, color = MaterialTheme.colors.onSurface, modifier = Modifier.padding( horizontal = 0.dp, vertical = 8.dp ) ) Spacer(modifier = Modifier.height(8.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { Button(onClick = { viewModel.onHappyButton() onShowChange(false) }) { Text(text = "😃") } Button(onClick = { viewModel.onNeutralButton() onShowChange(false) }) { Text(text = "😑") } Button(onClick = { viewModel.onSadButton() onShowChange(false) }) { Text(text = "🙁") } } } } } } // @Preview // @Composable // fun MoodDialogPreview() { // MoodLoggerTheme { // MoodDialog(viewModel = MoodDialogViewModel(), onShowChange = {}) // } // }
0
Kotlin
0
3
955d3bfab75bb307fad3d795baeab1a384de8721
2,847
MoodLoggerAndroid
Apache License 2.0
xnet_android/src/main/java/com/gfms/xnet_android/discovery/nearservice/NearAndroidImpl.kt
r3tr056
875,356,073
false
{"Kotlin": 382790, "C++": 177456, "C": 140193, "CMake": 3494}
package com.gfms.xnet_android.discovery.nearservice import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Handler import android.os.IBinder import android.os.Looper import com.gfms.xnet.xpeer.XPeer import java.net.InetAddress class NearAndroidImpl( private val mContext: Context, private val mListener: Near.NearListener private val mLooper: Looper, private val mxPeers: Set<XPeer>, private val mPort: Int): NearConnect { private var serverState: Boolean = false private var sendDataQueue: MutableList<ByteArray> = mutableListOf() private var sendDestQueue: MutableList<XPeer> = mutableListOf() private var sendJobQueue: MutableList<Long> = mutableListOf() private var clientServiceListener: TcpClientListener? = null private var serverServiceListener: TcpServerListener? = null private val clientConnection: ServiceConnection = object: ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { if (service is TcpClientService.TcpClientBinder) { service.setListener(getClientServiceListener(), Looper.myLooper()?:Looper.getMainLooper()) service.setPort(mPort) var candidateData: ByteArray? = null var candidateHost: XPeer? = null var jobId: Long = 0 while (sendDataQueue.isNotEmpty()) { synchronized(this@NearAndroidImpl) { if (sendDataQueue.isNotEmpty()) { candidateData = sendDataQueue.removeAt(0) candidateData = sendDataQueue.removeAt(0) jobId = sendJobQueue.removeAt(0) } } service.send(candidateData!!, candidateHost!!, jobId) } mContext.unbindService(this) } } override fun onServiceDisconnected(name: ComponentName?) { TODO("Not yet implemented") } } private fun getClientServiceListener(): TcpClientListener { if (clientServiceListener == null) { clientServiceListener = object : TcpClientListener { override fun onSendSuccess(jobId: Long) { Handler(mLooper).port { mListener.onSendFailure(jobId) } } override fun onSendFailure(jobId: Long, e: Throwable?) { Handler(mLooper).port { mListener.onSendFailure(e, jobId) } } } } return clientServiceListener!! } override fun send(bytes: ByteArray, xpeer: XPeer): Long { val jobId: Long = System.currentTimeMillis() synchronized(this@NearAndroidImpl) { sendDataQueue.add(bytes) sendDestQueue.add(xpeer) sendJobQueue.add(jobId) } val intent = Intent(mContext.applicationContext, TcpClientService::class.java) mContext.startService(intent) mContext.bindService(intent, clientConnection, Context.BIND_AUTO_CREATE) return jobId } private val startServerConnection = object: ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { if (service is TcpServerService.TcpServerBinder && serverState) { service.setListener(getServerServiceListener()) service.setPort(mPort) service.startServer() } } override fun onServiceDisconnected(name: ComponentName?) { TODO("Not yet implemented") } } private fun getServerServiceListener(): TcpServerListener { if (serverServiceListener == null) { serverServiceListener = object : TcpServerListener() { override fun onServerStartFailed(e: Throwable?) { Handler(mLooper).post { mListener.onStartListenFailure(e) } } override fun onReceive(bytes: ByteArray, inetAddress: InetAddress) { Handler(mLooper).post { mxPeers.forEach peerLoop@{ if (it.hostAddress == inetAddress.hostAddress) { mListener.onReceive(bytes, int) return @peerLoop } } } } } } return serverServiceListener!! } private val stopServerConnection = object: ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { if (service is TcpServerService.TcpServerBinder && !serverState) { service.stopServer() mContext.unbindService(this) mContext.unbindService(startServerConnection) } } override fun onServiceDisconnected(name: ComponentName?) { TODO("Not yet implemented") } } override fun stopReceiving(abortCurrentTransfers: Boolean) { if (serverState) { serverState = false val intent = Intent(mContext.applicationContext, TcpServerService::class.java) mContext.startService(intent) mContext.bindService(intent, stopServerConnection, Context.BIND_AUTO_CREATE) } } override val xpeers: Set<XPeer> = mxPeers override val isReceiving: Boolean = serverState }
0
Kotlin
0
0
d76c8c1f2c9a426354d88065f37c15e1c6a51b02
5,609
koinoor
MIT License
xnet_android/src/main/java/com/gfms/xnet_android/discovery/nearservice/NearAndroidImpl.kt
r3tr056
875,356,073
false
{"Kotlin": 382790, "C++": 177456, "C": 140193, "CMake": 3494}
package com.gfms.xnet_android.discovery.nearservice import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Handler import android.os.IBinder import android.os.Looper import com.gfms.xnet.xpeer.XPeer import java.net.InetAddress class NearAndroidImpl( private val mContext: Context, private val mListener: Near.NearListener private val mLooper: Looper, private val mxPeers: Set<XPeer>, private val mPort: Int): NearConnect { private var serverState: Boolean = false private var sendDataQueue: MutableList<ByteArray> = mutableListOf() private var sendDestQueue: MutableList<XPeer> = mutableListOf() private var sendJobQueue: MutableList<Long> = mutableListOf() private var clientServiceListener: TcpClientListener? = null private var serverServiceListener: TcpServerListener? = null private val clientConnection: ServiceConnection = object: ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { if (service is TcpClientService.TcpClientBinder) { service.setListener(getClientServiceListener(), Looper.myLooper()?:Looper.getMainLooper()) service.setPort(mPort) var candidateData: ByteArray? = null var candidateHost: XPeer? = null var jobId: Long = 0 while (sendDataQueue.isNotEmpty()) { synchronized(this@NearAndroidImpl) { if (sendDataQueue.isNotEmpty()) { candidateData = sendDataQueue.removeAt(0) candidateData = sendDataQueue.removeAt(0) jobId = sendJobQueue.removeAt(0) } } service.send(candidateData!!, candidateHost!!, jobId) } mContext.unbindService(this) } } override fun onServiceDisconnected(name: ComponentName?) { TODO("Not yet implemented") } } private fun getClientServiceListener(): TcpClientListener { if (clientServiceListener == null) { clientServiceListener = object : TcpClientListener { override fun onSendSuccess(jobId: Long) { Handler(mLooper).port { mListener.onSendFailure(jobId) } } override fun onSendFailure(jobId: Long, e: Throwable?) { Handler(mLooper).port { mListener.onSendFailure(e, jobId) } } } } return clientServiceListener!! } override fun send(bytes: ByteArray, xpeer: XPeer): Long { val jobId: Long = System.currentTimeMillis() synchronized(this@NearAndroidImpl) { sendDataQueue.add(bytes) sendDestQueue.add(xpeer) sendJobQueue.add(jobId) } val intent = Intent(mContext.applicationContext, TcpClientService::class.java) mContext.startService(intent) mContext.bindService(intent, clientConnection, Context.BIND_AUTO_CREATE) return jobId } private val startServerConnection = object: ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { if (service is TcpServerService.TcpServerBinder && serverState) { service.setListener(getServerServiceListener()) service.setPort(mPort) service.startServer() } } override fun onServiceDisconnected(name: ComponentName?) { TODO("Not yet implemented") } } private fun getServerServiceListener(): TcpServerListener { if (serverServiceListener == null) { serverServiceListener = object : TcpServerListener() { override fun onServerStartFailed(e: Throwable?) { Handler(mLooper).post { mListener.onStartListenFailure(e) } } override fun onReceive(bytes: ByteArray, inetAddress: InetAddress) { Handler(mLooper).post { mxPeers.forEach peerLoop@{ if (it.hostAddress == inetAddress.hostAddress) { mListener.onReceive(bytes, int) return @peerLoop } } } } } } return serverServiceListener!! } private val stopServerConnection = object: ServiceConnection { override fun onServiceConnected(name: ComponentName?, service: IBinder?) { if (service is TcpServerService.TcpServerBinder && !serverState) { service.stopServer() mContext.unbindService(this) mContext.unbindService(startServerConnection) } } override fun onServiceDisconnected(name: ComponentName?) { TODO("Not yet implemented") } } override fun stopReceiving(abortCurrentTransfers: Boolean) { if (serverState) { serverState = false val intent = Intent(mContext.applicationContext, TcpServerService::class.java) mContext.startService(intent) mContext.bindService(intent, stopServerConnection, Context.BIND_AUTO_CREATE) } } override val xpeers: Set<XPeer> = mxPeers override val isReceiving: Boolean = serverState }
0
Kotlin
0
0
d76c8c1f2c9a426354d88065f37c15e1c6a51b02
5,609
koinoor
MIT License
app/src/main/java/com/loc/newsapp/presentation/search/SearchViewModel.kt
xidsyed
809,749,440
false
{"Kotlin": 90629}
package com.loc.newsapp.presentation.search import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.cachedIn import com.loc.newsapp.domain.usecases.news.NewsUseCases import com.loc.newsapp.util.Constants.SOURCES import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import javax.inject.Inject @HiltViewModel class SearchViewModel @Inject constructor(val newsUseCases: NewsUseCases) : ViewModel() { private val _state = MutableStateFlow(SearchState()) val state = _state.asStateFlow() fun onSearchEvent(event: SearchEvent) { when (event) { is SearchEvent.UpdateSearchQuery -> { _state.update { state -> state.copy(searchQuery = event.query) } } is SearchEvent.SearchNews -> { val articlesFlow = newsUseCases.searchNews(state.value.searchQuery, SOURCES) .cachedIn(viewModelScope) _state.update { it.copy(articlesFlow = articlesFlow) } } } } }
0
Kotlin
0
1
57c5fbf7792b2a26d2a307d811be626fa7616a00
1,165
NewsBasket
MIT License
props/stubs/src/Stubs.kt
team55
29,602,286
true
{"Kotlin": 484392, "Java": 9672, "Shell": 175}
package kotlinx.android.koan import android.widget.LinearLayout import android.content.Context class _LinearLayout(ctx: Context) : LinearLayout(ctx)
0
Kotlin
0
0
68886b864e19d6523b77151d34450b802eb2e6e7
150
koan
Apache License 2.0
.space.kts
JetBrains-Research
290,508,461
false
{"Kotlin": 68437}
val image = "registry.jetbrains.team/p/ki/containers-ci/ci-corretto-17-firefox:1.0.1" job("Build") { container(image) { shellScript { content = """ ./gradlew build """ } } } job("Test") { container(image) { shellScript { content = """ ./gradlew test """ } } } job("Release") { startOn { gitPush { enabled = false } } container(image) { env["PUBLISHER_ID"] = Secrets("publisher_id") env["PUBLISHER_KEY"] = Secrets("publisher_key") shellScript { content = """ ./gradlew publish """ } } }
0
Kotlin
2
3
42f876bb6bb22f2447357e3c18108a1fb89ca0c6
731
kinference-primitives
Apache License 2.0
app/src/test/java/com/guillaumewilmot/swoleai/util/validation/FieldValidatorTest.kt
Poncholay
470,056,464
false
null
package com.guillaumewilmot.swoleai.util.validation import com.guillaumewilmot.swoleai.BaseUnitTest import com.guillaumewilmot.swoleai.R import com.guillaumewilmot.swoleai.RxImmediateSchedulerRule import com.guillaumewilmot.swoleai.model.Nullable import io.mockk.every import io.mockk.verifySequence import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Before import org.junit.Rule import org.junit.Test @ExperimentalCoroutinesApi class FieldValidatorTest : BaseUnitTest() { @Rule @JvmField val rxRule = RxImmediateSchedulerRule() @Before fun setup() { every { application.getString(R.string.app_field_validator_not_blank_error) } returns BLANK_ERROR every { application.getString(R.string.app_field_validator_not_number_error) } returns NOT_NUMBER_ERROR } @Test fun givenNotBlankValidator_andStartValidateWhenEmpty_andStartValidateWhenInFocus_testValidation() { val validator = FieldValidator( validator = ValidatorNotBlank(application), startValidateWhenEmpty = true, startValidateWhenInFocus = true ) val consumerFieldValue = spyConsumer(validator.fieldValue) val consumerFieldError = spyConsumer(validator.fieldError) val consumerFieldValidity = spyConsumer(validator.fieldValidity) testObserver(validator.fieldValue).assertValue("") testObserver(validator.fieldError).assertValue(Nullable(null)) //No error displayed until first event testObserver(validator.fieldValidity).assertValue(false) validator.onFieldFocusChanged(true) testObserver(validator.fieldValue).assertValue("") testObserver(validator.fieldError).assertValue(Nullable(BLANK_ERROR)) testObserver(validator.fieldValidity).assertValue(false) validator.onFieldChanged("a") testObserver(validator.fieldValue).assertValue("a") testObserver(validator.fieldError).assertValue(Nullable(null)) testObserver(validator.fieldValidity).assertValue(true) validator.onFieldChanged(" ") testObserver(validator.fieldValue).assertValue(" ") testObserver(validator.fieldError).assertValue(Nullable(BLANK_ERROR)) testObserver(validator.fieldValidity).assertValue(false) verifySequence { consumerFieldValue.accept("") // Default consumerFieldError.accept(Nullable(null)) // Default consumerFieldValidity.accept(false) // Default consumerFieldError.accept(Nullable(BLANK_ERROR)) // After gain focus consumerFieldValue.accept("a") consumerFieldError.accept(Nullable(null)) consumerFieldValidity.accept(true) consumerFieldValue.accept(" ") consumerFieldError.accept(Nullable(BLANK_ERROR)) consumerFieldValidity.accept(false) } } @Test fun givenNotBlankValidator_andNotStartValidateWhenEmpty_andStartValidateWhenInFocus_testValidation() { val validator = FieldValidator( validator = ValidatorNotBlank(application), startValidateWhenEmpty = false, startValidateWhenInFocus = true ) val consumerFieldValue = spyConsumer(validator.fieldValue) val consumerFieldError = spyConsumer(validator.fieldError) val consumerFieldValidity = spyConsumer(validator.fieldValidity) testObserver(validator.fieldValue).assertValue("") testObserver(validator.fieldError).assertValue(Nullable(null)) //No error displayed until first event testObserver(validator.fieldValidity).assertValue(false) validator.onFieldFocusChanged(true) testObserver(validator.fieldValue).assertValue("") testObserver(validator.fieldError).assertValue(Nullable(null)) //No error displayed because empty testObserver(validator.fieldValidity).assertValue(false) validator.onFieldChanged("a") testObserver(validator.fieldValue).assertValue("a") testObserver(validator.fieldError).assertValue(Nullable(null)) testObserver(validator.fieldValidity).assertValue(true) validator.onFieldChanged(" ") testObserver(validator.fieldValue).assertValue(" ") testObserver(validator.fieldError).assertValue(Nullable(BLANK_ERROR)) testObserver(validator.fieldValidity).assertValue(false) verifySequence { consumerFieldValue.accept("") // Default consumerFieldError.accept(Nullable(null)) // Default consumerFieldValidity.accept(false) // Default consumerFieldValue.accept("a") consumerFieldError.accept(Nullable(null)) consumerFieldValidity.accept(true) consumerFieldError.accept(Nullable(null)) //_canShowErrorField becomes true consumerFieldValue.accept(" ") consumerFieldError.accept(Nullable(BLANK_ERROR)) consumerFieldValidity.accept(false) } } @Test fun givenNotBlankValidator_andStartValidateWhenEmpty_andNotStartValidateWhenInFocus_testValidation() { val validator = FieldValidator( validator = ValidatorNotBlank(application), startValidateWhenEmpty = true, startValidateWhenInFocus = false ) val consumerFieldValue = spyConsumer(validator.fieldValue) val consumerFieldError = spyConsumer(validator.fieldError) val consumerFieldValidity = spyConsumer(validator.fieldValidity) testObserver(validator.fieldValue).assertValue("") testObserver(validator.fieldError).assertValue(Nullable(null)) //No error displayed until first event testObserver(validator.fieldValidity).assertValue(false) validator.onFieldFocusChanged(true) testObserver(validator.fieldValue).assertValue("") testObserver(validator.fieldError).assertValue(Nullable(null)) //No error displayed because in focus testObserver(validator.fieldValidity).assertValue(false) validator.onFieldFocusChanged(false) testObserver(validator.fieldValue).assertValue("") testObserver(validator.fieldError).assertValue(Nullable(BLANK_ERROR)) testObserver(validator.fieldValidity).assertValue(false) validator.onFieldChanged("a") testObserver(validator.fieldValue).assertValue("a") testObserver(validator.fieldError).assertValue(Nullable(null)) testObserver(validator.fieldValidity).assertValue(true) validator.onFieldChanged(" ") testObserver(validator.fieldValue).assertValue(" ") testObserver(validator.fieldError).assertValue(Nullable(BLANK_ERROR)) //No error displayed because in focus testObserver(validator.fieldValidity).assertValue(false) verifySequence { consumerFieldValue.accept("") // Default consumerFieldError.accept(Nullable(null)) // Default consumerFieldValidity.accept(false) // Default //Add focus //Remove focus consumerFieldError.accept(Nullable(BLANK_ERROR)) //_canShowErrorField becomes true consumerFieldValue.accept("a") consumerFieldError.accept(Nullable(null)) consumerFieldValidity.accept(true) consumerFieldValue.accept(" ") consumerFieldError.accept(Nullable(BLANK_ERROR)) consumerFieldValidity.accept(false) } } @Test fun givenNotBlankValidator_andNotStartValidateWhenEmpty_andNotStartValidateWhenInFocus_testValidation() { val validator = FieldValidator( validator = ValidatorNotBlank(application), startValidateWhenEmpty = false, startValidateWhenInFocus = false ) val consumerFieldValue = spyConsumer(validator.fieldValue) val consumerFieldError = spyConsumer(validator.fieldError) val consumerFieldValidity = spyConsumer(validator.fieldValidity) testObserver(validator.fieldValue).assertValue("") testObserver(validator.fieldError).assertValue(Nullable(null)) //No error displayed until first event testObserver(validator.fieldValidity).assertValue(false) validator.onFieldFocusChanged(true) testObserver(validator.fieldValue).assertValue("") testObserver(validator.fieldError).assertValue(Nullable(null)) //No error displayed because empty testObserver(validator.fieldValidity).assertValue(false) validator.onFieldChanged("a") testObserver(validator.fieldValue).assertValue("a") testObserver(validator.fieldError).assertValue(Nullable(null)) testObserver(validator.fieldValidity).assertValue(true) validator.onFieldChanged(" ") testObserver(validator.fieldValue).assertValue(" ") testObserver(validator.fieldError).assertValue(Nullable(null)) //No error displayed because in focus testObserver(validator.fieldValidity).assertValue(false) validator.onFieldFocusChanged(false) testObserver(validator.fieldValue).assertValue(" ") testObserver(validator.fieldError).assertValue(Nullable(BLANK_ERROR)) testObserver(validator.fieldValidity).assertValue(false) verifySequence { consumerFieldValue.accept("") // Default consumerFieldError.accept(Nullable(null)) // Default consumerFieldValidity.accept(false) // Default consumerFieldValue.accept("a") consumerFieldError.accept(Nullable(null)) consumerFieldValidity.accept(true) consumerFieldValue.accept(" ") consumerFieldError.accept(Nullable(null)) consumerFieldValidity.accept(false) //Remove focus consumerFieldError.accept(Nullable(BLANK_ERROR)) //_canShowErrorField becomes true } } @Test fun givenNotBlankAndIsDigitsValidator_andStartValidateWhenEmpty_andStartValidateWhenInFocus_testValidation() { val validator = FieldValidator( validators = listOf(ValidatorNotBlank(application), ValidatorIsDigits(application)), startValidateWhenEmpty = true, startValidateWhenInFocus = true ) val consumerFieldValue = spyConsumer(validator.fieldValue) val consumerFieldError = spyConsumer(validator.fieldError) val consumerFieldValidity = spyConsumer(validator.fieldValidity) testObserver(validator.fieldValue).assertValue("") testObserver(validator.fieldError).assertValue(Nullable(null)) //No error displayed until first event testObserver(validator.fieldValidity).assertValue(false) validator.onFieldFocusChanged(true) //Trigger first event validator.onFieldChanged("a") testObserver(validator.fieldValue).assertValue("a") testObserver(validator.fieldError).assertValue(Nullable(NOT_NUMBER_ERROR)) testObserver(validator.fieldValidity).assertValue(false) validator.onFieldChanged("1234") testObserver(validator.fieldValue).assertValue("1234") testObserver(validator.fieldError).assertValue(Nullable(null)) testObserver(validator.fieldValidity).assertValue(true) validator.onFieldChanged("123 345") testObserver(validator.fieldValue).assertValue("123 345") testObserver(validator.fieldError).assertValue(Nullable(NOT_NUMBER_ERROR)) testObserver(validator.fieldValidity).assertValue(false) validator.onFieldChanged(" ") testObserver(validator.fieldValue).assertValue(" ") testObserver(validator.fieldError).assertValue(Nullable(BLANK_ERROR)) testObserver(validator.fieldValidity).assertValue(false) verifySequence { consumerFieldValue.accept("") // Default consumerFieldError.accept(Nullable(null)) // Default consumerFieldValidity.accept(false) // Default //Add focus consumerFieldError.accept(Nullable(BLANK_ERROR)) consumerFieldValue.accept("a") consumerFieldError.accept(Nullable(NOT_NUMBER_ERROR)) consumerFieldValidity.accept(false) consumerFieldValue.accept("1234") consumerFieldError.accept(Nullable(null)) consumerFieldValidity.accept(true) consumerFieldValue.accept("123 345") consumerFieldError.accept(Nullable(NOT_NUMBER_ERROR)) consumerFieldValidity.accept(false) consumerFieldValue.accept(" ") consumerFieldError.accept(Nullable(BLANK_ERROR)) consumerFieldValidity.accept(false) } } companion object { const val BLANK_ERROR = "Blank" const val NOT_NUMBER_ERROR = "Not number" } }
0
Kotlin
0
0
3c091da3533dd032553df9006703c7ef8a767be6
12,794
SwoleAI
Apache License 2.0
module_video/src/main/java/com/knight/kotlin/module_video/entity/VideoPreLoaderEntity.kt
KnightAndroid
438,567,015
false
{"Kotlin": 1817006, "Java": 294277, "HTML": 46741, "C": 31605, "C++": 14920, "CMake": 5510}
package com.knight.kotlin.module_video.entity import android.os.Parcelable import kotlinx.parcelize.Parcelize /** * Author:Knight * Time:2024/4/7 10:29 * Description:VideoPreLoaderEntity */ @Parcelize data class VideoPreLoaderEntity ( val originalUrl:String, val proxyUrl:String, val preLoadBytes:Long = 1024*1024*2 ): Parcelable
0
Kotlin
3
6
d423c9cf863afe8e290c183b250950bf155d1f84
349
wanandroidByKotlin
Apache License 2.0
src/main/kotlin/com/github/erotourtes/harpoon/actions/OpenFileAction.kt
erotourtes
628,287,419
false
{"Kotlin": 33326}
package com.github.erotourtes.harpoon.actions import com.github.erotourtes.harpoon.utils.notify import com.github.erotourtes.harpoon.services.HarpoonService import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.service abstract class OpenFileAction : AnAction() { abstract fun index(): Int override fun actionPerformed(event: AnActionEvent) { val project = event.project ?: return val harpoonService = project.service<HarpoonService>() try { harpoonService.openFile(index()) } catch (e: Exception) { notify(e.message ?: "Error opening file") } } } class OpenFileAction0 : OpenFileAction() { override fun index(): Int = 0 } class OpenFileAction1 : OpenFileAction() { override fun index(): Int = 1 } class OpenFileAction2 : OpenFileAction() { override fun index(): Int = 2 } class OpenFileAction3 : OpenFileAction() { override fun index(): Int = 3 } class OpenFileAction4 : OpenFileAction() { override fun index(): Int = 4 } class OpenFileAction5 : OpenFileAction() { override fun index(): Int = 5 } class OpenFileAction6 : OpenFileAction() { override fun index(): Int = 6 } class OpenFileAction7 : OpenFileAction() { override fun index(): Int = 7 } class OpenFileAction8 : OpenFileAction() { override fun index(): Int = 8 } class OpenFileAction9 : OpenFileAction() { override fun index(): Int = 9 }
1
Kotlin
0
8
ea6ede205165287be714e518249536fd7364e20a
1,516
Harpooner
Apache License 2.0
app/src/main/java/com/example/mpgsandroidapp/activities/MainActivity.kt
AbdelkarimAtef
285,588,604
false
null
package com.example.mpgsandroidapp.activities import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.mpgsandroidapp.R import com.google.gson.GsonBuilder import com.mastercard.gateway.android.sdk.Gateway import com.mastercard.gateway.android.sdk.GatewayCallback import com.mastercard.gateway.android.sdk.GatewayMap import kotlinx.android.synthetic.main.activity_main.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response import com.example.mpgsandroidapp.api.MiddlewareClient import com.example.mpgsandroidapp.models.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // initialise all MPGS variables val gateway = Gateway().setMerchantId(getString(R.string.MID)).setRegion(Gateway.Region.MTF) var callback: GatewayCallback = object : GatewayCallback { override fun onSuccess(response: GatewayMap) { tvUpdate.setText(tvUpdate.getText().toString() + "\n---Session Update Successful---") } override fun onError(throwable: Throwable) { tvUpdate.setText(tvUpdate.getText().toString() + "\n---ERROR: Session Update FAILED---") } } val paymentInfo = SourceOfFunds( "CARD", Provided( Card( "A Person", "FULL_PAN", Expiry( "MM", "YY" ), "CVV") ) ) val apiVersion = "56" val request = GatewayMap() .set("sourceOfFunds.provided.card.nameOnCard", paymentInfo.provided.card.nameOnCard) .set("sourceOfFunds.provided.card.number", paymentInfo.provided.card.number) .set("sourceOfFunds.provided.card.securityCode", paymentInfo.provided.card.securityCode) .set("sourceOfFunds.provided.card.expiry.month", paymentInfo.provided.card.expiry.month) .set("sourceOfFunds.provided.card.expiry.year", paymentInfo.provided.card.expiry.year) var sessionId = "NONE" val gsonPretty = GsonBuilder().setPrettyPrinting().create() // Get Session Button Click cmdSession.setOnClickListener{ // Ask Middleware Server for a Session MiddlewareClient.instance.startPayment() .enqueue(object: Callback<GetSessionResponse>{ override fun onFailure(call: Call<GetSessionResponse>, t: Throwable) { tvMain.setText(getString(R.string.apiDown)) } override fun onResponse( call: Call<GetSessionResponse>, response: Response<GetSessionResponse> ) { tvMain.setText(gsonPretty.toJson(response.body())) sessionId = response.body()?.id.toString() } }) } // Update Button Click cmdUpdate.setOnClickListener{ tvUpdate.setText("---Sending---\n" + gsonPretty.toJson(paymentInfo)) if (sessionId != "NONE") { // Update the Session gateway.updateSession(sessionId, apiVersion, request, callback) } else { tvUpdate.setText(getString(R.string.defaultSession)) } } // Pay Button Click cmdPay.setOnClickListener{ // Send the PAY Request MiddlewareClient.instance.finishPayment(gsonPretty.toJson(sessionId)) .enqueue(object: Callback<GetPaymentResponse>{ override fun onFailure(call: Call<GetPaymentResponse>, t: Throwable) { tvPay.setText("Error with Request:\n" + call.request().toString()) } override fun onResponse( call: Call<GetPaymentResponse>, response: Response<GetPaymentResponse> ) { tvPay.setText(gsonPretty.toJson(response.body())) } }) } } }
0
Kotlin
0
0
257914a039ce2af4131ccad4336d21e28d3a3301
4,324
MPGSAndroidApp
Apache License 2.0
src/main/kotlin/org/misarch/returns/graphql/model/connection/OrderItemConnection.kt
MiSArch
771,890,143
false
{"Kotlin": 62793, "PLpgSQL": 2884, "Shell": 636, "Dockerfile": 219}
package org.misarch.returns.graphql.model.connection import com.expediagroup.graphql.generator.annotations.GraphQLDescription import com.expediagroup.graphql.generator.federation.directives.ShareableDirective import com.querydsl.core.types.dsl.BooleanExpression import com.querydsl.core.types.dsl.ComparableExpression import com.querydsl.sql.SQLQuery import org.misarch.returns.graphql.AuthorizedUser import org.misarch.returns.graphql.model.OrderItem import org.misarch.returns.graphql.model.connection.base.BaseConnection import org.misarch.returns.graphql.model.connection.base.CommonOrder import org.misarch.returns.persistence.model.OrderItemEntity import org.misarch.returns.persistence.repository.OrderItemRepository /** * A GraphQL connection for [OrderItem]s. * * @param first The maximum number of items to return * @param skip The number of items to skip * @param predicate The predicate to filter the items by * @param order The order to sort the items by * @param repository The repository to fetch the items from * @param authorizedUser The authorized user * @param applyJoin A function to apply a join to the query */ @GraphQLDescription("A connection to a list of `OrderItem` values.") @ShareableDirective class OrderItemConnection( first: Int?, skip: Int?, predicate: BooleanExpression?, order: CommonOrder?, repository: OrderItemRepository, authorizedUser: AuthorizedUser?, applyJoin: (query: SQLQuery<*>) -> SQLQuery<*> = { it } ) : BaseConnection<OrderItem, OrderItemEntity>( first, skip, null, predicate, (order ?: CommonOrder.DEFAULT).toOrderSpecifier(OrderItemEntity.ENTITY.id), repository, OrderItemEntity.ENTITY, authorizedUser, applyJoin ) { override val primaryKey: ComparableExpression<*> get() = OrderItemEntity.ENTITY.id }
0
Kotlin
0
0
e6b7fa01eb461cddf40af6345ce00aff03a93fd0
1,834
return
MIT License
app/src/main/java/ru/tech/easysearch/database/bookmarks/dao/BookmarkDao.kt
T8RIN
435,128,550
false
{"Kotlin": 257847}
package ru.tech.easysearch.database.bookmarks.dao import androidx.lifecycle.LiveData import androidx.room.* import ru.tech.easysearch.database.bookmarks.Bookmark @Dao interface BookmarkDao { @Insert(onConflict = OnConflictStrategy.IGNORE) fun insert(bookmark: Bookmark) @Insert(onConflict = OnConflictStrategy.IGNORE) fun insert(vararg bookmark: Bookmark) @Update(onConflict = OnConflictStrategy.IGNORE) fun update(bookmark: Bookmark) @Delete fun delete(bookmark: Bookmark) @Query("delete from bookmarks") fun deleteAllBookmarks() @Query("select * from bookmarks order by id desc") fun getAllBookmarks(): LiveData<List<Bookmark>> }
0
Kotlin
3
42
663e829d8b9e95dcbd3b19582265517d134dc7ea
688
ESearch
Apache License 2.0
app/src/main/java/com/example/lirboyoapp/activities/DetailActivity.kt
ziyanmuzakky
454,677,730
false
null
package com.example.lirboyoapp.activities import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.core.text.HtmlCompat import com.bumptech.glide.Glide import com.example.lirboyoapp.databinding.ActivityDetailBinding class DetailActivity : AppCompatActivity() { private lateinit var binding: ActivityDetailBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDetailBinding.inflate(layoutInflater) setContentView(binding.root) val actionBar = supportActionBar actionBar!!.title = "Detail" val title = intent.getStringExtra("title") val content = intent.getStringExtra("content") val date = intent.getStringExtra("date") val image = intent.getStringExtra("image") binding.textTitle.text = title binding.textDate.text = date binding.textDescription.text = HtmlCompat.fromHtml(content!!,HtmlCompat.FROM_HTML_MODE_LEGACY) Glide.with(applicationContext) .load(image) .into(binding.image) } }
0
Kotlin
0
0
dbf484e90ec3d14ed0b5a573f8ae95db6e459a4c
1,132
LirboyoApp
Apache License 2.0
app/src/main/java/it/sephiroth/android/app/appunti/widget/MySearchView.kt
sephiroth74
167,976,451
false
null
package com.lapism.searchview.widget import android.annotation.SuppressLint import android.content.Context import android.graphics.drawable.Drawable import android.os.Parcelable import android.text.TextUtils import android.util.AttributeSet import android.view.* import android.widget.Filter import android.widget.Filterable import android.widget.ImageView import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.annotation.NonNull import androidx.annotation.Nullable import androidx.core.content.ContextCompat import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.lapism.searchview.R import com.lapism.searchview.Search import com.lapism.searchview.graphics.SearchAnimator import com.lapism.searchview.graphics.SearchArrowDrawable @Suppress("MemberVisibilityCanBePrivate", "unused") class MySearchView : SearchLayout, Filter.FilterListener { // --------------------------------------------------------------------------------------------- @Search.Version @get:Search.Version var version: Int = 0 set(@Search.Version version) { field = version if (this.version == Search.Version.MENU_ITEM) { visibility = View.GONE } } private var mMenuItemCx = -1 private var mShadow: Boolean = false private var mAnimationDuration: Long = 0 private lateinit var mImageViewImage: ImageView private var mMenuItem: MenuItem? = null private var mMenuItemView: View? = null private lateinit var mViewShadow: View private lateinit var mViewDivider: View private lateinit var mRecyclerView: RecyclerView private var mOnLogoClickListener: Search.OnLogoClickListener? = null private var mOnOpenCloseListener: Search.OnOpenCloseListener? = null // Adapter var adapter: RecyclerView.Adapter<*>? get() = mRecyclerView.adapter set(adapter) { mRecyclerView.adapter = adapter } // --------------------------------------------------------------------------------------------- constructor(@NonNull context: Context) : super(context) { init(context, null, 0, 0) } constructor(@NonNull context: Context, @Nullable attrs: AttributeSet) : super(context, attrs) { init(context, attrs, 0, 0) } constructor(@NonNull context: Context, @Nullable attrs: AttributeSet, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) { init(context, attrs, defStyleAttr, 0) } constructor(@NonNull context: Context, @Nullable attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super( context, attrs, defStyleAttr, defStyleRes ) { init(context, attrs, defStyleAttr, defStyleRes) } // --------------------------------------------------------------------------------------------- private fun getCenterX(@NonNull view: View): Int { val location = IntArray(2) view.getLocationOnScreen(location) return location[0] + view.width / 2 } // --------------------------------------------------------------------------------------------- override fun onTextChanged(s: CharSequence) { mQueryText = s setMicOrClearIcon(true) filter(s) if (mOnQueryTextListener != null) { mOnQueryTextListener.onQueryTextChange(mQueryText) } } override fun addFocus() { filter(mQueryText) if (mShadow) { SearchAnimator.fadeOpen(mViewShadow, mAnimationDuration) } setMicOrClearIcon(true) if (version == Search.Version.TOOLBAR) { setLogoHamburgerToLogoArrowWithAnimation(true) // todo SavedState, marginy kulate a barva divideru if (mOnOpenCloseListener != null) { mOnOpenCloseListener!!.onOpen() } } postDelayed({ showKeyboard() }, mAnimationDuration) } override fun removeFocus() { if (mShadow) { SearchAnimator.fadeClose(mViewShadow, mAnimationDuration) } //setTextImageVisibility(false); todo error + shadow error pri otoceni, pak mizi animace hideSuggestions() hideKeyboard() setMicOrClearIcon(false) if (version == Search.Version.TOOLBAR) { setLogoHamburgerToLogoArrowWithAnimation(false) postDelayed({ if (mOnOpenCloseListener != null) { mOnOpenCloseListener!!.onClose() } }, mAnimationDuration) } } override fun isView(): Boolean { return false } @SuppressLint("PrivateResource") override fun getLayout(): Int { return R.layout.search_view } override fun open() { open(null) } override fun close() { when (version) { Search.Version.TOOLBAR -> mSearchEditText.clearFocus() Search.Version.MENU_ITEM -> { if (mMenuItem != null) { getMenuItemPosition(mMenuItem!!.itemId) } // SearchAnimator.revealClose( // mContext, // mCardView, // mMenuItemCx, // mAnimationDuration, // mSearchEditText, // this, // mOnOpenCloseListener // ) } } } // --------------------------------------------------------------------------------------------- @SuppressLint("PrivateResource") internal override fun init( @NonNull context: Context, @Nullable attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int ) { val a = context.obtainStyledAttributes(attrs, R.styleable.SearchView, defStyleAttr, defStyleRes) val layoutResId = layout val inflater = LayoutInflater.from(context) inflater.inflate(layoutResId, this, true) super.init(context, attrs, defStyleAttr, defStyleRes) mImageViewImage = findViewById(R.id.search_imageView_image) mImageViewImage.setOnClickListener(this) mImageViewClear = findViewById(R.id.search_imageView_clear) mImageViewClear.setOnClickListener(this) mImageViewClear.visibility = View.GONE mViewShadow = findViewById(R.id.search_view_shadow) mViewShadow.visibility = View.GONE mViewShadow.setOnClickListener(this) mViewDivider = findViewById(R.id.search_view_divider) mViewDivider.visibility = View.GONE mRecyclerView = findViewById(R.id.search_recyclerView) mRecyclerView.let {recyclerView -> recyclerView.visibility = View.GONE recyclerView.layoutManager = LinearLayoutManager(mContext) recyclerView.isNestedScrollingEnabled = false recyclerView.itemAnimator = DefaultItemAnimator() recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState == RecyclerView.SCROLL_STATE_DRAGGING) { hideKeyboard() } } }) } logo = a.getInteger(R.styleable.SearchView_search_logo, Search.Logo.HAMBURGER_ARROW) shape = a.getInteger(R.styleable.SearchView_search_shape, Search.Shape.CLASSIC) theme = a.getInteger(R.styleable.SearchView_search_theme, Search.Theme.PLAY) versionMargins = a.getInteger(R.styleable.SearchView_search_version_margins, Search.VersionMargins.TOOLBAR) version = a.getInteger(R.styleable.SearchView_search_version, Search.Version.TOOLBAR) if (a.hasValue(R.styleable.SearchView_search_logo_icon)) { setLogoIcon(a.getInteger(R.styleable.SearchView_search_logo_icon, 0)) } if (a.hasValue(R.styleable.SearchView_search_logo_color)) { setLogoColor(ContextCompat.getColor(mContext, a.getResourceId(R.styleable.SearchView_search_logo_color, 0))) } if (a.hasValue(R.styleable.SearchView_search_mic_icon)) { setMicIcon(a.getResourceId(R.styleable.SearchView_search_mic_icon, 0)) } if (a.hasValue(R.styleable.SearchView_search_mic_color)) { setMicColor(a.getColor(R.styleable.SearchView_search_mic_color, 0)) } if (a.hasValue(R.styleable.SearchView_search_clear_icon)) { setClearIcon(a.getDrawable(R.styleable.SearchView_search_clear_icon)) } else { setClearIcon(ContextCompat.getDrawable(mContext, R.drawable.search_ic_clear_black_24dp)) } if (a.hasValue(R.styleable.SearchView_search_clear_color)) { setClearColor(a.getColor(R.styleable.SearchView_search_clear_color, 0)) } if (a.hasValue(R.styleable.SearchView_search_menu_icon)) { setMenuIcon(a.getResourceId(R.styleable.SearchView_search_menu_icon, 0)) } if (a.hasValue(R.styleable.SearchView_search_menu_color)) { setMenuColor(a.getColor(R.styleable.SearchView_search_menu_color, 0)) } if (a.hasValue(R.styleable.SearchView_search_background_color)) { setBackgroundColor(a.getColor(R.styleable.SearchView_search_background_color, 0)) } if (a.hasValue(R.styleable.SearchView_search_text_image)) { setTextImage(a.getResourceId(R.styleable.SearchView_search_text_image, 0)) } if (a.hasValue(R.styleable.SearchView_search_text_color)) { setTextColor(a.getColor(R.styleable.SearchView_search_text_color, 0)) } if (a.hasValue(R.styleable.SearchView_search_text_size)) { setTextSize(a.getDimension(R.styleable.SearchView_search_text_size, 0f)) } if (a.hasValue(R.styleable.SearchView_search_text_style)) { setTextStyle(a.getInt(R.styleable.SearchView_search_text_style, 0)) } if (a.hasValue(R.styleable.SearchView_search_hint)) { setHint(a.getString(R.styleable.SearchView_search_hint)) } if (a.hasValue(R.styleable.SearchView_search_hint_color)) { setHintColor(a.getColor(R.styleable.SearchView_search_hint_color, 0)) } setAnimationDuration( a.getInt( R.styleable.SearchView_search_animation_duration, mContext.resources.getInteger(R.integer.search_animation_duration) ).toLong() ) setShadow(a.getBoolean(R.styleable.SearchView_search_shadow, true)) setShadowColor( a.getColor( R.styleable.SearchView_search_shadow_color, ContextCompat.getColor(mContext, R.color.search_shadow) ) ) if (a.hasValue(R.styleable.SearchView_search_elevation)) { elevation = a.getDimensionPixelSize(R.styleable.SearchView_search_elevation, 0).toFloat() } a.recycle() isSaveEnabled = true mSearchEditText.visibility = View.VISIBLE // todo } // --------------------------------------------------------------------------------------------- // Divider override fun setDividerColor(@ColorInt color: Int) { mViewDivider.setBackgroundColor(color) } // Clear fun setClearIcon(@DrawableRes resource: Int) { mImageViewClear.setImageResource(resource) } fun setClearIcon(@Nullable drawable: Drawable?) { mImageViewClear.setImageDrawable(drawable) } override fun setClearColor(@ColorInt color: Int) { mImageViewClear.setColorFilter(color) } // Image fun setTextImage(@DrawableRes resource: Int) { mImageViewImage.setImageResource(resource) setTextImageVisibility(false) } fun setTextImage(@Nullable drawable: Drawable) { mImageViewImage.setImageDrawable(drawable) setTextImageVisibility(false) } // Animation duration fun setAnimationDuration(animationDuration: Long) { mAnimationDuration = animationDuration } // Shadow fun setShadow(shadow: Boolean) { mShadow = shadow } fun setShadowColor(@ColorInt color: Int) { mViewShadow.setBackgroundColor(color) } fun addDivider(itemDecoration: RecyclerView.ItemDecoration) { mRecyclerView.addItemDecoration(itemDecoration) } fun removeDivider(itemDecoration: RecyclerView.ItemDecoration) { mRecyclerView.removeItemDecoration(itemDecoration) } // Others fun open(menuItem: MenuItem?) { mMenuItem = menuItem when (version) { Search.Version.TOOLBAR -> mSearchEditText.requestFocus() Search.Version.MENU_ITEM -> { visibility = View.VISIBLE if (mMenuItem != null) { getMenuItemPosition(mMenuItem!!.itemId) } mCardView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { mCardView.viewTreeObserver.removeOnGlobalLayoutListener(this) SearchAnimator.revealOpen( mContext, mCardView, mMenuItemCx, mAnimationDuration, mSearchEditText, mOnOpenCloseListener ) } }) } } } fun setLogoHamburgerToLogoArrowWithAnimation(animate: Boolean) { if (mSearchArrowDrawable != null) { if (animate) { mSearchArrowDrawable.setVerticalMirror(false) mSearchArrowDrawable.animate(SearchArrowDrawable.STATE_ARROW, mAnimationDuration) } else { mSearchArrowDrawable.setVerticalMirror(true) mSearchArrowDrawable.animate(SearchArrowDrawable.STATE_HAMBURGER, mAnimationDuration) } } } fun setLogoHamburgerToLogoArrowWithoutAnimation(animation: Boolean) { if (mSearchArrowDrawable != null) { if (animation) { mSearchArrowDrawable.progress = SearchArrowDrawable.STATE_ARROW } else { mSearchArrowDrawable.progress = SearchArrowDrawable.STATE_HAMBURGER } } } // Listeners fun setOnLogoClickListener(listener: Search.OnLogoClickListener) { mOnLogoClickListener = listener } fun setOnOpenCloseListener(listener: Search.OnOpenCloseListener) { mOnOpenCloseListener = listener } // --------------------------------------------------------------------------------------------- private fun setMicOrClearIcon(hasFocus: Boolean) { if (hasFocus && !TextUtils.isEmpty(mQueryText)) { if (mOnMicClickListener != null) { mImageViewMic.visibility = View.GONE } mImageViewClear.visibility = View.VISIBLE } else { mImageViewClear.visibility = View.GONE if (mOnMicClickListener != null) { mImageViewMic.visibility = View.VISIBLE } } } private fun setTextImageVisibility(hasFocus: Boolean) { if (hasFocus) { mImageViewImage.visibility = View.GONE mSearchEditText.visibility = View.VISIBLE mSearchEditText.requestFocus() } else { mSearchEditText.visibility = View.GONE mImageViewImage.visibility = View.VISIBLE } } private fun filter(s: CharSequence?) { if (adapter != null && adapter is Filterable) { (adapter as Filterable).filter.filter(s, this) } } private fun showSuggestions() { if (adapter != null && adapter!!.getItemCount() > 0) { mViewDivider.visibility = View.VISIBLE mRecyclerView.setVisibility(View.VISIBLE) } } private fun hideSuggestions() { if (adapter != null && adapter!!.itemCount > 0) { mViewDivider.visibility = View.GONE mRecyclerView.visibility = View.GONE } } private fun getMenuItemPosition(menuItemId: Int) { if (mMenuItemView != null) { mMenuItemCx = getCenterX(mMenuItemView!!) } var viewParent: ViewParent? = parent while (viewParent != null && viewParent is View) { val parent = viewParent as View? val view = parent!!.findViewById<View>(menuItemId) if (view != null) { mMenuItemView = view mMenuItemCx = getCenterX(mMenuItemView!!) break } viewParent = viewParent.getParent() } } // --------------------------------------------------------------------------------------------- // override fun onSaveInstanceState(): Parcelable? { // val superState = super.onSaveInstanceState() // val ss = SearchViewSavedState(superState) // ss.hasFocus = mSearchEditText.hasFocus() // ss.shadow = mShadow // ss.query = if (mQueryText != null) mQueryText!!.toString() else null // return ss // } // // override fun onRestoreInstanceState(state: Parcelable) { // if (state !is SearchViewSavedState) { // super.onRestoreInstanceState(state) // return // } // super.onRestoreInstanceState(state.superState) // // mShadow = state.shadow // if (mShadow) { //// mViewShadow!!.visibility = View.VISIBLE // } //// if (state.hasFocus) { //// open() //// } //// if (state.query != null) { //// setText(state.query) //// } //// requestLayout() // } // --------------------------------------------------------------------------------------------- override fun onClick(v: View) { if (v == mImageViewLogo) { if (mSearchEditText.hasFocus()) { close() } else { if (mOnLogoClickListener != null) { mOnLogoClickListener!!.onLogoClick() } } } else if (v == mImageViewImage) { setTextImageVisibility(true) } else if (v == mImageViewMic) { if (mOnMicClickListener != null) { mOnMicClickListener.onMicClick() } } else if (v == mImageViewClear) { if (mSearchEditText.length() > 0) { mSearchEditText.text!!.clear() } } else if (v == mImageViewMenu) { if (mOnMenuClickListener != null) { mOnMenuClickListener.onMenuClick() } } else if (v == mViewShadow) { close() } } override fun onFilterComplete(count: Int) { if (count > 0) { showSuggestions() } else { hideSuggestions() } } }
0
Kotlin
3
9
3e7929be96504dd68533042b8688d0be41096b53
19,380
Appunti
The Unlicense
app/src/main/java/it/sephiroth/android/app/appunti/widget/MySearchView.kt
sephiroth74
167,976,451
false
null
package com.lapism.searchview.widget import android.annotation.SuppressLint import android.content.Context import android.graphics.drawable.Drawable import android.os.Parcelable import android.text.TextUtils import android.util.AttributeSet import android.view.* import android.widget.Filter import android.widget.Filterable import android.widget.ImageView import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.annotation.NonNull import androidx.annotation.Nullable import androidx.core.content.ContextCompat import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.lapism.searchview.R import com.lapism.searchview.Search import com.lapism.searchview.graphics.SearchAnimator import com.lapism.searchview.graphics.SearchArrowDrawable @Suppress("MemberVisibilityCanBePrivate", "unused") class MySearchView : SearchLayout, Filter.FilterListener { // --------------------------------------------------------------------------------------------- @Search.Version @get:Search.Version var version: Int = 0 set(@Search.Version version) { field = version if (this.version == Search.Version.MENU_ITEM) { visibility = View.GONE } } private var mMenuItemCx = -1 private var mShadow: Boolean = false private var mAnimationDuration: Long = 0 private lateinit var mImageViewImage: ImageView private var mMenuItem: MenuItem? = null private var mMenuItemView: View? = null private lateinit var mViewShadow: View private lateinit var mViewDivider: View private lateinit var mRecyclerView: RecyclerView private var mOnLogoClickListener: Search.OnLogoClickListener? = null private var mOnOpenCloseListener: Search.OnOpenCloseListener? = null // Adapter var adapter: RecyclerView.Adapter<*>? get() = mRecyclerView.adapter set(adapter) { mRecyclerView.adapter = adapter } // --------------------------------------------------------------------------------------------- constructor(@NonNull context: Context) : super(context) { init(context, null, 0, 0) } constructor(@NonNull context: Context, @Nullable attrs: AttributeSet) : super(context, attrs) { init(context, attrs, 0, 0) } constructor(@NonNull context: Context, @Nullable attrs: AttributeSet, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) { init(context, attrs, defStyleAttr, 0) } constructor(@NonNull context: Context, @Nullable attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super( context, attrs, defStyleAttr, defStyleRes ) { init(context, attrs, defStyleAttr, defStyleRes) } // --------------------------------------------------------------------------------------------- private fun getCenterX(@NonNull view: View): Int { val location = IntArray(2) view.getLocationOnScreen(location) return location[0] + view.width / 2 } // --------------------------------------------------------------------------------------------- override fun onTextChanged(s: CharSequence) { mQueryText = s setMicOrClearIcon(true) filter(s) if (mOnQueryTextListener != null) { mOnQueryTextListener.onQueryTextChange(mQueryText) } } override fun addFocus() { filter(mQueryText) if (mShadow) { SearchAnimator.fadeOpen(mViewShadow, mAnimationDuration) } setMicOrClearIcon(true) if (version == Search.Version.TOOLBAR) { setLogoHamburgerToLogoArrowWithAnimation(true) // todo SavedState, marginy kulate a barva divideru if (mOnOpenCloseListener != null) { mOnOpenCloseListener!!.onOpen() } } postDelayed({ showKeyboard() }, mAnimationDuration) } override fun removeFocus() { if (mShadow) { SearchAnimator.fadeClose(mViewShadow, mAnimationDuration) } //setTextImageVisibility(false); todo error + shadow error pri otoceni, pak mizi animace hideSuggestions() hideKeyboard() setMicOrClearIcon(false) if (version == Search.Version.TOOLBAR) { setLogoHamburgerToLogoArrowWithAnimation(false) postDelayed({ if (mOnOpenCloseListener != null) { mOnOpenCloseListener!!.onClose() } }, mAnimationDuration) } } override fun isView(): Boolean { return false } @SuppressLint("PrivateResource") override fun getLayout(): Int { return R.layout.search_view } override fun open() { open(null) } override fun close() { when (version) { Search.Version.TOOLBAR -> mSearchEditText.clearFocus() Search.Version.MENU_ITEM -> { if (mMenuItem != null) { getMenuItemPosition(mMenuItem!!.itemId) } // SearchAnimator.revealClose( // mContext, // mCardView, // mMenuItemCx, // mAnimationDuration, // mSearchEditText, // this, // mOnOpenCloseListener // ) } } } // --------------------------------------------------------------------------------------------- @SuppressLint("PrivateResource") internal override fun init( @NonNull context: Context, @Nullable attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int ) { val a = context.obtainStyledAttributes(attrs, R.styleable.SearchView, defStyleAttr, defStyleRes) val layoutResId = layout val inflater = LayoutInflater.from(context) inflater.inflate(layoutResId, this, true) super.init(context, attrs, defStyleAttr, defStyleRes) mImageViewImage = findViewById(R.id.search_imageView_image) mImageViewImage.setOnClickListener(this) mImageViewClear = findViewById(R.id.search_imageView_clear) mImageViewClear.setOnClickListener(this) mImageViewClear.visibility = View.GONE mViewShadow = findViewById(R.id.search_view_shadow) mViewShadow.visibility = View.GONE mViewShadow.setOnClickListener(this) mViewDivider = findViewById(R.id.search_view_divider) mViewDivider.visibility = View.GONE mRecyclerView = findViewById(R.id.search_recyclerView) mRecyclerView.let {recyclerView -> recyclerView.visibility = View.GONE recyclerView.layoutManager = LinearLayoutManager(mContext) recyclerView.isNestedScrollingEnabled = false recyclerView.itemAnimator = DefaultItemAnimator() recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState == RecyclerView.SCROLL_STATE_DRAGGING) { hideKeyboard() } } }) } logo = a.getInteger(R.styleable.SearchView_search_logo, Search.Logo.HAMBURGER_ARROW) shape = a.getInteger(R.styleable.SearchView_search_shape, Search.Shape.CLASSIC) theme = a.getInteger(R.styleable.SearchView_search_theme, Search.Theme.PLAY) versionMargins = a.getInteger(R.styleable.SearchView_search_version_margins, Search.VersionMargins.TOOLBAR) version = a.getInteger(R.styleable.SearchView_search_version, Search.Version.TOOLBAR) if (a.hasValue(R.styleable.SearchView_search_logo_icon)) { setLogoIcon(a.getInteger(R.styleable.SearchView_search_logo_icon, 0)) } if (a.hasValue(R.styleable.SearchView_search_logo_color)) { setLogoColor(ContextCompat.getColor(mContext, a.getResourceId(R.styleable.SearchView_search_logo_color, 0))) } if (a.hasValue(R.styleable.SearchView_search_mic_icon)) { setMicIcon(a.getResourceId(R.styleable.SearchView_search_mic_icon, 0)) } if (a.hasValue(R.styleable.SearchView_search_mic_color)) { setMicColor(a.getColor(R.styleable.SearchView_search_mic_color, 0)) } if (a.hasValue(R.styleable.SearchView_search_clear_icon)) { setClearIcon(a.getDrawable(R.styleable.SearchView_search_clear_icon)) } else { setClearIcon(ContextCompat.getDrawable(mContext, R.drawable.search_ic_clear_black_24dp)) } if (a.hasValue(R.styleable.SearchView_search_clear_color)) { setClearColor(a.getColor(R.styleable.SearchView_search_clear_color, 0)) } if (a.hasValue(R.styleable.SearchView_search_menu_icon)) { setMenuIcon(a.getResourceId(R.styleable.SearchView_search_menu_icon, 0)) } if (a.hasValue(R.styleable.SearchView_search_menu_color)) { setMenuColor(a.getColor(R.styleable.SearchView_search_menu_color, 0)) } if (a.hasValue(R.styleable.SearchView_search_background_color)) { setBackgroundColor(a.getColor(R.styleable.SearchView_search_background_color, 0)) } if (a.hasValue(R.styleable.SearchView_search_text_image)) { setTextImage(a.getResourceId(R.styleable.SearchView_search_text_image, 0)) } if (a.hasValue(R.styleable.SearchView_search_text_color)) { setTextColor(a.getColor(R.styleable.SearchView_search_text_color, 0)) } if (a.hasValue(R.styleable.SearchView_search_text_size)) { setTextSize(a.getDimension(R.styleable.SearchView_search_text_size, 0f)) } if (a.hasValue(R.styleable.SearchView_search_text_style)) { setTextStyle(a.getInt(R.styleable.SearchView_search_text_style, 0)) } if (a.hasValue(R.styleable.SearchView_search_hint)) { setHint(a.getString(R.styleable.SearchView_search_hint)) } if (a.hasValue(R.styleable.SearchView_search_hint_color)) { setHintColor(a.getColor(R.styleable.SearchView_search_hint_color, 0)) } setAnimationDuration( a.getInt( R.styleable.SearchView_search_animation_duration, mContext.resources.getInteger(R.integer.search_animation_duration) ).toLong() ) setShadow(a.getBoolean(R.styleable.SearchView_search_shadow, true)) setShadowColor( a.getColor( R.styleable.SearchView_search_shadow_color, ContextCompat.getColor(mContext, R.color.search_shadow) ) ) if (a.hasValue(R.styleable.SearchView_search_elevation)) { elevation = a.getDimensionPixelSize(R.styleable.SearchView_search_elevation, 0).toFloat() } a.recycle() isSaveEnabled = true mSearchEditText.visibility = View.VISIBLE // todo } // --------------------------------------------------------------------------------------------- // Divider override fun setDividerColor(@ColorInt color: Int) { mViewDivider.setBackgroundColor(color) } // Clear fun setClearIcon(@DrawableRes resource: Int) { mImageViewClear.setImageResource(resource) } fun setClearIcon(@Nullable drawable: Drawable?) { mImageViewClear.setImageDrawable(drawable) } override fun setClearColor(@ColorInt color: Int) { mImageViewClear.setColorFilter(color) } // Image fun setTextImage(@DrawableRes resource: Int) { mImageViewImage.setImageResource(resource) setTextImageVisibility(false) } fun setTextImage(@Nullable drawable: Drawable) { mImageViewImage.setImageDrawable(drawable) setTextImageVisibility(false) } // Animation duration fun setAnimationDuration(animationDuration: Long) { mAnimationDuration = animationDuration } // Shadow fun setShadow(shadow: Boolean) { mShadow = shadow } fun setShadowColor(@ColorInt color: Int) { mViewShadow.setBackgroundColor(color) } fun addDivider(itemDecoration: RecyclerView.ItemDecoration) { mRecyclerView.addItemDecoration(itemDecoration) } fun removeDivider(itemDecoration: RecyclerView.ItemDecoration) { mRecyclerView.removeItemDecoration(itemDecoration) } // Others fun open(menuItem: MenuItem?) { mMenuItem = menuItem when (version) { Search.Version.TOOLBAR -> mSearchEditText.requestFocus() Search.Version.MENU_ITEM -> { visibility = View.VISIBLE if (mMenuItem != null) { getMenuItemPosition(mMenuItem!!.itemId) } mCardView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { mCardView.viewTreeObserver.removeOnGlobalLayoutListener(this) SearchAnimator.revealOpen( mContext, mCardView, mMenuItemCx, mAnimationDuration, mSearchEditText, mOnOpenCloseListener ) } }) } } } fun setLogoHamburgerToLogoArrowWithAnimation(animate: Boolean) { if (mSearchArrowDrawable != null) { if (animate) { mSearchArrowDrawable.setVerticalMirror(false) mSearchArrowDrawable.animate(SearchArrowDrawable.STATE_ARROW, mAnimationDuration) } else { mSearchArrowDrawable.setVerticalMirror(true) mSearchArrowDrawable.animate(SearchArrowDrawable.STATE_HAMBURGER, mAnimationDuration) } } } fun setLogoHamburgerToLogoArrowWithoutAnimation(animation: Boolean) { if (mSearchArrowDrawable != null) { if (animation) { mSearchArrowDrawable.progress = SearchArrowDrawable.STATE_ARROW } else { mSearchArrowDrawable.progress = SearchArrowDrawable.STATE_HAMBURGER } } } // Listeners fun setOnLogoClickListener(listener: Search.OnLogoClickListener) { mOnLogoClickListener = listener } fun setOnOpenCloseListener(listener: Search.OnOpenCloseListener) { mOnOpenCloseListener = listener } // --------------------------------------------------------------------------------------------- private fun setMicOrClearIcon(hasFocus: Boolean) { if (hasFocus && !TextUtils.isEmpty(mQueryText)) { if (mOnMicClickListener != null) { mImageViewMic.visibility = View.GONE } mImageViewClear.visibility = View.VISIBLE } else { mImageViewClear.visibility = View.GONE if (mOnMicClickListener != null) { mImageViewMic.visibility = View.VISIBLE } } } private fun setTextImageVisibility(hasFocus: Boolean) { if (hasFocus) { mImageViewImage.visibility = View.GONE mSearchEditText.visibility = View.VISIBLE mSearchEditText.requestFocus() } else { mSearchEditText.visibility = View.GONE mImageViewImage.visibility = View.VISIBLE } } private fun filter(s: CharSequence?) { if (adapter != null && adapter is Filterable) { (adapter as Filterable).filter.filter(s, this) } } private fun showSuggestions() { if (adapter != null && adapter!!.getItemCount() > 0) { mViewDivider.visibility = View.VISIBLE mRecyclerView.setVisibility(View.VISIBLE) } } private fun hideSuggestions() { if (adapter != null && adapter!!.itemCount > 0) { mViewDivider.visibility = View.GONE mRecyclerView.visibility = View.GONE } } private fun getMenuItemPosition(menuItemId: Int) { if (mMenuItemView != null) { mMenuItemCx = getCenterX(mMenuItemView!!) } var viewParent: ViewParent? = parent while (viewParent != null && viewParent is View) { val parent = viewParent as View? val view = parent!!.findViewById<View>(menuItemId) if (view != null) { mMenuItemView = view mMenuItemCx = getCenterX(mMenuItemView!!) break } viewParent = viewParent.getParent() } } // --------------------------------------------------------------------------------------------- // override fun onSaveInstanceState(): Parcelable? { // val superState = super.onSaveInstanceState() // val ss = SearchViewSavedState(superState) // ss.hasFocus = mSearchEditText.hasFocus() // ss.shadow = mShadow // ss.query = if (mQueryText != null) mQueryText!!.toString() else null // return ss // } // // override fun onRestoreInstanceState(state: Parcelable) { // if (state !is SearchViewSavedState) { // super.onRestoreInstanceState(state) // return // } // super.onRestoreInstanceState(state.superState) // // mShadow = state.shadow // if (mShadow) { //// mViewShadow!!.visibility = View.VISIBLE // } //// if (state.hasFocus) { //// open() //// } //// if (state.query != null) { //// setText(state.query) //// } //// requestLayout() // } // --------------------------------------------------------------------------------------------- override fun onClick(v: View) { if (v == mImageViewLogo) { if (mSearchEditText.hasFocus()) { close() } else { if (mOnLogoClickListener != null) { mOnLogoClickListener!!.onLogoClick() } } } else if (v == mImageViewImage) { setTextImageVisibility(true) } else if (v == mImageViewMic) { if (mOnMicClickListener != null) { mOnMicClickListener.onMicClick() } } else if (v == mImageViewClear) { if (mSearchEditText.length() > 0) { mSearchEditText.text!!.clear() } } else if (v == mImageViewMenu) { if (mOnMenuClickListener != null) { mOnMenuClickListener.onMenuClick() } } else if (v == mViewShadow) { close() } } override fun onFilterComplete(count: Int) { if (count > 0) { showSuggestions() } else { hideSuggestions() } } }
0
Kotlin
3
9
3e7929be96504dd68533042b8688d0be41096b53
19,380
Appunti
The Unlicense
src/main/kotlin/mixit/model/User.kt
obs3rver
79,236,155
true
{"Kotlin": 52015, "Java": 9070, "HTML": 3874, "JavaScript": 1319, "CSS": 282}
package mixit.model import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document @Document data class User( @Id val login: String, val firstname: String, val lastname: String, val email: String, val company: String? = null, val shortDescription: String? = null, val longDescription: String? = null, val logoUrl: String? = null, val events: List<String> = emptyList(), val role: Role = Role.ATTENDEE, val links: List<Link> = emptyList() ) enum class Role { STAFF, SPEAKER, SPONSOR, ATTENDEE }
0
Kotlin
0
0
8fa4da25fe17be8a9842226b999f315e49006930
646
mixit
Apache License 2.0
src/main/kotlin/com/github/plombardi89/kocean/model/ModelExtensions.kt
plombardi89
39,917,602
false
null
package com.github.plombardi89.kocean.model import com.eclipsesource.json.JsonObject private fun <T> ModelFactory<T>.readMetaAndLinksData(json: JsonObject): Pair<Meta, Links> { return Pair(Meta(json.get("meta").asObject()), Links(json.get("links").asObject())) }
0
Kotlin
0
0
c56a4863ebb97a095e115c66a29f29a67df031c2
268
KOcean
MIT License
app/src/main/java/com/monitor/MainActivity.kt
tiagocasemiro
240,608,365
false
null
package com.monitor import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import java.lang.Exception class MainActivity : AppCompatActivity() { companion object { var intervalInMinutes = 10 * 60 * 1000L } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val service = Intent(MainActivity@this, MonitorService::class.java) start.setOnClickListener { setInterval() startService(service) } stop.setOnClickListener { setInterval() stopService(service) } } fun setInterval() { try { val text = interval.text.toString() if(text.isNotEmpty()) { intervalInMinutes = text.toLong() * 60 * 1000L } } catch (e: Exception) { e.printStackTrace() } } }
0
Kotlin
0
0
3f25379249a628c7f5153660a173cdaa710115e4
1,049
Monitor
Apache License 2.0
src/Atmcomplaint.kt
spandey1296
269,556,751
false
null
import java.io.BufferedReader import java.io.File import java.io.InputStreamReader class Atmcomplaint { companion object { fun atm_complaint(){ println("Welcome to The Facility of Customer Grievence Cell") Dateandtime.dateandtime() val fileName = "src/resources/myfile3.txt" println("Complaint Registered Successfully!!") } } }
0
Kotlin
3
9
a94e2f3458844ff2c84caa7b7e34f6f067f48702
425
ModernBanking-Management-System
MIT License
smartAd/src/main/java/com/smartad/adapters/custom/huaweiadsadapter/SASHuaweiBannerBidderAdapter.kt
Explore-In-HMS
447,891,536
false
{"Kotlin": 45780}
/* * Copyright 2022. Explore in HMS. 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.smartad.adapters.custom.huaweiadsadapter import android.content.Context import android.util.Log import android.widget.LinearLayout import com.huawei.hms.ads.AdListener import com.huawei.hms.ads.banner.BannerView import com.smartad.adapters.custom.huaweiadsadapter.data.HuaweiAdResponse import com.smartad.adapters.custom.huaweiadsadapter.utils.Constants.SAS_TAG import com.smartadserver.android.coresdk.util.SCSUtil import com.smartadserver.android.library.thirdpartybidding.SASBannerBidderAdapter import com.smartadserver.android.library.thirdpartybidding.SASBannerBidderAdapterListener import com.smartadserver.android.library.util.SASUtil class SASHuaweiBannerBidderAdapter(adResponse: HuaweiAdResponse, context: Context) : SASHuaweiBaseBidderAdapter( adResponse ), SASBannerBidderAdapter { //Bid Response private val adResponse = adResponse //Huawei Banner view var bannerView: BannerView? = null //Banner parent view group for proper banner sizing var linearLayout: LinearLayout? = null //Callback to notify Smart SDK of events generated by Huawei banner var bannerBidderAdapterListener: SASBannerBidderAdapterListener? = null init { //No ad : abort if (adResponse.multiad?.size == 0) throw IllegalArgumentException("No ad size found for Huawei's banner, we will not render the ad.") //Create Huawei banner listener than will forward events to the SASBannerBidderAdapterListener instance val adListener: AdListener = object : AdListener() { override fun onAdLoaded() { super.onAdLoaded() // pass the linearLayout containing the Huawei banner to the smart SDK Log.d(SAS_TAG, "onAdLoaded: ") linearLayout?.let { bannerBidderAdapterListener?.onBannerLoaded(it) } } override fun onAdFailed(p0: Int) { super.onAdFailed(p0) Log.d(SAS_TAG, "onAdFailed: ") bannerBidderAdapterListener?.adRequestFailed( "Huawei bidder banner ad could not be displayed", false ) } override fun onAdClicked() { super.onAdClicked() Log.d(SAS_TAG, "onAdClicked: ") // ad click to open already handled in onAdOpen, discard any other click } override fun onAdLeave() { super.onAdLeave() Log.d(SAS_TAG, "onAdLeave: ") bannerBidderAdapterListener?.onAdLeftApplication() } override fun onAdOpened() { super.onAdOpened() Log.d(SAS_TAG, "onAdOpened: ") // onAdOpen corresponds to the onAdClicked in the smart SDK bannerBidderAdapterListener?.onAdClicked() } override fun onAdClosed() { super.onAdClosed() Log.d(SAS_TAG, "onAdClosed: ") bannerBidderAdapterListener?.onAdClosed() } override fun onAdImpression() { super.onAdImpression() Log.d(SAS_TAG, "onAdImpression: ") } } bannerView = BannerView(context) bannerView?.adListener = adListener val width: Int? = adResponse.multiad?.get(0)?.content?.get(0)?.metaData?.imageInfo?.get(0)?.width val height: Int? = adResponse.multiad?.get(0)?.content?.get(0)?.metaData?.imageInfo?.get(0)?.height if (width == null || height == null) { throw IllegalArgumentException("No ad size found for Huawei's banner, we will not render the ad.") } // ...and wrap it in the parent Layout with proper size as fetched above linearLayout = LinearLayout(context) linearLayout!!.addView( bannerView, LinearLayout.LayoutParams( SASUtil.getDimensionInPixels(width, context.resources), SASUtil.getDimensionInPixels(height, context.resources) ) ) } override fun loadBidderBanner(bannerAdapterListener: SASBannerBidderAdapterListener) { this.bannerBidderAdapterListener = bannerAdapterListener SCSUtil.getMainLooperHandler().post { //No operation // **HTML MARKUP** } } }
0
Kotlin
0
3
656eb81bda27e217146753ff4a5f8d27952bd297
5,039
huawei.ads.smartad.headerbidding
Apache License 2.0
app/src/main/java/com/andlill/composenotes/app/home/composables/Drawer.kt
AndreasLill
450,794,769
false
{"Kotlin": 190183}
package com.andlill.composenotes.app.home.composables import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.* import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.andlill.composenotes.BuildConfig import com.andlill.composenotes.R import com.andlill.composenotes.model.Label import com.andlill.composenotes.model.NoteFilter import com.andlill.composenotes.utils.DialogUtils @Composable fun Drawer( labels: List<Label>, onFilter: (NoteFilter) -> Unit, onAddLabel: (String) -> Unit, onEditLabels: () -> Unit, onClose: () -> Unit ) { val context = LocalContext.current val selectedId = rememberSaveable { mutableStateOf(-1) } LazyColumn(modifier = Modifier .statusBarsPadding() .navigationBarsPadding() .fillMaxHeight()) { item { Spacer(modifier = Modifier.height(16.dp)) } item { Text( modifier = Modifier.padding(start = 16.dp), text = stringResource(R.string.app_name), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onSurface ) } item { Text( modifier = Modifier.padding(start = 16.dp), text = BuildConfig.VERSION_NAME, fontSize = 13.sp, fontWeight = FontWeight.Normal, color = MaterialTheme.colorScheme.onSurface ) } item { Spacer(modifier = Modifier.height(16.dp)) } item { DrawerItem(selectedId = selectedId.value, id = -1, icon = Icons.Outlined.Notes, text = stringResource(R.string.drawer_item_notes), onClick = { selectedId.value = -1 onFilter(NoteFilter( name = context.resources.getString(R.string.drawer_item_notes), type = NoteFilter.Type.AllNotes )) onClose() }) } item { DrawerItem(selectedId = selectedId.value, id = -2, icon = Icons.Outlined.Alarm, text = stringResource(R.string.drawer_item_reminders), onClick = { selectedId.value = -2 onFilter(NoteFilter( name = context.resources.getString(R.string.drawer_item_reminders), type = NoteFilter.Type.Reminders )) onClose() }) } item { DrawerItem(selectedId = selectedId.value, id = -3, icon = Icons.Outlined.Delete, text = stringResource(R.string.drawer_item_trash), onClick = { selectedId.value = -3 onFilter(NoteFilter( name = context.resources.getString(R.string.drawer_item_trash), type = NoteFilter.Type.Trash )) onClose() }) } item { Divider(modifier = Modifier.padding(top = 16.dp, bottom = 0.dp)) } item { Box(modifier = Modifier .fillMaxWidth() .padding(start = 8.dp, end = 8.dp)) { TextButton( modifier = Modifier.align(Alignment.CenterStart), onClick = { DialogUtils.showInputDialog( title = context.resources.getString(R.string.home_screen_dialog_create_label_title), placeholder = context.resources.getString(R.string.home_screen_dialog_create_label_placeholder), onConfirm = onAddLabel ) }) { Icon( modifier = Modifier.size(18.dp), imageVector = Icons.Outlined.Add, contentDescription = null, ) Spacer(modifier = Modifier.width(4.dp)) Text( text = stringResource(R.string.drawer_item_new_label), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, ) } TextButton( modifier = Modifier.align(Alignment.CenterEnd), onClick = onEditLabels ) { Icon( modifier = Modifier.size(18.dp), imageVector = Icons.Outlined.Edit, contentDescription = null, ) Spacer(modifier = Modifier.width(4.dp)) Text( text = stringResource(R.string.drawer_item_edit), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, ) } } } items(items = labels, key = { label -> label.id }) { label -> DrawerItem( selectedId = selectedId.value, id = label.id, icon = Icons.Outlined.Label, text = label.value, onClick = { selectedId.value = label.id onFilter(NoteFilter( name = label.value, type = NoteFilter.Type.Label, label = label )) onClose() }, ) } } }
0
Kotlin
0
0
2e52901c0e4118e3bcc90c8bbad861ecab25f0b4
6,119
ComposeNotes
Apache License 2.0
src/main/kotlin/no/njoh/pulseengine/modules/graphics/Graphics.kt
NiklasJohansen
239,208,354
false
null
package no.njoh.pulseengine.modules.graphics import no.njoh.pulseengine.data.assets.Texture interface Graphics { val mainCamera: CameraInterface val mainSurface: Surface2D fun createSurface(name: String, zOrder: Int? = null, camera: CameraInterface? = null): Surface2D fun getSurfaceOrDefault(name: String): Surface2D fun getSurface(name: String): Surface2D? fun removeSurface(name: String) } interface GraphicsEngineInterface : Graphics { override val mainCamera: CameraEngineInterface fun init(viewPortWidth: Int, viewPortHeight: Int) fun initTexture(texture: Texture) fun cleanUp() fun updateViewportSize(width: Int, height: Int, windowRecreated: Boolean) fun updateCamera(deltaTime: Float) fun postRender() } interface LineRendererInterface { fun linePoint(x0: Float, y0: Float) fun line(x0: Float, y0: Float, x1: Float, y1: Float) }
0
Kotlin
0
0
d2c0d09732fed1f2221ee17e5a28f0e50857b333
903
PulseEngine
MIT License
yc-app-cli/src/main/kotlin/mikufan/cx/yc/cliapp/config/WebClientBuilderCustomizer.kt
CXwudi
556,059,867
false
null
package mikufan.cx.yc.cliapp.config import io.netty.handler.logging.LogLevel import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.web.reactive.function.client.WebClientCustomizer import org.springframework.http.HttpHeaders import org.springframework.http.client.reactive.ClientHttpConnector import org.springframework.http.client.reactive.ReactorClientHttpConnector import org.springframework.stereotype.Component import org.springframework.web.reactive.function.client.WebClient import reactor.netty.http.client.HttpClient import reactor.netty.transport.logging.AdvancedByteBufFormat /** * @author CX无敌 * 2023-01-04 */ @ConfigurationProperties(prefix = "cliapp.webclient") class WebClientConfig( /** * Do you want to check what does Spring Web 6 Declarative HTTP Client is really doing? * * Then enable this, but be careful, it will also log your bearer token */ val debug: Boolean = false, /** The user-agent, not really matter for YouTrack */ val userAgent: String = "YouCal @ https://github.com/CXwudi/youcal", ) @Component class WebClientBuilderCustomizer( private val config: WebClientConfig, ) : WebClientCustomizer { override fun customize(builder: WebClient.Builder) { if (config.debug) { val httpClient: HttpClient = HttpClient.create() .wiretap(this.javaClass.canonicalName, LogLevel.DEBUG, AdvancedByteBufFormat.TEXTUAL) val conn: ClientHttpConnector = ReactorClientHttpConnector(httpClient) builder.clientConnector(conn) } if (config.userAgent.isNotBlank()) { builder.defaultHeader(HttpHeaders.USER_AGENT, config.userAgent) } } }
5
Kotlin
0
0
75928ac6107c22323029c3517f256508cbaa59f7
1,677
youcal
MIT License
library-store-coroutines/src/test/java/ru/fabit/storecoroutines/TestEvent.kt
FabitMobile
456,836,220
false
null
package ru.fabit.storecoroutines sealed class TestEvent { object Event : TestEvent() { override fun toString(): String { return "TestEvent.Event" } } object Event2 : TestEvent() { override fun toString(): String { return "TestEvent.Event2" } } data class OrderEvent(val order: Int) : TestEvent() }
0
Kotlin
0
0
84f012d86329283c645da21d0e99dd94bb15bd3d
374
store-coroutines
MIT License
app/src/main/java/com/sombrero/cryptocap/features/ticker/list/TickerAdapter.kt
tonihuotari
145,533,443
false
null
package com.sombrero.cryptocap.features.ticker.list import android.support.v7.widget.RecyclerView import android.view.ViewGroup import com.sombrero.cryptocap.common.ActivityNavigator import com.sombrero.cryptomodel.ticker.TickerCoin class TickerAdapter : RecyclerView.Adapter<TickerViewHolder>() { private val HEADER_TYPE = 0 private val ITEM_TYPE = 1 var navigator: ActivityNavigator? = null var coins: List<TickerCoin>? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TickerViewHolder { return when (viewType) { HEADER_TYPE -> TickerHeaderViewHolder.newInstance(parent) ITEM_TYPE -> TickerViewHolder.newInstance(parent) else -> throw IllegalStateException("ViewHolder for type $viewType not implemented") } } override fun getItemCount(): Int { return 1 + (coins?.size ?: 0) } override fun getItemViewType(position: Int): Int { return if (position == 0) HEADER_TYPE else ITEM_TYPE } override fun onBindViewHolder(viewHolder: TickerViewHolder, position: Int) { when (getItemViewType(position)) { HEADER_TYPE -> { } // do nothing ITEM_TYPE -> { val coin = coins!![position - 1] viewHolder.onBind(coin) viewHolder.itemView.setOnClickListener { navigator?.openDetailsActivity(coin.id) } } } } }
0
Kotlin
0
0
87a64568167f481abb100447a901af433eea9ca3
1,453
crypto-cap
Apache License 2.0
part-1.ws.kts
shyzus
733,207,050
false
{"Kotlin": 1232}
import java.io.File import java.lang.IndexOutOfBoundsException import kotlin.system.exitProcess File("input.txt").useLines { lines -> val parsedLines = ArrayList<HashMap<Int, String>>() lines.forEachIndexed { index, line -> if( index > 3) { return@forEachIndexed } val buffer = hashMapOf<Int, String>() line.forEachIndexed { idx, char -> if (char.isDigit()) { buffer[idx] = char.toString() } else if (!char.isDigit() && !char.isLetter() && !char.isWhitespace() && char != '.') { buffer[idx] = char.toString() } } parsedLines.add(buffer) } println(parsedLines) exitProcess(0) parsedLines.forEachIndexed { index, hashMap -> var top: HashMap<Int, String>? = null try { top = parsedLines[index - 1] } catch (exception: IndexOutOfBoundsException) { // do nothing } var bot: HashMap<Int, String>? = null try { bot = parsedLines[index + 1] } catch (exception: IndexOutOfBoundsException) { // do nothing } hashMap.forEach { idx, char -> } } }
0
Kotlin
0
0
c9ccce73232d2d6a0d5c4c73800d0032bec36ed3
1,232
AoC2023-Day-3
MIT License
data/api/src/commonMain/kotlin/io/github/droidkaigi/feeder/data/request/DevicePostRequest.kt
DroidKaigi
283,062,475
false
null
package io.github.droidkaigi.feeder.data.request import kotlinx.serialization.Serializable @Serializable data class DevicePostRequest( val osName: String, ) expect fun platform(): String
45
Kotlin
189
633
3fb47a7b7b245e5a7c7c66d6c18cb7d2a7b295f2
194
conference-app-2021
Apache License 2.0
predict/src/test/kotlin/com/hellena/predict/HellenaApplicationTests.kt
IvanGavlik
415,026,862
false
{"Kotlin": 74020}
package com.hellena.predict import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class HellenaApplicationTests { @Test fun contextLoads() { } }
0
Kotlin
0
0
e7f120ba04d71248c62591b42f82fc2dae5f135f
208
Hellena
Apache License 2.0
src/main/kotlin/org/t3m8ch/budgettelegrambot/services/impl/ExpenseServiceImpl.kt
t3m8ch
565,573,339
false
null
package org.t3m8ch.budgettelegrambot.services.impl import org.springframework.stereotype.Service import org.t3m8ch.budgettelegrambot.models.ExpenseModel import org.t3m8ch.budgettelegrambot.repositories.ExpenseRepository import org.t3m8ch.budgettelegrambot.services.ExpenseService import java.math.BigDecimal @Service class ExpenseServiceImpl(private val expenseRepository: ExpenseRepository) : ExpenseService { override fun add(amount: BigDecimal, userId: Long) { val expense = ExpenseModel(amount = amount, userId = userId) expenseRepository.save(expense) } }
0
Kotlin
0
0
5ceabda338bce892c8743e26bc76980afe083a3d
587
budget-telegram-bot
MIT License
work-managers/src/main/java/com/aetherinsight/work_managers/Constants.kt
OdisBy
828,176,452
false
{"Kotlin": 188880, "Ruby": 6392}
package com.aetherinsight.work_managers object Constants { const val NOTIFICATION_TITLE_KEY = "NOTIFICATION_TITLE_KEY" const val NOTIFICATION_CONTENT_KEY = "NOTIFICATION_CONTENT_KEY" const val NOTIFICATION_TIMEOUT = "NOTIFICATION_TIMEOUT" const val NOTIFICATION_TAG = "MOVIE_NOTIFICATION_TAG" const val EARLY_NOTIFICATION_TAG = "EARLY_MOVIE_NOTIFICATION_TAG" const val ACTION_TAG = "ACTION_MOVIE_TAG" const val ACTION_CONTENT_DATA = "ACTION_CONTENT_DATA" }
1
Kotlin
0
1
7576077a60a27ffaede5b2c62b29f7a8194406f0
485
Golden-Movies
MIT License
year2019/day21/part1/src/test/kotlin/com/curtislb/adventofcode/year2019/day21/part1/Year2019Day21Part1Test.kt
curtislb
226,797,689
false
{"Kotlin": 1905641}
package com.curtislb.adventofcode.year2019.day21.part1 import java.math.BigInteger import kotlin.test.assertEquals import org.junit.jupiter.api.Test /** * Tests the solution to the puzzle for 2019, day 21, part 1. */ class Year2019Day21Part1Test { @Test fun testSolutionWithRealInput() { assertEquals(BigInteger("19357507"), solve()) } }
0
Kotlin
1
1
addf5ae8d002d30abf1ab816e23502a296debc4e
362
AdventOfCode
MIT License
src/main/kotlin/no/nav/tilleggsstonader/sak/vilkår/InngangsvilkårSteg.kt
navikt
685,490,225
false
{"Kotlin": 1741278, "Gherkin": 41585, "HTML": 39172, "Shell": 924, "Dockerfile": 164}
package no.nav.tilleggsstonader.sak.vilkår import no.nav.tilleggsstonader.sak.behandling.BehandlingService import no.nav.tilleggsstonader.sak.behandling.domain.BehandlingStatus import no.nav.tilleggsstonader.sak.behandling.domain.Saksbehandling import no.nav.tilleggsstonader.sak.behandlingsflyt.BehandlingSteg import no.nav.tilleggsstonader.sak.behandlingsflyt.StegType import no.nav.tilleggsstonader.sak.vilkår.stønadsperiode.StønadsperiodeService import org.springframework.stereotype.Service @Service class InngangsvilkårSteg( private val behandlingService: BehandlingService, private val stønadsperiodeService: StønadsperiodeService, ) : BehandlingSteg<Void?> { override fun validerSteg(saksbehandling: Saksbehandling) { stønadsperiodeService.validerStønadsperioder(saksbehandling.id) } override fun utførSteg(saksbehandling: Saksbehandling, data: Void?) { if (saksbehandling.status != BehandlingStatus.UTREDES) { behandlingService.oppdaterStatusPåBehandling(saksbehandling.id, BehandlingStatus.UTREDES) } } /** * håndteres av [StønadsperiodeService] */ override fun settInnHistorikk() = false override fun stegType(): StegType = StegType.INNGANGSVILKÅR }
2
Kotlin
1
0
c998bb4541f32e53252b208e947ca1529c5184a2
1,249
tilleggsstonader-sak
MIT License
jetpackmvvm/src/main/java/com/simplation/mvvm/data/model/enums/CollectType.kt
Simplation
324,966,218
false
null
package com.simplation.mvvm.data.model.enums /** * Collect type * * @property type * @constructor Create empty Collect type */ enum class CollectType(val type: Int) { // 0.文章 Article(0), // 1.网址 Url(1) }
0
Kotlin
0
2
9ff56c255a2f0e28791017ed528650de680a13b6
228
LearnJetpack
Apache License 2.0
src/main/kotlin/briscola/model/StartingPlayerOption.kt
andreazammarchi3
800,911,826
false
{"Kotlin": 62663, "ASL": 12678, "CSS": 1597}
package briscola.model /** * Enum class representing the possible options for the starting player. * - RANDOM: the starting player is randomly chosen. * - PLAYER: the starting player is the human player. * - PLAYER2: the starting player is the bot. */ enum class StartingPlayerOption { RANDOM, PLAYER, BOT; override fun toString(): String { return when (this) { RANDOM -> "Random" PLAYER -> "Player" BOT -> "Bot" } } companion object { /** * Get the corresponding [StartingPlayerOption] from a string. * @param string the string to convert * @return the corresponding [StartingPlayerOption] */ fun fromString(string: String?): StartingPlayerOption { return entries.find { it.toString() == string } ?: RANDOM } } }
0
Kotlin
0
0
922b34b744ee22a60781a1ae3d279b7d434389f9
865
intelligent-briscola
MIT License
client-core/src/main/kotlin/org/sinou/pydia/client/ui/models/AppState.kt
bsinou
434,248,316
false
{"Kotlin": 2133584, "Java": 10237}
package org.sinou.pydia.client.ui.models import org.sinou.pydia.sdk.transport.StateID class AppState( stateID: StateID, val intentID: String?, val route: String?, val context: String?, ) { // We rather rely on the string version of the StateID so that AppState is serializable by default private val stateIDStr: String val stateID: StateID get() = StateID.safeFromId(stateIDStr) init { stateIDStr = stateID.id } companion object { val NONE = AppState( stateID = StateID.NONE, intentID = null, route = null, context = null ) } }
0
Kotlin
0
1
51a128c49a24eedef1baf2d4f295f14aa799b5d3
656
pydia
Apache License 2.0
app/src/main/java/com/example/online_health_app/screens/SearchActivity.kt
lebelokamogelo
723,664,718
false
{"Kotlin": 140820}
package com.example.online_health_app.screens import android.os.Bundle import android.view.View import android.widget.SearchView import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.online_health_app.adapters.ListAdapter import com.example.online_health_app.data.AvailableDoctor import com.example.online_health_app.databinding.ActivitySearchBinding import com.example.online_health_app.model.AppDatabase import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class SearchActivity : AppCompatActivity() { private lateinit var binding: ActivitySearchBinding private lateinit var recyclerView: RecyclerView private lateinit var listAdapter: ListAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySearchBinding.inflate(layoutInflater) setContentView(binding.root) recyclerView = binding.ListRecycleView recyclerView.setHasFixedSize(true) recyclerView.layoutManager = GridLayoutManager(this, 2) // Load the data from Firebase. val availableDoctorList = mutableListOf<AvailableDoctor>() //availableDoctorList.addAll(loadAvailableDoctors()) // Get the database instance val database = AppDatabase.getInstance(this) binding.back.setOnClickListener { finish() } // Store the available doctors in Room val scope = CoroutineScope(Dispatchers.IO) scope.launch { val data = database.availableDoctorDao.getAllAvailableDoctors() for (it in data) { val availableDoctorTable = AvailableDoctor( uuid = it.uuid, name = it.name, specializing = it.specializing, rating = it.rating, experience = it.experience, image = it.image ) availableDoctorList.add(availableDoctorTable) } listAdapter = ListAdapter(availableDoctorList) recyclerView.adapter = listAdapter } binding.search.setOnQueryTextListener(object : SearchView.OnQueryTextListener, androidx.appcompat.widget.SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { return true } override fun onQueryTextChange(newText: String?): Boolean { if (newText.isNullOrBlank()) { // If the search query is empty, show all items in the list listAdapter.filterList(availableDoctorList) binding.ListRecycleView.visibility = View.VISIBLE binding.notFound.visibility = View.GONE } else { // Filter based on the search query val filteredList = availableDoctorList.filter { doctor -> doctor.name.contains( newText, ignoreCase = true ) || doctor.specializing.contains(newText, ignoreCase = true) } if (filteredList.isEmpty()) { binding.notFound.visibility = View.VISIBLE binding.ListRecycleView.visibility = View.GONE } else { listAdapter.filterList(filteredList as MutableList<AvailableDoctor>) binding.notFound.visibility = View.GONE binding.ListRecycleView.visibility = View.VISIBLE } } return true } }) } @Deprecated("Deprecated in Java") override fun onBackPressed() { super.onBackPressed() finish() } }
0
Kotlin
0
0
133fc341c7d10a29242322cb05e75e9bc986659e
4,027
health-app
MIT License
impl-coroutine/ktor-http/src/main/kotlin/playwrigkt/skript/stagemanager/KtorHttpClientStageManager.kt
playwrigkt
125,693,206
false
null
package playwrigkt.skript.stagemanager import io.ktor.client.HttpClient import io.ktor.client.engine.apache.Apache import playwrigkt.skript.coroutine.runAsync import playwrigkt.skript.result.AsyncResult import playwrigkt.skript.troupe.KtorHttpClientTroupe class KtorHttpClientStageManager : StageManager<KtorHttpClientTroupe> { private val httpClient by lazy { HttpClient(Apache) } override fun hireTroupe(): KtorHttpClientTroupe = KtorHttpClientTroupe(httpClient) override fun tearDown(): AsyncResult<Unit> = runAsync { httpClient.close() } }
6
Kotlin
1
1
da3714fd4e6e4910424a15feb7c383b9e961b360
571
skript
Apache License 2.0
src/main/kotlin/com/helltar/artific_intellig_bot/commands/ChatGPTCommand.kt
Helltar
591,327,331
false
null
package com.helltar.artific_intellig_bot.commands import com.annimon.tgbotsmodule.commands.context.MessageContext import com.github.kittinunf.fuel.core.ResponseResultOf import com.github.kittinunf.fuel.core.extensions.jsonBody import com.github.kittinunf.fuel.core.isSuccessful import com.github.kittinunf.fuel.httpPost import com.google.gson.Gson import com.helltar.artific_intellig_bot.DIR_DB import com.helltar.artific_intellig_bot.Strings import com.helltar.artific_intellig_bot.Utils.detectLangCode import com.helltar.artific_intellig_bot.commands.Commands.cmdChatAsVoice import kotlinx.serialization.Serializable import org.json.JSONException import org.json.JSONObject import org.slf4j.LoggerFactory import org.telegram.telegrambots.meta.api.objects.Message import java.io.File import java.util.* /* todo: refact. */ @Serializable private data class Chat(val model: String, val messages: List<ChatMessage>) @Serializable private data class ChatMessage(val role: String, val content: String) private val userContext = hashMapOf<Long, LinkedList<ChatMessage>>() class ChatGPTCommand(ctx: MessageContext, private val chatSystemMessage: String) : BotCommand(ctx) { private val log = LoggerFactory.getLogger(javaClass) private companion object { const val MAX_USER_MESSAGE_TEXT_LENGTH = 300 const val MAX_ADMIN_MESSAGE_TEXT_LENGTH = 1024 const val CHAT_GPT_MODEL = "gpt-3.5-turbo" const val DIALOG_CONTEXT_SIZE = 15 } override fun run() { val message = ctx.message() val isReply = message.isReply var messageId = ctx.messageId() var text = argsText // todo: temp. fix. ._. if (text.isEmpty()) text = message.text if (!isReply) { if (args.isEmpty()) { replyToMessage(Strings.chat_hello) return } } else { if (message.replyToMessage.from.id != ctx.sender.me.id) { text = message.replyToMessage.text ?: return messageId = message.replyToMessage.messageId } } if (args.isNotEmpty()) { when (args[0]) { "rm" -> { clearUserContext() return } "ctx" -> { printUserContext(message, isReply) return } } } val username = message.from.firstName val chatTitle = message.chat.title ?: username val textLength = if (isNotAdmin()) MAX_USER_MESSAGE_TEXT_LENGTH else MAX_ADMIN_MESSAGE_TEXT_LENGTH if (text.length > textLength) { replyToMessage(String.format(Strings.many_characters, textLength)) return } if (userContext.containsKey(userId)) userContext[userId]?.add(ChatMessage("user", text)) else userContext[userId] = LinkedList(listOf(ChatMessage("user", text))) val json: String sendPrompt(username, chatTitle).run { if (second.isSuccessful) json = third.get() else { replyToMessage(Strings.chat_exception) log.error(third.component2()?.message) userContext[userId]?.removeLast() return } } try { val answer = JSONObject(json) .getJSONArray("choices") .getJSONObject(0) .getJSONObject("message") .getString("content") userContext[userId]?.add(ChatMessage("assistant", answer)) if (!File(DIR_DB + cmdChatAsVoice).exists()) replyToMessage(answer, messageId, markdown = true) else { textToSpeech(answer, detectLangCode(answer))?.let { oggBytes -> // todo: tempFile val voice = File.createTempFile("tmp", ".ogg").apply { writeBytes(oggBytes) } sendVoice(voice, messageId) } ?: replyToMessage(Strings.chat_exception) } } catch (e: JSONException) { log.error(e.message) } } private fun clearUserContext() { if (userContext.containsKey(userId)) userContext[userId]?.clear() replyToMessage(Strings.context_removed) } private fun printUserContext(message: Message, isReply: Boolean) { val userId = if (!isReply) this.userId else if (isAdmin()) message.replyToMessage.from.id else return var text = "" if (userContext.containsKey(userId)) { userContext[userId]?.forEachIndexed { index, chatMessage -> if (chatMessage.role == "user") text += "*$index*: " + chatMessage.content + "\n" } } if (text.isEmpty()) text = "▫\uFE0F Empty" replyToMessage(text, markdown = true) } private fun sendPrompt(username: String, chatName: String): ResponseResultOf<String> { val messages = arrayListOf(ChatMessage("system", String.format(chatSystemMessage, chatName, username, userId))) if (userContext[userId]!!.size > DIALOG_CONTEXT_SIZE) { userContext[userId]?.removeFirst() userContext[userId]?.removeFirst() } messages.addAll(userContext[userId]!!) return "https://api.openai.com/v1/chat/completions".httpPost() .header("Content-Type", "application/json") .header("Authorization", "Bearer $openaiKey") .jsonBody(Gson().toJson(Chat(CHAT_GPT_MODEL, messages))) .responseString() } /* https://cloud.google.com/text-to-speech/docs/reference/rest/v1/text/synthesize */ private data class InputData( val text: String ) private data class VoiceData( val languageCode: String, val ssmlGender: String = "FEMALE" ) private data class AudioConfigData( val audioEncoding: String = "OGG_OPUS", val speakingRate: Float = 1.0f ) private data class TextToSpeechJsonData( val input: InputData, val voice: VoiceData, val audioConfig: AudioConfigData ) private fun textToSpeech(text: String, languageCode: String): ByteArray? { var json = Gson().toJson(TextToSpeechJsonData(InputData(text), VoiceData(languageCode), AudioConfigData())) "https://texttospeech.googleapis.com/v1/text:synthesize?fields=audioContent&key=$googleCloudKey".httpPost() .header("Content-Type", "application/json; charset=utf-8") .jsonBody(json) .responseString().run { json = if (second.isSuccessful) third.get() else { log.error(this.third.component2()?.message) return null } } return try { Base64.getDecoder().decode(JSONObject(json).getString("audioContent")) } catch (e: JSONException) { log.error(e.message) null } } }
0
Kotlin
2
9
7800751afbf6446b8d2b13b8817053205c4ab636
7,414
artific_intellig_bot
MIT License
app/router/src/main/java/com/gmail/jiangyang5157/router/fragment/mapping/FragmentMap.kt
jiangyang5157
95,332,458
false
null
package com.gmail.jiangyang5157.router.fragment.mapping import androidx.fragment.app.Fragment import com.gmail.jiangyang5157.kit.data.Key import com.gmail.jiangyang5157.router.core.KeyRoute import com.gmail.jiangyang5157.router.fragment.FragmentElementImpl import com.gmail.jiangyang5157.router.fragment.FragmentRoute import kotlin.reflect.KClass /** * # FragmentMap * Definition of which fragment should be displayed for a certain route * * In order to find fragment mapping, the route should be either [FragmentRoute] or [KeyRoute]. * @see FragmentElementImpl */ interface FragmentMap { /** * @return * - The class of the fragment that should be displayed for the [key] * - `null` if this map does not contain any information about the given [key] */ operator fun get(key: Key): KClass<out Fragment>? }
0
Kotlin
0
0
2487085d73192e25565ae4fe0b430e46df7cd566
842
kotlin-android
Apache License 2.0
src/main/kotlin/io/bvalentino/forum/dto/UserCredentials.kt
brunovalentino-dev
792,003,539
false
{"Kotlin": 39237, "HTML": 1121, "Dockerfile": 156, "Shell": 89, "Procfile": 88}
package io.bvalentino.forum.dto data class UserCredentials( val username: String, val password: String )
0
Kotlin
0
0
d8f0a1ef5b043483494f6af4435f759da5b58624
113
forum
Apache License 2.0
library/src/main/java/com/trendyol/showcase/ui/slidablecontent/SlidableContentAdapter.kt
bilgehankalkan
191,935,274
false
null
package com.trendyol.showcase.ui.slidablecontent import android.graphics.Typeface import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import com.trendyol.showcase.databinding.ItemSlidableContentBinding import com.trendyol.showcase.ui.loadImage import com.trendyol.showcase.ui.setTextSizeInSp internal class SlidableContentAdapter(private val slidableContentList: List<SlidableContent>) : RecyclerView.Adapter<SlidableContentAdapter.ViewPagerViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewPagerViewHolder = ViewPagerViewHolder( ItemSlidableContentBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) override fun onBindViewHolder(holder: ViewPagerViewHolder, position: Int) { holder.bind(slidableContentList[position]) } override fun getItemCount(): Int = slidableContentList.size inner class ViewPagerViewHolder( private val binding: ItemSlidableContentBinding, ) : RecyclerView.ViewHolder(binding.root) { fun bind(item: SlidableContent) { with(binding) { val viewState = SlidableContentViewState(item) with(textViewTitle) { typeface = Typeface.create( viewState.slidableContent.titleTextFontFamily, viewState.slidableContent.titleTextStyle, ) text = viewState.slidableContent.title textAlignment = viewState.getTextPosition() setTextColor(viewState.slidableContent.titleTextColor) isVisible = viewState.isTitleVisible() setTextSizeInSp(viewState.slidableContent.titleTextSize) } with(textViewDescription) { typeface = Typeface.create( viewState.slidableContent.descriptionTextFontFamily, viewState.slidableContent.descriptionTextStyle, ) text = viewState.slidableContent.description textAlignment = viewState.getTextPosition() setTextColor(viewState.slidableContent.descriptionTextColor) isVisible = viewState.isDescriptionVisible() setTextSizeInSp(viewState.slidableContent.descriptionTextSize) } imageView.loadImage(viewState.slidableContent.imageUrl) } } } }
0
Kotlin
10
8
fa998c9760e229d5b9378e7b511ae0a3e7528edb
2,677
showcase
Apache License 2.0
library/inspector/src/test/java/io/mehow/laboratory/inspector/SearchViewModelSpec.kt
MiSikora
271,023,663
false
{"Kotlin": 293428, "Shell": 2768, "HTML": 261, "CSS": 188}
package io.mehow.laboratory.inspector import app.cash.turbine.FlowTurbine import app.cash.turbine.test import io.kotest.core.spec.style.DescribeSpec import io.kotest.matchers.shouldBe import io.mehow.laboratory.inspector.SearchMode.Active import io.mehow.laboratory.inspector.SearchMode.Idle import io.mehow.laboratory.inspector.SearchViewModel.Event.CloseSearch import io.mehow.laboratory.inspector.SearchViewModel.Event.OpenSearch import io.mehow.laboratory.inspector.SearchViewModel.Event.UpdateQuery import io.mehow.laboratory.inspector.SearchViewModel.UiModel internal class SearchViewModelSpec : DescribeSpec({ setMainDispatcher() describe("feature flag searching") { it("has initial idle state") { SearchViewModel().uiModels.test { expectIdleModel() cancel() } } it("can be opened") { val viewModel = SearchViewModel() viewModel.uiModels.test { expectIdleModel() viewModel.sendEvent(OpenSearch) awaitItem() shouldBe UiModel(Active, SearchQuery.Empty) cancel() } } it("updates search queries in active mode") { val viewModel = SearchViewModel() viewModel.uiModels.test { expectIdleModel() viewModel.sendEvent(OpenSearch) awaitItem() viewModel.sendEvent(UpdateQuery("Hello")) awaitItem() shouldBe UiModel(Active, SearchQuery("Hello")) viewModel.sendEvent(UpdateQuery("World")) awaitItem() shouldBe UiModel(Active, SearchQuery("World")) cancel() } } it("ignores queries in idle mode") { val viewModel = SearchViewModel() viewModel.uiModels.test { expectIdleModel() viewModel.sendEvent(UpdateQuery("Hello")) expectNoEvents() cancel() } } it("clears queries when search is closed") { val viewModel = SearchViewModel() viewModel.uiModels.test { expectIdleModel() viewModel.sendEvent(OpenSearch) awaitItem() viewModel.sendEvent(UpdateQuery("Hello")) awaitItem() shouldBe UiModel(Active, SearchQuery("Hello")) viewModel.sendEvent(CloseSearch) expectIdleModel() cancel() } } } }) private suspend fun FlowTurbine<UiModel>.expectIdleModel() { awaitItem() shouldBe UiModel(Idle, SearchQuery.Empty) }
12
Kotlin
3
75
4053b2e2e9e5c1500e0e33b44713c9be11300993
2,356
laboratory
Apache License 2.0
lib/setting/src/test/kotlin/moe/pine/meteorshower/setting/repositories/UserOptionRepositoryTest.kt
pine
177,103,749
false
null
package moe.pine.meteorshower.setting.repositories import moe.pine.meteorshower.setting.models.UserOption import org.junit.Assert.* import org.junit.Before import org.junit.Test class UserOptionRepositoryTest : TestBase() { private lateinit var userOptionRepository: UserOptionRepository @Before override fun setUp() { super.setUp() userOptionRepository = sqlSession.getMapper(UserOptionRepository::class.java) } @Test fun findByUserIdTest() { val userOption = UserOption( userId = 12345L, excludeForked = true, excludeGist = true ) val insertedCount = userOptionRepository.add(userOption) assertEquals(1, insertedCount) val foundUser = userOptionRepository.findByUserId(userOption.userId) ?: return fail() assertEquals(userOption.userId, foundUser.userId) assertEquals(userOption.excludeForked, foundUser.excludeForked) assertEquals(userOption.excludeGist, foundUser.excludeGist) assertNotNull(foundUser.createdAt) assertNotNull(foundUser.updatedAt) } @Test fun insertOrUpdateTest() { val userOption = UserOption( userId = 12345L, excludeForked = false, excludeGist = false ) val excludedUserOption = userOption.copy( excludeForked = true, excludeGist = true ) val insertedCount = userOptionRepository.insertOrUpdate(userOption) assertEquals(1, insertedCount) val insertedUserOption = userOptionRepository.findByUserId(userOption.userId) ?: return fail() assertEquals(userOption.userId, insertedUserOption.userId) assertEquals(userOption.excludeForked, insertedUserOption.excludeForked) assertEquals(userOption.excludeGist, insertedUserOption.excludeGist) assertNotNull(insertedUserOption.createdAt) assertNotNull(insertedUserOption.updatedAt) val updatedCount = userOptionRepository.insertOrUpdate(excludedUserOption) assertEquals(2, updatedCount) val updatedUserOption = userOptionRepository.findByUserId(userOption.userId) ?: return fail() assertEquals(userOption.userId, updatedUserOption.userId) assertEquals(excludedUserOption.excludeForked, updatedUserOption.excludeForked) assertEquals(excludedUserOption.excludeGist, updatedUserOption.excludeGist) assertEquals(insertedUserOption.createdAt, updatedUserOption.createdAt) } }
0
Kotlin
0
0
0f9bffd7066283fa8cb63275378ce30eaef30e0d
2,689
meteorshower-server
MIT License
app/src/main/kotlin/example/maester/utils/SharedPreferencesHelper.kt
leonardis
129,817,643
false
null
package example.maester.utils import android.content.SharedPreferences import com.google.gson.Gson class SharedPreferencesHelper constructor(var sharedPreferences: SharedPreferences, var gson: Gson) { private var editor: SharedPreferences.Editor = sharedPreferences.edit() @Synchronized fun setSuggestions(suggestions: List<*>?) { setDataToSharedPref(gson.toJsonTree(suggestions, List::class.java) .toString(), String::class.java, "suggestions") } @Synchronized fun getSuggestions(): List<*>? { return gson.fromJson((getDataFromSharedPref(String::class.java, "suggestions")) as String?, List::class.java) } @Synchronized fun <T> getDataFromSharedPref(dataType: Class<T>, key: String): Any? = when (dataType) { Int::class.java -> sharedPreferences.getInt(key, 0) String::class.java -> sharedPreferences.getString(key, "") Long::class.java -> sharedPreferences.getLong(key, 0) Float::class.java -> sharedPreferences.getFloat(key, 0f) Boolean::class.java -> sharedPreferences.getBoolean(key, false) else -> null } @Synchronized fun <T> setDataToSharedPref(data: T, dataType: Class<T>, key: String) { when (dataType) { Int::class.java -> editor.putInt(key, data as Int) String::class.java -> editor.putString(key, data as String) Long::class.java -> editor.putLong(key, data as Long) Float::class.java -> editor.putFloat(key, data as Float) Boolean::class.java -> editor.putBoolean(key, data as Boolean) } editor.commit() } }
0
Kotlin
1
0
dbfde5ea9155c0d0f3f773c74a7c2e9252501886
1,728
maester
Apache License 2.0
sdk/src/commonMain/kotlin/io/timemates/sdk/authorization/email/requests/ConfigureNewAccountRequest.kt
timemates
575,534,072
false
{"Kotlin": 150561}
package io.timemates.sdk.authorization.email.requests import io.timemates.sdk.authorization.email.types.value.VerificationHash import io.timemates.sdk.authorization.sessions.types.Authorization import io.timemates.sdk.common.types.TimeMatesEntity import io.timemates.sdk.common.types.TimeMatesRequest import io.timemates.sdk.users.profile.types.value.UserDescription import io.timemates.sdk.users.profile.types.value.UserName public data class ConfigureNewAccountRequest( val verificationHash: VerificationHash, val name: UserName, val description: UserDescription?, ) : TimeMatesRequest<ConfigureNewAccountRequest.Result>() { public companion object Key : TimeMatesRequest.Key<ConfigureNewAccountRequest> public data class Result(val authorization: Authorization) : TimeMatesEntity() override val requestKey: Key get() = Key }
2
Kotlin
0
9
8d542c313773fbda8127ed8e1dc2d20a70107b19
863
sdk
MIT License
watari-discovery-gateway/src/main/kotlin/tv/dotstart/watari/discovery/gateway/registry/GatewayDiscoveryServiceRegistry.kt
dotStart
517,175,816
false
null
/* * Copyright 2022 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * 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 tv.dotstart.watari.discovery.gateway.registry import tv.dotstart.watari.common.service.registry.ServiceRegistry import tv.dotstart.watari.discovery.gateway.GatewayDiscoveryService import java.net.InetAddress import java.net.NetworkInterface /** * Provides a registry of installed gateway discovery services. * * @author Johannes Donath * @date 15/07/2022 * @since 0.1.0 */ interface GatewayDiscoveryServiceRegistry : ServiceRegistry<GatewayDiscoveryService> { companion object { /** * Provides a default class loader which relies on [ServiceTransportLoader]. */ val DEFAULT: GatewayDiscoveryServiceRegistry by lazy { ServiceLoaderGatewayDiscoveryServiceRegistry(ClassLoader.getSystemClassLoader()) } } /** * Performs a gateway discovery across the list of available discovery services in order of their * respective associated priority. * * This function will keep querying services until at least one of the available services returns * an acceptable value or the list is exhausted. */ fun discover(): Pair<NetworkInterface, InetAddress>? = this.available .sortedByDescending(GatewayDiscoveryService::priority) .firstNotNullOf(GatewayDiscoveryService::discover) }
0
Kotlin
0
0
13214a53df9d144c6e0c81e543b4f2a0326bc6c8
1,948
watari
Apache License 2.0
app/src/main/java/com/eroom/erooja/feature/ongoingGoal/OngoingGoalContract.kt
YAPP-16th
235,351,786
false
null
package com.eroom.erooja.feature.ongoingGoal import com.eroom.data.entity.MinimalTodoListDetail import com.eroom.data.request.GoalAbandonedRequest import com.eroom.data.response.GoalDetailResponse interface OngoingGoalContract { interface View { fun setGoalData(goalData: GoalDetailResponse) fun setTodoList(todoList: ArrayList<MinimalTodoListDetail>) fun reRequestTodoList() fun onAbandonedSuccess() fun onAbandonedFailure() fun settingEditButton(isMine: Boolean) fun settingDate(startDt: String, endDt: String) fun stopAnimation() } interface Presenter { var view: View fun getData(goalId: Long) fun getTodoData(uid: String, goalId: Long) fun onCleared() fun setTodoEnd(todoId: Long, boolean: Boolean) fun setGoalIsAbandoned(goalId: Long, abandonedRequest: GoalAbandonedRequest) fun getGoalInfo(goalId: Long) } }
15
Kotlin
5
14
c762fbf4ff35bfe7a2d4a0cfc4ffb11a23fb86c0
953
Team_Android_1_Client
Apache License 2.0
TeamCode/src/main/kotlin/org/firstinspires/ftc/teamcode/subsystem/output/drivetrain/OutputMotorGroup.kt
sollyucko
215,169,829
false
{"Java": 40541, "Kotlin": 35158, "Python": 32910}
package org.firstinspires.ftc.teamcode.subsystem.output.drivetrain import com.qualcomm.robotcore.hardware.DcMotor import com.qualcomm.robotcore.hardware.DcMotorSimple import org.firstinspires.ftc.teamcode.math.AngularVelocity import org.firstinspires.ftc.teamcode.math.TickCount import org.firstinspires.ftc.teamcode.math.TickCountPerAngle class OutputMotorGroup(vararg val motors: OutputMotor) : OutputMotor { override fun close() { for(motor in motors) { motor.close() } } override fun increaseTargetPosition(change: TickCount) { for(motor in motors) { motor.increaseTargetPosition(change) } } override fun resetDeviceConfigurationForOpMode() { for(motor in motors) { motor.resetDeviceConfigurationForOpMode() } } override fun setDirection(value: DcMotorSimple.Direction) { for(motor in motors) { motor.setDirection(value) } } override fun setGearing(value: Double) { for(motor in motors) { motor.setGearing(value) } } override fun setMaxAchievableSpeedFraction(value: Double) { for(motor in motors) { motor.setMaxAchievableSpeedFraction(value) } } override fun setMode(value: DcMotor.RunMode) { for(motor in motors) { motor.setMode(value) } } override fun setMaxSpeed(value: AngularVelocity) { for(motor in motors) { motor.setMaxSpeed(value) } } override fun setSpeed(value: AngularVelocity) { for(motor in motors) { motor.setSpeed(value) } } override fun setTargetPosition(value: TickCount) { for(motor in motors) { motor.setTargetPosition(value) } } override fun setTickCountPerAngle(value: TickCountPerAngle) { for(motor in motors) { motor.setTickCountPerAngle(value) } } override fun setPower(value: Double) { for(motor in motors) { motor.setPower(value) } } override fun setZeroPowerBehavior(value: DcMotor.ZeroPowerBehavior) { for(motor in motors) { motor.setZeroPowerBehavior(value) } } }
1
null
1
1
7ff516d0fafa69df25055b94a26072e85e15bff8
2,321
ftc_app
MIT License
role-admin/src/test/java/org/rfcx/guardian/admin/comms/swm/SwmApiCSTest.kt
rfcx
7,535,854
false
{"Gradle": 11, "Java Properties": 2, "Shell": 67, "Text": 29, "Ignore List": 10, "Batchfile": 2, "Markdown": 4, "INI": 1, "JSON": 37, "Proguard": 7, "Kotlin": 66, "XML": 159, "Java": 238, "Makefile": 170, "C": 541, "Python": 13, "Perl": 7, "Roff Manpage": 7, "Public Key": 1, "HTML": 165, "JavaScript": 4, "C++": 20, "M4Sugar": 39, "RPM Spec": 2, "CSS": 4, "OpenStep Property List": 2, "Microsoft Visual Studio Solution": 5, "Cue Sheet": 50, "CUE": 1, "Unity3D Asset": 80, "Java Server Pages": 1, "SVG": 2, "Assembly": 3, "M4": 1, "Unix Assembly": 2, "Dockerfile": 1}
package org.rfcx.guardian.admin.comms.swm import org.junit.Test import org.rfcx.guardian.admin.comms.swm.api.SwmApi import org.rfcx.guardian.admin.comms.swm.api.SwmConnection import kotlin.test.assertEquals import kotlin.test.assertNotNull class SwmApiCSTest { @Test fun canGetSwarmId() { // Arrange val shell = SwmMockShell(listOf("\$CS DI=0x000e57,DN=TILE*10")) val api = SwmApi(SwmConnection(shell)) // Act val deviceId = api.getSwarmDeviceId() // Assert assertNotNull(deviceId) assertEquals("000e57", deviceId) } }
21
C
0
0
627594651e0665b17f2990187c1c5d86ced1c199
601
rfcx-guardian-android
Apache License 2.0
src/main/kotlin/dev/afonsogarcia/pbxmanager/handler/GetCallHistoryHandler.kt
PBX-Manager
612,347,113
false
null
package dev.afonsogarcia.pbxmanager.handler import dev.afonsogarcia.pbxmanager.service.CallHistoryService import org.springframework.stereotype.Component import org.springframework.web.reactive.function.server.ServerRequest import org.springframework.web.reactive.function.server.ServerResponse import org.springframework.web.reactive.function.server.ServerResponse.ok import org.springframework.web.reactive.function.server.bodyValueAndAwait @Component class GetCallHistoryHandler( private val callHistoryService: CallHistoryService ) { suspend fun handleRequest(request: ServerRequest): ServerResponse = ok().bodyValueAndAwait(callHistoryService.getCallHistory()) }
2
Kotlin
0
1
1dbbfe4a9db76100a59ac7c7726099105582ebc0
686
pbx-manager
MIT License
app/src/main/java/ru/lopatin/mvvm_pattern_kotlin/ui/fragments/BulgakovFragment.kt
MyAndroidProjects
267,484,590
false
null
package ru.lopatin.mvvm_pattern_kotlin.ui.fragments import androidx.lifecycle.ViewModelProviders import androidx.databinding.DataBindingUtil import android.os.Bundle import androidx.fragment.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.coroutines.ExperimentalCoroutinesApi import ru.lopatin.mvvm_pattern_kotlin.R import ru.lopatin.mvvm_pattern_kotlin.databinding.FragmentBulgakovBinding import ru.lopatin.mvvm_pattern_kotlin.view_models.BulgakovFragmentViewModel import ru.lopatin.mvvm_pattern_kotlin.view_models.MainActivityViewModel class BulgakovFragment : Fragment() { companion object { @Synchronized fun getInstance(): BulgakovFragment { return BulgakovFragment() } } private lateinit var viewModel: BulgakovFragmentViewModel private lateinit var mainActivityViewModel: MainActivityViewModel private lateinit var binding: FragmentBulgakovBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) activity?.let { /** * если надо общаться междлу двуми ViewModel необходимо передавать активити, к которой принадлежат фрагменты * иначе будут созданы разные ViewModel */ viewModel = ViewModelProviders.of(it).get(BulgakovFragmentViewModel::class.java) mainActivityViewModel = ViewModelProviders.of(it).get(MainActivityViewModel::class.java) } binding = DataBindingUtil.inflate(inflater, R.layout.fragment_bulgakov, container, false) val myView: View = binding.root binding.bulgakovFragmentViewModel = viewModel binding.handler = ClickHandler() return myView } override fun onStart() { super.onStart() Log.d("myLog", "buttonNextPageSelected") viewModel.fragmentIsStarting() } @ExperimentalCoroutinesApi override fun onStop() { viewModel.fragmentIsStopping() super.onStop() } inner class ClickHandler { fun buttonNextPageSelected() { Log.d("myLog", "buttonNextPageSelected") viewModel.buttonNextPageSelected() } fun buttonBelyaevSelected() { Log.d("myLog", "buttonBelyaevSelected") mainActivityViewModel.belyaevButtonSelect() } } }
0
Kotlin
0
0
0bd6fbd1fbf724790506c294b3862fa636f4f58b
2,510
MVVMBookReaderImitation
MIT License
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/pages/WikipageVersion.kt
alatushkin
156,866,851
false
null
package name.alatushkin.api.vk.generated.pages open class WikipageVersion( val id: Long? = null, val length: Long? = null, val edited: Long? = null, val editorId: Long? = null, val editorName: String? = null )
2
Kotlin
3
10
123bd61b24be70f9bbf044328b98a3901523cb1b
231
kotlin-vk-api
MIT License
ret-plugin/src/test/kotlin/io/rabobank/ret/commands/PluginConfigureCommandTest.kt
rabobank
626,324,322
false
{"Kotlin": 81181, "Shell": 11977, "Java": 7849, "Dockerfile": 516}
package io.rabobank.ret.commands import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import io.mockk.every import io.mockk.mockk import io.rabobank.ret.RetConsole import io.rabobank.ret.configuration.version.VersionProperties import org.apache.commons.io.FileUtils import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.fail import org.junit.jupiter.api.io.TempDir import picocli.CommandLine.Model.CommandSpec import java.nio.file.Files import java.nio.file.Path class PluginConfigureCommandTest { private lateinit var command: PluginConfigureCommand private val objectMapper = jacksonObjectMapper() private val pluginName = "demo" private val retConsole = mockk<RetConsole>(relaxed = true) { every { prompt(any(), any()) } answers { fail { "No prompt configured for args '$args'" } } } private val pluginsPath by lazy { val retFolder = Files.createDirectory(mockUserHomeDirectory.resolve(".ret")) val pluginsPath = Files.createDirectory(retFolder.resolve("plugins")) val demoPlugin = "$pluginName-plugin.dylib" Files.createFile(pluginsPath.resolve(demoPlugin)) pluginsPath } private val config by lazy { TestConfig(pluginsPath) } @TempDir lateinit var mockUserHomeDirectory: Path @BeforeEach fun before() { command = PluginConfigureCommand(config, retConsole, jacksonObjectMapper(), VersionProperties()) command.commandSpec = CommandSpec.create() .parent(CommandSpec.create().name(pluginName)) } @AfterEach fun tearDown() { FileUtils.deleteQuietly(mockUserHomeDirectory.toFile()) } @Test fun newProperty() { every { retConsole.prompt("Enter your project:", any()) } returns "myProject" every { retConsole.prompt("Enter your organisation:", any()) } returns "myOrganisation" command.run() val pluginConfig = readConfig() assertThat(pluginConfig).containsExactlyInAnyOrderEntriesOf( mapOf( "project" to "myProject", "organisation" to "myOrganisation", "plugin_version" to "unknown", ), ) } @Test fun overwriteExistingProperty() { val demoConfig = mapOf( "project" to "oldProject", "organisation" to "oldOrganisation", ) storeConfig(demoConfig) every { retConsole.prompt("Enter your project:", "oldProject") } returns "newProject" every { retConsole.prompt("Enter your organisation:", "oldOrganisation") } returns "newOrganisation" command.run() val pluginConfig = readConfig() assertThat(pluginConfig).containsExactlyInAnyOrderEntriesOf( mapOf( "project" to "newProject", "organisation" to "newOrganisation", "plugin_version" to "unknown", ), ) } @Test fun overwriteExistingPropertyWithDefaults() { val demoConfig = mapOf( "project" to "oldProject", "organisation" to "oldOrganisation", "plugin_version" to "unknown", ) storeConfig(demoConfig) every { retConsole.prompt("Enter your project:", "oldProject") } returns "" every { retConsole.prompt("Enter your organisation:", "oldOrganisation") } returns "" command.run() val pluginConfig = readConfig() assertThat(pluginConfig).containsExactlyInAnyOrderEntriesOf(demoConfig) } private fun storeConfig(demoConfig: Map<String, String>) { demoConfig.forEach { (k, v) -> config[k] = v } } private fun readConfig() = objectMapper.readValue<Map<String, String>>(pluginsPath.resolve("$pluginName.json").toFile()) }
1
Kotlin
2
16
1e2e26f9c770d3106a55a9b782b8b934a5dfaf60
3,997
ret-engineering-tools
MIT License
app/src/main/java/com/adyen/testcards/domain/PaymentMethods.kt
Adyen
865,958,261
false
{"Kotlin": 112287, "Shell": 536}
package com.adyen.testcards.domain data class PaymentMethods( val creditCards: List<CreditCardGroup> = emptyList(), val giftCards: List<GiftCard> = emptyList(), val ibans: List<IBAN> = emptyList(), val upis: List<UPI> = emptyList(), val usernamePasswords: List<UsernamePassword> = emptyList(), ) { fun isEmpty(): Boolean = creditCards.isEmpty() && giftCards.isEmpty() && ibans.isEmpty() && upis.isEmpty() && usernamePasswords.isEmpty() } data class CombinedPaymentMethods( val favoriteCreditCards: List<CreditCard> = emptyList(), val favoriteGiftCards: List<GiftCard> = emptyList(), val favoriteIBANs: List<IBAN> = emptyList(), val favoriteUPIs: List<UPI> = emptyList(), val favoriteUsernamePasswords: List<UsernamePassword> = emptyList(), val creditCards: List<CreditCardGroup> = emptyList(), val giftCards: List<GiftCard> = emptyList(), val ibans: List<IBAN> = emptyList(), val upis: List<UPI> = emptyList(), val usernamePasswords: List<UsernamePassword> = emptyList(), ) { fun isEmpty(): Boolean = favoriteCreditCards.isEmpty() && favoriteGiftCards.isEmpty() && favoriteIBANs.isEmpty() && favoriteUPIs.isEmpty() && favoriteUsernamePasswords.isEmpty() && creditCards.isEmpty() && giftCards.isEmpty() && ibans.isEmpty() && upis.isEmpty() && usernamePasswords.isEmpty() fun hasFavorites() = favoriteCreditCards.isNotEmpty() || favoriteGiftCards.isNotEmpty() || favoriteIBANs.isNotEmpty() || favoriteUPIs.isNotEmpty() || favoriteUsernamePasswords.isNotEmpty() }
4
Kotlin
0
2
9dc3c55092c8c192580412ecc8b99f914e87f40f
1,674
adyen-testcards-android
MIT License
mobile/Stockii/app/src/main/java/me/vidrox/stockii/listeners/RequestListener.kt
VidroX
218,940,779
false
{"TypeScript": 344534, "Kotlin": 90669, "Python": 88408, "Dockerfile": 959, "HTML": 857, "CSS": 714, "Shell": 622}
package me.vidrox.stockii.listeners interface RequestListener<T: Any> { fun onRequest() fun onSuccess(result: T?) fun onError(responseCode: Int, errorCode: Int, errorMessage: String) }
0
TypeScript
0
0
237f30aa4b3b061bc0e9a1362c7ab66375feb59e
199
stockii
Apache License 2.0
lib_character_search/src/main/java/com/ezike/tobenna/starwarssearch/lib_character_search/domain/model/Specie.kt
Ezike
294,171,829
false
null
package com.ezike.tobenna.starwarssearch.lib_character_search.domain.model data class Specie( val name: String, val language: String, val homeWorld: String )
0
Kotlin
28
172
792caabf5a29b8bb4698c36c3257916a1cf6611d
171
StarWarsSearch-MVI
Apache License 2.0
common/src/main/java/com/pt/common/mutual/adapter/GlobalAdapterLong.kt
OmAr-Kader
674,357,483
false
{"Kotlin": 2780433}
package com.pt.common.mutual.adapter abstract class GlobalAdapterLong<VB : androidx.viewbinding.ViewBinding, I>( protected val binder: VB ) : GlobalAdapt<I>(binder.root as android.view.ViewGroup), android.view.View.OnLongClickListener { @com.pt.common.global.UiAnn override fun bind() { binder.bind() } @com.pt.common.global.UiAnn protected abstract fun VB.bind() @com.pt.common.global.UiAnn override fun attach() { posA.let { binder.attach(it.item, it) } } @com.pt.common.global.UiAnn protected abstract fun VB.attach(it: I, i: Int) @com.pt.common.global.UiAnn override fun clear() { binder.clear() } @com.pt.common.global.UiAnn protected abstract fun VB.clear() override fun onClick(v: android.view.View?) { v?.onClick(posA.item) } abstract fun android.view.View.onClick(it: I) override fun onLongClick(v: android.view.View?): Boolean { return v?.onLongClick(posA.item) ?: false } abstract fun android.view.View.onLongClick(it: I): Boolean }
0
Kotlin
0
0
fe57fe5a4029119ac287ab8d3d4b5ccfc05af3a0
1,108
PT-All-Pro
Apache License 2.0
src/main/kotlin/de/sirywell/handlehints/dfa/MethodHandleTypeResolver.kt
SirYwell
551,940,996
false
{"Kotlin": 142648, "Java": 19299, "HTML": 268}
package de.sirywell.handlehints.dfa import com.intellij.openapi.util.RecursionManager.doPreventingRecursion import com.intellij.psi.* import com.intellij.psi.util.childrenOfType import de.sirywell.handlehints.type.BotSignature import de.sirywell.handlehints.type.MethodHandleType class MethodHandleTypeResolver(private val ssaAnalyzer: SsaAnalyzer, private val block: SsaConstruction.Block) : JavaRecursiveElementVisitor() { var result: MethodHandleType? = null private set override fun visitSwitchExpression(expression: PsiSwitchExpression) { val rules = (expression.body ?: return).childrenOfType<PsiSwitchLabeledRuleStatement>() var r = MethodHandleType(BotSignature) for (rule in rules) { rule.body?.accept(this) ?: continue r = r.join(result ?: continue) } result = r } override fun visitExpressionStatement(statement: PsiExpressionStatement) { statement.expression.accept(this) } override fun visitExpression(expression: PsiExpression) { result = calculateType(expression) } override fun visitConditionalExpression(expression: PsiConditionalExpression) { val then = calculateType(expression.thenExpression ?: return) ?: MethodHandleType(BotSignature) val elsa = calculateType(expression.elseExpression ?: return) ?: MethodHandleType(BotSignature) result = then.join(elsa) } override fun visitParenthesizedExpression(expression: PsiParenthesizedExpression) { result = calculateType(expression.expression ?: return) } private fun calculateType(expression: PsiExpression): MethodHandleType? { return ssaAnalyzer.typeData[expression] // SsaAnalyzer might call us again. Prevent SOE ?: doPreventingRecursion(expression, true) { ssaAnalyzer.resolveMhType(expression, block) } } }
18
Kotlin
0
5
5f40947adb1c64a5b951a9c9511687eeaddc4f92
1,921
HandleHints
MIT License
src/main/kotlin/AslCaller.kt
nikolasrist
445,562,081
false
{"Kotlin": 13656, "Shell": 6380, "Batchfile": 2938}
class AslCaller private constructor( val input: String?, val output: String?, val mask: String?, val spatial: String?, val whitePaperMode: String?, val motionCorrection: String?, val infert1: String?, val iaf: String?, // <diff, tc, ct> val ibf: String?, // <rpt,tis> val casl: String?, val tis: String?, // <csv> val bolus: String?, // <value> or <csv> val slicedt: String?, val bat: String?, val t1: String?, val t1b: String?, val sliceband: String?, val rpts: String?, //csv val fslAnatOutput: String?, // output directory val calibration: String?, // -c <image_path> val calibrationTr: String?, // --tr=<value> val calibrationGain: String?, // --tr=<value> val calibrationTissref: String?, val calibrationT1csf: String?, val calibrationT2csf: String?, val calibrationT2bl: String?, val calibrationTe: String?, val calibrationAlpha: String?, // --tr=<value> val calibrationMethod: String?, // --cmethod=<single, voxel> val calibrationM0: String?, // --M0=<value> val alpha: String?, val fixbolus: String?, val artoff: String?, var echospacing: String?, var region_analysis: String?, var region_analysis_atlas: String?, var region_analysis_atlas_labels: String?, var pvcorr: String?, var pedir: String?, var cblip: String? ) { val INITIAL_CALL_STRING = "oxford_asl " fun toCallString(): String { return INITIAL_CALL_STRING.appendValue(this.input) .appendValue(this.iaf) .appendValue(this.ibf) .appendValue(this.casl) .appendValue(this.bolus) .appendValue(this.rpts) .appendValue(this.tis) .appendValue(this.fslAnatOutput) .appendValue(this.region_analysis) .appendValue(this.region_analysis_atlas) .appendValue(this.region_analysis_atlas_labels) .appendValue(this.calibration) .appendValue(this.calibrationMethod) .appendValue(this.calibrationTr) .appendValue(this.calibrationGain) .appendValue(this.output) .appendValue(this.bat) .appendValue(this.t1) .appendValue(this.t1b) .appendValue(this.alpha) .appendValue(this.fixbolus) .appendValue(this.artoff) .appendValue(this.spatial) .appendValue(this.whitePaperMode) .appendValue(this.motionCorrection) .appendValue(this.infert1) .appendValue(this.calibrationTissref) .appendValue(this.slicedt) .appendValue(this.sliceband) .appendValue(this.calibrationAlpha) .appendValue(this.calibrationT1csf) .appendValue(this.calibrationT2csf) .appendValue(this.calibrationT2bl) .appendValue(this.calibrationTe) .appendValue(this.calibrationM0) .appendValue(this.pvcorr) .appendValue(this.pedir) .appendValue(this.cblip) .appendValue(this.echospacing) } private fun String.appendValue(value: String?): String { return this + (value ?: "") } data class Builder( var input: String? = null, var output: String? = null, var mask: String? = null, var spatial: String? = null, var artoff: String? = null, var fixbolus: String? = null, var alpha: String? = null, var whitePaperMode: String? = null, var motionCorrection: String? = null, var iaf: String? = null, // <diff, tc, ct> var ibf: String? = null, // <rpt,tis> var casl: String? = null, var tis: String? = null, // <csv> var bolus: String? = null, // <value> or <csv> var slicedt: String? = null, var bat: String? = null, var t1: String? = null, var t1b: String? = null, var sliceband: String? = null, var rpts: String? = null, //csv var fslAnatOutput: String? = null, // output directory var calibration: String? = null, // -c <image_path> var calibrationTr: String? = null, // --tr=<value> var calibrationGain: String? = null, // --tr=<value> var calibrationTissref: String? = null, var calibrationT1csf: String? = null, var calibrationT2csf: String? = null, var calibrationT2bl: String? = null, var calibrationTe: String? = null, var calibrationAlpha: String? = null, // --tr=<value> var calibrationMethod: String? = null, // --cmethod=<single, voxel> var calibrationM0: String? = null, // --M0=<value> var echospacing: String? = null, var region_analysis: String? = null, var region_analysis_atlas: String? = null, var region_analysis_atlas_labels: String? = null, var infert1: String? = null, var pvcorr: String? = null, var pedir: String? = null, var cblip: String? = null ) { fun input(inputPath: String) = apply { this.input = " -i ${inputPath}" } fun output(outputPath: String) = apply { this.output = " -o ${outputPath}" } fun mask(mask: String) = apply { this.mask = " -m ${mask}" } fun spatial() = apply { this.spatial = " --spatial" } fun whitePaperMode() = apply { this.whitePaperMode = " --wp" } fun motionCorrection() = apply { this.motionCorrection = " --mc" } fun iaf(value: String) = apply { this.iaf = " --iaf ${value}" } fun ibf(value: String) = apply { this.ibf = " --ibf ${value}" } fun casl() = apply { this.casl = " --casl" } fun tis(value: List<String>) = apply { this.tis = " --tis=${transformToCSV(value)}" } fun bolus(value: List<String>) = apply { this.bolus = " --bolus ${transformToCSV(value)}" } fun slicedt(value: String) = apply { this.slicedt = " --slicedt ${value}" } fun bat(value: String) = apply { this.bat = " --bat ${value}" } fun t1(value: String) = apply { this.t1 = " --t1 ${value}" } fun t1b(value: String) = apply { this.t1b = " --t1b ${value}" } fun sliceband(value: String) = apply { this.sliceband = " --sliceband ${value}" } fun rpts(value: List<String>) = apply { this.rpts = " --rpts ${transformToCSV(value)}" } fun fslAnat(outputPath: String) = apply { this.fslAnatOutput = " --fslanat=${outputPath}" } fun calibration(imagePath: String) = apply { this.calibration = " -c ${imagePath}" } fun calibrationTr(value: String) = apply { this.calibrationTr = " --tr ${value}" } fun calibrationGain(value: String) = apply { this.calibrationGain = " --cgain ${value}" } fun calibrationTissref(value: String) = apply { this.calibrationTissref = " --tissref ${value}" } fun calibrationT1csf(value: String) = apply { this.calibrationT1csf = " --t1csf ${value}" } fun calibrationT2csf(value: String) = apply { this.calibrationT2csf = " --t2csf ${value}" } fun calibrationT2bl(value: String) = apply { this.calibrationT2bl = " --t2bl ${value}" } fun calibrationTe(value: String) = apply { this.calibrationTe = " --te ${value}" } fun tissref(value: String) = apply { this.calibrationTissref = " --tissref=${value}" } fun calibrationAlpha(value: String) = apply { this.calibrationAlpha = " --alpha ${value}" } fun calibrationMethod(value: String) = apply { this.calibrationMethod = " --cmethod ${value}" } fun calibrationM0(value: String) = apply { this.calibrationM0 = " --M0 ${value}" } fun alpha(value: String) = apply { this.alpha = " --alpha ${value}" } fun fixbolus() = apply { this.fixbolus = " --fixbolus" } fun artoff() = apply { this.artoff = " --artoff" } fun echospacing(value: String) = apply { this.echospacing = " --echospacing=${value}" } fun region_analysis() = apply { this.region_analysis = " --region-analysis" } fun region_analysis_atlas(value: String?) = apply { if (value != null) this.region_analysis_atlas = " --region-analysis-atlas=${value}" else this.region_analysis_atlas = "" } fun region_analysis_atlas_labels(value: String?) = apply { if (value != null) this.region_analysis_atlas_labels = " --region-analysis-atlas-labels=${value}" else this.region_analysis_atlas_labels = "" } fun infert1() = apply { this.infert1 = " --infert1" } fun pvcorr() = apply { this.pvcorr = " --pvcorr" } fun pedir() = apply { this.pedir = " --pedir y" } fun cblip(value: String) = apply { this.cblip = " --cblip ${value}" } fun build() = AslCaller( input, output, mask, spatial, whitePaperMode, motionCorrection, infert1, iaf, ibf, casl, tis, bolus, slicedt, bat, t1, t1b, sliceband, rpts, fslAnatOutput, calibration, calibrationTr, calibrationGain, calibrationTissref, calibrationT1csf, calibrationT2csf, calibrationT2bl, calibrationTe, calibrationAlpha, calibrationMethod, calibrationM0, alpha, fixbolus, artoff, echospacing, region_analysis, region_analysis_atlas, region_analysis_atlas_labels, pvcorr, pedir, cblip ) } } fun transformToCSV(value: List<String>): String { return value.joinToString(",") } enum class IAFValues(val value: String) { DIFF("diff"), TC("tc"), CT("ct") } enum class IBFValues(val value: String) { RPT("rpt"), TIS("tis") } enum class CMETHODValues(val value: String) { SINGLE("single"), VOXEL("voxel") }
0
Kotlin
0
0
a39761061faf00d5af6afec35822b9d08b62d6aa
10,093
asl-multi
MIT License
Common/src/main/java/ram/talia/moreiotas/common/casting/actions/strings/OpLenString.kt
Talia-12
565,479,446
false
null
package ram.talia.moreiotas.common.casting.actions.strings import at.petrak.hexcasting.api.spell.ConstMediaAction import at.petrak.hexcasting.api.spell.asActionResult import at.petrak.hexcasting.api.spell.casting.CastingContext import at.petrak.hexcasting.api.spell.iota.Iota import ram.talia.moreiotas.api.getString object OpLenString : ConstMediaAction { override val argc = 1 override fun execute(args: List<Iota>, ctx: CastingContext): List<Iota> { return args.getString(0, argc).length.asActionResult } }
5
Kotlin
4
1
3dd3c0ccc1933cbd5dcb4b60aabfd2a6e911b940
532
MoreIotas
MIT License
app/src/main/java/com/omongole/fred/yomovieapp/domain/model/shows/Show.kt
EngFred
724,071,728
false
{"Kotlin": 244248}
package com.omongole.fred.yomovieapp.domain.model.shows data class Show( val id: Int, val name:String, val posterPath: String, val rating: Double, val firstAirDate: String )
0
Kotlin
0
0
8a1a747c8edde86fe63595f318e157f3bd6de630
195
Cinema-app
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/Typewriter.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Filled.Typewriter: ImageVector get() { if (_typewriter != null) { return _typewriter!! } _typewriter = Builder(name = "Typewriter", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(10.0f, 6.0f) lineTo(4.0f, 6.0f) lineTo(4.0f, 3.0f) curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f) horizontalLineToRelative(10.0f) curveToRelative(1.654f, 0.0f, 3.0f, 1.346f, 3.0f, 3.0f) verticalLineToRelative(3.0f) horizontalLineToRelative(-6.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(1.0f) curveToRelative(0.552f, 0.0f, 1.0f, 0.448f, 1.0f, 1.0f) reflectiveCurveToRelative(-0.448f, 1.0f, -1.0f, 1.0f) horizontalLineToRelative(-6.0f) curveToRelative(-0.552f, 0.0f, -1.0f, -0.448f, -1.0f, -1.0f) reflectiveCurveToRelative(0.448f, -1.0f, 1.0f, -1.0f) horizontalLineToRelative(1.0f) verticalLineToRelative(-2.0f) close() moveTo(24.0f, 10.0f) horizontalLineToRelative(-2.0f) verticalLineToRelative(11.0f) curveToRelative(0.0f, 1.654f, -1.346f, 3.0f, -3.0f, 3.0f) lineTo(5.0f, 24.0f) curveToRelative(-1.654f, 0.0f, -3.0f, -1.346f, -3.0f, -3.0f) lineTo(2.0f, 10.0f) lineTo(0.0f, 10.0f) verticalLineToRelative(-2.0f) lineTo(6.184f, 8.0f) curveToRelative(-0.112f, 0.314f, -0.184f, 0.648f, -0.184f, 1.0f) curveToRelative(0.0f, 1.654f, 1.346f, 3.0f, 3.0f, 3.0f) horizontalLineToRelative(6.0f) curveToRelative(1.654f, 0.0f, 3.0f, -1.346f, 3.0f, -3.0f) curveToRelative(0.0f, -0.352f, -0.072f, -0.686f, -0.184f, -1.0f) horizontalLineToRelative(6.184f) verticalLineToRelative(2.0f) close() moveTo(13.0f, 16.0f) horizontalLineToRelative(2.0f) verticalLineToRelative(-2.0f) horizontalLineToRelative(-2.0f) verticalLineToRelative(2.0f) close() moveTo(9.0f, 16.0f) horizontalLineToRelative(2.0f) verticalLineToRelative(-2.0f) horizontalLineToRelative(-2.0f) verticalLineToRelative(2.0f) close() moveTo(5.0f, 16.0f) horizontalLineToRelative(2.0f) verticalLineToRelative(-2.0f) horizontalLineToRelative(-2.0f) verticalLineToRelative(2.0f) close() moveTo(19.0f, 18.0f) lineTo(5.0f, 18.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(14.0f) verticalLineToRelative(-2.0f) close() moveTo(19.0f, 14.0f) horizontalLineToRelative(-2.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(2.0f) verticalLineToRelative(-2.0f) close() } } .build() return _typewriter!! } private var _typewriter: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,332
icons
MIT License
app/src/main/java/top/jowanxu/coroutines/bean/LoginResultResponse.kt
wangzailfm
112,585,342
false
null
package top.jowanxu.coroutines.bean /** * 登录返回result * token 用户登录生成的token * uid 用户Id */ data class LoginResultResponse(val token: String, val uid: String)
0
Kotlin
0
4
e16d5e8e33321290180cd5e11838392a9f0a9baa
159
KotlinCoroutines
Apache License 2.0
app/src/main/java/ru/aleshi/letsplaycities/service/ServiceModule.kt
AlexanderShirokih
195,569,812
false
null
package ru.aleshi.letsplaycities.service import dagger.Module import dagger.android.ContributesAndroidInjector import ru.aleshi.letsplaycities.network.LpsRepositoryModule @Module(includes = [LpsRepositoryModule::class]) interface ServiceModule { @ContributesAndroidInjector fun injectFirebaseService(): MyFirebaseMessagingService }
0
Kotlin
0
1
19a3153b804b0aceafc94ef764193ad2d1a551bf
343
letsplaycities2_android
MIT License
ui/view/src/main/kotlin/me/gegenbauer/catspy/view/button/CloseButton.kt
Gegenbauer
609,809,576
false
{"Kotlin": 652879}
package me.gegenbauer.catspy.view.button import com.github.weisj.darklaf.iconset.AllIcons import me.gegenbauer.catspy.utils.setBorderless import java.awt.Dimension import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.Icon import javax.swing.JButton class CloseButton(private val onClose: () -> Unit = {}): JButton() { init { icon = closeIconNormal isRolloverEnabled = false isContentAreaFilled = false setBorderless() preferredSize = Dimension(CLOSE_BUTTON_SIZE, CLOSE_BUTTON_SIZE) addMouseListener(object : MouseAdapter() { override fun mouseEntered(e: MouseEvent) { setHover() } override fun mouseExited(e: MouseEvent) { setNormal() } }) addActionListener { onClose() } } fun setHover() { icon = closeIconHover } fun setNormal() { icon = closeIconNormal } companion object { private const val CLOSE_BUTTON_SIZE = 20 private val closeIconNormal: Icon by lazy { AllIcons.Navigation.Close.get() } private val closeIconHover: Icon by lazy { AllIcons.Navigation.Close.hovered() } } }
0
Kotlin
1
7
70d905761d3cb0cb2e5ee9b80ceec72fca46ee52
1,242
CatSpy
Apache License 2.0
ui/view/src/main/kotlin/me/gegenbauer/catspy/view/button/CloseButton.kt
Gegenbauer
609,809,576
false
{"Kotlin": 652879}
package me.gegenbauer.catspy.view.button import com.github.weisj.darklaf.iconset.AllIcons import me.gegenbauer.catspy.utils.setBorderless import java.awt.Dimension import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.Icon import javax.swing.JButton class CloseButton(private val onClose: () -> Unit = {}): JButton() { init { icon = closeIconNormal isRolloverEnabled = false isContentAreaFilled = false setBorderless() preferredSize = Dimension(CLOSE_BUTTON_SIZE, CLOSE_BUTTON_SIZE) addMouseListener(object : MouseAdapter() { override fun mouseEntered(e: MouseEvent) { setHover() } override fun mouseExited(e: MouseEvent) { setNormal() } }) addActionListener { onClose() } } fun setHover() { icon = closeIconHover } fun setNormal() { icon = closeIconNormal } companion object { private const val CLOSE_BUTTON_SIZE = 20 private val closeIconNormal: Icon by lazy { AllIcons.Navigation.Close.get() } private val closeIconHover: Icon by lazy { AllIcons.Navigation.Close.hovered() } } }
0
Kotlin
1
7
70d905761d3cb0cb2e5ee9b80ceec72fca46ee52
1,242
CatSpy
Apache License 2.0
z2-kotlin-plugin/testData/notready/rui/success/OnlyExternal.kt
spxbhuhb
665,463,766
false
{"Kotlin": 1381124, "CSS": 165882, "Java": 7121, "HTML": 1560, "JavaScript": 975}
/* * Copyright © 2020-2021, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package hu.simplexion.z2.kotlin.adaptive.success import hu.simplexion.z2.adaptive.Rui import hu.simplexion.z2.adaptive.rui import hu.simplexion.z2.adaptive.RuiAdapterRegistry import hu.simplexion.z2.adaptive.testing.RuiTestAdapter import hu.simplexion.z2.adaptive.testing.RuiTestAdapter.TraceEvent import hu.simplexion.z2.adaptive.testing.RuiTestAdapterFactory import hu.simplexion.z2.adaptive.testing.T1 @Rui fun OnlyExternal(i: Int, s: String) { } fun box() : String { RuiAdapterRegistry.register(RuiTestAdapterFactory) rui { OnlyExternal(123, "abc") } return RuiTestAdapter.assert(listOf( )) }
6
Kotlin
0
1
204f26074a796495a838f00adc3dbde1fb0fc9b0
765
z2
Apache License 2.0
app/src/test/java/com/whl/mvvm/ExampleUnitTest.kt
honglei92
398,157,044
false
null
package com.whl.mvvm import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } @Test fun liucheng() { listOf("1", "2", "3").forEach { println("aa $it") return@forEach } println("finish") } }
0
Kotlin
0
1
b8fdef077e64ced109c672f03d5c0fb2e22c10d2
507
MVVM
Apache License 2.0
src/jvmMain/kotlin/org/github/anisch/routing/Person.kt
anisch
612,110,087
false
{"Kotlin": 21031}
package org.github.anisch.routing import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.resources.delete import io.ktor.server.resources.get import io.ktor.server.resources.post import io.ktor.server.resources.put import io.ktor.server.response.* import io.ktor.server.routing.* import org.github.anisch.repos.PersonRepository import org.koin.ktor.ext.inject import org.github.anisch.resources.Person as RPerson import org.github.anisch.serial.Person as SPerson fun Application.personRouting() { val personRepository by inject<PersonRepository>() routing { get<RPerson> { _ -> val result = personRepository.read() call.respond(result) } get<RPerson.Id> { p -> val result = personRepository.read(p.id) if (result != null) call.respond(result) else call.respond(HttpStatusCode.NotFound, "Person not found") } post<RPerson> { val p = call.receive<SPerson>() val id = personRepository.create(p) call.respond(HttpStatusCode.Created, id) } put<RPerson> { val p = call.receive<SPerson>() val result = personRepository.update(p) call.respond(HttpStatusCode.OK, result) } delete<RPerson> { val result = personRepository.delete() call.respond(result) } delete<RPerson.Id> { p -> val result = personRepository.delete(p.id) if (result != null) call.respond(result) call.respond(HttpStatusCode.NotFound, "Person not found") } } }
0
Kotlin
0
0
b1bf4afc01f090a32436f6f22512bc5523abec15
1,679
kotlin-multiplatform-demo
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/makerecalldecisionapi/controller/PrisonApiController.kt
ministryofjustice
478,614,213
false
{"Kotlin": 1302200, "Shell": 18492, "Mustache": 1801, "Dockerfile": 1124, "Ruby": 229}
package uk.gov.justice.digital.hmpps.makerecalldecisionapi.controller import io.swagger.v3.oas.annotations.Operation import org.springframework.http.MediaType import org.springframework.security.access.prepost.PreAuthorize import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import uk.gov.justice.digital.hmpps.makerecalldecisionapi.domain.makerecalldecisions.PrisonOffenderSearchRequest import uk.gov.justice.digital.hmpps.makerecalldecisionapi.domain.makerecalldecisions.PrisonOffenderSearchResponse import uk.gov.justice.digital.hmpps.makerecalldecisionapi.service.PrisonerApiService @RestController @RequestMapping(produces = [MediaType.APPLICATION_JSON_VALUE]) internal class PrisonApiController( private val prisonerApiService: PrisonerApiService, ) { @PreAuthorize("hasRole('ROLE_MAKE_RECALL_DECISION')") @PostMapping("/prison-offender-search") @Operation(summary = "Returns a list of recommendation docs that are appropriate for ppcs to process.") suspend fun prisonOffenderSearch( @RequestBody request: PrisonOffenderSearchRequest, ): PrisonOffenderSearchResponse { return prisonerApiService.searchPrisonApi(request.nomsId) } }
1
Kotlin
1
1
87de9555a27b0c7198a487a6981b31d3cfec04e8
1,352
make-recall-decision-api
MIT License
src/main/kotlin/ru/tikhonovdo/enrichment/batch/matching/account/AccountMatchingStepProcessor.kt
tikhonovdo
578,711,174
false
{"Kotlin": 272462, "Java": 11305, "HTML": 8429, "JavaScript": 4858, "Dockerfile": 643}
package ru.tikhonovdo.enrichment.batch.matching.account import org.springframework.batch.core.StepExecution import org.springframework.batch.core.StepExecutionListener import org.springframework.batch.item.ItemProcessor import ru.tikhonovdo.enrichment.domain.enitity.AccountMatching import ru.tikhonovdo.enrichment.repository.matching.AccountMatchingRepository class AccountMatchingStepProcessor( private val accountMatchingRepository: AccountMatchingRepository ): ItemProcessor<AccountMatching, AccountMatching>, StepExecutionListener { private var accountMatchingCandidates = listOf<AccountMatching>() override fun beforeStep(stepExecution: StepExecution) { accountMatchingCandidates = accountMatchingRepository.findAll() } override fun process(item: AccountMatching): AccountMatching? { val probe = AccountMatching( bankId = item.bankId, bankAccountCode = item.bankAccountCode ) return if (accountMatchingCandidates.contains(probe)) { item } else { null } } }
0
Kotlin
0
0
e72e0933751d1fa7d498df4384576c446dc3154f
1,088
enrichment
MIT License
fontawesome/src/de/msrd0/fontawesome/icons/FA_POOP.kt
msrd0
363,665,023
false
null
/* @generated * * This file is part of the FontAwesome Kotlin library. * https://github.com/msrd0/fontawesome-kt * * This library is not affiliated with FontAwesome. * * 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 de.msrd0.fontawesome.icons import de.msrd0.fontawesome.Icon import de.msrd0.fontawesome.Style import de.msrd0.fontawesome.Style.SOLID /** Poop */ object FA_POOP: Icon { override val name get() = "Poop" override val unicode get() = "f619" override val styles get() = setOf(SOLID) override fun svg(style: Style) = when(style) { SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M512 440.1C512 479.9 479.7 512 439.1 512H71.92C32.17 512 0 479.8 0 440c0-35.88 26.19-65.35 60.56-70.85C43.31 356 32 335.4 32 312C32 272.2 64.25 240 104 240h13.99C104.5 228.2 96 211.2 96 192c0-35.38 28.56-64 63.94-64h16C220.1 128 256 92.12 256 48c0-17.38-5.784-33.35-15.16-46.47C245.8 .7754 250.9 0 256 0c53 0 96 43 96 96c0 11.25-2.288 22-5.913 32h5.879C387.3 128 416 156.6 416 192c0 19.25-8.59 36.25-22.09 48H408C447.8 240 480 272.2 480 312c0 23.38-11.38 44.01-28.63 57.14C485.7 374.6 512 404.3 512 440.1z"/></svg>""" else -> null } }
0
Kotlin
0
0
1358935395f9254cab27852457e2aa6c58902e16
1,708
fontawesome-kt
Apache License 2.0
ktorm-core/src/test/kotlin/org/ktorm/entity/EntityTest.kt
kotlin-orm
159,785,192
false
{"Kotlin": 1287281, "Java": 1980}
package org.ktorm.entity import org.junit.Test import org.ktorm.BaseTest import org.ktorm.database.Database import org.ktorm.dsl.* import org.ktorm.schema.* import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.time.LocalDate import java.util.* import kotlin.reflect.jvm.jvmErasure import kotlin.test.assertNotNull import kotlin.test.assertNull /** * Created by vince on Dec 09, 2018. */ class EntityTest : BaseTest() { @Test fun testTypeReference() { println(Employee) println(Employee.referencedKotlinType) assert(Employee.referencedKotlinType.jvmErasure == Employee::class) println(Employees) println(Employees.entityClass) assert(Employees.entityClass == Employee::class) println(Employees.aliased("t")) println(Employees.aliased("t").entityClass) assert(Employees.aliased("t").entityClass == Employee::class) } @Test fun testEntityProperties() { val employee = Employee { name = "vince" } println(employee) assert(employee["name"] == "vince") assert(employee.name == "vince") assert(employee["job"] == null) assert(employee.job == "") } @Test fun testDefaultMethod() { for (method in Employee::class.java.methods) { println(method) } val employee = Employee { name = "vince" } println(employee) assert(employee.upperName == "VINCE") assert(employee.upperName() == "VINCE") assert(employee.nameWithPrefix(":") == ":vince") assert(employee.nameWithSuffix(":") == "vince:") } interface Animal<T : Animal<T>> : Entity<T> { fun say1() = "animal1" fun say2() = "animal2" fun say3() = "animal3" } interface Dog : Animal<Dog> { override fun say1() = "${super.say1()} --> dog1" override fun say2() = "${super.say2()} --> dog2" override fun say3() = "${super.say3()} --> dog3" } @Test fun testDefaultMethodOverride() { val dog = Entity.create<Dog>() assert(dog.say1() == "animal1 --> dog1") assert(dog.say2() == "animal2 --> dog2") assert(dog.say3() == "animal3 --> dog3") } @Test fun testSerialize() { val employee = Employee { name = "jerry" job = "trainee" manager = database.employees.find { it.name eq "vince" } hireDate = LocalDate.now() salary = 50 department = database.departments.find { it.name eq "tech" } ?: throw AssertionError() } val bytes = serialize(employee) println(Base64.getEncoder().encodeToString(bytes)) } @Test fun testDeserialize() { Department { name = "test" println(this.javaClass) println(this) } Employee { name = "test" println(this.javaClass) println(this) } val str = "<KEY>Ny<KEY> val bytes = Base64.getDecoder().decode(str) val employee = deserialize(bytes) as Employee println(employee.javaClass) println(employee) assert(employee.name == "jerry") assert(employee.job == "trainee") assert(employee.manager?.name == "vince") assert(employee.salary == 50L) assert(employee.department.name == "tech") } private fun serialize(obj: Any): ByteArray { ByteArrayOutputStream().use { buffer -> ObjectOutputStream(buffer).use { output -> output.writeObject(obj) output.flush() return buffer.toByteArray() } } } private fun deserialize(bytes: ByteArray): Any { ByteArrayInputStream(bytes).use { buffer -> ObjectInputStream(buffer).use { input -> return input.readObject() } } } @Test fun testFind() { val employee = database.employees.find { it.id eq 1 } ?: throw AssertionError() println(employee) assert(employee.name == "vince") assert(employee.job == "engineer") } @Test fun testFindWithReference() { val employees = database.employees .filter { it.department.location like "%Guangzhou%" } .sortedBy { it.id } .toList() assert(employees.size == 2) assert(employees[0].name == "vince") assert(employees[1].name == "marry") } @Test fun testCreateEntity() { val employees = database .from(Employees) .joinReferencesAndSelect() .where { val dept = Employees.departmentId.referenceTable as Departments dept.location like "%Guangzhou%" } .orderBy(Employees.id.asc()) .map { Employees.createEntity(it) } assert(employees.size == 2) assert(employees[0].name == "vince") assert(employees[1].name == "marry") } @Test fun testUpdate() { var employee = Employee() employee.id = 2 employee.job = "engineer" employee.salary = 100 // employee.manager = null database.employees.update(employee) employee = database.employees.find { it.id eq 2 } ?: throw AssertionError() assert(employee.job == "engineer") assert(employee.salary == 100L) assert(employee.manager?.id == 1) } @Test fun testFlushChanges() { var employee = database.employees.find { it.id eq 2 } ?: throw AssertionError() employee.job = "engineer" employee.salary = 100 employee.manager = null employee.flushChanges() employee.flushChanges() employee = database.employees.find { it.id eq 2 } ?: throw AssertionError() assert(employee.job == "engineer") assert(employee.salary == 100L) assert(employee.manager == null) } @Test fun testDeleteEntity() { val employee = database.employees.find { it.id eq 2 } ?: throw AssertionError() employee.delete() assert(database.employees.count() == 3) } @Test fun testSaveEntity() { var employee = Employee { name = "jerry" job = "trainee" manager = null hireDate = LocalDate.now() salary = 50 department = database.departments.find { it.name eq "tech" } ?: throw AssertionError() } database.employees.add(employee) println(employee) employee = database.employees.find { it.id eq 5 } ?: throw AssertionError() assert(employee.name == "jerry") assert(employee.department.name == "tech") employee.job = "engineer" employee.salary = 100 employee.flushChanges() employee = database.employees.find { it.id eq 5 } ?: throw AssertionError() assert(employee.job == "engineer") assert(employee.salary == 100L) employee.delete() assert(database.employees.count() == 4) } @Test fun testFindMapById() { val employees = database.employees.filter { it.id.inList(1, 2) }.associateBy { it.id } assert(employees.size == 2) assert(employees[1]?.name == "vince") assert(employees[2]?.name == "marry") } interface Parent : Entity<Parent> { companion object : Entity.Factory<Parent>() var child: Child? } interface Child : Entity<Child> { companion object : Entity.Factory<Child>() var grandChild: GrandChild? } interface GrandChild : Entity<GrandChild> { companion object : Entity.Factory<GrandChild>() var id: Int? var name: String? } object Parents : Table<Parent>("t_employee") { val id = int("id").primaryKey().bindTo { it.child?.grandChild?.id } } @Test fun testHasColumnValue() { val p1 = Parent() assert(!p1.implementation.hasColumnValue(Parents.id.binding!!)) assert(p1.implementation.getColumnValue(Parents.id.binding!!) == null) val p2 = Parent { child = null } assert(p2.implementation.hasColumnValue(Parents.id.binding!!)) assert(p2.implementation.getColumnValue(Parents.id.binding!!) == null) val p3 = Parent { child = Child() } assert(!p3.implementation.hasColumnValue(Parents.id.binding!!)) assert(p3.implementation.getColumnValue(Parents.id.binding!!) == null) val p4 = Parent { child = Child { grandChild = null } } assert(p4.implementation.hasColumnValue(Parents.id.binding!!)) assert(p4.implementation.getColumnValue(Parents.id.binding!!) == null) val p5 = Parent { child = Child { grandChild = GrandChild() } } assert(!p5.implementation.hasColumnValue(Parents.id.binding!!)) assert(p5.implementation.getColumnValue(Parents.id.binding!!) == null) val p6 = Parent { child = Child { grandChild = GrandChild { id = null } } } assert(p6.implementation.hasColumnValue(Parents.id.binding!!)) assert(p6.implementation.getColumnValue(Parents.id.binding!!) == null) val p7 = Parent { child = Child { grandChild = GrandChild { id = 6 } } } assert(p7.implementation.hasColumnValue(Parents.id.binding!!)) assert(p7.implementation.getColumnValue(Parents.id.binding!!) == 6) } @Test fun testHasColumnValueAttached() { val sofiaDepartment = Department { name = "Sofia Office" location = LocationWrapper("Sofia") } database.departments.add(sofiaDepartment) val now = LocalDate.now() val employeeManager = Employee { name = "Simpson" job = "Manager" hireDate = now department = sofiaDepartment salary = 100 } database.employees.add(employeeManager) val employee1 = Employee { name = "McDonald" job = "Engineer" hireDate = now department = sofiaDepartment salary = 100 } val e1 = with(database.employees) { add(employee1) find { it.id eq employee1.id } } assertNotNull(e1) assert(!e1.implementation.hasColumnValue(Employees.managerId.binding!!)) assertNull(e1.implementation.getColumnValue(Employees.managerId.binding!!)) val employee2 = Employee { name = "Smith" job = "Engineer" hireDate = now department = sofiaDepartment manager = null salary = 100 } val e2 = with(database.employees) { add(employee2) find { it.id eq employee2.id } } assertNotNull(e2) assert(!e2.implementation.hasColumnValue(Employees.managerId.binding!!)) assertNull(e2.implementation.getColumnValue(Employees.managerId.binding!!)) val employee3 = Employee { name = "Dennis" job = "Engineer" hireDate = now department = sofiaDepartment manager = employeeManager salary = 100 } val e3 = with(database.employees) { add(employee3) find { it.id eq employee3.id } } assertNotNull(e3) assert(e3.implementation.hasColumnValue(Employees.managerId.binding!!)) assertNotNull(e3.implementation.getColumnValue(Employees.managerId.binding!!)) } @Test fun testUpdatePrimaryKey() { try { val parent = database.sequenceOf(Parents).find { it.id eq 1 } ?: throw AssertionError() assert(parent.child?.grandChild?.id == 1) parent.child?.grandChild?.id = 2 throw AssertionError() } catch (e: UnsupportedOperationException) { // expected println(e.message) } } interface EmployeeTestForReferencePrimaryKey : Entity<EmployeeTestForReferencePrimaryKey> { var employee: Employee var manager: EmployeeManagerTestForReferencePrimaryKey } interface EmployeeManagerTestForReferencePrimaryKey : Entity<EmployeeManagerTestForReferencePrimaryKey> { var employee: Employee } object EmployeeTestForReferencePrimaryKeys : Table<EmployeeTestForReferencePrimaryKey>("t_employee0") { val id = int("id").primaryKey().references(Employees) { it.employee } val managerId = int("manager_id").bindTo { it.manager.employee.id } } @Test fun testUpdateReferencesPrimaryKey() { val e = database.sequenceOf(EmployeeTestForReferencePrimaryKeys).find { it.id eq 2 } ?: return e.manager.employee = database.sequenceOf(Employees).find { it.id eq 1 } ?: return try { e.employee = database.sequenceOf(Employees).find { it.id eq 1 } ?: return throw AssertionError() } catch (e: UnsupportedOperationException) { // expected println(e.message) } e.flushChanges() } @Test fun testForeignKeyValue() { val employees = database .from(Employees) .select() .orderBy(Employees.id.asc()) .map { Employees.createEntity(it) } val vince = employees[0] assert(vince.manager == null) assert(vince.department.id == 1) val marry = employees[1] assert(marry.manager?.id == 1) assert(marry.department.id == 1) val tom = employees[2] assert(tom.manager == null) assert(tom.department.id == 2) val penny = employees[3] assert(penny.manager?.id == 3) assert(penny.department.id == 2) } @Test fun testCreateEntityWithoutReferences() { val employees = database .from(Employees) .leftJoin(Departments, on = Employees.departmentId eq Departments.id) .select(Employees.columns + Departments.columns) .map { Employees.createEntity(it, withReferences = false) } employees.forEach { println(it) } assert(employees.size == 4) assert(employees[0].department.id == 1) assert(employees[1].department.id == 1) assert(employees[2].department.id == 2) assert(employees[3].department.id == 2) } @Test fun testAutoDiscardChanges() { var department = database.departments.find { it.id eq 2 } ?: return department.name = "tech" val employee = Employee() employee.department = department employee.name = "jerry" employee.job = "trainee" employee.manager = database.employees.find { it.name eq "vince" } employee.hireDate = LocalDate.now() employee.salary = 50 database.employees.add(employee) department.location = LocationWrapper("Guangzhou") department.flushChanges() department = database.departments.find { it.id eq 2 } ?: return assert(department.name == "tech") assert(department.location.underlying == "Guangzhou") } interface Emp : Entity<Emp> { companion object : Entity.Factory<Emp>() val id: Int var employee: Employee var manager: Employee var hireDate: LocalDate var salary: Long var departmentId: Int } object Emps : Table<Emp>("t_employee") { val id = int("id").primaryKey().bindTo { it.id } val name = varchar("name").bindTo { it.employee.name } val job = varchar("job").bindTo { it.employee.job } val managerId = int("manager_id").bindTo { it.manager.id } val hireDate = date("hire_date").bindTo { it.hireDate } val salary = long("salary").bindTo { it.salary } val departmentId = int("department_id").bindTo { it.departmentId } } val Database.emps get() = this.sequenceOf(Emps) @Test fun testCheckUnexpectedFlush() { val emp1 = database.emps.find { it.id eq 1 } ?: return emp1.employee.name = "jerry" // emp1.flushChanges() val emp2 = Emp { employee = emp1.employee hireDate = LocalDate.now() salary = 100 departmentId = 1 } try { database.emps.add(emp2) throw AssertionError("failed") } catch (e: IllegalStateException) { assert(e.message == "this.employee.name may be unexpectedly discarded, please save it to database first.") } } @Test fun testCheckUnexpectedFlush0() { val emp1 = database.emps.find { it.id eq 1 } ?: return emp1.employee.name = "jerry" // emp1.flushChanges() val emp2 = database.emps.find { it.id eq 2 } ?: return emp2.employee = emp1.employee try { emp2.flushChanges() throw AssertionError("failed") } catch (e: IllegalStateException) { assert(e.message == "this.employee.name may be unexpectedly discarded, please save it to database first.") } } @Test fun testCheckUnexpectedFlush1() { val employee = database.employees.find { it.id eq 1 } ?: return employee.name = "jerry" // employee.flushChanges() val emp = database.emps.find { it.id eq 2 } ?: return emp.employee = employee try { emp.flushChanges() throw AssertionError("failed") } catch (e: IllegalStateException) { assert(e.message == "this.employee.name may be unexpectedly discarded, please save it to database first.") } } @Test fun testFlushChangesForDefaultValues() { var emp = database.emps.find { it.id eq 1 } ?: return emp.manager.id = 2 emp.flushChanges() emp = database.emps.find { it.id eq 1 } ?: return assert(emp.manager.id == 2) } @Test fun testDefaultValuesCache() { val department = Department() assert(department.id == 0) assert(department["id"] == null) } @Test fun testCopyStatus() { var employee = database.employees.find { it.id eq 2 }?.copy() ?: return employee.name = "jerry" employee.manager?.id = 3 employee.flushChanges() employee = database.employees.find { it.id eq 2 } ?: return assert(employee.name == "jerry") assert(employee.manager?.id == 3) } @Test fun testDeepCopy() { val employee = database.employees.find { it.id eq 2 } ?: return val copy = employee.copy() assert(employee == copy) assert(employee !== copy) assert(employee.hireDate !== copy.hireDate) // should not be the same instance because of deep copy. assert(copy.manager?.implementation?.parent === copy.implementation) // should keep the parent relationship. } @Test fun testRemoveIf() { database.employees.removeIf { it.departmentId eq 1 } assert(database.employees.count() == 2) } @Test fun testClear() { database.employees.clear() assert(database.employees.isEmpty()) } @Test fun testAddAndFlushChanges() { var employee = Employee { name = "jerry" job = "trainee" manager = database.employees.find { it.name eq "vince" } hireDate = LocalDate.now() salary = 50 department = database.departments.find { it.name eq "tech" } ?: throw AssertionError() } database.employees.add(employee) employee.job = "engineer" employee.flushChanges() employee = database.employees.find { it.id eq employee.id } ?: throw AssertionError() assert(employee.job == "engineer") } @Test fun testValueEquality() { val now = LocalDate.now() val employee1 = Employee { id = 1 name = "Eric" job = "contributor" hireDate = now salary = 50 } val employee2 = Employee { id = 1 name = "Eric" job = "contributor" hireDate = now salary = 50 } println(employee1) println(employee2) println(employee1.hashCode()) assert(employee1 == employee2) assert(employee2 == employee1) assert(employee1 !== employee2) assert(employee1.hashCode() == employee2.hashCode()) } @Test fun testDifferentClassesSameValuesNotEqual() { val employee = Employee { name = "name" } val department = Department { name = "name" } println(employee) println(department) println(employee.hashCode()) println(department.hashCode()) assert(employee != department) } @Test fun testEqualsWithNullValues() { val e1 = Employee { id = 1 name = "vince" } val e2 = Employee { id = 1 name = "vince" manager = null } println(e1) println(e2) println(e1.hashCode()) assert(e1 == e2) assert(e2 == e1) assert(e1 !== e2) assert(e1.hashCode() == e2.hashCode()) } @Test fun testEqualsForNestedEntities() { val p1 = Parent { child = Child { grandChild = GrandChild { id = 1 } } } val p2 = Parent { child = Child { grandChild = GrandChild { id = 1 name = null } } } println(p1) println(p2) println(p1.hashCode()) assert(p1 == p2) assert(p2 == p1) assert(p1 !== p2) assert(p1.hashCode() == p2.hashCode()) } @Test fun testValueNullEquality() { val departmentTransient = Department { name = "Sofia Office" location = LocationWrapper("Sofia") mixedCase = null // explicitly initialized to null } database.departments.add(departmentTransient) val departmentAttached = database.departments.find { it.name eq "Sofia Office" } assertNotNull(departmentAttached) println(departmentTransient) println(departmentAttached) println(departmentTransient.hashCode()) assert(departmentTransient == departmentAttached) assert(departmentAttached == departmentTransient) assert(departmentTransient !== departmentAttached) assert(departmentTransient.hashCode() == departmentAttached.hashCode()) } }
84
Kotlin
143
2,023
f59e40695218ae370401d1c27a9134f2b944364a
23,245
ktorm
Apache License 2.0
src/main/java/com/kenza/discholder/block/DiscHolderBlockEntityGuiDescription.kt
dmkenza
452,655,607
false
{"Kotlin": 47916, "Java": 9021, "PHP": 1627}
package com.kenza.discholder.block import com.kenza.discholder.DiscHolderMod.Companion.DISC_BLOCKENTITY_GUI_HANDLER_TYPE import net.minecraft.entity.player.PlayerInventory import net.minecraft.screen.ScreenHandlerContext import io.github.cottonmc.cotton.gui.SyncedGuiDescription import io.github.cottonmc.cotton.gui.ValidatedSlot import io.github.cottonmc.cotton.gui.widget.WGridPanel import io.github.cottonmc.cotton.gui.widget.WItemSlot import io.github.cottonmc.cotton.gui.widget.WButton import net.minecraft.item.ItemStack import net.minecraft.item.MusicDiscItem import net.minecraft.text.LiteralText class DiscHolderBlockEntityGuiDescription( syncId: Int, playerInventory: PlayerInventory, val context: ScreenHandlerContext, ) : SyncedGuiDescription( DISC_BLOCKENTITY_GUI_HANDLER_TYPE, syncId, playerInventory, getBlockInventory(context, DiscHolderBlockEntity.INVENTORY_SIZE), null ) { init { val root = getRootPanel() as WGridPanel // val slot = WItemSlot.of(blockInventory, 0, 7, 1).setFilter { // it.item is MusicDiscItem // } val slot1 = object : ValidatedSlot(blockInventory, 0, 7, 1) { override fun canInsert(stack: ItemStack?): Boolean { return super.canInsert(stack) } } val slot = WItemSlot.of(blockInventory, 0, 7, 1).setFilter { it.item is MusicDiscItem } // for (x in 0..6){ root.add(slot, root.insets.right / 2 + 1 - 3, 1) // } // val buttonB = WButton(LiteralText("Show Warnings")) // buttonB.onClick = Runnable { slot.icon = TextureIcon(Identifier("libgui-test", "saddle.png")) } // root.add(buttonB, 5, 3, 4, 1) val t1 = blockInventory.getStack(0) // val x1 = WButton(getRightClickModeText()) // // x1.setOnClick { //// blockEntity?.apply { //// rightClickMode = !rightClickMode //// x1.label = getRightClickModeText() //// AutoClickerBlockEntity.sendValueUpdatePacket(rightClickMode, context) //// } // } // // root.add(x1, root.insets.right / 2 - 1, 3, 5, 1) // root.add(WTextField(LiteralText("Type something...")).setMaxLength(64), 0, 7, 5, 1) // root.add(WLabel(LiteralText("Large slot:")), 0, 9) // root.add(WItemSlot.outputOf(blockInventory, 0), 4, 8) // root.add(WItemSlot.of(blockInventory, 7).setIcon(TextureIcon(Identifier("libgui-test", "saddle.png"))), 7, 9) root.add(createPlayerInventoryPanel(), 0, 3) // println(root.toString()) getRootPanel().validate(this) // ScreenNetworking.of(this, NetworkSide.SERVER) // .receive(TEST_MESSAGE) { buf: PacketByteBuf? -> println("Received on the server!") } // try { // slot.onHidden() // slot.onShown() // } catch (t: Throwable) { // throw AssertionError("ValidatedSlot.setVisible crashed", t) // } } var blockEntity: DiscHolderBlockEntity? = null get() { var block: DiscHolderBlockEntity? = null context.run { _, pos -> block = world.getBlockEntity(pos) as? DiscHolderBlockEntity } return block } fun getRightClickModeText(): LiteralText { val rightLickMode = false //blockEntity?.rightClickMode ?: false if (rightLickMode) { return LiteralText("Right Click Mode") } else { return LiteralText("Left Click Mode") } } }
1
Kotlin
0
0
66351560241de532347bddfa0b2a458f5ffef7ad
3,596
DiscHolder_Fabric
Creative Commons Zero v1.0 Universal
app/src/main/java/com/yigitbal/weatherapp/viewmodel/WeatherViewModel.kt
yigitbalbasi
672,211,006
false
null
package com.yigitbal.weatherapp.viewmodel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.yigitbal.weatherapp.Weather import com.yigitbal.weatherapp.repository.WeatherRepository import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.launch @HiltViewModel class WeatherViewModel @Inject constructor(private val repository: WeatherRepository) : ViewModel() { private val _resp = MutableLiveData<Weather>() val weatherResp: LiveData<Weather> get() = _resp init { getWeather() } private fun getWeather() = viewModelScope.launch { repository.getWeather().let { response -> if (response.isSuccessful) { _resp.postValue(response.body()) } else { Log.d("Tag", "getWeather Error response: ${response.message()}") } } } }
0
Kotlin
0
0
5f99f5409b88f0efbeaa8404fef0de1b59f240b3
1,034
WeatherApp
Apache License 2.0
PrimFastKotlin/KotlinAction/app/src/main/java/com/prim/gkapp/ui/home/NavItem.kt
annocjx
248,767,646
true
{"Python": 628830, "Java": 293115, "HTML": 159403, "JavaScript": 157080, "Kotlin": 131915, "CSS": 45863, "Dart": 39473, "Objective-C": 5647, "Shell": 3784, "PHP": 2469, "CMake": 1603}
package com.prim.gkapp.ui.home import android.app.Activity import android.os.Bundle import androidx.annotation.IdRes import androidx.fragment.app.Fragment import com.prim.gkapp.R.id import com.prim.gkapp.ui.feeds.EventsFragment import com.prim.gkapp.ui.feeds.IssuesFragment import com.prim.gkapp.ui.repos.ReposFragment import com.prim.gkapp.ui.settings.SettingsActivity /** * @desc * @author prim * @time 2019-06-27 - 21:14 * @version 1.0.0 * @param groupId menu groupId; * @param type = 0 fragment;1 activity */ class NavItem private constructor( val groupId: Int = 0, val type: Int = 0, val title: String, val fragmentClass: Class<out Fragment>? = null, val activityClass: Class<out Activity>? = null, val arguments: Bundle = Bundle() ) { //定义静态变量 companion object { //存储nav ID对应的NavItem private val items = mapOf( id.nav_feeds to NavItem( groupId = id.nav_menu2, type = 0, title = "Feeds", fragmentClass = EventsFragment::class.java ), id.nav_repositories to NavItem( groupId = id.nav_menu2, type = 0, title = "Repos", fragmentClass = ReposFragment::class.java ), id.nav_issues to NavItem( groupId = id.nav_menu2, type = 0, title = "Issues", fragmentClass = IssuesFragment::class.java ), id.nav_pull to NavItem( groupId = id.nav_menu2, type = 0, title = "Pull", fragmentClass = IssuesFragment::class.java ), id.nav_notification to NavItem( groupId = id.nav_menu3, type = 1, title = "Notification", fragmentClass = IssuesFragment::class.java ), id.nav_pinned to NavItem( groupId = id.nav_menu3, type = 0, title = "Pinned", fragmentClass = IssuesFragment::class.java ), id.nav_trending to NavItem( groupId = id.nav_menu3, type = 0, title = "Trending", fragmentClass = IssuesFragment::class.java ), id.nav_gists to NavItem( groupId = id.nav_menu3, type = 0, title = "Gists", fragmentClass = IssuesFragment::class.java ), id.nav_setting to NavItem( type = 1, title = "Settings", activityClass = SettingsActivity::class.java ), id.nav_about to NavItem( type = 1, title = "About", activityClass = SettingsActivity::class.java ) ) //重写get 操作符 operator fun get(@IdRes navId: Int): NavItem { return items[navId] ?: items[id.nav_feeds]!! } operator fun get(item: NavItem): Int { return items.filter { it.value == item }.keys.first() } } override fun toString(): String { return super.toString() } }
0
null
0
0
b435ca4bd2d0c682c7b40f2b856d7b36af8da7c9
3,159
Awsome-Android-Advanced
Apache License 2.0
src/main/kotlin/org/botellier/server/Client.kt
danielrs
88,327,994
false
null
package org.botellier.server import org.botellier.command.CommandParser import org.botellier.value.Lexer import org.botellier.value.LexerException import org.botellier.value.ParserException import org.botellier.value.toList import java.net.Socket import java.net.SocketException import java.net.SocketTimeoutException /** * Container class for client information. */ data class Client(val socket: Socket, var dbIndex: Int = 0, var isAuthenticated: Boolean = false) /** * Class for handling a new client connection. It reads the input, * tries to parse a command, and then sends back the constructed * request using the provided callback. * @property db the current db the client is connected to. */ class ClientHandler(val client: Client, val dispatcher: RequestDispatcher) : Runnable { var readTimeout: Int = 1000 override fun run() { println("Handling client ${client.socket.inetAddress.hostAddress}") loop@while (true) { try { val stream = client.socket.waitInput() client.socket.soTimeout = readTimeout val tokens = Lexer(stream).lex().toList() client.socket.soTimeout = 0 val command = CommandParser.parse(tokens) dispatcher.dispatch(Request(client, command)) } catch (e: SocketException) { break@loop } catch (e: Throwable) { println(e.message) val writer = client.socket.getOutputStream().bufferedWriter() when (e) { // Exception for Lexer waiting too much. is SocketTimeoutException -> writer.write("-ERR Command read timeout\r\n") // Exception regarding the serialized data. is LexerException -> writer.write("-COMMANDERR Unable to read command\r\n") // Exception regarding the structure of the data. is ParserException -> writer.write("-COMMANDERR Unable to parse command\r\n") // Exception regarding unknown command. is CommandParser.UnknownCommandException -> writer.write("-COMMANDERR ${e.message}\r\n") // Exception that we don't know how to handle. else -> { client.socket.close() break@loop } } writer.flush() } } println("Dropping client ${client.socket.inetAddress.hostAddress}") } }
0
Kotlin
1
10
5a52a4cd00b0d0fde429917d649da17c5b0481c6
2,691
botellier
MIT License
src/test/kotlin/tutorial/basic/AirplaneMode1.kt
ldi-github
538,873,481
false
{"Kotlin": 3794937, "JavaScript": 12703, "CSS": 5215}
package tutorial.basic import org.junit.jupiter.api.Order import org.junit.jupiter.api.Test import shirates.core.configuration.Testrun import shirates.core.driver.commandextension.* import shirates.core.testcode.UITest @Testrun("testConfig/android/androidSettings/testrun.properties") class AirplaneMode1 : UITest() { @Test @Order(10) fun airplaneMode() { scenario { case(1) { action { it.macro("[Airplane mode On]") .flickTopToBottom(startMarginRatio = 0.0) }.expectation { it.select("@Airplane mode") .checkIsON() } } case(2) { action { it.macro("[Airplane mode Off]") .flickTopToBottom(startMarginRatio = 0.0) }.expectation { it.select("@Airplane mode") .checkIsOFF() } } } } }
0
Kotlin
0
8
36de66a32862af904f97052aac8bd022e28da1ea
1,037
shirates-core
Apache License 2.0
src/main/java/kotlinremotelibrary/KotlinRemoteLibraryServer.kt
MarketSquare
236,125,361
false
{"RobotFramework": 3400, "Shell": 1912, "Kotlin": 1083}
package kotlinremotelibrary import org.robotframework.javalib.library.AnnotationLibrary import org.robotframework.remoteserver.RemoteServer class KotlinRemoteLibraryServer:AnnotationLibrary("kotlinremotelibrary/keywords/*Keywords.class") { override fun getKeywordDocumentation(keywordName:String):String { if (keywordName == "__intro__") { return "Intro" } return super.getKeywordDocumentation(keywordName) } companion object { @Throws(Exception::class) @JvmStatic fun main(args:Array<String>) { RemoteServer.configureLogging() val server = RemoteServer() server.addLibrary(KotlinRemoteLibraryServer::class.java, 8270) server.start() } } }
3
RobotFramework
0
0
f7d9f3bbae7c9acac60e933f85dac95b58694417
707
robotframework-kotlin-remote-library
MIT License
app/src/main/java/com/example/pianoanalytics/AnimalActivity.kt
at-internet
477,609,545
false
{"Kotlin": 188354, "Java": 404}
package com.example.pianoanalytics import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import by.kirich1409.viewbindingdelegate.viewBinding import com.example.pianoanalytics.databinding.ActivityAnimalBinding import io.piano.android.analytics.PianoAnalytics import io.piano.android.analytics.model.Event import io.piano.android.analytics.model.Property import io.piano.android.analytics.model.PropertyName class AnimalActivity: AppCompatActivity(R.layout.activity_animal) { private val binding: ActivityAnimalBinding by viewBinding(R.id.animalText) private lateinit var item: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) item = intent.getStringExtra(ITEM_KEY) ?: "" binding.animalText.text = getString(R.string.item_text, item) } override fun onResume() { super.onResume() PianoAnalytics.getInstance().apply { screenName(item) sendEvents( Event.Builder(Event.PAGE_DISPLAY) .properties( Property(PropertyName.PAGE_FULL_NAME, item), Property(PropertyName.PAGE_CHAPTER1, item), ) .build() ) } } companion object { const val ITEM_KEY = "item" } }
1
Kotlin
5
4
267fbd47f0f8abc4362576fd5cffff4e732cadc4
1,366
piano-analytics-android
MIT License
packages/app/core/data/src/main/java/com/posttrip/journeydex/core/data/model/travel/CourseDetail.kt
Woo-Dong93
821,739,845
false
{"Kotlin": 279139, "TypeScript": 73819}
package com.posttrip.journeydex.core.data.model.travel import kotlinx.serialization.Serializable @Serializable data class CourseDetail( val data: Course )
3
Kotlin
0
0
a312f4989677cf24ca1c945058e6fdadec019c93
161
PostTrip
MIT License
funcify-feature-eng-spring-webflux/src/main/kotlin/funcify/feature/spring/router/GraphiQLWebFluxHandlerFunction.kt
anticipasean
458,910,592
false
{"Kotlin": 2751524, "HTML": 1817}
package funcify.feature.spring.router import funcify.feature.tools.extensions.LoggerExtensions.loggerFor import org.slf4j.Logger import org.springframework.core.io.ClassPathResource import org.springframework.http.MediaType import org.springframework.web.reactive.function.server.HandlerFunction import org.springframework.web.reactive.function.server.ServerRequest import org.springframework.web.reactive.function.server.ServerResponse import org.springframework.web.util.UriBuilder import reactor.core.publisher.Mono import java.net.URI /** * @author smccarron * @created 2023-06-28 */ class GraphiQLWebFluxHandlerFunction( private val graphQLPath: String, private val graphiqlHtmlResource: ClassPathResource ) : HandlerFunction<ServerResponse> { companion object { private val logger: Logger = loggerFor<GraphiQLWebFluxHandlerFunction>() private const val PATH_QUERY_PARAMETER_KEY = "path" } override fun handle(request: ServerRequest): Mono<ServerResponse> { logger.info("handle: [ request.path: {} ]", request.path()) return if (request.queryParam(PATH_QUERY_PARAMETER_KEY).isPresent) { ServerResponse.ok().contentType(MediaType.TEXT_HTML).bodyValue(graphiqlHtmlResource) } else { ServerResponse.temporaryRedirect(getRedirectUrl(request)).build() } } private fun getRedirectUrl(request: ServerRequest): URI { val builder: UriBuilder = request.uriBuilder() val pathQueryParam: String = applyContextPath(request, graphQLPath) builder.queryParam(PATH_QUERY_PARAMETER_KEY, pathQueryParam) return builder.build(request.pathVariables()) } private fun applyContextPath(request: ServerRequest, path: String): String { val contextPath: String = request.requestPath().contextPath().toString() return if (contextPath.isNotBlank()) { contextPath + path } else { path } } }
0
Kotlin
0
0
284b941de10a5b85b9ba1b5236a1d57289e10492
1,975
funcify-feature-eng
Apache License 2.0
app/src/main/java/com/revature/findlawyer/data/repository/UserRetrofitHelp.kt
Gale6
473,278,613
false
{"Kotlin": 159194}
package com.revature.findlawyer.data.repository import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit object UserRetrofitHelper{ private val retrofit:Retrofit init { val builder=Retrofit.Builder() .baseUrl("https://private-f6bc26-findlawyerapi.apiary-mock.com")//add the api url here .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(CoroutineCallAdapterFactory()) val loggingInterceptor=HttpLoggingInterceptor() loggingInterceptor.level=HttpLoggingInterceptor.Level.BODY val okHttpClient=OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .writeTimeout(0,TimeUnit.MICROSECONDS) .writeTimeout(2,TimeUnit.MINUTES) .writeTimeout(1,TimeUnit.MINUTES).build() retrofit=builder.client(okHttpClient).build() } fun getUserService(): UserLoginService{ return retrofit.create(UserLoginService::class.java) } fun getUserRegisterService(): UserRegisterService{ return retrofit.create(UserRegisterService::class.java) } }
0
Kotlin
0
0
6f4c4325f0bbe9b40ffc8088e5573df3f4448434
1,342
FindLawyer
Apache License 2.0
common/src/main/java/io/github/kunal26das/common/compose/LocalComposition.kt
kunal26das
283,553,926
false
{"Kotlin": 125792}
package io.github.kunal26das.common.compose import androidx.compose.runtime.compositionLocalOf val LocalShimmer = compositionLocalOf<Shimmer> { error("No active shimmer found!") } val LocalShimmerAnimation = compositionLocalOf<ShimmerAnimation> { error("No active shimmer animation found!") }
1
Kotlin
0
2
b8f5b68fac6180bdee6289169a5ff637d2dd8798
303
yify
Apache License 2.0
wallpaperapp/src/main/java/com/doctoror/particleswallpaper/presentation/App.kt
smred
120,305,786
true
{"Kotlin": 192474, "Java": 1291, "IDL": 1203, "Prolog": 716}
package com.doctoror.particleswallpaper.presentation import android.app.Application import com.doctoror.particleswallpaper.BuildConfig import com.doctoror.particleswallpaper.presentation.di.Injector import com.doctoror.particleswallpaper.presentation.di.components.DaggerConfigComponent import com.doctoror.particleswallpaper.presentation.di.modules.AppModule import android.os.StrictMode /** * Created by <NAME> on 01.06.17. */ class App: Application() { override fun onCreate() { super.onCreate() initStrictMode() initDagger() } private fun initStrictMode() { if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build()) StrictMode.setVmPolicy(StrictMode.VmPolicy.Builder() .detectAll() .penaltyLog() .build()) } } private fun initDagger() { Injector.configComponent = DaggerConfigComponent.builder() .appModule(AppModule(this)) .build() } }
0
Kotlin
0
0
92594a3cee7cc9a897d12f57d95a0e02097e2135
1,161
ParticlesDrawable
Apache License 2.0
app/src/main/java/com/fbiego/dt78/app/MainApplication.kt
fbiego
285,092,125
false
{"Kotlin": 627720, "HTML": 28744, "Batchfile": 180}
/* * * MIT License * * Copyright (c) 2021 Felix Biego * * 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.fbiego.dt78.app import android.content.Context import android.content.SharedPreferences import androidx.multidex.MultiDexApplication import android.util.Log import com.fbiego.dt78.BuildConfig import timber.log.Timber /** * */ class MainApplication : MultiDexApplication() { companion object { const val PREFS_KEY_ALLOWED_PACKAGES = "PREFS_KEY_ALLOWED_PACKAGES" lateinit var sharedPrefs: SharedPreferences } override fun onCreate() { super.onCreate() sharedPrefs = getSharedPreferences(BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE) if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) //Timber.plant(FileLog(this, "timber.txt")) } Timber.plant(FileLog(this, "error.txt", Log.ERROR)) } }
4
Kotlin
21
41
5c694fa0e09d2a64ad40ff000b989525a264ec5c
1,950
DT78-App-Android
MIT License
data/src/main/kotlin/com/joeloewi/croissant/data/entity/remote/GameRecordEntity.kt
joeloewi7178
489,906,155
false
{"Kotlin": 707165}
package com.joeloewi.croissant.data.entity.remote import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class GameRecordEntity( @Json(name = "has_role") val hasRole: Boolean = false, @Json(name = "game_id") val gameId: Int = INVALID_GAME_ID, @Json(name = "game_role_id") val gameRoleId: Long = Long.MIN_VALUE, val nickname: String = "", val level: Int = Int.MIN_VALUE, @Json(name = "region_name") val regionName: String = "", val region: String = "", @Json(name = "data_switches") val dataSwitches: List<DataSwitchEntity> = listOf(), ) { companion object { const val INVALID_GAME_ID = Int.MIN_VALUE } }
12
Kotlin
0
9
d948faddca04e74db99c277897b7df03a495e6f8
726
Croissant
Apache License 2.0
src/main/java/com/thecout/cpg/Passes/Queries/AddIDFGEdge.kt
SAP-samples
610,187,569
false
null
package com.thecout.cpg.Passes.Queries class AddIDFGEdge(val callId: List<Long>, val fileNames: List<String> = emptyList()) : Query { override fun getQuery(): String { var queryModifier = "" if (fileNames.isNotEmpty()) { val fileNameString = fileNames.map { "\"$it\"" }.joinToString(separator = ",") { it } queryModifier = "(k.file in [$fileNameString] OR m.file in [$fileNameString]) AND" } return if (callId.size > 2) { val callIdString = callId.joinToString(separator = ",") "MATCH(o)<-[:AST]-(k)-[:ICG]->(m)-[:AST]->(f:ParamVariableDeclaration) WHERE m.id in [$callIdString] AND $queryModifier o.argumentIndex = f.argumentIndex MERGE (o)-[:IDFG]->(f);" } else { "MATCH(o)<-[:AST]-(k)-[:ICG]->(m {id: ${callId.first()}})-[:AST]->(f:ParamVariableDeclaration) WHERE $queryModifier o.argumentIndex = f.argumentIndex MERGE (o)-[:IDFG]->(f);" } } }
0
C
0
11
d3f79436e7f99fa149903f09ff0f1bee79fc2eff
964
security-research-taintgraphs
Apache License 2.0
app/src/main/java/com/davidfadare/notes/DrawingActivity.kt
offad
414,578,202
false
{"Kotlin": 306364, "Java": 137048}
package com.davidfadare.notes import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.DialogInterface import android.content.Intent import android.content.pm.PackageManager import android.content.res.Configuration import android.graphics.* import android.media.ExifInterface import android.net.Uri import android.os.Bundle import android.view.Gravity import android.widget.* import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.davidfadare.notes.EditorActivity.Companion.noteColorTAG import com.davidfadare.notes.EditorActivity.Companion.noteDrawingTAG import com.davidfadare.notes.recycler.ColorAdapter import com.davidfadare.notes.util.DrawView import com.davidfadare.notes.util.Utility import com.davidfadare.notes.util.Utility.Companion.changeWindowColor import com.davidfadare.notes.util.Utility.RealPathUtil.getRealPath import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException import java.text.SimpleDateFormat import java.util.* class DrawingActivity : AppCompatActivity() { private var locations: Array<String> = emptyArray() private var position: Int = -1 private var noteColor: Int = 0 private var imageUri: Uri? = null private var drawView: DrawView? = null private var pictureFile: String = "" override fun onCreate(savedInstanceState: Bundle?) { noteColor = intent.getIntExtra(noteColorTAG, 0) locations = intent.getStringArrayExtra(noteDrawingTAG) position = intent.getIntExtra(noteDrawingIDTAG, -1) if (noteColor == 0) { noteColor = ContextCompat.getColor(this, R.color.blue_note) } changeWindowColor(this, window, noteColor) super.onCreate(savedInstanceState) overridePendingTransition(0, android.R.anim.slide_out_right) setContentView(R.layout.activity_draw) imageUri = intent.getParcelableExtra(noteDrawingURITAG) if (savedInstanceState != null) { pictureFile = savedInstanceState.getString(noteDrawingURITAG, "") } else if (position != -1) { pictureFile = locations[position] } onSetup() checkDrawingPermissions(this) } private fun onSetup() { val clearButton = findViewById<ImageView>(R.id.drawing_clear_button) val undoButton = findViewById<ImageView>(R.id.drawing_undo_button) val redoButton = findViewById<ImageView>(R.id.drawing_redo_button) val paletteButton = findViewById<ImageView>(R.id.drawing_palette_button) val saveButton = findViewById<ImageView>(R.id.drawing_save_button) val buttonLayout = findViewById<LinearLayout>(R.id.drawing_button_layout) val drawingContainer = findViewById<FrameLayout>(R.id.drawing_container) buttonLayout.setBackgroundColor(noteColor) val display = windowManager.defaultDisplay val size = Point() display.getSize(size) val config = resources.configuration val currentBitmap = getBitmap(size) drawView = DrawView(this, currentBitmap) drawView?.requestFocus() drawingContainer?.addView(drawView) onChangeSize(config, size) if (pictureFile.isBlank()) pictureFile = getOutputMediaFile()?.path ?: return saveButton?.setOnClickListener { saveBitmap() } redoButton?.setOnClickListener { drawView?.redo() } undoButton?.setOnClickListener { drawView?.undo() } clearButton?.setOnClickListener { if (drawView?.edited == true) { drawView?.clear() drawView?.edited = false Toast.makeText(this, R.string.editor_drawing_cleared, Toast.LENGTH_SHORT).show() } else { onBackPressed() } } paletteButton?.setOnClickListener { showColorDialog(this) } } private fun onChangeSize(configuration: Configuration, size: Point) { val params = FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT) when (configuration.orientation) { Configuration.ORIENTATION_LANDSCAPE -> { params.height = size.y params.width = size.y } Configuration.ORIENTATION_PORTRAIT -> { params.height = size.x params.width = size.x } } params.gravity = Gravity.CENTER drawView?.layoutParams = params } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) if (imageUri == null) { try { val image = drawView?.getBitmap() val stream = FileOutputStream(pictureFile) image?.compress(Bitmap.CompressFormat.PNG, 100, stream) stream.close() } catch (e: FileNotFoundException) { Toast.makeText(this, R.string.error_occurred, Toast.LENGTH_SHORT).show() } catch (e: IOException) { Toast.makeText(this, R.string.pref_header_permission, Toast.LENGTH_SHORT).show() } } else { pictureFile = getRealPath(this, imageUri!!) ?: imageUri.toString() } outState.putString(noteDrawingURITAG, pictureFile) } private fun getBitmap(size: Point): Bitmap? { var imageBitmap: Bitmap? = null when { (pictureFile.isNotBlank()) -> { val option = BitmapFactory.Options() option.inMutable = true option.inPreferredConfig = Bitmap.Config.ARGB_8888 imageBitmap = BitmapFactory.decodeFile(pictureFile, option) } (imageUri != null) -> { try { val pathFile = getRealPath(this, imageUri!!) val option = BitmapFactory.Options() option.inMutable = true option.inPreferredConfig = Bitmap.Config.ARGB_8888 val selectedImage = BitmapFactory.decodeFile(pathFile, option) val exifInterface = ExifInterface(pathFile) val orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1) val width = selectedImage.width val height = selectedImage.height val scaledWidth = size.x.toFloat() / width val scaledHeight = size.x.toFloat() / height val matrix = Matrix() matrix.postScale(scaledWidth, scaledHeight) when (orientation) { ExifInterface.ORIENTATION_ROTATE_180 -> { matrix.postRotate(180f) } ExifInterface.ORIENTATION_ROTATE_90 -> { matrix.postRotate(90f) } ExifInterface.ORIENTATION_ROTATE_270 -> { matrix.postRotate(270f) } else -> { matrix.postRotate(0f) } } imageBitmap = Bitmap.createBitmap(selectedImage!!, 0, 0, width, height, matrix, false) selectedImage.recycle() } catch (e: Exception) { Toast.makeText(this, R.string.error_occurred, Toast.LENGTH_SHORT).show() setResult(Activity.RESULT_CANCELED) finish() } } } return imageBitmap } private fun saveBitmap() { try { val image = drawView?.getBitmap() val stream = FileOutputStream(pictureFile) image?.compress(Bitmap.CompressFormat.PNG, 100, stream) stream.close() if (position == -1) locations += File(pictureFile).path val returnIntent = Intent() returnIntent.putExtra(noteDrawingTAG, locations) setResult(Activity.RESULT_OK, returnIntent) } catch (e: FileNotFoundException) { Toast.makeText(this, R.string.error_occurred, Toast.LENGTH_SHORT).show() setResult(Activity.RESULT_CANCELED) } catch (e: IOException) { Toast.makeText(this, R.string.pref_header_permission, Toast.LENGTH_SHORT).show() setResult(Activity.RESULT_CANCELED) } finally { finish() } } private fun getOutputMediaFile(): File? { if (position == -1) { val mediaFile = File(Utility.mediaStorageDir) if (!mediaFile.exists()) if (!mediaFile.mkdirs()) return null val timeStamp = SimpleDateFormat("ddMMyy_hhmmss", Locale.getDefault()).format(Date()) val mImageName = "MI_$timeStamp.png" return File("${mediaFile.path}${File.separator}$mImageName") } else { return File(locations[position]) } } private fun checkDrawingPermissions(context: Activity) { val writeExternalStorage = ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) val readExternalStorage = ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE) val recordAudioResult = ContextCompat.checkSelfPermission(context, android.Manifest.permission.RECORD_AUDIO) if (writeExternalStorage != PackageManager.PERMISSION_GRANTED || recordAudioResult != PackageManager.PERMISSION_GRANTED || readExternalStorage != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(context, arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.RECORD_AUDIO, android.Manifest.permission.READ_EXTERNAL_STORAGE), EditorActivity.PERMISSION_REQUEST_DRAWING_CODE) } } @SuppressLint("InflateParams") private fun showColorDialog(context: Context) { var paintColor: Int = Color.BLACK val builder = AlertDialog.Builder(context) val colorArray = resources.getStringArray(R.array.color_options) val colorAdapter = ColorAdapter(context, *colorArray) val dialogView = layoutInflater .inflate(R.layout.color_selector, null) dialogView.setPadding(16, 16, 16, 16) builder.setView(dialogView) builder.setPositiveButton(R.string.done) { dialog, _ -> if (dialog != null) { drawView?.changePaint(paintColor) } } builder.setNegativeButton(R.string.cancel) { dialogInterface, _ -> dialogInterface?.dismiss() } val items = dialogView.findViewById<GridView>(R.id.color_grid) items.choiceMode = GridView.CHOICE_MODE_SINGLE items.adapter = colorAdapter items.onItemClickListener = AdapterView.OnItemClickListener { _, _, i, _ -> paintColor = Color.parseColor(colorArray[i]) } val alertDialog = builder.create() alertDialog.show() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { when (requestCode) { EditorActivity.PERMISSION_REQUEST_DRAWING_CODE -> { if (!(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED)) { Toast.makeText(this, getString(R.string.pref_header_permission), Toast.LENGTH_LONG).show() setResult(Activity.RESULT_CANCELED) finish() } } else -> { } } super.onRequestPermissionsResult(requestCode, permissions, grantResults) } override fun onBackPressed() { val discardButtonClickListener = DialogInterface.OnClickListener { _, _ -> setResult(Activity.RESULT_CANCELED) finish() } Utility.createDialog(this, getString(R.string.unsaved_changes_dialog_msg), getString(R.string.keep_editing), getString(R.string.discard), discardButtonClickListener) } override fun onDestroy() { drawView?.mBitmap?.recycle() drawView?.mBitmap = null super.onDestroy() } companion object { const val noteDrawingURITAG = "noteDrawingURI" const val noteDrawingIDTAG = "noteDrawingID" } }
0
Kotlin
0
1
f072e801b3555a18709052a1e9f7dfff435d8535
12,835
stylepad
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/pecs/jpc/service/spreadsheet/outbound/LockoutMovesSheet.kt
ministryofjustice
292,861,912
false
null
package uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound import org.apache.poi.ss.usermodel.Workbook import uk.gov.justice.digital.hmpps.pecs.jpc.domain.move.Move import uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound.PriceSheet.DataColumn.CONTRACTOR_BILLABLE import uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound.PriceSheet.DataColumn.DROP_OFF import uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound.PriceSheet.DataColumn.DROP_OFF_DATE import uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound.PriceSheet.DataColumn.DROP_OFF_TIME import uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound.PriceSheet.DataColumn.LOCATION_TYPE import uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound.PriceSheet.DataColumn.MOVE_ID import uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound.PriceSheet.DataColumn.NOMIS_PRISON_ID import uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound.PriceSheet.DataColumn.NOTES import uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound.PriceSheet.DataColumn.PICK_UP import uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound.PriceSheet.DataColumn.PICK_UP_DATE import uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound.PriceSheet.DataColumn.PICK_UP_TIME import uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound.PriceSheet.DataColumn.PRICE import uk.gov.justice.digital.hmpps.pecs.jpc.service.spreadsheet.outbound.PriceSheet.DataColumn.VEHICLE_REG class LockoutMovesSheet(workbook: Workbook, header: Header) : PriceSheet( sheet = workbook.createSheet("Lockouts"), header = header, subheading = "LOCKOUTS (refused admission to prison)", dataColumns = listOf( MOVE_ID, PICK_UP, LOCATION_TYPE, DROP_OFF, LOCATION_TYPE, PICK_UP_DATE, PICK_UP_TIME, DROP_OFF_DATE, DROP_OFF_TIME, VEHICLE_REG, NOMIS_PRISON_ID, PRICE, CONTRACTOR_BILLABLE, NOTES ) ) { override fun writeMove(move: Move) { writeMoveRow(move) writeJourneyRows(move.journeys) } }
1
Kotlin
2
1
4a01db5b169a4083509c2b7f7f5279f600085217
2,151
calculate-journey-variable-payments
MIT License
shared/src/commonMain/kotlin/com/ramitsuri/choresclient/model/enums/CreateType.kt
ramitsuri
426,858,599
false
{"Kotlin": 404799, "Shell": 8337, "Ruby": 1624, "Swift": 1574}
package com.ramitsuri.choresclient.model.enums enum class CreateType(val key: Int) { UNKNOWN(0), MANUAL(1), AUTO(2); companion object { fun fromKey(key: Int): CreateType { for (value in values()) { if (value.key == key) { return value } } return UNKNOWN } } }
0
Kotlin
0
2
6c5fe6165b5705e4597c588e40c7b0ad3db8d4c7
385
chores-client
MIT License
src/main/kotlin/databaseclient/DatabaseClientRunner.kt
BAC2-Graf-Rohatynski
208,084,264
false
null
package databaseclient import databaseclient.command.CommandSocketHandler import enumstorage.update.ApplicationName import org.json.JSONObject import org.slf4j.Logger import org.slf4j.LoggerFactory object DatabaseClientRunner { private val logger: Logger = LoggerFactory.getLogger(DatabaseClientRunner::class.java) @Volatile private var runApplication = true @Synchronized fun isRunnable(): Boolean = runApplication fun stop() { logger.info("Stopping application") runApplication = false CommandSocketHandler.closeSockets() } fun getUpdateInformation(): JSONObject = UpdateInformation.getAsJson(applicationName = ApplicationName.DatabaseClient.name) }
0
Kotlin
0
0
b7b0df65dbce5ba37b70b49e1cbb420b1a5899cf
714
DatabaseClient
MIT License
ok-tasktracker-be-common/src/main/kotlin/com/polyakovworkbox/tasktracker/backend/common/repositories/TaskIdRequest.kt
otuskotlin
377,711,514
false
null
package com.polyakovworkbox.tasktracker.backend.common.repositories import com.polyakovworkbox.tasktracker.backend.common.models.task.TaskIdReference import java.util.* data class TaskIdRequest( val id: String = "" ): ITaskRepoRequest { companion object { fun getRandom(): TaskIdRequest = TaskIdRequest(UUID.randomUUID()) } constructor(id: UUID) : this(id.toString()) fun asString() = id fun asUUID(): UUID = UUID.fromString(id) }
0
Kotlin
1
1
4ca55a569558ce9950c087bb299b17f667ac7cef
468
ok-202105-tasktracker-dp
MIT License
app/src/main/java/ch/lock/android/networkinfo/ui/base/viewmodel/BaseViewModel.kt
lock-user
743,121,750
false
{"Kotlin": 15139}
package ch.lock.android.networkinfo.ui.base.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import ch.lock.android.networkinfo.utils.base.flow.EventFlow import ch.lock.android.networkinfo.utils.base.flow.MutableEventFlow import kotlinx.coroutines.launch abstract class BaseViewModel : ViewModel() { private val _baseEventFlow = MutableEventFlow<Event>() val baseEventFlow: EventFlow<Event> = _baseEventFlow open fun showToast(message: String?) { event(Event.ShowToast(message)) } private fun event(event: Event) { viewModelScope.launch { _baseEventFlow.emit(event) } } /** * ViewModel default event */ sealed class Event { data class ShowToast(val text: String?) : Event() } }
0
Kotlin
0
0
4fdced287ea039ebaaa249d6cacb84bbb6f6a550
812
network-info-android
MIT License
shared-src/reflect/protokt/v1/reflect/FieldType.kt
open-toast
231,140,493
false
{"Kotlin": 1046958, "Shell": 346}
/* * Copyright (c) 2020 Toast, 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 protokt.v1.reflect import com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type import protokt.v1.Writer import kotlin.reflect.KClass internal sealed class FieldType { open val kotlinRepresentation: KClass<*>? = null open val inlineRepresentation: KClass<*>? = null open val ktRepresentation: KClass<*>? = null sealed class Nonscalar( override val kotlinRepresentation: KClass<*>? = null, override val ktRepresentation: KClass<*>? = null ) : FieldType() object Enum : Nonscalar(ktRepresentation = protokt.v1.Enum::class) object Message : Nonscalar(ktRepresentation = protokt.v1.Message::class) object String : Nonscalar(kotlin.String::class) object Bytes : Nonscalar(protokt.v1.Bytes::class) sealed class Scalar( override val kotlinRepresentation: KClass<*>? = null ) : FieldType() object Bool : Scalar(Boolean::class) object Double : Scalar(kotlin.Double::class) object Float : Scalar(kotlin.Float::class) object Fixed32 : Scalar(UInt::class) object Fixed64 : Scalar(ULong::class) object Int32 : Scalar(Int::class) object Int64 : Scalar(Long::class) object SFixed32 : Scalar(Int::class) object SFixed64 : Scalar(Long::class) object SInt32 : Scalar(Int::class) object SInt64 : Scalar(Long::class) object UInt32 : Scalar(UInt::class) object UInt64 : Scalar(ULong::class) val protoktFieldType get() = when (this) { is Bytes -> protokt.v1.Bytes::class else -> requireNotNull(kotlinRepresentation) { "no protokt field type for $this" } } val packable get() = this !in setOf(Bytes, Message, String) val writeFn get() = when (this) { Fixed32 -> Writer::writeFixed32.name SFixed32 -> Writer::writeSFixed32.name UInt32 -> Writer::writeUInt32.name SInt32 -> Writer::writeSInt32.name Fixed64 -> Writer::writeFixed64.name SFixed64 -> Writer::writeSFixed64.name UInt64 -> Writer::writeUInt64.name SInt64 -> Writer::writeSInt64.name else -> "write" } val scalar get() = this is Scalar val wireType get() = when (this) { Bool, Enum, Int32, Int64, SInt32, SInt64, UInt32, UInt64 -> 0 Double, Fixed64, SFixed64 -> 1 Bytes, Message, String -> 2 Float, Fixed32, SFixed32 -> 5 } companion object { fun from(type: Type) = when (type) { Type.TYPE_BOOL -> Bool Type.TYPE_BYTES -> Bytes Type.TYPE_DOUBLE -> Double Type.TYPE_ENUM -> Enum Type.TYPE_FIXED32 -> Fixed32 Type.TYPE_FIXED64 -> Fixed64 Type.TYPE_FLOAT -> Float Type.TYPE_INT32 -> Int32 Type.TYPE_INT64 -> Int64 Type.TYPE_MESSAGE -> Message Type.TYPE_SFIXED32 -> SFixed32 Type.TYPE_SFIXED64 -> SFixed64 Type.TYPE_SINT32 -> SInt32 Type.TYPE_SINT64 -> SInt64 Type.TYPE_STRING -> String Type.TYPE_UINT32 -> UInt32 Type.TYPE_UINT64 -> UInt64 else -> error("Unknown type: $type") } } }
26
Kotlin
14
154
2130b98a50f233cbb436d8e06a600e157e33a8b8
4,161
protokt
Apache License 2.0
client/app/src/main/java/com/microsoft/research/karya/database/models/LanguageRecord.kt
navana-tech
394,535,166
true
{"TypeScript": 729546, "Kotlin": 312743, "Java": 32041, "JavaScript": 6753, "CSS": 1987, "HTML": 1428}
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /** * This file was auto-generated using specs and scripts in the db-schema * repository. DO NOT EDIT DIRECTLY. */ package com.microsoft.research.karya.database.models import androidx.room.Entity import androidx.room.PrimaryKey import com.google.gson.JsonObject @Entity(tableName = "language") data class LanguageRecord( @PrimaryKey var id: Int, var name: String, var primary_language_name: String, var locale: String, var iso_639_3_code: String, var script: String?, var string_support: Boolean, var file_support: Boolean, var list_support: Boolean, var update_lrv_file: Boolean, var lrv_file_id: String?, var params: JsonObject, var created_at: String, var last_updated_at: String )
0
null
0
0
66d97154bc39d3107a0cd0f0694a68a81bd7b251
827
rural-crowdsourcing-toolkit
MIT License
app/src/main/java/cz/airbank/airbankapplication/model/TransactionDetailWrapper.kt
ivochvojka
151,829,533
false
null
package cz.airbank.airbankapplication.model /** * Wrapper for transaction detail. * * @author <NAME> */ class TransactionDetailWrapper(val contraAccount: TransactionDetail)
0
Kotlin
0
0
60b881f3b0de30bbbda6992073a82cbe2e402f24
177
airbank
MIT License
app/src/main/kotlin/no/nav/tiltakspenger/vedtak/repository/søknad/SpmFunctions.kt
navikt
487,246,438
false
{"Kotlin": 978138, "Dockerfile": 495, "Shell": 150, "HTML": 45}
package no.nav.tiltakspenger.vedtak.repository.søknad import kotliquery.Row import no.nav.tiltakspenger.felles.Periode import no.nav.tiltakspenger.vedtak.Søknad import no.nav.tiltakspenger.vedtak.db.booleanOrNull private const val JA = "JA" private const val NEI = "NEI" private const val IKKE_RELEVANT = "IKKE_RELEVANT" private const val IKKE_MED_I_SOKNADEN = "IKKE_MED_I_SOKNADEN" private const val FEILAKTIG_BESVART = "FEILAKTIG_BESVART" private const val IKKE_BESVART = "IKKE_BESVART" private const val JA_SUFFIX = "_ja" private const val FOM_SUFFIX = "_fom" private const val TOM_SUFFIX = "_tom" private const val TYPE_SUFFIX = "_type" fun Row.periodeSpm(navn: String): Søknad.PeriodeSpm { val type = string(navn + TYPE_SUFFIX) val janei = booleanOrNull(navn + JA_SUFFIX) val fom = localDateOrNull(navn + FOM_SUFFIX) val tom = localDateOrNull(navn + TOM_SUFFIX) // TODO: Dobbeltsjekke at det er lovlige kombinasjoner som leses opp? return when (type) { JA -> Søknad.PeriodeSpm.Ja(Periode(fom!!, tom!!)) NEI -> Søknad.PeriodeSpm.Nei IKKE_RELEVANT -> Søknad.PeriodeSpm.IkkeRelevant IKKE_MED_I_SOKNADEN -> Søknad.PeriodeSpm.IkkeMedISøknaden FEILAKTIG_BESVART -> Søknad.PeriodeSpm.FeilaktigBesvart(janei, fom, tom) IKKE_BESVART -> Søknad.PeriodeSpm.IkkeBesvart else -> throw IllegalArgumentException("Ugyldig type") } } fun Row.fraOgMedDatoSpm(navn: String): Søknad.FraOgMedDatoSpm { val type = string(navn + TYPE_SUFFIX) val janei = booleanOrNull(navn + JA_SUFFIX) val fom = localDateOrNull(navn + FOM_SUFFIX) // TODO: Dobbeltsjekke at det er lovlige kombinasjoner som leses opp? return when (type) { JA -> Søknad.FraOgMedDatoSpm.Ja(fom!!) NEI -> Søknad.FraOgMedDatoSpm.Nei IKKE_RELEVANT -> Søknad.FraOgMedDatoSpm.IkkeRelevant IKKE_MED_I_SOKNADEN -> Søknad.FraOgMedDatoSpm.IkkeMedISøknaden FEILAKTIG_BESVART -> Søknad.FraOgMedDatoSpm.FeilaktigBesvart(janei, fom) IKKE_BESVART -> Søknad.FraOgMedDatoSpm.IkkeBesvart else -> throw IllegalArgumentException("Ugyldig type") } } fun Row.jaNeiSpm(navn: String): Søknad.JaNeiSpm { return when (string(navn + TYPE_SUFFIX)) { JA -> Søknad.JaNeiSpm.Ja NEI -> Søknad.JaNeiSpm.Nei IKKE_RELEVANT -> Søknad.JaNeiSpm.IkkeRelevant IKKE_MED_I_SOKNADEN -> Søknad.JaNeiSpm.IkkeMedISøknaden IKKE_BESVART -> Søknad.JaNeiSpm.IkkeBesvart else -> throw IllegalArgumentException("Ugyldig type") } } fun Map<String, Søknad.PeriodeSpm>.toPeriodeSpmParams(): Map<String, Any?> = this.flatMap { (k, v) -> listOf( k + TYPE_SUFFIX to lagrePeriodeSpmType(v), k + JA_SUFFIX to lagrePeriodeSpmJa(v), k + FOM_SUFFIX to lagrePeriodeSpmFra(v), k + TOM_SUFFIX to lagrePeriodeSpmTil(v), ) }.associate { it.first to it.second as Any? } fun Map<String, Søknad.FraOgMedDatoSpm>.toFraOgMedDatoSpmParams(): Map<String, Any?> = this.flatMap { (k, v) -> listOf( k + TYPE_SUFFIX to lagreFraOgMedDatoSpmType(v), k + JA_SUFFIX to lagreFraOgMedDatoSpmJa(v), k + FOM_SUFFIX to lagreFraOgMedDatoSpmFra(v), ) }.associate { it.first to it.second as Any? } fun Map<String, Søknad.JaNeiSpm>.toJaNeiSpmParams(): Map<String, Any?> = this.flatMap { (k, v) -> listOf( k + TYPE_SUFFIX to lagreJaNeiSpmType(v), ) }.associate { it.first to it.second as Any? } fun lagrePeriodeSpmType(periodeSpm: Søknad.PeriodeSpm) = when (periodeSpm) { is Søknad.PeriodeSpm.Ja -> JA is Søknad.PeriodeSpm.Nei -> NEI is Søknad.PeriodeSpm.IkkeRelevant -> IKKE_RELEVANT is Søknad.PeriodeSpm.IkkeMedISøknaden -> IKKE_MED_I_SOKNADEN is Søknad.PeriodeSpm.FeilaktigBesvart -> FEILAKTIG_BESVART is Søknad.PeriodeSpm.IkkeBesvart -> IKKE_BESVART } fun lagrePeriodeSpmJa(periodeSpm: Søknad.PeriodeSpm) = when (periodeSpm) { is Søknad.PeriodeSpm.Ja -> true is Søknad.PeriodeSpm.Nei -> false is Søknad.PeriodeSpm.IkkeRelevant -> null is Søknad.PeriodeSpm.IkkeMedISøknaden -> null is Søknad.PeriodeSpm.FeilaktigBesvart -> periodeSpm.svartJa is Søknad.PeriodeSpm.IkkeBesvart -> null } fun lagrePeriodeSpmFra(periodeSpm: Søknad.PeriodeSpm) = when (periodeSpm) { is Søknad.PeriodeSpm.Ja -> periodeSpm.periode.fra is Søknad.PeriodeSpm.Nei -> null is Søknad.PeriodeSpm.IkkeRelevant -> null is Søknad.PeriodeSpm.IkkeMedISøknaden -> null is Søknad.PeriodeSpm.FeilaktigBesvart -> periodeSpm.fom is Søknad.PeriodeSpm.IkkeBesvart -> null } fun lagrePeriodeSpmTil(periodeSpm: Søknad.PeriodeSpm) = when (periodeSpm) { is Søknad.PeriodeSpm.Ja -> periodeSpm.periode.til is Søknad.PeriodeSpm.Nei -> null is Søknad.PeriodeSpm.IkkeRelevant -> null is Søknad.PeriodeSpm.IkkeMedISøknaden -> null is Søknad.PeriodeSpm.FeilaktigBesvart -> periodeSpm.tom is Søknad.PeriodeSpm.IkkeBesvart -> null } fun lagreFraOgMedDatoSpmType(fraOgMedDatoSpm: Søknad.FraOgMedDatoSpm) = when (fraOgMedDatoSpm) { is Søknad.FraOgMedDatoSpm.Ja -> JA is Søknad.FraOgMedDatoSpm.Nei -> NEI is Søknad.FraOgMedDatoSpm.IkkeRelevant -> IKKE_RELEVANT is Søknad.FraOgMedDatoSpm.IkkeMedISøknaden -> IKKE_MED_I_SOKNADEN is Søknad.FraOgMedDatoSpm.FeilaktigBesvart -> FEILAKTIG_BESVART is Søknad.FraOgMedDatoSpm.IkkeBesvart -> IKKE_BESVART } fun lagreFraOgMedDatoSpmJa(fraOgMedDatoSpm: Søknad.FraOgMedDatoSpm) = when (fraOgMedDatoSpm) { is Søknad.FraOgMedDatoSpm.Ja -> true is Søknad.FraOgMedDatoSpm.Nei -> false is Søknad.FraOgMedDatoSpm.IkkeRelevant -> null is Søknad.FraOgMedDatoSpm.IkkeMedISøknaden -> null is Søknad.FraOgMedDatoSpm.FeilaktigBesvart -> fraOgMedDatoSpm.svartJa is Søknad.FraOgMedDatoSpm.IkkeBesvart -> null } fun lagreFraOgMedDatoSpmFra(fraOgMedDatoSpm: Søknad.FraOgMedDatoSpm) = when (fraOgMedDatoSpm) { is Søknad.FraOgMedDatoSpm.Ja -> fraOgMedDatoSpm.fra is Søknad.FraOgMedDatoSpm.Nei -> null is Søknad.FraOgMedDatoSpm.IkkeRelevant -> null is Søknad.FraOgMedDatoSpm.IkkeMedISøknaden -> null is Søknad.FraOgMedDatoSpm.FeilaktigBesvart -> fraOgMedDatoSpm.fom is Søknad.FraOgMedDatoSpm.IkkeBesvart -> null } fun lagreJaNeiSpmType(jaNeiSpm: Søknad.JaNeiSpm): String = when (jaNeiSpm) { is Søknad.JaNeiSpm.Ja -> JA is Søknad.JaNeiSpm.Nei -> NEI is Søknad.JaNeiSpm.IkkeRelevant -> IKKE_RELEVANT is Søknad.JaNeiSpm.IkkeMedISøknaden -> IKKE_MED_I_SOKNADEN is Søknad.JaNeiSpm.IkkeBesvart -> IKKE_BESVART } fun lagreJaNeiSpmJa(jaNeiSpm: Søknad.JaNeiSpm) = when (jaNeiSpm) { is Søknad.JaNeiSpm.Ja -> true is Søknad.JaNeiSpm.Nei -> false is Søknad.JaNeiSpm.IkkeRelevant -> null is Søknad.JaNeiSpm.IkkeMedISøknaden -> null is Søknad.JaNeiSpm.IkkeBesvart -> null }
6
Kotlin
0
2
46302b321b65cd094c35c01319ff2781a511ba6c
7,205
tiltakspenger-vedtak
MIT License